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
@@ -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}