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: implement the UI
Adorian Doran7e853c8e86d7
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9ad876fc74..b6f6327f51 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2879,7 +2879,17 @@"menu_show_details": "Show details","menu_erase_deleted": "Erase deleted data","erase_deleted_message": "Deleted data has been erased.",- "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. Do you want to set the limit now?"+ "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. Do you want to set the limit now?",+ "cleanup_title": "Clean up",+ "cleanup_estimated": "Estimated saving",+ "cleanup_amount_of": "of {{total}}",+ "cleanup_deleted_entities": "Erase deleted notes and attachments",+ "cleanup_unused_attachments": "Erase unused attachments",+ "cleanup_revision_snapshots": "Erase revision snapshots",+ "cleanup_snapshots_to_keep": "Revision snapshots to keep",+ "cleanup_keep_named": "Keep named revisions",+ "cleanup_cancel": "Cancel",+ "cleanup_clean": "Clean"},"note_language": {"not_set": "No language set",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.cssnew file mode 100644index 0000000000..b4ff623127--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.css@@ -0,0 +1,149 @@+.modal.space-usage-cleanup-dialog {+ /* One per item, shared by its ring segment and its legend swatch: a legend is only a legend+ while the two are the same paint. Mixed into the theme surface like the browse donut's+ semantic colors, but at a higher share — three colors have to be told apart here, and the+ swatches are a few pixels wide. */+ --cleanup-deleted-color: color-mix(in srgb, var(--accented-background-color) 55%, #d9645b 45%);+ --cleanup-attachments-color: color-mix(in srgb, var(--accented-background-color) 55%, #d9a93d 45%);+ --cleanup-revisions-color: color-mix(in srgb, var(--accented-background-color) 55%, #8f959c 45%);++ /* Sized by its content rather than to the floor the component sets: no item title wraps, so a+ long one has to widen the dialog. Capped at the viewport, past which there is nowhere to grow. */+ .modal-dialog {+ width: fit-content;+ max-width: 100%;+ }++ .modal-body {+ display: flex;+ flex-direction: column;+ gap: 16px;+ }++ /* The largest square that fits inside the ring's hole, as a share of the chart's width. The hole+ is the ring's inner edge — radius 150 less half of its 40 thickness, so 260 across a 420-unit+ viewBox, or 61.9% — and a square inscribed in a circle has a side of that over √2. Keep in+ step with DONUT_RADIUS and DONUT_THICKNESS in the component. */+ --cleanup-donut-hole: 43.8%;+++ /* Drives the whole chart: the ring is laid out in viewBox units against a square aspect, so its+ radius and thickness scale with this rather than being sized here. */+ .cleanup-chart {+ height: 270px;+ }++ /* Held to the hole rather than to the chart: the primitive centers its children over the whole+ square, where a long amount would otherwise run out across the ring and past it. Whatever+ still will not fit wraps, and is clipped only as a last resort. */+ .cleanup-chart-center {+ display: flex;+ flex-direction: column;+ max-width: var(--cleanup-donut-hole);+ max-height: var(--cleanup-donut-hole);+ gap: 2px;+ overflow: hidden;+ overflow-wrap: anywhere;+ }++ .cleanup-chart-caption {+ color: var(--muted-text-color);+ font-size: 0.75em;+ }++ /* What the picked items would free — the figure the reading is about, so it carries the weight.+ A figure and its unit are one word, so neither line ever breaks between them. */+ .cleanup-chart-amount {+ font-size: 1.35em;+ font-weight: 600;+ white-space: nowrap;+ }++ /* Spans the reading rather than the text on either side of it: the children of this column+ stretch, so the rule is as wide as the widest line and reads as dividing them. */+ .cleanup-chart-rule {+ border-top: 1px solid var(--main-border-color);+ }++ /* The whole it is a part of, quieted so the figure above stays the one being read. */+ .cleanup-chart-total {+ color: var(--muted-text-color);+ font-size: 0.85em;+ white-space: nowrap;+ }++ .cleanup-segment-deletedEntities {+ --donut-segment-color: var(--cleanup-deleted-color);+ }++ .cleanup-segment-unusedAttachments {+ --donut-segment-color: var(--cleanup-attachments-color);+ }++ .cleanup-segment-revisionSnapshots {+ --donut-segment-color: var(--cleanup-revisions-color);+ }++ /* Left in place rather than removed: the ring stands for everything reclaimable, so an unpicked+ item keeps its share of it and only stops being claimed. */+ .cleanup-segment-unpicked {+ opacity: 0.25;+ }++ .cleanup-item {+ display: flex;+ align-items: center;+ gap: 10px;+ }++ .cleanup-item-swatch {+ flex: 0 0 auto;+ width: 4px;+ height: 1.2em;+ border-radius: 2px;+ background: var(--cleanup-swatch-color);+ }++ .cleanup-swatch-deletedEntities {+ --cleanup-swatch-color: var(--cleanup-deleted-color);+ }++ .cleanup-swatch-unusedAttachments {+ --cleanup-swatch-color: var(--cleanup-attachments-color);+ }++ .cleanup-swatch-revisionSnapshots {+ --cleanup-swatch-color: var(--cleanup-revisions-color);+ }++ /* Takes the slack, so the size and the switch stay at the trailing edge whatever the title —+ and never gives any back: an unwrapped title is what widens the dialog. */+ .cleanup-item-title {+ flex: 1 0 auto;+ white-space: nowrap;+ }++ .cleanup-item-size {+ flex: 0 0 auto;+ color: var(--muted-text-color);+ font-weight: 600;+ white-space: nowrap;+ }++ /* Indented by the card itself; the sub-rows carry no swatch, so their titles line up with the+ titles above rather than with the swatches. */+ .cleanup-item-nested .cleanup-item-title {+ color: var(--muted-text-color);+ }++ .cleanup-item-number {+ flex: 0 0 auto;+ width: 5em;+ text-align: right;+ }++ /* The switch brings its own label slot, unused here — the row's own title names the item. */+ .cleanup-item .switch-widget {+ flex: 0 0 auto;+ }+}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.tsxnew file mode 100644index 0000000000..300cbea0ed--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.spec.tsx@@ -0,0 +1,158 @@+import { type ComponentChildren, render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import { t } from "../../../../../services/i18n";+import { formatSize } from "../../../../../services/utils";++const mocks = vi.hoisted(() => ({+ getInt: vi.fn<(name: string) => number | null>(() => -1)+}));++vi.mock("../../../../../services/options", () => ({+ default: { getInt: mocks.getInt }+}));++// 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+ )+}));++import CleanupDialog, { type CleanupEstimates } from "./cleanup_dialog";++const ESTIMATES: CleanupEstimates = {+ deletedEntities: 3000,+ unusedAttachments: 2000,+ revisionSnapshots: 5000+};++let container: HTMLDivElement | undefined;++function renderDialog(estimates = ESTIMATES) {+ container = document.body.appendChild(document.createElement("div"));+ render(<CleanupDialog show onHidden={() => {}} estimates={estimates} />, container);+ return container;+}++/** 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"));+}++function titlesOf(sections: HTMLElement[]) {+ return sections.map((section) => section.querySelector(".cleanup-item-title")?.textContent);+}++function textOf(selector: string) {+ return document.body.querySelector<HTMLElement>(selector)?.textContent ?? "";+}++/**+ * 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.+ */+async function toggleRow(index: number) {+ const toggle = rows()[index]?.querySelector<HTMLInputElement>(".switch-toggle");+ await act(async () => {+ toggle?.dispatchEvent(new Event("input", { bubbles: true }));+ });+}++describe("CleanupDialog", () => {+ afterEach(() => {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+ mocks.getInt.mockReturnValue(-1);+ });++ it("lists every item with its own swatch, its estimate and a switch", () => {+ renderDialog();++ // 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") ?? ""+ ]);++ const sizes = rows().map((row) => row.querySelector(".cleanup-item-size")?.textContent);+ expect(sizes).toEqual([ formatSize(3000), formatSize(2000), formatSize(5000) ]);++ // A swatch per row, each its own color, so the list doubles as the ring's legend.+ expect(rows().map((row) => row.querySelector(".cleanup-item-swatch")?.className)).toEqual([+ "cleanup-item-swatch cleanup-swatch-deletedEntities",+ "cleanup-item-swatch cleanup-swatch-unusedAttachments",+ "cleanup-item-swatch cleanup-swatch-revisionSnapshots"+ ]);+ expect(rows().every((row) => row.querySelector(".switch-toggle"))).toBe(true);+ });++ it("reads the picked total against the whole, which unpicking an item does not move", async () => {+ renderDialog();++ expect(textOf(".cleanup-chart-caption")).toBe(t("space_usage.cleanup_estimated") ?? "");+ expect(textOf(".cleanup-chart-amount")).toBe(formatSize(10000));+ expect(textOf(".cleanup-chart-total")).toBe(+ t("space_usage.cleanup_amount_of", { total: formatSize(10000) }) ?? "");++ // 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) }) ?? "");+ });++ it("keeps an unpicked item's arc on the ring, drawn muted rather than dropped", async () => {+ renderDialog();++ 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 toggleRow(1);+ expect(arcs().length).toBe(3);+ expect(arcs().filter((className) => className.includes("cleanup-segment-unpicked")).length).toBe(1);+ });++ it("qualifies the revision trimming only while it is actually being run", async () => {+ renderDialog();++ expect(titlesOf(nestedRows())).toEqual([+ t("space_usage.cleanup_snapshots_to_keep") ?? "",+ t("space_usage.cleanup_keep_named") ?? ""+ ]);++ // The revisions row is the last of the three; unpicking it takes its qualifiers with it.+ await toggleRow(2);+ expect(nestedRows()).toEqual([]);+ });++ 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;++ // No limit configured: -1 keeps everything, which is no offer at all for a one-off trim.+ renderDialog();+ expect(keptField()).toBe("4");++ 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);+ }+ });+});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.tsxnew file mode 100644index 0000000000..9277f503f5--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/cleanup_dialog.tsx@@ -0,0 +1,164 @@+import "./cleanup_dialog.css";++import clsx from "clsx";+import { createPortal } from "preact/compat";+import { useMemo, useState } from "preact/hooks";++import { t } from "../../../../../services/i18n";+import optionService from "../../../../../services/options";+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 Modal from "../../../../react/Modal";++/** 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;+}++/**+ * What the cleanup can erase, picked item by item, with the space each would free drawn as one ring.+ *+ * The ring stands for everything reclaimable rather than for the current selection: every item keeps+ * its arc whether or not it is picked, unpicked ones drawn muted, so toggling one re-colors the+ * 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);++ const ring: DonutRing = useMemo(() => ({+ id: "cleanup",+ radius: DONUT_RADIUS,+ thickness: 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"),+ 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(+ <Modal+ className="space-usage-cleanup-dialog"+ title={t("space_usage.cleanup_title")}+ size="sm"+ minWidth={CLEANUP_DIALOG_MIN_WIDTH}+ show={show}+ onHidden={onHidden}+ footer={<>+ <Button text={t("space_usage.cleanup_cancel")} onClick={onHidden} />+ <Button text={t("space_usage.cleanup_clean")} kind="primary" />+ </>}+ stackable+ >+ <div className="cleanup-chart">+ <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>+ <div className="cleanup-chart-rule" aria-hidden="true" />+ <span className="cleanup-chart-total">+ {t("space_usage.cleanup_amount_of", { total: formatSize(total) })}+ </span>+ </div>+ </DonutChart>+ </div>++ <Card className="cleanup-items">+ {CLEANUP_ITEMS.map((item) => (+ <CardSection+ key={item.id}+ className="cleanup-item"+ // 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}+ 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>+ <FormTextBox+ className="cleanup-item-number"+ type="number"+ min={0}+ currentValue={String(snapshotsToKeep)}+ onChange={(value) => setSnapshotsToKeep(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} />+ </CardSection>+ ] : undefined}+ >+ <span className={`cleanup-item-swatch cleanup-swatch-${item.id}`} aria-hidden="true" />+ <span className="cleanup-item-title">{t(item.labelKey)}</span>+ <span className="cleanup-item-size">{formatSize(estimates[item.id])}</span>+ <FormToggle+ currentValue={picked[item.id]}+ onChange={(value) => setPicked((current) => ({ ...current, [item.id]: value }))}+ />+ </CardSection>+ ))}+ </Card>+ </Modal>,+ document.body+ );+}++/** 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"];++/**+ * The width the dialog starts at, narrow on purpose: a short list of choices, read top to bottom+ * rather than scanned across. A floor rather than a size — item titles never wrap, so a long one+ * widens the dialog instead of folding onto a second line (see the stylesheet).+ */+const CLEANUP_DIALOG_MIN_WIDTH = "400px";++/**+ * The ring's geometry, in the chart's own viewBox units. The stylesheet sizes the center labels to+ * the hole these leave, so changing either means revisiting `--cleanup-donut-hole` there.+ */+const DONUT_RADIUS = 150;+const DONUT_THICKNESS = 40;+++/** Where the field starts when no limit is configured — see {@link defaultSnapshotsToKeep}. */+const FALLBACK_SNAPSHOTS_TO_KEEP = 4;++/**+ * 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;++ return configured > 0 ? configured : FALLBACK_SNAPSHOTS_TO_KEEP;+}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 4013356f84..6ad2d8ac24 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,6 +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 Overview from "./overview";import SpaceUsagePlaceholder from "./placeholder";import { useSpaceUsageFetch } from "./use_space_usage_fetch";@@ -31,6 +32,7 @@ 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" ]);@@ -54,6 +56,13 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionProcurrentValue={view}onChange={setView}/>+ {/* Boxicons ships no broom; the eraser is what the dialog does anyway. */}+ <ActionButton+ className="space-usage-cleanup"+ icon="bx bx-eraser"+ text={t("space_usage.cleanup_title")}+ onClick={() => setCleanupShown(true)}+ />{/* Measuring is expensive, so a reading is taken when asked for rather thankept live — and the button stays out while one is being taken. */}<ActionButton@@ -66,6 +75,21 @@ 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}