Same markup, class names and behaviour as the hand-built views; the data modules are reused unchanged. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1242 lines
37 KiB
TypeScript
1242 lines
37 KiB
TypeScript
// 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<CheckStatus, Tone> = {
|
||
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 (
|
||
<article className={cx("module", master && "module-master", area)}>
|
||
<header className="module-head">
|
||
<span
|
||
className={cx("lamp", master && "lamp-big")}
|
||
data-state={module.state}
|
||
aria-hidden="true"
|
||
style={{ "--strike": String(strike) } as CSSProperties}
|
||
/>
|
||
<h4 className="module-name">{name}</h4>
|
||
<span className="module-status readout" data-tone={module.tone}>
|
||
{module.word}
|
||
</span>
|
||
</header>
|
||
<p className="module-role">{duty}</p>
|
||
<p className="module-detail readout">{module.detail ?? defaultDetail}</p>
|
||
</article>
|
||
);
|
||
}
|
||
|
||
function Bus({ area, tone }: { area: string; tone: Tone | null }) {
|
||
return (
|
||
<div className={cx("bus", area)} aria-hidden="true">
|
||
<svg
|
||
viewBox="0 0 40 8"
|
||
preserveAspectRatio="none"
|
||
className="bus-trace"
|
||
data-tone={tone === null || tone === "idle" ? undefined : tone}
|
||
aria-hidden="true"
|
||
>
|
||
<line x1="0" y1="4" x2="32" y2="4" />
|
||
<path d="M32 0.5 39 4 32 7.5 Z" className="bus-arrow" />
|
||
</svg>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/** 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 (
|
||
<article className="module">
|
||
<header className="module-head">
|
||
<span className="lamp" data-state={check.status} />
|
||
<h2 className="module-name">{name}</h2>
|
||
<span className="module-status readout" data-tone={TONE_BY_STATUS[check.status]}>
|
||
{check.status}
|
||
</span>
|
||
</header>
|
||
<p className="module-role">{duty}</p>
|
||
<p className="module-detail readout">{check.detail ?? ""}</p>
|
||
</article>
|
||
);
|
||
}
|
||
|
||
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 (
|
||
<>
|
||
<section className="chain-wrap" aria-label="signal chain">
|
||
<div className={cx("chain", probe !== null && "powered")}>
|
||
<ChainModule
|
||
name="tmdb"
|
||
area="area-tmdb"
|
||
duty="metadata in"
|
||
defaultDetail="titles, languages, release dates"
|
||
module={checks.tmdb}
|
||
strike={0}
|
||
/>
|
||
<Bus area="area-t1" tone={traces.tmdb} />
|
||
<ChainModule
|
||
name="prowlarr"
|
||
area="area-prowlarr"
|
||
duty="indexers in"
|
||
defaultDetail="torznab search and rss"
|
||
module={checks.prowlarr}
|
||
strike={1}
|
||
/>
|
||
<Bus area="area-t2" tone={traces.prowlarr} />
|
||
<ChainModule
|
||
name="arr"
|
||
area="area-master"
|
||
duty="reconcile core"
|
||
defaultDetail="decide · find · fetch · import"
|
||
module={master}
|
||
strike={2}
|
||
master
|
||
/>
|
||
<Bus area="area-out" tone={traces.master} />
|
||
<ChainModule
|
||
name="qbittorrent"
|
||
area="area-qbittorrent"
|
||
duty="torrents out"
|
||
defaultDetail="webui · grab and seed"
|
||
module={checks.qbit}
|
||
strike={3}
|
||
/>
|
||
</div>
|
||
</section>
|
||
<section className="chain-lane" aria-label="subtitle lane" hidden={lane === null}>
|
||
{lane?.map((entry) => (
|
||
<SubtitleModule
|
||
key={entry.name}
|
||
name={entry.name}
|
||
duty={entry.duty}
|
||
check={entry.check}
|
||
/>
|
||
))}
|
||
</section>
|
||
</>
|
||
);
|
||
}
|
||
|
||
/* ---- form primitives ---------------------------------------------------- */
|
||
|
||
function Field({ label, children }: { label: string; children: ReactNode }) {
|
||
return (
|
||
<div className="field">
|
||
<span className="field-label readout dim">{label}</span>
|
||
{children}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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<HTMLInputElement>(null);
|
||
useEffect(() => {
|
||
if (autoFocus) {
|
||
ref.current?.focus();
|
||
}
|
||
}, [autoFocus]);
|
||
return (
|
||
<input
|
||
ref={ref}
|
||
type="text"
|
||
className="form-input readout"
|
||
value={value}
|
||
placeholder={placeholder}
|
||
spellCheck={false}
|
||
autoComplete="off"
|
||
disabled={disabled}
|
||
data-invalid={invalid ? "true" : undefined}
|
||
onChange={(event) => 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 (
|
||
<input
|
||
type="number"
|
||
className={cx("form-input readout form-num", className)}
|
||
value={value}
|
||
placeholder={placeholder}
|
||
onChange={(event) => 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<HTMLSelectElement>(null);
|
||
useEffect(() => {
|
||
if (autoFocus) {
|
||
ref.current?.focus();
|
||
}
|
||
}, [autoFocus]);
|
||
return (
|
||
<select
|
||
ref={ref}
|
||
className="form-input readout"
|
||
value={value}
|
||
disabled={disabled}
|
||
onChange={(event) => onChange(event.target.value)}
|
||
>
|
||
{options.map((option) => {
|
||
const { value: optionValue, label } =
|
||
typeof option === "string" ? { value: option, label: option } : option;
|
||
return (
|
||
<option key={optionValue} value={optionValue}>
|
||
{label}
|
||
</option>
|
||
);
|
||
})}
|
||
</select>
|
||
);
|
||
}
|
||
|
||
/** `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 (
|
||
<div className="add-actions">
|
||
<Control text={saveLabel} disabled={busy} onClick={save} />
|
||
{onCancel && <Control text="cancel" quiet onClick={onCancel} />}
|
||
<NoteLine note={note} className="add-note readout" />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---- 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<Note | null>(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 (
|
||
<div className="edit-panel add-panel">
|
||
<div className="form-grid">
|
||
<Field label="kind">
|
||
<Select
|
||
options={["movie", "tv"]}
|
||
value={kind}
|
||
onChange={setKind}
|
||
autoFocus={root === null}
|
||
/>
|
||
</Field>
|
||
<Field label="audience">
|
||
<Select options={["main", "kids"]} value={audience} onChange={setAudience} />
|
||
</Field>
|
||
<Field label="path">
|
||
<TextInput
|
||
value={path}
|
||
onChange={setPath}
|
||
placeholder="/mnt/media/…"
|
||
autoFocus={root !== null}
|
||
/>
|
||
</Field>
|
||
<Field label="policy">
|
||
<Select
|
||
// readable option labels without coupling value → name lookups
|
||
options={policies.map((policy) => ({ value: String(policy.id), label: policy.name }))}
|
||
value={policyId}
|
||
onChange={setPolicyId}
|
||
/>
|
||
</Field>
|
||
</div>
|
||
<PanelActions
|
||
save={save}
|
||
saveLabel={root === null ? "create root" : "save root"}
|
||
busy={busy}
|
||
note={note}
|
||
onCancel={onCancel}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---- policies ---------------------------------------------------------- */
|
||
|
||
const WEIGHT_KEYS = [
|
||
"size_at_target",
|
||
"source_tier",
|
||
"seeder_doubling",
|
||
"resolution_step",
|
||
] as const;
|
||
type WeightKey = (typeof WEIGHT_KEYS)[number];
|
||
type SourceKey = (typeof SOURCES)[number];
|
||
|
||
const DV_PROFILES = ["5", "7", "8"] as const;
|
||
|
||
function newPolicyDoc(): Omit<PolicyDoc, "id"> {
|
||
return {
|
||
name: "",
|
||
required_audio: { require: "original_language" },
|
||
dub_blacklist: ["pt-BR"],
|
||
hdr_rules: { dv_profile_reject: ["5", "7"] },
|
||
size_bands: {},
|
||
resolution_pref: ["2160p", "1080p"],
|
||
source_weights: {},
|
||
score_weights: {
|
||
size_at_target: 1000,
|
||
source_tier: 25,
|
||
seeder_doubling: 8,
|
||
resolution_step: 10000,
|
||
},
|
||
};
|
||
}
|
||
|
||
interface BandFields {
|
||
floor: string;
|
||
target: string;
|
||
penalty: string;
|
||
ceiling: string;
|
||
}
|
||
|
||
function PolicyPanel({
|
||
policy,
|
||
onSaved,
|
||
onCancel,
|
||
}: {
|
||
policy: PolicyDoc | null;
|
||
onSaved: () => void;
|
||
onCancel: () => void;
|
||
}) {
|
||
const initial: Omit<PolicyDoc, "id"> = policy ?? newPolicyDoc();
|
||
const [name, setName] = useState(initial.name);
|
||
const [audioMode, setAudioMode] = useState<string>(initial.required_audio.require);
|
||
const [audioLangs, setAudioLangs] = useState(
|
||
initial.required_audio.require === "any_of" ? initial.required_audio.langs.join(", ") : "",
|
||
);
|
||
const [blacklist, setBlacklist] = useState(initial.dub_blacklist.join(", "));
|
||
const [profiles, setProfiles] = useState(initial.hdr_rules.dv_profile_reject.join(", "));
|
||
const [pref, setPref] = useState(initial.resolution_pref.join(", "));
|
||
// one line per resolution: floor, target, penalty, ceiling — numbers stay
|
||
// numbers, and an empty ceiling is no ceiling
|
||
const [bands, setBands] = useState<Record<string, BandFields>>(() =>
|
||
Object.fromEntries(
|
||
RESOLUTIONS.map((resolution) => {
|
||
const band = initial.size_bands[resolution];
|
||
return [
|
||
resolution,
|
||
{
|
||
floor: String(band?.floor_gib ?? 0),
|
||
target: String(band?.target_gib ?? 0),
|
||
penalty: String(band?.penalty_points_per_gib_over ?? 0),
|
||
ceiling: band?.ceiling_gib === undefined ? "" : String(band.ceiling_gib),
|
||
},
|
||
];
|
||
}),
|
||
),
|
||
);
|
||
const [sources, setSources] = useState<Record<SourceKey, string>>(
|
||
() =>
|
||
Object.fromEntries(
|
||
SOURCES.map((source) => [source, String(initial.source_weights[source] ?? 0)]),
|
||
) as Record<SourceKey, string>,
|
||
);
|
||
const [weights, setWeights] = useState<Record<WeightKey, string>>(
|
||
() =>
|
||
Object.fromEntries(
|
||
WEIGHT_KEYS.map((key) => [key, String(initial.score_weights[key])]),
|
||
) as Record<WeightKey, string>,
|
||
);
|
||
const [busy, setBusy] = useState(false);
|
||
const [saveNote, setSaveNote] = useState<Note | null>(null);
|
||
|
||
// the comma lists check their vocabulary while typing, so an unknown
|
||
// resolution or profile is named before a round trip
|
||
const badProfile = unknownIn(profiles, DV_PROFILES);
|
||
const badPref = unknownIn(pref, RESOLUTIONS);
|
||
const invalid =
|
||
badProfile !== undefined
|
||
? `rejected dv profiles: unknown value '${badProfile}'`
|
||
: badPref !== undefined
|
||
? `resolution preference (first wins): unknown value '${badPref}'`
|
||
: null;
|
||
const note: Note | null = invalid !== null ? { text: invalid, tone: "fault" } : saveNote;
|
||
|
||
const save = () => {
|
||
if (invalid !== null) {
|
||
setSaveNote({ text: "fix the highlighted fields first", tone: "fault" });
|
||
return;
|
||
}
|
||
const emptyWeight = [...Object.values(sources), ...Object.values(weights)].some(
|
||
(value) => value === "",
|
||
);
|
||
if (name.trim() === "" || emptyWeight) {
|
||
setSaveNote({ text: "name and every scoring weight are required", tone: "fault" });
|
||
return;
|
||
}
|
||
const sizeBands: PolicyDoc["size_bands"] = {};
|
||
for (const [resolution, band] of Object.entries(bands)) {
|
||
sizeBands[resolution] = {
|
||
floor_gib: Number(band.floor),
|
||
target_gib: Number(band.target),
|
||
penalty_points_per_gib_over: Number(band.penalty),
|
||
...(band.ceiling === "" ? {} : { ceiling_gib: Number(band.ceiling) }),
|
||
};
|
||
}
|
||
setBusy(true);
|
||
setSaveNote({ text: "saving…" });
|
||
const payload: Omit<PolicyDoc, "id"> = {
|
||
name: name.trim(),
|
||
required_audio:
|
||
audioMode === "any_of"
|
||
? { require: "any_of", langs: listValue(audioLangs) }
|
||
: { require: "original_language" },
|
||
dub_blacklist: listValue(blacklist),
|
||
hdr_rules: { dv_profile_reject: listValue(profiles) },
|
||
size_bands: sizeBands,
|
||
resolution_pref: listValue(pref),
|
||
source_weights: Object.fromEntries(
|
||
SOURCES.filter((source) => sources[source] !== "").map((source) => [
|
||
source,
|
||
Number(sources[source]),
|
||
]),
|
||
),
|
||
score_weights: Object.fromEntries(
|
||
WEIGHT_KEYS.map((key) => [key, Number(weights[key])]),
|
||
) as PolicyDoc["score_weights"],
|
||
};
|
||
void savePolicy(policy?.id ?? null, payload).then((outcome) => {
|
||
if (outcome.ok) {
|
||
onSaved();
|
||
return;
|
||
}
|
||
setBusy(false);
|
||
setSaveNote({ text: outcome.detail, tone: "fault" });
|
||
});
|
||
};
|
||
|
||
return (
|
||
<div className="edit-panel add-panel">
|
||
<div className="form-grid">
|
||
<Field label="name">
|
||
<TextInput value={name} onChange={setName} placeholder="policy name" autoFocus />
|
||
</Field>
|
||
<Field label="required audio">
|
||
<Select
|
||
options={["original_language", "any_of"]}
|
||
value={audioMode}
|
||
onChange={setAudioMode}
|
||
/>
|
||
</Field>
|
||
<Field label="required langs">
|
||
<TextInput
|
||
value={audioLangs}
|
||
onChange={setAudioLangs}
|
||
placeholder="pt-PT, …"
|
||
disabled={audioMode === "original_language"}
|
||
/>
|
||
</Field>
|
||
<Field label="dub blacklist">
|
||
<TextInput value={blacklist} onChange={setBlacklist} placeholder="pt-BR" />
|
||
</Field>
|
||
<Field label="rejected dv profiles">
|
||
<TextInput
|
||
value={profiles}
|
||
onChange={setProfiles}
|
||
placeholder={DV_PROFILES.join(", ")}
|
||
invalid={badProfile !== undefined}
|
||
/>
|
||
</Field>
|
||
{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 (
|
||
<div key={resolution} className="band-line" data-resolution={resolution}>
|
||
<span className="field-label readout dim">{resolution}</span>
|
||
<NumberInput
|
||
className="band-num"
|
||
value={band.floor}
|
||
onChange={set("floor")}
|
||
aria-label={`${resolution} floor GiB`}
|
||
/>
|
||
<NumberInput
|
||
className="band-num"
|
||
value={band.target}
|
||
onChange={set("target")}
|
||
aria-label={`${resolution} target GiB`}
|
||
/>
|
||
<NumberInput
|
||
className="band-num"
|
||
value={band.penalty}
|
||
onChange={set("penalty")}
|
||
aria-label={`${resolution} penalty points per GiB over`}
|
||
/>
|
||
<NumberInput
|
||
className="band-num"
|
||
value={band.ceiling}
|
||
onChange={set("ceiling")}
|
||
placeholder="∞"
|
||
aria-label={`${resolution} ceiling GiB, empty for none`}
|
||
/>
|
||
</div>
|
||
);
|
||
})}
|
||
<Field label="resolution preference (first wins)">
|
||
<TextInput
|
||
value={pref}
|
||
onChange={setPref}
|
||
placeholder={RESOLUTIONS.join(", ")}
|
||
invalid={badPref !== undefined}
|
||
/>
|
||
</Field>
|
||
{SOURCES.map((source) => (
|
||
<Field key={source} label={`source · ${source.toLowerCase()}`}>
|
||
<NumberInput
|
||
value={sources[source]}
|
||
onChange={(value) => setSources({ ...sources, [source]: value })}
|
||
aria-label={`${source} source weight`}
|
||
/>
|
||
</Field>
|
||
))}
|
||
{WEIGHT_KEYS.map((key) => (
|
||
<Field key={key} label={key.replaceAll("_", " ")}>
|
||
<NumberInput
|
||
value={weights[key]}
|
||
onChange={(value) => setWeights({ ...weights, [key]: value })}
|
||
aria-label={key.replaceAll("_", " ")}
|
||
/>
|
||
</Field>
|
||
))}
|
||
</div>
|
||
<PanelActions
|
||
save={save}
|
||
saveLabel={policy === null ? "create policy" : "save policy"}
|
||
busy={busy}
|
||
note={note}
|
||
onCancel={onCancel}
|
||
/>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
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<string | null>;
|
||
panel: (close: () => void) => ReactNode;
|
||
onDeleted: () => void;
|
||
}) {
|
||
const [note, say] = useNote();
|
||
const [editing, setEditing] = useState(false);
|
||
return (
|
||
<Row
|
||
kind="setting"
|
||
title={title}
|
||
titleClassName="readout"
|
||
meta={chips.map((text) => <Chip key={text}>{text}</Chip>)}
|
||
actions={[
|
||
{
|
||
node: (
|
||
<IconControl
|
||
glyph="pencil"
|
||
label={`edit ${label}`}
|
||
aria-expanded={editing}
|
||
onClick={() => setEditing(!editing)}
|
||
/>
|
||
),
|
||
width: "icon",
|
||
},
|
||
{
|
||
node: (
|
||
<ArmedDeleteIcon
|
||
label={`delete ${label}`}
|
||
explain={(text) => 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 (
|
||
<IconControl
|
||
glyph={glyph}
|
||
label={label}
|
||
className="provider-move"
|
||
data-move={direction}
|
||
disabled={disabled}
|
||
onClick={onClick}
|
||
/>
|
||
);
|
||
}
|
||
|
||
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<Record<string, string>>(() =>
|
||
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<ProviderFields[]>(() => {
|
||
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<Note | null>(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<ProviderFields>) => {
|
||
setProviders(providers.map((entry, at) => (at === index ? { ...entry, ...change } : entry)));
|
||
};
|
||
|
||
const save = () => {
|
||
const providerBudgets: Record<string, number> = {};
|
||
for (const entry of providers) {
|
||
const value = Number(entry.budget);
|
||
if (value > 0) {
|
||
providerBudgets[entry.provider] = value;
|
||
}
|
||
}
|
||
const translatorBudgets: Record<string, number> = {};
|
||
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 (
|
||
<div className="add-panel subtitle-panel">
|
||
<div className="form-grid">
|
||
<Field label="wanted languages">
|
||
<TextInput value={wanted} onChange={setWanted} placeholder="pt-PT, en" />
|
||
</Field>
|
||
<Field label="translation engine">
|
||
<Select
|
||
options={["none", ...settings.available_engines]}
|
||
value={engine}
|
||
onChange={setEngine}
|
||
disabled={!hasEngines}
|
||
/>
|
||
</Field>
|
||
<Field label="remote command timeout (s)">
|
||
<NumberInput value={timeout} onChange={setTimeoutValue} />
|
||
</Field>
|
||
</div>
|
||
{!hasEngines && (
|
||
<p className="add-note readout dim">
|
||
no translation engine is compiled into this binary — pick is unavailable
|
||
</p>
|
||
)}
|
||
{/* Their own labelled row rather than two more cells in the grid above:
|
||
paired, they belong to one engine, and a base URL needs the width. */}
|
||
{hasOpenAi && (
|
||
<>
|
||
<p className="field-label readout dim">
|
||
openai-compatible endpoint — blank means its default
|
||
</p>
|
||
<div className="form-grid">
|
||
<Field label="base url">
|
||
<TextInput
|
||
value={baseUrl}
|
||
onChange={setBaseUrl}
|
||
placeholder="optional — e.g. http://127.0.0.1:8080/v1"
|
||
aria-label="openai base url"
|
||
/>
|
||
</Field>
|
||
<Field label="model">
|
||
<TextInput
|
||
value={model}
|
||
onChange={setModel}
|
||
placeholder="optional — e.g. gpt-4o-mini"
|
||
aria-label="openai model"
|
||
/>
|
||
</Field>
|
||
</div>
|
||
</>
|
||
)}
|
||
{hasEngines && (
|
||
<>
|
||
<p className="field-label readout dim">translator daily budgets</p>
|
||
<div className="form-grid">
|
||
{settings.available_engines.map((name) => (
|
||
<Field key={name} label={name}>
|
||
<NumberInput
|
||
value={translators[name] ?? ""}
|
||
onChange={(value) => setTranslators({ ...translators, [name]: value })}
|
||
aria-label={`${name} daily budget`}
|
||
/>
|
||
</Field>
|
||
))}
|
||
</div>
|
||
</>
|
||
)}
|
||
<p className="field-label readout dim">providers — enabled, and in priority order</p>
|
||
<ul className="provider-list">
|
||
{providers.map((entry, index) => (
|
||
<Row
|
||
key={entry.provider}
|
||
kind="provider"
|
||
lead={
|
||
<label className="provider-check">
|
||
<input
|
||
type="checkbox"
|
||
className="provider-toggle"
|
||
checked={entry.enabled}
|
||
aria-label={`enable ${entry.provider}`}
|
||
onChange={(event) => updateProvider(index, { enabled: event.target.checked })}
|
||
/>
|
||
</label>
|
||
}
|
||
title={entry.provider}
|
||
actions={[
|
||
{
|
||
node: (
|
||
<NumberInput
|
||
className="provider-budget"
|
||
value={entry.budget}
|
||
onChange={(value) => updateProvider(index, { budget: value })}
|
||
aria-label={`${entry.provider} daily budget`}
|
||
/>
|
||
),
|
||
width: "word",
|
||
},
|
||
{
|
||
node: (
|
||
<MoveButton
|
||
direction="up"
|
||
label={`move ${entry.provider} up`}
|
||
disabled={index === 0}
|
||
onClick={() => move(index, -1)}
|
||
/>
|
||
),
|
||
width: "icon",
|
||
},
|
||
{
|
||
node: (
|
||
<MoveButton
|
||
direction="down"
|
||
label={`move ${entry.provider} down`}
|
||
disabled={index === providers.length - 1}
|
||
onClick={() => move(index, 1)}
|
||
/>
|
||
),
|
||
width: "icon",
|
||
},
|
||
]}
|
||
/>
|
||
))}
|
||
</ul>
|
||
<PanelActions save={save} saveLabel="save subtitles" busy={busy} note={note} />
|
||
</div>
|
||
);
|
||
}
|
||
|
||
/* ---- 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<Loaded | null>(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 (
|
||
<main className="deck" aria-label="settings" hidden={hidden}>
|
||
<header className="page-bar">
|
||
<h2 className="page-title">settings</h2>
|
||
<span className="deck-count readout">
|
||
{loaded === null
|
||
? ""
|
||
: `${loaded.roots.length} roots · ${loaded.policies.length} policies`}
|
||
</span>
|
||
<StatusSlot status={status} className="head-status readout" />
|
||
</header>
|
||
|
||
<section className="deck-group" aria-labelledby="label-chain">
|
||
<DeckHead label="signal chain" labelId="label-chain" labelClass="section-title" />
|
||
<Chain />
|
||
</section>
|
||
|
||
<section className="deck-group" hidden={loaded === null} aria-labelledby="label-roots">
|
||
<DeckHead label="roots" labelId="label-roots" labelClass="section-title">
|
||
<button
|
||
type="button"
|
||
className="control control-quiet head-action"
|
||
onClick={() => setAddingRoot(true)}
|
||
>
|
||
add root
|
||
</button>
|
||
</DeckHead>
|
||
<ul className="deck-rows" key={loaded?.paint}>
|
||
{loaded?.roots.map((root) => (
|
||
<SettingsRow
|
||
key={root.id}
|
||
title={root.path}
|
||
chips={[root.kind, root.audience, root.policy_name]}
|
||
label={`root ${root.path}`}
|
||
remove={() => deleteRow("roots", root.id)}
|
||
onDeleted={reload}
|
||
panel={(close) => (
|
||
<RootPanel
|
||
root={root}
|
||
policies={loaded.policies}
|
||
onSaved={reload}
|
||
onCancel={close}
|
||
/>
|
||
)}
|
||
/>
|
||
))}
|
||
</ul>
|
||
{addingRoot && loaded !== null && (
|
||
<RootPanel
|
||
root={null}
|
||
policies={loaded.policies}
|
||
onSaved={() => {
|
||
setAddingRoot(false);
|
||
reload();
|
||
}}
|
||
onCancel={() => setAddingRoot(false)}
|
||
/>
|
||
)}
|
||
</section>
|
||
|
||
<section className="deck-group" hidden={loaded === null} aria-labelledby="label-policies">
|
||
<DeckHead label="policies" labelId="label-policies" labelClass="section-title">
|
||
<button
|
||
type="button"
|
||
className="control control-quiet head-action"
|
||
onClick={() => setAddingPolicy(true)}
|
||
>
|
||
add policy
|
||
</button>
|
||
</DeckHead>
|
||
<div className="group-note">
|
||
<p>Editing a policy rescores every title's releases straight away.</p>
|
||
</div>
|
||
<ul className="deck-rows" key={loaded?.paint}>
|
||
{loaded?.policies.map((policy) => {
|
||
const bandCount = Object.keys(policy.size_bands).length;
|
||
return (
|
||
<SettingsRow
|
||
key={policy.id}
|
||
title={policy.name}
|
||
chips={[
|
||
policy.resolution_pref.join(" › ") || "no resolutions",
|
||
requiredAudioLabel(policy),
|
||
`${bandCount} band${bandCount === 1 ? "" : "s"}`,
|
||
]}
|
||
label={`policy ${policy.name}`}
|
||
remove={() => deleteRow("policies", policy.id)}
|
||
onDeleted={reload}
|
||
panel={(close) => <PolicyPanel policy={policy} onSaved={reload} onCancel={close} />}
|
||
/>
|
||
);
|
||
})}
|
||
</ul>
|
||
{addingPolicy && (
|
||
<PolicyPanel
|
||
policy={null}
|
||
onSaved={() => {
|
||
setAddingPolicy(false);
|
||
reload();
|
||
}}
|
||
onCancel={() => setAddingPolicy(false)}
|
||
/>
|
||
)}
|
||
</section>
|
||
|
||
<section
|
||
className="deck-group"
|
||
hidden={loaded === null}
|
||
aria-labelledby="label-settings-subtitles"
|
||
>
|
||
<DeckHead label="subtitles" labelId="label-settings-subtitles" labelClass="section-title" />
|
||
<GroupNote
|
||
short="Provider logins and translator keys are not shown here."
|
||
more="They live in the daemon's config and environment (§10), along with the remote-command template."
|
||
/>
|
||
<div>
|
||
{loaded !== null && (
|
||
<SubtitlesPanel key={loaded.paint} settings={loaded.subtitles} onSaved={reload} />
|
||
)}
|
||
</div>
|
||
</section>
|
||
</main>
|
||
);
|
||
}
|