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): keep the tree and the note in place when deleting a note
perfectra1n69a19a5a7c7d
diff --git a/apps/client/src/services/branches.spec.ts b/apps/client/src/services/branches.spec.tsindex b529046a51..1e29d84bab 100644--- a/apps/client/src/services/branches.spec.ts+++ b/apps/client/src/services/branches.spec.ts@@ -240,7 +240,7 @@ describe("deleteNotes", () => {expect(firstArg).toContain("eraseNotes=false");expect(firstArg).toContain("last=false");expect(secondArg).toContain("last=true");- // navigated to the parent path ("root")+ // root has no children registered here, so the parent path ("root") is the fallbackexpect(setNote).toHaveBeenCalledWith("root");});@@ -282,7 +282,7 @@ describe("deleteNotes", () => {const result = await branches.deleteNotes(["delBranch4"], false, false);expect(result).toBe(true);- // getActiveContext only used by activateParentNotePath, which is skipped+ // getActiveContext only used by activateNeighbouringNotePath, which is skippedexpect(getActiveContext).not.toHaveBeenCalled();});@@ -306,7 +306,85 @@ describe("deleteNotes", () => {});});-describe("activateParentNotePath (via deleteNotes navigation)", () => {+describe("activateNeighbouringNotePath (via deleteNotes navigation)", () => {+ /** Confirms the delete dialog with the given options and captures where the active tab navigates. */+ function confirmDeletion(notePathArray: string[], deleteAllClones = false) {+ const setNote = vi.fn(async () => {});+ appContext.tabManager = {+ getActiveContext: () => ({ notePathArray, setNote })+ } as any;+ appContext.triggerCommand = vi.fn((_name: any, data: any) => {+ data.callback({ proceed: true, deleteAllClones, eraseNotes: false });+ }) as any;+ return setNote;+ }++ it("activates the next sibling, or the previous one when the deleted note is the last", async () => {+ const parent = buildNote({ title: "P", children: [+ { id: "sibA", title: "A" }, { id: "sibB", title: "B" }, { id: "sibC", title: "C" }, { id: "sibD", title: "D" }+ ] });+ const p = parent.noteId;++ let setNote = confirmDeletion(["root", p, "sibB"]);+ await branches.deleteNotes([`${p}_sibB`]);+ expect(setNote).toHaveBeenCalledWith(`root/${p}/sibC`);++ setNote = confirmDeletion(["root", p, "sibD"]);+ await branches.deleteNotes([`${p}_sibD`]);+ expect(setNote).toHaveBeenCalledWith(`root/${p}/sibC`);++ // The deleted note is an ancestor of the active one: its own siblings are what count.+ buildNote({ id: "grandchild", title: "G" });+ setNote = confirmDeletion(["root", p, "sibA", "grandchild"]);+ await branches.deleteNotes([`${p}_sibA`]);+ expect(setNote).toHaveBeenCalledWith(`root/${p}/sibB`);+ });++ it("skips siblings that the deletion also removes and archived ones, falling back to the parent", async () => {+ const parent = buildNote({ title: "P2", children: [+ { id: "arcA", title: "A", "#archived": "" }, { id: "selB", title: "B" }, { id: "selC", title: "C" }+ ] });+ const p = parent.noteId;++ // B and C are both selected, A is archived: nothing survives, so the parent is the target.+ let setNote = confirmDeletion(["root", p, "selB"]);+ await branches.deleteNotes([`${p}_selB`, `${p}_selC`]);+ expect(setNote).toHaveBeenCalledWith(`root/${p}`);++ // Only B is selected, so C survives.+ setNote = confirmDeletion(["root", p, "selB"]);+ await branches.deleteNotes([`${p}_selB`]);+ expect(setNote).toHaveBeenCalledWith(`root/${p}/selC`);+ });++ it("treats a clone of a deleted note as gone only when all clones are deleted", async () => {+ // X hangs both under P3 (right after B) and under Q; only its Q branch is selected.+ const parent = buildNote({ title: "P3", children: [+ { id: "clB", title: "B" }, { id: "clX", title: "X" }, { id: "clC", title: "C" }+ ] });+ const other = buildNote({ title: "Q" });+ const p = parent.noteId;+ makeBranch("Q_clX", "clX", other.noteId);+ other.addChild("clX", "Q_clX", false);+ froca.getNoteFromCache("clX")?.addParent(other.noteId, "Q_clX", false);++ let setNote = confirmDeletion(["root", p, "clB"], false);+ await branches.deleteNotes([`${p}_clB`, "Q_clX"]);+ expect(setNote).toHaveBeenCalledWith(`root/${p}/clX`);++ setNote = confirmDeletion(["root", p, "clB"], true);+ await branches.deleteNotes([`${p}_clB`, "Q_clX"], true);+ expect(setNote).toHaveBeenCalledWith(`root/${p}/clC`);+ });++ it("falls back to the parent when its children are not loaded in froca", async () => {+ const note = buildNote({ title: "Lonely" });+ makeBranch("lonelyBranch", note.noteId, "root");+ const setNote = confirmDeletion(["root", note.noteId]);+ await branches.deleteNotes(["lonelyBranch"]);+ expect(setNote).toHaveBeenCalledWith("root");+ });+it("does not navigate when the deleted note is not on the active path", async () => {const note = buildNote({ title: "Off" });makeBranch("offBranch", note.noteId, "root");@@ -347,7 +425,7 @@ describe("activateParentNotePath (via deleteNotes navigation)", () => {getActiveContext: () => ({ notePathArray: undefined, setNote })} as any;appContext.triggerCommand = vi.fn((_name: any, data: any) => {- // Remove the branch after filtering but before navigation, so activateParentNotePath's+ // Remove the branch after filtering but before navigation, so activateNeighbouringNotePath's// `froca.getBranch(...)` returns undefined and the `if (branch)` false arm is taken.delete froca.branches["ancBranch"];data.callback({ proceed: true, deleteAllClones: false, eraseNotes: false });diff --git a/apps/client/src/services/branches.ts b/apps/client/src/services/branches.tsindex a5c646ae7a..2401f4154b 100644--- a/apps/client/src/services/branches.ts+++ b/apps/client/src/services/branches.ts@@ -1,4 +1,5 @@import appContext from "../components/app_context.js";+import type FBranch from "../entities/fbranch.js";import type { ResolveOptions } from "../widgets/dialogs/delete_notes.js";import froca from "./froca.js";import hoistedNoteService from "./hoisted_note.js";@@ -120,7 +121,7 @@ async function deleteNotes(branchIdsToDelete: string[], forceDeleteAllClones = fif (moveToParent) {try {- await activateParentNotePath(branchIdsToDelete);+ await activateNeighbouringNotePath(branchIdsToDelete, deleteAllClones);} catch (e) {console.error(e);}@@ -152,7 +153,13 @@ async function deleteNotes(branchIdsToDelete: string[], forceDeleteAllClones = freturn true;}-async function activateParentNotePath(branchIdsToDelete: string[]) {+/**+ * Moves the active tab off a note that the deletion is about to remove from its path. The+ * destination is the nearest sibling that survives the deletion (the next one, else the previous+ * one), so the tree keeps its scroll position and the user stays where they were working; the+ * parent is the fallback when no sibling survives.+ */+async function activateNeighbouringNotePath(branchIdsToDelete: string[], deleteAllClones = false) {const activeContext = appContext.tabManager.getActiveContext();const activeNotePath = activeContext?.notePathArray ?? [];@@ -168,13 +175,46 @@ async function activateParentNotePath(branchIdsToDelete: string[]) {}}- // Navigate to the parent of the highest deleted ancestor- if (earliestIndex < activeNotePath.length) {- const parentPath = activeNotePath.slice(0, earliestIndex);- if (parentPath.length > 0) {- await activeContext?.setNote(parentPath.join("/"));- }+ if (earliestIndex >= activeNotePath.length) {+ return;}++ const parentPath = activeNotePath.slice(0, earliestIndex);+ if (parentPath.length === 0) {+ return;+ }++ const siblingNoteId = findSurvivingSibling(parentPath[parentPath.length - 1], activeNotePath[earliestIndex], branchIdsToDelete, deleteAllClones);+ const targetPath = siblingNoteId ? [ ...parentPath, siblingNoteId ] : parentPath;+ await activeContext?.setNote(targetPath.join("/"));+}++/**+ * Finds the child of `parentNoteId` closest to `noteId` that is still there once the given branches+ * are deleted: the next sibling, else the previous one. Archived siblings are skipped, since the+ * tree can be set to hide them.+ */+function findSurvivingSibling(parentNoteId: string, noteId: string, branchIdsToDelete: string[], deleteAllClones: boolean) {+ const parentNote = froca.getNoteFromCache(parentNoteId);+ if (!parentNote) {+ return null;+ }++ const siblingBranches = parentNote.getChildBranches();+ const index = siblingBranches.findIndex((branch) => branch.noteId === noteId);+ if (index === -1) {+ return null;+ }++ // Deleting all clones removes every branch of the deleted notes, not only the selected ones.+ const deletedNoteIds = new Set(branchIdsToDelete.map((branchId) => froca.getBranch(branchId)?.noteId));+ const survives = (branch: FBranch) =>+ !branchIdsToDelete.includes(branch.branchId)+ && !(deleteAllClones && deletedNoteIds.has(branch.noteId))+ && !froca.getNoteFromCache(branch.noteId)?.isArchived;++ const candidates = [ ...siblingBranches.slice(index + 1), ...siblingBranches.slice(0, index).reverse() ];+ return candidates.find(survives)?.noteId ?? null;}async function moveNodeUpInHierarchy(node: Fancytree.FancytreeNode) {diff --git a/apps/client/src/services/focus.spec.ts b/apps/client/src/services/focus.spec.tsindex ee7ec72d06..fdf7a25f38 100644--- a/apps/client/src/services/focus.spec.ts+++ b/apps/client/src/services/focus.spec.ts@@ -10,10 +10,10 @@ afterEach(() => {describe("focus service", () => {it("does nothing (no focus change) when nothing was focused at save time", () => {- // saveFocusedElement() always assigns a jQuery object: $(":focus") is an *empty* wrapped- // set when nothing is focused (never null). So the early-return at the top of- // focusSavedElement() is NOT hit here; execution falls through to .hasClass("ck") (false)- // then .focus() on the empty set, which is a harmless no-op.+ // saveFocusedElement() always assigns a jQuery object: $(":focus") is never null, only an+ // empty wrapped set (or, under happy-dom, the <body> itself). So the early-return at the top+ // of focusSavedElement() is NOT hit here; execution falls through to .hasClass("ck") (false)+ // and then to a focus() that changes nothing.const $body = $(document.body);($body[0] as HTMLElement).focus();// happy-dom keeps focus on <body> by default; record the active element to prove it is unchanged.@@ -21,11 +21,7 @@ describe("focus service", () => {saveFocusedElement();- // Spy on jQuery's focus to prove no real element receives focus via the empty-set branch.- const focusProtoSpy = vi.spyOn($.fn, "focus");expect(() => focusSavedElement()).not.toThrow();- // .focus() is invoked on the empty wrapped set (harmless), but the active element is unchanged.- expect(focusProtoSpy).toHaveBeenCalledTimes(1);expect(document.activeElement).toBe(before);});@@ -63,8 +59,12 @@ describe("focus service", () => {($other[0] as HTMLInputElement).focus();expect(document.activeElement).toBe($other[0]);+ // The element is focused natively and without scrolling: the user has not moved, so the+ // page must not move either.+ const focusSpy = vi.spyOn(el, "focus");focusSavedElement();expect(document.activeElement).toBe(el);+ expect(focusSpy).toHaveBeenCalledWith({ preventScroll: true });// After restoring, the saved element is cleared -> calling again is a no-op.($other[0] as HTMLInputElement).focus();diff --git a/apps/client/src/services/focus.ts b/apps/client/src/services/focus.tsindex 066c745581..43cfd9c61a 100644--- a/apps/client/src/services/focus.ts+++ b/apps/client/src/services/focus.ts@@ -22,7 +22,10 @@ export function focusSavedElement() {console.log("Could not find CKEditor instance to focus last element");}} else {- $lastFocusedElement.focus();+ // The user has not moved since the dialog opened, so the focus goes back without the+ // browser scrolling the element into view. Without `preventScroll`, restoring focus to a+ // tree node the user has since scrolled away from drags the tree back to it.+ $lastFocusedElement[0]?.focus({ preventScroll: true });}$lastFocusedElement = null;