Merge pull request #171 from shumaiOne/feat/compare-versions

feat(webui): compare versions view for version stacks
This commit is contained in:
Yiling-J
2026-07-04 15:38:37 +08:00
committed by GitHub
29 changed files with 2474 additions and 467 deletions
+1
View File
@@ -90,6 +90,7 @@ Add any additional context, caveats, or follow-up work.
- `bun run format`
- `bun run typecheck`
- `bun run test`
- `bun run test:e2e`
- **Backend Testing Mandate**: Every backend feature, service method, workflow, and activity MUST be accompanied by comprehensive tests. Logic-heavy code without corresponding test coverage is considered incomplete.
+28 -3
View File
@@ -23,7 +23,7 @@ import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { AncestorFolder } from '@shumai/dtos'
import { Link, useNavigate } from '@tanstack/react-router'
import { Check, ChevronDown, FileIcon, History, LayoutGrid, List } from 'lucide-react'
import { Check, ChevronDown, Columns2, FileIcon, History, LayoutGrid, List } from 'lucide-react'
interface BreadcrumbNavProps {
teamId: string
@@ -62,6 +62,9 @@ interface BreadcrumbNavProps {
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
}>
compareMode?: boolean
canCompareVersions?: boolean
onCompareVersions?: () => void
}
export function BreadcrumbNav({
@@ -83,12 +86,24 @@ export function BreadcrumbNav({
shareId,
downloadInfo,
versions,
compareMode = false,
canCompareVersions = false,
onCompareVersions,
}: BreadcrumbNavProps) {
const navigate = useNavigate()
const { canEdit } = usePermissions(projectId)
const handleVersionClick = (versionId: string) => {
if (!projectId || !fileId) return
if (!fileId) return
if (isPublic && shareId) {
navigate({
to: '/share/$shareId/files/$fileId',
params: { shareId, fileId },
search: (prev: Record<string, unknown>) => ({ ...prev, version: versionId }),
})
return
}
if (!projectId) return
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId },
@@ -176,7 +191,7 @@ export function BreadcrumbNav({
)}
</div>
))}
{!isRootFolder && (
{!isRootFolder && !compareMode && (
<div className="flex items-center gap-1">
<span className="text-muted-foreground">/</span>
{currentAsset.type === 'folder' ? (
@@ -263,6 +278,16 @@ export function BreadcrumbNav({
</DropdownMenuItem>
)}
{canCompareVersions && onCompareVersions && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem onClick={() => onCompareVersions()}>
<Columns2 className="h-4 w-4" />
<span>{m.compare_versions()}</span>
</DropdownMenuItem>
</>
)}
{versions && versions.length > 0 && (
<>
<DropdownMenuSeparator />
@@ -0,0 +1,128 @@
import { ImageControlBar } from '@/ui/components/viewers/image-control-bar'
import {
VideoControlBar,
type DisplayTranscode,
type PlayerState,
} from '@/ui/components/viewers/video-control-bar'
import type { AssetInfo } from '@shumai/dtos'
import { Maximize, Minimize } from 'lucide-react'
import type { PaneReportedState } from './types'
interface CompareControlBarProps {
activeState: PaneReportedState | null
activeAsset: AssetInfo | null
previewUrl?: string
isFullScreen: boolean
onTogglePlay: () => void
onToggleLoop: () => void
onSeek: (frame: number) => void
onVolumeChange: (volume: number) => void
onToggleMute: () => void
onChangePlaybackRate: (rate: number) => void
onChangeResolution: (resolution: string) => void
onZoomIn: () => void
onZoomOut: () => void
onFit: () => void
onDownload: (key?: string) => void
onToggleFullScreen: () => void
}
export function CompareControlBar({
activeState,
activeAsset,
previewUrl,
isFullScreen,
onTogglePlay,
onToggleLoop,
onSeek,
onVolumeChange,
onToggleMute,
onChangePlaybackRate,
onChangeResolution,
onZoomIn,
onZoomOut,
onFit,
onDownload,
onToggleFullScreen,
}: CompareControlBarProps) {
// Active side is a video: reuse the shared VideoControlBar.
if (activeState?.kind === 'video' && activeState.video && activeAsset) {
const v = activeState.video
const duration = v.totalFrames / v.frameRate
const currentTime = v.currentFrame / v.frameRate
const state: PlayerState = {
isPlaying: v.isPlaying,
progress: duration > 0 ? (currentTime / duration) * 100 : 0,
currentTime,
duration,
volume: v.volume,
isMuted: v.isMuted,
isLooping: v.isLooping,
playbackRate: v.playbackRate,
isFullScreen,
showFrames: false,
currentResolution: v.currentResolution,
}
// The active-side asset carries the metadata used for timecode display and
// preview scrubbing; ensure the preview url is present for the shared bar.
const data =
previewUrl && !activeAsset.media?.videoPreview
? { ...activeAsset, media: { ...activeAsset.media, videoPreview: { url: previewUrl } } }
: activeAsset
return (
<VideoControlBar
state={state}
zoom={activeState.zoom}
isControlsVisible
floatOverlayInFullScreen={false}
buffered={v.buffered}
data={data}
resolutions={v.resolutions as DisplayTranscode[]}
togglePlay={onTogglePlay}
toggleLoop={onToggleLoop}
toggleMute={onToggleMute}
handleVolumeChange={onVolumeChange}
changePlaybackRate={onChangePlaybackRate}
changeResolution={(res) => onChangeResolution(res.resolution)}
handleDownload={(key) => onDownload(key)}
toggleFullScreen={onToggleFullScreen}
onZoomChange={(nz) => (nz >= activeState.zoom ? onZoomIn() : onZoomOut())}
onZoomReset={onFit}
frameRate={v.frameRate}
totalFrames={v.totalFrames}
currentFrame={v.currentFrame}
seekToFrame={onSeek}
/>
)
}
// Active side is an image: reuse the shared ImageControlBar.
if (activeState?.kind === 'image') {
return (
<ImageControlBar
zoom={activeState.zoom}
onZoomIn={onZoomIn}
onZoomOut={onZoomOut}
onFit={onFit}
onDownload={() => onDownload()}
canDownload={!!activeAsset?.media?.original?.key}
fullscreen={{ isFullScreen, onToggle: onToggleFullScreen }}
/>
)
}
// Unsupported / not yet loaded: only expose fullscreen.
return (
<div className="relative z-10 flex items-center justify-end gap-2 border-t border-border bg-card px-4 py-3">
<button
onClick={onToggleFullScreen}
className="text-foreground transition-colors hover:text-primary"
title="Fullscreen"
>
{isFullScreen ? <Minimize className="h-5 w-5" /> : <Maximize className="h-5 w-5" />}
</button>
</div>
)
}
@@ -0,0 +1,218 @@
import { client } from '@/ui/api/client'
import DrawingCanvas from '@/ui/components/drawing-canvas'
import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { getBestTranscode } from '@/ui/lib/media'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { Annotation } from '@/ui/types'
import type { AssetInfo } from '@shumai/dtos'
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import type { ComparePaneHandle, PaneReportedState } from './types'
interface CompareImagePaneProps {
file: AssetInfo
shareId?: string
isActive: boolean
annotations: Annotation[]
onStateChange: (state: PaneReportedState) => void
onUserPan?: (dx: number, dy: number) => void
onActivate?: () => void
}
const MIN_ZOOM = 0.01
const MAX_ZOOM = 50
export const CompareImagePane = forwardRef<ComparePaneHandle, CompareImagePaneProps>(
function CompareImagePane(
{ file, shareId, isActive, annotations, onStateChange, onUserPan, onActivate },
ref,
) {
const { width: screenWidth } = useScreenSize()
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
} = useAnnotationStore()
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const [zoom, setZoom] = useState(1)
const [pan, setPan] = useState({ x: 0, y: 0 })
const observerRef = useRef<ResizeObserver | null>(null)
const zoomRef = useRef(zoom)
zoomRef.current = zoom
const panRef = useRef(pan)
panRef.current = pan
const containerRef = useCallback((node: HTMLDivElement | null) => {
if (observerRef.current) {
observerRef.current.disconnect()
observerRef.current = null
}
if (node !== null) {
const observer = new ResizeObserver((entries) => {
const entry = entries[0]
if (entry) {
setContainerSize({
width: entry.contentRect.width,
height: entry.contentRect.height,
})
}
})
observer.observe(node)
observerRef.current = observer
}
}, [])
const imgW = file.media?.metadata?.originalWidth ?? 1920
const imgH = file.media?.metadata?.originalHeight ?? 1080
const conW = containerSize.width
const conH = containerSize.height
let baseScale = 1
if (conW > 0 && conH > 0) {
baseScale = Math.min(conW / imgW, conH / imgH)
}
// Fit on mount / container resize / file change
useEffect(() => {
if (conW > 0 && conH > 0) {
setZoom(baseScale)
setPan({
x: (conW - imgW * baseScale) / 2,
y: (conH - imgH * baseScale) / 2,
})
}
}, [file.id, conW, conH, baseScale, imgW, imgH])
const applyZoom = useCallback(
(factor: number) => {
const cx = conW / 2
const cy = conH / 2
const cur = zoomRef.current
const newZoom = cur * factor
if (newZoom < MIN_ZOOM || newZoom > MAX_ZOOM) return
const curPan = panRef.current
setPan({
x: cx - (cx - curPan.x) * (newZoom / cur),
y: cy - (cy - curPan.y) * (newZoom / cur),
})
setZoom(newZoom)
},
[conW, conH],
)
const fit = useCallback(() => {
setZoom(baseScale)
setPan({
x: (conW - imgW * baseScale) / 2,
y: (conH - imgH * baseScale) / 2,
})
}, [baseScale, conW, conH, imgW, imgH])
let bestUrl = file.media?.original?.downloadUrl
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
if (bestTranscode?.url) {
bestUrl = bestTranscode.url
}
const handleDownload = useCallback(async () => {
const key = file.media?.original?.key
if (!key || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key },
})
: await client.api.files['download-url'].$post({
json: { key, assetId: file.id },
})
if (!res.ok) return
const { url } = await res.json()
const link = document.createElement('a')
link.href = url
link.download = ''
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// silently fail
}
}, [file.id, file.media?.original?.key, shareId])
useImperativeHandle(
ref,
(): ComparePaneHandle => ({
getKind: () => 'image',
play: () => {},
pause: () => {},
togglePlay: () => {},
seekToFrame: () => {},
seekToSecond: () => {},
stepFrame: () => {},
setMuted: () => {},
setVolume: () => {},
setPlaybackRate: () => {},
toggleLoop: () => {},
changeResolution: () => {},
zoomBy: (factor) => applyZoom(factor),
fit,
panBy: (dx, dy) => setPan((p) => ({ x: p.x + dx, y: p.y + dy })),
download: handleDownload,
}),
[applyZoom, fit, handleDownload],
)
// Report state upward
useEffect(() => {
onStateChange({ kind: 'image', zoom })
}, [zoom, onStateChange])
const displayAnnotations = [...annotations, ...(isActive ? draftAnnotations : [])]
const handlePan = useCallback(
(newOffset: { x: number; y: number }) => {
const prev = panRef.current
const dx = newOffset.x - prev.x
const dy = newOffset.y - prev.y
setPan(newOffset)
if (dx !== 0 || dy !== 0) onUserPan?.(dx, dy)
},
[onUserPan],
)
if (!bestUrl) {
return (
<div className="flex flex-1 items-center justify-center bg-gray-100 dark:bg-gray-950">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
)
}
return (
<div
ref={containerRef}
className="relative flex-1 overflow-hidden bg-gray-100 dark:bg-gray-950"
onMouseDown={onActivate}
>
<DrawingCanvas
width={conW}
height={conH}
mediaDimensions={{ width: imgW, height: imgH }}
imageUrl={bestUrl}
annotations={displayAnnotations}
scale={zoom}
offset={pan}
onPan={handlePan}
className="absolute inset-0 z-0"
isDrawing={isActive && isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={isActive ? addAnnotation : undefined}
/>
</div>
)
},
)
@@ -0,0 +1,150 @@
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/ui/components/ui/dropdown-menu'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { Check, ChevronDown, FileIcon, X } from 'lucide-react'
import type { CompareSide } from './types'
interface VersionItem {
id: string
version: number
name?: string | null
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
}
interface ComparePaneTopbarProps {
side: CompareSide
fileName: string
version?: number
activeVersionId: string
versions: VersionItem[]
isActive: boolean
onActivate: () => void
onSwitchVersion: (versionId: string) => void
onExit: () => void
}
export function ComparePaneTopbar({
side,
fileName,
version,
activeVersionId,
versions,
isActive,
onActivate,
onSwitchVersion,
onExit,
}: ComparePaneTopbarProps) {
const iconButtonClass = cn(
'flex-shrink-0 rounded p-1 transition-colors hover:bg-muted',
isActive ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
)
const exitButton = (
<button onClick={onExit} title={m.exit_compare()} className={iconButtonClass}>
<X className="h-4 w-4" />
</button>
)
const label = (
<button
onClick={onActivate}
className={cn(
'flex min-w-0 items-center gap-1 rounded px-2 py-1 text-sm font-medium transition-colors hover:bg-muted',
isActive ? 'text-foreground' : 'text-muted-foreground hover:text-foreground',
)}
>
<span className="truncate">{fileName}</span>
{version !== undefined && (
<span
className={cn(
'flex-shrink-0 rounded border px-1 py-0 text-xs',
isActive ? 'border-foreground/40' : 'border-border',
)}
>
v{version}
</span>
)}
</button>
)
const versionDropdown = (
<DropdownMenu>
<DropdownMenuTrigger
onClick={onActivate}
title={m.switch_version()}
className={iconButtonClass}
>
<ChevronDown className="h-4 w-4" />
</DropdownMenuTrigger>
<DropdownMenuContent align={side === 'left' ? 'start' : 'end'} className="w-80 p-1">
<div className="flex max-h-96 flex-col gap-1 overflow-y-auto">
{versions.map((v) => {
const isCurrent = v.id === activeVersionId
return (
<DropdownMenuItem
key={v.id}
onClick={() => onSwitchVersion(v.id)}
className="flex cursor-pointer items-center gap-3 rounded-md px-3 py-2"
>
<div className="flex min-w-[2rem] flex-shrink-0 items-center justify-center rounded-full bg-muted px-2 py-0.5 text-xs font-semibold text-muted-foreground select-none">
v{v.version}
</div>
<div className="flex h-10 w-16 flex-shrink-0 items-center justify-center overflow-hidden rounded-md border border-border bg-muted">
{v.previewUrl ? (
<img
src={v.previewUrl}
alt={v.name || undefined}
className="h-full w-full object-cover"
/>
) : (
<FileIcon className="h-4 w-4 text-muted-foreground" />
)}
</div>
<div className="flex min-w-0 flex-1 flex-col text-left">
<span className="truncate text-sm font-semibold text-foreground">{v.name}</span>
<span className="truncate text-xs text-muted-foreground">
{v.creator?.name || 'Unknown'}
</span>
</div>
{isCurrent && <Check className="ml-auto h-4 w-4 flex-shrink-0 text-primary" />}
</DropdownMenuItem>
)
})}
</div>
</DropdownMenuContent>
</DropdownMenu>
)
return (
<div
onMouseDown={onActivate}
className={cn(
// Force the dark palette so the bar is always dark with light text in
// both light and dark app themes, using system tokens (no hardcoded hex).
'dark flex h-10 flex-shrink-0 items-center gap-1 border-b bg-background px-2 transition-colors',
isActive ? 'border-b-2 border-primary' : 'border-border',
)}
>
{side === 'left' ? (
<>
{exitButton}
{label}
{versionDropdown}
</>
) : (
<>
{label}
{versionDropdown}
<div className="ml-auto" />
{exitButton}
</>
)}
</div>
)
}
@@ -0,0 +1,82 @@
import { describe, it, expect } from 'vitest'
import { kindOf, pickDefaultCompareVersions, clampFrame, isSameType } from './compare-utils'
describe('compare-utils', () => {
describe('kindOf', () => {
it('classifies image media types', () => {
expect(kindOf('image/png')).toBe('image')
expect(kindOf('image/webp')).toBe('image')
})
it('classifies video media types', () => {
expect(kindOf('video/mp4')).toBe('video')
expect(kindOf('video/quicktime')).toBe('video')
})
it('returns unsupported for missing or unknown types', () => {
expect(kindOf(null)).toBe('unsupported')
expect(kindOf(undefined)).toBe('unsupported')
expect(kindOf('application/pdf')).toBe('unsupported')
})
})
describe('pickDefaultCompareVersions', () => {
it('picks latest and latest-1 regardless of input order', () => {
const versions = [
{ id: 'a', version: 1 },
{ id: 'c', version: 3 },
{ id: 'b', version: 2 },
]
const pair = pickDefaultCompareVersions(versions)
expect(pair).not.toBeNull()
expect(pair!.left.id).toBe('c') // v3 (latest)
expect(pair!.right.id).toBe('b') // v2 (latest - 1)
})
it('returns null when fewer than two versions', () => {
expect(pickDefaultCompareVersions([{ id: 'a', version: 1 }])).toBeNull()
expect(pickDefaultCompareVersions([])).toBeNull()
expect(pickDefaultCompareVersions(undefined)).toBeNull()
expect(pickDefaultCompareVersions(null)).toBeNull()
})
it('does not mutate the input array', () => {
const versions = [
{ id: 'a', version: 1 },
{ id: 'b', version: 2 },
]
pickDefaultCompareVersions(versions)
expect(versions.map((v) => v.id)).toEqual(['a', 'b'])
})
})
describe('clampFrame', () => {
it('clamps to the last frame when beyond total (shorter side holds last frame)', () => {
expect(clampFrame(500, 100)).toBe(99)
})
it('clamps negative frames to zero', () => {
expect(clampFrame(-5, 100)).toBe(0)
})
it('passes through in-range frames', () => {
expect(clampFrame(42, 100)).toBe(42)
})
it('handles zero-length safely', () => {
expect(clampFrame(10, 0)).toBe(0)
})
})
describe('isSameType', () => {
it('true only for matching, supported kinds', () => {
expect(isSameType('video', 'video')).toBe(true)
expect(isSameType('image', 'image')).toBe(true)
})
it('false for mismatched or unsupported kinds', () => {
expect(isSameType('video', 'image')).toBe(false)
expect(isSameType('unsupported', 'unsupported')).toBe(false)
})
})
})
@@ -0,0 +1,37 @@
import type { PaneKind } from './types'
/** Classify an asset's media type into a compare pane kind. */
export function kindOf(mediaType: string | null | undefined): PaneKind {
if (!mediaType) return 'unsupported'
if (mediaType.startsWith('image/')) return 'image'
if (mediaType.startsWith('video/')) return 'video'
return 'unsupported'
}
interface VersionLike {
id: string
version: number
}
/**
* Given a version stack's versions, pick the default compare pair:
* left = latest (highest version number), right = latest - 1.
* Returns null if fewer than two versions exist.
*/
export function pickDefaultCompareVersions(
versions: ReadonlyArray<VersionLike> | undefined | null,
): { left: VersionLike; right: VersionLike } | null {
if (!versions || versions.length < 2) return null
const sorted = [...versions].sort((a, b) => b.version - a.version)
return { left: sorted[0], right: sorted[1] }
}
/** Clamp a frame index into the valid range [0, totalFrames - 1]. */
export function clampFrame(frame: number, totalFrames: number): number {
return Math.max(0, Math.min(frame, Math.max(0, totalFrames - 1)))
}
/** True when both panes hold the same (non-unsupported) media kind. */
export function isSameType(left: PaneKind, right: PaneKind): boolean {
return left === right && left !== 'unsupported'
}
@@ -0,0 +1,474 @@
import { client } from '@/ui/api/client'
import DrawingCanvas from '@/ui/components/drawing-canvas'
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 } from 'lucide-react'
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'
import videojs from 'video.js'
import type Player from 'video.js/dist/types/player'
import { useFramePlayer } from '@/ui/components/viewers/use-frame-player'
import { clampFrame as clampFrameUtil } from './compare-utils'
import type { ComparePaneHandle, DisplayTranscode, PaneReportedState } from './types'
interface CompareVideoPaneProps {
file: AssetInfo
shareId?: string
isActive: boolean
/** Whether this pane's audio should be muted (only the active side plays audio). */
muted: boolean
volume: number
annotations: Annotation[]
onStateChange: (state: PaneReportedState) => void
onActivate?: () => void
onRequestTogglePlay?: () => void
/** Called with the current playhead time in seconds (used only for the active pane). */
onTimeUpdate?: (second: number) => void
onPlay?: () => void
}
function computeResolutions(file: AssetInfo): DisplayTranscode[] {
const original: DisplayTranscode | null = file.media?.original?.downloadUrl
? {
id: 'original',
url: file.media.original.downloadUrl,
key: file.media.original.key ?? '',
width: file.media?.metadata?.originalWidth ?? 0,
height: file.media?.metadata?.originalHeight ?? 0,
size: 0,
isRaw: true,
resolution: 'Original',
}
: null
const transcodes: DisplayTranscode[] = (file.media?.videoTranscodes ?? []).map((t) => {
const longSide = Math.max(t.width, t.height)
let resolution = `${t.height}p`
if (longSide >= 3840) resolution = '2160p'
else if (longSide >= 1920) resolution = '1080p'
else if (longSide >= 1280) resolution = '720p'
else if (longSide >= 960) resolution = '540p'
else if (longSide >= 640) resolution = '360p'
else if (longSide >= 320) resolution = '180p'
return { ...t, resolution: t.isRaw ? 'Original' : resolution }
})
const hasOriginalTranscode = transcodes.some((t) => t.isRaw)
if (!hasOriginalTranscode && original) {
return [...transcodes, original]
}
return transcodes
}
export const CompareVideoPane = forwardRef<ComparePaneHandle, CompareVideoPaneProps>(
function CompareVideoPane(
{
file,
shareId,
isActive,
muted,
volume,
annotations,
onStateChange,
onActivate,
onRequestTogglePlay,
onTimeUpdate,
onPlay,
},
ref,
) {
const playerRef = useRef<Player | null>(null)
const videoContainerRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const videoRef = useRef<HTMLVideoElement | null>(null)
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
const {
isDrawing,
currentTool,
currentColor,
addAnnotation,
annotations: draftAnnotations,
} = useAnnotationStore()
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
const [zoom, setZoom] = useState(1)
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
const [pan, setPan] = useState<{ x: number; y: number } | null>(null)
const [isPlaying, setIsPlaying] = useState(false)
const [isLooping, setIsLooping] = useState(false)
const [playbackRate, setPlaybackRate] = useState(1)
const [buffered, setBuffered] = useState(0)
const [playerVolume, setPlayerVolume] = useState(volume)
const [playerMuted, setPlayerMuted] = useState(muted)
const [isPlayerReady, setIsPlayerReady] = useState(false)
const metadata = file.media?.metadata
const frameRate = metadata?.frameRate || 30
const dbTotalFrames = metadata?.totalFrames || 0
const containerDuration = metadata?.duration || 0
const videoDuration = dbTotalFrames / frameRate
const frameDuration = 1 / frameRate
const totalFrames =
containerDuration - videoDuration > 0.5 * frameDuration
? Math.round(containerDuration * frameRate)
: dbTotalFrames
const resolutions = computeResolutions(file)
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const initialRes = previewResolutions[0] ?? resolutions[0]
const [currentResolution, setCurrentResolution] = useState(initialRes?.resolution ?? 'Original')
const currentSrcRef = useRef(initialRes?.url)
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
const zoomRef = useRef(zoom)
zoomRef.current = zoom
const currentFrameRef = useRef(currentFrame)
currentFrameRef.current = currentFrame
// 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()
}, [])
const vidW = metadata?.originalWidth ?? 1920
const vidH = metadata?.originalHeight ?? 1080
// Auto-fit zoom
useEffect(() => {
if (containerSize.width > 0 && containerSize.height > 0 && !hasManuallyZoomed) {
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
setZoom(scale)
}
}, [containerSize.width, containerSize.height, vidW, vidH, hasManuallyZoomed])
// Keep the resolution selection and source url in sync when the displayed
// asset changes, so the player (re)initializes with the correct source even
// if the parent renders this pane without a per-asset `key`. Runs before the
// video.js init effect below (declaration order) so the ref is fresh.
useEffect(() => {
setCurrentResolution(initialRes?.resolution ?? 'Original')
currentSrcRef.current = initialRes?.url
}, [file.id])
// Initialize video.js
useEffect(() => {
if (!videoContainerRef.current) return
const videoElement = document.createElement('video-js')
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
videoElement.style.opacity = '0'
videoElement.style.pointerEvents = 'none'
videoContainerRef.current.appendChild(videoElement)
const player = (playerRef.current = videojs(videoElement, {
controls: false,
autoplay: false,
preload: 'auto',
playsinline: true,
sources: [{ src: currentSrcRef.current ?? '', type: 'video/mp4' }],
}))
const htmlVid = videoElement.querySelector('video')
if (htmlVid) {
setVideoHtmlEl(htmlVid)
videoRef.current = htmlVid
} else {
player.ready(() => {
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
if (techEl) {
setVideoHtmlEl(techEl)
videoRef.current = techEl
}
})
}
player.on('play', () => {
setIsPlaying(true)
onPlay?.()
})
player.on('pause', () => setIsPlaying(false))
player.on('ended', () => setIsPlaying(false))
player.on('loadedmetadata', () => setIsPlayerReady(true))
player.on('loadstart', () => setIsPlayerReady(false))
player.on('timeupdate', () => {
const playerDuration = player.duration() || containerDuration || 0
const bufferedEnd = player.bufferedEnd()
if (playerDuration > 0) setBuffered((bufferedEnd / playerDuration) * 100)
})
player.on('volumechange', () => {
setPlayerVolume(player.volume() || 0)
setPlayerMuted(player.muted() || false)
})
player.on('ratechange', () => setPlaybackRate(player.playbackRate() || 1))
return () => {
if (player && !player.isDisposed()) {
player.dispose()
playerRef.current = null
videoRef.current = null
}
}
}, [file.id])
// Apply muted / volume (audio routing: only active side unmuted)
useEffect(() => {
const player = playerRef.current
if (!player || !isPlayerReady) return
player.muted(muted)
player.volume(volume)
}, [muted, volume, isPlayerReady])
// Report state upward
useEffect(() => {
const state: PaneReportedState = {
kind: 'video',
zoom,
video: {
frameRate,
totalFrames,
currentFrame,
isPlaying,
volume: playerVolume,
isMuted: playerMuted,
playbackRate,
isLooping,
currentResolution,
resolutions,
buffered,
},
}
onStateChange(state)
}, [
zoom,
frameRate,
totalFrames,
currentFrame,
isPlaying,
playerVolume,
playerMuted,
playbackRate,
isLooping,
currentResolution,
buffered,
])
// Propagate active playhead time
useEffect(() => {
if (isActive) onTimeUpdate?.(currentFrame / frameRate)
}, [currentFrame, frameRate, isActive, onTimeUpdate])
const applyZoom = useCallback((factor: number) => {
const cur = zoomRef.current
const newZoom = cur * factor
if (newZoom < 0.01 || newZoom > 50) return
setZoom(newZoom)
setHasManuallyZoomed(true)
}, [])
const fit = useCallback(() => {
setHasManuallyZoomed(false)
setPan(null)
}, [])
const clampFrame = useCallback(
(frame: number) => clampFrameUtil(frame, totalFrames),
[totalFrames],
)
const handleDownload = useCallback(
async (key?: string) => {
const dlKey = key ?? file.media?.original?.key
if (!dlKey || !file.id) return
try {
const res = shareId
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
param: { shareId, fileId: file.id },
json: { key: dlKey },
})
: await client.api.files['download-url'].$post({
json: { key: dlKey, assetId: file.id },
})
if (!res.ok) return
const { url } = await res.json()
const link = document.createElement('a')
link.href = url
link.download = ''
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
} catch {
// silently fail
}
},
[file.id, file.media?.original?.key, shareId],
)
const changeResolution = useCallback(
(resolution: string) => {
const player = playerRef.current
if (!player) return
const target = resolutions.find((r) => r.resolution === resolution)
if (!target) return
const wasPlaying = !player.paused()
const currentT = player.currentTime()
setCurrentResolution(resolution)
currentSrcRef.current = target.url
player.src({ type: 'video/mp4', src: target.url })
player.one('loadedmetadata', () => {
player.currentTime(currentT)
if (wasPlaying) {
const p = player.play()
if (p !== undefined) p.catch(() => {})
}
})
},
[resolutions],
)
useImperativeHandle(
ref,
(): ComparePaneHandle => ({
getKind: () => 'video',
play: () => {
const p = playerRef.current?.play()
if (p !== undefined) p.catch(() => {})
},
pause: () => playerRef.current?.pause(),
togglePlay: () => {
const player = playerRef.current
if (!player) return
if (player.paused() || player.ended()) {
const p = player.play()
if (p !== undefined) p.catch(() => {})
} else {
player.pause()
}
},
seekToFrame: (frame) => seekToFrame(clampFrame(frame)),
seekToSecond: (second) => {
const frame = Math.floor(second * frameRate + 0.45)
seekToFrame(clampFrame(frame))
},
stepFrame: (delta) => seekToFrame(clampFrame(currentFrameRef.current + delta)),
setMuted: (m) => playerRef.current?.muted(m),
setVolume: (v) => {
const player = playerRef.current
if (!player) return
player.volume(v)
if (v > 0 && player.muted()) player.muted(false)
else if (v === 0 && !player.muted()) player.muted(true)
},
setPlaybackRate: (rate) => playerRef.current?.playbackRate(rate),
toggleLoop: () => {
const player = playerRef.current
if (!player) return
const next = !player.loop()
player.loop(next)
setIsLooping(next)
},
changeResolution,
zoomBy: applyZoom,
fit,
panBy: (dx, dy) =>
setPan((p) => {
const scale = zoomRef.current
const base = p ?? {
x: (containerSize.width - vidW * scale) / 2,
y: (containerSize.height - vidH * scale) / 2,
}
return { x: base.x + dx, y: base.y + dy }
}),
download: (key?: string) => handleDownload(key),
}),
[
seekToFrame,
clampFrame,
frameRate,
applyZoom,
fit,
changeResolution,
handleDownload,
containerSize.width,
containerSize.height,
vidW,
vidH,
],
)
const displayAnnotations = [...annotations, ...(isActive ? draftAnnotations : [])]
const scale = zoom
const defaultPanX = (containerSize.width - vidW * scale) / 2
const defaultPanY = (containerSize.height - vidH * scale) / 2
const panX = pan?.x ?? defaultPanX
const panY = pan?.y ?? defaultPanY
const handleAreaClick = useCallback(() => {
if (useAnnotationStore.getState().isDrawing) return
// Clicking an inactive pane only activates it; playback is untouched.
if (!isActive) {
onActivate?.()
return
}
onRequestTogglePlay?.()
}, [isActive, onActivate, onRequestTogglePlay])
if (!file.media?.original?.downloadUrl || !metadata) {
return (
<div className="flex h-full w-full items-center justify-center bg-black">
<p className="text-muted-foreground">Media is not available.</p>
</div>
)
}
return (
<div
ref={containerRef}
className={cn(
'relative flex flex-1 cursor-pointer items-center justify-center overflow-hidden bg-black',
)}
onClick={handleAreaClick}
data-testid="compare-video-area"
>
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
{videoHtmlEl && containerSize.width > 0 && (
<DrawingCanvas
width={containerSize.width}
height={containerSize.height}
mediaDimensions={{ width: vidW, height: vidH }}
videoElement={videoHtmlEl}
annotations={displayAnnotations}
scale={scale}
offset={{ x: panX, y: panY }}
className="absolute inset-0"
onClick={handleAreaClick}
isDrawing={isActive && isDrawing}
currentTool={currentTool}
currentColor={currentColor}
onAddAnnotation={isActive ? addAnnotation : undefined}
/>
)}
{!isPlaying && !isDrawing && (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/20">
<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>
</div>
)}
</div>
)
},
)
@@ -0,0 +1,355 @@
import { client } from '@/ui/api/client'
import type { Annotation } from '@/ui/types'
import type { AssetInfo } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import { Loader2 } from 'lucide-react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { CompareControlBar } from './compare-control-bar'
import { CompareImagePane } from './compare-image-pane'
import { ComparePaneTopbar } from './compare-pane-topbar'
import { isSameType, kindOf } from './compare-utils'
import { CompareVideoPane } from './compare-video-pane'
import type { ComparePaneHandle, CompareSide, PaneKind, PaneReportedState } from './types'
interface VersionItem {
id: string
version: number
name?: string | null
previewUrl?: string | null
creator?: { id: string; name: string | null } | null
}
interface CompareViewerProps {
isPublic?: boolean
shareId?: string
versions: VersionItem[]
leftId: string
rightId: string
activeSide: CompareSide
annotations: Annotation[]
/** Bumped nonce requests the active pane seek to `second` (comment navigation). */
seekRequest?: { second: number; nonce: number }
onActiveSideChange: (side: CompareSide) => void
onSwitchVersion: (side: CompareSide, versionId: string) => void
onExit: () => void
onActiveAssetChange: (asset: AssetInfo | null) => void
onPlay?: () => void
onTimeUpdate?: (second: number) => void
}
function useCompareAsset(id: string, isPublic: boolean, shareId?: string) {
return useQuery({
queryKey: isPublic
? ['public-share-file', shareId, id, localStorage.getItem(`share_pwd_${shareId}`) || '']
: ['files', id],
queryFn: async () => {
if (isPublic) {
const password = localStorage.getItem(`share_pwd_${shareId}`) || ''
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
{ param: { shareId: shareId!, fileId: id } },
{ headers: { 'x-share-password': password } },
)
if (!res.ok) throw new Error('Failed to fetch version asset')
return (await res.json()) as unknown as AssetInfo
}
const res = await client.api.files[':fileId'].$get({ param: { fileId: id } })
if (!res.ok) throw new Error('Failed to fetch version asset')
return (await res.json()) as unknown as AssetInfo
},
enabled: !!id && (!isPublic || !!shareId),
})
}
export function CompareViewer({
isPublic = false,
shareId,
versions,
leftId,
rightId,
activeSide,
annotations,
seekRequest,
onActiveSideChange,
onSwitchVersion,
onExit,
onActiveAssetChange,
onPlay,
onTimeUpdate,
}: CompareViewerProps) {
const rootRef = useRef<HTMLDivElement>(null)
const leftRef = useRef<ComparePaneHandle | null>(null)
const rightRef = useRef<ComparePaneHandle | null>(null)
const [leftState, setLeftState] = useState<PaneReportedState | null>(null)
const [rightState, setRightState] = useState<PaneReportedState | null>(null)
const [userVolume, setUserVolume] = useState(1)
const [userMuted, setUserMuted] = useState(false)
const [isFullScreen, setIsFullScreen] = useState(false)
const { data: leftAsset, isLoading: leftLoading } = useCompareAsset(leftId, isPublic, shareId)
const { data: rightAsset, isLoading: rightLoading } = useCompareAsset(rightId, isPublic, shareId)
const leftKind = kindOf(leftAsset?.mediaType)
const rightKind = kindOf(rightAsset?.mediaType)
const sameType = isSameType(leftKind, rightKind)
const activeAsset = activeSide === 'left' ? leftAsset : rightAsset
const activeState = activeSide === 'left' ? leftState : rightState
const getActive = useCallback(
() => (activeSide === 'left' ? leftRef.current : rightRef.current),
[activeSide],
)
const getOther = useCallback(
() => (activeSide === 'left' ? rightRef.current : leftRef.current),
[activeSide],
)
// Bind right sidebar to active asset
useEffect(() => {
onActiveAssetChange(activeAsset ?? null)
}, [activeAsset, onActiveAssetChange])
// Comment-driven seek on the active pane
useEffect(() => {
if (!seekRequest) return
const active = getActive()
active?.seekToSecond(seekRequest.second)
active?.pause()
if (sameType) {
const other = getOther()
other?.seekToSecond(seekRequest.second)
other?.pause()
}
}, [seekRequest?.nonce])
// Fullscreen tracking
useEffect(() => {
const onFs = () => setIsFullScreen(!!document.fullscreenElement)
document.addEventListener('fullscreenchange', onFs)
return () => document.removeEventListener('fullscreenchange', onFs)
}, [])
const handleStateChangeLeft = useCallback((s: PaneReportedState) => setLeftState(s), [])
const handleStateChangeRight = useCallback((s: PaneReportedState) => setRightState(s), [])
const applyBoth = useCallback(
(fn: (h: ComparePaneHandle) => void) => {
const active = getActive()
if (active) fn(active)
if (sameType) {
const other = getOther()
if (other) fn(other)
}
},
[getActive, getOther, sameType],
)
// --- Control handlers ---
const handleTogglePlay = useCallback(() => {
const shouldPlay = !activeState?.video?.isPlaying
applyBoth((h) => (shouldPlay ? h.play() : h.pause()))
}, [activeState?.video?.isPlaying, applyBoth])
const handleSeek = useCallback(
(frame: number) => applyBoth((h) => h.seekToFrame(frame)),
[applyBoth],
)
const handleToggleLoop = useCallback(() => getActive()?.toggleLoop(), [getActive])
const handleVolumeChange = useCallback((v: number) => {
setUserVolume(v)
setUserMuted(v === 0)
}, [])
const handleToggleMute = useCallback(() => setUserMuted((m) => !m), [])
const handlePlaybackRate = useCallback(
(rate: number) => applyBoth((h) => h.setPlaybackRate(rate)),
[applyBoth],
)
const handleChangeResolution = useCallback(
(resolution: string) => getActive()?.changeResolution(resolution),
[getActive],
)
const handleZoomIn = useCallback(() => applyBoth((h) => h.zoomBy(1.2)), [applyBoth])
const handleZoomOut = useCallback(() => applyBoth((h) => h.zoomBy(0.8)), [applyBoth])
const handleFit = useCallback(() => applyBoth((h) => h.fit()), [applyBoth])
const handleDownload = useCallback(
(key?: string) => {
getActive()?.download(key)
},
[getActive],
)
const handleToggleFullScreen = useCallback(() => {
if (!rootRef.current) return
if (!document.fullscreenElement) {
rootRef.current.requestFullscreen()
} else {
document.exitFullscreen()
}
}, [])
const handleUserPanLeft = useCallback(
(dx: number, dy: number) => {
if (sameType) rightRef.current?.panBy(dx, dy)
},
[sameType],
)
const handleUserPanRight = useCallback(
(dx: number, dy: number) => {
if (sameType) leftRef.current?.panBy(dx, dy)
},
[sameType],
)
const handleRequestTogglePlay = useCallback(() => handleTogglePlay(), [handleTogglePlay])
const versionOf = useCallback(
(id: string) => versions.find((v) => v.id === id)?.version,
[versions],
)
const activePreviewUrl = useMemo(
() => activeAsset?.media?.videoPreview?.url,
[activeAsset?.media?.videoPreview?.url],
)
const renderPane = (side: CompareSide, asset: AssetInfo, kind: PaneKind) => {
const isActive = activeSide === side
const paneRef = side === 'left' ? leftRef : rightRef
const onStateChange = side === 'left' ? handleStateChangeLeft : handleStateChangeRight
const onUserPan = side === 'left' ? handleUserPanLeft : handleUserPanRight
const paneAnnotations = isActive ? annotations : []
if (kind === 'video') {
return (
<CompareVideoPane
key={asset.id}
ref={paneRef}
file={asset}
shareId={shareId}
isActive={isActive}
muted={isActive ? userMuted : true}
volume={userVolume}
annotations={paneAnnotations}
onStateChange={onStateChange}
onActivate={() => onActiveSideChange(side)}
onRequestTogglePlay={handleRequestTogglePlay}
onTimeUpdate={onTimeUpdate}
onPlay={onPlay}
/>
)
}
if (kind === 'image') {
return (
<CompareImagePane
key={asset.id}
ref={paneRef}
file={asset}
shareId={shareId}
isActive={isActive}
annotations={paneAnnotations}
onStateChange={onStateChange}
onUserPan={onUserPan}
onActivate={() => onActiveSideChange(side)}
/>
)
}
return (
<div className="flex flex-1 items-center justify-center bg-gray-100 dark:bg-gray-950">
<p className="text-muted-foreground">Preview unavailable</p>
</div>
)
}
const bothLoaded = !!leftAsset && !!rightAsset
const isLoading = leftLoading || rightLoading
return (
<div ref={rootRef} className="flex h-full flex-1 flex-col bg-background">
<div className="flex min-h-0 flex-1">
{/* Left pane */}
<div className="flex min-w-0 flex-1 flex-col border-r border-zinc-800">
{leftAsset && (
<ComparePaneTopbar
side="left"
fileName={leftAsset.name}
version={versionOf(leftId)}
activeVersionId={leftId}
versions={versions}
isActive={activeSide === 'left'}
onActivate={() => onActiveSideChange('left')}
onSwitchVersion={(vid) => onSwitchVersion('left', vid)}
onExit={onExit}
/>
)}
<div className="relative flex min-h-0 flex-1">
{leftAsset ? (
renderPane('left', leftAsset, leftKind)
) : (
<div className="flex flex-1 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-foreground" />
</div>
)}
</div>
</div>
{/* Right pane */}
<div className="flex min-w-0 flex-1 flex-col">
{rightAsset && (
<ComparePaneTopbar
side="right"
fileName={rightAsset.name}
version={versionOf(rightId)}
activeVersionId={rightId}
versions={versions}
isActive={activeSide === 'right'}
onActivate={() => onActiveSideChange('right')}
onSwitchVersion={(vid) => onSwitchVersion('right', vid)}
onExit={onExit}
/>
)}
<div className="relative flex min-h-0 flex-1">
{rightAsset ? (
renderPane('right', rightAsset, rightKind)
) : (
<div className="flex flex-1 items-center justify-center">
<Loader2 className="h-6 w-6 animate-spin text-foreground" />
</div>
)}
</div>
</div>
</div>
{isLoading && !bothLoaded && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/30">
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
</div>
)}
<CompareControlBar
activeState={activeState}
activeAsset={activeAsset ?? null}
previewUrl={activePreviewUrl}
isFullScreen={isFullScreen}
onTogglePlay={handleTogglePlay}
onToggleLoop={handleToggleLoop}
onSeek={handleSeek}
onVolumeChange={handleVolumeChange}
onToggleMute={handleToggleMute}
onChangePlaybackRate={handlePlaybackRate}
onChangeResolution={handleChangeResolution}
onZoomIn={handleZoomIn}
onZoomOut={handleZoomOut}
onFit={handleFit}
onDownload={handleDownload}
onToggleFullScreen={handleToggleFullScreen}
/>
</div>
)
}
@@ -0,0 +1,55 @@
import type { VideoTranscode } from '@shumai/dtos'
export type PaneKind = 'image' | 'video' | 'unsupported'
export type CompareSide = 'left' | 'right'
export type DisplayTranscode = VideoTranscode & { resolution: string }
/**
* Reactive state a pane reports upward so the shared control bar can render.
* `video` is populated only for video panes.
*/
export interface PaneReportedState {
kind: PaneKind
zoom: number
video?: {
frameRate: number
totalFrames: number
currentFrame: number
isPlaying: boolean
volume: number
isMuted: boolean
playbackRate: number
isLooping: boolean
currentResolution: string
resolutions: DisplayTranscode[]
buffered: number
}
}
/**
* Imperative command surface exposed by each pane via ref. The shared control
* bar dispatches to the active pane (and, when media types match, to both).
*/
export interface ComparePaneHandle {
getKind: () => PaneKind
// Playback (video only; no-ops for images)
play: () => void
pause: () => void
togglePlay: () => void
seekToFrame: (frame: number) => void
seekToSecond: (second: number) => void
stepFrame: (delta: number) => void
setMuted: (muted: boolean) => void
setVolume: (volume: number) => void
setPlaybackRate: (rate: number) => void
toggleLoop: () => void
changeResolution: (resolution: string) => void
// Zoom / pan (image + video)
zoomBy: (factor: number) => void
fit: () => void
panBy: (dx: number, dy: number) => void
// Download active side's original/selected media
download: (key?: string) => void
}
+13 -46
View File
@@ -2,12 +2,13 @@ import { useScreenSize } from '@/ui/hooks/useScreenSize'
import { client } from '@/ui/api/client'
import { getBestTranscode } from '@/ui/lib/media'
import type { AssetInfo } from '@shumai/dtos'
import { Check, Copy, Download, Minus, Plus } from 'lucide-react'
import { Download } from 'lucide-react'
import type { ReactNode, RefObject } from 'react'
import { useCallback, useEffect, useRef, useState } from 'react'
import type Player from 'video.js/dist/types/player'
import DrawingCanvas from './drawing-canvas'
import VideoPlayer from './viewers/video-player'
import { ImageControlBar } from './viewers/image-control-bar'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
import type { Annotation } from '@/ui/types'
@@ -271,51 +272,17 @@ export function FileViewer({
</div>
</div>
{/* Zoom Toolbar */}
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto">
<button
onClick={() => handleZoom(0.8)}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Zoom Out"
>
<Minus size={16} />
</button>
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
{Math.round(zoom * 100)}%
</span>
<button
onClick={() => handleZoom(1.2)}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Zoom In"
>
<Plus size={16} />
</button>
</div>
<button
onClick={handleFit}
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200"
>
Fit
</button>
<button
onClick={handleCopy}
disabled={!bestUrl}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Copy optimized image to clipboard"
>
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
{copied ? 'Copied' : 'Copy'}
</button>
<button
onClick={handleDownload}
disabled={!file.media?.original?.key}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Download original image"
>
<Download size={14} />
Download
</button>
</div>
<ImageControlBar
zoom={zoom}
onZoomIn={() => handleZoom(1.2)}
onZoomOut={() => handleZoom(0.8)}
onFit={handleFit}
onDownload={handleDownload}
canDownload={!!file.media?.original?.key}
onCopy={handleCopy}
copied={copied}
canCopy={!!bestUrl}
/>
</>
)}
{isVideo && (
@@ -16,6 +16,8 @@ import { Lock, AlertCircle, Loader2 } from 'lucide-react'
import type { AncestorFolder, AssetInfoPaginatedList, AssetInfo, CommentInfo } from '@shumai/dtos'
import { FieldInfo } from '@shumai/dtos'
import { FileViewer } from './file-viewer'
import { CompareViewer } from './compare/compare-viewer'
import { pickDefaultCompareVersions } from './compare/compare-utils'
import type Player from 'video.js/dist/types/player'
import type { Annotation } from '@/ui/types'
@@ -26,6 +28,11 @@ interface PublicShareManagerProps {
initialFolderId?: string
initialFileId?: string
startTime?: number
versionId?: string
compare?: boolean
compareLeftId?: string
compareRightId?: string
compareActiveSide?: 'left' | 'right'
}
interface PublicShareInfo {
@@ -46,8 +53,14 @@ export function PublicShareManager({
initialFolderId,
initialFileId,
startTime,
versionId,
compare,
compareLeftId,
compareRightId,
compareActiveSide = 'left',
}: PublicShareManagerProps) {
const navigate = useNavigate()
const isCompareMode = !!compare && !!compareLeftId && !!compareRightId
const [password, setPassword] = useState(() => {
return localStorage.getItem(`share_pwd_${shareId}`) || ''
})
@@ -87,6 +100,9 @@ export function PublicShareManager({
const currentFolderId = initialFolderId || shareInfo?.rootFolderId
const viewingFileId = initialFileId || null
// The stack asset is always fetched by the route file id; when a version is
// selected we additionally display that version child asset.
const activeFileId = versionId || viewingFileId
const [ancestorFolders, setAncestorFolders] = useState<AncestorFolder[]>([])
@@ -129,6 +145,10 @@ export function PublicShareManager({
const [annotations, setAnnotations] = useState<Annotation[]>([])
const [currentTime, setCurrentTime] = useState(0)
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
undefined,
)
const {
data: foldersData,
@@ -214,7 +234,7 @@ export function PublicShareManager({
enabled: !!shareInfo,
})
const { data: viewingFileData, isLoading: isViewingFileLoading } = useQuery({
const { data: stackFileData, isLoading: isStackFileLoading } = useQuery({
queryKey: ['public-share-file', shareId, viewingFileId, password],
queryFn: async () => {
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
@@ -233,6 +253,30 @@ export function PublicShareManager({
enabled: !!viewingFileId && !!shareInfo,
})
const { data: versionFileData, isLoading: isVersionFileLoading } = useQuery({
queryKey: ['public-share-file', shareId, versionId, password],
queryFn: async () => {
const res = await client.api.shares[':shareId'].files[':fileId'].$get(
{
param: { shareId, fileId: versionId! },
},
{
headers: {
'x-share-password': password,
},
},
)
if (res.status === 401) throw new Error('Unauthorized')
return (await res.json()) as unknown as AssetInfo
},
enabled: !!versionId && !!shareInfo,
})
// The stack asset provides the version list; the active asset (version child
// or the stack itself) is what we actually display.
const viewingFileData = versionId ? versionFileData : stackFileData
const isViewingFileLoading = isStackFileLoading || (!!versionId && isVersionFileLoading)
useEffect(() => {
if (foldersError?.message === 'Unauthorized') {
setPassword('')
@@ -307,6 +351,13 @@ export function PublicShareManager({
setAnnotations([])
}
if (isCompareMode) {
if (comment.second !== null && comment.second !== undefined) {
setSeekRequest({ second: comment.second, nonce: Date.now() })
}
return
}
if (comment.second !== null && comment.second !== undefined) {
if (videoRef.current) {
videoRef.current.currentTime(comment.second)
@@ -324,6 +375,26 @@ export function PublicShareManager({
setSelectedCommentId(null)
}
const updateCompareSearch = (patch: Record<string, unknown>) => {
if (!viewingFileId) return
navigate({
to: '/share/$shareId/files/$fileId',
params: { shareId, fileId: viewingFileId },
search: (p: Record<string, unknown>) => ({ ...p, ...patch }),
})
}
const handleCompareExit = () => {
const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
updateCompareSearch({
compare: undefined,
cmpLeft: undefined,
cmpRight: undefined,
cmpActive: undefined,
version: activeId,
})
}
const { setProjectState, clearProjectState } = useTopNavStore()
useEffect(() => {
@@ -341,9 +412,9 @@ export function PublicShareManager({
currentAsset: {
name: viewingFileData?.name || currentFolderName,
type: viewingFileId ? 'file' : 'folder',
version: viewingFileData?.versionStack
? (viewingFileData.versionStack.versions.find((v) => v.id === viewingFileData.id)
?.version ?? viewingFileData.versionStack.versions.length)
version: stackFileData?.versionStack
? (stackFileData.versionStack.versions.find((v) => v.id === activeFileId)?.version ??
stackFileData.versionStack.versions.length)
: undefined,
},
isRootFolder: currentFolderId === shareInfo.rootFolderId && !viewingFileId,
@@ -364,6 +435,24 @@ export function PublicShareManager({
onFolderClick: handleBreadcrumbClick,
isRightSidebarCollapsed,
onRightSidebarToggle: () => setIsRightSidebarCollapsed((prev) => !prev),
versions: stackFileData?.versionStack?.versions,
compareMode: isCompareMode,
canCompareVersions: (stackFileData?.versionStack?.versions?.length ?? 0) >= 2,
onCompareVersions: () => {
const pair = pickDefaultCompareVersions(stackFileData?.versionStack?.versions)
if (!pair || !viewingFileId) return
navigate({
to: '/share/$shareId/files/$fileId',
params: { shareId, fileId: viewingFileId },
search: (p: Record<string, unknown>) => ({
...p,
compare: true,
cmpLeft: pair.left.id,
cmpRight: pair.right.id,
cmpActive: 'left' as const,
}),
})
},
})
}
@@ -373,11 +462,16 @@ export function PublicShareManager({
currentFolderId,
folders,
viewingFileData,
stackFileData,
activeFileId,
viewingFileId,
ancestorFolders,
setProjectState,
clearProjectState,
isRightSidebarCollapsed,
isCompareMode,
navigate,
shareId,
])
let content
@@ -456,21 +550,44 @@ export function PublicShareManager({
<div className="flex flex-1 overflow-hidden relative">
{viewingFileId ? (
<div className="flex-1 relative bg-muted/30">
{isViewingFileLoading && (
{isViewingFileLoading && !isCompareMode && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
</div>
)}
{viewingFileData && (
<FileViewer
file={viewingFileData}
videoRef={videoRef}
{isCompareMode && compareLeftId && compareRightId ? (
<CompareViewer
isPublic
shareId={shareId}
versions={viewingFileData?.versionStack?.versions ?? []}
leftId={compareLeftId}
rightId={compareRightId}
activeSide={compareActiveSide}
annotations={annotations}
seekRequest={seekRequest}
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
onSwitchVersion={(side, versionId) =>
updateCompareSearch(
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
)
}
onExit={handleCompareExit}
onActiveAssetChange={setCompareActiveAsset}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
annotations={annotations}
startTime={startTime}
shareId={shareId}
/>
) : (
viewingFileData && (
<FileViewer
file={viewingFileData}
videoRef={videoRef}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
annotations={annotations}
startTime={startTime}
shareId={shareId}
/>
)
)}
</div>
) : (
@@ -520,7 +637,7 @@ export function PublicShareManager({
<FileViewerRightSidebar
teamId=""
projectId={shareInfo.projectId}
file={currentSelectedItem}
file={isCompareMode ? compareActiveAsset : currentSelectedItem}
onSaveField={() => {}}
members={[]}
readOnly={true}
+6
View File
@@ -24,6 +24,9 @@ export function TopNav() {
isPublic,
shareId,
onFolderClick,
compareMode,
canCompareVersions,
onCompareVersions,
} = projectState
const isFileView = !!fileId
@@ -91,6 +94,9 @@ export function TopNav() {
downloadInfo={downloadInfo}
versions={versions}
onFolderClick={onFolderClick}
compareMode={compareMode}
canCompareVersions={canCompareVersions}
onCompareVersions={onCompareVersions}
/>
)
}
@@ -0,0 +1,87 @@
import { Check, Copy, Download, Maximize, Minimize, Minus, Plus } from 'lucide-react'
export interface ImageControlBarProps {
zoom: number
onZoomIn: () => void
onZoomOut: () => void
onFit: () => void
onDownload: () => void
canDownload: boolean
onCopy?: () => void
copied?: boolean
canCopy?: boolean
/** When provided, renders a fullscreen toggle (used by compare mode). */
fullscreen?: { isFullScreen: boolean; onToggle: () => void }
}
export function ImageControlBar({
zoom,
onZoomIn,
onZoomOut,
onFit,
onDownload,
canDownload,
onCopy,
copied = false,
canCopy = true,
fullscreen,
}: ImageControlBarProps) {
return (
<div className="relative px-4 py-3 bg-card border-t border-gray-200 dark:border-gray-700 z-10 flex items-center justify-end gap-2 transition-colors duration-200">
<div className="flex items-center gap-1 bg-gray-200/50 dark:bg-white/10 rounded-md p-0.5 mr-auto">
<button
onClick={onZoomOut}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Zoom Out"
>
<Minus size={16} />
</button>
<span className="w-12 text-center text-xs font-mono font-medium text-gray-900 dark:text-gray-100 select-none">
{Math.round(zoom * 100)}%
</span>
<button
onClick={onZoomIn}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Zoom In"
>
<Plus size={16} />
</button>
</div>
<button
onClick={onFit}
className="text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent animate-in fade-in zoom-in-95 duration-200"
>
Fit
</button>
{onCopy && (
<button
onClick={onCopy}
disabled={!canCopy}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Copy optimized image to clipboard"
>
{copied ? <Check size={14} className="text-green-500" /> : <Copy size={14} />}
{copied ? 'Copied' : 'Copy'}
</button>
)}
<button
onClick={onDownload}
disabled={!canDownload}
className="flex items-center gap-1.5 text-xs font-medium px-3 py-1.5 rounded bg-gray-200/50 dark:bg-white/10 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors border border-transparent disabled:opacity-50 animate-in fade-in zoom-in-95 duration-200"
title="Download original image"
>
<Download size={14} />
Download
</button>
{fullscreen && (
<button
onClick={fullscreen.onToggle}
className="p-1.5 rounded hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-700 dark:text-gray-200 transition-colors"
title="Fullscreen"
>
{fullscreen.isFullScreen ? <Minimize size={16} /> : <Maximize size={16} />}
</button>
)}
</div>
)
}
@@ -0,0 +1,374 @@
import { cn } from '@/ui/lib/utils'
import { useUiStore } from '@/ui/stores/ui'
import type { AssetInfo, VideoTranscode } from '@shumai/dtos'
import {
Check,
ChevronDown,
Download,
Maximize,
Minimize,
Minus,
Pause,
Play,
Plus,
Repeat,
Settings,
Volume2,
VolumeX,
} from 'lucide-react'
import React from 'react'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import { Slider } from '../ui/slider'
import ProgressBar from './progress-bar'
import { formatTime, formatTimecode } from './utils'
export interface PlayerState {
isPlaying: boolean
progress: number // 0 to 100
currentTime: number
duration: number
volume: number
isMuted: boolean
isLooping: boolean
playbackRate: number
isFullScreen: boolean
showFrames: boolean // Toggle between time (02:30) and frames (1234)
currentResolution: string // 'Original' or '720p', '480p' etc.
currentSrc?: string
}
export type DisplayTranscode = VideoTranscode & { resolution: string }
export interface ControlBarProps {
state: PlayerState
zoom: number
isControlsVisible: boolean
buffered: number
data: AssetInfo
resolutions: DisplayTranscode[]
togglePlay: () => void
toggleLoop: () => void
toggleMute: () => void
handleVolumeChange: (newVolume: number) => void
changePlaybackRate: (rate: number) => void
changeResolution: (res: DisplayTranscode) => void
handleDownload: (key: string) => void
toggleFullScreen: () => void
onZoomChange: (zoom: number) => void
onZoomReset: () => void
// Frame-accurate props
frameRate: number
totalFrames: number
currentFrame: number
seekToFrame: (frame: number) => Promise<void> | void
/**
* Whether the bar floats as an absolute overlay over the media while
* fullscreen (single-file player). Compare mode sets this false so the bar
* stays in-flow. Colors are always theme-aware regardless of this flag.
*/
floatOverlayInFullScreen?: boolean
/** Fired when the cursor enters/leaves the bar (used to pin it visible). */
onMouseEnter?: () => void
onMouseLeave?: () => void
}
export const VideoControlBar: React.FC<ControlBarProps> = ({
state,
zoom,
isControlsVisible,
buffered,
data,
resolutions,
togglePlay,
toggleLoop,
toggleMute,
handleVolumeChange,
changePlaybackRate,
changeResolution,
handleDownload,
toggleFullScreen,
onZoomChange,
onZoomReset,
frameRate,
totalFrames,
currentFrame,
seekToFrame,
floatOverlayInFullScreen = true,
onMouseEnter,
onMouseLeave,
}) => {
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
if (!data.media?.metadata) {
return null
}
// Whether to render the bar as a floating overlay over the media (single-file
// fullscreen). Compare keeps it in-flow. Colors stay theme-aware either way.
const overlay = state.isFullScreen && floatOverlayInFullScreen
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const startTimecode = data.media?.metadata?.startTimecode
const displayTotalFrames = Math.max(0, totalFrames - 1)
const displayString =
videoTimeDisplayMode === 'frames'
? `${currentFrame} / ${displayTotalFrames} fr`
: videoTimeDisplayMode === 'standard'
? `${formatTimecode(currentFrame, frameRate, 'standard')} / ${formatTime(totalFrames / frameRate)}`
: `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}`
return (
<div
className={cn(
'transition-all duration-300 ease-in-out z-20 text-foreground',
overlay
? 'absolute bottom-0 left-0 right-0 px-4 py-4 bg-card/90 backdrop-blur-md border-t border-border'
: 'relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200',
isControlsVisible
? 'opacity-100 translate-y-0'
: 'opacity-0 translate-y-4 pointer-events-none',
)}
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>
{/* 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" />
) : (
<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) => 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>
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
<div className="relative flex items-center gap-3">
{/* Zoom Controls */}
<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"
>
<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"
>
<Plus size={14} />
</button>
</div>
<button
onClick={onZoomReset}
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
>
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>
{/* Resolution Selector */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="flex items-center gap-1 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>{state.currentResolution}</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Quality</DropdownMenuLabel>
{previewResolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => changeResolution(res)}
className={cn(
'flex w-full items-center justify-between',
state.currentResolution === res.resolution
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{res.resolution}</span>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Download */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="transition-colors hover:text-primary" title="Download">
<Download className="h-5 w-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Download</DropdownMenuLabel>
{resolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{res.resolution}</span>
<span className="text-xs text-muted-foreground">
{res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Fullscreen */}
<button onClick={toggleFullScreen} className="transition-colors hover:text-primary">
{state.isFullScreen ? (
<Minimize className="h-6 w-6" />
) : (
<Maximize className="h-6 w-6" />
)}
</button>
</div>
</div>
</div>
)
}
@@ -1,56 +1,17 @@
import type { AssetInfo, VideoTranscode } from '@shumai/dtos'
import type { AssetInfo } from '@shumai/dtos'
import { client } from '@/ui/api/client'
import { cn } from '@/ui/lib/utils'
import {
Check,
ChevronDown,
Download,
Maximize,
Minimize,
Minus,
Pause,
Play,
Plus,
Repeat,
Settings,
Volume2,
VolumeX,
} from 'lucide-react'
import { Play } from 'lucide-react'
import React, { useCallback, useEffect, useRef, useState } from 'react'
import videojs from 'video.js'
import type Player from 'video.js/dist/types/player'
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuTrigger,
} from '../ui/dropdown-menu'
import { Slider } from '../ui/slider'
import ProgressBar from './progress-bar'
import { formatTimecode, formatTime } from './utils'
import { useFramePlayer } from './use-frame-player'
import { useUiStore } from '@/ui/stores/ui'
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
import type { Annotation } from '@/ui/types'
import DrawingCanvas from '../drawing-canvas'
import { useAnnotationStore } from '@/ui/stores/annotation-store'
export interface PlayerState {
isPlaying: boolean
progress: number // 0 to 100
currentTime: number
duration: number
volume: number
isMuted: boolean
isLooping: boolean
playbackRate: number
isFullScreen: boolean
showFrames: boolean // Toggle between time (02:30) and frames (1234)
currentResolution: string // 'Original' or '720p', '480p' etc.
currentSrc?: string
}
interface VideoPlayerProps {
data: AssetInfo
playerRef?: React.RefObject<Player | null>
@@ -63,323 +24,6 @@ interface VideoPlayerProps {
children?: React.ReactNode
}
type DisplayTranscode = VideoTranscode & { resolution: string }
interface ControlBarProps {
state: PlayerState
zoom: number
isControlsVisible: boolean
buffered: number
data: AssetInfo
resolutions: DisplayTranscode[]
togglePlay: () => void
toggleLoop: () => void
toggleMute: () => void
handleVolumeChange: (newVolume: number) => void
changePlaybackRate: (rate: number) => void
changeResolution: (res: DisplayTranscode) => void
handleDownload: (key: string) => void
toggleFullScreen: () => void
onZoomChange: (zoom: number) => void
onZoomReset: () => void
// Frame-accurate props
frameRate: number
totalFrames: number
currentFrame: number
seekToFrame: (frame: number) => Promise<void>
}
const ControlBar: React.FC<ControlBarProps> = ({
state,
zoom,
isControlsVisible,
buffered,
data,
resolutions,
togglePlay,
toggleLoop,
toggleMute,
handleVolumeChange,
changePlaybackRate,
changeResolution,
handleDownload,
toggleFullScreen,
onZoomChange,
onZoomReset,
frameRate,
totalFrames,
currentFrame,
seekToFrame,
}) => {
if (!data.media?.metadata) {
return null
}
const previewResolutions = resolutions.filter((r) => !r.isRaw)
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
const startTimecode = data.media?.metadata?.startTimecode
const displayTotalFrames = Math.max(0, totalFrames - 1)
const displayString =
videoTimeDisplayMode === 'frames'
? `${currentFrame} / ${displayTotalFrames} fr`
: videoTimeDisplayMode === 'standard'
? `${formatTimecode(currentFrame, frameRate, 'standard')} / ${formatTime(totalFrames / frameRate)}`
: `${formatTimecode(currentFrame, frameRate, videoTimeDisplayMode, startTimecode)} / ${formatTimecode(displayTotalFrames, frameRate, videoTimeDisplayMode, startTimecode)}`
return (
<div
className={cn(
'transition-all duration-300 ease-in-out z-20',
state.isFullScreen
? 'absolute bottom-0 left-0 right-0 px-4 py-4 bg-black/60 backdrop-blur-md text-white'
: 'relative w-full bg-card border-t border-border px-4 py-3 z-10 transition-colors duration-200',
isControlsVisible
? 'opacity-100 translate-y-0'
: 'opacity-0 translate-y-4 pointer-events-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={cn(
'flex items-center justify-between',
state.isFullScreen ? 'text-white/90' : '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" />
) : (
<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) => 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>
{/* Right Side: Zoom, Speed, Res, Download, Fullscreen */}
<div className="relative flex items-center gap-3">
{/* Zoom Controls */}
<div className="flex items-center gap-1">
<div className="flex items-center gap-1 bg-muted rounded-md p-0.5">
<button
onClick={() => onZoomChange(zoom * 0.8)}
className="p-1 hover:text-primary rounded"
>
<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"
>
<Plus size={14} />
</button>
</div>
<button
onClick={onZoomReset}
className="text-xs font-medium px-2 py-1 rounded bg-muted hover:text-primary transition-colors"
>
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>
{/* Resolution Selector */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="flex items-center gap-1 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>{state.currentResolution}</span>
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Quality</DropdownMenuLabel>
{previewResolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => changeResolution(res)}
className={cn(
'flex w-full items-center justify-between',
state.currentResolution === res.resolution
? 'text-primary font-medium'
: 'text-foreground',
)}
>
<span>{res.resolution}</span>
<span className="pl-5 text-xs text-muted-foreground">
{res.width}x{res.height}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Download */}
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="transition-colors hover:text-primary" title="Download">
<Download className="h-5 w-5" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuLabel>Download</DropdownMenuLabel>
{resolutions.map((res) => (
<DropdownMenuItem
key={res.resolution}
onClick={() => handleDownload(res.key ?? '')}
className="flex w-full items-center justify-between px-3 py-2 text-left text-sm text-foreground"
>
<span>{res.resolution}</span>
<span className="text-xs text-muted-foreground">
{res.isRaw ? data.name?.split('.').pop()?.toUpperCase() || 'RAW' : 'MP4'}
</span>
</DropdownMenuItem>
))}
</DropdownMenuContent>
</DropdownMenu>
{/* Fullscreen */}
<button onClick={toggleFullScreen} className="transition-colors hover:text-primary">
{state.isFullScreen ? (
<Minimize className="h-6 w-6" />
) : (
<Maximize className="h-6 w-6" />
)}
</button>
</div>
</div>
</div>
)
}
const VideoPlayer: React.FC<VideoPlayerProps> = ({
data,
playerRef: passedPlayerRef,
@@ -396,7 +40,9 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
// We use a container ref to manually append the video element
const videoContainerRef = useRef<HTMLDivElement>(null)
const containerRef = useRef<HTMLDivElement>(null)
const rootRef = useRef<HTMLDivElement>(null)
const controlsTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const isOverControlsRef = useRef(false)
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
const videoRef = useRef<HTMLVideoElement | null>(null)
@@ -695,30 +341,42 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
}
}, [startTime, frameRate, seekToFrame, isPlayerReady])
const handleMouseMove = useCallback(() => {
// Always show controls on movement
setIsControlsVisible(true)
const scheduleHide = useCallback(() => {
if (controlsTimeoutRef.current) {
clearTimeout(controlsTimeoutRef.current)
}
// Only set auto-hide timer if we are in fullscreen and playing
// If paused, controls should remain visible so user can see what to do
if (state.isFullScreen && state.isPlaying) {
// Never hide while the cursor rests over the control bar itself.
if (state.isFullScreen && !isOverControlsRef.current) {
controlsTimeoutRef.current = setTimeout(() => {
setIsControlsVisible(false)
}, 2000)
}, 1200)
}
}, [state.isFullScreen, state.isPlaying])
}, [state.isFullScreen])
const handleMouseMove = useCallback(() => {
// Always show controls on movement, then (re)start the idle hide timer.
setIsControlsVisible(true)
scheduleHide()
}, [scheduleHide])
const handleControlsMouseEnter = useCallback(() => {
isOverControlsRef.current = true
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
setIsControlsVisible(true)
}, [])
const handleControlsMouseLeave = useCallback(() => {
isOverControlsRef.current = false
scheduleHide()
}, [scheduleHide])
const handleMouseLeave = useCallback(() => {
// If we leave the player area in fullscreen, hide controls (optional preference, usually good)
if (state.isFullScreen && state.isPlaying) {
// If the cursor leaves the player while fullscreen, hide the controls.
if (state.isFullScreen) {
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
setIsControlsVisible(false)
}
}, [state.isFullScreen, state.isPlaying])
}, [state.isFullScreen])
// Clean up timeout on unmount or state change
useEffect(() => {
@@ -727,13 +385,13 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
}
}, [])
// Ensure controls are visible when pausing or entering fullscreen initially
// Windowed mode: controls are always visible. Fullscreen: show now and let
// the idle timer hide them (re-runs on play/pause so pausing re-reveals them).
useEffect(() => {
if (!state.isPlaying) {
if (!state.isFullScreen) {
setIsControlsVisible(true)
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
} else {
// If we just started playing (or re-entered playing state), trigger the timer logic
handleMouseMove()
}
}, [state.isPlaying, state.isFullScreen, handleMouseMove])
@@ -844,9 +502,9 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
}
const toggleFullScreen = () => {
if (!containerRef.current) return
if (!rootRef.current) return
if (!document.fullscreenElement) {
containerRef.current.requestFullscreen()
rootRef.current.requestFullscreen()
setState((prev) => ({ ...prev, isFullScreen: true }))
} else {
document.exitFullscreen()
@@ -899,6 +557,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
return (
<div
ref={rootRef}
className={cn(
'group shadow-2xl font-sans select-none flex flex-col mx-auto transition-all duration-300 relative',
state.isFullScreen ? 'h-full w-full rounded-none bg-black' : 'w-full h-full',
@@ -958,7 +617,7 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
</div>
</div>
<ControlBar
<VideoControlBar
state={controlBarState}
zoom={zoom}
isControlsVisible={isControlsVisible}
@@ -979,6 +638,8 @@ const VideoPlayer: React.FC<VideoPlayerProps> = ({
totalFrames={totalFrames}
currentFrame={currentFrame}
seekToFrame={seekToFrame}
onMouseEnter={handleControlsMouseEnter}
onMouseLeave={handleControlsMouseLeave}
/>
</div>
)
+3
View File
@@ -433,6 +433,9 @@
"versions": "Versions",
"manage_versions": "Manage versions...",
"compare_versions": "Compare Versions",
"exit_compare": "Exit compare",
"switch_version": "Switch version",
"show_left_sidebar": "Show Left Sidebar",
"hide_left_sidebar": "Hide Left Sidebar",
"show_right_sidebar": "Show Right Sidebar",
+3
View File
@@ -433,6 +433,9 @@
"versions": "版本",
"manage_versions": "管理版本...",
"compare_versions": "对比版本",
"exit_compare": "退出对比",
"switch_version": "切换版本",
"show_left_sidebar": "显示左侧边栏",
"hide_left_sidebar": "隐藏左侧边栏",
"show_right_sidebar": "显示右侧边栏",
+3
View File
@@ -411,6 +411,9 @@ export * from "./auth_feature_teams.js";
export * from "./auth_community_cta.js";
export * from "./versions.js";
export * from "./manage_versions.js";
export * from "./compare_versions.js";
export * from "./exit_compare.js";
export * from "./switch_version.js";
export * from "./show_left_sidebar.js";
export * from "./hide_left_sidebar.js";
export * from "./show_right_sidebar.js";
+3
View File
@@ -413,6 +413,9 @@ export * from './auth_feature_teams.js'
export * from './auth_community_cta.js'
export * from './versions.js'
export * from './manage_versions.js'
export * from './compare_versions.js'
export * from './exit_compare.js'
export * from './switch_version.js'
export * from './show_left_sidebar.js'
export * from './hide_left_sidebar.js'
export * from './show_right_sidebar.js'
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Compare Versions" |
*
* @param {Compare_VersionsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const compare_versions: ((inputs?: Compare_VersionsInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Compare_VersionsInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Compare_VersionsInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Compare_VersionsInputs */
const en_compare_versions = /** @type {(inputs: Compare_VersionsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Compare Versions`)
};
const zh_compare_versions = /** @type {(inputs: Compare_VersionsInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`对比版本`)
};
/**
* | output |
* | --- |
* | "Compare Versions" |
*
* @param {Compare_VersionsInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const compare_versions = /** @type {((inputs?: Compare_VersionsInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Compare_VersionsInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_compare_versions(inputs)
return zh_compare_versions(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Exit compare" |
*
* @param {Exit_CompareInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const exit_compare: ((inputs?: Exit_CompareInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Exit_CompareInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Exit_CompareInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Exit_CompareInputs */
const en_exit_compare = /** @type {(inputs: Exit_CompareInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Exit compare`)
};
const zh_exit_compare = /** @type {(inputs: Exit_CompareInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`退出对比`)
};
/**
* | output |
* | --- |
* | "Exit compare" |
*
* @param {Exit_CompareInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const exit_compare = /** @type {((inputs?: Exit_CompareInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Exit_CompareInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_exit_compare(inputs)
return zh_exit_compare(inputs)
});
+16
View File
@@ -0,0 +1,16 @@
/**
* | output |
* | --- |
* | "Switch version" |
*
* @param {Switch_VersionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const switch_version: ((inputs?: Switch_VersionInputs, options?: {
locale?: "en" | "zh";
}) => LocalizedString) & import("../runtime.js").MessageMetadata<Switch_VersionInputs, {
locale?: "en" | "zh";
}, {}>;
export type LocalizedString = import("../runtime.js").LocalizedString;
export type Switch_VersionInputs = {};
+29
View File
@@ -0,0 +1,29 @@
/* eslint-disable */
import { getLocale, experimentalStaticLocale } from '../runtime.js';
/** @typedef {import('../runtime.js').LocalizedString} LocalizedString */
/** @typedef {{}} Switch_VersionInputs */
const en_switch_version = /** @type {(inputs: Switch_VersionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`Switch version`)
};
const zh_switch_version = /** @type {(inputs: Switch_VersionInputs) => LocalizedString} */ () => {
return /** @type {LocalizedString} */ (`切换版本`)
};
/**
* | output |
* | --- |
* | "Switch version" |
*
* @param {Switch_VersionInputs} inputs
* @param {{ locale?: "en" | "zh" }} options
* @returns {LocalizedString}
*/
export const switch_version = /** @type {((inputs?: Switch_VersionInputs, options?: { locale?: "en" | "zh" }) => LocalizedString) & import('../runtime.js').MessageMetadata<Switch_VersionInputs, { locale?: "en" | "zh" }, {}>} */ ((inputs = {}, options = {}) => {
const locale = experimentalStaticLocale ?? options.locale ?? getLocale()
if (locale === "en") return en_switch_version(inputs)
return zh_switch_version(inputs)
});
@@ -1,5 +1,7 @@
import { client } from '@/ui/api/client'
import { FileViewer } from '@/ui/components/file-viewer'
import { CompareViewer } from '@/ui/components/compare/compare-viewer'
import { pickDefaultCompareVersions } from '@/ui/components/compare/compare-utils'
import { FileViewerLeftSidebar } from '@/ui/components/file-viewer-left-sidebar'
import { m } from '@/ui/paraglide/messages.js'
import { FileViewerRightSidebar } from '@/ui/components/file-viewer-right-sidebar'
@@ -25,6 +27,10 @@ function FileViewPage() {
const versionAssetId = search.version
const startTime = search.start
const activeFileId = versionAssetId || fileId
const compareLeftId = search.cmpLeft
const compareRightId = search.cmpRight
const compareActiveSide = search.cmpActive ?? 'left'
const isCompareMode = !!search.compare && !!compareLeftId && !!compareRightId
const videoRef = useRef<Player | null>(null)
const { teamId, ensureTeamIdForProject } = useTeamContextStore()
@@ -32,6 +38,10 @@ function FileViewPage() {
const [annotations, setAnnotations] = useState<Annotation[]>([])
const [currentTime, setCurrentTime] = useState(0)
const [selectedCommentId, setSelectedCommentId] = useState<string | null>(null)
const [compareActiveAsset, setCompareActiveAsset] = useState<AssetInfo | null>(null)
const [seekRequest, setSeekRequest] = useState<{ second: number; nonce: number } | undefined>(
undefined,
)
const [carouselState, setCarouselState] = useState<{
show: boolean
files: AssetInfo[]
@@ -108,7 +118,7 @@ function FileViewPage() {
if (!res.ok) throw new Error('Failed to fetch versions')
return await res.json()
},
enabled: !!projectId && !!fileId && !!versionAssetId,
enabled: !!projectId && !!fileId && (!!versionAssetId || isCompareMode),
})
const { data: projectInfo } = useQuery({
@@ -158,6 +168,24 @@ function FileViewPage() {
})),
},
versions: versionsDataList,
compareMode: isCompareMode,
canCompareVersions: (versionsDataList?.length ?? 0) >= 2,
onCompareVersions: () => {
const pair = pickDefaultCompareVersions(versionsDataList)
if (!pair) return
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId },
search: (p: Record<string, unknown>) => ({
...p,
version: undefined,
compare: true,
cmpLeft: pair.left.id,
cmpRight: pair.right.id,
cmpActive: 'left' as const,
}),
})
},
onFolderClick: (id: string) => {
navigate({
to: '/projects/$projectId/folders/$folderId',
@@ -176,6 +204,7 @@ function FileViewPage() {
versionsDataList,
activeFileId,
fileId,
isCompareMode,
setProjectState,
clearProjectState,
navigate,
@@ -270,6 +299,11 @@ function FileViewPage() {
setAnnotations([])
}, [fileData?.id])
useEffect(() => {
setSelectedCommentId(null)
setAnnotations([])
}, [compareActiveAsset?.id])
if (isLoading && !fileData) {
return <FileDetailSkeleton />
}
@@ -278,23 +312,45 @@ function FileViewPage() {
return <div>{m.file_not_found()}</div>
}
const sidebarFile = isCompareMode ? compareActiveAsset : (fileData as unknown as AssetInfo)
const sidebarFileId = sidebarFile?.id ?? activeFileId
const handleSaveField = (fieldId: string, value: unknown) => {
if (!teamId) return
patchMetadata(
{
param: { fileId: activeFileId },
param: { fileId: sidebarFileId },
json: [{ key: fieldId, value }] as InferRequestType<typeof $patchMetadata>['json'],
},
{
onSuccess: () => {
queryClient.invalidateQueries({
queryKey: ['files', activeFileId],
queryKey: ['files', sidebarFileId],
})
},
},
)
}
const updateCompareSearch = (patch: Record<string, unknown>) => {
navigate({
to: '/projects/$projectId/files/$fileId',
params: { projectId, fileId },
search: (p: Record<string, unknown>) => ({ ...p, ...patch }),
})
}
const handleCompareExit = () => {
const activeId = compareActiveSide === 'left' ? compareLeftId : compareRightId
updateCompareSearch({
compare: undefined,
cmpLeft: undefined,
cmpRight: undefined,
cmpActive: undefined,
version: activeId,
})
}
const handleCommentSelect = (comment: CommentInfo) => {
setSelectedCommentId(comment.id || null)
const newAnnotations = comment.annotations as Annotation[]
@@ -304,6 +360,13 @@ function FileViewPage() {
setAnnotations([])
}
if (isCompareMode) {
if (comment.second !== null && comment.second !== undefined) {
setSeekRequest({ second: comment.second, nonce: Date.now() })
}
return
}
if (comment.second !== null && comment.second !== undefined) {
if (videoRef.current) {
videoRef.current.currentTime(comment.second)
@@ -325,29 +388,50 @@ function FileViewPage() {
<div className="h-full flex flex-1 flex-col bg-background">
<div className="h-full flex flex-1 overflow-hidden">
<div className="flex-1 relative">
{isFetching && (
{isFetching && !isCompareMode && (
<div className="absolute inset-0 z-10 flex items-center justify-center bg-background/50">
<Loader2 className="h-8 w-8 animate-spin text-foreground" />
</div>
)}
<FileViewer
file={fileData as unknown as AssetInfo}
videoRef={videoRef}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
annotations={annotations}
startTime={startTime}
>
{carouselState.show && (
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
/>
)}
</FileViewer>
{isCompareMode && compareLeftId && compareRightId ? (
<CompareViewer
versions={versionsDataList ?? []}
leftId={compareLeftId}
rightId={compareRightId}
activeSide={compareActiveSide}
annotations={annotations}
seekRequest={seekRequest}
onActiveSideChange={(side) => updateCompareSearch({ cmpActive: side })}
onSwitchVersion={(side, versionId) =>
updateCompareSearch(
side === 'left' ? { cmpLeft: versionId } : { cmpRight: versionId },
)
}
onExit={handleCompareExit}
onActiveAssetChange={setCompareActiveAsset}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
/>
) : (
<FileViewer
file={fileData as unknown as AssetInfo}
videoRef={videoRef}
onPlay={handlePlay}
onTimeUpdate={setCurrentTime}
annotations={annotations}
startTime={startTime}
>
{carouselState.show && (
<FileViewerLeftSidebar
projectId={projectId}
currentAssetId={activeFileId}
parentFolderId={parentFolderId}
initialFiles={carouselState.files}
initialNextCursor={carouselState.nextCursor}
/>
)}
</FileViewer>
)}
</div>
<ResizeHandle
onResize={(delta) => {
@@ -359,12 +443,13 @@ function FileViewPage() {
<FileViewerRightSidebar
teamId={teamId}
projectId={projectId}
file={fileData as unknown as AssetInfo}
file={sidebarFile}
onSaveField={handleSaveField}
members={members}
onCommentSelect={handleCommentSelect}
currentTime={currentTime}
onTyping={() => {
if (isCompareMode) return
if (videoRef.current) {
videoRef.current.pause()
}
@@ -383,6 +468,17 @@ export const Route = createFileRoute('/projects/$projectId/files/$fileId')({
return {
version: (search.version as string) || undefined,
start: search.start ? Number(search.start) : undefined,
} as { version?: string; start?: number }
compare: search.compare === true || search.compare === 'true' || undefined,
cmpLeft: (search.cmpLeft as string) || undefined,
cmpRight: (search.cmpRight as string) || undefined,
cmpActive: search.cmpActive === 'right' ? 'right' : undefined,
} as {
version?: string
start?: number
compare?: boolean
cmpLeft?: string
cmpRight?: string
cmpActive?: 'left' | 'right'
}
},
})
@@ -3,9 +3,20 @@ import { createFileRoute } from '@tanstack/react-router'
function PublicShareFilePage() {
const { shareId, fileId } = Route.useParams()
const { start } = Route.useSearch()
const { start, version, compare, cmpLeft, cmpRight, cmpActive } = Route.useSearch()
return <PublicShareManager shareId={shareId} initialFileId={fileId} startTime={start} />
return (
<PublicShareManager
shareId={shareId}
initialFileId={fileId}
startTime={start}
versionId={version}
compare={compare}
compareLeftId={cmpLeft}
compareRightId={cmpRight}
compareActiveSide={cmpActive}
/>
)
}
export const Route = createFileRoute('/share/$shareId/files/$fileId')({
@@ -13,6 +24,18 @@ export const Route = createFileRoute('/share/$shareId/files/$fileId')({
validateSearch: (search: Record<string, unknown>) => {
return {
start: search.start ? Number(search.start) : undefined,
} as { start?: number }
version: (search.version as string) || undefined,
compare: search.compare === true || search.compare === 'true' || undefined,
cmpLeft: (search.cmpLeft as string) || undefined,
cmpRight: (search.cmpRight as string) || undefined,
cmpActive: search.cmpActive === 'right' ? 'right' : undefined,
} as {
start?: number
version?: string
compare?: boolean
cmpLeft?: string
cmpRight?: string
cmpActive?: 'left' | 'right'
}
},
})
+4
View File
@@ -34,6 +34,10 @@ export interface TopNavProjectState {
onFolderClick?: (folderId: string) => void
isRightSidebarCollapsed?: boolean
onRightSidebarToggle?: () => void
// Compare Versions
compareMode?: boolean
canCompareVersions?: boolean
onCompareVersions?: () => void
}
interface TopNavStore {