Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/cleanup tool: wire up the UI to the API
Adorian Doranda28e3976244
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex b6f6327f51..abe5be3845 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2889,7 +2889,9 @@"cleanup_snapshots_to_keep": "Revision snapshots to keep","cleanup_keep_named": "Keep named revisions","cleanup_cancel": "Cancel",- "cleanup_clean": "Clean"+ "cleanup_clean": "Clean",+ "cleanup_confirm": "This permanently deletes the selected data. It cannot be undone.",+ "cleanup_done": "Cleanup completed, reclaiming {{size}}."},"note_language": {"not_set": "No language set",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsxindex 701c570854..76ea7253a2 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx@@ -1,48 +1,88 @@-import { type ComponentChildren, render } from "preact";+import type { ComponentChildren } from "preact";+import { useEffect } from "preact/hooks";import { act } from "preact/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { t } from "../../../../../services/i18n";import { formatSize } from "../../../../../services/utils";+// Hoisted with the mocks that read them: a `vi.mock` factory runs before any plain module constant.+const { REVISIONS_ALL, REVISIONS_TRIMMED, DELETED, UNUSED } = vi.hoisted(() => ({+ REVISIONS_ALL: 900,+ REVISIONS_TRIMMED: 300,+ DELETED: 100,+ UNUSED: 20+}));+const mocks = vi.hoisted(() => ({- getInt: vi.fn<(name: string) => number | null>(() => -1)+ getInt: vi.fn<(name: string) => number | null>(() => -1),+ storedOption: "{}",+ save: vi.fn(async () => {}),+ get: vi.fn(),+ post: vi.fn(async (_url: string, _body?: object) => {}),+ confirm: vi.fn(async () => true),+ showMessage: vi.fn()}));vi.mock("../../../../../services/options", () => ({- default: { getInt: mocks.getInt }+ default: {+ get: () => mocks.storedOption,+ getInt: mocks.getInt,+ save: mocks.save+ }}));-// Bootstrap's modal machinery is not what any of this is about; the stub renders the body and the-// footer inline so the dialog's own content can be read straight out of the DOM.-vi.mock("../../../../react/Modal", () => ({- default: ({ children, footer, show }: { children: ComponentChildren, footer: ComponentChildren, show: boolean }) => (- show ? <div className="modal-stub">{children}<div className="footer-stub">{footer}</div></div> : null- )+vi.mock("../../../../../services/server", () => ({+ default: {+ // The aggressive reading and the trimmed one differ only in the retention they were asked+ // for, which is what the URL carries. Everything else the client loads on the way past is+ // answered emptily rather than with a usage payload it would choke on.+ get: (url: string) => {+ mocks.get(url);++ if (!url.startsWith("space-usage/")) {+ return Promise.resolve(url === "keyboard-actions" ? [] : {});+ }++ const keeping = /snapshotsToKeep=(\d+)/.exec(url)?.[1];+ return Promise.resolve({+ subtreeRevisionsContentSize: keeping === "0" ? REVISIONS_ALL : REVISIONS_TRIMMED,+ deletedNotes: { size: DELETED, noteCount: 1, attachmentCount: 0 },+ unusedAttachments: { size: UNUSED, attachmentCount: 1 }+ });+ },+ post: mocks.post+ }}));-import CleanupDialog, { type CleanupEstimates } from "./cleanup_dialog";--const ESTIMATES: CleanupEstimates = {- deletedEntities: 3000,- unusedAttachments: 2000,- revisionSnapshots: 5000-};+vi.mock("../../../../../services/dialog", () => ({ default: { confirm: mocks.confirm } }));+vi.mock("../../../../../services/toast", () => ({ default: { showMessage: mocks.showMessage } }));-let container: HTMLDivElement | undefined;+// The real modal reports its close once the animation is done; the stub reports it as soon as it is+// told to hide, which is the signal the dialog's own flow keys off.+vi.mock("../../../../react/Modal", () => ({+ default: function ModalStub({ children, footer, show, onHidden }: {+ children: ComponentChildren, footer: ComponentChildren, show: boolean, onHidden: () => void+ }) {+ useEffect(() => {+ if (!show) {+ onHidden();+ }+ // Keyed on the visibility alone: the dialog hands down a fresh closure each render, and+ // following that identity would report the same close over and over.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ show ]);++ return show ? <div className="modal-stub">{children}<div className="footer-stub">{footer}</div></div> : null;+ }+}));-function renderDialog(estimates = ESTIMATES) {- container = document.body.appendChild(document.createElement("div"));- render(<CleanupDialog show onHidden={() => {}} estimates={estimates} />, container);- return container;-}+import { showCleanupDialog } from "./cleanup_dialog";-/** The dialog portals to `<body>`, so its content is looked up there rather than in the container. */function rows() {return Array.from(document.body.querySelectorAll<HTMLElement>(".cleanup-item:not(.cleanup-item-nested)"));}-/** The qualifiers under the revision item, which are card sections of their own. */function nestedRows() {return Array.from(document.body.querySelectorAll<HTMLElement>(".cleanup-item-nested"));}@@ -55,106 +95,126 @@ function textOf(selector: string) {return document.body.querySelector<HTMLElement>(selector)?.textContent ?? "";}+function buttons() {+ return Array.from(document.body.querySelectorAll<HTMLButtonElement>(".footer-stub button"));+}++const cancelButton = () => buttons()[0];+const cleanButton = () => buttons()[1];+/**- * Flips the switch of the row at `index`, the way a click on it does. Translations are absent under- * the test i18n, so rows are addressed by position rather than by their (empty) labels.+ * Opens the dialog and lets its opening measurements land. The pending close is handed back wrapped:+ * returned bare, awaiting this helper would adopt it and wait for the dialog to finish.*/-async function toggleRow(index: number) {- const toggle = rows()[index]?.querySelector<HTMLInputElement>(".switch-toggle");+async function openDialog() {+ const closed = showCleanupDialog();+ // Two measurements land, each through its own effect and state update: a macrotask turn drains+ // the microtasks between them, which flushing promises alone does not.+ await settle();+ await settle();+ return { closed };+}++function settle() {+ return act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+}++/** Flips the switch of a row, the way a click on it does. */+async function toggle(row: HTMLElement | undefined) {await act(async () => {- toggle?.dispatchEvent(new Event("input", { bubbles: true }));+ row?.querySelector<HTMLInputElement>(".switch-toggle")?.dispatchEvent(new Event("input", { bubbles: true }));});}-describe("CleanupDialog", () => {- afterEach(() => {- if (container) {- render(null, container);- container.remove();- container = undefined;- }- mocks.getInt.mockReturnValue(-1);+async function click(button: HTMLButtonElement | undefined) {+ await act(async () => {+ button?.dispatchEvent(new MouseEvent("click", { bubbles: true }));});+}- it("lists every item with its own swatch, its estimate and a switch", () => {- renderDialog();+beforeEach(() => {+ mocks.storedOption = "{}";+ mocks.getInt.mockReturnValue(-1);+ mocks.confirm.mockResolvedValue(true);+ vi.clearAllMocks();+});- // Compared against the same t() calls, so the assertion holds with translations loaded and- // stays faithful under the uninitialized test i18n (t yields undefined → empty span).- expect(titlesOf(rows())).toEqual([- t("space_usage.cleanup_deleted_entities") ?? "",- t("space_usage.cleanup_unused_attachments") ?? "",- t("space_usage.cleanup_revision_snapshots") ?? ""- ]);+afterEach(() => {+ document.body.innerHTML = "";+});++describe("showCleanupDialog", () => {+ it("opens with nothing picked when the setting has never been written", async () => {+ await openDialog();- const sizes = rows().map((row) => row.querySelector(".cleanup-item-size")?.textContent);- expect(sizes).toEqual([ formatSize(3000), formatSize(2000), formatSize(5000) ]);+ expect(rows().every((row) => !row.querySelector<HTMLInputElement>(".switch-toggle")?.checked)).toBe(true);+ // Nothing picked is nothing to gain, so the button that erases without recourse stays out.+ expect(cleanButton()?.disabled).toBe(true);+ // And the revision qualifiers are beside the point until that item is actually being run.+ expect(nestedRows()).toEqual([]);+ });- // Each row names its item, which is what carries the color its swatch and its amount are- // both painted from — so the list doubles as the ring's legend.- expect(rows().map((row) => row.className)).toEqual([- "tn-card-section cleanup-item cleanup-item-deletedEntities",- "tn-card-section cleanup-item cleanup-item-unusedAttachments",- "tn-card-section cleanup-item cleanup-item-revisionSnapshots"+ it("reads a stored answer back, qualifiers and all", async () => {+ mocks.storedOption = JSON.stringify({ revisionSnapshots: true, snapshotsToKeep: 2, keepNamedSnapshots: true });+ await openDialog();++ expect(titlesOf(nestedRows())).toEqual([+ t("space_usage.cleanup_snapshots_to_keep") ?? "",+ t("space_usage.cleanup_keep_named") ?? ""]);- expect(rows().every((row) => row.querySelector(".cleanup-item-swatch"))).toBe(true);- expect(rows().every((row) => row.querySelector(".switch-toggle"))).toBe(true);+ expect(document.body.querySelector<HTMLInputElement>(".cleanup-item-number")?.value).toBe("2");+ expect(cleanButton()?.disabled).toBe(false);});- it("reads the picked total against the whole, which unpicking an item does not move", async () => {- renderDialog();+ it("weighs the offer against everything reclaimable, and writes each pick back", async () => {+ mocks.storedOption = JSON.stringify({ revisionSnapshots: true, snapshotsToKeep: 2 });+ await openDialog();- expect(textOf(".cleanup-chart-caption")).toBe(t("space_usage.cleanup_estimated") ?? "");- expect(textOf(".cleanup-chart-amount")).toBe(formatSize(10000));+ // The whole is the history erased outright plus the rest; the offer, only what is picked.expect(textOf(".cleanup-chart-total")).toBe(- t("space_usage.cleanup_amount_of", { total: formatSize(10000) }) ?? "");+ t("space_usage.cleanup_amount_of", { total: formatSize(REVISIONS_ALL + DELETED + UNUSED) }) ?? "");+ expect(textOf(".cleanup-chart-amount")).toBe(formatSize(REVISIONS_TRIMMED));- // Unpicking the deleted entities takes their 3000 off the offer, never off the whole below- // the rule: only the figure being read moves.- await toggleRow(0);- expect(textOf(".cleanup-chart-amount")).toBe(formatSize(7000));- expect(textOf(".cleanup-chart-total")).toBe(- t("space_usage.cleanup_amount_of", { total: formatSize(10000) }) ?? "");+ await toggle(rows()[0]);+ expect(textOf(".cleanup-chart-amount")).toBe(formatSize(REVISIONS_TRIMMED + DELETED));+ expect(mocks.save).toHaveBeenCalledWith("cleanupToolOptions", expect.stringContaining('"deletedEntities":true'));});- it("keeps an unpicked item's arc on the ring, drawn muted rather than dropped", async () => {- renderDialog();+ it("runs only once confirmed, after the dialog is out of the way, and reports what it freed", async () => {+ mocks.storedOption = JSON.stringify({ unusedAttachments: true });+ const { closed } = await openDialog();- const arcs = () => Array.from(document.body.querySelectorAll(".donut-segment"))- .map((segment) => segment.getAttribute("class") ?? "");- expect(arcs().length).toBe(3);- expect(arcs().some((className) => className.includes("cleanup-segment-unpicked"))).toBe(false);+ await click(cleanButton());+ // The confirmation is the last chance to back out of something with no recovery.+ expect(mocks.confirm).toHaveBeenCalledOnce();- await toggleRow(1);- expect(arcs().length).toBe(3);- expect(arcs().filter((className) => className.includes("cleanup-segment-unpicked")).length).toBe(1);+ await expect(closed).resolves.toBe(UNUSED);+ expect(mocks.post).toHaveBeenCalledWith("notes/erase-unused-attachments-now");+ expect(mocks.showMessage).toHaveBeenCalledWith(+ t("space_usage.cleanup_done", { size: formatSize(UNUSED) }));+ // Gone from the page: it is mounted for the run and unmounted with it.+ expect(document.body.querySelector(".modal-stub")).toBeNull();});- it("qualifies the revision trimming only while it is actually being run", async () => {- renderDialog();+ it("erases nothing when the confirmation is declined, and stays open to be reconsidered", async () => {+ mocks.storedOption = JSON.stringify({ unusedAttachments: true });+ await openDialog();+ mocks.confirm.mockResolvedValue(false);- expect(titlesOf(nestedRows())).toEqual([- t("space_usage.cleanup_snapshots_to_keep") ?? "",- t("space_usage.cleanup_keep_named") ?? ""- ]);+ await click(cleanButton());- // The revisions row is the last of the three; unpicking it takes its qualifiers with it.- await toggleRow(2);- expect(nestedRows()).toEqual([]);+ expect(mocks.post).not.toHaveBeenCalled();+ expect(document.body.querySelector(".modal-stub")).not.toBeNull();});- it("offers the configured revision limit to keep, falling back where it keeps all or none", () => {- const keptField = () => document.body.querySelector<HTMLInputElement>(".cleanup-item-number")?.value;+ it("resolves with nothing when the dialog is dismissed, having touched nothing", async () => {+ mocks.storedOption = JSON.stringify({ unusedAttachments: true });+ const { closed } = await openDialog();- // No limit configured: -1 keeps everything, which is no offer at all for a one-off trim.- renderDialog();- expect(keptField()).toBe("4");+ await click(cancelButton());- for (const [ configured, expected ] of [ [ 7, "7" ], [ 0, "4" ] ] as const) {- render(null, container ?? document.createElement("div"));- mocks.getInt.mockReturnValue(configured);- renderDialog();- expect(keptField()).toBe(expected);- }+ await expect(closed).resolves.toBeNull();+ expect(mocks.post).not.toHaveBeenCalled();+ expect(mocks.showMessage).not.toHaveBeenCalled();});});diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsxindex aa5ca1f9a6..d4eb3ff876 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx@@ -1,30 +1,51 @@import "./cleanup_dialog.css";+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";import clsx from "clsx";-import { createPortal } from "preact/compat";-import { useMemo, useState } from "preact/hooks";+import { render } from "preact";+import { useEffect, useMemo, useRef, useState } from "preact/hooks";+import dialogService from "../../../../../services/dialog";import { t } from "../../../../../services/i18n";-import optionService from "../../../../../services/options";+import toast from "../../../../../services/toast";import { formatSize } from "../../../../../services/utils";import Button from "../../../../react/Button";import { Card, CardSection } from "../../../../react/Card";import DonutChart, { type DonutRing } from "../../../../react/charts/DonutChart";import FormTextBox from "../../../../react/FormTextBox";import FormToggle from "../../../../react/FormToggle";+import { useTriliumOptionJson } from "../../../../react/hooks";import Modal from "../../../../react/Modal";+import {+ CLEANUP_ITEMS,+ type CleanupToolOptions,+ computeCleanupSizes,+ readCleanupOptions,+ runCleanup+} from "./cleanup_operation";+import { useSpaceUsageFetch } from "./use_space_usage_fetch";-/** What each of the cleanup's items would reclaim, in bytes. */-export interface CleanupEstimates {- deletedEntities: number;- unusedAttachments: number;- revisionSnapshots: number;-}--export interface CleanupDialogProps {- show: boolean;- onHidden: () => void;- estimates: CleanupEstimates;+/**+ * Opens the cleanup dialog, and resolves once it has finished with the database: the bytes the run+ * was expected to reclaim, or `null` if the user backed out without running one. Callers await it to+ * know when their own figures are stale.+ *+ * Mounted on demand into a host of its own rather than kept in the page: the dialog measures the+ * whole database on open, which is not work to do for a page that merely *could* open it.+ */+export function showCleanupDialog(): Promise<number | null> {+ return new Promise((resolve) => {+ const host = document.body.appendChild(document.createElement("div"));++ render(+ <CleanupDialog onFinished={(reclaimed) => {+ resolve(reclaimed);+ render(null, host);+ host.remove();+ }} />,+ host+ );+ });}/**@@ -35,11 +56,32 @@ export interface CleanupDialogProps {* chart instead of re-laying it out — and the hole can read "this much of that much" against a whole* that holds still.*/-export default function CleanupDialog({ show, onHidden, estimates }: CleanupDialogProps) {- const [ picked, setPicked ] = useState<Record<CleanupItemId, boolean>>(- { deletedEntities: true, unusedAttachments: true, revisionSnapshots: true });- const [ snapshotsToKeep, setSnapshotsToKeep ] = useState(defaultSnapshotsToKeep);- const [ keepNamedSnapshots, setKeepNamedSnapshots ] = useState(true);+function CleanupDialog({ onFinished }: { onFinished: (reclaimed: number | null) => void }) {+ const [ shown, setShown ] = useState(true);+ const [ stored, setStored ] = useTriliumOptionJson<Partial<CleanupToolOptions>>("cleanupToolOptions");+ // The stored setting seeds the working copy; every change writes straight back to it, so the+ // next run opens where this one left off whether or not it was carried through.+ const [ options, setOptions ] = useState<CleanupToolOptions>(() => readCleanupOptions(stored));+ const update = (patch: Partial<CleanupToolOptions>) => {+ const next = { ...options, ...patch };+ setOptions(next);+ void setStored(next);+ };++ // Measured with the history erased outright: the whole the reading is "of", and fixed for as+ // long as the dialog is open, since no setting here can reclaim more than that.+ const everything = useSpaceUsageFetch<SpaceUsageNoteResponse>(`${ROOT_USAGE_URL}?snapshotsToKeep=0`);+ // Measured as the settings would trim it. The retention trails the field being typed in, so a+ // number entered digit by digit costs one measurement rather than one per keystroke.+ const settledSnapshotsToKeep = useDebouncedValue(options.snapshotsToKeep, ESTIMATE_DEBOUNCE_MS);+ const trimmed = useSpaceUsageFetch<SpaceUsageNoteResponse>(+ `${ROOT_USAGE_URL}?snapshotsToKeep=${settledSnapshotsToKeep}&keepNamedSnapshots=${options.keepNamedSnapshots}`);++ const sizes = computeCleanupSizes(everything.data, trimmed.data, options);+ const measuring = everything.loading || trimmed.loading;+ // Nothing picked, or nothing to gain from what is: either way the run would be a no-op, and a+ // button that erases without recourse must not be offered for one.+ const nothingToDo = measuring || sizes.selected <= 0;const ring: DonutRing = useMemo(() => ({id: "cleanup",@@ -47,27 +89,62 @@ export default function CleanupDialog({ show, onHidden, estimates }: CleanupDialthickness: DONUT_THICKNESS,segments: CLEANUP_ITEMS.map((item) => ({id: item.id,- value: estimates[item.id],- className: clsx(`cleanup-segment-${item.id}`, !picked[item.id] && "cleanup-segment-unpicked"),+ value: sizes.perItem[item.id],+ className: clsx(`cleanup-segment-${item.id}`, !options[item.id] && "cleanup-segment-unpicked"),tooltip: t(item.labelKey)}))- }), [ estimates, picked ]);-- const total = CLEANUP_ITEMS.reduce((sum, item) => sum + estimates[item.id], 0);- const selected = CLEANUP_ITEMS.reduce(- (sum, item) => sum + (picked[item.id] ? estimates[item.id] : 0), 0);-- return createPortal(+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }), [ sizes.perItem.deletedEntities, sizes.perItem.unusedAttachments, sizes.perItem.revisionSnapshots,+ options.deletedEntities, options.unusedAttachments, options.revisionSnapshots ]);++ // What the run was asked to do, held across the close: the operation starts once the dialog is+ // out of the way, by which time the state it was configured from is on its way out too.+ const pending = useRef<{ options: CleanupToolOptions, reclaimed: number } | null>(null);++ async function confirmAndClose() {+ if (!await dialogService.confirm(t("space_usage.cleanup_confirm"))) {+ return;+ }++ pending.current = { options, reclaimed: sizes.selected };+ setShown(false);+ }++ async function runPendingCleanup() {+ const work = pending.current;++ if (!work) {+ onFinished(null);+ return;+ }++ try {+ await runCleanup(work.options);+ toast.showMessage(t("space_usage.cleanup_done", { size: formatSize(work.reclaimed) }));+ } finally {+ // Settled either way: a run that failed part-way still changed the database, so whatever+ // was watching has to re-measure rather than keep the figures from before it. The+ // failure itself is already reported by the request layer.+ onFinished(work.reclaimed);+ }+ }++ return (<ModalclassName="space-usage-cleanup-dialog"title={t("space_usage.cleanup_title")}size="sm"minWidth={CLEANUP_DIALOG_MIN_WIDTH}- show={show}- onHidden={onHidden}+ show={shown}+ onHidden={() => void runPendingCleanup()}footer={<>- <Button text={t("space_usage.cleanup_cancel")} onClick={onHidden} />- <Button text={t("space_usage.cleanup_clean")} kind="primary" />+ <Button text={t("space_usage.cleanup_cancel")} onClick={() => setShown(false)} />+ <Button+ text={t("space_usage.cleanup_clean")}+ kind="primary"+ disabled={nothingToDo}+ onClick={() => void confirmAndClose()}+ /></>}stackable>@@ -75,10 +152,10 @@ export default function CleanupDialog({ show, onHidden, estimates }: CleanupDial<DonutChart rings={[ ring ]}><div className="cleanup-chart-center"><span className="cleanup-chart-caption">{t("space_usage.cleanup_estimated")}</span>- <span className="cleanup-chart-amount">{formatSize(selected)}</span>+ <span className="cleanup-chart-amount">{formatSize(sizes.selected)}</span><div className="cleanup-chart-rule" aria-hidden="true" /><span className="cleanup-chart-total">- {t("space_usage.cleanup_amount_of", { total: formatSize(total) })}+ {t("space_usage.cleanup_amount_of", { total: formatSize(sizes.total) })}</span></div></DonutChart>@@ -93,7 +170,7 @@ export default function CleanupDialog({ show, onHidden, estimates }: CleanupDialclassName={`cleanup-item cleanup-item-${item.id}`}// Only the revision item has any: they qualify how far its trimming goes, so// they are beside the point until it is actually being run.- subSectionsVisible={item.id === "revisionSnapshots" && picked.revisionSnapshots}+ subSectionsVisible={item.id === "revisionSnapshots" && options.revisionSnapshots}subSections={item.id === "revisionSnapshots" ? [<CardSection key="snapshots-to-keep" className="cleanup-item cleanup-item-nested"><span className="cleanup-item-title">{t("space_usage.cleanup_snapshots_to_keep")}</span>@@ -101,39 +178,35 @@ export default function CleanupDialog({ show, onHidden, estimates }: CleanupDialclassName="cleanup-item-number"type="number"min={0}- currentValue={String(snapshotsToKeep)}- onChange={(value) => setSnapshotsToKeep(Math.max(parseInt(value, 10) || 0, 0))}+ currentValue={String(options.snapshotsToKeep)}+ onChange={(value) => update({ snapshotsToKeep: Math.max(parseInt(value, 10) || 0, 0) })}/></CardSection>,<CardSection key="keep-named" className="cleanup-item cleanup-item-nested"><span className="cleanup-item-title">{t("space_usage.cleanup_keep_named")}</span>- <FormToggle currentValue={keepNamedSnapshots} onChange={setKeepNamedSnapshots} />+ <FormToggle+ currentValue={options.keepNamedSnapshots}+ onChange={(value) => update({ keepNamedSnapshots: value })}+ /></CardSection>] : undefined}><span className="cleanup-item-swatch" aria-hidden="true" /><span className="cleanup-item-title">{t(item.labelKey)}</span>- <span className="cleanup-item-size">{formatSize(estimates[item.id])}</span>+ <span className="cleanup-item-size">{formatSize(sizes.perItem[item.id])}</span><FormToggle- currentValue={picked[item.id]}- onChange={(value) => setPicked((current) => ({ ...current, [item.id]: value }))}+ currentValue={options[item.id]}+ onChange={(value) => update({ [item.id]: value })}/></CardSection>))}</Card>- </Modal>,- document.body+ </Modal>);}-/** The cleanup's items, in the order they are both listed and drawn. */-const CLEANUP_ITEMS = [- { id: "deletedEntities", labelKey: "space_usage.cleanup_deleted_entities" },- { id: "unusedAttachments", labelKey: "space_usage.cleanup_unused_attachments" },- { id: "revisionSnapshots", labelKey: "space_usage.cleanup_revision_snapshots" }-] as const;--type CleanupItemId = (typeof CLEANUP_ITEMS)[number]["id"];+/** Both figures come from the root, whose subtree is the whole visible database. */+const ROOT_USAGE_URL = "space-usage/note/root";/*** The width the dialog starts at, narrow on purpose: a short list of choices, read top to bottom@@ -149,18 +222,17 @@ const CLEANUP_DIALOG_MIN_WIDTH = "400px";const DONUT_RADIUS = 150;const DONUT_THICKNESS = 40;+/** Long enough to type a two-digit retention through without measuring the database twice. */+const ESTIMATE_DEBOUNCE_MS = 500;-/** Where the field starts when no limit is configured — see {@link defaultSnapshotsToKeep}. */-const FALLBACK_SNAPSHOTS_TO_KEEP = 4;+/** Trails `value` by `delay`, so a field being typed in does not fire a measurement per keystroke. */+function useDebouncedValue<T>(value: T, delay: number): T {+ const [ settled, setSettled ] = useState(value);-/**- * How many snapshots the field offers to keep: whatever the note revision limit is set to, so the- * cleanup starts out proposing the retention the user already chose. A limit of -1 keeps everything- * and 0 keeps none — neither is a useful opening offer for a one-off trim, so both fall back to a- * figure that plainly trims something without gutting the history.- */-function defaultSnapshotsToKeep(): number {- const configured = optionService.getInt("revisionSnapshotNumberLimit") ?? -1;+ useEffect(() => {+ const timer = setTimeout(() => setSettled(value), delay);+ return () => clearTimeout(timer);+ }, [ value, delay ]);- return configured > 0 ? configured : FALLBACK_SNAPSHOTS_TO_KEEP;+ return settled;}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.tsnew file mode 100644index 0000000000..9c824ca544--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.spec.ts@@ -0,0 +1,125 @@+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ getInt: vi.fn<(name: string) => number | null>(() => -1),+ post: vi.fn(async (_url: string, _body?: object) => {})+}));++vi.mock("../../../../../services/options", () => ({ default: { getInt: mocks.getInt } }));+vi.mock("../../../../../services/server", () => ({ default: { post: mocks.post } }));++import {+ type CleanupToolOptions,+ computeCleanupSizes,+ readCleanupOptions,+ runCleanup+} from "./cleanup_operation";++/** Only the fields the sizes are read from; the rest of the response is beside the point here. */+function usage(revisions: number, deleted = 0, unused = 0) {+ return {+ subtreeRevisionsContentSize: revisions,+ deletedNotes: { size: deleted, noteCount: 0, attachmentCount: 0 },+ unusedAttachments: { size: unused, attachmentCount: 0 }+ } as SpaceUsageNoteResponse;+}++const ALL_PICKED: CleanupToolOptions = {+ deletedEntities: true,+ unusedAttachments: true,+ revisionSnapshots: true,+ snapshotsToKeep: 3,+ keepNamedSnapshots: true+};++beforeEach(() => {+ mocks.getInt.mockReturnValue(-1);+ mocks.post.mockClear();+});++describe("readCleanupOptions", () => {+ it("picks nothing at all when the setting has never been written", () => {+ // The only safe reading of an absent answer, for an operation that deletes without recourse.+ for (const stored of [ undefined, null, {} ]) {+ expect(readCleanupOptions(stored)).toEqual({+ deletedEntities: false,+ unusedAttachments: false,+ revisionSnapshots: false,+ snapshotsToKeep: 4,+ keepNamedSnapshots: false+ });+ }+ });++ it("opens on the configured revision limit, where that limit trims anything", () => {+ mocks.getInt.mockReturnValue(7);+ expect(readCleanupOptions({}).snapshotsToKeep).toBe(7);++ // -1 keeps everything and 0 keeps none: neither is an opening offer for a one-off trim.+ for (const configured of [ -1, 0 ]) {+ mocks.getInt.mockReturnValue(configured);+ expect(readCleanupOptions({}).snapshotsToKeep).toBe(4);+ }+ });++ it("reads a stored answer back as it was left, zero retention included", () => {+ expect(readCleanupOptions({ revisionSnapshots: true, snapshotsToKeep: 0, keepNamedSnapshots: true }))+ .toEqual({+ deletedEntities: false,+ unusedAttachments: false,+ revisionSnapshots: true,+ snapshotsToKeep: 0,+ keepNamedSnapshots: true+ });++ // A retention that could not have been written by the dialog falls back rather than through.+ expect(readCleanupOptions({ snapshotsToKeep: -5 }).snapshotsToKeep).toBe(4);+ });+});++describe("computeCleanupSizes", () => {+ it("weighs the whole at the most aggressive trim, and the offer at the chosen one", () => {+ const sizes = computeCleanupSizes(usage(900, 100, 20), usage(300), ALL_PICKED);++ // Keeping snapshots can only take away from what erasing the history outright would free,+ // so the whole stays put while the item's own figure follows the settings.+ expect(sizes.total).toBe(900 + 100 + 20);+ expect(sizes.perItem).toEqual({ deletedEntities: 100, unusedAttachments: 20, revisionSnapshots: 300 });+ expect(sizes.selected).toBe(300 + 100 + 20);+ });++ it("counts only what is picked, and nothing at all before the measurements arrive", () => {+ const sizes = computeCleanupSizes(usage(900, 100, 20), usage(300),+ { ...ALL_PICKED, deletedEntities: false, revisionSnapshots: false });+ expect(sizes.selected).toBe(20);++ const unmeasured = computeCleanupSizes(null, null, ALL_PICKED);+ expect(unmeasured.total).toBe(0);+ expect(unmeasured.selected).toBe(0);+ });+});++describe("runCleanup", () => {+ it("erases what is picked, sweeping the orphaned blobs last", async () => {+ await runCleanup(ALL_PICKED);++ // Erasing revisions or attachments leaves the blobs they held; only the deleted-entity sweep+ // purges those, so it has to run after the two that create the orphans.+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([+ "revisions/erase-all-excess-revisions",+ "notes/erase-unused-attachments-now",+ "notes/erase-deleted-notes-now"+ ]);+ expect(mocks.post.mock.calls[0][1]).toEqual({ snapshotsToKeep: 3, keepNamedSnapshots: true });+ });++ it("asks for nothing that was not picked", async () => {+ await runCleanup({ ...ALL_PICKED, revisionSnapshots: false, deletedEntities: false });+ expect(mocks.post.mock.calls.map(([ url ]) => url)).toEqual([ "notes/erase-unused-attachments-now" ]);++ mocks.post.mockClear();+ await runCleanup({ ...ALL_PICKED, deletedEntities: false, unusedAttachments: false, revisionSnapshots: false });+ expect(mocks.post).not.toHaveBeenCalled();+ });+});diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.tsnew file mode 100644index 0000000000..cc32d4170a--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_operation.ts@@ -0,0 +1,123 @@+import type { SpaceUsageNoteResponse } from "@triliumnext/commons";++import optionService from "../../../../../services/options";+import server from "../../../../../services/server";++/** The cleanup's items, in the order they are both listed and drawn. */+export const CLEANUP_ITEMS = [+ { id: "deletedEntities", labelKey: "space_usage.cleanup_deleted_entities" },+ { id: "unusedAttachments", labelKey: "space_usage.cleanup_unused_attachments" },+ { id: "revisionSnapshots", labelKey: "space_usage.cleanup_revision_snapshots" }+] as const;++export type CleanupItemId = (typeof CLEANUP_ITEMS)[number]["id"];++/**+ * What the cleanup tool is set to erase, persisted as JSON in the `cleanupToolOptions` option so the+ * next run opens on the last answer rather than on a fresh set of defaults.+ */+export interface CleanupToolOptions {+ deletedEntities: boolean;+ unusedAttachments: boolean;+ revisionSnapshots: boolean;+ /** Revision snapshots kept per note; 0 erases the history outright. */+ snapshotsToKeep: number;+ keepNamedSnapshots: boolean;+}++/** Where the snapshots field starts when no useful limit is configured. */+export const FALLBACK_SNAPSHOTS_TO_KEEP = 4;++/**+ * Fills a stored setting out into the full set the dialog works with. Nothing is picked unless it+ * was picked before — an uninitialized setting erases nothing, which is the only safe reading of an+ * absent answer for an operation that deletes without recourse.+ */+export function readCleanupOptions(stored: Partial<CleanupToolOptions> | null | undefined): CleanupToolOptions {+ const snapshotsToKeep = stored?.snapshotsToKeep;++ return {+ deletedEntities: stored?.deletedEntities === true,+ unusedAttachments: stored?.unusedAttachments === true,+ revisionSnapshots: stored?.revisionSnapshots === true,+ snapshotsToKeep: Number.isInteger(snapshotsToKeep) && Number(snapshotsToKeep) >= 0+ ? Number(snapshotsToKeep)+ : defaultSnapshotsToKeep(),+ keepNamedSnapshots: stored?.keepNamedSnapshots === true+ };+}++/**+ * How many snapshots the field offers to keep before anything has been stored: whatever the note+ * revision limit is set to, so the cleanup opens proposing the retention the user already chose. A+ * limit of -1 keeps everything and 0 keeps none — neither is a useful opening offer for a one-off+ * trim, so both fall back to a figure that plainly trims something without gutting the history.+ */+export function defaultSnapshotsToKeep(): number {+ const configured = optionService.getInt("revisionSnapshotNumberLimit") ?? -1;++ return configured > 0 ? configured : FALLBACK_SNAPSHOTS_TO_KEEP;+}++export interface CleanupSizes {+ /** What erasing each item would free, the revisions measured as the settings would trim them. */+ perItem: Record<CleanupItemId, number>;+ /** Everything reclaimable, the revisions measured at their most aggressive — see below. */+ total: number;+ /** What the picked items would free. */+ selected: number;+}++/**+ * The figures the dialog reads out, from the root's usage measured two ways.+ *+ * The whole is measured with the history erased outright, because that is the most any of these+ * settings can ever reclaim: keeping snapshots only takes away from it. Anything else would leave+ * the reading growing when the user asks to keep *less*, which is not what "of" can mean.+ *+ * @param everything root usage measured at `snapshotsToKeep=0`.+ * @param trimmed root usage measured as the current settings would trim it; the same reading as+ * {@link everything} whenever those settings are the aggressive ones.+ */+export function computeCleanupSizes(+ everything: SpaceUsageNoteResponse | null,+ trimmed: SpaceUsageNoteResponse | null,+ options: CleanupToolOptions+): CleanupSizes {+ const perItem: Record<CleanupItemId, number> = {+ deletedEntities: everything?.deletedNotes?.size ?? 0,+ unusedAttachments: everything?.unusedAttachments?.size ?? 0,+ revisionSnapshots: trimmed?.subtreeRevisionsContentSize ?? 0+ };++ return {+ perItem,+ total: perItem.deletedEntities + perItem.unusedAttachments + (everything?.subtreeRevisionsContentSize ?? 0),+ selected: CLEANUP_ITEMS.reduce((sum, item) => sum + (options[item.id] ? perItem[item.id] : 0), 0)+ };+}++/**+ * Erases what the settings ask for, one endpoint per item.+ *+ * Ordered rather than issued at once, and deliberately: erasing revisions or attachments deletes the+ * rows but leaves the blobs they held, which only the deleted-entity sweep purges. Running that last+ * is therefore what actually hands the space back — and when it is not picked, the blobs the other+ * two orphan wait for the hourly cleanup instead.+ */+export async function runCleanup(options: CleanupToolOptions): Promise<void> {+ if (options.revisionSnapshots) {+ await server.post("revisions/erase-all-excess-revisions", {+ snapshotsToKeep: options.snapshotsToKeep,+ keepNamedSnapshots: options.keepNamedSnapshots+ });+ }++ if (options.unusedAttachments) {+ await server.post("notes/erase-unused-attachments-now");+ }++ if (options.deletedEntities) {+ await server.post("notes/erase-deleted-notes-now");+ }+}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.tsxindex 6ad2d8ac24..69e052b21d 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@@ -11,7 +11,7 @@ import SegmentedChoice from "../../../../react/SegmentedChoice";import OptionsPageHeader from "../../components/OptionsPageHeader";import type { ContentManagerSectionProps } from "../index";import Browse from "./browse";-import CleanupDialog from "./cleanup_dialog";+import { showCleanupDialog } from "./cleanup_dialog";import Overview from "./overview";import SpaceUsagePlaceholder from "./placeholder";import { useSpaceUsageFetch } from "./use_space_usage_fetch";@@ -32,7 +32,6 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro// Browse measures its own note through a separate request, which this component would not// otherwise know about; without it the button would free up while that reading was still running.const [ browseLoading, setBrowseLoading ] = useState(false);- const [ cleanupShown, setCleanupShown ] = useState(false);// 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" ]);@@ -56,12 +55,17 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionProcurrentValue={view}onChange={setView}/>- {/* Boxicons ships no broom; the eraser is what the dialog does anyway. */}+ {/* Boxicons ships no broom; the eraser is what the dialog does anyway. The+ charts re-measure once it is done, having just been made wrong by it. */}<ActionButtonclassName="space-usage-cleanup"icon="bx bx-eraser"text={t("space_usage.cleanup_title")}- onClick={() => setCleanupShown(true)}+ onClick={() => void showCleanupDialog().then((reclaimed) => {+ if (reclaimed !== null) {+ refresh();+ }+ })}/>{/* Measuring is expensive, so a reading is taken when asked for rather thankept live — and the button stays out while one is being taken. */}@@ -75,21 +79,6 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro</div>} />- {/* Kept out of the DOM until asked for: it is a modal over this page, not part of it.- The revision figure is still a placeholder — estimating it takes a request carrying- the retention picked in the dialog, which is the step after this one. */}- {cleanupShown && (- <CleanupDialog- show={cleanupShown}- onHidden={() => setCleanupShown(false)}- estimates={{- deletedEntities: overview?.deletedNotes.size ?? 0,- unusedAttachments: overview?.unusedAttachments.size ?? 0,- revisionSnapshots: overview?.content.revisionsSize ?? 0- }}- />- )}-{view === "browse" && (<Browsepath={browsePath}diff --git a/packages/commons/src/lib/options_interface.ts b/packages/commons/src/lib/options_interface.tsindex 3d76666416..f709799646 100644--- a/packages/commons/src/lib/options_interface.ts+++ b/packages/commons/src/lib/options_interface.ts@@ -83,6 +83,8 @@ export interface OptionDefinitions extends KeyboardShortcutsOptions<KeyboardActitextNoteEditorType: string;layoutOrientation: string;allowedHtmlTags: string;+ /** JSON: what the Content Manager's cleanup tool was last set to erase — see `CleanupToolOptions`. */+ cleanupToolOptions: string;documentId: string;documentSecret: string;passwordVerificationHash: string;diff --git a/packages/trilium-core/src/routes/api/options.ts b/packages/trilium-core/src/routes/api/options.tsindex d7a26e0821..7949819618 100644--- a/packages/trilium-core/src/routes/api/options.ts+++ b/packages/trilium-core/src/routes/api/options.ts@@ -122,6 +122,7 @@ const ALLOWED_OPTIONS = new Set<OptionNames>(["layoutOrientation","backgroundEffects","allowedHtmlTags",+ "cleanupToolOptions","searchEnableFuzzyMatching","searchAutocompleteFuzzy","redirectBareDomain",diff --git a/packages/trilium-core/src/services/options_init.ts b/packages/trilium-core/src/services/options_init.tsindex 039aeba57b..68733c420a 100644--- a/packages/trilium-core/src/services/options_init.ts+++ b/packages/trilium-core/src/services/options_init.ts@@ -296,6 +296,10 @@ const defaultOptions: DefaultOption[] = [isSynced: true},+ // Empty rather than a set of defaults: nothing the cleanup tool erases is picked until the user+ // picks it, so an uninitialized setting has to mean "nothing selected".+ { name: "cleanupToolOptions", value: "{}", isSynced: true },+// Share settings{ name: "redirectBareDomain", value: "false", isSynced: true },{ name: "showLoginInShareTheme", value: "false", isSynced: true },