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(templates): place a new note in every default parent
Elian Doran05acd9da619e
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex 4b366a6611..78064ef0c9 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -397,7 +397,7 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {}if (suggestion.action === "create-note") {- const { success, noteType, templateNoteId, notePath } = await noteCreateService.chooseNoteType();+ const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();if (!success) {return;}@@ -405,7 +405,8 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {title: suggestion.noteTitle,activate: false,type: noteType,- templateNoteId+ templateNoteId,+ cloneToNoteIds});const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.tsindex 96475d12d7..53664644cc 100644--- a/apps/client/src/services/note_create.spec.ts+++ b/apps/client/src/services/note_create.spec.ts@@ -1,7 +1,9 @@import { beforeEach, describe, expect, it, vi } from "vitest";+import FAttribute from "../entities/fattribute.js";import { buildNote } from "../test/easy-froca";import froca from "./froca";+import noteAttributeCache from "./note_attribute_cache.js";import server from "./server.js";import ws from "./ws.js";@@ -20,10 +22,17 @@ const h = vi.hoisted(() => {protectedAvailable: { value: false },triggerEvent: vi.fn(),triggerCommand: vi.fn(),- showMessage: vi.fn()+ showMessage: vi.fn(),+ cloneNoteToParentNote: vi.fn(async (..._args: unknown[]) => {})};});-const { tabManager, protectedAvailable, triggerEvent, triggerCommand, showMessage } = h;+const { tabManager, protectedAvailable, triggerEvent, triggerCommand, showMessage, cloneNoteToParentNote } = h;++vi.mock("./branches.js", () => ({+ default: {+ cloneNoteToParentNote: (...args: unknown[]) => h.cloneNoteToParentNote(...args)+ }+}));vi.mock("../components/app_context.js", () => ({default: {@@ -323,18 +332,25 @@ describe("chooseNoteType", () => {});describe("template default parent", () => {- // A template whose ~template:newNoteDefaultParent points at a note reachable from root, so- // that it has a note path.+ // Templates whose ~template:newNoteDefaultParent points at notes reachable from root, so+ // that they have note paths.const root = buildNote({id: "root",title: "root",children: [{ id: "people", title: "People" },+ { id: "advisors", title: "Advisors" },{ id: "person-tpl", title: "Person", "#template": "", "~template:newNoteDefaultParent": "people" },+ { id: "multi-tpl", title: "Multi", "#template": "", "~template:newNoteDefaultParent": "people" },+ { id: "inheriting-tpl", title: "Inheriting", "#template": "" },+ { id: "overriding-tpl", title: "Overriding", "#template": "", "~template:newNoteDefaultParent": "people" },{ id: "plain-tpl", title: "Plain", "#template": "" }]});expect(root.noteId).toBe("root");+ addOwnedRelation("multi-tpl", "template:newNoteDefaultParent", "advisors");+ addInheritedRelation("inheriting-tpl", "template:newNoteDefaultParent", "advisors");+ addInheritedRelation("overriding-tpl", "template:newNoteDefaultParent", "advisors");function choose(response: Record<string, unknown>) {triggerCommand.mockImplementation((_name: string, data: any) => data.callback(response));@@ -344,10 +360,23 @@ describe("chooseNoteType", () => {it("routes a template without an explicit parent into the template's default parent", async () => {await expect(choose({ success: true, noteType: "text", templateNoteId: "person-tpl" })).resolves.toEqual({- success: true, noteType: "text", templateNoteId: "person-tpl", notePath: "root/people"+ success: true, noteType: "text", templateNoteId: "person-tpl",+ notePath: "root/people", cloneToNoteIds: []});});+ it("reports every default parent: the first as the note path, the rest as clone targets", async () => {+ await expect(choose({ success: true, noteType: "text", templateNoteId: "multi-tpl" }))+ .resolves.toMatchObject({ notePath: "root/people", cloneToNoteIds: ["advisors"] });+ });++ it("uses an inherited default parent, unless the template owns one, which replaces it", async () => {+ await expect(choose({ success: true, noteType: "text", templateNoteId: "inheriting-tpl" }))+ .resolves.toMatchObject({ notePath: "root/advisors", cloneToNoteIds: [] });+ await expect(choose({ success: true, noteType: "text", templateNoteId: "overriding-tpl" }))+ .resolves.toMatchObject({ notePath: "root/people", cloneToNoteIds: [] });+ });+it("keeps a parent the user picked over the template's default parent", async () => {await expect(choose({success: true, noteType: "text", templateNoteId: "person-tpl", notePath: "root/elsewhere"@@ -361,19 +390,20 @@ describe("chooseNoteType", () => {.resolves.not.toHaveProperty("notePath", expect.any(String));});- it("creates the note in the default parent when the chooser is used through createNoteWithTypePrompt", async () => {+ it("creates the note in the first default parent and clones it into the others through createNoteWithTypePrompt", async () => {setActiveContext(true);triggerCommand.mockImplementation((_name: string, data: any) => {- data.callback({ success: true, noteType: "text", templateNoteId: "person-tpl" });+ data.callback({ success: true, noteType: "text", templateNoteId: "multi-tpl" });});await noteCreateService.createNoteWithTypePrompt("fallback-parent", {});expect(server.post).toHaveBeenCalledWith(`notes/people/children?target=into&targetBranchId=`,- expect.objectContaining({ templateNoteId: "person-tpl" }),+ expect.objectContaining({ templateNoteId: "multi-tpl" }),undefined);+ expect(cloneNoteToParentNote).toHaveBeenCalledExactlyOnceWith(NOTE_ID, "advisors");});});});@@ -398,3 +428,36 @@ describe("duplicateSubtree", () => {expect(showMessage).toHaveBeenCalled();});});++// easy-froca note definitions are object literals, so a repeated or inherited relation cannot be+// declared there; these append the attribute to an already-built fixture note instead.++function addOwnedRelation(noteId: string, name: string, value: string) {+ const note = froca.getNoteFromCache(noteId);+ if (!note) {+ throw new Error(`Missing fixture note '${noteId}'`);+ }++ const attr = buildRelation(noteId, name, value);+ froca.attributes[attr.attributeId] = attr;+ note.attributes.push(attr.attributeId);+ (noteAttributeCache.attributes[noteId] ??= []).push(attr);+}++/** The relation is served by the attribute cache (getRelations) but is owned by another note. */+function addInheritedRelation(noteId: string, name: string, value: string) {+ const attr = buildRelation(`ancestor-of-${noteId}`, name, value);+ (noteAttributeCache.attributes[noteId] ??= []).push(attr);+}++function buildRelation(ownerNoteId: string, name: string, value: string) {+ return new FAttribute(froca, {+ noteId: ownerNoteId,+ attributeId: `${ownerNoteId}_${name}_${value}`,+ type: "relation",+ name,+ value,+ position: 100,+ isInheritable: false+ });+}diff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.tsindex cf959c0fdf..7d3dfe3e06 100644--- a/apps/client/src/services/note_create.ts+++ b/apps/client/src/services/note_create.ts@@ -6,6 +6,7 @@ import type NoteContext from "../components/note_context.js";import type FBranch from "../entities/fbranch.js";import type FNote from "../entities/fnote.js";import type { ChooseNoteTypeResponse } from "../widgets/dialogs/note_type_chooser.js";+import branchService from "./branches.js";import froca from "./froca.js";import { t } from "./i18n.js";import protectedSessionHolder from "./protected_session_holder.js";@@ -27,6 +28,11 @@ export interface CreateNoteOpts {target?: string;targetBranchId?: string;textEditor?: CKTextEditor;+ /**+ * Parents the created note is cloned into, in addition to the one it is created under. Set from+ * a template's `~template:newNoteDefaultParent` relations; all resulting branches are equal.+ */+ cloneToNoteIds?: string[];/** Attributes to be set on the note. These are set atomically on note creation, so entity changes are not sent for attributes defined here. */attributes?: Omit<AttributeRow, "noteId" | "attributeId">[];/**@@ -93,6 +99,10 @@ async function createNote(parentNotePath: string | undefined, options: CreateNotoptions.textEditor?.removeSelection();}+ for (const cloneParentNoteId of options.cloneToNoteIds ?? []) {+ await branchService.cloneNoteToParentNote(note.noteId, cloneParentNoteId);+ }+await ws.waitForMaxKnownEntityChangeId();const activeNoteContext = options.noteContext ?? appContext.tabManager.getActiveContext();@@ -119,8 +129,9 @@ async function createNote(parentNotePath: string | undefined, options: CreateNot/*** Prompts for the type / template of a new note and, optionally, a parent. When the user picks a- * template without picking a parent, the template's own `~template:newNoteDefaultParent` (if any)- * is returned as the `notePath` instead, so a template gathers the notes created from it in one place.+ * template without picking a parent, the note goes to the template's `~template:newNoteDefaultParent`+ * targets (if any) instead, so a template gathers the notes created from it in one place: one target+ * is returned as the `notePath` to create under, the rest as `cloneToNoteIds` to clone into.*/async function chooseNoteType() {const response = await new Promise<ChooseNoteTypeResponse>((res) => {@@ -128,14 +139,18 @@ async function chooseNoteType() {});if (response.success && !response.notePath && response.templateNoteId) {- response.notePath = await getTemplateDefaultParentNotePath(response.templateNoteId);+ const defaultParents = await getTemplateDefaultParents(response.templateNoteId);+ if (defaultParents) {+ response.notePath = defaultParents.notePath;+ response.cloneToNoteIds = defaultParents.cloneToNoteIds;+ }}return response;}async function createNoteWithTypePrompt(parentNotePath: string, options: CreateNoteOpts = {}) {- const { success, noteType, templateNoteId, notePath } = await chooseNoteType();+ const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await chooseNoteType();if (!success) {return;@@ -143,21 +158,42 @@ async function createNoteWithTypePrompt(parentNotePath: string, options: CreateNoptions.type = noteType;options.templateNoteId = templateNoteId;+ options.cloneToNoteIds = cloneToNoteIds;return await createNote(notePath || parentNotePath, options);}/**- * Resolves the path of the note the template's `~template:newNoteDefaultParent` relation points at,- * relative to the current hoisting. Undefined when the template has no such relation, or its target- * has no visible path.+ * Resolves the targets of the template's `~template:newNoteDefaultParent` relations. The note is+ * placed in every target: created under the first resolvable one (`notePath`, relative to the+ * current hoisting) and cloned into the rest (`cloneToNoteIds`) — the split is only how the API is+ * called, since all branches of a note are equal. Owned relations replace inherited ones, so a+ * template overrides an inheritable default on an ancestor instead of adding to it. Undefined when+ * no target resolves to a note with a visible path.*/-async function getTemplateDefaultParentNotePath(templateNoteId: string) {+async function getTemplateDefaultParents(templateNoteId: string) {const templateNote = await froca.getNote(templateNoteId);- const defaultParentNote = await templateNote?.getRelationTarget("template:newNoteDefaultParent");+ if (!templateNote) {+ return undefined;+ }++ const ownedRelations = templateNote.getOwnedRelations("template:newNoteDefaultParent");+ const relations = ownedRelations.length+ ? ownedRelations+ : templateNote.getRelations("template:newNoteDefaultParent");+ const targetNoteIds = [...new Set(relations.map((relation) => relation.value).filter(Boolean))];+ const targetNotes = await froca.getNotes(targetNoteIds, true);const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;- return defaultParentNote?.getBestNotePathString(hoistedNoteId);+ const notePath = targetNotes[0]?.getBestNotePathString(hoistedNoteId);+ if (!notePath) {+ return undefined;+ }++ return {+ notePath,+ cloneToNoteIds: targetNotes.slice(1).map((targetNote) => targetNote.noteId)+ };}/* If the first element is heading, parse it out and use it as a new heading. */diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.tsxindex 225d61c001..df150e4948 100644--- a/apps/client/src/widgets/dialogs/note_type_chooser.tsx+++ b/apps/client/src/widgets/dialogs/note_type_chooser.tsx@@ -17,6 +17,8 @@ export interface ChooseNoteTypeResponse {noteType?: string;templateNoteId?: string;notePath?: string;+ /** Extra parents to clone the created note into, from the template's default parents. */+ cloneToNoteIds?: string[];}export type ChooseNoteTypeCallback = (data: ChooseNoteTypeResponse) => void;diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Attributes/Relations.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Attributes/Relations.htmlindex cb5ea367fd..bc996cc5db 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Attributes/Relations.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Attributes/Relations.html@@ -85,7 +85,8 @@ class="table"><td><code spellcheck="false">template:newNoteDefaultParent</code></td><td>set on a template note, points to the note under which notes created- from the template are placed when no other location is picked. See + from the template are placed when no other location is picked; when+ set several times, the note is cloned into every target. See <aclass="reference-link" href="#root/_help_KC1HB96bqqHX">Templates</a>.</td></tr>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Templates.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Templates.htmlindex e68b38a129..b3e463c548 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Templates.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Advanced Usage/Templates.html@@ -64,6 +64,11 @@spellcheck="false">~template:newNoteDefaultParent</code>relation to the template note, pointingat the note that should hold the instances — for example a <em>Person</em> templatepointing to a <em>People</em> note.</p>+<p>Adding the relation several times places the new note in every target,+ as <a class="reference-link" href="#root/_help_IakOLONlIfGI">clones</a>.+ The relation can also be inherited — for example from a folder holding several+ templates — in which case a relation owned by the template itself replaces+ the inherited one.</p><p>The default parent is used whenever a note is created from the templatethrough the <em>Choose note type</em> dialog — for example via <code spellcheck="false">@</code>-completionin a <a class="reference-link" href="#root/_help_iPIMuisry3hd">Text</a> note,diff --git a/docs/User Guide/User Guide/Advanced Usage/Attributes/Relations.md b/docs/User Guide/User Guide/Advanced Usage/Attributes/Relations.mdindex 1652982ae4..80fa841a92 100644--- a/docs/User Guide/User Guide/Advanced Usage/Attributes/Relations.md+++ b/docs/User Guide/User Guide/Advanced Usage/Attributes/Relations.md@@ -42,7 +42,7 @@ These relations are supported and used internally by Trilium.| --- | --- || `runOn*` | See <a class="reference-link" href="../../Scripting/Backend%20scripts/Backend%20Events.md">Events</a> || `template` | note's attributes will be inherited even without a parent-child relationship, note's content and subtree will be added to instance notes if empty. See documentation for details. |-| `template:newNoteDefaultParent` | set on a template note, points to the note under which notes created from the template are placed when no other location is picked. See <a class="reference-link" href="../Templates.md">Templates</a>. |+| `template:newNoteDefaultParent` | set on a template note, points to the note under which notes created from the template are placed when no other location is picked; when set several times, the note is cloned into every target. See <a class="reference-link" href="../Templates.md">Templates</a>. || `inherit` | note's attributes will be inherited even without a parent-child relationship. See <a class="reference-link" href="../Templates.md">Templates</a> for a similar concept. See <a class="reference-link" href="Attribute%20Inheritance.md">Attribute Inheritance</a> in the documentation. || `renderNote` | notes of type <a class="reference-link" href="../../Note%20Types/Render%20Note.md">Render Note</a> will be rendered using a code note (HTML or script) and it is necessary to point using this relation to which note should be rendered || `widget` | Used in the context of custom <a class="reference-link" href="../../Scripting/Frontend%20Basics/Launch%20Bar%20Widgets.md">Launch Bar Widgets</a>, to refer to the widget that will be rendered. |diff --git a/docs/User Guide/User Guide/Advanced Usage/Templates.md b/docs/User Guide/User Guide/Advanced Usage/Templates.mdindex 971c279ea5..517d227094 100644--- a/docs/User Guide/User Guide/Advanced Usage/Templates.md+++ b/docs/User Guide/User Guide/Advanced Usage/Templates.md@@ -37,6 +37,8 @@ To specify a template for child notes, you can use a `~child:template` relationA template can gather the notes created from it in one place, instead of having them land wherever they happen to be created. To do so, add a `~template:newNoteDefaultParent` relation to the template note, pointing at the note that should hold the instances — for example a _Person_ template pointing to a _People_ note.+Adding the relation several times places the new note in every target, as <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Notes/Cloning%20Notes.md">clones</a>. The relation can also be inherited — for example from a folder holding several templates — in which case a relation owned by the template itself replaces the inherited one.+The default parent is used whenever a note is created from the template through the _Choose note type_ dialog — for example via `@`-completion in a <a class="reference-link" href="../Note%20Types/Text.md">Text</a> note, or the _Create and link child note_ option of the note search — and no other location is picked in that dialog. Creating an instance note from the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree.md">Note Tree</a> context menu (_Insert child note_, _Insert note after_) still creates it at the chosen place.Unlike the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Notes/Note%20Inbox.md">Note Inbox</a>, which holds quickly captured notes until they are sorted, the default parent is meant as the instances' permanent location.