Skip to content

Build your personal knowledge base with Trilium Notes

test(calendar): cover the pieces the branch added to its own modules

Elian Doranab87b93aee41
diff --git a/apps/client/src/menus/context_menu.spec.ts b/apps/client/src/menus/context_menu.spec.ts
index 9a9b5f59f3..b733c1c8e3 100644
--- a/apps/client/src/menus/context_menu.spec.ts
+++ b/apps/client/src/menus/context_menu.spec.ts
@@ -59,4 +59,19 @@ describe("contextMenu", () => {
expect(menu?.parentElement).toBe(document.body);
});
+
+ it("says whether it is up, for a host whose own press would otherwise not know", async () => {
+ buildPage();
+ const contextMenu = await buildContextMenu();
+
+ // A host that answers a press itself keeps it from the document, whose click is what puts
+ // the menu away — so it has to ask, rather than let a standing menu outlive the press.
+ expect(contextMenu.isShown()).toBe(false);
+
+ await contextMenu.show({ x: 10, y: 10, items, selectMenuItemHandler: () => {} });
+ expect(contextMenu.isShown()).toBe(true);
+
+ await contextMenu.hide();
+ expect(contextMenu.isShown()).toBe(false);
+ });
});
diff --git a/apps/client/src/widgets/collections/calendar/api.spec.ts b/apps/client/src/widgets/collections/calendar/api.spec.ts
index 6e2aebd861..91d3453f09 100644
--- a/apps/client/src/widgets/collections/calendar/api.spec.ts
+++ b/apps/client/src/widgets/collections/calendar/api.spec.ts
@@ -2,8 +2,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { setAttribute } from "../../../services/attributes";
import dialog from "../../../services/dialog";
+import froca from "../../../services/froca";
+import note_create from "../../../services/note_create";
+import { deleteNoteOrBranch } from "../../../services/note_deletion";
import { buildNote } from "../../../test/easy-froca";
-import { changeEvent, removeFromCalendar } from "./api";
+import { changeEvent, newEvent, removeFromCalendar } from "./api";
vi.mock("../../../services/attributes", async (importOriginal) => ({
...await importOriginal<typeof import("../../../services/attributes")>(),
@@ -55,6 +58,89 @@ describe("changeEvent", () => {
[ "endTime", null ]
]);
});
+
+ it("drops an end date equal to the start, a one-day event standing on its start alone", async () => {
+ const note = buildNote({ title: "Fair", "#startDate": "2026-06-05" });
+
+ await changeEvent(note, { startDate: "2026-06-06", endDate: "2026-06-06" });
+
+ expect(writtenLabels()).toEqual([
+ [ "startDate", "2026-06-06" ],
+ [ "endDate", null ],
+ [ "startTime", null ],
+ [ "endTime", null ]
+ ]);
+ });
+});
+
+describe("newEvent", () => {
+ /** What the calendar was handed to create the note with, the note itself being the mock's. */
+ const creationRequest = () => {
+ const call = vi.mocked(note_create.createNote).mock.calls[0];
+ // `createNote` defaults its options, so the recorded argument is optional to the type even
+ // though the calendar always passes one.
+ if (!call?.[1]) throw new Error("No note was created.");
+ return { parentNoteId: call[0], opts: call[1], componentId: call[2] };
+ };
+
+ beforeEach(() => {
+ vi.mocked(note_create.createNote).mockReset();
+ vi.mocked(note_create.createNote).mockResolvedValue({ note: buildNote({ title: "Fair" }) } as never);
+ });
+
+ it("writes only the labels it was given, a bare event standing on its start date alone", async () => {
+ const calendar = buildNote({ title: "Calendar" });
+
+ await newEvent(calendar, { startDate: "2026-06-05" });
+
+ const { parentNoteId, opts } = creationRequest();
+ expect(parentNoteId).toBe(calendar.noteId);
+ expect(opts.attributes).toEqual([
+ { type: "label", name: "startDate", value: "2026-06-05" }
+ ]);
+ });
+
+ it("writes every date and hour it was given, in the order the calendar reads them", async () => {
+ const calendar = buildNote({ title: "Calendar" });
+
+ await newEvent(calendar, {
+ title: "Fair", startDate: "2026-06-05", endDate: "2026-06-07",
+ startTime: "13:00", endTime: "14:30", componentId: "comp-1"
+ });
+
+ const { opts, componentId } = creationRequest();
+ expect(opts.title).toBe("Fair");
+ expect(opts.attributes).toEqual([
+ { type: "label", name: "startDate", value: "2026-06-05" },
+ { type: "label", name: "endDate", value: "2026-06-07" },
+ { type: "label", name: "startTime", value: "13:00" },
+ { type: "label", name: "endTime", value: "14:30" }
+ ]);
+ expect(componentId).toBe("comp-1");
+ });
+
+ it("leaves out what was given as nothing, rather than writing an empty label for it", async () => {
+ const calendar = buildNote({ title: "Calendar" });
+
+ await newEvent(calendar, { startDate: "2026-06-05", endDate: null, startTime: null, endTime: "" });
+
+ expect(creationRequest().opts.attributes).toEqual([
+ { type: "label", name: "startDate", value: "2026-06-05" }
+ ]);
+ });
+
+ it("takes the calendar's protection, and hands the new note back for the pane to open on", async () => {
+ const calendar = buildNote({ title: "Calendar" });
+ const created = buildNote({ title: "Fair" });
+ vi.mocked(note_create.createNote).mockResolvedValue({ note: created } as never);
+
+ expect(await newEvent(calendar, { startDate: "2026-06-05" })).toBe(created);
+
+ const { opts } = creationRequest();
+ expect(opts.isProtected).toBe(calendar.isProtected);
+ // The note is not switched to: the pane opens on it where the calendar stands.
+ expect(opts.activate).toBe(false);
+ });
});
describe("removeFromCalendar", () => {
@@ -75,6 +161,24 @@ describe("removeFromCalendar", () => {
]);
});
+ it("deletes the note by the calendar's own branch where that was asked for as well", async () => {
+ vi.mocked(dialog.confirmDeleteNoteBoxWithNote)
+ .mockResolvedValue({ confirmed: true, isDeleteNoteChecked: true });
+ const calendar = buildNote({
+ title: "Calendar",
+ children: [ { id: "doomedEvent", title: "Fair", "#startDate": "2026-06-05" } ]
+ });
+ const note = froca.notes["doomedEvent"];
+
+ expect(await removeFromCalendar(note, calendar)).toBe(true);
+ // The branch the calendar holds it by, which is what tells a note cloned in from elsewhere
+ // from one that lives here and nowhere else.
+ expect(deleteNoteOrBranch).toHaveBeenCalledWith("doomedEvent", note.parentToBranch[calendar.noteId]);
+ expect(note.parentToBranch[calendar.noteId]).toBeTruthy();
+ // The labels are left alone: the note is going, not merely coming off the calendar.
+ expect(setAttribute).not.toHaveBeenCalled();
+ });
+
it("does nothing where the dialog was dismissed", async () => {
vi.mocked(dialog.confirmDeleteNoteBoxWithNote).mockResolvedValue(undefined);
const calendar = buildNote({ title: "Calendar" });
diff --git a/apps/client/src/widgets/collections/calendar/hooks.spec.tsx b/apps/client/src/widgets/collections/calendar/hooks.spec.tsx
new file mode 100644
index 0000000000..7dc348870a
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/hooks.spec.tsx
@@ -0,0 +1,151 @@
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import Component from "../../../components/component";
+import type FNote from "../../../entities/fnote";
+import attributes from "../../../services/attributes";
+import { buildNote } from "../../../test/easy-froca";
+import { ParentComponent } from "../../react/react_utils";
+import { useEventLabel, useEventLabelOmissions } from "./hooks";
+import { EventLabelName } from "./utils";
+
+describe("calendar hooks", () => {
+ let container: HTMLElement;
+ const setLabel = vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);
+ const removeLabel = vi.spyOn(attributes, "removeOwnedLabelByName").mockResolvedValue(true);
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ setLabel.mockClear();
+ removeLabel.mockClear();
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ /**
+ * Mounts a hook in the tree it expects to stand in and hands back what it answered — read from
+ * the last render, the label hooks reporting through an effect rather than on the first pass.
+ */
+ function renderHook<T>(use: () => T): () => T {
+ const answers: T[] = [];
+
+ function Probe() {
+ answers.push(use());
+ return null;
+ }
+
+ act(() => render(
+ <ParentComponent.Provider value={new Component()}>
+ <Probe />
+ </ParentComponent.Provider>,
+ container));
+
+ return () => {
+ const last = answers.at(-1);
+ if (last === undefined) throw new Error("The hook was never rendered.");
+ return last;
+ };
+ }
+
+ describe("useEventLabel", () => {
+ /** The hook's pair, for the note and the label the calendar draws an event by. */
+ function mount(note: FNote, name: EventLabelName) {
+ return renderHook(() => useEventLabel(note, name));
+ }
+
+ it("reads the stock label where the note renames none", () => {
+ const note = buildNote({ title: "Fair", "#startDate": "2026-06-05" });
+ expect(mount(note, "startDate")()[0]).toBe("2026-06-05");
+ });
+
+ it("reads the label a note renames for itself, in preference to the stock one", () => {
+ const note = buildNote({
+ title: "Fair",
+ "#calendar:startDate": "myStartDate", "#myStartDate": "2026-06-09",
+ "#startDate": "2026-06-05"
+ });
+ expect(mount(note, "startDate")()[0]).toBe("2026-06-09");
+ });
+
+ it("falls back to the stock label where the renamed one holds nothing, as the builder does", () => {
+ const note = buildNote({
+ title: "Fair", "#calendar:startDate": "myStartDate", "#startDate": "2026-06-05"
+ });
+ expect(mount(note, "startDate")()[0]).toBe("2026-06-05");
+ });
+
+ it("says nothing at all where neither label holds a value", () => {
+ expect(mount(buildNote({ title: "Fair" }), "startDate")()[0]).toBeNull();
+ });
+
+ it("writes the stock label where the note renames none", () => {
+ const note = buildNote({ title: "Fair", "#startDate": "2026-06-05" });
+ act(() => mount(note, "startDate")()[1]("2026-06-09"));
+
+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "startDate", "2026-06-09");
+ });
+
+ it("writes the renamed label, leaving the stock one where it stands", () => {
+ const note = buildNote({
+ title: "Fair", "#calendar:startDate": "myStartDate", "#startDate": "2026-06-05"
+ });
+ act(() => mount(note, "startDate")()[1]("2026-06-09"));
+
+ expect(setLabel).toHaveBeenCalledWith(note.noteId, "myStartDate", "2026-06-09");
+ expect(setLabel).toHaveBeenCalledTimes(1);
+ });
+
+ it("clears the stock label along with the renamed one, so the fallback cannot resurrect it", () => {
+ const note = buildNote({
+ title: "Fair",
+ "#calendar:startDate": "myStartDate", "#myStartDate": "2026-06-09",
+ "#startDate": "2026-06-05"
+ });
+ act(() => mount(note, "startDate")()[1](null));
+
+ // Both names, the stale stock value being exactly what the builder's fallback would
+ // pick up the moment the renamed label went.
+ expect(removeLabel.mock.calls.map((call) => call[1])).toEqual([ "myStartDate", "startDate" ]);
+ });
+ });
+
+ describe("useEventLabelOmissions", () => {
+ it("names the stock labels, which the popover's own fields already speak for", () => {
+ const omissions = renderHook(() => useEventLabelOmissions(buildNote({ title: "Fair" })))();
+
+ expect(omissions).toEqual([ "startDate", "endDate", "startTime", "endTime", "recurrence" ]);
+ });
+
+ it("names the labels a note points the calendar at as well, so the grid does not repeat them", () => {
+ const note = buildNote({
+ title: "Fair",
+ "#calendar:startDate": "myStartDate",
+ "#calendar:endDate": "myEndDate",
+ "#calendar:startTime": "myStartTime",
+ "#calendar:endTime": "myEndTime",
+ "#calendar:recurrence": "myRecurrence"
+ });
+
+ expect(renderHook(() => useEventLabelOmissions(note))()).toEqual([
+ "startDate", "endDate", "startTime", "endTime", "recurrence",
+ "myStartDate", "myEndDate", "myStartTime", "myEndTime", "myRecurrence"
+ ]);
+ });
+
+ it("names only the renamings that were actually made", () => {
+ const note = buildNote({
+ title: "Fair", "#calendar:startDate": "myStartDate", "#calendar:recurrence": "myRecurrence"
+ });
+
+ expect(renderHook(() => useEventLabelOmissions(note))()).toEqual([
+ "startDate", "endDate", "startTime", "endTime", "recurrence",
+ "myStartDate", "myRecurrence"
+ ]);
+ });
+ });
+});
diff --git a/apps/client/src/widgets/collections/calendar/recurrence.spec.ts b/apps/client/src/widgets/collections/calendar/recurrence.spec.ts
index f700224ab0..9f18c1f97d 100644
--- a/apps/client/src/widgets/collections/calendar/recurrence.spec.ts
+++ b/apps/client/src/widgets/collections/calendar/recurrence.spec.ts
@@ -57,7 +57,14 @@ describe("parseRecurrence", () => {
[ "a zero interval", "RRULE:FREQ=DAILY;INTERVAL=0" ],
[ "a malformed UNTIL", "RRULE:FREQ=DAILY;UNTIL=2026-06-05" ],
[ "an unknown frequency", "RRULE:FREQ=HOURLY" ],
- [ "something that is not an RRULE at all", "every second thursday" ]
+ [ "something that is not an RRULE at all", "every second thursday" ],
+ [ "a parameter that says nothing", "RRULE:FREQ=DAILY;JUSTAWORD" ],
+ [ "a parameter with no name", "RRULE:=DAILY" ],
+ [ "an unknown weekday", "RRULE:FREQ=WEEKLY;BYDAY=MO,XX" ],
+ [ "an interval that is not a number", "RRULE:FREQ=DAILY;INTERVAL=often" ],
+ [ "an interval left blank", "RRULE:FREQ=DAILY;INTERVAL=" ],
+ [ "a count that is not a number", "RRULE:FREQ=DAILY;COUNT=many" ],
+ [ "a zero count", "RRULE:FREQ=DAILY;COUNT=0" ]
])("steps aside for %s", (_description, value) => {
expect(parseRecurrence(value)).toEqual({ kind: "custom", value });
});
diff --git a/apps/client/src/widgets/collections/calendar/utils.spec.ts b/apps/client/src/widgets/collections/calendar/utils.spec.ts
new file mode 100644
index 0000000000..fabf98ee8d
--- /dev/null
+++ b/apps/client/src/widgets/collections/calendar/utils.spec.ts
@@ -0,0 +1,126 @@
+import { describe, expect, it } from "vitest";
+
+import { formatDateToLocalISO, formatTimeToLocalISO, getMonthsInDateRange, offsetDate, parseStartEndDateFromEvent, parseStartEndTimeFromEvent } from "./utils";
+
+/**
+ * A moment built in the machine's own zone, which is what the calendar hands these functions: a
+ * click on the grid names a wall-clock time, not an instant in UTC. Built this way the expectations
+ * below hold in any zone the suite happens to run in — the functions answer with the local reading,
+ * and that is the reading these arguments were written in.
+ */
+function localDate(year: number, month: number, day: number, hours = 0, minutes = 0) {
+ return new Date(year, month - 1, day, hours, minutes);
+}
+
+/** What the calendar hands over for a selection or an event: the two ends and whether it is all-day. */
+function span(start: Date | null, end: Date | null, allDay: boolean) {
+ return { start, end, allDay } as unknown as Parameters<typeof parseStartEndDateFromEvent>[0];
+}
+
+describe("formatDateToLocalISO", () => {
+ it("says the day as it reads on the local clock, whatever the time of day", () => {
+ expect(formatDateToLocalISO(localDate(2026, 6, 5))).toBe("2026-06-05");
+ // Either side of midnight, where a UTC reading would slip to a neighbouring day in most zones.
+ expect(formatDateToLocalISO(localDate(2026, 6, 5, 23, 59))).toBe("2026-06-05");
+ expect(formatDateToLocalISO(localDate(2026, 1, 1, 0, 30))).toBe("2026-01-01");
+ });
+
+ it("has nothing to say for a moment that was never given", () => {
+ expect(formatDateToLocalISO(null)).toBeUndefined();
+ expect(formatDateToLocalISO(undefined)).toBeUndefined();
+ });
+});
+
+describe("formatTimeToLocalISO", () => {
+ it("says the hour and minute on the local clock, dropping the seconds", () => {
+ expect(formatTimeToLocalISO(localDate(2026, 6, 5, 13, 30))).toBe("13:30");
+ expect(formatTimeToLocalISO(localDate(2026, 6, 5, 0, 0))).toBe("00:00");
+ expect(formatTimeToLocalISO(localDate(2026, 6, 5, 23, 59))).toBe("23:59");
+ });
+
+ it("has nothing to say for a moment that was never given", () => {
+ expect(formatTimeToLocalISO(null)).toBeUndefined();
+ expect(formatTimeToLocalISO(undefined)).toBeUndefined();
+ });
+});
+
+describe("offsetDate", () => {
+ it("walks a date by whole days, over the end of a month and of a year", () => {
+ expect(formatDateToLocalISO(offsetDate(localDate(2026, 6, 5), 1))).toBe("2026-06-06");
+ expect(formatDateToLocalISO(offsetDate(localDate(2026, 6, 5), -1))).toBe("2026-06-04");
+ expect(formatDateToLocalISO(offsetDate(localDate(2026, 6, 30), 1))).toBe("2026-07-01");
+ expect(formatDateToLocalISO(offsetDate(localDate(2026, 1, 1), -1))).toBe("2025-12-31");
+ });
+
+ it("takes a date written out as well as one already built", () => {
+ expect(formatDateToLocalISO(offsetDate("2026-06-05T00:00:00", 2))).toBe("2026-06-07");
+ });
+
+ it("has nothing to walk where no date was given", () => {
+ expect(offsetDate(null, 1)).toBeUndefined();
+ expect(offsetDate(undefined, 1)).toBeUndefined();
+ // The empty string is no date either, and is what an unfilled label reads as.
+ expect(offsetDate("", 1)).toBeUndefined();
+ });
+});
+
+describe("parseStartEndDateFromEvent", () => {
+ it("takes the end of an all-day span back a day, the calendar's own end being exclusive", () => {
+ // FullCalendar says a span covering the 5th and the 6th as ending on the 7th.
+ expect(parseStartEndDateFromEvent(span(localDate(2026, 6, 5), localDate(2026, 6, 7), true)))
+ .toEqual({ startDate: "2026-06-05", endDate: "2026-06-06" });
+ });
+
+ it("keeps the end of a timed span as it stands, that one naming the day it falls on", () => {
+ expect(parseStartEndDateFromEvent(span(localDate(2026, 6, 5, 13, 0), localDate(2026, 6, 5, 14, 0), false)))
+ .toEqual({ startDate: "2026-06-05", endDate: "2026-06-05" });
+ });
+
+ it("answers with neither date where there is no start to read", () => {
+ expect(parseStartEndDateFromEvent(span(null, localDate(2026, 6, 7), true)))
+ .toEqual({ startDate: null, endDate: null });
+ });
+
+ it("leaves the end unsaid where the calendar names none", () => {
+ expect(parseStartEndDateFromEvent(span(localDate(2026, 6, 5), null, true)))
+ .toEqual({ startDate: "2026-06-05", endDate: undefined });
+ expect(parseStartEndDateFromEvent(span(localDate(2026, 6, 5, 13, 0), null, false)))
+ .toEqual({ startDate: "2026-06-05", endDate: undefined });
+ });
+});
+
+describe("parseStartEndTimeFromEvent", () => {
+ it("reads the hours of a timed span", () => {
+ expect(parseStartEndTimeFromEvent(span(localDate(2026, 6, 5, 13, 0), localDate(2026, 6, 5, 14, 30), false)))
+ .toEqual({ startTime: "13:00", endTime: "14:30" });
+ });
+
+ it("says no hours at all for an all-day span, which has none to give", () => {
+ expect(parseStartEndTimeFromEvent(span(localDate(2026, 6, 5), localDate(2026, 6, 7), true)))
+ .toEqual({ startTime: null, endTime: null });
+ });
+});
+
+describe("getMonthsInDateRange", () => {
+ it("names every month a range touches within one year", () => {
+ expect(getMonthsInDateRange("2026-03-14", "2026-06-02"))
+ .toEqual([ "2026-03", "2026-04", "2026-05", "2026-06" ]);
+ });
+
+ it("names a single month where both ends fall in it", () => {
+ expect(getMonthsInDateRange("2026-06-01", "2026-06-30")).toEqual([ "2026-06" ]);
+ });
+
+ it("runs a range spanning years out to the end of each one and in from the start of the next", () => {
+ expect(getMonthsInDateRange("2025-11-20", "2026-02-03"))
+ .toEqual([ "2025-11", "2025-12", "2026-01", "2026-02" ]);
+ });
+
+ it("pads the single-digit months, the names being what a lookup is keyed by", () => {
+ const months = getMonthsInDateRange("2026-01-01", "2026-12-31");
+ expect(months).toHaveLength(12);
+ expect(months[0]).toBe("2026-01");
+ expect(months[8]).toBe("2026-09");
+ expect(months[9]).toBe("2026-10");
+ });
+});
diff --git a/apps/client/src/widgets/react/floating_layers.spec.ts b/apps/client/src/widgets/react/floating_layers.spec.ts
new file mode 100644
index 0000000000..6671a83cdc
--- /dev/null
+++ b/apps/client/src/widgets/react/floating_layers.spec.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from "vitest";
+
+import { isWithinFloatingLayer } from "./floating_layers";
+
+/** Builds an element of the given class inside another, and answers with the innermost one — what a
+ * press actually lands on being a control deep inside the layer rather than the layer itself. */
+function elementIn(...classNames: string[]) {
+ let element = document.createElement("div");
+ for (const className of classNames) {
+ const child = document.createElement("div");
+ child.className = className;
+ element.appendChild(child);
+ element = child;
+ }
+ return element;
+}
+
+describe("isWithinFloatingLayer", () => {
+ it("recognises a press on one of the app's portaled layers", () => {
+ // One of each family named in the selector: a menu, a modal, an editor balloon, a picker,
+ // the context menu (matched by id rather than class), and an autocomplete.
+ for (const className of [ "dropdown-menu", "modal", "modal-backdrop", "popover", "tooltip", "gutter",
+ "ck-balloon-panel", "ck-body", "flatpickr-calendar", "attr-detail", "form-autocomplete-dropdown", "aa-dropdown-menu" ]) {
+ expect(isWithinFloatingLayer(elementIn(className)), className).toBe(true);
+ }
+ });
+
+ it("recognises the context menu, which the selector names by its id", () => {
+ const container = document.createElement("div");
+ container.id = "context-menu-container";
+ const item = document.createElement("a");
+ container.appendChild(item);
+
+ expect(isWithinFloatingLayer(item)).toBe(true);
+ });
+
+ it("looks past the element pressed to the layer enclosing it", () => {
+ // What a press lands on is a control several levels inside the menu, not the menu itself.
+ expect(isWithinFloatingLayer(elementIn("dropdown-menu", "dropdown-item", "bx bx-check"))).toBe(true);
+ });
+
+ it("says no for ordinary content, which is exactly what should dismiss a surface", () => {
+ expect(isWithinFloatingLayer(elementIn("note-detail", "some-widget"))).toBe(false);
+ });
+
+ it("says no for anything that is not an element at all", () => {
+ // A press heard on the document or the window carries a target that cannot be asked about
+ // ancestors; it must not read as a layer and hold a surface open.
+ expect(isWithinFloatingLayer(null)).toBe(false);
+ expect(isWithinFloatingLayer(document)).toBe(false);
+ expect(isWithinFloatingLayer(document.createTextNode("text"))).toBe(false);
+ });
+});
diff --git a/apps/client/src/widgets/react/peek_pane.spec.tsx b/apps/client/src/widgets/react/peek_pane.spec.tsx
index 3cb50516fe..ffd179e250 100644
--- a/apps/client/src/widgets/react/peek_pane.spec.tsx
+++ b/apps/client/src/widgets/react/peek_pane.spec.tsx
@@ -2,6 +2,7 @@ import { render } from "preact";
import { act } from "preact/test-utils";
import { afterEach, describe, expect, it, vi } from "vitest";
+import options from "../../services/options";
import { isWithinPeek, PaneModeController, persistedPaneVisible, reducePaneMode, usePaneMode, usePeekDismiss } from "./peek_pane";
describe("reducePaneMode", () => {
@@ -69,6 +70,46 @@ describe("usePaneMode", () => {
act(() => render(null, host));
});
+
+ it("opens docked where the option says so, and writes the distinction back as it changes", () => {
+ // The pane was left docked last time, which is the one thing the option remembers.
+ const isOption = vi.spyOn(options, "is").mockReturnValue(true);
+ const save = vi.spyOn(options, "save").mockResolvedValue(undefined);
+
+ let controller: PaneModeController | undefined;
+ const host = document.createElement("div");
+ document.body.appendChild(host);
+ function Harness() {
+ controller = usePaneMode("rightPaneVisible");
+ return null;
+ }
+ act(() => render(<Harness />, host));
+
+ expect(isOption).toHaveBeenCalledWith("rightPaneVisible");
+ expect(controller?.mode).toBe("docked");
+ expect(controller?.mounted).toBe(true);
+ // Nothing is written for merely arriving at what the option already said.
+ expect(save).not.toHaveBeenCalled();
+
+ // Leaving docked is a change of the distinction, so it is remembered.
+ act(() => controller?.toggleDocked());
+ expect(controller?.mode).toBe("closed");
+ expect(save).toHaveBeenCalledWith("rightPaneVisible", "false");
+
+ // A peek is not, being ephemeral: it comes and goes without touching the option.
+ save.mockClear();
+ act(() => controller?.togglePeek());
+ act(() => controller?.dismiss());
+ expect(save).not.toHaveBeenCalled();
+
+ // Docking again writes it back.
+ act(() => controller?.dock());
+ expect(save).toHaveBeenCalledWith("rightPaneVisible", "true");
+
+ act(() => render(null, host));
+ isOption.mockRestore();
+ save.mockRestore();
+ });
});
describe("persistedPaneVisible", () => {
@@ -111,11 +152,11 @@ describe("usePeekDismiss", () => {
document.body.innerHTML = "";
});
- function renderHook(active: boolean, onDismiss: () => void, keepOpenSelector = "#right-pane") {
+ function renderHook(active: boolean, onDismiss: () => void, keepOpenSelector = "#right-pane", focusSelector?: string) {
const host = document.createElement("div");
document.body.appendChild(host);
function Harness() {
- usePeekDismiss(active, onDismiss, { keepOpenSelector });
+ usePeekDismiss(active, onDismiss, { keepOpenSelector, focusSelector });
return null;
}
// act() flushes the effect so the document listeners are attached before we dispatch.
@@ -169,4 +210,35 @@ describe("usePeekDismiss", () => {
expect(onDismiss).toHaveBeenCalledTimes(1);
unmountActive();
});
+
+ it("leaves an Escape an inner element already answered alone", () => {
+ const onDismiss = vi.fn();
+ const unmount = renderHook(true, onDismiss);
+
+ // What a dropdown closing itself on Escape leaves behind: the press is spent, and the pane
+ // it was opened from stays where it is.
+ const handled = new KeyboardEvent("keydown", { key: "Escape", cancelable: true });
+ handled.preventDefault();
+ document.dispatchEvent(handled);
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ // Any other key is not this hook's business either.
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "a" }));
+ expect(onDismiss).not.toHaveBeenCalled();
+
+ unmount();
+ });
+
+ it("hands the focus back to what opened the peek, where it was told what that is", () => {
+ document.body.innerHTML = `<button class="peek-button"></button>`;
+ const onDismiss = vi.fn();
+ const unmount = renderHook(true, onDismiss, "#right-pane", ".peek-button");
+
+ document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" }));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ // Escape is a keyboard gesture, so the keyboard is left somewhere it can go on from.
+ expect(document.activeElement).toBe(document.querySelector(".peek-button"));
+
+ unmount();
+ });
});