Files
shumai/packages/webui/components/file-viewer/transcript-segment-row.tsx
T
Yiling-J d3899d1257 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
2026-12-04 13:49:25 +08:00

232 lines
7.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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>
)
})