import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react' import { AlertCircle, Loader2 } from 'lucide-react' import { cn } from '@/ui/lib/utils' import { client } from '@/ui/api/client' import DrawingCanvas from '@/ui/components/drawing-canvas' import { useAnnotationStore } from '@/ui/stores/annotation-store' import type { FileViewerProps, MediaController } from '../types' import { centeredPan, fitScale, zoomAtPoint } from '../pan-zoom' import { usePanZoomGestures } from '../use-pan-zoom' import { ModelControlBar } from './model-control-bar' import { secondToDegree, secondToFrame, calculateFrameCenterTime, TOTAL_FRAMES, FRAME_DURATION, } from './utils' export const ModelViewer = React.forwardRef( ( { file: data, onPlay, onPause, onTimeUpdate, onSeek, annotations, startTime, shareId, children, allowDownload = true, autoPlay = false, }, ref, ) => { const rootRef = useRef(null) const videoRef = useRef(null) const containerRef = useRef(null) const [containerSize, setContainerSize] = useState({ width: 0, height: 0 }) const [isPlaying, setIsPlaying] = useState(false) const [currentTime, setCurrentTime] = useState(startTime || 0) const [isLoading, setIsLoading] = useState(true) const [error, setError] = useState(null) const [isFullScreen, setIsFullScreen] = useState(false) // Pan & Zoom const [zoom, setZoom] = useState(1) const [pan, setPan] = useState({ x: 0, y: 0 }) const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false) useEffect(() => { setHasManuallyZoomed(false) }, [data.id]) // Drag-to-rotate state const [isDraggingRotation, setIsDraggingRotation] = useState(false) const dragStartRef = useRef<{ clientX: number; frame: number }>({ clientX: 0, frame: 0 }) const hasTriggeredSeekInDragRef = useRef(false) const videoSrc = data.media?.videoTranscodes?.[0]?.url || data.media?.videoPreview?.url || '' const handleDownload = async () => { const key = data.media?.original?.key if (!key || !data.id) return try { const res = shareId ? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({ param: { shareId, fileId: data.id }, json: { key }, }) : await client.api.files['download-url'].$post({ json: { key, assetId: data.id }, }) if (!res.ok) return const { url } = await res.json() const link = document.createElement('a') link.href = url link.download = data.name || 'model.glb' document.body.appendChild(link) link.click() document.body.removeChild(link) } catch { // fail silently } } // Drawing Annotation store const { isDrawing, currentTool, currentColor, addAnnotation, annotations: draftAnnotations, } = useAnnotationStore() const displayAnnotations = [...(annotations || []), ...draftAnnotations] const isDrawingMode = isDrawing const mediaWidth = data.media?.metadata?.originalWidth || 1080 const mediaHeight = data.media?.metadata?.originalHeight || 1080 const baseScale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight) // 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() }, []) // Initial scale and center useEffect(() => { if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) { setZoom(baseScale) setPan( centeredPan( containerSize.width, containerSize.height, mediaWidth, mediaHeight, baseScale, ), ) } }, [containerSize, mediaWidth, mediaHeight, baseScale, hasManuallyZoomed]) usePanZoomGestures({ containerRef, zoom, pan, baseScale, onZoomChange: (next) => { setHasManuallyZoomed(true) setZoom(next.zoom) setPan(next.pan) }, onPanChange: setPan, }) // Current angle const currentDegree = secondToDegree(currentTime) const onTimeUpdateRef = useRef(onTimeUpdate) useEffect(() => { onTimeUpdateRef.current = onTimeUpdate }, [onTimeUpdate]) const onSeekRef = useRef(onSeek) useEffect(() => { onSeekRef.current = onSeek }, [onSeek]) // Synchronized playback frame loop (via requestVideoFrameCallback / requestAnimationFrame) useEffect(() => { if (!isPlaying) return const video = videoRef.current if (!video) return let animationFrameId: number | null = null let rvfcId: number | null = null let isCancelled = false type VideoWithRvfc = HTMLVideoElement & { requestVideoFrameCallback?: ( callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void, ) => number cancelVideoFrameCallback?: (id: number) => void } const videoWithRvfc = video as VideoWithRvfc const rvfcSupported = typeof videoWithRvfc.requestVideoFrameCallback === 'function' const updateTime = (time: number) => { if (!isDraggingRotation) { setCurrentTime(time) onTimeUpdateRef.current?.(time) } } if (rvfcSupported) { const onFrame = (_now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => { if (isCancelled) return updateTime(metadata.mediaTime) rvfcId = videoWithRvfc.requestVideoFrameCallback!(onFrame) } rvfcId = videoWithRvfc.requestVideoFrameCallback!(onFrame) } else { const loop = () => { if (isCancelled) return if (videoRef.current) { updateTime(videoRef.current.currentTime) } animationFrameId = requestAnimationFrame(loop) } animationFrameId = requestAnimationFrame(loop) } return () => { isCancelled = true if (rvfcId !== null && typeof videoWithRvfc.cancelVideoFrameCallback === 'function') { videoWithRvfc.cancelVideoFrameCallback(rvfcId) } if (animationFrameId !== null) { cancelAnimationFrame(animationFrameId) } } }, [isPlaying, isDraggingRotation]) // Seek helper const seekToFrame = useCallback( (frameIndex: number) => { const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES const targetSec = normalizedFrame * FRAME_DURATION const centerSec = calculateFrameCenterTime(normalizedFrame) if (videoRef.current) { videoRef.current.currentTime = centerSec } setCurrentTime(targetSec) onTimeUpdate?.(targetSec) }, [onTimeUpdate], ) const seekToDegree = useCallback( (degree: number) => { onSeekRef.current?.() videoRef.current?.pause() const frame = Math.round((((degree % 360) + 360) % 360) / 15) % TOTAL_FRAMES seekToFrame(frame) }, [seekToFrame], ) // Play / Pause toggle const togglePlay = useCallback(() => { const video = videoRef.current if (!video) return if (video.paused || video.ended) { video.play().catch(() => {}) } else { video.pause() } }, []) // Video Imperative Controller useImperativeHandle( ref, () => ({ play: () => { videoRef.current?.play().catch(() => {}) }, pause: () => { videoRef.current?.pause() }, seekTo: (second: number) => { seekToFrame(secondToFrame(second)) }, getCurrentTime: () => videoRef.current?.currentTime || 0, getDuration: () => 4, }), [seekToFrame], ) // Keyboard Hotkeys useEffect(() => { const handleKeyDown = (e: KeyboardEvent) => { const active = document.activeElement if ( active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || (active instanceof HTMLElement && active.isContentEditable)) ) { return } if (e.key === ' ') { e.preventDefault() togglePlay() } else if (e.key === 'ArrowLeft') { e.preventDefault() onSeekRef.current?.() const currentFrame = secondToFrame(currentTime) seekToFrame(currentFrame - 1) } else if (e.key === 'ArrowRight') { e.preventDefault() onSeekRef.current?.() const currentFrame = secondToFrame(currentTime) seekToFrame(currentFrame + 1) } } window.addEventListener('keydown', handleKeyDown) return () => window.removeEventListener('keydown', handleKeyDown) }, [currentTime, seekToFrame, togglePlay]) // Pointer events for Drag-to-Rotate const handleViewerPointerDown = (e: React.PointerEvent) => { if (isDrawingMode || e.button !== 0) return const target = e.currentTarget target.setPointerCapture(e.pointerId) videoRef.current?.pause() const currentFrame = Math.round(currentDegree / 15) % TOTAL_FRAMES dragStartRef.current = { clientX: e.clientX, frame: currentFrame, } hasTriggeredSeekInDragRef.current = false setIsDraggingRotation(true) } const handleViewerPointerMove = (e: React.PointerEvent) => { if (!isDraggingRotation) return const deltaX = e.clientX - dragStartRef.current.clientX // 12px drag movement corresponds to 1 frame (15°) // Dragging right (deltaX > 0) rotates turntable counterclockwise (decreasing frame index) const deltaFrames = Math.round(deltaX / 12) if (deltaFrames !== 0 && !hasTriggeredSeekInDragRef.current) { hasTriggeredSeekInDragRef.current = true onSeekRef.current?.() } const targetFrame = dragStartRef.current.frame - deltaFrames seekToFrame(targetFrame) } const handleViewerPointerUp = (e: React.PointerEvent) => { if (!isDraggingRotation) return hasTriggeredSeekInDragRef.current = false setIsDraggingRotation(false) try { e.currentTarget.releasePointerCapture(e.pointerId) } catch { // pointer may already be released } } // Fullscreen toggle const toggleFullScreen = () => { if (!rootRef.current) return if (!document.fullscreenElement) { rootRef.current.requestFullscreen().catch(() => {}) } else { document.exitFullscreen().catch(() => {}) } } useEffect(() => { const onFsChange = () => { setIsFullScreen(Boolean(document.fullscreenElement)) } document.addEventListener('fullscreenchange', onFsChange) return () => document.removeEventListener('fullscreenchange', onFsChange) }, []) const handleZoomChange = (newZoom: number) => { setHasManuallyZoomed(true) const next = zoomAtPoint( zoom, pan, newZoom / zoom, containerSize.width / 2, containerSize.height / 2, ) setZoom(next.zoom) setPan(next.pan) } const handleZoomReset = () => { setHasManuallyZoomed(false) if (containerSize.width > 0 && containerSize.height > 0) { setZoom(baseScale) setPan( centeredPan( containerSize.width, containerSize.height, mediaWidth, mediaHeight, baseScale, ), ) } } return (
{/* Render Carousel/Sidebar here if not fullscreen */} {!isFullScreen && children} {/* Interactive Drag Rotation Surface & Model Area */}
{/* Centered Scaled Media Wrapper */}
{videoSrc && (
{/* Drawing Canvas Overlay */} {containerSize.width > 0 && containerSize.height > 0 && ( )} {/* Loading Spinner */} {isLoading && !error && (
)} {/* Error Display */} {error && (

{error}

)}
{/* Full-width docked bottom control bar */}
) }, ) ModelViewer.displayName = 'ModelViewer' export default ModelViewer