import { Avatar, AvatarFallback, AvatarImage } from '@/ui/components/ui/avatar' import { Button } from '@/ui/components/ui/button' import { DrawAnnotation, ShumaiLogo } from '@/ui/components/ui/icons' import { getViewerForFile } from '@/ui/components/viewers/registry' import { formatFrame, formatTimecode } from '@/ui/components/viewers/video/utils' import { isImageFileName } from '@/ui/lib/media' import { m } from '@/ui/paraglide/messages.js' import { useUiStore } from '@/ui/stores/ui' import type { AssetInfo, CommentInfo } from '@shumai/dtos' import { ArrowDownWideNarrow, CheckCircle2, FileAudio, FileIcon, FileText, Loader2, Printer, } from 'lucide-react' import React, { useCallback, useMemo, useState } from 'react' import Markdown from 'react-markdown' import { parseAnnotations } from './annotation-overlay-svg' import { CommentFrameThumbnail } from './comment-frame-thumbnail' export type PrintSortMode = 'position' | 'oldest' | 'newest' export interface PrintCommentsViewProps { asset: AssetInfo breadcrumbs: string[] comments: CommentInfo[] shareId?: string sharePassword?: string } function getHeaderThumbnailUrl(asset: AssetInfo): string | null { if (asset.preview?.thumbnailUrl) return asset.preview.thumbnailUrl if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) { const sorted = [...asset.media.imageTranscodes] .filter((t) => Boolean(t.url)) .sort((a, b) => (a.width || 0) - (b.width || 0)) if (sorted[0]?.url) return sorted[0].url } return null } function getImageCommentThumbnailUrl(asset: AssetInfo): string | null { if (asset.media?.imageTranscodes && asset.media.imageTranscodes.length > 0) { const valid = asset.media.imageTranscodes.filter((t) => Boolean(t.url)) const adequate = valid .filter((t) => (t.width || 0) >= 400) .sort((a, b) => (a.width || 0) - (b.width || 0)) if (adequate[0]?.url) return adequate[0].url const largest = [...valid].sort((a, b) => (b.width || 0) - (a.width || 0)) if (largest[0]?.url) return largest[0].url } return asset.preview?.thumbnailUrl || null } function buildFrameEndpointUrl(params: { assetId: string second: number width?: number shareId?: string sharePassword?: string }): string { const qs = new URLSearchParams({ second: String(params.second), width: String(params.width ?? 400), }) if (params.shareId) { if (params.sharePassword) { qs.set('p', params.sharePassword) } return `/api/shares/${encodeURIComponent(params.shareId)}/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}` } return `/api/files/${encodeURIComponent(params.assetId)}/comments/frame?${qs.toString()}` } function formatShortDate(iso?: string | null): string { if (!iso) return '' const date = new Date(iso) if (Number.isNaN(date.getTime())) return '' return new Intl.DateTimeFormat(undefined, { month: 'numeric', day: 'numeric', year: '2-digit', }).format(date) } function formatCommentDateTime(iso?: string | null): string { if (!iso) return '' const date = new Date(iso) if (Number.isNaN(date.getTime())) return '' const datePart = new Intl.DateTimeFormat(undefined, { month: 'numeric', day: 'numeric', year: '2-digit', }).format(date) const timePart = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit', }).format(date) return `${datePart} ยท ${timePart}` } function splitMiddleTruncate(name: string): { head: string; tail: string } { if (name.length <= 16) return { head: name, tail: '' } const tailLen = 10 return { head: name.slice(0, name.length - tailLen), tail: name.slice(name.length - tailLen), } } function preprocessMarkdown(text: string): string { return text.replace(/<@([a-zA-Z0-9_-]+)>/g, '@$1').replace(/^\[([^\]]+)\]:/gm, '\\[$1\\]:') } function renderPlainCommentText(comment: CommentInfo): React.ReactNode { const text = comment.message ?? '' const parts = text.split(/(<@[a-zA-Z0-9_-]+>)/g) return parts.map((part, index) => { if (part.match(/^<@[a-zA-Z0-9_-]+>$/)) { const userId = part.slice(2, -1) const mentionedUser = comment.mentions?.find((u) => u.id === userId) return ( @{mentionedUser?.name || 'Unknown'} ) } return {part} }) } export const PrintCommentsView: React.FC = ({ asset, breadcrumbs, comments, shareId, sharePassword, }) => { const { videoTimeDisplayMode } = useUiStore() const viewerDef = useMemo(() => getViewerForFile(asset), [asset]) const proxyType = asset.proxyType ?? asset.media?.proxyType ?? null const hasPositionSort = Boolean(viewerDef.commentsConfig?.hasTimestamp) const [sortMode, setSortMode] = useState(hasPositionSort ? 'position' : 'oldest') const [settledFrameUrls, setSettledFrameUrls] = useState>({}) const frameRate = viewerDef.commentsConfig?.hasTimestamp ? asset.media?.metadata?.frameRate || 30 : undefined const startTimecode = viewerDef.commentsConfig?.hasTimestamp ? asset.media?.metadata?.startTimecode : undefined const formatCommentTimestamp = useCallback( (second: number | null | undefined): string => { if (second === null || second === undefined) return '' if (viewerDef.commentsConfig?.formatTimestamp) { return viewerDef.commentsConfig.formatTimestamp(second) } if (!frameRate) return '' const frameIndex = formatFrame(second, frameRate) return formatTimecode(frameIndex, frameRate, videoTimeDisplayMode, startTimecode) }, [viewerDef, frameRate, videoTimeDisplayMode, startTimecode], ) const sortedComments = useMemo(() => { const list = [...comments] if (sortMode === 'position') { list.sort((a, b) => { const aHas = a.second !== null && a.second !== undefined const bHas = b.second !== null && b.second !== undefined if (aHas && bHas) { if (a.second! !== b.second!) return a.second! - b.second! return a.id.localeCompare(b.id) } if (aHas) return -1 if (bHas) return 1 return a.id.localeCompare(b.id) }) } else if (sortMode === 'newest') { list.sort((a, b) => b.id.localeCompare(a.id)) } else { list.sort((a, b) => a.id.localeCompare(b.id)) } return list }, [comments, sortMode]) const hasVisualThumbnailColumn = proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf' || proxyType === 'image' const getCommentFrameUrl = useCallback( (comment: CommentInfo): string | null => { if (!hasVisualThumbnailColumn) return null if (proxyType === 'image') { return getImageCommentThumbnailUrl(asset) } if (proxyType === 'video' || proxyType === '3d' || proxyType === 'pdf') { if (comment.second !== null && comment.second !== undefined) { return buildFrameEndpointUrl({ assetId: asset.id, second: comment.second, width: 400, shareId, sharePassword, }) } // If an untimestamped comment still carries visual annotations, show the asset poster/thumbnail const anns = parseAnnotations(comment.annotations) if (anns.length > 0) { return getHeaderThumbnailUrl(asset) } return null } return null }, [hasVisualThumbnailColumn, proxyType, asset, shareId, sharePassword], ) const frameUrls = useMemo(() => { const urls = new Map() for (const comment of comments) { const url = getCommentFrameUrl(comment) if (url) urls.set(comment.id, url) for (const reply of comment.replies ?? []) { if (parseAnnotations(reply.annotations).length === 0) continue const replyUrl = getCommentFrameUrl(reply) if (replyUrl) urls.set(reply.id, replyUrl) } } return urls }, [comments, getCommentFrameUrl]) const settledFrameCount = Array.from(frameUrls).filter( ([id, url]) => settledFrameUrls[id] === url, ).length const isLoadingFrames = settledFrameCount < frameUrls.size const sortIndicatorLabel = useMemo(() => { if (sortMode === 'oldest') return m.print_comments_sorted_by_oldest() if (sortMode === 'newest') return m.print_comments_sorted_by_newest() if (proxyType === 'pdf') return m.print_comments_sorted_by_page() if (proxyType === '3d') return m.print_comments_sorted_by_angle() return m.print_comments_sorted_by_timecode() }, [sortMode, proxyType]) const positionSortOptionLabel = useMemo(() => { if (proxyType === 'pdf') return m.print_comments_sort_page() if (proxyType === '3d') return m.print_comments_sort_angle() return m.print_comments_sort_timecode() }, [proxyType]) const headerThumbUrl = useMemo(() => getHeaderThumbnailUrl(asset), [asset]) const { head: nameHead, tail: nameTail } = splitMiddleTruncate(asset.name || '') const creatorAndDate = [asset.creator?.name, formatShortDate(asset.createdAt)] .filter(Boolean) .join(', ') const commentCountLabel = comments.length === 1 ? m.print_comments_count_one() : m.print_comments_count({ count: String(comments.length) }) const renderFrame = (commentId: string, annotations: ReturnType) => { const url = frameUrls.get(commentId) if (!url) return null return ( setSettledFrameUrls((prev) => prev[commentId] === url ? prev : { ...prev, [commentId]: url }, ) } /> ) } const renderCommentEntry = ( comment: CommentInfo, options: { indexNumber?: number isReply: boolean hasReplies: boolean isLastReply: boolean }, ) => { const timestamp = formatCommentTimestamp(comment.second) const annotations = parseAnnotations(comment.annotations) const hasAnnotations = annotations.length > 0 const creatorName = comment.creator?.name || 'Unknown' return (
{/* Avatar + vertical thread connector matching Frame.io / Shumai threads */}
{options.isReply && (
)} {((options.hasReplies && !options.isReply) || (options.isReply && !options.isLastReply)) && (
)} {comment.creator?.image && ( )} {creatorName[0]?.toUpperCase() || 'U'}
{/* Entry content */}
{/* Author + timestamp + #index + completed status */}
{creatorName} {formatCommentDateTime(comment.createdAt)}
{comment.isCompleted && ( {m.print_comments_completed()} )} {options.indexNumber !== undefined && ( # {options.indexNumber} )}
{/* Prefix (timecode / page / angle + annotation indicator) + Comment text */}
{(timestamp || hasAnnotations) && ( {timestamp && ( {timestamp} )} {hasAnnotations && ( )} )} {comment.sessionId && comment.message ? (
{preprocessMarkdown(comment.message)}
) : ( {renderPlainCommentText(comment)} )}
{options.isReply && frameUrls.has(comment.id) && (
{renderFrame(comment.id, annotations)}
)} {/* Attachments */} {comment.attachments && comment.attachments.length > 0 && (
{comment.attachments.map((att) => { const rawName = att.url?.split('/').pop()?.split('?')[0] || 'file' const name = decodeURIComponent(rawName) const isImage = isImageFileName(name) return (
{isImage ? ( {name} ) : ( )} {name}
) })}
)} {/* Emoji reactions */} {comment.reactionCounts && comment.reactionCounts.length > 0 && (
{comment.reactionCounts.map((reaction) => ( {reaction.code} {reaction.count} ))}
)}
) } return (
{/* Non-printable action toolbar */}
{isLoadingFrames ? ( {m.print_comments_loading_frames({ loaded: String(settledFrameCount), total: String(frameUrls.size), })} ) : ( {commentCountLabel} )}
{hasPositionSort && ( )}
{/* Printable document body */}
{/* Document Header */}
{headerThumbUrl ? ( ) : proxyType === 'audio' ? ( ) : proxyType === 'pdf' ? ( ) : ( )}
{/* Top row: Breadcrumbs + Shumai Logo */}
{/* Bottom row: Filename + Creator & Date */}

{nameHead} {nameTail && {nameTail}}

{creatorAndDate && ( {creatorAndDate} )}
{/* Sort Indicator */}
{sortIndicatorLabel}
{/* Comments List */} {sortedComments.length === 0 ? (
{m.print_comments_empty()}
) : (
{sortedComments.map((comment, idx) => { const annotations = parseAnnotations(comment.annotations) const replies = comment.replies ?? [] return (
{hasVisualThumbnailColumn && (
{renderFrame(comment.id, annotations)}
)}
{renderCommentEntry(comment, { indexNumber: idx + 1, isReply: false, hasReplies: replies.length > 0, isLastReply: false, })} {replies.map((reply, replyIdx) => renderCommentEntry(reply, { isReply: true, hasReplies: false, isLastReply: replyIdx === replies.length - 1, }), )}
) })}
)}
) }