Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(options): cover ShortcutRecorder, spellcheck live-apply and TOTP helpers
Elian Doran156e4d9eeb25
diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.recorder.spec.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.recorder.spec.tsxnew file mode 100644index 0000000000..22ea46461e--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.recorder.spec.tsx@@ -0,0 +1,99 @@+import { render, VNode } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++const { showPersistent, closePersistent } = vi.hoisted(() => ({+ showPersistent: vi.fn(),+ closePersistent: vi.fn()+}));++vi.mock("../../../services/toast", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../../services/toast")>();+ return {+ ...actual,+ default: { ...actual.default, showPersistent, closePersistent }+ };+});++vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useStaticTooltip: vi.fn()+}));++import { keyboardEventToShortcut, ShortcutRecorder } from "./shortcuts";++let container: HTMLDivElement | undefined;++async function renderInto(vnode: VNode) {+ const target = document.createElement("div");+ document.body.appendChild(target);+ container = target;+ await act(async () => {+ render(vnode, target);+ });+ return target;+}++afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ showPersistent.mockClear();+ closePersistent.mockClear();+});++async function keyDown(init: KeyboardEventInit) {+ await act(async () => {+ window.dispatchEvent(new KeyboardEvent("keydown", { ...init, bubbles: true }));+ });+}++async function clickRecorder(root: HTMLElement) {+ const button = root.querySelector("button.shortcut-recorder");+ expect(button).toBeInstanceOf(HTMLButtonElement);+ await act(async () => {+ (button as HTMLButtonElement).click();+ });+ return button as HTMLButtonElement;+}++describe("ShortcutRecorder", () => {+ it("records a valid combination, ignoring lone modifiers, and reports it via onCapture", async () => {+ const onCapture = vi.fn();+ const root = await renderInto(<ShortcutRecorder onCapture={onCapture} />);++ // Starting recording surfaces the persistent toast.+ const button = await clickRecorder(root);+ expect(showPersistent).toHaveBeenCalledTimes(1);+ expect(button.className).toContain("recording");++ // A lone modifier keeps recording active and produces nothing.+ await keyDown({ key: "Control", code: "ControlLeft", ctrlKey: true });+ expect(onCapture).not.toHaveBeenCalled();+ expect(closePersistent).not.toHaveBeenCalled();++ // A bindable combination is captured and stops recording.+ const combo: KeyboardEventInit = { key: "k", code: "KeyK", ctrlKey: true };+ const expected = keyboardEventToShortcut(new KeyboardEvent("keydown", combo));+ expect(expected).toBeTruthy();++ await keyDown(combo);+ expect(onCapture).toHaveBeenCalledTimes(1);+ expect(onCapture).toHaveBeenCalledWith(expected);+ expect(closePersistent).toHaveBeenCalledTimes(1);+ });++ it("cancels on a bare Escape without capturing a shortcut", async () => {+ const onCapture = vi.fn();+ const root = await renderInto(<ShortcutRecorder onCapture={onCapture} />);++ await clickRecorder(root);+ expect(showPersistent).toHaveBeenCalledTimes(1);++ await keyDown({ key: "Escape", code: "Escape" });+ expect(onCapture).not.toHaveBeenCalled();+ expect(closePersistent).toHaveBeenCalledTimes(1);+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx b/apps/client/src/widgets/type_widgets/options/shortcuts.tsxindex 2c373e9504..5024f16c24 100644--- a/apps/client/src/widgets/type_widgets/options/shortcuts.tsx+++ b/apps/client/src/widgets/type_widgets/options/shortcuts.tsx@@ -518,7 +518,7 @@ function ShortcutEditor({ keyboardShortcut: action, conflicts }: { keyboardShortconst RECORDING_TOAST_ID = "shortcut-recorder-recording";-function ShortcutRecorder({ onCapture }: { onCapture: (shortcut: string) => void }) {+export function ShortcutRecorder({ onCapture }: { onCapture: (shortcut: string) => void }) {const [ recording, setRecording ] = useState(false);useEffect(() => {diff --git a/apps/client/src/widgets/type_widgets/options/spellcheck.spec.tsx b/apps/client/src/widgets/type_widgets/options/spellcheck.spec.tsxnew file mode 100644index 0000000000..8d0bce20b0--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/spellcheck.spec.tsx@@ -0,0 +1,124 @@+import { ComponentChildren, render, VNode } from "preact";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// Capture the `onChange` props the wiring under test passes into its children so we can invoke the+// "live apply" handlers directly without depending on the real toggle/checkbox DOM plumbing.+const captured: {+ toggleOnChange?: (enabled: boolean) => void;+ checkboxOnChange?: (codes: string[]) => void;+} = {};++const setSpellCheckEnabled = vi.fn();+const setSpellCheckLanguageCode = vi.fn();++// `useTriliumOptionBool` drives the enabled state, `useTriliumOption` drives the language codes; both+// return the value plus a setter spy so we can assert the persisted option is written. Partial-mock so+// other hooks used by sibling components (e.g. `useUniqueName` in OptionsRow) keep their real impl.+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useTriliumOptionBool: vi.fn(() => [true, setSpellCheckEnabled]),+ useTriliumOption: vi.fn(() => ["en-US", setSpellCheckLanguageCode]),+ useNoteContext: vi.fn(() => ({ note: undefined }))+}));++vi.mock("../../../services/utils", async (importActual) => ({+ ...(await importActual<typeof import("../../../services/utils")>()),+ isElectron: vi.fn(() => true)+}));++vi.mock("./components/OptionsPageHeader", () => ({+ default: ({ actions }: { actions?: ComponentChildren }) => <div className="header-stub">{actions}</div>+}));++vi.mock("../../react/FormToggle", () => ({+ default: ({ onChange }: { onChange: (enabled: boolean) => void }) => {+ captured.toggleOnChange = onChange;+ return <div className="toggle-stub" />;+ }+}));++vi.mock("./components/CheckboxList", () => ({+ default: ({ onChange }: { onChange: (codes: string[]) => void }) => {+ captured.checkboxOnChange = onChange;+ return <div className="checkbox-stub" />;+ }+}));++// Import AFTER the mocks (vi.mock is hoisted, but the component import must resolve the mocked deps).+import SpellcheckSettings from "./spellcheck";++let container: HTMLDivElement | undefined;++function renderInto(vnode: VNode) {+ container = document.createElement("div");+ document.body.appendChild(container);+ render(vnode, container);+ return container;+}++afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+});++function setElectronApi(api: unknown) {+ (window as unknown as { electronApi?: unknown }).electronApi = api;+}++function spellcheckApiStub() {+ return {+ setSpellCheckerEnabled: vi.fn(),+ setSpellCheckerLanguages: vi.fn(),+ getAvailableSpellCheckerLanguages: vi.fn(() => ["en-US", "de-DE"]),+ addWordToDictionary: vi.fn()+ };+}++describe("SpellcheckSettings live apply", () => {+ beforeEach(() => {+ captured.toggleOnChange = undefined;+ captured.checkboxOnChange = undefined;+ vi.clearAllMocks();+ });++ it("persists the option AND applies to live Electron sessions for both toggle and languages", () => {+ const spellcheck = spellcheckApiStub();+ setElectronApi({ spellcheck });++ renderInto(<SpellcheckSettings />);++ const toggleOnChange = captured.toggleOnChange;+ const checkboxOnChange = captured.checkboxOnChange;+ expect(toggleOnChange).toBeDefined();+ expect(checkboxOnChange).toBeDefined();++ toggleOnChange?.(false);+ expect(setSpellCheckEnabled).toHaveBeenCalledWith(false);+ expect(spellcheck.setSpellCheckerEnabled).toHaveBeenCalledWith(false);++ checkboxOnChange?.(["en-US", "de-DE"]);+ expect(setSpellCheckLanguageCode).toHaveBeenCalledWith("en-US, de-DE");+ expect(spellcheck.setSpellCheckerLanguages).toHaveBeenCalledWith(["en-US", "de-DE"]);+ });++ it("does not throw when window.electronApi is undefined (web/server build no-op)", () => {+ setElectronApi(undefined);++ renderInto(<SpellcheckSettings />);++ const toggleOnChange = captured.toggleOnChange;+ const checkboxOnChange = captured.checkboxOnChange;+ expect(toggleOnChange).toBeDefined();+ expect(checkboxOnChange).toBeDefined();++ expect(() => toggleOnChange?.(true)).not.toThrow();+ expect(() => checkboxOnChange?.(["fr-FR"])).not.toThrow();++ // The persisted option is still written even without the Electron bridge.+ expect(setSpellCheckEnabled).toHaveBeenCalledWith(true);+ expect(setSpellCheckLanguageCode).toHaveBeenCalledWith("fr-FR");+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/totp.spec.ts b/apps/client/src/widgets/type_widgets/options/totp.spec.tsnew file mode 100644index 0000000000..13e5d218be--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/totp.spec.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from "vitest";++import { formatRecoveryCodeUsedDate, isUnusedRecoveryCode } from "./totp";++describe("isUnusedRecoveryCode", () => {+ it("treats purely-numeric entries as unused and anything else as used", () => {+ expect(isUnusedRecoveryCode("0")).toBe(true);+ expect(isUnusedRecoveryCode("7")).toBe(true);+ expect(isUnusedRecoveryCode("2026/06/17T12:34:56.789Z")).toBe(false);+ expect(isUnusedRecoveryCode("aGVsbG8=")).toBe(false);+ });+});++describe("formatRecoveryCodeUsedDate", () => {+ it("formats a stored timestamp and passes through unparseable input unchanged", () => {+ const stored = "2026/06/17T12:34:56.789Z";+ const formatted = formatRecoveryCodeUsedDate(stored);+ expect(formatted).not.toBe(stored);+ expect(formatted).toBe(new Date("2026-06-17T12:34:56.789Z").toLocaleString());++ expect(formatRecoveryCodeUsedDate("not-a-date")).toBe("not-a-date");+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/totp.tsx b/apps/client/src/widgets/type_widgets/options/totp.tsxindex 53a888bbc8..e3bb5a86db 100644--- a/apps/client/src/widgets/type_widgets/options/totp.tsx+++ b/apps/client/src/widgets/type_widgets/options/totp.tsx@@ -539,12 +539,12 @@ function RecoveryCodeDots({ status }: { status: string[] }) {* a used code as an ISO timestamp of when it was consumed, and an unused one as its plain numeric* index, so a purely numeric entry is one that's still available.*/-function isUnusedRecoveryCode(statusEntry: string) {+export function isUnusedRecoveryCode(statusEntry: string) {return /^\d+$/.test(statusEntry);}/** Formats a used-code timestamp (stored with `/` date separators) into a readable local date. */-function formatRecoveryCodeUsedDate(statusEntry: string) {+export function formatRecoveryCodeUsedDate(statusEntry: string) {const date = new Date(statusEntry.replace(/\//g, "-"));return isNaN(date.getTime()) ? statusEntry : date.toLocaleString();}