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
fix(client): stop the note info tab asking about a deleted note
Elian Doran540ee4c9f6bb
diff --git a/apps/client/src/widgets/ribbon/NoteInfoTab.spec.tsx b/apps/client/src/widgets/ribbon/NoteInfoTab.spec.tsxnew file mode 100644index 0000000000..3ddd0a2503--- /dev/null+++ b/apps/client/src/widgets/ribbon/NoteInfoTab.spec.tsx@@ -0,0 +1,114 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++// Hoisted alongside the mock factories, which can run before this file's top-level constants exist.+const mocks = vi.hoisted(() => ({+ // Hoisted rather than a plain const: app_context pulls the server service in at module scope, so the+ // factory below runs before this file's own top-level statements do.+ serverGet: vi.fn<(url: string) => Promise<unknown>>(async () => ({})),+ entitiesReloadedHandler: undefined as ((data: { loadResults: unknown }) => void) | undefined+}));+const serverGet = mocks.serverGet;++vi.mock("../../services/server", () => ({+ default: { get: (url: string) => mocks.serverGet(url) }+}));++// Fully mocked: the real hooks module imports half the app (app_context, keyboard actions) at module+// scope, and capturing the handler is what lets a test drive the entity-change path directly.+vi.mock("../react/hooks", () => ({+ useTriliumEvent: (_name: string, handler: (data: { loadResults: unknown }) => void) => {+ mocks.entitiesReloadedHandler = handler;+ }+}));++import type FNote from "../../entities/fnote";+import froca from "../../services/froca";+import { buildNote } from "../../test/easy-froca";+import { useNoteMetadata } from "./NoteInfoTab";++/** A reload touching this note, which is what a deletion looks like to the hook. */+const NOTE_RELOADED = { loadResults: { isNoteReloaded: () => true, isNoteContentReloaded: () => false } };++function Probe({ note }: { note: FNote | null }) {+ useNoteMetadata(note);+ return <div />;+}++let container: HTMLDivElement | undefined;++/** Renders and flushes the mount effect, which is what issues the tab's first metadata request. */+async function renderProbe(note: FNote | null) {+ const target = container ?? document.body.appendChild(document.createElement("div"));+ container = target;+ await act(async () => {+ render(<Probe note={note} />, target);+ });+ return target;+}++function unmount() {+ if (container) {+ render(null, container);+ container.remove();+ container = undefined;+ }+}++afterEach(() => {+ unmount();+ mocks.entitiesReloadedHandler = undefined;+ serverGet.mockClear();+ vi.useRealTimers();+});++describe("useNoteMetadata", () => {+ it("asks the server for the metadata of a note that exists", async () => {+ const note = buildNote({ title: "Present" });++ await renderProbe(note);++ expect(serverGet).toHaveBeenCalledWith(`notes/${note.noteId}/metadata`);+ });++ it("does not ask about a note deleted while the debounced refresh was pending", async () => {+ vi.useFakeTimers();+ const note = buildNote({ title: "Doomed" });+ await renderProbe(note);+ serverGet.mockClear();++ // Deleting a note is itself an entity change for it, so the tab schedules a refresh — and only+ // then does the note leave froca. Ten seconds later the request would 404 (#10823 follow-up).+ mocks.entitiesReloadedHandler?.(NOTE_RELOADED);+ delete froca.notes[note.noteId];+ vi.advanceTimersByTime(10_000);++ expect(serverGet).not.toHaveBeenCalled();+ });++ it("drops a pending refresh when the tab goes away", async () => {+ vi.useFakeTimers();+ const note = buildNote({ title: "Closed" });+ await renderProbe(note);+ serverGet.mockClear();++ mocks.entitiesReloadedHandler?.(NOTE_RELOADED);+ unmount();+ vi.advanceTimersByTime(10_000);++ expect(serverGet).not.toHaveBeenCalled();+ });++ it("still refreshes a note that is merely modified", async () => {+ vi.useFakeTimers();+ const note = buildNote({ title: "Edited" });+ await renderProbe(note);+ serverGet.mockClear();++ mocks.entitiesReloadedHandler?.(NOTE_RELOADED);+ vi.advanceTimersByTime(10_000);++ expect(serverGet).toHaveBeenCalledWith(`notes/${note.noteId}/metadata`);+ });+});diff --git a/apps/client/src/widgets/ribbon/NoteInfoTab.tsx b/apps/client/src/widgets/ribbon/NoteInfoTab.tsxindex 90427ef5da..79716eebe1 100644--- a/apps/client/src/widgets/ribbon/NoteInfoTab.tsx+++ b/apps/client/src/widgets/ribbon/NoteInfoTab.tsx@@ -6,6 +6,7 @@ import { useCallback, useEffect, useMemo, useState } from "preact/hooks";import FNote from "../../entities/fnote";import debounce from "../../services/debounce";import { isExperimentalFeatureEnabled } from "../../services/experimental_features";+import froca from "../../services/froca";import { t } from "../../services/i18n";import server from "../../services/server";import { formatSize } from "../../services/utils";@@ -81,8 +82,12 @@ export function useNoteMetadata(note: FNote | null | undefined, debounceTime = 1const [ metadata, setMetadata ] = useState<MetadataResponse>();const refresh = useCallback(() => {- if (note) {- server.get<MetadataResponse>(`notes/${note?.noteId}/metadata`).then(setMetadata);+ // The froca check matters because this also runs off a ten-second debounce: deleting a note is+ // itself an entity change for that note, so a refresh gets scheduled for a note that is about to+ // stop existing, and asking the server about it ten seconds later answers 404 and reports a+ // failure the user can do nothing about.+ if (note && froca.getNoteFromCache(note.noteId)) {+ server.get<MetadataResponse>(`notes/${note.noteId}/metadata`).then(setMetadata);}setNoteSizeResponse(undefined);@@ -91,6 +96,9 @@ export function useNoteMetadata(note: FNote | null | undefined, debounceTime = 1}, [ note ]);const debouncedRefresh = useMemo(() => debounce(refresh, debounceTime), [ refresh, debounceTime ]);+ // Drop a pending refresh when the note changes or the tab goes away, so it can't fire against the+ // note that was showing ten seconds ago.+ useEffect(() => () => debouncedRefresh.clear(), [ debouncedRefresh ]);function requestSizeInfo() {if (!note) return;