import { client } from '@/ui/api/client' import { MessageCard } from '@/ui/components/chat/message-card' import { ChatInput } from '@/ui/components/chat/message-input' import FieldRenderer from '@/ui/components/field-renderer' import { GuestIdentityPopup } from '@/ui/components/guest-identity-popup' import { ScrollArea } from '@/ui/components/ui/scroll-area' import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/ui/components/ui/tabs' import { getViewerForFile } from '@/ui/components/viewers/registry' import { usePermissions } from '@/ui/hooks/use-permissions' import { cn } from '@/ui/lib/utils' import { m } from '@/ui/paraglide/messages.js' import { useFieldStore } from '@/ui/stores/fields' import type { MemberInfo } from '@/ui/stores/members' import type { Annotation } from '@/ui/types' import type { AssetInfo, CommentInfo, FieldValueInfo } from '@shumai/dtos' import { type FieldInfo as MetadataFieldInfo } from '@shumai/dtos' import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useInView } from 'react-intersection-observer' import { toast } from 'sonner' export interface MobileFileBottomSheetProps { 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 heightPercent: number onHeightPercentChange: (height: number) => void } export function MobileFileBottomSheet({ teamId, projectId, file, onSaveField, members, onCommentSelect, hideAnnotationControl = false, readOnly = false, publicFields, isPublic = false, shareId, currentTime, onTyping, selectedCommentId, heightPercent, onHeightPercentChange, }: MobileFileBottomSheetProps) { 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 [pendingComment, setPendingComment] = useState<{ text: string attachmentIds: string[] annotations?: Annotation[] replyToId?: string | null second?: number | null } | null>(null) // Dragging state const isDragging = useRef(false) const dragStartY = useRef(0) const dragStartHeightPercent = useRef(heightPercent) const handlePointerDown = (e: React.PointerEvent) => { isDragging.current = true dragStartY.current = e.clientY dragStartHeightPercent.current = heightPercent ;(e.target as HTMLElement).setPointerCapture?.(e.pointerId) } const handlePointerMove = useCallback( (e: React.PointerEvent) => { if (!isDragging.current) return const deltaY = dragStartY.current - e.clientY const deltaPercent = (deltaY / window.innerHeight) * 100 const newHeight = Math.min(85, Math.max(10, dragStartHeightPercent.current + deltaPercent)) onHeightPercentChange(newHeight) }, [onHeightPercentChange], ) const handlePointerUp = (e: React.PointerEvent) => { isDragging.current = false try { ;(e.target as HTMLElement).releasePointerCapture?.(e.pointerId) } catch { // Ignore } } 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, 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'], }) }, onError: () => { toast.error(m.failed_to_post_comment?.() || 'Failed to post comment') }, }) const totalComments = commentsData?.pages?.[0]?.pageInfo?.total ?? commentsData?.pages.reduce((acc, page) => acc + (page.data?.length || 0), 0) ?? 0 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 = ( text: string, attachmentIds: string[], annotations: Annotation[] = [], replyToId?: string | null, second?: number | null, ) => { if (!text.trim() && attachmentIds.length === 0 && annotations.length === 0) return const actualReplyToId = replyToId || replyingTo?.id || null if (isPublic) { const guestUserId = localStorage.getItem(`guest_user_id_${shareId}`) if (!guestUserId) { setPendingComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, second }) setIsGuestPopupOpen(true) } else { createComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, guestUserId, second, }) } } else { createComment({ text, attachmentIds, annotations, replyToId: actualReplyToId, second }) } setReplyingTo(null) } const handleGuestSuccess = (guestUserId: string) => { if (pendingComment) { createComment({ ...pendingComment, guestUserId }) 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', } } const isCollapsed = heightPercent <= 15 return (
{/* Drag Handle Bar */}
{/* Tabs Header */} {m.comments()} {totalComments > 0 && `(${totalComments})`} {m.fields()} {/* Comments Tab Content */}
{m.all_comments?.() || 'All comments'} {totalComments > 0 ? ` (${totalComments})` : ''}
{comments.length === 0 ? (
{m.no_comments_yet()}
) : (
{comments.map((comment) => (
{ onCommentSelect?.(comment) }} /> {comment.replies?.map((reply, index) => (
{ onCommentSelect?.(reply) }} />
))}
))}
)} {/* Sticky Bottom Comment Input Bar */} {(!readOnly || isPublic) && (
setIsGuestPopupOpen(false)} onSuccess={handleGuestSuccess} > 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} />
)} {/* Fields Tab Content */} {sortedFields && sortedFields.length > 0 ? (
{sortedFields.map((field) => (
onSaveField(field.id!, val) : undefined} readOnly={readOnly || field.readOnly || !canEdit} />
))}
) : (
No custom fields defined
)}
) }