From 2723d725a83e4add27c92d525d86d3509903323f Mon Sep 17 00:00:00 2001 From: yiling Date: Wed, 4 Nov 2026 18:58:24 +0800 Subject: [PATCH] feat(file-browser): add context-aware copy submenu --- CHANGELOG.md | 3 + apps/web/e2e/README.md | 1 + apps/web/e2e/tests/project/copy-menu.spec.ts | 36 +++ packages/api/src/file.test.ts | 110 +++++++ packages/api/src/file.ts | 33 +++ packages/core/src/asset/asset.test.ts | 105 +++++++ packages/core/src/asset/asset.ts | 91 +++++- packages/dtos/src/asset.ts | 19 ++ .../file-browser/context-menu.test.tsx | 9 + .../components/file-browser/context-menu.tsx | 48 ++-- .../file-browser/copy-options.test.ts | 269 ++++++++++++++++++ .../components/file-browser/copy-options.ts | 210 ++++++++++++++ .../components/file-browser/copy-submenu.tsx | 234 +++++++++++++++ .../components/file-browser/file-browser.tsx | 8 +- .../file-browser/file-card.test.tsx | 30 ++ .../components/file-browser/file-card.tsx | 17 ++ .../components/file-browser/folder-card.tsx | 17 ++ .../file-browser/use-file-actions.ts | 199 +++++++++++-- .../components/viewers/image/image-viewer.tsx | 44 +-- packages/webui/lib/clipboard.test.ts | 92 +++++- packages/webui/lib/clipboard.ts | 109 +++++++ packages/webui/messages/en.json | 26 ++ packages/webui/messages/zh.json | 26 ++ 23 files changed, 1646 insertions(+), 90 deletions(-) create mode 100644 apps/web/e2e/tests/project/copy-menu.spec.ts create mode 100644 packages/webui/components/file-browser/copy-options.test.ts create mode 100644 packages/webui/components/file-browser/copy-options.ts create mode 100644 packages/webui/components/file-browser/copy-submenu.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index f61208f5..b2f2c9b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,12 +10,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). - **storage**: Add optional archive storage support (`local` folder/NAS or `s3` with configurable storage class and Glacier restore) allowing editors and owners to archive and restore original files while keeping previews, proxy streams, comments, and metadata available in main storage - **storage**: Add team-level automatic asset archival based on age policies (creation time or last modified time) with configurable post-restore grace periods, an hourly background scanning worker, and a dedicated Storage settings page displaying read-only archive backend status and policy configurations +- **file-browser**: Add a context-aware Copy submenu in file browser context menus and card action dropdowns, enabling users to copy image proxy to clipboard for AI chat tools, asset names, in-app links, download links, IDs, Markdown links, multi-item TSV tables, and team-owner storage paths ### Fixed ### Changed +- **file-browser**: Replace the legacy combined "Copy name and download link" action with the dedicated Copy submenu + ## [0.6.3] - 2026-11-01 ### Added diff --git a/apps/web/e2e/README.md b/apps/web/e2e/README.md index 178aae2e..89481c26 100644 --- a/apps/web/e2e/README.md +++ b/apps/web/e2e/README.md @@ -99,6 +99,7 @@ apps/web/e2e/ | Video share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` | | Owner views a file and it appears in recents | `tests/project/recents.spec.ts` | | Owner archives a file to archive storage and restores it back to main storage | `tests/project/archive-restore.spec.ts` | +| Owner opens Copy submenu in context menu and copies file name | `tests/project/copy-menu.spec.ts` | ### file | Test | File | diff --git a/apps/web/e2e/tests/project/copy-menu.spec.ts b/apps/web/e2e/tests/project/copy-menu.spec.ts new file mode 100644 index 00000000..95fb5196 --- /dev/null +++ b/apps/web/e2e/tests/project/copy-menu.spec.ts @@ -0,0 +1,36 @@ +import { expect, test } from '../../fixtures' +import { fileCard } from '../../helpers/files' + +test('owner sees Copy submenu in context menu and copies file name', async ({ file }) => { + const { page, projectId, fileName } = file + + await page.context().grantPermissions(['clipboard-read', 'clipboard-write']) + await page.goto(`/projects/${projectId}`) + await expect(fileCard(page, fileName)).toBeVisible() + + // Right-click context menu + await fileCard(page, fileName).click({ button: 'right' }) + const copySubTrigger = page.getByRole('menuitem', { name: /^Copy$|^复制$/i }) + await expect(copySubTrigger).toBeVisible() + await copySubTrigger.click() + + // Verify submenu items are visible + await expect(page.getByRole('menuitem', { name: /^Name$|^名称$/i })).toBeVisible() + await expect(page.getByRole('menuitem', { name: /^Link$|^链接$/i })).toBeVisible() + await expect(page.getByRole('menuitem', { name: /^Download link$|^下载链接$/i })).toBeVisible() + await expect(page.getByRole('menuitem', { name: /^ID$/i })).toBeVisible() + await expect( + page.getByRole('menuitem', { name: /^Markdown link$|^Markdown 链接$/i }), + ).toBeVisible() + await expect(page.getByRole('menuitem', { name: /^Storage path$|^存储路径$/i })).toBeVisible() + + // Click "Name" + await page.getByRole('menuitem', { name: /^Name$|^名称$/i }).click() + const toast = page.locator('[data-sonner-toast]').filter({ + hasText: /Copied name to clipboard|已复制名称到剪贴板/i, + }) + await expect(toast).toBeVisible() + + const clipboardText = await page.evaluate(() => navigator.clipboard.readText()) + expect(clipboardText).toBe(fileName) +}) diff --git a/packages/api/src/file.test.ts b/packages/api/src/file.test.ts index 05fb5dad..6e322e1e 100644 --- a/packages/api/src/file.test.ts +++ b/packages/api/src/file.test.ts @@ -3,6 +3,7 @@ import { Hono, type Context, type Next } from 'hono' import { HTTPException } from 'hono/http-exception' import fileRoute from './file' import { assetService } from '@shumai/core/src/asset/asset' +import { projectService } from '@shumai/core/src/project/project' import { metadataService } from '@shumai/core/src/metadata/metadata' import { notificationService } from '@shumai/core/src/notification/notification' import { s3Service } from '@shumai/core/src/s3/s3' @@ -871,6 +872,115 @@ describe('file api', () => { mockGetProjectIds.mockRestore() }) + describe('POST /files/storage-paths', () => { + it('returns empty paths if ids are empty', async () => { + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/storage-paths', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: [] }), + }) + + expect(res.status).toBe(200) + const json = await res.json() + expect(json).toEqual({ paths: [] }) + }) + + it('rejects if assets belong to multiple projects', async () => { + const mockGetProjectIds = vi + .spyOn(assetService, 'getProjectIds') + .mockResolvedValue(['proj-1', 'proj-2']) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/storage-paths', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset-1', 'asset-2'] }), + }) + + expect(res.status).toBe(400) + const json = await res.json() + expect(json.error).toBe('All selected items must belong to the same project') + + mockGetProjectIds.mockRestore() + }) + + it('denies access if user is not a team owner (admin)', async () => { + const mockGetProjectIds = vi + .spyOn(assetService, 'getProjectIds') + .mockResolvedValue(['proj-1']) + const mockGetProjectTeam = vi + .spyOn(projectService, 'getProjectTeam') + .mockResolvedValue('team-1') + vi.mocked(authzService.hasPermission).mockRejectedValueOnce( + new HTTPException(403, { message: 'Permission denied' }), + ) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/storage-paths', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset-1'] }), + }) + + expect(res.status).toBe(403) + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user1', name: 'Test User' }, + permission: Permission.Admin, + type: ResourceType.Team, + id: 'team-1', + }) + + mockGetProjectIds.mockRestore() + mockGetProjectTeam.mockRestore() + }) + + it('returns storage paths if user has team admin permission', async () => { + const mockGetProjectIds = vi + .spyOn(assetService, 'getProjectIds') + .mockResolvedValue(['proj-1']) + const mockGetProjectTeam = vi + .spyOn(projectService, 'getProjectTeam') + .mockResolvedValue('team-1') + const mockGetStoragePaths = vi.spyOn(assetService, 'getStoragePaths').mockResolvedValue({ + paths: [ + { + id: 'asset-1', + name: 'clip.mp4', + path: 's3://shumai/files/1/clip.mp4', + backend: 's3', + isArchived: false, + }, + ], + }) + + const app = new Hono().use('*', authMiddleware).route('/', fileRoute) + const res = await app.request('/files/storage-paths', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ids: ['asset-1'] }), + }) + + expect(res.status).toBe(200) + const json = await res.json() + expect(json.paths).toHaveLength(1) + expect(json.paths[0].name).toBe('clip.mp4') + expect(json.paths[0].path).toBe('s3://shumai/files/1/clip.mp4') + + expect(authzService.hasPermission).toHaveBeenCalledWith({ + user: { id: 'user1', name: 'Test User' }, + permission: Permission.Admin, + type: ResourceType.Team, + id: 'team-1', + }) + expect(assetService.getStoragePaths).toHaveBeenCalledWith(['asset-1']) + + mockGetProjectIds.mockRestore() + mockGetProjectTeam.mockRestore() + mockGetStoragePaths.mockRestore() + }) + }) + describe('GET /files/:fileId/m3u8 routes', () => { it('returns master playlist with correct content-type', async () => { const mockMaster = vi diff --git a/packages/api/src/file.ts b/packages/api/src/file.ts index 76c6e84b..a1cb26f3 100644 --- a/packages/api/src/file.ts +++ b/packages/api/src/file.ts @@ -1,5 +1,6 @@ import { zValidator } from '@hono/zod-validator' import { assetService } from '@shumai/core/src/asset/asset' +import { projectService } from '@shumai/core/src/project/project' import { authzService, Permission, ResourceType } from '@shumai/core/src/authz/authz' import { commentService } from '@shumai/core/src/comment/comment' import { s3Service } from '@shumai/core/src/s3/s3' @@ -26,6 +27,7 @@ import { updateFileRequestSchema, uploadFileRequestSchema, getDownloadLinksRequestSchema, + getStoragePathsRequestSchema, completeCommentRequestSchema, exportCommentsRequestSchema, addCommentReactionRequestSchema, @@ -456,6 +458,37 @@ const route = new Hono<{ Variables: { user: User } }>() ...(skippedArchivedCount > 0 ? { skippedArchivedCount } : {}), }) }) + .post('/files/storage-paths', zValidator('json', getStoragePathsRequestSchema), async (c) => { + const user = c.get('user') + const req = c.req.valid('json') + + if (req.ids.length === 0) { + return c.json({ paths: [] }) + } + + const projectIds = await assetService.getProjectIds(req.ids) + if (projectIds.length === 0) { + return c.json({ paths: [] }) + } + + if (projectIds.length !== 1) { + return c.json({ error: 'All selected items must belong to the same project' }, 400) + } + + const projectId = projectIds[0] + const teamId = await projectService.getProjectTeam(projectId) + + // Verify user has Admin (owner) permission on the team + await authzService.hasPermission({ + user, + permission: Permission.Admin, + type: ResourceType.Team, + id: teamId, + }) + + const result = await assetService.getStoragePaths(req.ids) + return c.json(result) + }) .post( '/files/download-url', zValidator('json', z.object({ key: z.string().min(1), assetId: z.string().min(1) })), diff --git a/packages/core/src/asset/asset.test.ts b/packages/core/src/asset/asset.test.ts index bfbd9716..371b10cb 100644 --- a/packages/core/src/asset/asset.test.ts +++ b/packages/core/src/asset/asset.test.ts @@ -21,6 +21,7 @@ vi.mock('@shumai/core/src/s3/s3', () => ({ deletePrefix: vi.fn().mockResolvedValue(1), copyObject: vi.fn().mockResolvedValue(undefined), }, + getStorageBackend: vi.fn().mockReturnValue('local'), })) vi.mock('@shumai/core/src/s3/preview-converter', async (importOriginal) => { @@ -3076,6 +3077,110 @@ describe('AssetService — natural sort by name', () => { }) }) + describe('getStoragePaths', () => { + it('returns empty array for empty inputs', async () => { + const result = await assetService.getStoragePaths([]) + expect(result).toEqual({ paths: [] }) + }) + + it('resolves files, symlinks, and version stacks while skipping folders', async () => { + const user = await prisma.user.create({ + data: { + name: 'StoragePathUser', + email: `storage-path-${Date.now()}@example.com`, + }, + }) + const team = await prisma.team.create({ data: { name: 'StoragePathTeam' } }) + const project = await prisma.project.create({ + data: { name: 'StoragePathProject', teamId: team.id }, + }) + + const folder = await prisma.asset.create({ + data: { + name: 'MyFolder', + type: AssetType.folder, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.processed, + }, + }) + + 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.processed, + storageKey: { create: { key: 'files/ulid1/clip.mp4' } }, + }, + }) + + const symlink = await prisma.asset.create({ + data: { + name: 'clip-symlink', + type: AssetType.symlink, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.uploaded, + target: { connect: { id: file.id } }, + }, + }) + + const stack = await prisma.asset.create({ + data: { + name: 'stack.png', + type: AssetType.version_stack, + project: { connect: { id: project.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.processed, + }, + }) + + await prisma.asset.create({ + data: { + name: 'stack_v1.png', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: stack.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.processed, + sortIndex: 'b', + storageKey: { create: { key: 'files/ulid2/stack_v1.png' } }, + }, + }) + + const latestChild = await prisma.asset.create({ + data: { + name: 'stack_v2.png', + type: AssetType.file, + project: { connect: { id: project.id } }, + parent: { connect: { id: stack.id } }, + creator: { connect: { id: user.id } }, + status: AssetStatus.processed, + sortIndex: 'a', + storageKey: { create: { key: 'files/ulid3/stack_v2.png' } }, + }, + }) + + const result = await assetService.getStoragePaths([folder.id, file.id, symlink.id, stack.id]) + + // folder should be skipped, symlink deduplicated to file, stack resolved to latest child + expect(result.paths).toHaveLength(2) + const names = result.paths.map((p) => p.name) + expect(names).toContain('clip.mp4') + expect(names).toContain('stack_v2.png') + + const clipPath = result.paths.find((p) => p.name === 'clip.mp4')! + expect(clipPath.path).toContain('files/ulid1/clip.mp4') + expect(clipPath.isArchived).toBe(false) + + const stackPath = result.paths.find((p) => p.name === 'stack_v2.png')! + expect(stackPath.id).toBe(latestChild.id) + expect(stackPath.path).toContain('files/ulid3/stack_v2.png') + }) + }) + describe('getProjectIds', () => { it('returns empty lists for empty inputs', async () => { const result = await assetService.getProjectIds([]) diff --git a/packages/core/src/asset/asset.ts b/packages/core/src/asset/asset.ts index d23773d0..17cd2bc0 100644 --- a/packages/core/src/asset/asset.ts +++ b/packages/core/src/asset/asset.ts @@ -23,6 +23,8 @@ import { CommentExportFormat, PreviewFormat, TRASH_RETENTION_DAYS, + GetStoragePathsResponse, + StoragePathItem, } from '@shumai/dtos' import { exportCommentsToFormat, @@ -43,10 +45,11 @@ import { import { HTTPException } from 'hono/http-exception' import { logger } from '@shumai/core/src/logger' import { PaginatedData, paginateQuery, PaginationParams } from '@shumai/core/src/pagination' -import { s3Service } from '@shumai/core/src/s3/s3' +import { s3Service, getStorageBackend } from '@shumai/core/src/s3/s3' import { getArchiveStorageService, isArchiveStorageEnabled, + getArchiveStorageConfig, } from '@shumai/core/src/s3/archive-storage' import { assetArchiveService } from './asset-archive' import { @@ -2886,6 +2889,92 @@ 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 uniqueTargetIds = Array.from(new Set(targetAssetIds)) + + const assets = await this.prismaClient.asset.findMany({ + where: { + id: { in: uniqueTargetIds }, + isDeleted: false, + type: { + notIn: [AssetType.folder, AssetType.root, AssetType.share_root, AssetType.share], + }, + }, + select: { + id: true, + name: true, + status: true, + storageKey: { + select: { + key: true, + isArchived: true, + }, + }, + }, + }) + + const archiveConfig = getArchiveStorageConfig() + const defaultBackend = getStorageBackend() + const mainBucket = process.env.S3_BUCKET || 'shumai' + + const paths: StoragePathItem[] = [] + + for (const asset of assets) { + const sk = asset.storageKey + if (!sk?.key) continue + + const isArchived = + asset.status === AssetStatus.archived || + asset.status === AssetStatus.archiving || + 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, + }) + } + } 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, + }) + } + } + } + + return { paths } + } + /** * Generate a presigned download URL for a given key, verifying it belongs to the asset's * storage directory. This ensures users can only download files (original, transcodes, etc.) diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 09564993..980e77be 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -400,6 +400,25 @@ export const getDownloadLinksResponseSchema = z.object({ }) export type GetDownloadLinksResponse = z.infer +export const getStoragePathsRequestSchema = z.object({ + ids: z.array(z.string()), +}) +export type GetStoragePathsRequest = z.infer + +export const storagePathItemSchema = z.object({ + id: z.string(), + name: z.string(), + path: z.string(), + backend: z.enum(['s3', 'local']), + isArchived: z.boolean(), +}) +export type StoragePathItem = z.infer + +export const getStoragePathsResponseSchema = z.object({ + paths: z.array(storagePathItemSchema), +}) +export type GetStoragePathsResponse = z.infer + export const archiveAssetsRequestSchema = z.object({ ids: z.array(z.string().min(1)).min(1), }) diff --git a/packages/webui/components/file-browser/context-menu.test.tsx b/packages/webui/components/file-browser/context-menu.test.tsx index 6b065884..85f43010 100644 --- a/packages/webui/components/file-browser/context-menu.test.tsx +++ b/packages/webui/components/file-browser/context-menu.test.tsx @@ -80,4 +80,13 @@ describe('FileBrowserContextMenu', () => { expect(screen.queryByText(/Manage versions|管理版本/i)).toBeNull() }) + + it('renders Copy submenu trigger for regular file item', () => { + renderWithMenu(fileItem) + + fireEvent.contextMenu(screen.getByTestId('context-trigger')) + + const copyOption = screen.getByText(/^Copy$|^复制$/i) + expect(copyOption).toBeTruthy() + }) }) diff --git a/packages/webui/components/file-browser/context-menu.tsx b/packages/webui/components/file-browser/context-menu.tsx index 669b5e9a..843089d7 100644 --- a/packages/webui/components/file-browser/context-menu.tsx +++ b/packages/webui/components/file-browser/context-menu.tsx @@ -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) } @@ -167,10 +165,6 @@ export function FileBrowserContextMenu({ {m.download()} - - - {m.copy_name_and_download_link()} - {canEdit && ( onRemoveFromShare?.(itemsToModify)} @@ -238,10 +232,15 @@ export function FileBrowserContextMenu({ {m.download()} - - - {m.copy_name_and_download_link()} - + onCopy?.(kind, targetItems)} + /> {canEdit && ( onMoveTo(itemsToModify)}> @@ -330,10 +329,15 @@ export function FileBrowserContextMenu({ {m.download()} - - - {m.copy_name_and_download_link()} - + onCopy?.(kind, targetItems)} + /> {canEdit && ( onMoveTo(itemsToModify)}> diff --git a/packages/webui/components/file-browser/copy-options.test.ts b/packages/webui/components/file-browser/copy-options.test.ts new file mode 100644 index 00000000..3e8913ab --- /dev/null +++ b/packages/webui/components/file-browser/copy-options.test.ts @@ -0,0 +1,269 @@ +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', + ) + }) + }) +}) diff --git a/packages/webui/components/file-browser/copy-options.ts b/packages/webui/components/file-browser/copy-options.ts new file mode 100644 index 00000000..fa6e14ce --- /dev/null +++ b/packages/webui/components/file-browser/copy-options.ts @@ -0,0 +1,210 @@ +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 + archiveStorageEnabled?: 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 url = getItemInAppUrl(item, context.origin, context.projectId) + return `[${item.name}](${url})` + } + return items + .map((i) => { + const url = getItemInAppUrl(i, context.origin, context.projectId) + return `- [${i.name}](${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 + return `${i.name}\t${type}\t${size}\t${link}\t${id}` + }) + return [header, ...rows].join('\n') + } + + default: + return '' + } +} diff --git a/packages/webui/components/file-browser/copy-submenu.tsx b/packages/webui/components/file-browser/copy-submenu.tsx new file mode 100644 index 00000000..3ff73f98 --- /dev/null +++ b/packages/webui/components/file-browser/copy-submenu.tsx @@ -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 + case 'name': + return + case 'link': + return + case 'download-link': + return + case 'id': + return + case 'markdown': + return + case 'tsv': + return + case 'storage-path': + return + } +} + +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 ( + + + + {m.copy()} + + + + {imageOpt && ( + <> + onCopy('image', items)}> + {renderCopyIcon('image')} + {renderCopyLabel('image')} + + + + )} + + {coreOpts.map((opt) => ( + onCopy(opt.kind, items)} + > + {renderCopyIcon(opt.kind)} + {renderCopyLabel(opt.kind)} + + ))} + + {docOpts.length > 0 && ( + <> + + {docOpts.map((opt) => ( + onCopy(opt.kind, items)} + > + {renderCopyIcon(opt.kind)} + {renderCopyLabel(opt.kind)} + + ))} + + )} + + {storageOpt && ( + <> + + onCopy('storage-path', items)} + > + {renderCopyIcon('storage-path')} + {renderCopyLabel('storage-path')} + + + )} + + + + ) +} + +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 ( + + + + {m.copy()} + + + {imageOpt && ( + <> + { + e.stopPropagation() + onCopy('image', items) + }} + > + {renderCopyIcon('image')} + {renderCopyLabel('image')} + + + + )} + + {coreOpts.map((opt) => ( + { + e.stopPropagation() + onCopy(opt.kind, items) + }} + > + {renderCopyIcon(opt.kind)} + {renderCopyLabel(opt.kind)} + + ))} + + {docOpts.length > 0 && ( + <> + + {docOpts.map((opt) => ( + { + e.stopPropagation() + onCopy(opt.kind, items) + }} + > + {renderCopyIcon(opt.kind)} + {renderCopyLabel(opt.kind)} + + ))} + + )} + + {storageOpt && ( + <> + + { + e.stopPropagation() + onCopy('storage-path', items) + }} + > + {renderCopyIcon('storage-path')} + {renderCopyLabel('storage-path')} + + + )} + + + ) +} diff --git a/packages/webui/components/file-browser/file-browser.tsx b/packages/webui/components/file-browser/file-browser.tsx index e68fddcd..f3f7349f 100644 --- a/packages/webui/components/file-browser/file-browser.tsx +++ b/packages/webui/components/file-browser/file-browser.tsx @@ -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 ?? []} diff --git a/packages/webui/components/file-browser/file-card.test.tsx b/packages/webui/components/file-browser/file-card.test.tsx index d1e7c515..79cc7722 100644 --- a/packages/webui/components/file-browser/file-card.test.tsx +++ b/packages/webui/components/file-browser/file-card.test.tsx @@ -772,4 +772,34 @@ describe('FileCard', () => { ) expect(screen.getByTestId('file-card-restoring-badge')).toBeTruthy() }) + + it('renders Copy submenu in dropdown menu', () => { + render( + + + , + ) + + const moreBtn = screen.getByRole('button', { name: '' }) + fireEvent.keyDown(moreBtn, { key: 'ArrowDown', code: 'ArrowDown' }) + + const copyOption = screen.getByText(/^Copy$|^复制$/i) + expect(copyOption).toBeTruthy() + }) }) diff --git a/packages/webui/components/file-browser/file-card.tsx b/packages/webui/components/file-browser/file-card.tsx index 0b69c10a..680bbcf2 100644 --- a/packages/webui/components/file-browser/file-card.tsx +++ b/packages/webui/components/file-browser/file-card.tsx @@ -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,17 @@ export function FileCard({ {m.download()} )} + {!isRecentlyDeleted && !isShareView && ( + onCopy?.(kind, targetItems)} + /> + )} {canEdit && archiveStorageEnabled && canArchiveItem && ( 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,17 @@ export function FolderCard({ {m.download()} )} + {!isRecentlyDeleted && !isShareView && ( + onCopy?.(kind, targetItems)} + /> + )} {canEdit && archiveStorageEnabled && ( <> { + const handleCopy = async (kind: CopyKind, 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()) - } + + 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 } - 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 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 copyToClipboard(text) + const ok = await copyImageToClipboard(urlPromise) if (ok) { - toast.success(m.copied_name_and_download_link_to_clipboard()) + toast.success(m.copied_image_toast()) + } else { + toast.error(m.copy_image_failed()) } - } catch (error) { - toast.error('Failed to copy name and download link') - console.error(error) + 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()) } } @@ -543,7 +691,7 @@ export function useFileActions({ handleRestore(targetItems) break case 'copy-name-and-download-link': - handleCopyNameAndDownloadLink(targetItems) + handleCopy('download-link', targetItems) break case 'archive': handleArchive(targetItems) @@ -554,6 +702,10 @@ export function useFileActions({ } } + const handleCopyNameAndDownloadLink = (items: AssetInfo[]) => { + handleCopy('download-link', items) + } + return { editingItemId, setEditingItemId, @@ -561,6 +713,7 @@ export function useFileActions({ handleDelete, handleRestore, handleDownload, + handleCopy, handleCopyNameAndDownloadLink, handleArchive, handleRestoreArchive, diff --git a/packages/webui/components/viewers/image/image-viewer.tsx b/packages/webui/components/viewers/image/image-viewer.tsx index 9cceaec9..abb96328 100644 --- a/packages/webui/components/viewers/image/image-viewer.tsx +++ b/packages/webui/components/viewers/image/image-viewer.tsx @@ -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( 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((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) } } diff --git a/packages/webui/lib/clipboard.test.ts b/packages/webui/lib/clipboard.test.ts index d9856789..72e6293d 100644 --- a/packages/webui/lib/clipboard.test.ts +++ b/packages/webui/lib/clipboard.test.ts @@ -1,6 +1,6 @@ // @vitest-environment happy-dom import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' -import { copyToClipboard } from './clipboard' +import { copyToClipboard, copyToClipboardDeferred, copyImageToClipboard } from './clipboard' describe('copyToClipboard', () => { const originalClipboard = navigator.clipboard @@ -49,3 +49,93 @@ describe('copyToClipboard', () => { expect(execCommandFn).toHaveBeenCalledWith('copy') }) }) + +describe('copyToClipboardDeferred', () => { + it('uses navigator.clipboard.write with ClipboardItem when available', async () => { + const mockWrite = vi.fn().mockResolvedValue(undefined) + class MockClipboardItem { + types: Record + constructor(types: Record) { + this.types = types + } + } + + Object.defineProperty(globalThis, 'ClipboardItem', { + value: MockClipboardItem, + configurable: true, + writable: true, + }) + + Object.defineProperty(navigator, 'clipboard', { + value: { write: mockWrite }, + configurable: true, + writable: true, + }) + + const success = await copyToClipboardDeferred(Promise.resolve('deferred text')) + expect(success).toBe(true) + expect(mockWrite).toHaveBeenCalledTimes(1) + }) + + it('falls back to copyToClipboard when ClipboardItem is unavailable', async () => { + const mockWriteText = vi.fn().mockResolvedValue(undefined) + Object.defineProperty(globalThis, 'ClipboardItem', { + value: undefined, + configurable: true, + writable: true, + }) + Object.defineProperty(navigator, 'clipboard', { + value: { writeText: mockWriteText }, + configurable: true, + writable: true, + }) + + const success = await copyToClipboardDeferred(Promise.resolve('fallback deferred text')) + expect(success).toBe(true) + expect(mockWriteText).toHaveBeenCalledWith('fallback deferred text') + }) +}) + +describe('copyImageToClipboard', () => { + it('returns false when clipboard API is unavailable', async () => { + Object.defineProperty(navigator, 'clipboard', { + value: undefined, + configurable: true, + writable: true, + }) + + const success = await copyImageToClipboard('http://example.com/image.png') + expect(success).toBe(false) + }) + + it('accepts a Promise resolving to a URL and writes to clipboard', async () => { + const mockWrite = vi.fn().mockResolvedValue(undefined) + class MockClipboardItem { + types: Record + constructor(types: Record) { + this.types = types + } + } + + Object.defineProperty(globalThis, 'ClipboardItem', { + value: MockClipboardItem, + configurable: true, + writable: true, + }) + + Object.defineProperty(navigator, 'clipboard', { + value: { write: mockWrite }, + configurable: true, + writable: true, + }) + + const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => { + return new Response(new Blob(['fake-image-bytes'], { type: 'image/webp' })) + }) + + const success = await copyImageToClipboard(Promise.resolve('http://example.com/image.png')) + expect(success).toBe(true) + expect(mockWrite).toHaveBeenCalledTimes(1) + fetchSpy.mockRestore() + }) +}) diff --git a/packages/webui/lib/clipboard.ts b/packages/webui/lib/clipboard.ts index c6e74f5e..d31c357d 100644 --- a/packages/webui/lib/clipboard.ts +++ b/packages/webui/lib/clipboard.ts @@ -41,3 +41,112 @@ export async function copyToClipboard(text: string): Promise { return false } } + +/** + * Copies text resolved asynchronously to clipboard, using ClipboardItem to preserve + * Safari's transient user activation when fetching links. + */ +export async function copyToClipboardDeferred(textPromise: Promise): Promise { + if ( + typeof navigator !== 'undefined' && + navigator.clipboard && + typeof navigator.clipboard.write === 'function' && + typeof ClipboardItem !== 'undefined' + ) { + try { + const blobPromise = textPromise.then((text) => new Blob([text], { type: 'text/plain' })) + await navigator.clipboard.write([ + new ClipboardItem({ + 'text/plain': blobPromise, + }), + ]) + return true + } catch { + // Fall back if deferred writing fails or is rejected + } + } + + try { + const text = await textPromise + return await copyToClipboard(text) + } catch (err) { + console.error('Failed to copy deferred text to clipboard:', err) + return false + } +} + +/** + * Copies an image at a given URL (or promise resolving to URL) to the clipboard as PNG. + */ +export async function copyImageToClipboard( + imageUrlOrPromise: string | Promise, +): Promise { + if ( + typeof navigator === 'undefined' || + !navigator.clipboard || + typeof navigator.clipboard.write !== 'function' || + typeof ClipboardItem === 'undefined' + ) { + return false + } + + const renderPngBlob = async (): Promise => { + const imageUrl = await imageUrlOrPromise + const response = await fetch(imageUrl) + 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((resolve) => { + canvas.toBlob(resolve, 'image/png') + }) + + if (!pngBlob) throw new Error('Failed to convert image to PNG') + return pngBlob + } finally { + URL.revokeObjectURL(objectUrl) + } + } + + try { + const blobPromise = renderPngBlob() + + // Try passing promise to ClipboardItem (Safari / Chrome 86+) to preserve user activation + try { + await navigator.clipboard.write([ + new ClipboardItem({ + 'image/png': blobPromise, + }), + ]) + return true + } catch { + // Fallback for environments requiring a concrete Blob in ClipboardItem + const blob = await blobPromise + await navigator.clipboard.write([ + new ClipboardItem({ + 'image/png': blob, + }), + ]) + return true + } + } catch (err) { + console.error('Failed to copy image to clipboard:', err) + return false + } +} diff --git a/packages/webui/messages/en.json b/packages/webui/messages/en.json index e749479f..70111cad 100644 --- a/packages/webui/messages/en.json +++ b/packages/webui/messages/en.json @@ -428,6 +428,32 @@ "api_token_hidden_hint": "Tokens can only be viewed when they are created.", "copy_name_and_download_link": "Copy name and download link", "copied_name_and_download_link_to_clipboard": "Copied name and download link to clipboard", + "copy_image": "Image", + "copy_name": "Name", + "copy_app_link": "Link", + "copy_download_link": "Download link", + "copy_id": "ID", + "copy_markdown_link": "Markdown link", + "copy_as_table": "As table (TSV)", + "copy_storage_path": "Storage path", + "copied_image_toast": "Copied image to clipboard", + "copied_name_toast": "Copied name to clipboard", + "copied_names_toast": "Copied {count} names to clipboard", + "copied_link_toast": "Copied link to clipboard", + "copied_links_toast": "Copied {count} links to clipboard", + "copied_download_link_toast": "Copied download link (expires soon)", + "copied_download_links_toast": "Copied {count} download links (expires soon)", + "copied_id_toast": "Copied ID to clipboard", + "copied_ids_toast": "Copied {count} IDs to clipboard", + "copied_markdown_link_toast": "Copied Markdown link to clipboard", + "copied_markdown_links_toast": "Copied {count} Markdown links to clipboard", + "copied_table_toast": "Copied {count} items as table", + "copied_storage_path_toast": "Copied storage path to clipboard", + "copied_storage_paths_toast": "Copied {count} storage paths to clipboard", + "copy_failed": "Failed to copy to clipboard", + "copy_image_failed": "Failed to copy image", + "copied_skipped_archived_suffix": "({count} archived skipped)", + "copied_skipped_folders_suffix": "({count} folders skipped)", "ai": "AI", "providers": "Providers", diff --git a/packages/webui/messages/zh.json b/packages/webui/messages/zh.json index 998c277f..c9f522e1 100644 --- a/packages/webui/messages/zh.json +++ b/packages/webui/messages/zh.json @@ -428,6 +428,32 @@ "api_token_hidden_hint": "令牌仅在创建时可见。", "copy_name_and_download_link": "复制名称和下载链接", "copied_name_and_download_link_to_clipboard": "已复制名称和下载链接到剪贴板", + "copy_image": "图片", + "copy_name": "名称", + "copy_app_link": "链接", + "copy_download_link": "下载链接", + "copy_id": "ID", + "copy_markdown_link": "Markdown 链接", + "copy_as_table": "表格格式 (TSV)", + "copy_storage_path": "存储路径", + "copied_image_toast": "已复制图片到剪贴板", + "copied_name_toast": "已复制名称到剪贴板", + "copied_names_toast": "已复制 {count} 个名称到剪贴板", + "copied_link_toast": "已复制链接到剪贴板", + "copied_links_toast": "已复制 {count} 个链接到剪贴板", + "copied_download_link_toast": "已复制下载链接(即将过期)", + "copied_download_links_toast": "已复制 {count} 个下载链接(即将过期)", + "copied_id_toast": "已复制 ID 到剪贴板", + "copied_ids_toast": "已复制 {count} 个 ID 到剪贴板", + "copied_markdown_link_toast": "已复制 Markdown 链接到剪贴板", + "copied_markdown_links_toast": "已复制 {count} 个 Markdown 链接到剪贴板", + "copied_table_toast": "已复制 {count} 项为表格", + "copied_storage_path_toast": "已复制存储路径到剪贴板", + "copied_storage_paths_toast": "已复制 {count} 个存储路径到剪贴板", + "copy_failed": "复制到剪贴板失败", + "copy_image_failed": "复制图片失败", + "copied_skipped_archived_suffix": "(已跳过 {count} 个已归档项)", + "copied_skipped_folders_suffix": "(已跳过 {count} 个文件夹)", "ai": "AI", "providers": "提供商",