Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager/space usage: fix some issues

Adorian Doranc8d451686a8b
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 4729038def..6e59b94bd9 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2857,7 +2857,7 @@
"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",
- "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."
+ "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?"
},
"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 6a2a46af47..d45d3e242d 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
@@ -22,7 +22,8 @@ const mocks = vi.hoisted(() => ({
post: vi.fn(async (..._args: unknown[]) => undefined),
showMessage: vi.fn(),
revisionLimit: 0 as number | null,
- configureLimit: vi.fn()
+ // Answers like the real one: true when the user accepts the box, false when they dismiss it.
+ confirm: vi.fn(async (..._args: unknown[]) => true)
}));
vi.mock("../../../../../menus/context_menu", () => ({
@@ -61,6 +62,10 @@ vi.mock("../../../../../services/options", () => ({
default: { getInt: () => mocks.revisionLimit }
}));
+vi.mock("../../../../../services/dialog", () => ({
+ default: { confirm: (...args: unknown[]) => mocks.confirm(...args) }
+}));
+
vi.mock("../../../../../components/app_context", () => ({
default: {
triggerCommand: mocks.triggerCommand,
@@ -248,7 +253,7 @@ describe("openDeletedNotesContextMenu", () => {
describe("openRevisionsContextMenu", () => {
async function openRevisionsFor(revisionLimit: number | null) {
mocks.revisionLimit = revisionLimit;
- await openRevisionsContextMenu(contextMenuEvent(), mocks.contentChanged, mocks.configureLimit);
+ await openRevisionsContextMenu(contextMenuEvent(), mocks.contentChanged);
}
it("trims the excess snapshots and asks for a fresh reading, once a limit is set", async () => {
@@ -258,7 +263,7 @@ describe("openRevisionsContextMenu", () => {
invoke(ERASE);
expect(mocks.post).toHaveBeenCalledWith("revisions/erase-all-excess-revisions");
- expect(mocks.configureLimit).not.toHaveBeenCalled();
+ expect(mocks.triggerCommand).not.toHaveBeenCalled();
await vi.waitFor(() => expect(mocks.contentChanged).toHaveBeenCalledTimes(1));
expect(mocks.showMessage).toHaveBeenCalled();
@@ -268,20 +273,52 @@ describe("openRevisionsContextMenu", () => {
await openRevisionsFor(0);
invoke(ERASE);
expect(mocks.post).toHaveBeenCalledTimes(2);
- expect(mocks.configureLimit).not.toHaveBeenCalled();
+ expect(mocks.triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("lands on the limit field itself, cursor in it, once the settings page has rendered", async () => {
+ // Rendered late on purpose: the page comes up after the command asking for it, which is
+ // what the reveal has to wait out.
+ const field = document.createElement("input");
+ field.name = "revision-snapshot-number-limit";
+ field.scrollIntoView = vi.fn();
+ setTimeout(() => document.body.appendChild(field), 60);
+
+ await openRevisionsFor(-1);
+ invoke(ERASE);
+
+ await vi.waitFor(() => expect(document.activeElement).toBe(field));
+ expect(field.scrollIntoView).toHaveBeenCalled();
+
+ field.remove();
});
- it("offers the limit instead of an erasure that would drop nothing, when there is none", async () => {
+ it("offers the limit setting 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);
+ await vi.waitFor(() => expect(mocks.confirm).toHaveBeenCalled());
}
- expect(mocks.configureLimit).toHaveBeenCalledTimes(2);
expect(mocks.post).not.toHaveBeenCalled();
expect(mocks.contentChanged).not.toHaveBeenCalled();
+ // Accepted: lands on the card holding the limit, in the settings dialog already open.
+ expect(mocks.triggerCommand)
+ .toHaveBeenCalledWith("showOptions", { section: "_optionsOther" });
+ });
+
+ it("leaves the map where it is when the box is dismissed", async () => {
+ mocks.confirm.mockResolvedValueOnce(false);
+ await openRevisionsFor(-1);
+
+ invoke(ERASE);
+ await vi.waitFor(() => expect(mocks.confirm).toHaveBeenCalledTimes(1));
+
+ // Nothing erased and nowhere else to be: someone who backs out of the box stays on the map.
+ expect(mocks.triggerCommand).not.toHaveBeenCalled();
+ expect(mocks.post).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 4000a48e6b..3b4955ef12 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
@@ -5,6 +5,7 @@ import contextMenu, {
type MenuItem
} from "../../../../../menus/context_menu";
import branches from "../../../../../services/branches";
+import dialog from "../../../../../services/dialog";
import froca from "../../../../../services/froca";
import { t } from "../../../../../services/i18n";
import { downloadFileNote } from "../../../../../services/open";
@@ -171,13 +172,12 @@ export async function openDeletedNotesContextMenu(
* 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.
+ * shows the setting instead, by taking the settings dialog it is already inside to the card that
+ * holds it, the way the deleted-notes view offers its own retention settings.
*/
export async function openRevisionsContextMenu(
event: ContextMenuEvent,
- onContentChanged: ContentChangedHandler,
- onConfigureLimit: () => void
+ onContentChanged: ContentChangedHandler
) {
event.preventDefault();
event.stopPropagation();
@@ -193,7 +193,15 @@ export async function openRevisionsContextMenu(
// 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();
+ // Offered rather than done: the card lives on another settings page, and being
+ // taken off the map is only worth it for someone who means to set the limit.
+ void dialog.confirm(t("space_usage.revisions_limit_required"))
+ .then(async (confirmed) => {
+ if (confirmed) {
+ await appContext.triggerCommand("showOptions", { section: "_optionsOther" });
+ await revealRevisionLimitField();
+ }
+ });
return;
}
@@ -227,3 +235,28 @@ export function openNoteInNewTab(noteId: string) {
function isDownloadable(note: FNote) {
return note.type === "file" || note.type === "image";
}
+
+/**
+ * Brings the snapshot limit field into view with the cursor in it, once the settings page holding it
+ * has rendered: someone who accepted being taken there should land on the field to fill in, not on a
+ * page to search through.
+ *
+ * The field is found by its name, which the settings row keeps as given (its `id` carries a random
+ * suffix, being unique per mount). Awaited in short steps because the page renders after the command
+ * that asks for it, and given up on quietly — a page that never came is not worth an error.
+ */
+async function revealRevisionLimitField() {
+ for (let attempt = 0; attempt < 20; attempt++) {
+ const field = document.querySelector<HTMLElement>('[name="revision-snapshot-number-limit"]');
+
+ if (field) {
+ // Focused first, without the jump it would cause on its own, so the smooth scroll is
+ // the only movement the eye has to follow.
+ field.focus({ preventScroll: true });
+ field.scrollIntoView({ block: "center", behavior: "smooth" });
+ return;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
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 1c7e170055..2ff9dfa09e 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
@@ -33,13 +33,6 @@ vi.mock("../../../../react/hooks", async (importOriginal) => ({
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[]) =>
@@ -147,23 +140,14 @@ describe("Overview", () => {
expect(mocks.triggerCommand).not.toHaveBeenCalled();
});
- it("answers the revisions bucket with its own menu, which can raise the limit dialog", async () => {
+ it("answers the revisions bucket with its own menu, never the note one", () => {
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"));
+ expect(mocks.openRevisionsMenu)
+ .toHaveBeenCalledWith(expect.anything(), mocks.contentChanged);
});
});
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 de794308f1..5b81cb5f84 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 { useCallback, useEffect, useMemo, useState } from "preact/hooks";
+import { useEffect, useMemo, useState } from "preact/hooks";
import froca from "../../../../../services/froca";
import { t } from "../../../../../services/i18n";
@@ -14,7 +14,6 @@ import {
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
@@ -34,9 +33,6 @@ 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.
@@ -82,7 +78,7 @@ export default function Overview({ overview, onShowDetails, onContentChanged }:
}
if (item.data?.bucket === "revisions") {
- void openRevisionsContextMenu(event, onContentChanged, configureRevisionLimit);
+ void openRevisionsContextMenu(event, onContentChanged);
return;
}
@@ -90,11 +86,6 @@ export default function Overview({ overview, onShowDetails, onContentChanged }:
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
deleted file mode 100644
index 8742308a22..0000000000
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.spec.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-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
deleted file mode 100644
index 1212bb3031..0000000000
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/revision_limit_dialog.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-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 51e3a87ada..930f9fb52b 100644
--- a/apps/client/src/widgets/type_widgets/options/other.tsx
+++ b/apps/client/src/widgets/type_widgets/options/other.tsx
@@ -106,12 +106,7 @@ function AttachmentErasureTimeout() {
);
}
-/**
- * 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() {
+function RevisionSettings() {
const [ revisionSnapshotNumberLimit, setRevisionSnapshotNumberLimit ] = useTriliumOption("revisionSnapshotNumberLimit");
return (
@@ -142,6 +137,9 @@ export function RevisionSettings() {
label={t("revisions_snapshot_limit.erase_excess_revision_snapshots")}
description={t("revisions_snapshot_limit.erase_excess_revision_snapshots_description")}
buttonText={t("revisions_snapshot_limit.erase_now_button")}
+ // A negative limit keeps every snapshot, so nothing is excess and the erasure would
+ // report success having dropped nothing. Offered again as soon as a limit is set.
+ disabled={parseInt(revisionSnapshotNumberLimit, 10) < 0}
onClick={async () => {
await server.post("revisions/erase-all-excess-revisions");
toast.showMessage(t("revisions_snapshot_limit.erase_excess_revision_snapshots_prompt"));