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/deleted notes dialog: add preview for deleted notes
Adorian Doranaeb2d0933792
diff --git a/apps/client/src/entities/deleted_fnote.spec.ts b/apps/client/src/entities/deleted_fnote.spec.tsnew file mode 100644index 0000000000..a0ae2dc9c2--- /dev/null+++ b/apps/client/src/entities/deleted_fnote.spec.ts@@ -0,0 +1,99 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++// --- Mocks (hoisted above imports) ---++// Default to a resolved promise: importing FNote's dependency graph calls `server.get(...).then(...)`+// at module load (e.g. keyboard_actions), so the mock must be thenable before any test runs.+const { get } = vi.hoisted(() => ({ get: vi.fn((): Promise<any> => Promise.resolve([])) }));++vi.mock("../services/server.js", () => ({+ default: { get }+}));++// The detached note stores the froca singleton but never calls it, so a bare stub is enough.+vi.mock("../services/froca.js", () => ({+ default: {}+}));++// Imports AFTER vi.mock calls.+import DeletedFNote from "./deleted_fnote.js";+import FNote from "./fnote.js";++const META = {+ noteId: "deletedabc12",+ title: "Deleted note",+ isProtected: false,+ type: "text",+ mime: "text/html",+ blobId: "blob123456"+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe("DeletedFNote", () => {+ it("load builds an instance that is interchangeable with a live FNote", async () => {+ get.mockResolvedValueOnce(META);++ const note = await DeletedFNote.load("deletedabc12");++ // Must satisfy `instanceof FNote` — content_renderer and the tooltip branch on it.+ expect(note).toBeInstanceOf(DeletedFNote);+ expect(note).toBeInstanceOf(FNote);+ expect(note?.noteId).toBe("deletedabc12");+ expect(note?.type).toBe("text");+ expect(note?.mime).toBe("text/html");+ expect(get).toHaveBeenCalledWith("deleted-notes/deletedabc12/metadata");+ });++ it("load returns null when the note is not previewable (server rejects)", async () => {+ get.mockRejectedValueOnce(new Error("404 Not Found"));++ expect(await DeletedFNote.load("gone12345678")).toBeNull();+ });++ it("getBlob fetches from the isolated deleted-content route", async () => {+ get.mockResolvedValueOnce(META);+ const note = await DeletedFNote.load("deletedabc12");++ get.mockResolvedValueOnce({+ blobId: "blob123456",+ content: "<p>gone but readable</p>",+ contentLength: 24,+ dateModified: "",+ utcDateModified: ""+ });+ const blob = await note?.getBlob();++ expect(get).toHaveBeenLastCalledWith("deleted-notes/deletedabc12/blob");+ expect(blob?.content).toBe("<p>gone but readable</p>");+ });++ it("getBlob returns null when the blob has already been erased", async () => {+ get.mockResolvedValueOnce(META);+ const note = await DeletedFNote.load("deletedabc12");++ get.mockRejectedValueOnce(new Error("404 Not Found"));++ expect(await note?.getBlob()).toBeNull();+ });++ it("reports no live tree path", async () => {+ get.mockResolvedValueOnce(META);+ const note = await DeletedFNote.load("deletedabc12");++ expect(note?.getBestNotePathString()).toBe("");+ });++ it("loadMany drops ids that aren't previewable and keeps request order", async () => {+ get+ .mockResolvedValueOnce(META)+ .mockRejectedValueOnce(new Error("404 Not Found"))+ .mockResolvedValueOnce({ ...META, noteId: "deleteddef34" });++ const notes = await DeletedFNote.loadMany(["deletedabc12", "gone12345678", "deleteddef34"]);++ expect(notes.map((note) => note.noteId)).toEqual(["deletedabc12", "deleteddef34"]);+ });+});diff --git a/apps/client/src/entities/deleted_fnote.ts b/apps/client/src/entities/deleted_fnote.tsnew file mode 100644index 0000000000..9054a055ce--- /dev/null+++ b/apps/client/src/entities/deleted_fnote.ts@@ -0,0 +1,53 @@+import froca from "../services/froca.js";+import server from "../services/server.js";+import FBlob, { FBlobRow } from "./fblob.js";+import FNote, { FNoteRow } from "./fnote.js";++/**+ * A read-only, tree-detached view of a soft-deleted (not-yet-erased) note.+ *+ * It extends {@link FNote} so it satisfies `instanceof FNote` — required because `content_renderer`+ * and the note tooltip branch on `instanceof FNote` rather than a structural interface, so a mere+ * look-alike would render through the wrong code path. This makes a `DeletedFNote` interchangeable+ * with a live note everywhere a note is rendered read-only.+ *+ * It is never inserted into Froca (nor is the note in Becca): its parent/child/attribute arrays stay+ * empty, so every inherited Froca-backed method degrades to a safe default (no path, no attributes,+ * default icon). Only content access is overridden, pointing at the isolated `deleted-notes` route+ * that reads the soft-deleted row via SQL. Instances are transient and disappear when the caller+ * drops them, keeping the "caches hold live notes only" invariant intact.+ */+export default class DeletedFNote extends FNote {+ readonly isDeleted = true as const;++ private constructor(row: FNoteRow) {+ super(froca, row);+ }++ /** Fetches content from the isolated deleted-content route (bypasses Becca and the Froca blob cache). */+ override async getBlob(): Promise<FBlob | null> {+ const row = await server.get<FBlobRow>(`deleted-notes/${this.noteId}/blob`).catch(() => null);+ return row ? new FBlob(row) : null;+ }++ /** A soft-deleted note has no live tree path. */+ override getBestNotePathString(): string {+ return "";+ }++ /** Loads a single soft-deleted note, or `null` if it is live, already erased, or unknown. */+ static async load(noteId: string): Promise<DeletedFNote | null> {+ const row = await server.get<FNoteRow>(`deleted-notes/${noteId}/metadata`).catch(() => null);+ return row ? new DeletedFNote(row) : null;+ }++ /**+ * Factory for several ids at once. Returns a `DeletedFNote` for each id that is genuinely+ * soft-deleted-and-previewable; live/erased/unknown ids are dropped, so the result is exactly+ * the viewable subset (not necessarily in the requested order or length).+ */+ static async loadMany(noteIds: string[]): Promise<DeletedFNote[]> {+ const notes = await Promise.all(noteIds.map((noteId) => DeletedFNote.load(noteId)));+ return notes.filter((note): note is DeletedFNote => note != null);+ }+}diff --git a/apps/client/src/services/note_tooltip.spec.ts b/apps/client/src/services/note_tooltip.spec.tsindex 4f0043335f..02ef4d7557 100644--- a/apps/client/src/services/note_tooltip.spec.ts+++ b/apps/client/src/services/note_tooltip.spec.ts@@ -36,6 +36,7 @@ vi.mock("./i18n.js", () => ({}));// Imports AFTER vi.mock calls.+import DeletedFNote from "../entities/deleted_fnote.js";import froca from "./froca.js";import noteTooltipService, { mouseEnterHandler, renderFootnoteOrAnchor, renderTooltip } from "./note_tooltip.js";@@ -250,6 +251,32 @@ describe("renderTooltip", () => {expect(html).not.toContain("note-tooltip-title");expect(html.startsWith('<div class="note-tooltip-attributes">')).toBe(true);});++ it("renders a deleted note with a plain (escaped, unlinked) title and no quick-edit button", async () => {+ // A real DeletedFNote so renderTooltip's `instanceof DeletedFNote` branch is taken.+ const note = new (DeletedFNote as any)({+ noteId: "d1",+ title: "Deleted & Gone",+ isProtected: false,+ type: "text",+ mime: "text/html",+ blobId: "b1"+ });++ const html = (await renderTooltip(note)) as string;++ expect(html).toContain('class="note-tooltip-title"');+ // Title is escaped plain text, not a navigable link, and no path suffix is fetched.+ expect(html).toContain("Deleted & Gone");+ expect(html).not.toContain('href="#d1"');+ expect(getNoteTitleWithPathAsSuffix).not.toHaveBeenCalled();+ // No quick-edit popup affordance for a note that no longer has a live editor.+ expect(html).not.toContain("open-popup-button");+ expect(html).not.toContain("?popup");+ // Attributes and content are still rendered.+ expect(html).toContain('class="note-tooltip-attributes"');+ expect(html).toContain("body");+ });});describe("mouseEnterHandler", () => {@@ -307,6 +334,36 @@ describe("mouseEnterHandler", () => {expect($link.attr("data-link-id")).toBe("existing");});+ it("routes elements marked data-note-deleted through the deleted-content route, not froca", async () => {+ vi.useFakeTimers();+ const loadSpy = vi.spyOn(DeletedFNote, "load").mockResolvedValue(null);+ froca.getNote = vi.fn(async () => null) as any;+ const $link = makeLink('<span data-href="#deleted12345?" data-note-deleted>x</span>');+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "deleted12345", noteId: "deleted12345", viewScope: { viewMode: "default" } });++ const promise = mouseEnterHandler.call($link[0], eventFor($link));+ await vi.advanceTimersByTimeAsync(600);+ await promise;++ expect(loadSpy).toHaveBeenCalledWith("deleted12345");+ expect(froca.getNote).not.toHaveBeenCalled();+ });++ it("routes ordinary note links through froca, not the deleted-content route", async () => {+ vi.useFakeTimers();+ const loadSpy = vi.spyOn(DeletedFNote, "load").mockResolvedValue(null);+ froca.getNote = vi.fn(async () => null) as any;+ const $link = makeLink('<a data-href="#root/abc">x</a>');+ parseNavigationStateFromUrl.mockReturnValue({ notePath: "root/abc", noteId: "abc", viewScope: { viewMode: "default" } });++ const promise = mouseEnterHandler.call($link[0], eventFor($link));+ await vi.advanceTimersByTimeAsync(600);+ await promise;++ expect(froca.getNote).toHaveBeenCalledWith("abc");+ expect(loadSpy).not.toHaveBeenCalled();+ });+it("assigns a fresh random link id and skips the tooltip on the not-hovering branch", async () => {vi.useFakeTimers();const $link = makeLink('<a href="#root/abc">x</a>');diff --git a/apps/client/src/services/note_tooltip.ts b/apps/client/src/services/note_tooltip.tsindex ceea554ced..ac80d4e14d 100644--- a/apps/client/src/services/note_tooltip.ts+++ b/apps/client/src/services/note_tooltip.ts@@ -1,4 +1,5 @@import appContext from "../components/app_context.js";+import DeletedFNote from "../entities/deleted_fnote.js";import type FNote from "../entities/fnote.js";import attributeRenderer from "./attribute_renderer.js";import contentRenderer from "./content_renderer.js";@@ -83,7 +84,15 @@ export async function mouseEnterHandler<T>(this: HTMLElement, e: JQuery.Triggere// note tooltip rather than being fed into a jQuery selector (the `?` is an invalid selector).if (url && url.startsWith("#") && !url.startsWith("#root/") && !url.includes("?")) {renderPromise = renderFootnoteOrAnchor($link, url);+ } else if ($link.attr("data-note-deleted") != null) {+ // The element explicitly targets a soft-deleted note (e.g. an entry in the deleted-notes+ // dialog): read it via the deleted-content route. `DeletedFNote.load` returns null once the+ // note is erased, so the tooltip then shows the "note has been deleted" message.+ note = await DeletedFNote.load(noteId);+ renderPromise = renderTooltip(note);} else {+ // Default route: a live note. A missing note (deleted/erased) renders the "note has been+ // deleted" placeholder — content previews of deleted notes are opt-in via `data-note-deleted`.note = await froca.getNote(noteId);renderPromise = renderTooltip(note);}@@ -156,15 +165,15 @@ export async function renderTooltip(note: FNote | null) {return `<div>${t("note_tooltip.note-has-been-deleted")}</div>`;}+ const isDeleted = note instanceof DeletedFNote;const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;const bestNotePath = note.getBestNotePathString(hoistedNoteId);- if (!bestNotePath) {+ // A soft-deleted note has no navigable path; still render it, just without the path-based title link.+ if (!bestNotePath && !isDeleted) {return;}- const noteTitleWithPathAsSuffix = await treeService.getNoteTitleWithPathAsSuffix(bestNotePath);-const { $renderedAttributes } = await attributeRenderer.renderNormalAttributes(note);const { $renderedContent } = await contentRenderer.getRenderedContent(note, {@@ -173,16 +182,23 @@ export async function renderTooltip(note: FNote | null) {});const isContentEmpty = $renderedContent[0].innerHTML.length === 0;+ const titleClasses = ["note-tooltip-title"];+ if (isContentEmpty) {+ titleClasses.push("note-no-content");+ }+let content = "";- if (noteTitleWithPathAsSuffix) {- const classes = ["note-tooltip-title"];- if (isContentEmpty) {- classes.push("note-no-content");+ if (isDeleted) {+ // Plain, unlinked title — there is no live note to navigate to.+ content = `<h5 class="${titleClasses.join(" ")}">${utils.escapeHtml(note.title)}</h5>`;+ } else if (bestNotePath) {+ const noteTitleWithPathAsSuffix = await treeService.getNoteTitleWithPathAsSuffix(bestNotePath);+ if (noteTitleWithPathAsSuffix) {+ content = `\+ <h5 class="${titleClasses.join(" ")}">+ <a href="#${note.noteId}" data-no-context-menu="true">${noteTitleWithPathAsSuffix.prop("outerHTML")}</a>+ </h5>`;}- content = `\- <h5 class="${classes.join(" ")}">- <a href="#${note.noteId}" data-no-context-menu="true">${noteTitleWithPathAsSuffix.prop("outerHTML")}</a>- </h5>`;}content = `${content}<div class="note-tooltip-attributes">${$renderedAttributes[0].outerHTML}</div>`;@@ -190,7 +206,10 @@ export async function renderTooltip(note: FNote | null) {content += $renderedContent[0].outerHTML;}- content += `<a class="open-popup-button" title="${t("note_tooltip.quick-edit")}" href="#${note.noteId}?popup"><span class="bx bx-edit" /></a>`;+ // The quick-edit (popup) button opens the live editor, which doesn't apply to a deleted note.+ if (!isDeleted) {+ content += `<a class="open-popup-button" title="${t("note_tooltip.quick-edit")}" href="#${note.noteId}?popup"><span class="bx bx-edit" /></a>`;+ }return content;}diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 9d7a6613e2..67646713b8 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -757,6 +757,13 @@ table.promoted-attributes-in-tooltip th {z-index: 32767 !important;}+/* Note tooltips are appended to <body> and are frequently triggered from inside modals+ (e.g. links or deleted-note entries in a dialog). The base .tooltip z-index sits below+ Bootstrap's modal, so raise them above it — matching .tooltip-top. */+.tooltip.note-tooltip {+ z-index: 32767 !important;+}+/* Tooltip for text editor content, placed at the bottom of the screen to be less intruive when editing */.tooltip.text-editor-content-tooltip {diff --git a/apps/client/src/widgets/dialogs/recent_changes.tsx b/apps/client/src/widgets/dialogs/recent_changes.tsxindex d9abc52294..29d00e2276 100644--- a/apps/client/src/widgets/dialogs/recent_changes.tsx+++ b/apps/client/src/widgets/dialogs/recent_changes.tsx@@ -130,7 +130,10 @@ function NoteLink({ notePath, title }: { notePath: string, title: string }) {function DeletedNoteLink({ change, setShown }: { change: RecentChangeRow, setShown: Dispatch<StateUpdater<boolean>> }) {return (<>- <span className="note-title">{change.current_title}</span>+ {/* `data-href` (not `href`, so it stays non-navigable) carries the note id to the global+ tooltip; the trailing `?` marks it as a note link rather than an in-page anchor.+ `data-note-deleted` tells the tooltip to resolve it via the deleted-content route. */}+ <span className="note-title" data-href={`#${change.noteId}?`} data-note-deleted>{change.current_title}</span> (<a href="javascript:"onClick={async () => {diff --git a/packages/commons/src/lib/hidden_subtree.ts b/packages/commons/src/lib/hidden_subtree.tsindex ff4060119e..5967c46fff 100644--- a/packages/commons/src/lib/hidden_subtree.ts+++ b/packages/commons/src/lib/hidden_subtree.ts@@ -5,6 +5,7 @@ enum Command {searchNotes,createNoteIntoInbox,showRecentChanges,+ showDeletedNotes,showOptions,commandPalette,toggleZenMode