fix(webui): add video loading state and poster placeholder (#444)

* fix(webui): add video loading state and poster placeholder

* fix(webui): prevent buffer progress events from canceling stall indicator
This commit is contained in:
Yiling-J
2026-10-02 16:19:49 +08:00
committed by GitHub
parent 3564d4d164
commit daa20aed20
8 changed files with 1111 additions and 515 deletions
@@ -68,6 +68,7 @@ export function CompareControlBar({
isCurrentHdr: v.isCurrentHdr,
activeAutoResolution: v.activeAutoResolution,
isHlsManualSupported: v.isHlsManualSupported,
isLoading: v.isLoading,
}
// The active-side asset carries the metadata used for timecode display and
@@ -35,6 +35,7 @@ export interface PaneReportedState {
buffered: number
activeAutoResolution?: string
isHlsManualSupported?: boolean
isLoading?: boolean
}
}
@@ -305,4 +305,198 @@ describe('CompareVideoPane', () => {
const lastState = reportedStates[reportedStates.length - 1]
expect(lastState?.video?.resolutions?.[0]?.resolution).toBe('1080p')
})
it('sets poster on video element from file.preview.thumbnailUrl', () => {
const videoWithThumb: AssetInfo = {
id: 'compare-thumb',
name: 'thumb.mp4',
proxyType: 'video',
preview: {
thumbnailUrl: 'https://cdn.example.com/compare-poster.jpg',
},
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/compare-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const { container } = render(
<CompareVideoPane
file={videoWithThumb}
isActive={true}
annotations={[]}
onActivate={vi.fn()}
onStateChange={vi.fn()}
/>,
)
const video = container.querySelector(
'[data-testid="compare-video-area"] video',
) as HTMLVideoElement
expect(video.getAttribute('poster')).toBe('https://cdn.example.com/compare-poster.jpg')
})
it('shows loading spinner initially, transitions on loadeddata, and blocks play while loading', () => {
const testVideo: AssetInfo = {
id: 'compare-loading-test',
name: 'loading.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/compare-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const onRequestTogglePlay = vi.fn()
const { container } = render(
<CompareVideoPane
file={testVideo}
isActive={true}
annotations={[]}
onActivate={vi.fn()}
onStateChange={vi.fn()}
onRequestTogglePlay={onRequestTogglePlay}
/>,
)
const area = container.querySelector('[data-testid="compare-video-area"]') as HTMLDivElement
const video = area.querySelector('video') as HTMLVideoElement
// Initially loading spinner is visible
expect(container.querySelector('[data-testid="compare-video-loading-spinner"]')).not.toBeNull()
expect(container.querySelector('[data-testid="compare-video-play-overlay"]')).toBeNull()
// Clicking while loading should not trigger play
act(() => {
area.click()
})
expect(onRequestTogglePlay).not.toHaveBeenCalled()
// Dispatch loadeddata
act(() => {
video.dispatchEvent(new Event('loadeddata'))
})
// Spinner gone, play overlay visible
expect(container.querySelector('[data-testid="compare-video-loading-spinner"]')).toBeNull()
expect(container.querySelector('[data-testid="compare-video-play-overlay"]')).not.toBeNull()
// Clicking now triggers toggle play
act(() => {
area.click()
})
expect(onRequestTogglePlay).toHaveBeenCalledTimes(1)
})
it('does not cancel waiting stall debounce when progress events fire during stall', () => {
vi.useFakeTimers()
try {
const testVideo: AssetInfo = {
id: 'compare-stall-progress-test',
name: 'compare-stall-progress.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/compare-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const { container } = render(
<CompareVideoPane
file={testVideo}
isActive={true}
annotations={[]}
onActivate={vi.fn()}
onStateChange={vi.fn()}
/>,
)
const video = container.querySelector(
'[data-testid="compare-video-area"] video',
) as HTMLVideoElement
// 1. Initial ready state
act(() => {
video.dispatchEvent(new Event('loadeddata'))
})
expect(container.querySelector('[data-testid="compare-video-loading-spinner"]')).toBeNull()
// 2. Play starts (paused === false)
Object.defineProperty(video, 'paused', { value: false, configurable: true, writable: true })
act(() => {
video.dispatchEvent(new Event('playing'))
})
// 3. Stalls: dispatches waiting
act(() => {
video.dispatchEvent(new Event('waiting'))
})
// Spinner not visible immediately (within 200ms debounce)
expect(container.querySelector('[data-testid="compare-video-loading-spinner"]')).toBeNull()
// 4. Progress event fires at 100ms while paused is false (data still trickling in)
act(() => {
vi.advanceTimersByTime(100)
video.dispatchEvent(new Event('progress'))
})
// Should NOT clear debounce or mark loading false
expect(container.querySelector('[data-testid="compare-video-loading-spinner"]')).toBeNull()
// 5. Advance past 200ms debounce (advance remaining 110ms)
act(() => {
vi.advanceTimersByTime(110)
})
// Spinner should now appear despite the progress event!
expect(
container.querySelector('[data-testid="compare-video-loading-spinner"]'),
).not.toBeNull()
// 6. Playback resumes: dispatch playing
act(() => {
video.dispatchEvent(new Event('playing'))
})
// Spinner disappears
expect(container.querySelector('[data-testid="compare-video-loading-spinner"]')).toBeNull()
} finally {
vi.useRealTimers()
}
})
})
@@ -4,7 +4,7 @@ import { cn } from '@/ui/lib/utils'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { Annotation } from '@/ui/types'
import type { AssetInfo } from '@shumai/dtos'
import { Play, AudioLines } from 'lucide-react'
import { Play, AudioLines, Loader2 } from 'lucide-react'
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import Hls from 'hls.js'
import { useFramePlayer } from './use-frame-player'
@@ -107,6 +107,8 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
const [playerVolume, setPlayerVolume] = useState(volume)
const [playerMuted, setPlayerMuted] = useState(muted)
const [isPlayerReady, setIsPlayerReady] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const waitingTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const metadata = file.media?.metadata
const frameRate = metadata?.frameRate || 30
@@ -168,6 +170,12 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
setIsCurrentHdr(res?.hdr)
setActiveAutoResolution(undefined)
currentSrcRef.current = isHls ? file.media!.hls!.url : res?.url
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
waitingTimeoutRef.current = null
}
setIsLoading(true)
setIsPlayerReady(false)
setHasStartedPlaying(false)
}, [file.id, Boolean(isHls ? file.media?.hls?.url : initialRes?.url)])
@@ -184,7 +192,12 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
hlsRef.current = null
}
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
waitingTimeoutRef.current = null
}
setIsPlayerReady(false)
setIsLoading(true)
let hls: Hls | null = null
@@ -200,10 +213,6 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
hls.attachMedia(video)
hls.loadSource(targetSrc)
hls.on(Hls.Events.MANIFEST_PARSED, () => {
setIsPlayerReady(true)
})
hls.on(Hls.Events.LEVEL_SWITCHED, (_event, eventData) => {
const level = hls?.levels[eventData.level]
if (level) {
@@ -244,7 +253,17 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
video.src = targetSrc
}
const clearWaitingTimeout = () => {
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
waitingTimeoutRef.current = null
}
}
const handlePlay = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlayerReady(true)
if (pendingResolutionCorrectionRef.current) {
pendingResolutionCorrectionRef.current()
pendingResolutionCorrectionRef.current = null
@@ -254,9 +273,36 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
onPlay?.()
}
const handlePause = () => setIsPlaying(false)
const handleEnded = () => setIsPlaying(false)
const handleLoadedMetadata = () => setIsPlayerReady(true)
const handleLoadStart = () => setIsPlayerReady(false)
const handleEnded = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlaying(false)
}
const handleLoadedData = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlayerReady(true)
}
const handleCanPlay = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlayerReady(true)
}
const handlePlaying = () => {
clearWaitingTimeout()
setIsLoading(false)
}
const handleWaiting = () => {
clearWaitingTimeout()
waitingTimeoutRef.current = setTimeout(() => {
setIsLoading(true)
}, 200)
}
const handleLoadStart = () => {
clearWaitingTimeout()
setIsLoading(true)
setIsPlayerReady(false)
}
const handleProgress = () => {
const vidDuration = video.duration || containerDuration || 0
if (vidDuration > 0 && video.buffered.length > 0) {
@@ -282,10 +328,18 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
}
const handleRateChange = () => setPlaybackRate(video.playbackRate || 1)
if (video.readyState >= 2) {
setIsLoading(false)
setIsPlayerReady(true)
}
video.addEventListener('play', handlePlay)
video.addEventListener('pause', handlePause)
video.addEventListener('ended', handleEnded)
video.addEventListener('loadedmetadata', handleLoadedMetadata)
video.addEventListener('loadeddata', handleLoadedData)
video.addEventListener('canplay', handleCanPlay)
video.addEventListener('playing', handlePlaying)
video.addEventListener('waiting', handleWaiting)
video.addEventListener('loadstart', handleLoadStart)
video.addEventListener('timeupdate', handleProgress)
video.addEventListener('progress', handleProgress)
@@ -293,10 +347,14 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
video.addEventListener('ratechange', handleRateChange)
return () => {
clearWaitingTimeout()
video.removeEventListener('play', handlePlay)
video.removeEventListener('pause', handlePause)
video.removeEventListener('ended', handleEnded)
video.removeEventListener('loadedmetadata', handleLoadedMetadata)
video.removeEventListener('loadeddata', handleLoadedData)
video.removeEventListener('canplay', handleCanPlay)
video.removeEventListener('playing', handlePlaying)
video.removeEventListener('waiting', handleWaiting)
video.removeEventListener('loadstart', handleLoadStart)
video.removeEventListener('timeupdate', handleProgress)
video.removeEventListener('progress', handleProgress)
@@ -343,6 +401,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
buffered,
activeAutoResolution,
isHlsManualSupported,
isLoading,
},
}
onStateChange(state)
@@ -361,6 +420,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
buffered,
activeAutoResolution,
isHlsManualSupported,
isLoading,
])
// Propagate active playhead time
@@ -634,8 +694,9 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
onActivate?.()
return
}
if (isLoading) return
onRequestTogglePlay?.()
}, [isActive, onActivate, onRequestTogglePlay])
}, [isActive, isLoading, onActivate, onRequestTogglePlay])
if (!file.media?.metadata || resolutions.length === 0) {
return (
@@ -672,6 +733,7 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
className="w-full h-full block object-contain pointer-events-none"
playsInline
preload="auto"
poster={file.preview?.thumbnailUrl || undefined}
/>
</div>
)}
@@ -712,8 +774,23 @@ export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPanePr
)
)}
{!hasStartedPlaying && !isDrawing && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20 transition-opacity duration-200">
{/* Loading Spinner Overlay */}
{isLoading && (
<div
className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20 transition-opacity duration-200"
data-testid="compare-video-loading-spinner"
>
<div className="flex h-14 w-14 items-center justify-center rounded-full border-2 border-white/30 bg-white/10 backdrop-blur-sm">
<Loader2 className="h-7 w-7 text-white animate-spin" />
</div>
</div>
)}
{!isLoading && !hasStartedPlaying && !isDrawing && (
<div
className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20 transition-opacity duration-200"
data-testid="compare-video-play-overlay"
>
<div className="flex h-16 w-16 items-center justify-center rounded-full border-2 border-white/30 bg-white/10 backdrop-blur-sm">
<Play className="ml-1 h-8 w-8 fill-white text-white" />
</div>
@@ -45,7 +45,9 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
floatOverlayInFullScreen = true,
onMouseEnter,
onMouseLeave,
isLoading: propIsLoading,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
if (!data.media?.metadata) {
@@ -78,241 +80,248 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
{/* Progress Bar */}
<div className="mb-2 px-0.5">
<ProgressBar
totalFrames={totalFrames}
currentFrame={currentFrame}
fps={frameRate}
buffered={buffered}
previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame}
metadata={{
...data.media.metadata,
frameRate: frameRate,
}}
/>
</div>
<div
className={cn(
'transition-opacity duration-200',
isLoading && 'pointer-events-none opacity-60 select-none',
)}
>
{/* Progress Bar */}
<div className="mb-2 px-0.5">
<ProgressBar
totalFrames={totalFrames}
currentFrame={currentFrame}
fps={frameRate}
buffered={buffered}
previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame}
metadata={{
...data.media.metadata,
frameRate: frameRate,
}}
/>
</div>
{/* Control Row */}
<div className="flex items-center justify-between text-foreground gap-1 select-none">
{/* Left Side: Play, Mute, Time */}
<div className="flex items-center gap-2 min-w-0">
<button
onClick={togglePlay}
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
data-testid="play-toggle"
data-playing={state.isPlaying}
aria-label={state.isPlaying ? 'Pause' : 'Play'}
>
{state.isPlaying ? (
<Pause className="w-5 h-5 fill-current" />
) : (
<Play className="w-5 h-5 fill-current" />
)}
</button>
<button
onClick={toggleMute}
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
aria-label={state.isMuted ? 'Unmute' : 'Mute'}
>
{state.isMuted || state.volume === 0 ? (
<VolumeX className="w-5 h-5" />
) : (
<Volume2 className="w-5 h-5" />
)}
</button>
<div className="flex items-center gap-0.5 text-xs font-medium tabular-nums min-w-0">
<span
className="text-muted-foreground font-mono truncate text-[11px] sm:text-xs"
data-testid="time-readout"
{/* Control Row */}
<div className="flex items-center justify-between text-foreground gap-1 select-none">
{/* Left Side: Play, Mute, Time */}
<div className="flex items-center gap-2 min-w-0">
<button
onClick={togglePlay}
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
data-testid="play-toggle"
data-playing={state.isPlaying}
aria-label={state.isPlaying ? 'Pause' : 'Play'}
>
{displayString}
</span>
{state.isPlaying ? (
<Pause className="w-5 h-5 fill-current" />
) : (
<Play className="w-5 h-5 fill-current" />
)}
</button>
<button
onClick={toggleMute}
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
aria-label={state.isMuted ? 'Unmute' : 'Mute'}
>
{state.isMuted || state.volume === 0 ? (
<VolumeX className="w-5 h-5" />
) : (
<Volume2 className="w-5 h-5" />
)}
</button>
<div className="flex items-center gap-0.5 text-xs font-medium tabular-nums min-w-0">
<span
className="text-muted-foreground font-mono truncate text-[11px] sm:text-xs"
data-testid="time-readout"
>
{displayString}
</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
className="h-5 w-5 inline-flex items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none shrink-0"
aria-label={m.change_time_format()}
>
<ChevronDown className="h-3 w-3" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-40 z-30">
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
{m.format()}
</DropdownMenuLabel>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('standard')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>{m.standard_time()}</span>
{videoTimeDisplayMode === 'standard' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('frames')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>{m.frames()}</span>
{videoTimeDisplayMode === 'frames' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('timecode')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>{m.timecode()}</span>
{videoTimeDisplayMode === 'timecode' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Right Side: Settings (Quality + Speed) & Fullscreen */}
<div className="flex items-center gap-1 shrink-0">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
className="h-5 w-5 inline-flex items-center justify-center rounded hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none shrink-0"
aria-label={m.change_time_format()}
className="flex items-center gap-1 rounded border border-border px-1.5 py-1 text-xs font-semibold hover:bg-muted transition-colors cursor-pointer"
title={m.settings()}
aria-label={m.settings()}
>
<ChevronDown className="h-3 w-3" />
<Settings className="h-3.5 w-3.5" />
<span className="flex items-center gap-1 text-[11px]">
<span>
{!isAudio && state.currentResolution
? state.currentResolution === 'Auto'
? state.activeAutoResolution
? `${m.quality_auto()} (${state.activeAutoResolution})`
: m.quality_auto()
: state.currentResolution === 'Original'
? m.original()
: state.currentResolution
: `${state.playbackRate}x`}
</span>
{!isAudio && state.isCurrentHdr && (
<span className="px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-40 z-30">
<DropdownMenuContent align="end" className="w-48 z-30">
{!isAudio && resolutions.length > 0 && (
<>
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
{m.quality()}
</DropdownMenuLabel>
{data.media?.isHls && (
<DropdownMenuItem
onClick={() =>
changeResolution({
resolution: 'Auto',
width: data.media?.metadata?.originalWidth ?? 0,
height: data.media?.metadata?.originalHeight ?? 0,
} as DisplayTranscode)
}
className={cn(
'flex w-full items-center justify-between text-xs cursor-pointer',
state.currentResolution === 'Auto'
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{m.quality_auto()}</span>
</DropdownMenuItem>
)}
{resolutions.map((res) => {
const itemKey = `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
const isSelected =
state.currentResolution === res.resolution &&
Boolean(state.isCurrentHdr) === Boolean(res.hdr)
const isManualDisabled =
Boolean(data.media?.isHls) && state.isHlsManualSupported === false
return (
<DropdownMenuItem
key={itemKey}
disabled={isManualDisabled}
onClick={() => !isManualDisabled && changeResolution(res)}
className={cn(
'flex w-full items-center justify-between text-xs',
isSelected ? 'text-primary font-medium' : 'text-foreground',
isManualDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer',
)}
>
<div className="flex items-center gap-1.5">
<span>
{res.resolution === 'Original' ? m.original() : res.resolution}
</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="text-[10px] text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
)
})}
<DropdownMenuSeparator />
</>
)}
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
{m.format()}
{m.playback_speed()}
</DropdownMenuLabel>
{[0.5, 1, 1.5, 2].map((rate) => (
<DropdownMenuItem
key={rate}
onClick={() => changePlaybackRate(rate)}
className={cn(
'flex items-center justify-between text-xs cursor-pointer',
state.playbackRate === rate ? 'text-primary font-medium' : 'text-foreground',
)}
>
<span>{rate}x</span>
{state.playbackRate === rate && <Check className="h-3.5 w-3.5 text-primary" />}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('standard')}
className="flex items-center justify-between cursor-pointer text-xs"
onClick={toggleLoop}
className="flex items-center justify-between text-xs cursor-pointer"
>
<span>{m.standard_time()}</span>
{videoTimeDisplayMode === 'standard' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('frames')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>{m.frames()}</span>
{videoTimeDisplayMode === 'frames' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('timecode')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>{m.timecode()}</span>
{videoTimeDisplayMode === 'timecode' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
<span className="flex items-center gap-1.5">
<Repeat className="h-3.5 w-3.5" />
<span>{m.loop()}</span>
</span>
{state.isLooping && <Check className="h-3.5 w-3.5 text-primary" />}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Right Side: Settings (Quality + Speed) & Fullscreen */}
<div className="flex items-center gap-1 shrink-0">
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
className="flex items-center gap-1 rounded border border-border px-1.5 py-1 text-xs font-semibold hover:bg-muted transition-colors cursor-pointer"
title={m.settings()}
aria-label={m.settings()}
>
<Settings className="h-3.5 w-3.5" />
<span className="flex items-center gap-1 text-[11px]">
<span>
{!isAudio && state.currentResolution
? state.currentResolution === 'Auto'
? state.activeAutoResolution
? `${m.quality_auto()} (${state.activeAutoResolution})`
: m.quality_auto()
: state.currentResolution === 'Original'
? m.original()
: state.currentResolution
: `${state.playbackRate}x`}
</span>
{!isAudio && state.isCurrentHdr && (
<span className="px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-48 z-30">
{!isAudio && resolutions.length > 0 && (
<>
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
{m.quality()}
</DropdownMenuLabel>
{data.media?.isHls && (
<DropdownMenuItem
onClick={() =>
changeResolution({
resolution: 'Auto',
width: data.media?.metadata?.originalWidth ?? 0,
height: data.media?.metadata?.originalHeight ?? 0,
} as DisplayTranscode)
}
className={cn(
'flex w-full items-center justify-between text-xs cursor-pointer',
state.currentResolution === 'Auto'
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{m.quality_auto()}</span>
</DropdownMenuItem>
)}
{resolutions.map((res) => {
const itemKey = `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
const isSelected =
state.currentResolution === res.resolution &&
Boolean(state.isCurrentHdr) === Boolean(res.hdr)
const isManualDisabled =
Boolean(data.media?.isHls) && state.isHlsManualSupported === false
return (
<DropdownMenuItem
key={itemKey}
disabled={isManualDisabled}
onClick={() => !isManualDisabled && changeResolution(res)}
className={cn(
'flex w-full items-center justify-between text-xs',
isSelected ? 'text-primary font-medium' : 'text-foreground',
isManualDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer',
)}
>
<div className="flex items-center gap-1.5">
<span>
{res.resolution === 'Original' ? m.original() : res.resolution}
</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[9px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="text-[10px] text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
)
})}
<DropdownMenuSeparator />
</>
{/* Fullscreen */}
<button
onClick={toggleFullScreen}
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
title={m.fullscreen()}
aria-label={m.fullscreen()}
>
{state.isFullScreen ? (
<Minimize className="h-5 w-5" />
) : (
<Maximize className="h-5 w-5" />
)}
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
{m.playback_speed()}
</DropdownMenuLabel>
{[0.5, 1, 1.5, 2].map((rate) => (
<DropdownMenuItem
key={rate}
onClick={() => changePlaybackRate(rate)}
className={cn(
'flex items-center justify-between text-xs cursor-pointer',
state.playbackRate === rate ? 'text-primary font-medium' : 'text-foreground',
)}
>
<span>{rate}x</span>
{state.playbackRate === rate && <Check className="h-3.5 w-3.5 text-primary" />}
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={toggleLoop}
className="flex items-center justify-between text-xs cursor-pointer"
>
<span className="flex items-center gap-1.5">
<Repeat className="h-3.5 w-3.5" />
<span>{m.loop()}</span>
</span>
{state.isLooping && <Check className="h-3.5 w-3.5 text-primary" />}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
{/* Fullscreen */}
<button
onClick={toggleFullScreen}
className="p-1 hover:text-primary transition-colors cursor-pointer shrink-0"
title={m.fullscreen()}
aria-label={m.fullscreen()}
>
{state.isFullScreen ? (
<Minimize className="h-5 w-5" />
) : (
<Maximize className="h-5 w-5" />
)}
</button>
</button>
</div>
</div>
</div>
</div>
@@ -47,6 +47,7 @@ export interface PlayerState {
isCurrentHdr?: boolean
activeAutoResolution?: string
isHlsManualSupported?: boolean
isLoading?: boolean
}
export interface DisplayTranscode {
@@ -93,6 +94,7 @@ export interface ControlBarProps {
onMouseLeave?: () => void
/** When false, hides the download affordance. Defaults to true. */
allowDownload?: boolean
isLoading?: boolean
}
export const VideoControlBar: React.FC<ControlBarProps> = ({
@@ -120,7 +122,9 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
onMouseEnter,
onMouseLeave,
allowDownload = true,
isLoading: propIsLoading,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
if (!data.media?.metadata) {
@@ -156,332 +160,341 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
{/* Progress Bar */}
<div className="mb-4 px-1">
<ProgressBar
totalFrames={totalFrames}
currentFrame={currentFrame}
fps={frameRate}
buffered={buffered}
previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame}
metadata={{
...data.media.metadata,
frameRate: frameRate,
}}
/>
</div>
<div
className={cn(
'transition-opacity duration-200',
isLoading && 'pointer-events-none opacity-60 select-none',
)}
>
{/* Progress Bar */}
<div className="mb-4 px-1">
<ProgressBar
totalFrames={totalFrames}
currentFrame={currentFrame}
fps={frameRate}
buffered={buffered}
previewUrl={data.media.videoPreview?.url}
onSeek={seekToFrame}
metadata={{
...data.media.metadata,
frameRate: frameRate,
}}
/>
</div>
{/* Lower Controls Row */}
<div className="flex items-center justify-between text-foreground">
{/* Left Side: Play, Vol, Time */}
<div className="flex items-center gap-4">
<button
onClick={togglePlay}
className="hover:text-primary transition-colors"
data-testid="play-toggle"
data-playing={state.isPlaying}
aria-label={state.isPlaying ? 'Pause' : 'Play'}
>
{state.isPlaying ? (
<Pause className="w-6 h-6 fill-current" />
) : (
<Play className="w-6 h-6 fill-current" />
)}
</button>
<button
onClick={toggleLoop}
className={cn(
'transition-colors',
state.isLooping ? 'text-primary' : 'text-muted-foreground',
)}
title="Loop"
>
<Repeat className="w-5 h-5" />
</button>
<div className="flex items-center gap-3 group/vol">
<button onClick={toggleMute} className="hover:text-primary">
{state.isMuted || state.volume === 0 ? (
<VolumeX className="w-6 h-6" />
{/* Lower Controls Row */}
<div className="flex items-center justify-between text-foreground">
{/* Left Side: Play, Vol, Time */}
<div className="flex items-center gap-4">
<button
onClick={togglePlay}
className="hover:text-primary transition-colors"
data-testid="play-toggle"
data-playing={state.isPlaying}
aria-label={state.isPlaying ? 'Pause' : 'Play'}
>
{state.isPlaying ? (
<Pause className="w-6 h-6 fill-current" />
) : (
<Volume2 className="w-6 h-6" />
<Play className="w-6 h-6 fill-current" />
)}
</button>
<div className="w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out">
<div className="w-24 px-1">
<Slider
value={state.isMuted ? [0] : [state.volume]}
onValueChange={(v: number[]) => handleVolumeChange(v[0])}
max={1}
step={0.05}
/>
<button
onClick={toggleLoop}
className={cn(
'transition-colors',
state.isLooping ? 'text-primary' : 'text-muted-foreground',
)}
title="Loop"
>
<Repeat className="w-5 h-5" />
</button>
<div className="flex items-center gap-3 group/vol">
<button onClick={toggleMute} className="hover:text-primary">
{state.isMuted || state.volume === 0 ? (
<VolumeX className="w-6 h-6" />
) : (
<Volume2 className="w-6 h-6" />
)}
</button>
<div className="w-0 overflow-hidden group-hover/vol:w-24 transition-all duration-300 ease-in-out">
<div className="w-24 px-1">
<Slider
value={state.isMuted ? [0] : [state.volume]}
onValueChange={(v: number[]) => handleVolumeChange(v[0])}
max={1}
step={0.05}
/>
</div>
</div>
</div>
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
<span className="text-muted-foreground font-mono" data-testid="time-readout">
{displayString}
</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
<ChevronDown className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-40 z-30">
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
Format
</DropdownMenuLabel>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('standard')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Standard Time</span>
{videoTimeDisplayMode === 'standard' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('frames')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Frames</span>
{videoTimeDisplayMode === 'frames' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('timecode')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Timecode</span>
{videoTimeDisplayMode === 'timecode' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
<div className="flex items-center gap-1 text-sm font-medium tabular-nums select-none min-w-[100px]">
<span className="text-muted-foreground font-mono" data-testid="time-readout">
{displayString}
</span>
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button className="h-6 w-6 inline-flex items-center justify-center rounded-md hover:bg-muted text-muted-foreground hover:text-foreground transition-colors cursor-pointer focus:outline-none">
<ChevronDown className="h-3.5 w-3.5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="start" className="w-40 z-30">
<DropdownMenuLabel className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider">
Format
</DropdownMenuLabel>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('standard')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Standard Time</span>
{videoTimeDisplayMode === 'standard' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('frames')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Frames</span>
{videoTimeDisplayMode === 'frames' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setVideoTimeDisplayMode('timecode')}
className="flex items-center justify-between cursor-pointer text-xs"
>
<span>Timecode</span>
{videoTimeDisplayMode === 'timecode' && (
<Check className="h-3.5 w-3.5 text-primary" />
)}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
<div className="relative flex items-center gap-3">
{/* Zoom Controls */}
{!isAudio && (
<div className="flex items-center gap-1">
<div className="flex items-center gap-1 rounded-md bg-muted p-0.5">
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
<div className="relative flex items-center gap-3">
{/* Zoom Controls */}
{!isAudio && (
<div className="flex items-center gap-1">
<div className="flex items-center gap-1 rounded-md bg-muted p-0.5">
<button
onClick={() => onZoomChange(zoom * 0.8)}
className="p-1 hover:text-primary rounded"
title={m.zoom_out()}
>
<Minus size={14} />
</button>
<span className="text-xs w-8 text-center tabular-nums">
{Math.round(zoom * 100)}%
</span>
<button
onClick={() => onZoomChange(zoom * 1.2)}
className="p-1 hover:text-primary rounded"
title={m.zoom_in()}
>
<Plus size={14} />
</button>
</div>
<button
onClick={() => onZoomChange(zoom * 0.8)}
className="p-1 hover:text-primary rounded"
title={m.zoom_out()}
onClick={onZoomReset}
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
>
<Minus size={14} />
</button>
<span className="text-xs w-8 text-center tabular-nums">
{Math.round(zoom * 100)}%
</span>
<button
onClick={() => onZoomChange(zoom * 1.2)}
className="p-1 hover:text-primary rounded"
title={m.zoom_in()}
>
<Plus size={14} />
{m.fit()}
</button>
</div>
<button
onClick={onZoomReset}
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
>
{m.fit()}
</button>
</div>
)}
)}
{/* Playback Rate */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="w-8 text-sm font-bold hover:text-primary">
{state.playbackRate}x
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
{[0.5, 1, 1.5, 2].map((rate) => (
<DropdownMenuItem
key={rate}
onClick={() => changePlaybackRate(rate)}
className={cn(
'rounded py-1 px-2 text-left text-xs',
state.playbackRate === rate
? 'bg-primary text-primary-foreground focus:bg-primary focus:text-primary-foreground'
: 'text-foreground',
)}
>
{rate}x
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Settings / Resolution */}
{!isAudio && resolutions.length > 0 && (
{/* Playback Rate */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="flex items-center gap-1.5 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors">
<Settings className="h-3.5 w-3.5" />
<span className="flex items-center gap-1">
<span>
{state.currentResolution === 'Auto'
? state.activeAutoResolution
? `${m.quality_auto()} (${state.activeAutoResolution})`
: m.quality_auto()
: state.currentResolution === 'Original'
? m.original()
: state.currentResolution}
</span>
{state.isCurrentHdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</span>
<button className="w-8 text-sm font-bold hover:text-primary">
{state.playbackRate}x
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>{m.quality()}</DropdownMenuLabel>
{data.media?.isHls && (
{[0.5, 1, 1.5, 2].map((rate) => (
<DropdownMenuItem
onClick={() =>
changeResolution({
resolution: 'Auto',
width: data.media?.metadata?.originalWidth ?? 0,
height: data.media?.metadata?.originalHeight ?? 0,
} as DisplayTranscode)
}
key={rate}
onClick={() => changePlaybackRate(rate)}
className={cn(
'flex w-full items-center justify-between cursor-pointer',
state.currentResolution === 'Auto'
? 'text-primary font-medium'
'rounded py-1 px-2 text-left text-xs',
state.playbackRate === rate
? 'bg-primary text-primary-foreground focus:bg-primary focus:text-primary-foreground'
: 'text-foreground',
)}
>
<span>{m.quality_auto()}</span>
{rate}x
</DropdownMenuItem>
)}
{resolutions.map((res) => {
const itemKey = `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
const isSelected =
state.currentResolution === res.resolution &&
Boolean(state.isCurrentHdr) === Boolean(res.hdr)
const isManualDisabled =
Boolean(data.media?.isHls) && state.isHlsManualSupported === false
return (
<DropdownMenuItem
key={itemKey}
disabled={isManualDisabled}
onClick={() => !isManualDisabled && changeResolution(res)}
className={cn(
'flex w-full items-center justify-between',
isSelected ? 'text-primary font-medium' : 'text-foreground',
isManualDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer',
)}
>
<div className="flex items-center gap-1.5">
<span>{res.resolution === 'Original' ? m.original() : res.resolution}</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
)
})}
))}
</DropdownMenuContent>
</DropdownMenu>
)}
{/* Download */}
{allowDownload &&
(isAudio ? (
<button
onClick={() => handleDownload(data.media?.original?.key || '')}
className="transition-colors hover:text-primary"
title={m.download()}
disabled={!data.media?.original?.key}
>
<Download className="h-5 w-5" />
</button>
) : (
{/* Settings / Resolution */}
{!isAudio && resolutions.length > 0 && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="transition-colors hover:text-primary" title={m.download()}>
<Download className="h-5 w-5" />
<button className="flex items-center gap-1.5 rounded border border-border px-2 py-0.5 text-sm font-semibold hover:bg-muted transition-colors">
<Settings className="h-3.5 w-3.5" />
<span className="flex items-center gap-1">
<span>
{state.currentResolution === 'Auto'
? state.activeAutoResolution
? `${m.quality_auto()} (${state.activeAutoResolution})`
: m.quality_auto()
: state.currentResolution === 'Original'
? m.original()
: state.currentResolution}
</span>
{state.isCurrentHdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>{m.download()}</DropdownMenuLabel>
{(data.media?.videoTranscodes && data.media.videoTranscodes.length > 0
? data.media.videoTranscodes
: resolutions
).map((res) => {
const resLabel = getVideoResolutionLabel(res)
const itemKey = res.key || `${resLabel}-${res.hdr ? 'hdr' : 'sdr'}`
<DropdownMenuLabel>{m.quality()}</DropdownMenuLabel>
{data.media?.isHls && (
<DropdownMenuItem
onClick={() =>
changeResolution({
resolution: 'Auto',
width: data.media?.metadata?.originalWidth ?? 0,
height: data.media?.metadata?.originalHeight ?? 0,
} as DisplayTranscode)
}
className={cn(
'flex w-full items-center justify-between cursor-pointer',
state.currentResolution === 'Auto'
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{m.quality_auto()}</span>
</DropdownMenuItem>
)}
{resolutions.map((res) => {
const itemKey = `${res.resolution}-${res.hdr ? 'hdr' : 'sdr'}`
const isSelected =
state.currentResolution === res.resolution &&
Boolean(state.isCurrentHdr) === Boolean(res.hdr)
const isManualDisabled =
Boolean(data.media?.isHls) && state.isHlsManualSupported === false
return (
<DropdownMenuItem
key={itemKey}
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground cursor-pointer"
disabled={isManualDisabled}
onClick={() => !isManualDisabled && changeResolution(res)}
className={cn(
'flex w-full items-center justify-between',
isSelected ? 'text-primary font-medium' : 'text-foreground',
isManualDisabled ? 'opacity-50 cursor-not-allowed' : 'cursor-pointer',
)}
>
<div className="flex items-center gap-1.5">
<span>{resLabel}</span>
<span>
{res.resolution === 'Original' ? m.original() : res.resolution}
</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="text-xs text-muted-foreground">MP4</span>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
)
})}
{data.media?.original?.key && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleDownload(data.media?.original?.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{m.original()}</span>
<span className="text-xs text-muted-foreground">
{data.name?.split('.').pop()?.toUpperCase() || 'RAW'}
</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
))}
{/* Fullscreen */}
<button
onClick={toggleFullScreen}
className="transition-colors hover:text-primary"
title={m.fullscreen()}
>
{state.isFullScreen ? (
<Minimize className="h-6 w-6" />
) : (
<Maximize className="h-6 w-6" />
)}
</button>
{/* Download */}
{allowDownload &&
(isAudio ? (
<button
onClick={() => handleDownload(data.media?.original?.key || '')}
className="transition-colors hover:text-primary"
title={m.download()}
disabled={!data.media?.original?.key}
>
<Download className="h-5 w-5" />
</button>
) : (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="transition-colors hover:text-primary" title={m.download()}>
<Download className="h-5 w-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>{m.download()}</DropdownMenuLabel>
{(data.media?.videoTranscodes && data.media.videoTranscodes.length > 0
? data.media.videoTranscodes
: resolutions
).map((res) => {
const resLabel = getVideoResolutionLabel(res)
const itemKey = res.key || `${resLabel}-${res.hdr ? 'hdr' : 'sdr'}`
return (
<DropdownMenuItem
key={itemKey}
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground cursor-pointer"
>
<div className="flex items-center gap-1.5">
<span>{resLabel}</span>
{res.hdr && (
<span className="px-1 py-0.2 rounded text-[10px] font-bold bg-amber-500/20 text-amber-500 border border-amber-500/30">
{m.hdr()}
</span>
)}
</div>
<span className="text-xs text-muted-foreground">MP4</span>
</DropdownMenuItem>
)
})}
{data.media?.original?.key && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onClick={() => handleDownload(data.media?.original?.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{m.original()}</span>
<span className="text-xs text-muted-foreground">
{data.name?.split('.').pop()?.toUpperCase() || 'RAW'}
</span>
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
))}
{/* Fullscreen */}
<button
onClick={toggleFullScreen}
className="transition-colors hover:text-primary"
title={m.fullscreen()}
>
{state.isFullScreen ? (
<Minimize className="h-6 w-6" />
) : (
<Maximize className="h-6 w-6" />
)}
</button>
</div>
</div>
</div>
</div>
@@ -566,4 +566,229 @@ describe('VideoViewer', () => {
expect(settingsButton?.textContent).toContain('1080p')
expect(settingsButton?.textContent).not.toContain('1920p')
})
it('sets poster on video element from file.preview.thumbnailUrl', () => {
const videoWithThumb: AssetInfo = {
id: 'video-thumb',
name: 'thumb.mp4',
proxyType: 'video',
preview: {
thumbnailUrl: 'https://cdn.example.com/poster.jpg',
},
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const { container } = render(<VideoViewer file={videoWithThumb} />)
const video = container.querySelector('[data-testid="video-area"] video') as HTMLVideoElement
expect(video.getAttribute('poster')).toBe('https://cdn.example.com/poster.jpg')
})
it('shows loading spinner initially and transitions to play overlay on loadeddata', () => {
const testVideo: AssetInfo = {
id: 'video-loading-test',
name: 'loading.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const { container } = render(<VideoViewer file={testVideo} />)
const video = container.querySelector('[data-testid="video-area"] video') as HTMLVideoElement
// 1. Initially loading spinner is visible, play overlay is not
expect(container.querySelector('[data-testid="video-loading-spinner"]')).not.toBeNull()
expect(container.querySelector('[data-testid="video-play-overlay"]')).toBeNull()
// 2. Control bar inner wrapper is dimmed & non-interactive
const controlBarWrapper = container.querySelector('.pointer-events-none.opacity-60')
expect(controlBarWrapper).not.toBeNull()
// 3. Dispatch loadeddata
act(() => {
video.dispatchEvent(new Event('loadeddata'))
})
// Spinner is gone, play overlay is visible, controls are interactive
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
expect(container.querySelector('[data-testid="video-play-overlay"]')).not.toBeNull()
expect(container.querySelector('.pointer-events-none.opacity-60')).toBeNull()
})
it('debounces waiting stall with 200ms delay and cancels spinner on quick recovery', () => {
vi.useFakeTimers()
try {
const testVideo: AssetInfo = {
id: 'video-stall-test',
name: 'stall.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const { container } = render(<VideoViewer file={testVideo} />)
const video = container.querySelector('[data-testid="video-area"] video') as HTMLVideoElement
// Become ready first
act(() => {
video.dispatchEvent(new Event('loadeddata'))
})
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
// Stalls briefly (<200ms)
act(() => {
video.dispatchEvent(new Event('waiting'))
})
// Immediately after waiting, spinner should NOT be shown yet (debounced)
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
// Recovers quickly at 100ms
act(() => {
vi.advanceTimersByTime(100)
video.dispatchEvent(new Event('playing'))
})
act(() => {
vi.advanceTimersByTime(150)
})
// Spinner still not shown
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
// Now a long stall (>200ms)
act(() => {
video.dispatchEvent(new Event('waiting'))
})
act(() => {
vi.advanceTimersByTime(250)
})
// Spinner should now appear!
expect(container.querySelector('[data-testid="video-loading-spinner"]')).not.toBeNull()
// Resume playing
act(() => {
video.dispatchEvent(new Event('playing'))
})
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
} finally {
vi.useRealTimers()
}
})
it('does not cancel waiting stall debounce when progress events fire during stall', () => {
vi.useFakeTimers()
try {
const testVideo: AssetInfo = {
id: 'video-stall-progress-test',
name: 'stall-progress.mp4',
proxyType: 'video',
media: {
metadata: {
originalWidth: 1920,
originalHeight: 1080,
duration: 10,
frameRate: 30,
totalFrames: 300,
},
videoTranscodes: [
{
resolution: '1080p',
url: 'https://cdn.example.com/video-1080p.mp4',
width: 1920,
height: 1080,
},
],
},
} as unknown as AssetInfo
const { container } = render(<VideoViewer file={testVideo} />)
const video = container.querySelector('[data-testid="video-area"] video') as HTMLVideoElement
// 1. Initial ready state
act(() => {
video.dispatchEvent(new Event('loadeddata'))
})
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
// 2. Play starts (paused === false)
Object.defineProperty(video, 'paused', { value: false, configurable: true, writable: true })
act(() => {
video.dispatchEvent(new Event('playing'))
})
// 3. Stalls: dispatches waiting
act(() => {
video.dispatchEvent(new Event('waiting'))
})
// Spinner not visible immediately (within 200ms debounce)
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
// 4. Progress event fires at 100ms while paused is false (data still trickling in)
act(() => {
vi.advanceTimersByTime(100)
video.dispatchEvent(new Event('progress'))
})
// Should NOT clear debounce or mark loading false
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
// 5. Advance past 200ms debounce (advance remaining 110ms)
act(() => {
vi.advanceTimersByTime(110)
})
// Spinner should now appear despite the progress event!
expect(container.querySelector('[data-testid="video-loading-spinner"]')).not.toBeNull()
// 6. Playback resumes: dispatch playing
act(() => {
video.dispatchEvent(new Event('playing'))
})
// Spinner disappears
expect(container.querySelector('[data-testid="video-loading-spinner"]')).toBeNull()
} finally {
vi.useRealTimers()
}
})
})
@@ -1,6 +1,6 @@
import { client } from '@/ui/api/client'
import { cn } from '@/ui/lib/utils'
import { Play, AudioLines } from 'lucide-react'
import { Play, AudioLines, Loader2 } from 'lucide-react'
import React, { useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react'
import Hls from 'hls.js'
import { useFramePlayer } from './use-frame-player'
@@ -157,7 +157,12 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}))
setActiveAutoResolution(undefined)
setHasManuallyZoomed(false)
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
waitingTimeoutRef.current = null
}
setIsPlayerReady(false)
setIsLoading(true)
setBuffered(0)
lastProcessedStartTimeRef.current = null
setHasStartedPlaying(false)
@@ -250,6 +255,8 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const [buffered, setBuffered] = useState(0)
const [isControlsVisible, setIsControlsVisible] = useState(true)
const [isPlayerReady, setIsPlayerReady] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const waitingTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const lastProcessedStartTimeRef = useRef<number | null>(null)
// Frame-accurate hook and derived state
@@ -285,6 +292,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
progress,
activeAutoResolution,
isHlsManualSupported,
isLoading,
}
// Trigger time update event reactively
@@ -309,7 +317,12 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
hlsRef.current = null
}
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
waitingTimeoutRef.current = null
}
setIsPlayerReady(false)
setIsLoading(true)
setActiveAutoResolution(undefined)
const startAutoPlay = () => {
@@ -339,7 +352,6 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
hls.loadSource(targetSrc)
hls.on(Hls.Events.MANIFEST_PARSED, () => {
setIsPlayerReady(true)
if (autoPlay) {
if (video.readyState >= 2) {
startAutoPlay()
@@ -406,7 +418,17 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}
}
const clearWaitingTimeout = () => {
if (waitingTimeoutRef.current) {
clearTimeout(waitingTimeoutRef.current)
waitingTimeoutRef.current = null
}
}
const handlePlay = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlayerReady(true)
if (pendingResolutionCorrectionRef.current) {
pendingResolutionCorrectionRef.current()
pendingResolutionCorrectionRef.current = null
@@ -420,12 +442,33 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onPause?.()
}
const handleEnded = () => {
clearWaitingTimeout()
setIsLoading(false)
setState((p) => ({ ...p, isPlaying: false }))
}
const handleLoadedMetadata = () => {
const handleLoadedData = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlayerReady(true)
}
const handleCanPlay = () => {
clearWaitingTimeout()
setIsLoading(false)
setIsPlayerReady(true)
}
const handlePlaying = () => {
clearWaitingTimeout()
setIsLoading(false)
}
const handleWaiting = () => {
clearWaitingTimeout()
waitingTimeoutRef.current = setTimeout(() => {
setIsLoading(true)
}, 200)
}
const handleLoadStart = () => {
clearWaitingTimeout()
setIsLoading(true)
setIsPlayerReady(false)
}
const handleProgress = () => {
@@ -461,13 +504,23 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}))
}
const handleError = () => {
clearWaitingTimeout()
setIsLoading(false)
console.error('Video Error:', video.error)
}
if (video.readyState >= 2) {
setIsLoading(false)
setIsPlayerReady(true)
}
video.addEventListener('play', handlePlay)
video.addEventListener('pause', handlePause)
video.addEventListener('ended', handleEnded)
video.addEventListener('loadedmetadata', handleLoadedMetadata)
video.addEventListener('loadeddata', handleLoadedData)
video.addEventListener('canplay', handleCanPlay)
video.addEventListener('playing', handlePlaying)
video.addEventListener('waiting', handleWaiting)
video.addEventListener('loadstart', handleLoadStart)
video.addEventListener('timeupdate', handleProgress)
video.addEventListener('progress', handleProgress)
@@ -480,10 +533,14 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
// Cleanup
return () => {
clearWaitingTimeout()
video.removeEventListener('play', handlePlay)
video.removeEventListener('pause', handlePause)
video.removeEventListener('ended', handleEnded)
video.removeEventListener('loadedmetadata', handleLoadedMetadata)
video.removeEventListener('loadeddata', handleLoadedData)
video.removeEventListener('canplay', handleCanPlay)
video.removeEventListener('playing', handlePlaying)
video.removeEventListener('waiting', handleWaiting)
video.removeEventListener('loadstart', handleLoadStart)
video.removeEventListener('timeupdate', handleProgress)
video.removeEventListener('progress', handleProgress)
@@ -570,6 +627,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
// -- Event Handlers --
const togglePlay = useCallback(() => {
if (isLoading) return
// Disable click-to-play if drawing
if (useAnnotationStore.getState().isDrawing) return
@@ -593,7 +651,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
} else {
video.pause()
}
}, [])
}, [isLoading])
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -949,6 +1007,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
className="w-full h-full block object-contain pointer-events-none"
playsInline
preload="auto"
poster={data.preview?.thumbnailUrl || undefined}
/>
</div>
)}
@@ -996,9 +1055,24 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
)
)}
{/* Loading Spinner Overlay */}
{isLoading && (
<div
className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200"
data-testid="video-loading-spinner"
>
<div className="w-16 h-16 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30">
<Loader2 className="w-8 h-8 text-white animate-spin" />
</div>
</div>
)}
{/* Initial Big Play Button Overlay (shown only before playback starts) */}
{!hasStartedPlaying && !isDrawing && (
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200">
{!isLoading && !hasStartedPlaying && !isDrawing && (
<div
className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10 transition-opacity duration-200"
data-testid="video-play-overlay"
>
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30">
<Play className="w-10 h-10 text-white ml-1 fill-white" />
</div>
@@ -1032,6 +1106,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseEnter={handleControlsMouseEnter}
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
/>
) : (
<VideoControlBar
@@ -1058,6 +1133,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseEnter={handleControlsMouseEnter}
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
/>
)}
</div>