mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 21:04:59 +00:00
feat(transcode): add 3D asset support and turntable viewer
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import ModelViewer from './model-viewer'
|
||||
|
||||
export function secondToDegree(second: number): number {
|
||||
const frameIndex = Math.min(Math.max(0, Math.floor(second * 6)), 23)
|
||||
return frameIndex * 15
|
||||
}
|
||||
|
||||
export const modelTypeDefinition: FileTypeDefinition = {
|
||||
id: '3d',
|
||||
name: '3D Model',
|
||||
match: (file) => file.proxyType === '3d',
|
||||
viewer: ModelViewer,
|
||||
commentsConfig: {
|
||||
hasTimestamp: true,
|
||||
hasAnnotations: true,
|
||||
formatTimestamp: (second: number) => {
|
||||
const deg = secondToDegree(second)
|
||||
return `${deg}°`
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import React from 'react'
|
||||
import { Play, Pause, RotateCcw, Maximize, Minimize, Minus, Plus, Download } from 'lucide-react'
|
||||
import { RulerSlider } from './ruler-slider'
|
||||
|
||||
export interface ModelControlBarProps {
|
||||
isPlaying: boolean
|
||||
currentDegree: number
|
||||
zoom: number
|
||||
isFullScreen: boolean
|
||||
allowDownload?: boolean
|
||||
downloadUrl?: string
|
||||
fileName?: string
|
||||
togglePlay: () => void
|
||||
onSeekDegree: (degree: number) => void
|
||||
onResetRotation: () => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
toggleFullScreen: () => void
|
||||
}
|
||||
|
||||
export const ModelControlBar: React.FC<ModelControlBarProps> = ({
|
||||
isPlaying,
|
||||
currentDegree,
|
||||
zoom,
|
||||
isFullScreen,
|
||||
allowDownload = true,
|
||||
downloadUrl,
|
||||
fileName,
|
||||
togglePlay,
|
||||
onSeekDegree,
|
||||
onResetRotation,
|
||||
onZoomChange,
|
||||
onZoomReset,
|
||||
toggleFullScreen,
|
||||
}) => {
|
||||
const handleDownload = () => {
|
||||
if (!downloadUrl) return
|
||||
const a = document.createElement('a')
|
||||
a.href = downloadUrl
|
||||
a.download = fileName || 'model.glb'
|
||||
document.body.appendChild(a)
|
||||
a.click()
|
||||
document.body.removeChild(a)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="absolute inset-x-0 bottom-4 z-20 flex justify-center px-4 pointer-events-none">
|
||||
<div className="pointer-events-auto flex items-center gap-3 px-4 py-2 rounded-xl bg-card/90 backdrop-blur-md border border-border/80 shadow-xl w-full max-w-4xl text-foreground">
|
||||
{/* Play/Pause & Degree Readout */}
|
||||
<div className="flex items-center gap-3 shrink-0">
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePlay}
|
||||
aria-label={isPlaying ? 'Pause' : 'Play'}
|
||||
className="flex items-center justify-center w-8 h-8 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 transition-colors shadow-xs"
|
||||
>
|
||||
{isPlaying ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4 ml-0.5" />}
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="text-xs font-mono font-medium tabular-nums min-w-[76px]"
|
||||
data-testid="degree-readout"
|
||||
>
|
||||
{currentDegree}° / 360°
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Ruler Slider */}
|
||||
<div className="flex-1 min-w-[200px]">
|
||||
<RulerSlider currentDegree={currentDegree} onChange={onSeekDegree} />
|
||||
</div>
|
||||
|
||||
{/* Right Action Tools */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{/* Reset rotation to 0° */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onResetRotation}
|
||||
title="Reset to 0°"
|
||||
aria-label="Reset rotation to 0°"
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<RotateCcw className="w-4 h-4" />
|
||||
</button>
|
||||
|
||||
{/* Zoom controls */}
|
||||
<div className="hidden sm:flex items-center gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onZoomChange(Math.max(0.2, zoom - 0.2))}
|
||||
aria-label="Zoom out"
|
||||
className="p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Minus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onZoomReset}
|
||||
aria-label="Reset zoom"
|
||||
className="px-1.5 py-0.5 text-[11px] font-mono text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{Math.round(zoom * 100)}%
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onZoomChange(Math.min(5, zoom + 0.2))}
|
||||
aria-label="Zoom in"
|
||||
className="p-1 rounded hover:bg-background/80 text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Download */}
|
||||
{allowDownload && downloadUrl && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleDownload}
|
||||
title="Download asset"
|
||||
aria-label="Download asset"
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<Download className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{/* Fullscreen */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={toggleFullScreen}
|
||||
title={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
|
||||
aria-label={isFullScreen ? 'Exit fullscreen' : 'Fullscreen'}
|
||||
className="p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
{isFullScreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import React, { createRef } from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { ModelViewer } from './model-viewer'
|
||||
import type { MediaController } from '../types'
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
|
||||
vi.mock('@/ui/components/drawing-canvas', () => ({
|
||||
default: () => <div data-testid="drawing-canvas" />,
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/paraglide/messages.js', () => ({
|
||||
m: new Proxy({}, { get: () => () => '' }),
|
||||
}))
|
||||
|
||||
class MockResizeObserver {
|
||||
observe = vi.fn(() => {
|
||||
// Immediate callback with mock size
|
||||
this.callback(
|
||||
[{ contentRect: { width: 800, height: 600 } } as unknown as ResizeObserverEntry],
|
||||
this,
|
||||
)
|
||||
})
|
||||
unobserve = vi.fn()
|
||||
disconnect = vi.fn()
|
||||
constructor(private callback: ResizeObserverCallback) {}
|
||||
}
|
||||
|
||||
const mockAsset: AssetInfo = {
|
||||
id: 'asset-3d-1',
|
||||
name: 'robot.glb',
|
||||
proxyType: '3d',
|
||||
createdAt: '2026-01-01T00:00:00Z',
|
||||
updatedAt: '2026-01-01T00:00:00Z',
|
||||
type: 'file',
|
||||
sizeByte: 1024,
|
||||
fileCount: 1,
|
||||
status: 'processed',
|
||||
projectId: 'proj-1',
|
||||
media: {
|
||||
videoPreview: {
|
||||
url: 'https://example.com/robot-turntable.mp4',
|
||||
},
|
||||
original: {
|
||||
key: 'files/robot.glb',
|
||||
},
|
||||
metadata: {
|
||||
originalWidth: 1080,
|
||||
originalHeight: 1080,
|
||||
},
|
||||
},
|
||||
preview: {
|
||||
thumbnailUrl: 'https://example.com/robot-poster.webp',
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
describe('ModelViewer', () => {
|
||||
beforeEach(() => {
|
||||
global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver
|
||||
vi.spyOn(HTMLMediaElement.prototype, 'play').mockImplementation(() => Promise.resolve())
|
||||
vi.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('renders model viewer container, surface, video, and control bar', () => {
|
||||
const { getByTestId, getByText } = render(<ModelViewer file={mockAsset} />)
|
||||
|
||||
expect(getByTestId('model-viewer-container')).toBeDefined()
|
||||
expect(getByTestId('model-viewer-surface')).toBeDefined()
|
||||
expect(getByTestId('drawing-canvas')).toBeDefined()
|
||||
// Control bar shows 0° / 360° initially
|
||||
expect(getByText(/0°\s*\/\s*360°/)).toBeDefined()
|
||||
})
|
||||
|
||||
it('toggles play/pause via spacebar hotkey', () => {
|
||||
const onPlay = vi.fn()
|
||||
const onPause = vi.fn()
|
||||
const { container } = render(<ModelViewer file={mockAsset} onPlay={onPlay} onPause={onPause} />)
|
||||
|
||||
const video = container.querySelector('video')
|
||||
expect(video).toBeDefined()
|
||||
|
||||
// Space key triggers togglePlay
|
||||
fireEvent.keyDown(window, { key: ' ' })
|
||||
expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
|
||||
|
||||
// Simulate video playing event
|
||||
if (video) {
|
||||
fireEvent.play(video)
|
||||
expect(onPlay).toHaveBeenCalled()
|
||||
}
|
||||
})
|
||||
|
||||
it('seeks frames via arrow hotkeys', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
|
||||
|
||||
// Press ArrowRight -> advance 1 frame (15 deg = 1/6 sec = ~0.1667)
|
||||
fireEvent.keyDown(window, { key: 'ArrowRight' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
|
||||
|
||||
// Press ArrowLeft -> back 1 frame (frame 0 = 0 sec)
|
||||
fireEvent.keyDown(window, { key: 'ArrowLeft' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('handles pointer dragging to rotate 3D asset', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { getByTestId } = render(<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />)
|
||||
|
||||
const surface = getByTestId('model-viewer-surface')
|
||||
// Mock setPointerCapture / releasePointerCapture
|
||||
surface.setPointerCapture = vi.fn()
|
||||
surface.releasePointerCapture = vi.fn()
|
||||
|
||||
// Start drag at x = 100
|
||||
fireEvent.pointerDown(surface, { clientX: 100, button: 0, pointerId: 1 })
|
||||
expect(surface.setPointerCapture).toHaveBeenCalledWith(1)
|
||||
|
||||
// Move right by 24px (+2 frames = +30 deg)
|
||||
fireEvent.pointerMove(surface, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
|
||||
|
||||
// Release drag
|
||||
fireEvent.pointerUp(surface, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(surface.releasePointerCapture).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('exposes imperative media controller via ref', () => {
|
||||
const ref = createRef<MediaController>()
|
||||
render(<ModelViewer ref={ref} file={mockAsset} />)
|
||||
|
||||
expect(ref.current).toBeDefined()
|
||||
expect(ref.current?.getDuration?.()).toBe(4)
|
||||
expect(typeof ref.current?.getCurrentTime?.()).toBe('number')
|
||||
|
||||
ref.current?.play()
|
||||
expect(HTMLMediaElement.prototype.play).toHaveBeenCalled()
|
||||
|
||||
ref.current?.pause()
|
||||
expect(HTMLMediaElement.prototype.pause).toHaveBeenCalled()
|
||||
|
||||
ref.current?.seekTo(1) // 1 second -> frame 6 -> 1 second
|
||||
expect(ref.current?.getCurrentTime?.()).toBeDefined()
|
||||
})
|
||||
|
||||
it('resets rotation to 0° when reset button is clicked', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { getByRole } = render(
|
||||
<ModelViewer file={mockAsset} startTime={1} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
|
||||
// Reset rotation button has aria-label 'Reset rotation to 0°'
|
||||
const resetBtn = getByRole('button', { name: /Reset rotation/i })
|
||||
fireEvent.click(resetBtn)
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,391 @@
|
||||
import React, { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
|
||||
import { AlertCircle, Loader2 } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
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 { ModelControlBar } from './model-control-bar'
|
||||
import { secondToDegree } from './index'
|
||||
|
||||
const TOTAL_FRAMES = 24
|
||||
const FPS = 6
|
||||
const FRAME_DURATION = 1 / FPS
|
||||
|
||||
export const ModelViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
(
|
||||
{
|
||||
file: data,
|
||||
onPlay,
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
children,
|
||||
allowDownload = true,
|
||||
autoPlay = false,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null)
|
||||
const containerRef = useRef<HTMLDivElement | null>(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<string | null>(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)
|
||||
|
||||
// Drag-to-rotate state
|
||||
const [isDraggingRotation, setIsDraggingRotation] = useState(false)
|
||||
const dragStartRef = useRef<{ clientX: number; frame: number }>({ clientX: 0, frame: 0 })
|
||||
|
||||
const videoSrc = data.media?.videoPreview?.url || data.media?.videoTranscodes?.[0]?.url || ''
|
||||
|
||||
const posterUrl = data.preview?.thumbnailUrl || undefined
|
||||
const downloadUrl = data.media?.original?.key ? videoSrc : undefined
|
||||
|
||||
// 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
|
||||
|
||||
// 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) {
|
||||
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
|
||||
setZoom(scale)
|
||||
setPan(
|
||||
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
|
||||
)
|
||||
}
|
||||
}, [containerSize, mediaWidth, mediaHeight, hasManuallyZoomed])
|
||||
|
||||
// Current angle
|
||||
const currentDegree = secondToDegree(currentTime)
|
||||
|
||||
// Seek helper
|
||||
const seekToFrame = useCallback(
|
||||
(frameIndex: number) => {
|
||||
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
|
||||
const targetSec = normalizedFrame * FRAME_DURATION
|
||||
if (videoRef.current) {
|
||||
videoRef.current.currentTime = targetSec
|
||||
}
|
||||
setCurrentTime(targetSec)
|
||||
onTimeUpdate?.(targetSec)
|
||||
},
|
||||
[onTimeUpdate],
|
||||
)
|
||||
|
||||
const seekToDegree = useCallback(
|
||||
(degree: number) => {
|
||||
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(Math.floor(second * FPS))
|
||||
},
|
||||
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()
|
||||
const currentFrame = Math.floor(currentTime * FPS)
|
||||
seekToFrame(currentFrame - 1)
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
const currentFrame = Math.floor(currentTime * FPS)
|
||||
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<HTMLDivElement>) => {
|
||||
if (isDrawingMode || e.button !== 0) return
|
||||
const target = e.currentTarget
|
||||
target.setPointerCapture(e.pointerId)
|
||||
videoRef.current?.pause()
|
||||
|
||||
const currentFrame = Math.floor(currentTime * FPS)
|
||||
dragStartRef.current = {
|
||||
clientX: e.clientX,
|
||||
frame: currentFrame,
|
||||
}
|
||||
setIsDraggingRotation(true)
|
||||
}
|
||||
|
||||
const handleViewerPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDraggingRotation) return
|
||||
const deltaX = e.clientX - dragStartRef.current.clientX
|
||||
// 12px drag movement corresponds to 1 frame (15°)
|
||||
const deltaFrames = Math.round(deltaX / 12)
|
||||
seekToFrame(dragStartRef.current.frame + deltaFrames)
|
||||
}
|
||||
|
||||
const handleViewerPointerUp = (e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDraggingRotation) return
|
||||
setIsDraggingRotation(false)
|
||||
try {
|
||||
e.currentTarget.releasePointerCapture(e.pointerId)
|
||||
} catch {
|
||||
// pointer may already be released
|
||||
}
|
||||
}
|
||||
|
||||
// Fullscreen toggle
|
||||
const toggleFullScreen = () => {
|
||||
if (!document.fullscreenElement) {
|
||||
containerRef.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) {
|
||||
const scale = fitScale(containerSize.width, containerSize.height, mediaWidth, mediaHeight)
|
||||
setZoom(scale)
|
||||
setPan(
|
||||
centeredPan(containerSize.width, containerSize.height, mediaWidth, mediaHeight, scale),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-testid="model-viewer-container"
|
||||
className="relative w-full h-full bg-background overflow-hidden select-none flex items-center justify-center"
|
||||
>
|
||||
{/* Interactive Drag Rotation Surface */}
|
||||
<div
|
||||
data-testid="model-viewer-surface"
|
||||
onPointerDown={handleViewerPointerDown}
|
||||
onPointerMove={handleViewerPointerMove}
|
||||
onPointerUp={handleViewerPointerUp}
|
||||
onPointerCancel={handleViewerPointerUp}
|
||||
className={cn(
|
||||
'absolute inset-0 z-0 touch-none',
|
||||
isDrawingMode
|
||||
? 'cursor-crosshair'
|
||||
: isDraggingRotation
|
||||
? 'cursor-grabbing'
|
||||
: 'cursor-grab',
|
||||
)}
|
||||
>
|
||||
{/* Centered Scaled Media Wrapper */}
|
||||
<div
|
||||
className="absolute pointer-events-none"
|
||||
style={{
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: mediaWidth,
|
||||
height: mediaHeight,
|
||||
transform: `translate(${pan.x}px, ${pan.y}px) scale(${zoom})`,
|
||||
transformOrigin: '0 0',
|
||||
}}
|
||||
>
|
||||
{videoSrc && (
|
||||
<video
|
||||
ref={videoRef}
|
||||
src={videoSrc}
|
||||
poster={posterUrl}
|
||||
playsInline
|
||||
loop
|
||||
muted
|
||||
autoPlay={autoPlay}
|
||||
preload="auto"
|
||||
onLoadedData={() => {
|
||||
setIsLoading(false)
|
||||
if (startTime && startTime > 0) {
|
||||
seekToFrame(Math.floor(startTime * FPS))
|
||||
}
|
||||
}}
|
||||
onPlay={() => {
|
||||
setIsPlaying(true)
|
||||
onPlay?.()
|
||||
}}
|
||||
onPause={() => {
|
||||
setIsPlaying(false)
|
||||
onPause?.()
|
||||
}}
|
||||
onTimeUpdate={() => {
|
||||
if (videoRef.current && !isDraggingRotation) {
|
||||
setCurrentTime(videoRef.current.currentTime)
|
||||
onTimeUpdate?.(videoRef.current.currentTime)
|
||||
}
|
||||
}}
|
||||
onError={() => {
|
||||
setIsLoading(false)
|
||||
setError('Failed to load turntable video')
|
||||
}}
|
||||
className="w-full h-full block object-contain pointer-events-none"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Drawing Canvas Overlay */}
|
||||
{containerSize.width > 0 && containerSize.height > 0 && (
|
||||
<DrawingCanvas
|
||||
width={containerSize.width}
|
||||
height={containerSize.height}
|
||||
mediaDimensions={{
|
||||
width: mediaWidth,
|
||||
height: mediaHeight,
|
||||
}}
|
||||
annotations={displayAnnotations}
|
||||
scale={zoom}
|
||||
offset={pan}
|
||||
className="absolute inset-0 pointer-events-none"
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Loading Spinner */}
|
||||
{isLoading && !error && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
|
||||
<div className="w-14 h-14 bg-background/80 backdrop-blur-md rounded-full flex items-center justify-center border border-border shadow-lg">
|
||||
<Loader2 className="w-7 h-7 text-primary animate-spin" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="absolute inset-0 flex flex-col items-center justify-center gap-2 text-destructive z-10 bg-background/90 p-4 text-center">
|
||||
<AlertCircle className="w-10 h-10" />
|
||||
<p className="text-sm font-medium">{error}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Floating Bottom Control Bar */}
|
||||
<ModelControlBar
|
||||
isPlaying={isPlaying}
|
||||
currentDegree={currentDegree}
|
||||
zoom={zoom}
|
||||
isFullScreen={isFullScreen}
|
||||
allowDownload={allowDownload}
|
||||
downloadUrl={downloadUrl}
|
||||
fileName={data.name}
|
||||
togglePlay={togglePlay}
|
||||
onSeekDegree={seekToDegree}
|
||||
onResetRotation={() => seekToDegree(0)}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
/>
|
||||
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ModelViewer.displayName = 'ModelViewer'
|
||||
export default ModelViewer
|
||||
@@ -0,0 +1,61 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { RulerSlider } from './ruler-slider'
|
||||
|
||||
describe('RulerSlider', () => {
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
it('renders slider and shows current degree text', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, getAllByText } = render(
|
||||
<RulerSlider currentDegree={90} onChange={onChange} />,
|
||||
)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
expect(slider).toBeDefined()
|
||||
expect(slider.getAttribute('aria-valuenow')).toBe('90')
|
||||
expect(getAllByText('90°').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('handles keyboard navigation with 15 degree snapping', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole } = render(<RulerSlider currentDegree={45} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
fireEvent.keyDown(slider, { key: 'ArrowRight' })
|
||||
expect(onChange).toHaveBeenCalledWith(60)
|
||||
|
||||
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
|
||||
expect(onChange).toHaveBeenCalledWith(30)
|
||||
|
||||
fireEvent.keyDown(slider, { key: 'Home' })
|
||||
expect(onChange).toHaveBeenCalledWith(0)
|
||||
|
||||
fireEvent.keyDown(slider, { key: 'End' })
|
||||
expect(onChange).toHaveBeenCalledWith(360)
|
||||
})
|
||||
|
||||
it('snaps pointer events to nearest 15 degrees', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
// Mock getBoundingClientRect
|
||||
slider.getBoundingClientRect = () =>
|
||||
({
|
||||
left: 0,
|
||||
width: 360,
|
||||
top: 0,
|
||||
height: 40,
|
||||
right: 360,
|
||||
bottom: 40,
|
||||
}) as DOMRect
|
||||
|
||||
// Pointer down at x=50 -> ratio = 50/360 = 50 deg -> round(50/15)*15 = 45 deg
|
||||
fireEvent.pointerDown(slider, { clientX: 50, button: 0, pointerId: 1 })
|
||||
expect(onChange).toHaveBeenCalledWith(45)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,163 @@
|
||||
import React, { useCallback, useRef, useState } from 'react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
|
||||
interface RulerSliderProps {
|
||||
currentDegree: number // 0 to 360
|
||||
onChange: (degree: number) => void
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const TICKS = Array.from({ length: 25 }, (_, i) => i * 15)
|
||||
const MAJOR_TICKS = new Set([0, 90, 180, 270, 360])
|
||||
|
||||
export const RulerSlider: React.FC<RulerSliderProps> = ({
|
||||
currentDegree,
|
||||
onChange,
|
||||
className,
|
||||
disabled = false,
|
||||
}) => {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (disabled || e.button !== 0) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
const target = containerRef.current
|
||||
if (!target) return
|
||||
target.setPointerCapture(e.pointerId)
|
||||
setIsDragging(true)
|
||||
|
||||
const rect = target.getBoundingClientRect()
|
||||
const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
|
||||
const snapped = Math.min(360, Math.max(0, Math.round((ratio * 360) / 15) * 15))
|
||||
onChange(snapped)
|
||||
},
|
||||
[disabled, onChange],
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging || disabled) return
|
||||
const target = containerRef.current
|
||||
if (!target) return
|
||||
|
||||
const rect = target.getBoundingClientRect()
|
||||
const ratio = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
|
||||
const snapped = Math.min(360, Math.max(0, Math.round((ratio * 360) / 15) * 15))
|
||||
onChange(snapped)
|
||||
},
|
||||
[isDragging, disabled, onChange],
|
||||
)
|
||||
|
||||
const handlePointerUp = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging) return
|
||||
setIsDragging(false)
|
||||
try {
|
||||
containerRef.current?.releasePointerCapture(e.pointerId)
|
||||
} catch {
|
||||
// pointer may have already been released
|
||||
}
|
||||
},
|
||||
[isDragging],
|
||||
)
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (disabled) return
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
onChange(Math.max(0, currentDegree - 15))
|
||||
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
onChange(Math.min(360, currentDegree + 15))
|
||||
} else if (e.key === 'Home') {
|
||||
e.preventDefault()
|
||||
onChange(0)
|
||||
} else if (e.key === 'End') {
|
||||
e.preventDefault()
|
||||
onChange(360)
|
||||
}
|
||||
},
|
||||
[disabled, currentDegree, onChange],
|
||||
)
|
||||
|
||||
const clampedDegree = Math.min(360, Math.max(0, currentDegree))
|
||||
const percent = (clampedDegree / 360) * 100
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={containerRef}
|
||||
role="slider"
|
||||
aria-label="Turntable angle"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={360}
|
||||
aria-valuenow={clampedDegree}
|
||||
aria-valuetext={`${clampedDegree}°`}
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerUp}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={cn(
|
||||
'relative select-none cursor-pointer flex flex-col justify-end h-11 px-2.5 touch-none group',
|
||||
disabled && 'opacity-50 cursor-not-allowed',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Major tick labels */}
|
||||
<div className="relative w-full h-3 mb-1 pointer-events-none">
|
||||
{Array.from(MAJOR_TICKS).map((deg) => (
|
||||
<span
|
||||
key={`label-${deg}`}
|
||||
className="absolute text-[10px] leading-none font-mono text-muted-foreground -translate-x-1/2"
|
||||
style={{ left: `${(deg / 360) * 100}%` }}
|
||||
>
|
||||
{deg}°
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Track & Ticks */}
|
||||
<div className="relative w-full h-4 flex items-end">
|
||||
{/* Baseline bar */}
|
||||
<div className="absolute inset-x-0 bottom-0 h-0.5 bg-muted-foreground/30 rounded-full" />
|
||||
|
||||
{/* Ticks */}
|
||||
{TICKS.map((deg) => {
|
||||
const isMajor = MAJOR_TICKS.has(deg)
|
||||
return (
|
||||
<div
|
||||
key={`tick-${deg}`}
|
||||
className={cn(
|
||||
'absolute bottom-0 -translate-x-1/2 transition-colors',
|
||||
isMajor
|
||||
? 'w-0.5 h-3.5 bg-foreground/70'
|
||||
: 'w-px h-2 bg-muted-foreground/40 group-hover:bg-muted-foreground/70',
|
||||
)}
|
||||
style={{ left: `${(deg / 360) * 100}%` }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Current Position Thumb */}
|
||||
<div
|
||||
className="absolute bottom-0 -translate-x-1/2 flex flex-col items-center pointer-events-none transition-[left] duration-75 ease-out"
|
||||
style={{ left: `${percent}%` }}
|
||||
>
|
||||
{/* Degree Tooltip on drag/hover */}
|
||||
<div className="text-[10px] font-mono font-semibold px-1 py-0.5 rounded bg-primary text-primary-foreground mb-1 shadow-xs whitespace-nowrap">
|
||||
{clampedDegree}°
|
||||
</div>
|
||||
{/* Thumb needle */}
|
||||
<div className="w-1.5 h-5 bg-primary rounded-full ring-2 ring-background shadow-md" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user