Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager/space usage: improve test coverage

Adorian Doranbb5406b8f3c1
diff --git a/apps/client/src/widgets/react/charts/DonutChart.render.spec.tsx b/apps/client/src/widgets/react/charts/DonutChart.render.spec.tsx
new file mode 100644
index 0000000000..0dbc160a6f
--- /dev/null
+++ b/apps/client/src/widgets/react/charts/DonutChart.render.spec.tsx
@@ -0,0 +1,145 @@
+import { render } from "preact";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+
+import DonutChart, { type DonutRing } from "./DonutChart";
+
+// Preact decides the event name by probing for the element's on* IDL property; happy-dom's SVG (and
+// some HTML) prototypes lack the mouse ones, so without this the handlers register under a
+// case-mangled name and dispatched events never connect. Real browsers have these properties.
+beforeAll(() => {
+ for (const prototype of [ SVGElement.prototype, HTMLElement.prototype ]) {
+ for (const name of [ "onmouseenter", "onmouseleave", "onmousemove", "onclick" ]) {
+ if (!(name in prototype)) {
+ Object.defineProperty(prototype, name, { value: null, writable: true });
+ }
+ }
+ }
+});
+
+let container: HTMLDivElement | undefined;
+
+function renderChart(rings: DonutRing<string>[], center?: preact.ComponentChildren) {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<DonutChart<string> rings={rings}>{center}</DonutChart>, container);
+ return container;
+}
+
+/** happy-dom lays nothing out, so the chart box is stated explicitly for the flip math. */
+function statChartBox(probe: HTMLElement) {
+ const chart = probe.querySelector<HTMLElement>(".donut-chart");
+ if (!chart) throw new Error("No chart rendered");
+ chart.getBoundingClientRect = () => ({
+ left: 0, top: 0, width: 200, height: 200, right: 200, bottom: 200, x: 0, y: 0,
+ toJSON: () => ({})
+ } as DOMRect);
+ return chart;
+}
+
+/** State set in an event handler renders on Preact's microtask, not synchronously. */
+function flushRender() {
+ return new Promise((resolve) => setTimeout(resolve));
+}
+
+function ring(overrides: Partial<DonutRing<string>> = {}): DonutRing<string> {
+ return {
+ id: "test-ring",
+ radius: 100,
+ thickness: 20,
+ segments: [
+ { id: "a", value: 75, tooltip: "A tip", hue: 10, data: "a" },
+ { id: "b", value: 25, className: "seg-b", data: "b" },
+ { id: "empty", value: 0, tooltip: "never shown" }
+ ],
+ ...overrides
+ };
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+});
+
+describe("DonutChart rendering", () => {
+ it("draws one dash-arc circle per non-empty segment, proportional to its value", () => {
+ const probe = renderChart([ ring() ]);
+ const circles = [ ...probe.querySelectorAll<SVGCircleElement>("circle") ];
+
+ expect(circles.length).toBe(2);
+
+ const arcLength = (circle: SVGCircleElement) => parseFloat(circle.style.strokeDasharray);
+ // 75 vs 25 — the shared gap shaving keeps it just off exactly 3.
+ expect(arcLength(circles[0]) / arcLength(circles[1])).toBeGreaterThan(2.5);
+ expect(circles[0].style.strokeWidth).toContain("20");
+ });
+
+ it("tints by hue variable, forwards classes, and renders the center content", () => {
+ const probe = renderChart([ ring() ], <span className="center-probe">middle</span>);
+ const [ a, b ] = [ ...probe.querySelectorAll<SVGCircleElement>("circle") ];
+
+ expect(a.classList.contains("donut-colored")).toBe(true);
+ expect(a.style.getPropertyValue("--donut-hue")).toBe("10");
+ expect(b.classList.contains("donut-colored")).toBe(false);
+ expect(b.classList.contains("seg-b")).toBe(true);
+
+ expect(probe.querySelector(".donut-chart-center .center-probe")?.textContent).toBe("middle");
+ });
+
+ it("hands the clicked segment back and marks the ring clickable", () => {
+ const onSegmentClick = vi.fn();
+ const probe = renderChart([ ring({ onSegmentClick }) ]);
+ const [ , b ] = [ ...probe.querySelectorAll<SVGCircleElement>("circle") ];
+
+ expect(b.classList.contains("donut-clickable")).toBe(true);
+ b.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ expect(onSegmentClick).toHaveBeenCalledTimes(1);
+ expect(onSegmentClick.mock.calls[0][0]).toMatchObject({ id: "b", data: "b" });
+ });
+
+ it("shows the cursor-following tooltip on hover, moves it, flips it past midline and hides it", async () => {
+ const probe = renderChart([ ring() ]);
+ const chart = statChartBox(probe);
+ const [ a ] = [ ...probe.querySelectorAll<SVGCircleElement>("circle") ];
+
+ a.dispatchEvent(new MouseEvent("mouseenter", { clientX: 30, clientY: 40 }));
+ await flushRender();
+ const tooltip = probe.querySelector<HTMLElement>(".donut-chart-tooltip");
+ expect(tooltip?.textContent).toBe("A tip");
+ // The Trilium look depends on riding the real tooltip classes.
+ expect(tooltip?.classList.contains("tooltip")).toBe(true);
+ expect(tooltip?.classList.contains("show")).toBe(true);
+ expect(tooltip?.style.left).toBe("30px");
+ expect(tooltip?.classList.contains("donut-chart-tooltip-flipped")).toBe(false);
+
+ chart.dispatchEvent(new MouseEvent("mousemove", { clientX: 150, clientY: 60 }));
+ await flushRender();
+ const moved = probe.querySelector<HTMLElement>(".donut-chart-tooltip");
+ expect(moved?.style.left).toBe("150px");
+ expect(moved?.style.top).toBe("60px");
+ expect(moved?.classList.contains("donut-chart-tooltip-flipped")).toBe(true);
+
+ a.dispatchEvent(new MouseEvent("mouseleave"));
+ await flushRender();
+ expect(probe.querySelector(".donut-chart-tooltip")).toBeNull();
+ });
+
+ it("shows no tooltip for a segment without one, and clears on leaving the chart", async () => {
+ const probe = renderChart([ ring() ]);
+ statChartBox(probe);
+ const [ a, b ] = [ ...probe.querySelectorAll<SVGCircleElement>("circle") ];
+
+ b.dispatchEvent(new MouseEvent("mouseenter", { clientX: 10, clientY: 10 }));
+ await flushRender();
+ expect(probe.querySelector(".donut-chart-tooltip")).toBeNull();
+
+ a.dispatchEvent(new MouseEvent("mouseenter", { clientX: 10, clientY: 10 }));
+ await flushRender();
+ expect(probe.querySelector(".donut-chart-tooltip")).not.toBeNull();
+ probe.querySelector(".donut-chart")?.dispatchEvent(new MouseEvent("mouseleave"));
+ await flushRender();
+ expect(probe.querySelector(".donut-chart-tooltip")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/react/charts/DonutChart.tsx b/apps/client/src/widgets/react/charts/DonutChart.tsx
index 864dfbb8ec..3329ecece5 100644
--- a/apps/client/src/widgets/react/charts/DonutChart.tsx
+++ b/apps/client/src/widgets/react/charts/DonutChart.tsx
@@ -70,6 +70,7 @@ export default function DonutChart<T>({ rings, className, children }: DonutChart
const positionOf = (event: { clientX: number, clientY: number }) => {
const rect = containerRef.current?.getBoundingClientRect();
+ /* v8 ignore next 3 -- the events only fire from inside the rendered container */
if (!rect) {
return { x: 0, y: 0, flipped: false };
}
@@ -82,8 +83,10 @@ export default function DonutChart<T>({ rings, className, children }: DonutChart
<div
ref={containerRef}
className={clsx("donut-chart", className)}
- onPointerMove={(event) => setHover((current) => current && { ...current, ...positionOf(event) })}
- onPointerLeave={() => setHover(null)}
+ // Mouse events rather than pointer events: hover has no meaning on touch anyway, and
+ // pointer handlers don't register correctly under the test DOM (see the render spec).
+ onMouseMove={(event) => setHover((current) => current && { ...current, ...positionOf(event) })}
+ onMouseLeave={() => setHover(null)}
>
<svg viewBox={`${-half} ${-half} ${DONUT_VIEW_SIZE} ${DONUT_VIEW_SIZE}`}>
{/* Rotated so every ring starts at 12 o'clock. */}
@@ -143,8 +146,8 @@ function Ring<T>({ ring, onSegmentHover }: {
r={ring.radius}
fill="none"
onClick={ring.onSegmentClick && (() => ring.onSegmentClick?.(segment))}
- onPointerEnter={(event) => onSegmentHover(segment, event)}
- onPointerLeave={() => onSegmentHover(null)}
+ onMouseEnter={(event) => onSegmentHover(segment, event)}
+ onMouseLeave={() => onSegmentHover(null)}
// Arc geometry is data-driven; as inline *style* (not attributes) it stays
// animatable by the stylesheet's transition and sweep keyframes.
style={{
diff --git a/apps/client/src/widgets/react/charts/Treemap.spec.tsx b/apps/client/src/widgets/react/charts/Treemap.spec.tsx
new file mode 100644
index 0000000000..ba278ded6a
--- /dev/null
+++ b/apps/client/src/widgets/react/charts/Treemap.spec.tsx
@@ -0,0 +1,114 @@
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+// The container never gets a real layout under happy-dom, so the size hook is stubbed to give the
+// treemap a canvas; everything else renders for real.
+const mocks = vi.hoisted(() => ({
+ size: { width: 400, height: 300 } as { width: number, height: number } | undefined
+}));
+vi.mock("../hooks", () => ({
+ useElementSize: () => mocks.size
+}));
+
+import Treemap, { type TreemapItem } from "./Treemap";
+
+let container: HTMLDivElement | undefined;
+
+function renderTreemap(root: TreemapItem<string>, onItemClick?: (item: TreemapItem<string>) => void) {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<Treemap<string> root={root} onItemClick={onItemClick} />, container);
+ return container;
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ mocks.size = { width: 400, height: 300 };
+});
+
+const ROOT: TreemapItem<string> = {
+ id: "root",
+ children: [
+ {
+ id: "folder",
+ children: [
+ {
+ id: "big",
+ value: 300,
+ hue: 120,
+ data: "big",
+ attributes: { "data-href": "#root/folder/big" }
+ },
+ { id: "small", value: 100, data: "small" }
+ ]
+ },
+ { id: "bucket", value: 100, className: "bucket-cell" },
+ { id: "empty", value: 0 },
+ { id: "no-value" }
+ ]
+};
+
+describe("Treemap", () => {
+ it("draws only the leaves: parents shape the layout, zero-weight cells disappear", () => {
+ const probe = renderTreemap(ROOT);
+ const cells = [ ...probe.querySelectorAll(".treemap-cell") ];
+
+ // big, small and the bucket — no cell for the folder, none for the empty leaf.
+ expect(cells.length).toBe(3);
+
+ for (const cell of cells) {
+ const { left, top, width, height } = (cell as HTMLElement).style;
+ expect(parseFloat(width)).toBeGreaterThan(0);
+ expect(parseFloat(height)).toBeGreaterThan(0);
+ expect(left).not.toBe("");
+ expect(top).not.toBe("");
+ }
+ });
+
+ it("tints a cell through its hue variable and forwards attributes and classes", () => {
+ const probe = renderTreemap(ROOT);
+
+ const big = probe.querySelector<HTMLElement>('[data-href="#root/folder/big"]');
+ expect(big?.classList.contains("treemap-colored")).toBe(true);
+ expect(big?.style.getPropertyValue("--treemap-hue")).toBe("120");
+
+ const bucket = probe.querySelector<HTMLElement>(".bucket-cell");
+ expect(bucket?.classList.contains("treemap-colored")).toBe(false);
+ expect(bucket?.style.getPropertyValue("--treemap-hue")).toBe("");
+ });
+
+ it("hands the clicked item back to the consumer", () => {
+ const onItemClick = vi.fn();
+ const probe = renderTreemap(ROOT, onItemClick);
+
+ probe.querySelector('[data-href="#root/folder/big"]')
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+
+ expect(onItemClick).toHaveBeenCalledTimes(1);
+ expect(onItemClick.mock.calls[0][0]).toMatchObject({ id: "big", data: "big" });
+ });
+
+ it("draws nothing until the container has a usable size", () => {
+ mocks.size = undefined;
+ expect(renderTreemap(ROOT).querySelectorAll(".treemap-cell").length).toBe(0);
+
+ render(null, container as HTMLDivElement);
+ mocks.size = { width: 5, height: 5 };
+ expect(renderTreemap(ROOT).querySelectorAll(".treemap-cell").length).toBe(0);
+ });
+
+ it("gives bigger values proportionally bigger areas", () => {
+ const probe = renderTreemap(ROOT);
+ const areaOf = (selector: string) => {
+ const cell = probe.querySelector<HTMLElement>(selector);
+ if (!cell) throw new Error(`No cell for '${selector}'`);
+ return parseFloat(cell.style.width) * parseFloat(cell.style.height);
+ };
+
+ // 300 vs 100: padding shaves a little off, so demand a clear factor rather than exactness.
+ expect(areaOf('[data-href="#root/folder/big"]') / areaOf(".bucket-cell")).toBeGreaterThan(2);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx
new file mode 100644
index 0000000000..ef5057ebf0
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx
@@ -0,0 +1,168 @@
+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+import { type ComponentChildren, render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type { DonutRing } from "../../../../react/charts/DonutChart";
+import type { UsageSegmentData } from "./donut_segments";
+
+interface CapturedDonutProps {
+ usage: SpaceUsageNoteResponse;
+ title: string;
+ notePath: string[];
+ outerRings: DonutRing<UsageSegmentData>[];
+ centerActions: ComponentChildren;
+}
+
+const mocks = vi.hoisted(() => ({
+ usage: undefined as unknown,
+ fetchedUrls: [] as string[],
+ donutProps: undefined as unknown
+}));
+
+vi.mock("./use_space_usage_fetch", () => ({
+ useSpaceUsageFetch: (url: string) => {
+ mocks.fetchedUrls.push(url);
+ return mocks.usage;
+ }
+}));
+
+// The donut is covered by its own spec; here it captures its props and renders the center actions
+// so the back button is reachable.
+vi.mock("./note_usage_donut", () => ({
+ default: (props: CapturedDonutProps) => {
+ mocks.donutProps = props;
+ return <div className="donut-stub">{props.centerActions}</div>;
+ },
+ segmentTooltip: (kind: string, title: string, size: number) => `${kind}:${title}:${size}`
+}));
+
+vi.mock("../../../../react/ActionButton", () => ({
+ default: ({ className, disabled, onClick }: { className?: string, disabled?: boolean, onClick?: () => void }) => (
+ <button type="button" className={`back-stub ${className ?? ""}`} disabled={disabled} onClick={onClick} />
+ )
+}));
+
+vi.mock("../../../../../services/froca", () => ({
+ default: {
+ getNotes: async (noteIds: string[]) => noteIds.map((noteId) => ({ noteId, title: `title:${noteId}` }))
+ }
+}));
+
+import Browse from "./browse";
+
+function usageOf(noteId: string, children: string[]): SpaceUsageNoteResponse {
+ return {
+ noteId,
+ ownSize: 10,
+ attachmentsSize: 0,
+ revisionsSize: 0,
+ noteContentSize: 10,
+ subtreeContentSize: 100,
+ attachments: [],
+ children: children.map((childId) => ({
+ noteId: childId,
+ subtreeSize: 40,
+ subtreeRevisionsSize: 0,
+ subtreeNoteCount: 2
+ }))
+ };
+}
+
+let container: HTMLDivElement | undefined;
+
+function renderBrowse() {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<Browse />, container);
+ return container;
+}
+
+function donutProps() {
+ return mocks.donutProps as CapturedDonutProps;
+}
+
+/** State set in event handlers and froca's async titles both land on later ticks. */
+function flushRender() {
+ return new Promise((resolve) => setTimeout(resolve));
+}
+
+function crumbTexts(probe: HTMLElement) {
+ return [ ...probe.querySelectorAll(".space-usage-crumb") ].map((crumb) => crumb.textContent);
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ mocks.usage = undefined;
+ mocks.fetchedUrls = [];
+ mocks.donutProps = undefined;
+});
+
+describe("Browse", () => {
+ it("shows the loading state until the usage arrives", () => {
+ mocks.usage = undefined;
+ const probe = renderBrowse();
+
+ expect(probe.querySelector(".space-usage-loading")).not.toBeNull();
+ expect(probe.querySelector(".donut-stub")).toBeNull();
+ expect(mocks.fetchedUrls).toEqual([ "space-usage/note/root" ]);
+ });
+
+ it("renders the donut for the root with its children ring and resolved titles", async () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ const probe = renderBrowse();
+ // The titles arrive via an effect, which Preact schedules a frame later than state updates.
+ await vi.waitFor(() => expect(donutProps().title).toBe("title:root"));
+ expect(donutProps().notePath).toEqual([ "root" ]);
+ expect(crumbTexts(probe)).toEqual([ "title:root" ]);
+
+ const ring = donutProps().outerRings[0];
+ expect(ring.segments[0]).toMatchObject({
+ data: { noteId: "child1" },
+ tooltip: "child:title:child1:40"
+ });
+
+ // Nowhere to go back to from the root.
+ expect(probe.querySelector<HTMLButtonElement>(".back-stub")?.disabled).toBe(true);
+ });
+
+ it("descends into a clicked child, then navigates back via button and breadcrumb", async () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ const probe = renderBrowse();
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root" ]));
+
+ donutProps().outerRings[0].onSegmentClick?.({ id: "child/child1", value: 40, data: { noteId: "child1" } });
+ await flushRender();
+
+ expect(mocks.fetchedUrls).toContain("space-usage/note/child1");
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root", "title:child1" ]));
+
+ const back = probe.querySelector<HTMLButtonElement>(".back-stub");
+ expect(back?.disabled).toBe(false);
+ back?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root" ]));
+
+ // Descend twice, then jump straight home through the first crumb.
+ donutProps().outerRings[0].onSegmentClick?.({ id: "child/child1", value: 40, data: { noteId: "child1" } });
+ await flushRender();
+ donutProps().outerRings[0].onSegmentClick?.({ id: "child/child2", value: 40, data: { noteId: "child2" } });
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root", "title:child1", "title:child2" ]));
+
+ probe.querySelector<HTMLButtonElement>("button.space-usage-crumb")
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root" ]));
+ });
+
+ it("ignores clicks on segments that name no note, like the deleted bucket", async () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ const probe = renderBrowse();
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root" ]));
+
+ donutProps().outerRings[0].onSegmentClick?.({ id: "/deleted-notes", value: 5, data: {} });
+ await flushRender();
+
+ expect(crumbTexts(probe)).toEqual([ "title:root" ]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts
index b980c79565..aa088a4306 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts
@@ -68,6 +68,17 @@ describe("buildCompositionSegments", () => {
});
});
+ it("breaks size ties deterministically by attachment ID", () => {
+ const segments = buildCompositionSegments(usage({
+ attachments: [
+ { attachmentId: "beta", title: "B", role: "file", size: 40 },
+ { attachmentId: "alpha", title: "A", role: "file", size: 40 }
+ ]
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "attachment/alpha", "attachment/beta" ]);
+ });
+
it("drops empty components entirely", () => {
const segments = buildCompositionSegments(usage({
attachments: [ { attachmentId: "empty", title: "Empty", role: "file", size: 0 } ]
@@ -99,6 +110,14 @@ describe("buildChildrenSegments", () => {
});
});
+ it("breaks subtree-size ties deterministically by note ID", () => {
+ const segments = buildChildrenSegments(usage({
+ children: [ child("zebra", 40), child("aardvark", 40) ]
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "child/aardvark", "child/zebra" ]);
+ });
+
it("consolidates children below 0.5% of the ring into an inert counted bucket", () => {
const segments = buildChildrenSegments(usage({
children: [ child("big", 10000), child("tiny1", 30), child("tiny2", 10) ]
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx
new file mode 100644
index 0000000000..a42e100a36
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx
@@ -0,0 +1,121 @@
+import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
+import { type ComponentChildren, render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { t } from "../../../../../services/i18n";
+import { formatSize } from "../../../../../services/utils";
+
+const mocks = vi.hoisted(() => ({
+ overview: undefined as unknown
+}));
+
+vi.mock("./use_space_usage_fetch", () => ({
+ useSpaceUsageFetch: () => mocks.overview
+}));
+
+vi.mock("./browse", () => ({
+ default: () => <div className="browse-stub" />
+}));
+
+vi.mock("./overview", () => ({
+ default: () => <div className="overview-stub" />
+}));
+
+vi.mock("../../components/OptionsPageHeader", () => ({
+ default: ({ actions, below }: { actions?: ComponentChildren, below?: ComponentChildren }) => (
+ <div className="header-stub">{actions}{below}</div>
+ )
+}));
+
+import type { ContentManagerSectionProps } from "../index";
+import SpaceUsage from "./index";
+
+// Only the switcher matters to this section; the note-context plumbing of TypeWidgetProps is the
+// shell's business and stays unused here.
+const SECTION_PROPS = {
+ sectionSwitcher: <span className="switcher-stub" />
+} as unknown as ContentManagerSectionProps;
+
+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 },
+ total: { size: 3500, revisionsSize: 0, noteCount: 12 }
+};
+
+let container: HTMLDivElement | undefined;
+
+function renderSection() {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<SpaceUsage {...SECTION_PROPS} />, container);
+ return container;
+}
+
+function flushRender() {
+ return new Promise((resolve) => setTimeout(resolve));
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ mocks.overview = undefined;
+});
+
+describe("SpaceUsage section", () => {
+ it("shows the loading state without a status line until the overview arrives", () => {
+ mocks.overview = undefined;
+ const probe = renderSection();
+
+ expect(probe.querySelector(".space-usage-loading")).not.toBeNull();
+ expect(probe.querySelector(".space-usage-status")).toBeNull();
+ expect(probe.querySelector(".switcher-stub")).not.toBeNull();
+ });
+
+ it("renders the overview with the two-part status line", () => {
+ mocks.overview = OVERVIEW;
+ const probe = renderSection();
+
+ expect(probe.querySelector(".overview-stub")).not.toBeNull();
+ expect(probe.querySelector(".browse-stub")).toBeNull();
+
+ // Symmetric against the same t() call: meaningful with translations loaded, and still a
+ // faithful comparison when the test i18n is uninitialized (t yields undefined → empty span).
+ const [ contentSpan, , deletedSpan ] = [ ...probe.querySelectorAll(".space-usage-status span") ];
+ expect(contentSpan.textContent?.trim()).toBe(t("space_usage.status_content", {
+ count: 12,
+ size: formatSize(4000),
+ revisionsSize: formatSize(200),
+ attachmentsSize: formatSize(300)
+ }) ?? "");
+ expect(deletedSpan.textContent?.trim()).toBe(t("space_usage.status_deleted", {
+ count: 3,
+ size: formatSize(900)
+ }) ?? "");
+ });
+
+ it("switches to Browse and back, keeping the status line up", async () => {
+ mocks.overview = OVERVIEW;
+ const probe = renderSection();
+
+ // Labels depend on the (uninitialized) test i18n; the inactive button is the other view.
+ const inactiveViewButton = () =>
+ [ ...probe.querySelectorAll<HTMLButtonElement>(".header-stub button") ]
+ .find((button) => !button.classList.contains("active"));
+
+ inactiveViewButton()?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await flushRender();
+ expect(probe.querySelector(".browse-stub")).not.toBeNull();
+ expect(probe.querySelector(".overview-stub")).toBeNull();
+ expect(probe.querySelector(".space-usage-status")).not.toBeNull();
+
+ inactiveViewButton()?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await flushRender();
+ expect(probe.querySelector(".overview-stub")).not.toBeNull();
+ expect(probe.querySelector(".browse-stub")).toBeNull();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.spec.tsx
new file mode 100644
index 0000000000..9341f9253f
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.spec.tsx
@@ -0,0 +1,118 @@
+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { t } from "../../../../../services/i18n";
+import { formatSize } from "../../../../../services/utils";
+
+const mocks = vi.hoisted(() => ({
+ openContextWithNote: vi.fn()
+}));
+
+vi.mock("../../../../../components/app_context", () => ({
+ default: {
+ tabManager: {
+ openContextWithNote: mocks.openContextWithNote,
+ getActiveContext: () => ({ hoistedNoteId: "hoistedNote" })
+ }
+ }
+}));
+
+// The real i18n is not initialized under test, so `Trans` would render the bare key and drop the
+// interpolated value; the stub renders exactly what the component wires in.
+vi.mock("react-i18next", () => ({
+ Trans: ({ i18nKey, components }: { i18nKey: string, components: { Size: preact.VNode } }) => (
+ <span data-i18n-key={i18nKey}>{components.Size}</span>
+ )
+}));
+
+import NoteUsageDonut, { segmentTooltip } from "./note_usage_donut";
+
+const USAGE: SpaceUsageNoteResponse = {
+ noteId: "n1",
+ ownSize: 10000,
+ attachmentsSize: 5010,
+ revisionsSize: 3000,
+ noteContentSize: 150,
+ subtreeContentSize: 700,
+ attachments: [
+ { attachmentId: "a1", title: "Attachment one", role: "file", size: 5000 },
+ // Below 2% of the ring: consolidates into the "others" segment.
+ { attachmentId: "tiny", title: "Tiny attachment", role: "file", size: 10 }
+ ],
+ children: []
+};
+
+let container: HTMLDivElement | undefined;
+
+function renderDonut() {
+ container = document.body.appendChild(document.createElement("div"));
+ render(
+ <NoteUsageDonut
+ usage={USAGE}
+ title="My note"
+ notePath={[ "root", "n1" ]}
+ centerActions={<button className="extra-action" />}
+ />,
+ container
+ );
+ return container;
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ mocks.openContextWithNote.mockClear();
+});
+
+describe("NoteUsageDonut", () => {
+ it("renders the composition ring with the semantic segment classes", () => {
+ const probe = renderDonut();
+
+ expect(probe.querySelector("circle.space-usage-segment-body")).not.toBeNull();
+ expect(probe.querySelector("circle.space-usage-segment-attachment")).not.toBeNull();
+ expect(probe.querySelector("circle.space-usage-segment-revisions")).not.toBeNull();
+ // The sub-2% attachment consolidated into the counted bucket.
+ expect(probe.querySelector("circle.space-usage-segment-others")).not.toBeNull();
+ });
+
+ it("links the center title to the note and opens it in a new tab instead of navigating", () => {
+ const probe = renderDonut();
+ const title = probe.querySelector<HTMLAnchorElement>(".note-usage-donut-title");
+
+ expect(title?.textContent).toBe("My note");
+ expect(title?.getAttribute("href")).toBe("#root/n1");
+
+ const click = new MouseEvent("click", { bubbles: true, cancelable: true });
+ title?.dispatchEvent(click);
+
+ expect(click.defaultPrevented).toBe(true);
+ expect(mocks.openContextWithNote).toHaveBeenCalledWith("n1", {
+ activate: true,
+ hoistedNoteId: "hoistedNote"
+ });
+ });
+
+ it("shows the deduplicated note and subtree sizes, with the actions above the title", () => {
+ const probe = renderDonut();
+ const center = probe.querySelector<HTMLElement>(".donut-chart-center");
+ const values = [ ...probe.querySelectorAll(".note-usage-donut-size-value") ].map((el) => el.textContent);
+
+ expect(values).toEqual([ formatSize(150), formatSize(700) ]);
+ expect(center?.firstElementChild?.classList.contains("extra-action")).toBe(true);
+ });
+});
+
+describe("segmentTooltip", () => {
+ it("routes each kind to its own wording", () => {
+ expect(segmentTooltip("plain", "Body", 10))
+ .toBe(t("space_usage.segment_tooltip", { title: "Body", size: formatSize(10) }));
+ expect(segmentTooltip("attachment", "img.png", 20))
+ .toBe(t("space_usage.attachment_tooltip", { title: "img.png", size: formatSize(20) }));
+ expect(segmentTooltip("child", "Projects", 30))
+ .toBe(t("space_usage.child_tooltip", { title: "Projects", size: formatSize(30) }));
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx
new file mode 100644
index 0000000000..26ad9ab824
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx
@@ -0,0 +1,76 @@
+import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ openContextWithNote: vi.fn()
+}));
+
+vi.mock("../../../../../components/app_context", () => ({
+ default: {
+ tabManager: {
+ openContextWithNote: mocks.openContextWithNote,
+ getActiveContext: () => null
+ }
+ }
+}));
+
+// The treemap container never gets a real layout under happy-dom.
+vi.mock("../../../../react/hooks", () => ({
+ useElementSize: () => ({ width: 400, height: 300 })
+}));
+
+import Overview from "./overview";
+
+const OVERVIEW: SpaceUsageOverviewResponse = {
+ content: { size: 400, noteCount: 3, attachmentsSize: 0, revisionsSize: 0 },
+ notes: [ { noteId: "n1", notePath: [ "n1" ], ownSize: 200, attachmentsSize: 0, revisionsSize: 0 } ],
+ otherNotes: { size: 50, revisionsSize: 0, noteCount: 2 },
+ hiddenNotes: { size: 80, revisionsSize: 0, noteCount: 10 },
+ deletedNotes: { size: 70, noteCount: 1 },
+ total: { size: 250, revisionsSize: 0, noteCount: 3 }
+};
+
+let container: HTMLDivElement | undefined;
+
+function renderOverview() {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<Overview overview={OVERVIEW} />, container);
+ return container;
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ mocks.openContextWithNote.mockClear();
+});
+
+describe("Overview", () => {
+ it("renders a cell per note plus the three bucket cells", () => {
+ const probe = renderOverview();
+
+ expect(probe.querySelector('[data-href="#root/n1"]')).not.toBeNull();
+ expect(probe.querySelector(".treemap-cell-other")).not.toBeNull();
+ expect(probe.querySelector(".treemap-cell-hidden")).not.toBeNull();
+ expect(probe.querySelector(".treemap-cell-deleted")).not.toBeNull();
+ });
+
+ it("opens a clicked note in a new tab, while the bucket cells stay inert", () => {
+ const probe = renderOverview();
+
+ probe.querySelector('[data-href="#root/n1"]')
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(mocks.openContextWithNote).toHaveBeenCalledWith("n1", {
+ activate: true,
+ hoistedNoteId: null
+ });
+
+ mocks.openContextWithNote.mockClear();
+ probe.querySelector(".treemap-cell-deleted")
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(mocks.openContextWithNote).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/trilium-core/src/routes/api/space_usage.spec.ts b/packages/trilium-core/src/routes/api/space_usage.spec.ts
index f70ea27e1c..1b5137fef3 100644
--- a/packages/trilium-core/src/routes/api/space_usage.spec.ts
+++ b/packages/trilium-core/src/routes/api/space_usage.spec.ts
@@ -204,6 +204,22 @@ describe("Space usage API (core)", () => {
expect(rootUsage.deletedNotes?.size).toBeGreaterThanOrEqual(doomedSize);
});
+ it("defaults and clamps the overview limit", async () => {
+ // No limit → the server default applies and the request just works.
+ const defaulted = await getOverview();
+ expect(defaulted.notes.length).toBeGreaterThan(0);
+
+ // Below the floor → clamped up to a single note, not zero.
+ const floored = await getOverview({ limit: 0 });
+ expect(floored.notes.length).toBe(1);
+
+ // Absurdly high and non-numeric values are tolerated too.
+ const ceiled = await getOverview({ limit: 999999 });
+ expect(ceiled.notes.length).toBeGreaterThan(0);
+ const garbage = await getOverview({ limit: "abc" });
+ expect(garbage.notes.length).toBeGreaterThan(0);
+ });
+
it("404s for a missing note", async () => {
const res = await api.get("/api/space-usage/note/spaceUsageMissing");
expect(res.status).toBe(404);
diff --git a/packages/trilium-core/src/services/space_usage.spec.ts b/packages/trilium-core/src/services/space_usage.spec.ts
index 799a7c6b5c..4336a2245f 100644
--- a/packages/trilium-core/src/services/space_usage.spec.ts
+++ b/packages/trilium-core/src/services/space_usage.spec.ts
@@ -49,6 +49,14 @@ describe("buildCanonicalForest", () => {
expect(forest.childrenByNoteId.get("a")).toBeUndefined();
});
+ it("handles a root whose only child is the hidden subtree", () => {
+ const forest = forestOf({ root: [ "_hidden" ], _hidden: [ "h1" ] });
+
+ expect(forest.userNoteIds).toEqual([ "root" ]);
+ expect(forest.hiddenNoteIds).toEqual([ "_hidden", "h1" ]);
+ expect(forest.childrenByNoteId.get("root")).toEqual([ "_hidden" ]);
+ });
+
it("walks the hidden subtree last, so a note cloned into both worlds stays a user note", () => {
// `bm` models a bookmark: a user note cloned under the hidden bookmarks folder.
const forest = forestOf({
diff --git a/packages/trilium-core/src/services/space_usage.ts b/packages/trilium-core/src/services/space_usage.ts
index 9ce47a74b8..b967db3af5 100644
--- a/packages/trilium-core/src/services/space_usage.ts
+++ b/packages/trilium-core/src/services/space_usage.ts
@@ -78,6 +78,8 @@ export function getNoteUsage(noteId: string): SpaceUsageNoteResponse {
return {
noteId: childId,
+ /* v8 ignore next 3 -- the totals cover every note of the forest, so the fallbacks
+ would only fire on an internally inconsistent forest */
subtreeSize: total?.size ?? 0,
subtreeRevisionsSize: total?.revisionsSize ?? 0,
subtreeNoteCount: total?.noteCount ?? 0
@@ -93,6 +95,8 @@ export function getNoteUsage(noteId: string): SpaceUsageNoteResponse {
[ noteId ]
);
const attachments = note.getAttachments().flatMap((attachment) => {
+ /* v8 ignore next 3 -- a becca-loaded attachment always carries its row ID; the type merely
+ allows unsaved ones */
if (!attachment.attachmentId) {
return [];
}
@@ -455,11 +459,13 @@ function buildForestFromBecca(): CanonicalForest {
return buildCanonicalForest(
(noteId) => {
const note = becca.notes[noteId];
+ /* v8 ignore next 3 -- only visited IDs are queried, and those come from becca itself */
if (!note) {
return [];
}
return note.getChildBranches()
+ /* v8 ignore next -- getChildBranches' nulls only appear on a corrupted cache */
.flatMap((branch) => branch ? [ branch ] : [])
// Sorted here rather than trusting cache order, so the canonical choice between
// equally deep clones is the same on every instance of a sync cluster.