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(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(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 (
{ 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() } }} >