// Settings (issue #116, §9.7): the signal chain, roots, policies, and the // runtime half of subtitle config (§15). import { type CSSProperties, type ReactNode, useCallback, useEffect, useRef, useState, } from "react"; import { LAYER, useEscape, useLive, useNav } from "../context"; import type { Check, CheckStatus } from "../health"; import { ArmedDeleteIcon, type IconName } from "../icons"; import type { Root } from "../search"; import { deleteRow, fetchPolicies, fetchRoots, fetchSubtitleSettings, type PolicyDoc, PROVIDERS, RESOLUTIONS, type RootInput, SOURCES, type SubtitleSettings, type SubtitleSettingsInput, savePolicy, saveRoot, saveSubtitleSettings, } from "../settings"; import { forgetSubtitleOptions } from "../subtitles"; import { Chip, Control, cx, DeckHead, GroupNote, IconControl, type Note, NoteLine, Row, StatusSlot, useNote, useStatus, } from "../ui"; /* ---- the signal chain ---------------------------------------------------- */ type Tone = "ok" | "warn" | "fault" | "idle"; const TONE_BY_STATUS: Record = { ok: "ok", unconfigured: "warn", unreachable: "fault", }; interface ModuleState { state: string; tone: Tone; word: string; detail?: string | null; } function ChainModule({ name, area, duty, defaultDetail, module, strike, master = false, }: { name: string; area: string; duty: string; defaultDetail: string; module: ModuleState; /** Stagger order for the one power-up animation, upstream to downstream. */ strike: number; master?: boolean; }) { return (

{duty}

