mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 20:34:28 +00:00
feat(transcode): add 3D asset support and turntable viewer (#454)
* feat(transcode): add 3D asset support and turntable viewer * perf(turntable): stream file via Bun.file and increase upload timeout * feat(turntable): increase upload timeout to 15m to support 5GB uploads * fix(webui): align 3D model viewer layout and full-width control bar with video viewer * feat(webui): unify 3D viewer bottom bar and redesign cyclic ruler slider - Place RulerSlider in single row with playback and zoom controls, centered with max 320px width - Flank RulerSlider with minus and plus buttons to step angle by 15° - Redesign RulerSlider with fixed center indicator and moving cyclic track with continuous 360° wrapping - Render major ticks longer at 60° intervals without numeric text labels on track - Display floating degree tooltip above center indicator only during dragging * fix(webui): prevent RulerSlider from collapsing to 0px width in control bar - Use flex layout with flex-1 on left and right clusters to preserve center cluster width - Enforce min-w-[140px] and w-full on RulerSlider - Fix tooltip positioning and remove outer overflow-hidden * feat(webui): snap RulerSlider track directly to discrete 15° ticks during drag * fix(webui): prevent ruler snap-back caused by floating point second truncation - Use Math.round instead of Math.floor in secondToDegree to avoid 0.999996 dropping to previous frame - Ensure final dragDegree is committed on pointer up * fix(webui): fix arrow key frame rounding and duplicate event bubbling - Use Math.round instead of Math.floor for keyboard arrow frame navigation in ModelViewer - Add e.stopPropagation() to RulerSlider keyboard events to prevent duplicate bubbling to window listener * feat(webui): redesign RulerSlider with encapsulated step buttons and capsule pill track * feat(webui): make RulerSlider responsive on mobile and remove bottom bar reset button * fix(webui): load 3d video directly without poster and invert drag rotation to counterclockwise * fix(webui): fix 3d asset viewer frame seeking and drag jitter * feat(transcode): show 3D asset poster preview immediately after render start * fix(viewer): synchronize 3D turntable playback via frame callback to prevent skipped degrees * fix(viewer): handle touchpad zoom gestures and prevent page zoom in 3D viewer * fix(viewer): eliminate 3D model rotation jitter at 345 degrees * fix(share): watermark 3D asset turntable video on share links * fix(share): preserve video transcode resolution on watermarked share links * fix(viewer): download original 3D model file instead of rendered turntable MP4
This commit is contained in:
@@ -263,4 +263,45 @@ describe('BreadcrumbNav component', () => {
|
||||
expect(items.some((i) => i.textContent?.includes('1080p'))).toBe(true)
|
||||
expect(items.some((i) => i.textContent?.includes('1920p'))).toBe(false)
|
||||
})
|
||||
|
||||
it('correctly labels 1080p square / 3D turntable transcode in download menu', () => {
|
||||
render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<BreadcrumbNav
|
||||
{...baseProps}
|
||||
fileId="file-3d"
|
||||
currentAsset={{
|
||||
id: 'file-3d',
|
||||
name: 'model.glb',
|
||||
type: 'file',
|
||||
version: 1,
|
||||
proxyType: '3d',
|
||||
}}
|
||||
allowDownload={true}
|
||||
downloadInfo={{
|
||||
originalKey: 'model.glb',
|
||||
videoTranscodes: [
|
||||
{
|
||||
key: 'turntable-1080p.mp4',
|
||||
width: 1080,
|
||||
height: 1080,
|
||||
resolution: '1080p',
|
||||
hdr: false,
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</QueryClientProvider>,
|
||||
)
|
||||
|
||||
const triggerButton = screen.getByRole('button', { name: 'model.glb' })
|
||||
fireEvent.pointerDown(triggerButton, { button: 0, ctrlKey: false })
|
||||
|
||||
const downloadSubTrigger = screen.getByText('Download')
|
||||
fireEvent.click(downloadSubTrigger)
|
||||
|
||||
const items = screen.getAllByRole('menuitem')
|
||||
expect(items.some((i) => i.textContent?.includes('1080p'))).toBe(true)
|
||||
expect(items.some((i) => i.textContent?.includes('480p'))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -60,7 +60,7 @@ interface BreadcrumbNavProps {
|
||||
name?: string
|
||||
type: 'file' | 'folder'
|
||||
version?: number
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
}
|
||||
isRootFolder: boolean
|
||||
customTerminalBreadcrumb?: string
|
||||
|
||||
@@ -4,10 +4,10 @@ import { formatTime } from '../viewers/video/utils'
|
||||
|
||||
type FilePreviewItem = {
|
||||
type?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
preview?: {
|
||||
mediaType?: string | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | null
|
||||
proxyType?: 'image' | 'video' | 'audio' | 'pdf' | '3d' | null
|
||||
spriteUrl?: string
|
||||
thumbnailUrl?: string
|
||||
originalWidth?: number
|
||||
@@ -27,6 +27,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
|
||||
const isVideo = proxyType === 'video'
|
||||
const isAudio = proxyType === 'audio'
|
||||
const isPdf = proxyType === 'pdf'
|
||||
const is3D = proxyType === '3d'
|
||||
const hasDuration = isVideo || isAudio
|
||||
const duration = item.preview?.duration
|
||||
const pageCount = item.preview?.pageCount
|
||||
@@ -43,7 +44,7 @@ export const FilePreview = ({ item, showDuration = false }: FilePreviewProps) =>
|
||||
) : null
|
||||
|
||||
const isMediaWithSprite =
|
||||
(isVideo || isPdf) &&
|
||||
(isVideo || isPdf || is3D) &&
|
||||
item.preview?.spriteUrl &&
|
||||
item.preview.thumbnailUrl &&
|
||||
item.preview.originalWidth &&
|
||||
|
||||
@@ -136,14 +136,14 @@ export const NotificationCard = ({ notification }: NotificationCardProps) => {
|
||||
|
||||
const hasPreview = asset?.preview && (asset.proxyType === 'image' || asset.proxyType === 'video')
|
||||
|
||||
const handleClick = () => {
|
||||
const handleClick = () => {
|
||||
if (kanbanTask?.id && team?.id) {
|
||||
navigate({
|
||||
to: '/teams/$teamId/kanban',
|
||||
params: { teamId: team.id },
|
||||
search: { taskId: kanbanTask.id },
|
||||
})
|
||||
}else if(project?.id && asset?.id){
|
||||
} else if (project?.id && asset?.id) {
|
||||
//TODO: Perhaps it should be marked as read too when redirecting to it.
|
||||
navigate({
|
||||
to: '/projects/$projectId/files/$fileId',
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { TurntableSettingsCard } from './TurntableSettingsCard'
|
||||
import type { TurntableSettingsResponse } from '@shumai/dtos'
|
||||
|
||||
const mockGetSettings = vi.fn()
|
||||
const mockPutSettings = vi.fn()
|
||||
const mockTestSettings = vi.fn()
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
teams: {
|
||||
':teamId': {
|
||||
'turntable-settings': {
|
||||
$get: () => mockGetSettings(),
|
||||
$put: (args: unknown) => mockPutSettings(args),
|
||||
test: {
|
||||
$post: (args: unknown) => mockTestSettings(args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: {
|
||||
success: vi.fn(),
|
||||
error: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/ui/paraglide/messages.js', () => ({
|
||||
m: {
|
||||
turntable_settings: () => 'Turntable Renderer Settings',
|
||||
turntable_settings_description: () => 'Configure external Blender turntable renderer',
|
||||
turntable_env_configured: () => 'Configured via Environment',
|
||||
turntable_server_url: () => 'Server URL',
|
||||
turntable_server_url_placeholder: () => 'http://localhost:3000',
|
||||
turntable_username: () => 'Username',
|
||||
turntable_password: () => 'Password',
|
||||
turntable_password_placeholder: () => 'Saved password',
|
||||
turntable_test_connection: () => 'Test Connection',
|
||||
turntable_testing: () => 'Testing...',
|
||||
turntable_connection_success: () => 'Connection successful',
|
||||
turntable_connection_failed: () => 'Connection failed',
|
||||
save: () => 'Save',
|
||||
settings_updated: () => 'Settings updated',
|
||||
failed_update_settings: () => 'Failed to update settings',
|
||||
},
|
||||
}))
|
||||
|
||||
const createWrapper = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: { retry: false },
|
||||
mutations: { retry: false },
|
||||
},
|
||||
})
|
||||
return ({ children }: { children: React.ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
)
|
||||
}
|
||||
|
||||
describe('TurntableSettingsCard', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
})
|
||||
|
||||
it('renders loaded settings with URL and username', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: 'http://turntable.local:3000',
|
||||
username: 'render-user',
|
||||
hasPassword: true,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue('http://turntable.local:3000')).toBeDefined()
|
||||
expect(screen.getByDisplayValue('render-user')).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('disables inputs and displays badge when configured via environment', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: true,
|
||||
url: 'http://env-turntable:3000',
|
||||
username: 'env-user',
|
||||
hasPassword: true,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Configured via Environment')).toBeDefined()
|
||||
const urlInput = screen.getByDisplayValue('http://env-turntable:3000') as HTMLInputElement
|
||||
expect(urlInput.disabled).toBe(true)
|
||||
const saveBtn = screen.getByRole('button', { name: 'Save' }) as HTMLButtonElement
|
||||
expect(saveBtn.disabled).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('saves updated settings', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: '',
|
||||
username: '',
|
||||
hasPassword: false,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
mockPutSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
...settings,
|
||||
url: 'http://new-turntable:3000',
|
||||
username: 'alice',
|
||||
}),
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByLabelText('Server URL')).toBeDefined()
|
||||
})
|
||||
|
||||
const urlInput = screen.getByLabelText('Server URL')
|
||||
fireEvent.change(urlInput, { target: { value: 'http://new-turntable:3000' } })
|
||||
|
||||
const usernameInput = screen.getByLabelText('Username')
|
||||
fireEvent.change(usernameInput, { target: { value: 'alice' } })
|
||||
|
||||
const saveBtn = screen.getByRole('button', { name: 'Save' })
|
||||
fireEvent.click(saveBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockPutSettings).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
param: { teamId: 'team-123' },
|
||||
json: expect.objectContaining({
|
||||
url: 'http://new-turntable:3000',
|
||||
username: 'alice',
|
||||
}),
|
||||
}),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('tests connection successfully and displays version info', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: 'http://turntable:3000',
|
||||
username: 'user',
|
||||
hasPassword: false,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
mockTestSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
ok: true,
|
||||
version: '1.0.0',
|
||||
blender: '5.2.0',
|
||||
}),
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue('http://turntable:3000')).toBeDefined()
|
||||
})
|
||||
|
||||
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
|
||||
fireEvent.click(testBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockTestSettings).toHaveBeenCalled()
|
||||
expect(screen.getByText(/Connection successful \(v1\.0\.0, Blender 5\.2\.0\)/)).toBeDefined()
|
||||
})
|
||||
})
|
||||
|
||||
it('tests connection and displays error when unreachable', async () => {
|
||||
const settings: TurntableSettingsResponse = {
|
||||
isEnvConfigured: false,
|
||||
url: 'http://invalid-url:3000',
|
||||
username: '',
|
||||
hasPassword: false,
|
||||
}
|
||||
|
||||
mockGetSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => settings,
|
||||
})
|
||||
|
||||
mockTestSettings.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
ok: false,
|
||||
error: 'ECONNREFUSED',
|
||||
}),
|
||||
})
|
||||
|
||||
render(<TurntableSettingsCard teamId="team-123" />, { wrapper: createWrapper() })
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByDisplayValue('http://invalid-url:3000')).toBeDefined()
|
||||
})
|
||||
|
||||
const testBtn = screen.getByRole('button', { name: 'Test Connection' })
|
||||
fireEvent.click(testBtn)
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/Connection failed: ECONNREFUSED/)).toBeDefined()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,243 @@
|
||||
import React, { useState, useEffect } from 'react'
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { client } from '@/ui/api/client'
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
CardFooter,
|
||||
} from '@/ui/components/ui/card'
|
||||
import { Input } from '@/ui/components/ui/input'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import { Badge } from '@/ui/components/ui/badge'
|
||||
import { Loader2, CheckCircle2, XCircle, Info } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface TurntableSettingsCardProps {
|
||||
teamId: string
|
||||
}
|
||||
|
||||
export const TurntableSettingsCard: React.FC<TurntableSettingsCardProps> = ({ teamId }) => {
|
||||
const queryClient = useQueryClient()
|
||||
|
||||
const [url, setUrl] = useState('')
|
||||
const [username, setUsername] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [testResult, setTestResult] = useState<{
|
||||
ok: boolean
|
||||
version?: string
|
||||
blender?: string
|
||||
error?: string
|
||||
} | null>(null)
|
||||
const [isTesting, setIsTesting] = useState(false)
|
||||
|
||||
const { data: turntableSettings, isLoading } = useQuery({
|
||||
queryKey: ['teams', teamId, 'turntable-settings'],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId']['turntable-settings'].$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error('Failed to load turntable settings')
|
||||
return await res.json()
|
||||
},
|
||||
enabled: !!teamId,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (turntableSettings) {
|
||||
setUrl(turntableSettings.url || '')
|
||||
setUsername(turntableSettings.username || '')
|
||||
setPassword('')
|
||||
setTestResult(null)
|
||||
}
|
||||
}, [turntableSettings])
|
||||
|
||||
const { mutateAsync: saveSettings, isPending: isSaving } = useMutation({
|
||||
mutationFn: async () => {
|
||||
const res = await client.api.teams[':teamId']['turntable-settings'].$put({
|
||||
param: { teamId },
|
||||
json: {
|
||||
url: url || undefined,
|
||||
username: username || undefined,
|
||||
password: password || undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
throw new Error(
|
||||
(err as { message?: string }).message || 'Failed to update turntable settings',
|
||||
)
|
||||
}
|
||||
return await res.json()
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'turntable-settings'],
|
||||
})
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['teams', teamId, 'settings'],
|
||||
})
|
||||
toast.success(m.settings_updated())
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error(err.message || m.failed_update_settings())
|
||||
},
|
||||
})
|
||||
|
||||
const handleTestConnection = async () => {
|
||||
setIsTesting(true)
|
||||
setTestResult(null)
|
||||
try {
|
||||
const res = await client.api.teams[':teamId']['turntable-settings'].test.$post({
|
||||
param: { teamId },
|
||||
json: {
|
||||
url: url || undefined,
|
||||
username: username || undefined,
|
||||
password: password || undefined,
|
||||
},
|
||||
})
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}))
|
||||
const errorMsg = (err as { message?: string }).message || 'Request failed'
|
||||
setTestResult({ ok: false, error: errorMsg })
|
||||
toast.error(m.turntable_connection_failed())
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
setTestResult(data)
|
||||
if (data.ok) {
|
||||
toast.success(m.turntable_connection_success())
|
||||
} else {
|
||||
toast.error(data.error || m.turntable_connection_failed())
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err)
|
||||
setTestResult({ ok: false, error: msg })
|
||||
toast.error(m.turntable_connection_failed())
|
||||
} finally {
|
||||
setIsTesting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const isEnvConfigured = Boolean(turntableSettings?.isEnvConfigured)
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle>{m.turntable_settings()}</CardTitle>
|
||||
{isEnvConfigured && (
|
||||
<Badge variant="secondary" className="gap-1">
|
||||
<Info className="w-3 h-3" />
|
||||
{m.turntable_env_configured()}
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardDescription>{m.turntable_settings_description()}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-6">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="turntable-url" className="text-sm font-medium">
|
||||
{m.turntable_server_url()}
|
||||
</label>
|
||||
<Input
|
||||
id="turntable-url"
|
||||
value={url}
|
||||
onChange={(e) => setUrl(e.target.value)}
|
||||
placeholder={m.turntable_server_url_placeholder()}
|
||||
disabled={isEnvConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="turntable-username" className="text-sm font-medium">
|
||||
{m.turntable_username()}
|
||||
</label>
|
||||
<Input
|
||||
id="turntable-username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
placeholder="admin"
|
||||
disabled={isEnvConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<label htmlFor="turntable-password" className="text-sm font-medium">
|
||||
{m.turntable_password()}
|
||||
</label>
|
||||
<Input
|
||||
id="turntable-password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder={
|
||||
turntableSettings?.hasPassword ? m.turntable_password_placeholder() : '••••••••'
|
||||
}
|
||||
disabled={isEnvConfigured || isSaving}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{testResult && (
|
||||
<div
|
||||
className={`flex items-center gap-2 p-3 rounded-lg border text-sm ${
|
||||
testResult.ok
|
||||
? 'border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400'
|
||||
: 'border-destructive/30 bg-destructive/10 text-destructive'
|
||||
}`}
|
||||
>
|
||||
{testResult.ok ? (
|
||||
<>
|
||||
<CheckCircle2 className="w-4 h-4 shrink-0" />
|
||||
<span>
|
||||
{m.turntable_connection_success()} (v{testResult.version || 'unknown'}
|
||||
{testResult.blender ? `, Blender ${testResult.blender}` : ''})
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<XCircle className="w-4 h-4 shrink-0" />
|
||||
<span>
|
||||
{m.turntable_connection_failed()}: {testResult.error}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
<CardFooter className="flex justify-between border-t border-border pt-4">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={handleTestConnection}
|
||||
disabled={isLoading || isTesting || !url.trim()}
|
||||
>
|
||||
{isTesting && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{isTesting ? m.turntable_testing() : m.turntable_test_connection()}
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
onClick={() => saveSettings()}
|
||||
disabled={isEnvConfigured || isSaving || isLoading}
|
||||
>
|
||||
{isSaving && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
|
||||
{m.save()}
|
||||
</Button>
|
||||
</CardFooter>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import ModelViewer from './model-viewer'
|
||||
|
||||
import { secondToDegree } from './utils'
|
||||
export { secondToDegree } from './utils'
|
||||
|
||||
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,131 @@
|
||||
import React from 'react'
|
||||
import { Play, Pause, Maximize, Minimize, Minus, Plus, Download } from 'lucide-react'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { RulerSlider } from './ruler-slider'
|
||||
|
||||
export interface ModelControlBarProps {
|
||||
isPlaying: boolean
|
||||
currentDegree: number
|
||||
zoom: number
|
||||
isFullScreen: boolean
|
||||
allowDownload?: boolean
|
||||
onDownload?: () => void
|
||||
togglePlay: () => void
|
||||
onSeekDegree: (degree: number) => void
|
||||
onZoomChange: (zoom: number) => void
|
||||
onZoomReset: () => void
|
||||
toggleFullScreen: () => void
|
||||
}
|
||||
|
||||
export const ModelControlBar: React.FC<ModelControlBarProps> = ({
|
||||
isPlaying,
|
||||
currentDegree,
|
||||
zoom,
|
||||
isFullScreen,
|
||||
allowDownload = true,
|
||||
onDownload,
|
||||
togglePlay,
|
||||
onSeekDegree,
|
||||
onZoomChange,
|
||||
onZoomReset,
|
||||
toggleFullScreen,
|
||||
}) => {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'transition-all duration-300 ease-in-out z-20 text-foreground',
|
||||
isFullScreen
|
||||
? 'absolute bottom-0 left-0 right-0 px-2 py-2 sm:px-4 sm:py-2.5 bg-card/90 backdrop-blur-md border-t border-border'
|
||||
: 'relative w-full bg-card border-t border-border px-2 py-2 sm:px-4 sm:py-2.5 z-10 transition-colors duration-200',
|
||||
)}
|
||||
>
|
||||
{/* Unified Single Row Controls */}
|
||||
<div className="flex items-center justify-between text-foreground gap-1.5 sm:gap-3 md:gap-4">
|
||||
{/* Left Side: Play/Pause, Degree Readout */}
|
||||
<div className="flex items-center gap-1.5 sm:gap-3 justify-start min-w-0 flex-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={togglePlay}
|
||||
aria-label={isPlaying ? 'Pause' : 'Play'}
|
||||
className="hover:text-primary transition-colors shrink-0 p-0.5 sm:p-1"
|
||||
data-testid="play-toggle"
|
||||
data-playing={isPlaying}
|
||||
>
|
||||
{isPlaying ? (
|
||||
<Pause className="w-4 h-4 sm:w-5 sm:h-5 fill-current" />
|
||||
) : (
|
||||
<Play className="w-4 h-4 sm:w-5 sm:h-5 fill-current" />
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div
|
||||
className="flex items-center text-xs sm:text-sm font-medium tabular-nums select-none shrink-0"
|
||||
data-testid="degree-readout"
|
||||
>
|
||||
<span className="text-muted-foreground font-mono">{currentDegree}° / 360°</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Center: RulerSlider with encapsulated minus & plus buttons */}
|
||||
<div className="flex items-center w-full max-w-[130px] sm:max-w-[220px] md:max-w-[320px] justify-center mx-auto shrink min-w-0">
|
||||
<RulerSlider currentDegree={currentDegree} onChange={onSeekDegree} className="w-full" />
|
||||
</div>
|
||||
|
||||
{/* Right Side: Zoom controls, Download, Fullscreen */}
|
||||
<div className="flex items-center gap-1 sm:gap-2 justify-end min-w-0 flex-1">
|
||||
{/* Zoom controls */}
|
||||
<div className="flex items-center gap-0.5 sm:gap-1 bg-muted/60 rounded-lg p-0.5 border border-border/40 shrink-0">
|
||||
<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 sm:px-1.5 py-0.5 text-[10px] sm: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 && onDownload && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onDownload}
|
||||
title="Download asset"
|
||||
aria-label="Download asset"
|
||||
className="p-1 sm:p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
>
|
||||
<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 sm:p-1.5 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors shrink-0"
|
||||
>
|
||||
{isFullScreen ? <Minimize className="w-4 h-4" /> : <Maximize className="w-4 h-4" />}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, 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: () => () => '' }),
|
||||
}))
|
||||
|
||||
const mockFileDownloadPost = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://example.com/download-model.glb' }),
|
||||
})
|
||||
const mockShareDownloadPost = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ url: 'https://example.com/share-download-model.glb' }),
|
||||
})
|
||||
|
||||
vi.mock('@/ui/api/client', () => ({
|
||||
client: {
|
||||
api: {
|
||||
files: {
|
||||
'download-url': {
|
||||
$post: (...args: unknown[]) => mockFileDownloadPost(...args),
|
||||
},
|
||||
},
|
||||
shares: {
|
||||
':shareId': {
|
||||
files: {
|
||||
':fileId': {
|
||||
'download-url': {
|
||||
$post: (...args: unknown[]) => mockShareDownloadPost(...args),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
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 { container, 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()
|
||||
// Video does not use low-res poster
|
||||
expect(container.querySelector('video')?.getAttribute('poster')).toBeNull()
|
||||
})
|
||||
|
||||
it('prioritizes videoTranscodes URL over videoPreview URL for watermarked share compatibility', () => {
|
||||
const fileWithBoth = {
|
||||
...mockAsset,
|
||||
media: {
|
||||
...mockAsset.media,
|
||||
videoPreview: { url: 'https://example.com/unwatermarked-turntable.mp4' },
|
||||
videoTranscodes: [{ url: 'https://example.com/watermarked-turntable.mp4' }],
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { container } = render(<ModelViewer file={fileWithBoth} />)
|
||||
const video = container.querySelector('video')
|
||||
expect(video?.getAttribute('src')).toBe('https://example.com/watermarked-turntable.mp4')
|
||||
})
|
||||
|
||||
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 ArrowRight second time -> advance to frame 2 (30 deg = 2/6 sec)
|
||||
fireEvent.keyDown(window, { key: 'ArrowRight' })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
|
||||
|
||||
// Press ArrowLeft -> back 1 frame (frame 1 = 1/6 sec)
|
||||
fireEvent.keyDown(window, { key: 'ArrowLeft' })
|
||||
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 (drag right rotates counterclockwise)', () => {
|
||||
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 (drag right rotates counterclockwise: frame 0 - 2 = 22 frames = 22/6s)
|
||||
fireEvent.pointerMove(surface, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(22 / 6, 2))
|
||||
|
||||
// Move left by 24px from origin (frame 0 - (-2) = 2 frames = 2/6s)
|
||||
fireEvent.pointerMove(surface, { clientX: 76, button: 0, pointerId: 1 })
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(2 / 6, 2))
|
||||
|
||||
// Release drag
|
||||
fireEvent.pointerUp(surface, { clientX: 76, 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('renders children alongside viewer surface when provided', () => {
|
||||
const { getByTestId } = render(
|
||||
<ModelViewer file={mockAsset}>
|
||||
<div data-testid="test-sidebar">Sidebar</div>
|
||||
</ModelViewer>,
|
||||
)
|
||||
|
||||
expect(getByTestId('test-sidebar')).toBeDefined()
|
||||
expect(getByTestId('model-viewer-surface')).toBeDefined()
|
||||
})
|
||||
|
||||
it('steps rotation by 15° forward and backward via plus and minus buttons', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { getByTestId } = render(
|
||||
<ModelViewer file={mockAsset} startTime={0} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
|
||||
const plusBtn = getByTestId('ruler-step-plus')
|
||||
const minusBtn = getByTestId('ruler-step-minus')
|
||||
|
||||
// Click plus button at 0° -> seeks to 15° (frame 1, 1/6s)
|
||||
fireEvent.click(plusBtn)
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(1 / 6, 2))
|
||||
|
||||
// Click minus button at 0° (or current) -> wraps backward
|
||||
fireEvent.click(minusBtn)
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('updates playback smoothly on each frame via requestVideoFrameCallback without skipping degrees', () => {
|
||||
let frameCallback: ((now: number, metadata: { mediaTime: number }) => void) | null = null
|
||||
const rvfcMock = vi.fn().mockImplementation((cb) => {
|
||||
frameCallback = cb
|
||||
return 101
|
||||
})
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(HTMLVideoElement.prototype as any).requestVideoFrameCallback = rvfcMock
|
||||
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { container, getByTestId } = render(
|
||||
<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
|
||||
const video = container.querySelector('video')
|
||||
expect(video).toBeDefined()
|
||||
|
||||
// Start playing
|
||||
fireEvent.play(video!)
|
||||
expect(rvfcMock).toHaveBeenCalled()
|
||||
|
||||
// Simulate decoded frames arriving sequentially at 6 FPS (every 1/6 second)
|
||||
const degreeReadout = getByTestId('degree-readout')
|
||||
|
||||
// Frame 0: 0.083s -> 0°
|
||||
act(() => {
|
||||
frameCallback!(100, { mediaTime: 0.083 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('0° / 360°')
|
||||
|
||||
// Frame 1: 0.25s -> 15°
|
||||
act(() => {
|
||||
frameCallback!(267, { mediaTime: 0.25 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('15° / 360°')
|
||||
|
||||
// Frame 2: 0.417s -> 30°
|
||||
act(() => {
|
||||
frameCallback!(433, { mediaTime: 0.417 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('30° / 360°')
|
||||
|
||||
// Frame 3: 0.583s -> 45°
|
||||
act(() => {
|
||||
frameCallback!(600, { mediaTime: 0.583 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('45° / 360°')
|
||||
|
||||
// Frame 4: 0.75s -> 60°
|
||||
act(() => {
|
||||
frameCallback!(767, { mediaTime: 0.75 })
|
||||
})
|
||||
expect(degreeReadout.textContent).toContain('60° / 360°')
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (HTMLVideoElement.prototype as any).requestVideoFrameCallback
|
||||
})
|
||||
|
||||
it('cancels frame callback loop when video is paused', () => {
|
||||
const cancelMock = vi.fn()
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(HTMLVideoElement.prototype as any).requestVideoFrameCallback = vi.fn().mockReturnValue(123)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
;(HTMLVideoElement.prototype as any).cancelVideoFrameCallback = cancelMock
|
||||
|
||||
const { container } = render(<ModelViewer file={mockAsset} />)
|
||||
const video = container.querySelector('video')
|
||||
|
||||
fireEvent.play(video!)
|
||||
fireEvent.pause(video!)
|
||||
|
||||
expect(cancelMock).toHaveBeenCalledWith(123)
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (HTMLVideoElement.prototype as any).requestVideoFrameCallback
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
delete (HTMLVideoElement.prototype as any).cancelVideoFrameCallback
|
||||
})
|
||||
|
||||
it('zooms viewer and prevents browser default on touchpad pinch (ctrl+wheel)', () => {
|
||||
const { getByTestId, getByRole } = render(<ModelViewer file={mockAsset} />)
|
||||
const surface = getByTestId('model-viewer-surface')
|
||||
const resetZoomBtn = getByRole('button', { name: 'Reset zoom' })
|
||||
|
||||
const initialZoomText = resetZoomBtn.textContent
|
||||
|
||||
surface.getBoundingClientRect = () =>
|
||||
({
|
||||
left: 0,
|
||||
top: 0,
|
||||
width: 800,
|
||||
height: 600,
|
||||
right: 800,
|
||||
bottom: 600,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: () => {},
|
||||
}) as DOMRect
|
||||
|
||||
const wheelEvent = new WheelEvent('wheel', {
|
||||
deltaY: -100,
|
||||
deltaMode: 0,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
})
|
||||
Object.defineProperty(wheelEvent, 'ctrlKey', { value: true })
|
||||
Object.defineProperty(wheelEvent, 'clientX', { value: 400 })
|
||||
Object.defineProperty(wheelEvent, 'clientY', { value: 300 })
|
||||
|
||||
let notPrevented = true
|
||||
act(() => {
|
||||
notPrevented = surface.dispatchEvent(wheelEvent)
|
||||
})
|
||||
|
||||
expect(notPrevented).toBe(false)
|
||||
expect(resetZoomBtn.textContent).not.toBe(initialZoomText)
|
||||
})
|
||||
|
||||
it('pans viewer content and prevents scroll on two-finger wheel when zoomed in', () => {
|
||||
const { getByTestId, getByRole } = render(<ModelViewer file={mockAsset} />)
|
||||
const surface = getByTestId('model-viewer-surface')
|
||||
const zoomInBtn = getByRole('button', { name: 'Zoom in' })
|
||||
|
||||
// Zoom in multiple times so zoom exceeds baseScale significantly
|
||||
fireEvent.click(zoomInBtn)
|
||||
fireEvent.click(zoomInBtn)
|
||||
fireEvent.click(zoomInBtn)
|
||||
|
||||
const mediaWrapper = surface.querySelector('div.absolute.pointer-events-none') as HTMLElement
|
||||
const initialTransform = mediaWrapper.style.transform
|
||||
|
||||
const scrollEvent = new WheelEvent('wheel', {
|
||||
deltaX: 20,
|
||||
deltaY: 30,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
})
|
||||
Object.defineProperty(scrollEvent, 'ctrlKey', { value: false })
|
||||
|
||||
let notPrevented = true
|
||||
act(() => {
|
||||
notPrevented = surface.dispatchEvent(scrollEvent)
|
||||
})
|
||||
|
||||
expect(notPrevented).toBe(false)
|
||||
expect(mediaWrapper.style.transform).not.toBe(initialTransform)
|
||||
})
|
||||
|
||||
it('keeps video loop attribute disabled when paused to prevent browser EOF reset, and enables loop when playing', () => {
|
||||
const { container } = render(<ModelViewer file={mockAsset} />)
|
||||
const video = container.querySelector('video') as HTMLVideoElement
|
||||
expect(video).toBeDefined()
|
||||
|
||||
// Paused initially: loop should be false so seeking to final frame does not trigger browser loop-reset
|
||||
expect(video.loop).toBe(false)
|
||||
|
||||
// Play: loop should become true
|
||||
fireEvent.play(video)
|
||||
expect(video.loop).toBe(true)
|
||||
|
||||
// Pause: loop should become false again
|
||||
fireEvent.pause(video)
|
||||
expect(video.loop).toBe(false)
|
||||
})
|
||||
|
||||
it('seeks safely to 345° without touching 4.0s EOF boundary', () => {
|
||||
const onTimeUpdate = vi.fn()
|
||||
const { container, getByTestId } = render(
|
||||
<ModelViewer file={mockAsset} onTimeUpdate={onTimeUpdate} />,
|
||||
)
|
||||
const video = container.querySelector('video') as HTMLVideoElement
|
||||
const degreeReadout = getByTestId('degree-readout')
|
||||
|
||||
// At 0°, press ArrowLeft to rotate counterclockwise to 345° (Frame 23)
|
||||
fireEvent.keyDown(window, { key: 'ArrowLeft' })
|
||||
|
||||
// Target time should be 23 / 6s = 3.8333s
|
||||
expect(onTimeUpdate).toHaveBeenCalledWith(expect.closeTo(23 / 6, 2))
|
||||
// Video currentTime should be safely offset from 4.0s EOF (3.875s)
|
||||
expect(video.currentTime).toBeCloseTo(3.875, 3)
|
||||
expect(video.currentTime).toBeLessThan(4.0)
|
||||
expect(degreeReadout.textContent).toContain('345° / 360°')
|
||||
})
|
||||
|
||||
it('downloads the original model via files download-url endpoint when Download asset is clicked', async () => {
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
const { getByTitle } = render(<ModelViewer file={mockAsset} />)
|
||||
const downloadBtn = getByTitle('Download asset')
|
||||
expect(downloadBtn).toBeDefined()
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(downloadBtn)
|
||||
})
|
||||
|
||||
expect(mockFileDownloadPost).toHaveBeenCalledWith({
|
||||
json: { key: 'files/robot.glb', assetId: 'asset-3d-1' },
|
||||
})
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('downloads the model via shares download-url endpoint when shareId is provided', async () => {
|
||||
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {})
|
||||
const { getByTitle } = render(<ModelViewer file={mockAsset} shareId="share-test-123" />)
|
||||
const downloadBtn = getByTitle('Download asset')
|
||||
expect(downloadBtn).toBeDefined()
|
||||
|
||||
await act(async () => {
|
||||
fireEvent.click(downloadBtn)
|
||||
})
|
||||
|
||||
expect(mockShareDownloadPost).toHaveBeenCalledWith({
|
||||
param: { shareId: 'share-test-123', fileId: 'asset-3d-1' },
|
||||
json: { key: 'files/robot.glb' },
|
||||
})
|
||||
expect(clickSpy).toHaveBeenCalled()
|
||||
clickSpy.mockRestore()
|
||||
})
|
||||
|
||||
it('hides the download button when allowDownload is false', () => {
|
||||
const { queryByTitle } = render(<ModelViewer file={mockAsset} allowDownload={false} />)
|
||||
expect(queryByTitle('Download asset')).toBeNull()
|
||||
})
|
||||
|
||||
it('hides the download button when original key is missing', () => {
|
||||
const assetWithoutOriginal = {
|
||||
...mockAsset,
|
||||
media: {
|
||||
...mockAsset.media,
|
||||
original: undefined,
|
||||
},
|
||||
} as unknown as AssetInfo
|
||||
|
||||
const { queryByTitle } = render(<ModelViewer file={assetWithoutOriginal} />)
|
||||
expect(queryByTitle('Download asset')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,514 @@
|
||||
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<MediaController, FileViewerProps>(
|
||||
(
|
||||
{
|
||||
file: data,
|
||||
onPlay,
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
children,
|
||||
allowDownload = true,
|
||||
autoPlay = false,
|
||||
},
|
||||
ref,
|
||||
) => {
|
||||
const rootRef = useRef<HTMLDivElement | null>(null)
|
||||
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)
|
||||
|
||||
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 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])
|
||||
|
||||
// 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) => {
|
||||
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()
|
||||
const currentFrame = secondToFrame(currentTime)
|
||||
seekToFrame(currentFrame - 1)
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
e.preventDefault()
|
||||
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<HTMLDivElement>) => {
|
||||
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,
|
||||
}
|
||||
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°)
|
||||
// Dragging right (deltaX > 0) rotates turntable counterclockwise (decreasing frame index)
|
||||
const deltaFrames = Math.round(deltaX / 12)
|
||||
const targetFrame = dragStartRef.current.frame - deltaFrames
|
||||
seekToFrame(targetFrame)
|
||||
}
|
||||
|
||||
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 (!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 (
|
||||
<div
|
||||
ref={rootRef}
|
||||
data-testid="model-viewer-container"
|
||||
className={cn(
|
||||
'group shadow-2xl font-sans select-none flex flex-col mx-auto relative',
|
||||
isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
|
||||
)}
|
||||
>
|
||||
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
|
||||
{/* Render Carousel/Sidebar here if not fullscreen */}
|
||||
{!isFullScreen && children}
|
||||
|
||||
{/* Interactive Drag Rotation Surface & Model Area */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
data-testid="model-viewer-surface"
|
||||
onPointerDown={handleViewerPointerDown}
|
||||
onPointerMove={handleViewerPointerMove}
|
||||
onPointerUp={handleViewerPointerUp}
|
||||
onPointerCancel={handleViewerPointerUp}
|
||||
className={cn(
|
||||
'flex-1 bg-black relative flex items-center justify-center overflow-hidden min-h-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}
|
||||
playsInline
|
||||
loop={isPlaying}
|
||||
muted
|
||||
autoPlay={autoPlay}
|
||||
preload="auto"
|
||||
onLoadedData={() => {
|
||||
setIsLoading(false)
|
||||
if (startTime && startTime > 0) {
|
||||
seekToFrame(secondToFrame(startTime))
|
||||
}
|
||||
}}
|
||||
onPlay={() => {
|
||||
setIsPlaying(true)
|
||||
onPlay?.()
|
||||
}}
|
||||
onPause={() => {
|
||||
setIsPlaying(false)
|
||||
onPause?.()
|
||||
}}
|
||||
onEnded={() => {
|
||||
setIsPlaying(false)
|
||||
}}
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 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>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Full-width docked bottom control bar */}
|
||||
<ModelControlBar
|
||||
isPlaying={isPlaying}
|
||||
currentDegree={currentDegree}
|
||||
zoom={zoom}
|
||||
isFullScreen={isFullScreen}
|
||||
allowDownload={allowDownload}
|
||||
onDownload={data.media?.original?.key ? handleDownload : undefined}
|
||||
togglePlay={togglePlay}
|
||||
onSeekDegree={seekToDegree}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
ModelViewer.displayName = 'ModelViewer'
|
||||
export default ModelViewer
|
||||
@@ -0,0 +1,164 @@
|
||||
// @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 with fixed center indicator and aria values', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, getByTestId, queryByTestId } = render(
|
||||
<RulerSlider currentDegree={90} onChange={onChange} />,
|
||||
)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
expect(slider).toBeDefined()
|
||||
expect(slider.getAttribute('aria-valuenow')).toBe('90')
|
||||
expect(slider.getAttribute('aria-valuetext')).toBe('90°')
|
||||
|
||||
// Fixed center indicator exists
|
||||
expect(getByTestId('ruler-center-indicator')).toBeDefined()
|
||||
|
||||
// Tooltip should not be rendered while not dragging
|
||||
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('renders ticks at 15° intervals, longer at 60° intervals, and no numeric tick labels', () => {
|
||||
const onChange = vi.fn()
|
||||
const { container, getAllByTestId } = render(
|
||||
<RulerSlider currentDegree={0} onChange={onChange} />,
|
||||
)
|
||||
|
||||
// Major ticks at multiples of 60°
|
||||
const ticks0 = getAllByTestId('tick-0')
|
||||
expect(ticks0.length).toBeGreaterThan(0)
|
||||
expect(ticks0[0]?.getAttribute('data-major')).toBe('true')
|
||||
|
||||
const ticks60 = getAllByTestId('tick-60')
|
||||
expect(ticks60.length).toBeGreaterThan(0)
|
||||
expect(ticks60[0]?.getAttribute('data-major')).toBe('true')
|
||||
|
||||
// Regular tick at 15° is not major
|
||||
const ticks15 = getAllByTestId('tick-15')
|
||||
expect(ticks15.length).toBeGreaterThan(0)
|
||||
expect(ticks15[0]?.getAttribute('data-major')).toBe('false')
|
||||
|
||||
// No numeric degree text inside the slider track
|
||||
expect(container.textContent).toBe('')
|
||||
})
|
||||
|
||||
it('shows tooltip displaying degree while dragging and hides on pointer up', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, getByTestId, queryByTestId } = render(
|
||||
<RulerSlider currentDegree={45} onChange={onChange} />,
|
||||
)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
slider.setPointerCapture = vi.fn()
|
||||
slider.releasePointerCapture = vi.fn()
|
||||
|
||||
// Initially no tooltip
|
||||
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
|
||||
|
||||
// Start dragging
|
||||
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
|
||||
const tooltip = getByTestId('ruler-slider-tooltip')
|
||||
expect(tooltip).toBeDefined()
|
||||
expect(tooltip.textContent).toBe('45°')
|
||||
|
||||
// Release drag
|
||||
fireEvent.pointerUp(slider, { clientX: 100, button: 0, pointerId: 1 })
|
||||
expect(queryByTestId('ruler-slider-tooltip')).toBeNull()
|
||||
})
|
||||
|
||||
it('handles keyboard navigation with 15 degree stepping and wrapping', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole } = render(<RulerSlider currentDegree={45} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
|
||||
// 45 + 15 = 60
|
||||
fireEvent.keyDown(slider, { key: 'ArrowRight' })
|
||||
expect(onChange).toHaveBeenCalledWith(60)
|
||||
|
||||
// 45 - 15 = 30
|
||||
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
|
||||
expect(onChange).toHaveBeenCalledWith(30)
|
||||
|
||||
// Home -> 0
|
||||
fireEvent.keyDown(slider, { key: 'Home' })
|
||||
expect(onChange).toHaveBeenCalledWith(0)
|
||||
|
||||
// End -> 345
|
||||
fireEvent.keyDown(slider, { key: 'End' })
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
})
|
||||
|
||||
it('wraps around 0° and 360° on keyboard navigation', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
|
||||
// 0 - 15 wraps to 345
|
||||
fireEvent.keyDown(slider, { key: 'ArrowLeft' })
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
|
||||
// 345 + 15 wraps to 0
|
||||
rerender(<RulerSlider currentDegree={345} onChange={onChange} />)
|
||||
fireEvent.keyDown(slider, { key: 'ArrowRight' })
|
||||
expect(onChange).toHaveBeenCalledWith(0)
|
||||
})
|
||||
|
||||
it('handles pointer drag interaction with 15 degree snapping and wrapping', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByRole } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const slider = getByRole('slider')
|
||||
slider.setPointerCapture = vi.fn()
|
||||
slider.releasePointerCapture = vi.fn()
|
||||
|
||||
// Start drag at x = 100
|
||||
fireEvent.pointerDown(slider, { clientX: 100, button: 0, pointerId: 1 })
|
||||
expect(slider.setPointerCapture).toHaveBeenCalledWith(1)
|
||||
|
||||
// Drag left by 24px (15° forward: deltaX = -24 => deltaDeg = +15)
|
||||
fireEvent.pointerMove(slider, { clientX: 76, button: 0, pointerId: 1 })
|
||||
expect(onChange).toHaveBeenCalledWith(15)
|
||||
|
||||
// Drag right by 24px from origin (x=124 => deltaX = +24 => deltaDeg = -15 => wraps to 345)
|
||||
fireEvent.pointerMove(slider, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
|
||||
// Release pointer
|
||||
fireEvent.pointerUp(slider, { clientX: 124, button: 0, pointerId: 1 })
|
||||
expect(slider.releasePointerCapture).toHaveBeenCalledWith(1)
|
||||
})
|
||||
|
||||
it('steps degree forward and backward via encapsulated plus and minus buttons', () => {
|
||||
const onChange = vi.fn()
|
||||
const { getByTestId, rerender } = render(<RulerSlider currentDegree={0} onChange={onChange} />)
|
||||
|
||||
const plusBtn = getByTestId('ruler-step-plus')
|
||||
const minusBtn = getByTestId('ruler-step-minus')
|
||||
|
||||
// 0 + 15 = 15
|
||||
fireEvent.click(plusBtn)
|
||||
expect(onChange).toHaveBeenCalledWith(15)
|
||||
|
||||
// 0 - 15 wraps to 345
|
||||
fireEvent.click(minusBtn)
|
||||
expect(onChange).toHaveBeenCalledWith(345)
|
||||
|
||||
// When disabled, clicking should not trigger onChange
|
||||
onChange.mockClear()
|
||||
rerender(<RulerSlider currentDegree={0} onChange={onChange} disabled />)
|
||||
fireEvent.click(plusBtn)
|
||||
fireEvent.click(minusBtn)
|
||||
expect(onChange).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,228 @@
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { Minus, Plus } from 'lucide-react'
|
||||
import React, { useCallback, useRef, useState } from 'react'
|
||||
|
||||
export interface RulerSliderProps {
|
||||
currentDegree: number // 0 to 360 (or normalized modulo 360)
|
||||
onChange: (degree: number) => void
|
||||
className?: string
|
||||
disabled?: boolean
|
||||
}
|
||||
|
||||
const STEP = 15
|
||||
const PX_PER_STEP = 20 // 20px per 15° step
|
||||
const PX_PER_DEGREE = PX_PER_STEP / STEP // ~1.333px per degree
|
||||
const BUFFER_DEGREE = 240 // Render buffer on each side of the active degree
|
||||
|
||||
export const RulerSlider: React.FC<RulerSliderProps> = ({
|
||||
currentDegree,
|
||||
onChange,
|
||||
className,
|
||||
disabled = false,
|
||||
}) => {
|
||||
const trackRef = useRef<HTMLDivElement>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [dragDegree, setDragDegree] = useState<number | null>(null)
|
||||
const dragStartRef = useRef<{ clientX: number; startDegree: number }>({
|
||||
clientX: 0,
|
||||
startDegree: 0,
|
||||
})
|
||||
|
||||
const normalizedDegree = (((Math.round(currentDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
const activeDegree = isDragging && dragDegree !== null ? dragDegree : normalizedDegree
|
||||
const displayedDegree = (((Math.round(activeDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
|
||||
const handleStep = useCallback(
|
||||
(delta: number) => {
|
||||
if (disabled) return
|
||||
const next = (((normalizedDegree + delta) % 360) + 360) % 360
|
||||
onChange(next)
|
||||
},
|
||||
[disabled, normalizedDegree, onChange],
|
||||
)
|
||||
|
||||
const handlePointerDown = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (disabled || e.button !== 0) return
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
|
||||
const target = trackRef.current
|
||||
if (!target) return
|
||||
target.setPointerCapture(e.pointerId)
|
||||
|
||||
dragStartRef.current = {
|
||||
clientX: e.clientX,
|
||||
startDegree: currentDegree,
|
||||
}
|
||||
setIsDragging(true)
|
||||
setDragDegree(currentDegree)
|
||||
},
|
||||
[disabled, currentDegree],
|
||||
)
|
||||
|
||||
const handlePointerMove = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging || disabled) return
|
||||
const deltaX = e.clientX - dragStartRef.current.clientX
|
||||
// Dragging left (deltaX < 0) rotates turntable forward (angle increases)
|
||||
const nextRawDegree = dragStartRef.current.startDegree - deltaX / PX_PER_DEGREE
|
||||
const snapped = (((Math.round(nextRawDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
setDragDegree(nextRawDegree)
|
||||
onChange(snapped)
|
||||
},
|
||||
[isDragging, disabled, onChange],
|
||||
)
|
||||
|
||||
const handlePointerUp = useCallback(
|
||||
(e: React.PointerEvent<HTMLDivElement>) => {
|
||||
if (!isDragging) return
|
||||
setIsDragging(false)
|
||||
if (dragDegree !== null) {
|
||||
const snapped = (((Math.round(dragDegree / STEP) * STEP) % 360) + 360) % 360
|
||||
onChange(snapped)
|
||||
}
|
||||
setDragDegree(null)
|
||||
try {
|
||||
trackRef.current?.releasePointerCapture(e.pointerId)
|
||||
} catch {
|
||||
// pointer may have already been released
|
||||
}
|
||||
},
|
||||
[isDragging, dragDegree, onChange],
|
||||
)
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (disabled) return
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
handleStep(-STEP)
|
||||
} else if (e.key === 'ArrowRight' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
handleStep(STEP)
|
||||
} else if (e.key === 'Home') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange(0)
|
||||
} else if (e.key === 'End') {
|
||||
e.preventDefault()
|
||||
e.stopPropagation()
|
||||
onChange(345)
|
||||
}
|
||||
},
|
||||
[disabled, handleStep, onChange],
|
||||
)
|
||||
|
||||
// Compute visible ticks dynamically around activeDegree for seamless cyclic looping
|
||||
const minTickIndex = Math.floor((activeDegree - BUFFER_DEGREE) / STEP)
|
||||
const maxTickIndex = Math.ceil((activeDegree + BUFFER_DEGREE) / STEP)
|
||||
const ticks: number[] = []
|
||||
for (let i = minTickIndex; i <= maxTickIndex; i++) {
|
||||
ticks.push(i * STEP)
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
'relative select-none flex items-center gap-1 sm:gap-2.5 w-full min-w-0 sm:min-w-[140px]',
|
||||
disabled && 'opacity-50',
|
||||
className,
|
||||
)}
|
||||
>
|
||||
{/* Minus button on left */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStep(-STEP)}
|
||||
disabled={disabled}
|
||||
title="Decrease 15°"
|
||||
aria-label="Decrease 15°"
|
||||
data-testid="ruler-step-minus"
|
||||
className="p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<Minus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
|
||||
{/* Center Capsule Slider Track Container */}
|
||||
<div className="relative flex-1 min-w-0">
|
||||
{/* Tooltip above center indicator (visible only when dragging) */}
|
||||
{isDragging && (
|
||||
<div
|
||||
data-testid="ruler-slider-tooltip"
|
||||
className="absolute -top-7 left-1/2 -translate-x-1/2 px-1.5 py-0.5 rounded bg-primary text-primary-foreground text-[10px] font-mono font-medium shadow-md whitespace-nowrap pointer-events-none z-30 animate-in fade-in zoom-in-95 duration-100"
|
||||
>
|
||||
{displayedDegree}°
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Capsule track with rounded pill shape, clipping scrolling ticks */}
|
||||
<div
|
||||
ref={trackRef}
|
||||
role="slider"
|
||||
aria-label="Turntable angle"
|
||||
aria-valuemin={0}
|
||||
aria-valuemax={360}
|
||||
aria-valuenow={displayedDegree}
|
||||
aria-valuetext={`${displayedDegree}°`}
|
||||
tabIndex={disabled ? -1 : 0}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerMove={handlePointerMove}
|
||||
onPointerUp={handlePointerUp}
|
||||
onPointerCancel={handlePointerUp}
|
||||
onKeyDown={handleKeyDown}
|
||||
className={cn(
|
||||
'relative w-full h-7 rounded-full bg-muted border border-border overflow-hidden cursor-ew-resize touch-none select-none group focus:outline-none focus-visible:ring-1 focus-visible:ring-ring',
|
||||
disabled && 'cursor-not-allowed',
|
||||
)}
|
||||
>
|
||||
{/* Cyclic Ticks - vertically centered */}
|
||||
<div className="absolute inset-0 flex items-center justify-center pointer-events-none">
|
||||
{ticks.map((tickAngle) => {
|
||||
const offsetPx = (tickAngle - activeDegree) * PX_PER_DEGREE
|
||||
const deg = ((tickAngle % 360) + 360) % 360
|
||||
const isMajor = deg % 60 === 0
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`tick-${tickAngle}`}
|
||||
data-testid={`tick-${deg}`}
|
||||
data-major={isMajor}
|
||||
className={cn(
|
||||
'absolute top-1/2 -translate-y-1/2 -translate-x-1/2 transition-colors pointer-events-none rounded-[0.5px]',
|
||||
isMajor
|
||||
? 'w-0.5 h-2.5 bg-foreground/75'
|
||||
: 'w-px h-1.5 bg-muted-foreground/45 group-hover:bg-muted-foreground/65',
|
||||
)}
|
||||
style={{ left: `calc(50% + ${offsetPx}px)` }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Fixed Center Red Indicator (Pinned at 50% horizontally, spans full height) */}
|
||||
<div
|
||||
data-testid="ruler-center-indicator"
|
||||
className="absolute inset-y-0 left-1/2 -translate-x-1/2 w-0.5 flex items-center justify-center pointer-events-none z-20"
|
||||
>
|
||||
<div className="w-full h-full bg-[#ea3349] rounded-full" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Plus button on right */}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleStep(STEP)}
|
||||
disabled={disabled}
|
||||
title="Increase 15°"
|
||||
aria-label="Increase 15°"
|
||||
data-testid="ruler-step-plus"
|
||||
className="p-0.5 sm:p-1 rounded text-muted-foreground hover:text-foreground transition-colors shrink-0 disabled:opacity-40 disabled:cursor-not-allowed focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
>
|
||||
<Plus className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
calculateFrameCenterTime,
|
||||
secondToFrame,
|
||||
secondToDegree,
|
||||
TOTAL_FRAMES,
|
||||
FPS,
|
||||
FRAME_DURATION,
|
||||
} from './utils'
|
||||
|
||||
describe('model viewer utils', () => {
|
||||
describe('calculateFrameCenterTime', () => {
|
||||
it('calculates the center time for frame 0', () => {
|
||||
expect(calculateFrameCenterTime(0)).toBeCloseTo(0.5 / FPS)
|
||||
})
|
||||
|
||||
it('calculates presentation times safely within frame boundaries for all frames 0 to 23', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES - 1; i++) {
|
||||
const center = calculateFrameCenterTime(i)
|
||||
expect(center).toBeCloseTo((i + 0.5) * FRAME_DURATION)
|
||||
}
|
||||
// For the final frame (frame 23, 345°), ensure it is safely offset away from EOF (4.0s)
|
||||
const lastCenter = calculateFrameCenterTime(TOTAL_FRAMES - 1)
|
||||
expect(lastCenter).toBeCloseTo((TOTAL_FRAMES - 1) * FRAME_DURATION + FRAME_DURATION * 0.25)
|
||||
expect(lastCenter).toBeLessThan(TOTAL_FRAMES * FRAME_DURATION)
|
||||
})
|
||||
|
||||
it('handles negative and wrapping frames properly', () => {
|
||||
expect(calculateFrameCenterTime(-1)).toBeCloseTo(calculateFrameCenterTime(23))
|
||||
expect(calculateFrameCenterTime(24)).toBeCloseTo(calculateFrameCenterTime(0))
|
||||
})
|
||||
})
|
||||
|
||||
describe('secondToFrame', () => {
|
||||
it('correctly maps frame start times to frame index without float truncation', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const startSec = i * FRAME_DURATION
|
||||
expect(secondToFrame(startSec)).toBe(i)
|
||||
}
|
||||
})
|
||||
|
||||
it('correctly maps frame center times to frame index', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const centerSec = calculateFrameCenterTime(i)
|
||||
expect(secondToFrame(centerSec)).toBe(i)
|
||||
}
|
||||
})
|
||||
|
||||
it('clamps values below 0 and above total duration', () => {
|
||||
expect(secondToFrame(-1)).toBe(0)
|
||||
expect(secondToFrame(100)).toBe(TOTAL_FRAMES - 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('secondToDegree', () => {
|
||||
it('returns 0 for 0s', () => {
|
||||
expect(secondToDegree(0)).toBe(0)
|
||||
})
|
||||
|
||||
it('returns exact degrees (0..345) for every frame center', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const center = calculateFrameCenterTime(i)
|
||||
expect(secondToDegree(center)).toBe((i * 15) % 360)
|
||||
}
|
||||
})
|
||||
|
||||
it('returns exact degrees for frame start times', () => {
|
||||
for (let i = 0; i < TOTAL_FRAMES; i++) {
|
||||
const start = i * FRAME_DURATION
|
||||
expect(secondToDegree(start)).toBe((i * 15) % 360)
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
export const TOTAL_FRAMES = 24
|
||||
export const FPS = 6
|
||||
export const FRAME_DURATION = 1 / FPS
|
||||
|
||||
/**
|
||||
* Calculates the presentation time within a frame.
|
||||
* Seeking near the frame center avoids PTS boundary inaccuracies in browser video decoders.
|
||||
* For the final frame (TOTAL_FRAMES - 1), we use a safe offset inside the frame
|
||||
* to avoid grazing the EOF boundary (video duration) which can cause browser decoders
|
||||
* to trigger end-of-stream or loop behavior.
|
||||
*/
|
||||
export function calculateFrameCenterTime(frameIndex: number): number {
|
||||
const normalizedFrame = ((frameIndex % TOTAL_FRAMES) + TOTAL_FRAMES) % TOTAL_FRAMES
|
||||
if (normalizedFrame === TOTAL_FRAMES - 1) {
|
||||
return normalizedFrame * FRAME_DURATION + FRAME_DURATION * 0.25
|
||||
}
|
||||
return (normalizedFrame + 0.5) * FRAME_DURATION
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a playback second into a frame index (0..23), clamped.
|
||||
* Works with frame start times, frame center times, or continuous playback seconds.
|
||||
*/
|
||||
export function secondToFrame(second: number): number {
|
||||
return Math.min(Math.max(0, Math.floor(second * FPS + 1e-4)), TOTAL_FRAMES - 1)
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a second to turntable degree (0, 15, 30, ..., 345).
|
||||
*/
|
||||
export function secondToDegree(second: number): number {
|
||||
const frameIndex = secondToFrame(second)
|
||||
return (frameIndex * 15) % 360
|
||||
}
|
||||
@@ -3,9 +3,15 @@ import { FileTypeDefinition } from './types'
|
||||
import { videoTypeDefinition } from './video'
|
||||
import { imageTypeDefinition } from './image'
|
||||
import { pdfTypeDefinition } from './pdf'
|
||||
import { modelTypeDefinition } from './model'
|
||||
import { defaultTypeDefinition } from './default'
|
||||
|
||||
const registry: FileTypeDefinition[] = [pdfTypeDefinition, videoTypeDefinition, imageTypeDefinition]
|
||||
const registry: FileTypeDefinition[] = [
|
||||
modelTypeDefinition,
|
||||
pdfTypeDefinition,
|
||||
videoTypeDefinition,
|
||||
imageTypeDefinition,
|
||||
]
|
||||
|
||||
export function getViewerForFile(file: AssetInfo | null | undefined): FileTypeDefinition {
|
||||
if (!file) return defaultTypeDefinition
|
||||
|
||||
Reference in New Issue
Block a user