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/content manager/space usage: fix an issue
Adorian Dorane38ba525b3a8
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9e32745c47..5a569bcaf7 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2665,6 +2665,7 @@},"space_usage": {"loading": "Measuring space usage...",+ "load_failed": "Space usage could not be measured","view_overview": "Overview","view_browse": "Browse","other_notes_one": "1 other note",diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsxindex 3cf14153f5..2f3d6d4cda 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx@@ -17,6 +17,7 @@ interface CapturedDonutProps {const mocks = vi.hoisted(() => ({usage: undefined as unknown,+ failed: false,fetchedUrls: [] as string[],donutProps: undefined as unknown,openContextMenu: vi.fn()@@ -29,7 +30,7 @@ vi.mock("./context_menu", () => ({vi.mock("./use_space_usage_fetch", () => ({useSpaceUsageFetch: (url: string) => {mocks.fetchedUrls.push(url);- return mocks.usage;+ return { data: mocks.usage, failed: mocks.failed };}}));@@ -110,6 +111,7 @@ afterEach(() => {container = undefined;}mocks.usage = undefined;+ mocks.failed = false;mocks.fetchedUrls = [];mocks.donutProps = undefined;mocks.openContextMenu.mockClear();@@ -125,6 +127,17 @@ describe("Browse", () => {expect(mocks.fetchedUrls).toEqual([ "space-usage/note/root" ]);});+ it("says so when the note's usage could not be measured, rather than measuring on", () => {+ mocks.usage = undefined;+ mocks.failed = true;+ const probe = renderBrowse();++ expect(probe.querySelector(".space-usage-loading")).toBeNull();+ expect(probe.querySelector(".no-items")).not.toBeNull();+ // The breadcrumb still stands, so the user can climb back out of a note that would not load.+ expect(probe.querySelector(".space-usage-breadcrumb")).not.toBeNull();+ });+it("renders the donut for the root with its children ring and resolved titles", async () => {mocks.usage = usageOf("root", [ "child1" ]);const probe = renderBrowse();diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsxindex 3e27c5ac85..d52b200ef5 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx@@ -12,6 +12,7 @@ import type { DonutRing } from "../../../../react/charts/DonutChart";import { openSpaceUsageContextMenu } from "./context_menu";import { buildChildrenSegments, type UsageSegmentData } from "./donut_segments";import NoteUsageDonut, { segmentTooltip } from "./note_usage_donut";+import SpaceUsagePlaceholder from "./placeholder";import { useSpaceUsageFetch } from "./use_space_usage_fetch";const CHILDREN_RING_RADIUS = 180;@@ -33,7 +34,7 @@ interface BrowseProps {*/export default function Browse({ path, onPathChange }: BrowseProps) {const noteId = path[path.length - 1];- const usage = useSpaceUsageFetch<SpaceUsageNoteResponse>(`space-usage/note/${noteId}`);+ const { data: usage, failed } = useSpaceUsageFetch<SpaceUsageNoteResponse>(`space-usage/note/${noteId}`);const titles = useNoteTitles(path, usage);const getTitle = useCallback((id: string) => titles.get(id) ?? id, [ titles ]);@@ -106,7 +107,7 @@ export default function Browse({ path, onPathChange }: BrowseProps) {/></div>) : (- <p className="space-usage-loading">{t("space_usage.loading")}</p>+ <SpaceUsagePlaceholder failed={failed} />)}</div>);diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsxindex b14bd56a4a..fe5f5c38d2 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx@@ -6,11 +6,12 @@ import { t } from "../../../../../services/i18n";import { formatSize } from "../../../../../services/utils";const mocks = vi.hoisted(() => ({- overview: undefined as unknown+ overview: undefined as unknown,+ failed: false}));vi.mock("./use_space_usage_fetch", () => ({- useSpaceUsageFetch: () => mocks.overview+ useSpaceUsageFetch: () => ({ data: mocks.overview, failed: mocks.failed })}));vi.mock("./browse", () => ({@@ -64,6 +65,7 @@ afterEach(() => {container = undefined;}mocks.overview = undefined;+ mocks.failed = false;});describe("SpaceUsage section", () => {@@ -76,6 +78,15 @@ describe("SpaceUsage section", () => {expect(probe.querySelector(".switcher-stub")).not.toBeNull();});+ it("says so when the overview could not be measured, rather than measuring on", () => {+ mocks.overview = undefined;+ mocks.failed = true;+ const probe = renderSection();++ expect(probe.querySelector(".space-usage-loading")).toBeNull();+ expect(probe.querySelector(".no-items")).not.toBeNull();+ });+it("renders the overview with the two-part status line", () => {mocks.overview = OVERVIEW;const probe = renderSection();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 c0b5646a2b..4437dcda82 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 OptionsPageHeader from "../../components/OptionsPageHeader";import type { ContentManagerSectionProps } from "../index";import Browse from "./browse";import Overview from "./overview";+import SpaceUsagePlaceholder from "./placeholder";import { useSpaceUsageFetch } from "./use_space_usage_fetch";/** Matches the server default; the treemap could not label more cells anyway. */@@ -30,7 +31,7 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro// Kept fetched across both views so returning to the treemap draws immediately rather than// blanking. Revisions stay out of the ranking so it shares the basis of the areas the treemap// draws — asking for one basis and drawing the other would rank in notes the cells then shrink.- const overview = useSpaceUsageFetch<SpaceUsageOverviewResponse>(+ const { data: overview, failed } = useSpaceUsageFetch<SpaceUsageOverviewResponse>(`space-usage/overview?limit=${OVERVIEW_LIMIT}`);return (@@ -49,7 +50,7 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro{view === "browse" && <Browse path={browsePath} onPathChange={setBrowsePath} />}{view === "overview" && (overview? <Overview overview={overview} onShowDetails={showDetails} />- : <p className="space-usage-loading">{t("space_usage.loading")}</p>)}+ : <SpaceUsagePlaceholder failed={failed} />)}{/* Overview only: these are whole-database totals, and beside a single note's donutthey would read as being about that note. */}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/placeholder.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/placeholder.tsxnew file mode 100644index 0000000000..5c9af91d5b--- /dev/null+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/placeholder.tsx@@ -0,0 +1,13 @@+import { t } from "../../../../../services/i18n";+import NoItems from "../../../../react/NoItems";++/**+ * What a view stands in with before it has anything to draw. Measuring is the usual case; a failure+ * only shows once the first request has come back empty-handed, since there is no earlier payload+ * to keep on screen then — and claiming to still be measuring would outlast the page.+ */+export default function SpaceUsagePlaceholder({ failed }: { failed: boolean }) {+ return failed+ ? <NoItems icon="bx bx-error-circle" text={t("space_usage.load_failed")} />+ : <p className="space-usage-loading">{t("space_usage.loading")}</p>;+}diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.spec.tsxindex 9b702e5bc7..3391aba7c1 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.spec.tsx+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.spec.tsx@@ -32,8 +32,8 @@ function fireEntitiesReloaded(loadResults: LoadResults) {import { useSpaceUsageFetch } from "./use_space_usage_fetch";function Probe({ url }: { url: string }) {- const data = useSpaceUsageFetch<{ label: string }>(url);- return <div>{data ? data.label : "loading"}</div>;+ const { data, failed } = useSpaceUsageFetch<{ label: string }>(url);+ return <div>{data ? data.label : (failed ? "failed" : "loading")}</div>;}let container: HTMLDivElement | undefined;@@ -85,6 +85,19 @@ describe("useSpaceUsageFetch", () => {expect(probe.textContent).toBe("first");});+ it("reports a first fetch that fails, instead of measuring forever", async () => {+ // Nothing to fall back on yet, and a browser-rejected request is not even toasted, so a+ // silent catch would leave the view claiming to measure for as long as it stayed open.+ serverGet.mockRejectedValueOnce(new Error("rejected by browser"));+ const probe = renderProbe("space-usage/overview");+ await vi.waitFor(() => expect(probe.textContent).toBe("failed"));++ // ...and it clears itself the moment an attempt succeeds.+ serverGet.mockResolvedValueOnce({ label: "recovered" });+ renderProbe("space-usage/note/a");+ await vi.waitFor(() => expect(probe.textContent).toBe("recovered"));+ });+it("drops a stale response that resolves after a newer request", async () => {let resolveSlow: ((value: unknown) => void) | undefined;serverGet.mockReturnValueOnce(new Promise((resolve) => { resolveSlow = resolve; }));diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.tsindex 749ba4944d..8557ae57e7 100644--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts@@ -7,15 +7,28 @@ import { useTriliumEvent } from "../../../../react/hooks";/** One reload per burst — a subtree delete floods entity changes. */const REFRESH_DEBOUNCE_MS = 1000;+export interface SpaceUsageFetch<T> {+ data: T | null;+ /** The last attempt failed. Meaningful only while {@link data} is still null — see below. */+ failed: boolean;+}+/*** Fetches a space-usage endpoint and keeps it current: content changes anywhere — deletes, moves,* uploads — shift the sizes, so any note/branch/attachment change schedules one debounced reload.** `null` until the first response; on a URL change (Browse navigation) the previous payload stays* up while the new one is in flight, so the charts transition instead of blanking.+ *+ * A failure is reported rather than swallowed, because there is nothing to fall back on before the+ * first success: the view would otherwise claim to be measuring for as long as it stayed open. The+ * server service toasts most failures, but not one the browser itself rejected (a dropped+ * connection, an unreachable server), which would leave no trace at all. Callers show the failure+ * only while `data` is null — once a payload exists, keeping it beats blanking the charts.*/-export function useSpaceUsageFetch<T>(url: string) {+export function useSpaceUsageFetch<T>(url: string): SpaceUsageFetch<T> {const [ data, setData ] = useState<T | null>(null);+ const [ failed, setFailed ] = useState(false);const latestRequest = useRef(0);const refresh = useCallback(async () => {@@ -27,11 +40,13 @@ export function useSpaceUsageFetch<T>(url: string) {// A stale response must not repaint over a newer one.if (requestId === latestRequest.current) {setData(response);+ setFailed(false);}} catch {- // The server service has already reported the failure to the user (toast); keeping the- // last successful payload beats blanking the charts, and the callers fire-and-forget,- // so the rejection must not escape.+ // The callers fire-and-forget, so the rejection must not escape.+ if (requestId === latestRequest.current) {+ setFailed(true);+ }}}, [ url ]);@@ -46,5 +61,5 @@ export function useSpaceUsageFetch<T>(url: string) {}});- return data;+ return { data, failed };}