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
@@ -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 }
}