feat(file-browser): add context-aware copy submenu (#517)

* feat(file-browser): add context-aware copy submenu

* refactor(file-browser): address code review feedback for copy submenu

* fix(webui): align submenu trigger text and widen file context menu

* test(e2e): guard clipboard permissions in copy-menu spec for cross-browser support
This commit is contained in:
Yiling-J
2026-11-05 09:57:34 +08:00
committed by GitHub
parent 2ecbd49d18
commit 0dc0bbeb03
30 changed files with 2285 additions and 106 deletions
@@ -80,4 +80,19 @@ describe('FileBrowserContextMenu', () => {
expect(screen.queryByText(/Manage versions|管理版本/i)).toBeNull()
})
it('renders Copy submenu trigger for regular file item with aligned gap-2 and w-52 menu width', () => {
renderWithMenu(fileItem)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
const copyOption = screen.getByText(/^Copy$|^复制$/i)
expect(copyOption).toBeTruthy()
const trigger = copyOption.closest('[data-slot="context-menu-sub-trigger"]')
expect(trigger?.className).toContain('gap-2')
const menuContent = copyOption.closest('[data-slot="context-menu-content"]')
expect(menuContent?.className).toContain('w-52')
})
})
@@ -26,6 +26,8 @@ import {
Copy,
Layers,
} from 'lucide-react'
import { CopyContextMenuSub } from './copy-submenu'
import type { CopyKind } from './copy-options'
interface FileBrowserContextMenuProps {
item: AssetInfo | null
@@ -33,11 +35,13 @@ interface FileBrowserContextMenuProps {
onRename: (item: AssetInfo) => void
onDelete: (items: AssetInfo[]) => void
onDownload: (items: AssetInfo[]) => void
onCopyNameAndDownloadLink?: (items: AssetInfo[]) => void
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
onRestore: (items: AssetInfo[]) => void
onArchive?: (items: AssetInfo[]) => void
onRestoreArchive?: (items: AssetInfo[]) => void
archiveStorageEnabled?: boolean
isTeamOwner?: boolean
allowDownload?: boolean
onNewFolder: (name: string) => void
onUploadFile: () => void
onUploadFolder: () => void
@@ -64,11 +68,13 @@ export function FileBrowserContextMenu({
onRename,
onDelete,
onDownload,
onCopyNameAndDownloadLink,
onCopy,
onRestore,
onArchive,
onRestoreArchive,
archiveStorageEnabled = false,
isTeamOwner = false,
allowDownload = true,
onNewFolder,
onUploadFile,
onUploadFolder,
@@ -113,14 +119,6 @@ export function FileBrowserContextMenu({
}
}
const handleCopyNameAndDownloadLink = () => {
if (isItemSelected) {
onCopyNameAndDownloadLink?.(selectedItems)
} else if (item) {
onCopyNameAndDownloadLink?.([item])
}
}
const handleRestore = () => {
onRestore(itemsToRestore)
}
@@ -162,15 +160,11 @@ export function FileBrowserContextMenu({
if (isShareView) {
if (!item) return null
return (
<ContextMenuContent>
<ContextMenuContent className="w-52">
<ContextMenuItem onSelect={handleDownload}>
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink}>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy_name_and_download_link()}</span>
</ContextMenuItem>
{canEdit && (
<ContextMenuItem
onSelect={() => onRemoveFromShare?.(itemsToModify)}
@@ -189,7 +183,7 @@ export function FileBrowserContextMenu({
return null
}
return (
<ContextMenuContent>
<ContextMenuContent className="w-52">
<ContextMenuItem onSelect={handleRestore}>
<History className="mr-2 h-4 w-4" />
<span>{m.restore()}</span>
@@ -203,6 +197,7 @@ export function FileBrowserContextMenu({
// Right-click on empty area
return (
<ContextMenuContent
className="w-52"
onCloseAutoFocus={(e) => {
e.preventDefault()
}}
@@ -230,6 +225,7 @@ export function FileBrowserContextMenu({
const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? (
<ContextMenuContent
className="w-52"
onCloseAutoFocus={(e) => {
e.preventDefault()
}}
@@ -238,10 +234,14 @@ export function FileBrowserContextMenu({
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink} disabled={isDownloadUnavailable}>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy_name_and_download_link()}</span>
</ContextMenuItem>
<CopyContextMenuSub
items={itemsToModify}
context={{
isTeamOwner,
allowDownload,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
{canEdit && (
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
<ArrowRight className="mr-2 h-4 w-4" />
@@ -294,7 +294,7 @@ export function FileBrowserContextMenu({
<span>{m.add_to_share_links()}</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent className="w-48">
<ContextMenuSubContent className="w-52">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
@@ -312,6 +312,7 @@ export function FileBrowserContextMenu({
</ContextMenuContent>
) : (
<ContextMenuContent
className="w-52"
onCloseAutoFocus={(e) => {
e.preventDefault()
}}
@@ -330,10 +331,14 @@ export function FileBrowserContextMenu({
<Download className="mr-2 h-4 w-4" />
<span>{m.download()}</span>
</ContextMenuItem>
<ContextMenuItem onSelect={handleCopyNameAndDownloadLink} disabled={isDownloadUnavailable}>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy_name_and_download_link()}</span>
</ContextMenuItem>
<CopyContextMenuSub
items={itemsToModify}
context={{
isTeamOwner,
allowDownload,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
{canEdit && (
<ContextMenuItem onSelect={() => onMoveTo(itemsToModify)}>
@@ -409,7 +414,7 @@ export function FileBrowserContextMenu({
<span>{m.add_to_share_links()}</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent className="w-48">
<ContextMenuSubContent className="w-52">
{shareLinks.map((share) => (
<ContextMenuItem
key={share.id}
@@ -0,0 +1,282 @@
import { describe, it, expect } from 'vitest'
import type { AssetInfo } from '@shumai/dtos'
import {
isImageItem,
pickClipboardTranscode,
getCopyOptions,
formatCopyText,
getItemInAppUrl,
} from './copy-options'
describe('copy-options', () => {
const dummyFile: AssetInfo = {
id: 'file-1',
name: 'document.pdf',
type: 'file',
status: 'processed',
sizeByte: 1024 * 1024,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
}
const dummyImage: AssetInfo = {
id: 'image-1',
name: 'photo.jpg',
type: 'file',
proxyType: 'image',
status: 'processed',
sizeByte: 2 * 1024 * 1024,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
media: {
imageTranscodes: [
{ id: 't1', key: 'k1', url: 'https://cdn/1080.webp', width: 1920, height: 1080, size: 200 },
{ id: 't2', key: 'k2', url: 'https://cdn/3000.webp', width: 3000, height: 2000, size: 500 },
],
},
}
const dummyFolder: AssetInfo = {
id: 'folder-1',
name: 'Assets',
type: 'folder',
status: 'processed',
sizeByte: 0,
fileCount: 5,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
}
const dummyVersionStack: AssetInfo = {
id: 'stack-1',
name: 'render.png',
type: 'version_stack',
proxyType: 'image',
status: 'processed',
sizeByte: 5 * 1024 * 1024,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
versionStack: {
id: 'stack-1',
versions: [
{ version: 2, current: true, id: 'child-2' },
{ version: 1, current: false, id: 'child-1' },
],
},
media: {
imageTranscodes: [
{
id: 't1',
key: 'k1',
url: 'https://cdn/render-1080.webp',
width: 1920,
height: 1080,
size: 200,
},
],
},
}
describe('isImageItem', () => {
it('detects images by proxyType and extension', () => {
expect(isImageItem(dummyImage)).toBe(true)
expect(isImageItem({ ...dummyFile, name: 'graphic.png' })).toBe(true)
expect(isImageItem(dummyVersionStack)).toBe(true)
expect(isImageItem(dummyFile)).toBe(false)
expect(isImageItem(dummyFolder)).toBe(false)
})
})
describe('pickClipboardTranscode', () => {
it('picks largest transcode <= 2048px on long edge', () => {
const transcode = pickClipboardTranscode(dummyImage.media?.imageTranscodes)
expect(transcode?.url).toBe('https://cdn/1080.webp')
})
it('falls back to smallest available if all > 2048px', () => {
const transcode = pickClipboardTranscode([
{ url: 'https://cdn/4000.webp', width: 4000, height: 3000 },
{ url: 'https://cdn/2500.webp', width: 2500, height: 2000 },
])
expect(transcode?.url).toBe('https://cdn/2500.webp')
})
it('picks transcode by key even without presigned url', () => {
const transcode = pickClipboardTranscode([
{ key: 'files/asset-768p.webp', width: 768, height: 1376 },
])
expect(transcode?.key).toBe('files/asset-768p.webp')
})
it('returns null if empty or missing', () => {
expect(pickClipboardTranscode([])).toBeNull()
expect(pickClipboardTranscode(undefined)).toBeNull()
})
})
describe('getCopyOptions', () => {
it('returns options for single image file with team owner', () => {
const options = getCopyOptions([dummyImage], { isTeamOwner: true })
const kinds = options.map((o) => o.kind)
expect(kinds).toEqual([
'image',
'name',
'link',
'download-link',
'id',
'markdown',
'storage-path',
])
expect(options.find((o) => o.kind === 'image')?.disabled).toBe(false)
expect(options.find((o) => o.kind === 'download-link')?.disabled).toBe(false)
})
it('enables image option for processed image file with only transcode key and no url', () => {
const imageWithoutUrls: AssetInfo = {
...dummyImage,
media: {
imageTranscodes: [
{
id: 't1',
key: 'files/asset-768p.webp',
url: '',
width: 768,
height: 1376,
size: 200,
},
],
},
}
const options = getCopyOptions([imageWithoutUrls])
expect(options.find((o) => o.kind === 'image')?.disabled).toBe(false)
})
it('hides image option for non-image files', () => {
const options = getCopyOptions([dummyFile], { isTeamOwner: true })
const kinds = options.map((o) => o.kind)
expect(kinds).not.toContain('image')
expect(kinds).toContain('download-link')
expect(kinds).toContain('storage-path')
})
it('hides download-link and storage-path for single folder', () => {
const options = getCopyOptions([dummyFolder], { isTeamOwner: true })
const kinds = options.map((o) => o.kind)
expect(kinds).toEqual(['name', 'link', 'id', 'markdown'])
expect(kinds).not.toContain('download-link')
expect(kinds).not.toContain('storage-path')
})
it('handles multi-select with only files', () => {
const options = getCopyOptions([dummyFile, dummyImage], { isTeamOwner: true })
const kinds = options.map((o) => o.kind)
expect(kinds).toEqual([
'name',
'link',
'download-link',
'id',
'markdown',
'tsv',
'storage-path',
])
expect(kinds).not.toContain('image')
})
it('hides download-link and storage-path when all items in multi-select are folders', () => {
const folder2 = { ...dummyFolder, id: 'folder-2', name: 'Folder 2' }
const options = getCopyOptions([dummyFolder, folder2], { isTeamOwner: true })
const kinds = options.map((o) => o.kind)
expect(kinds).toEqual(['name', 'link', 'id', 'markdown', 'tsv'])
expect(kinds).not.toContain('download-link')
expect(kinds).not.toContain('storage-path')
})
it('disables download-link if all files in selection are archived', () => {
const archivedFile: AssetInfo = { ...dummyFile, status: 'archived' }
const options = getCopyOptions([archivedFile])
expect(options.find((o) => o.kind === 'download-link')?.disabled).toBe(true)
})
it('hides id and storage-path in public share mode', () => {
const options = getCopyOptions([dummyFile], { isPublicShare: true, isTeamOwner: true })
const kinds = options.map((o) => o.kind)
expect(kinds).not.toContain('id')
expect(kinds).not.toContain('storage-path')
})
})
describe('getItemInAppUrl', () => {
it('formats URL for file and folder', () => {
expect(getItemInAppUrl(dummyFile, 'https://shumai.app', 'proj-1')).toBe(
'https://shumai.app/projects/proj-1/files/file-1',
)
expect(getItemInAppUrl(dummyFolder, 'https://shumai.app', 'proj-1')).toBe(
'https://shumai.app/projects/proj-1/folders/folder-1',
)
expect(getItemInAppUrl(dummyVersionStack, 'https://shumai.app', 'proj-1')).toBe(
'https://shumai.app/projects/proj-1/files/stack-1',
)
})
})
describe('formatCopyText', () => {
const ctx = { origin: 'https://shumai.app', projectId: 'proj-1' }
it('formats name for single and multi-select', () => {
expect(formatCopyText('name', [dummyFile], ctx)).toBe('document.pdf')
expect(formatCopyText('name', [dummyFile, dummyFolder], ctx)).toBe('document.pdf\nAssets')
})
it('formats link for single and multi-select', () => {
expect(formatCopyText('link', [dummyFile], ctx)).toBe(
'https://shumai.app/projects/proj-1/files/file-1',
)
expect(formatCopyText('link', [dummyFile, dummyFolder], ctx)).toBe(
'https://shumai.app/projects/proj-1/files/file-1\nhttps://shumai.app/projects/proj-1/folders/folder-1',
)
})
it('formats id for single and multi-select', () => {
expect(formatCopyText('id', [dummyFile], ctx)).toBe('file-1')
expect(formatCopyText('id', [dummyVersionStack], ctx)).toBe('stack-1')
expect(formatCopyText('id', [dummyFile, dummyFolder], ctx)).toBe('file-1\nfolder-1')
})
it('formats markdown link for single and bullet list for multi-select', () => {
expect(formatCopyText('markdown', [dummyFile], ctx)).toBe(
'[document.pdf](https://shumai.app/projects/proj-1/files/file-1)',
)
expect(formatCopyText('markdown', [dummyFile, dummyFolder], ctx)).toBe(
'- [document.pdf](https://shumai.app/projects/proj-1/files/file-1)\n- [Assets](https://shumai.app/projects/proj-1/folders/folder-1)',
)
})
it('formats TSV table with header and sizes for multi-select', () => {
const tsv = formatCopyText('tsv', [dummyFile, dummyFolder], ctx)
const lines = tsv.split('\n')
expect(lines[0]).toBe('Name\tType\tSize\tLink\tID')
expect(lines[1]).toContain(
'document.pdf\tfile\t1.05 MB\thttps://shumai.app/projects/proj-1/files/file-1\tfile-1',
)
expect(lines[2]).toContain(
'Assets\tfolder\t—\thttps://shumai.app/projects/proj-1/folders/folder-1\tfolder-1',
)
})
it('escapes brackets in markdown links', () => {
const fileWithBrackets = { ...dummyFile, name: 'Report [Final] (v1).pdf' }
expect(formatCopyText('markdown', [fileWithBrackets], ctx)).toBe(
'[Report \\[Final\\] (v1).pdf](https://shumai.app/projects/proj-1/files/file-1)',
)
})
it('sanitizes tabs and newlines in TSV file names', () => {
const fileWithTabs = { ...dummyFile, name: 'test\tfile\nname.pdf' }
const tsv = formatCopyText('tsv', [fileWithTabs], ctx)
expect(tsv).toContain('test file name.pdf\tfile\t1.05 MB')
})
})
})
@@ -0,0 +1,212 @@
import type { AssetInfo } from '@shumai/dtos'
import { formatSize } from '@/ui/lib/format'
export type CopyKind =
'image' | 'name' | 'link' | 'download-link' | 'id' | 'markdown' | 'tsv' | 'storage-path'
export interface CopyOption {
kind: CopyKind
disabled: boolean
hint?: string
}
export interface CopyOptionsContext {
isPublicShare?: boolean
isTeamOwner?: boolean
allowDownload?: boolean
}
export interface CopyFormatContext {
origin: string
projectId?: string
}
const IMAGE_EXTENSIONS = new Set([
'jpg',
'jpeg',
'png',
'webp',
'gif',
'svg',
'bmp',
'tiff',
'avif',
'heic',
])
export function isImageItem(item: AssetInfo): boolean {
if (item.type === 'folder' || item.type === 'root' || item.type === 'share_root') return false
if (item.proxyType === 'image') return true
const ext = item.name?.split('.').pop()?.toLowerCase()
return IMAGE_EXTENSIONS.has(ext || '')
}
export function isArchivedStatus(status?: string | null): boolean {
return status === 'archived' || status === 'archiving' || status === 'restoring'
}
export interface TranscodeCandidate {
url?: string
key?: string
width?: number
height?: number
}
export function pickClipboardTranscode(
transcodes?: TranscodeCandidate[],
): TranscodeCandidate | null {
if (!transcodes || transcodes.length === 0) return null
const valid = transcodes.filter((t) => !!t.url || !!t.key)
if (valid.length === 0) return null
// Prefer largest transcode <= 2048px on long edge
const suitable = valid.filter((t) => {
const maxDim = Math.max(t.width || 0, t.height || 0)
return maxDim <= 2048
})
if (suitable.length > 0) {
suitable.sort((a, b) => {
const dimA = Math.max(a.width || 0, a.height || 0)
const dimB = Math.max(b.width || 0, b.height || 0)
return dimB - dimA
})
return suitable[0]
}
// Fallback to smallest available if all > 2048px
valid.sort((a, b) => {
const dimA = Math.max(a.width || 0, a.height || 0)
const dimB = Math.max(b.width || 0, b.height || 0)
return dimA - dimB
})
return valid[0]
}
export function getItemInAppUrl(item: AssetInfo, origin: string, projectId?: string): string {
const base = origin.replace(/\/$/, '')
if (item.type === 'folder') {
return projectId
? `${base}/projects/${projectId}/folders/${item.id}`
: `${base}/folders/${item.id}`
}
const targetId = item.versionStack ? item.versionStack.id : item.id
return projectId ? `${base}/projects/${projectId}/files/${targetId}` : `${base}/files/${targetId}`
}
export function getCopyOptions(items: AssetInfo[], context: CopyOptionsContext = {}): CopyOption[] {
if (items.length === 0) return []
const { isPublicShare = false, isTeamOwner = false, allowDownload = true } = context
const options: CopyOption[] = []
if (items.length === 1) {
const item = items[0]
const isImage = isImageItem(item)
if (isImage) {
const isArchived = isArchivedStatus(item.status)
const transcode = pickClipboardTranscode(item.media?.imageTranscodes)
const hasTranscode =
!!transcode || item.status === 'processed' || !!item.preview?.thumbnailUrl
const disabled = isArchived || !hasTranscode || (isPublicShare && !allowDownload)
options.push({ kind: 'image', disabled })
}
options.push({ kind: 'name', disabled: false })
options.push({ kind: 'link', disabled: false })
if (item.type !== 'folder') {
const isArchived = isArchivedStatus(item.status)
const disabled = isArchived || (isPublicShare && !allowDownload)
options.push({ kind: 'download-link', disabled })
}
if (!isPublicShare) {
options.push({ kind: 'id', disabled: false })
}
options.push({ kind: 'markdown', disabled: false })
if (isTeamOwner && !isPublicShare && item.type !== 'folder') {
options.push({ kind: 'storage-path', disabled: false })
}
return options
}
// Multi-selection
options.push({ kind: 'name', disabled: false })
options.push({ kind: 'link', disabled: false })
const files = items.filter((i) => i.type !== 'folder')
if (files.length > 0) {
const allArchived = files.every((f) => isArchivedStatus(f.status))
const disabled = allArchived || (isPublicShare && !allowDownload)
options.push({ kind: 'download-link', disabled })
}
if (!isPublicShare) {
options.push({ kind: 'id', disabled: false })
}
options.push({ kind: 'markdown', disabled: false })
options.push({ kind: 'tsv', disabled: false })
if (isTeamOwner && !isPublicShare && files.length > 0) {
options.push({ kind: 'storage-path', disabled: false })
}
return options
}
export function formatCopyText(
kind: CopyKind,
items: AssetInfo[],
context: CopyFormatContext,
): string {
if (items.length === 0) return ''
switch (kind) {
case 'name':
return items.map((i) => i.name).join('\n')
case 'link':
return items.map((i) => getItemInAppUrl(i, context.origin, context.projectId)).join('\n')
case 'id':
return items.map((i) => (i.versionStack ? i.versionStack.id : i.id)).join('\n')
case 'markdown':
if (items.length === 1) {
const item = items[0]
const safeName = item.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
const url = getItemInAppUrl(item, context.origin, context.projectId)
return `[${safeName}](${url})`
}
return items
.map((i) => {
const safeName = i.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
const url = getItemInAppUrl(i, context.origin, context.projectId)
return `- [${safeName}](${url})`
})
.join('\n')
case 'tsv': {
const header = 'Name\tType\tSize\tLink\tID'
const rows = items.map((i) => {
const type = i.type === 'folder' ? 'folder' : 'file'
const size = i.type === 'folder' ? '—' : formatSize(i.sizeByte || 0)
const link = getItemInAppUrl(i, context.origin, context.projectId)
const id = i.versionStack ? i.versionStack.id : i.id
const safeName = i.name.replace(/[\t\r\n]+/g, ' ')
return `${safeName}\t${type}\t${size}\t${link}\t${id}`
})
return [header, ...rows].join('\n')
}
default:
return ''
}
}
@@ -0,0 +1,234 @@
import type { AssetInfo } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import {
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
ContextMenuItem,
ContextMenuSeparator,
ContextMenuPortal,
} from '@/ui/components/ui/context-menu'
import {
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
DropdownMenuItem,
DropdownMenuSeparator,
} from '@/ui/components/ui/dropdown-menu'
import {
Copy,
Image as ImageIcon,
FileText,
Link,
Download,
Hash,
Code,
Table,
HardDrive,
} from 'lucide-react'
import { type CopyKind, type CopyOptionsContext, getCopyOptions } from './copy-options'
interface CopyMenuProps {
items: AssetInfo[]
context: CopyOptionsContext
onCopy: (kind: CopyKind, items: AssetInfo[]) => void
}
function renderCopyIcon(kind: CopyKind) {
switch (kind) {
case 'image':
return <ImageIcon className="mr-2 h-4 w-4" />
case 'name':
return <FileText className="mr-2 h-4 w-4" />
case 'link':
return <Link className="mr-2 h-4 w-4" />
case 'download-link':
return <Download className="mr-2 h-4 w-4" />
case 'id':
return <Hash className="mr-2 h-4 w-4" />
case 'markdown':
return <Code className="mr-2 h-4 w-4" />
case 'tsv':
return <Table className="mr-2 h-4 w-4" />
case 'storage-path':
return <HardDrive className="mr-2 h-4 w-4" />
}
}
function renderCopyLabel(kind: CopyKind) {
switch (kind) {
case 'image':
return m.copy_image()
case 'name':
return m.copy_name()
case 'link':
return m.copy_app_link()
case 'download-link':
return m.copy_download_link()
case 'id':
return m.copy_id()
case 'markdown':
return m.copy_markdown_link()
case 'tsv':
return m.copy_as_table()
case 'storage-path':
return m.copy_storage_path()
}
}
export function CopyContextMenuSub({ items, context, onCopy }: CopyMenuProps) {
const options = getCopyOptions(items, context)
if (options.length === 0) return null
const imageOpt = options.find((o) => o.kind === 'image')
const coreOpts = options.filter((o) => ['name', 'link', 'download-link', 'id'].includes(o.kind))
const docOpts = options.filter((o) => ['markdown', 'tsv'].includes(o.kind))
const storageOpt = options.find((o) => o.kind === 'storage-path')
return (
<ContextMenuSub>
<ContextMenuSubTrigger>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy()}</span>
</ContextMenuSubTrigger>
<ContextMenuPortal>
<ContextMenuSubContent className="w-52">
{imageOpt && (
<>
<ContextMenuItem disabled={imageOpt.disabled} onSelect={() => onCopy('image', items)}>
{renderCopyIcon('image')}
<span>{renderCopyLabel('image')}</span>
</ContextMenuItem>
<ContextMenuSeparator />
</>
)}
{coreOpts.map((opt) => (
<ContextMenuItem
key={opt.kind}
disabled={opt.disabled}
onSelect={() => onCopy(opt.kind, items)}
>
{renderCopyIcon(opt.kind)}
<span>{renderCopyLabel(opt.kind)}</span>
</ContextMenuItem>
))}
{docOpts.length > 0 && (
<>
<ContextMenuSeparator />
{docOpts.map((opt) => (
<ContextMenuItem
key={opt.kind}
disabled={opt.disabled}
onSelect={() => onCopy(opt.kind, items)}
>
{renderCopyIcon(opt.kind)}
<span>{renderCopyLabel(opt.kind)}</span>
</ContextMenuItem>
))}
</>
)}
{storageOpt && (
<>
<ContextMenuSeparator />
<ContextMenuItem
disabled={storageOpt.disabled}
onSelect={() => onCopy('storage-path', items)}
>
{renderCopyIcon('storage-path')}
<span>{renderCopyLabel('storage-path')}</span>
</ContextMenuItem>
</>
)}
</ContextMenuSubContent>
</ContextMenuPortal>
</ContextMenuSub>
)
}
export function CopyDropdownMenuSub({ items, context, onCopy }: CopyMenuProps) {
const options = getCopyOptions(items, context)
if (options.length === 0) return null
const imageOpt = options.find((o) => o.kind === 'image')
const coreOpts = options.filter((o) => ['name', 'link', 'download-link', 'id'].includes(o.kind))
const docOpts = options.filter((o) => ['markdown', 'tsv'].includes(o.kind))
const storageOpt = options.find((o) => o.kind === 'storage-path')
return (
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Copy className="mr-2 h-4 w-4" />
<span>{m.copy()}</span>
</DropdownMenuSubTrigger>
<DropdownMenuSubContent className="w-52">
{imageOpt && (
<>
<DropdownMenuItem
disabled={imageOpt.disabled}
onClick={(e) => {
e.stopPropagation()
onCopy('image', items)
}}
>
{renderCopyIcon('image')}
<span>{renderCopyLabel('image')}</span>
</DropdownMenuItem>
<DropdownMenuSeparator />
</>
)}
{coreOpts.map((opt) => (
<DropdownMenuItem
key={opt.kind}
disabled={opt.disabled}
onClick={(e) => {
e.stopPropagation()
onCopy(opt.kind, items)
}}
>
{renderCopyIcon(opt.kind)}
<span>{renderCopyLabel(opt.kind)}</span>
</DropdownMenuItem>
))}
{docOpts.length > 0 && (
<>
<DropdownMenuSeparator />
{docOpts.map((opt) => (
<DropdownMenuItem
key={opt.kind}
disabled={opt.disabled}
onClick={(e) => {
e.stopPropagation()
onCopy(opt.kind, items)
}}
>
{renderCopyIcon(opt.kind)}
<span>{renderCopyLabel(opt.kind)}</span>
</DropdownMenuItem>
))}
</>
)}
{storageOpt && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
disabled={storageOpt.disabled}
onClick={(e) => {
e.stopPropagation()
onCopy('storage-path', items)
}}
>
{renderCopyIcon('storage-path')}
<span>{renderCopyLabel('storage-path')}</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuSubContent>
</DropdownMenuSub>
)
}
@@ -485,7 +485,7 @@ export function FileBrowser({
handleRename,
handleRestore,
handleDownload,
handleCopyNameAndDownloadLink,
handleCopy,
handleArchive,
handleRestoreArchive,
handleAction,
@@ -781,6 +781,8 @@ export function FileBrowser({
allowDownload,
fields: displayedFields,
canEdit,
isTeamOwner: canAdmin,
onCopy: handleCopy,
archiveStorageEnabled,
isExternalDragging,
externalOverFolderId,
@@ -1172,7 +1174,7 @@ export function FileBrowser({
onRename={handleRename}
onDelete={handleDelete}
onDownload={handleDownload}
onCopyNameAndDownloadLink={handleCopyNameAndDownloadLink}
onCopy={handleCopy}
onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick}
@@ -1190,6 +1192,8 @@ export function FileBrowser({
onArchive={handleArchive}
onRestoreArchive={handleRestoreArchive}
archiveStorageEnabled={archiveStorageEnabled}
isTeamOwner={canAdmin}
allowDownload={allowDownload}
isRecentlyDeleted={isRecentlyDeleted}
isRecents={isRecents}
shareLinks={shareLinksData?.data ?? []}
@@ -772,4 +772,34 @@ describe('FileCard', () => {
)
expect(screen.getByTestId('file-card-restoring-badge')).toBeTruthy()
})
it('renders Copy submenu in dropdown menu', () => {
render(
<QueryClientProvider client={queryClient}>
<FileCard
item={fileItem}
isSelected={false}
isChecked={false}
isEditing={false}
onSelect={vi.fn()}
onDoubleClick={vi.fn()}
onContextMenu={vi.fn()}
onDragStart={vi.fn()}
onDrop={vi.fn()}
onRename={vi.fn()}
onFinishEditing={vi.fn()}
onSaveField={vi.fn()}
onAction={vi.fn()}
fields={[]}
canEdit={true}
/>
</QueryClientProvider>,
)
const moreBtn = screen.getByRole('button', { name: '' })
fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' })
const copyOption = screen.getByText(/^Copy$|^复制$/i)
expect(copyOption).toBeTruthy()
})
})
@@ -1,5 +1,7 @@
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { CopyDropdownMenuSub } from './copy-submenu'
import type { CopyKind } from './copy-options'
import type { AssetInfo, FieldValueInfo } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
@@ -89,6 +91,8 @@ interface FileCardProps {
allowDownload?: boolean
hideCheckbox?: boolean
hideActions?: boolean
isTeamOwner?: boolean
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
}
export function FileCard({
@@ -110,6 +114,8 @@ export function FileCard({
dragState,
disabled,
onAction,
onCopy,
isTeamOwner = false,
isRecentlyDeleted,
isRecents,
selectedCount,
@@ -693,6 +699,16 @@ export function FileCard({
<span>{m.download()}</span>
</DropdownMenuItem>
)}
{!isRecentlyDeleted && !isShareView && (
<CopyDropdownMenuSub
items={[item]}
context={{
isTeamOwner,
allowDownload,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
)}
{canEdit && archiveStorageEnabled && canArchiveItem && (
<DropdownMenuItem
data-testid="file-card-archive-action"
@@ -12,6 +12,8 @@ import { useDraggable, useDroppable } from '@dnd-kit/react'
import type { AssetInfo, ChildPreview } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import { getTrashDaysLeft } from '@/ui/lib/time'
import { CopyDropdownMenuSub } from './copy-submenu'
import type { CopyKind } from './copy-options'
import {
Archive,
ArchiveRestore,
@@ -68,6 +70,8 @@ interface FolderCardProps {
allowDownload?: boolean
hideCheckbox?: boolean
hideActions?: boolean
isTeamOwner?: boolean
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
}
const FolderPreviewGrid = ({ items }: { items: ChildPreview[] }) => {
@@ -140,6 +144,8 @@ export function FolderCard({
dragState,
disabled,
onAction,
onCopy,
isTeamOwner = false,
isRecentlyDeleted,
isRecents,
selectedCount,
@@ -473,6 +479,16 @@ export function FolderCard({
<span>{m.download()}</span>
</DropdownMenuItem>
)}
{!isRecentlyDeleted && !isShareView && (
<CopyDropdownMenuSub
items={[item]}
context={{
isTeamOwner,
allowDownload,
}}
onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)}
/>
)}
{canEdit && archiveStorageEnabled && (
<>
<DropdownMenuItem
@@ -424,4 +424,17 @@ describe('MobileFileBrowser', () => {
expect(screen.queryByRole('button', { name: /actions/i })).toBeNull()
})
it('renders Copy submenu in file card dropdown menu on mobile', async () => {
const { container } = renderComponent()
const dropdownTrigger = container.querySelector(
'[data-slot="dropdown-menu-trigger"]',
) as HTMLElement
expect(dropdownTrigger).toBeTruthy()
fireEvent.keyDown(dropdownTrigger, { key: 'ArrowDown', code: 'ArrowDown' })
const copyOption = await screen.findByText(/^Copy$|^复制$/i)
expect(copyOption).toBeTruthy()
})
})
@@ -176,6 +176,7 @@ export function MobileFileBrowser({
confirmArchiveOrRestore,
isArchiving,
isRestoringArchive,
handleCopy,
} = useFileActions({
teamId,
projectId,
@@ -537,6 +538,8 @@ export function MobileFileBrowser({
archiveStorageEnabled={archiveStorageEnabled}
isShareView={isShareView}
allowDownload={allowDownload}
onCopy={handleCopy}
isTeamOwner={canAdmin}
/>
))}
</div>
@@ -600,6 +603,8 @@ export function MobileFileBrowser({
archiveStorageEnabled={archiveStorageEnabled}
isShareView={isShareView}
allowDownload={allowDownload}
onCopy={handleCopy}
isTeamOwner={canAdmin}
/>
))}
</div>
@@ -0,0 +1,306 @@
// @vitest-environment happy-dom
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { renderHook, act } from '@testing-library/react'
import { useCopyActions } from './use-copy-actions'
import type { AssetInfo } from '@shumai/dtos'
import { toast } from 'sonner'
import * as clipboardModule from '@/ui/lib/clipboard'
vi.mock('sonner', () => ({
toast: {
success: vi.fn(),
error: vi.fn(),
},
}))
const mockDownloadUrlPost = vi.fn()
const mockStoragePathsPost = vi.fn()
vi.mock('@/ui/api/client', () => ({
client: {
api: {
files: {
'download-url': {
$post: (...args: unknown[]) => mockDownloadUrlPost(...args),
},
'storage-paths': {
$post: (...args: unknown[]) => mockStoragePathsPost(...args),
},
},
},
},
}))
describe('useCopyActions', () => {
const dummyFile: AssetInfo = {
id: 'f1',
name: 'document.pdf',
type: 'file',
status: 'processed',
sizeByte: 1024,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
}
const dummyFolder: AssetInfo = {
id: 'd1',
name: 'Folder1',
type: 'folder',
status: 'processed',
sizeByte: 0,
fileCount: 2,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
}
const dummyImage: AssetInfo = {
id: 'img1',
name: 'photo.jpg',
type: 'file',
proxyType: 'image',
status: 'processed',
sizeByte: 2048,
fileCount: 0,
createdAt: '2026-01-01',
updatedAt: '2026-01-01',
media: {
imageTranscodes: [
{
id: 't1',
url: '',
key: 'files/img1/proxy-768p.webp',
width: 768,
height: 1024,
size: 500,
},
],
},
}
beforeEach(() => {
vi.restoreAllMocks()
vi.clearAllMocks()
})
afterEach(() => {
vi.restoreAllMocks()
})
describe('R2 Regression: Empty download links or storage paths', () => {
it('does not touch clipboard and does not toast success when all files are archived', async () => {
const getDownloadLinks = vi.fn().mockResolvedValue({
files: [],
skippedArchivedCount: 2,
})
const copyDeferredSpy = vi.spyOn(clipboardModule, 'copyToClipboardDeferred')
const copyTextSpy = vi.spyOn(clipboardModule, 'copyToClipboard')
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks,
}),
)
await act(async () => {
await result.current.handleCopy('download-link', [dummyFile, { ...dummyFile, id: 'f2' }])
})
// Must show error toast
expect(toast.error).toHaveBeenCalled()
// Must NOT show success toast
expect(toast.success).not.toHaveBeenCalled()
// Must NOT have copied empty string with copyToClipboard
expect(copyTextSpy).not.toHaveBeenCalled()
// If deferred was called, it should have returned false and avoided success
if (copyDeferredSpy.mock.results.length > 0) {
expect(await copyDeferredSpy.mock.results[0].value).toBe(false)
}
})
it('does not toast success and shows error toast when storage paths return empty array', async () => {
mockStoragePathsPost.mockResolvedValueOnce({
ok: true,
json: async () => ({ paths: [] }),
})
const copyDeferredSpy = vi.spyOn(clipboardModule, 'copyToClipboardDeferred')
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('storage-path', [dummyFile])
})
expect(toast.error).toHaveBeenCalled()
expect(toast.success).not.toHaveBeenCalled()
if (copyDeferredSpy.mock.results.length > 0) {
expect(await copyDeferredSpy.mock.results[0].value).toBe(false)
}
})
})
describe('image copying', () => {
it('resolves download URL on demand for transcode key and copies image to clipboard', async () => {
mockDownloadUrlPost.mockResolvedValueOnce({
ok: true,
json: async () => ({ url: 'https://cdn/proxy-768p.webp' }),
})
const copyImageSpy = vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('image', [dummyImage])
})
expect(mockDownloadUrlPost).toHaveBeenCalledWith({
json: { key: 'files/img1/proxy-768p.webp', assetId: 'img1' },
})
expect(copyImageSpy).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
})
it('falls back to thumbnail URL if no transcodes are present', async () => {
const imageWithThumb: AssetInfo = {
...dummyImage,
media: undefined,
preview: {
thumbnailUrl: 'https://cdn/thumb.webp',
},
}
const copyImageSpy = vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('image', [imageWithThumb])
})
expect(copyImageSpy).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
})
it('toasts error if copying image fails or is unsupported', async () => {
vi.spyOn(clipboardModule, 'copyImageToClipboard').mockResolvedValue(false)
mockDownloadUrlPost.mockResolvedValueOnce({
ok: true,
json: async () => ({ url: 'https://cdn/proxy-768p.webp' }),
})
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('image', [dummyImage])
})
expect(toast.error).toHaveBeenCalled()
expect(toast.success).not.toHaveBeenCalled()
})
})
describe('download links copying', () => {
it('copies download links and shows skipped folders suffix when folders are included', async () => {
const getDownloadLinks = vi.fn().mockResolvedValue({
files: [{ id: 'f1', name: 'document.pdf', url: 'https://cdn/download-1' }],
})
vi.spyOn(clipboardModule, 'copyToClipboardDeferred').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks,
}),
)
await act(async () => {
await result.current.handleCopy('download-link', [dummyFile, dummyFolder])
})
expect(getDownloadLinks).toHaveBeenCalledWith({ json: { ids: ['f1'] } })
expect(toast.success).toHaveBeenCalled()
})
})
describe('storage paths copying', () => {
it('fetches storage paths and copies via deferred clipboard', async () => {
mockStoragePathsPost.mockResolvedValueOnce({
ok: true,
json: async () => ({
paths: [
{
id: 'f1',
name: 'document.pdf',
path: '/data/shumai/files/1',
backend: 'local',
isArchived: false,
},
],
}),
})
vi.spyOn(clipboardModule, 'copyToClipboardDeferred').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
await act(async () => {
await result.current.handleCopy('storage-path', [dummyFile])
})
expect(mockStoragePathsPost).toHaveBeenCalledWith({ json: { ids: ['f1'] } })
expect(toast.success).toHaveBeenCalled()
})
})
describe('text copying formats', () => {
it('copies name, link, id, markdown, and tsv with success toasts', async () => {
vi.spyOn(clipboardModule, 'copyToClipboard').mockResolvedValue(true)
const { result } = renderHook(() =>
useCopyActions({
projectId: 'p1',
getDownloadLinks: vi.fn(),
}),
)
for (const kind of ['name', 'link', 'id', 'markdown', 'tsv'] as const) {
vi.clearAllMocks()
await act(async () => {
await result.current.handleCopy(kind, [dummyFile, dummyFolder])
})
expect(clipboardModule.copyToClipboard).toHaveBeenCalled()
expect(toast.success).toHaveBeenCalled()
}
})
})
})
@@ -0,0 +1,223 @@
'use client'
import { client } from '@/ui/api/client'
import type { AssetInfo } from '@shumai/dtos'
import { toast } from 'sonner'
import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard'
import { type CopyKind, formatCopyText, pickClipboardTranscode } from './copy-options'
import { m } from '@/ui/paraglide/messages.js'
export interface UseCopyActionsProps {
projectId?: string
isPublic?: boolean
shareId?: string
getDownloadLinks: (args: { json: { ids: string[] } }) => Promise<{
files: Array<{ id: string; name: string; url: string }>
skippedArchivedCount?: number
}>
}
export function useCopyActions({
projectId,
isPublic,
shareId,
getDownloadLinks,
}: UseCopyActionsProps) {
const handleCopy = async (kind: CopyKind, items: AssetInfo[]) => {
if (items.length === 0) return
if (kind === 'image') {
const item = items[0]
const transcode = pickClipboardTranscode(item.media?.imageTranscodes)
if (!transcode && !item.preview?.thumbnailUrl && item.status !== 'processed') {
toast.error(m.copy_image_failed())
return
}
const fetchImageUrl = async (): Promise<string> => {
if (transcode?.url) return transcode.url
if (transcode?.key && item.id) {
if (isPublic && shareId) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId']['download-url'].$post(
{
param: { shareId, fileId: item.id },
json: { key: transcode.key },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.ok) {
const { url } = await res.json()
return url
}
} else {
const res = await client.api.files['download-url'].$post({
json: { key: transcode.key, assetId: item.id },
})
if (res.ok) {
const { url } = await res.json()
return url
}
}
}
if (item.preview?.thumbnailUrl) {
return item.preview.thumbnailUrl
}
throw new Error('No image URL available')
}
try {
const ok = await copyImageToClipboard(fetchImageUrl())
if (ok) {
toast.success(m.copied_image_toast())
} else {
toast.error(m.copy_image_failed())
}
} catch {
toast.error(m.copy_image_failed())
}
return
}
if (kind === 'download-link') {
const targetFiles = items.filter((i) => i.type !== 'folder')
if (targetFiles.length === 0) return
let hasShownEmptyError = false
try {
const fetchDownloadLinksPromise = (async () => {
const res = await getDownloadLinks({
json: { ids: targetFiles.map((i) => i.id!) },
})
const files = res.files
if (files.length === 0) {
hasShownEmptyError = true
if ((res.skippedArchivedCount ?? 0) > 0) {
toast.error(m.download_all_archived_error())
} else {
toast.error(m.copy_failed())
}
throw new Error('NO_FILES_TO_COPY')
}
return files.map((f) => f.url).join('\n')
})()
const ok = await copyToClipboardDeferred(fetchDownloadLinksPromise)
if (ok) {
const skippedFolders = items.length - targetFiles.length
if (targetFiles.length === 1 && skippedFolders === 0) {
toast.success(m.copied_download_link_toast())
} else {
const baseToast = m.copied_download_links_toast({ count: targetFiles.length })
const msg =
skippedFolders > 0
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
: baseToast
toast.success(msg)
}
} else if (!hasShownEmptyError) {
toast.error(m.copy_failed())
}
} catch (err) {
if (!hasShownEmptyError) {
console.error('Failed to copy download links:', err)
toast.error(m.copy_failed())
}
}
return
}
if (kind === 'storage-path') {
const targetFiles = items.filter((i) => i.type !== 'folder')
if (targetFiles.length === 0) return
let hasShownEmptyError = false
try {
const fetchStoragePathsPromise = (async () => {
const res = await client.api.files['storage-paths'].$post({
json: { ids: targetFiles.map((i) => i.id!) },
})
if (!res.ok) throw new Error('Failed to fetch storage paths')
const data = await res.json()
if (!data.paths || data.paths.length === 0) {
hasShownEmptyError = true
toast.error(m.copy_failed())
throw new Error('NO_PATHS_TO_COPY')
}
return data.paths.map((p) => p.path).join('\n')
})()
const ok = await copyToClipboardDeferred(fetchStoragePathsPromise)
if (ok) {
const skippedFolders = items.length - targetFiles.length
if (targetFiles.length === 1 && skippedFolders === 0) {
toast.success(m.copied_storage_path_toast())
} else {
const baseToast = m.copied_storage_paths_toast({ count: targetFiles.length })
const msg =
skippedFolders > 0
? `${baseToast} ${m.copied_skipped_folders_suffix({ count: skippedFolders })}`
: baseToast
toast.success(msg)
}
} else if (!hasShownEmptyError) {
toast.error(m.copy_failed())
}
} catch (err) {
if (!hasShownEmptyError) {
console.error('Failed to copy storage paths:', err)
toast.error(m.copy_failed())
}
}
return
}
// Synchronous text copy
const origin = typeof window !== 'undefined' ? window.location.origin : ''
const text = formatCopyText(kind, items, { origin, projectId })
const ok = await copyToClipboard(text)
if (ok) {
switch (kind) {
case 'name':
toast.success(
items.length === 1
? m.copied_name_toast()
: m.copied_names_toast({ count: items.length }),
)
break
case 'link':
toast.success(
items.length === 1
? m.copied_link_toast()
: m.copied_links_toast({ count: items.length }),
)
break
case 'id':
toast.success(
items.length === 1 ? m.copied_id_toast() : m.copied_ids_toast({ count: items.length }),
)
break
case 'markdown':
toast.success(
items.length === 1
? m.copied_markdown_link_toast()
: m.copied_markdown_links_toast({ count: items.length }),
)
break
case 'tsv':
toast.success(m.copied_table_toast({ count: items.length }))
break
}
} else {
toast.error(m.copy_failed())
}
}
return { handleCopy }
}
@@ -6,7 +6,7 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'
import type { InferRequestType, InferResponseType } from 'hono/client'
import { useState } from 'react'
import { toast } from 'sonner'
import { copyToClipboard } from '@/ui/lib/clipboard'
import { useCopyActions } from './use-copy-actions'
import { m } from '@/ui/paraglide/messages.js'
interface UseFileActionsProps {
@@ -316,36 +316,12 @@ export function useFileActions({
}
}
const handleCopyNameAndDownloadLink = async (items: AssetInfo[]) => {
if (items.length === 0) return
try {
const res = await getDownloadLinks({
json: { ids: items.map((i) => i.id!) },
})
const files = res.files
if (files.length === 0) {
if ((res.skippedArchivedCount ?? 0) > 0) {
toast.error(m.download_all_archived_error())
}
return
}
let text = ''
if (files.length === 1) {
text = `Name: ${files[0].name}\nPath: ${files[0].url}`
} else {
text = files.map((f) => `${f.name}\t${f.url}`).join('\n')
}
const ok = await copyToClipboard(text)
if (ok) {
toast.success(m.copied_name_and_download_link_to_clipboard())
}
} catch (error) {
toast.error('Failed to copy name and download link')
console.error(error)
}
}
const { handleCopy } = useCopyActions({
projectId,
isPublic,
shareId,
getDownloadLinks: (args) => getDownloadLinks(args),
})
const handleArchive = (items: AssetInfo[]) => {
if (items.length === 0) return
@@ -543,7 +519,7 @@ export function useFileActions({
handleRestore(targetItems)
break
case 'copy-name-and-download-link':
handleCopyNameAndDownloadLink(targetItems)
handleCopy('download-link', targetItems)
break
case 'archive':
handleArchive(targetItems)
@@ -561,7 +537,7 @@ export function useFileActions({
handleDelete,
handleRestore,
handleDownload,
handleCopyNameAndDownloadLink,
handleCopy,
handleArchive,
handleRestoreArchive,
handleNewFolder,
@@ -47,7 +47,7 @@ function ContextMenuSubTrigger({
data-slot="context-menu-sub-trigger"
data-inset={inset}
className={cn(
"flex cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[inset]:pl-8 data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
{...props}
@@ -1,6 +1,7 @@
import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { client } from '@/ui/api/client'
import { getBestTranscode } from '@/ui/lib/media'
import { copyImageToClipboard } from '@/ui/lib/clipboard'
import React, { useEffect, useRef, useState, useImperativeHandle } from 'react'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { ImageControlBar } from './image-control-bar'
@@ -128,49 +129,10 @@ export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
const handleCopy = async () => {
const webpUrl = bestUrl
if (!webpUrl) return
try {
const copyPromise = (async () => {
const response = await fetch(webpUrl)
const blob = await response.blob()
const img = new Image()
img.crossOrigin = 'anonymous'
const objectUrl = URL.createObjectURL(blob)
img.src = objectUrl
try {
await new Promise((resolve, reject) => {
img.onload = resolve
img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
})
const canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
const ctx = canvas.getContext('2d')
if (!ctx) throw new Error('Could not get canvas context')
ctx.drawImage(img, 0, 0)
const pngBlob = await new Promise<Blob | null>((resolve) => {
canvas.toBlob(resolve, 'image/png')
})
if (!pngBlob) throw new Error('Failed to convert image to PNG')
return pngBlob
} finally {
URL.revokeObjectURL(objectUrl)
}
})()
await navigator.clipboard.write([
new ClipboardItem({
'image/png': copyPromise,
}),
])
const ok = await copyImageToClipboard(webpUrl)
if (ok) {
setCopied(true)
setTimeout(() => setCopied(false), 2000)
} catch (err) {
console.error('Failed to copy image to clipboard:', err)
}
}