// The manual subtitle surface for one media file (§9.3, §15, issue #203): a // chip in the file's row, and the inline panel it opens with a fetch lane over // the providers and a translate lane over what is already on the file. import { type ReactNode, useEffect, useRef, useState } from "react"; import { ArmedDeleteIcon, Icon } from "./icons"; import { control, seg, segmented } from "./look"; import { fileName } from "./movie"; import { cachedSubtitleOptions, deleteSubtitle, type EmbeddedTrack, embeddedTrackLabel, extractableTracks, extractTrack, formatCandidateFlags, formatDownloads, formatHashMatch, formatReleaseMatch, formatUploaderRating, grabSubtitle, languageChoices, type MissingSubtitle, missingChipLabel, type Subtitle, type SubtitleCandidate, type SubtitleSearchResults, type SubtitleStatus, searchSubtitles, subtitleChipLabel, subtitleRuleLabel, subtitleSummary, subtitleSummaryLabel, summaryWidth, type Translation, translateSubtitle, translationSources, wantedSubtitles, } from "./subtitles"; import { Chip, Control, DeckHead, Disclosure, EmptyRow, type Note, NoteLine, Row, Rows, type Say, Section, useNote, } from "./ui"; /** How often an open title re-reads a running translation's status. */ const TRANSLATION_POLL_MS = 5000; /** * One present-subtitle chip. Green like an eligible release (the want is * met); a forced track never satisfies a want (§15) so it stays neutral * instead, and so does a language nobody asked for — green here means the * wanted set moved, not merely that a track exists. `data-mt` marks a * machine translation with the same dashed border a waived release already * carries — a translation is a relaxed case of "has a subtitle", not the * clean one, and §15 wants it readable at a glance rather than by hovering * for the origin word. */ function SubtitleChip({ subtitle, wanted, onDeleted, say, }: { subtitle: Subtitle; wanted: string[] | null; onDeleted: () => void; say: Say; }) { const [failed, setFailed] = useState(false); const path = subtitle.path; return ( {subtitleChipLabel(subtitle)} {/* An embedded track has no sidecar (§15) — nothing on disk to name or delete. A chip is too narrow to spell out a filename, so the lane's note names the sidecar while armed and says why a delete failed. */} {path !== null && ( say(text, "warn")} execute={() => { setFailed(false); return deleteSubtitle(subtitle.id).then((outcome) => { if (outcome.kind === "error") { setFailed(true); say(`delete failed — ${outcome.detail}`, "fault"); return false; } onDeleted(); return undefined; }); }} /> )} ); } /** One missing-language chip; a failure's detail is a tap away in the lane's note. */ export function MissingSubtitleChip({ missing, say }: { missing: MissingSubtitle; say?: Say }) { return ( {missingChipLabel(missing)} ); } /** * A language picker as pressed controls rather than a select: three or four * options, all worth seeing at once, and the same affordance the root picker * and the library view toggles already use. */ function LanguagePicker({ label, languages, choice, barred, onPick, }: { label: string; languages: string[]; choice: string | null; /** Bars one language — the translate lane cannot target its own source. */ barred?: string | null; onPick: (language: string) => void; }) { return ( // biome-ignore lint/a11y/useSemanticElements: a fieldset brings its own border, padding and min-width, which this group does not want
{languages.map((language) => ( ))}
); } /** The picker's effective choice: the one picked, unless it is barred or gone. */ function effectiveChoice( languages: string[], picked: string | null, barred: string | null = null, ): string | null { if (picked !== null && picked !== barred && languages.includes(picked)) { return picked; } return languages.find((language) => language !== barred) ?? null; } /** A labelled select, the same field vocabulary `/settings` already uses. */ function SubtitleField({ label, narrow = false, children, }: { label: string; narrow?: boolean; children: ReactNode; }) { return ( // biome-ignore lint/a11y/noLabelWithoutControl: the select is the child ); } type GrabState = "idle" | "busy" | "done" | "failed"; /** * One subtitle candidate. Its facts ride as chips in §15's ranking order: a * `moviehash` match wins outright and is the only chip that earns the * eligible green; the release name, then rating and download count, only * order what is left — so on a phone the tiebreakers are the first to go. */ function CandidateRow({ candidate, bucket, fetchCandidate, }: { candidate: SubtitleCandidate; bucket: "eligible" | "rejected"; fetchCandidate: (candidate: SubtitleCandidate, say: Say) => Promise; }) { const [note, say] = useNote(); const [grab, setGrab] = useState("idle"); const fact = (value: string, description: string, secondary: boolean, eligible = false) => ( {value} ); const flags = formatCandidateFlags(candidate); return ( {bucket === "rejected" && ( {`rejected · ${subtitleRuleLabel(candidate.rejected_rule)}`} )} {fact( formatHashMatch(candidate), candidate.hash_match ? "matched to this exact file by moviehash" : "no moviehash match against this file", false, candidate.hash_match, )} {fact( formatReleaseMatch(candidate), candidate.release_match ? "same release name as the file on disk" : "a different release name from the file on disk", false, )} {fact( formatUploaderRating(candidate.rating), candidate.rating === null ? "no uploader rating from this provider" : `uploader rating ${formatUploaderRating(candidate.rating)} out of 10`, true, )} {fact( formatDownloads(candidate.download_count), candidate.download_count === null ? "no download count from this provider" : `downloaded ${candidate.download_count} times`, true, )} {fact( flags, flags === "—" ? "a plain subtitle, neither SDH nor forced" : `flagged ${flags}`, true, )} } sub={candidate.release_name ?? "no release name given"} subExpands actions={[ { node: bucket === "eligible" ? ( { setGrab("busy"); void fetchCandidate(candidate, say).then((ok) => setGrab(ok ? "done" : "failed")); }} /> ) : null, width: "word", }, ]} note={note} /> ); } /** * §9.3's bucket structure with the middle bucket left out: `arr_core::subs` * has no `waived` verdict, because nothing about a subtitle is worth * overriding by hand. */ function CandidateBuckets({ results, fetchCandidate, }: { results: SubtitleSearchResults; fetchCandidate: (candidate: SubtitleCandidate, say: Say) => Promise; }) { const [open, setOpen] = useState(false); const eligible = results.candidates.filter((c) => c.verdict === "eligible"); const rejected = results.candidates.filter((c) => c.verdict !== "eligible"); return (
{eligible.length === 0 && ( )} {eligible.map((candidate) => ( ))}
); } /** Providers that could not answer are named, so "no candidates" and * "nobody could be asked" never read the same. */ function searchSummary(results: SubtitleSearchResults, language: string): string { const failures = results.provider_errors .map((failure) => `${failure.provider} could not answer — ${failure.error}`) .join(" · "); if (results.candidates.length === 0) { const nothing = `no ${language} candidate from any provider that answered`; return failures === "" ? nothing : `${nothing} · ${failures}`; } return failures === "" ? "" : failures; } interface LoadedOptions { languages: string[]; engines: string[]; } /** * One media file's subtitle chip and the manual panel it opens. The chip * rides in the file's own row (§9.6 keeps a file to one line), so the caller * places it among that row's other chips rather than on a line of its own, * and the panel in the row's tray. A new `status` after a manual fetch or * translation repaints both without resetting the panel underneath — an * operator mid-search does not lose the search. */ export function useSubtitleSection( status: SubtitleStatus | undefined, refresh: () => void, ): { chip: ReactNode; panel: ReactNode } { const [subtitles, setSubtitles] = useState(status?.subtitles ?? []); const missing = status?.missing ?? []; const tracks = status?.embedded_tracks ?? []; const runs = status?.translations ?? []; const [localRuns, setLocalRuns] = useState(null); const shownRuns = localRuns ?? runs; useEffect(() => { setSubtitles(status?.subtitles ?? []); setLocalRuns(null); }, [status]); const [open, setOpen] = useState(false); /** Null until the settings request lands; see `wantedSubtitles`. */ const [wanted, setWanted] = useState(null); const [options, setOptions] = useState(null); const [engine, setEngine] = useState(""); const [hintFault, setHintFault] = useState(null); const [presentNote, presentSay] = useNote(); const [searchLanguage, setSearchLanguage] = useState(null); const [targetLanguage, setTargetLanguage] = useState(null); const [searching, setSearching] = useState(false); const [searchNote, setSearchNote] = useState<(Note & { hidden?: boolean }) | null>({ text: "nothing is asked of a provider until you search.", }); const [fetchCount, setFetchCount] = useState(""); const [results, setResults] = useState<{ results: SubtitleSearchResults; paint: number } | null>( null, ); const [sourceValue, setSourceValue] = useState(""); const [extracting, setExtracting] = useState(false); const [starting, setStarting] = useState(false); const [translateNote, setTranslateNote] = useState(null); const previousRuns = useRef([]); // the wanted set decides which languages the chip may name at all, so it // is asked for on sight rather than when the panel opens; the request is // shared by every row on the page useEffect(() => { let live = true; void cachedSubtitleOptions().then((outcome) => { if (live) { setWanted(outcome.kind === "options" ? outcome.options.wanted_languages : []); } }); return () => { live = false; }; }, []); const mediaFileId = status?.media_file_id ?? 0; /** * Say where the file's translations stand, from the status rather than * from the click, so a run started before the page was left still shows. * The previous runs tell a landed language from one that never ran. */ useEffect(() => { const before = previousRuns.current; previousRuns.current = shownRuns; const now = shownRuns.filter((run) => run.state === "running"); const failed = shownRuns.find((run) => run.state === "failed"); const landed = before.find( (run) => run.state === "running" && !shownRuns.some((next) => next.language === run.language) && subtitles.some((subtitle) => subtitle.language === run.language), ); if (now.length > 0) { setTranslateNote({ text: `translating into ${now.map((run) => run.language).join(", ")}…` }); } else if (failed !== undefined) { setTranslateNote({ text: `translation into ${failed.language} failed — ${failed.detail ?? "no reason given"}`, tone: "fault", }); } else if (landed !== undefined) { setTranslateNote({ text: `written next to the video as a machine translation into ${landed.language}`, }); } // a run takes minutes; re-read on a slow beat until it settles, and stop // once the panel has left the page if (now.length === 0) { return; } const timer = window.setTimeout(refresh, TRANSLATION_POLL_MS); return () => window.clearTimeout(timer); }, [shownRuns, subtitles, refresh]); if (status === undefined) { return { chip: null, panel: null }; } const loadOptions = () => { if (options !== null) { return; } setOptions({ languages: [], engines: [] }); void cachedSubtitleOptions().then((outcome) => { const loaded = outcome.kind === "options" ? outcome.options : { wanted_languages: [], translation_engine: null, available_engines: [] }; setOptions({ languages: languageChoices(loaded.wanted_languages), engines: loaded.available_engines, }); if ( loaded.translation_engine !== null && loaded.available_engines.includes(loaded.translation_engine) ) { setEngine(loaded.translation_engine); } else { setEngine(loaded.available_engines[0] ?? ""); } if (outcome.kind === "error") { setHintFault( `subtitle settings unreadable — ${outcome.detail}. The language choices fall back to Portuguese and English.`, ); } else if (loaded.available_engines.length === 0) { setHintFault( "no translation engine is compiled into this binary — each backend is its own cargo feature.", ); } }); }; /* ---- the chip ---- */ const summary = subtitleSummary( { media_file_id: mediaFileId, subtitles, missing, embedded_tracks: tracks, translations: shownRuns, }, wanted, ); const panelId = `subs-panel-${mediaFileId}`; const chip = ( ); /* ---- sources: what is on the file, and what is still inside it ---- */ const sources = translationSources(subtitles); const offered = extractableTracks(tracks, subtitles); const empty = sources.length === 0 && offered.length === 0; const sourceOptions: string[] = [ // nothing on disk to fall back on, and a browser selects the first // option on sight — which would leave a track reading as picked // without having been written out. The operator picks it themselves. ...(sources.length === 0 && offered.length > 0 ? [""] : []), ...sources.map((subtitle) => `subtitle:${subtitle.id}`), ...offered.map((track) => `track:${track.index}`), ]; const source = sourceOptions.includes(sourceValue) ? sourceValue : (sourceOptions[0] ?? ""); /** * What the picker currently names, and which of the two kinds it is: a * subtitle already on disk, or a track still inside the video. Only the * second carries an `index`. */ const pickedFrom = (value: string): Subtitle | EmbeddedTrack | null => { const [kind, rest] = value.split(":"); if (kind === "subtitle") { return sources.find((subtitle) => String(subtitle.id) === rest) ?? null; } if (kind === "track") { return offered.find((track) => String(track.index) === rest) ?? null; } return null; }; const picked = pickedFrom(source); const languages = options?.languages ?? []; const searchChoice = effectiveChoice(languages, searchLanguage); // the target picker never offers the source's own language, whichever // kind of source it is — the API refuses it and it is never what was meant const barred = picked?.language ?? null; const targetChoice = effectiveChoice(languages, targetLanguage, barred); const engines = options?.engines ?? []; const engineDisabled = engines.length === 0; const running = shownRuns.filter((run) => run.state === "running"); // a track is a source only once it has been written out, so until then // the button has nothing to translate from const translateDisabled = engineDisabled || picked === null || "index" in picked || running.length > 0 || extracting || starting; const hint = empty ? "no subtitle with text on this file, and no text track inside it either — fetch one above. An image-based track carries bitmaps, not text, and is never a source." : (hintFault ?? (offered.length > 0 ? "any subtitle already on the file is a legal source, and so is a text track inside the video — picking one writes it out beside the video first." : "any subtitle already on the file is a legal source — a fetched one, an extracted embedded track, even another machine translation.")); /** * §15's extraction, on demand: the sidecar lands beside the video and * becomes an ordinary source. The row repaints from the answer before the * refresh returns, so the lane is usable immediately. The reconcile loop * only ever extracts while closing a gap, so on a file where nothing is * missing this is the only way a sidecar is ever written. */ const extractPicked = (track: EmbeddedTrack) => { setExtracting(true); setTranslateNote({ text: `writing the ${track.language} ${track.codec} track out…` }); void extractTrack(mediaFileId, track.index).then((outcome) => { setExtracting(false); if (outcome.kind === "error") { setTranslateNote({ text: `extraction failed — ${outcome.detail}`, tone: "fault" }); return; } setTranslateNote({ text: `written beside the video — ${outcome.subtitle.language} is now a source`, }); setSubtitles((current) => [...current, outcome.subtitle]); setSourceValue(`subtitle:${outcome.subtitle.id}`); refresh(); }); }; /** One click grabs, syncs and writes (§15) — then the chips repaint. */ const fetchCandidate = async (candidate: SubtitleCandidate, note: Say): Promise => { note(null); const outcome = await grabSubtitle(mediaFileId, candidate); if (outcome.kind === "error") { const stale = outcome.code === "candidate_expired" ? " — search again, a candidate id does not outlive its search" : ""; note(`grab failed — ${outcome.detail}${stale}`, "fault"); return false; } note( outcome.subtitle.sync === "rejected" ? "written — alass was implausible, so the unsynced original was kept and the file is flagged" : "fetched, synced and written", ); refresh(); return true; }; const search = () => { const language = searchChoice; if (language === null) { return; } setSearching(true); setFetchCount(""); setSearchNote({ text: `searching providers for ${language}…` }); void searchSubtitles(mediaFileId, language).then((outcome) => { setSearching(false); if (outcome.kind === "error") { setResults(null); setSearchNote({ text: `search failed — ${outcome.detail}`, tone: "fault" }); return; } setResults((current) => ({ results: outcome.results, paint: (current?.paint ?? 0) + 1 })); setFetchCount(String(outcome.results.candidates.length)); const text = searchSummary(outcome.results, language); setSearchNote({ text, tone: outcome.results.provider_errors.length > 0 ? "fault" : undefined, hidden: text === "", }); }); }; const translate = () => { const target = targetChoice; // a track that has not been written out carries no text; the change // handler extracts on pick, so this only guards the moment in between if (target === null || picked === null || "index" in picked || extracting) { return; } setStarting(true); setTranslateNote({ text: `starting a translation into ${target}…` }); void translateSubtitle(mediaFileId, { source_subtitle_id: picked.id, target_language: target, engine, }).then((outcome) => { setStarting(false); if (outcome.kind === "error") { setTranslateNote({ text: `translation failed — ${outcome.detail}`, tone: "fault" }); return; } setLocalRuns([ ...shownRuns.filter((run) => run.language !== outcome.run.language), outcome.run, ]); }); }; // the wanted set first, then its gaps, then everything nobody asked for: // the lane reads as the answer to "am I done here", with the stray // languages as the footnote they are const asked = wantedSubtitles(subtitles, wanted); const rest = subtitles.filter((subtitle) => !asked.includes(subtitle)); const panel = ( ); return { chip, panel }; }