feat(video): add video transcripts (#559)

* feat(video): generate transcripts with the local embedding server

* feat(video): show saved transcripts in the player

* fix(video): preserve transcript seek timestamps

* fix(video): refine transcript viewing and generation

* feat(video): resize transcripts and follow playback earlier

* fix(video): animate transcript playback scrolling

* fix(video): transcribe from the smallest full proxy

* fix(video): refine the sync to playback button

* feat(video): edit transcript segment text inline

* fix(video): keep transcript segment highlighted over edit button

* docs(video): note embedding server version for transcripts
This commit is contained in:
Yiling-J
2026-12-04 13:49:25 +08:00
committed by GitHub
parent e420f03b35
commit d3899d1257
69 changed files with 7635 additions and 174 deletions
@@ -31,6 +31,15 @@ describe('FileBrowserContextMenu', () => {
updatedAt: '2026-01-01T00:00:00Z',
} as AssetInfo
const fullProxy = {
id: 'proxy-480p',
url: '/video-480p.mp4',
key: 'video-480p.mp4',
width: 854,
height: 480,
size: 100,
}
const renderWithMenu = (
item: AssetInfo,
props: Partial<React.ComponentProps<typeof FileBrowserContextMenu>> = {},
@@ -87,6 +96,71 @@ describe('FileBrowserContextMenu', () => {
expect(screen.queryByRole('menuitem', { name: 'Open in new tab' })).toBeNull()
})
it('starts transcription on the displayed video file in a stack', () => {
const onGenerateTranscripts = vi.fn()
renderWithMenu(
{
...stackItem,
proxyType: 'video',
media: { videoTranscodes: [fullProxy] },
versionStack: {
id: stackItem.id,
versions: [
{ id: 'old', name: 'old.mp4', version: 1, current: false },
{ id: 'current', name: 'current.mp4', version: 2, current: true },
],
},
},
{ onGenerateTranscripts },
)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
fireEvent.click(screen.getByRole('menuitem', { name: 'Generate Transcripts' }))
expect(onGenerateTranscripts).toHaveBeenCalledWith('current', 'current.mp4')
})
it.each([
{ status: 'uploaded', media: undefined },
{ status: 'processing', media: { videoTranscodes: [fullProxy] } },
{ status: 'processed', media: { videoPreview: { url: '/preview.mp4', key: 'preview.mp4' } } },
])('disables generation for a $status video until a full proxy is ready', ({ status, media }) => {
const onGenerateTranscripts = vi.fn()
renderWithMenu(
{ ...fileItem, mediaType: 'video/mp4', status, media },
{ onGenerateTranscripts },
)
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
const action = screen.getByRole('menuitem', { name: 'Generate Transcripts' })
expect(action.getAttribute('aria-disabled')).toBe('true')
fireEvent.click(action)
expect(onGenerateTranscripts).not.toHaveBeenCalled()
})
it.each([
{
label: 'a read-only member',
item: { ...fileItem, proxyType: 'video' as const },
canEdit: false,
},
{ label: 'a non-video asset', item: fileItem, canEdit: true },
{
label: 'an audio-only upload with a video MIME type',
item: { ...fileItem, proxyType: 'audio' as const, mediaType: 'video/mp4' },
canEdit: true,
},
{
label: 'an archived video',
item: { ...fileItem, proxyType: 'video' as const, status: 'archived' },
canEdit: true,
},
])('hides the action for $label', ({ item, canEdit }) => {
renderWithMenu(item, { canEdit, onGenerateTranscripts: vi.fn() })
fireEvent.contextMenu(screen.getByTestId('context-trigger'))
expect(screen.queryByRole('menuitem', { name: 'Generate Transcripts' })).toBeNull()
})
it('renders Manage versions for version_stack item when canEdit is true', () => {
const onManageVersions = vi.fn()
renderWithMenu(stackItem, { onManageVersions })
@@ -1,5 +1,4 @@
import type { AssetInfo } from '@shumai/dtos'
import type { ShareLinkInfo } from '@shumai/dtos'
import { selectTranscriptVideoProxyKey, type AssetInfo, type ShareLinkInfo } from '@shumai/dtos'
import { m } from '@/ui/paraglide/messages.js'
import {
ContextMenuContent,
@@ -27,6 +26,7 @@ import {
Copy,
Layers,
ScanSearch,
Captions,
} from 'lucide-react'
import { CopyContextMenuSub } from './copy-submenu'
import { isImageItem, type CopyKind } from './copy-options'
@@ -40,6 +40,7 @@ interface FileBrowserContextMenuProps {
onDownload: (items: AssetInfo[]) => void
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
onFindSimilar?: (item: AssetInfo) => void
onGenerateTranscripts?: (assetId: string, name: string) => void
onRestore: (items: AssetInfo[]) => void
onArchive?: (items: AssetInfo[]) => void
onRestoreArchive?: (items: AssetInfo[]) => void
@@ -75,6 +76,7 @@ export function FileBrowserContextMenu({
onDownload,
onCopy,
onFindSimilar,
onGenerateTranscripts,
onRestore,
onArchive,
onRestoreArchive,
@@ -237,6 +239,18 @@ export function FileBrowserContextMenu({
</ContextMenuItem>
)
const videoVersion =
item.type === 'version_stack'
? item.versionStack?.versions.find((version) => version.current)
: undefined
const transcriptAssetId = item.type === 'file' ? item.id : videoVersion?.id
const transcriptAssetStatus = videoVersion?.status ?? item.status
const isTranscriptVideo = item.proxyType
? item.proxyType === 'video'
: item.mediaType?.startsWith('video/')
const transcriptReady =
transcriptAssetStatus === 'processed' && Boolean(selectTranscriptVideoProxyKey(item.media))
const contextMenuContent =
isItemSelected && selectedIds.size > 1 ? (
<ContextMenuContent
@@ -360,6 +374,21 @@ export function FileBrowserContextMenu({
<span>{m.download()}</span>
</ContextMenuItem>
{findSimilarItem}
{canEdit &&
onGenerateTranscripts &&
transcriptAssetId &&
['uploading', 'uploaded', 'processing', 'processed'].includes(transcriptAssetStatus) &&
isTranscriptVideo && (
<ContextMenuItem
disabled={!transcriptReady}
onSelect={() =>
onGenerateTranscripts(transcriptAssetId, videoVersion?.name || item.name)
}
>
<Captions className="mr-2 h-4 w-4" />
<span>{m.generate_transcripts()}</span>
</ContextMenuItem>
)}
<CopyContextMenuSub
items={itemsToModify}
context={{
@@ -30,6 +30,7 @@ import { FilePreviewDialog } from '../file-preview-dialog'
import { ShareLinkCreatedDialog } from '../share-link-created-dialog'
import { FileBrowserContentSkeleton } from '../loading-skeletons'
import { FileBrowserContextMenu } from './context-menu'
import { GenerateTranscriptsDialog } from './generate-transcripts-dialog'
import { getItemInAppUrl } from './copy-options'
import { FindSimilarDialog } from '../search/find-similar-dialog'
import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled'
@@ -63,6 +64,7 @@ import { FileBrowserToolbar } from './toolbar'
import { useFileActions } from './use-file-actions'
import { useBatchFileStatus } from '@/ui/hooks/use-batch-file-status'
import { useArchiveConfig } from '@/ui/hooks/use-archive-config'
import { useServerFeatures } from '@/ui/hooks/use-server-features'
import { ArchiveConfirmDialog } from '../archive-confirm-dialog'
interface FileBrowserProps {
@@ -161,6 +163,9 @@ export function FileBrowser({
}: FileBrowserProps) {
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
const [transcriptVideo, setTranscriptVideo] = useState<{ id: string; name: string } | null>(null)
const closeTranscriptDialog = useCallback(() => setTranscriptVideo(null), [])
const transcriptionEnabled = useServerFeatures().data?.transcriptionEnabled
const semanticSearchEnabled = useSemanticSearchEnabled(
teamId,
Boolean(
@@ -1122,6 +1127,11 @@ export function FileBrowser({
onDownload={handleDownload}
onCopy={handleCopy}
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
onGenerateTranscripts={
transcriptionEnabled && !isShareView && !isPublic
? (id, name) => setTranscriptVideo({ id, name })
: undefined
}
onNewFolder={handleNewFolder}
onUploadFile={handleUploadFilesClick}
onUploadFolder={handleUploadFolderClick}
@@ -1182,6 +1192,15 @@ export function FileBrowser({
)}
{renderContent()}
{transcriptVideo && (
<GenerateTranscriptsDialog
key={transcriptVideo.id}
assetId={transcriptVideo.id}
name={transcriptVideo.name}
onClose={closeTranscriptDialog}
/>
)}
{semanticSearchEnabled && similarImage && rootFolderId && (
<FindSimilarDialog
image={similarImage}
@@ -0,0 +1,227 @@
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import type { TranscriptJobStatus } from '@shumai/dtos'
import { toast } from 'sonner'
import { client } from '@/ui/api/client'
import { m } from '@/ui/paraglide/messages.js'
import { savedTranscriptLanguagesKey } from '@/ui/hooks/use-video-transcript'
import { Button } from '@/ui/components/ui/button'
import {
Combobox,
ComboboxContent,
ComboboxEmpty,
ComboboxInput,
ComboboxItem,
ComboboxList,
} from '@/ui/components/ui/combobox'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/ui/components/ui/dialog'
function isActive(status?: TranscriptJobStatus | null) {
return status?.status === 'pending' || status?.status === 'processing'
}
function statusMessage(job: TranscriptJobStatus) {
switch (job.status) {
case 'pending':
return m.transcript_queued()
case 'processing':
return m.transcript_generating()
case 'completed':
return m.transcript_completed()
case 'no_speech':
return m.transcript_no_speech()
case 'failed':
if (job.reason === 'tooLarge') return m.transcript_audio_too_large()
if (job.reason === 'noAudio') return m.transcript_no_audio()
if (job.reason === 'noProxy') return m.transcript_proxy_required()
return m.transcript_failed()
}
}
export function GenerateTranscriptsDialog({
assetId,
name,
onClose,
}: {
assetId: string
name: string
onClose: () => void
}) {
const dialogRef = useRef<HTMLDivElement>(null)
const activeTaskId = useRef<string>(undefined)
const queryClient = useQueryClient()
const [language, setLanguage] = useState('')
const param = { fileId: assetId }
const statusKey = ['transcription-status', assetId]
const languages = useQuery({
queryKey: ['transcription-languages'],
queryFn: async () => {
const response = await client.api.transcription.languages.$get()
if (!response.ok) throw new Error(m.transcript_languages_unavailable())
return await response.json()
},
staleTime: 5 * 60 * 1000,
retry: false,
})
const job = useQuery({
queryKey: statusKey,
queryFn: async () => {
const response = await client.api.files[':fileId']['transcription-status'].$get({ param })
if (!response.ok) throw new Error(m.transcript_status_unavailable())
return await response.json()
},
refetchInterval: (query) => (isActive(query.state.data) ? 2_000 : false),
})
const hasFreshJobStatus = job.isFetchedAfterMount && job.isSuccess
useEffect(() => {
if (!job.data) return
if (isActive(job.data)) {
// Reopening the dialog can briefly show a cached status for a finished job.
if (hasFreshJobStatus) activeTaskId.current = job.data.taskId
return
}
if (job.data.status !== 'completed') return
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
if (activeTaskId.current === job.data.taskId) {
activeTaskId.current = undefined
toast.success(m.transcript_completed())
onClose()
}
}, [assetId, hasFreshJobStatus, job.data, onClose, queryClient])
const generate = useMutation({
mutationFn: async () => {
const response = await client.api.files[':fileId'].transcripts.$post({
param,
json: { language: language || undefined },
})
if (!response.ok) throw new Error(m.transcript_submit_failed())
return await response.json()
},
onSuccess: (result) => {
if (result.kind === 'existing' || result.kind === 'no_speech') {
if (result.kind === 'existing') {
void queryClient.invalidateQueries({ queryKey: savedTranscriptLanguagesKey(assetId) })
}
toast.info(
result.kind === 'existing' ? m.transcript_already_exists() : m.transcript_no_speech(),
)
return
}
activeTaskId.current = result.taskId
queryClient.setQueryData<TranscriptJobStatus>(statusKey, {
status: 'pending',
taskId: result.taskId,
})
void queryClient.invalidateQueries({ queryKey: statusKey })
if (result.kind === 'queued') toast.success(m.transcript_queued())
},
})
const choices = [
{ code: '', name: m.transcript_language_auto() },
...(languages.data?.languages ?? []),
]
const busy = generate.isPending || isActive(job.data)
return (
<Dialog
open
onOpenChange={(open) => {
if (!open) onClose()
}}
>
<DialogContent ref={dialogRef} showCloseButton={false}>
<DialogHeader>
<DialogTitle>{m.generate_transcripts()}</DialogTitle>
<DialogDescription>{name}</DialogDescription>
</DialogHeader>
<Combobox
items={choices}
value={choices.find((choice) => choice.code === language)}
onValueChange={(choice) => setLanguage(choice?.code ?? '')}
itemToStringLabel={(choice) => choice.name}
isItemEqualToValue={(choice, value) => choice.code === value.code}
disabled={busy || languages.isPending || languages.isError}
>
<label htmlFor="transcript-language" className="text-sm font-medium">
{m.language()}
</label>
<ComboboxInput id="transcript-language" />
<ComboboxContent container={dialogRef}>
<ComboboxEmpty>{m.transcript_no_languages_found()}</ComboboxEmpty>
<ComboboxList>
{(choice) => (
<ComboboxItem key={choice.code} value={choice}>
{choice.name}
</ComboboxItem>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
{languages.isPending && (
<p role="status" className="text-sm text-muted-foreground">
{m.loading()}
</p>
)}
{languages.isError && (
<div className="flex items-center justify-between gap-2">
<p role="alert" className="text-sm text-destructive">
{m.transcript_languages_unavailable()}
</p>
<Button variant="outline" size="sm" onClick={() => languages.refetch()}>
{m.retry()}
</Button>
</div>
)}
{generate.isError && (
<p role="alert" className="text-sm text-destructive">
{generate.error.message}
</p>
)}
{job.isError && (
<p role="alert" className="text-sm text-destructive">
{m.transcript_status_unavailable()}
</p>
)}
{job.data && (
<p
role="status"
className={
job.data.status === 'failed'
? 'text-sm text-destructive'
: 'text-sm text-muted-foreground'
}
>
{statusMessage(job.data)}
</p>
)}
<DialogFooter>
<Button variant="outline" onClick={onClose}>
{m.close()}
</Button>
<Button
disabled={busy || !languages.data || job.isPending}
onClick={() => generate.mutate()}
>
{m.generate()}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}
@@ -18,6 +18,7 @@ export function FileViewer({
shareId,
allowDownload,
autoPlay,
transcriptToggle,
children,
}: OuterFileViewerProps) {
const viewerDef = getViewerForFile(file)
@@ -37,6 +38,7 @@ export function FileViewer({
shareId={shareId}
allowDownload={allowDownload}
autoPlay={autoPlay}
transcriptToggle={transcriptToggle}
>
{children}
</ViewerComponent>
@@ -56,6 +56,12 @@ vi.mock('@/ui/api/client', () => ({
},
files: {
':fileId': {
transcripts: {
$get: vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ languages: [] }),
}),
},
comments: {
$get: vi.fn().mockResolvedValue({
ok: true,
@@ -21,6 +21,7 @@ import {
} from '@/ui/components/ui/dialog'
import { Input } from '@/ui/components/ui/input'
import { usePermissions } from '@/ui/hooks/use-permissions'
import { useVideoTranscript } from '@/ui/hooks/use-video-transcript'
import { selectFileNameWithoutExtension } from '@/ui/lib/rename-utils'
import { m } from '@/ui/paraglide/messages.js'
import { useMemberStore } from '@/ui/stores/members'
@@ -32,6 +33,7 @@ import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { MediaController } from '../viewers/types'
import { MobileFileBottomSheet } from './mobile-file-bottom-sheet'
import { MobileFileHeader } from './mobile-file-header'
import { TranscriptPanel } from './transcript-panel'
export interface MobileFileDetailProps {
projectId: string
@@ -100,6 +102,7 @@ export function MobileFileDetail({
const { canEdit } = usePermissions(projectId)
const { members } = useMemberStore()
const mediaControllerRef = useRef<MediaController | null>(null)
const transcript = useVideoTranscript(!isPublic && file.id === activeFileId ? file : undefined)
const [sheetHeightPercent, setSheetHeightPercent] = useState(50)
const [annotations, setAnnotations] = useState<Annotation[]>([])
@@ -268,28 +271,40 @@ export function MobileFileDetail({
startTime={startTime}
shareId={shareId}
allowDownload={allowDownload}
transcriptToggle={transcript?.toggle}
/>
</div>
{/* Part 3: Freely Draggable Bottom Sheet */}
<MobileFileBottomSheet
teamId={teamId}
projectId={projectId}
file={file}
onSaveField={onSaveField}
members={members}
onCommentSelect={handleCommentSelect}
hideAnnotationControl={file.proxyType === 'audio'}
readOnly={isPublic || !canEdit}
publicFields={publicFields}
isPublic={isPublic}
shareId={shareId}
currentTime={currentTime}
onTyping={() => mediaControllerRef.current?.pause()}
selectedCommentId={selectedCommentId}
heightPercent={sheetHeightPercent}
onHeightPercentChange={setSheetHeightPercent}
/>
{transcript?.panel && (
<TranscriptPanel
key={transcript.panel.assetId}
{...transcript.panel}
canEdit={canEdit}
mediaControllerRef={mediaControllerRef}
className="z-20 h-[46dvh] w-full rounded-t-2xl border-t border-border"
/>
)}
<div className={transcript?.panel ? 'hidden' : 'contents'}>
<MobileFileBottomSheet
teamId={teamId}
projectId={projectId}
file={file}
onSaveField={onSaveField}
members={members}
onCommentSelect={handleCommentSelect}
hideAnnotationControl={file.proxyType === 'audio'}
readOnly={isPublic || !canEdit}
publicFields={publicFields}
isPublic={isPublic}
shareId={shareId}
currentTime={currentTime}
onTyping={() => mediaControllerRef.current?.pause()}
selectedCommentId={selectedCommentId}
heightPercent={sheetHeightPercent}
onHeightPercentChange={setSheetHeightPercent}
/>
</div>
{/* Dialogs */}
{!isPublic && isLinkedTasksOpen && (
@@ -0,0 +1,112 @@
import { ResizeHandle } from '@/ui/components/resize-handle'
import { m } from '@/ui/paraglide/messages.js'
import {
useCallback,
useLayoutEffect,
useRef,
useState,
type ComponentProps,
type Dispatch,
type SetStateAction,
} from 'react'
import { TranscriptPanel } from './transcript-panel'
const minTranscriptWidth = 20
const maxTranscriptWidth = 45
const preferredPlayerWidth = 256
const keyboardSteps = new Map([
['ArrowLeft', -1],
['ArrowRight', 1],
['Home', -maxTranscriptWidth],
['End', maxTranscriptWidth],
])
interface ResizableTranscriptPanelProps extends Omit<
ComponentProps<typeof TranscriptPanel>,
'className'
> {
widthPercent: number
setWidthPercent: Dispatch<SetStateAction<number>>
}
export function ResizableTranscriptPanel({
widthPercent,
setWidthPercent,
...panelProps
}: ResizableTranscriptPanelProps) {
const sheetRef = useRef<HTMLDivElement>(null)
const [maxWidthPercent, setMaxWidthPercent] = useState(maxTranscriptWidth)
const minWidthPercent = Math.min(minTranscriptWidth, maxWidthPercent)
useLayoutEffect(() => {
const viewer = sheetRef.current?.parentElement
if (!viewer) return
const updateLimit = () => {
const viewerWidth = viewer.clientWidth
const playerWidth = Math.min(preferredPlayerWidth, viewerWidth / 2)
const availablePercent = ((viewerWidth - playerWidth) / window.innerWidth) * 100
setMaxWidthPercent(Math.min(maxTranscriptWidth, availablePercent))
}
updateLimit()
const observer = new ResizeObserver(updateLimit)
observer.observe(viewer)
window.addEventListener('resize', updateLimit)
return () => {
observer.disconnect()
window.removeEventListener('resize', updateLimit)
}
}, [])
const adjustWidth = useCallback(
(deltaPercent: number) => {
setWidthPercent((previous) => {
const displayedWidth = Math.min(previous, maxWidthPercent)
const nextWidth = Math.min(
maxWidthPercent,
Math.max(minWidthPercent, displayedWidth + deltaPercent),
)
return nextWidth === displayedWidth ? previous : nextWidth
})
},
[maxWidthPercent, minWidthPercent, setWidthPercent],
)
const onResize = useCallback(
(deltaPixels: number) => adjustWidth((deltaPixels / window.innerWidth) * 100),
[adjustWidth],
)
const displayedWidth = Math.min(widthPercent, maxWidthPercent)
return (
<>
<div ref={sheetRef} className="min-w-0 shrink-0" style={{ width: `${displayedWidth}vw` }}>
<TranscriptPanel {...panelProps} className="h-full" />
</div>
<ResizeHandle
role="separator"
aria-orientation="vertical"
aria-label={m.transcript_resize()}
aria-controls={panelProps.id}
aria-valuemin={Math.round(minWidthPercent)}
aria-valuemax={Math.round(maxWidthPercent)}
aria-valuenow={Math.round(displayedWidth)}
aria-valuetext={`${Math.round(displayedWidth)}%`}
tabIndex={0}
className="shrink-0 focus-visible:outline-2 focus-visible:outline-ring"
hitAreaClassName="left-0 -right-3"
onResize={onResize}
onKeyDown={(event) => {
const step = keyboardSteps.get(event.key)
if (step === undefined) return
event.preventDefault()
event.stopPropagation()
adjustWidth(step)
}}
/>
</>
)
}
@@ -0,0 +1,352 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Input } from '@/ui/components/ui/input'
import { NativeSelect, NativeSelectOption } from '@/ui/components/ui/native-select'
import { ScrollArea } from '@/ui/components/ui/scroll-area'
import type { MediaController } from '@/ui/components/viewers/types'
import { savedTranscriptKey } from '@/ui/hooks/use-video-transcript'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { getLocale } from '@/ui/paraglide/runtime.js'
import type { TranscriptSegment } from '@shumai/dtos'
import { useQuery } from '@tanstack/react-query'
import { ChevronDown, ChevronUp, Search, X } from 'lucide-react'
import {
memo,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
type RefObject,
} from 'react'
import { TranscriptSegmentRow, type TextMatch } from './transcript-segment-row'
import { createTranscriptTimeline } from './transcript-timeline'
import { useTranscriptScroll } from './use-transcript-scroll'
interface TranscriptPanelProps {
id: string
assetId: string
languages: string[]
canEdit: boolean
mediaControllerRef: RefObject<MediaController | null>
onClose: () => void
className?: string
}
const noSegments: TranscriptSegment[] = []
function findMatches(segments: TranscriptSegment[], search: string) {
const bySegment = new Map<string, TextMatch[]>()
let total = 0
const query = search.trim()
if (!query) return { bySegment, total }
const literal = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
const expression = new RegExp(literal, 'giu')
for (const segment of segments) {
const matches = Array.from(segment.text.matchAll(expression), ({ index, 0: text }) => ({
index: total++,
start: index,
end: index + text.length,
}))
if (matches.length) bySegment.set(segment.id, matches)
}
return { bySegment, total }
}
export const TranscriptPanel = memo(function TranscriptPanel({
id,
assetId,
languages,
canEdit,
mediaControllerRef,
onClose,
className,
}: TranscriptPanelProps) {
const locale = getLocale()
const options = useMemo(() => {
const names = new Intl.DisplayNames(locale, { type: 'language' })
return languages
.map((code) => ({ code, name: names.of(code) ?? code }))
.sort((a, b) => a.name.localeCompare(b.name, locale))
}, [languages, locale])
const [preferredLanguage, setPreferredLanguage] = useState<string>(locale)
const language = options.find(({ code }) => code === preferredLanguage)?.code ?? options[0].code
const [searchOpen, setSearchOpen] = useState(false)
const [search, setSearch] = useState('')
const [matchIndex, setMatchIndex] = useState(0)
const [following, setFollowing] = useState(true)
const [activeId, setActiveId] = useState<string>()
const [editingId, setEditingId] = useState<string>()
const toggleSearchRef = useRef<HTMLButtonElement>(null)
const closeRef = useRef<HTMLButtonElement>(null)
const { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel } =
useTranscriptScroll(() => setFollowing(false))
const transcript = useQuery({
queryKey: savedTranscriptKey(assetId, language),
queryFn: async ({ signal }) => {
const response = await client.api.files[':fileId'].transcripts[':language'].$get(
{ param: { fileId: assetId, language } },
{ init: { signal } },
)
if (!response.ok) throw new Error(m.transcript_load_failed())
return await response.json()
},
retry: false,
})
const segments = transcript.data?.segments ?? noSegments
const activeAt = useMemo(() => createTranscriptTimeline(segments), [segments])
const matches = useMemo(() => findMatches(segments, search), [segments, search])
const selectedMatch = matches.total ? matchIndex % matches.total : undefined
const startEditing = useCallback(
(segmentId: string) => {
mediaControllerRef.current?.pause()
cancelScroll()
setEditingId(segmentId)
},
[cancelScroll, mediaControllerRef],
)
const finishEditing = useCallback(() => setEditingId(undefined), [])
useEffect(() => closeRef.current?.focus({ preventScroll: true }), [])
useEffect(() => {
let active: string | undefined
setActiveId(undefined)
return mediaControllerRef.current?.subscribeToPlaybackTime?.((second) => {
const segmentId = activeAt(second * 1000)
if (segmentId === active) return
active = segmentId
setActiveId(segmentId)
})
}, [activeAt, mediaControllerRef])
useLayoutEffect(() => {
if (editingId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(editingId)}"]`))
}
}, [editingId])
useLayoutEffect(() => {
if (following && activeId && !editingId) {
scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(activeId)}"]`), {
followPlayback: true,
})
}
}, [activeId, following, editingId])
useLayoutEffect(() => {
if (selectedMatch === undefined || editingId) return
setFollowing(false)
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 })
}, [matches, selectedMatch, editingId])
function toggleSearch() {
if (searchOpen) {
setSearch('')
setMatchIndex(0)
toggleSearchRef.current?.focus({ preventScroll: true })
}
setSearchOpen(!searchOpen)
}
function moveMatch(step: number) {
if (selectedMatch === undefined || editingId) return
setFollowing(false)
setMatchIndex((selectedMatch + step + matches.total) % matches.total)
if (matches.total === 1) {
scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 })
}
}
return (
<aside
id={id}
aria-label={m.transcript_title()}
onKeyDown={(event) => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') event.stopPropagation()
}}
className={cn(
'flex min-h-0 shrink-0 flex-col overflow-hidden bg-background text-foreground',
className,
)}
>
<div className="shrink-0 space-y-2 border-b border-border p-2">
<div className="flex items-center justify-between gap-2">
<div className="min-w-0 [&>[data-slot=native-select-wrapper]]:max-w-full">
<NativeSelect
size="sm"
className="max-w-40 truncate"
aria-label={m.language()}
value={language}
disabled={!!editingId}
onChange={(event) => {
cancelScroll()
setPreferredLanguage(event.target.value)
setMatchIndex(0)
setFollowing(true)
}}
>
{options.map(({ code, name }) => (
<NativeSelectOption key={code} value={code}>
{name}
</NativeSelectOption>
))}
</NativeSelect>
</div>
<div className="flex shrink-0 items-center gap-1">
<Button
ref={toggleSearchRef}
size="icon-sm"
variant="ghost"
aria-expanded={searchOpen}
aria-label={m.transcript_search()}
title={m.transcript_search()}
onClick={toggleSearch}
>
<Search />
</Button>
<Button
ref={closeRef}
size="icon-sm"
variant="ghost"
aria-label={m.transcript_close()}
title={m.transcript_close()}
onClick={onClose}
>
<X />
</Button>
</div>
</div>
{searchOpen && (
<div className="flex items-center gap-1">
<Input
autoFocus
type="search"
className="h-8 min-w-0 px-2"
aria-label={m.transcript_search()}
placeholder={m.transcript_search()}
value={search}
onChange={(event) => {
setSearch(event.target.value)
setMatchIndex(0)
}}
onKeyDown={(event) => {
if (event.key === 'Enter' || event.key === 'Escape') {
event.preventDefault()
event.stopPropagation()
if (event.key === 'Escape') toggleSearch()
else moveMatch(event.shiftKey ? -1 : 1)
}
}}
/>
{search.trim() && (
<output className="shrink-0 px-1 text-xs tabular-nums text-muted-foreground">
{m.transcript_search_count({
current: selectedMatch === undefined ? 0 : selectedMatch + 1,
total: matches.total,
})}
</output>
)}
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_previous_match()}
title={m.transcript_previous_match()}
disabled={!matches.total || !!editingId}
onClick={() => moveMatch(-1)}
>
<ChevronUp />
</Button>
<Button
size="icon-sm"
variant="ghost"
className="shrink-0"
aria-label={m.transcript_next_match()}
title={m.transcript_next_match()}
disabled={!matches.total || !!editingId}
onClick={() => moveMatch(1)}
>
<ChevronDown />
</Button>
</div>
)}
</div>
{transcript.isPending && (
<p role="status" className="p-3 text-sm text-muted-foreground">
{m.loading()}
</p>
)}
{transcript.isError && (
<div className="space-y-2 p-3">
<p role="alert" className="text-sm text-destructive">
{m.transcript_load_failed()}
</p>
<Button size="sm" variant="outline" onClick={() => void transcript.refetch()}>
{m.retry()}
</Button>
</div>
)}
{transcript.data && (
<div className="relative min-h-0 flex-1">
<ScrollArea
className="h-full [&>div>div]:block!"
viewportProps={{
ref: setViewport,
tabIndex: 0,
className: '[overflow-anchor:none]',
onScroll,
onWheel,
}}
>
<ol className="space-y-0.5 px-2 pt-2 pb-14">
{segments.map((segment) => {
const segmentMatches = matches.bySegment.get(segment.id)
return (
<TranscriptSegmentRow
key={segment.id}
segment={segment}
active={segment.id === activeId}
matches={segmentMatches}
selectedMatch={
segmentMatches?.some(({ index }) => index === selectedMatch)
? selectedMatch
: undefined
}
mediaControllerRef={mediaControllerRef}
canEdit={canEdit}
onEdit={canEdit && !editingId ? startEditing : undefined}
editTarget={
segment.id === editingId
? { assetId, language, onFinish: finishEditing }
: undefined
}
/>
)
})}
</ol>
</ScrollArea>
{!following && !editingId && (
<div className="pointer-events-none absolute inset-x-0 bottom-3 flex justify-center px-2">
<Button
size="sm"
variant="outline"
className="pointer-events-auto rounded-full shadow-md dark:bg-background dark:hover:bg-accent"
onClick={() => {
viewportRef.current?.focus({ preventScroll: true })
setFollowing(true)
}}
>
{m.transcript_sync_to_playback()}
</Button>
</div>
)}
</div>
)}
</aside>
)
})
@@ -0,0 +1,231 @@
import { client } from '@/ui/api/client'
import { Button } from '@/ui/components/ui/button'
import { Textarea } from '@/ui/components/ui/textarea'
import type { MediaController } from '@/ui/components/viewers/types'
import { formatTime } from '@/ui/components/viewers/video/utils'
import { savedTranscriptKey } from '@/ui/hooks/use-video-transcript'
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import type { SavedTranscript, TranscriptSegment } from '@shumai/dtos'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { Pencil } from 'lucide-react'
import { memo, useLayoutEffect, useRef, useState, type RefObject } from 'react'
export interface TextMatch {
index: number
start: number
end: number
}
interface SegmentEditTarget {
assetId: string
language: string
onFinish: () => void
}
function formatTranscriptTime(ms: number) {
return `${formatTime(ms / 1000)}.${String(ms % 1000).padStart(3, '0')}`
}
function SegmentEditor({
segment,
assetId,
language,
onFinish,
}: SegmentEditTarget & { segment: TranscriptSegment }) {
const [text, setText] = useState(segment.text)
const inputRef = useRef<HTMLTextAreaElement>(null)
const queryClient = useQueryClient()
const queryKey = savedTranscriptKey(assetId, language)
const save = useMutation({
mutationFn: async (draft: string) => {
const response = await client.api.files[':fileId'].transcripts[':language'].segments[
':segmentId'
].$patch({
param: { fileId: assetId, language, segmentId: segment.id },
json: { text: draft },
})
if (!response.ok) throw new Error(m.transcript_save_failed())
return await response.json()
},
onSuccess: async (updated) => {
await queryClient.cancelQueries({ queryKey, exact: true })
queryClient.setQueryData<SavedTranscript>(queryKey, (current) => {
if (!current) return current
return {
...current,
segments: current.segments.map((item) => (item.id === updated.id ? updated : item)),
}
})
},
})
useLayoutEffect(() => inputRef.current?.focus({ preventScroll: true }), [])
return (
<form
className="space-y-2"
onSubmit={(event) => {
event.preventDefault()
if (!save.isPending) save.mutate(text, { onSuccess: onFinish })
}}
onKeyDown={(event) => {
event.stopPropagation()
if (event.key === 'Escape' && !event.nativeEvent.isComposing && !save.isPending) {
event.preventDefault()
onFinish()
}
}}
>
<Textarea
ref={inputRef}
aria-label={m.transcript_edit_segment()}
className="max-h-40 resize-none"
dir="auto"
value={text}
readOnly={save.isPending}
onChange={(event) => setText(event.target.value)}
/>
{save.isError && (
<p role="alert" className="text-sm text-destructive">
{m.transcript_save_failed()}
</p>
)}
<div className="flex justify-end gap-2">
<Button
type="button"
size="sm"
variant="ghost"
disabled={save.isPending}
onClick={onFinish}
>
{m.cancel()}
</Button>
<Button type="submit" size="sm" disabled={save.isPending}>
{save.isPending ? m.saving() : m.save()}
</Button>
</div>
</form>
)
}
export const TranscriptSegmentRow = memo(function TranscriptSegmentRow({
segment,
active,
matches,
selectedMatch,
mediaControllerRef,
canEdit,
onEdit,
editTarget,
}: {
segment: TranscriptSegment
active: boolean
matches?: TextMatch[]
selectedMatch?: number
mediaControllerRef: RefObject<MediaController | null>
canEdit: boolean
onEdit?: (segmentId: string) => void
editTarget?: SegmentEditTarget
}) {
const editButtonRef = useRef<HTMLButtonElement>(null)
const restoreFocus = useRef(false)
useLayoutEffect(() => {
if (!editTarget && restoreFocus.current) {
restoreFocus.current = false
editButtonRef.current?.focus({ preventScroll: true })
}
}, [editTarget])
const timestamp = (
<span
className={cn(
'mb-1 block font-mono text-xs tabular-nums text-muted-foreground',
canEdit && !editTarget && 'pe-7',
)}
dir="ltr"
>
{formatTranscriptTime(segment.startMs)} – {formatTranscriptTime(segment.endMs)}
</span>
)
if (editTarget) {
return (
<li data-segment-id={segment.id} className="px-3 py-2">
{timestamp}
<SegmentEditor {...editTarget} segment={segment} />
</li>
)
}
let textOffset = 0
return (
<li data-segment-id={segment.id} className="group/segment relative">
<button
type="button"
aria-current={active ? 'true' : undefined}
className="block w-full cursor-pointer select-text rounded-md px-3 py-2 text-start group-hover/segment:bg-accent focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring focus-visible:outline-none"
onClick={(event) => {
const selection = window.getSelection()
if (
event.detail > 0 &&
selection?.anchorNode &&
!selection.isCollapsed &&
event.currentTarget.contains(selection.anchorNode)
) {
return
}
mediaControllerRef.current?.seekTo(segment.startMs / 1000, { exact: true })
}}
>
{timestamp}
<span
className={cn(
'block text-sm leading-relaxed whitespace-pre-wrap wrap-anywhere',
active && 'font-bold text-primary',
)}
dir="auto"
>
{matches?.map((match) => {
const preceding = segment.text.slice(textOffset, match.start)
textOffset = match.end
const selected = selectedMatch === match.index
return (
<span key={match.start}>
{preceding}
<mark
data-current-match={selected ? '' : undefined}
className={cn(
'rounded-sm bg-primary/15 px-px text-foreground',
selected && 'bg-primary text-primary-foreground',
)}
>
{segment.text.slice(match.start, match.end)}
</mark>
</span>
)
})}
{segment.text.slice(textOffset)}
</span>
</button>
{onEdit && (
<Button
ref={editButtonRef}
type="button"
size="icon-xs"
variant="ghost"
aria-label={m.transcript_edit_segment()}
title={m.transcript_edit_segment()}
className="absolute end-2 top-1 text-muted-foreground transition-opacity pointer-fine:opacity-0 pointer-fine:group-hover/segment:opacity-100 pointer-fine:group-focus-within/segment:opacity-100"
onClick={() => {
restoreFocus.current = true
onEdit(segment.id)
}}
>
<Pencil />
</Button>
)}
</li>
)
})
@@ -0,0 +1,42 @@
import { describe, expect, it } from 'vitest'
import { createTranscriptTimeline } from './transcript-timeline'
describe('createTranscriptTimeline', () => {
it('uses inclusive starts and exclusive ends for adjacent segments and gaps', () => {
const at = createTranscriptTimeline([
{ id: 'later', startMs: 2000, endMs: 2500, text: '' },
{ id: 'first', startMs: 300, endMs: 1000, text: '' },
{ id: 'second', startMs: 1000, endMs: 1700, text: '' },
])
expect(at(0)).toBeUndefined()
expect(at(300)).toBe('first')
expect(at(1000)).toBe('second')
expect(at(1700)).toBeUndefined()
expect(at(2000)).toBe('later')
expect(at(2500)).toBeUndefined()
})
it('finds the latest active start when a shorter segment overlaps a longer one', () => {
const at = createTranscriptTimeline([
{ id: 'long', startMs: 0, endMs: 4000, text: '' },
{ id: 'short', startMs: 1050, endMs: 1120, text: '' },
])
expect(at(1049.5)).toBe('long')
expect(at(1050)).toBe('short')
expect(at(1120)).toBe('long')
expect(at(4000)).toBeUndefined()
expect(createTranscriptTimeline([])(0)).toBeUndefined()
})
it('uses the new segment at an exact millisecond after converting the seek through seconds', () => {
const at = createTranscriptTimeline([
{ id: 'before', startMs: 1800, endMs: 2010, text: '' },
{ id: 'after', startMs: 2010, endMs: 2200, text: '' },
])
expect(at(2009.999)).toBe('before')
expect(at((2010 / 1000) * 1000)).toBe('after')
})
})
@@ -0,0 +1,30 @@
import type { TranscriptSegment } from '@shumai/dtos'
export function createTranscriptTimeline(segments: TranscriptSegment[]) {
const ordered = [...segments].sort((a, b) => a.startMs - b.startMs)
let latestEndMs = 0
const timeline = ordered.map((segment) => {
latestEndMs = Math.max(latestEndMs, segment.endMs)
return { segment, latestEndMs }
})
return (playbackTimeMs: number): string | undefined => {
// Remove floating-point noise around millisecond boundaries while keeping microsecond precision.
const timeMs = Math.round(playbackTimeMs * 1000) / 1000
let first = 0
let last = timeline.length
while (first < last) {
const middle = Math.floor((first + last) / 2)
if (timeline[middle].segment.startMs <= timeMs) first = middle + 1
else last = middle
}
// Prefer the most recent start when segments overlap. The running maximum bounds
// the backward scan even in long gaps or after the last segment.
for (let index = first - 1; index >= 0; index--) {
const { segment, latestEndMs } = timeline[index]
if (latestEndMs <= timeMs) break
if (segment.endMs > timeMs) return segment.id
}
}
}
@@ -0,0 +1,135 @@
import { useCallback, useEffect, useRef, type UIEvent, type WheelEvent } from 'react'
const followDurationMs = 220
interface FollowAnimation {
viewport: HTMLDivElement
targetTop: number
frame: number
}
export function useTranscriptScroll(onManualScroll: () => void) {
const viewportRef = useRef<HTMLDivElement>(null)
const scrollPosition = useRef(0)
const animation = useRef<FollowAnimation | null>(null)
const cancelScroll = useCallback(() => {
if (animation.current) cancelAnimationFrame(animation.current.frame)
animation.current = null
}, [])
const setViewport = useCallback(
(viewport: HTMLDivElement | null) => {
if (viewportRef.current === viewport) return
cancelScroll()
viewportRef.current = viewport
scrollPosition.current = viewport?.scrollTop ?? 0
},
[cancelScroll],
)
useEffect(() => cancelScroll, [cancelScroll])
function setScrollTop(viewport: HTMLDivElement, top: number) {
viewport.scrollTop = top
scrollPosition.current = viewport.scrollTop
}
function detectManualScroll(viewport: HTMLDivElement) {
const top = viewport.scrollTop
if (top === scrollPosition.current) return false
// A height or width change may clamp the browser's last scroll position.
const clampedTop = Math.min(
scrollPosition.current,
viewport.scrollHeight - viewport.clientHeight,
)
scrollPosition.current = top
if (top === clampedTop) return false
cancelScroll()
onManualScroll()
return true
}
function animateFollow(viewport: HTMLDivElement, top: number) {
const targetTop = Math.max(0, Math.min(top, viewport.scrollHeight - viewport.clientHeight))
if (animation.current?.viewport === viewport) {
if (detectManualScroll(viewport) || animation.current?.targetTop === targetTop) return
}
cancelScroll()
const startTop = viewport.scrollTop
scrollPosition.current = startTop
if (startTop === targetTop) return
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
setScrollTop(viewport, targetTop)
return
}
const motion = { viewport, targetTop, frame: 0 }
let startedAt: number | undefined
const step = (time: number) => {
if (animation.current !== motion) return
if (viewportRef.current !== viewport) {
animation.current = null
return
}
if (detectManualScroll(viewport)) return
startedAt ??= time
const progress = Math.min(1, (time - startedAt) / followDurationMs)
const eased = 1 - (1 - progress) ** 3
setScrollTop(viewport, startTop + (targetTop - startTop) * eased)
if (progress === 1) animation.current = null
else motion.frame = requestAnimationFrame(step)
}
animation.current = motion
motion.frame = requestAnimationFrame(step)
}
function scrollTo(
target: HTMLElement | null | undefined,
{ bottomInset = 0, followPlayback = false } = {},
) {
if (!followPlayback) cancelScroll()
const viewport = viewportRef.current
if (!viewport || !target) return
const item = target.getBoundingClientRect()
const { top, bottom } = viewport.getBoundingClientRect()
if (followPlayback) {
const height = bottom - top
// Check where the segment will settle so nearby segments don't restart the motion.
const pendingTop =
animation.current?.viewport === viewport ? animation.current.targetTop : viewport.scrollTop
const relativeTop = item.top - top
const settledTop = relativeTop + viewport.scrollTop - pendingTop
if (settledTop < 0 || settledTop + item.height / 2 >= height * 0.75) {
const centerOffset = Math.max(0, (height - item.height) / 2)
animateFollow(viewport, viewport.scrollTop + relativeTop - centerOffset)
}
return
}
const visibleBottom = bottom - bottomInset
if (item.top < top || item.height > visibleBottom - top) {
setScrollTop(viewport, viewport.scrollTop + item.top - top)
} else if (item.bottom > visibleBottom) {
setScrollTop(viewport, viewport.scrollTop + item.bottom - visibleBottom)
}
}
function onScroll(event: UIEvent<HTMLDivElement>) {
detectManualScroll(event.currentTarget)
}
function onWheel(event: WheelEvent<HTMLDivElement>) {
if (event.deltaY !== 0 && !event.ctrlKey && animation.current) {
cancelScroll()
onManualScroll()
}
}
return { viewportRef, setViewport, scrollTo, cancelScroll, onScroll, onWheel }
}
+22 -14
View File
@@ -1,14 +1,19 @@
import { cn } from '@/ui/lib/utils'
import { useEffect, useRef, useState } from 'react'
interface ResizeHandleProps {
interface ResizeHandleProps extends Omit<
React.ComponentProps<'div'>,
'children' | 'onMouseDown' | 'onResize'
> {
onResize: (delta: number) => void
className?: string
hitAreaClassName?: string
}
export const ResizeHandle: React.FC<ResizeHandleProps> = ({
onResize,
hitAreaClassName,
className = '',
...props
}) => {
const [isDragging, setIsDragging] = useState(false)
const startXref = useRef(0)
@@ -50,36 +55,39 @@ export const ResizeHandle: React.FC<ResizeHandleProps> = ({
startXref.current = e.clientX
}
// Common hit area that is always larger than the visible element for usability
const HitArea = () => (
<div className="absolute inset-y-0 -left-4 -right-4 z-20 cursor-col-resize touch-none" />
)
return (
<div
className={`group relative z-20 flex h-full w-[2px] cursor-col-resize items-center justify-center bg-border transition-all hover:bg-transparent ${className}`}
{...props}
data-slot="resize-handle"
className={`group/resize relative z-20 flex h-full w-[2px] cursor-col-resize items-center justify-center bg-border transition-all hover:bg-transparent ${className}`}
onMouseDown={handleMouseDown}
>
<HitArea />
<div
aria-hidden="true"
className={cn(
'absolute inset-y-0 -left-4 -right-4 z-20 cursor-col-resize touch-none',
hitAreaClassName,
)}
/>
{/* The glowing vertical line */}
<div
className={`absolute inset-y-0 w-[2px] transition-all duration-300 ease-out
className={`pointer-events-none absolute inset-y-0 w-[2px] transition-all duration-300 ease-out
${
isDragging
? 'bg-blue-600 shadow-[0_0_15px_rgba(37,99,235,0.6)] opacity-100'
: 'bg-blue-400 opacity-0 group-hover:opacity-100 group-hover:shadow-[0_0_8px_rgba(96,165,250,0.5)]'
: 'bg-blue-400 opacity-0 group-hover/resize:opacity-100 group-hover/resize:shadow-[0_0_8px_rgba(96,165,250,0.5)]'
}
`}
/>
{/* The central drag handle (Pill) */}
<div
className={`absolute top-1/2 left-1/2 h-10 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-600 transition-all duration-300 ease-out
className={`pointer-events-none absolute top-1/2 left-1/2 h-10 w-1.5 -translate-x-1/2 -translate-y-1/2 rounded-full bg-blue-600 transition-all duration-300 ease-out
${
isDragging
? 'opacity-100 scale-100 shadow-[0_0_10px_rgba(37,99,235,0.5)]'
: 'opacity-0 scale-75 group-hover:opacity-100 group-hover:scale-100'
: 'opacity-0 scale-75 group-hover/resize:opacity-100 group-hover/resize:scale-100'
}`}
/>
</div>
+4 -2
View File
@@ -89,14 +89,16 @@ function ComboboxContent({
align = 'start',
alignOffset = 0,
anchor,
container,
...props
}: ComboboxPrimitive.Popup.Props &
Pick<
ComboboxPrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
>) {
> &
Pick<ComboboxPrimitive.Portal.Props, 'container'>) {
return (
<ComboboxPrimitive.Portal>
<ComboboxPrimitive.Portal container={container}>
<ComboboxPrimitive.Positioner
side={side}
sideOffset={sideOffset}
+9 -2
View File
@@ -6,8 +6,11 @@ import { cn } from '@/ui/lib/utils'
function ScrollArea({
className,
children,
viewportProps,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root> & {
viewportProps?: React.ComponentProps<typeof ScrollAreaPrimitive.Viewport>
}) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
@@ -15,8 +18,12 @@ function ScrollArea({
{...props}
>
<ScrollAreaPrimitive.Viewport
{...viewportProps}
data-slot="scroll-area-viewport"
className="size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1"
className={cn(
'size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1',
viewportProps?.className,
)}
>
{children}
</ScrollAreaPrimitive.Viewport>
+10 -1
View File
@@ -6,9 +6,17 @@ import type React from 'react'
export interface MediaController {
play: () => void
pause: () => void
seekTo: (second: number) => void
seekTo: (second: number, options?: { exact?: boolean }) => void
getCurrentTime?: () => number
getDuration?: () => number
subscribeToPlaybackTime?: (listener: (second: number) => void) => (() => void) | undefined
}
export interface TranscriptToggle {
panelId: string
open: boolean
buttonRef: React.RefObject<HTMLButtonElement | null>
onToggle: () => void
}
export interface FileViewerProps {
@@ -23,6 +31,7 @@ export interface FileViewerProps {
/** When false, the viewer hides its download affordances. Defaults to true. */
allowDownload?: boolean
autoPlay?: boolean
transcriptToggle?: TranscriptToggle
children?: React.ReactNode
}
@@ -25,6 +25,7 @@ import {
import ProgressBar from './progress-bar'
import { formatTime, formatTimecode } from './utils'
import type { ControlBarProps, DisplayTranscode } from './video-control-bar'
import { TranscriptToggleButton } from './transcript-toggle-button'
export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
state,
@@ -47,6 +48,7 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
onMouseEnter,
onMouseLeave,
isLoading: propIsLoading,
transcriptToggle,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
@@ -188,6 +190,9 @@ export const MobileVideoControlBar: React.FC<ControlBarProps> = ({
{/* Right Side: Settings (Quality + Speed) & Fullscreen */}
<div className="flex items-center gap-1 shrink-0">
{transcriptToggle && !isAudio && !state.isFullScreen && (
<TranscriptToggleButton {...transcriptToggle} className="p-1" />
)}
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<button
@@ -0,0 +1,31 @@
import { cn } from '@/ui/lib/utils'
import { m } from '@/ui/paraglide/messages.js'
import { ListVideo } from 'lucide-react'
import type { TranscriptToggle } from '../types'
export function TranscriptToggleButton({
panelId,
open,
buttonRef,
onToggle,
className,
}: TranscriptToggle & { className?: string }) {
return (
<button
ref={buttonRef}
type="button"
aria-label={m.transcript_view()}
aria-expanded={open}
aria-controls={open ? panelId : undefined}
title={m.transcript_view()}
className={cn(
'shrink-0 cursor-pointer rounded transition-colors hover:text-primary focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none',
open && 'text-primary',
className,
)}
onClick={onToggle}
>
<ListVideo className="size-5" aria-hidden="true" />
</button>
)
}
@@ -109,6 +109,136 @@ afterEach(() => {
// --- Tests --------------------------------------------------------------------
describe('useFramePlayer exact timestamp seeking', () => {
it.each([true, false])('keeps the settled timestamp with paused=%s', async (paused) => {
const video = new FakeVideo()
video.paused = paused
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
let exactSeek: Promise<void> | undefined
act(() => {
exactSeek = result.current.seekToTime(0.995, true)
})
await act(async () => {
video.dispatchEvent(new Event('seeked'))
await exactSeek
})
expect(video.currentTime).toBe(0.995)
expect(video.paused).toBe(paused)
expect(result.current.currentFrame).toBe(29)
act(() => {
video.currentTime = 0.996
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBeCloseTo(29.5 / 30)
})
it('keeps the latest transcript seek queued behind a frame seek when playback is paused mid-seek', async () => {
const video = new FakeVideo()
video.paused = false
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
const seeks: Promise<void>[] = []
act(() => {
seeks.push(result.current.seekToFrame(18))
seeks.push(result.current.seekToTime(0.005, true))
seeks.push(result.current.seekToTime(0.995, true))
})
expect(video.currentTime).toBeCloseTo(18.5 / 30)
await act(async () => {
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBe(0.995)
act(() => video.pause())
await act(async () => {
video.dispatchEvent(new Event('seeked'))
await Promise.all(seeks)
})
expect(video.currentTime).toBe(0.995)
expect(video.paused).toBe(true)
expect(result.current.currentFrame).toBe(29)
})
it('keeps the exact timestamp when the native seek completes after the seek queue times out', async () => {
vi.useFakeTimers()
try {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
let exactSeek: Promise<void> | undefined
act(() => {
exactSeek = result.current.seekToTime(0.995, true)
})
await act(async () => {
await vi.advanceTimersByTimeAsync(501)
await exactSeek
})
act(() => video.dispatchEvent(new Event('seeked')))
expect(video.currentTime).toBe(0.995)
} finally {
vi.useRealTimers()
}
})
it.each(['controller', 'native'] as const)(
'lets a newer ordinary %s seek supersede a timed-out exact seek',
async (source) => {
vi.useFakeTimers()
try {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
await act(async () => {
const exactSeek = result.current.seekToTime(0.995, true)
await vi.advanceTimersByTimeAsync(501)
await exactSeek
})
act(() => {
if (source === 'controller') {
void result.current.seekToTime(0.995)
} else {
video.currentTime = 0.996
}
video.dispatchEvent(new Event('seeking'))
video.dispatchEvent(new Event('seeked'))
})
expect(video.currentTime).toBeCloseTo(29.5 / 30)
} finally {
vi.useRealTimers()
}
},
)
it('lets a comment seek supersede both the active and queued transcript seeks', async () => {
const video = new FakeVideo()
const ref = makeRef(video)
const { result } = renderHook(() => useFramePlayer(ref, 30, 30))
const transcriptSeeks: Promise<void>[] = []
act(() => {
transcriptSeeks.push(result.current.seekToTime(0.5, true))
transcriptSeeks.push(result.current.seekToTime(0.7, true))
void result.current.seekToTime(0.996)
})
expect(video.currentTime).toBe(0.996)
await act(async () => video.dispatchEvent(new Event('seeked')))
expect(video.currentTime).toBeCloseTo(29.5 / 30)
await Promise.all(transcriptSeeks)
expect(result.current.currentFrame).toBe(29)
})
})
describe('useFramePlayer Safari playhead synchronization', () => {
it('does not rewind the playhead on play when currentTime leads the presented frame', () => {
const video = new FakeVideo()
@@ -5,10 +5,22 @@ export interface UseFramePlayerResult {
currentFrame: number
setCurrentFrame: React.Dispatch<React.SetStateAction<number>>
seekToFrame: (targetFrame: number) => Promise<void>
seekToTime: (second: number, exact?: boolean) => Promise<void>
pauseForScrub: () => void
isSeeking: React.RefObject<boolean>
}
interface SeekTarget {
frame: number
exactSecond?: number
}
interface SeekSession {
completion: Promise<void> | null
pending: SeekTarget | null
finishWait: (() => void) | null
}
interface HtmlVideoElementWithCallback {
requestVideoFrameCallback?: (
callback: (now: DOMHighResTimeStamp, metadata: { mediaTime: number }) => void,
@@ -29,9 +41,9 @@ export function useFramePlayer(
): UseFramePlayerResult {
const [currentFrame, setCurrentFrame] = useState<number>(0)
const isSeekingRef = useRef<boolean>(false)
const seekCompletionRef = useRef<Promise<void> | null>(null)
const exactSeekRef = useRef<{ video: HTMLVideoElement; second: number } | null>(null)
const seekSessionRef = useRef<SeekSession | null>(null)
const isPlayingRef = useRef<boolean>(false)
const pendingSeekFrameRef = useRef<number | null>(null)
const scrubPauseRef = useRef(false)
const currentFrameRef = useRef<number>(currentFrame)
currentFrameRef.current = currentFrame
@@ -186,7 +198,9 @@ export function useFramePlayer(
// Snap the playhead to the center of the paused frame to align browser compositor
// Skip snapping if the video has ended to preserve the native ended state and allow native replay
if (!video.ended && !scrubPause) {
const exactSeekPending =
exactSeekRef.current?.video === video && (isSeekingRef.current || video.seeking)
if (!video.ended && !scrubPause && !exactSeekPending) {
const safeCenterTime = calculateFrameCenterTime(clamped, frameRate)
video.currentTime = safeCenterTime
}
@@ -237,47 +251,50 @@ export function useFramePlayer(
}
}, [videoRef])
const seekToFrame = useCallback(
async (targetFrame: number) => {
const seek = useCallback(
async (target: SeekTarget) => {
const video = videoRef.current
if (!video) return
const roundedFrame = Math.round(targetFrame)
const clampedFrame = Math.max(0, Math.min(roundedFrame, totalFrames - 1))
// If a seek is already active, queue this target and update UI state optimistically
if (seekCompletionRef.current) {
pendingSeekFrameRef.current = clampedFrame
setCurrentFrame(clampedFrame)
return seekCompletionRef.current
const activeSession = seekSessionRef.current
if (activeSession?.completion) {
activeSession.pending = target
setCurrentFrame(target.frame)
return activeSession.completion
}
const session: SeekSession = { completion: null, pending: null, finishWait: null }
seekSessionRef.current = session
isSeekingRef.current = true
setCurrentFrame(clampedFrame) // Optimistic update for active seek
setCurrentFrame(target.frame) // Optimistic update for active seek
const performSeek = async (frameToSeek: number) => {
const safeTargetTime = calculateFrameCenterTime(frameToSeek, frameRate)
const performSeek = async ({ frame, exactSecond }: SeekTarget) => {
exactSeekRef.current = exactSecond === undefined ? null : { video, second: exactSecond }
const wasPlaying = !video.paused
video.currentTime = safeTargetTime
video.currentTime = exactSecond ?? calculateFrameCenterTime(frame, frameRate)
// Wait for native seek to complete (with a 500ms fallback timeout to prevent hanging)
await new Promise<void>((resolve) => {
let timeoutId: ReturnType<typeof setTimeout> | null = null
const onSeeked = () => {
if (timeoutId) clearTimeout(timeoutId)
const finishWait = () => {
clearTimeout(timeoutId)
video.removeEventListener('seeked', onSeeked)
session.finishWait = null
resolve()
}
const onSeeked = () => {
if (!video.seeking) finishWait()
}
const timeoutId = setTimeout(finishWait, 500)
session.finishWait = finishWait
video.addEventListener('seeked', onSeeked)
timeoutId = setTimeout(() => {
video.removeEventListener('seeked', onSeeked)
resolve()
}, 500)
})
if (seekSessionRef.current !== session) return
// Pause only if we started paused and the user hasn't pressed play in the meantime
if (!wasPlaying && !isPlayingRef.current) {
if (exactSecond === undefined && !wasPlaying && !isPlayingRef.current) {
video.pause()
}
@@ -300,25 +317,55 @@ export function useFramePlayer(
const runSeeks = async () => {
try {
// Process the latest queued seek before signaling completion to any caller.
let nextFrame: number | null = clampedFrame
while (nextFrame !== null) {
await performSeek(nextFrame)
nextFrame = pendingSeekFrameRef.current
pendingSeekFrameRef.current = null
let next: SeekTarget | null = target
while (next !== null && seekSessionRef.current === session) {
await performSeek(next)
next = session.pending
session.pending = null
}
} finally {
seekCompletionRef.current = null
pendingSeekFrameRef.current = null
isSeekingRef.current = false
if (seekSessionRef.current === session) {
seekSessionRef.current = null
isSeekingRef.current = false
}
}
}
seekCompletionRef.current = runSeeks()
await seekCompletionRef.current
session.completion = runSeeks()
return session.completion
},
[videoRef, frameRate, totalFrames],
)
const seekToFrame = useCallback(
(targetFrame: number) =>
seek({ frame: Math.max(0, Math.min(Math.round(targetFrame), totalFrames - 1)) }),
[seek, totalFrames],
)
const seekToTime = useCallback(
(second: number, exact = false) => {
if (!exact) {
// Ordinary timestamp seeks take effect immediately, superseding queued frame and transcript seeks.
const previousSession = seekSessionRef.current
seekSessionRef.current = null
isSeekingRef.current = false
previousSession?.finishWait?.()
exactSeekRef.current = null
const video = videoRef.current
if (video) video.currentTime = second
return Promise.resolve()
}
const frame = Math.floor(second * frameRate + 0.45)
return seek({
frame: Math.max(0, Math.min(frame, totalFrames - 1)),
exactSecond: second,
})
},
[seek, videoRef, frameRate, totalFrames],
)
// Keyboard Shortcuts Keydown Listener
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
@@ -353,12 +400,26 @@ export function useFramePlayer(
const video = videoRef.current
if (!video) return
const handleSeeking = () => {
const exactSeek = exactSeekRef.current
// A newer native seek can replace the pending target.
if (exactSeek?.video === video && Math.abs(exactSeek.second - video.currentTime) > 0.000001) {
exactSeekRef.current = null
}
}
const handleExternalSeeked = () => {
// Only sync if this seek was not triggered internally by seekToFrame
if (video.seeking) return
// The queue may have timed out while the browser was still seeking.
const preserveTime = exactSeekRef.current?.video === video
if (preserveTime) exactSeekRef.current = null
// The queue updates its own seeks when they settle.
if (!isSeekingRef.current) {
const actualFrame = Math.floor(video.currentTime * frameRate + 0.45)
const finalFrame = Math.max(0, Math.min(actualFrame, totalFrames - 1))
setCurrentFrame(finalFrame)
if (preserveTime) return
// Nudge to safe frame center to guarantee correct browser decoding
const safeCenterTime = calculateFrameCenterTime(finalFrame, frameRate)
@@ -369,8 +430,10 @@ export function useFramePlayer(
}
}
video.addEventListener('seeking', handleSeeking)
video.addEventListener('seeked', handleExternalSeeked)
return () => {
video.removeEventListener('seeking', handleSeeking)
video.removeEventListener('seeked', handleExternalSeeked)
}
}, [videoRef.current, frameRate, totalFrames])
@@ -379,6 +442,7 @@ export function useFramePlayer(
currentFrame,
setCurrentFrame,
seekToFrame,
seekToTime,
pauseForScrub,
isSeeking: isSeekingRef,
}
@@ -30,6 +30,8 @@ import { Slider } from '../../ui/slider'
import ProgressBar, { type SeekbarScrubHandlers } from './progress-bar'
import { formatTime, formatTimecode } from './utils'
import { getVideoResolutionLabel } from '@/ui/lib/media'
import type { TranscriptToggle } from '../types'
import { TranscriptToggleButton } from './transcript-toggle-button'
export interface PlayerState {
isPlaying: boolean
@@ -96,6 +98,7 @@ export interface ControlBarProps {
/** When false, hides the download affordance. Defaults to true. */
allowDownload?: boolean
isLoading?: boolean
transcriptToggle?: TranscriptToggle
}
export const VideoControlBar: React.FC<ControlBarProps> = ({
@@ -125,6 +128,7 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
onMouseLeave,
allowDownload = true,
isLoading: propIsLoading,
transcriptToggle,
}) => {
const isLoading = propIsLoading ?? state.isLoading ?? false
const { videoTimeDisplayMode, setVideoTimeDisplayMode } = useUiStore()
@@ -423,6 +427,10 @@ export const VideoControlBar: React.FC<ControlBarProps> = ({
</DropdownMenu>
)}
{transcriptToggle && !isAudio && !state.isFullScreen && (
<TranscriptToggleButton {...transcriptToggle} />
)}
{/* Download */}
{allowDownload &&
(isAudio ? (
@@ -32,11 +32,14 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
children,
allowDownload,
autoPlay,
transcriptToggle,
},
ref,
) => {
const hlsRef = useRef<Hls | null>(null)
const videoRef = useRef<HTMLVideoElement | null>(null)
const refreshPlaybackTime = useRef<() => void>(undefined)
const scrubTime = useRef<number | null>(null)
const [activeAutoResolution, setActiveAutoResolution] = useState<string | undefined>(undefined)
const [isHlsManualSupported, setIsHlsManualSupported] = useState<boolean>(true)
const isHls = Boolean(data.media?.isHls && data.media.hls?.url)
@@ -123,15 +126,13 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
pause: () => {
videoRef.current?.pause()
},
seekTo: (second: number) => {
seekTo: (second, options) => {
if (pendingResolutionCorrectionRef.current) {
pendingResolutionCorrectionRef.current()
pendingResolutionCorrectionRef.current = null
}
setHasStartedPlaying(true)
if (videoRef.current) {
videoRef.current.currentTime = second
}
void seekToTime(second, options?.exact)
},
getCurrentTime: () => {
return (videoRef.current ? videoRef.current.currentTime : 0) ?? 0
@@ -139,6 +140,20 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
getDuration: () => {
return (videoRef.current ? videoRef.current.duration : 0) ?? 0
},
subscribeToPlaybackTime: (listener) => {
const video = videoRef.current
if (!video) return
const update = () => listener(scrubTime.current ?? video.currentTime)
const events = ['timeupdate', 'seeking', 'seeked', 'loadedmetadata', 'ended']
refreshPlaybackTime.current = update
for (const event of events) video.addEventListener(event, update)
update()
return () => {
if (refreshPlaybackTime.current === update) refreshPlaybackTime.current = undefined
for (const event of events) video.removeEventListener(event, update)
}
},
}))
const isOverControlsRef = useRef(false)
@@ -271,7 +286,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const isAudio = data.proxyType === 'audio'
const totalFrames = resolveTotalFrames({ dbTotalFrames, containerDuration, frameRate })
const { currentFrame, seekToFrame, pauseForScrub } = useFramePlayer(
const { currentFrame, seekToFrame, seekToTime, pauseForScrub } = useFramePlayer(
videoRef,
frameRate,
totalFrames,
@@ -303,6 +318,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
const displayFrame = scrubFrame ?? currentFrame
const isScrubbing = scrubFrame !== null
const currentTime = displayFrame / frameRate
scrubTime.current = isScrubbing ? currentTime : null
const duration = totalFrames / frameRate
const progress = duration > 0 ? (currentTime / duration) * 100 : 0
@@ -323,6 +339,10 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
}
}, [currentFrame, frameRate, onTimeUpdate])
useEffect(() => {
refreshPlaybackTime.current?.()
}, [currentFrame, scrubFrame, frameRate])
// Initialize player (Hls.js or native HTML5 video)
useEffect(() => {
const video = videoRef.current
@@ -1159,6 +1179,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
transcriptToggle={transcriptToggle}
/>
) : (
<VideoControlBar
@@ -1187,6 +1208,7 @@ const VideoViewer = React.forwardRef<MediaController, FileViewerProps>(
onMouseLeave={handleControlsMouseLeave}
allowDownload={allowDownload}
isLoading={isLoading}
transcriptToggle={transcriptToggle}
/>
)}
</div>