Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager: add a per-note space analysis view

Adorian Doran003f47d2b170
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 6c93c16fd4..90c3ddb5c1 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2665,8 +2665,19 @@
},
"space_usage": {
"loading": "Measuring space usage...",
+ "view_overview": "Overview",
+ "view_browse": "Browse",
"other_notes": "Other notes",
"deleted_notes": "Deleted notes",
+ "note_body": "Note content",
+ "revisions": "Revisions",
+ "others": "Others",
+ "segment_tooltip": "{{- title}} ({{size}})",
+ "attachment_tooltip": "Attachment: {{- title}} ({{size}})",
+ "child_tooltip": "Child note: {{- title}} ({{size}})",
+ "center_note_size": "Note: {{size}}",
+ "center_subtree_size": "Subtree: {{size}}",
+ "back": "Back",
"status_total": "Total: {{size}}",
"status_deleted": "Deleted notes: {{size}}"
},
diff --git a/apps/client/src/widgets/react/charts/DonutChart.css b/apps/client/src/widgets/react/charts/DonutChart.css
new file mode 100644
index 0000000000..4f431ef2e9
--- /dev/null
+++ b/apps/client/src/widgets/react/charts/DonutChart.css
@@ -0,0 +1,80 @@
+.donut-chart {
+ display: flex;
+ position: relative;
+ margin: auto;
+ height: 100%;
+ aspect-ratio: 1 / 1;
+ max-width: 100%;
+
+ svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ /* Colored through a variable, not a competing rule: consumers set `--donut-segment-color` and
+ never race this stylesheet's cascade position. */
+ .donut-segment {
+ stroke: var(--donut-segment-color, var(--accented-background-color));
+ /* Dash geometry is the segment's shape, so transitions carry re-layouts and the keyframe
+ sweeps a freshly mounted segment in from zero length. */
+ transition: stroke-dasharray 0.45s ease, stroke-dashoffset 0.45s ease;
+ animation: donut-sweep 0.45s ease;
+ }
+
+ /* The same tint recipe as the treemap cells, so the two charts speak one color language. */
+ .donut-segment.donut-colored {
+ --donut-segment-color: color-mix(
+ in srgb,
+ var(--accented-background-color) 55%,
+ hsl(var(--donut-hue) 65% 55%) 45%
+ );
+ }
+
+ .donut-segment:hover {
+ filter: brightness(1.12);
+ }
+
+ .donut-clickable {
+ cursor: pointer;
+ }
+
+ .donut-chart-center {
+ display: flex;
+ position: absolute;
+ inset: 0;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ /* The hole is inside the rings' hit area; only the actual content should catch the pointer. */
+ pointer-events: none;
+ }
+
+ .donut-chart-center > * {
+ pointer-events: auto;
+ }
+
+ /* The cursor-following tooltip. It must never catch the pointer, or it would flicker by
+ stealing the hover it reports. */
+ .donut-chart-tooltip {
+ position: absolute;
+ pointer-events: none;
+ transform: translate(14px, 14px);
+ }
+
+ .donut-chart-tooltip-flipped {
+ transform: translate(calc(-100% - 14px), 14px);
+ }
+
+ .donut-chart-tooltip .tooltip-inner {
+ white-space: nowrap;
+ max-width: none;
+ }
+}
+
+@keyframes donut-sweep {
+ from {
+ stroke-dasharray: 0 var(--donut-circumference);
+ }
+}
diff --git a/apps/client/src/widgets/react/charts/DonutChart.spec.ts b/apps/client/src/widgets/react/charts/DonutChart.spec.ts
new file mode 100644
index 0000000000..626269d1e4
--- /dev/null
+++ b/apps/client/src/widgets/react/charts/DonutChart.spec.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from "vitest";
+
+import { computeDonutLayout } from "./DonutChart";
+
+describe("computeDonutLayout", () => {
+ it("distributes values proportionally, in order, shaving the gap off both ends", () => {
+ const [ first, second ] = computeDonutLayout([ 75, 25 ], 100, 4);
+
+ expect(first).toEqual({ length: 71, offset: 2 });
+ expect(second).toEqual({ length: 21, offset: 77 });
+ });
+
+ it("keeps a lone segment a closed circle", () => {
+ expect(computeDonutLayout([ 42 ], 100, 4)).toEqual([ { length: 100, offset: 0 } ]);
+ });
+
+ it("keeps slivers at their full span instead of vanishing into the gap", () => {
+ const layout = computeDonutLayout([ 995, 5 ], 1000, 4);
+
+ // 5 units ≤ twice the gap: drawn whole, no shaving.
+ expect(layout[1]).toEqual({ length: 5, offset: 995 });
+ });
+
+ it("paints nothing for empty or negative values while spacing the rest correctly", () => {
+ const layout = computeDonutLayout([ 50, 0, -3, 50 ], 100, 4);
+
+ expect(layout[1]).toBeNull();
+ expect(layout[2]).toBeNull();
+ expect(layout[0]).toEqual({ length: 46, offset: 2 });
+ expect(layout[3]).toEqual({ length: 46, offset: 52 });
+ });
+
+ it("returns only nulls when there is nothing to paint", () => {
+ expect(computeDonutLayout([ 0, 0 ], 100, 4)).toEqual([ null, null ]);
+ expect(computeDonutLayout([], 100, 4)).toEqual([]);
+ });
+});
diff --git a/apps/client/src/widgets/react/charts/DonutChart.tsx b/apps/client/src/widgets/react/charts/DonutChart.tsx
new file mode 100644
index 0000000000..864dfbb8ec
--- /dev/null
+++ b/apps/client/src/widgets/react/charts/DonutChart.tsx
@@ -0,0 +1,201 @@
+import "./DonutChart.css";
+
+import clsx from "clsx";
+import type { ComponentChildren } from "preact";
+import { useRef, useState } from "preact/hooks";
+
+export interface DonutSegment<T = unknown> {
+ /** Stable identity for reconciliation; unique within the ring. */
+ id: string;
+ value: number;
+ /** Tooltip text, shown in the chart's own cursor-following tooltip while the segment is hovered. */
+ tooltip?: string;
+ /**
+ * Categorical tint (0–359), mixed into the theme surface exactly like the treemap cells.
+ * Absent = the plain surface color, unless a {@link className} paints its own.
+ */
+ hue?: number;
+ /** Extra class on the segment, e.g. to give it a semantic color. */
+ className?: string;
+ /** The consumer's payload, handed back on click. */
+ data?: T;
+}
+
+export interface DonutRing<T = unknown> {
+ /** Stable identity for reconciliation; unique within the chart. */
+ id: string;
+ /** Distance from the center to the middle of the band, in viewBox units (see {@link DONUT_VIEW_SIZE}). */
+ radius: number;
+ thickness: number;
+ segments: DonutSegment<T>[];
+ onSegmentClick?: (segment: DonutSegment<T>) => void;
+}
+
+interface DonutChartProps<T> {
+ rings: DonutRing<T>[];
+ className?: string;
+ /** Rendered centered in the hole, above the rings. */
+ children?: ComponentChildren;
+}
+
+/** The square viewBox rings are laid out in; radii and thicknesses are expressed in these units. */
+export const DONUT_VIEW_SIZE = 420;
+
+const SEGMENT_GAP = 3;
+
+interface HoverState {
+ text: string;
+ x: number;
+ y: number;
+ /** Near the right edge the tooltip sits to the cursor's left instead of running off the chart. */
+ flipped: boolean;
+}
+
+/**
+ * One or more concentric donut rings, drawn as circle strokes: each segment is a `stroke-dasharray`
+ * arc, which is what makes navigation animate — dash geometry is plain CSS, so segments sweep in on
+ * mount and transition on change, with no path morphing. The chart stretches to its container's
+ * height and keeps a square aspect where the width allows; center content overlays the hole as
+ * regular HTML.
+ *
+ * Segment tooltips are the chart's own cursor-following bubble (Trilium-styled via `tooltip-inner`)
+ * rather than anything anchored to the element: a dashed circle's bounding box is the whole ring,
+ * so an anchored tooltip would hover far from the segment it describes.
+ */
+export default function DonutChart<T>({ rings, className, children }: DonutChartProps<T>) {
+ const half = DONUT_VIEW_SIZE / 2;
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [ hover, setHover ] = useState<HoverState | null>(null);
+
+ const positionOf = (event: { clientX: number, clientY: number }) => {
+ const rect = containerRef.current?.getBoundingClientRect();
+
+ if (!rect) {
+ return { x: 0, y: 0, flipped: false };
+ }
+
+ const x = event.clientX - rect.left;
+ return { x, y: event.clientY - rect.top, flipped: x > rect.width / 2 };
+ };
+
+ return (
+ <div
+ ref={containerRef}
+ className={clsx("donut-chart", className)}
+ onPointerMove={(event) => setHover((current) => current && { ...current, ...positionOf(event) })}
+ onPointerLeave={() => setHover(null)}
+ >
+ <svg viewBox={`${-half} ${-half} ${DONUT_VIEW_SIZE} ${DONUT_VIEW_SIZE}`}>
+ {/* Rotated so every ring starts at 12 o'clock. */}
+ <g transform="rotate(-90)">
+ {rings.map((ring) => (
+ <Ring
+ key={ring.id}
+ ring={ring}
+ onSegmentHover={(segment, event) => setHover(segment?.tooltip && event
+ ? { text: segment.tooltip, ...positionOf(event) }
+ : null)}
+ />
+ ))}
+ </g>
+ </svg>
+ {children && <div className="donut-chart-center">{children}</div>}
+ {hover && (
+ // The `tooltip show` classes matter: the themes set the tooltip colors on `.tooltip`
+ // and scope the text color to `.tooltip .tooltip-inner` — a bare inner keeps the
+ // theme's background but inherits the page's text color.
+ <div
+ className={clsx("tooltip", "show", "donut-chart-tooltip", hover.flipped && "donut-chart-tooltip-flipped")}
+ style={{ left: hover.x, top: hover.y }}
+ >
+ <div className="tooltip-inner">{hover.text}</div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+function Ring<T>({ ring, onSegmentHover }: {
+ ring: DonutRing<T>,
+ onSegmentHover: (segment: DonutSegment<T> | null, event?: { clientX: number, clientY: number }) => void
+}) {
+ const circumference = 2 * Math.PI * ring.radius;
+ const layout = computeDonutLayout(ring.segments.map((segment) => segment.value), circumference, SEGMENT_GAP);
+
+ return (
+ <g>
+ {ring.segments.map((segment, index) => {
+ const arc = layout[index];
+
+ if (!arc) {
+ return null;
+ }
+
+ return (
+ <circle
+ key={segment.id}
+ className={clsx(
+ "donut-segment",
+ segment.hue !== undefined && "donut-colored",
+ ring.onSegmentClick && "donut-clickable",
+ segment.className
+ )}
+ r={ring.radius}
+ fill="none"
+ onClick={ring.onSegmentClick && (() => ring.onSegmentClick?.(segment))}
+ onPointerEnter={(event) => onSegmentHover(segment, event)}
+ onPointerLeave={() => onSegmentHover(null)}
+ // Arc geometry is data-driven; as inline *style* (not attributes) it stays
+ // animatable by the stylesheet's transition and sweep keyframes.
+ style={{
+ strokeWidth: ring.thickness,
+ strokeDasharray: `${arc.length} ${Math.max(circumference - arc.length, 0)}`,
+ strokeDashoffset: -arc.offset,
+ "--donut-circumference": `${circumference}px`,
+ ...(segment.hue !== undefined && { "--donut-hue": String(segment.hue) })
+ }}
+ />
+ );
+ })}
+ </g>
+ );
+}
+
+export interface DonutArc {
+ /** Arc length along the circumference. */
+ length: number;
+ /** Distance from the ring's start to the arc's start. */
+ offset: number;
+}
+
+/**
+ * Distributes values proportionally along a ring's circumference, `null` where a value paints
+ * nothing. The gap is shaved off a segment only where it fits: slivers keep their full span so
+ * they don't vanish, and a lone segment stays a closed circle.
+ */
+export function computeDonutLayout(values: number[], circumference: number, gap: number): (DonutArc | null)[] {
+ const total = values.reduce((sum, value) => sum + Math.max(value, 0), 0);
+
+ if (total <= 0) {
+ return values.map(() => null);
+ }
+
+ const visibleCount = values.filter((value) => value > 0).length;
+ let position = 0;
+
+ return values.map((value) => {
+ if (value <= 0) {
+ return null;
+ }
+
+ const span = (value / total) * circumference;
+ const start = position;
+ position += span;
+
+ if (visibleCount > 1 && span > gap * 2) {
+ return { length: span - gap, offset: start + gap / 2 };
+ }
+
+ return { length: span, offset: start };
+ });
+}
diff --git a/apps/client/src/widgets/react/charts/Treemap.css b/apps/client/src/widgets/react/charts/Treemap.css
index 4839243efa..2c6e2760e7 100644
--- a/apps/client/src/widgets/react/charts/Treemap.css
+++ b/apps/client/src/widgets/react/charts/Treemap.css
@@ -4,17 +4,19 @@
height: 100%;
overflow: hidden;
+ /* Painted through a variable, not a competing rule: consumers set `--treemap-cell-background`
+ and never race this stylesheet's cascade position. */
.treemap-cell {
position: absolute;
border-radius: 4px;
- background: var(--accented-background-color);
+ background: var(--treemap-cell-background, var(--accented-background-color));
cursor: pointer;
}
/* The group tint stays a mix into the theme's own surface, so the map keeps a coherent look
under light and dark themes alike. */
.treemap-cell.treemap-colored {
- background: color-mix(
+ --treemap-cell-background: color-mix(
in srgb,
var(--accented-background-color) 55%,
hsl(var(--treemap-hue) 65% 55%) 45%
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.css
new file mode 100644
index 0000000000..50cdf7d75c
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.css
@@ -0,0 +1,61 @@
+.space-usage-browse {
+ display: flex;
+ flex: 1 1 auto;
+ flex-direction: column;
+ min-height: 0;
+
+ .space-usage-breadcrumb {
+ display: flex;
+ flex: 0 0 auto;
+ align-items: center;
+ gap: 0.35em;
+ padding-block: 6px;
+ overflow: hidden;
+ white-space: nowrap;
+ }
+
+ .space-usage-crumb {
+ display: inline-block;
+ overflow: hidden;
+ max-width: 14em;
+ border: none;
+ background: none;
+ padding: 0;
+ color: var(--main-text-color);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+
+ .space-usage-crumb:hover {
+ text-decoration: underline;
+ }
+
+ .space-usage-crumb-current {
+ font-weight: 600;
+ cursor: default;
+ }
+
+ .space-usage-crumb-current:hover {
+ text-decoration: none;
+ }
+
+ .space-usage-crumb-separator {
+ flex-shrink: 0;
+ opacity: 0.6;
+ }
+
+ .space-usage-browse-chart {
+ display: flex;
+ flex: 1 1 auto;
+ min-height: 0;
+ padding-block: 8px;
+ }
+
+ /* Not a note: nothing to navigate into, painted like the revisions it will one day free.
+ Repeats .donut-segment to outrank the primitive's clickable-cursor rule. */
+ .donut-segment.space-usage-segment-deleted {
+ --donut-segment-color: var(--space-usage-revisions-color);
+ cursor: default;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx
new file mode 100644
index 0000000000..4bd136f033
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx
@@ -0,0 +1,114 @@
+import "./browse.css";
+
+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+import { Fragment } from "preact";
+import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
+
+import froca from "../../../../../services/froca";
+import { t } from "../../../../../services/i18n";
+import ActionButton from "../../../../react/ActionButton";
+import type { DonutRing } from "../../../../react/charts/DonutChart";
+import { buildChildrenSegments, type UsageSegmentData } from "./donut_segments";
+import NoteUsageDonut, { segmentTooltip } from "./note_usage_donut";
+import { useSpaceUsageFetch } from "./use_space_usage_fetch";
+
+const CHILDREN_RING_RADIUS = 180;
+const CHILDREN_RING_THICKNESS = 46;
+
+/**
+ * The Browse view: the composition donut of the current note wrapped by its children ring, entered
+ * from the root and navigated by clicking children. The breadcrumb mirrors the descent and jumps
+ * anywhere back up; the back button pops one level.
+ */
+export default function Browse() {
+ const [ stack, setStack ] = useState([ "root" ]);
+ const noteId = stack[stack.length - 1];
+ const usage = useSpaceUsageFetch<SpaceUsageNoteResponse>(`space-usage/note/${noteId}`);
+ const titles = useNoteTitles(stack, usage);
+ const getTitle = useCallback((id: string) => titles.get(id) ?? id, [ titles ]);
+
+ const childrenRing: DonutRing<UsageSegmentData> = useMemo(() => ({
+ id: "children",
+ radius: CHILDREN_RING_RADIUS,
+ thickness: CHILDREN_RING_THICKNESS,
+ segments: usage ? buildChildrenSegments(usage, {
+ getTitle,
+ deletedNotesLabel: t("space_usage.deleted_notes"),
+ othersLabel: t("space_usage.others"),
+ makeTooltip: segmentTooltip
+ }) : [],
+ onSegmentClick: (segment) => {
+ const childId = segment.data?.noteId;
+
+ if (childId) {
+ setStack((current) => [ ...current, childId ]);
+ }
+ }
+ }), [ usage, getTitle ]);
+
+ return (
+ <div className="space-usage-browse">
+ <nav className="space-usage-breadcrumb">
+ <ActionButton
+ icon="bx bx-arrow-back"
+ text={t("space_usage.back")}
+ disabled={stack.length === 1}
+ onClick={() => setStack((current) => current.length > 1 ? current.slice(0, -1) : current)}
+ />
+ {stack.map((id, index) => (
+ <Fragment key={`${index}/${id}`}>
+ {index > 0 && <span className="space-usage-crumb-separator" aria-hidden="true">›</span>}
+ {index < stack.length - 1 ? (
+ <button
+ type="button"
+ className="space-usage-crumb"
+ onClick={() => setStack((current) => current.slice(0, index + 1))}
+ >{getTitle(id)}</button>
+ ) : (
+ <span className="space-usage-crumb space-usage-crumb-current">{getTitle(id)}</span>
+ )}
+ </Fragment>
+ ))}
+ </nav>
+
+ {usage ? (
+ <div className="space-usage-browse-chart">
+ <NoteUsageDonut
+ usage={usage}
+ title={getTitle(usage.noteId)}
+ notePath={stack}
+ outerRings={[ childrenRing ]}
+ />
+ </div>
+ ) : (
+ <p className="space-usage-loading">{t("space_usage.loading")}</p>
+ )}
+ </div>
+ );
+}
+
+/**
+ * Batch-loads the titles the view needs — the breadcrumb's path and the children ring's tooltips.
+ * Until (or unless) a title arrives, the ID stands in.
+ */
+function useNoteTitles(stack: string[], usage: SpaceUsageNoteResponse | null) {
+ const [ titles, setTitles ] = useState(new Map<string, string>());
+
+ useEffect(() => {
+ const noteIds = [ ...stack, ...(usage?.children.map((child) => child.noteId) ?? []) ];
+ let cancelled = false;
+
+ // Silent: a note deleted since the usage was computed must not fail the whole view.
+ void froca.getNotes(noteIds, true).then((notes) => {
+ if (!cancelled) {
+ setTitles(new Map(notes.map((note) => [ note.noteId, note.title ])));
+ }
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [ stack, usage ]);
+
+ return titles;
+}
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
new file mode 100644
index 0000000000..4ac0a1d741
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.spec.ts
@@ -0,0 +1,129 @@
+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+import { describe, expect, it } from "vitest";
+
+import { buildChildrenSegments, buildCompositionSegments, type UsageTooltipKind } from "./donut_segments";
+import { hueOf } from "./overview_model";
+
+function usage(overrides: Partial<SpaceUsageNoteResponse> = {}): SpaceUsageNoteResponse {
+ return {
+ noteId: "note",
+ ownSize: 0,
+ attachmentsSize: 0,
+ revisionsSize: 0,
+ attachments: [],
+ children: [],
+ ...overrides
+ };
+}
+
+function child(noteId: string, subtreeSize: number) {
+ return { noteId, subtreeSize, subtreeRevisionsSize: 0, subtreeNoteCount: 1 };
+}
+
+const makeTooltip = (kind: UsageTooltipKind, title: string, size: number) => `${kind}:${title}/${size}`;
+
+describe("buildCompositionSegments", () => {
+ const options = { bodyLabel: "Body", revisionsLabel: "Revisions", othersLabel: "Others", makeTooltip };
+
+ it("orders body, attachments largest-first, then revisions, with case-prefixed tooltips", () => {
+ const segments = buildCompositionSegments(usage({
+ noteId: "note",
+ ownSize: 100,
+ revisionsSize: 40,
+ attachments: [
+ { attachmentId: "small", title: "Small file", role: "file", size: 20 },
+ { attachmentId: "big", title: "Big image", role: "image", size: 50 }
+ ]
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "body", "attachment/big", "attachment/small", "revisions" ]);
+ expect(segments[0]).toMatchObject({
+ value: 100,
+ className: "space-usage-segment-body",
+ tooltip: "plain:Body/100",
+ data: { noteId: "note" }
+ });
+ expect(segments[1]).toMatchObject({ value: 50, tooltip: "attachment:Big image/50", data: { attachmentId: "big" } });
+ expect(segments[3]).toMatchObject({ value: 40, className: "space-usage-segment-revisions", tooltip: "plain:Revisions/40" });
+ });
+
+ it("consolidates segments below 2% of the ring into an inert Others", () => {
+ const segments = buildCompositionSegments(usage({
+ ownSize: 1000,
+ attachments: [
+ { attachmentId: "tiny1", title: "Tiny 1", role: "file", size: 10 },
+ { attachmentId: "tiny2", title: "Tiny 2", role: "file", size: 5 }
+ ]
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "body", "others" ]);
+ expect(segments[1]).toMatchObject({
+ value: 15,
+ className: "space-usage-segment-others",
+ tooltip: "plain:Others/15",
+ data: {}
+ });
+ });
+
+ it("drops empty components entirely", () => {
+ const segments = buildCompositionSegments(usage({
+ attachments: [ { attachmentId: "empty", title: "Empty", role: "file", size: 0 } ]
+ }), options);
+
+ expect(segments).toEqual([]);
+ });
+});
+
+describe("buildChildrenSegments", () => {
+ const options = {
+ getTitle: (noteId: string) => `title of ${noteId}`,
+ deletedNotesLabel: "Deleted notes",
+ othersLabel: "Others",
+ makeTooltip
+ };
+
+ it("weights children by subtree, largest first, each with its own stable hue", () => {
+ const segments = buildChildrenSegments(usage({
+ children: [ child("small", 10), child("big", 90), child("empty", 0) ]
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "child/big", "child/small" ]);
+ expect(segments[0]).toMatchObject({
+ value: 90,
+ hue: hueOf("big"),
+ tooltip: "child:title of big/90",
+ data: { noteId: "big" }
+ });
+ });
+
+ it("consolidates children below 0.5% of the ring into an inert Others", () => {
+ const segments = buildChildrenSegments(usage({
+ children: [ child("big", 10000), child("tiny1", 30), child("tiny2", 10) ]
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "child/big", "others" ]);
+ expect(segments[1]).toMatchObject({ value: 40, tooltip: "plain:Others/40", data: {} });
+ expect(segments[1].hue).toBeUndefined();
+ });
+
+ it("closes the root's ring with the deleted-notes segment, never folded into Others", () => {
+ const segments = buildChildrenSegments(usage({
+ // The deleted bucket is far below 0.5% of the ring, yet must stay its own segment.
+ children: [ child("big", 100000) ],
+ deletedNotes: { size: 25, noteCount: 3 }
+ }), options);
+
+ expect(segments.map((segment) => segment.id)).toEqual([ "child/big", "/deleted-notes" ]);
+ expect(segments[1]).toMatchObject({
+ value: 25,
+ className: "space-usage-segment-deleted",
+ tooltip: "plain:Deleted notes/25",
+ data: {}
+ });
+ });
+
+ it("omits the deleted-notes segment off the root or when nothing is deleted", () => {
+ expect(buildChildrenSegments(usage(), options)).toEqual([]);
+ expect(buildChildrenSegments(usage({ deletedNotes: { size: 0, noteCount: 0 } }), options)).toEqual([]);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.ts
new file mode 100644
index 0000000000..8448ef8214
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/donut_segments.ts
@@ -0,0 +1,154 @@
+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+
+import type { DonutSegment } from "../../../../react/charts/DonutChart";
+import { hueOf } from "./overview_model";
+
+/** What a donut segment stands for; the bucket segments ("others", "deleted") name neither. */
+export interface UsageSegmentData {
+ noteId?: string;
+ attachmentId?: string;
+}
+
+/** Which wording a segment's tooltip gets: a plain label, or one prefixed with its case. */
+export type UsageTooltipKind = "plain" | "attachment" | "child";
+
+type MakeTooltip = (kind: UsageTooltipKind, title: string, size: number) => string;
+
+/** Composition segments smaller than this share of the ring consolidate into "Others". */
+export const MIN_COMPOSITION_SEGMENT_FRACTION = 0.02;
+
+/** Child segments smaller than this share of the ring consolidate into "Others". */
+export const MIN_CHILD_SEGMENT_FRACTION = 0.005;
+
+interface CompositionOptions {
+ bodyLabel: string;
+ revisionsLabel: string;
+ othersLabel: string;
+ makeTooltip: MakeTooltip;
+}
+
+/**
+ * The composition ring of a single note: its body, each attachment on its own, and the revisions
+ * total — in that order, attachments largest-first. Empty components are dropped, and segments too
+ * small to see consolidate into a trailing "Others".
+ */
+export function buildCompositionSegments(
+ usage: SpaceUsageNoteResponse,
+ { bodyLabel, revisionsLabel, othersLabel, makeTooltip }: CompositionOptions
+): DonutSegment<UsageSegmentData>[] {
+ const segments: DonutSegment<UsageSegmentData>[] = [];
+
+ if (usage.ownSize > 0) {
+ segments.push({
+ id: "body",
+ value: usage.ownSize,
+ className: "space-usage-segment-body",
+ tooltip: makeTooltip("plain", bodyLabel, usage.ownSize),
+ data: { noteId: usage.noteId }
+ });
+ }
+
+ const attachments = [ ...usage.attachments ]
+ .filter((attachment) => attachment.size > 0)
+ .sort((a, b) => b.size - a.size || a.attachmentId.localeCompare(b.attachmentId));
+
+ for (const attachment of attachments) {
+ segments.push({
+ id: `attachment/${attachment.attachmentId}`,
+ value: attachment.size,
+ className: "space-usage-segment-attachment",
+ tooltip: makeTooltip("attachment", attachment.title, attachment.size),
+ data: { attachmentId: attachment.attachmentId }
+ });
+ }
+
+ if (usage.revisionsSize > 0) {
+ segments.push({
+ id: "revisions",
+ value: usage.revisionsSize,
+ className: "space-usage-segment-revisions",
+ tooltip: makeTooltip("plain", revisionsLabel, usage.revisionsSize)
+ });
+ }
+
+ return consolidateSmallSegments(segments, MIN_COMPOSITION_SEGMENT_FRACTION, othersLabel, makeTooltip);
+}
+
+interface ChildrenOptions {
+ getTitle: (noteId: string) => string;
+ deletedNotesLabel: string;
+ othersLabel: string;
+ makeTooltip: MakeTooltip;
+}
+
+/**
+ * The children ring: each child weighted by its whole subtree, largest first, tinted by its own
+ * "random" stable hue. Slivers consolidate into "Others"; on the root, the deleted-notes bucket
+ * closes the ring afterwards — deleted space is its own entry, never folded away.
+ */
+export function buildChildrenSegments(
+ usage: SpaceUsageNoteResponse,
+ { getTitle, deletedNotesLabel, othersLabel, makeTooltip }: ChildrenOptions
+): DonutSegment<UsageSegmentData>[] {
+ const children = [ ...usage.children ]
+ .filter((child) => child.subtreeSize > 0)
+ .sort((a, b) => b.subtreeSize - a.subtreeSize || a.noteId.localeCompare(b.noteId))
+ .map((child) => ({
+ id: `child/${child.noteId}`,
+ value: child.subtreeSize,
+ hue: hueOf(child.noteId),
+ tooltip: makeTooltip("child", getTitle(child.noteId), child.subtreeSize),
+ data: { noteId: child.noteId }
+ }));
+
+ const segments = consolidateSmallSegments(children, MIN_CHILD_SEGMENT_FRACTION, othersLabel, makeTooltip);
+
+ if (usage.deletedNotes && usage.deletedNotes.size > 0) {
+ segments.push({
+ id: "/deleted-notes",
+ value: usage.deletedNotes.size,
+ className: "space-usage-segment-deleted",
+ tooltip: makeTooltip("plain", deletedNotesLabel, usage.deletedNotes.size),
+ data: {}
+ });
+ }
+
+ return segments;
+}
+
+/** Replaces the segments below the given share of the ring's total with one inert "Others". */
+function consolidateSmallSegments(
+ segments: DonutSegment<UsageSegmentData>[],
+ minFraction: number,
+ othersLabel: string,
+ makeTooltip: MakeTooltip
+): DonutSegment<UsageSegmentData>[] {
+ const total = segments.reduce((sum, segment) => sum + segment.value, 0);
+
+ if (total <= 0) {
+ return segments;
+ }
+
+ const kept: DonutSegment<UsageSegmentData>[] = [];
+ let othersSize = 0;
+
+ for (const segment of segments) {
+ if (segment.value / total >= minFraction) {
+ kept.push(segment);
+ } else {
+ othersSize += segment.value;
+ }
+ }
+
+ if (othersSize > 0) {
+ kept.push({
+ id: "others",
+ value: othersSize,
+ className: "space-usage-segment-others",
+ tooltip: makeTooltip("plain", othersLabel, othersSize),
+ data: {}
+ });
+ }
+
+ return kept;
+}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css
index af99987246..7e98ed04e7 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css
@@ -45,17 +45,19 @@
}
/* The bucket cells stand for no single note: identity comes from the border and texture rather
- than a hue (user themes make any fixed palette unreliable), and they respond to nothing. */
+ than a hue (user themes make any fixed palette unreliable), and they respond to nothing.
+ Repeats .treemap-cell to outrank the primitive's cursor rule. */
.space-usage-overview {
- .treemap-cell-other,
- .treemap-cell-deleted {
+ .treemap-cell.treemap-cell-other,
+ .treemap-cell.treemap-cell-deleted {
+ --treemap-cell-background: transparent;
+
border: 1px dashed var(--main-border-color);
- background: transparent;
cursor: default;
}
- .treemap-cell-deleted {
- background: repeating-linear-gradient(
+ .treemap-cell.treemap-cell-deleted {
+ --treemap-cell-background: repeating-linear-gradient(
-45deg,
var(--accented-background-color) 0 5px,
transparent 5px 10px
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx
index 8d404e1739..95f0bba55c 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx
@@ -1,73 +1,49 @@
import "./index.css";
import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
-import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import { useState } from "preact/hooks";
-import debounce from "../../../../../services/debounce";
import { t } from "../../../../../services/i18n";
-import server from "../../../../../services/server";
import { formatSize } from "../../../../../services/utils";
-import { useTriliumEvent } from "../../../../react/hooks";
+import SegmentedChoice from "../../../../react/SegmentedChoice";
import OptionsPageHeader from "../../components/OptionsPageHeader";
import type { ContentManagerSectionProps } from "../index";
+import Browse from "./browse";
import Overview from "./overview";
+import { useSpaceUsageFetch } from "./use_space_usage_fetch";
/** Matches the server default; the treemap could not label more cells anyway. */
const OVERVIEW_LIMIT = 500;
-/** One reload per burst — a subtree delete floods entity changes. */
-const REFRESH_DEBOUNCE_MS = 1000;
+type SpaceUsageView = "overview" | "browse";
export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionProps) {
- const overview = useOverview();
+ const [ view, setView ] = useState<SpaceUsageView>("overview");
+ // Fetched in both views: the treemap consumes it, and the status line is view-independent.
+ const overview = useSpaceUsageFetch<SpaceUsageOverviewResponse>(`space-usage/overview?limit=${OVERVIEW_LIMIT}`);
return (
<div className="space-usage-section">
- <OptionsPageHeader actions={sectionSwitcher} />
- {overview ? (
- <>
- <Overview overview={overview} />
- <footer className="space-usage-status">
- <span>{t("space_usage.status_total", { size: formatSize(overview.total.size) })}</span>
- <span>{t("space_usage.status_deleted", { size: formatSize(overview.deletedNotes.size) })}</span>
- </footer>
- </>
- ) : (
- <p className="space-usage-loading">{t("space_usage.loading")}</p>
+ <OptionsPageHeader actions={sectionSwitcher} below={
+ <SegmentedChoice options={VIEWS} currentValue={view} onChange={setView} />
+ } />
+
+ {view === "browse" && <Browse />}
+ {view === "overview" && (overview
+ ? <Overview overview={overview} />
+ : <p className="space-usage-loading">{t("space_usage.loading")}</p>)}
+
+ {overview && (
+ <footer className="space-usage-status">
+ <span>{t("space_usage.status_total", { size: formatSize(overview.total.size) })}</span>
+ <span>{t("space_usage.status_deleted", { size: formatSize(overview.deletedNotes.size) })}</span>
+ </footer>
)}
</div>
);
}
-/**
- * Fetches the overview and keeps it current: content changes anywhere — deletes, moves, uploads —
- * shift the sizes, so any note/branch/attachment change schedules one debounced reload. `null`
- * until the first response, so the loading state is distinguishable from an empty database.
- */
-function useOverview() {
- const [ overview, setOverview ] = useState<SpaceUsageOverviewResponse | null>(null);
- const latestRequest = useRef(0);
-
- const refresh = useCallback(async () => {
- const requestId = ++latestRequest.current;
- const response = await server.get<SpaceUsageOverviewResponse>(`space-usage/overview?limit=${OVERVIEW_LIMIT}`);
-
- // A stale response must not repaint over a newer one.
- if (requestId === latestRequest.current) {
- setOverview(response);
- }
- }, []);
-
- useEffect(() => { void refresh(); }, [ refresh ]);
-
- const delayedRefresh = useMemo(() => debounce(() => void refresh(), REFRESH_DEBOUNCE_MS), [ refresh ]);
- useEffect(() => () => delayedRefresh.clear(), [ delayedRefresh ]);
-
- useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
- if (loadResults.getNoteIds().length || loadResults.getBranchRows().length || loadResults.getAttachmentRows().length) {
- delayedRefresh();
- }
- });
-
- return overview;
-}
+const VIEWS: { value: SpaceUsageView, label: string }[] = [
+ { value: "overview", label: t("space_usage.view_overview") },
+ { value: "browse", label: t("space_usage.view_browse") }
+];
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.css
new file mode 100644
index 0000000000..a44dc4e199
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.css
@@ -0,0 +1,45 @@
+.note-usage-donut {
+ /* The semantic segment colors; themes can override the variables. Mixed into the theme surface
+ at a lower share than the children ring's tints (45%), so the composition ring reads
+ deliberately quieter than the ring around it. */
+ --space-usage-body-color: color-mix(in srgb, var(--accented-background-color) 70%, #5b8dd9 30%);
+ --space-usage-attachments-color: color-mix(in srgb, var(--accented-background-color) 70%, #d9a93d 30%);
+ --space-usage-revisions-color: color-mix(in srgb, var(--accented-background-color) 70%, #8f959c 30%);
+
+ .space-usage-segment-body {
+ --donut-segment-color: var(--space-usage-body-color);
+ }
+
+ .space-usage-segment-attachment {
+ --donut-segment-color: var(--space-usage-attachments-color);
+ }
+
+ .space-usage-segment-revisions {
+ --donut-segment-color: var(--space-usage-revisions-color);
+ }
+
+ /* Repeats .donut-segment to outrank the primitive's clickable-cursor rule. */
+ .donut-segment.space-usage-segment-others {
+ cursor: default;
+ }
+
+ /* Keeps the text inside the hole (inner ring inner edge ≈ 21% in from the box edge). */
+ .donut-chart-center {
+ padding: 23%;
+ gap: 2px;
+ }
+
+ .note-usage-donut-title {
+ overflow: hidden;
+ max-width: 100%;
+ color: var(--main-text-color);
+ font-size: 1.05rem;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ }
+
+ .note-usage-donut-size {
+ opacity: 0.7;
+ font-size: 0.85rem;
+ }
+}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsx
new file mode 100644
index 0000000000..f02fb0c924
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/note_usage_donut.tsx
@@ -0,0 +1,83 @@
+import "./note_usage_donut.css";
+
+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
+import clsx from "clsx";
+import { useMemo } from "preact/hooks";
+
+import appContext from "../../../../../components/app_context";
+import { t } from "../../../../../services/i18n";
+import { formatSize } from "../../../../../services/utils";
+import DonutChart, { type DonutRing } from "../../../../react/charts/DonutChart";
+import { buildCompositionSegments, type UsageSegmentData, type UsageTooltipKind } from "./donut_segments";
+
+export const COMPOSITION_RING_RADIUS = 133;
+/** Half the children ring's: the note's own breakdown reads as the quieter, supporting ring. */
+export const COMPOSITION_RING_THICKNESS = 23;
+
+interface NoteUsageDonutProps {
+ usage: SpaceUsageNoteResponse;
+ /** Shown in the hole; links to the note and carries its preview tooltip. */
+ title: string;
+ /** Note IDs from the root (inclusive) down to the note, for the center link and its tooltip. */
+ notePath: string[];
+ /** Extra rings drawn around the composition ring, e.g. Browse's children ring. */
+ outerRings?: DonutRing<UsageSegmentData>[];
+ className?: string;
+}
+
+/**
+ * The composition donut of a single note — body (blue), each attachment (yellow) and revisions
+ * (gray) as ring segments, the note's name and total size in the hole. The name is a live note
+ * link: it opens the note and carries the note preview tooltip. Reusable wherever one note's usage
+ * needs breaking down; Browse wraps it with its children ring via {@link outerRings}.
+ */
+export default function NoteUsageDonut({ usage, title, notePath, outerRings = [], className }: NoteUsageDonutProps) {
+ const compositionRing: DonutRing<UsageSegmentData> = useMemo(() => ({
+ id: "composition",
+ radius: COMPOSITION_RING_RADIUS,
+ thickness: COMPOSITION_RING_THICKNESS,
+ segments: buildCompositionSegments(usage, {
+ bodyLabel: t("space_usage.note_body"),
+ revisionsLabel: t("space_usage.revisions"),
+ othersLabel: t("space_usage.others"),
+ makeTooltip: segmentTooltip
+ })
+ }), [ usage ]);
+
+ const noteSize = usage.ownSize + usage.attachmentsSize + usage.revisionsSize;
+ const subtreeSize = noteSize + usage.children.reduce(
+ (sum, child) => sum + child.subtreeSize + child.subtreeRevisionsSize, 0);
+
+ return (
+ <DonutChart<UsageSegmentData>
+ rings={[ compositionRing, ...outerRings ]}
+ className={clsx("note-usage-donut", className)}
+ >
+ <a
+ className="note-usage-donut-title"
+ href={`#${notePath.join("/")}`}
+ onClick={(event) => {
+ // Handled here: default hash navigation would swap the settings page itself,
+ // and the dialog's link interception must not double-handle it.
+ event.preventDefault();
+ event.stopPropagation();
+ void appContext.tabManager.openContextWithNote(usage.noteId, {
+ activate: true,
+ hoistedNoteId: appContext.tabManager.getActiveContext()?.hoistedNoteId ?? null
+ });
+ }}
+ >{title}</a>
+ <span className="note-usage-donut-size">{t("space_usage.center_note_size", { size: formatSize(noteSize) })}</span>
+ <span className="note-usage-donut-size">{t("space_usage.center_subtree_size", { size: formatSize(subtreeSize) })}</span>
+ </DonutChart>
+ );
+}
+
+/** "Title (1.2 MiB)", prefixed with its case ("Attachment: ", "Child note: ") where one applies. */
+export function segmentTooltip(kind: UsageTooltipKind, title: string, size: number) {
+ const key = kind === "attachment" ? "space_usage.attachment_tooltip"
+ : kind === "child" ? "space_usage.child_tooltip"
+ : "space_usage.segment_tooltip";
+
+ return t(key, { title, size: formatSize(size) });
+}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts
new file mode 100644
index 0000000000..d0daf775d9
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts
@@ -0,0 +1,43 @@
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+
+import debounce from "../../../../../services/debounce";
+import server from "../../../../../services/server";
+import { useTriliumEvent } from "../../../../react/hooks";
+
+/** One reload per burst — a subtree delete floods entity changes. */
+const REFRESH_DEBOUNCE_MS = 1000;
+
+/**
+ * Fetches a space-usage endpoint and keeps it current: content changes anywhere — deletes, moves,
+ * uploads — shift the sizes, so any note/branch/attachment change schedules one debounced reload.
+ *
+ * `null` until the first response; on a URL change (Browse navigation) the previous payload stays
+ * up while the new one is in flight, so the charts transition instead of blanking.
+ */
+export function useSpaceUsageFetch<T>(url: string) {
+ const [ data, setData ] = useState<T | null>(null);
+ const latestRequest = useRef(0);
+
+ const refresh = useCallback(async () => {
+ const requestId = ++latestRequest.current;
+ const response = await server.get<T>(url);
+
+ // A stale response must not repaint over a newer one.
+ if (requestId === latestRequest.current) {
+ setData(response);
+ }
+ }, [ url ]);
+
+ useEffect(() => { void refresh(); }, [ refresh ]);
+
+ const delayedRefresh = useMemo(() => debounce(() => void refresh(), REFRESH_DEBOUNCE_MS), [ refresh ]);
+ useEffect(() => () => delayedRefresh.clear(), [ delayedRefresh ]);
+
+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {
+ if (loadResults.getNoteIds().length || loadResults.getBranchRows().length || loadResults.getAttachmentRows().length) {
+ delayedRefresh();
+ }
+ });
+
+ return data;
+}