mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-29 04:14:30 +00:00
refactor(webui): modularize file viewer components into registry-driven architecture
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { Download } from 'lucide-react'
|
||||
import React, { useImperativeHandle } from 'react'
|
||||
import { FileViewerProps, MediaController } from '../types'
|
||||
|
||||
export const DefaultViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
({ file, shareId, children }, ref) => {
|
||||
// Implement no-op media controller
|
||||
useImperativeHandle(ref, () => ({
|
||||
play: () => {},
|
||||
pause: () => {},
|
||||
seekTo: () => {},
|
||||
}))
|
||||
|
||||
const handleDownload = 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
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
|
||||
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
|
||||
{children}
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-muted-foreground">Preview unavailable</p>
|
||||
</div>
|
||||
</div>
|
||||
<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">
|
||||
<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 file"
|
||||
>
|
||||
<Download size={14} />
|
||||
Download
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export default DefaultViewer
|
||||
@@ -0,0 +1,14 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import DefaultViewer from './default-viewer'
|
||||
|
||||
export const defaultTypeDefinition: FileTypeDefinition = {
|
||||
id: 'default',
|
||||
name: 'Default',
|
||||
match: () => true,
|
||||
viewer: DefaultViewer,
|
||||
commentsConfig: {
|
||||
hasTimestamp: false,
|
||||
hasAnnotations: false,
|
||||
hasAiBots: false,
|
||||
},
|
||||
}
|
||||
@@ -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 '../../compare/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,223 @@
|
||||
import { useScreenSize } from '@/ui/hooks/useScreenSize'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { getBestTranscode } from '@/ui/lib/media'
|
||||
import React, { useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { ImageControlBar } from './image-control-bar'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import { FileViewerProps, MediaController } from '../types'
|
||||
|
||||
export const ImageViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
({ file, annotations, shareId, children }, ref) => {
|
||||
// Implement no-op media controller since images are static
|
||||
useImperativeHandle(ref, () => ({
|
||||
play: () => {},
|
||||
pause: () => {},
|
||||
seekTo: () => {},
|
||||
}))
|
||||
|
||||
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 [copied, setCopied] = useState(false)
|
||||
|
||||
const observerRef = useRef<ResizeObserver | null>(null)
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// Reset/Fit logic
|
||||
useEffect(() => {
|
||||
if (conW > 0 && conH > 0) {
|
||||
setZoom(baseScale)
|
||||
// Center
|
||||
const x = (conW - imgW * baseScale) / 2
|
||||
const y = (conH - imgH * baseScale) / 2
|
||||
setPan({ x, y })
|
||||
}
|
||||
}, [file.id, conW, conH, baseScale, imgW, imgH])
|
||||
|
||||
const handleZoom = (factor: number) => {
|
||||
const cx = conW / 2
|
||||
const cy = conH / 2
|
||||
|
||||
const newZoom = zoom * factor
|
||||
if (newZoom < 0.01 || newZoom > 50) return
|
||||
|
||||
const newPanX = cx - (cx - pan.x) * (newZoom / zoom)
|
||||
const newPanY = cy - (cy - pan.y) * (newZoom / zoom)
|
||||
|
||||
setZoom(newZoom)
|
||||
setPan({ x: newPanX, y: newPanY })
|
||||
}
|
||||
|
||||
const handleFit = () => {
|
||||
setZoom(baseScale)
|
||||
const x = (conW - imgW * baseScale) / 2
|
||||
const y = (conH - imgH * baseScale) / 2
|
||||
setPan({ x, y })
|
||||
}
|
||||
|
||||
let bestUrl = file.media?.original?.downloadUrl
|
||||
|
||||
const bestTranscode = getBestTranscode(file.media?.imageTranscodes, screenWidth)
|
||||
if (bestTranscode?.url) {
|
||||
bestUrl = bestTranscode.url
|
||||
}
|
||||
|
||||
const handleDownload = 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
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopy = async () => {
|
||||
const webpUrl = bestUrl
|
||||
if (!webpUrl) return
|
||||
try {
|
||||
const copyPromise = (async () => {
|
||||
const response = await fetch(webpUrl)
|
||||
const blob = await response.blob()
|
||||
|
||||
const img = new Image()
|
||||
img.crossOrigin = 'anonymous'
|
||||
const objectUrl = URL.createObjectURL(blob)
|
||||
img.src = objectUrl
|
||||
|
||||
try {
|
||||
await new Promise((resolve, reject) => {
|
||||
img.onload = resolve
|
||||
img.onerror = (e) => reject(new Error('Failed to load image: ' + String(e)))
|
||||
})
|
||||
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = img.width
|
||||
canvas.height = img.height
|
||||
const ctx = canvas.getContext('2d')
|
||||
if (!ctx) throw new Error('Could not get canvas context')
|
||||
ctx.drawImage(img, 0, 0)
|
||||
|
||||
const pngBlob = await new Promise<Blob | null>((resolve) => {
|
||||
canvas.toBlob(resolve, 'image/png')
|
||||
})
|
||||
|
||||
if (!pngBlob) throw new Error('Failed to convert image to PNG')
|
||||
return pngBlob
|
||||
} finally {
|
||||
URL.revokeObjectURL(objectUrl)
|
||||
}
|
||||
})()
|
||||
|
||||
await navigator.clipboard.write([
|
||||
new ClipboardItem({
|
||||
'image/png': copyPromise,
|
||||
}),
|
||||
])
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 2000)
|
||||
} catch (err) {
|
||||
console.error('Failed to copy image to clipboard:', err)
|
||||
}
|
||||
}
|
||||
|
||||
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
|
||||
|
||||
return (
|
||||
<div className="flex flex-col flex-1 h-full overflow-hidden bg-gray-100 dark:bg-gray-950 relative">
|
||||
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
|
||||
{children}
|
||||
<div ref={containerRef} className="flex-1 relative overflow-hidden">
|
||||
<DrawingCanvas
|
||||
width={conW}
|
||||
height={conH}
|
||||
mediaDimensions={{
|
||||
width: imgW,
|
||||
height: imgH,
|
||||
}}
|
||||
imageUrl={bestUrl}
|
||||
annotations={displayAnnotations}
|
||||
scale={zoom}
|
||||
offset={pan}
|
||||
onPan={setPan}
|
||||
className="absolute inset-0 z-0"
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
</div>
|
||||
</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}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export default ImageViewer
|
||||
@@ -0,0 +1,16 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import ImageViewer from './image-viewer'
|
||||
import { CompareImagePane } from './compare-image-pane'
|
||||
|
||||
export const imageTypeDefinition: FileTypeDefinition = {
|
||||
id: 'image',
|
||||
name: 'Image',
|
||||
match: (file) => !!file.mediaType?.startsWith('image/'),
|
||||
viewer: ImageViewer,
|
||||
comparePane: CompareImagePane,
|
||||
commentsConfig: {
|
||||
hasTimestamp: false,
|
||||
hasAnnotations: true,
|
||||
hasAiBots: true,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { FileTypeDefinition } from './types'
|
||||
import { videoTypeDefinition } from './video'
|
||||
import { imageTypeDefinition } from './image'
|
||||
import { defaultTypeDefinition } from './default'
|
||||
|
||||
const registry: FileTypeDefinition[] = [videoTypeDefinition, imageTypeDefinition]
|
||||
|
||||
export function getViewerForFile(file: AssetInfo | null | undefined): FileTypeDefinition {
|
||||
if (!file) return defaultTypeDefinition
|
||||
const match = registry.find((viewer) => viewer.match(file))
|
||||
return match || defaultTypeDefinition
|
||||
}
|
||||
|
||||
export function getAllViewers(): FileTypeDefinition[] {
|
||||
return registry
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import type { Annotation } from '@/ui/types'
|
||||
import type { ComparePaneHandle, PaneReportedState } from '@/ui/components/compare/types'
|
||||
import type React from 'react'
|
||||
|
||||
export interface MediaController {
|
||||
play: () => void
|
||||
pause: () => void
|
||||
seekTo: (second: number) => void
|
||||
getCurrentTime?: () => number
|
||||
getDuration?: () => number
|
||||
}
|
||||
|
||||
export interface FileViewerProps {
|
||||
file: AssetInfo
|
||||
annotations?: Annotation[]
|
||||
onPlay?: () => void
|
||||
onPause?: () => void
|
||||
onTimeUpdate?: (time: number) => void
|
||||
startTime?: number
|
||||
shareId?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
export interface ComparePaneProps {
|
||||
file: AssetInfo
|
||||
isActive: boolean
|
||||
annotations: Annotation[]
|
||||
onStateChange: (state: PaneReportedState) => void
|
||||
onActivate: () => void
|
||||
onUserPan?: (dx: number, dy: number) => void
|
||||
shareId?: string
|
||||
muted?: boolean
|
||||
volume?: number
|
||||
onPlay?: () => void
|
||||
onTimeUpdate?: (second: number) => void
|
||||
onRequestTogglePlay?: () => void
|
||||
}
|
||||
|
||||
export interface FileTypeDefinition {
|
||||
id: string
|
||||
name: string
|
||||
match: (file: AssetInfo) => boolean
|
||||
viewer: React.ForwardRefExoticComponent<FileViewerProps & React.RefAttributes<MediaController>>
|
||||
comparePane?: React.ForwardRefExoticComponent<
|
||||
ComparePaneProps & React.RefAttributes<ComparePaneHandle>
|
||||
>
|
||||
commentsConfig?: {
|
||||
hasTimestamp?: boolean
|
||||
hasAnnotations?: boolean
|
||||
hasAiBots?: boolean
|
||||
}
|
||||
}
|
||||
@@ -1,644 +0,0 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
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 { useFramePlayer } from './use-frame-player'
|
||||
import { resolveTotalFrames } from './utils'
|
||||
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'
|
||||
|
||||
interface VideoPlayerProps {
|
||||
data: AssetInfo
|
||||
playerRef?: React.RefObject<Player | null>
|
||||
onPlay?: () => void
|
||||
onPause?: () => void
|
||||
onTimeUpdate?: (time: number) => void
|
||||
annotations?: Annotation[]
|
||||
startTime?: number
|
||||
shareId?: string
|
||||
children?: React.ReactNode
|
||||
}
|
||||
|
||||
const VideoPlayer: React.FC<VideoPlayerProps> = ({
|
||||
data,
|
||||
playerRef: passedPlayerRef,
|
||||
onPlay,
|
||||
onPause,
|
||||
onTimeUpdate,
|
||||
annotations,
|
||||
startTime,
|
||||
shareId,
|
||||
children,
|
||||
}) => {
|
||||
const localPlayerRef = useRef<Player | null>(null)
|
||||
const playerRef = passedPlayerRef || localPlayerRef
|
||||
// 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)
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
|
||||
const handleZoomChange = (newZoom: number) => {
|
||||
setZoom(newZoom)
|
||||
setHasManuallyZoomed(true)
|
||||
}
|
||||
|
||||
const handleZoomReset = () => {
|
||||
setHasManuallyZoomed(false)
|
||||
}
|
||||
|
||||
// Store
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
// Combine annotations
|
||||
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
|
||||
|
||||
// Resize Observer for container
|
||||
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()
|
||||
}, [])
|
||||
|
||||
// Fit to screen initial / responsive resize
|
||||
useEffect(() => {
|
||||
if (containerSize.width > 0 && containerSize.height > 0) {
|
||||
const vidW = data.media?.metadata?.originalWidth ?? 1920
|
||||
const vidH = data.media?.metadata?.originalHeight ?? 1080
|
||||
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
|
||||
if (!hasManuallyZoomed) {
|
||||
setZoom(scale)
|
||||
}
|
||||
}
|
||||
}, [containerSize.width, containerSize.height, data.media?.metadata, hasManuallyZoomed])
|
||||
|
||||
// Cleanup ref when player is disposed
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
videoRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!data.media?.original?.downloadUrl || !data.media.metadata) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<p className="text-muted-foreground">Media is not available.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Initial resolution setup
|
||||
const originalRes: DisplayTranscode = {
|
||||
id: 'original',
|
||||
url: data.media.original.downloadUrl,
|
||||
key: data.media.original.key ?? '',
|
||||
width: data.media.metadata.originalWidth ?? 0,
|
||||
height: data.media.metadata.originalHeight ?? 0,
|
||||
size: 0,
|
||||
isRaw: true,
|
||||
resolution: 'Original',
|
||||
}
|
||||
|
||||
const resolutions: DisplayTranscode[] = (data.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 previewResolutions = resolutions.filter((r) => !r.isRaw)
|
||||
|
||||
// Logic to select best resolution based on screen size
|
||||
const getInitialResolution = (): DisplayTranscode => {
|
||||
if (previewResolutions.length === 0) return originalRes
|
||||
|
||||
if (typeof window === 'undefined') return previewResolutions[0]
|
||||
|
||||
// Use device pixel ratio for high DPI screens
|
||||
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
|
||||
|
||||
// 1. Sort by width ascending
|
||||
const sortedResolutions = [...previewResolutions].sort((a, b) => {
|
||||
const wA = a.width ?? 0
|
||||
const wB = b.width ?? 0
|
||||
return wA - wB
|
||||
})
|
||||
|
||||
// 2. Find first one >= screenWidth
|
||||
const bestFit = sortedResolutions.find((r) => (r.width ?? 0) >= screenWidth)
|
||||
|
||||
// 3. If found, return it. If not (all are smaller), return the last one (largest).
|
||||
return bestFit || sortedResolutions[sortedResolutions.length - 1]
|
||||
}
|
||||
|
||||
const initialRes = getInitialResolution()
|
||||
|
||||
// State
|
||||
const [state, setState] = useState<PlayerState>({
|
||||
isPlaying: false,
|
||||
progress: 0,
|
||||
currentTime: 0,
|
||||
duration: data.media.metadata.duration || 0,
|
||||
volume: 1,
|
||||
isMuted: false,
|
||||
isLooping: false,
|
||||
playbackRate: 1,
|
||||
isFullScreen: false,
|
||||
showFrames: false,
|
||||
currentResolution: initialRes.resolution,
|
||||
currentSrc: initialRes.url,
|
||||
})
|
||||
|
||||
const [buffered, setBuffered] = useState(0)
|
||||
const [isControlsVisible, setIsControlsVisible] = useState(true)
|
||||
const [isPlayerReady, setIsPlayerReady] = useState(false)
|
||||
const lastProcessedStartTimeRef = useRef<number | null>(null)
|
||||
|
||||
// Frame-accurate hook and derived state
|
||||
const metadata = data.media.metadata
|
||||
const frameRate = metadata.frameRate || 30
|
||||
const dbTotalFrames = metadata.totalFrames || 0
|
||||
const containerDuration = metadata.duration || 0
|
||||
|
||||
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
|
||||
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
|
||||
|
||||
const currentTime = currentFrame / frameRate
|
||||
const duration = totalFrames / frameRate
|
||||
const progress = duration > 0 ? (currentTime / duration) * 100 : 0
|
||||
|
||||
const controlBarState: PlayerState = {
|
||||
...state,
|
||||
currentTime,
|
||||
duration,
|
||||
progress,
|
||||
}
|
||||
|
||||
// Trigger time update event reactively
|
||||
useEffect(() => {
|
||||
if (onTimeUpdate) {
|
||||
onTimeUpdate(currentFrame / frameRate)
|
||||
}
|
||||
}, [currentFrame, frameRate, onTimeUpdate])
|
||||
|
||||
// Initialize Video.js
|
||||
useEffect(() => {
|
||||
if (!videoContainerRef.current) return
|
||||
|
||||
// 1. Create the video element manually
|
||||
// This avoids conflicts with React Strict Mode where the DOM might not match React's virtual DOM expectations after Video.js modifies it.
|
||||
const videoElement = document.createElement('video-js')
|
||||
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
|
||||
|
||||
// Hide it, but keep it in DOM
|
||||
videoElement.style.opacity = '0'
|
||||
videoElement.style.pointerEvents = 'none'
|
||||
|
||||
// Append to our container
|
||||
videoContainerRef.current.appendChild(videoElement)
|
||||
|
||||
// 2. Initialize the player
|
||||
const player = (playerRef.current = videojs(videoElement, {
|
||||
controls: false,
|
||||
autoplay: false,
|
||||
preload: 'auto',
|
||||
playsinline: true,
|
||||
sources: [
|
||||
{
|
||||
src: state.currentSrc,
|
||||
type: 'video/mp4',
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
||||
// Extract video element for Konva
|
||||
const htmlVid = videoElement.querySelector('video')
|
||||
if (htmlVid) {
|
||||
setVideoHtmlEl(htmlVid)
|
||||
videoRef.current = htmlVid
|
||||
} else {
|
||||
// Fallback: try player.tech().el()
|
||||
// Wait for ready?
|
||||
player.ready(() => {
|
||||
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
|
||||
if (techEl) {
|
||||
setVideoHtmlEl(techEl)
|
||||
videoRef.current = techEl
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
player.on('play', () => {
|
||||
setState((p) => ({ ...p, isPlaying: true }))
|
||||
onPlay?.()
|
||||
})
|
||||
player.on('pause', () => {
|
||||
setState((p) => ({ ...p, isPlaying: false }))
|
||||
onPause?.()
|
||||
})
|
||||
player.on('ended', () => setState((p) => ({ ...p, isPlaying: false })))
|
||||
player.on('loadedmetadata', () => {
|
||||
setIsPlayerReady(true)
|
||||
})
|
||||
player.on('loadstart', () => {
|
||||
setIsPlayerReady(false)
|
||||
})
|
||||
|
||||
player.on('timeupdate', () => {
|
||||
const playerDuration = player.duration() || data.media?.metadata?.duration || 0
|
||||
|
||||
const bufferedEnd = player.bufferedEnd()
|
||||
if (playerDuration > 0) {
|
||||
setBuffered((bufferedEnd / playerDuration) * 100)
|
||||
}
|
||||
})
|
||||
|
||||
player.on('volumechange', () => {
|
||||
const vol = player.volume()
|
||||
const muted = player.muted()
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
volume: vol || 0,
|
||||
isMuted: muted || false,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('ratechange', () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
playbackRate: player.playbackRate() || 1,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('error', () => {
|
||||
console.error('VideoJS Error:', player.error())
|
||||
})
|
||||
|
||||
// Set initial state
|
||||
player.volume(state.volume)
|
||||
|
||||
// 4. Cleanup
|
||||
return () => {
|
||||
if (player && !player.isDisposed()) {
|
||||
player.dispose()
|
||||
playerRef.current = null
|
||||
videoRef.current = null
|
||||
}
|
||||
}
|
||||
}, [data])
|
||||
|
||||
// Handle changes to startTime (e.g., clicking different chunks in search results)
|
||||
useEffect(() => {
|
||||
if (!isPlayerReady) return
|
||||
|
||||
if (startTime !== undefined && startTime !== null && startTime > 0) {
|
||||
if (startTime !== lastProcessedStartTimeRef.current) {
|
||||
lastProcessedStartTimeRef.current = startTime
|
||||
const targetFrame = Math.floor(startTime * frameRate + 0.45)
|
||||
seekToFrame(targetFrame)
|
||||
}
|
||||
}
|
||||
}, [startTime, frameRate, seekToFrame, isPlayerReady])
|
||||
|
||||
const scheduleHide = useCallback(() => {
|
||||
if (controlsTimeoutRef.current) {
|
||||
clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
// Never hide while the cursor rests over the control bar itself.
|
||||
if (state.isFullScreen && !isOverControlsRef.current) {
|
||||
controlsTimeoutRef.current = setTimeout(() => {
|
||||
setIsControlsVisible(false)
|
||||
}, 1200)
|
||||
}
|
||||
}, [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 the cursor leaves the player while fullscreen, hide the controls.
|
||||
if (state.isFullScreen) {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
setIsControlsVisible(false)
|
||||
}
|
||||
}, [state.isFullScreen])
|
||||
|
||||
// Clean up timeout on unmount or state change
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 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.isFullScreen) {
|
||||
setIsControlsVisible(true)
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
} else {
|
||||
handleMouseMove()
|
||||
}
|
||||
}, [state.isPlaying, state.isFullScreen, handleMouseMove])
|
||||
|
||||
// -- Event Handlers --
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
// Disable click-to-play if drawing
|
||||
if (useAnnotationStore.getState().isDrawing) return
|
||||
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
if (player.paused() || player.ended()) {
|
||||
const playPromise = player.play()
|
||||
if (playPromise !== undefined) {
|
||||
playPromise.catch((error) => {
|
||||
// Ignore AbortError which happens when pausing rapidly after playing
|
||||
if (error.name === 'AbortError') return
|
||||
console.error('Play failed:', error)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
player.pause()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const toggleLoop = () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const newLoop = !state.isLooping
|
||||
player.loop(newLoop)
|
||||
setState((prev) => ({ ...prev, isLooping: newLoop }))
|
||||
}
|
||||
|
||||
const handleVolumeChange = (newVolume: number) => {
|
||||
// Optimistic update to prevent slider jumping and ensure immediate UI feedback
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
volume: newVolume,
|
||||
isMuted: newVolume === 0, // If dragging to 0, consider it muted
|
||||
}))
|
||||
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
// Set volume first so if we unmute, it is at the correct level
|
||||
player.volume(newVolume)
|
||||
|
||||
// Manage mute state based on volume
|
||||
if (newVolume > 0 && player.muted()) {
|
||||
player.muted(false)
|
||||
} else if (newVolume === 0 && !player.muted()) {
|
||||
player.muted(true)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleMute = () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
const isMuted = player.muted()
|
||||
if (isMuted) {
|
||||
player.muted(false)
|
||||
// If volume was 0 (e.g. user dragged to 0), restore to default 0.5 so they hear something
|
||||
if (player.volume() === 0) {
|
||||
player.volume(0.5)
|
||||
}
|
||||
} else {
|
||||
player.muted(true)
|
||||
}
|
||||
}
|
||||
|
||||
const changePlaybackRate = (rate: number) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.playbackRate(rate)
|
||||
}
|
||||
|
||||
const changeResolution = (res: DisplayTranscode) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
const wasPlaying = !player.paused()
|
||||
const currentT = player.currentTime()
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentResolution: res.resolution,
|
||||
currentSrc: res.url,
|
||||
}))
|
||||
|
||||
player.src({ type: 'video/mp4', src: res.url })
|
||||
|
||||
player.one('loadedmetadata', () => {
|
||||
player.currentTime(currentT)
|
||||
if (wasPlaying) {
|
||||
const playPromise = player.play()
|
||||
if (playPromise !== undefined) {
|
||||
playPromise.catch((error) => {
|
||||
if (error.name === 'AbortError') return
|
||||
console.error('Play after seek failed:', error)
|
||||
})
|
||||
}
|
||||
}
|
||||
player.playbackRate(state.playbackRate)
|
||||
})
|
||||
}
|
||||
|
||||
const toggleFullScreen = () => {
|
||||
if (!rootRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
rootRef.current.requestFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: false }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = async (key: string) => {
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: data.id! },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: data.id! },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for fullscreen change events (ESC key)
|
||||
useEffect(() => {
|
||||
const onFsChange = () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
isFullScreen: !!document.fullscreenElement,
|
||||
}))
|
||||
}
|
||||
document.addEventListener('fullscreenchange', onFsChange)
|
||||
return () => document.removeEventListener('fullscreenchange', onFsChange)
|
||||
}, [])
|
||||
|
||||
// Calculate center pan
|
||||
const vidW = data.media?.metadata?.originalWidth ?? 1920
|
||||
const vidH = data.media?.metadata?.originalHeight ?? 1080
|
||||
|
||||
const scale = zoom
|
||||
const panX = (containerSize.width - vidW * scale) / 2
|
||||
const panY = (containerSize.height - vidH * scale) / 2
|
||||
|
||||
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',
|
||||
!isControlsVisible && state.isFullScreen ? 'cursor-none' : '',
|
||||
)}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
|
||||
{/* Render Carousel/Sidebar here if not fullscreen */}
|
||||
{!state.isFullScreen && children}
|
||||
|
||||
{/* Video Area */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0',
|
||||
)}
|
||||
onClick={togglePlay}
|
||||
data-vjs-player
|
||||
data-testid="video-area"
|
||||
>
|
||||
{/* Hidden VideoJS container */}
|
||||
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
|
||||
|
||||
{/* Drawing Canvas (Visible) */}
|
||||
{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={togglePlay}
|
||||
// Drawing Props
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Big Play Button Overlay (when paused) */}
|
||||
{!state.isPlaying && !isDrawing && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
|
||||
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
|
||||
<Play className="w-10 h-10 text-white ml-1 fill-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<VideoControlBar
|
||||
state={controlBarState}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
buffered={buffered}
|
||||
data={data}
|
||||
resolutions={resolutions}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={toggleLoop}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={handleVolumeChange}
|
||||
changePlaybackRate={changePlaybackRate}
|
||||
changeResolution={changeResolution}
|
||||
handleDownload={handleDownload}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
frameRate={frameRate}
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
seekToFrame={seekToFrame}
|
||||
onMouseEnter={handleControlsMouseEnter}
|
||||
onMouseLeave={handleControlsMouseLeave}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default VideoPlayer
|
||||
@@ -0,0 +1,470 @@
|
||||
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 './use-frame-player'
|
||||
import { resolveTotalFrames } from './utils'
|
||||
import { clampFrame as clampFrameUtil } from '../../compare/compare-utils'
|
||||
import type { ComparePaneHandle, DisplayTranscode, PaneReportedState } from '../../compare/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 = true,
|
||||
volume = 1,
|
||||
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 totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
|
||||
|
||||
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,16 @@
|
||||
import { FileTypeDefinition } from '../types'
|
||||
import VideoViewer from './video-viewer'
|
||||
import { CompareVideoPane } from './compare-video-pane'
|
||||
|
||||
export const videoTypeDefinition: FileTypeDefinition = {
|
||||
id: 'video',
|
||||
name: 'Video',
|
||||
match: (file) => !!file.mediaType?.startsWith('video/'),
|
||||
viewer: VideoViewer,
|
||||
comparePane: CompareVideoPane,
|
||||
commentsConfig: {
|
||||
hasTimestamp: true,
|
||||
hasAnnotations: true,
|
||||
hasAiBots: true,
|
||||
},
|
||||
}
|
||||
+3
-3
@@ -23,8 +23,8 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuTrigger,
|
||||
} from '../ui/dropdown-menu'
|
||||
import { Slider } from '../ui/slider'
|
||||
} from '../../ui/dropdown-menu'
|
||||
import { Slider } from '../../ui/slider'
|
||||
import ProgressBar from './progress-bar'
|
||||
import { formatTime, formatTimecode } from './utils'
|
||||
|
||||
@@ -196,7 +196,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
|
||||
<div className="w-24 px-1">
|
||||
<Slider
|
||||
value={state.isMuted ? [0] : [state.volume]}
|
||||
onValueChange={(v) => handleVolumeChange(v[0])}
|
||||
onValueChange={(v: number[]) => handleVolumeChange(v[0])}
|
||||
max={1}
|
||||
step={0.05}
|
||||
/>
|
||||
@@ -0,0 +1,649 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { Play } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useRef, useState, useImperativeHandle } from 'react'
|
||||
import videojs from 'video.js'
|
||||
import type Player from 'video.js/dist/types/player'
|
||||
import { useFramePlayer } from './use-frame-player'
|
||||
import { resolveTotalFrames } from './utils'
|
||||
import { VideoControlBar, type PlayerState, type DisplayTranscode } from './video-control-bar'
|
||||
import DrawingCanvas from '@/ui/components/drawing-canvas'
|
||||
import { useAnnotationStore } from '@/ui/stores/annotation-store'
|
||||
import { FileViewerProps, MediaController } from '../types'
|
||||
|
||||
const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
|
||||
(
|
||||
{ file: data, onPlay, onPause, onTimeUpdate, annotations, startTime, shareId, children },
|
||||
ref,
|
||||
) => {
|
||||
const localPlayerRef = useRef<Player | null>(null)
|
||||
const playerRef = localPlayerRef
|
||||
// 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)
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
play: () => {
|
||||
if (localPlayerRef.current) {
|
||||
localPlayerRef.current.play()
|
||||
}
|
||||
},
|
||||
pause: () => {
|
||||
if (localPlayerRef.current) {
|
||||
localPlayerRef.current.pause()
|
||||
}
|
||||
},
|
||||
seekTo: (second: number) => {
|
||||
if (localPlayerRef.current) {
|
||||
localPlayerRef.current.currentTime(second)
|
||||
}
|
||||
},
|
||||
getCurrentTime: () => {
|
||||
return (localPlayerRef.current ? localPlayerRef.current.currentTime() : 0) ?? 0
|
||||
},
|
||||
getDuration: () => {
|
||||
return (localPlayerRef.current ? localPlayerRef.current.duration() : 0) ?? 0
|
||||
},
|
||||
}))
|
||||
const isOverControlsRef = useRef(false)
|
||||
|
||||
const [videoHtmlEl, setVideoHtmlEl] = useState<HTMLVideoElement | undefined>(undefined)
|
||||
const videoRef = useRef<HTMLVideoElement | null>(null)
|
||||
const [zoom, setZoom] = useState(1)
|
||||
const [hasManuallyZoomed, setHasManuallyZoomed] = useState(false)
|
||||
const [containerSize, setContainerSize] = useState({ width: 0, height: 0 })
|
||||
|
||||
const handleZoomChange = (newZoom: number) => {
|
||||
setZoom(newZoom)
|
||||
setHasManuallyZoomed(true)
|
||||
}
|
||||
|
||||
const handleZoomReset = () => {
|
||||
setHasManuallyZoomed(false)
|
||||
}
|
||||
|
||||
// Store
|
||||
const {
|
||||
isDrawing,
|
||||
currentTool,
|
||||
currentColor,
|
||||
addAnnotation,
|
||||
annotations: draftAnnotations,
|
||||
} = useAnnotationStore()
|
||||
|
||||
// Combine annotations
|
||||
const displayAnnotations = [...(annotations || []), ...draftAnnotations]
|
||||
|
||||
// Resize Observer for container
|
||||
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()
|
||||
}, [])
|
||||
|
||||
// Fit to screen initial / responsive resize
|
||||
useEffect(() => {
|
||||
if (containerSize.width > 0 && containerSize.height > 0) {
|
||||
const vidW = data.media?.metadata?.originalWidth ?? 1920
|
||||
const vidH = data.media?.metadata?.originalHeight ?? 1080
|
||||
const scale = Math.min(containerSize.width / vidW, containerSize.height / vidH)
|
||||
if (!hasManuallyZoomed) {
|
||||
setZoom(scale)
|
||||
}
|
||||
}
|
||||
}, [containerSize.width, containerSize.height, data.media?.metadata, hasManuallyZoomed])
|
||||
|
||||
// Cleanup ref when player is disposed
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
videoRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
if (!data.media?.original?.downloadUrl || !data.media.metadata) {
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center">
|
||||
<p className="text-muted-foreground">Media is not available.</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// Initial resolution setup
|
||||
const originalRes: DisplayTranscode = {
|
||||
id: 'original',
|
||||
url: data.media.original.downloadUrl,
|
||||
key: data.media.original.key ?? '',
|
||||
width: data.media.metadata.originalWidth ?? 0,
|
||||
height: data.media.metadata.originalHeight ?? 0,
|
||||
size: 0,
|
||||
isRaw: true,
|
||||
resolution: 'Original',
|
||||
}
|
||||
|
||||
const resolutions: DisplayTranscode[] = (data.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 previewResolutions = resolutions.filter((r) => !r.isRaw)
|
||||
|
||||
// Logic to select best resolution based on screen size
|
||||
const getInitialResolution = (): DisplayTranscode => {
|
||||
if (previewResolutions.length === 0) return originalRes
|
||||
|
||||
if (typeof window === 'undefined') return previewResolutions[0]
|
||||
|
||||
// Use device pixel ratio for high DPI screens
|
||||
const screenWidth = window.innerWidth * (window.devicePixelRatio || 1)
|
||||
|
||||
// 1. Sort by width ascending
|
||||
const sortedResolutions = [...previewResolutions].sort((a, b) => {
|
||||
const wA = a.width ?? 0
|
||||
const wB = b.width ?? 0
|
||||
return wA - wB
|
||||
})
|
||||
|
||||
// 2. Find first one >= screenWidth
|
||||
const bestFit = sortedResolutions.find((r) => (r.width ?? 0) >= screenWidth)
|
||||
|
||||
// 3. If found, return it. If not (all are smaller), return the last one (largest).
|
||||
return bestFit || sortedResolutions[sortedResolutions.length - 1]
|
||||
}
|
||||
|
||||
const initialRes = getInitialResolution()
|
||||
|
||||
// State
|
||||
const [state, setState] = useState<PlayerState>({
|
||||
isPlaying: false,
|
||||
progress: 0,
|
||||
currentTime: 0,
|
||||
duration: data.media.metadata.duration || 0,
|
||||
volume: 1,
|
||||
isMuted: false,
|
||||
isLooping: false,
|
||||
playbackRate: 1,
|
||||
isFullScreen: false,
|
||||
showFrames: false,
|
||||
currentResolution: initialRes.resolution,
|
||||
currentSrc: initialRes.url,
|
||||
})
|
||||
|
||||
const [buffered, setBuffered] = useState(0)
|
||||
const [isControlsVisible, setIsControlsVisible] = useState(true)
|
||||
const [isPlayerReady, setIsPlayerReady] = useState(false)
|
||||
const lastProcessedStartTimeRef = useRef<number | null>(null)
|
||||
|
||||
// Frame-accurate hook and derived state
|
||||
const metadata = data.media.metadata
|
||||
const frameRate = metadata.frameRate || 30
|
||||
const dbTotalFrames = metadata.totalFrames || 0
|
||||
const containerDuration = metadata.duration || 0
|
||||
|
||||
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
|
||||
const { currentFrame, seekToFrame } = useFramePlayer(videoRef, frameRate, totalFrames)
|
||||
|
||||
const currentTime = currentFrame / frameRate
|
||||
const duration = totalFrames / frameRate
|
||||
const progress = duration > 0 ? (currentTime / duration) * 100 : 0
|
||||
|
||||
const controlBarState: PlayerState = {
|
||||
...state,
|
||||
currentTime,
|
||||
duration,
|
||||
progress,
|
||||
}
|
||||
|
||||
// Trigger time update event reactively
|
||||
useEffect(() => {
|
||||
if (onTimeUpdate) {
|
||||
onTimeUpdate(currentFrame / frameRate)
|
||||
}
|
||||
}, [currentFrame, frameRate, onTimeUpdate])
|
||||
|
||||
// Initialize Video.js
|
||||
useEffect(() => {
|
||||
if (!videoContainerRef.current) return
|
||||
|
||||
// 1. Create the video element manually
|
||||
// This avoids conflicts with React Strict Mode where the DOM might not match React's virtual DOM expectations after Video.js modifies it.
|
||||
const videoElement = document.createElement('video-js')
|
||||
videoElement.classList.add('vjs-big-play-centered', '!h-full', '!w-full')
|
||||
|
||||
// Hide it, but keep it in DOM
|
||||
videoElement.style.opacity = '0'
|
||||
videoElement.style.pointerEvents = 'none'
|
||||
|
||||
// Append to our container
|
||||
videoContainerRef.current.appendChild(videoElement)
|
||||
|
||||
// 2. Initialize the player
|
||||
const player = (playerRef.current = videojs(videoElement, {
|
||||
controls: false,
|
||||
autoplay: false,
|
||||
preload: 'auto',
|
||||
playsinline: true,
|
||||
sources: [
|
||||
{
|
||||
src: state.currentSrc,
|
||||
type: 'video/mp4',
|
||||
},
|
||||
],
|
||||
}))
|
||||
|
||||
// Extract video element for Konva
|
||||
const htmlVid = videoElement.querySelector('video')
|
||||
if (htmlVid) {
|
||||
setVideoHtmlEl(htmlVid)
|
||||
videoRef.current = htmlVid
|
||||
} else {
|
||||
// Fallback: try player.tech().el()
|
||||
// Wait for ready?
|
||||
player.ready(() => {
|
||||
const techEl = player.tech({ iWillNotUseThisInPlugins: true })?.el() as HTMLVideoElement
|
||||
if (techEl) {
|
||||
setVideoHtmlEl(techEl)
|
||||
videoRef.current = techEl
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
player.on('play', () => {
|
||||
setState((p) => ({ ...p, isPlaying: true }))
|
||||
onPlay?.()
|
||||
})
|
||||
player.on('pause', () => {
|
||||
setState((p) => ({ ...p, isPlaying: false }))
|
||||
onPause?.()
|
||||
})
|
||||
player.on('ended', () => setState((p) => ({ ...p, isPlaying: false })))
|
||||
player.on('loadedmetadata', () => {
|
||||
setIsPlayerReady(true)
|
||||
})
|
||||
player.on('loadstart', () => {
|
||||
setIsPlayerReady(false)
|
||||
})
|
||||
|
||||
player.on('timeupdate', () => {
|
||||
const playerDuration = player.duration() || data.media?.metadata?.duration || 0
|
||||
|
||||
const bufferedEnd = player.bufferedEnd()
|
||||
if (playerDuration > 0) {
|
||||
setBuffered((bufferedEnd / playerDuration) * 100)
|
||||
}
|
||||
})
|
||||
|
||||
player.on('volumechange', () => {
|
||||
const vol = player.volume()
|
||||
const muted = player.muted()
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
volume: vol || 0,
|
||||
isMuted: muted || false,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('ratechange', () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
playbackRate: player.playbackRate() || 1,
|
||||
}))
|
||||
})
|
||||
|
||||
player.on('error', () => {
|
||||
console.error('VideoJS Error:', player.error())
|
||||
})
|
||||
|
||||
// Set initial state
|
||||
player.volume(state.volume)
|
||||
|
||||
// 4. Cleanup
|
||||
return () => {
|
||||
if (player && !player.isDisposed()) {
|
||||
player.dispose()
|
||||
playerRef.current = null
|
||||
videoRef.current = null
|
||||
}
|
||||
}
|
||||
}, [data])
|
||||
|
||||
// Handle changes to startTime (e.g., clicking different chunks in search results)
|
||||
useEffect(() => {
|
||||
if (!isPlayerReady) return
|
||||
|
||||
if (startTime !== undefined && startTime !== null && startTime > 0) {
|
||||
if (startTime !== lastProcessedStartTimeRef.current) {
|
||||
lastProcessedStartTimeRef.current = startTime
|
||||
const targetFrame = Math.floor(startTime * frameRate + 0.45)
|
||||
seekToFrame(targetFrame)
|
||||
}
|
||||
}
|
||||
}, [startTime, frameRate, seekToFrame, isPlayerReady])
|
||||
|
||||
const scheduleHide = useCallback(() => {
|
||||
if (controlsTimeoutRef.current) {
|
||||
clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
// Never hide while the cursor rests over the control bar itself.
|
||||
if (state.isFullScreen && !isOverControlsRef.current) {
|
||||
controlsTimeoutRef.current = setTimeout(() => {
|
||||
setIsControlsVisible(false)
|
||||
}, 1200)
|
||||
}
|
||||
}, [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 the cursor leaves the player while fullscreen, hide the controls.
|
||||
if (state.isFullScreen) {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
setIsControlsVisible(false)
|
||||
}
|
||||
}, [state.isFullScreen])
|
||||
|
||||
// Clean up timeout on unmount or state change
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
}
|
||||
}, [])
|
||||
|
||||
// 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.isFullScreen) {
|
||||
setIsControlsVisible(true)
|
||||
if (controlsTimeoutRef.current) clearTimeout(controlsTimeoutRef.current)
|
||||
} else {
|
||||
handleMouseMove()
|
||||
}
|
||||
}, [state.isPlaying, state.isFullScreen, handleMouseMove])
|
||||
|
||||
// -- Event Handlers --
|
||||
|
||||
const togglePlay = useCallback(() => {
|
||||
// Disable click-to-play if drawing
|
||||
if (useAnnotationStore.getState().isDrawing) return
|
||||
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
if (player.paused() || player.ended()) {
|
||||
const playPromise = player.play()
|
||||
if (playPromise !== undefined) {
|
||||
playPromise.catch((error) => {
|
||||
// Ignore AbortError which happens when pausing rapidly after playing
|
||||
if (error.name === 'AbortError') return
|
||||
console.error('Play failed:', error)
|
||||
})
|
||||
}
|
||||
} else {
|
||||
player.pause()
|
||||
}
|
||||
}, [])
|
||||
|
||||
const toggleLoop = () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
const newLoop = !state.isLooping
|
||||
player.loop(newLoop)
|
||||
setState((prev) => ({ ...prev, isLooping: newLoop }))
|
||||
}
|
||||
|
||||
const handleVolumeChange = (newVolume: number) => {
|
||||
// Optimistic update to prevent slider jumping and ensure immediate UI feedback
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
volume: newVolume,
|
||||
isMuted: newVolume === 0, // If dragging to 0, consider it muted
|
||||
}))
|
||||
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
// Set volume first so if we unmute, it is at the correct level
|
||||
player.volume(newVolume)
|
||||
|
||||
// Manage mute state based on volume
|
||||
if (newVolume > 0 && player.muted()) {
|
||||
player.muted(false)
|
||||
} else if (newVolume === 0 && !player.muted()) {
|
||||
player.muted(true)
|
||||
}
|
||||
}
|
||||
|
||||
const toggleMute = () => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
const isMuted = player.muted()
|
||||
if (isMuted) {
|
||||
player.muted(false)
|
||||
// If volume was 0 (e.g. user dragged to 0), restore to default 0.5 so they hear something
|
||||
if (player.volume() === 0) {
|
||||
player.volume(0.5)
|
||||
}
|
||||
} else {
|
||||
player.muted(true)
|
||||
}
|
||||
}
|
||||
|
||||
const changePlaybackRate = (rate: number) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
player.playbackRate(rate)
|
||||
}
|
||||
|
||||
const changeResolution = (res: DisplayTranscode) => {
|
||||
const player = playerRef.current
|
||||
if (!player) return
|
||||
|
||||
const wasPlaying = !player.paused()
|
||||
const currentT = player.currentTime()
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentResolution: res.resolution,
|
||||
currentSrc: res.url,
|
||||
}))
|
||||
|
||||
player.src({ type: 'video/mp4', src: res.url })
|
||||
|
||||
player.one('loadedmetadata', () => {
|
||||
player.currentTime(currentT)
|
||||
if (wasPlaying) {
|
||||
const playPromise = player.play()
|
||||
if (playPromise !== undefined) {
|
||||
playPromise.catch((error) => {
|
||||
if (error.name === 'AbortError') return
|
||||
console.error('Play after seek failed:', error)
|
||||
})
|
||||
}
|
||||
}
|
||||
player.playbackRate(state.playbackRate)
|
||||
})
|
||||
}
|
||||
|
||||
const toggleFullScreen = () => {
|
||||
if (!rootRef.current) return
|
||||
if (!document.fullscreenElement) {
|
||||
rootRef.current.requestFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: true }))
|
||||
} else {
|
||||
document.exitFullscreen()
|
||||
setState((prev) => ({ ...prev, isFullScreen: false }))
|
||||
}
|
||||
}
|
||||
|
||||
const handleDownload = async (key: string) => {
|
||||
try {
|
||||
const res = shareId
|
||||
? await client.api.shares[':shareId'].files[':fileId']['download-url'].$post({
|
||||
param: { shareId, fileId: data.id! },
|
||||
json: { key },
|
||||
})
|
||||
: await client.api.files['download-url'].$post({
|
||||
json: { key, assetId: data.id! },
|
||||
})
|
||||
if (!res.ok) return
|
||||
const { url } = await res.json()
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = ''
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
} catch {
|
||||
// silently fail
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for fullscreen change events (ESC key)
|
||||
useEffect(() => {
|
||||
const onFsChange = () => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
isFullScreen: !!document.fullscreenElement,
|
||||
}))
|
||||
}
|
||||
document.addEventListener('fullscreenchange', onFsChange)
|
||||
return () => document.removeEventListener('fullscreenchange', onFsChange)
|
||||
}, [])
|
||||
|
||||
// Calculate center pan
|
||||
const vidW = data.media?.metadata?.originalWidth ?? 1920
|
||||
const vidH = data.media?.metadata?.originalHeight ?? 1080
|
||||
|
||||
const scale = zoom
|
||||
const panX = (containerSize.width - vidW * scale) / 2
|
||||
const panY = (containerSize.height - vidH * scale) / 2
|
||||
|
||||
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',
|
||||
!isControlsVisible && state.isFullScreen ? 'cursor-none' : '',
|
||||
)}
|
||||
onMouseMove={handleMouseMove}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
>
|
||||
<div className="flex-1 flex flex-col-reverse md:flex-row min-h-0 relative">
|
||||
{/* Render Carousel/Sidebar here if not fullscreen */}
|
||||
{!state.isFullScreen && children}
|
||||
|
||||
{/* Video Area */}
|
||||
<div
|
||||
ref={containerRef}
|
||||
className={cn(
|
||||
'flex-1 bg-black cursor-pointer relative flex items-center justify-center overflow-hidden min-h-0',
|
||||
)}
|
||||
onClick={togglePlay}
|
||||
data-vjs-player
|
||||
data-testid="video-area"
|
||||
>
|
||||
{/* Hidden VideoJS container */}
|
||||
<div ref={videoContainerRef} className="absolute inset-0 z-[-1]" />
|
||||
|
||||
{/* Drawing Canvas (Visible) */}
|
||||
{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={togglePlay}
|
||||
// Drawing Props
|
||||
isDrawing={isDrawing}
|
||||
currentTool={currentTool}
|
||||
currentColor={currentColor}
|
||||
onAddAnnotation={addAnnotation}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Big Play Button Overlay (when paused) */}
|
||||
{!state.isPlaying && !isDrawing && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-black/20 pointer-events-none z-10">
|
||||
<div className="w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full flex items-center justify-center border-2 border-white/30 animate-pulse">
|
||||
<Play className="w-10 h-10 text-white ml-1 fill-white" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<VideoControlBar
|
||||
state={controlBarState}
|
||||
zoom={zoom}
|
||||
isControlsVisible={isControlsVisible}
|
||||
buffered={buffered}
|
||||
data={data}
|
||||
resolutions={resolutions}
|
||||
togglePlay={togglePlay}
|
||||
toggleLoop={toggleLoop}
|
||||
toggleMute={toggleMute}
|
||||
handleVolumeChange={handleVolumeChange}
|
||||
changePlaybackRate={changePlaybackRate}
|
||||
changeResolution={changeResolution}
|
||||
handleDownload={handleDownload}
|
||||
toggleFullScreen={toggleFullScreen}
|
||||
onZoomChange={handleZoomChange}
|
||||
onZoomReset={handleZoomReset}
|
||||
frameRate={frameRate}
|
||||
totalFrames={totalFrames}
|
||||
currentFrame={currentFrame}
|
||||
seekToFrame={seekToFrame}
|
||||
onMouseEnter={handleControlsMouseEnter}
|
||||
onMouseLeave={handleControlsMouseLeave}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
)
|
||||
|
||||
export default VideoViewer
|
||||
Reference in New Issue
Block a user