Closes the burn-down. Hook suppressions 113 -> 34, `exhaustive-deps` 45 -> 2 (the target was <10), and every one of the 34 survivors is an inline directive NAMING the invariant it protects. The suppressions file is deleted, because a bulk file hides the next violation instead of answering it — and it cannot hold a warning-level rule at all. The sprint plan's three verdicts missed the answer that turned out to be the most common one: adjust the state DURING RENDER. React re-runs the component and discards that pass rather than committing it, so the stale frame an effect-based reset paints does not exist. Applied to the Plex player's up-next card, the playlist view reset, the feed's optimistic overrides, the channel banner's retry count, the download center's tab guard, the Plex search highlight, the comfort-pin latch, Welcome's per-view outcome and the card pager's page clamp. It is legal only for a component's own state — PlexBrowse's language commit resets PlexProvider's filters, so that one stays an effect and says why. Mirrors of a prop or query became derived values or `draft ?? server`: - `downloadRow` had ui/Avatar's defect exactly — a boolean "poster failed" that an effect reset, in rows recycled down a virtualized list, so one job's missing poster painted over the next one's for a frame. Keyed by URL now. - Scheduler's two number editors held a mirror an effect re-synced, on a page that POLLS — the shape a poll can overwrite mid-edit. A draft while editing, the server's value otherwise; six tests where there were none, the one behavioural change (the save button stops being dirty at commit rather than at the echo) mutation-checked. - SetupWizard's "no token" and WatchPage's "gone" are facts about the URL, so they are seeded and derived rather than pushed into state by an effect that had to commit first. Elsewhere: PlexInfo's rating chip was a component declared during render — a new component type every render, so React remounted the subtree and dropped the focus on its filter button. Hoisted. Feed's undo action and PlexPlayer's session reclaim both re-entered their own useCallback, which the checker reads as a forward reference; both go through the ref idiom this file already uses. BootGate's dep list was load-bearing for correctness — a re-run meant `location.reload()` — so the "already adopted THIS identity" comparison now enforces it in code, with a test that fails without it (the existing reload tests all install their spy too late to catch it). One correction to the batch before this: keying ChatThread's and Messages' decrypt passes on `q.data` instead of `q.dataUpdatedAt` was wrong. react-query's structural sharing makes it safe in production, but the component must not melt down when something hands back a fresh object per render — and Messages.keyboard.dom.test does exactly that, so the effect span the suite. Both are back on the fetch as the trigger with the payload behind a ref, which is honest AND loop-proof; the replaced comment had warned about precisely this. CLAUDE.md gains four canonical-patterns rows for the above, and its "React 18" line is now true.
344 lines
12 KiB
TypeScript
344 lines
12 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import { Check, ChevronLeft, ChevronRight, Loader2, Send } from "lucide-react";
|
|
import { api, HttpError } from "../lib/api";
|
|
import { setLanguage, type LangCode } from "../i18n";
|
|
import LanguageSwitcher from "./LanguageSwitcher";
|
|
import { Button } from "./ui/Button";
|
|
import { inputCls } from "./ui/form";
|
|
import { FocusSafeButton } from "./ui/FocusSafeButton";
|
|
|
|
// First-run install wizard. Shown by App.tsx while the instance is unconfigured. The one-time
|
|
// setup token comes from the URL the app printed to the container logs (?token=…); every step
|
|
// posts it back as the X-Setup-Token header. On finish the instance flips to configured, the
|
|
// wizard disappears, and the operator signs in with the admin account they just created.
|
|
type StepId = "intro" | "admin" | "google" | "smtp" | "finish";
|
|
|
|
const PASSWORD_MIN = 10;
|
|
|
|
export default function SetupWizard() {
|
|
const { t, i18n } = useTranslation();
|
|
const [token] = useState(() => new URLSearchParams(window.location.search).get("token") ?? "");
|
|
const [info, setInfo] = useState<{ secrets_manageable: boolean } | null>(null);
|
|
// "No token at all" is not a fetch outcome, it is a fact about the URL — so it is derived rather
|
|
// than pushed into state by an effect, which had to run and commit before the error could show.
|
|
const [infoFailed, setInfoFailed] = useState(false);
|
|
const tokenError = !token || infoFailed;
|
|
|
|
useEffect(() => {
|
|
if (!token) return;
|
|
api
|
|
.setupInfo(token)
|
|
.then(setInfo)
|
|
.catch(() => setInfoFailed(true));
|
|
}, [token]);
|
|
|
|
// Step state.
|
|
const [stepIdx, setStepIdx] = useState(0);
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState("");
|
|
// Keys the error: failing the same way twice is a new node, so a screen reader announces it again (a clear
|
|
// and a set in one handler commit together, leaving the node untouched).
|
|
const [attempt, setAttempt] = useState(0);
|
|
// Admin account.
|
|
const [email, setEmail] = useState("");
|
|
const [password, setPassword] = useState("");
|
|
// Google OAuth (optional).
|
|
const [gid, setGid] = useState("");
|
|
const [gsecret, setGsecret] = useState("");
|
|
// SMTP (optional).
|
|
const [smtp, setSmtp] = useState({ host: "", port: "587", user: "", from: "", password: "" });
|
|
const [testTo, setTestTo] = useState("");
|
|
const [testState, setTestState] = useState<"idle" | "sending" | "ok" | "fail">("idle");
|
|
|
|
if (tokenError)
|
|
return (
|
|
<Centered>
|
|
<TokenError />
|
|
</Centered>
|
|
);
|
|
if (!info)
|
|
return (
|
|
<Centered>
|
|
<Loader2 className="w-6 h-6 animate-spin text-muted" />
|
|
</Centered>
|
|
);
|
|
|
|
// Steps adapt to the instance: Google + SMTP need encrypted secret storage (TOKEN_ENCRYPTION_KEY).
|
|
const steps: StepId[] = [
|
|
"intro",
|
|
"admin",
|
|
...(info.secrets_manageable ? (["google", "smtp"] as StepId[]) : []),
|
|
"finish",
|
|
];
|
|
const step = steps[stepIdx];
|
|
const go = (delta: number) => {
|
|
setError("");
|
|
setStepIdx((i) => Math.min(steps.length - 1, Math.max(0, i + delta)));
|
|
};
|
|
|
|
// Each step's "Next" action persists what it collected, then advances. Optional steps with empty
|
|
// fields just advance (skip). Errors surface inline (the setup calls use the quiet flag); a step's own
|
|
// validation sets its message and stays.
|
|
async function next() {
|
|
setAttempt((n) => n + 1);
|
|
setError("");
|
|
setBusy(true);
|
|
try {
|
|
if (step === "admin") {
|
|
if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email))
|
|
return setError(t("setup.admin.invalidEmail"));
|
|
if (password.length < PASSWORD_MIN)
|
|
return setError(t("setup.admin.shortPassword", { n: PASSWORD_MIN }));
|
|
await api.setupAdmin(token, email, password);
|
|
} else if (step === "google" && (gid.trim() || gsecret.trim())) {
|
|
if (!gid.trim() || !gsecret.trim()) return setError(t("setup.google.bothRequired"));
|
|
await api.setupConfig(token, {
|
|
google_client_id: gid.trim(),
|
|
google_client_secret: gsecret.trim(),
|
|
});
|
|
} else if (step === "smtp" && smtp.host.trim()) {
|
|
await api.setupConfig(token, {
|
|
smtp_host: smtp.host.trim(),
|
|
smtp_port: Number(smtp.port) || 587,
|
|
smtp_user: smtp.user.trim(),
|
|
smtp_from: smtp.from.trim(),
|
|
smtp_password: smtp.password,
|
|
});
|
|
} else if (step === "finish") {
|
|
await api.setupFinish(token);
|
|
window.location.href = "/"; // configured now → reloads into the login page
|
|
return;
|
|
}
|
|
go(1);
|
|
} catch (e) {
|
|
setError((e instanceof HttpError ? e.detail : undefined) ?? t("setup.genericError"));
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
async function sendTest() {
|
|
setTestState("sending");
|
|
try {
|
|
// Persist the SMTP fields first so the test uses them, then send.
|
|
if (smtp.host.trim())
|
|
await api.setupConfig(token, {
|
|
smtp_host: smtp.host.trim(),
|
|
smtp_port: Number(smtp.port) || 587,
|
|
smtp_user: smtp.user.trim(),
|
|
smtp_from: smtp.from.trim(),
|
|
smtp_password: smtp.password,
|
|
});
|
|
await api.setupTestEmail(token, testTo.trim());
|
|
setTestState("ok");
|
|
} catch {
|
|
setTestState("fail");
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Centered>
|
|
<div className="w-full max-w-lg">
|
|
<div className="flex items-center justify-between mb-4">
|
|
<div className="text-xl font-bold tracking-tight">
|
|
Sift<span className="text-accent">lode</span>
|
|
</div>
|
|
<LanguageSwitcher value={i18n.language as LangCode} onChange={setLanguage} />
|
|
</div>
|
|
|
|
{/* Step progress dots */}
|
|
<div className="flex items-center gap-1.5 mb-4">
|
|
{steps.map((s, i) => (
|
|
<div
|
|
key={s}
|
|
className={`h-1.5 flex-1 rounded-full transition ${
|
|
i <= stepIdx ? "bg-accent" : "bg-border"
|
|
}`}
|
|
/>
|
|
))}
|
|
</div>
|
|
|
|
<div className="glass rounded-2xl p-6">
|
|
{step === "intro" && (
|
|
<Section title={t("setup.intro.title")} desc={t("setup.intro.body")} />
|
|
)}
|
|
|
|
{step === "admin" && (
|
|
<Section title={t("setup.admin.title")} desc={t("setup.admin.desc")}>
|
|
<input
|
|
type="email"
|
|
value={email}
|
|
onChange={(e) => setEmail(e.target.value)}
|
|
placeholder={t("setup.admin.email")}
|
|
autoComplete="username"
|
|
className={inputCls}
|
|
/>
|
|
<input
|
|
type="password"
|
|
value={password}
|
|
onChange={(e) => setPassword(e.target.value)}
|
|
placeholder={t("setup.admin.password", { n: PASSWORD_MIN })}
|
|
autoComplete="new-password"
|
|
className={inputCls}
|
|
/>
|
|
</Section>
|
|
)}
|
|
|
|
{step === "google" && (
|
|
<Section title={t("setup.google.title")} desc={t("setup.google.desc")}>
|
|
<input
|
|
value={gid}
|
|
onChange={(e) => setGid(e.target.value)}
|
|
placeholder={t("setup.google.clientId")}
|
|
className={inputCls}
|
|
/>
|
|
<input
|
|
value={gsecret}
|
|
onChange={(e) => setGsecret(e.target.value)}
|
|
placeholder={t("setup.google.clientSecret")}
|
|
className={inputCls}
|
|
/>
|
|
<p className="text-xs text-muted">{t("setup.google.skipHint")}</p>
|
|
</Section>
|
|
)}
|
|
|
|
{step === "smtp" && (
|
|
<Section title={t("setup.smtp.title")} desc={t("setup.smtp.desc")}>
|
|
<input
|
|
value={smtp.host}
|
|
onChange={(e) => setSmtp({ ...smtp, host: e.target.value })}
|
|
placeholder={t("setup.smtp.host")}
|
|
className={inputCls}
|
|
/>
|
|
<div className="flex gap-2">
|
|
<input
|
|
value={smtp.port}
|
|
onChange={(e) => setSmtp({ ...smtp, port: e.target.value })}
|
|
placeholder={t("setup.smtp.port")}
|
|
className={`${inputCls} w-24`}
|
|
/>
|
|
<input
|
|
value={smtp.user}
|
|
onChange={(e) => setSmtp({ ...smtp, user: e.target.value })}
|
|
placeholder={t("setup.smtp.user")}
|
|
className={inputCls}
|
|
/>
|
|
</div>
|
|
<input
|
|
value={smtp.from}
|
|
onChange={(e) => setSmtp({ ...smtp, from: e.target.value })}
|
|
placeholder={t("setup.smtp.from")}
|
|
className={inputCls}
|
|
/>
|
|
<input
|
|
type="password"
|
|
value={smtp.password}
|
|
onChange={(e) => setSmtp({ ...smtp, password: e.target.value })}
|
|
placeholder={t("setup.smtp.password")}
|
|
className={inputCls}
|
|
/>
|
|
{smtp.host.trim() && (
|
|
<div className="flex items-center gap-2 pt-1">
|
|
<input
|
|
value={testTo}
|
|
onChange={(e) => setTestTo(e.target.value)}
|
|
placeholder={t("setup.smtp.testTo")}
|
|
className={inputCls}
|
|
/>
|
|
<Button
|
|
variant="glass"
|
|
size="md"
|
|
className="shrink-0"
|
|
type="button"
|
|
onClick={sendTest}
|
|
disabled={testState === "sending" || !testTo.trim()}
|
|
>
|
|
<Send className={`w-4 h-4 ${testState === "sending" ? "animate-pulse" : ""}`} />
|
|
{t("setup.smtp.test")}
|
|
</Button>
|
|
</div>
|
|
)}
|
|
{testState === "ok" && (
|
|
<p className="text-xs text-success">{t("setup.smtp.testOk")}</p>
|
|
)}
|
|
{testState === "fail" && (
|
|
<p className="text-xs text-danger">{t("setup.smtp.testFail")}</p>
|
|
)}
|
|
<p className="text-xs text-muted">{t("setup.smtp.skipHint")}</p>
|
|
</Section>
|
|
)}
|
|
|
|
{step === "finish" && (
|
|
<Section title={t("setup.finish.title")} desc={t("setup.finish.body")} />
|
|
)}
|
|
|
|
{error && (
|
|
<p key={attempt} role="alert" className="text-sm text-danger mt-3">
|
|
{error}
|
|
</p>
|
|
)}
|
|
|
|
<div className="flex items-center justify-between mt-6">
|
|
<FocusSafeButton
|
|
onClick={() => go(-1)}
|
|
disabled={stepIdx === 0 || busy}
|
|
className="glass-card glass-hover inline-flex items-center gap-1 px-3 py-2 rounded-xl text-sm disabled:opacity-40 transition"
|
|
>
|
|
<ChevronLeft className="w-4 h-4" />
|
|
{t("setup.nav.back")}
|
|
</FocusSafeButton>
|
|
<FocusSafeButton
|
|
onClick={next}
|
|
disabled={busy}
|
|
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl text-sm btn-primary font-medium shadow-md shadow-accent/20 disabled:opacity-50 transition"
|
|
>
|
|
{busy ? (
|
|
<Loader2 className="w-4 h-4 animate-spin" />
|
|
) : step === "finish" ? (
|
|
<Check className="w-4 h-4" />
|
|
) : null}
|
|
{step === "finish" ? t("setup.nav.finish") : t("setup.nav.next")}
|
|
{step !== "finish" && !busy && <ChevronRight className="w-4 h-4" />}
|
|
</FocusSafeButton>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
</Centered>
|
|
);
|
|
}
|
|
|
|
function Centered({ children }: { children: React.ReactNode }) {
|
|
return <div className="min-h-screen bg-bg text-fg grid place-items-center p-4">{children}</div>;
|
|
}
|
|
|
|
function Section({
|
|
title,
|
|
desc,
|
|
children,
|
|
}: {
|
|
title: string;
|
|
desc: string;
|
|
children?: React.ReactNode;
|
|
}) {
|
|
return (
|
|
<div className="space-y-3">
|
|
<div>
|
|
<h2 className="text-lg font-semibold">{title}</h2>
|
|
<p className="text-sm text-muted leading-relaxed mt-1">{desc}</p>
|
|
</div>
|
|
{children}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
function TokenError() {
|
|
const { t } = useTranslation();
|
|
return (
|
|
<div className="max-w-md glass rounded-2xl p-6 text-center">
|
|
<h2 className="text-lg font-semibold">{t("setup.token.title")}</h2>
|
|
<p className="text-sm text-muted leading-relaxed mt-2">{t("setup.token.body")}</p>
|
|
</div>
|
|
);
|
|
}
|