Skip to content

Build your personal knowledge base with Trilium Notes

client: improve test coverage

Adorian Doran73e2e5057946
diff --git a/apps/client/src/widgets/react/ActionButton.mobile.spec.tsx b/apps/client/src/widgets/react/ActionButton.mobile.spec.tsx
new file mode 100644
index 0000000000..f16edc0e91
--- /dev/null
+++ b/apps/client/src/widgets/react/ActionButton.mobile.spec.tsx
@@ -0,0 +1,50 @@
+import { Tooltip } from "bootstrap";
+import { render } from "preact";
+import { act } from "preact/test-utils";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+/**
+ * `isMobile()` is read once, when the module loads, so the touch branch needs a file of its own; the
+ * pointer behaviour is what `ActionButton.spec.tsx` covers.
+ */
+vi.mock("../../services/utils", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../../services/utils")>(),
+ isMobile: () => true
+}));
+
+import ActionButton from "./ActionButton";
+
+describe("ActionButton on a touch screen", () => {
+ let container: HTMLElement;
+
+ beforeEach(() => {
+ container = document.createElement("div");
+ document.body.appendChild(container);
+ });
+
+ afterEach(() => {
+ render(null, container);
+ container.remove();
+ });
+
+ it("declines its tooltip where asked, handing the label to assistive technology instead", async () => {
+ await act(async () => render(
+ <ActionButton icon="bx bx-arrow-back" text="Back" noTooltipOnTouch />, container));
+
+ const button = container.querySelector("button");
+
+ // Nothing to open with the tap that presses the button, and the name is still given.
+ expect(button && Tooltip.getInstance(button)).toBeNull();
+ expect(button?.getAttribute("aria-label")).toBe("Back");
+ });
+
+ it("keeps the tooltip, and leaves the name to it, for a button that did not ask", async () => {
+ await act(async () => render(
+ <ActionButton icon="bx bx-refresh" text="Measure again" />, container));
+
+ const button = container.querySelector("button");
+
+ expect(button && Tooltip.getInstance(button)).not.toBeNull();
+ expect(button?.getAttribute("aria-label")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/react/ScrollableLabel.spec.tsx b/apps/client/src/widgets/react/ScrollableLabel.spec.tsx
index 5128d013b5..7c8ca1f78c 100644
--- a/apps/client/src/widgets/react/ScrollableLabel.spec.tsx
+++ b/apps/client/src/widgets/react/ScrollableLabel.spec.tsx
@@ -138,6 +138,24 @@ describe("ScrollableLabel", () => {
}
});
+ it("does not walk a label at all where motion has been asked against", () => {
+ const reduced = vi.spyOn(window, "matchMedia").mockReturnValue(
+ { matches: true } as unknown as MediaQueryList);
+
+ vi.useFakeTimers();
+
+ try {
+ const label = renderLabel("a name that would otherwise read itself out", 300, 100, true);
+
+ vi.advanceTimersByTime(5000);
+
+ expect(label.scrollLeft).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ reduced.mockRestore();
+ }
+ });
+
it("leaves a label that fits alone, fading nothing", async () => {
const label = renderLabel("short", 100);
diff --git a/apps/client/src/widgets/type_widgets/space_usage/browse.spec.tsx b/apps/client/src/widgets/type_widgets/space_usage/browse.spec.tsx
index 78022de281..1d140f90e5 100644
--- a/apps/client/src/widgets/type_widgets/space_usage/browse.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/space_usage/browse.spec.tsx
@@ -11,6 +11,7 @@ interface CapturedDonutProps {
title: string;
notePath: string[];
outerRings: DonutRing<UsageSegmentData>[];
+ selectedSegmentId?: string;
centerActions: ComponentChildren;
onTitleContextMenu: (event: MouseEvent) => void;
}
@@ -23,7 +24,9 @@ const mocks = vi.hoisted(() => ({
donutProps: undefined as unknown,
openContextMenu: vi.fn(),
contentChanged: vi.fn(),
- loadingChange: vi.fn()
+ loadingChange: vi.fn(),
+ select: vi.fn(),
+ pathChanged: vi.fn()
}));
vi.mock("./context_menu", () => ({
@@ -53,6 +56,12 @@ vi.mock("../../react/ActionButton", () => ({
)
}));
+// Uninitialized, the real `t` answers undefined for every key — which would leave the two figures
+// closing the ring unnamed, and a mark with no name is one the strip has nothing to say about.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
vi.mock("../../../services/froca", () => ({
default: {
getNotes: async (noteIds: string[]) => noteIds.map((noteId) => ({ noteId, title: `title:${noteId}` }))
@@ -60,6 +69,7 @@ vi.mock("../../../services/froca", () => ({
}));
import Browse from "./browse";
+import type { SpaceUsageSelection } from "./selection";
function usageOf(noteId: string, children: string[]): SpaceUsageNoteResponse {
return {
@@ -107,6 +117,40 @@ function donutProps() {
return mocks.donutProps as CapturedDonutProps;
}
+/** The children ring is the outer one; its segments are what a tap in this view lands on. */
+function childSegment(id: string) {
+ const ring = donutProps().outerRings[0];
+ const segment = ring?.segments.find((candidate) => candidate.id === id);
+
+ if (!ring || !segment) {
+ throw new Error(`no segment ${id} on the children ring`);
+ }
+
+ ring.onSegmentClick?.(segment);
+}
+
+function lastSelection(): SpaceUsageSelection {
+ return mocks.select.mock.calls[mocks.select.mock.calls.length - 1]?.[0] as SpaceUsageSelection;
+}
+
+/** How the page renders this view on a phone: a tap names a segment rather than descending into it. */
+function renderSelectableBrowse(selection?: SpaceUsageSelection) {
+ container = document.body.appendChild(document.createElement("div"));
+ render(
+ <Browse
+ path={[ "root" ]}
+ onPathChange={mocks.pathChanged}
+ refreshToken={0}
+ onContentChanged={mocks.contentChanged}
+ selection={selection ?? null}
+ onSelect={mocks.select}
+ onLoadingChange={mocks.loadingChange}
+ />,
+ container
+ );
+ return container;
+}
+
/** State set in event handlers and froca's async titles both land on later ticks. */
function flushRender() {
return new Promise((resolve) => setTimeout(resolve));
@@ -127,6 +171,8 @@ afterEach(() => {
mocks.fetchedUrls = [];
mocks.donutProps = undefined;
mocks.openContextMenu.mockClear();
+ mocks.select.mockClear();
+ mocks.pathChanged.mockClear();
});
describe("Browse", () => {
@@ -246,4 +292,80 @@ describe("Browse", () => {
ring.onSegmentContextMenu?.({ id: "/deleted-notes", value: 5, data: {} }, event);
expect(mocks.openContextMenu).not.toHaveBeenCalled();
});
+ it("names a tapped child for the strip instead of descending, keeping both actions on it", () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ renderSelectableBrowse();
+
+ childSegment("child/child1");
+
+ const selection = lastSelection();
+
+ expect(selection).toMatchObject({ markId: "child/child1", notePath: [ "root", "child1" ], size: 40 });
+ expect(mocks.pathChanged).not.toHaveBeenCalled();
+
+ // A second tap on the same segment is what walks in; the strip raises the menu instead.
+ selection.onOpen?.();
+ expect(mocks.pathChanged).toHaveBeenCalledWith([ "root", "child1" ]);
+
+ selection.onActivate?.(new MouseEvent("click"));
+ expect(mocks.openContextMenu).toHaveBeenCalledWith(
+ expect.anything(), [ "root", "child1" ], mocks.pathChanged, mocks.contentChanged);
+ });
+
+ it("names the two figures closing the ring, which stand for no note and open nothing", () => {
+ mocks.usage = {
+ ...usageOf("root", [ "child1" ]),
+ subtreeRevisionsContentSize: 500,
+ deletedNotes: { size: 300, noteCount: 1, attachmentCount: 0 }
+ };
+ renderSelectableBrowse();
+
+ childSegment("revisions");
+ expect(lastSelection()).toMatchObject({ markId: "revisions", size: 500 });
+ expect(lastSelection().notePath).toBeUndefined();
+ expect(lastSelection().onOpen).toBeUndefined();
+ expect(lastSelection().onActivate).toBeUndefined();
+
+ childSegment("/deleted-notes");
+ expect(lastSelection()).toMatchObject({ markId: "/deleted-notes", size: 300 });
+
+ });
+
+ it("names nothing for the bucket standing for several children at once", () => {
+ mocks.usage = {
+ ...usageOf("root", []),
+ children: [
+ { noteId: "big", subtreeSize: 100000, subtreeNoteCount: 1 },
+ { noteId: "sliver", subtreeSize: 1, subtreeNoteCount: 1 }
+ ]
+ };
+ renderSelectableBrowse();
+
+ childSegment("others");
+
+ expect(mocks.select).not.toHaveBeenCalled();
+ });
+
+ it("offers the chosen mark's own action as a line under the chart, and none without one", () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ const open = vi.fn();
+ const probe = renderSelectableBrowse({ markId: "child/child1", notePath: [ "root", "child1" ], size: 40, onOpen: open });
+
+ probe.querySelector<HTMLElement>(".space-usage-details-link")?.click();
+ expect(open).toHaveBeenCalledTimes(1);
+
+ // The line itself stays, holding the chart's layout still; only its label goes.
+ render(null, probe);
+ const empty = renderSelectableBrowse({ markId: "revisions", label: "Revisions", size: 10 });
+
+ expect(empty.querySelector(".space-usage-browse-details")).not.toBeNull();
+ expect(empty.querySelector(".space-usage-details-link")).toBeNull();
+ });
+
+ it("hands the chosen mark to the donut, so the ring can draw it", () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ renderSelectableBrowse({ markId: "child/child1", notePath: [ "root", "child1" ], size: 40 });
+
+ expect(donutProps().selectedSegmentId).toBe("child/child1");
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/space_usage/index.mobile.spec.tsx b/apps/client/src/widgets/type_widgets/space_usage/index.mobile.spec.tsx
new file mode 100644
index 0000000000..a046d26434
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/space_usage/index.mobile.spec.tsx
@@ -0,0 +1,208 @@
+import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { SpaceUsageSelection } from "./selection";
+
+/**
+ * The page reads `isMobile()` once, when the module loads, so what a phone gets is decided by the
+ * mock below rather than by anything a test can do afterwards. Hence a file of its own: the pointer
+ * behaviour is what `index.spec.tsx` covers.
+ */
+const mocks = vi.hoisted(() => ({
+ overview: undefined as unknown,
+ /** The page hands these to whichever view is on show; the stubs keep the last set. */
+ select: undefined as ((selection: SpaceUsageSelection) => void) | undefined,
+ selectedMarkId: undefined as string | undefined,
+ browseSelection: undefined as SpaceUsageSelection | null | undefined,
+ showDetails: undefined as ((notePath: string[]) => void) | undefined
+}));
+
+vi.mock("../../../services/utils", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../../../services/utils")>(),
+ isMobile: () => true
+}));
+
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+// The strip is measured with a ResizeObserver, which happy-dom does not provide; the page only
+// wants the height to leave the map room for it, so a fixed one stands in.
+vi.mock("../../react/hooks", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../../react/hooks")>(),
+ useElementSize: () => ({ height: 48 })
+}));
+
+vi.mock("../../react/use_fetch", () => ({
+ useFetch: () => ({ data: mocks.overview, failed: false, loading: false })
+}));
+
+vi.mock("../../../services/froca", () => ({
+ default: {
+ getNotes: async (noteIds: string[]) => noteIds.map((noteId) => ({ noteId, title: `title:${noteId}` }))
+ }
+}));
+
+vi.mock("./overview", () => ({
+ default: ({ selectedMarkId, onSelect, onShowDetails }: {
+ selectedMarkId?: string,
+ onSelect?: (selection: SpaceUsageSelection) => void,
+ onShowDetails: (notePath: string[]) => void
+ }) => {
+ mocks.select = onSelect;
+ mocks.selectedMarkId = selectedMarkId;
+ mocks.showDetails = onShowDetails;
+ return <div className="overview-stub" />;
+ }
+}));
+
+vi.mock("./browse", () => ({
+ default: ({ selection, onSelect }: {
+ selection?: SpaceUsageSelection | null,
+ onSelect?: (selection: SpaceUsageSelection) => void
+ }) => {
+ mocks.select = onSelect;
+ mocks.browseSelection = selection;
+ return <div className="browse-stub" />;
+ }
+}));
+
+import SpaceUsage from "./index";
+
+const OVERVIEW: SpaceUsageOverviewResponse = {
+ content: { size: 4000, noteCount: 12, attachmentsSize: 300, revisionsSize: 200 },
+ notes: [],
+ otherNotes: { size: 0, revisionsSize: 0, noteCount: 0 },
+ hiddenNotes: { size: 0, revisionsSize: 0, noteCount: 0 },
+ deletedNotes: { size: 900, noteCount: 3, attachmentCount: 2 },
+ unusedAttachments: { size: 0, attachmentCount: 0 },
+ total: { size: 3500, revisionsSize: 0, noteCount: 12 }
+};
+
+let container: HTMLDivElement | undefined;
+
+function renderPage() {
+ mocks.overview = OVERVIEW;
+ container = document.body.appendChild(document.createElement("div"));
+ render(<SpaceUsage />, container);
+ return container;
+}
+
+/** State set from a handler renders on a microtask. */
+function flushRender() {
+ return new Promise((resolve) => setTimeout(resolve));
+}
+
+/**
+ * Effects flush on an animation frame, so the page's own mount effects have to land before a tap is
+ * simulated: one of them lets the selection go whenever the ground under it moves, and arriving late
+ * it would let go of a mark chosen a moment earlier. In a browser it has long since run.
+ */
+function flushEffects() {
+ return new Promise((resolve) => requestAnimationFrame(() => setTimeout(resolve)));
+}
+
+function selectionOf(markId: string, onOpen?: () => void): SpaceUsageSelection {
+ return { markId, notePath: [ "root", markId ], size: 10, onOpen };
+}
+
+function stripTexts(probe: HTMLElement) {
+ return {
+ hint: probe.querySelector(".space-usage-selection-hint")?.textContent,
+ name: probe.querySelector(".space-usage-selection-name")?.textContent
+ };
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ mocks.overview = undefined;
+ mocks.select = undefined;
+ mocks.selectedMarkId = undefined;
+ mocks.browseSelection = undefined;
+});
+
+describe("SpaceUsage page on a phone", () => {
+ it("draws the totals as a grid of figures rather than as the status line", () => {
+ const probe = renderPage();
+ const figures = [ ...probe.querySelectorAll(".space-usage-status-value") ].map((el) => el.textContent);
+
+ expect(probe.querySelector(".space-usage-status")).toBeNull();
+ // Notes, total, attachments, deleted items, in that order.
+ expect(figures).toEqual([ "12", "3.91 KiB", "300 B", "900 B" ]);
+ });
+
+ it("keeps the strip on show from the start, saying what to do until something is chosen", async () => {
+ const probe = renderPage();
+
+ await flushEffects();
+
+ expect(stripTexts(probe).hint).toBe("space_usage.selection_hint");
+
+ mocks.select?.(selectionOf("n1"));
+ await flushRender();
+
+ expect(stripTexts(probe).hint).toBeUndefined();
+ await vi.waitFor(() => expect(stripTexts(probe).name).toBe("title:n1"));
+ expect(mocks.selectedMarkId).toBe("n1");
+ });
+
+ it("opens the chosen mark on a second tap, and lets go of one with nothing to open", async () => {
+ const open = vi.fn();
+ const probe = renderPage();
+
+ await flushEffects();
+ mocks.select?.(selectionOf("n1", open));
+ await flushRender();
+ mocks.select?.(selectionOf("n1", open));
+ await flushRender();
+
+ // Still chosen, and opened rather than let go of.
+ expect(open).toHaveBeenCalledTimes(1);
+ expect(mocks.selectedMarkId).toBe("n1");
+
+ mocks.select?.(selectionOf("bucket"));
+ await flushRender();
+ mocks.select?.(selectionOf("bucket"));
+ await flushRender();
+
+ expect(mocks.selectedMarkId).toBeUndefined();
+ expect(stripTexts(probe).hint).toBe("space_usage.selection_hint");
+ });
+
+ it("lets the selection go when the ground under it moves", async () => {
+ const probe = renderPage();
+
+ await flushEffects();
+ mocks.select?.(selectionOf("n1"));
+ await flushRender();
+ expect(mocks.selectedMarkId).toBe("n1");
+
+ // "Show details" switches the view and walks Browse to that note: the mark it named is not
+ // on the chart that follows.
+ mocks.showDetails?.([ "root", "p1", "n1" ]);
+ await flushRender();
+
+ expect(probe.querySelector(".browse-stub")).not.toBeNull();
+ expect(mocks.browseSelection ?? null).toBeNull();
+ expect(stripTexts(probe).hint).toBe("space_usage.selection_hint");
+ });
+
+ it("asks for a fresh reading and drops the selection when refresh is pressed", async () => {
+ const probe = renderPage();
+
+ await flushEffects();
+ mocks.select?.(selectionOf("n1"));
+ await flushRender();
+ expect(mocks.selectedMarkId).toBe("n1");
+
+ probe.querySelector<HTMLElement>(".space-usage-refresh")?.click();
+ await flushEffects();
+
+ expect(stripTexts(probe).hint).toBe("space_usage.selection_hint");
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/space_usage/note_usage_donut.spec.tsx b/apps/client/src/widgets/type_widgets/space_usage/note_usage_donut.spec.tsx
index dfc91b09af..ed1f7473dd 100644
--- a/apps/client/src/widgets/type_widgets/space_usage/note_usage_donut.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/space_usage/note_usage_donut.spec.tsx
@@ -6,7 +6,9 @@ import { t } from "../../../services/i18n";
import { formatSize } from "../../../services/utils";
const mocks = vi.hoisted(() => ({
- triggerCommand: vi.fn()
+ triggerCommand: vi.fn(),
+ select: vi.fn(),
+ titleContextMenu: vi.fn()
}));
vi.mock("../../../components/app_context", () => ({
@@ -31,6 +33,7 @@ vi.mock("react-i18next", () => ({
}));
import NoteUsageDonut, { segmentTooltip } from "./note_usage_donut";
+import type { SpaceUsageSelection } from "./selection";
const USAGE: SpaceUsageNoteResponse = {
noteId: "n1",
@@ -65,6 +68,27 @@ function renderDonut() {
return container;
}
+/** How Browse renders it on a phone: a tap names the segment rather than opening what it stands for. */
+function renderSelectableDonut(selectedSegmentId?: string) {
+ container = document.body.appendChild(document.createElement("div"));
+ render(
+ <NoteUsageDonut
+ usage={USAGE}
+ title="My note"
+ notePath={[ "root", "n1" ]}
+ selectedSegmentId={selectedSegmentId}
+ onSelectSegment={mocks.select}
+ onTitleContextMenu={mocks.titleContextMenu}
+ />,
+ container
+ );
+ return container;
+}
+
+function lastSelection(): SpaceUsageSelection {
+ return mocks.select.mock.calls[mocks.select.mock.calls.length - 1]?.[0] as SpaceUsageSelection;
+}
+
afterEach(() => {
if (container) {
render(null, container);
@@ -72,6 +96,8 @@ afterEach(() => {
container = undefined;
}
mocks.triggerCommand.mockClear();
+ mocks.select.mockClear();
+ mocks.titleContextMenu.mockClear();
});
describe("NoteUsageDonut", () => {
@@ -154,6 +180,42 @@ describe("NoteUsageDonut", () => {
expect(mocks.triggerCommand).not.toHaveBeenCalled();
});
+ it("names a tapped composition segment for the strip, opening nothing itself", () => {
+ const probe = renderSelectableDonut();
+ const tap = (selector: string) => probe.querySelector(selector)
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
+
+ tap("circle.space-usage-segment-body");
+ expect(lastSelection()).toMatchObject({ markId: "body", notePath: [ "root", "n1" ], size: 10000 });
+ // The body stands for the note, so the strip raises what the centre title raises.
+ lastSelection().onActivate?.(new MouseEvent("click"));
+ expect(mocks.titleContextMenu).toHaveBeenCalled();
+
+ tap("circle.space-usage-segment-attachment");
+ expect(lastSelection()).toMatchObject({ markId: "attachment/a1", label: "Attachment one", size: 5000 });
+ lastSelection().onActivate?.(new MouseEvent("click"));
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("openInPopup", {
+ noteIdOrPath: "root/n1",
+ viewScope: { viewMode: "attachments", attachmentId: "a1" }
+ });
+
+ // A ring tap opens nothing on its own, whichever segment it lands on.
+ expect(lastSelection().onOpen).toBeUndefined();
+
+ // The bucket stands for several attachments at once, so it names nothing.
+ mocks.select.mockClear();
+ tap("circle.space-usage-segment-others");
+ expect(mocks.select).not.toHaveBeenCalled();
+ });
+
+ it("draws the chosen segment as chosen", () => {
+ const probe = renderSelectableDonut("body");
+
+ expect(probe.querySelector("circle.space-usage-segment-body")?.classList
+ .contains("donut-segment-selected")).toBe(true);
+ expect(probe.querySelectorAll(".donut-segment-selected")).toHaveLength(1);
+ });
+
it("totals each ring in the hole, with the actions above the title", () => {
const probe = renderDonut();
const center = probe.querySelector<HTMLElement>(".donut-chart-center");
diff --git a/apps/client/src/widgets/type_widgets/space_usage/overview.spec.tsx b/apps/client/src/widgets/type_widgets/space_usage/overview.spec.tsx
index 1624ba8e96..fed4cee5d8 100644
--- a/apps/client/src/widgets/type_widgets/space_usage/overview.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/space_usage/overview.spec.tsx
@@ -8,7 +8,8 @@ const mocks = vi.hoisted(() => ({
openDeletedNotesMenu: vi.fn(),
openRevisionsMenu: vi.fn(),
showDetails: vi.fn(),
- contentChanged: vi.fn()
+ contentChanged: vi.fn(),
+ select: vi.fn()
}));
vi.mock("../../../components/app_context", () => ({
@@ -41,6 +42,7 @@ vi.mock("../../../services/froca", () => ({
}));
import Overview from "./overview";
+import type { SpaceUsageSelection } from "./selection";
const OVERVIEW: SpaceUsageOverviewResponse = {
content: { size: 400, noteCount: 3, attachmentsSize: 0, revisionsSize: 60 },
@@ -67,6 +69,26 @@ function renderOverview() {
return container;
}
+/** The page renders the map this way on a phone: a tap names the cell instead of opening it. */
+function renderSelectableOverview(selectedMarkId?: string) {
+ container = document.body.appendChild(document.createElement("div"));
+ render(
+ <Overview
+ overview={OVERVIEW}
+ selectedMarkId={selectedMarkId}
+ onSelect={mocks.select}
+ onShowDetails={mocks.showDetails}
+ onContentChanged={mocks.contentChanged}
+ />,
+ container
+ );
+ return container;
+}
+
+function lastSelection(): SpaceUsageSelection {
+ return mocks.select.mock.calls[mocks.select.mock.calls.length - 1]?.[0] as SpaceUsageSelection;
+}
+
afterEach(() => {
if (container) {
render(null, container);
@@ -74,6 +96,7 @@ afterEach(() => {
container = undefined;
}
mocks.triggerCommand.mockClear();
+ mocks.select.mockClear();
mocks.openContextMenu.mockClear();
mocks.openDeletedNotesMenu.mockClear();
mocks.openRevisionsMenu.mockClear();
@@ -164,6 +187,58 @@ describe("Overview", () => {
expect(mocks.triggerCommand).not.toHaveBeenCalled();
});
+ it("names a tapped cell for the strip instead of opening it, offering the note's own actions", () => {
+ const probe = renderSelectableOverview();
+
+ probe.querySelector('[data-href="#root/n1"]')?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ const selection = lastSelection();
+
+ expect(selection).toMatchObject({ markId: "n1", notePath: [ "root", "n1" ], size: 200 });
+ expect(mocks.triggerCommand).not.toHaveBeenCalled();
+
+ // The strip raises the note menu; a second tap on the cell opens the note.
+ selection.onActivate?.(new MouseEvent("click"));
+ expect(mocks.openContextMenu).toHaveBeenCalledWith(
+ expect.anything(), [ "root", "n1" ], mocks.showDetails, mocks.contentChanged);
+
+ selection.onOpen?.();
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "root/n1" });
+ });
+
+ it("names a tapped bucket by the crowd it stands for, with nothing to open", () => {
+ const probe = renderSelectableOverview();
+ const tap = (selector: string) =>
+ probe.querySelector(selector)?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ tap(".treemap-cell-deleted");
+ expect(lastSelection()).toMatchObject({ markId: "/deleted-notes", size: 70 });
+ // It names a crowd rather than a note, so it carries a label instead of a path and has
+ // nothing to open. What that label says is the labels spec's business; `t` answers nothing
+ // here, the catalogue being uninitialized under test.
+ expect(lastSelection().notePath).toBeUndefined();
+ expect(lastSelection().onOpen).toBeUndefined();
+
+ // The buckets that can be acted on answer with their own menu, the others with none.
+ lastSelection().onActivate?.(new MouseEvent("click"));
+ expect(mocks.openDeletedNotesMenu).toHaveBeenCalledWith(expect.anything(), mocks.contentChanged);
+
+ tap(".treemap-cell-revisions");
+ lastSelection().onActivate?.(new MouseEvent("click"));
+ expect(mocks.openRevisionsMenu).toHaveBeenCalledWith(expect.anything(), mocks.contentChanged);
+
+ tap(".treemap-cell-other");
+ expect(lastSelection().onActivate).toBeUndefined();
+ });
+
+ it("draws the chosen cell as chosen, and only that one", () => {
+ const probe = renderSelectableOverview("n1");
+
+ expect(probe.querySelector('[data-href="#root/n1"]')?.classList.contains("treemap-cell-selected"))
+ .toBe(true);
+ expect(probe.querySelectorAll(".treemap-cell-selected")).toHaveLength(1);
+ });
+
it("answers the revisions bucket with its own menu, never the note one", () => {
const probe = renderOverview();
diff --git a/apps/client/src/widgets/type_widgets/space_usage/selection.spec.tsx b/apps/client/src/widgets/type_widgets/space_usage/selection.spec.tsx
new file mode 100644
index 0000000000..7740be3034
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/space_usage/selection.spec.tsx
@@ -0,0 +1,92 @@
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// Uninitialized, the real `t` answers undefined for every key, which would drop the hint the strip
+// stands in with entirely.
+vi.mock("../../../services/i18n", () => ({
+ t: (key: string) => key
+}));
+
+vi.mock("../../../services/froca", () => ({
+ default: {
+ getNotes: async (noteIds: string[]) => noteIds.map((noteId) => ({ noteId, title: `title:${noteId}` }))
+ }
+}));
+
+import SelectionStrip, { type SpaceUsageSelection } from "./selection";
+
+let container: HTMLDivElement | undefined;
+
+function renderStrip(selection: SpaceUsageSelection | null) {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<SelectionStrip selection={selection} />, container);
+ return container;
+}
+
+function textOf(probe: HTMLElement, selector: string) {
+ return probe.querySelector(selector)?.textContent;
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+});
+
+describe("SelectionStrip", () => {
+ it("names the chosen note: where it sits, what it is called, and how much it takes", async () => {
+ const probe = renderStrip({
+ markId: "n1",
+ notePath: [ "root", "p1", "n1" ],
+ size: 1024
+ });
+
+ // The strip draws first and picks the titles up once froca has answered.
+ await vi.waitFor(() =>
+ expect(textOf(probe, ".space-usage-selection-name")).toBe("title:n1"));
+
+ // The note's own title is the name; everything above it is the location.
+ expect(textOf(probe, ".space-usage-selection-path")).toBe("title:root › title:p1");
+ expect(textOf(probe, ".space-usage-selection-size")).toBe("1 KiB");
+ });
+
+ it("stands in with the note IDs until the titles arrive", () => {
+ const probe = renderStrip({ markId: "n1", notePath: [ "root", "n1" ], size: 10 });
+
+ // Rendered before froca has answered: the strip draws rather than waiting.
+ expect(textOf(probe, ".space-usage-selection-name")).toBe("");
+ });
+
+ it("names a mark that stands for no note by its own label, with no location to show", () => {
+ const probe = renderStrip({ markId: "/deleted-notes", label: "Deleted items", size: 2048 });
+
+ expect(textOf(probe, ".space-usage-selection-name")).toBe("Deleted items");
+ expect(textOf(probe, ".space-usage-selection-path")).toBe("");
+ expect(textOf(probe, ".space-usage-selection-size")).toBe("2 KiB");
+ });
+
+ it("says what to do while nothing is chosen, naming nothing", () => {
+ const probe = renderStrip(null);
+
+ expect(textOf(probe, ".space-usage-selection-hint")).toBe("space_usage.selection_hint");
+ expect(probe.querySelector(".space-usage-selection-name")).toBeNull();
+ expect(probe.querySelector(".space-usage-selection-actionable")).toBeNull();
+ });
+
+ it("raises the mark's own action on a tap, and stays inert for a mark with none", () => {
+ const activate = vi.fn();
+ const probe = renderStrip({ markId: "n1", notePath: [ "root", "n1" ], size: 10, onActivate: activate });
+
+ const strip = probe.querySelector(".space-usage-selection");
+
+ expect(strip?.classList.contains("space-usage-selection-actionable")).toBe(true);
+ strip?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(activate).toHaveBeenCalledTimes(1);
+
+ render(<SelectionStrip selection={{ markId: "others", label: "3 more notes", size: 10 }} />, probe);
+ probe.querySelector(".space-usage-selection")?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(activate).toHaveBeenCalledTimes(1);
+ });
+});