Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager/space usage: add a context menu command to erase excess revisions

Adorian Doraneba54757c08a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index fa98d7342a..4729038def 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2856,7 +2856,8 @@
"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",
- "menu_show_details": "Show details"
+ "menu_show_details": "Show details",
+ "revisions_limit_required": "Excess snapshots can only be erased once a maximum number of revision snapshots per note is set. Without a limit, no snapshot counts as excess."
},
"note_language": {
"not_set": "No language set",
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
index 2b72aa9aea..6a2a46af47 100644
--- 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
@@ -20,7 +20,9 @@ const mocks = vi.hoisted(() => ({
showDetails: vi.fn(),
contentChanged: vi.fn(),
post: vi.fn(async (..._args: unknown[]) => undefined),
- showMessage: vi.fn()
+ showMessage: vi.fn(),
+ revisionLimit: 0 as number | null,
+ configureLimit: vi.fn()
}));
vi.mock("../../../../../menus/context_menu", () => ({
@@ -55,6 +57,10 @@ vi.mock("../../../../../services/toast", () => ({
default: { showMessage: (...args: unknown[]) => mocks.showMessage(...args) }
}));
+vi.mock("../../../../../services/options", () => ({
+ default: { getInt: () => mocks.revisionLimit }
+}));
+
vi.mock("../../../../../components/app_context", () => ({
default: {
triggerCommand: mocks.triggerCommand,
@@ -65,7 +71,11 @@ vi.mock("../../../../../components/app_context", () => ({
}
}));
-import { openDeletedNotesContextMenu, openSpaceUsageContextMenu } from "./context_menu";
+import {
+ openDeletedNotesContextMenu,
+ openRevisionsContextMenu,
+ 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.
@@ -234,3 +244,44 @@ describe("openDeletedNotesContextMenu", () => {
expect(mocks.showMessage).toHaveBeenCalled();
});
});
+
+describe("openRevisionsContextMenu", () => {
+ async function openRevisionsFor(revisionLimit: number | null) {
+ mocks.revisionLimit = revisionLimit;
+ await openRevisionsContextMenu(contextMenuEvent(), mocks.contentChanged, mocks.configureLimit);
+ }
+
+ it("trims the excess snapshots and asks for a fresh reading, once a limit is set", async () => {
+ await openRevisionsFor(10);
+
+ expect(icons()).toEqual([ ERASE ]);
+
+ invoke(ERASE);
+ expect(mocks.post).toHaveBeenCalledWith("revisions/erase-all-excess-revisions");
+ expect(mocks.configureLimit).not.toHaveBeenCalled();
+
+ await vi.waitFor(() => expect(mocks.contentChanged).toHaveBeenCalledTimes(1));
+ expect(mocks.showMessage).toHaveBeenCalled();
+
+ // A limit of zero keeps no snapshot at all, so every one of them is excess — a limit like
+ // any other, not an unset one.
+ await openRevisionsFor(0);
+ invoke(ERASE);
+ expect(mocks.post).toHaveBeenCalledTimes(2);
+ expect(mocks.configureLimit).not.toHaveBeenCalled();
+ });
+
+ it("offers the limit instead of an erasure that would drop nothing, when there is none", async () => {
+ // A negative limit keeps everything, so there is no ceiling to trim down to and the erasure
+ // would report success having changed nothing. An unreadable option counts as no limit
+ // rather than as the harshest one, which would erase every snapshot in the database.
+ for (const noLimit of [ -1, null ]) {
+ await openRevisionsFor(noLimit);
+ invoke(ERASE);
+ }
+
+ expect(mocks.configureLimit).toHaveBeenCalledTimes(2);
+ expect(mocks.post).not.toHaveBeenCalled();
+ expect(mocks.contentChanged).not.toHaveBeenCalled();
+ });
+});
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
index 6bea2e7d10..4000a48e6b 100644
--- 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
@@ -8,6 +8,7 @@ import branches from "../../../../../services/branches";
import froca from "../../../../../services/froca";
import { t } from "../../../../../services/i18n";
import { downloadFileNote } from "../../../../../services/open";
+import options from "../../../../../services/options";
import server from "../../../../../services/server";
import toast from "../../../../../services/toast";
@@ -165,6 +166,47 @@ export async function openDeletedNotesContextMenu(
});
}
+/**
+ * The menu on the revisions cell, offering the same trimming as the options page: dropping the
+ * snapshots each note keeps beyond its limit.
+ *
+ * Without a limit set, nothing is excess and the action would do nothing at all — so it says why and
+ * offers the setting, via `onConfigureLimit`, rather than answering with an erasure that changes
+ * nothing.
+ */
+export async function openRevisionsContextMenu(
+ event: ContextMenuEvent,
+ onContentChanged: ContentChangedHandler,
+ onConfigureLimit: () => void
+) {
+ event.preventDefault();
+ event.stopPropagation();
+
+ await contextMenu.show({
+ x: event.pageX,
+ y: event.pageY,
+ items: [ {
+ title: t("revisions_snapshot_limit.erase_excess_revision_snapshots"),
+ uiIcon: "bx bx-trash destructive-action-icon",
+ handler: () => {
+ // A negative limit is the one that keeps everything, so there is nothing to trim
+ // down to; 0 is a limit like any other, and erases every snapshot there is. An
+ // unreadable option is treated as no limit rather than as the harshest one.
+ if ((options.getInt("revisionSnapshotNumberLimit") ?? -1) < 0) {
+ onConfigureLimit();
+ return;
+ }
+
+ void server.post("revisions/erase-all-excess-revisions").then(() => {
+ toast.showMessage(t("revisions_snapshot_limit.erase_excess_revision_snapshots_prompt"));
+ onContentChanged();
+ });
+ }
+ } ],
+ 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.
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 d6f33b981c..1c7e170055 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
@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({
triggerCommand: vi.fn(),
openContextMenu: vi.fn(),
openDeletedNotesMenu: vi.fn(),
+ openRevisionsMenu: vi.fn(),
showDetails: vi.fn(),
contentChanged: vi.fn()
}));
@@ -21,14 +22,24 @@ vi.mock("../../../../../components/app_context", () => ({
vi.mock("./context_menu", async (importOriginal) => ({
...await importOriginal<typeof import("./context_menu")>(),
openSpaceUsageContextMenu: (...args: unknown[]) => mocks.openContextMenu(...args),
- openDeletedNotesContextMenu: (...args: unknown[]) => mocks.openDeletedNotesMenu(...args)
+ openDeletedNotesContextMenu: (...args: unknown[]) => mocks.openDeletedNotesMenu(...args),
+ openRevisionsContextMenu: (...args: unknown[]) => mocks.openRevisionsMenu(...args)
}));
-// The treemap container never gets a real layout under happy-dom.
-vi.mock("../../../../react/hooks", () => ({
+// The treemap container never gets a real layout under happy-dom; the rest of the hooks are the
+// real ones.
+vi.mock("../../../../react/hooks", async (importOriginal) => ({
+ ...await importOriginal<typeof import("../../../../react/hooks")>(),
useElementSize: () => ({ width: 400, height: 300 })
}));
+// Stood in for so the dialog's own state is visible in the DOM: what this spec covers is whether
+// the revisions menu raises it, not the options card it carries.
+vi.mock("./revision_limit_dialog", () => ({
+ default: ({ show }: { show: boolean }) =>
+ <div className="revision-limit-dialog" data-show={String(show)} />
+}));
+
vi.mock("../../../../../services/froca", () => ({
default: {
getNotes: async (noteIds: string[]) =>
@@ -71,6 +82,7 @@ afterEach(() => {
mocks.triggerCommand.mockClear();
mocks.openContextMenu.mockClear();
mocks.openDeletedNotesMenu.mockClear();
+ mocks.openRevisionsMenu.mockClear();
mocks.showDetails.mockClear();
});
@@ -134,4 +146,24 @@ describe("Overview", () => {
deleted?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
expect(mocks.triggerCommand).not.toHaveBeenCalled();
});
+
+ it("answers the revisions bucket with its own menu, which can raise the limit dialog", async () => {
+ const probe = renderOverview();
+ const dialogShown = () =>
+ probe.querySelector(".revision-limit-dialog")?.getAttribute("data-show");
+
+ expect(dialogShown()).toBe("false");
+
+ probe.querySelector(".treemap-cell-revisions")
+ ?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
+
+ expect(mocks.openContextMenu).not.toHaveBeenCalled();
+ expect(mocks.openRevisionsMenu).toHaveBeenCalledWith(
+ expect.anything(), mocks.contentChanged, expect.any(Function));
+
+ // The menu raises the dialog only when there is no snapshot limit to erase down to; the
+ // view's part is having one to raise.
+ mocks.openRevisionsMenu.mock.calls[0][2]();
+ await vi.waitFor(() => expect(dialogShown()).toBe("true"));
+ });
});
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 17b68c90a7..de794308f1 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,5 +1,5 @@
import type { SpaceUsageOverviewResponse } from "@triliumnext/commons";
-import { useEffect, useMemo, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useState } from "preact/hooks";
import froca from "../../../../../services/froca";
import { t } from "../../../../../services/i18n";
@@ -8,11 +8,13 @@ import Treemap, { type TreemapItem } from "../../../../react/charts/Treemap";
import {
type ContentChangedHandler,
openDeletedNotesContextMenu,
+ openRevisionsContextMenu,
openSpaceUsageContextMenu,
quickEditNote,
type ShowDetailsHandler
} from "./context_menu";
import { bucketWeight, buildOverviewModel, type OverviewCell } from "./overview_model";
+import RevisionLimitDialog from "./revision_limit_dialog";
/**
* A cell's area covers a note's body and attachments, leaving history out; its tooltip says the
@@ -32,6 +34,9 @@ interface OverviewProps {
/** The treemap over the whole database: every large note at its tree location. */
export default function Overview({ overview, onShowDetails, onContentChanged }: OverviewProps) {
const icons = useNoteIcons(overview);
+ // Only ever raised by the revisions cell, when there is no snapshot limit for it to trim to.
+ const [ configuringRevisionLimit, setConfiguringRevisionLimit ] = useState(false);
+ const configureRevisionLimit = useCallback(() => setConfiguringRevisionLimit(true), []);
// 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.
@@ -69,17 +74,27 @@ export default function Overview({ overview, onShowDetails, onContentChanged }:
root={model}
onItemClick={(item) => withCellPath(item, quickEditNote)}
onItemContextMenu={(item, event) => {
- // The deleted bucket names no note, so it answers with what can be done to the
- // crowd it stands for rather than with the note menu.
+ // The buckets name no note, so those with something to offer answer with what
+ // can be done to the crowd they stand for rather than with the note menu.
if (item.data?.bucket === "deleted") {
void openDeletedNotesContextMenu(event, onContentChanged);
return;
}
+ if (item.data?.bucket === "revisions") {
+ void openRevisionsContextMenu(event, onContentChanged, configureRevisionLimit);
+ return;
+ }
+
withCellPath(item, (notePath) =>
void openSpaceUsageContextMenu(event, notePath, onShowDetails, onContentChanged));
}}
/>
+
+ <RevisionLimitDialog
+ show={configuringRevisionLimit}
+ onHidden={() => setConfiguringRevisionLimit(false)}
+ />
</div>
);
}
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.spec.tsx
new file mode 100644
index 0000000000..8742308a22
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.spec.tsx
@@ -0,0 +1,81 @@
+import { render } from "preact";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ optionValues: {
+ revisionSnapshotNumberLimit: "-1",
+ revisionSnapshotTimeInterval: "600",
+ revisionSnapshotTimeIntervalTimeScale: "1"
+ } as Record<string, string>,
+ save: vi.fn(async (..._args: unknown[]) => undefined),
+ post: vi.fn(async (..._args: unknown[]) => undefined)
+}));
+
+vi.mock("../../../../../services/options", () => ({
+ default: {
+ get: (key: string) => mocks.optionValues[key],
+ getInt: (key: string) => parseInt(mocks.optionValues[key], 10),
+ save: (...args: unknown[]) => mocks.save(...args)
+ }
+}));
+
+// The shared setup already stands the server in for; only the writes this dialog makes are added.
+vi.mock("../../../../../services/server", async (importOriginal) => {
+ const actual = await importOriginal<{ default: object }>();
+
+ return {
+ default: {
+ ...actual.default,
+ post: (...args: unknown[]) => mocks.post(...args),
+ put: (...args: unknown[]) => mocks.post(...args)
+ }
+ };
+});
+
+import RevisionLimitDialog from "./revision_limit_dialog";
+
+let container: HTMLDivElement | undefined;
+
+function renderDialog() {
+ container = document.body.appendChild(document.createElement("div"));
+ render(<RevisionLimitDialog show onHidden={() => {}} />, container);
+
+ // Portalled to the body, so the dialog is not inside the container it was rendered from.
+ const dialog = document.querySelector<HTMLElement>(".space-usage-revision-limit-dialog");
+ if (!dialog) {
+ throw new Error("dialog not rendered");
+ }
+
+ return dialog;
+}
+
+afterEach(() => {
+ if (container) {
+ render(null, container);
+ container.remove();
+ container = undefined;
+ }
+ document.querySelectorAll(".space-usage-revision-limit-dialog").forEach((el) => el.remove());
+ vi.clearAllMocks();
+});
+
+describe("RevisionLimitDialog", () => {
+ it("carries the options page's revision card, which saves the limit as it does there", () => {
+ const dialog = renderDialog();
+ const input = dialog.querySelector<HTMLInputElement>('input[name="revision-snapshot-number-limit"]');
+
+ expect(input).not.toBeNull();
+ expect(input?.value).toBe("-1");
+
+ let seen = 0;
+ if (input) {
+ input.addEventListener("blur", () => seen++);
+ input.value = "10";
+ input.focus();
+ input.blur();
+ }
+
+ console.log("SAVE CALLS", JSON.stringify(mocks.save.mock.calls), "BLUR SEEN", seen);
+ expect(mocks.save).toHaveBeenCalledWith("revisionSnapshotNumberLimit", 10);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.tsx
new file mode 100644
index 0000000000..1212bb3031
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.tsx
@@ -0,0 +1,40 @@
+import { createPortal } from "preact/compat";
+
+import { t } from "../../../../../services/i18n";
+import FormText from "../../../../react/FormText";
+import Modal from "../../../../react/Modal";
+import { RevisionSettings } from "../../other";
+
+interface RevisionLimitDialogProps {
+ show: boolean;
+ onHidden: () => void;
+}
+
+/**
+ * Shown when the revisions cell is asked to erase excess snapshots while no limit is set: it says
+ * why nothing would be erased and carries the options page's own Note revisions card, so the limit
+ * can be set here and the action retried without leaving Space Usage.
+ *
+ * The card is the real one rather than a copy of its fields — it saves through the same options
+ * hooks, so the setting is live the moment it is entered.
+ */
+export default function RevisionLimitDialog({ show, onHidden }: RevisionLimitDialogProps) {
+ // Portalled to the body: rendered where it stands, the dialog would sit inside the settings
+ // dialog's own stacking context and end up under the backdrop Bootstrap appends for it.
+ return createPortal(
+ <Modal
+ className="space-usage-revision-limit-dialog"
+ title={t("revisions_snapshot_limit.erase_excess_revision_snapshots")}
+ size="md"
+ show={show}
+ onHidden={onHidden}
+ // The settings dialog it is opened from stays where it is, underneath.
+ stackable
+ >
+ <FormText>{t("space_usage.revisions_limit_required")}</FormText>
+
+ <RevisionSettings />
+ </Modal>,
+ document.body
+ );
+}
diff --git a/apps/client/src/widgets/type_widgets/options/other.tsx b/apps/client/src/widgets/type_widgets/options/other.tsx
index 4fe1673dd4..51e3a87ada 100644
--- a/apps/client/src/widgets/type_widgets/options/other.tsx
+++ b/apps/client/src/widgets/type_widgets/options/other.tsx
@@ -106,7 +106,12 @@ function AttachmentErasureTimeout() {
);
}
-function RevisionSettings() {
+/**
+ * Exported so a surface that needs the revision limit set — Space Usage, whose revisions cell can
+ * only erase excess snapshots once there is a limit — can offer this very card in a dialog rather
+ * than sending the user off to the options page and back.
+ */
+export function RevisionSettings() {
const [ revisionSnapshotNumberLimit, setRevisionSnapshotNumberLimit ] = useTriliumOption("revisionSnapshotNumberLimit");
return (