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' import { usePermissions } from '@/ui/hooks/use-permissions' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs' import { useFieldStore } from '@/ui/stores/fields' import type { Annotation } from '@/ui/types' import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import React, { useEffect, useMemo, useState } from 'react' import { useInView } from 'react-intersection-observer' import { MessageCard } from './chat/message-card' 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' interface FileViewerRightSidebarProps { teamId: string projectId: string file: AssetInfo | null onSaveField: (fieldId: string, value: unknown) => void members: MemberInfo[] onCommentSelect?: (comment: CommentInfo) => void hideAnnotationControl?: boolean readOnly?: boolean publicFields?: MetadataFieldInfo[] isPublic?: boolean shareId?: string currentTime?: number onTyping?: () => void 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, file, onSaveField, members, onCommentSelect, hideAnnotationControl = false, readOnly = false, publicFields, isPublic = false, shareId, currentTime, onTyping, selectedCommentId, }: FileViewerRightSidebarProps) { const { canEdit } = usePermissions(projectId) const { fields, setFields } = useFieldStore() const queryClient = useQueryClient() 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[] annotations?: Annotation[] replyToId?: string | null 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 () => { const res = await client.api.projects[':projectId'].fields.$get({ param: { projectId: projectId }, }) if (!res.ok) throw new Error('Failed to fetch fields') return await res.json() }, enabled: !!projectId && !publicFields, }) const viewerDef = getViewerForFile(file) useEffect(() => { if (publicFields) { setFields(publicFields, projectId) } else if (apiFields) { setFields(apiFields as unknown as MetadataFieldInfo[], projectId) } }, [apiFields, publicFields, projectId, setFields]) const { data: commentsData, fetchNextPage, hasNextPage, } = useInfiniteQuery({ queryKey: isPublic ? ['shares', shareId, 'files', file?.id, 'comments'] : ['files', file?.id, 'comments'], queryFn: async ({ pageParam }) => { if (isPublic) { const password = localStorage.getItem(`share_pwd_${shareId}`) || '' const res = await client.api.shares[':shareId'].files[':fileId'].comments.$get( { param: { shareId: shareId!, fileId: file!.id! }, query: { after: pageParam as string }, }, { headers: { 'x-share-password': password, }, }, ) if (!res.ok) throw new Error('Failed to fetch comments') return await res.json() } else { const res = await client.api.files[':fileId'].comments.$get({ param: { fileId: file!.id! }, query: { after: pageParam as string }, }) if (!res.ok) throw new Error('Failed to fetch comments') return await res.json() } }, enabled: !!file?.id && (!isPublic || !!shareId), initialPageParam: '', refetchInterval: 2000, // eslint-disable-next-line @typescript-eslint/no-explicit-any getNextPageParam: (lastPage: any) => lastPage.pageInfo?.cursor || undefined, }) const { mutate: createComment } = useMutation({ mutationFn: async ({ text, attachmentIds, annotations, replyToId, second, }: { text: string attachmentIds: string[] annotations?: Annotation[] replyToId?: string | null second?: number | null }) => { if (isPublic) { const password = localStorage.getItem(`share_pwd_${shareId}`) || '' const res = await client.api.shares[':shareId'].files[':fileId'].comments.$post( { param: { shareId: shareId!, fileId: file!.id! }, json: { message: text, attachmentIds: attachmentIds, replyToId: replyToId ?? undefined, annotations: annotations, second: second ?? undefined, }, }, { headers: { 'x-share-password': password, }, }, ) if (!res.ok) throw new Error('Failed to create comment') return await res.json() } else { const res = await client.api.files[':fileId'].comments.$post({ param: { fileId: file!.id! }, json: { message: text, attachmentIds: attachmentIds, replyToId: replyToId ?? undefined, annotations: annotations, second: second ?? undefined, }, }) if (!res.ok) throw new Error('Failed to create comment') return await res.json() } }, onSuccess: () => { queryClient.invalidateQueries({ queryKey: isPublic ? ['shares', shareId, 'files', file?.id, 'comments'] : ['files', file?.id, 'comments'], }) }, }) React.useEffect(() => { if (inView && hasNextPage) { fetchNextPage() } }, [inView, fetchNextPage, hasNextPage]) const itemFieldValueMap = useMemo(() => { return (file?.fieldValues || []).reduce( (acc: Record, val: FieldValueInfo) => { acc[val.fieldId!] = val return acc }, {}, ) }, [file?.fieldValues]) const sortedFields = useMemo(() => { return [...fields].sort((a, b) => { const nameA = a.config?.name?.toLowerCase() || '' const nameB = b.config?.name?.toLowerCase() || '' if (nameA < nameB) return -1 if (nameA > nameB) return 1 return 0 }) }, [fields]) const comments = // eslint-disable-next-line @typescript-eslint/no-explicit-any (commentsData?.pages.flatMap((page: any) => page.data ?? []) as CommentInfo[]) ?? [] const handleSendMessage = async ( text: string, attachmentIds: string[], annotations?: Annotation[], replyToId?: string | null, second?: number | null, ) => { if (!file?.id) return if (isPublic) { // Check if logged in console.log('[handleSendMessage] checking auth status') const meRes = await client.api.me.$get() const { id: loggedInUserId } = await meRes.json() console.log('[handleSendMessage] loggedInUserId:', loggedInUserId) if (!loggedInUserId) { const guestUserId = localStorage.getItem('guest_user_id') console.log('[handleSendMessage] guestUserId from storage:', guestUserId) if (!guestUserId) { console.log('[handleSendMessage] no guest ID, opening popup') setPendingComment({ text, attachmentIds, annotations, replyToId, second }) setIsGuestPopupOpen(true) return } createComment({ text, attachmentIds, annotations, replyToId, second }) } else { createComment({ text, attachmentIds, annotations, replyToId, second }) } } else { createComment({ text, attachmentIds, annotations, replyToId, second }) } setReplyingTo(null) } const handleGuestSuccess = () => { if (pendingComment) { createComment({ ...pendingComment }) setPendingComment(null) setReplyingTo(null) } } const getUser = (id: string): MemberInfo => { const member = members.find((m) => m.id === id) if (member) { return member } return { id: 'unknown', name: 'Unknown', role: 'unknown', } } if (!file) { return (

