import { useScreenSize } from '@/ui/hooks/useScreenSize' import { getBestTranscode } from '@/ui/lib/media' import type { AssetInfo } from '@shumai/dtos' import { Check, Copy, Download, Minus, Plus } from 'lucide-react' import type { RefObject } from 'react' import { useEffect, useRef, useState } from 'react' import type Player from 'video.js/dist/types/player' import DrawingCanvas from './drawing-canvas' import VideoPlayer from './viewers/video-player' import { useAnnotationStore } from '@/ui/stores/annotation-store' import type { Annotation } from '@/ui/types' type FileViewerProps = { file: AssetInfo videoRef?: RefObject onPlay?: () => void onPause?: () => void onTimeUpdate?: (time: number) => void annotations?: Annotation[] } export function FileViewer({ file, videoRef, onPlay, onPause, onTimeUpdate, annotations, }: FileViewerProps) { const { width: screenWidth } = useScreenSize() const isImage = file.mediaType?.startsWith('image/') const isVideo = file.mediaType?.startsWith('video/') // Annotation Store const { isDrawing, currentTool, currentColor, addAnnotation, annotations: draftAnnotations, reset: resetAnnotations, } = useAnnotationStore() // Reset annotations when file changes useEffect(() => { resetAnnotations() }, [file.id, resetAnnotations]) // State for Image Viewer const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }) const containerRef = useRef(null) const [zoom, setZoom] = useState(1) const [pan, setPan] = useState({ x: 0, y: 0 }) const [copied, setCopied] = useState(false) const imgW = file.media?.metadata?.originalWidth ?? 1920 const imgH = file.media?.metadata?.originalHeight ?? 1080 const conW = containerSize.width const conH = containerSize.height let baseScale = 1 if (conW > 0 && conH > 0) { baseScale = Math.min(conW / imgW, conH / imgH) } // Reset/Fit logic useEffect(() => { if (conW > 0 && conH > 0 && isImage) { setZoom(baseScale) // Center const x = (conW - imgW * baseScale) / 2 const y = (conH - imgH * baseScale) / 2 setPan({ x, y }) } }, [file.id, conW, conH, isImage, baseScale, imgW, imgH]) // Resize Observer useEffect(() => { if (!containerRef.current) return const observer = new ResizeObserver((entries) => { const entry = entries[0] if (entry) { setContainerSize({ width: entry.contentRect.width, height: entry.contentRect.height, }) } }) observer.observe(containerRef.current) return () => observer.disconnect() }, []) const handleZoom = (factor: number) => { const cx = conW / 2 const cy = conH / 2 // Limit min/max zoom if needed? const newZoom = zoom * factor if (newZoom < 0.01 || newZoom > 50) return const newPanX = cx - (cx - pan.x) * (newZoom / zoom) const newPanY = cy - (cy - pan.y) * (newZoom / zoom) setZoom(newZoom) setPan({ x: newPanX, y: newPanY }) } const handleFit = () => { setZoom(baseScale) const x = (conW - imgW * baseScale) / 2 const y = (conH - imgH * baseScale) / 2 setPan({ x, y }) } let bestUrl = file.media?.original?.downloadUrl if (isImage) { const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth) if (bestTranscode?.url) { bestUrl = bestTranscode.url } } const handleDownload = () => { const url = file.media?.original?.downloadUrl if (!url) return const link = document.createElement('a') link.href = url link.download = file.name || 'image' document.body.appendChild(link) link.click() document.body.removeChild(link) } const handleCopy = async () => { const webpUrl = bestUrl if (!webpUrl) return try { // To support Safari and iOS, we must invoke navigator.clipboard.write // synchronously inside the click handler. We can pass a promise to ClipboardItem // which resolves to the Blob asynchronously. const copyPromise = (async () => { const response = await fetch(webpUrl) const blob = await response.blob() const img = new Image() img.crossOrigin = 'anonymous' const objectUrl = URL.createObjectURL(blob) img.src = objectUrl try { await new Promise((resolve, reject) => { img.onload = resolve img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e))) }) const canvas = document.createElement('canvas') canvas.width = img.width canvas.height = img.height const ctx = canvas.getContext('2d') if (!ctx) throw new Error('Could not get canvas context') ctx.drawImage(img, 0, 0) const pngBlob = await new Promise((resolve) => { canvas.toBlob(resolve, 'image/png') }) if (!pngBlob) throw new Error('Failed to convert image to PNG') return pngBlob } finally { URL.revokeObjectURL(objectUrl) } })() await navigator.clipboard.write([ new ClipboardItem({ 'image/png': copyPromise, }), ]) setCopied(true) setTimeout(() => setCopied(false), 2000) } catch (err) { console.error('Failed to copy image to clipboard:', err) } } if (!bestUrl) { return (

Preview unavailable

) } // Combine saved annotations and draft annotations const displayAnnotations = [...(annotations || []), ...draftAnnotations] return (
{isImage && ( <>
{/* Zoom Toolbar */}
{Math.round(zoom * 100)}%
)} {isVideo && ( )}
) }