mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-27 11:24:43 +00:00
feat(transcode): add 3D asset support and turntable viewer
This commit is contained in:
@@ -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,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>
|
||||
)
|
||||
}
|
||||
@@ -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