{module.detail ?? defaultDetail}

); } function Bus({ area, tone }: { area: string; tone: Tone | null }) { return ( ); } /** One lamp of the subtitle lane (#200): same module shape as the chain. */ function SubtitleModule({ name, duty, check }: { name: string; duty: string; check: Check }) { return (

{name}

{check.status}

{duty}

{check.detail ?? ""}

); } const PROBING: ModuleState = { state: "probing", tone: "idle", word: "probing" }; function Chain() { const { probe } = useLive(); let master = PROBING; let checks = { tmdb: PROBING, prowlarr: PROBING, qbit: PROBING }; let traces: Record<"tmdb" | "prowlarr" | "master", Tone | null> = { tmdb: null, prowlarr: null, master: null, }; let lane: { name: string; duty: string; check: Check }[] | null = null; if (probe?.kind === "unreachable") { // the outage detail lives on the chain's arr module — the header has no verdict line master = { state: "unreachable", tone: "fault", word: "down", detail: probe.detail }; const off: ModuleState = { state: "off", tone: "idle", word: "no signal" }; checks = { tmdb: off, prowlarr: off, qbit: off }; } else if (probe?.kind === "report") { const { report } = probe; const degraded = report.status === "degraded"; master = { state: degraded ? "degraded" : "ok", tone: degraded ? "warn" : "ok", word: report.status, }; const module = (check: Check): ModuleState => ({ state: check.status, tone: TONE_BY_STATUS[check.status], word: check.status, detail: check.detail, }); checks = { tmdb: module(report.tmdb), prowlarr: module(report.prowlarr), qbit: module(report.qbit), }; traces = { tmdb: TONE_BY_STATUS[report.tmdb.status], prowlarr: TONE_BY_STATUS[report.prowlarr.status], master: degraded ? "warn" : "ok", }; const subs = report.subtitles; lane = subs.providers.map((provider) => ({ name: provider.id, duty: "subtitles in", check: provider, })); if (subs.translation) { lane.push({ name: "translate", duty: "engine out", check: subs.translation }); } lane.push({ name: "alass", duty: "timing sync", check: subs.alass }); lane.push({ name: "ffmpeg", duty: "track extraction", check: subs.ffmpeg }); } return ( <>
); } /* ---- form primitives ---------------------------------------------------- */ function Field({ label, children }: { label: string; children: ReactNode }) { return (
{label} {children}
); } function TextInput({ value, onChange, placeholder = "", invalid, disabled, autoFocus, ...rest }: { value: string; onChange: (value: string) => void; placeholder?: string; invalid?: boolean; disabled?: boolean; autoFocus?: boolean; "aria-label"?: string; }) { const ref = useRef(null); useEffect(() => { if (autoFocus) { ref.current?.focus(); } }, [autoFocus]); return ( onChange(event.target.value)} {...rest} /> ); } function NumberInput({ value, onChange, className, placeholder, ...rest }: { value: string; onChange: (value: string) => void; className?: string; placeholder?: string; "aria-label"?: string; }) { return ( onChange(event.target.value)} {...rest} /> ); } function Select({ options, value, onChange, disabled, autoFocus, }: { options: readonly (string | { value: string; label: string })[]; value: string; onChange: (value: string) => void; disabled?: boolean; autoFocus?: boolean; }) { const ref = useRef(null); useEffect(() => { if (autoFocus) { ref.current?.focus(); } }, [autoFocus]); return ( ); } /** `a, b, c` ⇄ parts. Empty entries dropped; validation happens at save. */ function listValue(value: string): string[] { return value .split(",") .map((part) => part.trim()) .filter((part) => part !== ""); } /** The first entry a comma list carries that its vocabulary does not know. */ function unknownIn(value: string, known: readonly string[]): string | undefined { return listValue(value).find((part) => !known.includes(part)); } /** A panel's save, cancel and status line. */ function PanelActions({ save, saveLabel, busy, note, onCancel, }: { save: () => void; saveLabel: string; busy: boolean; note: Note | null; onCancel?: () => void; }) { return (
{onCancel && }
); } /* ---- roots ------------------------------------------------------------- */ function RootPanel({ root, policies, onSaved, onCancel, }: { root: Root | null; policies: PolicyDoc[]; onSaved: () => void; onCancel: () => void; }) { const [kind, setKind] = useState(root?.kind ?? "movie"); const [audience, setAudience] = useState(root?.audience ?? "main"); const [path, setPath] = useState(root?.path ?? ""); const [policyId, setPolicyId] = useState(String(root?.policy_id ?? policies[0]?.id ?? "")); const [busy, setBusy] = useState(false); const [note, setNote] = useState(null); const save = () => { setBusy(true); setNote({ text: "saving…" }); const input: RootInput = { kind, audience, path: path.trim(), policy_id: Number(policyId) }; void saveRoot(root?.id ?? null, input).then((outcome) => { if (outcome.ok) { onSaved(); return; } setBusy(false); setNote({ text: outcome.detail, tone: "fault" }); }); }; return (
{RESOLUTIONS.map((resolution) => { const band = bands[resolution] ?? { floor: "", target: "", penalty: "", ceiling: "" }; const set = (key: keyof BandFields) => (value: string) => setBands({ ...bands, [resolution]: { ...band, [key]: value } }); return (
{resolution}
); })} {SOURCES.map((source) => ( setSources({ ...sources, [source]: value })} aria-label={`${source} source weight`} /> ))} {WEIGHT_KEYS.map((key) => ( setWeights({ ...weights, [key]: value })} aria-label={key.replaceAll("_", " ")} /> ))}
); } function requiredAudioLabel(policy: PolicyDoc): string { return policy.required_audio.require === "original_language" ? "original language" : `any of ${policy.required_audio.langs.join(", ")}`; } /** * One settings row: identity, chips, then the edit and delete pair in the * row's fixed action column. The edit panel opens in the row's tray. */ function SettingsRow({ title, chips, label, remove, panel, onDeleted, }: { title: string; chips: string[]; label: string; remove: () => Promise; panel: (close: () => void) => ReactNode; onDeleted: () => void; }) { const [note, say] = useNote(); const [editing, setEditing] = useState(false); return ( {text})} actions={[ { node: ( setEditing(!editing)} /> ), width: "icon", }, { node: ( say(text, "warn")} execute={() => remove().then((detail) => { if (detail !== null) { say(detail, "fault"); return false; } onDeleted(); return undefined; }) } /> ), width: "icon", }, ]} note={note} tray={editing && panel(() => setEditing(false))} /> ); } /* ---- subtitles ----------------------------------------------------------- */ /** * A reorder control: the same icon control the sibling rows in this view * use (#231), with a chevron off the shared glyph set (#251) rather than * the words "up" and "down". */ function MoveButton({ direction, label, disabled, onClick, }: { direction: "up" | "down"; label: string; disabled: boolean; onClick: () => void; }) { const glyph: IconName = direction === "up" ? "chevronUp" : "chevronDown"; return ( ); } interface ProviderFields { provider: string; enabled: boolean; budget: string; } function SubtitlesPanel({ settings, onSaved, }: { settings: SubtitleSettings; onSaved: () => void; }) { const [wanted, setWanted] = useState(settings.wanted_languages.join(", ")); const hasEngines = settings.available_engines.length > 0; const [engine, setEngine] = useState(settings.translation_engine ?? "none"); const [timeout, setTimeoutValue] = useState(String(settings.remote_command_timeout_seconds)); const hasOpenAi = settings.available_engines.includes("openai"); const [baseUrl, setBaseUrl] = useState(settings.openai_base_url ?? ""); const [model, setModel] = useState(settings.openai_model ?? ""); const [translators, setTranslators] = useState>(() => Object.fromEntries( settings.available_engines.map((name) => [ name, String(settings.translator_daily_budgets[name] ?? 0), ]), ), ); // list order is the priority order the API stores in `providers_enabled`. // Disabled providers stay in the list, at whatever position they were // left, so re-enabling one keeps its spot. const [providers, setProviders] = useState(() => { const enabled = new Set(settings.providers_enabled); return [ ...settings.providers_enabled, ...PROVIDERS.filter((provider) => !enabled.has(provider)), ].map((provider) => ({ provider, enabled: enabled.has(provider), budget: String(settings.provider_daily_budgets[provider] ?? 0), })); }); const [busy, setBusy] = useState(false); const [note, setNote] = useState(null); const move = (index: number, by: number) => { const next = [...providers]; const [moved] = next.splice(index, 1); if (moved) { next.splice(index + by, 0, moved); setProviders(next); } }; const updateProvider = (index: number, change: Partial) => { setProviders(providers.map((entry, at) => (at === index ? { ...entry, ...change } : entry))); }; const save = () => { const providerBudgets: Record = {}; for (const entry of providers) { const value = Number(entry.budget); if (value > 0) { providerBudgets[entry.provider] = value; } } const translatorBudgets: Record = {}; for (const [name, raw] of Object.entries(translators)) { const value = Number(raw); if (value > 0) { translatorBudgets[name] = value; } } setBusy(true); setNote({ text: "saving…" }); const input: SubtitleSettingsInput = { wanted_languages: listValue(wanted), providers_enabled: providers.filter((entry) => entry.enabled).map((entry) => entry.provider), translation_engine: engine === "none" ? null : engine, provider_daily_budgets: providerBudgets, translator_daily_budgets: translatorBudgets, remote_command_timeout_seconds: Number(timeout), // An emptied field is "use the backend's default", which the API // stores as NULL. openai_base_url: hasOpenAi ? baseUrl.trim() || null : settings.openai_base_url, openai_model: hasOpenAi ? model.trim() || null : settings.openai_model, }; void saveSubtitleSettings(input).then((outcome) => { if (outcome.ok) { // the wanted set decides which languages a title page's subtitle // chip may name, and that page caches it — this is where it goes // stale, so this is where it is dropped forgetSubtitleOptions(); onSaved(); return; } setBusy(false); setNote({ text: outcome.detail, tone: "fault" }); }); }; return (
updateProvider(index, { enabled: event.target.checked })} /> } title={entry.provider} actions={[ { node: ( updateProvider(index, { budget: value })} aria-label={`${entry.provider} daily budget`} /> ), width: "word", }, { node: ( move(index, -1)} /> ), width: "icon", }, { node: ( move(index, 1)} /> ), width: "icon", }, ]} /> ))}
); } /* ---- the view ------------------------------------------------------------ */ interface Loaded { roots: Root[]; policies: PolicyDoc[]; subtitles: SubtitleSettings; /** Bumped on every reload, so open panels close on the fresh rows. */ paint: number; } export function SettingsView({ hidden }: { hidden: boolean }) { const nav = useNav(); const [loaded, setLoaded] = useState(null); const [status, setStatus] = useStatus(); const [addingRoot, setAddingRoot] = useState(false); const [addingPolicy, setAddingPolicy] = useState(false); // guards a stale fetch from painting over a newer view const sequence = useRef(0); useEscape(LAYER.base, !hidden, nav.goHome); const load = useCallback(async () => { sequence.current += 1; const ticket = sequence.current; setStatus("reading settings…"); try { const [roots, policies, subtitles] = await Promise.all([ fetchRoots(), fetchPolicies(), fetchSubtitleSettings(), ]); if (ticket !== sequence.current) { return; } setLoaded((previous) => ({ roots, policies, subtitles, paint: (previous?.paint ?? 0) + 1 })); setStatus(null); } catch (error) { if (ticket !== sequence.current) { return; } setLoaded(null); setStatus(`settings unavailable — ${(error as Error).message}`, "fault"); } }, [setStatus]); useEffect(() => { void load(); return () => { sequence.current += 1; }; }, [load]); const reload = () => void load(); return (

settings

{loaded === null ? "" : `${loaded.roots.length} roots · ${loaded.policies.length} policies`}
); }