Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager/space usage: add context menu support

Adorian Doran7a2bf0577414
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 00ee34fb7d..cb2b91338d 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2694,7 +2694,8 @@
"status_content_hint": "Space the content actually occupies: all notes (hidden ones included), attachments and revisions, with duplicated content counted once. The bracketed figures are the space only revisions, respectively only attachments, hold.",
"status_deleted_one": "Deleted notes: {{size}} in {{count}} note",
"status_deleted_other": "Deleted notes: {{size}} in {{count}} notes",
- "status_deleted_hint": "Space still held by deleted notes; erasing them reclaims it"
+ "status_deleted_hint": "Space still held by deleted notes; erasing them reclaims it",
+ "menu_show_details": "Show details"
},
"note_language": {
"not_set": "No language set",
diff --git a/apps/client/src/widgets/react/charts/DonutChart.tsx b/apps/client/src/widgets/react/charts/DonutChart.tsx
index 19c4bc5b2f..1006186dac 100644
--- a/apps/client/src/widgets/react/charts/DonutChart.tsx
+++ b/apps/client/src/widgets/react/charts/DonutChart.tsx
@@ -30,6 +30,7 @@ export interface DonutRing<T = unknown> {
thickness: number;
segments: DonutSegment<T>[];
onSegmentClick?: (segment: DonutSegment<T>) => void;
+ onSegmentContextMenu?: (segment: DonutSegment<T>, event: MouseEvent) => void;
}
interface DonutChartProps<T> {
@@ -111,6 +112,7 @@ function Ring<T>({ ring, onSegmentHover }: {
r={ring.radius}
fill="none"
onClick={ring.onSegmentClick && (() => ring.onSegmentClick?.(segment))}
+ onContextMenu={ring.onSegmentContextMenu && ((event) => ring.onSegmentContextMenu?.(segment, event))}
onMouseEnter={(event) => onSegmentHover(segment, event)}
onMouseLeave={() => onSegmentHover(null)}
// Arc geometry is data-driven; as inline *style* (not attributes) it stays
diff --git a/apps/client/src/widgets/react/charts/Treemap.tsx b/apps/client/src/widgets/react/charts/Treemap.tsx
index 7ec2607a94..0ac354e575 100644
--- a/apps/client/src/widgets/react/charts/Treemap.tsx
+++ b/apps/client/src/widgets/react/charts/Treemap.tsx
@@ -34,6 +34,7 @@ export interface TreemapItem<T = unknown> {
interface TreemapProps<T> {
root: TreemapItem<T>;
onItemClick?: (item: TreemapItem<T>) => void;
+ onItemContextMenu?: (item: TreemapItem<T>, event: MouseEvent) => void;
className?: string;
}
@@ -69,7 +70,7 @@ const EDGE_EPSILON = 0.5;
* tooltips behave like everywhere else in the app. The hue tint is mixed into the theme's own
* surface color, which keeps the map coherent under any user theme.
*/
-export default function Treemap<T>({ root, onItemClick, className }: TreemapProps<T>) {
+export default function Treemap<T>({ root, onItemClick, onItemContextMenu, className }: TreemapProps<T>) {
const { containerRef, containerProps, showTooltip, hideTooltip, tooltipNode } = useChartTooltip<HTMLDivElement>();
const size = useElementSize(containerRef);
const width = Math.floor(size?.width ?? 0);
@@ -123,6 +124,7 @@ export default function Treemap<T>({ root, onItemClick, className }: TreemapProp
...(item.hue !== undefined && { "--treemap-hue": String(item.hue) })
}}
onClick={onItemClick && (() => onItemClick(item))}
+ onContextMenu={onItemContextMenu && ((event) => onItemContextMenu(item, event))}
onMouseEnter={(event) => showTooltip(item.tooltip, event)}
onMouseLeave={hideTooltip}
{...item.attributes}
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
index ef5057ebf0..4c93ae2176 100644
--- 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
@@ -1,5 +1,6 @@
import type { SpaceUsageNoteResponse } from "@triliumnext/commons";
import { type ComponentChildren, render } from "preact";
+import { useState } from "preact/hooks";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { DonutRing } from "../../../../react/charts/DonutChart";
@@ -11,12 +12,18 @@ interface CapturedDonutProps {
notePath: string[];
outerRings: DonutRing<UsageSegmentData>[];
centerActions: ComponentChildren;
+ onTitleContextMenu: (event: MouseEvent) => void;
}
const mocks = vi.hoisted(() => ({
usage: undefined as unknown,
fetchedUrls: [] as string[],
- donutProps: undefined as unknown
+ donutProps: undefined as unknown,
+ openContextMenu: vi.fn()
+}));
+
+vi.mock("./context_menu", () => ({
+ openSpaceUsageContextMenu: (...args: unknown[]) => mocks.openContextMenu(...args)
}));
vi.mock("./use_space_usage_fetch", () => ({
@@ -70,9 +77,16 @@ function usageOf(noteId: string, children: string[]): SpaceUsageNoteResponse {
let container: HTMLDivElement | undefined;
+/** The path is owned by the section in the app; here a minimal host stands in for it. */
+function BrowseHost() {
+ const [ path, setPath ] = useState([ "root" ]);
+
+ return <Browse path={path} onPathChange={setPath} />;
+}
+
function renderBrowse() {
container = document.body.appendChild(document.createElement("div"));
- render(<Browse />, container);
+ render(<BrowseHost />, container);
return container;
}
@@ -98,6 +112,7 @@ afterEach(() => {
mocks.usage = undefined;
mocks.fetchedUrls = [];
mocks.donutProps = undefined;
+ mocks.openContextMenu.mockClear();
});
describe("Browse", () => {
@@ -165,4 +180,27 @@ describe("Browse", () => {
expect(crumbTexts(probe)).toEqual([ "title:root" ]);
});
+
+ it("opens the shared menu on a child's own path and on the current note, descending on show-details", async () => {
+ mocks.usage = usageOf("root", [ "child1" ]);
+ const probe = renderBrowse();
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root" ]));
+
+ const event = new MouseEvent("contextmenu");
+ const ring = donutProps().outerRings[0];
+ ring.onSegmentContextMenu?.({ id: "child/child1", value: 40, data: { noteId: "child1" } }, event);
+ expect(mocks.openContextMenu).toHaveBeenCalledWith(event, [ "root", "child1" ], expect.any(Function));
+
+ donutProps().onTitleContextMenu(event);
+ expect(mocks.openContextMenu).toHaveBeenLastCalledWith(event, [ "root" ], expect.any(Function));
+
+ // Showing a note's details from within Browse is this view's own descent.
+ mocks.openContextMenu.mock.calls[0][2]([ "root", "child1" ]);
+ await vi.waitFor(() => expect(crumbTexts(probe)).toEqual([ "title:root", "title:child1" ]));
+
+ // A segment naming no note has nothing to offer.
+ mocks.openContextMenu.mockClear();
+ ring.onSegmentContextMenu?.({ id: "/deleted-notes", value: 5, data: {} }, event);
+ expect(mocks.openContextMenu).not.toHaveBeenCalled();
+ });
});
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
index 960c1b1e28..399d709029 100644
--- 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
@@ -9,6 +9,7 @@ import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
import ActionButton from "../../../../react/ActionButton";
import type { DonutRing } from "../../../../react/charts/DonutChart";
+import { openSpaceUsageContextMenu } from "./context_menu";
import { buildChildrenSegments, type UsageSegmentData } from "./donut_segments";
import NoteUsageDonut, { segmentTooltip } from "./note_usage_donut";
import { useSpaceUsageFetch } from "./use_space_usage_fetch";
@@ -16,16 +17,24 @@ import { useSpaceUsageFetch } from "./use_space_usage_fetch";
const CHILDREN_RING_RADIUS = 180;
const CHILDREN_RING_THICKNESS = 46;
+interface BrowseProps {
+ /** Note IDs from the root (inclusive) down to the note in view. */
+ path: string[];
+ onPathChange: (path: string[]) => void;
+}
+
/**
* 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.
+ *
+ * The path is owned by the section rather than the view, so that "Show details" elsewhere in Space
+ * Usage can drop the user straight onto a note here.
*/
-export default function Browse() {
- const [ stack, setStack ] = useState([ "root" ]);
- const noteId = stack[stack.length - 1];
+export default function Browse({ path, onPathChange }: BrowseProps) {
+ const noteId = path[path.length - 1];
const usage = useSpaceUsageFetch<SpaceUsageNoteResponse>(`space-usage/note/${noteId}`);
- const titles = useNoteTitles(stack, usage);
+ const titles = useNoteTitles(path, usage);
const getTitle = useCallback((id: string) => titles.get(id) ?? id, [ titles ]);
const childrenRing: DonutRing<UsageSegmentData> = useMemo(() => ({
@@ -43,23 +52,31 @@ export default function Browse() {
const childId = segment.data?.noteId;
if (childId) {
- setStack((current) => [ ...current, childId ]);
+ onPathChange([ ...path, childId ]);
+ }
+ },
+ // Descending is what "Show details" means here, so the menu's own handler is the navigation.
+ onSegmentContextMenu: (segment, event) => {
+ const childId = segment.data?.noteId;
+
+ if (childId) {
+ void openSpaceUsageContextMenu(event, [ ...path, childId ], onPathChange);
}
}
- }), [ usage, getTitle ]);
+ }), [ usage, getTitle, path, onPathChange ]);
return (
<div className="space-usage-browse">
<nav className="space-usage-breadcrumb">
<span className="space-usage-crumb-label">{t("space_usage.current_note")}</span>
- {stack.map((id, index) => (
+ {path.map((id, index) => (
<Fragment key={`${index}/${id}`}>
{index > 0 && <span className="space-usage-crumb-separator" aria-hidden="true">›</span>}
- {index < stack.length - 1 ? (
+ {index < path.length - 1 ? (
<button
type="button"
className="space-usage-crumb"
- onClick={() => setStack((current) => current.slice(0, index + 1))}
+ onClick={() => onPathChange(path.slice(0, index + 1))}
>{getTitle(id)}</button>
) : (
<span className="space-usage-crumb space-usage-crumb-current">{getTitle(id)}</span>
@@ -73,15 +90,16 @@ export default function Browse() {
<NoteUsageDonut
usage={usage}
title={getTitle(usage.noteId)}
- notePath={stack}
+ notePath={path}
outerRings={[ childrenRing ]}
+ onTitleContextMenu={(event) => void openSpaceUsageContextMenu(event, path, onPathChange)}
centerActions={
<ActionButton
className="space-usage-back"
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)}
+ disabled={path.length === 1}
+ onClick={() => path.length > 1 && onPathChange(path.slice(0, -1))}
/>
}
/>
@@ -97,11 +115,11 @@ export default function Browse() {
* 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) {
+function useNoteTitles(path: string[], usage: SpaceUsageNoteResponse | null) {
const [ titles, setTitles ] = useState(new Map<string, string>());
useEffect(() => {
- const noteIds = [ ...stack, ...(usage?.children.map((child) => child.noteId) ?? []) ];
+ const noteIds = [ ...path, ...(usage?.children.map((child) => child.noteId) ?? []) ];
let cancelled = false;
// Silent: a note deleted since the usage was computed must not fail the whole view.
@@ -114,7 +132,7 @@ function useNoteTitles(stack: string[], usage: SpaceUsageNoteResponse | null) {
return () => {
cancelled = true;
};
- }, [ stack, usage ]);
+ }, [ path, usage ]);
return titles;
}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts
new file mode 100644
index 0000000000..cb37fb76c7
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts
@@ -0,0 +1,165 @@
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import type FNote from "../../../../../entities/fnote";
+import type { ContextMenuEvent, MenuCommandItem, MenuItem } from "../../../../../menus/context_menu";
+
+const mocks = vi.hoisted(() => ({
+ shown: undefined as { items: MenuItem<never>[] } | undefined,
+ notes: new Map<string, unknown>(),
+ branchIds: new Map<string, string>(),
+ triggerCommand: vi.fn(),
+ openContextWithNote: vi.fn(),
+ deleteNotes: vi.fn(),
+ downloadFileNote: vi.fn(),
+ showDetails: vi.fn()
+}));
+
+vi.mock("../../../../../menus/context_menu", () => ({
+ default: {
+ show: async (options: { items: MenuItem<never>[] }) => {
+ mocks.shown = options;
+ }
+ }
+}));
+
+vi.mock("../../../../../services/froca", () => ({
+ default: {
+ getNote: async (noteId: string) => mocks.notes.get(noteId) ?? null,
+ getBranchId: async (parentNoteId: string, noteId: string) =>
+ mocks.branchIds.get(`${parentNoteId}/${noteId}`) ?? null
+ }
+}));
+
+vi.mock("../../../../../services/branches", () => ({
+ default: { deleteNotes: (...args: unknown[]) => mocks.deleteNotes(...args) }
+}));
+
+vi.mock("../../../../../services/open", () => ({
+ downloadFileNote: (...args: unknown[]) => mocks.downloadFileNote(...args)
+}));
+
+vi.mock("../../../../../components/app_context", () => ({
+ default: {
+ triggerCommand: mocks.triggerCommand,
+ tabManager: {
+ openContextWithNote: mocks.openContextWithNote,
+ getActiveContext: () => null
+ }
+ }
+}));
+
+import { openSpaceUsageContextMenu } from "./context_menu";
+
+// The translations are uninitialized under the test i18n, so titles come back empty; items are
+// identified by their icon, which is what distinguishes them anyway.
+const QUICK_EDIT = "bx bx-edit";
+const NEW_TAB = "bx bx-link-external";
+const SHOW_DETAILS = "bx bx-detail";
+const DOWNLOAD = "bx bx-download";
+const EXPORT = "bx bx-export";
+const DELETE = "bx bx-trash destructive-action-icon";
+
+function givenNote(noteId: string, type = "text", isContentAvailable = true) {
+ mocks.notes.set(noteId, { noteId, type, isContentAvailable: () => isContentAvailable } as FNote);
+}
+
+function contextMenuEvent() {
+ return {
+ pageX: 10,
+ pageY: 20,
+ preventDefault: vi.fn(),
+ stopPropagation: vi.fn()
+ } as unknown as ContextMenuEvent;
+}
+
+function itemByIcon(icon: string) {
+ return mocks.shown?.items.find(
+ (item): item is MenuCommandItem<never> => "uiIcon" in item && item.uiIcon === icon
+ );
+}
+
+function icons() {
+ return mocks.shown?.items.flatMap((item) => "uiIcon" in item && item.uiIcon ? [ item.uiIcon ] : []);
+}
+
+/** Every item carries a nullary handler; the menu dispatches no commands by name. */
+function invoke(icon: string) {
+ (itemByIcon(icon) as { handler?: () => void } | undefined)?.handler?.();
+}
+
+afterEach(() => {
+ mocks.shown = undefined;
+ mocks.notes.clear();
+ mocks.branchIds.clear();
+ vi.clearAllMocks();
+});
+
+describe("openSpaceUsageContextMenu", () => {
+ it("offers the whole set for a placed note, each action targeting that placement", async () => {
+ givenNote("n1");
+ mocks.branchIds.set("p/n1", "b1");
+ const event = contextMenuEvent();
+
+ await openSpaceUsageContextMenu(event, [ "root", "p", "n1" ], mocks.showDetails);
+
+ // The chart keeps the pointer, and the browser's own menu stays out of the way.
+ expect(event.preventDefault).toHaveBeenCalled();
+ expect(event.stopPropagation).toHaveBeenCalled();
+ // No Download: a text note has no file to save.
+ expect(icons()).toEqual([ QUICK_EDIT, NEW_TAB, SHOW_DETAILS, EXPORT, DELETE ]);
+
+ invoke(QUICK_EDIT);
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "root/p/n1" });
+
+ invoke(NEW_TAB);
+ expect(mocks.openContextWithNote).toHaveBeenCalledWith("n1", { activate: true, hoistedNoteId: null });
+
+ invoke(SHOW_DETAILS);
+ expect(mocks.showDetails).toHaveBeenCalledWith([ "root", "p", "n1" ]);
+
+ invoke(EXPORT);
+ expect(mocks.triggerCommand).toHaveBeenLastCalledWith("showExportDialog", {
+ notePath: "root/p/n1",
+ defaultType: "subtree"
+ });
+
+ // The canonical placement's branch, so a clone loses only the placement the sizes were
+ // attributed to.
+ invoke(DELETE);
+ expect(mocks.deleteNotes).toHaveBeenCalledWith([ "b1" ], false, false);
+ });
+
+ it("adds Download for the note types that hold a file, disabled when the content is unavailable", async () => {
+ givenNote("f1", "file");
+ mocks.branchIds.set("p/f1", "b1");
+ await openSpaceUsageContextMenu(contextMenuEvent(), [ "root", "p", "f1" ], mocks.showDetails);
+ expect(itemByIcon(DOWNLOAD)?.enabled).toBe(true);
+
+ invoke(DOWNLOAD);
+ expect(mocks.downloadFileNote).toHaveBeenCalledWith(mocks.notes.get("f1"), null, null);
+
+ // A protected image whose content is locked away: offered, but not actionable.
+ givenNote("i1", "image", false);
+ await openSpaceUsageContextMenu(contextMenuEvent(), [ "root", "p", "i1" ], mocks.showDetails);
+ expect(itemByIcon(DOWNLOAD)?.enabled).toBe(false);
+ });
+
+ it("disables Export and Delete on the root, which has no parent to place it under", async () => {
+ givenNote("root");
+
+ await openSpaceUsageContextMenu(contextMenuEvent(), [ "root" ], mocks.showDetails);
+
+ expect(itemByIcon(EXPORT)?.enabled).toBe(false);
+ expect(itemByIcon(DELETE)?.enabled).toBe(false);
+ invoke(DELETE);
+ expect(mocks.deleteNotes).not.toHaveBeenCalled();
+ // Opening it is still fine.
+ expect(itemByIcon(QUICK_EDIT)?.enabled).toBeUndefined();
+ });
+
+ it("shows no menu at all for a note deleted since the usage was measured", async () => {
+ await openSpaceUsageContextMenu(contextMenuEvent(), [ "root", "gone" ], mocks.showDetails);
+
+ expect(mocks.shown).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts
new file mode 100644
index 0000000000..eccfa4dd0b
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts
@@ -0,0 +1,126 @@
+import appContext from "../../../../../components/app_context";
+import type FNote from "../../../../../entities/fnote";
+import contextMenu, { type ContextMenuEvent, type MenuItem } from "../../../../../menus/context_menu";
+import branches from "../../../../../services/branches";
+import froca from "../../../../../services/froca";
+import { t } from "../../../../../services/i18n";
+import { downloadFileNote } from "../../../../../services/open";
+
+/** Switches the section to Browse, focused on the given path. */
+export type ShowDetailsHandler = (notePath: string[]) => void;
+
+/**
+ * The actions every Space Usage view offers on a note it draws — the treemap cells of Overview, the
+ * children ring and center note of Browse. One builder so a note answers the same way whichever
+ * chart the pointer is over.
+ *
+ * `notePath` runs from the root (inclusive) down to the note: the charts already carry it for their
+ * links, and it is what identifies the placement to act on — a clone occupies space once, at the
+ * canonical placement the usage figures were attributed to, so that is the branch Delete removes and
+ * the path Export resolves.
+ */
+export async function openSpaceUsageContextMenu(
+ event: ContextMenuEvent,
+ notePath: string[],
+ onShowDetails: ShowDetailsHandler
+) {
+ event.preventDefault();
+ event.stopPropagation();
+
+ const noteId = notePath[notePath.length - 1];
+ const parentNoteId = notePath[notePath.length - 2];
+ // Silent: the usage snapshot predates the menu, so the note may already be gone — no menu, no error.
+ const note = noteId ? await froca.getNote(noteId, true) : null;
+
+ if (!note) {
+ return;
+ }
+
+ // The root has no parent, so it has neither a branch to delete nor a path the export dialog can
+ // resolve into one.
+ const branchId = parentNoteId ? await froca.getBranchId(parentNoteId, noteId) : null;
+ const notePathString = notePath.join("/");
+
+ // Wording and icons are borrowed from the surfaces that already offer these actions — the tree
+ // context menu and the note menu — so a note reads the same here as it does there. Only "Show
+ // details" is particular to Space Usage.
+ const items: MenuItem<never>[] = [
+ {
+ title: t("tree-context-menu.open-in-popup"),
+ uiIcon: "bx bx-edit",
+ handler: () => quickEditNote(notePath)
+ },
+ {
+ title: t("tree-context-menu.open-in-a-new-tab"),
+ uiIcon: "bx bx-link-external",
+ handler: () => openNoteInNewTab(noteId)
+ },
+ {
+ title: t("space_usage.menu_show_details"),
+ uiIcon: "bx bx-detail",
+ handler: () => onShowDetails(notePath)
+ },
+
+ { kind: "separator" },
+
+ ...(isDownloadable(note) ? [ {
+ title: t("file_properties.download"),
+ uiIcon: "bx bx-download",
+ enabled: note.isContentAvailable(),
+ handler: () => downloadFileNote(note, null, null)
+ } ] : []),
+ {
+ title: t("tree-context-menu.export"),
+ uiIcon: "bx bx-export",
+ enabled: !!parentNoteId,
+ handler: () => {
+ void appContext.triggerCommand("showExportDialog", {
+ notePath: notePathString,
+ defaultType: "subtree"
+ });
+ }
+ },
+
+ { kind: "separator" },
+
+ {
+ title: t("tree-context-menu.delete"),
+ uiIcon: "bx bx-trash destructive-action-icon",
+ enabled: !!branchId,
+ handler: () => {
+ if (branchId) {
+ void branches.deleteNotes([ branchId ], false, false);
+ }
+ }
+ }
+ ];
+
+ await contextMenu.show({
+ x: event.pageX,
+ y: event.pageY,
+ items,
+ // Every item carries its own handler; nothing here dispatches a command by name.
+ selectMenuItemHandler: () => {}
+ });
+}
+
+/**
+ * The default action on a Space Usage note: the quick-edit popup, which stacks above the settings
+ * dialog instead of replacing what the user was looking at.
+ */
+export function quickEditNote(notePath: string[]) {
+ void appContext.triggerCommand("openInPopup", { noteIdOrPath: notePath.join("/") });
+}
+
+/** Opens the note in a new tab, leaving the settings page in place. */
+export function openNoteInNewTab(noteId: string) {
+ void appContext.tabManager.openContextWithNote(noteId, {
+ activate: true,
+ hoistedNoteId: appContext.tabManager.getActiveContext()?.hoistedNoteId ?? null
+ });
+}
+
+/** The note types whose content is a saveable file — the same ones the ribbon offers Download for. */
+function isDownloadable(note: FNote) {
+ return note.type === "file" || note.type === "image";
+}
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 0256918fd9..5fe9d5c144 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,7 +1,7 @@
import "./index.css";
import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
-import { useMemo, useRef, useState } from "preact/hooks";
+import { useCallback, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
@@ -20,6 +20,13 @@ type SpaceUsageView = "overview" | "browse";
export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionProps) {
const [ view, setView ] = useState<SpaceUsageView>("overview");
+ // Browse's position lives here so that "Show details", offered on any note either view draws,
+ // can land the user on that note — switching the view along the way when it comes from Overview.
+ const [ browsePath, setBrowsePath ] = useState([ "root" ]);
+ const showDetails = useCallback((notePath: string[]) => {
+ setBrowsePath(notePath);
+ setView("browse");
+ }, []);
// Fetched in both views: the treemap consumes it, and the status line is view-independent.
// Revisions stay out of the ranking so it shares the basis of the areas the treemap draws —
// asking for one basis and drawing the other would rank in notes the cells then shrink away.
@@ -39,9 +46,9 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro
</div>
} />
- {view === "browse" && <Browse />}
+ {view === "browse" && <Browse path={browsePath} onPathChange={setBrowsePath} />}
{view === "overview" && (overview
- ? <Overview overview={overview} />
+ ? <Overview overview={overview} onShowDetails={showDetails} />
: <p className="space-usage-loading">{t("space_usage.loading")}</p>)}
{overview && (
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
index b37507b3c8..0798f24586 100644
--- 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
@@ -7,11 +7,11 @@ import { useMemo, useRef } from "preact/hooks";
import type React from "react";
import { Trans } from "react-i18next";
-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 { useStaticTooltip } from "../../../../react/hooks";
+import { openNoteInNewTab } from "./context_menu";
import { buildCompositionSegments, type UsageSegmentData, type UsageTooltipKind } from "./donut_segments";
export const COMPOSITION_RING_RADIUS = 133;
@@ -28,6 +28,8 @@ interface NoteUsageDonutProps {
outerRings?: DonutRing<UsageSegmentData>[];
/** Rendered centered above the title in the hole — e.g. Browse's back button. */
centerActions?: ComponentChildren;
+ /** Right-clicking the center title, which stands for the note itself. */
+ onTitleContextMenu?: (event: MouseEvent) => void;
className?: string;
}
@@ -37,7 +39,7 @@ interface NoteUsageDonutProps {
* 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 = [], centerActions, className }: NoteUsageDonutProps) {
+export default function NoteUsageDonut({ usage, title, notePath, outerRings = [], centerActions, onTitleContextMenu, className }: NoteUsageDonutProps) {
const compositionRing: DonutRing<UsageSegmentData> = useMemo(() => ({
id: "composition",
radius: COMPOSITION_RING_RADIUS,
@@ -66,11 +68,9 @@ export default function NoteUsageDonut({ usage, title, notePath, outerRings = []
// 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
- });
+ openNoteInNewTab(usage.noteId);
}}
+ onContextMenu={onTitleContextMenu}
>{title}</a>
<SizeLine
i18nKey="space_usage.center_note_size"
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
index 26ad9ab824..32240b06bf 100644
--- 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
@@ -3,18 +3,24 @@ import { render } from "preact";
import { afterEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
- openContextWithNote: vi.fn()
+ triggerCommand: vi.fn(),
+ openContextMenu: vi.fn(),
+ showDetails: vi.fn()
}));
vi.mock("../../../../../components/app_context", () => ({
default: {
- tabManager: {
- openContextWithNote: mocks.openContextWithNote,
- getActiveContext: () => null
- }
+ triggerCommand: mocks.triggerCommand,
+ tabManager: { getActiveContext: () => null }
}
}));
+// The menu itself is covered by its own spec; here only the wiring matters.
+vi.mock("./context_menu", async (importOriginal) => ({
+ ...await importOriginal<typeof import("./context_menu")>(),
+ openSpaceUsageContextMenu: (...args: unknown[]) => mocks.openContextMenu(...args)
+}));
+
// The treemap container never gets a real layout under happy-dom.
vi.mock("../../../../react/hooks", () => ({
useElementSize: () => ({ width: 400, height: 300 })
@@ -35,7 +41,7 @@ let container: HTMLDivElement | undefined;
function renderOverview() {
container = document.body.appendChild(document.createElement("div"));
- render(<Overview overview={OVERVIEW} />, container);
+ render(<Overview overview={OVERVIEW} onShowDetails={mocks.showDetails} />, container);
return container;
}
@@ -45,7 +51,9 @@ afterEach(() => {
container.remove();
container = undefined;
}
- mocks.openContextWithNote.mockClear();
+ mocks.triggerCommand.mockClear();
+ mocks.openContextMenu.mockClear();
+ mocks.showDetails.mockClear();
});
describe("Overview", () => {
@@ -58,19 +66,23 @@ describe("Overview", () => {
expect(probe.querySelector(".treemap-cell-deleted")).not.toBeNull();
});
- it("opens a clicked note in a new tab, while the bucket cells stay inert", () => {
+ it("quick-edits a clicked note and offers the menu on right-click, while the bucket cells stay inert", () => {
const probe = renderOverview();
+ const cell = probe.querySelector('[data-href="#root/n1"]');
+
+ cell?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ expect(mocks.triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: "root/n1" });
- probe.querySelector('[data-href="#root/n1"]')
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- expect(mocks.openContextWithNote).toHaveBeenCalledWith("n1", {
- activate: true,
- hoistedNoteId: null
- });
+ cell?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ expect(mocks.openContextMenu).toHaveBeenCalledWith(
+ expect.anything(), [ "root", "n1" ], mocks.showDetails);
- mocks.openContextWithNote.mockClear();
- probe.querySelector(".treemap-cell-deleted")
- ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
- expect(mocks.openContextWithNote).not.toHaveBeenCalled();
+ mocks.triggerCommand.mockClear();
+ mocks.openContextMenu.mockClear();
+ const bucket = probe.querySelector(".treemap-cell-deleted");
+ bucket?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ bucket?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+ expect(mocks.triggerCommand).not.toHaveBeenCalled();
+ expect(mocks.openContextMenu).not.toHaveBeenCalled();
});
});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx
index 1a4e32312f..d3cc4e2c95 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx
@@ -1,10 +1,10 @@
import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
import { useMemo } from "preact/hooks";
-import appContext from "../../../../../components/app_context";
import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
import Treemap, { type TreemapItem } from "../../../../react/charts/Treemap";
+import { openSpaceUsageContextMenu, quickEditNote, type ShowDetailsHandler } from "./context_menu";
import { bucketWeight, buildOverviewModel, type OverviewCell } from "./overview_model";
/**
@@ -16,8 +16,13 @@ import { bucketWeight, buildOverviewModel, type OverviewCell } from "./overview_
*/
const INCLUDE_REVISIONS = false;
+interface OverviewProps {
+ overview: SpaceUsageOverviewResponse;
+ onShowDetails: ShowDetailsHandler;
+}
+
/** The treemap over the whole database: every large note at its tree location. */
-export default function Overview({ overview }: { overview: SpaceUsageOverviewResponse }) {
+export default function Overview({ overview, onShowDetails }: OverviewProps) {
// The labels are formatted here rather than in the model, which stays free of i18n: a bucket
// stands for a crowd, so its tooltip names how many notes it holds and how much they take.
const model = useMemo(() => buildOverviewModel(overview, {
@@ -39,7 +44,12 @@ export default function Overview({ overview }: { overview: SpaceUsageOverviewRes
return (
<div className="space-usage-overview">
- <Treemap<OverviewCell> root={model} onItemClick={openCellNote} />
+ <Treemap<OverviewCell>
+ root={model}
+ onItemClick={(item) => withCellPath(item, quickEditNote)}
+ onItemContextMenu={(item, event) => withCellPath(item, (notePath) =>
+ void openSpaceUsageContextMenu(event, notePath, onShowDetails))}
+ />
</div>
);
}
@@ -53,19 +63,11 @@ function withSize(name: string, size: number) {
return t("space_usage.segment_tooltip", { title: name, size: formatSize(size) });
}
-/**
- * Opens the clicked note in a new tab, leaving the settings page in place. The bucket cells carry
- * no note and do nothing.
- */
-function openCellNote(item: TreemapItem<OverviewCell>) {
- const noteId = item.data?.noteId;
+/** Runs an action on the cell's note, if it has one — the bucket cells stand for a crowd and stay inert. */
+function withCellPath(item: TreemapItem<OverviewCell>, action: (notePath: string[]) => void) {
+ const notePath = item.data?.notePath;
- if (!noteId) {
- return;
+ if (notePath?.length) {
+ action(notePath);
}
-
- void appContext.tabManager.openContextWithNote(noteId, {
- activate: true,
- hoistedNoteId: appContext.tabManager.getActiveContext()?.hoistedNoteId ?? null
- });
}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts
index eef40c57fd..85eb6f0aff 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.spec.ts
@@ -49,7 +49,8 @@ describe("buildOverviewModel", () => {
const leaf = childById(folder, "leaf");
expect(leaf.value).toBe(120);
- expect(leaf.data).toEqual({ noteId: "leaf" });
+ // The path the cell's actions need, rooted — unlike the server's, which omits the root.
+ expect(leaf.data).toEqual({ noteId: "leaf", notePath: [ "root", "folder", "leaf" ] });
// The size rides along in the note preview tooltip rather than a second tooltip of its own.
expect(leaf.attributes).toEqual({
"data-href": "#root/folder/leaf",
@@ -98,7 +99,7 @@ describe("buildOverviewModel", () => {
const selfCell = childById(parent, "parent/own");
expect(selfCell.value).toBe(50);
expect(selfCell.hue).toBe(hueOf("parent"));
- expect(selfCell.data).toEqual({ noteId: "parent" });
+ expect(selfCell.data).toEqual({ noteId: "parent", notePath: [ "root", "parent" ] });
expect(selfCell.attributes).toEqual({
"data-href": "#root/parent",
"data-tooltip-detail": "size:50"
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.ts
index a2beb6cc68..775095b907 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview_model.ts
@@ -2,9 +2,13 @@ import type { SpaceUsageBucket, SpaceUsageOverviewNote, SpaceUsageOverviewRespon
import type { TreemapItem } from "../../../../react/charts/Treemap";
+const ROOT_NOTE_ID = "root";
+
/** What a treemap cell stands for; the bucket cells ("other", "deleted") name no note at all. */
export interface OverviewCell {
noteId?: string;
+ /** Note IDs from the root (inclusive) down to the note, as the cell's actions need it. */
+ notePath?: string[];
}
interface OverviewModelOptions {
@@ -74,8 +78,10 @@ export function buildOverviewModel(
continue;
}
+ // The server omits the root from its paths, but a note path the app can act on starts there.
+ const cell: OverviewCell = { noteId: entry.noteId, notePath: [ ROOT_NOTE_ID, ...path ] };
const attributes = {
- "data-href": `#root/${path.join("/")}`,
+ "data-href": `#${cell.notePath?.join("/")}`,
// The note preview tooltip shows this under the title, which is how a cell states its
// size without any text of its own — and without a second tooltip competing with it.
...(makeSizeDetail ? { "data-tooltip-detail": makeSizeDetail(weight) } : {})
@@ -87,13 +93,13 @@ export function buildOverviewModel(
value: weight,
// The self-cell sits among the note's own children, so it wears their group hue.
hue: hueOf(entry.noteId),
- data: { noteId: entry.noteId },
+ data: cell,
attributes
});
} else {
node.value = weight;
- node.hue = hueOf(path.at(-2) ?? "root");
- node.data = { noteId: entry.noteId };
+ node.hue = hueOf(path.at(-2) ?? ROOT_NOTE_ID);
+ node.data = cell;
node.attributes = attributes;
}
}