import type { AssetInfo, AttachmentInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos' import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import type { UserInfo } from '@shumai/dtos' 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 { XIcon } from 'lucide-react' 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' interface FileViewerRightSidebarProps { teamId: string projectId: string file: AssetInfo | null onSaveField: (fieldId: string, value: unknown) => void members: UserInfo[] onCommentSelect?: (comment: CommentInfo) => void hideAnnotationControl?: boolean readOnly?: boolean publicFields?: MetadataFieldInfo[] isPublic?: boolean shareId?: string currentTime?: number onTyping?: () => void selectedCommentId?: string | null } 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 [viewingAttachment, setViewingAttachment] = useState(null) const [isGuestPopupOpen, setIsGuestPopupOpen] = useState(false) const [pendingComment, setPendingComment] = useState<{ text: string attachmentIds: string[] annotations?: Annotation[] replyToId?: string | null second?: number | null } | null>(null) 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 { data: bots } = useQuery({ queryKey: ['projects', projectId, 'bots'], queryFn: async () => { const res = await client.api.projects[':projectId'].bots.$get({ param: { projectId: projectId }, }) if (!res.ok) throw new Error('Failed to fetch bots') return await res.json() }, enabled: !!projectId && !readOnly, }) const isAiEnabled = file?.mediaType?.startsWith('image/') || file?.mediaType?.startsWith('video/') // eslint-disable-next-line @typescript-eslint/no-explicit-any const enabledBots = isAiEnabled ? (bots as any[]) || [] : [] 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, guestUserId, second, }: { text: string attachmentIds: string[] annotations?: Annotation[] replyToId?: string | null guestUserId?: string 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, ...(guestUserId ? { 'x-guest-user-id': guestUserId } : {}), }, }, ) 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, guestUserId, second }) } else { createComment({ text, attachmentIds, annotations, replyToId, second }) } } else { createComment({ text, attachmentIds, annotations, replyToId, second }) } setReplyingTo(null) } const handleGuestSuccess = (guestUserId: string) => { console.log('[handleGuestSuccess] guestUserId:', guestUserId) if (pendingComment) { createComment({ ...pendingComment, guestUserId }) setPendingComment(null) setReplyingTo(null) } } const getUser = (id: string): UserInfo => { const member = members.find((m) => m.id === id) if (member) { return member } if (bots) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const bot = (bots as any[]).find((b) => b.id === id) if (bot) { return { id: bot.id, name: bot.name, role: 'bot' } } } return { id: 'unknown', name: 'Unknown', role: 'unknown', } } if (!file) { return (

No item selected

Select a file to view its details and comments.

) } return (
{/* Lightbox */} {viewingAttachment && viewingAttachment.mediaType?.startsWith('image/') && (
setViewingAttachment(null)} >
Enlarged view setViewingAttachment(null)} />
)} Comments Fields
{comments.map((comment) => (
{ onCommentSelect?.(comment) }} /> {comment.replies?.map((reply, index) => (
{ onCommentSelect?.(reply) }} />
))}
))}
{(!readOnly || isPublic) && (
setIsGuestPopupOpen(false)} onSuccess={handleGuestSuccess} > setReplyingTo(null)} bots={enabledBots} hideAnnotationControl={hideAnnotationControl} disableMentions={isPublic} currentTime={file?.mediaType?.startsWith('video/') ? currentTime : undefined} frameRate={ file?.mediaType?.startsWith('video/') ? file?.media?.metadata?.frameRate || 30 : undefined } onTyping={onTyping} />
)} {sortedFields && sortedFields.length > 0 && (
{sortedFields.map((field) => (
onSaveField(field.id!, val) : undefined} readOnly={readOnly || field.readOnly || !canEdit} />
))}
)}
) }