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
perf(tree): move several notes into a parent in one request
Elian Doran0a69d8f8031f
diff --git a/apps/client/src/services/branches.spec.ts b/apps/client/src/services/branches.spec.tsindex c98675c763..f56fcf4865 100644--- a/apps/client/src/services/branches.spec.ts+++ b/apps/client/src/services/branches.spec.ts@@ -164,13 +164,15 @@ describe("moveToParentNote", () => {expect(server.put).not.toHaveBeenCalled();});- it("skips missing/hoisted/search-parent branches and moves valid ones", async () => {+ it("skips missing/hoisted/search-parent branches and moves the valid ones in one request", async () => {const parentNote = buildNote({ title: "Parent" });makeBranch("destParent", parentNote.noteId);// a regular note under rootconst regular = buildNote({ title: "Regular" });makeBranch("regularBranch", regular.noteId, "root");+ const regular2 = buildNote({ title: "Regular too" });+ makeBranch("regularBranch2", regular2.noteId, "root");// a note whose parent is a search note -> skippedconst searchParent = buildNote({ title: "Search", type: "search" });@@ -182,10 +184,19 @@ describe("moveToParentNote", () => {const hoisted = buildNote({ id: "hoistedId", title: "Hoisted" });makeBranch("hoistedBranch", hoisted.noteId, "root");- await branches.moveToParentNote(["missingBranch", "hoistedBranch", "searchChildBranch", "regularBranch"], "destParent", "comp-1");+ await branches.moveToParentNote(["missingBranch", "hoistedBranch", "regularBranch", "searchChildBranch", "regularBranch2"], "destParent", "comp-1");expect(server.put).toHaveBeenCalledTimes(1);- expect(server.put).toHaveBeenCalledWith("branches/regularBranch/move-to/destParent", undefined, "comp-1");+ expect(server.put).toHaveBeenCalledWith("branches/move-to/destParent",+ { branchIds: [ "regularBranch", "regularBranch2" ] }, "comp-1");+ });++ it("sends nothing when no branch can be moved", async () => {+ const parentNote = buildNote({ title: "Parent3" });+ makeBranch("destParent3", parentNote.noteId);++ await branches.moveToParentNote(["missingBranch"], "destParent3");+ expect(server.put).not.toHaveBeenCalled();});it("shows error and bails when the move fails", async () => {diff --git a/apps/client/src/services/branches.ts b/apps/client/src/services/branches.tsindex 3980fff22f..98f8584999 100644--- a/apps/client/src/services/branches.ts+++ b/apps/client/src/services/branches.ts@@ -80,21 +80,25 @@ async function moveToParentNote(branchIdsToMove: string[], newParentBranchId: streturn;}- branchIdsToMove = filterRootNote(branchIdsToMove);-- for (const branchIdToMove of branchIdsToMove) {+ const movableBranchIds: string[] = [];+ for (const branchIdToMove of filterRootNote(branchIdsToMove)) {const branchToMove = froca.getBranch(branchIdToMove);if (!branchToMove || branchToMove.noteId === hoistedNoteService.getHoistedNoteId() || (await branchToMove.getParentNote())?.type === "search") {continue;}- const resp = await server.put<Response>(`branches/${branchIdToMove}/move-to/${newParentBranchId}`, undefined, componentId);+ movableBranchIds.push(branchIdToMove);+ }- if (!resp.success) {- toastService.showError(resp.message);- return;- }+ if (movableBranchIds.length === 0) {+ return;+ }++ const resp = await server.put<Response>(`branches/move-to/${newParentBranchId}`, { branchIds: movableBranchIds }, componentId);++ if (!resp.success) {+ toastService.showError(resp.message);}}diff --git a/packages/trilium-core/src/routes/api/branches.spec.ts b/packages/trilium-core/src/routes/api/branches.spec.tsindex 3f096453d2..ca35a8c582 100644--- a/packages/trilium-core/src/routes/api/branches.spec.ts+++ b/packages/trilium-core/src/routes/api/branches.spec.ts@@ -47,25 +47,68 @@ describe("Branches API (core)", () => {});describe("moving", () => {- it("moves a branch under a different parent and returns the new clone", async () => {- const parent = await createTextNote(api, { title: "Move target parent" });- const child = await createTextNote(api, { title: "Branch to move" });+ it("moves several branches into a childless note, in order, and expands it", async () => {+ const source = await createTextNote(api, { title: "Move source" });+ const target = await createTextNote(api, { parentNoteId: source.noteId, title: "Move target" });+ const children = [+ await createTextNote(api, { parentNoteId: source.noteId, title: "Moved 1" }),+ await createTextNote(api, { parentNoteId: source.noteId, title: "Moved 2" }),+ await createTextNote(api, { parentNoteId: source.noteId, title: "Moved 3" })+ ];++ const res = await api.put<{ success: boolean }>(`/api/branches/move-to/${target.branchId}`, {+ body: { branchIds: children.map((child) => child.branchId) }+ });++ expect(res.status).toBe(200);+ expect(res.body.success).toBe(true);+ // Each original branch is replaced by a clone under the new parent.+ for (const child of children) {+ expect(getBranchRow(child.branchId)?.isDeleted).toBe(1);+ }+ expect(getSql().getColumn(+ "SELECT noteId FROM branches WHERE parentNoteId = ? AND isDeleted = 0 ORDER BY notePosition",+ [ target.noteId ]+ )).toEqual(children.map((child) => child.noteId));+ expect(getBranchRow(target.branchId)?.isExpanded).toBe(1);+ });++ it("stops at the first move that fails validation", async () => {+ const movable = await createTextNote(api, { title: "Movable" });+ const ancestor = await createTextNote(api, { title: "Ancestor of target" });+ const nestedTarget = await createTextNote(api, { parentNoteId: ancestor.noteId, title: "Nested target" });+ const notReached = await createTextNote(api, { title: "Not reached" });- const res = await api.put<{ success: boolean; branch?: { parentNoteId: string } }>(- `/api/branches/${child.branchId}/move-to/${parent.branchId}`+ // Moving `ancestor` under its own descendant would create a cycle.+ const res = await api.put<{ success: boolean; message: string }>(+ `/api/branches/move-to/${nestedTarget.branchId}`,+ { body: { branchIds: [ movable.branchId, ancestor.branchId, notReached.branchId ] } });expect(res.status).toBe(200);- expect(res.body.success).toBe(true);- expect(res.body.branch?.parentNoteId).toBe(parent.noteId);- // The original branch is replaced by a clone under the new parent.- expect(getBranchRow(child.branchId)?.isDeleted).toBe(1);+ expect(res.body.success).toBe(false);+ expect(res.body.message).toBeTruthy();+ expect(getBranchRow(movable.branchId)?.isDeleted).toBe(1);+ expect(getBranchRow(ancestor.branchId)?.isDeleted).toBe(0);+ expect(getBranchRow(notReached.branchId)?.isDeleted).toBe(0);});- it("400s when moving a non-existent branch", async () => {+ it("400s without moving anything when a branch or the target does not exist", async () => {const parent = await createTextNote(api, { title: "Has a valid parent branch" });- const res = await api.put(`/api/branches/missingBranch123/move-to/${parent.branchId}`);- expect(res.status).toBe(400);+ const child = await createTextNote(api, { title: "Not moved" });++ const missingBranch = await api.put(`/api/branches/move-to/${parent.branchId}`, {+ body: { branchIds: [ child.branchId, "missingBranch123" ] }+ });+ const missingTarget = await api.put("/api/branches/move-to/missingBranch123", {+ body: { branchIds: [ child.branchId ] }+ });+ const notAnArray = await api.put(`/api/branches/move-to/${parent.branchId}`, {+ body: { branchIds: child.branchId }+ });++ expect([ missingBranch.status, missingTarget.status, notAnArray.status ]).toEqual([ 400, 400, 400 ]);+ expect(getBranchRow(child.branchId)?.isDeleted).toBe(0);});it("reorders a branch before a sibling", async () => {diff --git a/packages/trilium-core/src/routes/api/branches.ts b/packages/trilium-core/src/routes/api/branches.tsindex 4f66c517fd..1a5aedbf14 100644--- a/packages/trilium-core/src/routes/api/branches.ts+++ b/packages/trilium-core/src/routes/api/branches.ts@@ -17,17 +17,41 @@ import { ValidationError } from "../../errors.js";* for not deleted branches. There may be multiple deleted note-parent note relationships.*/-function moveBranchToParent(req: Request<{ branchId: string, parentBranchId: string }>) {- const { branchId, parentBranchId } = req.params;+/**+ * Moves the branches in `branchIds`, in order, under the note of `parentBranchId`. All moves run in one+ * transaction, so the client receives them as a single frontend update. The first move that fails+ * validation stops the batch; the moves before it stay.+ */+function moveBranchesToParent(req: Request<{ parentBranchId: string }>) {+ const { parentBranchId } = req.params;+ const { branchIds } = req.body;++ if (!Array.isArray(branchIds)) {+ throw new ValidationError("branchIds must be an array");+ }- const branchToMove = becca.getBranch(branchId);const targetParentBranch = becca.getBranch(parentBranchId);+ if (!targetParentBranch) {+ throw new ValidationError(`Target branch '${parentBranchId}' has not been found`);+ }++ const branchesToMove = branchIds.map((branchId) => {+ const branch = typeof branchId === "string" ? becca.getBranch(branchId) : null;+ if (!branch) {+ throw new ValidationError(`Branch '${branchId}' has not been found`);+ }+ return { branchId: branchId as string, branch };+ });- if (!branchToMove || !targetParentBranch) {- throw new ValidationError(`One or both branches '${branchId}', '${parentBranchId}' have not been found`);+ for (const { branchId, branch } of branchesToMove) {+ const res = branchService.moveBranchToBranch(branch, targetParentBranch, branchId);++ if (!("success" in res) || !res.success) {+ return res;+ }}- return branchService.moveBranchToBranch(branchToMove, targetParentBranch, branchId);+ return { success: true };}function moveBranchBeforeNote(req: Request<{ branchId: string, beforeBranchId: string }>) {@@ -305,7 +329,7 @@ function setPrefixBatch(req: Request) {}export default {- moveBranchToParent,+ moveBranchesToParent,moveBranchBeforeNote,moveBranchAfterNote,setExpanded,diff --git a/packages/trilium-core/src/routes/index.ts b/packages/trilium-core/src/routes/index.tsindex 375be28344..bec719d4e8 100644--- a/packages/trilium-core/src/routes/index.ts+++ b/packages/trilium-core/src/routes/index.ts@@ -147,7 +147,7 @@ export function buildSharedApiRoutes({ route, asyncRoute, asyncRouteWithoutTransapiRoute(PST, "/api/revisions/:revisionId/restore", revisionsApiRoute.restoreRevision);apiRoute(GET, "/api/edited-notes/:date", revisionsApiRoute.getEditedNotesOnDate);- apiRoute(PUT, "/api/branches/:branchId/move-to/:parentBranchId", branchesApiRoute.moveBranchToParent);+ apiRoute(PUT, "/api/branches/move-to/:parentBranchId", branchesApiRoute.moveBranchesToParent);apiRoute(PUT, "/api/branches/:branchId/move-before/:beforeBranchId", branchesApiRoute.moveBranchBeforeNote);apiRoute(PUT, "/api/branches/:branchId/move-after/:afterBranchId", branchesApiRoute.moveBranchAfterNote);apiRoute(PUT, "/api/branches/:branchId/expanded/:expanded", branchesApiRoute.setExpanded);