{m.no_item_selected()}

{m.select_file_to_view_details()}

) } return (
{m.comments()} {m.fields()} {!isPublic && (
{m.all_comments()} {m.export_comments()} {COMMENT_EXPORT_OPTIONS.map((opt) => ( handleExportComments(opt.format)} > {opt.label} {opt.ext} ))}
)}
{comments.map((comment) => (
{ onCommentSelect?.(comment) }} readOnly={readOnly} isPublic={isPublic} /> {comment.replies?.map((reply, index) => (
{ onCommentSelect?.(reply) }} readOnly={readOnly} isPublic={isPublic} />
))}
))}
{(!readOnly || isPublic) && (
setIsGuestPopupOpen(false)} onSuccess={handleGuestSuccess} shareId={shareId || undefined} > setReplyingTo(null)} hideAnnotationControl={hideAnnotationControl} disableMentions={isPublic} currentTime={viewerDef?.commentsConfig?.hasTimestamp ? currentTime : undefined} formatTimestamp={viewerDef?.commentsConfig?.formatTimestamp} frameRate={ viewerDef?.commentsConfig?.hasTimestamp ? file?.media?.metadata?.frameRate || 30 : undefined } startTimecode={ viewerDef?.commentsConfig?.hasTimestamp ? file?.media?.metadata?.startTimecode : undefined } onTyping={onTyping} />
)} {sortedFields && sortedFields.length > 0 && (
{sortedFields.map((field) => (
onSaveField(field.id!, val) : undefined} readOnly={readOnly || field.readOnly || !canEdit} />
))}
)}
) }