feat(share): allow creating share links from media view with quick share dialog (#548)

* feat(share): allow creating share links from media view with quick share dialog

* fix(share): prevent horizontal overflow in quick share dialog
This commit is contained in:
Yiling-J
2026-11-24 19:39:06 +08:00
committed by GitHub
parent dc9adcf9ac
commit 9c8eb16259
24 changed files with 1457 additions and 266 deletions
+2
View File
@@ -8,6 +8,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
- **share**: Add options to create a share link or add to existing share links directly from the media view dropdown menu, and open a quick share dialog with inline renaming, one-click link copying, and security settings upon creation.
### Fixed
### Changed
+2 -1
View File
@@ -77,7 +77,8 @@ apps/web/e2e/
| Owner deletes a file, finds it in recently deleted, and restores it | `tests/project/delete-restore.spec.ts` |
| Owner deletes a folder and still sees its contents preview and countdown in recently deleted | `tests/project/delete-restore.spec.ts` |
| Owner deletes a version stack and restores it from recently deleted | `tests/project/delete-restore.spec.ts` |
| Owner creates a share link from a file context menu and lands on the share page | `tests/project/create-share-link.spec.ts` |
| Owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings | `tests/project/create-share-link.spec.ts` |
| Owner creates a share link and adds to an existing share link from media view | `tests/project/create-share-link.spec.ts` |
| Owner protects a share with a password; guests must enter it to view | `tests/project/share-password.spec.ts` |
| Owner creates a collection from the sidebar; the collection shows project files | `tests/project/create-collection.spec.ts` |
| Owner invites a member to a project; the member only sees the invited project | `tests/project/invite-member.spec.ts` |
@@ -1,7 +1,7 @@
import { expect, test } from '../../fixtures'
import { fileCard } from '../../helpers/files'
import { apiCreateShare, fileCard } from '../../helpers/files'
test('owner creates a share link from a file context menu and lands on the share page', async ({
test('owner creates a share link from a file context menu, edits it in the quick dialog, and opens advanced settings', async ({
file,
prisma,
}) => {
@@ -14,19 +14,38 @@ test('owner creates a share link from a file context menu and lands on the share
await fileCard(page, fileName).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
// The toast offers a "View" action that navigates to the share page
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
await expect(toast).toBeVisible()
await toast.getByRole('button', { name: 'View' }).click()
// Quick share dialog opens with share name, URL, security controls, and footer actions
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await expect(dialog.getByText(fileName)).toBeVisible()
await expect(dialog.getByRole('button', { name: 'Copy Link' }).last()).toBeVisible()
await expect(dialog.getByRole('button', { name: 'Done' })).toBeVisible()
// Rename share link inline via the pen icon
await dialog.getByRole('button', { name: 'Rename Share Link' }).click()
const nameInput = dialog.getByRole('textbox', { name: 'Rename Share Link' })
await expect(nameInput).toBeVisible()
await nameInput.fill('Client Review Cut')
await nameInput.press('Enter')
await expect(dialog.getByText('Client Review Cut')).toBeVisible()
// Toggle Allow download off in quick security settings
const allowDownloadRow = dialog.getByText('Allow download').locator('..')
await allowDownloadRow.getByRole('switch').click()
await expect(page.getByText('Settings updated')).toBeVisible()
// Navigate to full settings via Advanced settings
await dialog.getByRole('button', { name: 'Advanced settings' }).click()
await expect(page).toHaveURL(/\/projects\/[^/]+\/shares\/[^/]+/)
// The shared file is listed in the share contents
await expect(fileCard(page, fileName)).toBeVisible()
// DB: the share exists and the file is symlinked under the share root
// DB: the share exists with updated settings and the file is symlinked under the share root
const share = await prisma.shareLink.findFirst({ where: { projectId } })
expect(share).not.toBeNull()
expect(share?.name).toBe('Client Review Cut')
expect(share?.allowDownload).toBe(false)
const symlink = await prisma.asset.findFirst({
where: { parentId: share?.rootFolderId, targetId: fileId },
@@ -34,3 +53,58 @@ test('owner creates a share link from a file context menu and lands on the share
expect(symlink).not.toBeNull()
expect(symlink?.type).toBe('symlink')
})
test('owner creates a share link and adds to an existing share link from media view', async ({
file,
prisma,
}) => {
const { context, page, projectId, fileName, fileId } = file
// Seed an existing share link so "Add to Share Links" submenu is available
const existingShare = await apiCreateShare(context.request, projectId, 'Existing Client Share')
await page.goto(`/projects/${projectId}/files/${fileId}`)
const headerTrigger = page.getByRole('button', { name: fileName })
await expect(headerTrigger).toBeVisible()
// Open the media view header arrow dropdown and create a new share link
await headerTrigger.click()
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
await expect(dialog.getByText(fileName)).toBeVisible()
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
// Close the dialog with Done and stay on the media view
await dialog.getByRole('button', { name: 'Done' }).click()
await expect(dialog).toBeHidden()
await expect(page).toHaveURL(new RegExp(`/projects/${projectId}/files/${fileId}$`))
// DB: new share link created with symlink to the file
const createdShare = await prisma.shareLink.findFirst({
where: { projectId, id: { not: existingShare.id } },
})
expect(createdShare).not.toBeNull()
expect(createdShare?.name).toBe(fileName)
const createdSymlink = await prisma.asset.findFirst({
where: { parentId: createdShare?.rootFolderId, targetId: fileId },
})
expect(createdSymlink).not.toBeNull()
expect(createdSymlink?.type).toBe('symlink')
// Open the header dropdown again and add the file to the existing share link
await headerTrigger.click()
await page.getByRole('menuitem', { name: 'Add to Share Links' }).hover()
await page.getByRole('menuitem', { name: 'Existing Client Share' }).click()
const addedToast = page.locator('[data-sonner-toast]').filter({ hasText: 'Added to share link' })
await expect(addedToast).toBeVisible()
const addedSymlink = await prisma.asset.findFirst({
where: { parentId: existingShare.rootFolderId, targetId: fileId },
})
expect(addedSymlink).not.toBeNull()
expect(addedSymlink?.type).toBe('symlink')
})
@@ -147,8 +147,10 @@ test('dissolving a shared version stack renders the remaining standalone file na
// Share the version stack
await fileCard(page, fileB.name).click({ button: 'right' })
await page.getByRole('menuitem', { name: 'Create Share Link' }).click()
const toast = page.locator('[data-sonner-toast]').filter({ hasText: 'Share link created' })
await expect(toast).toBeVisible()
const shareDialog = page.getByRole('dialog')
await expect(shareDialog).toBeVisible()
await shareDialog.getByRole('button', { name: 'Done' }).click()
await expect(shareDialog).toBeHidden()
const share = await prisma.shareLink.findFirstOrThrow({
where: { projectId },
@@ -392,4 +392,103 @@ describe('BreadcrumbNav component', () => {
expect(screen.queryByText('Archived')).toBeNull()
expect(screen.queryByText('已归档')).toBeNull()
})
it('renders Create Share Link and Add to Share Links at top of dropdown above Download for editors', () => {
const editorQueryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
editorQueryClient.setQueryData(['projects', 'proj-1', 'me'], { role: 'owner' })
const onCreateShareLink = vi.fn()
const onAddToShareLink = vi.fn()
render(
<QueryClientProvider client={editorQueryClient}>
<BreadcrumbNav
{...baseProps}
fileId="file-share"
currentAsset={{ id: 'file-share', name: 'review.mp4', type: 'file', version: 1 }}
allowDownload={true}
downloadInfo={{ originalKey: 'review.mp4' }}
shareLinks={[
{
id: 'share-1',
name: 'Client Cut',
isDisabled: false,
allowDownload: true,
hasPassword: false,
rootFolderId: 'rf-1',
projectId: 'proj-1',
isExpired: false,
createdAt: '2026-11-24T00:00:00.000Z',
updatedAt: '2026-11-24T00:00:00.000Z',
},
]}
onCreateShareLink={onCreateShareLink}
onAddToShareLink={onAddToShareLink}
/>
</QueryClientProvider>,
)
const triggerButton = screen.getByRole('button', { name: 'review.mp4' })
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
const items = screen.getAllByRole('menuitem')
expect(items[0].textContent).toContain('Create Share Link')
expect(items[1].textContent).toContain('Add to Share Links')
expect(items[2].textContent).toContain('Download')
fireEvent.click(items[0])
expect(onCreateShareLink).toHaveBeenCalledTimes(1)
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
fireEvent.click(screen.getByText('Add to Share Links'))
fireEvent.click(screen.getByText('Client Cut'))
expect(onAddToShareLink).toHaveBeenCalledWith('share-1')
})
it('hides share link options when public or when user lacks edit permission', () => {
const reviewerQueryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
reviewerQueryClient.setQueryData(['projects', 'proj-1', 'me'], { role: 'reviewer' })
const { rerender } = render(
<QueryClientProvider client={reviewerQueryClient}>
<BreadcrumbNav
{...baseProps}
fileId="file-share"
currentAsset={{ id: 'file-share', name: 'review.mp4', type: 'file' }}
onCreateShareLink={vi.fn()}
onAddToShareLink={vi.fn()}
/>
</QueryClientProvider>,
)
fireEvent.pointerDown(screen.getByRole('button', { name: 'review.mp4' }), {
button: 0,
ctrlKey: false,
})
expect(screen.queryByText('Create Share Link')).toBeNull()
expect(screen.queryByText('Add to Share Links')).toBeNull()
const ownerQueryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
})
ownerQueryClient.setQueryData(['projects', 'proj-1', 'me'], { role: 'owner' })
rerender(
<QueryClientProvider client={ownerQueryClient}>
<BreadcrumbNav
{...baseProps}
isPublic={true}
fileId="file-share"
currentAsset={{ id: 'file-share', name: 'review.mp4', type: 'file' }}
onCreateShareLink={vi.fn()}
onAddToShareLink={vi.fn()}
/>
</QueryClientProvider>,
)
expect(screen.queryByText('Create Share Link')).toBeNull()
})
})
+34 -1
View File
@@ -29,7 +29,7 @@ import {
import { usePermissions } from '@/ui/hooks/use-permissions'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { AncestorFolder } from '@shumai/dtos'
import type { AncestorFolder, ShareLinkInfo } from '@shumai/dtos'
import { Link, useNavigate } from '@tanstack/react-router'
import { useQuery } from '@tanstack/react-query'
import {
@@ -84,6 +84,10 @@ interface BreadcrumbNavProps {
onDelete?: () => void
onArchive?: () => void
onRestoreArchive?: () => void
shareLinks?: ShareLinkInfo[]
onCreateShareLink?: () => void
onAddToShareLink?: (shareId: string) => void
isShareActionPending?: boolean
fileId?: string
downloadInfo?: {
originalKey?: string
@@ -131,6 +135,10 @@ export function BreadcrumbNav({
onDelete,
onArchive,
onRestoreArchive,
shareLinks,
onCreateShareLink,
onAddToShareLink,
isShareActionPending = false,
fileId,
shareId,
allowDownload = true,
@@ -318,6 +326,31 @@ export function BreadcrumbNav({
</DropdownMenuTrigger>
</div>
<DropdownMenuContent className="w-56" align="center">
{canEdit && !isPublic && onCreateShareLink && (
<>
<DropdownMenuItem onClick={onCreateShareLink} disabled={isShareActionPending}>
{m.create_share_link()}
</DropdownMenuItem>
{shareLinks && shareLinks.length > 0 && onAddToShareLink && (
<DropdownMenuSub>
<DropdownMenuSubTrigger>{m.add_to_share_links()}</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent className="w-52">
{shareLinks.map((share) => (
<DropdownMenuItem
key={share.id}
disabled={isShareActionPending}
onClick={() => onAddToShareLink(share.id)}
>
<span className="truncate">{share.name}</span>
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
)}
</>
)}
{allowDownload &&
(hasVideoTranscodes ? (
<DropdownMenuSub>
@@ -16,6 +16,7 @@ interface DateTimePickerProps {
placeholder?: string
disabled?: boolean
className?: string
modal?: boolean
}
export function DateTimePicker({
@@ -24,6 +25,7 @@ export function DateTimePicker({
placeholder = 'Pick a date',
disabled,
className,
modal = false,
}: DateTimePickerProps) {
const [isOpen, setIsOpen] = React.useState(false)
const [tempValue, setTempValue] = React.useState<Date | undefined>(value)
@@ -78,7 +80,7 @@ export function DateTimePicker({
}
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<Popover modal={modal} open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
@@ -4,6 +4,7 @@ import type { InferRequestType, InferResponseType } from 'hono/client'
import { m } from '@/ui/paraglide/messages.js'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions'
import { getAllFilesFromEntries } from '@/ui/lib/dnd-utils'
import { formatSize } from '@/ui/lib/format'
import { useFieldStore } from '@/ui/stores/fields'
@@ -15,9 +16,8 @@ import type {
CreateUploadTaskRequest,
SearchCondition,
SearchSort,
ShareLinkInfo,
} from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { AlertTriangle, Download, FolderClock, Loader2 } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
@@ -27,6 +27,7 @@ import type { DragState } from '../dnd-types'
import { MoveCopyDialog } from '../move-copy-dialog'
import { ManageVersionsDialog } from '../manage-versions-dialog'
import { FilePreviewDialog } from '../file-preview-dialog'
import { ShareLinkCreatedDialog } from '../share-link-created-dialog'
import { FileBrowserContentSkeleton } from '../loading-skeletons'
import { FileBrowserContextMenu } from './context-menu'
import { FindSimilarDialog } from '../search/find-similar-dialog'
@@ -309,18 +310,11 @@ export function FileBrowser({
}
}, [isPreviewOpen, selectedIds.size, activePreviewItem])
const { data: shareLinksData } = useQuery({
queryKey: ['shares', projectId, 'list'],
queryFn: async () => {
const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error('Failed to fetch share links')
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
},
enabled: !!projectId && !isPublic,
})
const { shareLinks, createShareLink, addToShareLink, createdShareLink, clearCreatedShareLink } =
useShareLinkActions({
projectId,
enabled: !isPublic,
})
const $reparent = client.api.projects[':projectId'].reparent.$post
const { mutate: reparentAssets } = useMutation<
@@ -413,71 +407,6 @@ export function FileBrowser({
}
}
const { mutate: createShareLink } = useMutation({
mutationFn: async (items: AssetInfo[]) => {
const name =
items.length === 1
? items[0].name
: new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
})
const res = await client.api.projects[':projectId'].shares.$post({
param: { projectId },
json: { name },
})
if (!res.ok) throw new Error('Failed to create share link')
const share = await res.json()
// Add assets to the new share link
const assetsRes = await client.api.shares[':shareId'].assets.$post({
param: { shareId: share.id },
json: { assetIds: items.map((i) => i.id!) },
})
if (!assetsRes.ok) throw new Error('Failed to add assets to share link')
return share
},
onSuccess: (share) => {
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
toast.success('Share link created', {
action: {
label: 'View',
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: share.id },
}),
},
})
},
})
const { mutate: addToShareLink } = useMutation({
mutationFn: async ({ shareId, items }: { shareId: string; items: AssetInfo[] }) => {
const res = await client.api.shares[':shareId'].assets.$post({
param: { shareId },
json: { assetIds: items.map((i) => i.id!) },
})
if (!res.ok) throw new Error('Failed to add assets')
return { shareId }
},
onSuccess: ({ shareId }) => {
toast.success('Added to share link', {
action: {
label: 'View',
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId },
}),
},
})
},
})
const handleCreateShareLink = (items: AssetInfo[]) => {
createShareLink(items)
}
@@ -1210,7 +1139,7 @@ export function FileBrowser({
allowDownload={allowDownload}
isRecentlyDeleted={isRecentlyDeleted}
isRecents={isRecents}
shareLinks={shareLinksData?.data ?? []}
shareLinks={shareLinks}
onCreateShareLink={handleCreateShareLink}
onAddToShareLink={handleAddToShareLink}
canEdit={canEdit}
@@ -1411,6 +1340,15 @@ export function FileBrowser({
isPublic={isPublic}
/>
<ShareLinkCreatedDialog
open={!!createdShareLink}
onOpenChange={(open) => {
if (!open) clearCreatedShareLink()
}}
shareLink={createdShareLink}
projectId={projectId}
/>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
@@ -25,7 +25,7 @@ import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
import { m } from '@/ui/paraglide/messages.js'
import { useMemberStore } from '@/ui/stores/members'
import type { Annotation } from '@/ui/types'
import type { AncestorFolder, AssetInfo, CommentInfo, FieldInfo } from '@shumai/dtos'
import type { AncestorFolder, AssetInfo, CommentInfo, FieldInfo, ShareLinkInfo } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import React, { useEffect, useMemo, useRef, useState } from 'react'
@@ -61,6 +61,10 @@ export interface MobileFileDetailProps {
onDeleteFile?: () => Promise<void>
onArchiveFile?: () => void
onRestoreArchiveFile?: () => void
shareLinks?: ShareLinkInfo[]
onCreateShareLink?: () => void
onAddToShareLink?: (shareId: string) => void
isShareActionPending?: boolean
onSaveField: (fieldId: string, value: unknown) => void
onSelectVersion?: (versionId: string) => void
}
@@ -86,6 +90,10 @@ export function MobileFileDetail({
onDeleteFile,
onArchiveFile,
onRestoreArchiveFile,
shareLinks,
onCreateShareLink,
onAddToShareLink,
isShareActionPending = false,
onSaveField,
onSelectVersion,
}: MobileFileDetailProps) {
@@ -240,6 +248,10 @@ export function MobileFileDetail({
onDelete={() => setIsDeleteDialogOpen(true)}
onArchive={onArchiveFile}
onRestoreArchive={onRestoreArchiveFile}
shareLinks={shareLinks}
onCreateShareLink={onCreateShareLink}
onAddToShareLink={onAddToShareLink}
isShareActionPending={isShareActionPending}
onLinkedTasks={!isPublic ? () => setIsLinkedTasksOpen(true) : undefined}
linkedTaskCount={linkedTaskCount}
/>
@@ -216,4 +216,83 @@ describe('MobileFileHeader', () => {
expect(screen.queryByText('Restoring...')).toBeNull()
expect(screen.queryByText('恢复中...')).toBeNull()
})
it('renders Create Share Link and Add to Share Links at top of three-dot menu above Download for editors', () => {
const onCreateShareLink = vi.fn()
const onAddToShareLink = vi.fn()
render(
<MobileFileHeader
fileName="clip.mp4"
activeFileId="file-1"
canEdit={true}
allowDownload={true}
downloadInfo={{ originalKey: 'clip.mp4' }}
shareLinks={[
{
id: 'share-1',
name: 'Client Review',
isDisabled: false,
allowDownload: true,
hasPassword: false,
rootFolderId: 'rf-1',
projectId: 'proj-1',
isExpired: false,
createdAt: '2026-11-24T00:00:00.000Z',
updatedAt: '2026-11-24T00:00:00.000Z',
},
]}
onCreateShareLink={onCreateShareLink}
onAddToShareLink={onAddToShareLink}
onBack={vi.fn()}
/>,
)
const menuBtn = screen.getByLabelText(/More options/i)
fireEvent.pointerDown(menuBtn, { button: 0, ctrlKey: false })
const items = screen.getAllByRole('menuitem')
expect(items[0].textContent).toContain('Create Share Link')
expect(items[1].textContent).toContain('Add to Share Links')
expect(items[2].textContent).toContain('Download')
fireEvent.click(items[0])
expect(onCreateShareLink).toHaveBeenCalledTimes(1)
fireEvent.pointerDown(menuBtn, { button: 0, ctrlKey: false })
fireEvent.click(screen.getByText('Add to Share Links'))
fireEvent.click(screen.getByText('Client Review'))
expect(onAddToShareLink).toHaveBeenCalledWith('share-1')
})
it('hides share link options when public or when canEdit is false', () => {
const { rerender } = render(
<MobileFileHeader
fileName="clip.mp4"
activeFileId="file-1"
canEdit={false}
onCreateShareLink={vi.fn()}
onAddToShareLink={vi.fn()}
onBack={vi.fn()}
/>,
)
const menuBtn = screen.getByLabelText(/More options/i)
fireEvent.pointerDown(menuBtn, { button: 0, ctrlKey: false })
expect(screen.queryByText('Create Share Link')).toBeNull()
rerender(
<MobileFileHeader
fileName="clip.mp4"
activeFileId="file-1"
canEdit={true}
isPublic={true}
onCreateShareLink={vi.fn()}
onAddToShareLink={vi.fn()}
onBack={vi.fn()}
/>,
)
expect(screen.queryByText('Create Share Link')).toBeNull()
})
})
@@ -15,6 +15,7 @@ import {
} from '@/ui/components/ui/dropdown-menu'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { ShareLinkInfo } from '@shumai/dtos'
import {
Archive,
ArchiveRestore,
@@ -22,9 +23,11 @@ import {
ChevronLeft,
ChevronRight,
Download,
Link as LinkIcon,
Loader2,
MoreVertical,
Pencil,
Plus,
SquareKanban,
Trash2,
} from 'lucide-react'
@@ -67,6 +70,10 @@ export interface MobileFileHeaderProps {
onDelete?: () => void
onArchive?: () => void
onRestoreArchive?: () => void
shareLinks?: ShareLinkInfo[]
onCreateShareLink?: () => void
onAddToShareLink?: (shareId: string) => void
isShareActionPending?: boolean
onLinkedTasks?: () => void
linkedTaskCount?: number
}
@@ -93,6 +100,10 @@ export function MobileFileHeader({
onDelete,
onArchive,
onRestoreArchive,
shareLinks,
onCreateShareLink,
onAddToShareLink,
isShareActionPending = false,
onLinkedTasks,
linkedTaskCount = 0,
}: MobileFileHeaderProps) {
@@ -279,6 +290,42 @@ export function MobileFileHeader({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-52 z-40">
{/* Share Links */}
{canEdit && !isPublic && onCreateShareLink && (
<>
<DropdownMenuItem
onClick={onCreateShareLink}
disabled={isShareActionPending}
className="flex items-center gap-2 text-xs cursor-pointer"
>
<Plus className="h-3.5 w-3.5" />
<span>{m.create_share_link()}</span>
</DropdownMenuItem>
{shareLinks && shareLinks.length > 0 && onAddToShareLink && (
<DropdownMenuSub>
<DropdownMenuSubTrigger className="flex items-center gap-2 text-xs cursor-pointer">
<LinkIcon className="h-3.5 w-3.5" />
<span>{m.add_to_share_links()}</span>
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent className="w-48 z-50">
{shareLinks.map((share) => (
<DropdownMenuItem
key={share.id}
disabled={isShareActionPending}
onClick={() => onAddToShareLink(share.id)}
className="text-xs cursor-pointer"
>
<span className="truncate">{share.name}</span>
</DropdownMenuItem>
))}
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
)}
</>
)}
{/* Download */}
{allowDownload &&
(hasVideoTranscodes ? (
@@ -0,0 +1,231 @@
// @vitest-environment happy-dom
import React from 'react'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import type { ShareLinkInfo } from '@shumai/dtos'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { ShareLinkCreatedDialog } from './share-link-created-dialog'
const mockNavigate = vi.fn()
const mockCopyToClipboard = vi.fn().mockResolvedValue(true)
const mockGetShare = vi.fn()
const mockPutShare = vi.fn()
const mockGetWatermark = vi.fn()
const mockPutWatermark = vi.fn()
vi.mock('@tanstack/react-router', () => ({
useNavigate: () => mockNavigate,
}))
vi.mock('@/ui/lib/clipboard', () => ({
copyToClipboard: (...args: unknown[]) => mockCopyToClipboard(...args),
}))
vi.mock('@/ui/components/watermark-editor-dialog', () => ({
WatermarkEditorDialog: () => null,
}))
vi.mock('@/ui/api/client', () => ({
client: {
api: {
shares: {
':shareId': {
$get: (...args: unknown[]) => mockGetShare(...args),
$put: (...args: unknown[]) => mockPutShare(...args),
watermark: {
$get: (...args: unknown[]) => mockGetWatermark(...args),
$put: (...args: unknown[]) => mockPutWatermark(...args),
},
},
},
},
},
}))
const sampleShare: ShareLinkInfo = {
id: 'share-1',
name: 'hero-cut.mp4',
isDisabled: false,
allowDownload: true,
hasPassword: false,
password: null,
rootFolderId: 'folder-share-1',
projectId: 'proj-1',
isExpired: false,
watermarkConfigId: null,
watermarkStatus: 'disabled',
watermarkConfig: null,
createdAt: '2026-11-24T00:00:00.000Z',
updatedAt: '2026-11-24T00:00:00.000Z',
creator: null,
}
function createQueryClient() {
return new QueryClient({
defaultOptions: {
queries: { retry: false },
mutations: { retry: false },
},
})
}
describe('ShareLinkCreatedDialog', () => {
beforeEach(() => {
vi.clearAllMocks()
mockGetShare.mockResolvedValue({
ok: true,
json: async () => sampleShare,
})
mockGetWatermark.mockResolvedValue({
ok: true,
json: async () => ({ watermarkStatus: 'disabled', watermarkConfig: null }),
})
mockPutShare.mockImplementation(async ({ json }: { json: Record<string, unknown> }) => ({
ok: true,
json: async () => ({ ...sampleShare, ...json }),
}))
})
afterEach(() => {
cleanup()
})
it('renders share name, URL, all 4 expanded security controls, and footer buttons', () => {
const queryClient = createQueryClient()
render(
<QueryClientProvider client={queryClient}>
<ShareLinkCreatedDialog
open={true}
onOpenChange={vi.fn()}
shareLink={sampleShare}
projectId="proj-1"
/>
</QueryClientProvider>,
)
expect(screen.getByText('hero-cut.mp4')).toBeDefined()
expect(screen.getByRole('button', { name: 'Rename Share Link' })).toBeDefined()
const urlInput = screen.getByRole('textbox', { name: /share link/i }) as HTMLInputElement
expect(urlInput.value).toBe(`${window.location.origin}/share/share-1`)
// All 4 security settings rendered directly without needing an accordion
expect(screen.getByText('Password')).toBeDefined()
expect(screen.getByText('Expiration Date')).toBeDefined()
expect(screen.getByText('Allow download')).toBeDefined()
expect(screen.getByText('Watermark')).toBeDefined()
// Footer buttons
expect(screen.getByRole('button', { name: 'Advanced settings' })).toBeDefined()
expect(screen.getAllByRole('button', { name: 'Copy Link' }).length).toBe(2)
expect(screen.getByRole('button', { name: 'Done' })).toBeDefined()
})
it('supports inline renaming via pen icon and cancels on Escape', async () => {
const queryClient = createQueryClient()
render(
<QueryClientProvider client={queryClient}>
<ShareLinkCreatedDialog
open={true}
onOpenChange={vi.fn()}
shareLink={sampleShare}
projectId="proj-1"
/>
</QueryClientProvider>,
)
// Enter edit mode and cancel with Escape
fireEvent.click(screen.getByRole('button', { name: 'Rename Share Link' }))
const input = screen.getByRole('textbox', { name: 'Rename Share Link' }) as HTMLInputElement
expect(input.value).toBe('hero-cut.mp4')
fireEvent.change(input, { target: { value: 'Temporary Name' } })
fireEvent.keyDown(input, { key: 'Escape' })
expect(mockPutShare).not.toHaveBeenCalled()
expect(screen.getByText('hero-cut.mp4')).toBeDefined()
// Re-enter edit mode and save with Enter
fireEvent.click(screen.getByRole('button', { name: 'Rename Share Link' }))
const input2 = screen.getByRole('textbox', { name: 'Rename Share Link' }) as HTMLInputElement
fireEvent.change(input2, { target: { value: 'Client Delivery v2' } })
fireEvent.keyDown(input2, { key: 'Enter' })
await waitFor(() => {
expect(mockPutShare).toHaveBeenCalledWith({
param: { shareId: 'share-1' },
json: { name: 'Client Delivery v2' },
})
})
})
it('updates security settings via PUT /shares/:shareId', async () => {
const queryClient = createQueryClient()
render(
<QueryClientProvider client={queryClient}>
<ShareLinkCreatedDialog
open={true}
onOpenChange={vi.fn()}
shareLink={sampleShare}
projectId="proj-1"
/>
</QueryClientProvider>,
)
const switches = screen.getAllByRole('switch')
// Switches order: Password (0), Expiration Date (1), Allow Download (2), Watermark (3)
fireEvent.click(switches[2])
await waitFor(() => {
expect(mockPutShare).toHaveBeenCalledWith({
param: { shareId: 'share-1' },
json: { allowDownload: false },
})
})
// Enable password and save
fireEvent.click(switches[0])
const passwordInput = screen.getByPlaceholderText('Enter password')
fireEvent.change(passwordInput, { target: { value: 'pass123' } })
fireEvent.click(screen.getByRole('button', { name: 'Save' }))
await waitFor(() => {
expect(mockPutShare).toHaveBeenCalledWith({
param: { shareId: 'share-1' },
json: { password: 'pass123' },
})
})
})
it('copies link while staying open, closes on Done, and navigates on Advanced settings', async () => {
const onOpenChange = vi.fn()
const queryClient = createQueryClient()
render(
<QueryClientProvider client={queryClient}>
<ShareLinkCreatedDialog
open={true}
onOpenChange={onOpenChange}
shareLink={sampleShare}
projectId="proj-1"
/>
</QueryClientProvider>,
)
const copyButtons = screen.getAllByRole('button', { name: 'Copy Link' })
fireEvent.click(copyButtons[copyButtons.length - 1])
await waitFor(() => {
expect(mockCopyToClipboard).toHaveBeenCalledWith(`${window.location.origin}/share/share-1`)
})
expect(onOpenChange).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Advanced settings' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
expect(mockNavigate).toHaveBeenCalledWith({
to: '/projects/$projectId/shares/$shareId',
params: { projectId: 'proj-1', shareId: 'share-1' },
})
onOpenChange.mockClear()
fireEvent.click(screen.getByRole('button', { name: 'Done' }))
expect(onOpenChange).toHaveBeenCalledWith(false)
})
})
@@ -0,0 +1,277 @@
import { client } from '@/ui/api/client'
import { ShareSecuritySettings } from '@/ui/components/share-security-settings'
import { Button } from '@/ui/components/ui/button'
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { copyToClipboard } from '@/ui/lib/clipboard'
import { m } from '@/ui/paraglide/messages.js'
import type { ShareLinkInfo } from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { ArrowUpRight, Check, Copy, Pencil } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
interface ShareLinkCreatedDialogProps {
open: boolean
onOpenChange: (open: boolean) => void
shareLink: ShareLinkInfo | null
projectId: string
}
export function ShareLinkCreatedDialog({
open,
onOpenChange,
shareLink,
projectId,
}: ShareLinkCreatedDialogProps) {
const navigate = useNavigate()
const queryClient = useQueryClient()
const [isEditingName, setIsEditingName] = useState(false)
const [nameInput, setNameInput] = useState('')
const [copied, setCopied] = useState(false)
const nameInputRef = useRef<HTMLInputElement>(null)
const cancelEditRef = useRef(false)
const copiedTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const shareId = shareLink?.id
const { data: liveShareLink } = useQuery({
queryKey: ['share', shareId],
queryFn: async () => {
if (!shareId) return null
const res = await client.api.shares[':shareId'].$get({
param: { shareId },
})
if (!res.ok) throw new Error(m.failed_fetch_share_link())
return (await res.json()) as unknown as ShareLinkInfo
},
initialData: shareLink ?? undefined,
enabled: open && !!shareId,
})
const activeShare = liveShareLink ?? shareLink
useEffect(() => {
if (!open) {
setIsEditingName(false)
setCopied(false)
if (copiedTimeoutRef.current) {
clearTimeout(copiedTimeoutRef.current)
copiedTimeoutRef.current = null
}
}
}, [open])
useEffect(() => {
return () => {
if (copiedTimeoutRef.current) {
clearTimeout(copiedTimeoutRef.current)
}
}
}, [])
useEffect(() => {
if (isEditingName) {
nameInputRef.current?.focus()
nameInputRef.current?.select()
}
}, [isEditingName])
const { mutate: renameShare, isPending: isRenaming } = useMutation({
mutationFn: async (name: string) => {
if (!activeShare) throw new Error(m.failed_rename_share_link())
const res = await client.api.shares[':shareId'].$put({
param: { shareId: activeShare.id },
json: { name },
})
if (!res.ok) throw new Error(m.failed_rename_share_link())
return (await res.json()) as unknown as ShareLinkInfo
},
onSuccess: (updated) => {
queryClient.setQueryData(['share', updated.id], updated)
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
queryClient.invalidateQueries({ queryKey: ['share', updated.id] })
toast.success(m.share_link_renamed())
},
onError: () => {
toast.error(m.failed_rename_share_link())
},
})
if (!activeShare) {
return null
}
const shareUrl = `${window.location.origin}/share/${activeShare.id}`
const startEditingName = () => {
cancelEditRef.current = false
setNameInput(activeShare.name)
setIsEditingName(true)
}
const commitRename = () => {
if (cancelEditRef.current) {
cancelEditRef.current = false
return
}
const trimmed = nameInput.trim()
setIsEditingName(false)
if (!trimmed || trimmed === activeShare.name) {
return
}
renameShare(trimmed)
}
const handleCopyLink = async () => {
const ok = await copyToClipboard(shareUrl)
if (ok) {
toast.success(m.copied_to_clipboard())
setCopied(true)
if (copiedTimeoutRef.current) {
clearTimeout(copiedTimeoutRef.current)
}
copiedTimeoutRef.current = setTimeout(() => {
setCopied(false)
copiedTimeoutRef.current = null
}, 2000)
}
}
const handleAdvancedSettings = () => {
onOpenChange(false)
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId: activeShare.id },
})
}
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-md overflow-hidden">
<DialogHeader className="min-w-0">
{isEditingName ? (
<>
<DialogTitle className="sr-only">{m.rename_share_link()}</DialogTitle>
<div className="flex min-w-0 items-center gap-1.5 pr-8">
<Input
ref={nameInputRef}
value={nameInput}
disabled={isRenaming}
onChange={(e) => setNameInput(e.target.value)}
onBlur={commitRename}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault()
commitRename()
} else if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
cancelEditRef.current = true
setIsEditingName(false)
}
}}
aria-label={m.rename_share_link()}
className="h-8 min-w-0 flex-1 text-sm font-semibold"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
aria-label={m.save()}
onMouseDown={(e) => e.preventDefault()}
onClick={commitRename}
>
<Check className="h-4 w-4" />
</Button>
</div>
</>
) : (
<DialogTitle className="flex w-full min-w-0 items-center gap-1.5 pr-8">
<span
className="min-w-0 truncate cursor-pointer hover:text-foreground/80"
onClick={startEditingName}
title={activeShare.name}
>
{activeShare.name}
</span>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0 text-muted-foreground hover:text-foreground"
aria-label={m.rename_share_link()}
onClick={startEditingName}
>
<Pencil className="h-3.5 w-3.5" />
</Button>
</DialogTitle>
)}
</DialogHeader>
<div className="min-w-0 space-y-4 py-1">
<div className="relative w-full min-w-0">
<Input
value={shareUrl}
readOnly
aria-label={m.share_link()}
className="pr-10 bg-muted/50 text-xs"
/>
<Button
type="button"
variant="ghost"
size="icon"
className="absolute right-0 top-0 h-full"
aria-label={m.copy_link()}
onClick={handleCopyLink}
>
{copied ? (
<Check className="h-4 w-4 text-emerald-500" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
<div className="min-w-0 rounded-lg border border-border bg-muted/20 p-3.5">
<ShareSecuritySettings shareLink={activeShare} inDialog />
</div>
</div>
<DialogFooter className="min-w-0 flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-between">
<Button
type="button"
variant="ghost"
size="sm"
className="w-fit gap-1 px-2 text-muted-foreground hover:text-foreground"
onClick={handleAdvancedSettings}
>
<span>{m.advanced_settings()}</span>
<ArrowUpRight className="h-4 w-4" />
</Button>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="outline" onClick={handleCopyLink} className="gap-2">
{copied ? (
<Check className="h-4 w-4 text-emerald-500" />
) : (
<Copy className="h-4 w-4" />
)}
<span>{m.copy_link()}</span>
</Button>
<Button type="button" onClick={() => onOpenChange(false)}>
{m.done()}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -0,0 +1,223 @@
import { client } from '@/ui/api/client'
import { DateTimePicker } from '@/ui/components/datetime-picker'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
import { Switch } from '@/ui/components/ui/switch'
import { WatermarkEditorDialog } from '@/ui/components/watermark-editor-dialog'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { ShareLinkInfo, UpdateShareLinkRequest } from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { toast } from 'sonner'
interface ShareSecuritySettingsProps {
shareLink: ShareLinkInfo
inDialog?: boolean
className?: string
}
export function ShareSecuritySettings({
shareLink,
inDialog = false,
className,
}: ShareSecuritySettingsProps) {
const queryClient = useQueryClient()
const [password, setPassword] = useState(shareLink.password || '')
const [expireAt, setExpireAt] = useState<Date | undefined>(
shareLink.expireAt ? new Date(shareLink.expireAt) : undefined,
)
const [isPasswordEnabled, setIsPasswordEnabled] = useState(shareLink.hasPassword)
const [isExpireEnabled, setIsExpireEnabled] = useState(!!shareLink.expireAt)
const [isWatermarkEditorOpen, setIsWatermarkEditorOpen] = useState(false)
useEffect(() => {
setPassword(shareLink.password || '')
}, [shareLink.password])
useEffect(() => {
setIsPasswordEnabled(shareLink.hasPassword)
setExpireAt(shareLink.expireAt ? new Date(shareLink.expireAt) : undefined)
setIsExpireEnabled(!!shareLink.expireAt)
}, [shareLink.id, shareLink.hasPassword, shareLink.expireAt])
const { data: watermarkInfo, refetch: refetchWatermark } = useQuery({
queryKey: ['share-watermark', shareLink.id],
queryFn: async () => {
const res = await client.api.shares[':shareId'].watermark.$get({
param: { shareId: shareLink.id },
})
if (!res.ok) return null
return await res.json()
},
refetchInterval: (query) => {
const status = query.state.data?.watermarkStatus || shareLink.watermarkStatus
return status === 'processing' ? 3000 : false
},
})
const $updateWatermark = client.api.shares[':shareId'].watermark.$put
const { mutate: disableWatermark } = useMutation({
mutationFn: async () => {
const res = await $updateWatermark({
param: { shareId: shareLink.id },
json: { enabled: false },
})
if (!res.ok) throw new Error(m.failed_update())
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
queryClient.invalidateQueries({ queryKey: ['share-watermark', shareLink.id] })
toast.success(m.watermark_disabled_msg())
},
})
const $updateShare = client.api.shares[':shareId'].$put
const { mutate: updateShare } = useMutation({
mutationFn: async (json: UpdateShareLinkRequest) => {
const res = await $updateShare({
param: { shareId: shareLink.id },
json,
})
if (!res.ok) throw new Error(m.failed_update())
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
toast.success(m.settings_updated())
},
})
const watermarkStatus =
watermarkInfo?.watermarkStatus ??
shareLink.watermarkStatus ??
(shareLink.watermarkConfigId ? 'ready' : 'disabled')
const watermarkConfig =
watermarkInfo?.watermarkConfig?.config ?? shareLink.watermarkConfig?.config ?? null
const isWatermarkEnabled = watermarkConfig !== null && watermarkStatus !== 'disabled'
return (
<>
<div className={cn('space-y-4', className)}>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.password()}</Label>
<Switch
checked={isPasswordEnabled}
onCheckedChange={(checked) => {
setIsPasswordEnabled(checked)
if (!checked) updateShare({ password: null })
}}
/>
</div>
{isPasswordEnabled && (
<div className="flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
<Input
type="text"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={m.enter_password()}
className="text-xs"
/>
<Button size="sm" onClick={() => updateShare({ password })}>
{m.save()}
</Button>
</div>
)}
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.expiration_date()}</Label>
<Switch
checked={isExpireEnabled}
onCheckedChange={(checked) => {
setIsExpireEnabled(checked)
if (!checked) {
setExpireAt(undefined)
updateShare({ expireAt: null })
}
}}
/>
</div>
{isExpireEnabled && (
<div className="animate-in fade-in slide-in-from-top-1 duration-200">
<DateTimePicker
modal={inDialog}
value={expireAt}
onChange={(date) => {
setExpireAt(date)
updateShare({ expireAt: date ? date.toISOString() : null })
}}
className="text-xs"
/>
</div>
)}
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.allow_download()}</Label>
<Switch
checked={shareLink.allowDownload}
onCheckedChange={(checked) => updateShare({ allowDownload: checked })}
/>
</div>
<p className="text-xs text-muted-foreground">{m.allow_download_description()}</p>
</div>
<div className="space-y-2 pt-2 border-t border-border/50">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.watermark()}</Label>
<Switch
checked={isWatermarkEnabled}
disabled={watermarkStatus === 'processing'}
onCheckedChange={(checked) => {
if (!checked) {
disableWatermark()
} else {
setIsWatermarkEditorOpen(true)
}
}}
/>
</div>
{isWatermarkEnabled && watermarkStatus === 'processing' && (
<div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
<span>{m.watermark_transcoding_processing()}</span>
</div>
)}
{isWatermarkEnabled && watermarkStatus !== 'processing' && (
<Button
variant="outline"
size="sm"
className="w-full text-xs gap-1.5 mt-1"
onClick={() => setIsWatermarkEditorOpen(true)}
>
{m.edit_watermark()}
</Button>
)}
</div>
</div>
<WatermarkEditorDialog
open={isWatermarkEditorOpen}
onOpenChange={setIsWatermarkEditorOpen}
initialConfig={watermarkConfig}
shareId={shareLink.id}
onSaveSuccess={() => {
refetchWatermark()
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
}}
/>
</>
)
}
@@ -1,5 +1,5 @@
import { client } from '@/ui/api/client'
import { DateTimePicker } from '@/ui/components/datetime-picker'
import { ShareSecuritySettings } from '@/ui/components/share-security-settings'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { Label } from '@/ui/components/ui/label'
@@ -11,7 +11,6 @@ import {
SelectValue,
} from '@/ui/components/ui/select'
import { Switch } from '@/ui/components/ui/switch'
import { WatermarkEditorDialog } from '@/ui/components/watermark-editor-dialog'
import { copyToClipboard as copyTextToClipboard } from '@/ui/lib/clipboard'
import { m } from '@/ui/paraglide/messages.js'
import {
@@ -28,7 +27,6 @@ import {
LayoutGrid,
List,
ListFilter,
Loader2,
Palette,
Shield,
SortAsc,
@@ -52,58 +50,6 @@ export function ShareSettingsSidebar({
onSortOrderChange,
}: ShareSettingsSidebarProps) {
const queryClient = useQueryClient()
const [password, setPassword] = useState(shareLink.password || '')
const [expireAt, setExpireAt] = useState<Date | undefined>(
shareLink.expireAt ? new Date(shareLink.expireAt) : undefined,
)
const [isWatermarkEditorOpen, setIsWatermarkEditorOpen] = useState(false)
React.useEffect(() => {
setPassword(shareLink.password || '')
}, [shareLink.password])
const [isPasswordEnabled, setIsPasswordEnabled] = useState(shareLink.hasPassword)
const [isExpireEnabled, setIsExpireEnabled] = useState(!!shareLink.expireAt)
const { data: watermarkInfo, refetch: refetchWatermark } = useQuery({
queryKey: ['share-watermark', shareLink.id],
queryFn: async () => {
const res = await client.api.shares[':shareId'].watermark.$get({
param: { shareId: shareLink.id },
})
if (!res.ok) return null
return await res.json()
},
refetchInterval: (query) => {
const status = query.state.data?.watermarkStatus || shareLink.watermarkStatus
return status === 'processing' ? 3000 : false
},
})
const $updateWatermark = client.api.shares[':shareId'].watermark.$put
const { mutate: disableWatermark } = useMutation({
mutationFn: async () => {
const res = await $updateWatermark({
param: { shareId: shareLink.id },
json: { enabled: false },
})
if (!res.ok) throw new Error(m.failed_update())
return await res.json()
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
queryClient.invalidateQueries({ queryKey: ['share-watermark', shareLink.id] })
toast.success(m.watermark_disabled_msg())
},
})
const watermarkStatus =
watermarkInfo?.watermarkStatus ??
shareLink.watermarkStatus ??
(shareLink.watermarkConfigId ? 'ready' : 'disabled')
const watermarkConfig =
watermarkInfo?.watermarkConfig?.config ?? shareLink.watermarkConfig?.config ?? null
const isWatermarkEnabled = watermarkConfig !== null && watermarkStatus !== 'disabled'
const { data: fields } = useQuery({
queryKey: ['fields', shareLink.projectId],
@@ -186,107 +132,7 @@ export function ShareSettingsSidebar({
<div className="space-y-1">
<SidebarAccordionItem title={m.security()} icon={<Shield className="h-4 w-4" />}>
<div className="p-3 space-y-4 pt-2">
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.password()}</Label>
<Switch
checked={isPasswordEnabled}
onCheckedChange={(checked) => {
setIsPasswordEnabled(checked)
if (!checked) updateShare({ password: null })
}}
/>
</div>
{isPasswordEnabled && (
<div className="flex gap-2 animate-in fade-in slide-in-from-top-1 duration-200">
<Input
type="text"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder={m.enter_password()}
className="text-xs"
/>
<Button size="sm" onClick={() => updateShare({ password })}>
{m.save()}
</Button>
</div>
)}
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.expiration_date()}</Label>
<Switch
checked={isExpireEnabled}
onCheckedChange={(checked) => {
setIsExpireEnabled(checked)
if (!checked) {
setExpireAt(undefined)
updateShare({ expireAt: null })
}
}}
/>
</div>
{isExpireEnabled && (
<div className="animate-in fade-in slide-in-from-top-1 duration-200">
<DateTimePicker
value={expireAt}
onChange={(date) => {
setExpireAt(date)
updateShare({ expireAt: date ? date.toISOString() : null })
}}
className="text-xs"
/>
</div>
)}
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.allow_download()}</Label>
<Switch
checked={shareLink.allowDownload}
onCheckedChange={(checked) => updateShare({ allowDownload: checked })}
/>
</div>
<p className="text-xs text-muted-foreground">{m.allow_download_description()}</p>
</div>
<div className="space-y-2 pt-2 border-t border-border/50">
<div className="flex items-center justify-between">
<Label className="text-xs">{m.watermark()}</Label>
<Switch
checked={isWatermarkEnabled}
disabled={watermarkStatus === 'processing'}
onCheckedChange={(checked) => {
if (!checked) {
disableWatermark()
} else {
setIsWatermarkEditorOpen(true)
}
}}
/>
</div>
{isWatermarkEnabled && watermarkStatus === 'processing' && (
<div className="flex items-center gap-2 text-xs text-amber-600 dark:text-amber-400 font-medium py-1 animate-pulse">
<Loader2 className="h-3.5 w-3.5 animate-spin" />
<span>{m.watermark_transcoding_processing()}</span>
</div>
)}
{isWatermarkEnabled && watermarkStatus !== 'processing' && (
<Button
variant="outline"
size="sm"
className="w-full text-xs gap-1.5 mt-1"
onClick={() => setIsWatermarkEditorOpen(true)}
>
{m.edit_watermark()}
</Button>
)}
</div>
</div>
<ShareSecuritySettings shareLink={shareLink} className="p-3 pt-2" />
</SidebarAccordionItem>
<SidebarAccordionItem title={m.appearance()} icon={<Palette className="h-4 w-4" />}>
<div className="p-3 space-y-3 pt-2 flex gap-2">
@@ -403,18 +249,6 @@ export function ShareSettingsSidebar({
{m.copy_link()}
</Button>
</div>
<WatermarkEditorDialog
open={isWatermarkEditorOpen}
onOpenChange={setIsWatermarkEditorOpen}
initialConfig={watermarkConfig}
shareId={shareLink.id}
onSaveSuccess={() => {
refetchWatermark()
queryClient.invalidateQueries({ queryKey: ['share', shareLink.id] })
queryClient.invalidateQueries({ queryKey: ['shares', shareLink.projectId] })
}}
/>
</div>
)
}
+8
View File
@@ -66,6 +66,10 @@ export function TopNav() {
onDelete,
onArchive,
onRestoreArchive,
shareLinks,
onCreateShareLink,
onAddToShareLink,
isShareActionPending,
compareMode,
canCompareVersions,
onCompareVersions,
@@ -166,6 +170,10 @@ export function TopNav() {
onDelete={onDelete}
onArchive={onArchive}
onRestoreArchive={onRestoreArchive}
shareLinks={shareLinks}
onCreateShareLink={onCreateShareLink}
onAddToShareLink={onAddToShareLink}
isShareActionPending={isShareActionPending}
compareMode={compareMode}
canCompareVersions={canCompareVersions}
onCompareVersions={onCompareVersions}
+77 -1
View File
@@ -1,5 +1,14 @@
import { type ReactElement, useCallback, useEffect, useRef, useState } from 'react'
import ReactDOM from 'react-dom/client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import {
RouterProvider,
createMemoryHistory,
createRootRoute,
createRouter,
} from '@tanstack/react-router'
import type { ShareLinkInfo } from '@shumai/dtos'
import { ShareLinkCreatedDialog } from '@/ui/components/share-link-created-dialog'
import type { MediaController } from '@/ui/components/viewers/types'
import VideoPlayer from '@/ui/components/viewers/video/video-viewer'
import ModelViewer from '@/ui/components/viewers/model/model-viewer'
@@ -269,6 +278,67 @@ function UploaderHarness(): ReactElement {
)
}
function ShareDialogHarness(): ReactElement {
const nameParam =
typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('name') : null
const shareName =
nameParam || 'Client_Delivery_2026_11_24_Final_Master_ProRes422HQ_v04_ColorGraded_Stereo.mov'
const [queryClient] = useState(
() =>
new QueryClient({
defaultOptions: {
queries: { retry: false, enabled: false },
},
}),
)
const [router] = useState(() => {
const rootRoute = createRootRoute({
component: () => {
const mockShare: ShareLinkInfo = {
id: '01K9XYZABCDEFGHJKLMNPQRSTV',
name: shareName,
isDisabled: false,
allowDownload: true,
hasPassword: false,
password: null,
rootFolderId: 'rf-1',
projectId: 'proj-1',
isExpired: false,
watermarkConfigId: null,
watermarkStatus: 'disabled',
watermarkConfig: null,
createdAt: '2026-11-24T00:00:00.000Z',
updatedAt: '2026-11-24T00:00:00.000Z',
creator: null,
}
return (
<div className="p-6">
<Toaster position="top-right" />
<ShareLinkCreatedDialog
open={true}
onOpenChange={() => {}}
shareLink={mockShare}
projectId="proj-1"
/>
</div>
)
},
})
return createRouter({
routeTree: rootRoute,
history: createMemoryHistory({ initialEntries: ['/'] }),
})
})
return (
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
</QueryClientProvider>
)
}
const rootElement = document.getElementById('root')
if (!rootElement) {
throw new Error('Harness root element not found')
@@ -278,5 +348,11 @@ const currentView =
typeof window !== 'undefined' ? new URLSearchParams(window.location.search).get('view') : null
ReactDOM.createRoot(rootElement).render(
currentView === 'uploader' ? <UploaderHarness /> : <Harness />,
currentView === 'uploader' ? (
<UploaderHarness />
) : currentView === 'share-dialog' ? (
<ShareDialogHarness />
) : (
<Harness />
),
)
@@ -0,0 +1,63 @@
import { expect, test, type Locator } from '@playwright/test'
async function assertNoHorizontalOverflow(dialog: Locator, viewportWidth: number) {
const metrics = await dialog.evaluate((el) => {
const dialogRect = el.getBoundingClientRect()
const overflowing: Array<{ tag: string; text: string; right: number; dialogRight: number }> = []
for (const child of el.querySelectorAll('*')) {
const rect = child.getBoundingClientRect()
if (rect.width === 0 || rect.height === 0) continue
if (rect.right > dialogRect.right + 1 || rect.left < dialogRect.left - 1) {
overflowing.push({
tag: child.tagName.toLowerCase(),
text: (child.textContent || '').trim().slice(0, 60),
right: Math.round(rect.right),
dialogRight: Math.round(dialogRect.right),
})
}
}
return {
clientWidth: el.clientWidth,
scrollWidth: el.scrollWidth,
dialogWidth: Math.round(dialogRect.width),
overflowing,
}
})
expect(metrics.dialogWidth).toBeLessThanOrEqual(viewportWidth)
expect(metrics.scrollWidth, JSON.stringify(metrics)).toBeLessThanOrEqual(metrics.clientWidth)
expect(metrics.overflowing, JSON.stringify(metrics)).toEqual([])
}
test.describe('ShareLinkCreatedDialog layout', () => {
for (const viewport of [
{ name: 'desktop', width: 1280, height: 800 },
{ name: 'mobile', width: 375, height: 812 },
]) {
test(`does not overflow horizontally on ${viewport.name} across default, edit, and expanded security states`, async ({
page,
}) => {
await page.setViewportSize({ width: viewport.width, height: viewport.height })
await page.goto('/?view=share-dialog')
const dialog = page.getByRole('dialog')
await expect(dialog).toBeVisible()
// Default state with a very long unbroken share name
await assertNoHorizontalOverflow(dialog, viewport.width)
// Inline edit mode
await dialog.getByRole('button', { name: 'Rename Share Link' }).click()
await expect(dialog.getByRole('textbox', { name: 'Rename Share Link' })).toBeVisible()
await assertNoHorizontalOverflow(dialog, viewport.width)
await dialog.getByRole('textbox', { name: 'Rename Share Link' }).press('Escape')
// Expanded Password and Expiration Date controls
const switches = dialog.getByRole('switch')
await switches.nth(0).click()
await switches.nth(1).click()
await expect(dialog.getByPlaceholder('Enter password')).toBeVisible()
await assertNoHorizontalOverflow(dialog, viewport.width)
})
}
})
@@ -0,0 +1,124 @@
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import type { ShareLinkInfo } from '@shumai/dtos'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useCallback, useState } from 'react'
import { toast } from 'sonner'
export interface ShareableAssetTarget {
id?: string
name: string
}
const EMPTY_SHARE_LINKS: ShareLinkInfo[] = []
interface UseShareLinkActionsOptions {
projectId: string
enabled?: boolean
}
export function useShareLinkActions({ projectId, enabled = true }: UseShareLinkActionsOptions) {
const queryClient = useQueryClient()
const navigate = useNavigate()
const [createdShareLink, setCreatedShareLink] = useState<ShareLinkInfo | null>(null)
const { data: shareLinksData } = useQuery({
queryKey: ['shares', projectId, 'list'],
queryFn: async () => {
const res = await client.api.projects[':projectId'].shares.$get({
param: { projectId },
query: { first: '100' },
})
if (!res.ok) throw new Error(m.failed_fetch_share_links())
return (await res.json()) as unknown as { data: ShareLinkInfo[] }
},
enabled: !!projectId && enabled,
})
const { mutate: createShareLink, isPending: isCreatingShareLink } = useMutation({
mutationFn: async (items: ShareableAssetTarget[]) => {
const assetIds = items.map((i) => i.id).filter((id): id is string => Boolean(id))
if (assetIds.length === 0) {
throw new Error(m.failed_create_share_link())
}
const name =
items.length === 1
? items[0].name
: new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
})
const res = await client.api.projects[':projectId'].shares.$post({
param: { projectId },
json: { name },
})
if (!res.ok) throw new Error(m.failed_create_share_link())
const share = (await res.json()) as unknown as ShareLinkInfo
const assetsRes = await client.api.shares[':shareId'].assets.$post({
param: { shareId: share.id },
json: { assetIds },
})
if (!assetsRes.ok) throw new Error(m.failed_add_to_share_link())
return share
},
onSuccess: (share) => {
queryClient.invalidateQueries({ queryKey: ['shares', projectId] })
setCreatedShareLink(share)
},
onError: () => {
toast.error(m.failed_create_share_link())
},
})
const { mutate: addToShareLink, isPending: isAddingToShareLink } = useMutation({
mutationFn: async ({ shareId, items }: { shareId: string; items: ShareableAssetTarget[] }) => {
const assetIds = items.map((i) => i.id).filter((id): id is string => Boolean(id))
if (assetIds.length === 0) {
throw new Error(m.failed_add_to_share_link())
}
const res = await client.api.shares[':shareId'].assets.$post({
param: { shareId },
json: { assetIds },
})
if (!res.ok) throw new Error(m.failed_add_to_share_link())
return { shareId }
},
onSuccess: ({ shareId }) => {
toast.success(m.added_to_share_link(), {
action: {
label: m.view(),
onClick: () =>
navigate({
to: '/projects/$projectId/shares/$shareId',
params: { projectId, shareId },
}),
},
})
},
onError: () => {
toast.error(m.failed_add_to_share_link())
},
})
const clearCreatedShareLink = useCallback(() => {
setCreatedShareLink(null)
}, [])
return {
shareLinks: shareLinksData?.data ?? EMPTY_SHARE_LINKS,
createShareLink,
addToShareLink,
isCreatingShareLink,
isAddingToShareLink,
isShareActionPending: isCreatingShareLink || isAddingToShareLink,
createdShareLink,
clearCreatedShareLink,
}
}
+3 -1
View File
@@ -1758,5 +1758,7 @@
"agent_runner_description": "Select which runner executes shell commands and downloads workspace assets for this agent.",
"agent_runner_team_default": "Team Default Runner",
"agent_runner_team_default_with_name": "Team Default ({name})",
"agent_runner_none_configured_warning": "No runners are configured for this team yet. The bash and download_asset tools will remain unavailable until you register a runner in Team Settings → Agent Runners."
"agent_runner_none_configured_warning": "No runners are configured for this team yet. The bash and download_asset tools will remain unavailable until you register a runner in Team Settings → Agent Runners.",
"advanced_settings": "Advanced settings",
"failed_add_to_share_link": "Failed to add to share link"
}
+3 -1
View File
@@ -1688,5 +1688,7 @@
"agent_runner_description": "이 에이전트의 셸 명령을 실행하고 워크스페이스 에셋을 다운로드할 러너를 선택합니다.",
"agent_runner_team_default": "팀 기본 러너",
"agent_runner_team_default_with_name": "팀 기본({name})",
"agent_runner_none_configured_warning": "이 팀에 아직 구성된 러너가 없습니다. 팀 설정 → 에이전트 러너에서 러너를 등록할 때까지 bash 및 download_asset 도구를 사용할 수 없습니다."
"agent_runner_none_configured_warning": "이 팀에 아직 구성된 러너가 없습니다. 팀 설정 → 에이전트 러너에서 러너를 등록할 때까지 bash 및 download_asset 도구를 사용할 수 없습니다.",
"advanced_settings": "고급 설정",
"failed_add_to_share_link": "공유 링크에 추가하지 못했습니다"
}
+3 -1
View File
@@ -1758,5 +1758,7 @@
"agent_runner_description": "选择为该 Agent 执行命令和下载工作空间资产的运行器。",
"agent_runner_team_default": "团队默认运行器",
"agent_runner_team_default_with_name": "团队默认({name})",
"agent_runner_none_configured_warning": "当前团队尚未配置任何运行器。在“团队设置 → Agent 运行器”中注册运行器之前,bash 和 download_asset 工具将不可用。"
"agent_runner_none_configured_warning": "当前团队尚未配置任何运行器。在“团队设置 → Agent 运行器”中注册运行器之前,bash 和 download_asset 工具将不可用。",
"advanced_settings": "高级设置",
"failed_add_to_share_link": "添加到分享链接失败"
}
@@ -9,8 +9,11 @@ import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sideba
import { MobileFileDetail } from '@/ui/components/file-viewer/mobile-file-detail'
import { FileDetailSkeleton } from '@/ui/components/loading-skeletons'
import { ResizeHandle } from '@/ui/components/resize-handle'
import { ShareLinkCreatedDialog } from '@/ui/components/share-link-created-dialog'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useIsMobile } from '@/ui/hooks/use-mobile'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useShareLinkActions } from '@/ui/hooks/use-share-link-actions'
import { m } from '@/ui/paraglide/messages.js'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import { useChatbotStore } from '@/ui/stores/chatbot'
@@ -67,6 +70,15 @@ function FileViewPage() {
const mediaControllerRef = useRef<MediaController | null>(null)
const { archiveStorageEnabled } = useArchiveConfig()
const { canEdit } = usePermissions(projectId)
const {
shareLinks,
createShareLink,
addToShareLink,
isShareActionPending,
createdShareLink,
clearCreatedShareLink,
} = useShareLinkActions({ projectId, enabled: canEdit })
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
const [rightSidebarWidth, setRightSidebarWidth] = useState(360)
const [annotations, setAnnotations] = useState<Annotation[]>([])
@@ -406,6 +418,17 @@ function FileViewPage() {
onRestoreArchive: () => {
setArchiveConfirmState({ open: true, mode: 'restore' })
},
shareLinks,
onCreateShareLink: () => {
createShareLink([{ id: fileId, name: stackData?.name ?? fileData.name }])
},
onAddToShareLink: (targetShareId: string) => {
addToShareLink({
shareId: targetShareId,
items: [{ id: fileId, name: stackData?.name ?? fileData.name }],
})
},
isShareActionPending,
})
}
@@ -415,10 +438,15 @@ function FileViewPage() {
projectId,
projectInfo,
fileData,
stackData?.name,
versionsDataList,
activeFileId,
fileId,
isCompareMode,
shareLinks,
createShareLink,
addToShareLink,
isShareActionPending,
setProjectState,
clearProjectState,
navigate,
@@ -747,8 +775,27 @@ function FileViewPage() {
? () => setArchiveConfirmState({ open: true, mode: 'restore' })
: undefined
}
shareLinks={shareLinks}
onCreateShareLink={() => {
createShareLink([{ id: fileId, name: stackData?.name ?? fileData.name }])
}}
onAddToShareLink={(targetShareId) => {
addToShareLink({
shareId: targetShareId,
items: [{ id: fileId, name: stackData?.name ?? fileData.name }],
})
}}
isShareActionPending={isShareActionPending}
onSaveField={handleSaveField}
/>
<ShareLinkCreatedDialog
open={!!createdShareLink}
onOpenChange={(open) => {
if (!open) clearCreatedShareLink()
}}
shareLink={createdShareLink}
projectId={projectId}
/>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
@@ -917,6 +964,15 @@ function FileViewPage() {
</AlertDialogContent>
</AlertDialog>
<ShareLinkCreatedDialog
open={!!createdShareLink}
onOpenChange={(open) => {
if (!open) clearCreatedShareLink()
}}
shareLink={createdShareLink}
projectId={projectId}
/>
<ArchiveConfirmDialog
open={archiveConfirmState.open}
onOpenChange={(open) => setArchiveConfirmState((prev) => ({ ...prev, open }))}
+5 -1
View File
@@ -1,5 +1,5 @@
import { create } from 'zustand'
import type { AncestorFolder } from '@shumai/dtos'
import type { AncestorFolder, ShareLinkInfo } from '@shumai/dtos'
export interface TopNavProjectState {
teamId: string
@@ -46,6 +46,10 @@ export interface TopNavProjectState {
onDelete?: () => void
onArchive?: () => void
onRestoreArchive?: () => void
shareLinks?: ShareLinkInfo[]
onCreateShareLink?: () => void
onAddToShareLink?: (shareId: string) => void
isShareActionPending?: boolean
isRightSidebarCollapsed?: boolean
onRightSidebarToggle?: () => void
// Compare Versions