import { useCallback, useEffect, useMemo, useState } from "react"; import { AlertTriangle, ChevronDown, ChevronRight, RotateCcw } from "lucide-react"; import { api, asUiError, type FieldError, type JsonValue, type PresetInfo, type PresetPreview, type SaveReport, type Scope, type SettingsView, type SettingView, type UiError, } from "@/lib/api"; import { cn } from "@/lib/utils"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { CompanionsCard } from "@/screens/CompanionsCard"; import { useHuman, useI18n, useT, type Key } from "@/i18n"; type T = (k: Key, v?: Record) => string; const RESTART_LABEL = { runtime: "set.restart.runtime", world: "set.restart.world", full: "set.restart.full" } as const; function fmt(t: T, v: JsonValue, s: { type: string; unit?: string | null; options: { value: JsonValue; label: string }[] }): string { if (typeof v === "boolean") return v ? t("set.on") : t("set.off"); if (s.type === "enum") return s.options.find((o) => o.value === v)?.label ?? String(v); return s.unit ? `${v} ${s.unit}` : String(v); } function clientCheck(t: T, s: SettingView, v: JsonValue): string | null { if (s.type === "int" || s.type === "float") { if (typeof v !== "number" || Number.isNaN(v)) return t("set.enterNumber"); if (s.type === "int" && !Number.isInteger(v)) return t("set.enterInt"); if (s.min !== undefined && v < s.min) return t("set.atLeast", { n: s.min }); if (s.max !== undefined && v > s.max) return t("set.atMost", { n: s.max }); } return null; } function Field(props: { s: SettingView; value: JsonValue; error: string | null; onChange: (v: JsonValue) => void }) { const { s, value, error, onChange } = props; const t = useT(); const id = `f-${s.key}`; const base = "rounded-md border bg-bg px-3 py-2 text-sm outline-none focus:border-gold"; if (s.type === "bool") { return ( ); } if (s.type === "enum") { return ( ); } const numeric = s.type === "int" || s.type === "float"; return (
{ const raw = e.target.value; onChange(numeric ? (raw.trim() === "" || Number.isNaN(Number(raw)) ? (raw as unknown as number) : Number(raw)) : raw); }} /> {s.unit && {s.unit}}
); } function Row(props: { s: SettingView; value: JsonValue; error: string | null; onChange: (v: JsonValue) => void; onReset: () => void }) { const { s, value, error } = props; const t = useT(); const changed = value !== s.value; return (

{s.description}

{t("set.default", { v: fmt(t, s.default, s) })} {s.min !== undefined && s.max !== undefined && s.type !== "bool" ? ` · ${t("set.range", { min: s.min, max: s.max })}` : ""} · {t(RESTART_LABEL[s.restartRequired])}

{s.problem &&

{t("set.badValue", { problem: s.problem })}

} {s.drift &&

{t("set.drift")}

} {error && (

{error}

)}
); } export function SettingsPage(props: { serverId: string; scope: Scope; title: string; question: string }) { const { serverId, scope } = props; const { t, tn } = useI18n(); const human = useHuman(); const [view, setView] = useState(null); const [draft, setDraft] = useState>({}); const [errors, setErrors] = useState>({}); const [fatal, setFatal] = useState(null); const [saveErr, setSaveErr] = useState(null); const [saved, setSaved] = useState(null); const [presets, setPresets] = useState([]); const [preview, setPreview] = useState(null); const [category, setCategory] = useState(""); const [showAdvanced, setShowAdvanced] = useState(false); const [busy, setBusy] = useState(false); const [running, setRunning] = useState(false); const load = useCallback(async () => { try { const v = await api.settings(serverId, scope); setView(v); setDraft({}); setErrors({}); setCategory((c) => c || v.categories.find((x) => v.settings.some((s) => s.category === x.id && !s.advanced))?.id || v.categories[0].id); setFatal(null); } catch (e) { setFatal(asUiError(e)); } }, [serverId, scope]); useEffect(() => { setView(null); setSaved(null); void load(); void api.presets(scope).then(setPresets); void api.status(serverId).then((s) => setRunning(s.observed.world.state === "running")); }, [load, scope, serverId]); const valueOf = (s: SettingView): JsonValue => (s.key in draft ? draft[s.key] : s.value); const dirtyKeys = useMemo(() => Object.keys(draft).filter((k) => view && draft[k] !== view.settings.find((s) => s.key === k)?.value), [draft, view]); if (fatal) { return (

{props.title}

{fatal.human.code === "unknown" ? t("set.nothingYet") : human(fatal.human).title}

{fatal.human.code === "unknown" ? fatal.technical : human(fatal.human).message}

); } if (!view) return

{t("set.loading")}

; const inCategory = view.settings.filter((s) => s.category === category); const basic = inCategory.filter((s) => !s.advanced); const advanced = inCategory.filter((s) => s.advanced); const advancedCount = (id: string) => view.settings.filter((s) => s.category === id && s.advanced).length; const basicCount = (id: string) => view.settings.filter((s) => s.category === id && !s.advanced).length; async function save(changes: Record) { const local: Record = {}; for (const [k, v] of Object.entries(changes)) { const s = view!.settings.find((x) => x.key === k)!; const m = clientCheck(t, s, v); if (m) local[k] = m; } setErrors(local); if (Object.keys(local).length) return; const dangerous = Object.keys(changes).filter((k) => view!.settings.find((s) => s.key === k)?.dangerous); if (dangerous.length && !window.confirm(t("set.confirmCareful", { n: dangerous.length }))) return; setBusy(true); setSaveErr(null); try { const report = await api.save(serverId, scope, changes); setSaved(report); setPreview(null); await load(); void api.status(serverId).then((s) => setRunning(s.observed.world.state === "running")); } catch (e) { const ui = asUiError(e); setSaveErr(ui); const map: Record = {}; (ui.fields ?? ([] as FieldError[])).forEach((f) => (map[f.key] = f.message)); setErrors(map); } finally { setBusy(false); } } async function openPreset(id: string) { setSaved(null); setPreview(await api.previewPreset(serverId, scope, id)); } async function restartNow() { setBusy(true); try { await api.stop(serverId); await api.start(serverId); setSaved(null); setRunning(true); } finally { setBusy(false); } } return (

{props.title}

{props.question}

{scope === "bots" && } {view.drift_keys.length > 0 && (

{t("set.driftTitle", { n: view.drift_keys.length })}

{t("set.driftText")}{" "} {view.drift_keys.slice(0, 6).join(", ")} {view.drift_keys.length > 6 ? "…" : ""}

)}
{t("set.presets")} {presets.map((p) => ( ))}
{preview && (

{preview.title}

{preview.description}

{preview.changes.length === 0 ? (

{t("set.matches")}

) : ( <>

{tn("set.willChange", preview.changes.length)}

    {preview.changes.map((c) => { const s = view.settings.find((x) => x.key === c.key)!; return (
  • {c.title} {fmt(t, c.from, s)} → {fmt(t, c.to, s)}
  • ); })}
)}
{preview.changes.length > 0 && ( )}
)} {saved && ( {saved.changed.length === 0 ? (

{t("set.nothingChanged")}

) : ( <>

{t("set.saved")}

{running && saved.restart ? tn("set.restartRequired", saved.changed.length) : t("set.appliesNextStart")}

{running && saved.restart && (
)} )}
)} {saveErr && (

{human(saveErr.human).title}

{t("set.notSaved")}

)}
{view.categories .filter((c) => basicCount(c.id) + advancedCount(c.id) > 0) .map((c) => ( ))}
{basic.map((s) => ( setDraft((d) => ({ ...d, [s.key]: v }))} onReset={() => setDraft((d) => ({ ...d, [s.key]: s.default }))} /> ))}
{advanced.length > 0 && (
{showAdvanced && (
{advanced.map((s) => ( setDraft((d) => ({ ...d, [s.key]: v }))} onReset={() => setDraft((d) => ({ ...d, [s.key]: s.default }))} /> ))}
)}
)} {view.unknown_keys > 0 && (

{t("set.unknownKept", { n: view.unknown_keys })}

)} {dirtyKeys.length > 0 && (
{tn("set.unsaved", dirtyKeys.length)}
)}
); }