Merge branch 'feat/v144-settings' into release/v1.44.0

# Conflicts:
#	src/components/settings/privacy-section.tsx
This commit is contained in:
Marc-André Bombeck committed 2026-10-21 20:51:39 +02:00
commit e1b70537cc
129 files changed
+5138 -3169

No files matched your search

@@ -218,7 +218,7 @@ describe("<AiSection> — dropdown-driven UX (B2)", () => {
// both ship without the "KI"/"AI" prefix per the project-voice rule
// ("Aktiver KI-Provider" → "Aktiver Provider"). The picker below it is
// labelled for what it does: it chooses the form, not the order.
expect(html).toContain("Aktiver Provider");
expect(html).toContain("Aktiver Anbieter");
expect(html).toContain("Anbieter einrichten");
});
@@ -243,6 +243,6 @@ describe("<AiSection> — dropdown-driven UX (B2)", () => {
it("no longer mounts the Coach cards (moved to the Coach section)", () => {
activeProviderQuery = "codex";
const html = render();
expect(html).not.toContain('data-testid="settings-disable-coach-card"');
expect(html).not.toContain('data-slot="settings-coach-state-card"');
});
});
@@ -35,6 +35,9 @@ vi.mock("@/components/records/ai-profile-inclusion-manager", () => ({
vi.mock("@/components/records/conditions-manager", () => ({
ConditionsManager: () => null,
}));
vi.mock("@/components/records/screening-hints-card", () => ({
ScreeningHintsCard: () => null,
}));
vi.mock("@/components/records/life-circumstances-manager", () => ({
LifeCircumstancesManager: () => null,
}));
@@ -18,6 +18,9 @@ vi.mock("@/components/records/ai-profile-inclusion-manager", () => ({
vi.mock("@/components/records/conditions-manager", () => ({
ConditionsManager: () => <div data-slot="conditions" />,
}));
vi.mock("@/components/records/screening-hints-card", () => ({
ScreeningHintsCard: () => null,
}));
vi.mock("@/components/records/life-circumstances-manager", () => ({
LifeCircumstancesManager: () => null,
}));
@@ -21,6 +21,7 @@ describe("channel form dirty state", () => {
headerName: "X-Gotify-Key",
headerValue: "",
format: "gotify" as const,
enabled: false,
};
it("webhook: a form that matches the saved config is clean", () => {
@@ -56,7 +57,12 @@ describe("channel form dirty state", () => {
it("ntfy: server, topic and a typed auth token count", () => {
const saved = { serverUrl: "https://ntfy.sh", topic: "t" };
const form = { serverUrl: "https://ntfy.sh", topic: "t", authToken: "" };
const form = {
serverUrl: "https://ntfy.sh",
topic: "t",
authToken: "",
enabled: false,
};
expect(isNtfyFormDirty(form, saved)).toBe(false);
expect(isNtfyFormDirty({ ...form, topic: "u" }, saved)).toBe(true);
expect(isNtfyFormDirty({ ...form, serverUrl: "https://x" }, saved)).toBe(
@@ -67,39 +73,86 @@ describe("channel form dirty state", () => {
it("email: the recipient counts", () => {
expect(
isEmailFormDirty({ recipient: "a@x.io" }, { recipient: "a@x.io" }),
isEmailFormDirty(
{ recipient: "a@x.io", enabled: false },
{ recipient: "a@x.io" },
),
).toBe(false);
expect(
isEmailFormDirty({ recipient: "b@x.io" }, { recipient: "a@x.io" }),
isEmailFormDirty(
{ recipient: "b@x.io", enabled: false },
{ recipient: "a@x.io" },
),
).toBe(true);
});
it("telegram: a typed bot token or a changed chat id counts; whitespace alone does not", () => {
expect(
isTelegramFormDirty({ botToken: "", chatId: "1" }, { chatId: "1" }),
).toBe(false);
expect(
isTelegramFormDirty({ botToken: " ", chatId: "" }, { chatId: null }),
isTelegramFormDirty(
{ botToken: "", chatId: "1", enabled: false },
{ chatId: "1" },
),
).toBe(false);
expect(
isTelegramFormDirty(
{ botToken: "123:abc", chatId: "1" },
{ botToken: " ", chatId: "", enabled: false },
{ chatId: null },
),
).toBe(false);
expect(
isTelegramFormDirty(
{ botToken: "123:abc", chatId: "1", enabled: false },
{ chatId: "1" },
),
).toBe(true);
expect(
isTelegramFormDirty({ botToken: "", chatId: "2" }, { chatId: "1" }),
isTelegramFormDirty(
{ botToken: "", chatId: "2", enabled: false },
{ chatId: "1" },
),
).toBe(true);
});
it("a flipped enable switch is a change on every channel, since it saves with the form", () => {
expect(
isWebhookFormDirty({ ...webhookForm, enabled: true }, webhookSaved),
).toBe(true);
expect(
isNtfyFormDirty(
{ serverUrl: "s", topic: "t", authToken: "", enabled: true },
{ serverUrl: "s", topic: "t", enabled: false },
),
).toBe(true);
expect(
isEmailFormDirty(
{ recipient: "a@x.io", enabled: false },
{ recipient: "a@x.io", enabled: true },
),
).toBe(true);
expect(
isTelegramFormDirty(
{ botToken: "", chatId: "1", enabled: true },
{ chatId: "1", enabled: true },
),
).toBe(false);
});
it("nothing loaded yet is never a change", () => {
expect(isWebhookFormDirty(webhookForm, undefined)).toBe(false);
expect(
isNtfyFormDirty({ serverUrl: "", topic: "", authToken: "x" }, undefined),
isNtfyFormDirty(
{ serverUrl: "", topic: "", authToken: "x", enabled: true },
undefined,
),
).toBe(false);
expect(isEmailFormDirty({ recipient: "x" }, undefined)).toBe(false);
expect(isTelegramFormDirty({ botToken: "x", chatId: "" }, undefined)).toBe(
expect(isEmailFormDirty({ recipient: "x", enabled: true }, undefined)).toBe(
false,
);
expect(
isTelegramFormDirty(
{ botToken: "x", chatId: "", enabled: true },
undefined,
),
).toBe(false);
});
});
@@ -12,8 +12,7 @@
* The mutation wiring itself (DELETE `/facts/{id}` and DELETE `/facts`
* → `queryKeys.coachFacts()` invalidation + toast) is pinned by the
* route-shape contract in the component plus the typecheck gate; this
* suite guards the render contract the way the sibling
* `disable-coach-card.test.tsx` does for the toggle.
* suite guards the render contract.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
@@ -1,10 +1,10 @@
/**
* v1.18.0 — Settings → Coach section.
*
* The Coach preference cards (disable toggle, preferences, memory) moved
* out of the AI / Assistant section into their own dedicated, module-gated
* entry. SSR-only smoke test — interactive contracts live in the cards'
* own suites (`disable-coach-card.test.tsx`, `coach-memory-section.test.tsx`).
* The Coach preference cards (state, preferences, memory) moved out of the
* AI / Assistant section into their own dedicated, module-gated entry.
* SSR-only smoke test — interactive contracts live in the cards' own suites
* (`coach-memory-section.test.tsx`; the switch in `modules-section.test.tsx`).
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
@@ -78,34 +78,51 @@ function render(locale: "en" | "de" = "en") {
}
describe("<CoachSection> — SSR smoke", () => {
it("renders the section scaffold + the Activate-Coach toggle card", () => {
it("shows the Coach state with a link to the one switch, not a second switch", () => {
authState.disableCoach = false;
const html = render();
expect(html).toContain('id="settings-section-coach-title"');
expect(html).toContain('data-testid="settings-disable-coach-card"');
expect(html).toContain('data-testid="settings-disable-coach-switch"');
// v1.18.1 — polarity flipped to activate/default-on.
expect(html).toContain("Activate Coach");
expect(html).toContain("Show the Coach button and drawer");
// v1.18.6 — the proactive Coach nudge card moved here from
// Benachrichtigungen; its anchor renders under the enabled-coach gate.
expect(html).toContain('id="coach-nudge"');
expect(html).toContain('data-slot="settings-coach-state-card"');
expect(html).toContain('data-enabled="true"');
expect(html).toContain('href="/settings/modules#module-coach"');
// v1.44 — no switch of its own: one state, one control, in Modules.
const card = html.match(
/data-slot="settings-coach-state-card"[\s\S]*?<\/a>/,
)?.[0];
expect(card).toBeDefined();
expect(card).not.toContain('role="switch"');
expect(html).not.toContain("settings-disable-coach");
// Raw key never leaks past i18n.
expect(html).not.toContain("settings.sections.coach.");
expect(html).not.toContain("settings.coach.activate.");
expect(html).not.toContain("settings.coach.state.");
});
it("renders the German Activate-Coach copy", () => {
authState.disableCoach = false;
it("reads off once the account has the Coach off", () => {
mountState.mounted = true;
authState.disableCoach = true;
try {
expect(render()).toContain('data-enabled="false"');
} finally {
mountState.mounted = false;
authState.disableCoach = false;
}
});
it("points the nudges at Settings > Notifications", () => {
const html = render();
expect(html).toContain('href="/settings/notifications#coach-nudge"');
expect(html).not.toContain('id="coach-nudge"');
});
it("renders the German copy", () => {
const html = render("de");
expect(html).toContain("Coach aktivieren");
expect(html).not.toContain("settings.sections.coach.");
expect(html).not.toContain("settings.coach.activate.");
expect(html).not.toContain("settings.coach.state.");
});
});
describe("<CoachSection> — the tuning follows the record, not the account", () => {
it("hides the nudge when the record has the Coach off, whatever the viewer's own opt-out says", () => {
it("hides the nudge pointer when the record has the Coach off, whatever the viewer's own opt-out says", () => {
// A guardian with the Coach on, inside a managed record that has it off:
// `/me` publishes the viewer's own `disableCoach` and the RECORD's module
// map. The record's answer decides.
@@ -113,10 +130,10 @@ describe("<CoachSection> — the tuning follows the record, not the account", ()
authState.disableCoach = false;
authState.modules = { coach: false };
try {
expect(render()).not.toContain('id="coach-nudge"');
expect(render()).not.toContain('data-slot="settings-coach-nudge-link"');
authState.disableCoach = true;
authState.modules = { coach: true };
expect(render()).toContain('id="coach-nudge"');
expect(render()).toContain('data-slot="settings-coach-nudge-link"');
} finally {
mountState.mounted = false;
authState.disableCoach = false;
@@ -0,0 +1,75 @@
/**
* One confirm style across Settings.
*
* A destructive act (delete, revoke, remove, reset, sign out) confirms through
* `ConfirmButton` / `ConfirmDialog` (`src/components/ui/confirm-button.tsx`),
* which owns the dialog's anatomy and wears the destructive style when the
* caller says the act is destructive. A hand-built `AlertDialog` is how the
* same question ended up styled three different ways on neighbouring cards.
*
* So no file under `src/components/settings` imports the raw `AlertDialog`
* unless it is listed below with the reason the primitive does not fit.
*/
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
const ROOT = join(process.cwd(), "src", "components", "settings");
const ALLOWED: Readonly<Record<string, string>> = {
"security-section/existing-factor-reauth-dialog.tsx":
"a re-authentication form, not a destructive confirm",
"security-section/passkey-list-section.tsx":
"the add-passkey re-authentication form; the delete confirm uses ConfirmButton",
"security-section/totp-card.tsx":
"the disable confirm asks for a current code and stays open until the server answers; both actions wear the destructive style",
};
/** Owned by the integration cards, which follow their own card kit. */
const ALLOWED_PREFIXES: readonly string[] = ["integrations/"];
function walk(dir: string): string[] {
return readdirSync(dir).flatMap((name) => {
const path = join(dir, name);
if (statSync(path).isDirectory()) {
return name === "__tests__" ? [] : walk(path);
}
return /\.tsx?$/.test(name) ? [path] : [];
});
}
const IMPORTS_ALERT_DIALOG = /from\s+["']@\/components\/ui\/alert-dialog["']/;
describe("settings confirm style", () => {
const files = walk(ROOT);
it("scans the settings tree", () => {
expect(files.length).toBeGreaterThan(50);
});
it("imports the raw AlertDialog only where the primitive does not fit", () => {
const offenders = files
.map((path) => relative(ROOT, path))
.filter((rel) =>
IMPORTS_ALERT_DIALOG.test(readFileSync(join(ROOT, rel), "utf8")),
)
.filter(
(rel) =>
!(rel in ALLOWED) &&
!ALLOWED_PREFIXES.some((prefix) => rel.startsWith(prefix)),
);
expect(
offenders,
"Confirm a destructive act through ConfirmButton / ConfirmDialog, or list the file here with the reason",
).toEqual([]);
});
it("lists no file that no longer needs the exemption", () => {
const stale = Object.keys(ALLOWED).filter(
(rel) =>
!IMPORTS_ALERT_DIALOG.test(readFileSync(join(ROOT, rel), "utf8")),
);
expect(stale).toEqual([]);
});
});
@@ -1,155 +0,0 @@
/**
* v1.4.47 — Settings → Coach activation toggle persistence contract.
*
* v1.18.1 — the card reads "Activate Coach" (default ON). The persisted
* column is still `User.disableCoach`; the Switch shows the activated view
* (`checked = !disableCoach`). The SSR render is `mounted=false`, where the
* card paints the default-ON (checked) state so the default-on contract holds
* before the wire value resolves — both default and opted-out users render
* checked under `renderToStaticMarkup`.
*
* The card is a small client-only `<Switch>` that PATCHes
* `/api/auth/me/disable-coach` and invalidates `queryKeys.authMe()` so
* every Coach mount point in the app reacts on the next /me refetch.
*
* Test strategy: use the real `useMutation` + `QueryClient` from
* `@tanstack/react-query`, stub `fetch`, and drive the Switch via a
* `renderToStaticMarkup` pass plus a hand-invoked mutation call. The
* file SSR-renders inside a `<QueryClientProvider>` so the hook
* branches execute and the spies fire.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import type { AuthUser } from "@/hooks/use-auth";
const authSpy = vi.fn<
() => { user: AuthUser | null; isAuthenticated: boolean }
>(() => ({ user: buildUser(false), isAuthenticated: true }));
vi.mock("@/hooks/use-auth", async () => {
const actual =
await vi.importActual<typeof import("@/hooks/use-auth")>(
"@/hooks/use-auth",
);
return {
...actual,
useAuth: () => authSpy(),
};
});
// Stub the navigation hooks the parent `<CoachSection>` (and its child
// cards) reach for so the SSR pass doesn't blow up. The disable-coach card
// itself doesn't trigger any GET — it only writes through PATCH on click.
//
// v1.18.0 — the Coach cards moved from `<AiSection>` to the dedicated
// `<CoachSection>`; this contract test renders the new parent.
vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
usePathname: () => "/settings/coach",
useSearchParams: () => new URLSearchParams(""),
}));
function buildUser(disableCoach: boolean): AuthUser {
return {
id: "user-1",
username: "testuser",
email: null,
role: "USER",
heightCm: null,
dateOfBirth: null,
gender: null,
timezone: "Europe/Berlin",
onboardingCompletedAt: null,
onboardingTourCompleted: true,
onboardingTourProgress: null,
avatarUrl: null,
glucoseUnit: null,
unitPreference: "metric",
timeFormat: "AUTO",
dateFormat: "AUTO",
disableCoach,
fullName: null,
insurerName: null,
insurerIkNumber: null,
insuranceNumber: null,
lastReportPracticeName: null,
reportSelection: null,
cycleTrackingEnabled: false,
modules: {},
};
}
import { CoachSection } from "../coach-section";
function makeFetch() {
return vi.fn(async (_url: RequestInfo | URL, init?: RequestInit) => {
const body = init?.body ? JSON.parse(init.body as string) : {};
return new Response(
JSON.stringify({
data: { disableCoach: body.disableCoach ?? false },
}),
{
status: 200,
headers: { "Content-Type": "application/json" },
},
);
});
}
beforeEach(() => {
authSpy.mockClear();
authSpy.mockImplementation(() => ({
user: buildUser(false),
isAuthenticated: true,
}));
vi.stubGlobal("fetch", makeFetch());
});
afterEach(() => {
vi.unstubAllGlobals();
});
function render(): string {
const client = new QueryClient({
defaultOptions: { queries: { retry: 0 } },
});
return renderToStaticMarkup(
<QueryClientProvider client={client}>
<I18nProvider initialLocale="en">
<CoachSection />
</I18nProvider>
</QueryClientProvider>,
);
}
describe("Settings — DisableCoachCard", () => {
it("renders the activation Switch checked at SSR (default-on contract)", () => {
const html = render();
// v1.18.1 — the SSR render is `mounted=false`, where the card paints
// the default-ON (activated → checked) state regardless of the wire value,
// so the Switch never flashes off before /me resolves.
expect(html).toContain('data-testid="settings-disable-coach-switch"');
expect(html).toContain('data-state="checked"');
});
it("paints the activated (checked) SSR state even for an opted-out user", () => {
authSpy.mockImplementation(() => ({
user: buildUser(true),
isAuthenticated: true,
}));
const html = render();
expect(html).toContain('data-testid="settings-disable-coach-switch"');
// The activated state resolves on the first client re-render once
// `mounted` flips; the SSR pass stays on the default-ON shape.
expect(html).toContain('data-state="checked"');
});
it("renders the Coach-activation title + description", () => {
const html = render();
// v1.18.1 — polarity flipped to activate/default-on.
expect(html).toContain("Activate Coach");
expect(html).toContain("Show the Coach button and drawer");
});
});
@@ -16,7 +16,6 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("../dashboard-section", () => ({ DashboardSection: () => null }));
vi.mock("../insights-section", () => ({ InsightsSection: () => null }));
vi.mock("../medications-section", () => ({ MedicationsSection: () => null }));
vi.mock("../mood-section", () => ({ MoodSection: () => null }));
vi.mock("../labs-section", () => ({ LabsSection: () => null }));
vi.mock("../illness-section", () => ({ IllnessSection: () => null }));
vi.mock("../vorsorge-section", () => ({ VorsorgeSection: () => null }));
@@ -29,12 +28,13 @@ import {
} from "../layout-groups";
describe("layout-groups registry", () => {
it("exposes the eight Appearance modules as statically-generated subpage params", () => {
it("exposes the seven Arrangement modules as statically-generated subpage params", () => {
// v1.44 — mood left: its page was tag management, which lives under
// Settings > Modules > Mood now (`/settings/layout/mood` redirects).
expect(LAYOUT_GROUP_IDS).toEqual([
"dashboard",
"insights",
"medications",
"mood",
"labs",
"illness",
"documents",
@@ -45,7 +45,6 @@ describe("layout-groups registry", () => {
{ module: "dashboard" },
{ module: "insights" },
{ module: "medications" },
{ module: "mood" },
{ module: "labs" },
{ module: "illness" },
{ module: "documents" },
@@ -66,7 +65,7 @@ describe("layout-groups registry", () => {
? layoutGroupModule(id)
: "not-a-group";
expect(gate("medications")).toBe("medications");
expect(gate("mood")).toBe("mood");
expect(gate("mood")).toBe("not-a-group");
expect(gate("labs")).toBe("labs");
expect(gate("illness")).toBe("illness");
// dashboard / insights / vorsorge are never gated.
@@ -54,7 +54,6 @@ describe("<LayoutSection> hub", () => {
"dashboard",
"insights",
"medications",
"mood",
"labs",
"illness",
"vorsorge",
@@ -68,7 +67,7 @@ describe("<LayoutSection> hub", () => {
expect(html).not.toContain('href="/settings/layout/medications"');
expect(html).not.toContain('href="/settings/layout/labs"');
// Other modules unaffected; Vorsorge is never gated.
expect(html).toContain('href="/settings/layout/mood"');
expect(html).toContain('href="/settings/layout/illness"');
expect(html).toContain('href="/settings/layout/vorsorge"');
});
@@ -82,6 +81,7 @@ describe("<LayoutSection> hub", () => {
expect(html).toContain('href="/settings/layout/dashboard"');
expect(html).toContain('href="/settings/layout/insights"');
expect(html).toContain('href="/settings/layout/vorsorge"');
// v1.44 — mood is tag management and left Arrangement for Modules.
expect(html).not.toContain('href="/settings/layout/mood"');
});
@@ -137,11 +137,11 @@ describe("<MedicationsSection> — SSR smoke", () => {
expect(lastActive).toBeLessThan(html.indexOf("Amoxicillin"));
});
it("gathers the injection-sites card (moved from the account profile)", () => {
// v1.18.0 — injection-site exclusions are a medication setting and
// now live on this screen alongside the list view + order.
it("holds order and view only; the injection sites live under Modules", () => {
// v1.44 — Arrangement holds order and view; the injection-site
// exclusions moved to Settings > Modules > Medications.
const html = render();
expect(html).toContain("Globally excluded injection sites");
expect(html).not.toContain("Globally excluded injection sites");
});
it("feeds the editor the saved order (active block re-sorted by layout.order)", () => {
@@ -131,7 +131,6 @@ vi.mock("@/hooks/use-auth", () => ({
}));
import { I18nProvider } from "@/lib/i18n/context";
import { SettingsSectionFrame } from "./section-frame-harness";
import { MoodSection } from "../mood-section";
import { primeLocales } from "@/__tests__/helpers/prime-locales";
@@ -142,9 +141,7 @@ function render(locale: "en" | "de" = "en"): string {
// shared frame the route wraps the section in.
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<SettingsSectionFrame slug="mood">
<MoodSection />
</SettingsSectionFrame>
<MoodSection />
</I18nProvider>,
);
}
@@ -159,7 +156,8 @@ describe("<MoodSection> — SSR smoke", () => {
// v1.18.1 — the section blurb was dropped; the sr-only heading + the
// card content carry the meaning.
const html = render();
expect(html).toContain("settings-section-mood-title");
// v1.44 — the page lives under Settings > Modules > Mood; its heading
// comes from the route, not from a frame here.
expect(html).not.toContain("settings.sections.");
expect(html).not.toContain("mood.manage.");
});
@@ -121,60 +121,27 @@ describe("notification channel cards", () => {
);
it.each([
["webhook", <WebhookCard key="webhook" isAuthenticated />, 1],
["ntfy", <NtfyCard key="ntfy" isAuthenticated />, 1],
["email", <EmailCard key="email" isAuthenticated />, 1],
["telegram", <TelegramCard key="telegram" isAuthenticated />, 0],
["webhook", <WebhookCard key="webhook" isAuthenticated />],
["ntfy", <NtfyCard key="ntfy" isAuthenticated />],
["email", <EmailCard key="email" isAuthenticated />],
["telegram", <TelegramCard key="telegram" isAuthenticated />],
] as const)(
"%s switch invokes the enable-only mutation rather than the full save",
async (channel, card, toggleMutationIndex) => {
render(card);
await mocks.mutationOptions[toggleMutationIndex]!.mutationFn(true);
expect(mocks.apiFetchRaw).toHaveBeenCalledTimes(1);
expect(mocks.apiFetchRaw).toHaveBeenCalledWith(
`/api/settings/${channel}`,
{
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled: true }),
},
);
},
);
it.each([
[<WebhookCard key="webhook" isAuthenticated />, 1, ["settings", "webhook"]],
[<NtfyCard key="ntfy" isAuthenticated />, 1, ["settings", "ntfy"]],
[<EmailCard key="email" isAuthenticated />, 1, ["settings", "email"]],
[
<TelegramCard key="telegram" isAuthenticated />,
0,
["telegram", "settings"],
],
] as const)(
"rolls each visible switch back to its previous server state on error",
async (card, toggleMutationIndex, queryKey) => {
const previous = { enabled: false, persistedConfig: "unchanged" };
mocks.queryClient.getQueryData.mockReturnValue(previous);
render(card);
const toggle = mocks.mutationOptions[toggleMutationIndex]!;
const context = await toggle.onMutate!(true);
const optimisticUpdater = mocks.queryClient.setQueryData.mock
.calls[0]![1] as (current: typeof previous) => typeof previous;
expect(optimisticUpdater(previous)).toEqual({
...previous,
enabled: true,
});
toggle.onError!(new Error("save failed"), true, context);
expect(mocks.queryClient.setQueryData).toHaveBeenLastCalledWith(
queryKey,
previous,
);
"%s enable switch is a form field: it writes nothing on its own",
async (_channel, card) => {
const html = render(card);
// Rendering the switch writes nothing, and the card mounts no
// switch-only mutation: every write it can make is the full form.
expect(html).toContain('role="switch"');
expect(mocks.apiFetchRaw).not.toHaveBeenCalled();
for (const mutation of mocks.mutationOptions) {
await mutation.mutationFn(true);
}
for (const [, init] of mocks.apiFetchRaw.mock.calls as Array<
[string, { body: string }]
>) {
const body = JSON.parse(init.body) as Record<string, unknown>;
expect(Object.keys(body).length).toBeGreaterThan(1);
}
},
);
@@ -185,9 +152,9 @@ describe("notification channel cards", () => {
expect(html).toMatch(/<option value="generic" selected="">/);
expect(html).toContain('<option value="gotify">');
// The full save is the first mutation of the last render, whose closure
// holds the values seeded from the server.
const save = mocks.mutationOptions[mocks.mutationOptions.length - 2]!;
// The full save is the mutation of the last render, whose closure holds
// the values seeded from the server, the enable switch included.
const save = mocks.mutationOptions.at(-1)!;
await save.mutationFn(false);
const [, init] = mocks.apiFetchRaw.mock.calls[0] as [
@@ -1,93 +0,0 @@
import { QueryClient } from "@tanstack/react-query";
import { beforeEach, describe, expect, it, vi } from "vitest";
vi.mock("@/lib/api/api-fetch", () => ({
apiFetchRaw: vi.fn(),
}));
import { apiFetchRaw } from "@/lib/api/api-fetch";
import {
optimisticallySetChannelEnabled,
persistChannelEnabled,
rollbackChannelEnabled,
} from "../notification-channel-toggle";
beforeEach(() => {
vi.clearAllMocks();
});
describe("notification channel enable-only mutation", () => {
it.each([
"/api/settings/webhook",
"/api/settings/ntfy",
"/api/settings/email",
"/api/settings/telegram",
])("sends only enabled to %s", async (endpoint) => {
vi.mocked(apiFetchRaw).mockResolvedValue(
new Response(JSON.stringify({ data: { saved: true } }), { status: 200 }),
);
await persistChannelEnabled(endpoint, true, "save failed");
expect(apiFetchRaw).toHaveBeenCalledWith(endpoint, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ enabled: true }),
});
expect(
JSON.parse(vi.mocked(apiFetchRaw).mock.calls[0]![1]!.body as string),
).toEqual({ enabled: true });
});
it("changes only cached enabled state and leaves configuration fields intact", () => {
const client = new QueryClient();
const key = ["settings", "webhook"] as const;
const settings = {
enabled: false,
url: "https://saved.example/hook",
topic: "saved-topic",
recipient: "saved@example.com",
hasHeaderValue: true,
};
client.setQueryData(key, settings);
const previous = optimisticallySetChannelEnabled(client, key, true);
expect(previous).toEqual(settings);
expect(client.getQueryData(key)).toEqual({ ...settings, enabled: true });
});
it("restores the exact previous cached settings after a failed toggle", () => {
const client = new QueryClient();
const key = ["settings", "telegram"] as const;
const previousSettings = {
enabled: false,
hasBotToken: true,
chatId: "123456",
};
client.setQueryData(key, previousSettings);
const previous = optimisticallySetChannelEnabled(client, key, true);
expect(client.getQueryData<{ enabled: boolean }>(key)?.enabled).toBe(true);
rollbackChannelEnabled(client, key, previous);
expect(client.getQueryData(key)).toEqual(previousSettings);
expect(client.getQueryData<{ enabled: boolean }>(key)?.enabled).toBe(false);
});
it("surfaces the route error so the card mutation can roll back", async () => {
vi.mocked(apiFetchRaw).mockResolvedValue(
new Response(
JSON.stringify({ error: "Stored configuration is missing" }),
{
status: 422,
},
),
);
await expect(
persistChannelEnabled("/api/settings/ntfy", true, "save failed"),
).rejects.toThrow("Stored configuration is missing");
});
});
@@ -1,14 +1,12 @@
/**
* v1.18.0 — module-gated per-type visibility on the consolidated
* "Benachrichtigungen" reminder-types home.
* Settings > Notifications is the one home for every reminder kind, each
* card gated on its module and failing open.
*
* The mood reminder shows only when the `mood` module is enabled. Low-stock
* maps to the medications domain (shown unless explicitly disabled). The gate
* fails OPEN, so a `/me` payload without a module map keeps every card
* visible.
*
* v1.18.6 — the proactive Coach nudge card moved to Settings → Coach, so
* it no longer appears on this screen.
* v1.18.0 — mood reminder on `mood`, low-stock on `medications`.
* v1.44 — the Coach nudges came back (gated on the Coach surface), the
* checkup reminder switches joined (not a module, always shown), and a card
* names the reminders set where their subject lives (dose times on the
* medication, the cycle reminders in the per-event matrix).
*/
import { describe, expect, it, vi } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
@@ -25,8 +23,9 @@ vi.mock("@tanstack/react-query", () => ({
useMutation: () => ({ mutate: vi.fn(), isPending: false }),
}));
// The auth mock is driven per-test via a mutable ref so each render can pick
// a different module map without re-mocking the module.
// Mounted, so the Coach gate reads the module map like a hydrated page.
vi.mock("@/hooks/use-mounted", () => ({ useMounted: () => true }));
const authRef: { modules?: Record<string, boolean> } = {};
vi.mock("@/hooks/use-auth", () => ({
useAuth: () => ({
@@ -49,38 +48,43 @@ function render(modules?: Record<string, boolean>) {
);
}
describe("<NotificationsSection> module-gated reminder types", () => {
it("shows mood + low-stock cards when no module map (fails open); no coach nudge", () => {
describe("<NotificationsSection> reminder kinds", () => {
it("shows every reminder card when no module map (fails open)", () => {
const html = render(undefined);
expect(html).toContain('id="mood-reminder"');
expect(html).toContain('id="low-stock"');
// v1.18.6 — the coach nudge moved to Settings → Coach.
expect(html).not.toContain('id="coach-nudge"');
expect(html).toContain('id="coach-nudge"');
expect(html).toContain('id="vorsorge-reminders"');
expect(html).toContain('data-slot="notifications-elsewhere"');
expect(html).toContain('id="cycle-reminders"');
});
it("hides the mood card when the mood module is disabled", () => {
const html = render({ mood: false });
expect(html).not.toContain('id="mood-reminder"');
// Low-stock is unaffected.
expect(html).toContain('id="low-stock"');
});
it("always shows low-stock unless medications is disabled", () => {
const html = render({ mood: false });
expect(html).toContain('id="low-stock"');
expect(html).not.toContain('id="mood-reminder"');
expect(html).not.toContain('id="coach-nudge"');
it("hides the low-stock card and the dose row when medications is disabled", () => {
const html = render({ medications: false });
expect(html).not.toContain('id="low-stock"');
expect(html).not.toContain('href="/medications"');
});
it("drops the channels / inbox cross-links and the Vorsorge block (D5)", () => {
// v1.18.1 — the page is lean: no section blurb, no channels/inbox
// cross-links, and no embedded Vorsorge editor (it has its own page).
it("hides the Coach nudges when the Coach is off", () => {
expect(render({ coach: false })).not.toContain('id="coach-nudge"');
});
it("drops the elsewhere card when neither of its reminders applies", () => {
const html = render({ medications: false, cycle: false });
expect(html).not.toContain('data-slot="notifications-elsewhere"');
// The checkup reminders are not a module and stay.
expect(html).toContain('id="vorsorge-reminders"');
});
it("links to the per-event matrix and to the delivery channels", () => {
const html = render({});
expect(html).not.toContain('data-slot="notifications-channels-cross-link"');
expect(html).not.toContain('data-slot="notifications-inbox-cross-link"');
// The remaining reminder-type cards (no coach nudge here anymore).
expect(html).toContain('id="mood-reminder"');
expect(html).toContain('id="low-stock"');
expect(html).not.toContain('id="coach-nudge"');
expect(html).toContain('href="/notifications"');
expect(html).toContain('href="/settings/integrations#channels"');
});
});
@@ -0,0 +1,51 @@
import { describe, expect, it } from "vitest";
import { renderToStaticMarkup } from "react-dom/server";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { I18nProvider } from "@/lib/i18n/context";
import { queryKeys } from "@/lib/query-keys";
import { PreviewSection } from "../preview-section";
import { primeLocales } from "@/__tests__/helpers/prime-locales";
primeLocales("de");
function render(topics: boolean | undefined, locale: "en" | "de" = "en") {
const client = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnMount: false } },
});
if (topics !== undefined) {
client.setQueryData(queryKeys.previewFeatures(), { topics });
}
return renderToStaticMarkup(
<I18nProvider initialLocale={locale}>
<QueryClientProvider client={client}>
<PreviewSection />
</QueryClientProvider>
</I18nProvider>,
);
}
describe("<PreviewSection>", () => {
it("shows the Topics switch off by default, saved on change", () => {
const html = render(false);
expect(html).toContain('data-slot="settings-preview-topics-switch"');
expect(html).toMatch(
/data-slot="settings-preview-topics-switch"[^>]*aria-checked="false"|aria-checked="false"[^>]*data-slot="settings-preview-topics-switch"/,
);
expect(html).toContain("Topics (beta)");
// A switch, no Save: one save model per card.
expect(html).not.toContain('type="submit"');
});
it("reads on once the person switched it on", () => {
expect(render(true)).toMatch(
/data-slot="settings-preview-topics-switch"[^>]*aria-checked="true"|aria-checked="true"[^>]*data-slot="settings-preview-topics-switch"/,
);
});
it("says the existing pages stay as they are and nothing raw leaks", () => {
const html = render(false, "de");
expect(html).toContain("Themen (Beta)");
expect(html).not.toContain("settings.preview.");
});
});
@@ -55,7 +55,7 @@ function render(node: React.ReactNode, locale: "en" | "de" = "en") {
}
describe("<PrivacySection> — assembled Data & Privacy dashboard", () => {
it("renders the assembled sections (encryption, retention, export, delete, sessions, activity)", () => {
it("renders the assembled sections (encryption, retention, delete)", () => {
const html = render(<PrivacySection />);
// Encryption-at-rest block driven from the seeded summary.
expect(html).toContain("AES-256-GCM");
@@ -63,15 +63,14 @@ describe("<PrivacySection> — assembled Data & Privacy dashboard", () => {
expect(html).toContain("365");
// The honest backup↔deletion lag disclosure is present.
expect(html.toLowerCase()).toContain("backup");
// Links to the existing export + destructive surfaces (assembly, not rebuild).
expect(html).toContain('href="/settings/export"');
expect(html).toContain('href="/settings/gesundheitsakte"');
// Links to the destructive surface (assembly, not rebuild).
expect(html).toContain('href="/settings/advanced"');
// Embedded active-session + security-activity cards.
expect(html).toContain("settings-security-sessions-card");
// Trusted devices now lives here (and only here) — its single home is the
// Privacy dashboard, not the Security section.
expect(html).toContain("settings-trusted-devices-card");
// v1.44 — sessions, trusted devices and the activity feed live under
// Security, and the duplicate export card is gone: Export & import and
// the Health record sit beside this page in the Data group.
expect(html).not.toContain("settings-security-sessions-card");
expect(html).not.toContain("settings-trusted-devices-card");
expect(html).not.toContain('href="/settings/export"');
});
it("shows a loading placeholder for the retention block before the summary resolves", () => {
@@ -0,0 +1,256 @@
/**
* One save model per card.
*
* A settings card either saves each control the moment it changes (switches,
* selects, segmented choices) or collects a multi-field draft behind one
* explicit Save. Never both: a card with an instant switch beside a Save
* button leaves a person guessing which of their changes the button covers,
* and the channel cards (Telegram, ntfy, webhook, email) did exactly that —
* the enable switch wrote on tap while the rest of the form waited for Save.
*
* The guard splits every settings source into card units (each
* `<SettingsCard>…</SettingsCard>` block; a file without one is a single
* unit) and fails a unit that both
* - saves explicitly: a `type="submit"` control or the `common.save` label,
* - saves instantly: a Switch / NativeSelect / Select / Segmented / Checkbox
* whose change handler does more than set local draft state.
*
* Its limit, written down: the handler check is textual. It follows calls to
* functions declared in the same file two levels deep; a write hidden behind
* a callback handed in through props, or behind an imported helper whose
* name carries none of the write markers, reads as a draft field.
*/
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
import { describe, expect, it } from "vitest";
const ROOT = process.cwd();
const SETTINGS_DIR = join(ROOT, "src", "components", "settings");
const EXTRA_FILES = [
"src/components/labs/labs-settings.tsx",
"src/components/illness/illness-settings.tsx",
"src/components/measurement-reminders/vorsorge-settings.tsx",
];
/**
* `<file>#<card index>` → why the unit may mix both models. Empty on purpose;
* an entry needs a reason a reviewer can check.
*/
const ALLOWLIST: Readonly<Record<string, string>> = {};
function walk(dir: string): string[] {
const out: string[] = [];
for (const entry of readdirSync(dir)) {
const full = join(dir, entry);
if (statSync(full).isDirectory()) {
if (entry === "__tests__") continue;
out.push(...walk(full));
} else if (entry.endsWith(".tsx")) {
out.push(full);
}
}
return out;
}
/** Each `<SettingsCard>` block with its nested cards counted. */
function splitCardUnits(source: string): string[] {
const open = /<SettingsCard\b/g;
const units: string[] = [];
let match: RegExpExecArray | null;
let consumedTo = 0;
while ((match = open.exec(source)) !== null) {
if (match.index < consumedTo) continue;
let depth = 0;
const token = /<SettingsCard\b|<\/SettingsCard>/g;
token.lastIndex = match.index;
let t: RegExpExecArray | null;
let end = source.length;
while ((t = token.exec(source)) !== null) {
depth += t[0] === "</SettingsCard>" ? -1 : 1;
if (depth === 0) {
end = t.index + t[0].length;
break;
}
}
units.push(source.slice(match.index, end));
consumedTo = end;
}
return units.length > 0 ? units : [source];
}
/** The JSX opening tag starting at `start`, braces and strings respected. */
function openingTag(source: string, start: number): string {
let depth = 0;
let quote: string | null = null;
for (let i = start; i < source.length; i++) {
const c = source[i];
if (quote) {
if (c === quote && source[i - 1] !== "\\") quote = null;
continue;
}
if (depth > 0 && (c === '"' || c === "'" || c === "`")) {
quote = c;
continue;
}
if (c === "{") depth++;
else if (c === "}") depth--;
else if (c === ">" && depth === 0) return source.slice(start, i + 1);
}
return source.slice(start);
}
/** The `{…}` expression of `attr=` inside a tag, or null. */
function attributeExpression(tag: string, attr: string): string | null {
const at = tag.search(new RegExp(`\\b${attr}=\\{`));
if (at < 0) return null;
const open = tag.indexOf("{", at);
let depth = 0;
for (let i = open; i < tag.length; i++) {
if (tag[i] === "{") depth++;
else if (tag[i] === "}") {
depth--;
if (depth === 0) return tag.slice(open + 1, i).trim();
}
}
return null;
}
/** A call that writes to the server (or the locale) on its own. */
const WRITE_MARKER =
/\.mutate(?:Async)?\(|\bapi(?:FetchRaw|Fetch|Get|Put|Patch|Post|Delete)\(|\bsafeFetch\(|\bpersist\w*\(/;
/** The body of a function or arrow const declared in `source`, or null. */
function localDefinition(source: string, name: string): string | null {
const decl = new RegExp(
`(?:function\\s+${name}\\s*\\(|(?:const|let)\\s+${name}\\s*=)`,
).exec(source);
if (!decl) return null;
// A braceless arrow (`const f = (v) => g(v);`) ends at its line.
const rest = source.slice(decl.index);
const arrow = /^[^\n{]*=>\s*(?!\{)([^\n]*)/.exec(rest);
if (arrow) return arrow[0];
const open = source.indexOf("{", decl.index);
if (open < 0) return null;
let depth = 0;
for (let i = open; i < source.length; i++) {
if (source[i] === "{") depth++;
else if (source[i] === "}") {
depth--;
if (depth === 0) return source.slice(decl.index, i + 1);
}
}
return null;
}
/**
* True when a change handler writes on change: the handler itself carries a
* write call, or a function it calls that is declared in the same file does
* (followed two levels deep). A handler that only touches local state, or
* calls a callback handed in through props, reads as a draft field.
*/
function writesOnChange(handler: string, source: string, depth = 0): boolean {
if (WRITE_MARKER.test(handler)) return true;
if (depth >= 2) return false;
const names = new Set<string>();
if (/^[A-Za-z_]\w*$/.test(handler)) names.add(handler);
for (const m of handler.matchAll(/\b([A-Za-z_]\w*)\s*\(/g)) {
names.add(m[1]);
}
for (const name of names) {
const body = localDefinition(source, name);
if (body && writesOnChange(body, source, depth + 1)) return true;
}
return false;
}
const CONTROL = /<(Switch|NativeSelect|Select|Segmented|Checkbox)\b/g;
const HANDLERS = ["onCheckedChange", "onChange", "onValueChange"];
function savesInstantly(unit: string, source: string = unit): boolean {
CONTROL.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = CONTROL.exec(unit)) !== null) {
const tag = openingTag(unit, match.index);
for (const attr of HANDLERS) {
const handler = attributeExpression(tag, attr);
if (handler !== null && writesOnChange(handler, source)) return true;
}
}
return false;
}
function savesExplicitly(unit: string): boolean {
return /type="submit"/.test(unit) || /t\("common\.save"\)/.test(unit);
}
function scan() {
const files = [
...walk(SETTINGS_DIR),
...EXTRA_FILES.map((f) => join(ROOT, f)),
];
const mixed: string[] = [];
let units = 0;
for (const file of files) {
const rel = relative(ROOT, file);
const source = readFileSync(file, "utf8");
splitCardUnits(source).forEach((unit, index) => {
units++;
if (savesInstantly(unit, source) && savesExplicitly(unit)) {
const key = `${rel}#${index}`;
if (!ALLOWLIST[key]) mixed.push(key);
}
});
}
return { mixed, units, files: files.length };
}
describe("settings save model", () => {
it("classifies handlers", () => {
const source = `
function handleToggle(next) { mutation.mutate(next); }
function toggleItem(kind, on) { setDraft({ kind, on }); }
const flip = (v) => handleToggle(v);
`;
expect(writesOnChange("setChatId", source)).toBe(false);
expect(writesOnChange("(e) => setUrl(e.target.value)", source)).toBe(false);
expect(writesOnChange("(v) => toggleItem('a', v)", source)).toBe(false);
expect(
writesOnChange("(checked) => toggleEnabled.mutate(checked)", source),
).toBe(true);
expect(writesOnChange("handleToggle", source)).toBe(true);
expect(writesOnChange("(v) => flip(v)", source)).toBe(true);
});
it("refuses a card that both saves on change and behind a Save button", () => {
const mixedCard = `<SettingsCard><Switch onCheckedChange={(v) => save.mutate(v)} /><Button type="submit">{t("common.save")}</Button></SettingsCard>`;
const draftCard = `<SettingsCard><Switch onCheckedChange={setEnabled} /><Button type="submit">{t("common.save")}</Button></SettingsCard>`;
expect(
savesInstantly(splitCardUnits(mixedCard)[0]) &&
savesExplicitly(splitCardUnits(mixedCard)[0]),
).toBe(true);
expect(savesInstantly(splitCardUnits(draftCard)[0])).toBe(false);
});
it("finds no card that mixes instant and explicit saving", () => {
const { mixed, units, files } = scan();
// An empty scan would pass for the wrong reason.
expect(files).toBeGreaterThan(50);
expect(units).toBeGreaterThan(100);
expect(
mixed,
`cards mixing both save models:\n${mixed.join("\n")}`,
).toEqual([]);
});
it("keeps every allowlist entry pointing at a unit that still mixes", () => {
for (const key of Object.keys(ALLOWLIST)) {
const [file, index] = key.split("#");
const source = readFileSync(join(ROOT, file), "utf8");
const unit = splitCardUnits(source)[Number(index)];
expect(unit, key).toBeDefined();
expect(savesInstantly(unit, source) && savesExplicitly(unit), key).toBe(
true,
);
}
});
});
@@ -246,7 +246,8 @@ describe("settings sections — SSR smoke", () => {
// card is gone.
expect(html).toContain('id="mood-reminder"');
expect(html).toContain('id="low-stock"');
expect(html).not.toContain('id="coach-nudge"');
// v1.44 — the Coach nudges are back with the other reminders.
expect(html).toContain('id="coach-nudge"');
// v1.25.7 — delivery channels moved to Settings → Integrationen, so the
// channels group + panel no longer render on this surface.
expect(html).not.toContain('id="channels"');
@@ -11,6 +11,7 @@ import { join } from "node:path";
const mockPathnameRef = { value: "/settings/account" };
vi.mock("next/navigation", () => ({
usePathname: () => mockPathnameRef.value,
useRouter: () => ({ replace: () => {}, push: () => {} }),
}));
// v1.18.0 — the shell module-gates per-submodule nav entries off
@@ -169,6 +170,8 @@ describe("SETTINGS_SECTION_SLUGS", () => {
// v1.23 — "Data & Privacy" assembles the export / deletion / retention /
// encryption / session / activity pieces into one pane, after `advanced`.
"privacy",
// v1.44 — per-user preview opt-ins, in the System group before About.
"preview",
"about",
]);
});
@@ -193,23 +196,59 @@ describe("SETTINGS_SECTION_SLUGS", () => {
});
describe("<SettingsShell>", () => {
it("keeps meaningful non-interactive desktop groups while the mobile strip uses quiet separators", () => {
it("renders the nine groups as non-interactive sidebar headers, in order", () => {
const html = renderShell({ active: "account" });
for (const label of [
const labels = [
"Account",
"Your data",
"Display",
"Tracking",
"Arrangement",
"Notifications",
"Health profile",
"AI",
"Connectivity",
"Connections",
"Data",
"System",
]) {
expect(html).toContain(`>${label}</li>`);
];
let cursor = -1;
for (const label of labels) {
const at = html.indexOf(`>${label}</li>`);
expect(at, label).toBeGreaterThan(cursor);
cursor = at;
}
// Seven groups produce six quiet separators in the mobile strip.
expect(
html.match(/aria-hidden="true"/g)?.length ?? 0,
).toBeGreaterThanOrEqual(6);
});
it("puts every section in the group the plan names", () => {
const groupOf = Object.fromEntries(
SETTINGS_SECTIONS.map((section) => [section.slug, section.group]),
);
expect(groupOf).toEqual({
account: "account",
security: "account",
access: "account",
modules: "tracking",
layout: "arrangement",
notifications: "notifications",
score: "healthProfile",
thresholds: "healthProfile",
anamnesis: "healthProfile",
environment: "healthProfile",
ai: "ai",
coach: "ai",
integrations: "connections",
sources: "connections",
api: "connections",
mcp: "connections",
export: "data",
gesundheitsakte: "data",
privacy: "data",
advanced: "data",
preview: "system",
about: "system",
});
// Every routable section has a nav entry, and nothing else does.
expect([...SETTINGS_SECTIONS.map((s) => s.slug)].sort()).toEqual(
[...SETTINGS_SECTION_SLUGS].sort(),
);
});
it("starts the sticky desktop sidebar on the heading row", () => {
@@ -230,19 +269,14 @@ describe("<SettingsShell>", () => {
expect(source).not.toMatch(/<aside[\s\S]*?md:row-start-2/);
});
it("renders every navigable section link — once for the mobile strip and once for the desktop sidebar", () => {
it("renders every navigable section link in the sidebar", () => {
const html = renderShell({ active: "account" });
// Every slug — including `about`, which returned to the shell nav
// as the last entry after living dropdown-only since v1.4.33 IW7 —
// renders in both layouts.
// The phone's section sheet mounts its list only when opened, so the
// server markup carries each link once, in the desktop sidebar.
const navigableSlugs = SETTINGS_SECTIONS.map((section) => section.slug);
for (const slug of navigableSlugs) {
const matches = html.match(new RegExp(`href="/settings/${slug}"`, "g"));
// Two renders — mobile strip + desktop sidebar — guarantee the link
// exists in both layouts. Tablet/desktop hide the strip with `md:`,
// but the markup is always present so it's keyboard-discoverable
// before media queries resolve.
expect(matches?.length ?? 0).toBe(2);
expect(matches?.length ?? 0).toBe(1);
}
});
@@ -259,9 +293,9 @@ describe("<SettingsShell>", () => {
it('marks the active section with aria-current="page" (and only that one)', () => {
const html = renderShell({ active: "notifications" });
// Both layouts emit the active link, so two `aria-current="page"`.
// The sidebar marks the active link; the phone sheet is closed.
const occurrences = html.match(/aria-current="page"/g);
expect(occurrences?.length ?? 0).toBe(2);
expect(occurrences?.length ?? 0).toBe(1);
// And the active link is on the notifications href. Attribute order
// in React SSR is alphabetic, so `aria-current` precedes `href` —
@@ -269,28 +303,38 @@ describe("<SettingsShell>", () => {
// future React renderer changes.
const activeLinkRegex =
/<a\b[^>]*\baria-current="page"[^>]*\bhref="\/settings\/notifications"|<a\b[^>]*\bhref="\/settings\/notifications"[^>]*\baria-current="page"/g;
expect(html.match(activeLinkRegex)?.length ?? 0).toBe(2);
expect(html.match(activeLinkRegex)?.length ?? 0).toBe(1);
});
it("derives the active slug from the current pathname when `active` is omitted", () => {
const html = renderShell({ pathname: "/settings/api" });
const activeLinkRegex =
/<a\b[^>]*\baria-current="page"[^>]*\bhref="\/settings\/api"|<a\b[^>]*\bhref="\/settings\/api"[^>]*\baria-current="page"/g;
expect(html.match(activeLinkRegex)?.length ?? 0).toBe(2);
expect(html.match(activeLinkRegex)?.length ?? 0).toBe(1);
});
it("highlights the Layout hub when on a Layout child editor (v1.17.1 F-2)", () => {
// On `/settings/dashboard` (a Layout child reached through the hub) the
// Layout nav entry must read active even though Dashboard has no nav
// entry of its own. Both layouts emit the active link → two matches.
for (const child of ["/settings/dashboard", "/settings/insights"]) {
it("highlights the Arrangement hub on a legacy child path and on its sub-pages", () => {
// `/settings/dashboard` (a redirected legacy child) and the sub-pages
// under `/settings/layout/<id>` both read as the Arrangement entry.
for (const child of [
"/settings/dashboard",
"/settings/insights",
"/settings/layout/labs",
]) {
const html = renderShell({ pathname: child });
const layoutActive =
/<a\b[^>]*\baria-current="page"[^>]*\bhref="\/settings\/layout"|<a\b[^>]*\bhref="\/settings\/layout"[^>]*\baria-current="page"/g;
expect(html.match(layoutActive)?.length ?? 0).toBe(2);
expect(html.match(layoutActive)?.length ?? 0).toBe(1);
}
});
it("highlights Modules on a module's own settings page", () => {
const html = renderShell({ pathname: "/settings/modules/labs" });
const modulesActive =
/<a\b[^>]*\baria-current="page"[^>]*\bhref="\/settings\/modules"|<a\b[^>]*\bhref="\/settings\/modules"[^>]*\baria-current="page"/g;
expect(html.match(modulesActive)?.length ?? 0).toBe(1);
});
// v1.37.19 — the Layout children left `SETTINGS_SECTION_SLUGS`, so no
// page can pass one as the `active` override anymore; the pathname-based
// case above is the remaining (defensive) mapping.
@@ -424,7 +468,7 @@ describe("<SettingsShell>", () => {
const html = renderShell({ pathname: "/settings/totally-bogus" });
const activeLinkRegex =
/<a\b[^>]*\baria-current="page"[^>]*\bhref="\/settings\/account"|<a\b[^>]*\bhref="\/settings\/account"[^>]*\baria-current="page"/g;
expect(html.match(activeLinkRegex)?.length ?? 0).toBe(2);
expect(html.match(activeLinkRegex)?.length ?? 0).toBe(1);
});
it("resolves every section title via the i18n provider — English", () => {
@@ -440,7 +484,8 @@ describe("<SettingsShell>", () => {
// "Layout": it arranges and picks what each module shows and holds no
// theme, so "Appearance" promised a control it does not have.
expect(html).toContain('href="/settings/layout"');
expect(html).toContain(">Layout</a>");
// v1.44 — the hub holds only order and view, and says so.
expect(html).toContain(">Arrangement</a>");
// v1.25.3 — Channels folded into Notifications, so it is no longer a
// left-side entry; Sources keeps its own.
expect(html).not.toContain('href="/settings/channels"');
@@ -484,7 +529,7 @@ describe("<SettingsShell>", () => {
// (route stays `/settings/layout`). v1.42 — "Layout" in German too;
// "Darstellung" now names the account page's language-and-units card.
expect(html).toContain('href="/settings/layout"');
expect(html).toContain(">Layout</a>");
expect(html).toContain(">Anordnung</a>");
// v1.25.3 — Channels ("Kanäle") folded into Notifications; Sources keeps
// its own left-side entry.
expect(html).not.toContain('href="/settings/channels"');
@@ -512,17 +557,14 @@ describe("<SettingsShell>", () => {
expect(html).not.toContain("settings.sections.");
});
it("mobile section strip uses `no-scrollbar` so the swipe area doesn't paint a horizontal scrollbar", () => {
// The 10-section strip is wider than 393 CSS px, so without
// `no-scrollbar` Chromium/WebKit paints an always-on horizontal
// scrollbar at the top of every settings page. The class is
// defined in `globals.css` and combines `scrollbar-width: none`
// (Firefox) with `::-webkit-scrollbar { display: none }` (everyone
// else) — scroll behaviour is preserved.
const html = renderShell({ active: "account" });
const nav = html.match(/<nav\b[^>]*md:hidden[^>]*>/);
it("gives the phone one button naming the section, not a strip of every section", () => {
const html = renderShell({ active: "security" });
const nav = html.match(/<nav\b[^>]*md:hidden[^>]*>[\s\S]*?<\/nav>/);
expect(nav).not.toBeNull();
expect(nav![0]).toMatch(/\bno-scrollbar\b/);
expect(nav![0]).toMatch(/\boverflow-x-auto\b/);
expect(nav![0]).toContain('data-slot="settings-mobile-nav-trigger"');
expect(nav![0]).toContain("Security");
expect(nav![0]).toContain("Account");
expect(nav![0]).not.toContain("overflow-x-auto");
expect(nav![0]).not.toContain('href="/settings/');
});
});
@@ -26,10 +26,14 @@ function read(rel: string): string {
return readFileSync(join(process.cwd(), rel), "utf8");
}
/** The body of every `<AlertDialogAction …>…</AlertDialogAction>` block. */
/**
* Every confirm the source spells: an `<AlertDialogAction …>…</AlertDialogAction>`
* block, or a `<ConfirmButton … />` whose `confirmLabel` is the action label.
*/
function actions(source: string): string[] {
return [
...source.matchAll(/<AlertDialogAction\b[\s\S]*?<\/AlertDialogAction>/g),
...source.matchAll(/<ConfirmButton\b[\s\S]*?\/>/g),
].map((m) => m[0]);
}
@@ -41,7 +45,9 @@ describe("token revoke labels", () => {
);
expect(revokes.length).toBeGreaterThan(0);
for (const action of revokes) {
expect(action).toContain('t("settings.tokenRevokeAction")');
expect(action).toMatch(
/(confirmLabel=\{|>\s*\{)t\("settings\.tokenRevokeAction"\)/,
);
}
});