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/options/database: add space usage and cleanup commands
Adorian Doran8b72a5899cfd
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex d3455829e3..017b14e7ec 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -1758,6 +1758,11 @@"info_attachments_other": "{{count}} attachments","info_size": "Size","maintenance": "Maintenance",+ "analyze_space_usage": "Analyze space usage",+ "analyze_space_usage_description": "Identify which notes take up the most space, and get a clearer picture of how large your notes are.",+ "analyze_space_usage_button": "Analyze",+ "cleanup": "Perform a cleanup",+ "cleanup_description": "Erase deleted notes and attachments, trim revision snapshots and compress images to keep the database slim.","start_over_description": "Switch to a new blank database, start again syncing with a new server or restore a backup. You will be prompted to backup your data before discarding the existing data.","start_over": "Start over","start_over_confirm": "Trilium will go back to the setup screen, where you can start a new knowledge base, restore a backup or sync from another device. You will be offered a backup of your current data first, and nothing is deleted until you choose one of those. Continue?",diff --git a/apps/client/src/widgets/type_widgets/options/database.spec.tsx b/apps/client/src/widgets/type_widgets/options/database.spec.tsxindex 61c0908749..064d5ad21f 100644--- a/apps/client/src/widgets/type_widgets/options/database.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.spec.tsx@@ -59,6 +59,22 @@ vi.mock("../../../services/toast", () => ({ default: toast }));// The page header renders the note's own title, which needs a note context this spec has no use for.vi.mock("./components/OptionsPageHeader", () => ({ default: () => null }));+// Maintenance hands over to the Content Manager, which needs a note context to navigate with. Only+// that hook is replaced: the card rows still need the rest of the module, ID generation included.+const noteContext = vi.hoisted(() => ({ setNote: vi.fn(async () => {}) }));+vi.mock("../../react/hooks", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../react/hooks")>()),+ useNoteContext: () => ({ noteContext })+}));++const contentManager = vi.hoisted(() => ({ requestContentManagerSection: vi.fn() }));+vi.mock("./content_manager", () => contentManager);++// Opening the real dialog would measure the whole database and draw its charts; what this page+// answers for is that it opens one, and what it does with the answer.+const cleanup = vi.hoisted(() => ({ showCleanupDialog: vi.fn(async () => 1234 as number | null) }));+vi.mock("./content_manager/space_usage/cleanup_dialog", () => cleanup);+import DatabaseSettings from "./database";let container: HTMLDivElement;@@ -86,6 +102,9 @@ beforeEach(() => {setupMode.isStartOverPending.mockReset().mockResolvedValue(false);setupMode.cancelStartOver.mockReset().mockResolvedValue(undefined);failing.info = false;+ noteContext.setNote.mockClear();+ contentManager.requestContentManagerSection.mockClear();+ cleanup.showCleanupDialog.mockReset().mockResolvedValue(1234);server.get.mockClear();server.post.mockClear();server.postWithTimeout.mockClear();@@ -146,6 +165,37 @@ describe("what the database is", () => {});describe("database maintenance", () => {+ it("hands the two tools over to the Content Manager rather than repeating them", async () => {+ renderPage();+ await settle();++ button("analyze-space-usage-button")?.click();+ await settle();++ // The Content Manager opens on Active Content unless asked otherwise, and the page is+ // reached through this page's own note context — Options can itself be a dialog.+ expect(contentManager.requestContentManagerSection).toHaveBeenCalledWith("spaceUsage");+ expect(noteContext.setNote).toHaveBeenCalledWith("_optionsContentManager", { keepActiveDialog: true });++ button("cleanup-button")?.click();+ await settle();++ expect(cleanup.showCleanupDialog).toHaveBeenCalled();+ // Erasing changes what the database holds, so the card above states it again.+ expect(server.get.mock.calls.filter(([ url ]) => url === "database/info")).toHaveLength(2);+ });++ it("leaves the figures alone when the cleanup was called off", async () => {+ cleanup.showCleanupDialog.mockResolvedValue(null);+ renderPage();+ await settle();++ button("cleanup-button")?.click();+ await settle();++ expect(server.get.mock.calls.filter(([ url ]) => url === "database/info")).toHaveLength(1);+ });+it("runs each check against its own endpoint, and says how it went", async () => {renderPage();await settle();diff --git a/apps/client/src/widgets/type_widgets/options/database.tsx b/apps/client/src/widgets/type_widgets/options/database.tsxindex 7ffb70438e..ab7e0cabae 100644--- a/apps/client/src/widgets/type_widgets/options/database.tsx+++ b/apps/client/src/widgets/type_widgets/options/database.tsx@@ -24,9 +24,12 @@ import Admonition from "../../react/Admonition";import Button from "../../react/Button";import { Card, CardOption } from "../../react/Card";import DirectoryLink from "../../react/DirectoryLink";+import { useNoteContext } from "../../react/hooks";import { useFetch } from "../../react/use_fetch";import DatabaseFileList from "./components/DatabaseFileList";import OptionsPageHeader from "./components/OptionsPageHeader";+import { requestContentManagerSection } from "./content_manager";+import { showCleanupDialog } from "./content_manager/space_usage/cleanup_dialog";/*** What can be done to the knowledge base as a whole, rather than to anything inside it: keeping the@@ -37,8 +40,8 @@ import OptionsPageHeader from "./components/OptionsPageHeader";*/export default function DatabaseSettings() {const startOverState = useStartOver();- // Compacting is the one action on this page that changes what the card above it states, so the- // figures are read again once a rebuild has finished rather than left saying what they did.+ // Maintenance is what changes the figures the card above it states — a rebuild its size, a+ // cleanup what it holds — so they are read again afterwards rather than left as they were.const [ infoToken, setInfoToken ] = useState(0);const refreshInfo = useCallback(() => setInfoToken((token) => token + 1), []);@@ -64,7 +67,7 @@ export default function DatabaseSettings() {)}<DatabaseInfo refreshToken={infoToken} />- <MaintenanceOptions onDatabaseCompacted={refreshInfo} />+ <MaintenanceOptions onDatabaseChanged={refreshInfo} /><AnonymizationOptions /><StartOverOption state={startOverState} /></>@@ -118,11 +121,58 @@ function DatabaseInfo({ refreshToken }: { refreshToken: number }) {);}-/** Checks and repairs that act on the database file itself, rather than on what is kept in it. */-function MaintenanceOptions({ onDatabaseCompacted }: { onDatabaseCompacted: () => void }) {+/**+ * Keeping the database in good order: finding out what it is spent on, taking back what is no longer+ * needed, and the checks and repairs that act on the file itself rather than on what is kept in it.+ *+ * The first two hand over to the tools that do the work — the Content Manager's space usage section+ * and its cleanup dialog — which is why they are named here rather than duplicated.+ */+function MaintenanceOptions({ onDatabaseChanged }: { onDatabaseChanged: () => void }) {+ const { noteContext } = useNoteContext();+return (<div className="options-section database-maintenance"><Card heading={t("database.maintenance")}>+ <CardOption+ label={t("database.analyze_space_usage")}+ description={t("database.analyze_space_usage_description")}+ >+ <Button+ name="analyze-space-usage-button"+ text={t("database.analyze_space_usage_button")}+ size="micro"+ onClick={() => {+ // The Content Manager opens on Active Content unless asked otherwise,+ // and navigating by hand rather than by link is what lets us ask first.+ requestContentManagerSection("spaceUsage");+ // Kept in whichever context this page is shown in — the settings dialog+ // holds a note context of its own, outside the tab manager.+ void noteContext?.setNote("_optionsContentManager", { keepActiveDialog: true });+ }}+ />+ </CardOption>++ <CardOption+ label={t("database.cleanup")}+ description={t("database.cleanup_description")}+ >+ {/* Named after the tool it opens, so the button and the dialog's own heading+ cannot come to say different things. */}+ <Button+ name="cleanup-button"+ text={t("space_usage.cleanup_title")}+ size="micro"+ onClick={() => void showCleanupDialog().then((reclaimed) => {+ // Erasing frees pages inside the file rather than shrinking it, so what+ // the card above has to re-read is what the database holds.+ if (reclaimed !== null) {+ onDatabaseChanged();+ }+ })}+ />+ </CardOption>+<CardOptionlabel={t("database_integrity_check.check_integrity_label")}description={t("database_integrity_check.check_integrity_description")}@@ -157,7 +207,7 @@ function MaintenanceOptions({ onDatabaseCompacted }: { onDatabaseCompacted: () =size="micro"onClick={async () => {await vacuumDatabase();- onDatabaseCompacted();+ onDatabaseChanged();}}/></CardOption>