From c5b57ca8625ec44a82bec86cfa7afbc7d1f5d0ff Mon Sep 17 00:00:00 2001 From: Yiling-J Date: Sun, 13 Sep 2026 16:29:58 +0800 Subject: [PATCH] feat(webui): add NLE comments export and migrate export API to POST (#401) --- packages/api/src/file.test.ts | 54 +++- packages/api/src/file.ts | 8 +- packages/dtos/src/asset.ts | 9 +- .../file-viewer-right-sidebar.test.tsx | 305 ++++++++++++++++++ .../components/file-viewer-right-sidebar.tsx | 110 ++++++- packages/webui/messages/en.json | 2 + packages/webui/messages/zh.json | 2 + 7 files changed, 468 insertions(+), 22 deletions(-) create mode 100644 packages/webui/components/file-viewer-right-sidebar.test.tsx diff --git a/packages/api/src/file.test.ts b/packages/api/src/file.test.ts index a6da5999..c169484a 100644 --- a/packages/api/src/file.test.ts +++ b/packages/api/src/file.test.ts @@ -351,7 +351,7 @@ describe('file api', () => { }) }) - it('GET /files/:fileId/comments/export - success', async () => { + it('POST /files/:fileId/comments/export - success', async () => { vi.mocked(assetService.exportComments).mockResolvedValue({ content: 'TITLE: test\n001 ...', filename: 'test-video_comments.edl', @@ -359,7 +359,11 @@ describe('file api', () => { }) const app = new Hono().use('*', authMiddleware).route('/', fileRoute) - const res = await app.request('/files/test-id/comments/export?format=resolve-edl') + const res = await app.request('/files/test-id/comments/export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ format: 'resolve-edl' }), + }) expect(res.status).toBe(200) expect(res.headers.get('Content-Disposition')).toBe( @@ -381,7 +385,7 @@ describe('file api', () => { }) }) - it('GET /files/:fileId/comments/export - handles CJK filename in Content-Disposition', async () => { + it('POST /files/:fileId/comments/export - handles CJK filename in Content-Disposition', async () => { vi.mocked(assetService.exportComments).mockResolvedValue({ content: 'TITLE: 中文视频\n001 ...', filename: '宣传片_2026_resolve.edl', @@ -389,7 +393,11 @@ describe('file api', () => { }) const app = new Hono().use('*', authMiddleware).route('/', fileRoute) - const res = await app.request('/files/test-id/comments/export?format=resolve-edl') + const res = await app.request('/files/test-id/comments/export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ format: 'resolve-edl' }), + }) expect(res.status).toBe(200) expect(res.headers.get('Content-Disposition')).toBe( @@ -397,7 +405,7 @@ describe('file api', () => { ) }) - it('GET /files/:fileId/comments/export - with timezone query', async () => { + it('POST /files/:fileId/comments/export - with timezone in body', async () => { vi.mocked(assetService.exportComments).mockResolvedValue({ content: '{}', filename: 'test.fiojson', @@ -405,9 +413,14 @@ describe('file api', () => { }) const app = new Hono().use('*', authMiddleware).route('/', fileRoute) - const res = await app.request( - '/files/test-id/comments/export?format=fcp-fiojson&timeZone=America%2FNew_York', - ) + const res = await app.request('/files/test-id/comments/export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + format: 'fcp-fiojson', + timeZone: 'America/New_York', + }), + }) expect(res.status).toBe(200) expect(assetService.exportComments).toHaveBeenCalledWith('test-id', 'fcp-fiojson', { @@ -415,18 +428,31 @@ describe('file api', () => { }) }) - it('GET /files/:fileId/comments/export - 400 on missing or invalid format', async () => { + it('POST /files/:fileId/comments/export - 400 on missing or invalid format', async () => { const app = new Hono().use('*', authMiddleware).route('/', fileRoute) - const resMissing = await app.request('/files/test-id/comments/export') + const resMissing = await app.request('/files/test-id/comments/export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}), + }) expect(resMissing.status).toBe(400) - const resInvalid = await app.request('/files/test-id/comments/export?format=invalid-format') + const resInvalid = await app.request('/files/test-id/comments/export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ format: 'invalid-format' }), + }) expect(resInvalid.status).toBe(400) - const resInvalidTz = await app.request( - '/files/test-id/comments/export?format=resolve-edl&timeZone=Invalid/Fake_Zone', - ) + const resInvalidTz = await app.request('/files/test-id/comments/export', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + format: 'resolve-edl', + timeZone: 'Invalid/Fake_Zone', + }), + }) expect(resInvalidTz.status).toBe(400) }) diff --git a/packages/api/src/file.ts b/packages/api/src/file.ts index d3e6ca9e..89c17e2d 100644 --- a/packages/api/src/file.ts +++ b/packages/api/src/file.ts @@ -17,7 +17,7 @@ import { uploadFileRequestSchema, getDownloadLinksRequestSchema, completeCommentRequestSchema, - exportCommentsQuerySchema, + exportCommentsRequestSchema, AuditAction, } from '@shumai/dtos' import { transcodeService, buildContentDisposition } from '@shumai/core' @@ -228,13 +228,13 @@ const route = new Hono<{ Variables: { user: User } }>() const comments = await assetService.listComments(fileId, req) return c.json(comments) }) - .get( + .post( '/files/:fileId/comments/export', - zValidator('query', exportCommentsQuerySchema), + zValidator('json', exportCommentsRequestSchema), async (c) => { const fileId = c.req.param('fileId') const user = c.get('user') - const { format, timeZone } = c.req.valid('query') + const { format, timeZone } = c.req.valid('json') await authzService.hasPermission({ user, diff --git a/packages/dtos/src/asset.ts b/packages/dtos/src/asset.ts index 17f6e3c1..2f50869a 100644 --- a/packages/dtos/src/asset.ts +++ b/packages/dtos/src/asset.ts @@ -348,7 +348,7 @@ export const commentExportFormatSchema = z.enum([ ]) export type CommentExportFormat = z.infer -export const exportCommentsQuerySchema = z.object({ +export const exportCommentsRequestSchema = z.object({ format: commentExportFormatSchema, timeZone: z .string() @@ -365,4 +365,9 @@ export const exportCommentsQuerySchema = z.object({ ) .optional(), }) -export type ExportCommentsQuery = z.infer +export type ExportCommentsRequest = z.infer + +/** @deprecated Use exportCommentsRequestSchema */ +export const exportCommentsQuerySchema = exportCommentsRequestSchema +/** @deprecated Use ExportCommentsRequest */ +export type ExportCommentsQuery = ExportCommentsRequest diff --git a/packages/webui/components/file-viewer-right-sidebar.test.tsx b/packages/webui/components/file-viewer-right-sidebar.test.tsx new file mode 100644 index 00000000..f8ff930b --- /dev/null +++ b/packages/webui/components/file-viewer-right-sidebar.test.tsx @@ -0,0 +1,305 @@ +// @vitest-environment happy-dom +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import React from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { FileViewerRightSidebar } from './file-viewer-right-sidebar' +import type { AssetInfo } from '@shumai/dtos' +import { toast } from 'sonner' + +vi.mock('react-intersection-observer', () => ({ + useInView: () => ({ + ref: vi.fn(), + inView: false, + }), +})) + +vi.mock('@/ui/hooks/use-permissions', () => ({ + usePermissions: () => ({ + canEdit: true, + }), +})) + +vi.mock('sonner', () => ({ + toast: { + error: vi.fn(), + success: vi.fn(), + }, +})) + +const mockExportPost = vi.fn() + +vi.mock('@/ui/api/client', () => ({ + client: { + api: { + projects: { + ':projectId': { + fields: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => [], + }), + }, + team: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ id: 'team-1' }), + }), + }, + }, + }, + files: { + ':fileId': { + comments: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ + data: [ + { + id: 'comment-1', + message: 'Great shot!', + userId: 'user-1', + createdAt: new Date().toISOString(), + }, + ], + pageInfo: {}, + }), + }), + $post: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ id: 'new-comment-id' }), + }), + export: { + $post: (...args: unknown[]) => mockExportPost(...args), + }, + }, + }, + }, + shares: { + ':shareId': { + files: { + ':fileId': { + comments: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ data: [], pageInfo: {} }), + }), + }, + }, + }, + }, + }, + me: { + $get: vi.fn().mockResolvedValue({ + ok: true, + json: async () => ({ id: 'user-1', name: 'Test User' }), + }), + }, + }, + }, +})) + +describe('FileViewerRightSidebar - Comments Export', () => { + let queryClient: QueryClient + let createObjectUrlMock: ReturnType + let revokeObjectUrlMock: ReturnType + + beforeEach(() => { + queryClient = new QueryClient({ + defaultOptions: { + queries: { retry: false }, + }, + }) + vi.clearAllMocks() + + createObjectUrlMock = vi.spyOn(window.URL, 'createObjectURL').mockReturnValue('blob:mock-url') + revokeObjectUrlMock = vi.spyOn(window.URL, 'revokeObjectURL').mockImplementation(() => {}) + window.HTMLElement.prototype.hasPointerCapture = vi.fn().mockReturnValue(false) + window.HTMLElement.prototype.setPointerCapture = vi.fn() + window.HTMLElement.prototype.releasePointerCapture = vi.fn() + window.HTMLElement.prototype.scrollIntoView = vi.fn() + }) + + afterEach(() => { + cleanup() + }) + + const mockFile: AssetInfo = { + id: 'file-123', + name: 'sample_cut.mp4', + proxyType: 'video', + media: { + metadata: { + duration: 120, + frameRate: 24, + }, + }, + } as AssetInfo + + it('renders "All comments" and the three-dot button in authenticated sidebar', async () => { + render( + + + , + ) + + expect(screen.getByText('All comments')).toBeDefined() + expect(screen.getByRole('button', { name: 'More options' })).toBeDefined() + }) + + it('does NOT render "All comments" header row in public share view', async () => { + render( + + + , + ) + + expect(screen.queryByText('All comments')).toBeNull() + expect(screen.queryByRole('button', { name: 'More options' })).toBeNull() + }) + + it('opens dropdown menu with Export Comments and the 4 NLE options', async () => { + render( + + + , + ) + + const moreButton = screen.getByRole('button', { name: 'More options' }) + fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false }) + + // Submenu trigger should be visible + const exportText = await screen.findByText('Export Comments') + const subTrigger = exportText.closest('[data-slot="dropdown-menu-sub-trigger"]') || exportText + expect(subTrigger).toBeDefined() + + // Open submenu via ArrowRight or click + fireEvent.keyDown(subTrigger, { key: 'ArrowRight', code: 'ArrowRight' }) + + // All 4 formats should be rendered + expect(await screen.findByText('FCP 10.4.0+')).toBeDefined() + expect(screen.getByText('FIOJSON')).toBeDefined() + + expect(screen.getByText('Media Composer')).toBeDefined() + + expect(screen.getByText('Premiere Pro')).toBeDefined() + expect(screen.getAllByText('XML').length).toBe(2) // Media Composer + Premiere Pro + + expect(screen.getByText('Resolve')).toBeDefined() + expect(screen.getByText('EDL')).toBeDefined() + }) + + it('calls export API and triggers download when selecting an NLE format', async () => { + const mockBlob = new Blob(['TITLE: sample\n001 ...'], { type: 'application/edl' }) + mockExportPost.mockResolvedValueOnce({ + ok: true, + blob: async () => mockBlob, + headers: new Headers({ + 'content-disposition': 'attachment; filename="sample_cut_comments.edl"', + }), + }) + + const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {}) + + render( + + + , + ) + + const moreButton = screen.getByRole('button', { name: 'More options' }) + fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false }) + + const exportText = await screen.findByText('Export Comments') + const subTrigger = exportText.closest('[data-slot="dropdown-menu-sub-trigger"]') || exportText + fireEvent.keyDown(subTrigger, { key: 'ArrowRight', code: 'ArrowRight' }) + + const resolveOption = await screen.findByText('Resolve') + fireEvent.click(resolveOption.closest('[data-slot="dropdown-menu-item"]') || resolveOption) + + await waitFor(() => { + expect(mockExportPost).toHaveBeenCalledWith({ + param: { fileId: 'file-123' }, + json: { + format: 'resolve-edl', + timeZone: expect.any(String), + }, + }) + }) + + expect(createObjectUrlMock).toHaveBeenCalledWith(mockBlob) + expect(clickSpy).toHaveBeenCalled() + expect(revokeObjectUrlMock).toHaveBeenCalledWith('blob:mock-url') + clickSpy.mockRestore() + }) + + it('shows error toast when export fails', async () => { + mockExportPost.mockResolvedValueOnce({ + ok: false, + status: 500, + }) + + render( + + + , + ) + + const moreButton = screen.getByRole('button', { name: 'More options' }) + fireEvent.pointerDown(moreButton, { button: 0, ctrlKey: false }) + + const exportText = await screen.findByText('Export Comments') + const subTrigger = exportText.closest('[data-slot="dropdown-menu-sub-trigger"]') || exportText + fireEvent.keyDown(subTrigger, { key: 'ArrowRight', code: 'ArrowRight' }) + + const premiereOption = await screen.findByText('Premiere Pro') + fireEvent.click(premiereOption.closest('[data-slot="dropdown-menu-item"]') || premiereOption) + + await waitFor(() => { + expect(mockExportPost).toHaveBeenCalledWith({ + param: { fileId: 'file-123' }, + json: { + format: 'premiere-xml', + timeZone: expect.any(String), + }, + }) + expect(toast.error).toHaveBeenCalledWith('Failed to export comments') + }) + }) +}) diff --git a/packages/webui/components/file-viewer-right-sidebar.tsx b/packages/webui/components/file-viewer-right-sidebar.tsx index 21fba44b..6bf6a64b 100644 --- a/packages/webui/components/file-viewer-right-sidebar.tsx +++ b/packages/webui/components/file-viewer-right-sidebar.tsx @@ -1,4 +1,4 @@ -import type { AssetInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos' +import type { AssetInfo, CommentExportFormat, CommentInfo, FieldValueInfo } from '@shumai/dtos' import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import type { MemberInfo } from '@/ui/stores/members' import { client } from '@/ui/api/client' @@ -14,6 +14,18 @@ import { ChatInput } from './chat/message-input' import FieldRenderer from './field-renderer' import { GuestIdentityPopup } from './guest-identity-popup' import { ScrollArea } from './ui/scroll-area' +import { Button } from './ui/button' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSub, + DropdownMenuSubContent, + DropdownMenuSubTrigger, + DropdownMenuTrigger, +} from './ui/dropdown-menu' +import { MoreHorizontal } from 'lucide-react' +import { toast } from 'sonner' import { m } from '@/ui/paraglide/messages.js' import { getViewerForFile } from '@/ui/components/viewers/registry' @@ -34,6 +46,17 @@ interface FileViewerRightSidebarProps { selectedCommentId?: string | null } +const COMMENT_EXPORT_OPTIONS: { + format: CommentExportFormat + label: string + ext: string +}[] = [ + { format: 'fcp-fiojson', label: 'FCP 10.4.0+', ext: 'FIOJSON' }, + { format: 'media-composer-xml', label: 'Media Composer', ext: 'XML' }, + { format: 'premiere-xml', label: 'Premiere Pro', ext: 'XML' }, + { format: 'resolve-edl', label: 'Resolve', ext: 'EDL' }, +] + export function FileViewerRightSidebar({ teamId, projectId, @@ -56,6 +79,7 @@ export function FileViewerRightSidebar({ const { ref, inView } = useInView() const [replyingTo, setReplyingTo] = useState(null) const [isGuestPopupOpen, setIsGuestPopupOpen] = useState(false) + const [isExporting, setIsExporting] = useState(false) const [pendingComment, setPendingComment] = useState<{ text: string attachmentIds: string[] @@ -64,6 +88,49 @@ export function FileViewerRightSidebar({ second?: number | null } | null>(null) + const handleExportComments = async (format: CommentExportFormat) => { + if (!file?.id || isExporting) return + try { + setIsExporting(true) + const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone + const res = await client.api.files[':fileId'].comments.export.$post({ + param: { fileId: file.id }, + json: { format, timeZone }, + }) + + if (!res.ok) { + throw new Error('Failed to export comments') + } + + const disposition = res.headers.get('content-disposition') + let filename = `${file.name || 'comments'}_comments` + if (disposition) { + const utf8Match = /filename\*=UTF-8''([^;]+)/i.exec(disposition) + const basicMatch = /filename="?([^";]+)"?/i.exec(disposition) + if (utf8Match?.[1]) { + filename = decodeURIComponent(utf8Match[1]) + } else if (basicMatch?.[1]) { + filename = basicMatch[1] + } + } + + const blob = await res.blob() + const downloadUrl = window.URL.createObjectURL(blob) + const link = document.createElement('a') + link.href = downloadUrl + link.download = filename + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + window.URL.revokeObjectURL(downloadUrl) + } catch (error) { + console.error('Failed to export comments:', error) + toast.error(m.failed_to_export_comments()) + } finally { + setIsExporting(false) + } + } + const { data: apiFields } = useQuery({ queryKey: ['fields', projectId], queryFn: async () => { @@ -298,8 +365,47 @@ export function FileViewerRightSidebar({ + {!isPublic && ( +
+ {m.all_comments()} + + + + + + + + {m.export_comments()} + + + {COMMENT_EXPORT_OPTIONS.map((opt) => ( + handleExportComments(opt.format)} + > + {opt.label} + + {opt.ext} + + + ))} + + + + +
+ )} -
+
{comments.map((comment) => (