Skip to content

Build your personal knowledge base with Trilium Notes

client: improve test coverage for option pages and some of their dependencies

Adorian Doran6f95155a1085
diff --git a/apps/client/src/widgets/react/Card.spec.tsx b/apps/client/src/widgets/react/Card.spec.tsx
new file mode 100644
index 0000000000..3c53fce65e
--- /dev/null
+++ b/apps/client/src/widgets/react/Card.spec.tsx
@@ -0,0 +1,128 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../test/render";
+import { Card, CardFrame, CardOption, CardSection } from "./Card";
+
+describe("Card", () => {
+ it("carries a heading, a sentence and controls of its own, and drops the heading line with nothing on it", () => {
+ const withHeading = renderInto(
+ <Card heading="Backups" description="How often a copy is taken." actions={<button>Add</button>}>
+ <CardSection>body</CardSection>
+ </Card>
+ );
+
+ expect(withHeading.querySelector(".tn-card-heading")?.textContent).toContain("Backups");
+ expect(withHeading.querySelector(".tn-card-heading-actions button")).not.toBeNull();
+ expect(withHeading.querySelector(".tn-card-description")?.textContent).toBe("How often a copy is taken.");
+
+ const bare = renderInto(<Card><CardSection>body</CardSection></Card>);
+ expect(bare.querySelector(".tn-card-heading")).toBeNull();
+ expect(bare.querySelector(".tn-card-body")).not.toBeNull();
+ });
+});
+
+describe("CardFrame", () => {
+ it("is a lone framed block, highlighting only when asked", () => {
+ const plain = renderInto(<CardFrame>held</CardFrame>).querySelector(".tn-card-frame");
+ expect(plain?.className).not.toContain("tn-card-highlight-on-hover");
+
+ const hoverable = renderInto(<CardFrame highlightOnHover>held</CardFrame>).querySelector(".tn-card-frame");
+ expect(hoverable?.className).toContain("tn-card-highlight-on-hover");
+ });
+});
+
+describe("CardSection", () => {
+ it("is a plain section, pressable when given something to do", () => {
+ const onAction = vi.fn();
+ const container = renderInto(<CardSection onAction={onAction}>held</CardSection>);
+ const section = container.querySelector("section");
+
+ expect(section?.className).toContain("tn-card-highlight-on-hover");
+ section?.click();
+ expect(onAction).toHaveBeenCalledTimes(1);
+ });
+
+ it("drops its padding on request, for a segment filled edge to edge", () => {
+ const section = renderInto(<CardSection noPadding>held</CardSection>).querySelector("section");
+ expect(section?.className).toContain("tn-no-padding");
+ });
+
+ it("shows what is nested beneath it only while that is asked for, marked a level deeper", () => {
+ const nested = <CardSection className="child">nested</CardSection>;
+
+ const hidden = renderInto(<CardSection subSections={[ nested ]}>parent</CardSection>);
+ expect(hidden.querySelector(".child")).toBeNull();
+
+ const shown = renderInto(<CardSection subSections={[ nested ]} subSectionsVisible>parent</CardSection>);
+ const child = shown.querySelector(".child");
+ expect(child?.className).toContain("tn-card-section-nested");
+ // The level drives the indent and the ground tint, so it has to say which one it is.
+ expect(child?.getAttribute("style")).toContain("--tn-card-section-nesting-level: 1");
+ });
+});
+
+describe("CardOption", () => {
+ it("ties the label to its control when named, and leaves it loose when not", () => {
+ const bound = renderInto(
+ <CardOption name="word-wrap" label="Word wrapping"><input type="checkbox" /></CardOption>
+ );
+ const input = bound.querySelector("input");
+ expect(bound.querySelector("label")?.getAttribute("for")).toBe(input?.id);
+ expect(input?.id).toBeTruthy();
+
+ // Nothing to point at: a set of buttons, not one control.
+ const loose = renderInto(
+ <CardOption label="Shortcut"><button>a</button><button>b</button></CardOption>
+ );
+ expect(loose.querySelector("label")?.getAttribute("for")).toBeNull();
+ });
+
+ it("keeps the sentence with the label, so the two read as one name", () => {
+ const container = renderInto(<CardOption label="Word wrapping" description="Wraps long lines." />);
+ const label = container.querySelector(".tn-card-option-label");
+
+ expect(label?.firstChild?.textContent).toBe("Word wrapping");
+ expect(label?.querySelector(".tn-card-option-description")?.textContent).toBe("Wraps long lines.");
+ });
+
+ it("puts the control on the line below when stacked", () => {
+ const inline = renderInto(<CardOption label="Address"><input /></CardOption>);
+ expect(inline.querySelector(".tn-card-option")?.className).not.toContain("tn-card-option-stacked");
+
+ const stacked = renderInto(<CardOption label="Address" stacked><input /></CardOption>);
+ expect(stacked.querySelector(".tn-card-option")?.className).toContain("tn-card-option-stacked");
+ });
+});
+
+describe("a segment that leads somewhere", () => {
+ it("becomes a link carrying a chevron, rather than a section", () => {
+ const container = renderInto(<CardOption label="Backup" href="#root/_hidden/_options/_optionsBackup" />);
+ const link = container.querySelector("a");
+
+ expect(container.querySelector("section")).toBeNull();
+ expect(link?.getAttribute("href")).toBe("#root/_hidden/_options/_optionsBackup");
+ expect(link?.className).toContain("tn-card-section-link");
+ // It leads somewhere, so it highlights under the pointer like any other pressable segment.
+ expect(link?.className).toContain("tn-card-highlight-on-hover");
+ // The note tooltip would otherwise open over a row that is only a way onwards.
+ expect(link?.className).toContain("no-tooltip-preview");
+ expect(link?.querySelector(".tn-card-section-chevron")).not.toBeNull();
+ });
+
+ it("hands its handler the event, which is what lets an entry navigate for itself", () => {
+ const onAction = vi.fn();
+ const container = renderInto(<CardOption label="Task states" href="#root/_hidden/_taskStates" onAction={onAction} />);
+
+ container.querySelector("a")?.click();
+ expect(onAction).toHaveBeenCalledTimes(1);
+ expect(onAction.mock.calls[0][0]).toBeInstanceOf(Event);
+ });
+
+ it("opts out of the dialog's contained navigation only when told to", () => {
+ const contained = renderInto(<CardOption label="Backup" href="#a" />);
+ expect(contained.querySelector("a")?.hasAttribute("data-no-contained-navigation")).toBe(false);
+
+ const own = renderInto(<CardOption label="Backup" href="#a" noContainedNavigation />);
+ expect(own.querySelector("a")?.hasAttribute("data-no-contained-navigation")).toBe(true);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/advanced.spec.tsx b/apps/client/src/widgets/type_widgets/options/advanced.spec.tsx
new file mode 100644
index 0000000000..fd5ff15539
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/advanced.spec.tsx
@@ -0,0 +1,109 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ features: [] as { id: string; name: string; description: string }[],
+ enabled: [] as string[],
+ saved: [] as string[][],
+ post: vi.fn(async (_url: string) => ({}))
+}));
+
+vi.mock("../../../services/experimental_features", () => ({
+ getAvailableExperimentalFeatures: () => mocks.features
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// Replacing the shared server mock means also answering what the modules pulled in alongside the
+// page ask for on import — the options load and the keyboard actions.
+vi.mock("../../../services/server", () => ({
+ default: {
+ post: mocks.post,
+ get: async (url: string) => (url === "keyboard-actions" ? [] : {})
+ }
+}));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: vi.fn(), showError: vi.fn() }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOptionJson: () => [ mocks.enabled, (value: string[]) => void mocks.saved.push(value) ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import AdvancedSettings from "./advanced";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.features = [
+ { id: "new-layout", name: "New layout", description: "…" },
+ { id: "llm", name: "AI", description: "…" },
+ { id: "spreadsheets", name: "Spreadsheets", description: "…" }
+ ];
+ mocks.enabled = [];
+ mocks.saved = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+function open() {
+ act(() => {
+ render(<AdvancedSettings />, host);
+ });
+}
+
+const cardHeadings = () => [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.textContent);
+const featureSwitches = () => [ ...host.querySelectorAll<HTMLInputElement>("input.switch-toggle") ];
+
+describe("the experimental features card", () => {
+ it("leaves out the features that are switched somewhere better suited to them", () => {
+ open();
+
+ // The layout has its own illustrated choice on Appearance, and the AI switch heads its own page.
+ expect(featureSwitches()).toHaveLength(1);
+ expect(host.querySelector(".tn-card-option-label")?.firstChild?.textContent).toBe("Spreadsheets");
+ });
+
+ it("stands down entirely when nothing is left to offer, rather than showing an empty card", () => {
+ mocks.features = [ { id: "llm", name: "AI", description: "…" } ];
+ open();
+
+ expect(cardHeadings()).toEqual([ "sync.title" ]);
+ });
+
+ it("adds a feature to the set it is turned on in, and takes it back out again", () => {
+ open();
+ act(() => void featureSwitches()[0].dispatchEvent(new Event("input", { bubbles: true })));
+ expect(mocks.saved.at(-1)).toEqual([ "spreadsheets" ]);
+
+ mocks.enabled = [ "spreadsheets" ];
+ open();
+ act(() => void featureSwitches()[0].dispatchEvent(new Event("input", { bubbles: true })));
+ expect(mocks.saved.at(-1)).toEqual([]);
+ });
+});
+
+describe("the advanced sync actions", () => {
+ it("asks the server for each of the two repairs it offers", async () => {
+ open();
+
+ const [ forceSync, fillChanges ] = [ ...host.querySelectorAll<HTMLButtonElement>(".tn-card-option button") ];
+ await act(async () => forceSync.click());
+ await act(async () => fillChanges.click());
+
+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([
+ "sync/force-full-sync",
+ "sync/fill-entity-changes"
+ ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
new file mode 100644
index 0000000000..156515dc02
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/appearance.spec.tsx
@@ -0,0 +1,140 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ electron: true,
+ mobile: false,
+ stored: {} as Record<string, string | boolean>
+}));
+
+// Both the desktop card and the illustrated layout choices turn on which kind of client this is.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isElectron: () => mocks.electron,
+ isMobile: () => mocks.mobile,
+ reloadFrontendApp: vi.fn(),
+ restartDesktopApp: vi.fn()
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// The theme card asks for the user's own themes as it mounts, and renders straight from the answer —
+// an unanswered request leaves it reading `undefined`, which throws mid-render.
+vi.mock("../../../services/server", () => ({
+ default: {
+ get: async (url: string) => (url === "options/user-themes" || url === "keyboard-actions" ? [] : {}),
+ post: async () => ({}),
+ put: async () => ({}),
+ remove: async () => ({})
+ }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: (name: string) => [ String(mocks.stored[name] ?? ""), vi.fn() ],
+ useTriliumOptionBool: (name: string) => [ mocks.stored[name] === true, vi.fn() ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import AppearanceSettings from "./appearance";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.electron = true;
+ mocks.mobile = false;
+ mocks.stored = {};
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+});
+
+/**
+ * Opens the page fresh. The tree is torn down first so that a scenario changing a setting and
+ * reopening gets a clean mount, rather than a diff against what the previous values rendered.
+ */
+function open() {
+ act(() => {
+ render(null, host);
+ render(<AppearanceSettings />, host);
+ });
+}
+
+const fontRows = () => [ ...host.querySelectorAll(".font-option") ];
+
+describe("the font settings", () => {
+ it("keeps the fonts on show with custom fonts off, greyed rather than gone", () => {
+ open();
+
+ // What turning the switch on would put in force is the whole reason for turning it on.
+ expect(fontRows()).toHaveLength(4);
+ expect(fontRows().every((row) => row.className.includes("disabled"))).toBe(true);
+ });
+
+ it("brings them within reach once custom fonts are on", () => {
+ mocks.stored = { overrideThemeFonts: true };
+ open();
+
+ expect(fontRows()).toHaveLength(4);
+ expect(fontRows().some((row) => row.className.includes("disabled"))).toBe(false);
+ });
+
+ it("nests them under the switch that governs them", () => {
+ open();
+ expect(fontRows().every((row) => row.className.includes("tn-card-section-nested"))).toBe(true);
+ });
+
+ it("leaves ligatures alone, since they come from the theme's own font", () => {
+ open();
+
+ // Not nested under custom fonts: the setting is needed exactly when those are off.
+ const ligatures = host.querySelector("input.switch-toggle[id^='monospace-ligatures-enabled-']");
+ expect(ligatures?.closest(".tn-card-option")?.className).not.toContain("tn-card-section-nested");
+ expect((ligatures as HTMLInputElement | null)?.disabled).toBe(false);
+ });
+});
+
+describe("the layout choices", () => {
+ it("gives each an illustrated card of its own, side by side", () => {
+ open();
+
+ const cards = [ ...host.querySelectorAll(".appearance-layout-choices .tn-card") ];
+ expect(cards).toHaveLength(2);
+ expect(cards.every((card) => card.className.includes("thumbnail-selector-option-card"))).toBe(true);
+ expect(host.querySelectorAll(".appearance-layout-choices .radio-with-illustration")).toHaveLength(2);
+ });
+
+ it("offers neither on a phone, where the window has no shape to choose", () => {
+ mocks.mobile = true;
+ open();
+
+ expect(host.querySelector(".appearance-layout-choices")).toBeNull();
+ });
+
+ it("offers the ribbon setting only on the old layout, which is the only one that has one", () => {
+ open();
+ expect(host.querySelector("input.switch-toggle[id^='edited-notes-open-in-ribbon-']")).not.toBeNull();
+
+ mocks.stored = { newLayout: true };
+ open();
+ expect(host.querySelector("input.switch-toggle[id^='edited-notes-open-in-ribbon-']")).toBeNull();
+ });
+});
+
+describe("the desktop-only settings", () => {
+ it("are offered with the way to apply them, and neither is on a server build", () => {
+ open();
+ expect(host.querySelector(".appearance-electron")).not.toBeNull();
+ expect(host.querySelector(".restart-action")).not.toBeNull();
+
+ mocks.electron = false;
+ open();
+ expect(host.querySelector(".appearance-electron")).toBeNull();
+ expect(host.querySelector(".restart-action")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/backup.options.spec.tsx b/apps/client/src/widgets/type_widgets/options/backup.options.spec.tsx
new file mode 100644
index 0000000000..4a6c6aeec8
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/backup.options.spec.tsx
@@ -0,0 +1,203 @@
+import type { BackupPassphraseStatus } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ /** What the OS keyring reports: whether there is one, and whether it holds a passphrase. */
+ passphrase: { available: true, set: false } as BackupPassphraseStatus,
+ /** What the keyring answers when asked to store or forget one. */
+ setResult: "applied" as string,
+ clearResult: "applied" as string,
+ /** Whether the encryption option actually reached the server, read back after each write. */
+ encryptionStored: false,
+ stored: {} as Record<string, boolean>,
+ saved: [] as [ string, boolean ][],
+ showMessage: vi.fn(),
+ showError: vi.fn()
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: mocks.showError }
+}));
+
+// The page re-reads the option straight from the store after writing it, to catch a save that was
+// swallowed — which is the difference between "encrypted" and "quietly in the clear".
+vi.mock("../../../services/options", () => ({
+ default: { is: () => mocks.encryptionStored }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === true,
+ async (value: boolean) => void mocks.saved.push([ name, value ])
+ ]
+}));
+
+import { BackupOptions } from "./backup";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.passphrase = { available: true, set: false };
+ mocks.setResult = "applied";
+ mocks.clearResult = "applied";
+ mocks.encryptionStored = false;
+ mocks.stored = {};
+ mocks.saved = [];
+ (window as unknown as { electronApi: unknown }).electronApi = {
+ backupPassphrase: {
+ getStatus: async () => mocks.passphrase,
+ set: async () => mocks.setResult,
+ clear: async () => mocks.clearResult
+ }
+ };
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ delete (window as unknown as { electronApi?: unknown }).electronApi;
+ vi.clearAllMocks();
+});
+
+async function open() {
+ await act(async () => {
+ render(null, host);
+ render(<BackupOptions />, host);
+ });
+ // The keyring is asked what it holds as the card mounts.
+ await act(async () => {});
+}
+
+const button = (name: string) => host.querySelector<HTMLButtonElement>(`button[name='${name}']`);
+const encryptionRow = () => host.querySelector(".tn-card-option");
+
+describe("what the encryption controls offer", () => {
+ it("holds the whole feature out of reach without a keyring to keep the passphrase in", async () => {
+ mocks.passphrase = { available: false, set: false };
+ await open();
+
+ expect(button("turn-on-backup-encryption-button")?.disabled).toBe(true);
+ expect(encryptionRow()?.querySelector(".tn-card-option-description")?.textContent).toBe("backup.no_keyring");
+ });
+
+ it("offers to set a passphrase where there is a keyring but nothing in it yet", async () => {
+ await open();
+
+ expect(button("turn-on-backup-encryption-button")?.disabled).toBe(false);
+ expect(button("change-backup-password-button")).toBeNull();
+ // Nothing to switch on until there is a passphrase to switch it on with.
+ expect(host.querySelector("input.switch-toggle[id^='backup-compression']")).not.toBeNull();
+ });
+
+ it("offers to replace the passphrase, and a switch, once one is held", async () => {
+ mocks.passphrase = { available: true, set: true };
+ await open();
+
+ expect(button("change-backup-password-button")).not.toBeNull();
+ expect(button("turn-on-backup-encryption-button")).toBeNull();
+ });
+});
+
+describe("storing a passphrase", () => {
+ /** Types a password into the dialog twice over and saves it, which is what the card acts on. */
+ async function savePassword(password = "hunter2") {
+ await act(async () => button("turn-on-backup-encryption-button")?.click());
+
+ const boxes = [ ...document.querySelectorAll<HTMLInputElement>(".backup-password-modal input[type='password']") ];
+ for (const box of boxes) {
+ await act(async () => {
+ box.value = password;
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+
+ await act(async () => {
+ document.querySelector<HTMLFormElement>(".backup-password-modal form")?.requestSubmit();
+ });
+ await act(async () => {});
+ }
+
+ it("turns encryption on and says so once the keyring has taken the passphrase", async () => {
+ mocks.encryptionStored = true;
+ await open();
+ await savePassword();
+
+ expect(mocks.saved).toContainEqual([ "backupEnableEncryption", true ]);
+ expect(mocks.showMessage).toHaveBeenCalledWith("backup.password_stored");
+ });
+
+ it("says nothing at all when the user declines the OS confirmation", async () => {
+ mocks.setResult = "cancelled";
+ await open();
+ await savePassword();
+
+ expect(mocks.saved).toEqual([]);
+ expect(mocks.showError).not.toHaveBeenCalled();
+ expect(mocks.showMessage).not.toHaveBeenCalled();
+ });
+
+ it("reports a keyring that would not take it, and leaves encryption off", async () => {
+ mocks.setResult = "failed";
+ await open();
+ await savePassword();
+
+ expect(mocks.saved).toEqual([]);
+ expect(mocks.showError).toHaveBeenCalledWith("backup.password_not_stored");
+ });
+
+ it("warns when the passphrase was kept but the setting never reached the server", async () => {
+ // Otherwise the next backup goes out in the clear under the belief that it is encrypted.
+ mocks.encryptionStored = false;
+ await open();
+ await savePassword();
+
+ expect(mocks.showError).toHaveBeenCalledWith("backup.encryption_not_enabled");
+ expect(mocks.showMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe("turning encryption off", () => {
+ beforeEach(() => {
+ mocks.passphrase = { available: true, set: true };
+ mocks.stored = { backupEnableEncryption: true };
+ });
+
+ /** Flips the encryption switch, which is the one beside the change-password button. */
+ async function flipOff() {
+ const toggle = host.querySelector<HTMLInputElement>(".tn-card-option input.switch-toggle");
+ await act(async () => void toggle?.dispatchEvent(new Event("input", { bubbles: true })));
+ await act(async () => {});
+ }
+
+ it("forgets the passphrase along with the setting, there being nothing left to keep it for", async () => {
+ await open();
+ await flipOff();
+
+ expect(mocks.saved).toContainEqual([ "backupEnableEncryption", false ]);
+ expect(mocks.showError).not.toHaveBeenCalled();
+ });
+
+ it("leaves the setting alone when the OS confirmation is declined", async () => {
+ mocks.clearResult = "cancelled";
+ await open();
+ await flipOff();
+
+ expect(mocks.saved).toEqual([]);
+ });
+
+ it("warns when the passphrase is gone but the setting stayed on", async () => {
+ // The passphrase is already forgotten by this point, so a backup believed encrypted would
+ // quietly fall back to an unencrypted one with nothing on the page to explain why.
+ mocks.encryptionStored = true;
+ await open();
+ await flipOff();
+
+ expect(mocks.showError).toHaveBeenCalledWith("backup.encryption_not_disabled");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/backup.page.spec.tsx b/apps/client/src/widgets/type_widgets/options/backup.page.spec.tsx
new file mode 100644
index 0000000000..e152c4b5a7
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/backup.page.spec.tsx
@@ -0,0 +1,156 @@
+import type { ExistingBackupsResponse } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ /** Whether this build keeps backups as files, or hands one over as a download. */
+ downloadSupported: false,
+ backups: { backups: [], backupFolderPath: "/data/backups" } as ExistingBackupsResponse,
+ stored: {} as Record<string, boolean>,
+ saved: [] as [ string, boolean ][],
+ post: vi.fn(async (_url: string) => ({ backupFile: "/data/backups/now.db" })),
+ showMessage: vi.fn()
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../services/backup_download", () => ({
+ isBackupDownloadSupported: () => mocks.downloadSupported,
+ backUpAndDownload: vi.fn()
+}));
+
+// Replacing the shared server mock means also answering what the modules pulled in alongside the
+// page ask for on import — the keyboard actions, which expect a list.
+vi.mock("../../../services/server", () => ({
+ default: {
+ get: async (url: string) => {
+ if (url === "database/backups") return mocks.backups;
+ if (url === "keyboard-actions") return [];
+ return {};
+ },
+ post: mocks.post
+ }
+}));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: vi.fn() }
+}));
+
+vi.mock("../../../services/database_files", () => ({
+ summarizeBackups: (backups: unknown[]) => `summary:${backups.length}`,
+ describeDatabaseFile: () => "12 MB, yesterday",
+ describeDatabaseFormat: () => "SQLite"
+}));
+
+vi.mock("../../../services/setup_mode", () => ({
+ canBootToSetup: () => false,
+ bootToSetup: vi.fn()
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === true,
+ (value: boolean) => void mocks.saved.push([ name, value ])
+ ],
+ useStaticTooltip: vi.fn()
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({
+ default: ({ below }: { below?: preact.ComponentChildren }) => <div className="header-stub">{below}</div>
+}));
+
+import BackupSettings from "./backup";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.downloadSupported = false;
+ mocks.backups = { backups: [], backupFolderPath: "/data/backups" } as ExistingBackupsResponse;
+ mocks.stored = {};
+ mocks.saved = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+async function open() {
+ await act(async () => {
+ render(null, host);
+ render(<BackupSettings />, host);
+ });
+ // The stored backups are fetched as the page mounts.
+ await act(async () => {});
+}
+
+describe("which page a build gets", () => {
+ it("lists the backups kept as files, wherever there are any to keep", async () => {
+ await open();
+
+ expect(host.querySelector(".header-stub")?.textContent).toContain("summary:0");
+ expect(host.querySelector("button[name='backup-database-now-button']")).not.toBeNull();
+ });
+
+ it("reduces to the one backup it can take, where none are kept at all", async () => {
+ mocks.downloadSupported = true;
+ await open();
+
+ // Nothing to list and nowhere to list it: the browser build streams a copy on request.
+ expect(host.querySelector(".standalone-backup")).not.toBeNull();
+ expect(host.querySelector("button[name='backup-database-now-button']")).toBeNull();
+ });
+
+ it("leaves out the folder card where there is no location anyone could open", async () => {
+ mocks.backups = { backups: [], backupFolderPath: null } as unknown as ExistingBackupsResponse;
+ await open();
+
+ // Backups kept in OPFS, say: real enough, but with no path to reveal.
+ expect(host.querySelector(".backup-location")).toBeNull();
+ });
+});
+
+describe("taking a backup now", () => {
+ it("says where the copy was written, and re-reads the list it was added to", async () => {
+ await open();
+
+ const button = host.querySelector<HTMLButtonElement>("button[name='backup-database-now-button']");
+ await act(async () => button?.click());
+ await act(async () => {});
+
+ expect(mocks.post).toHaveBeenCalledWith("database/backup-database");
+ expect(mocks.showMessage).toHaveBeenCalledWith(
+ expect.stringContaining("backup.database_backed_up_to"),
+ expect.any(Number)
+ );
+ });
+
+ it("holds the button while one is being written, so a second is not asked for", async () => {
+ // Never settles, which is what being mid-backup looks like.
+ mocks.post.mockImplementationOnce(() => new Promise(() => ({ backupFile: "" })));
+ await open();
+
+ const button = () => host.querySelector<HTMLButtonElement>("button[name='backup-database-now-button']");
+ await act(async () => button()?.click());
+
+ expect(button()?.disabled).toBe(true);
+ });
+});
+
+describe("the automatic backups", () => {
+ it("offers one switch per interval, each writing back to its own setting", async () => {
+ mocks.stored = { dailyBackupEnabled: true };
+ await open();
+
+ const toggles = [ ...host.querySelectorAll<HTMLInputElement>(".backup-configuration input.switch-toggle") ];
+ expect(toggles).toHaveLength(3);
+ expect(toggles.map((toggle) => toggle.checked)).toEqual([ true, false, false ]);
+
+ await act(async () => void toggles[1].dispatchEvent(new Event("input", { bubbles: true })));
+ expect(mocks.saved).toContainEqual([ "weeklyBackupEnabled", true ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsx b/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsx
new file mode 100644
index 0000000000..666c62a369
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/code_mime_types_list.spec.tsx
@@ -0,0 +1,115 @@
+import type { Tooltip } from "bootstrap";
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../test/render";
+
+const mocks = vi.hoisted(() => ({
+ stored: [] as string[],
+ saved: [] as string[][],
+ /** The tooltip config the list hands the hook, so its title callback can be asked directly. */
+ tooltipConfig: undefined as Partial<Tooltip.Options> | undefined
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../services/mime_types", () => ({
+ default: {
+ loadMimeTypes: () => {},
+ getMimeTypes: () => [
+ { mime: "text/plain", title: "Plain text", enabled: true },
+ { mime: "application/javascript;env=frontend", title: "JavaScript", enabled: true },
+ { mime: "text/x-csrc", title: "C", enabled: false },
+ { mime: "text/x-java", title: "Java", enabled: false }
+ ]
+ }
+}));
+
+// Which languages each highlighter knows: what the tooltip reports per row.
+vi.mock("@triliumnext/highlightjs/src/syntax_highlighting", () => ({
+ byMimeType: { "application/javascript;env=frontend": {} }
+}));
+
+vi.mock("@triliumnext/codemirror/src/syntax_highlighting", () => ({
+ default: { "application/javascript;env=frontend": {}, "text/x-java": {} }
+}));
+
+// Captured rather than stubbed away: the callback it holds is what these cases read.
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useStaticTooltip: (_ref: unknown, config: Partial<Tooltip.Options>) => {
+ mocks.tooltipConfig = config;
+ },
+ useTriliumOptionJson: () => [ mocks.stored, (value: string[]) => void mocks.saved.push(value) ]
+}));
+
+import { CodeMimeTypesList } from "./code_mime_types_list";
+
+/** Asks the tooltip what it would say over the row holding the given MIME type. */
+function tooltipFor(container: HTMLElement, mime: string) {
+ const label = [ ...container.querySelectorAll<HTMLElement>("label") ]
+ .find((candidate) => candidate.querySelector("input")?.value === mime);
+ const title = mocks.tooltipConfig?.title;
+
+ return typeof title === "function" && label ? title.call(label) : undefined;
+}
+
+describe("the code MIME type list", () => {
+ it("files each language under its initial, with plain text kept apart and out of reach", () => {
+ mocks.stored = [ "text/plain" ];
+ const container = renderInto(<CodeMimeTypesList />);
+
+ // The first group carries no heading: plain text is not filed under a letter.
+ const headings = [ ...container.querySelectorAll("h5") ].map((heading) => heading.textContent);
+ expect(headings).toEqual([ "C", "J" ]);
+
+ const plainText = [ ...container.querySelectorAll<HTMLInputElement>("input") ]
+ .find((box) => box.value === "text/plain");
+ expect(plainText?.checked).toBe(true);
+ // It cannot be turned off: a code note has to be able to fall back to something.
+ expect(plainText?.disabled).toBe(true);
+ });
+
+ it("sorts the languages by name rather than leaving them in the order they arrived", () => {
+ const container = renderInto(<CodeMimeTypesList />);
+ const titles = [ ...container.querySelectorAll("label") ]
+ .map((label) => label.textContent?.trim())
+ .filter((title) => title !== "Plain text");
+
+ expect(titles).toEqual([ ...titles ].sort((a, b) => (a ?? "").localeCompare(b ?? "")));
+ });
+
+ it("takes back what was ticked, keeping what was already there", () => {
+ mocks.stored = [ "text/x-java" ];
+ mocks.saved = [];
+ const container = renderInto(<CodeMimeTypesList />);
+
+ const c = [ ...container.querySelectorAll<HTMLInputElement>("input") ].find((box) => box.value === "text/x-csrc");
+ c?.dispatchEvent(new Event("change", { bubbles: true }));
+
+ expect(mocks.saved.at(-1)).toEqual([ "text/x-java", "text/x-csrc" ]);
+ });
+});
+
+describe("what the tooltip says about a language", () => {
+ it("reports each highlighter separately, since a language may be known to only one", () => {
+ const container = renderInto(<CodeMimeTypesList />);
+
+ // Known to both.
+ expect(tooltipFor(container, "application/javascript;env=frontend")).toContain("✅");
+ expect(tooltipFor(container, "application/javascript;env=frontend")).not.toContain("❌");
+
+ // Known to the code editor but not to the code-block highlighter.
+ const java = tooltipFor(container, "text/x-java");
+ expect(java).toContain("✅");
+ expect(java).toContain("❌");
+
+ // Known to neither.
+ expect(tooltipFor(container, "text/x-csrc")).not.toContain("✅");
+ });
+
+ it("says nothing at all over plain text, which is not highlighted by anything", () => {
+ const container = renderInto(<CodeMimeTypesList />);
+
+ expect(tooltipFor(container, "text/plain")).toBe("");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/code_notes.spec.tsx b/apps/client/src/widgets/type_widgets/options/code_notes.spec.tsx
new file mode 100644
index 0000000000..1588c74de0
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/code_notes.spec.tsx
@@ -0,0 +1,133 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ stored: {} as Record<string, string | boolean>,
+ saved: [] as [ string, string | boolean ][],
+ colorScheme: "light" as "light" | "dark"
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// The preview instantiates the real editor, which happy-dom has no layout for; the settings around
+// it are what these cases read.
+vi.mock("@triliumnext/codemirror", () => ({
+ default: class {
+ setText() {}
+ setMimeType() {}
+ setLineWrapping() {}
+ setIndentSize() {}
+ setTheme() {}
+ destroy() {}
+ },
+ ColorThemes: [
+ { id: "one-light", name: "One Light", variant: "light" },
+ { id: "solarized", name: "Solarized", variant: "light" },
+ { id: "one-dark", name: "One Dark", variant: "dark" }
+ ],
+ getThemeById: (id: string) => ({ id })
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useColorScheme: () => mocks.colorScheme,
+ useTriliumOption: (name: string) => [
+ String(mocks.stored[name] ?? ""),
+ (value: string) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === true,
+ (value: boolean) => void mocks.saved.push([ name, value ])
+ ],
+ // The MIME type list at the foot of the page reads its set as JSON and hangs a delegated
+ // tooltip off it; neither is what these cases are about.
+ useTriliumOptionJson: () => [ [], vi.fn() ],
+ useStaticTooltip: vi.fn()
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import CodeNoteSettings from "./code_notes";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.stored = { codeNoteTabWidth: "4" };
+ mocks.saved = [];
+ mocks.colorScheme = "light";
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+});
+
+function open() {
+ act(() => {
+ render(null, host);
+ render(<CodeNoteSettings />, host);
+ });
+}
+
+const optionLabels = () =>
+ [ ...host.querySelectorAll(".tn-card-option-label") ].map((label) => label.firstChild?.textContent);
+const selects = () => [ ...host.querySelectorAll<HTMLSelectElement>("select") ];
+
+describe("the code note theme", () => {
+ it("asks for one theme when it is not to follow the app, and for a pair when it is", () => {
+ open();
+ expect(optionLabels()).toContain("code_theme.color-scheme");
+ expect(optionLabels()).not.toContain("code_theme.light_theme");
+
+ mocks.stored = { ...mocks.stored, codeNoteThemeMatchesApp: true };
+ open();
+ expect(optionLabels()).not.toContain("code_theme.color-scheme");
+ expect(optionLabels()).toEqual(expect.arrayContaining([ "code_theme.light_theme", "code_theme.dark_theme" ]));
+ });
+
+ it("offers each list only the themes of its own kind, and every theme to the single choice", () => {
+ open();
+ // The one fixed choice: light and dark alike.
+ expect(selects()[0].querySelectorAll("option")).toHaveLength(3);
+
+ mocks.stored = { ...mocks.stored, codeNoteThemeMatchesApp: true };
+ open();
+ const [ light, dark ] = selects();
+ expect(light.querySelectorAll("option")).toHaveLength(2);
+ expect(dark.querySelectorAll("option")).toHaveLength(1);
+ });
+
+ it("writes the theme back to the option the list stands for", () => {
+ open();
+
+ act(() => {
+ const select = selects()[0];
+ select.value = "default:one-dark";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+
+ expect(mocks.saved).toContainEqual([ "codeNoteTheme", "default:one-dark" ]);
+ });
+});
+
+describe("the code note editor settings", () => {
+ it("shows the preview as its own segment, filling it edge to edge", () => {
+ open();
+
+ const preview = host.querySelector(".code-note-preview");
+ expect(preview?.className).toContain("tn-no-padding");
+ expect(preview?.querySelector(".note-detail-readonly-code-content")).not.toBeNull();
+ });
+
+ it("keeps word wrapping on the editor card, where it belongs with the rest of the editing settings", () => {
+ open();
+
+ const wrap = host.querySelector<HTMLInputElement>("input.switch-toggle[id^='word-wrap-']");
+ expect(wrap).not.toBeNull();
+
+ act(() => void wrap?.dispatchEvent(new Event("input", { bubbles: true })));
+ expect(mocks.saved).toContainEqual([ "codeLineWrapEnabled", true ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/AutoReadOnlySize.tsx b/apps/client/src/widgets/type_widgets/options/components/AutoReadOnlySize.tsx
deleted file mode 100644
index b2d2ea42fe..0000000000
--- a/apps/client/src/widgets/type_widgets/options/components/AutoReadOnlySize.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import { OptionNames } from "@triliumnext/commons";
-import FormText from "../../../react/FormText";
-import { FormTextBoxWithUnit } from "../../../react/FormTextBox";
-import OptionsSection from "./OptionsSection";
-import { useTriliumOption } from "../../../react/hooks";
-import { t } from "../../../../services/i18n";
-import FormGroup from "../../../react/FormGroup";
-
-interface AutoReadOnlySizeProps {
- label: string;
- option: OptionNames;
-}
-
-export default function AutoReadOnlySize({ label, option }: AutoReadOnlySizeProps) {
- const [ autoReadonlyOpt, setAutoReadonlyOpt ] = useTriliumOption(option);
-
- return (
- <OptionsSection title={t("text_auto_read_only_size.title")}>
- <FormText>{t("text_auto_read_only_size.description")}</FormText>
-
- <FormGroup name="auto-readonly-size-text" label={label}>
- <FormTextBoxWithUnit
- type="number" min={0}
- unit={t("text_auto_read_only_size.unit")}
- currentValue={autoReadonlyOpt} onChange={setAutoReadonlyOpt}
- />
- </FormGroup>
- </OptionsSection>
- )
-}
\ No newline at end of file
diff --git a/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.spec.tsx
new file mode 100644
index 0000000000..0c6b339a47
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/DatabaseFileList.spec.tsx
@@ -0,0 +1,95 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../../test/render";
+
+const mocks = vi.hoisted(() => ({
+ download: vi.fn(),
+ getUrlForDownload: vi.fn((url: string) => `resolved:${url}`)
+}));
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../../services/open", () => ({
+ default: { download: mocks.download, getUrlForDownload: mocks.getUrlForDownload }
+}));
+
+// The line under each file states its size and age; neither is what these cases are reading.
+vi.mock("../../../../services/database_files", () => ({
+ describeDatabaseFile: () => "12 MB, yesterday"
+}));
+
+vi.mock("../../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../react/hooks")>()),
+ useStaticTooltip: vi.fn()
+}));
+
+import DatabaseFileList from "./DatabaseFileList";
+
+const FILES = [
+ { fileName: "older.db", filePath: "/backups/older.db", mtime: new Date(1000), fileSize: 10 },
+ { fileName: "newest.db", filePath: "/backups/newest.db", mtime: new Date(3000), fileSize: 30 },
+ { fileName: "middle.db", filePath: "/backups/middle.db", mtime: new Date(2000), fileSize: 20 }
+];
+
+function list(files = FILES, extra: Record<string, unknown> = {}) {
+ return renderInto(
+ <DatabaseFileList
+ title="backup.title"
+ files={files}
+ downloadEndpoint="database/download-backup"
+ downloadText="backup.download"
+ emptyIcon="bx bx-data"
+ emptyText="backup.no_backups"
+ {...extra}
+ />
+ );
+}
+
+const fileNames = (container: HTMLElement) =>
+ [ ...container.querySelectorAll(".selectable-text") ].map((name) => name.textContent);
+
+describe("DatabaseFileList", () => {
+ it("puts the newest first, which is the one anyone is looking for", () => {
+ expect(fileNames(list())).toEqual([ "newest.db", "middle.db", "older.db" ]);
+ });
+
+ it("says there are none rather than showing an empty card", () => {
+ const container = list([]);
+
+ expect(container.querySelector(".no-items")).not.toBeNull();
+ expect(fileNames(container)).toEqual([]);
+ });
+
+ it("downloads the file it was pressed on, by path rather than by name", () => {
+ const [ download ] = [ ...list().querySelectorAll<HTMLButtonElement>("button") ];
+ download.click();
+
+ // Encoded, since a path may hold characters a query string would otherwise end on.
+ expect(mocks.getUrlForDownload).toHaveBeenCalledWith(
+ "database/download-backup?filePath=%2Fbackups%2Fnewest.db"
+ );
+ expect(mocks.download).toHaveBeenCalledWith("resolved:database/download-backup?filePath=%2Fbackups%2Fnewest.db");
+ });
+
+ it("offers removal only where the list has somewhere to remove to", () => {
+ expect(list().querySelectorAll("button")).toHaveLength(3);
+
+ const onDelete = vi.fn();
+ const withDelete = list(FILES, { onDelete });
+ expect(withDelete.querySelectorAll("button")).toHaveLength(6);
+
+ const remove = [ ...withDelete.querySelectorAll<HTMLButtonElement>("button") ][1];
+ expect(remove.className).toContain("destructive-action-icon");
+ remove.click();
+ expect(onDelete).toHaveBeenCalledWith(FILES[1]);
+ });
+
+ it("marks a file with whatever the list has to say about it", () => {
+ const container = list(FILES, {
+ fileBadges: (file: { fileName: string }) =>
+ (file.fileName === "newest.db" ? [ { text: "backup.latest" } ] : [])
+ });
+
+ expect(container.querySelectorAll(".ext-badge")).toHaveLength(1);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.spec.tsx
new file mode 100644
index 0000000000..035418c3e6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/OptionsPageHeader.spec.tsx
@@ -0,0 +1,62 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../../test/render";
+
+const mocks = vi.hoisted(() => ({
+ note: undefined as { title: string; getIcon: () => string } | undefined
+}));
+
+vi.mock("../../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../react/hooks")>()),
+ useNoteContext: () => ({ note: mocks.note })
+}));
+
+import OptionsPageHeader from "./OptionsPageHeader";
+
+const NOTE = { title: "Appearance", getIcon: () => "bx bx-palette" };
+
+describe("OptionsPageHeader", () => {
+ it("names the page and shows the icon the note carries", () => {
+ mocks.note = NOTE;
+ const container = renderInto(<OptionsPageHeader />);
+
+ expect(container.querySelector(".options-page-header-title")?.textContent).toBe("Appearance");
+ expect(container.querySelector(".options-page-header-icon")?.className).toContain("bx-palette");
+ });
+
+ it("marks itself as carrying nothing but the name, which a phone shows elsewhere", () => {
+ mocks.note = NOTE;
+ const bare = renderInto(<OptionsPageHeader />);
+ expect(bare.querySelector(".options-page-header")?.className).toContain("options-page-header-title-only");
+
+ // Once it carries something of the page's own it is a band in its own right.
+ const withActions = renderInto(<OptionsPageHeader actions={<button>Reset</button>} />);
+ expect(withActions.querySelector(".options-page-header")?.className)
+ .not.toContain("options-page-header-title-only");
+ });
+
+ it("keeps the page's own controls on the title row and its second row beneath", () => {
+ mocks.note = NOTE;
+ const container = renderInto(
+ <OptionsPageHeader actions={<button name="reset">Reset</button>} below={<input name="filter" />} />
+ );
+
+ expect(container.querySelector(".options-page-header-actions button[name='reset']")).not.toBeNull();
+ expect(container.querySelector(".options-page-header-below input[name='filter']")).not.toBeNull();
+ });
+
+ it("offers page-level help beside the name, told apart from the name it stands next to", () => {
+ mocks.note = NOTE;
+ const container = renderInto(<OptionsPageHeader helpUrl="cbkrhQjrkKrh" />);
+
+ expect(container.querySelector(".options-page-header-help")).not.toBeNull();
+ });
+
+ it("renders nothing at all before the note has arrived and with nothing else to show", () => {
+ mocks.note = undefined;
+ expect(renderInto(<OptionsPageHeader />).innerHTML).toBe("");
+
+ // ...but a page that feeds it controls still gets its band, note or no note.
+ expect(renderInto(<OptionsPageHeader below={<input />} />).innerHTML).not.toBe("");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/RelatedSettings.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/RelatedSettings.spec.tsx
new file mode 100644
index 0000000000..5762d57f6a
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/RelatedSettings.spec.tsx
@@ -0,0 +1,79 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../../test/render";
+
+const mocks = vi.hoisted(() => ({ triggerCommand: vi.fn() }));
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../../components/app_context", () => ({
+ default: { triggerCommand: mocks.triggerCommand }
+}));
+
+import RelatedSettings from "./RelatedSettings";
+
+const links = (container: HTMLElement) => [ ...container.querySelectorAll<HTMLAnchorElement>("a.tn-card-section-link") ];
+
+describe("RelatedSettings", () => {
+ it("stands down entirely when nothing is left to point at", () => {
+ const container = renderInto(
+ <RelatedSettings items={[ { title: "Backup", targetPage: "_optionsBackup", enabled: false } ]} />
+ );
+
+ expect(container.innerHTML).toBe("");
+ });
+
+ it("leaves out the entries that do not apply here, and keeps the rest", () => {
+ const container = renderInto(
+ <RelatedSettings items={[
+ { title: "Backup", targetPage: "_optionsBackup" },
+ { title: "Spellcheck", targetPage: "_optionsSpellcheck", enabled: false }
+ ]} />
+ );
+
+ expect(links(container)).toHaveLength(1);
+ expect(links(container)[0].getAttribute("href")).toBe("#root/_hidden/_options/_optionsBackup");
+ });
+
+ it("takes its own heading when the entries are something other than related settings", () => {
+ const withDefault = renderInto(<RelatedSettings items={[ { title: "Backup", targetPage: "_optionsBackup" } ]} />);
+ expect(withDefault.querySelector(".tn-card-heading")?.textContent).toBe("settings.related_settings");
+
+ const named = renderInto(
+ <RelatedSettings title="settings.related_actions" items={[ { title: "Space usage", targetPage: "_optionsContentManager" } ]} />
+ );
+ expect(named.querySelector(".tn-card-heading")?.textContent).toBe("settings.related_actions");
+ });
+
+ it("points a hidden-subtree entry at the note itself, and opens it rather than following the link", () => {
+ const container = renderInto(<RelatedSettings items={[ { title: "Task states", targetNoteId: "_taskStates" } ]} />);
+ const [ link ] = links(container);
+
+ expect(link.getAttribute("href")).toBe("#root/_hidden/_taskStates");
+ // It navigates for itself, so the dialog's own link handling has to stand aside.
+ expect(link.hasAttribute("data-no-contained-navigation")).toBe(true);
+
+ link.click();
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("openInTreePopup", {
+ noteIdOrPath: "_taskStates",
+ hoistedNoteId: "_taskStates"
+ });
+ });
+
+ it("lets an entry with something of its own to do handle the press, link and all", () => {
+ const onClick = vi.fn();
+ const container = renderInto(
+ <RelatedSettings items={[ { title: "Space usage", targetPage: "_optionsContentManager", onClick } ]} />
+ );
+ const [ link ] = links(container);
+
+ expect(link.hasAttribute("data-no-contained-navigation")).toBe(true);
+ link.click();
+ expect(onClick).toHaveBeenCalledTimes(1);
+ });
+
+ it("leaves a plain page entry to be followed as the link it is", () => {
+ const container = renderInto(<RelatedSettings items={[ { title: "Backup", targetPage: "_optionsBackup" } ]} />);
+ expect(links(container)[0].hasAttribute("data-no-contained-navigation")).toBe(false);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.spec.tsx
new file mode 100644
index 0000000000..d4c135279c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/SettingsNavigation.spec.tsx
@@ -0,0 +1,57 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../../test/render";
+
+const mocks = vi.hoisted(() => ({
+ pages: [] as { noteId: string; title: string; getIcon: () => string }[]
+}));
+
+// The list is read straight from the `_options` subtree, so titles, icons and ordering stay in step
+// with the note tree rather than being restated here.
+vi.mock("../../../dialogs/OptionsDialog", () => ({ useOptionPages: () => mocks.pages }));
+
+import SettingsNavigation from "./SettingsNavigation";
+
+const PAGES = [
+ { noteId: "_optionsAppearance", title: "Appearance", getIcon: () => "bx bx-palette" },
+ { noteId: "_optionsShortcuts", title: "Shortcuts", getIcon: () => "bx bx-keyboard" }
+];
+
+describe("SettingsNavigation", () => {
+ it("lists every page in the order the tree holds them, each with its own icon", () => {
+ mocks.pages = PAGES;
+ const links = [ ...renderInto(<SettingsNavigation activeNoteId="_optionsAppearance" />)
+ .querySelectorAll<HTMLAnchorElement>("a.settings-navigation-item") ];
+
+ expect(links.map((link) => link.querySelector(".settings-navigation-title")?.textContent))
+ .toEqual([ "Appearance", "Shortcuts" ]);
+ expect(links[1].innerHTML).toContain("bx-keyboard");
+ });
+
+ it("points each entry at its page, as a link a modified click can still open elsewhere", () => {
+ mocks.pages = PAGES;
+ const [ first ] = [ ...renderInto(<SettingsNavigation activeNoteId="_optionsAppearance" />).querySelectorAll("a") ];
+
+ expect(first.getAttribute("href")).toBe("#root/_hidden/_options/_optionsAppearance");
+ // The note tooltip has no business opening over a way to another settings page.
+ expect(first.className).toContain("no-tooltip-preview");
+ });
+
+ it("marks the page being shown, for the eye and for a reader alike", () => {
+ mocks.pages = PAGES;
+ const links = [ ...renderInto(<SettingsNavigation activeNoteId="_optionsShortcuts" />).querySelectorAll("a") ];
+
+ expect(links[0].className).not.toContain("active");
+ expect(links[0].getAttribute("aria-current")).toBeNull();
+ expect(links[1].className).toContain("active");
+ expect(links[1].getAttribute("aria-current")).toBe("page");
+ });
+
+ it("draws an empty list rather than failing when the subtree has nothing to show", () => {
+ mocks.pages = [];
+ const container = renderInto(<SettingsNavigation activeNoteId="_optionsAppearance" />);
+
+ expect(container.querySelector(".settings-navigation")).not.toBeNull();
+ expect(container.querySelectorAll("a")).toHaveLength(0);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsx
new file mode 100644
index 0000000000..83458709bf
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.spec.tsx
@@ -0,0 +1,109 @@
+import { act } from "preact/test-utils";
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../../test/render";
+
+const mocks = vi.hoisted(() => ({
+ stored: {} as Record<string, string>,
+ saved: [] as [ string, string | number ][],
+ showError: vi.fn()
+}));
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../../services/toast", () => ({
+ default: { showError: mocks.showError, showMessage: vi.fn() }
+}));
+
+vi.mock("../../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../react/hooks")>()),
+ useTriliumOption: (name: string) => [
+ mocks.stored[name] ?? "",
+ (value: string | number) => void mocks.saved.push([ name, value ])
+ ]
+}));
+
+import TimeSelector from "./TimeSelector";
+
+/**
+ * The option holds seconds; the box shows them in whatever scale is chosen beside it. Both are
+ * stored, so the pair round-trips without the user's chosen unit being lost.
+ */
+function selector(seconds: string, scale: string, minimumSeconds?: number) {
+ mocks.stored = { theValue: seconds, theScale: scale };
+ mocks.saved = [];
+ mocks.showError.mockClear();
+
+ // The figure is put into the box by an effect rather than at first render, so the tree has to be
+ // let settle before it can be read.
+ let container!: HTMLElement;
+ act(() => {
+ container = renderInto(
+ <TimeSelector
+ name="timeout"
+ optionValueId={"theValue" as never}
+ optionTimeScaleId={"theScale" as never}
+ minimumSeconds={minimumSeconds}
+ />
+ );
+ });
+
+ return {
+ box: container.querySelector<HTMLInputElement>("input[type='number']"),
+ scaleSelect: container.querySelector<HTMLSelectElement>("select")
+ };
+}
+
+/** Types a figure and commits it, which for a number box rides on the native change event. */
+function enter(box: HTMLInputElement | null, value: string) {
+ if (!box) return;
+ box.value = value;
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+}
+
+describe("TimeSelector", () => {
+ it("reads the stored seconds out in the scale chosen beside them", () => {
+ // 7200 seconds shown as 2, with hours chosen.
+ expect(selector("7200", "3600").box?.value).toBe("2");
+ expect(selector("7200", "60").box?.value).toBe("120");
+ });
+
+ it("stores what was typed back as seconds, whatever scale it was typed in", () => {
+ const { box } = selector("3600", "3600");
+ enter(box, "3");
+
+ expect(mocks.saved).toContainEqual([ "theValue", 10800 ]);
+ });
+
+ it("offers every scale from seconds up to days", () => {
+ const { scaleSelect } = selector("60", "1");
+ expect([ ...(scaleSelect?.options ?? []) ].map((option) => option.value)).toEqual([ "1", "60", "3600", "86400" ]);
+ });
+
+ it("holds a figure below the floor up to it, and says so rather than storing it", () => {
+ const { box } = selector("600", "1", 60);
+ enter(box, "10");
+
+ expect(mocks.showError).toHaveBeenCalled();
+ expect(mocks.saved).toContainEqual([ "theValue", 60 ]);
+ });
+
+ it("stores nothing at all for a figure that is no figure, rather than guessing at one", () => {
+ const { box } = selector("600", "1", 60);
+ enter(box, "");
+
+ expect(mocks.showError).toHaveBeenCalled();
+ expect(mocks.saved).toEqual([]);
+ });
+
+ it("keeps the figure as it stands when only the scale changes, so the stored seconds move with it", () => {
+ const { scaleSelect } = selector("3600", "3600");
+
+ if (scaleSelect) {
+ scaleSelect.value = "60";
+ scaleSelect.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+
+ expect(mocks.saved).toContainEqual([ "theScale", "60" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx
index 6ea6a8baca..716073071c 100644
--- a/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx
+++ b/apps/client/src/widgets/type_widgets/options/components/TimeSelector.tsx
@@ -58,13 +58,16 @@ export default function TimeSelector({ id, name, includedTimeScales, optionValue
return false;
}
- let time = parseInt(value, 10);
+ const time = parseInt(value, 10);
const minimumSecondsOrDefault = (minimumSeconds ?? 0);
const newTime = convertTime(time, scale).toOption();
- if (Number.isNaN(time) || newTime < (minimumSecondsOrDefault)) {
+ // Held up to the floor rather than merely complained about: the figure is
+ // stored in seconds, so that is what the floor is applied to.
+ if (Number.isNaN(time) || newTime < minimumSecondsOrDefault) {
toast.showError(t("time_selector.minimum_input", { minimumSeconds: minimumSecondsOrDefault }));
- time = minimumSecondsOrDefault;
+ setValue(minimumSecondsOrDefault);
+ return;
}
setValue(newTime);
diff --git a/apps/client/src/widgets/type_widgets/options/components/options_components.spec.tsx b/apps/client/src/widgets/type_widgets/options/components/options_components.spec.tsx
new file mode 100644
index 0000000000..963d72c8b8
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/components/options_components.spec.tsx
@@ -0,0 +1,139 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../../test/render";
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../react/hooks")>()),
+ useStaticTooltip: vi.fn()
+}));
+
+import CheckboxList from "./CheckboxList";
+import MfaStatusBadge from "./MfaStatusBadge";
+import PlatformIndicator from "./PlatformIndicator";
+import RadioWithIllustration from "./RadioWithIllustration";
+import RestartAction from "./RestartAction";
+import ThemeModeSelector from "./ThemeModeSelector";
+
+describe("CheckboxList", () => {
+ const VALUES = [
+ { id: "en", title: "English" },
+ { id: "de", title: "German" },
+ { id: "fixed", title: "Always on", locked: true }
+ ];
+
+ function list(currentValue: string[], onChange = vi.fn()) {
+ const container = renderInto(
+ <CheckboxList
+ values={VALUES}
+ keyProperty="id" titleProperty="title" disabledProperty="locked"
+ currentValue={currentValue}
+ onChange={onChange}
+ />
+ );
+ return { container, boxes: [ ...container.querySelectorAll<HTMLInputElement>("input") ], onChange };
+ }
+
+ it("ticks what is held, and holds out of reach what cannot be unticked", () => {
+ const { boxes } = list([ "de" ]);
+
+ expect(boxes.map((box) => box.checked)).toEqual([ false, true, false ]);
+ expect(boxes.map((box) => box.disabled)).toEqual([ false, false, true ]);
+ });
+
+ it("adds a value that was ticked, and drops one that was unticked", () => {
+ const onChange = vi.fn();
+ const { boxes } = list([ "de" ], onChange);
+
+ boxes[0].dispatchEvent(new Event("change", { bubbles: true }));
+ expect(onChange).toHaveBeenLastCalledWith([ "de", "en" ]);
+
+ boxes[1].dispatchEvent(new Event("change", { bubbles: true }));
+ expect(onChange).toHaveBeenLastCalledWith([]);
+ });
+});
+
+describe("RadioWithIllustration", () => {
+ const VALUES = [
+ { key: "old", text: "Old layout", illustration: <span className="old-picture" /> },
+ { key: "new", text: "New layout", illustration: <span className="new-picture" /> }
+ ];
+
+ it("marks the choice in force and reports the other when its picture is pressed", () => {
+ const onChange = vi.fn();
+ const container = renderInto(
+ <RadioWithIllustration values={VALUES} currentValue="old" onChange={onChange} />
+ );
+
+ const items = [ ...container.querySelectorAll("li") ];
+ expect(items.map((item) => item.className)).toEqual([ "selected", "" ]);
+ // The picture is what is pressed, the caption naming it beneath.
+ expect(items[1].querySelector("figcaption")?.textContent).toBe("New layout");
+
+ items[1].querySelector<HTMLElement>(".illustration")?.click();
+ expect(onChange).toHaveBeenCalledWith("new");
+ });
+});
+
+describe("MfaStatusBadge", () => {
+ it("carries its tone as a class and a glyph of its own, so the state reads without the colour", () => {
+ // A different glyph per tone, so the three are never told apart by colour alone.
+ const expected = { active: "bx-check", pending: "bx-link", inactive: "bx-x" } as const;
+
+ for (const [ tone, icon ] of Object.entries(expected)) {
+ const badge = renderInto(<MfaStatusBadge tone={tone as keyof typeof expected} text={tone} />)
+ .querySelector(".mfa-status-badge");
+
+ expect(badge?.className).toContain(tone);
+ expect(badge?.innerHTML).toContain(icon);
+ }
+ });
+});
+
+describe("PlatformIndicator", () => {
+ it("shows one glyph per platform it was given, each naming that platform on hover", () => {
+ const both = [ ...renderInto(<PlatformIndicator windows="11" mac />).querySelectorAll(".platform-indicator span") ];
+
+ expect(both.map((icon) => icon.className).join(" ")).toContain("bxl-windows");
+ expect(both.map((icon) => icon.className).join(" ")).toContain("bxl-apple");
+ // The platform is named in the tooltip rather than written out beside the glyph.
+ expect(both.every((icon) => icon.hasAttribute("title"))).toBe(true);
+ });
+
+ it("shows nothing at all for a setting that is not tied to a platform", () => {
+ const none = renderInto(<PlatformIndicator mac={false} />);
+ expect(none.querySelectorAll(".platform-indicator span")).toHaveLength(0);
+ });
+});
+
+describe("ThemeModeSelector", () => {
+ it("shows which of the two the theme currently follows", () => {
+ const following = renderInto(<ThemeModeSelector matchesApp onMatchesAppChange={vi.fn()} />);
+ const [ app, fixed ] = [ ...following.querySelectorAll("button") ];
+
+ expect(app.className).toContain("active");
+ expect(fixed.className).not.toContain("active");
+ });
+
+ it("reports the choice as whether it follows the app, not as the word on the button", () => {
+ const onChange = vi.fn();
+ const container = renderInto(<ThemeModeSelector matchesApp onMatchesAppChange={onChange} />);
+
+ const [ , fixed ] = [ ...container.querySelectorAll<HTMLElement>("button") ];
+ fixed.click();
+ expect(onChange).toHaveBeenCalledWith(false);
+ });
+});
+
+describe("RestartAction", () => {
+ it("stands outside any card, at the width the cards end on", () => {
+ const container = renderInto(<RestartAction text="Restart" icon="bx-refresh" />);
+ const block = container.querySelector(".restart-action");
+
+ // `options-section` is what gives it the cards' width; `restart-action` puts it at their end.
+ expect(block?.className).toContain("options-section");
+ expect(block?.querySelector("button[name='restart-app-button']")).not.toBeNull();
+ expect(container.querySelector(".tn-card")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/active_content.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/active_content.spec.tsx
new file mode 100644
index 0000000000..59d378a164
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/active_content.spec.tsx
@@ -0,0 +1,296 @@
+import type { ComponentProps } from "preact";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ /** What each category's search resolves to, keyed by category id. */
+ found: {} as Record<string, { noteId: string; title: string }[]>,
+ /** The last filter each search was asked for, so the debounce can be watched. */
+ queried: [] as string[],
+ enabled: true,
+ setCategoryEnabled: vi.fn(),
+ stored: { contentManagerSortOrder: "title", contentManagerViewMode: "category" } as Record<string, string>,
+ saved: [] as [ string, string ][]
+}));
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+/*
+ * The data layer is stubbed out: what each category holds, and whether a note counts as enabled, is
+ * decided by searches and attribute reads that `services/active_content` owns and its own spec
+ * covers. What is left here — and what these cases are about — is which of the page's states is
+ * shown for a given answer.
+ */
+vi.mock("../../../../services/active_content", () => ({
+ CONTENT_CATEGORIES: [
+ { id: "templates", titleKey: "content_manager.category_templates", filter: "#template" },
+ { id: "scripts", titleKey: "content_manager.category_scripts", filter: "#run" }
+ ],
+ findCategoryNotes: async (category: { id: string }, _sortOrder: string, titleFilter: string) => {
+ mocks.queried.push(titleFilter);
+ return mocks.found[category.id] ?? [];
+ },
+ isCategoryEnabled: () => mocks.enabled,
+ setCategoryEnabled: mocks.setCategoryEnabled,
+ resolveProperties: () => [],
+ // One node per item, at the top level: the real grouping is this service's business, and the
+ // page only walks whatever tree it is handed.
+ buildLocationTree: (notes: { noteId: string; title: string }[]) =>
+ notes.map((note) => ({ note, isGroup: false, children: [] })),
+ getDisplayedBranchId: () => "branch-1"
+}));
+
+/*
+ * The collection widget itself is not what these cases read — but the page hands it the two render
+ * hooks that draw each row's detail and its menu, so the stub calls them the way the real list does.
+ * A row's note is only ever read for its id here, the rest being this page's own business.
+ */
+vi.mock("../../../collections/legacy/ListOrGridView", () => {
+ // One object per id, kept: a row re-reads its setting whenever the note it was handed changes,
+ // and a fresh object each render would look like a different note every time.
+ const notes = new Map<string, { noteId: string }>();
+ const noteFor = (noteId: string) => {
+ const held = notes.get(noteId) ?? { noteId };
+ notes.set(noteId, held);
+ return held;
+ };
+
+ return {
+ ListView: ({ noteIds, listOptions }: {
+ noteIds: string[];
+ listOptions?: {
+ renderItemActions?: (note: { noteId: string }) => preact.ComponentChildren;
+ renderItemMenu?: (note: { noteId: string }) => preact.ComponentChildren;
+ };
+ }) => (
+ <div className="list-stub" data-notes={noteIds.join(",")}>
+ {noteIds.map((noteId) => (
+ <div key={noteId} className="row-stub" data-note={noteId}>
+ {listOptions?.renderItemActions?.(noteFor(noteId))}
+ {listOptions?.renderItemMenu?.(noteFor(noteId))}
+ </div>
+ ))}
+ </div>
+ )
+ };
+});
+
+// The row menu reaches for the tab manager as it opens a note; nothing here presses it.
+vi.mock("../../../../components/app_context", () => ({
+ default: {
+ tabManager: {
+ openContextWithNote: vi.fn(),
+ getActiveContext: () => undefined,
+ getActiveContextNotePath: () => undefined
+ }
+ }
+}));
+
+vi.mock("../components/OptionsPageHeader", () => ({
+ default: ({ below }: { below?: preact.ComponentChildren }) => <div className="header-stub">{below}</div>
+}));
+
+vi.mock("../../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../react/hooks")>()),
+ useTriliumOption: (name: string) => [
+ mocks.stored[name] ?? "",
+ (value: string) => void mocks.saved.push([ name, value ])
+ ]
+}));
+
+import ActiveContent from "./active_content";
+
+/** Only the fields the page itself reads; the rest of a type widget's props are the host's business. */
+const PAGE_PROPS = { note: { noteId: "_optionsContentManager" }, sectionSwitcher: null } as unknown as ComponentProps<typeof ActiveContent>;
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ mocks.found = {};
+ mocks.queried = [];
+ mocks.enabled = true;
+ mocks.stored = { contentManagerSortOrder: "title", contentManagerViewMode: "category" };
+ mocks.saved = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.useRealTimers();
+ vi.clearAllMocks();
+});
+
+/** Opens the page and lets the per-category searches settle. */
+async function open() {
+ await act(async () => {
+ render(null, host);
+ render(<ActiveContent {...PAGE_PROPS} />, host);
+ });
+ await act(async () => {});
+}
+
+const lists = () => [ ...host.querySelectorAll(".list-stub") ].map((list) => list.getAttribute("data-notes"));
+const filterBox = () => host.querySelector<HTMLInputElement>(".active-content-filter input");
+
+describe("what the page shows for a given answer", () => {
+ it("says it is still looking before the first search comes back", async () => {
+ await act(async () => {
+ render(<ActiveContent {...PAGE_PROPS} />, host);
+ });
+
+ // Nothing has resolved yet, which is not the same as there being nothing to show.
+ expect(host.querySelector(".active-content-loading")).not.toBeNull();
+ });
+
+ it("says there is nothing yet, with a hint, once the searches come back empty", async () => {
+ await open();
+
+ expect(host.querySelector(".no-items")).not.toBeNull();
+ expect(host.querySelector(".no-items small")).not.toBeNull();
+ expect(host.querySelector(".active-content-loading")).toBeNull();
+ });
+
+ it("lists a category that holds something, and leaves out one that does not", async () => {
+ mocks.found = { templates: [ { noteId: "a", title: "A" } ] };
+ await open();
+
+ expect(lists()).toEqual([ "a" ]);
+ expect(host.querySelector(".no-items")).toBeNull();
+ });
+});
+
+describe("filtering", () => {
+ beforeEach(() => {
+ mocks.found = { templates: [ { noteId: "a", title: "A" } ] };
+ });
+
+ it("keeps typing instant and only searches again once it stops", async () => {
+ await open();
+ mocks.queried = [];
+
+ await act(async () => {
+ const box = filterBox();
+ if (box) {
+ box.value = "tem";
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+
+ // The box shows the text at once, but nothing has been searched for yet.
+ expect(filterBox()?.value).toBe("tem");
+ expect(mocks.queried).toEqual([]);
+
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+ expect(mocks.queried).toContain("tem");
+ });
+
+ it("says nothing matched rather than that there is nothing at all, while filtering", async () => {
+ mocks.found = {};
+ await open();
+
+ await act(async () => {
+ const box = filterBox();
+ if (box) {
+ box.value = "nothing";
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+
+ // Content may well exist, just none matching — so the "nothing here yet" hint would mislead.
+ expect(host.querySelector(".no-items small")).toBeNull();
+ expect(host.querySelector(".no-items")?.textContent).toContain("content_manager.no_matches");
+ });
+
+ it("clears the box and searches for everything again, dropping the pending search with it", async () => {
+ await open();
+
+ await act(async () => {
+ const box = filterBox();
+ if (box) {
+ box.value = "tem";
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+
+ mocks.queried = [];
+ await act(async () => void host.querySelector<HTMLButtonElement>(".input-clearer-button")?.click());
+ await act(async () => { await vi.advanceTimersByTimeAsync(400); });
+
+ expect(filterBox()?.value).toBe("");
+ // The text just cleared must not be re-applied by the call that was already pending.
+ expect(mocks.queried.every((query) => query === "")).toBe(true);
+ });
+});
+
+describe("arranging the same items another way", () => {
+ it("groups by where the items live rather than what they are, when asked to", async () => {
+ mocks.found = { templates: [ { noteId: "a", title: "A" } ] };
+ mocks.stored = { ...mocks.stored, contentManagerViewMode: "location" };
+ await open();
+
+ // The same notes, arranged by the tree the service handed back rather than by category.
+ expect(lists()).toEqual([ "a" ]);
+ });
+
+ it("writes the chosen arrangement back, so the page opens the same way next time", async () => {
+ await open();
+
+ const [ , location ] = [ ...host.querySelectorAll<HTMLElement>(".content-manager-view-choice button") ];
+ await act(async () => location?.click());
+
+ expect(mocks.saved).toContainEqual([ "contentManagerViewMode", "location" ]);
+ });
+});
+
+/**
+ * Each row's own controls, drawn by the hooks the page hands the list: what the item is, and the one
+ * switch that turns it off.
+ */
+describe("a row's detail and its switch", () => {
+ const toggles = () => [ ...host.querySelectorAll<HTMLInputElement>(".row-stub input.switch-toggle") ];
+
+ beforeEach(() => {
+ mocks.found = { templates: [ { noteId: "a", title: "A" } ] };
+ });
+
+ it("gives each item a switch reading whether its content is on", async () => {
+ await open();
+ expect(toggles()[0]?.checked).toBe(true);
+
+ mocks.enabled = false;
+ await open();
+ expect(toggles()[0]?.checked).toBe(false);
+ });
+
+ it("writes through to the one category it was switched under, never to the note as a whole", async () => {
+ await open();
+ await act(async () => void toggles()[0]?.dispatchEvent(new Event("input", { bubbles: true })));
+
+ // A note can be active content in several ways at once, and one switch over all of them
+ // would overwrite the states the user never touched.
+ expect(mocks.setCategoryEnabled).toHaveBeenCalledTimes(1);
+ const [ , category, willEnable ] = mocks.setCategoryEnabled.mock.calls[0];
+ expect((category as { id: string }).id).toBe("templates");
+ expect(willEnable).toBe(false);
+ });
+
+ it("names the category on a row only where the headings do not already say it", async () => {
+ await open();
+ // Filed under its category's own heading, so saying it again on the row would be noise.
+ expect(host.querySelectorAll(".row-stub .active-content-badge")).toHaveLength(0);
+
+ mocks.stored = { ...mocks.stored, contentManagerViewMode: "location" };
+ await open();
+ // Arranged by place instead, where nothing else says what the item is.
+ expect(host.querySelectorAll(".row-stub .active-content-badge")).toHaveLength(1);
+ });
+
+ it("offers each item the same menu, whichever way the list is arranged", async () => {
+ await open();
+ expect(host.querySelectorAll(".row-stub .active-content-item-menu")).toHaveLength(1);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/desktop.spec.tsx b/apps/client/src/widgets/type_widgets/options/desktop.spec.tsx
new file mode 100644
index 0000000000..f8057bfff7
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/desktop.spec.tsx
@@ -0,0 +1,130 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ electron: true,
+ stored: {} as Record<string, string | boolean>,
+ saved: [] as [ string, string | boolean ][]
+}));
+
+// The page is desktop-only; on a server build it stands down to a placeholder, so a scenario has to
+// be able to say which kind of build it is pretending to be.
+vi.mock("../../../services/utils", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("../../../services/utils")>();
+ return {
+ ...actual,
+ isElectron: () => mocks.electron,
+ default: { ...actual.default, reloadTray: vi.fn(), reapplyLaunchOnStartup: vi.fn() }
+ };
+});
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: (name: string) => [
+ String(mocks.stored[name] ?? ""),
+ (value: string) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === true,
+ (value: boolean) => void mocks.saved.push([ name, value ])
+ ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import DesktopSettings from "./desktop";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.electron = true;
+ mocks.stored = {};
+ mocks.saved = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+});
+
+function open() {
+ act(() => {
+ render(<DesktopSettings />, host);
+ });
+}
+
+/** The switches, keyed by the setting each one carries — their ids are `<name>-<random>`. */
+function toggle(name: string) {
+ return host.querySelector<HTMLInputElement>(`input.switch-toggle[id^='${name}-']`);
+}
+
+describe("the desktop settings on a server build", () => {
+ it("says the page has nothing to offer here, rather than showing settings that do nothing", () => {
+ mocks.electron = false;
+ open();
+
+ expect(host.querySelector(".no-items")).not.toBeNull();
+ expect(host.querySelector(".tn-card")).toBeNull();
+ });
+});
+
+describe("the tray and startup settings", () => {
+ it("shows the tray as on when it has not been disabled, since the setting is stored the other way round", () => {
+ open();
+ expect(toggle("tray-enabled")?.checked).toBe(true);
+
+ mocks.stored = { disableTray: true };
+ open();
+ expect(toggle("tray-enabled")?.checked).toBe(false);
+ });
+
+ it("writes the tray setting inverted, so turning the switch on clears the disable flag", () => {
+ open();
+ act(() => {
+ toggle("tray-enabled")?.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+
+ expect(mocks.saved).toContainEqual([ "disableTray", true ]);
+ });
+
+ it("holds close-to-tray out of reach without a tray, which would hide the app with no way back", () => {
+ open();
+ expect(toggle("close-to-tray")?.disabled).toBe(false);
+
+ mocks.stored = { disableTray: true };
+ open();
+ expect(toggle("close-to-tray")?.disabled).toBe(true);
+ });
+
+ it("holds starting hidden out of reach unless the app both starts itself and has a tray to hide in", () => {
+ open();
+ expect(toggle("hide-on-auto-start")?.disabled).toBe(true);
+
+ mocks.stored = { launchOnStartup: true };
+ open();
+ expect(toggle("hide-on-auto-start")?.disabled).toBe(false);
+
+ // A tray is the only way back from hidden, so losing it takes this with it.
+ mocks.stored = { launchOnStartup: true, disableTray: true };
+ open();
+ expect(toggle("hide-on-auto-start")?.disabled).toBe(true);
+ });
+});
+
+describe("the search engine settings", () => {
+ it("marks the engine currently in use, and takes both its name and its address when one is picked", () => {
+ mocks.stored = { customSearchEngineUrl: "https://www.google.com/search?q={keyword}" };
+ open();
+
+ const chips = [ ...host.querySelectorAll(".search-engine-templates .ext-badge") ];
+ expect(chips).toHaveLength(4);
+ expect(chips.filter((chip) => chip.className.includes("selected"))).toHaveLength(1);
+
+ act(() => (chips[0] as HTMLElement).click());
+ expect(mocks.saved.map(([ name ]) => name)).toEqual([ "customSearchEngineName", "customSearchEngineUrl" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/etapi.spec.tsx b/apps/client/src/widgets/type_widgets/options/etapi.spec.tsx
new file mode 100644
index 0000000000..b668e48bb6
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/etapi.spec.tsx
@@ -0,0 +1,138 @@
+import type { EtapiToken } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ // Held in a box so the GET can read whatever the scenario set. Replacing the shared server mock
+ // means answering what the modules pulled in alongside the page ask for on import, too — the
+ // options load and the keyboard actions, both of which expect a particular shape.
+ const tokens: { current: unknown[] } = { current: [] };
+
+ return {
+ tokens,
+ get: vi.fn(async (url: string) => {
+ if (url === "etapi-tokens") return tokens.current;
+ if (url === "keyboard-actions") return [];
+ return {};
+ }),
+ post: vi.fn(async () => ({ authToken: "fresh-token" })),
+ patch: vi.fn(async () => ({})),
+ remove: vi.fn(async () => ({})),
+ prompt: vi.fn(async () => "A token"),
+ confirm: vi.fn(async () => true)
+ };
+});
+
+vi.mock("../../../services/server", () => ({
+ default: { get: mocks.get, post: mocks.post, patch: mocks.patch, remove: mocks.remove }
+}));
+
+vi.mock("../../../services/dialog", () => ({
+ default: { prompt: mocks.prompt, confirm: mocks.confirm }
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("./components/OptionsPageHeader", () => ({
+ default: ({ below }: { below?: preact.ComponentChildren }) => <div className="header-stub">{below}</div>
+}));
+
+import EtapiSettings from "./etapi";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.tokens.current = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+async function open() {
+ await act(async () => {
+ render(<EtapiSettings />, host);
+ });
+}
+
+const tokenRows = () => [ ...host.querySelectorAll(".tn-card-option") ];
+
+describe("the ETAPI token page with none yet", () => {
+ it("says so on the page itself rather than inside an empty card", async () => {
+ await open();
+
+ expect(host.querySelector(".no-items")).not.toBeNull();
+ expect(host.querySelector(".tn-card")).toBeNull();
+ });
+
+ it("still offers the way to make one, since that is what the page is for", async () => {
+ await open();
+
+ // In the header rather than the list: with no list there would be nowhere else for it.
+ const create = host.querySelector<HTMLButtonElement>(".header-stub button[name='create-etapi-token-button']");
+ expect(create).not.toBeNull();
+
+ await act(async () => create?.click());
+ expect(mocks.post).toHaveBeenCalledWith("etapi-tokens", { tokenName: "A token" });
+ });
+});
+
+describe("the ETAPI tokens once there are some", () => {
+ beforeEach(() => {
+ mocks.tokens.current = [
+ { etapiTokenId: "abc", name: "Laptop", utcDateCreated: "2025-01-02 03:04:05.000Z" },
+ { etapiTokenId: "def", name: "Phone", utcDateCreated: "2025-02-03 04:05:06.000Z" }
+ ] satisfies EtapiToken[];
+ });
+
+ it("gives each token a segment of its own, named and dated", async () => {
+ await open();
+
+ expect(host.querySelector(".no-items")).toBeNull();
+ expect(tokenRows()).toHaveLength(2);
+ expect(tokenRows().map((row) => row.querySelector("label")?.firstChild?.textContent)).toEqual([ "Laptop", "Phone" ]);
+ });
+
+ it("marks only the destructive action as such, so the two are told apart at a glance", async () => {
+ await open();
+
+ const [ rename, remove ] = [ ...tokenRows()[0].querySelectorAll("button") ];
+ expect(rename.className).not.toContain("destructive-action-icon");
+ expect(remove.className).toContain("destructive-action-icon");
+ });
+
+ it("renames the token that was pressed, leaving the others alone", async () => {
+ await open();
+ const [ rename ] = [ ...tokenRows()[1].querySelectorAll("button") ];
+
+ await act(async () => rename.click());
+ expect(mocks.patch).toHaveBeenCalledWith("etapi-tokens/def", { name: "A token" });
+ });
+
+ it("asks before deleting, and does nothing at all when the answer is no", async () => {
+ mocks.confirm.mockResolvedValueOnce(false);
+ await open();
+ const remove = [ ...tokenRows()[0].querySelectorAll("button") ][1];
+
+ await act(async () => remove.click());
+ expect(mocks.confirm).toHaveBeenCalled();
+ expect(mocks.remove).not.toHaveBeenCalled();
+
+ await act(async () => remove.click());
+ expect(mocks.remove).toHaveBeenCalledWith("etapi-tokens/abc");
+ });
+});
+
+describe("naming a new token", () => {
+ it("refuses a blank name rather than creating one that cannot be told apart", async () => {
+ mocks.prompt.mockResolvedValueOnce(" ");
+ await open();
+
+ await act(async () => host.querySelector<HTMLButtonElement>("button[name='create-etapi-token-button']")?.click());
+ expect(mocks.post).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/highlights_list_options.spec.tsx b/apps/client/src/widgets/type_widgets/options/highlights_list_options.spec.tsx
new file mode 100644
index 0000000000..0635bd5396
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/highlights_list_options.spec.tsx
@@ -0,0 +1,51 @@
+import { describe, expect, it, vi } from "vitest";
+
+import { renderInto } from "../../../test/render";
+
+const mocks = vi.hoisted(() => ({
+ stored: [] as string[],
+ saved: [] as string[][]
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOptionJson: () => [ mocks.stored, (value: string[]) => void mocks.saved.push(value) ]
+}));
+
+import { HIGHLIGHT_FORMATS, HighlightsListOptions } from "./highlights_list_options";
+
+describe("the highlights list options", () => {
+ it("offers every format the list can be told to count, in the toolbar's own order", () => {
+ mocks.stored = [];
+ const boxes = [ ...renderInto(<HighlightsListOptions />).querySelectorAll<HTMLInputElement>("input") ];
+
+ expect(boxes.map((box) => box.value)).toEqual(HIGHLIGHT_FORMATS.map(({ val }) => val));
+ expect(boxes.every((box) => !box.checked)).toBe(true);
+ });
+
+ it("ticks the formats already counted, and adds the one that was ticked", () => {
+ mocks.stored = [ "bold" ];
+ mocks.saved = [];
+ const boxes = [ ...renderInto(<HighlightsListOptions />).querySelectorAll<HTMLInputElement>("input") ];
+
+ expect(boxes.filter((box) => box.checked).map((box) => box.value)).toEqual([ "bold" ]);
+
+ const italic = boxes.find((box) => box.value === "italic");
+ italic?.dispatchEvent(new Event("change", { bubbles: true }));
+ expect(mocks.saved.at(-1)).toEqual([ "bold", "italic" ]);
+ });
+});
+
+describe("the formats themselves", () => {
+ it("gives each one an icon and a title, since the sidebar's menu shows both", () => {
+ for (const format of HIGHLIGHT_FORMATS) {
+ expect(format.val, "every format is named").toBeTruthy();
+ expect(format.icon, `${format.val} has an icon`).toMatch(/^bx /);
+ // Held as keys rather than resolved, a module-level `t()` running before the
+ // translations have loaded.
+ expect(format.titleKey, `${format.val} has a title key`).toMatch(/^highlights_list\./);
+ }
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/i18n.spec.tsx b/apps/client/src/widgets/type_widgets/options/i18n.spec.tsx
new file mode 100644
index 0000000000..43ff276737
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/i18n.spec.tsx
@@ -0,0 +1,114 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ electron: true,
+ stored: {} as Record<string, string>,
+ saved: [] as [ string, string ][]
+}));
+
+// Spellcheck is only related to this page where the app owns the spell checker, so which kind of
+// build we are pretending to be decides whether that entry is offered at all.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isElectron: () => mocks.electron,
+ restartDesktopApp: vi.fn()
+}));
+
+vi.mock("../../../services/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/i18n")>()),
+ t: (key: string) => key
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: (name: string) => [
+ mocks.stored[name] ?? "",
+ (value: string) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionJson: () => [ [], vi.fn() ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import InternationalizationOptions from "./i18n";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.electron = true;
+ mocks.stored = {};
+ mocks.saved = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+});
+
+function open() {
+ act(() => {
+ render(<InternationalizationOptions />, host);
+ });
+}
+
+const cardHeadings = () => [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.textContent);
+const optionLabels = () =>
+ [ ...host.querySelectorAll(".tn-card-option-label") ].map((label) => label.firstChild?.textContent);
+
+describe("the Language & Region page", () => {
+ it("keeps the languages and the calendar conventions in cards of their own", () => {
+ open();
+
+ expect(cardHeadings()).toEqual([
+ "i18n.title",
+ "i18n.dates-title",
+ "content_language.title",
+ "settings.related_settings"
+ ]);
+ });
+
+ it("asks for the minimum days only under the rule that measures against them", () => {
+ open();
+ expect(optionLabels()).not.toContain("i18n.min-days-in-first-week");
+
+ // "First week has minimum days" — the one rule the figure means anything under.
+ mocks.stored = { firstWeekOfYear: "2" };
+ open();
+ expect(optionLabels()).toContain("i18n.min-days-in-first-week");
+ });
+
+ it("offers the way to start again, which is what every setting above it waits on", () => {
+ open();
+
+ const restart = host.querySelector(".restart-action button");
+ expect(restart).not.toBeNull();
+ // Outside every card: it acts rather than holds anything.
+ expect(restart?.closest(".tn-card")).toBeNull();
+ });
+
+ it("names spellcheck as related only where the app owns the spell checker", () => {
+ open();
+ expect(host.querySelectorAll(".tn-card-section-link")).toHaveLength(1);
+
+ mocks.electron = false;
+ open();
+ expect(host.querySelectorAll(".tn-card-section-link")).toHaveLength(0);
+ });
+
+ it("writes the day a week starts on back to the option it came from", () => {
+ open();
+
+ const select = host.querySelector<HTMLSelectElement>("select[name='first-day-of-week']");
+ act(() => {
+ if (select) {
+ select.value = "7";
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+ });
+
+ expect(mocks.saved).toContainEqual([ "firstDayOfWeek", "7" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/llm.spec.tsx b/apps/client/src/widgets/type_widgets/options/llm.spec.tsx
index 06695943f3..738509e289 100644
--- a/apps/client/src/widgets/type_widgets/options/llm.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm.spec.tsx
@@ -4,10 +4,15 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
stored: {} as Record<string, string>,
+ /** Every option write, which is where the provider list is kept. */
+ saved: [] as [ string, string ][],
+ confirm: vi.fn(async () => true),
standalone: false,
// Routed by URL: the page under test asks for network addresses, while modules pulled in
// alongside it (keyboard actions) expect a list from the same service.
- get: vi.fn(async (url: string) => (url === "network-addresses" ? { addresses: [], reachableOnNetwork: false } : []))
+ /** What the server says about the interfaces it is bound to. */
+ network: { addresses: [] as string[], reachableOnNetwork: false },
+ get: vi.fn(async (url: string) => (url === "network-addresses" ? mocks.network : []))
}));
// `isStandalone` is a const in the target, read here through a getter so a scenario can flip which
@@ -27,10 +32,15 @@ vi.mock("../../../services/i18n", () => ({
vi.mock("../../react/hooks", async (importOriginal) => ({
...(await importOriginal<typeof import("../../react/hooks")>()),
- useTriliumOption: (name: string) => [ mocks.stored[name] ?? "", () => {} ],
+ useTriliumOption: (name: string) => [
+ mocks.stored[name] ?? "",
+ (value: string) => void mocks.saved.push([ name, value ])
+ ],
useTriliumOptionBool: (name: string) => [ mocks.stored[name] === "true", () => {} ]
}));
+vi.mock("../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));
+
// The request the card makes: the LAN addresses the endpoint is reachable on. Standalone serves
// no such route, so whether it is asked for at all is part of what is under test.
vi.mock("../../../services/server", () => ({ default: { get: mocks.get } }));
@@ -53,6 +63,8 @@ let host: HTMLElement;
beforeEach(() => {
mocks.standalone = false;
mocks.stored = { aiEnabled: "true", mcpEnabled: "true" };
+ mocks.saved = [];
+ mocks.network = { addresses: [], reachableOnNetwork: false };
host = document.body.appendChild(document.createElement("div"));
});
@@ -142,6 +154,115 @@ describe("the MCP card in standalone", () => {
});
});
+describe("the addresses MCP is reachable on", () => {
+ const groups = () => [ ...host.querySelectorAll(".mcp-endpoint-group") ];
+ const urls = () => [ ...host.querySelectorAll<HTMLInputElement>(".mcp-endpoint-list input") ].map((box) => box.value);
+
+ /** Opens the page and lets the address lookup settle. */
+ async function openAndSettle() {
+ open();
+ await act(async () => {});
+ }
+
+ it("offers the address on this device, whatever the machine is bound to", async () => {
+ await openAndSettle();
+
+ expect(groups()).toHaveLength(1);
+ expect(urls()[0]).toMatch(/\/mcp$/);
+ });
+
+ it("says so plainly when nothing outside this machine could reach it", async () => {
+ await openAndSettle();
+
+ // Every LAN address would refuse the connection on a loopback-only binding.
+ expect(host.querySelector(".mcp-endpoint-note")).not.toBeNull();
+ });
+
+ it("adds the addresses on the network once it is actually bound to one", async () => {
+ mocks.network = {
+ addresses: [ "http://192.168.1.10:8080", "http://10.0.0.5:8080" ],
+ reachableOnNetwork: true
+ };
+ await openAndSettle();
+
+ expect(groups()).toHaveLength(2);
+ expect(urls()).toContain("http://192.168.1.10:8080/mcp");
+ // Nothing to explain once there is something to hand out.
+ expect(host.querySelector(".mcp-endpoint-note")).toBeNull();
+ });
+
+ it("does not offer the same address twice under two headings", async () => {
+ mocks.network = { addresses: [ `${window.location.protocol}//${window.location.host}` ], reachableOnNetwork: true };
+ await openAndSettle();
+
+ // The one it is already offering as "this device" is left out of the network list.
+ expect(new Set(urls()).size).toBe(urls().length);
+ });
+});
+
+describe("the configured providers", () => {
+ const providers = () => [ ...host.querySelectorAll(".tn-card-option") ]
+ .filter((option) => option.querySelector(".llm-provider-name"));
+
+ function withProviders(configured: { id: string; name: string; provider: string; apiKey: string; selectedModels?: unknown[] }[]) {
+ mocks.stored = { ...mocks.stored, llmProviders: JSON.stringify(configured) };
+ }
+
+ it("says there are none rather than showing an empty card", () => {
+ open();
+
+ expect(host.querySelector(".no-items")).not.toBeNull();
+ expect(providers()).toHaveLength(0);
+ });
+
+ it("survives a stored list that is not readable, rather than taking the page down with it", () => {
+ mocks.stored = { ...mocks.stored, llmProviders: "{ not json" };
+ open();
+
+ expect(host.querySelector(".no-items")).not.toBeNull();
+ });
+
+ it("gives each provider a segment, named, and says how many models it was given", () => {
+ withProviders([
+ { id: "a", name: "My OpenAI", provider: "openai", apiKey: "sk", selectedModels: [ {}, {} ] },
+ { id: "b", name: "Local", provider: "ollama", apiKey: "" }
+ ]);
+ open();
+
+ expect(providers()).toHaveLength(2);
+ expect(providers()[0].querySelector(".llm-provider-name")?.textContent).toContain("My OpenAI");
+ // With no models chosen there is no count to give, so the kind of provider is said instead.
+ expect(providers()[1].querySelector(".tn-card-option-description")?.textContent).toBeTruthy();
+ });
+
+ it("marks only the destructive action, and drops the one provider it was pressed on", async () => {
+ withProviders([
+ { id: "a", name: "First", provider: "openai", apiKey: "sk" },
+ { id: "b", name: "Second", provider: "openai", apiKey: "sk" }
+ ]);
+ open();
+
+ const [ edit, remove ] = [ ...providers()[0].querySelectorAll("button") ];
+ expect(edit.className).not.toContain("destructive-action-icon");
+ expect(remove.className).toContain("destructive-action-icon");
+
+ await act(async () => remove.click());
+ const written = mocks.saved.find(([ name ]) => name === "llmProviders");
+ expect(JSON.parse(written?.[1] ?? "[]").map((provider: { id: string }) => provider.id)).toEqual([ "b" ]);
+ });
+
+ it("asks first, and keeps the provider when the answer is no", async () => {
+ withProviders([ { id: "a", name: "First", provider: "openai", apiKey: "sk" } ]);
+ mocks.confirm.mockResolvedValueOnce(false);
+ open();
+
+ const remove = [ ...providers()[0].querySelectorAll("button") ][1];
+ await act(async () => remove.click());
+
+ expect(mocks.saved.some(([ name ]) => name === "llmProviders")).toBe(false);
+ });
+});
+
describe("MCP client configuration samples", () => {
it("emits a config clients can paste verbatim", () => {
const parsed = JSON.parse(buildMcpClientConfig(URL, TOKEN));
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
index a38bf1cc57..13b128fc4b 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.spec.ts
@@ -2,107 +2,118 @@ import { describe, expect, it, vi } from "vitest";
vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
-import { prefilledBaseUrl, PROVIDER_TYPES } from "./AddProviderModal";
-
-/** Card ids are persisted in the llmProviders option, so they double as an API. */
-const SELF_HOSTED = ["ollama", "lmstudio", "openai-compatible"];
-
-describe("AddProviderModal provider cards", () => {
- it("prefills an endpoint for self-hosted providers only", () => {
- // The port is the one detail a self-hosted user must get right, and it
- // differs per runtime — whereas prefilling a vendor endpoint would store
- // a redundant override on every provider the user adds.
- expect(prefilledBaseUrl("ollama")).toBe("http://localhost:11434");
- expect(prefilledBaseUrl("lmstudio")).toBe("http://localhost:1234/v1");
- expect(prefilledBaseUrl("openai")).toBe("");
- expect(prefilledBaseUrl("anthropic")).toBe("");
- expect(prefilledBaseUrl("claude-agent")).toBe("");
- // The generic card has no single sensible endpoint to guess.
- expect(prefilledBaseUrl("openai-compatible")).toBe("");
- expect(prefilledBaseUrl("unknown")).toBe("");
+import {
+ isConnectionValid,
+ isValidBaseUrl,
+ prefilledBaseUrl,
+ PROVIDER_TYPES,
+ type ProviderType
+} from "./AddProviderModal";
+
+const provider = (id: string) => PROVIDER_TYPES.find((type) => type.id === id);
+
+describe("isValidBaseUrl", () => {
+ it("accepts an empty field, which means the provider's own default stands", () => {
+ expect(isValidBaseUrl("")).toBe(true);
});
- it("declares an endpoint and a setup hint for every self-hosted card", () => {
- for (const id of SELF_HOSTED) {
- const card = PROVIDER_TYPES.find(p => p.id === id);
- expect(card, `missing card: ${id}`).toBeDefined();
- expect(card?.baseUrl).toBe("required");
- expect(card?.setupHintKey).toBeTruthy();
- expect(card?.defaultBaseUrl).toBeTruthy();
- }
+ it("accepts what can actually be reached over the wire, and nothing else", () => {
+ expect(isValidBaseUrl("https://api.openai.com/v1")).toBe(true);
+ expect(isValidBaseUrl("http://localhost:11434")).toBe(true);
+
+ // Parses as a URL, but not one the app could ever request.
+ expect(isValidBaseUrl("ftp://example.com")).toBe(false);
+ expect(isValidBaseUrl("file:///etc/passwd")).toBe(false);
+ // Not a URL at all — a host with no scheme is the usual slip.
+ expect(isValidBaseUrl("localhost:11434")).toBe(false);
+ expect(isValidBaseUrl("not a url")).toBe(false);
});
+});
- it("sorts every card into a section by how it is billed and where it runs", () => {
- // Groups follow the user guide's taxonomy — metered API keys, a fixed-fee
- // subscription reused from elsewhere, self-hosted — plus a custom-endpoint
- // section, which exists because that card also reaches *hosted* services
- // (OpenRouter, Groq) and so can claim neither free use nor locality.
- expect(PROVIDER_TYPES.filter(p => p.group === "cloud").map(p => p.id))
- .toEqual(["anthropic", "openai", "google", "deepseek"]);
- expect(PROVIDER_TYPES.filter(p => p.group === "subscription").map(p => p.id))
- .toEqual(["claude-agent", "copilot-agent"]);
- expect(PROVIDER_TYPES.filter(p => p.group === "local").map(p => p.id))
- .toEqual(["ollama", "lmstudio"]);
- expect(PROVIDER_TYPES.filter(p => p.group === "custom").map(p => p.id))
- .toEqual(["openai-compatible"]);
- // Every card lands in exactly one section.
- expect(PROVIDER_TYPES.filter(p => p.group === undefined)).toEqual([]);
+describe("isConnectionValid", () => {
+ const withModes = (apiKey: ProviderType["apiKey"], baseUrl: ProviderType["baseUrl"]) =>
+ ({ apiKey, baseUrl } as ProviderType);
+
+ it("wants a key from a provider that requires one, and counts blank as none", () => {
+ const vendor = withModes("required", "advanced");
+
+ expect(isConnectionValid(vendor, "", "")).toBe(false);
+ expect(isConnectionValid(vendor, " ", "")).toBe(false);
+ expect(isConnectionValid(vendor, "sk-abc", "")).toBe(true);
});
- it("keeps the endpoint-driven cards together regardless of section", () => {
- // `group` and `baseUrl` are independent fields: splitting the custom
- // endpoint out of "local" must not stop it asking for a URL.
- expect(PROVIDER_TYPES.filter(p => p.baseUrl === "required").map(p => p.id)).toEqual(SELF_HOSTED);
+ it("treats a required key as the default, for a provider that says nothing about it", () => {
+ expect(isConnectionValid(undefined, "", "")).toBe(false);
+ expect(isConnectionValid(undefined, "sk-abc", "")).toBe(true);
});
- it("bills every subscription provider through an existing account rather than a key", () => {
- for (const card of PROVIDER_TYPES.filter(p => p.group === "subscription")) {
- expect(card.apiKey, `${card.id} should not ask for an API key`).toBe("none");
- }
+ it("wants an endpoint from a provider that has no default of its own", () => {
+ const selfHosted = withModes("optional", "required");
+
+ expect(isConnectionValid(selfHosted, "", "")).toBe(false);
+ expect(isConnectionValid(selfHosted, "", "http://localhost:11434")).toBe(true);
+ // A key is welcome but not required — a proxy in front of the endpoint may want one.
+ expect(isConnectionValid(selfHosted, "sk-abc", "http://localhost:11434")).toBe(true);
});
- it("keeps vendor cards on a required key and an advanced endpoint override", () => {
- for (const id of ["anthropic", "openai", "google", "deepseek"]) {
- const card = PROVIDER_TYPES.find(p => p.id === id);
- // Both default, so neither is set explicitly.
- expect(card?.apiKey ?? "required").toBe("required");
- expect(card?.baseUrl ?? "advanced").toBe("advanced");
+ it("refuses a malformed endpoint even where the field is only an override", () => {
+ const vendor = withModes("required", "advanced");
+
+ expect(isConnectionValid(vendor, "sk-abc", "localhost:11434")).toBe(false);
+ expect(isConnectionValid(vendor, "sk-abc", "https://proxy.example.com")).toBe(true);
+ });
+
+ it("asks for nothing from a provider that authenticates elsewhere", () => {
+ // Claude Code and the like: the subscription is signed in through its own program.
+ expect(isConnectionValid(withModes("none", "none"), "", "")).toBe(true);
+ // Even a field left in a mess cannot hold it up, there being no field.
+ expect(isConnectionValid(withModes("none", "none"), "", "not a url")).toBe(true);
+ });
+});
+
+describe("prefilledBaseUrl", () => {
+ it("fills in an endpoint only where the port is the user's to get right", () => {
+ // Self-hosted runtimes differ by port per install, so the default is written in.
+ expect(prefilledBaseUrl("ollama")).toBe(provider("ollama")?.defaultBaseUrl);
+ // A vendor's endpoint is a hint only, so an unedited field stores no override.
+ expect(prefilledBaseUrl("openai")).toBe("");
+ expect(prefilledBaseUrl("no-such-provider")).toBe("");
+ });
+});
+
+describe("the provider list", () => {
+ it("gives every provider what a card needs to be drawn", () => {
+ for (const type of PROVIDER_TYPES) {
+ expect(type.id, `${type.id} has an id`).toBeTruthy();
+ expect(type.name, `${type.id} has a name`).toBeTruthy();
+ expect(type.iconUrl, `${type.id} has an icon`).toBeTruthy();
}
});
- it("asks for no key from local runtimes and an optional one from arbitrary endpoints", () => {
- const byId = new Map(PROVIDER_TYPES.map(p => [p.id, p]));
- expect(byId.get("ollama")?.apiKey).toBe("none");
- expect(byId.get("lmstudio")?.apiKey).toBe("none");
- // A generic endpoint may sit behind an authenticating proxy (vLLM, LiteLLM).
- expect(byId.get("openai-compatible")?.apiKey).toBe("optional");
- // Subscription auth belongs to Claude Code itself.
- expect(byId.get("claude-agent")?.apiKey).toBe("none");
- expect(byId.get("claude-agent")?.baseUrl).toBe("none");
+ it("gives every provider an endpoint, bar the ones that are not reached over one", () => {
+ for (const type of PROVIDER_TYPES) {
+ // A subscription provider is driven through its own program, so there is no address to
+ // offer and its card asks for none.
+ const expected = type.baseUrl === "none" ? "" : expect.stringMatching(/^https?:\/\//);
+ expect(type.defaultBaseUrl, `${type.id}'s endpoint`).toEqual(expected);
+ }
});
- it("marks the CLI-driven cards as the ones a browser-only build cannot run", () => {
- // They work by running a CLI as a separate process, which the standalone
- // build — whose entire server is a worker in the page — has nowhere to do;
- // the picker disables those cards there rather than dropping them. Every
- // other provider is reached over HTTP and so runs anywhere.
- expect(PROVIDER_TYPES.filter(p => p.needsHostProcess).map(p => p.id)).toEqual(["claude-agent", "copilot-agent"]);
+ it("keeps the ids apart, since the stored config is keyed by them", () => {
+ const ids = PROVIDER_TYPES.map((type) => type.id);
+ expect(new Set(ids).size).toBe(ids.length);
});
- it("explains the account behind every card that asks for neither key nor endpoint", () => {
- // With both fields gone the connection step would otherwise be empty, so
- // the blurb is what the user reads there — and it must be the right one:
- // each names its own CLI and login command.
- for (const card of PROVIDER_TYPES.filter(p => p.apiKey === "none" && p.baseUrl === "none")) {
- expect(card.connectionDescription, `${card.id} has nothing to show on the connection step`).toBeTruthy();
+ it("files every provider under a section the list actually renders", () => {
+ const groups = new Set([ "cloud", "subscription", "local", "custom" ]);
+ for (const type of PROVIDER_TYPES) {
+ expect(groups, `${type.id} is filed somewhere`).toContain(type.group);
}
});
- it("gives every card a logo", () => {
- // SelectableCard is only passed `iconUrl`, so a card without one renders
- // with an empty icon slot rather than falling back to anything.
- for (const card of PROVIDER_TYPES) {
- expect(card.iconUrl, `no icon for ${card.id}`).toBeTruthy();
+ it("prefills only the providers that run on the user's own machine", () => {
+ for (const type of PROVIDER_TYPES.filter((candidate) => candidate.prefillBaseUrl)) {
+ expect(type.baseUrl, `${type.id} asks for its endpoint`).toBe("required");
}
});
});
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
index 5923961903..ebb1a24524 100644
--- a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.tsx
@@ -147,7 +147,11 @@ export const PROVIDER_TYPES: ProviderType[] = [
}
];
-function isValidBaseUrl(value: string): boolean {
+/**
+ * Whether an endpoint is one the app could actually reach. An empty field is not invalid — it means
+ * the provider's own default stands — so it is only the shape of what was typed that is judged here.
+ */
+export function isValidBaseUrl(value: string): boolean {
if (!value) {
return true;
}
@@ -159,6 +163,29 @@ function isValidBaseUrl(value: string): boolean {
}
}
+/**
+ * Whether the connection step has been given everything the provider needs of it: a key where one is
+ * required, an endpoint where the provider has no default of its own, and nothing malformed in the
+ * endpoint field either way.
+ *
+ * Both fields are taken as typed; the trimming is done here so a field of spaces counts as empty.
+ */
+export function isConnectionValid(providerType: ProviderType | undefined, apiKey: string, baseUrl: string): boolean {
+ const apiKeyMode = providerType?.apiKey ?? "required";
+ const baseUrlMode = providerType?.baseUrl ?? "advanced";
+ const trimmedBaseUrl = baseUrl.trim();
+
+ if (apiKeyMode === "required" && !apiKey.trim()) {
+ return false;
+ }
+
+ if (baseUrlMode === "none") {
+ return true;
+ }
+
+ return isValidBaseUrl(trimmedBaseUrl) && (baseUrlMode !== "required" || !!trimmedBaseUrl);
+}
+
/**
* Pick a provider, enter its credentials, choose its models. Named rather than
* numbered because editing skips the first one — the provider type of a saved
@@ -202,8 +229,7 @@ export default function AddProviderModal({ show, onHidden, onSave, existingProvi
const trimmedApiKey = apiKey.trim();
const trimmedBaseUrl = baseUrl.trim();
const baseUrlIsValid = isValidBaseUrl(trimmedBaseUrl);
- const connectionValid = (apiKeyMode !== "required" || !!trimmedApiKey)
- && (baseUrlMode === "none" || (baseUrlIsValid && (baseUrlMode !== "required" || !!trimmedBaseUrl)));
+ const connectionValid = isConnectionValid(providerType, apiKey, baseUrl);
/**
* Picking a card swaps in that provider's endpoint — so the right port is
diff --git a/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.wizard.spec.tsx b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.wizard.spec.tsx
new file mode 100644
index 0000000000..12612d3879
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/llm/AddProviderModal.wizard.spec.tsx
@@ -0,0 +1,202 @@
+import type { LlmModelInfo } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({ onSave: vi.fn(), onHidden: vi.fn() }));
+
+vi.mock("../../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("react-i18next", () => ({ Trans: ({ i18nKey }: { i18nKey: string }) => <>{i18nKey}</> }));
+
+/*
+ * Stands in for the wizard shell, keeping only what drives it: the step being shown, and the one
+ * button that leaves it. The real one opens through Bootstrap, which happy-dom cannot carry — and it
+ * throws from an effect, which abandons the rest of that flush along with it.
+ */
+vi.mock("../../../react/WizardModal", () => ({
+ default: ({ show, steps, step, onStepChange, onFinish }: {
+ show?: boolean;
+ steps: { id: string; content: preact.ComponentChildren; canContinue?: boolean }[];
+ step: string;
+ onStepChange: (id: string) => void;
+ onFinish: () => void;
+ }) => {
+ if (!show) return null;
+
+ const index = steps.findIndex((candidate) => candidate.id === step);
+ const current = steps[index];
+ const isLast = index === steps.length - 1;
+
+ return (
+ <div className="wizard-stub">
+ <div className="wizard-step">{current?.content}</div>
+ <button
+ className="wizard-next"
+ disabled={current?.canContinue === false}
+ onClick={() => (isLast ? onFinish() : onStepChange(steps[index + 1].id))}
+ >next</button>
+ </div>
+ );
+ }
+}));
+
+// Listing a provider's models is a request of its own, and none of these cases are about it.
+vi.mock("./ModelSelection", () => ({ default: () => <div className="model-selection-stub" /> }));
+
+import AddProviderModal, { type LlmProviderConfig } from "./AddProviderModal";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+function open(existingProvider?: LlmProviderConfig) {
+ act(() => {
+ render(null, host);
+ render(
+ <AddProviderModal
+ show
+ onHidden={mocks.onHidden}
+ onSave={mocks.onSave}
+ existingProvider={existingProvider}
+ />,
+ host
+ );
+ });
+}
+
+const nextButton = () => document.querySelector<HTMLButtonElement>("button.wizard-next");
+const providerCard = (name: string) =>
+ [ ...document.querySelectorAll<HTMLElement>(".selectable-card") ]
+ .find((card) => card.textContent?.includes(name));
+const textBoxes = () => [ ...document.querySelectorAll<HTMLInputElement>(".wizard-step input[type='text'], .wizard-step input[type='password']") ];
+
+/** Types into one of the connection fields, as a keystroke rather than an assignment. */
+function type(box: HTMLInputElement | undefined, value: string) {
+ if (!box) return;
+ act(() => {
+ box.value = value;
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+/** Walks to the last step, where the wizard's button commits what has been entered. */
+function finish() {
+ act(() => void nextButton()?.click());
+ act(() => void nextButton()?.click());
+}
+
+describe("picking a provider", () => {
+ it("holds the step until one has been chosen, rather than taking whichever is first", () => {
+ open();
+ expect(nextButton()?.disabled).toBe(true);
+ });
+
+ it("moves straight on once a card is pressed, the choice being the action", () => {
+ open();
+ act(() => providerCard("OpenAI")?.click());
+
+ // The picker is gone: what is on screen now is the chosen provider's connection step.
+ expect(providerCard("OpenAI")).toBeUndefined();
+ expect(textBoxes().length).toBeGreaterThan(0);
+ });
+
+ it("writes in the endpoint only for a provider whose port is the user's to get right", () => {
+ open();
+ act(() => providerCard("Ollama")?.click());
+ // Self-hosted: the default is filled in so the port can be corrected rather than guessed.
+ expect(textBoxes().some((box) => box.value.startsWith("http"))).toBe(true);
+
+ open();
+ act(() => providerCard("OpenAI")?.click());
+ // A vendor's endpoint is a hint only, so an unedited field stores no override.
+ expect(textBoxes().every((box) => box.value === "")).toBe(true);
+ });
+});
+
+describe("the connection step", () => {
+ it("will not go on without the key a vendor requires, and will once it has one", () => {
+ open();
+ act(() => providerCard("OpenAI")?.click());
+ expect(nextButton()?.disabled).toBe(true);
+
+ type(textBoxes()[0], "sk-abc");
+ expect(nextButton()?.disabled).toBe(false);
+ });
+
+ it("asks nothing of a provider that signs in through its own program", () => {
+ open();
+ act(() => providerCard("Claude Code")?.click());
+
+ // No key, no endpoint — the step is complete the moment it is reached.
+ expect(nextButton()?.disabled).toBe(false);
+ });
+
+ it("opens on the connection step when editing, the provider type being fixed by then", () => {
+ open({ id: "openai_1", name: "OpenAI", provider: "openai", apiKey: "sk-old" });
+
+ expect(providerCard("OpenAI")).toBeUndefined();
+ expect(textBoxes()[0]?.value).toBe("sk-old");
+ });
+});
+
+describe("what gets saved", () => {
+ it("stores the key and the provider it belongs to, and no endpoint that was never set", () => {
+ open();
+ act(() => providerCard("OpenAI")?.click());
+ type(textBoxes()[0], " sk-abc ");
+ finish();
+
+ const [ saved ] = mocks.onSave.mock.calls[0] as [ LlmProviderConfig ];
+ expect(saved).toMatchObject({ provider: "openai", name: "OpenAI", apiKey: "sk-abc" });
+ // Left out entirely rather than stored empty, so the provider's own default stands.
+ expect(saved).not.toHaveProperty("baseURL");
+ });
+
+ it("stores no key at all for a provider that authenticates elsewhere", () => {
+ open();
+ act(() => providerCard("Claude Code")?.click());
+ finish();
+
+ const [ saved ] = mocks.onSave.mock.calls[0] as [ LlmProviderConfig ];
+ expect(saved.apiKey).toBe("");
+ expect(saved).not.toHaveProperty("baseURL");
+ });
+
+ it("keeps the id of the provider being edited, so it replaces rather than adds", () => {
+ const existing: LlmProviderConfig = {
+ id: "openai_123",
+ name: "OpenAI",
+ provider: "openai",
+ apiKey: "sk-old",
+ selectedModels: [ { id: "gpt-4" } as LlmModelInfo ]
+ };
+
+ open(existing);
+ type(textBoxes()[0], "sk-new");
+ act(() => void nextButton()?.click());
+ act(() => void nextButton()?.click());
+
+ const [ saved ] = mocks.onSave.mock.calls[0] as [ LlmProviderConfig ];
+ expect(saved.id).toBe("openai_123");
+ expect(saved.apiKey).toBe("sk-new");
+ // The stored selection is carried through rather than reset by reopening the editor.
+ expect(saved.selectedModels).toEqual(existing.selectedModels);
+ });
+
+ it("puts the dialog away once it has saved", () => {
+ open();
+ act(() => providerCard("Claude Code")?.click());
+ finish();
+
+ expect(mocks.onHidden).toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/media.spec.tsx b/apps/client/src/widgets/type_widgets/options/media.spec.tsx
index ed0367f44c..a4fa385058 100644
--- a/apps/client/src/widgets/type_widgets/options/media.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/media.spec.tsx
@@ -15,7 +15,30 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
stored: {} as Record<string, string>,
saved: vi.fn<(name: string, value: string) => void>(),
- standalone: false
+ standalone: false,
+ /** How the batch run reports itself, read again on every poll. */
+ progress: { inProgress: false, total: 0, processed: 0, failed: 0, percentage: 0 },
+ /** Whether asking for a run is accepted at all. */
+ startResult: { success: true } as { success: boolean; message?: string },
+ showMessage: vi.fn(),
+ showError: vi.fn()
+}));
+
+// Replacing the shared server mock means also answering what the modules pulled in alongside the
+// page ask for on import — the keyboard actions, which expect a list.
+vi.mock("../../../services/server", () => ({
+ default: {
+ get: async (url: string) => {
+ if (url === "ocr/batch-progress") return mocks.progress;
+ if (url === "keyboard-actions") return [];
+ return {};
+ },
+ post: async (url: string) => (url === "ocr/batch-process" ? mocks.startResult : {})
+ }
+}));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: mocks.showError }
}));
// `isStandalone` is a const in the target, read here through a getter so a scenario can flip which
@@ -138,6 +161,8 @@ async function choose(title: string, label: string) {
beforeEach(() => {
mocks.standalone = false;
+ mocks.progress = { inProgress: false, total: 0, processed: 0, failed: 0, percentage: 0 };
+ mocks.startResult = { success: true };
host = document.body.appendChild(document.createElement("div"));
});
@@ -240,3 +265,54 @@ describe("the OCR card", () => {
expect(host.querySelector(".media-ocr .tn-card-option")).not.toBeNull();
});
});
+
+/**
+ * Running OCR over everything already stored. The run belongs to the server, so the page's part is
+ * asking for it and then reporting what it hears back — polled, because there is nothing pushed.
+ */
+describe("processing every image at once", () => {
+ const startButton = () => host.querySelector<HTMLButtonElement>("button[name='batch-ocr-start-button']");
+ const progressBar = () => host.querySelector(".media-batch-ocr-progress");
+
+ /** Presses the button and lets the request and its first poll settle. */
+ async function start() {
+ await act(async () => startButton()?.click());
+ await act(async () => {});
+ }
+
+ it("swaps the button for a bar once a run is under way", async () => {
+ mocks.progress = { inProgress: true, total: 10, processed: 3, failed: 0, percentage: 30 };
+ open();
+ await start();
+
+ expect(startButton()).toBeNull();
+ expect(progressBar()).not.toBeNull();
+ });
+
+ it("puts the button back and says what the run came to, once it is over", async () => {
+ mocks.progress = { inProgress: false, total: 4, processed: 4, failed: 0, percentage: 100 };
+ open();
+ await start();
+
+ expect(progressBar()).toBeNull();
+ expect(startButton()).not.toBeNull();
+ expect(mocks.showMessage).toHaveBeenCalledWith(expect.stringContaining("images.batch_ocr_completed"));
+ });
+
+ it("reports a run that finished with failures as a failure, not as a success", async () => {
+ mocks.progress = { inProgress: false, total: 4, processed: 3, failed: 1, percentage: 100 };
+ open();
+ await start();
+
+ expect(mocks.showError).toHaveBeenCalledWith(expect.stringContaining("images.batch_ocr_completed_with_failures"));
+ });
+
+ it("says why when the server will not start one at all", async () => {
+ mocks.startResult = { success: false, message: "no engine" };
+ open();
+ await start();
+
+ expect(mocks.showError).toHaveBeenCalledWith("no engine");
+ expect(progressBar()).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/other.spec.tsx b/apps/client/src/widgets/type_widgets/options/other.spec.tsx
new file mode 100644
index 0000000000..428eafccd3
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/other.spec.tsx
@@ -0,0 +1,205 @@
+import { SANITIZER_DEFAULT_ALLOWED_TAGS } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ stored: {} as Record<string, string>,
+ json: {} as Record<string, unknown>,
+ saved: [] as [ string, unknown ][],
+ post: vi.fn(async (_url: string) => ({})),
+ showMessage: vi.fn(),
+ showError: vi.fn(),
+ /** What a search for `#shareRoot` turns up, and whether what it found is actually shared. */
+ shareRoots: [] as { title: string; isShared: () => boolean }[]
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// Replacing the shared server mock means also answering what the modules pulled in alongside the
+// page ask for on import — the options load and the keyboard actions.
+vi.mock("../../../services/server", () => ({
+ default: {
+ post: mocks.post,
+ get: async (url: string) => (url === "keyboard-actions" ? [] : {})
+ }
+}));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: mocks.showError }
+}));
+
+vi.mock("../../../services/search", () => ({
+ default: { searchForNotes: async () => mocks.shareRoots }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useNoteContext: () => ({ noteContext: undefined }),
+ useTriliumOption: (name: string) => [
+ mocks.stored[name] ?? "",
+ (value: string) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === "true",
+ (value: boolean) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionJson: (name: string) => [
+ mocks.json[name] ?? [],
+ (value: unknown) => void mocks.saved.push([ name, value ])
+ ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import OtherSettings from "./other";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ // Every duration row does arithmetic on a figure and a scale, so none of them may be the empty
+ // string an unset option would answer with.
+ mocks.stored = {
+ eraseEntitiesAfterTimeInSeconds: "86400", eraseEntitiesAfterTimeScale: "1",
+ eraseUnusedAttachmentsAfterSeconds: "86400", eraseUnusedAttachmentsAfterTimeScale: "1",
+ revisionSnapshotTimeInterval: "600", revisionSnapshotTimeIntervalTimeScale: "1",
+ revisionSnapshotNumberLimit: "-1"
+ };
+ mocks.json = {};
+ mocks.saved = [];
+ mocks.shareRoots = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+function open() {
+ act(() => {
+ render(null, host);
+ render(<OtherSettings />, host);
+ });
+}
+
+const button = (name: string) => host.querySelector<HTMLButtonElement>(`button[name='${name}']`);
+
+describe("erasing what has been deleted", () => {
+ it("asks the server to erase now, for notes and for attachments alike", async () => {
+ open();
+
+ await act(async () => button("erase-deleted-notes-now-button")?.click());
+ await act(async () => button("erase-unused-attachments-now-button")?.click());
+
+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([
+ "notes/erase-deleted-notes-now",
+ "notes/erase-unused-attachments-now"
+ ]);
+ });
+});
+
+describe("the revision snapshot limit", () => {
+ it("holds the erase action out of reach while every snapshot is being kept", () => {
+ open();
+ // A negative limit keeps everything, so there is no excess for the action to drop.
+ expect(button("erase-excess-revisions-button")?.disabled).toBe(true);
+
+ mocks.stored = { ...mocks.stored, revisionSnapshotNumberLimit: "10" };
+ open();
+ expect(button("erase-excess-revisions-button")?.disabled).toBe(false);
+ });
+
+ it("holds a limit typed below the keep-everything one up to it, rather than storing nonsense", () => {
+ mocks.stored = { ...mocks.stored, revisionSnapshotNumberLimit: "10" };
+ open();
+
+ // The last figure on the page: the three durations above it are the erasure and snapshot
+ // intervals, and this is the only one that is a count rather than a time.
+ const box = [ ...host.querySelectorAll<HTMLInputElement>("input[type='number']") ].at(-1);
+ act(() => {
+ if (box) {
+ box.value = "-5";
+ box.dispatchEvent(new Event("change", { bubbles: true }));
+ }
+ });
+
+ expect(mocks.saved.at(-1)).toEqual([ "revisionSnapshotNumberLimit", -1 ]);
+ });
+});
+
+describe("redirecting the bare domain", () => {
+ /** Turns the redirect on, which is what sends the page looking for a share root. */
+ async function turnOn() {
+ const toggle = host.querySelector<HTMLInputElement>("input.switch-toggle[id^='redirect-bare-domain-']");
+ await act(async () => void toggle?.dispatchEvent(new Event("input", { bubbles: true })));
+ await act(async () => {});
+ }
+
+ it("names the note the bare domain will land on, once there is a shared one", async () => {
+ mocks.shareRoots = [ { title: "Public", isShared: () => true } ];
+ open();
+ await turnOn();
+
+ expect(mocks.showMessage).toHaveBeenCalled();
+ expect(mocks.showError).not.toHaveBeenCalled();
+ expect(mocks.saved).toContainEqual([ "redirectBareDomain", true ]);
+ });
+
+ it("says the note it found is not shared, which is what would make the redirect land nowhere", async () => {
+ mocks.shareRoots = [ { title: "Private", isShared: () => false } ];
+ open();
+ await turnOn();
+
+ expect(mocks.showError).toHaveBeenCalled();
+ expect(mocks.showMessage).not.toHaveBeenCalled();
+ // Stored all the same: the setting is the user's, and the note can be shared afterwards.
+ expect(mocks.saved).toContainEqual([ "redirectBareDomain", true ]);
+ });
+
+ it("says there is no share root at all, which is a different thing to fix", async () => {
+ mocks.shareRoots = [];
+ open();
+ await turnOn();
+
+ expect(mocks.showError).toHaveBeenCalled();
+ });
+
+ it("looks for nothing when the redirect is being turned off", async () => {
+ mocks.stored = { ...mocks.stored, redirectBareDomain: "true" };
+ open();
+ await turnOn();
+
+ expect(mocks.showMessage).not.toHaveBeenCalled();
+ expect(mocks.showError).not.toHaveBeenCalled();
+ expect(mocks.saved).toContainEqual([ "redirectBareDomain", false ]);
+ });
+});
+
+describe("the tags an HTML import may keep", () => {
+ it("reads the stored set out as one line, and takes back what is typed over it", () => {
+ mocks.json = { allowedHtmlTags: [ "p", "strong", "em" ] };
+ open();
+
+ const textarea = host.querySelector<HTMLTextAreaElement>("textarea.allowed-html-tags");
+ expect(textarea?.value).toBe("p strong em");
+
+ act(() => {
+ if (textarea) {
+ textarea.value = "p, strong\nem b";
+ textarea.dispatchEvent(new Event("focusout", { bubbles: true }));
+ }
+ });
+
+ // Split on commas, newlines or runs of spaces alike — however the list was pasted in.
+ expect(mocks.saved.at(-1)).toEqual([ "allowedHtmlTags", [ "p", "strong", "em", "b" ] ]);
+ });
+
+ it("puts back the set the sanitizer ships with", () => {
+ open();
+ act(() => void button("reset-allowed-html-tags-button")?.click());
+
+ expect(mocks.saved.at(-1)).toEqual([ "allowedHtmlTags", SANITIZER_DEFAULT_ALLOWED_TAGS ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/password.spec.tsx b/apps/client/src/widgets/type_widgets/options/password.spec.tsx
new file mode 100644
index 0000000000..1b856d154b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/password.spec.tsx
@@ -0,0 +1,273 @@
+import type { OAuthStatus } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ const state = {
+ electron: false,
+ stored: {} as Record<string, string>,
+ oauth: {} as Partial<OAuthStatus>,
+ totpSet: false
+ };
+
+ return {
+ state,
+ get: vi.fn(async (url: string) => {
+ if (url === "oauth/status") return state.oauth;
+ if (url === "totp/status") return { set: state.totpSet };
+ if (url === "totp_recovery/enabled") return { success: true, keysExist: false };
+ if (url === "keyboard-actions") return [];
+ return {};
+ }),
+ post: vi.fn(async (_url: string): Promise<{ success: boolean; message?: string }> => ({ success: true })),
+ confirm: vi.fn(async () => true),
+ showMessage: vi.fn(),
+ showError: vi.fn(),
+ resetProtectedSession: vi.fn()
+ };
+});
+
+// The whole sign-in section is server-only; the desktop app authenticates differently.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isElectron: () => mocks.state.electron
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+/*
+ * Stands in for the Bootstrap shell, keeping only what the dialog inside it is driven through. The
+ * real one opens through jQuery and Bootstrap, which happy-dom cannot carry — and it throws from an
+ * effect, which abandons the rest of that flush along with it.
+ */
+vi.mock("../../react/Modal", () => ({
+ default: ({ className, show, footer, onSubmit, children }: {
+ className?: string;
+ show?: boolean;
+ footer?: preact.ComponentChildren;
+ onSubmit?: () => void;
+ children?: preact.ComponentChildren;
+ }) => (show
+ ? <div className={`modal ${className ?? ""}`}>
+ <form onSubmit={(e) => { e.preventDefault(); onSubmit?.(); }}>
+ <div className="modal-body">{children}</div>
+ <div className="modal-footer">{footer}</div>
+ </form>
+ </div>
+ : null)
+}));
+
+vi.mock("../../../services/server", () => ({
+ default: { get: mocks.get, post: mocks.post, put: async () => ({}), remove: async () => ({}) }
+}));
+
+vi.mock("../../../services/dialog", () => ({
+ default: { confirm: mocks.confirm, prompt: vi.fn() }
+}));
+
+// A changed password invalidates whatever the old one unlocked, so the session is dropped with it.
+vi.mock("../../../services/protected_session_holder", () => ({
+ default: { resetProtectedSession: mocks.resetProtectedSession }
+}));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: mocks.showError }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: (name: string) => [ mocks.state.stored[name] ?? "", vi.fn() ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import PasswordSettings from "./password";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.state.electron = false;
+ // The protected-session row does arithmetic on both, so neither may be the empty string an
+ // unset option would answer with.
+ mocks.state.stored = { protectedSessionTimeout: "600", protectedSessionTimeoutTimeScale: "1" };
+ mocks.state.oauth = {};
+ mocks.state.totpSet = false;
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+async function open() {
+ await act(async () => {
+ render(null, host);
+ render(<PasswordSettings />, host);
+ });
+}
+
+// Read from the text leading the heading: a status badge sits in the same line, and its own words
+// would otherwise be run together with the title's.
+const cardHeadings = () =>
+ [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.firstChild?.textContent);
+const badgeTone = () => host.querySelector(".mfa-status-badge")?.className;
+const button = (name: string) => host.querySelector<HTMLButtonElement>(`button[name='${name}']`);
+
+describe("the page on a desktop build", () => {
+ it("offers the password settings alone, the sign-in method being the server's business", async () => {
+ mocks.state.electron = true;
+ await open();
+
+ expect(cardHeadings()).toEqual([ "password.heading", "password.protected_session_timeout" ]);
+ expect(mocks.get).not.toHaveBeenCalledWith("oauth/status");
+ });
+});
+
+describe("choosing a sign-in method", () => {
+ it("offers the local password with two-factor beside it, by default", async () => {
+ await open();
+
+ expect(cardHeadings()).toContain("multi_factor_authentication.authentication_title");
+ // TOTP, not the OpenID card: the two are alternatives, never both.
+ expect(cardHeadings()).toContain("multi_factor_authentication.totp_section_title");
+ expect(cardHeadings()).not.toContain("multi_factor_authentication.oauth_title");
+ });
+
+ it("swaps to the OpenID card once that is the chosen method", async () => {
+ mocks.state.stored = { ...mocks.state.stored, mfaMethod: "oauth" };
+ await open();
+
+ expect(cardHeadings()).toContain("multi_factor_authentication.oauth_title");
+ expect(cardHeadings()).not.toContain("multi_factor_authentication.totp_section_title");
+ });
+});
+
+describe("the OpenID card", () => {
+ beforeEach(() => {
+ mocks.state.stored = { ...mocks.state.stored, mfaMethod: "oauth" };
+ });
+
+ it("says the server is not set up, and names the variables it is missing", async () => {
+ mocks.state.oauth = { missingVars: [ "oauthClientId", "oauthClientSecret" ] };
+ await open();
+
+ expect(badgeTone()).toContain("inactive");
+ expect(host.querySelector(".mfa-notice .admonition")).not.toBeNull();
+ // Nothing to connect with yet, so nothing is offered.
+ expect(button("oauth-connect-button")).toBeNull();
+ });
+
+ it("offers to bind an account once the server is set up but none is bound", async () => {
+ mocks.state.oauth = { missingVars: [], enrolled: false };
+ await open();
+
+ expect(badgeTone()).toContain("pending");
+ expect(button("oauth-connect-button")).not.toBeNull();
+ expect(button("oauth-disconnect-button")).toBeNull();
+ });
+
+ it("shows the bound account and the way to be rid of it once one is bound", async () => {
+ mocks.state.oauth = {
+ missingVars: [],
+ enrolled: true,
+ name: "Ada",
+ email: "[email protected]",
+ issuerUrl: "https://accounts.example.com"
+ };
+ await open();
+
+ expect(badgeTone()).toContain("active");
+ expect(host.textContent).toContain("[email protected]");
+ expect(button("oauth-connect-button")).toBeNull();
+ expect(button("oauth-disconnect-button")).not.toBeNull();
+ });
+
+ it("asks before unbinding, and leaves the account alone when the answer is no", async () => {
+ mocks.state.oauth = { missingVars: [], enrolled: true, name: "Ada", email: "[email protected]" };
+ mocks.confirm.mockResolvedValueOnce(false);
+ await open();
+
+ await act(async () => button("oauth-disconnect-button")?.click());
+ expect(mocks.post).not.toHaveBeenCalledWith("oauth/disconnect");
+
+ await act(async () => button("oauth-disconnect-button")?.click());
+ expect(mocks.post).toHaveBeenCalledWith("oauth/disconnect");
+ });
+});
+
+describe("changing the password", () => {
+ const dialog = () => document.querySelector(".change-password-modal");
+ const boxes = () => [ ...(dialog()?.querySelectorAll<HTMLInputElement>("input[type='password']") ?? []) ];
+
+ /** Opens the dialog and fills it in: the current password, then the new one twice over. */
+ async function fillIn(oldPassword: string, first: string, second: string) {
+ await act(async () => button("change-password-button")?.click());
+
+ for (const [ index, value ] of [ oldPassword, first, second ].entries()) {
+ await act(async () => {
+ const box = boxes()[index];
+ if (box) {
+ box.value = value;
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ }
+
+ await act(async () => {
+ dialog()?.querySelector<HTMLFormElement>("form")?.requestSubmit();
+ });
+ await act(async () => {});
+ }
+
+ it("asks for the current password and the new one twice over", async () => {
+ await open();
+ await act(async () => button("change-password-button")?.click());
+
+ expect(boxes()).toHaveLength(3);
+ });
+
+ it("refuses a pair that does not match, without asking the server anything", async () => {
+ await open();
+ await fillIn("old", "new-one", "new-other");
+
+ expect(mocks.showError).toHaveBeenCalledWith("password.password_mismatch");
+ expect(mocks.post).not.toHaveBeenCalled();
+ });
+
+ it("sends the change and clears the protected session, which the old password unlocked", async () => {
+ await open();
+ await fillIn("old", "new", "new");
+
+ expect(mocks.post).toHaveBeenCalledWith("password/change", {
+ current_password: "old",
+ new_password: "new"
+ });
+ expect(mocks.resetProtectedSession).toHaveBeenCalled();
+ expect(mocks.showMessage).toHaveBeenCalledWith("password.password_changed_success");
+ });
+
+ it("reports what the server objected to, and keeps the session as it was", async () => {
+ mocks.post.mockResolvedValueOnce({ success: false, message: "password.wrong_password" });
+ await open();
+ await fillIn("wrong", "new", "new");
+
+ expect(mocks.showError).toHaveBeenCalledWith("password.wrong_password");
+ expect(mocks.resetProtectedSession).not.toHaveBeenCalled();
+ });
+});
+
+describe("the password actions", () => {
+ it("asks before resetting, since it costs access to every protected note", async () => {
+ mocks.confirm.mockResolvedValueOnce(false);
+ await open();
+
+ await act(async () => button("reset-password-button")?.click());
+ expect(mocks.post).not.toHaveBeenCalled();
+
+ await act(async () => button("reset-password-button")?.click());
+ expect(mocks.post.mock.calls[0][0]).toContain("password/reset");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/security.spec.tsx b/apps/client/src/widgets/type_widgets/options/security.spec.tsx
new file mode 100644
index 0000000000..7404a155a3
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/security.spec.tsx
@@ -0,0 +1,135 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ electron: true,
+ /** What the settings currently are, as the options store answers them. */
+ stored: {} as Record<string, boolean>,
+ /** What the main process answers when asked to write one — refusing leaves nothing pending. */
+ confirms: true
+}));
+
+// `isElectron` decides both whether these settings can be written at all and whether the LAN card is
+// on offer, so a scenario has to be able to say which kind of build it is pretending to be.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isElectron: () => mocks.electron
+}));
+
+// i18next is never initialised here and answers `undefined` until it is, which would make every
+// assertion about a description true of any string at all.
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOptionBool: (name: string) => [ mocks.stored[name] === true, vi.fn() ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import SecuritySettings from "./security";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.electron = true;
+ mocks.stored = {};
+ mocks.confirms = true;
+ (window as unknown as { electronApi: unknown }).electronApi = {
+ security: {
+ setBackendScriptingEnabled: vi.fn(async () => mocks.confirms),
+ setSqlConsoleEnabled: vi.fn(async () => mocks.confirms),
+ setLanAccessEnabled: vi.fn(async () => mocks.confirms)
+ }
+ };
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ delete (window as unknown as { electronApi?: unknown }).electronApi;
+});
+
+function open() {
+ act(() => {
+ render(<SecuritySettings />, host);
+ });
+}
+
+const switches = () => [ ...host.querySelectorAll<HTMLInputElement>("input.switch-toggle") ];
+const restartOffered = () => !!host.querySelector(".restart-action button");
+
+/** Flips a switch, which writes the setting and — once confirmed — leaves it pending a restart. */
+async function flip(index: number) {
+ await act(async () => {
+ switches()[index].dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+describe("the security settings", () => {
+ it("offers one switch per setting, with nothing to restart for until something changes", () => {
+ open();
+
+ // Backend scripting, SQL console and LAN access — the last of which is desktop-only.
+ expect(switches()).toHaveLength(3);
+ expect(restartOffered()).toBe(false);
+ });
+
+ it("asks for a restart once a setting has actually been written, saying so on the row too", async () => {
+ open();
+ await flip(0);
+
+ const api = (window as unknown as { electronApi: { security: { setBackendScriptingEnabled: ReturnType<typeof vi.fn> } } }).electronApi;
+ expect(api.security.setBackendScriptingEnabled).toHaveBeenCalledWith(true);
+ expect(restartOffered()).toBe(true);
+
+ const row = switches()[0].closest(".tn-card-option");
+ expect(row?.querySelector(".tn-card-option-description")?.textContent).toBe("security.restart_required");
+ });
+
+ it("writes each setting through its own channel, never one through another's", async () => {
+ open();
+ const api = (window as unknown as { electronApi: { security: Record<string, ReturnType<typeof vi.fn>> } }).electronApi;
+
+ await flip(1);
+ expect(api.security.setSqlConsoleEnabled).toHaveBeenCalledWith(true);
+ expect(api.security.setBackendScriptingEnabled).not.toHaveBeenCalled();
+
+ await flip(2);
+ expect(api.security.setLanAccessEnabled).toHaveBeenCalledWith(true);
+ // One restart covers however many were changed.
+ expect(restartOffered()).toBe(true);
+ });
+
+ it("leaves everything as it was when the main process refuses the write", async () => {
+ mocks.confirms = false;
+ open();
+ await flip(0);
+
+ expect(restartOffered()).toBe(false);
+ });
+
+ it("treats a setting turned back to what it already was as no change at all", async () => {
+ open();
+ await flip(0);
+ expect(restartOffered()).toBe(true);
+
+ await flip(0);
+ expect(restartOffered()).toBe(false);
+ });
+
+ it("holds the switches out of reach on a server build, and says where to set them instead", () => {
+ mocks.electron = false;
+ open();
+
+ // LAN access is not offered at all: a server is already bound to its configured interface.
+ expect(switches()).toHaveLength(2);
+ expect(switches().every((toggle) => toggle.disabled)).toBe(true);
+
+ // The config-file and environment-variable instructions, which the desktop build has no use for.
+ expect(host.querySelectorAll(".collapsible")).toHaveLength(2);
+ expect(restartOffered()).toBe(false);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.editing.spec.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.editing.spec.tsx
new file mode 100644
index 0000000000..165f279965
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.editing.spec.tsx
@@ -0,0 +1,220 @@
+import type { KeyboardShortcut } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * Two actions clash on Ctrl+J, one of them also carries an OS-level shortcut, and two differ from
+ * their defaults — so every filter has something to keep and something to drop.
+ */
+const SHORTCUTS = vi.hoisted(() => ([
+ { separator: "Navigation" },
+ {
+ actionName: "back",
+ friendlyName: "Back",
+ effectiveShortcuts: [ "Alt+Left" ],
+ defaultShortcuts: [ "Alt+Left" ],
+ scope: "window"
+ },
+ {
+ actionName: "jumpTo",
+ friendlyName: "Jump to note",
+ effectiveShortcuts: [ "Ctrl+J", "global:Ctrl+G" ],
+ defaultShortcuts: [ "Ctrl+J" ],
+ scope: "window"
+ },
+ { separator: "Editing" },
+ {
+ actionName: "bold",
+ friendlyName: "Bold",
+ effectiveShortcuts: [ "Ctrl+J" ],
+ defaultShortcuts: [ "Ctrl+B" ],
+ scope: "window"
+ }
+] as KeyboardShortcut[]));
+
+const mocks = vi.hoisted(() => ({
+ /** Every option write, which is how a shortcut is stored. */
+ saved: [] as [ string, string ][],
+ savedMany: [] as Record<string, string>[],
+ confirm: vi.fn(async () => true)
+}));
+
+// A fresh copy per request: `keyboard_actions` reads the same route as it loads and normalizes what
+// it gets in place, which would otherwise strip the fixture's global shortcut before the page sees it.
+vi.mock("../../../services/server", () => ({
+ default: { get: vi.fn(async () => structuredClone(SHORTCUTS)) }
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// Only the desktop build can claim a combination from the OS, so only there is the globe a button
+// rather than a mark saying that a shortcut already is one.
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../../services/utils")>()),
+ isElectron: () => true
+}));
+
+vi.mock("../../../services/options", () => ({
+ default: {
+ save: (name: string, value: string) => void mocks.saved.push([ name, value ]),
+ saveMany: (values: Record<string, string>) => void mocks.savedMany.push(values),
+ get: () => "[]"
+ }
+}));
+
+vi.mock("../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));
+
+vi.mock("./components/OptionsPageHeader", () => ({
+ default: ({ actions, below }: { actions?: preact.ComponentChildren; below?: preact.ComponentChildren }) =>
+ <div className="header-stub">{actions}{below}</div>
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useStaticTooltip: vi.fn()
+}));
+
+import ShortcutSettings from "./shortcuts";
+
+let host: HTMLElement;
+
+beforeEach(async () => {
+ mocks.saved = [];
+ mocks.savedMany = [];
+ host = document.body.appendChild(document.createElement("div"));
+ await act(async () => {
+ render(<ShortcutSettings />, host);
+ });
+ // The list is fetched as the page mounts, so it arrives a turn after the first render.
+ await act(async () => {});
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+const shortcutNames = () =>
+ [ ...host.querySelectorAll(".tn-card-option-label") ].map((label) => label.textContent?.trim());
+const categories = () =>
+ [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.textContent);
+const conflictsBadge = () => host.querySelector<HTMLElement>(".shortcut-conflicts-badge");
+
+/** The row for an action, found by the name it carries. */
+function rowFor(name: string) {
+ return [ ...host.querySelectorAll(".tn-card-option") ]
+ .find((row) => row.querySelector(".tn-card-option-label")?.textContent?.includes(name));
+}
+
+/** Picks one of the filter menu's entries. The menu is only built once the dropdown is opened. */
+async function chooseFilter(index: number) {
+ await act(async () => host.querySelector<HTMLElement>(".header-stub .dropdown button")?.click());
+
+ const items = [ ...host.querySelectorAll<HTMLElement>(".header-stub .dropdown-menu .dropdown-item") ];
+ await act(async () => items[index]?.click());
+}
+
+/** What was written for an action, parsed back into the list of shortcuts it stands for. */
+function storedFor(actionName: string): string[] | undefined {
+ const written = mocks.saved.find(([ name ]) => name.toLowerCase().includes(actionName.toLowerCase()));
+ return written ? JSON.parse(written[1]) : undefined;
+}
+
+describe("flagging conflicts", () => {
+ it("counts clashing combinations rather than the actions caught up in them", () => {
+ // Two actions on Ctrl+J is one conflict, not two.
+ expect(conflictsBadge()?.textContent).toContain("shortcuts.conflicts_badge");
+ expect(host.querySelectorAll(".shortcut-chip.conflict").length).toBe(2);
+ });
+
+ it("groups the clashing actions by the combination they collide on, when filtered to them", async () => {
+ await act(async () => conflictsBadge()?.click());
+
+ // Filed under the combination itself rather than under the sections they came from.
+ expect(categories()).toEqual([ "Ctrl+J" ]);
+ expect(shortcutNames()).toHaveLength(2);
+ });
+
+ it("puts the whole list back when the badge is pressed again", async () => {
+ await act(async () => conflictsBadge()?.click());
+ await act(async () => conflictsBadge()?.click());
+
+ expect(categories()).toEqual([ "Navigation", "Editing" ]);
+ });
+});
+
+describe("the filter menu", () => {
+ it("keeps only the actions carrying an OS-level shortcut", async () => {
+ // All, conflicts, global, modified — in the order the menu offers them.
+ await chooseFilter(2);
+
+ expect(shortcutNames()?.length).toBe(1);
+ expect(shortcutNames()[0]).toContain("Jump to note");
+ });
+
+ it("keeps only the actions that differ from what they shipped with", async () => {
+ await chooseFilter(3);
+
+ // Back is untouched; the other two have both been changed.
+ expect(shortcutNames()).toHaveLength(2);
+ expect(shortcutNames().join(" ")).not.toContain("Back");
+ });
+
+ it("brings everything back when the filter is cleared", async () => {
+ await chooseFilter(2);
+ await chooseFilter(0);
+
+ expect(categories()).toEqual([ "Navigation", "Editing" ]);
+ });
+});
+
+describe("editing an action's shortcuts", () => {
+ it("stores the rest when one is removed", async () => {
+ const remove = rowFor("Jump to note")?.querySelector<HTMLButtonElement>(".shortcut-chip-remove");
+ await act(async () => remove?.click());
+
+ expect(storedFor("jumpTo")).toEqual([ "global:Ctrl+G" ]);
+ });
+
+ it("rewrites a shortcut with the global prefix rather than adding a second one", async () => {
+ const [ makeGlobal ] = [ ...(rowFor("Jump to note")?.querySelectorAll<HTMLButtonElement>(".shortcut-chip-global") ?? []) ];
+ await act(async () => makeGlobal?.click());
+
+ expect(storedFor("jumpTo")).toEqual([ "global:Ctrl+J", "global:Ctrl+G" ]);
+ });
+
+ it("offers a way back to the default only where something was changed", () => {
+ expect(rowFor("Back")?.querySelector(".shortcut-revert-slot button")).toBeNull();
+ expect(rowFor("Bold")?.querySelector(".shortcut-revert-slot button")).not.toBeNull();
+ });
+
+ it("marks a changed action, so it reads as changed without comparing anything", () => {
+ expect(rowFor("Back")?.querySelector(".shortcut-modified-indicator")).toBeNull();
+ expect(rowFor("Bold")?.querySelector(".shortcut-modified-indicator")).not.toBeNull();
+ });
+
+ it("puts back what the action shipped with when reverted", async () => {
+ const revert = rowFor("Bold")?.querySelector<HTMLButtonElement>(".shortcut-revert-slot button");
+ await act(async () => revert?.click());
+
+ expect(storedFor("bold")).toEqual([ "Ctrl+B" ]);
+ });
+});
+
+describe("setting everything back to default", () => {
+ it("asks first, and writes only the actions that had actually been changed", async () => {
+ const reset = [ ...host.querySelectorAll<HTMLButtonElement>(".header-stub button") ]
+ .find((button) => button.textContent?.includes("shortcuts.set_all_to_default"));
+
+ mocks.confirm.mockResolvedValueOnce(false);
+ await act(async () => reset?.click());
+ expect(mocks.savedMany).toEqual([]);
+
+ await act(async () => reset?.click());
+ const written = mocks.savedMany[0] ?? {};
+ // Back already matches its default, so writing it would be a change record for nothing.
+ expect(Object.keys(written)).toHaveLength(2);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/sync.spec.tsx b/apps/client/src/widgets/type_widgets/options/sync.spec.tsx
new file mode 100644
index 0000000000..cb8591458d
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/sync.spec.tsx
@@ -0,0 +1,122 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ stored: {} as Record<string, string>,
+ /** Every option write, in the order it was made — the test connection depends on that order. */
+ saved: [] as [ string, string ][],
+ post: vi.fn(async () => ({ success: true, message: "ok" })),
+ showMessage: vi.fn(),
+ showError: vi.fn()
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// Replacing the shared server mock means also answering what the modules pulled in alongside the
+// page ask for on import — the options load and the keyboard actions.
+vi.mock("../../../services/server", () => ({
+ default: {
+ post: mocks.post,
+ get: async (url: string) => (url === "keyboard-actions" ? [] : {})
+ }
+}));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: mocks.showError }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useTriliumOption: (name: string) => [
+ mocks.stored[name] ?? "",
+ async (value: string) => void mocks.saved.push([ name, value ])
+ ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import SyncOptions from "./sync";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ // The timeout row reads a figure and a scale and does arithmetic on both, so it needs real
+ // values rather than the empty string an unset option would answer with.
+ mocks.stored = { syncServerTimeout: "120", syncServerTimeoutTimeScale: "1" };
+ mocks.saved = [];
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+function open() {
+ act(() => {
+ render(<SyncOptions />, host);
+ });
+}
+
+const testButton = () => host.querySelector<HTMLButtonElement>("button[name='test-sync-button']");
+
+/** Presses "Test now" and lets it settle: it saves, then posts, and only then reports. */
+async function pressTest() {
+ await act(async () => testButton()?.click());
+ await act(async () => {});
+}
+
+/** Types into one of the address boxes, as a keystroke rather than an assignment. */
+function type(index: number, value: string) {
+ const box = [ ...host.querySelectorAll<HTMLInputElement>("input[type='text']") ][index];
+ act(() => {
+ box.value = value;
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+}
+
+describe("the sync settings", () => {
+ it("keeps the test apart from the settings it checks, in a card with no heading of its own", () => {
+ open();
+
+ const headings = [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.textContent);
+ expect(headings).toEqual([ "sync_2.config_title" ]);
+
+ // Its own card all the same, so it reads as an action rather than one more setting.
+ expect(testButton()?.closest(".tn-card")).not.toBeNull();
+ expect(testButton()?.closest(".tn-card")?.querySelector(".tn-card-heading")).toBeNull();
+ });
+
+ it("commits what has been typed before testing, so the test uses the address on screen", async () => {
+ open();
+ type(0, "https://sync.example.com:8080");
+ type(1, "https://proxy.example.com:3128");
+
+ await pressTest();
+
+ expect(mocks.saved).toEqual([
+ [ "syncServerHost", "https://sync.example.com:8080" ],
+ [ "syncProxy", "https://proxy.example.com:3128" ]
+ ]);
+ expect(mocks.post).toHaveBeenCalledWith("sync/test");
+ });
+
+ it("reports what the server said on a successful handshake", async () => {
+ open();
+ await pressTest();
+
+ expect(mocks.showMessage).toHaveBeenCalledWith("ok");
+ expect(mocks.showError).not.toHaveBeenCalled();
+ });
+
+ it("reports a refused handshake as a failure, even when the server explains itself", async () => {
+ mocks.post.mockResolvedValueOnce({ success: false, message: "no route to host" });
+ open();
+
+ await pressTest();
+ expect(mocks.showError).toHaveBeenCalled();
+ expect(mocks.showMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsx b/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsx
new file mode 100644
index 0000000000..9a262c3fec
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/text_notes.spec.tsx
@@ -0,0 +1,157 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ stored: {} as Record<string, string | boolean>,
+ saved: [] as [ string, string | boolean ][],
+ colorScheme: "light" as "light" | "dark"
+}));
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// The new layout drops the right pane's own settings; this file's page is the old-layout one.
+vi.mock("../../../services/experimental_features", () => ({
+ isExperimentalFeatureEnabled: () => false
+}));
+
+vi.mock("../../../services/syntax_highlight", () => ({
+ ensureMimeTypesForHighlighting: async () => {},
+ loadHighlightingTheme: vi.fn()
+}));
+
+vi.mock("@triliumnext/highlightjs", () => ({
+ Themes: {
+ "one-light": { name: "One Light" },
+ "one-dark": { name: "One Dark" }
+ },
+ getThemeVariant: (theme: { name: string }) => (theme.name.includes("Dark") ? "dark" : "light"),
+ highlight: () => ({ value: "" })
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useColorScheme: () => mocks.colorScheme,
+ useTriliumOption: (name: string) => [
+ String(mocks.stored[name] ?? ""),
+ (value: string) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionBool: (name: string) => [
+ mocks.stored[name] === true,
+ (value: boolean) => void mocks.saved.push([ name, value ])
+ ],
+ useTriliumOptionJson: () => [ [], vi.fn() ]
+}));
+
+vi.mock("./components/OptionsPageHeader", () => ({ default: () => <div className="header-stub" /> }));
+
+import TextNoteSettings from "./text_notes";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.stored = { textNoteEditorType: "ckeditor-classic", codeBlockTabWidth: "4" };
+ mocks.saved = [];
+ mocks.colorScheme = "light";
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+});
+
+function open() {
+ act(() => {
+ render(null, host);
+ render(<TextNoteSettings />, host);
+ });
+}
+
+const cardHeadings = () =>
+ [ ...host.querySelectorAll(".tn-card-heading") ].map((heading) => heading.firstChild?.textContent);
+const optionLabels = () =>
+ [ ...host.querySelectorAll(".tn-card-option-label") ].map((label) => label.firstChild?.textContent);
+const toggle = (name: string) => host.querySelector<HTMLInputElement>(`input.switch-toggle[id^='${name}-']`);
+
+describe("the page's shape", () => {
+ it("opens on the illustrated toolbar choice, with the multi-line setting under its own heading", () => {
+ open();
+
+ expect(cardHeadings().slice(0, 2)).toEqual([
+ "editing.editor_type.toolbar_style",
+ "editing.editor_type.label"
+ ]);
+ // A pair of pictures, given a card that stands back behind them.
+ expect(host.querySelector(".thumbnail-selector-option-card .radio-with-illustration")).not.toBeNull();
+ });
+
+ it("tells what the highlights list is made of apart from where it is shown", () => {
+ open();
+
+ expect(cardHeadings()).toEqual(expect.arrayContaining([
+ "highlights_list.title",
+ "highlights_list.visibility_title"
+ ]));
+ });
+});
+
+describe("the formatting toolbar", () => {
+ it("has nothing to wrap onto a second line while the toolbar follows the cursor", () => {
+ open();
+ expect(toggle("multiline-toolbar")?.disabled).toBe(false);
+
+ mocks.stored = { ...mocks.stored, textNoteEditorType: "ckeditor-balloon" };
+ open();
+ expect(toggle("multiline-toolbar")?.disabled).toBe(true);
+ });
+
+ it("writes the chosen style back, from the picture that was pressed", () => {
+ open();
+
+ const [ floating ] = [ ...host.querySelectorAll<HTMLElement>(".radio-with-illustration .illustration") ];
+ act(() => floating.click());
+
+ expect(mocks.saved).toContainEqual([ "textNoteEditorType", "ckeditor-balloon" ]);
+ });
+});
+
+describe("the code block appearance", () => {
+ it("asks for one theme when it is not to follow the app, and for a pair when it is", () => {
+ open();
+ expect(optionLabels()).toContain("highlighting.color-scheme");
+
+ mocks.stored = { ...mocks.stored, codeBlockThemeMatchesApp: true };
+ open();
+ expect(optionLabels()).not.toContain("highlighting.color-scheme");
+ expect(optionLabels()).toEqual(expect.arrayContaining([ "code_theme.light_theme", "code_theme.dark_theme" ]));
+ });
+
+ it("shows a sample of what the settings amount to, in a segment of its own", () => {
+ open();
+ expect(host.querySelector(".code-block-preview .code-sample")).not.toBeNull();
+ });
+});
+
+describe("the automatic replacements", () => {
+ it("offers the same set of quotation marks for both keys, which convention rather than the marks decides", () => {
+ open();
+
+ const [ doubleQuotes, singleQuotes ] = [ ...host.querySelectorAll<HTMLSelectElement>(".text-notes-replacements select") ];
+ expect(doubleQuotes.querySelectorAll("option").length).toBe(singleQuotes.querySelectorAll("option").length);
+ // "Based on the note's content language" and "Disabled", ahead of the mark pairs themselves.
+ expect(doubleQuotes.querySelectorAll("option").length).toBeGreaterThan(2);
+ });
+
+ it("writes a chosen pair back to the key it was chosen for", () => {
+ open();
+
+ const [ doubleQuotes ] = [ ...host.querySelectorAll<HTMLSelectElement>(".text-notes-replacements select") ];
+ act(() => {
+ doubleQuotes.value = "off";
+ doubleQuotes.dispatchEvent(new Event("change", { bubbles: true }));
+ });
+
+ expect(mocks.saved).toContainEqual([ "textNoteDoubleQuoteStyle", "off" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/totp.spec.tsx b/apps/client/src/widgets/type_widgets/options/totp.spec.tsx
new file mode 100644
index 0000000000..e983e547ba
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/totp.spec.tsx
@@ -0,0 +1,316 @@
+import type { TOTPStatus } from "@triliumnext/commons";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => {
+ /** The per-code status the server answers with: a number is unused, a timestamp is spent. */
+ const recovery: { keysExist: boolean; used: string[] } = { keysExist: false, used: [] };
+ /** What each step of enrollment answers; a scenario overrides the one it is about. */
+ const enrollment = { generated: true, verified: true, enabled: true };
+
+ return {
+ recovery,
+ enrollment,
+ get: vi.fn(async (url: string) => {
+ if (url === "totp_recovery/enabled") return { success: true, keysExist: recovery.keysExist };
+ if (url === "totp_recovery/used") return { success: true, usedRecoveryCodes: recovery.used };
+ if (url === "totp/generate") {
+ return enrollment.generated
+ ? { success: true, message: "JBSWY3DPEHPK3PXP", url: "otpauth://totp/Trilium" }
+ : { success: false };
+ }
+ if (url === "keyboard-actions") return [];
+ return {};
+ }),
+ post: vi.fn(async (url: string) => {
+ if (url === "totp/verify") {
+ return enrollment.verified
+ ? { success: true, recoveryCodes: [ "aaaa-bbbb", "cccc-dddd" ] }
+ : { success: false };
+ }
+ if (url === "totp/enable") return { success: enrollment.enabled };
+ return { success: true, recoveryCodes: [ "aaaa-bbbb", "cccc-dddd" ] };
+ }),
+ confirm: vi.fn(async () => true),
+ showMessage: vi.fn(),
+ showError: vi.fn(),
+ refresh: vi.fn()
+ };
+});
+
+vi.mock("../../../services/i18n", () => ({ t: (key: string) => key }));
+
+// The recovery-codes dialog carries a `<Trans>`, which reads its catalogue from a React context that
+// i18next never installs here.
+vi.mock("react-i18next", () => ({ Trans: ({ i18nKey }: { i18nKey: string }) => <>{i18nKey}</> }));
+
+/*
+ * Stands in for the Bootstrap shell, keeping only what the wizard inside it is driven through: the
+ * body, the footer, and submitting the form.
+ *
+ * The real one opens itself through jQuery and Bootstrap, neither of which happy-dom can carry — and
+ * the failure is not confined to the dialog: it throws from an effect, which abandons the rest of
+ * that flush, so the enrolment step's own effect never runs and no secret is ever requested.
+ */
+vi.mock("../../react/Modal", () => ({
+ default: ({ className, show, footer, onSubmit, children }: {
+ className?: string;
+ show?: boolean;
+ footer?: preact.ComponentChildren;
+ onSubmit?: () => void;
+ children?: preact.ComponentChildren;
+ }) => (show
+ ? <div className={`modal ${className ?? ""}`}>
+ <form onSubmit={(e) => { e.preventDefault(); onSubmit?.(); }}>
+ <div className="modal-body">{children}</div>
+ <div className="modal-footer">{footer}</div>
+ </form>
+ </div>
+ : null)
+}));
+
+vi.mock("../../../services/server", () => ({
+ default: { get: mocks.get, post: mocks.post, put: async () => ({}), remove: async () => ({}) }
+}));
+
+vi.mock("../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));
+
+vi.mock("../../../services/toast", () => ({
+ default: { showMessage: mocks.showMessage, showError: mocks.showError }
+}));
+
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../react/hooks")>()),
+ useStaticTooltip: vi.fn()
+}));
+
+// The two status helpers this file's `.ts` sibling covers are deliberately left to it.
+import { TotpSettings } from "./totp";
+
+let host: HTMLElement;
+
+beforeEach(() => {
+ mocks.recovery.keysExist = false;
+ mocks.recovery.used = [];
+ mocks.enrollment.generated = true;
+ mocks.enrollment.verified = true;
+ mocks.enrollment.enabled = true;
+ host = document.body.appendChild(document.createElement("div"));
+});
+
+afterEach(() => {
+ render(null, host);
+ document.body.innerHTML = "";
+ vi.clearAllMocks();
+});
+
+async function open(totpStatus?: TOTPStatus) {
+ await act(async () => {
+ render(null, host);
+ render(<TotpSettings totpStatus={totpStatus} refreshTotpStatus={mocks.refresh} />, host);
+ });
+ // The codes arrive in two hops — whether any exist, and then which of them have been spent.
+ await act(async () => {});
+}
+
+const badge = () => host.querySelector(".mfa-status-badge")?.className;
+const button = (name: string) => host.querySelector<HTMLButtonElement>(`button[name='${name}']`);
+const dots = () => [ ...host.querySelectorAll(".recovery-code-dot") ];
+
+describe("TOTP before it has been set up", () => {
+ it("offers the one way in, and says the method is off", async () => {
+ await open({ set: false } as TOTPStatus);
+
+ expect(badge()).toContain("inactive");
+ expect(button("totp-setup-button")).not.toBeNull();
+ // Recovery codes are part of TOTP and never exist without it.
+ expect(button("regenerate-recovery-keys-button")).toBeNull();
+ expect(button("totp-remove-button")).toBeNull();
+ });
+});
+
+describe("TOTP once a secret is set", () => {
+ beforeEach(() => {
+ mocks.recovery.keysExist = true;
+ // Two still available, one spent — the entries the server distinguishes by shape.
+ mocks.recovery.used = [ "0", "2025-01-02 03:04:05", "2" ];
+ });
+
+ it("replaces the call to action with the codes panel, and says the method is on", async () => {
+ await open({ set: true } as TOTPStatus);
+
+ expect(badge()).toContain("active");
+ expect(button("totp-setup-button")).toBeNull();
+ expect(button("regenerate-recovery-keys-button")).not.toBeNull();
+ expect(button("totp-remove-button")).not.toBeNull();
+ });
+
+ it("shows one dot per code, filled for the ones still to be spent", async () => {
+ await open({ set: true } as TOTPStatus);
+
+ expect(dots()).toHaveLength(3);
+ expect(dots().filter((dot) => dot.className.includes("available"))).toHaveLength(2);
+ expect(dots().filter((dot) => dot.className.includes("used"))).toHaveLength(1);
+ });
+
+ it("asks before minting a fresh batch, the old ones being lost either way", async () => {
+ mocks.confirm.mockResolvedValueOnce(false);
+ await open({ set: true } as TOTPStatus);
+
+ await act(async () => button("regenerate-recovery-keys-button")?.click());
+ expect(mocks.post).not.toHaveBeenCalled();
+
+ await act(async () => button("regenerate-recovery-keys-button")?.click());
+ expect(mocks.post).toHaveBeenCalledWith("totp_recovery/regenerate");
+ });
+
+ it("asks before removing TOTP, and refreshes the page's idea of it once gone", async () => {
+ mocks.confirm.mockResolvedValueOnce(false);
+ await open({ set: true } as TOTPStatus);
+
+ await act(async () => button("totp-remove-button")?.click());
+ expect(mocks.post).not.toHaveBeenCalled();
+
+ await act(async () => button("totp-remove-button")?.click());
+ expect(mocks.post).toHaveBeenCalledWith("totp/reset");
+ expect(mocks.refresh).toHaveBeenCalled();
+ });
+
+ it("says so plainly when there are no codes at all, rather than showing an empty row of dots", async () => {
+ mocks.recovery.keysExist = false;
+ await open({ set: true } as TOTPStatus);
+
+ expect(dots()).toHaveLength(0);
+ const row = button("regenerate-recovery-keys-button")?.closest(".tn-card-option");
+ expect(row?.querySelector(".tn-card-option-description")?.textContent)
+ .toBe("multi_factor_authentication.recovery_keys_no_key_set");
+ });
+});
+
+/**
+ * The enrollment dialog, which persists nothing until it is finished: dismissing at any point has to
+ * leave TOTP exactly as it was, so what each step does — and does not — commit is the whole of it.
+ */
+describe("enrolling in TOTP", () => {
+ const dialog = () => document.querySelector(".totp-enrollment-modal");
+ const secretBox = () => dialog()?.querySelector<HTMLInputElement>(".totp-enroll-secret");
+ // The step holds two boxes: the secret, which is only ever read, and the code, which is typed.
+ const codeBox = () => [ ...(dialog()?.querySelectorAll<HTMLInputElement>("input") ?? []) ]
+ .find((input) => !input.readOnly);
+ const footerButtons = () => [ ...(dialog()?.querySelectorAll<HTMLButtonElement>(".modal-footer button") ?? []) ];
+
+ /** Opens the dialog and lets the secret it asks for arrive — requested as the step is shown. */
+ async function startEnrolling() {
+ await open({ set: false } as TOTPStatus);
+ await act(async () => button("totp-setup-button")?.click());
+ await act(async () => {});
+ await act(async () => {});
+ }
+
+ /** Types a code and submits, which is what the verify step acts on. */
+ async function enterCode(code: string) {
+ await act(async () => {
+ const box = codeBox();
+ if (box) {
+ box.value = code;
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+ await act(async () => {
+ dialog()?.querySelector<HTMLFormElement>("form")?.requestSubmit();
+ });
+ await act(async () => {});
+ }
+
+ it("shows the secret both ways it can be taken down: scanned, and read out to be typed", async () => {
+ await startEnrolling();
+
+ expect(dialog()?.querySelector(".totp-enroll-qr-code svg")).not.toBeNull();
+ expect(secretBox()?.value).toBe("JBSWY3DPEHPK3PXP");
+ });
+
+ it("says so and commits nothing when the secret cannot even be had", async () => {
+ mocks.enrollment.generated = false;
+ await startEnrolling();
+
+ expect(dialog()?.querySelector(".admonition")).not.toBeNull();
+ expect(mocks.post).not.toHaveBeenCalled();
+ });
+
+ it("keeps only digits, and no more of them than a code has", async () => {
+ await startEnrolling();
+
+ await act(async () => {
+ const box = codeBox();
+ if (box) {
+ box.value = "12ab34cd5678";
+ box.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+ });
+
+ expect(codeBox()?.value).toBe("123456");
+ });
+
+ it("stays on the first step when the code is refused, clearing it to be typed again", async () => {
+ mocks.enrollment.verified = false;
+ await startEnrolling();
+ await enterCode("000000");
+
+ expect(mocks.post).toHaveBeenCalledWith("totp/verify", { secret: "JBSWY3DPEHPK3PXP", token: "000000" });
+ // Nothing is stored by verifying, so a refusal leaves TOTP exactly as it was.
+ expect(mocks.post).not.toHaveBeenCalledWith("totp/enable", expect.anything());
+ expect(codeBox()?.value).toBe("");
+ expect(dialog()?.querySelector(".totp-recovery-codes")).toBeNull();
+ });
+
+ it("moves on to the codes once the authenticator has proved itself, still committing nothing", async () => {
+ await startEnrolling();
+ await enterCode("123456");
+
+ const codes = [ ...(dialog()?.querySelectorAll(".totp-recovery-codes li") ?? []) ];
+ expect(codes.map((code) => code.textContent)).toEqual([ "aaaa-bbbb", "cccc-dddd" ]);
+ expect(mocks.post).not.toHaveBeenCalledWith("totp/enable", expect.anything());
+ });
+
+ it("will not finish until the codes have been acknowledged as saved", async () => {
+ await startEnrolling();
+ await enterCode("123456");
+
+ const [ finish ] = footerButtons();
+ expect(finish.disabled).toBe(true);
+
+ const acknowledge = dialog()?.querySelector<HTMLInputElement>("input[type='checkbox']");
+ await act(async () => void acknowledge?.click());
+ expect(footerButtons()[0].disabled).toBe(false);
+ });
+
+ it("commits the secret and its codes together, in the one step that stores anything", async () => {
+ await startEnrolling();
+ await enterCode("123456");
+
+ await act(async () => void dialog()?.querySelector<HTMLInputElement>("input[type='checkbox']")?.click());
+ await act(async () => footerButtons()[0].click());
+ await act(async () => {});
+
+ expect(mocks.post).toHaveBeenCalledWith("totp/enable", {
+ secret: "JBSWY3DPEHPK3PXP",
+ recoveryCodes: [ "aaaa-bbbb", "cccc-dddd" ]
+ });
+ expect(mocks.refresh).toHaveBeenCalled();
+ expect(mocks.showMessage).toHaveBeenCalledWith("multi_factor_authentication.totp_enroll_enabled");
+ });
+
+ it("reports a refused commit rather than claiming TOTP is on", async () => {
+ mocks.enrollment.enabled = false;
+ await startEnrolling();
+ await enterCode("123456");
+
+ await act(async () => void dialog()?.querySelector<HTMLInputElement>("input[type='checkbox']")?.click());
+ await act(async () => footerButtons()[0].click());
+ await act(async () => {});
+
+ expect(mocks.showError).toHaveBeenCalledWith("multi_factor_authentication.totp_enroll_enable_error");
+ expect(mocks.refresh).not.toHaveBeenCalled();
+ });
+});