From 10bda73cb98bf4d1f20647e76e2b8967ea0cfceb Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 4 Nov 2026 21:52:49 +0800 Subject: [PATCH] refactor(file-browser): address code review feedback for copy submenu --- packages/api/src/file.test.ts | 12 + packages/core/src/asset/asset.test.ts | 142 ++++++++- packages/core/src/asset/asset.ts | 128 +++++--- packages/core/src/s3/archive-storage.ts | 11 + packages/core/src/s3/s3.ts | 9 + packages/dtos/src/asset.ts | 2 +- .../components/file-browser/context-menu.tsx | 2 - .../file-browser/copy-options.test.ts | 13 + .../components/file-browser/copy-options.ts | 10 +- .../components/file-browser/file-card.tsx | 1 - .../components/file-browser/folder-card.tsx | 1 - .../file-browser/mobile-file-browser.test.tsx | 13 + .../file-browser/mobile-file-browser.tsx | 5 + .../file-browser/use-copy-actions.test.ts | 299 ++++++++++++++++++ .../file-browser/use-copy-actions.ts | 223 +++++++++++++ .../file-browser/use-file-actions.ts | 191 +---------- packages/webui/lib/clipboard.ts | 9 +- 17 files changed, 836 insertions(+), 235 deletions(-) create mode 100644 packages/webui/components/file-browser/use-copy-actions.test.ts create mode 100644 packages/webui/components/file-browser/use-copy-actions.ts diff --git a/packages/api/src/file.test.ts b/packages/api/src/file.test.ts index 6e322e1e..f6e2cd08 100644 --- a/packages/api/src/file.test.ts +++ b/packages/api/src/file.test.ts @@ -979,6 +979,18 @@ describe('file api', () => { mockGetProjectTeam.mockRestore() mockGetStoragePaths.mockRestore() }) + + it('rejects if more than 100 ids are provided', async () => { + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const ids = Array.from({ length: 101 }, (_, i) => `asset-${i}`) + const res = await app.request('/files/storage-paths', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids }), + }) + + expect(res.status).toBe(400) + }) }) describe('GET /files/:fileId/m3u8 routes', () => { diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index 371b10cb..1aeca14c 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -4,7 +4,8 @@ import { setupTestDbHooks } from '@shumai/db/test' import { HTTPException } from 'hono/http-exception' import { AssetType, AssetStatus, Prisma, WorkflowTaskType, WorkflowTaskStatus } from '@shumai/db' -import { s3Service } from '@shumai/core/src/s3/s3' +import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3' +import * as archiveStorageModule from '@shumai/core/src/s3/archive-storage' import { uploadService } from '@shumai/core/src/upload/upload' import { metadataService } from '@shumai/core/src/metadata/metadata' import { AssetService } from './asset' @@ -20,6 +21,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ deleteObject: vi.fn().mockResolvedValue(1), deletePrefix: vi.fn().mockResolvedValue(1), copyObject: vi.fn().mockResolvedValue(undefined), + getStoragePath: vi.fn((bucket: string, key: string) => `/mock/data/${bucket}/${key}`), }, getStorageBackend: vi.fn().mockReturnValue('local'), })) @@ -3179,6 +3181,144 @@ describe('AssetService — natural sort by name', () => { expect(stackPath.id).toBe(latestChild.id) expect(stackPath.path).toContain('files/ulid3/stack_v2.png') }) + + it('returns S3 path when main storage backend is s3', async () => { + vi.mocked(getStorageBackend).mockReturnValueOnce('s3') + vi.mocked(s3Service.getStoragePath).mockReturnValueOnce('s3://shumai/files/test/s3-file.mp4') + + const project = await prisma.project.create({ + data: { name: 'P-S3', team: { create: { name: 'T-S3' } } }, + }) + const user = await prisma.user.create({ + data: { name: 'U-S3', email: `s3-${Date.now()}@example.com` }, + }) + const file = await prisma.asset.create({ + data: { + name: 's3-file.mp4', + type: AssetType.file, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.processed, + storageKey: { create: { key: 'files/test/s3-file.mp4' } }, + }, + }) + + const res = await assetService.getStoragePaths([file.id]) + expect(res.paths).toEqual([ + { + id: file.id, + name: 's3-file.mp4', + path: 's3://shumai/files/test/s3-file.mp4', + backend: 's3', + isArchived: false, + }, + ]) + }) + + it('returns archive S3 path when asset is archived and archive backend is s3', async () => { + vi.spyOn(archiveStorageModule, 'getArchiveStoragePath').mockReturnValueOnce({ + path: 's3://my-archive-bucket/files/archived/clip.mp4', + backend: 's3', + }) + + const project = await prisma.project.create({ + data: { name: 'P-Archive-S3', team: { create: { name: 'T-Archive-S3' } } }, + }) + const user = await prisma.user.create({ + data: { name: 'U-Arch', email: `arch-${Date.now()}@example.com` }, + }) + const file = await prisma.asset.create({ + data: { + name: 'clip.mp4', + type: AssetType.file, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.archived, + storageKey: { create: { key: 'files/archived/clip.mp4', isArchived: true } }, + }, + }) + + const res = await assetService.getStoragePaths([file.id]) + expect(res.paths).toEqual([ + { + id: file.id, + name: 'clip.mp4', + path: 's3://my-archive-bucket/files/archived/clip.mp4', + backend: 's3', + isArchived: true, + }, + ]) + }) + + it('returns archive local path when asset is archived and archive backend is local', async () => { + vi.spyOn(archiveStorageModule, 'getArchiveStoragePath').mockReturnValueOnce({ + path: '/mnt/archive/files/archived/clip.mp4', + backend: 'local', + }) + + const project = await prisma.project.create({ + data: { name: 'P-Archive-Local', team: { create: { name: 'T-Archive-Local' } } }, + }) + const user = await prisma.user.create({ + data: { name: 'U-ArchLocal', email: `archloc-${Date.now()}@example.com` }, + }) + const file = await prisma.asset.create({ + data: { + name: 'clip.mp4', + type: AssetType.file, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.archived, + storageKey: { create: { key: 'files/archived/clip.mp4', isArchived: true } }, + }, + }) + + const res = await assetService.getStoragePaths([file.id]) + expect(res.paths).toEqual([ + { + id: file.id, + name: 'clip.mp4', + path: '/mnt/archive/files/archived/clip.mp4', + backend: 'local', + isArchived: true, + }, + ]) + }) + + it('marks isArchived: true with main storage path when archive storage is disabled', async () => { + vi.spyOn(archiveStorageModule, 'getArchiveStoragePath').mockReturnValueOnce(null) + vi.mocked(s3Service.getStoragePath).mockReturnValueOnce( + '/mock/data/shumai/files/archived/clip.mp4', + ) + + const project = await prisma.project.create({ + data: { name: 'P-DisabledArchive', team: { create: { name: 'T-DisabledArchive' } } }, + }) + const user = await prisma.user.create({ + data: { name: 'U-DisArch', email: `disarch-${Date.now()}@example.com` }, + }) + const file = await prisma.asset.create({ + data: { + name: 'clip.mp4', + type: AssetType.file, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.archived, + storageKey: { create: { key: 'files/archived/clip.mp4', isArchived: true } }, + }, + }) + + const res = await assetService.getStoragePaths([file.id]) + expect(res.paths).toEqual([ + { + id: file.id, + name: 'clip.mp4', + path: '/mock/data/shumai/files/archived/clip.mp4', + backend: 'local', + isArchived: true, + }, + ]) + }) }) describe('getProjectIds', () => { diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index 17cd2bc0..45c8d600 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -49,7 +49,7 @@ import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3' import { getArchiveStorageService, isArchiveStorageEnabled, - getArchiveStorageConfig, + getArchiveStoragePath, } from '@shumai/core/src/s3/archive-storage' import { assetArchiveService } from './asset-archive' import { @@ -1251,6 +1251,75 @@ export class AssetService { return currentId } + async resolveLatestVersionIds(assetIds: string[]): Promise { + if (assetIds.length === 0) return [] + + const initialAssets = await this.prismaClient.asset.findMany({ + where: { id: { in: assetIds }, isDeleted: false }, + select: { id: true, type: true, targetId: true }, + }) + const assetMap = new Map(initialAssets.map((a) => [a.id, a])) + + // Find symlinks to resolve + const symlinks = initialAssets.filter((a) => a.type === AssetType.symlink && a.targetId) + const targetIds = Array.from(new Set(symlinks.map((s) => s.targetId!))) + + const symlinkTargetMap = new Map() + if (targetIds.length > 0) { + const targets = await this.prismaClient.asset.findMany({ + where: { id: { in: targetIds }, isDeleted: false }, + select: { id: true, type: true }, + }) + for (const t of targets) { + symlinkTargetMap.set(t.id, t) + } + } + + // Determine current ID and type for each input ID + const intermediate = assetIds.map((id) => { + const asset = assetMap.get(id) + if (!asset) return { originalId: id, currentId: id, type: null } + if (asset.type === AssetType.symlink && asset.targetId) { + const target = symlinkTargetMap.get(asset.targetId) + if (target) { + return { originalId: id, currentId: target.id, type: target.type } + } + } + return { originalId: id, currentId: asset.id, type: asset.type } + }) + + // Find version stacks to resolve to their latest child + const versionStackIds = Array.from( + new Set( + intermediate + .filter((item) => item.type === AssetType.version_stack) + .map((item) => item.currentId), + ), + ) + + const latestChildByParent = new Map() + if (versionStackIds.length > 0) { + const children = await this.prismaClient.asset.findMany({ + where: { parentId: { in: versionStackIds }, isDeleted: false }, + select: { id: true, parentId: true, sortIndex: true }, + orderBy: { sortIndex: 'asc' }, + }) + for (const child of children) { + if (child.parentId && !latestChildByParent.has(child.parentId)) { + latestChildByParent.set(child.parentId, child.id) + } + } + } + + return intermediate.map((item) => { + if (item.type === AssetType.version_stack) { + const childId = latestChildByParent.get(item.currentId) + if (childId) return childId + } + return item.currentId + }) + } + async updateAssetName(req: UpdateAssetNameRequest): Promise { const existing = await this.prismaClient.asset.findUnique({ where: { id: req.id }, @@ -2892,8 +2961,7 @@ export class AssetService { async getStoragePaths(ids: string[]): Promise { if (ids.length === 0) return { paths: [] } - const targetAssetIds = await Promise.all(ids.map(async (id) => this.resolveLatestVersionId(id))) - + const targetAssetIds = await this.resolveLatestVersionIds(ids) const uniqueTargetIds = Array.from(new Set(targetAssetIds)) const assets = await this.prismaClient.asset.findMany({ @@ -2917,10 +2985,8 @@ export class AssetService { }, }) - const archiveConfig = getArchiveStorageConfig() const defaultBackend = getStorageBackend() const mainBucket = process.env.S3_BUCKET || 'shumai' - const paths: StoragePathItem[] = [] for (const asset of assets) { @@ -2933,42 +2999,24 @@ export class AssetService { asset.status === AssetStatus.restoring || sk.isArchived - if (isArchived && archiveConfig.enabled) { - if (archiveConfig.backend === 's3') { - paths.push({ - id: asset.id, - name: asset.name, - path: `s3://${archiveConfig.bucket}/${sk.key}`, - backend: 's3', - isArchived: true, - }) - } else { - paths.push({ - id: asset.id, - name: asset.name, - path: path.join(archiveConfig.localRoot, sk.key), - backend: 'local', - isArchived: true, - }) - } + const archivePathInfo = isArchived ? getArchiveStoragePath(sk.key) : null + if (archivePathInfo) { + paths.push({ + id: asset.id, + name: asset.name, + path: archivePathInfo.path, + backend: archivePathInfo.backend, + isArchived: true, + }) } else { - if (defaultBackend === 's3') { - paths.push({ - id: asset.id, - name: asset.name, - path: `s3://${mainBucket}/${sk.key}`, - backend: 's3', - isArchived: false, - }) - } else { - paths.push({ - id: asset.id, - name: asset.name, - path: path.resolve('data', mainBucket, sk.key), - backend: 'local', - isArchived: false, - }) - } + const storagePath = s3Service.getStoragePath(mainBucket, sk.key) + paths.push({ + id: asset.id, + name: asset.name, + path: storagePath, + backend: defaultBackend, + isArchived, + }) } } diff --git a/packages/core/src/s3/archive-storage.ts b/packages/core/src/s3/archive-storage.ts index 035d9362..52edc79f 100644 --- a/packages/core/src/s3/archive-storage.ts +++ b/packages/core/src/s3/archive-storage.ts @@ -303,6 +303,17 @@ export function validateArchiveStorageConfig(): ArchiveStorageConfig { return getArchiveStorageConfig() } +export function getArchiveStoragePath( + key: string, +): { path: string; backend: 's3' | 'local' } | null { + const config = getArchiveStorageConfig() + if (!config.enabled) return null + if (config.backend === 's3') { + return { path: `s3://${config.bucket}/${key}`, backend: 's3' } + } + return { path: path.join(config.localRoot, key), backend: 'local' } +} + export class LocalArchiveStorageService implements ArchiveStorageService { readonly backend = 'local' as const readonly isSameS3Target = false diff --git a/packages/core/src/s3/s3.ts b/packages/core/src/s3/s3.ts index 62e8e0a9..26783165 100644 --- a/packages/core/src/s3/s3.ts +++ b/packages/core/src/s3/s3.ts @@ -360,6 +360,7 @@ export interface S3Service { ) => Promise<{ url: string }> abortMultipartUpload: (bucket: string, key: string, uploadId: string) => Promise resolveInput: (bucket: string, key: string) => Promise + getStoragePath: (bucket: string, key: string) => string } export class S3StorageService implements S3Service { @@ -760,6 +761,10 @@ export class S3StorageService implements S3Service { async resolveInput(bucket: string, key: string): Promise { return this.presign(bucket, key, 'GET', false, undefined, true) } + + getStoragePath(bucket: string, key: string): string { + return `s3://${bucket}/${key}` + } } export class LocalStorageService implements S3Service { @@ -1049,6 +1054,10 @@ export class LocalStorageService implements S3Service { } return this.presign(bucket, key, 'GET') } + + getStoragePath(bucket: string, key: string): string { + return this.getFilePath(bucket, key) + } } export function getStorageBackend(): 's3' | 'local' { diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 980e77be..5277bec3 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -401,7 +401,7 @@ export const getDownloadLinksResponseSchema = z.object({ export type GetDownloadLinksResponse = z.infer export const getStoragePathsRequestSchema = z.object({ - ids: z.array(z.string()), + ids: z.array(z.string()).max(100), }) export type GetStoragePathsRequest = z.infer diff --git a/packages/webui/components/file-browser/context-menu.tsx b/packages/webui/components/file-browser/context-menu.tsx index 843089d7..9e41758e 100644 --- a/packages/webui/components/file-browser/context-menu.tsx +++ b/packages/webui/components/file-browser/context-menu.tsx @@ -237,7 +237,6 @@ export function FileBrowserContextMenu({ context={{ isTeamOwner, allowDownload, - archiveStorageEnabled, }} onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)} /> @@ -334,7 +333,6 @@ export function FileBrowserContextMenu({ context={{ isTeamOwner, allowDownload, - archiveStorageEnabled, }} onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)} /> diff --git a/packages/webui/components/file-browser/copy-options.test.ts b/packages/webui/components/file-browser/copy-options.test.ts index 3e8913ab..721ec876 100644 --- a/packages/webui/components/file-browser/copy-options.test.ts +++ b/packages/webui/components/file-browser/copy-options.test.ts @@ -265,5 +265,18 @@ describe('copy-options', () => { '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') + }) }) }) diff --git a/packages/webui/components/file-browser/copy-options.ts b/packages/webui/components/file-browser/copy-options.ts index fa6e14ce..e07bc806 100644 --- a/packages/webui/components/file-browser/copy-options.ts +++ b/packages/webui/components/file-browser/copy-options.ts @@ -14,7 +14,6 @@ export interface CopyOptionsContext { isPublicShare?: boolean isTeamOwner?: boolean allowDownload?: boolean - archiveStorageEnabled?: boolean } export interface CopyFormatContext { @@ -182,13 +181,15 @@ export function formatCopyText( 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 `[${item.name}](${url})` + return `[${safeName}](${url})` } return items .map((i) => { + const safeName = i.name.replace(/\[/g, '\\[').replace(/\]/g, '\\]') const url = getItemInAppUrl(i, context.origin, context.projectId) - return `- [${i.name}](${url})` + return `- [${safeName}](${url})` }) .join('\n') @@ -199,7 +200,8 @@ export function formatCopyText( 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 - return `${i.name}\t${type}\t${size}\t${link}\t${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') } diff --git a/packages/webui/components/file-browser/file-card.tsx b/packages/webui/components/file-browser/file-card.tsx index 680bbcf2..f6eb0003 100644 --- a/packages/webui/components/file-browser/file-card.tsx +++ b/packages/webui/components/file-browser/file-card.tsx @@ -705,7 +705,6 @@ export function FileCard({ context={{ isTeamOwner, allowDownload, - archiveStorageEnabled, }} onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)} /> diff --git a/packages/webui/components/file-browser/folder-card.tsx b/packages/webui/components/file-browser/folder-card.tsx index bbed051b..d107c1b3 100644 --- a/packages/webui/components/file-browser/folder-card.tsx +++ b/packages/webui/components/file-browser/folder-card.tsx @@ -485,7 +485,6 @@ export function FolderCard({ context={{ isTeamOwner, allowDownload, - archiveStorageEnabled, }} onCopy={(kind, targetItems) => onCopy?.(kind, targetItems)} /> diff --git a/packages/webui/components/file-browser/mobile-file-browser.test.tsx b/packages/webui/components/file-browser/mobile-file-browser.test.tsx index 42a1ff96..1997c651 100644 --- a/packages/webui/components/file-browser/mobile-file-browser.test.tsx +++ b/packages/webui/components/file-browser/mobile-file-browser.test.tsx @@ -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() + }) }) diff --git a/packages/webui/components/file-browser/mobile-file-browser.tsx b/packages/webui/components/file-browser/mobile-file-browser.tsx index 16216cfc..c439f5f7 100644 --- a/packages/webui/components/file-browser/mobile-file-browser.tsx +++ b/packages/webui/components/file-browser/mobile-file-browser.tsx @@ -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} /> ))} @@ -600,6 +603,8 @@ export function MobileFileBrowser({ archiveStorageEnabled={archiveStorageEnabled} isShareView={isShareView} allowDownload={allowDownload} + onCopy={handleCopy} + isTeamOwner={canAdmin} /> ))} diff --git a/packages/webui/components/file-browser/use-copy-actions.test.ts b/packages/webui/components/file-browser/use-copy-actions.test.ts new file mode 100644 index 00000000..32b476a8 --- /dev/null +++ b/packages/webui/components/file-browser/use-copy-actions.test.ts @@ -0,0 +1,299 @@ +// @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() + } + }) + }) +}) diff --git a/packages/webui/components/file-browser/use-copy-actions.ts b/packages/webui/components/file-browser/use-copy-actions.ts new file mode 100644 index 00000000..1af27855 --- /dev/null +++ b/packages/webui/components/file-browser/use-copy-actions.ts @@ -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 => { + 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 } +} diff --git a/packages/webui/components/file-browser/use-file-actions.ts b/packages/webui/components/file-browser/use-file-actions.ts index 2abe0db9..c65d2ffd 100644 --- a/packages/webui/components/file-browser/use-file-actions.ts +++ b/packages/webui/components/file-browser/use-file-actions.ts @@ -6,8 +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, copyToClipboardDeferred, copyImageToClipboard } from '@/ui/lib/clipboard' -import { type CopyKind, formatCopyText, pickClipboardTranscode } from './copy-options' +import { useCopyActions } from './use-copy-actions' import { m } from '@/ui/paraglide/messages.js' interface UseFileActionsProps { @@ -317,183 +316,12 @@ export function useFileActions({ } } - 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 urlPromise = (async () => { - 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') - })() - - const ok = await copyImageToClipboard(urlPromise) - if (ok) { - toast.success(m.copied_image_toast()) - } else { - toast.error(m.copy_image_failed()) - } - return - } - - if (kind === 'download-link') { - const targetFiles = items.filter((i) => i.type !== 'folder') - if (targetFiles.length === 0) return - - try { - const fetchDownloadLinksPromise = (async () => { - const res = await getDownloadLinks({ - json: { ids: targetFiles.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 '' - } - 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 { - toast.error(m.copy_failed()) - } - } catch (err) { - 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 - - 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()) as { paths: Array<{ path: string }> } - 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 { - toast.error(m.copy_failed()) - } - } catch (err) { - 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()) - } - } + const { handleCopy } = useCopyActions({ + projectId, + isPublic, + shareId, + getDownloadLinks: (args) => getDownloadLinks(args), + }) const handleArchive = (items: AssetInfo[]) => { if (items.length === 0) return @@ -702,10 +530,6 @@ export function useFileActions({ } } - const handleCopyNameAndDownloadLink = (items: AssetInfo[]) => { - handleCopy('download-link', items) - } - return { editingItemId, setEditingItemId, @@ -714,7 +538,6 @@ export function useFileActions({ handleRestore, handleDownload, handleCopy, - handleCopyNameAndDownloadLink, handleArchive, handleRestoreArchive, handleNewFolder, diff --git a/packages/webui/lib/clipboard.ts b/packages/webui/lib/clipboard.ts index d31c357d..9418363e 100644 --- a/packages/webui/lib/clipboard.ts +++ b/packages/webui/lib/clipboard.ts @@ -54,12 +54,18 @@ export async function copyToClipboardDeferred(textPromise: Promise): Pro typeof ClipboardItem !== 'undefined' ) { try { - const blobPromise = textPromise.then((text) => new Blob([text], { type: 'text/plain' })) + const blobPromise = textPromise.then((text) => { + if (!text) throw new Error('EMPTY_TEXT') + return new Blob([text], { type: 'text/plain' }) + }) + blobPromise.catch(() => {}) + await navigator.clipboard.write([ new ClipboardItem({ 'text/plain': blobPromise, }), ]) + await textPromise return true } catch { // Fall back if deferred writing fails or is rejected @@ -68,6 +74,7 @@ export async function copyToClipboardDeferred(textPromise: Promise): Pro try { const text = await textPromise + if (!text) return false return await copyToClipboard(text) } catch (err) { console.error('Failed to copy deferred text to clipboard:', err)