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 { formatTime } from '@/ui/components/viewers/video/utils' import { savedTranscriptLanguagesKey } 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, LocateFixed, Search, X } from 'lucide-react' import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type RefObject } from 'react' import { createTranscriptTimeline } from './transcript-timeline' interface TranscriptPanelProps { id: string assetId: string languages: string[] mediaControllerRef: RefObject onClose: () => void className?: string } interface TextMatch { index: number start: number end: number } const noSegments: TranscriptSegment[] = [] function findMatches(segments: TranscriptSegment[], search: string) { const bySegment = new Map() 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 } } function formatTranscriptTime(ms: number) { return `${formatTime(ms / 1000)}.${String(ms % 1000).padStart(3, '0')}` } const SegmentRow = memo(function SegmentRow({ segment, active, matches, selectedMatch, mediaControllerRef, }: { segment: TranscriptSegment active: boolean matches?: TextMatch[] selectedMatch?: number mediaControllerRef: RefObject }) { let textOffset = 0 return (
  • ) }) export const TranscriptPanel = memo(function TranscriptPanel({ id, assetId, languages, 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(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() const toggleSearchRef = useRef(null) const closeRef = useRef(null) const viewportRef = useRef(null) const scrollPosition = useRef(0) const transcript = useQuery({ queryKey: [...savedTranscriptLanguagesKey(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 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]) function scrollTo( target: HTMLElement | null | undefined, { bottomInset = 0, followPlayback = false } = {}, ) { const viewport = viewportRef.current if (!viewport || !target) return const item = target.getBoundingClientRect() const { top, bottom } = viewport.getBoundingClientRect() if (followPlayback) { const height = bottom - top const midpoint = item.top + item.height / 2 if (item.top < top || midpoint >= top + height * 0.75) { viewport.scrollTop += item.top - top - Math.max(0, (height - item.height) / 2) } } else { const visibleBottom = bottom - bottomInset if (item.top < top || item.height > visibleBottom - top) { viewport.scrollTop += item.top - top } else if (item.bottom > visibleBottom) { viewport.scrollTop += item.bottom - visibleBottom } } scrollPosition.current = viewport.scrollTop } useLayoutEffect(() => { if (following && activeId) { scrollTo(viewportRef.current?.querySelector(`[data-segment-id="${CSS.escape(activeId)}"]`), { followPlayback: true, }) } }, [activeId, following]) useLayoutEffect(() => { if (selectedMatch === undefined) return setFollowing(false) scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 }) }, [matches, selectedMatch]) function toggleSearch() { if (searchOpen) { setSearch('') setMatchIndex(0) toggleSearchRef.current?.focus({ preventScroll: true }) } setSearchOpen(!searchOpen) } function moveMatch(step: number) { if (selectedMatch === undefined) return setFollowing(false) setMatchIndex((selectedMatch + step + matches.total) % matches.total) if (matches.total === 1) { scrollTo(viewportRef.current?.querySelector('[data-current-match]'), { bottomInset: 48 }) } } return ( ) })