mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 08:12:52 +00:00
fix(settings): one save model and one confirm per card
The Telegram, ntfy, webhook and email cards saved their enable switch on tap and the rest of the form on Save; the switch is now part of the form and the one Save sends it. The display selects confirm a change with a toast. Destructive confirmations in Settings go through ConfirmButton or ConfirmDialog with the destructive style. Two structural guards hold both rules: a card may not mix instant and explicit saves, and no settings file reaches for a raw AlertDialog without a written reason.
This commit is contained in:
1 parent
93198017d6
commit
3ebef19ac3
32 files changed
+830
-1135
No files matched your search
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* 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",
|
||||
"mcp-section.tsx":
|
||||
"the connection and token revoke confirms; the MCP card is reshaped separately",
|
||||
};
|
||||
|
||||
/** 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([]);
|
||||
});
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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"\)/,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user