look.ts builds each control's class list from its whole state, so no two utilities fight over a property. The contextual overrides from rows, trays, page heads and the removal panel become props. Refs #280 Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
884 lines
30 KiB
TypeScript
884 lines
30 KiB
TypeScript
// 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 (
|
|
<Chip
|
|
data-verdict={
|
|
!subtitle.forced && (wanted === null || wanted.includes(subtitle.language))
|
|
? "eligible"
|
|
: undefined
|
|
}
|
|
data-mt={subtitle.origin === "translated" ? "true" : undefined}
|
|
data-tone={failed ? "fault" : undefined}
|
|
>
|
|
{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 && (
|
|
<ArmedDeleteIcon
|
|
label={`delete ${fileName(path)}`}
|
|
compact
|
|
explain={(text) => 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;
|
|
});
|
|
}}
|
|
/>
|
|
)}
|
|
</Chip>
|
|
);
|
|
}
|
|
|
|
/** 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 (
|
|
<Chip
|
|
data-movie-state="missing"
|
|
data-wanted="true"
|
|
explain={
|
|
say && missing.reason === "failed" && missing.detail !== null
|
|
? { text: missing.detail, say, tone: "fault" }
|
|
: undefined
|
|
}
|
|
>
|
|
{missingChipLabel(missing)}
|
|
</Chip>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 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
|
|
<div className={segmented(true)} role="group" aria-label={label}>
|
|
{languages.map((language) => (
|
|
<button
|
|
key={language}
|
|
type="button"
|
|
className={seg(language === choice)}
|
|
data-language={language}
|
|
aria-pressed={language === choice}
|
|
disabled={language === barred}
|
|
onClick={() => onPick(language)}
|
|
>
|
|
{language}
|
|
</button>
|
|
))}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** 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
|
|
<label className={narrow ? "field subs-field subs-field-narrow" : "field subs-field"}>
|
|
<span className="field-label readout dim">{label}</span>
|
|
{children}
|
|
</label>
|
|
);
|
|
}
|
|
|
|
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<boolean>;
|
|
}) {
|
|
const [note, say] = useNote();
|
|
const [grab, setGrab] = useState<GrabState>("idle");
|
|
const fact = (value: string, description: string, secondary: boolean, eligible = false) => (
|
|
<Chip
|
|
className={value === "—" ? "dim" : undefined}
|
|
aria-label={description}
|
|
data-pri={secondary ? "2" : undefined}
|
|
data-verdict={eligible ? "eligible" : undefined}
|
|
>
|
|
{value}
|
|
</Chip>
|
|
);
|
|
const flags = formatCandidateFlags(candidate);
|
|
return (
|
|
<Row
|
|
kind="candidate"
|
|
title={candidate.provider}
|
|
meta={
|
|
<>
|
|
{bucket === "rejected" && (
|
|
<Chip data-verdict="rejected">{`rejected · ${subtitleRuleLabel(candidate.rejected_rule)}`}</Chip>
|
|
)}
|
|
{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" ? (
|
|
<Control
|
|
text={
|
|
grab === "busy"
|
|
? "fetching"
|
|
: grab === "done"
|
|
? "written"
|
|
: grab === "failed"
|
|
? "retry"
|
|
: "grab"
|
|
}
|
|
fixed
|
|
busy={grab === "busy"}
|
|
done={grab === "done"}
|
|
failed={grab === "failed"}
|
|
disabled={grab === "busy" || grab === "done"}
|
|
onClick={() => {
|
|
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<boolean>;
|
|
}) {
|
|
const [open, setOpen] = useState(false);
|
|
const eligible = results.candidates.filter((c) => c.verdict === "eligible");
|
|
const rejected = results.candidates.filter((c) => c.verdict !== "eligible");
|
|
return (
|
|
<div className="subs-buckets">
|
|
<Section spacing="mb-3">
|
|
<DeckHead as="h4" label="eligible" count={eligible.length} />
|
|
<Rows>
|
|
{eligible.length === 0 && (
|
|
<EmptyRow text="none — every candidate names the rule that rejected it below" />
|
|
)}
|
|
{eligible.map((candidate) => (
|
|
<CandidateRow
|
|
key={`${candidate.provider}:${candidate.candidate_id}`}
|
|
candidate={candidate}
|
|
bucket="eligible"
|
|
fetchCandidate={fetchCandidate}
|
|
/>
|
|
))}
|
|
</Rows>
|
|
</Section>
|
|
<Section spacing="mb-3" hidden={rejected.length === 0}>
|
|
<DeckHead as="h4" label="rejected" count={rejected.length}>
|
|
<Disclosure count={rejected.length} open={open} onToggle={() => setOpen(!open)} />
|
|
</DeckHead>
|
|
<div hidden={!open}>
|
|
<Rows>
|
|
{rejected.map((candidate) => (
|
|
<CandidateRow
|
|
key={`${candidate.provider}:${candidate.candidate_id}`}
|
|
candidate={candidate}
|
|
bucket="rejected"
|
|
fetchCandidate={fetchCandidate}
|
|
/>
|
|
))}
|
|
</Rows>
|
|
</div>
|
|
</Section>
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/** 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<Subtitle[]>(status?.subtitles ?? []);
|
|
const missing = status?.missing ?? [];
|
|
const tracks = status?.embedded_tracks ?? [];
|
|
const runs = status?.translations ?? [];
|
|
const [localRuns, setLocalRuns] = useState<Translation[] | null>(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<string[] | null>(null);
|
|
const [options, setOptions] = useState<LoadedOptions | null>(null);
|
|
const [engine, setEngine] = useState("");
|
|
const [hintFault, setHintFault] = useState<string | null>(null);
|
|
|
|
const [presentNote, presentSay] = useNote();
|
|
const [searchLanguage, setSearchLanguage] = useState<string | null>(null);
|
|
const [targetLanguage, setTargetLanguage] = useState<string | null>(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<Note | null>(null);
|
|
const previousRuns = useRef<Translation[]>([]);
|
|
|
|
// 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 = (
|
|
<button
|
|
type="button"
|
|
className="chip subs-chip"
|
|
aria-expanded={open}
|
|
aria-controls={panelId}
|
|
data-verdict={summary.satisfied ? "eligible" : "wanted"}
|
|
aria-label={subtitleSummaryLabel(summary)}
|
|
onClick={() => {
|
|
setOpen(!open);
|
|
if (!open) {
|
|
loadOptions();
|
|
}
|
|
}}
|
|
>
|
|
<Icon name="captions" />
|
|
{/* the codes read as one string — the chip's own flex gap would otherwise
|
|
open a space in front of every comma. The run is as wide as the wanted
|
|
set can ever need, so the chips after it stay in column. */}
|
|
<span className="subs-chip-langs" style={{ width: `${summaryWidth(wanted)}ch` }}>
|
|
{summary.languages.length === 0 && <span className="dim">none</span>}
|
|
{summary.languages.map((entry, index) => (
|
|
<span key={entry.language} data-mt={entry.translated ? "true" : undefined}>
|
|
{index === 0 ? entry.language : `,${entry.language}`}
|
|
</span>
|
|
))}
|
|
{summary.overflow > 0 && <span>{`+${summary.overflow}`}</span>}
|
|
</span>
|
|
{/* §4.2's one glyph exemption: everything wanted is on disk, drawn as a
|
|
check. The slot is there either way, so a check appearing never
|
|
moves the row's other chips. */}
|
|
<span className="subs-chip-mark">{summary.satisfied && <Icon name="check" />}</span>
|
|
</button>
|
|
);
|
|
|
|
/* ---- 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<boolean> => {
|
|
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 = (
|
|
<div className="subs-panel" id={panelId} hidden={!open}>
|
|
<Section spacing="mb-4 last:mb-0">
|
|
<DeckHead label="on this file" />
|
|
<div className="subs-present">
|
|
{asked.map((subtitle) => (
|
|
<SubtitleChip
|
|
key={subtitle.id}
|
|
subtitle={subtitle}
|
|
wanted={wanted}
|
|
onDeleted={refresh}
|
|
say={presentSay}
|
|
/>
|
|
))}
|
|
{missing.map((gap) => (
|
|
<MissingSubtitleChip key={gap.language} missing={gap} say={presentSay} />
|
|
))}
|
|
{rest.map((subtitle) => (
|
|
<SubtitleChip
|
|
key={subtitle.id}
|
|
subtitle={subtitle}
|
|
wanted={wanted}
|
|
onDeleted={refresh}
|
|
say={presentSay}
|
|
/>
|
|
))}
|
|
{subtitles.length === 0 && missing.length === 0 && (
|
|
<p className="readout dim">no subtitles on this file yet.</p>
|
|
)}
|
|
</div>
|
|
<NoteLine note={presentNote} className="subs-note readout" />
|
|
</Section>
|
|
|
|
<Section spacing="mb-4 last:mb-0">
|
|
<DeckHead label="fetch" count={fetchCount} />
|
|
<div className="subs-controls">
|
|
<LanguagePicker
|
|
label="language to search for"
|
|
languages={languages}
|
|
choice={searchChoice}
|
|
onPick={setSearchLanguage}
|
|
/>
|
|
<button type="button" className={control()} disabled={searching} onClick={search}>
|
|
search
|
|
</button>
|
|
</div>
|
|
<p
|
|
className="subs-note readout"
|
|
role="status"
|
|
data-tone={searchNote?.tone}
|
|
hidden={searchNote?.hidden}
|
|
>
|
|
{searchNote?.text ?? ""}
|
|
</p>
|
|
{results !== null && (
|
|
<CandidateBuckets
|
|
key={results.paint}
|
|
results={results.results}
|
|
fetchCandidate={fetchCandidate}
|
|
/>
|
|
)}
|
|
</Section>
|
|
|
|
<Section spacing="mb-4 last:mb-0">
|
|
<DeckHead label="translate" />
|
|
<div className="subs-controls">
|
|
<SubtitleField label="source">
|
|
<select
|
|
className="form-input"
|
|
value={source}
|
|
disabled={empty || extracting}
|
|
onChange={(event) => {
|
|
const value = event.target.value;
|
|
setSourceValue(value);
|
|
const next = pickedFrom(value);
|
|
if (next !== null && "index" in next) {
|
|
extractPicked(next);
|
|
}
|
|
}}
|
|
>
|
|
{sources.length === 0 && offered.length > 0 && (
|
|
<option value="">pick a track to write out</option>
|
|
)}
|
|
{sources.length > 0 && (
|
|
<optgroup label="on this file">
|
|
{sources.map((subtitle) => (
|
|
<option key={subtitle.id} value={`subtitle:${subtitle.id}`}>
|
|
{subtitleChipLabel(subtitle)}
|
|
</option>
|
|
))}
|
|
</optgroup>
|
|
)}
|
|
{offered.length > 0 && (
|
|
<optgroup label="inside the video — written out when picked">
|
|
{offered.map((track) => (
|
|
<option key={track.index} value={`track:${track.index}`}>
|
|
{embeddedTrackLabel(track)}
|
|
</option>
|
|
))}
|
|
</optgroup>
|
|
)}
|
|
{empty && <option value="">nothing to translate from</option>}
|
|
</select>
|
|
</SubtitleField>
|
|
<LanguagePicker
|
|
label="language to translate into"
|
|
languages={languages}
|
|
choice={targetChoice}
|
|
barred={barred}
|
|
onPick={setTargetLanguage}
|
|
/>
|
|
<SubtitleField label="engine" narrow>
|
|
<select
|
|
className="form-input"
|
|
value={engineDisabled ? "" : engine}
|
|
disabled={engineDisabled}
|
|
onChange={(event) => setEngine(event.target.value)}
|
|
>
|
|
{engines.map((name) => (
|
|
<option key={name} value={name}>
|
|
{name}
|
|
</option>
|
|
))}
|
|
{engineDisabled && <option value="">none compiled in</option>}
|
|
</select>
|
|
</SubtitleField>
|
|
<button
|
|
type="button"
|
|
className={control()}
|
|
disabled={translateDisabled}
|
|
onClick={translate}
|
|
>
|
|
translate
|
|
</button>
|
|
</div>
|
|
<p
|
|
className="subs-note readout"
|
|
role="status"
|
|
data-tone={empty ? undefined : hintFault === null ? undefined : "fault"}
|
|
>
|
|
{options === null ? "" : hint}
|
|
</p>
|
|
<NoteLine note={translateNote} className="subs-note readout" />
|
|
</Section>
|
|
</div>
|
|
);
|
|
|
|
return { chip, panel };
|
|
}
|