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
feat(tree): duplicate a note without its children
Elian Doranda325337815f
diff --git a/apps/client/src/components/app_context.ts b/apps/client/src/components/app_context.tsindex dbd2250b39..6329b162f0 100644--- a/apps/client/src/components/app_context.ts+++ b/apps/client/src/components/app_context.ts@@ -215,6 +215,7 @@ export type CommandMappings = {editBranchPrefix: ContextMenuCommandData;convertNoteToAttachment: ContextMenuCommandData;duplicateSubtree: ContextMenuCommandData;+ duplicateNote: ContextMenuCommandData;expandSubtree: ContextMenuCommandData;collapseSubtree: ContextMenuCommandData;toggleArchivedNotes: CommandData;diff --git a/apps/client/src/components/main_tree_executors.ts b/apps/client/src/components/main_tree_executors.tsindex 5c9c49d09c..a696c1d6b0 100644--- a/apps/client/src/components/main_tree_executors.ts+++ b/apps/client/src/components/main_tree_executors.ts@@ -166,13 +166,21 @@ export default class MainTreeExecutors extends Component {}async duplicateSubtreeCommand({ selectedOrActiveBranchIds }: CommandListenerData<"duplicateSubtree">) {- for (const branchId of selectedOrActiveBranchIds) {+ await this.#duplicate(selectedOrActiveBranchIds, true);+ }++ async duplicateNoteCommand({ selectedOrActiveBranchIds }: CommandListenerData<"duplicateNote">) {+ await this.#duplicate(selectedOrActiveBranchIds, false);+ }++ async #duplicate(branchIds: string[], withChildren: boolean) {+ for (const branchId of branchIds) {const branch = froca.getBranch(branchId);if (!branch) continue;const note = await froca.getNote(branch.noteId);if (!note) continue;if (note.isProtected && !protectedSessionHolder.isProtectedSessionAvailable()) continue;- noteCreateService.duplicateSubtree(branch.noteId, branch.parentNoteId);+ noteCreateService.duplicateSubtree(branch.noteId, branch.parentNoteId, { withChildren });}}diff --git a/apps/client/src/menus/tree_context_menu.spec.ts b/apps/client/src/menus/tree_context_menu.spec.tsnew file mode 100644index 0000000000..08c733cb4d--- /dev/null+++ b/apps/client/src/menus/tree_context_menu.spec.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from "vitest";++import { buildNote } from "../test/easy-froca";+import { getDuplicateItems } from "./tree_context_menu";++describe("getDuplicateItems", () => {+ it("offers the note-only copy as soon as one of the notes has children", () => {+ const leaf = buildNote({ title: "Leaf" });+ const parent = buildNote({ title: "Parent", children: [ { title: "Child" } ] });++ expect(getDuplicateItems([ leaf ])).toBeNull();++ const items = getDuplicateItems([ leaf, parent ]);+ expect(items?.map((item) => "command" in item && item.command))+ .toStrictEqual([ "duplicateSubtree", "duplicateNote" ]);+ });+});diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.tsindex fbd91f121d..82733c3bcb 100644--- a/apps/client/src/menus/tree_context_menu.ts+++ b/apps/client/src/menus/tree_context_menu.ts@@ -289,7 +289,8 @@ export async function buildTreeContextMenuItems(ctx: TreeContextMenuContext): Prcommand: "duplicateSubtree",keyboardShortcut: "duplicateSubtree",uiIcon: "bx bx-outline",- enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp+ enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp,+ items: getDuplicateItems(selectedNotes)},{@@ -442,6 +443,20 @@ export async function handleTreeContextMenuSelect(}}+/**+ * The choice between copying the children or not, offered only when a note to copy has children.+ */+export function getDuplicateItems(notes: FNote[]): MenuItem<TreeCommandNames>[] | null {+ if (!notes.some((n) => n.hasChildren())) {+ return null;+ }++ return [+ { title: t("tree-context-menu.duplicate-with-children"), command: "duplicateSubtree", keyboardShortcut: "duplicateSubtree", uiIcon: "bx bx-sitemap" },+ { title: t("tree-context-menu.duplicate-note-only"), command: "duplicateNote", keyboardShortcut: "duplicateNote", uiIcon: "bx bx-file" }+ ];+}+function parentNotePathOf(notePath: string): string {const idx = notePath.lastIndexOf("/");return idx >= 0 ? notePath.slice(0, idx) : "";diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.tsindex 5caf5613d4..d57011a2e3 100644--- a/apps/client/src/services/note_create.spec.ts+++ b/apps/client/src/services/note_create.spec.ts@@ -483,11 +483,20 @@ describe("duplicateSubtree", () => {await noteCreateService.duplicateSubtree(NOTE_ID, "root");- expect(server.post).toHaveBeenCalledWith(`notes/${NOTE_ID}/duplicate/root`);+ expect(server.post).toHaveBeenCalledWith(`notes/${NOTE_ID}/duplicate/root`, { withChildren: true });expect(setNote).toHaveBeenCalledWith(`root/${NOTE_ID}`);expect(showMessage).toHaveBeenCalledWith(expect.stringContaining("note_create.duplicated"));});+ it("asks the server to leave the children out when told to", async () => {+ setActiveContext(true);+ server.post = vi.fn(async () => ({ note: { noteId: NOTE_ID } })) as typeof server.post;++ await noteCreateService.duplicateSubtree(NOTE_ID, "root", { withChildren: false });++ expect(server.post).toHaveBeenCalledWith(`notes/${NOTE_ID}/duplicate/root`, { withChildren: false });+ });+it("does not throw when there is no active context", async () => {setActiveContext(false);server.post = vi.fn(async () => ({ note: { noteId: NOTE_ID } })) as typeof server.post;diff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.tsindex 9a7b01461b..6c4cbf2af0 100644--- a/apps/client/src/services/note_create.ts+++ b/apps/client/src/services/note_create.ts@@ -230,9 +230,13 @@ function parseSelectedHtml(selectedHtml: string) {return [null, selectedHtml];}-async function duplicateSubtree(noteId: string, parentNotePath: string) {+/**+ * Duplicates a note next to the original and opens the copy. With `withChildren: false`, the copy+ * leaves out the note's children.+ */+async function duplicateSubtree(noteId: string, parentNotePath: string, { withChildren = true }: { withChildren?: boolean } = {}) {const parentNoteId = treeService.getNoteIdFromUrl(parentNotePath);- const { note } = await server.post<DuplicateResponse>(`notes/${noteId}/duplicate/${parentNoteId}`);+ const { note } = await server.post<DuplicateResponse>(`notes/${noteId}/duplicate/${parentNoteId}`, { withChildren });await ws.waitForMaxKnownEntityChangeId();diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 9a28759ef9..4a09c9a587 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2532,6 +2532,8 @@"paste-into": "Paste into","paste-after": "Paste after","duplicate": "Duplicate",+ "duplicate-with-children": "Note and its children",+ "duplicate-note-only": "This note only","export": "Export","import-into-note": "Import into note","apply-bulk-actions": "Apply bulk actions",diff --git a/apps/client/src/widgets/layout/Breadcrumb.tsx b/apps/client/src/widgets/layout/Breadcrumb.tsxindex b5f28e6143..7eaddb5a06 100644--- a/apps/client/src/widgets/layout/Breadcrumb.tsx+++ b/apps/client/src/widgets/layout/Breadcrumb.tsx@@ -10,7 +10,7 @@ import NoteContext from "../../components/note_context";import contextMenu, { MenuItem } from "../../menus/context_menu";import NoteColorPicker from "../../menus/custom-items/NoteColorPicker";import link_context_menu from "../../menus/link_context_menu";-import { TreeCommandNames } from "../../menus/tree_context_menu";+import { getDuplicateItems, TreeCommandNames } from "../../menus/tree_context_menu";import attributes from "../../services/attributes";import branches from "../../services/branches";import { copyTextWithToast } from "../../services/clipboard_ext";@@ -356,7 +356,7 @@ function buildContextMenu(notePath: string, parentComponent: Component | null) {command: "duplicateSubtree",uiIcon: "bx bx-outline",enabled: parentNotSearch && isNotRoot && !isHoisted && notOptionsOrHelp && note.isContentAvailable(),- handler: () => note_create.duplicateSubtree(noteId, branch.parentNoteId)+ items: getDuplicateItems([ note ])},{diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.htmlindex 416addc8cd..5f12e43b89 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html@@ -98,7 +98,7 @@the note itself will be present in two locations at once, and editing itin one place will edit it everywhere).</li><li>To simply create a duplicate note that can be modified independently,- look for <em>Duplicate subtree</em>.</li>+ look for <em>Duplicate</em>.</li></ul></li><li><strong>Paste into</strong>@@ -126,7 +126,16 @@</li><li><strong>Duplicate</strong><ul>- <li>Creates a copy of the note and its descendants.</li>+ <li>Creates a copy of the note and its descendants, placed right after the+ original.</li>+ <li>When the note has child notes, hovering the item opens a submenu:+ <ul>+ <li><em>Note and its children</em> does the same as clicking <em>Duplicate</em>.</li>+ <li><em>This note only</em> copies the note with its content and attributes,+ but without any of its child notes. Links and relations to the original+ children keep pointing at them.</li>+ </ul>+ </li><li>This process is different from <a class="reference-link" href="#root/_help_IakOLONlIfGI">Cloning Notes</a> sincethe duplicated note can be edited independently from the original.</li><li>An alternative to this, if done regularly, would be <a class="reference-link"diff --git a/apps/server/src/assets/translations/en/server.json b/apps/server/src/assets/translations/en/server.jsonindex 63a51fd921..4b68990e43 100644--- a/apps/server/src/assets/translations/en/server.json+++ b/apps/server/src/assets/translations/en/server.json@@ -111,6 +111,7 @@"add-note-above-to-selection": "Add Note Above to Selection","add-note-below-to-selection": "Add Note Below to Selection","duplicate-subtree": "Duplicate Subtree",+ "duplicate-note": "Duplicate Note Without Children","open-new-tab": "Open New Tab","close-active-tab": "Close Active Tab","reopen-last-tab": "Reopen Last Tab",diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.mdindex bb3ad779fe..e92f23363e 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md@@ -42,7 +42,7 @@ The contextual menu can operate:* Will place the given notes in clipboard.* Use one of the two paste functions (or the keyboard shortcuts) to copy them to the desired location.* Note that the copy function here works according to the <a class="reference-link" href="../../Notes/Cloning%20Notes.md">Cloning Notes</a> functionality (i.e. the note itself will be present in two locations at once, and editing it in one place will edit it everywhere).- * To simply create a duplicate note that can be modified independently, look for _Duplicate subtree_.+ * To simply create a duplicate note that can be modified independently, look for _Duplicate_.* **Paste into*** If there are any notes in clipboard, they will be pasted as child notes to the right-clicked one.* **Paste after**@@ -52,7 +52,10 @@ The contextual menu can operate:* **Clone to…*** Will display a modal to specify where to [clone](../../Notes/Cloning%20Notes.md) the desired notes.* **Duplicate**- * Creates a copy of the note and its descendants.+ * Creates a copy of the note and its descendants, placed right after the original.+ * When the note has child notes, hovering the item opens a submenu:+ * _Note and its children_ does the same as clicking _Duplicate_.+ * _This note only_ copies the note with its content and attributes, but without any of its child notes. Links and relations to the original children keep pointing at them.* This process is different from <a class="reference-link" href="../../Notes/Cloning%20Notes.md">Cloning Notes</a> since the duplicated note can be edited independently from the original.* An alternative to this, if done regularly, would be <a class="reference-link" href="../../../Advanced%20Usage/Templates.md">Templates</a>.* **Archive/Unarchive**diff --git a/packages/commons/src/lib/keyboard_actions_interface.ts b/packages/commons/src/lib/keyboard_actions_interface.tsindex c479ae1e30..1b48764d09 100644--- a/packages/commons/src/lib/keyboard_actions_interface.ts+++ b/packages/commons/src/lib/keyboard_actions_interface.ts@@ -30,6 +30,7 @@ const enum KeyboardActionNamesEnum {addNoteAboveToSelection,addNoteBelowToSelection,duplicateSubtree,+ duplicateNote,openNewTab,closeActiveTab,reopenLastTab,diff --git a/packages/trilium-core/src/routes/api/notes.spec.ts b/packages/trilium-core/src/routes/api/notes.spec.tsindex 8e4ec2864d..eb59086f81 100644--- a/packages/trilium-core/src/routes/api/notes.spec.ts+++ b/packages/trilium-core/src/routes/api/notes.spec.ts@@ -621,6 +621,18 @@ describe("Notes API (core)", () => {expect(res.status).toBe(200);expect(res.body.note.noteId).not.toBe(original.noteId);expect(res.body.note.title).toContain("Original subtree");+ expect(becca.getNoteOrThrow(res.body.note.noteId).getChildNotes()).toHaveLength(1);+ });++ it("duplicates only the note when the body asks for no children", async () => {+ const original = await createTextNote(api, { title: "Original note only" });+ await createTextNote(api, { parentNoteId: original.noteId, title: "Child" });++ const res = await api.post<{ note: { noteId: string } }>(+ `/api/notes/${original.noteId}/duplicate/root`, { body: { withChildren: false } }+ );+ expect(res.status).toBe(200);+ expect(becca.getNoteOrThrow(res.body.note.noteId).getChildNotes()).toHaveLength(0);});});diff --git a/packages/trilium-core/src/routes/api/notes.ts b/packages/trilium-core/src/routes/api/notes.tsindex 1101a9dadb..aed98f290e 100644--- a/packages/trilium-core/src/routes/api/notes.ts+++ b/packages/trilium-core/src/routes/api/notes.ts@@ -355,8 +355,9 @@ function changeTitle(req: Request<{ noteId: string }>) {function duplicateSubtree(req: Request<{ noteId: string; parentNoteId: string }>) {const { noteId, parentNoteId } = req.params;+ const { withChildren } = (req.body ?? {}) as { withChildren?: unknown };- return noteService.duplicateSubtree(noteId, parentNoteId);+ return noteService.duplicateSubtree(noteId, parentNoteId, { withChildren: withChildren !== false });}function eraseDeletedNotesNow() {diff --git a/packages/trilium-core/src/services/keyboard_actions.ts b/packages/trilium-core/src/services/keyboard_actions.tsindex ba91967186..34b3ae5b72 100644--- a/packages/trilium-core/src/services/keyboard_actions.ts+++ b/packages/trilium-core/src/services/keyboard_actions.ts@@ -272,6 +272,13 @@ function getDefaultKeyboardActions() {defaultShortcuts: [],scope: "note-tree"},+ {+ actionName: "duplicateNote",+ friendlyName: t("keyboard_action_names.duplicate-note"),+ iconClass: "bx bx-file",+ defaultShortcuts: [],+ scope: "note-tree"+ },{separator: t("keyboard_actions.tabs-and-windows")diff --git a/packages/trilium-core/src/services/notes.spec.ts b/packages/trilium-core/src/services/notes.spec.tsindex cfca4e6f5d..2195c08c0c 100644--- a/packages/trilium-core/src/services/notes.spec.ts+++ b/packages/trilium-core/src/services/notes.spec.ts@@ -672,6 +672,28 @@ describe("notes service (real DB)", () => {expect(dupChildren[0].noteId).not.toBe(child.note.noteId);});+ it("duplicates only the note when withChildren is false, keeping references to the original children", () => {+ const parent = createNote("root", { title: "spec-dup-only" });+ const child = createNote(parent.note.noteId, { title: "spec-dup-only-child" });+ getContext().init(() => {+ parent.note.setLabel("iconClass", "bx bx-star");+ parent.note.setRelation("selfRel", parent.note.noteId);+ parent.note.setRelation("childRel", child.note.noteId);+ parent.note.setContent(`<p><a href="#root/${child.note.noteId}">child</a></p>`);+ });++ const { note: dupNote } = getContext().init(() =>+ noteService.duplicateSubtree(parent.note.noteId, "root", { withChildren: false }));++ expect(dupNote.noteId).not.toBe(parent.note.noteId);+ expect(dupNote.getChildNotes()).toHaveLength(0);+ expect(parent.note.getChildNotes().map((n) => n.noteId)).toStrictEqual([ child.note.noteId ]);+ expect(dupNote.getLabelValue("iconClass")).toBe("bx bx-star");+ expect(dupNote.getRelationValue("selfRel")).toBe(dupNote.noteId);+ expect(dupNote.getRelationValue("childRel")).toBe(child.note.noteId);+ expect(dupNote.getContent()).toContain(child.note.noteId);+ });+it("refuses to duplicate the root note", () => {expect(() => getContext().init(() => noteService.duplicateSubtree("root", "root"))).toThrow(/Duplicating root is not possible/diff --git a/packages/trilium-core/src/services/notes.ts b/packages/trilium-core/src/services/notes.tsindex 77dc1ab1f5..d9fa0bc976 100644--- a/packages/trilium-core/src/services/notes.ts+++ b/packages/trilium-core/src/services/notes.ts@@ -1366,7 +1366,14 @@ function replaceByMap(str: string, mapObj: Record<string, string>) {return str.replace(re, (matched) => mapObj[matched]);}-function duplicateSubtree(origNoteId: string, newParentNoteId: string) {+/**+ * Copies a note and its descendants into `newParentNoteId`, right after the original, and appends+ * `notes.duplicate-note-suffix` to the copy's title.+ *+ * With `withChildren: false`, only the note itself is copied; links and relations to its children+ * keep pointing at the original children.+ */+function duplicateSubtree(origNoteId: string, newParentNoteId: string, { withChildren = true }: { withChildren?: boolean } = {}) {if (origNoteId === "root") {throw new Error("Duplicating root is not possible");}@@ -1377,9 +1384,11 @@ function duplicateSubtree(origNoteId: string, newParentNoteId: string) {// might be null if orig note is not in the target newParentNoteIdconst origBranch = origNote.getParentBranches().find((branch) => branch.parentNoteId === newParentNoteId);- const noteIdMapping = getNoteIdMapping(origNote);+ const noteIdMapping = withChildren+ ? getNoteIdMapping(origNote)+ : { [origNote.noteId]: newEntityId() };- const res = duplicateSubtreeInner(origNote, origBranch, newParentNoteId, noteIdMapping);+ const res = duplicateSubtreeInner(origNote, origBranch, newParentNoteId, noteIdMapping, withChildren);const duplicateNoteSuffix = t("notes.duplicate-note-suffix");@@ -1410,7 +1419,7 @@ function duplicateSubtreeWithoutRoot(origNoteId: string, newNoteId: string) {}}-function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch | null | undefined, newParentNoteId: string, noteIdMapping: Record<string, string>) {+function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch | null | undefined, newParentNoteId: string, noteIdMapping: Record<string, string>, withChildren = true) {if (origNote.isProtected && !protectedSessionService.isProtectedSessionAvailable()) {throw new Error(`Cannot duplicate note '${origNote.noteId}' because it is protected and protected session is not available. Enter protected session and try again.`);}@@ -1460,9 +1469,11 @@ function duplicateSubtreeInner(origNote: BNote, origBranch: BBranch | null | undattr.save({ skipValidation: true });}- for (const childBranch of origNote.getChildBranches()) {- if (childBranch) {- duplicateSubtreeInner(childBranch.getNote(), childBranch, newNote.noteId, noteIdMapping);+ if (withChildren) {+ for (const childBranch of origNote.getChildBranches()) {+ if (childBranch) {+ duplicateSubtreeInner(childBranch.getNote(), childBranch, newNote.noteId, noteIdMapping);+ }}}