mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-16 15:23:29 +00:00
fix(settings): channel switches act on tap again, beside their form
The Telegram, ntfy, webhook and email cards had folded the enable switch into the form, so turning a channel off took a Save as well. The switch saves on tap again, optimistically with a rollback, and sits outside the form; the form's Save covers the channel's fields and sends the stored enable state unchanged. The save-model guard now splits a card into save units, each form and the rest of the card, and refuses a unit that mixes both models: an instant switch inside the form its Save submits, or a Save outside any form next to one, still fails. A form shows its refusal inline only, no longer as a toast on top.
This commit is contained in:
1 parent
709d28523c
commit
9cfc72fe1f
11 files changed
+413
-189
No files matched your search
@@ -21,7 +21,6 @@ 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", () => {
|
||||
@@ -57,12 +56,7 @@ 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: "",
|
||||
enabled: false,
|
||||
};
|
||||
const form = { serverUrl: "https://ntfy.sh", topic: "t", authToken: "" };
|
||||
expect(isNtfyFormDirty(form, saved)).toBe(false);
|
||||
expect(isNtfyFormDirty({ ...form, topic: "u" }, saved)).toBe(true);
|
||||
expect(isNtfyFormDirty({ ...form, serverUrl: "https://x" }, saved)).toBe(
|
||||
@@ -73,86 +67,39 @@ describe("channel form dirty state", () => {
|
||||
|
||||
it("email: the recipient counts", () => {
|
||||
expect(
|
||||
isEmailFormDirty(
|
||||
{ recipient: "a@x.io", enabled: false },
|
||||
{ recipient: "a@x.io" },
|
||||
),
|
||||
isEmailFormDirty({ recipient: "a@x.io" }, { recipient: "a@x.io" }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isEmailFormDirty(
|
||||
{ recipient: "b@x.io", enabled: false },
|
||||
{ recipient: "a@x.io" },
|
||||
),
|
||||
isEmailFormDirty({ recipient: "b@x.io" }, { 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", enabled: false },
|
||||
{ chatId: "1" },
|
||||
),
|
||||
isTelegramFormDirty({ botToken: "", chatId: "1" }, { chatId: "1" }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isTelegramFormDirty({ botToken: " ", chatId: "" }, { chatId: null }),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isTelegramFormDirty(
|
||||
{ botToken: " ", chatId: "", enabled: false },
|
||||
{ chatId: null },
|
||||
),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isTelegramFormDirty(
|
||||
{ botToken: "123:abc", chatId: "1", enabled: false },
|
||||
{ botToken: "123:abc", chatId: "1" },
|
||||
{ chatId: "1" },
|
||||
),
|
||||
).toBe(true);
|
||||
expect(
|
||||
isTelegramFormDirty(
|
||||
{ botToken: "", chatId: "2", enabled: false },
|
||||
{ chatId: "1" },
|
||||
),
|
||||
isTelegramFormDirty({ botToken: "", chatId: "2" }, { 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", enabled: true },
|
||||
undefined,
|
||||
),
|
||||
isNtfyFormDirty({ serverUrl: "", topic: "", authToken: "x" }, undefined),
|
||||
).toBe(false);
|
||||
expect(isEmailFormDirty({ recipient: "x", enabled: true }, undefined)).toBe(
|
||||
expect(isEmailFormDirty({ recipient: "x" }, undefined)).toBe(false);
|
||||
expect(isTelegramFormDirty({ botToken: "x", chatId: "" }, undefined)).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
isTelegramFormDirty(
|
||||
{ botToken: "x", chatId: "", enabled: true },
|
||||
undefined,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -126,22 +126,56 @@ describe("notification channel cards", () => {
|
||||
["email", <EmailCard key="email" isAuthenticated />],
|
||||
["telegram", <TelegramCard key="telegram" isAuthenticated />],
|
||||
] as const)(
|
||||
"%s enable switch is a form field: it writes nothing on its own",
|
||||
async (_channel, card) => {
|
||||
"%s enable switch saves on tap, alone, outside the form",
|
||||
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"');
|
||||
// The switch precedes the form: its Save covers the fields, not the
|
||||
// switch.
|
||||
expect(html.indexOf('role="switch"')).toBeGreaterThan(-1);
|
||||
expect(html.indexOf('role="switch"')).toBeLessThan(html.indexOf("<form"));
|
||||
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);
|
||||
}
|
||||
|
||||
// The card's first mutation is the switch's, and it sends `enabled`
|
||||
// and nothing else.
|
||||
await mocks.mutationOptions[0]!.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 />, ["settings", "webhook"]],
|
||||
[<NtfyCard key="ntfy" isAuthenticated />, ["settings", "ntfy"]],
|
||||
[<EmailCard key="email" isAuthenticated />, ["settings", "email"]],
|
||||
[<TelegramCard key="telegram" isAuthenticated />, ["telegram", "settings"]],
|
||||
] as const)(
|
||||
"rolls each switch back to its previous server state on error",
|
||||
async (card, queryKey) => {
|
||||
const previous = { enabled: false, persistedConfig: "unchanged" };
|
||||
mocks.queryClient.getQueryData.mockReturnValue(previous);
|
||||
render(card);
|
||||
const toggle = mocks.mutationOptions[0]!;
|
||||
|
||||
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,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -153,7 +187,7 @@ describe("notification channel cards", () => {
|
||||
expect(html).toContain('<option value="gotify">');
|
||||
|
||||
// The full save is the mutation of the last render, whose closure holds
|
||||
// the values seeded from the server, the enable switch included.
|
||||
// the values seeded from the server; it carries the stored enable state.
|
||||
const save = mocks.mutationOptions.at(-1)!;
|
||||
await save.mutationFn(false);
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -10,11 +10,20 @@
|
||||
*
|
||||
* 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
|
||||
* unit), and each card into save units: every `<form>…</form>` inside it is
|
||||
* one, and the rest of the card is one more. It fails a save 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.
|
||||
*
|
||||
* So a card may carry an instant switch beside a form with its own Save, as
|
||||
* long as the switch is outside that form: the channel cards (Telegram, ntfy,
|
||||
* webhook, email) switch delivery on and off on tap, and their Save covers
|
||||
* the address, topic or token fields inside the form. What stays refused is
|
||||
* an instant control inside the form its Save submits, or a Save outside any
|
||||
* form next to an instant control, where nothing marks which change the
|
||||
* button covers.
|
||||
*
|
||||
* 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
|
||||
@@ -179,6 +188,45 @@ function savesInstantly(unit: string, source: string = unit): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A card's save units: each `<form>` block inside it, then whatever of the
|
||||
* card lies outside every form.
|
||||
*/
|
||||
function splitSaveUnits(card: string): string[] {
|
||||
const forms: string[] = [];
|
||||
let rest = "";
|
||||
let cursor = 0;
|
||||
const open = /<form\b/g;
|
||||
let match: RegExpExecArray | null;
|
||||
while ((match = open.exec(card)) !== null) {
|
||||
if (match.index < cursor) continue;
|
||||
let depth = 0;
|
||||
const token = /<form\b|<\/form>/g;
|
||||
token.lastIndex = match.index;
|
||||
let t: RegExpExecArray | null;
|
||||
let end = card.length;
|
||||
while ((t = token.exec(card)) !== null) {
|
||||
depth += t[0] === "</form>" ? -1 : 1;
|
||||
if (depth === 0) {
|
||||
end = t.index + t[0].length;
|
||||
break;
|
||||
}
|
||||
}
|
||||
rest += card.slice(cursor, match.index);
|
||||
forms.push(card.slice(match.index, end));
|
||||
cursor = end;
|
||||
}
|
||||
rest += card.slice(cursor);
|
||||
return [...forms, rest];
|
||||
}
|
||||
|
||||
/** Does any save unit of this card mix both models? */
|
||||
function mixesSaveModels(card: string, source: string = card): boolean {
|
||||
return splitSaveUnits(card).some(
|
||||
(unit) => savesInstantly(unit, source) && savesExplicitly(unit),
|
||||
);
|
||||
}
|
||||
|
||||
function savesExplicitly(unit: string): boolean {
|
||||
return /type="submit"/.test(unit) || /t\("common\.save"\)/.test(unit);
|
||||
}
|
||||
@@ -195,7 +243,7 @@ function scan() {
|
||||
const source = readFileSync(file, "utf8");
|
||||
splitCardUnits(source).forEach((unit, index) => {
|
||||
units++;
|
||||
if (savesInstantly(unit, source) && savesExplicitly(unit)) {
|
||||
if (mixesSaveModels(unit, source)) {
|
||||
const key = `${rel}#${index}`;
|
||||
if (!ALLOWLIST[key]) mixed.push(key);
|
||||
}
|
||||
@@ -231,6 +279,15 @@ describe("settings save model", () => {
|
||||
expect(savesInstantly(splitCardUnits(draftCard)[0])).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts an instant switch beside a form with its own Save, nothing looser", () => {
|
||||
const split = `<SettingsCard><Switch onCheckedChange={(v) => toggle.mutate(v)} /><form onSubmit={save}><Input /><Button type="submit">{t("common.save")}</Button></form></SettingsCard>`;
|
||||
const inside = `<SettingsCard><form onSubmit={save}><Switch onCheckedChange={(v) => toggle.mutate(v)} /><Button type="submit">{t("common.save")}</Button></form></SettingsCard>`;
|
||||
const formless = `<SettingsCard><Switch onCheckedChange={(v) => toggle.mutate(v)} /><Button onClick={save}>{t("common.save")}</Button></SettingsCard>`;
|
||||
expect(mixesSaveModels(split)).toBe(false);
|
||||
expect(mixesSaveModels(inside)).toBe(true);
|
||||
expect(mixesSaveModels(formless)).toBe(true);
|
||||
});
|
||||
|
||||
it("finds no card that mixes instant and explicit saving", () => {
|
||||
const { mixed, units, files } = scan();
|
||||
// An empty scan would pass for the wrong reason.
|
||||
@@ -248,9 +305,7 @@ describe("settings save model", () => {
|
||||
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,
|
||||
);
|
||||
expect(mixesSaveModels(unit, source), key).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user