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/collections/board/card templates: allow creating new templates
Adorian Dorane1c2d5ee92e6
diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.tsindex 6383c5097b..7d1b2a0cd1 100644--- a/apps/client/src/services/note_create.spec.ts+++ b/apps/client/src/services/note_create.spec.ts@@ -275,6 +275,30 @@ describe("createNote", () => {});});+describe("createTemplateNote", () => {+ /**+ * A template is a note carrying `#template`, and it is opened in a popup rather than in the+ * tab: what asked for one is usually a dialog the reader is still standing in.+ */+ it("makes a note carrying the label under the given one, and opens it in a popup", async () => {+ const result = await noteCreateService.createTemplateNote("board1", "New card template");++ expect(server.post).toHaveBeenCalledWith(+ expect.stringContaining("notes/board1/children"),+ expect.objectContaining({+ title: "New card template",+ type: "text",+ attributes: [+ { type: "label", name: "template", value: "", isInheritable: false }+ ]+ }),+ undefined+ );+ expect(triggerCommand).toHaveBeenCalledWith("openInPopup", { noteIdOrPath: NOTE_ID });+ expect(result).toBe(childNote);+ });+});+describe("createNoteWithTypePrompt", () => {it("returns undefined and posts nothing when the chooser is cancelled", async () => {triggerCommand.mockImplementation((_name: string, data: any) => {diff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.tsindex f41de24063..e1a7d9d547 100644--- a/apps/client/src/services/note_create.ts+++ b/apps/client/src/services/note_create.ts@@ -236,9 +236,41 @@ async function duplicateSubtree(noteId: string, parentNotePath: string) {toastService.showMessage(t("note_create.duplicated", { title: origNote?.title }));}+/**+ * Makes a template under the given note and opens it for the reader to write.+ *+ * A template is a note carrying `#template`, which is what makes it something other notes can be+ * made from. Written here rather than in the view that asked for one, since a collection of any+ * kind may want the same: a board makes the templates its cards are made from, and the next one to+ * offer templates makes them the same way.+ *+ * Opened in a popup rather than in the tab: what asked for it is usually a dialog, which the reader+ * is still standing in and expects to come back to.+ *+ * @returns the note that was made, or nothing where it could not be.+ */+async function createTemplateNote(parentNoteId: string, title: string) {+ const { note } = await createNote(parentNoteId, {+ activate: false,+ title,+ type: "text",+ attributes: [+ { type: "label", name: "template", value: "", isInheritable: false }+ ]+ });++ if (!note) {+ return undefined;+ }++ appContext.triggerCommand("openInPopup", { noteIdOrPath: note.noteId });+ return note;+}+export default {createNote,createNoteWithTypePrompt,+ createTemplateNote,duplicateSubtree,chooseNoteType};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex a5cf9cbbd4..2291dceb32 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -3439,7 +3439,8 @@"card-templates-hint": "Choose what note types and note templates you would like to use when creating new board cards.","add-existing-template": "Add existing template","add-template-title": "Add a template to the board",- "create-template": "Create template",+ "create-template": "Create a new template",+ "new-template-name": "New card template","remove-template": "Remove from the board","more-templates": "More templates…","card-template": "Select a card template",diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 0c1079db5d..7e2080a4c1 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -824,6 +824,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC<BoardPropertiesapi={api}available={availableTemplates}+ note={parentNote}shown={isEditingProperties}onClose={() => setIsEditingProperties(false)}/>diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsxindex 4547be2657..7d42090184 100644--- a/apps/client/src/widgets/collections/board/properties.spec.tsx+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx@@ -4,6 +4,8 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import dialog from "../../../services/dialog";+import type FNote from "../../../entities/fnote";+import note_create from "../../../services/note_create";import { type NoteTypeOption } from "../../../services/note_types";import BoardApi from "./api";import BoardProperties from "./properties";@@ -24,6 +26,9 @@ const AVAILABLE = [id, title, group, icon: "bx bx-note", options: { type: "text" }}) as NoteTypeOption);+/** The board a template made here is filed under. */+const BOARD = { noteId: "board1" } as FNote;+describe("Board properties", () => {let container: HTMLElement;let stored: string[][];@@ -137,8 +142,18 @@ describe("Board properties", () => {expect(captions()).toEqual([ "Text", "Markdown" ]);});- /** The second way in is drawn, and does nothing yet. */- it("offers a way to make one, which makes nothing for now", async () => {+ /**+ * The second way in makes a template of its own: a note under the board carrying+ * `#template`, opened for the reader to write, and offered by the board from then on.+ */+ it("makes a template under the board, and offers it from then on", async () => {+ const made = vi.spyOn(note_create, "createTemplateNote").mockResolvedValue({+ noteId: "fresh",+ title: "board_view.new-template-name",+ type: "text",+ mime: "text/html",+ getIcon: () => "bx bx-note"+ } as unknown as FNote);draw();expect(adders().map((button) => button.textContent)).toEqual([@@ -146,7 +161,23 @@ describe("Board properties", () => {]);await add("board_view.create-template");++ expect(made).toHaveBeenCalledWith("board1", "board_view.new-template-name");+ expect(stored.at(-1)).toEqual([+ "type:text:text/html", "type:code:text/x-markdown", "template:fresh"+ ]);+ // Drawn straight away: the board has yet to hear of the note this was made from.+ expect(captions()).toEqual([ "Text", "Markdown", "board_view.new-template-name" ]);+ });++ it("adds nothing where the template could not be made", async () => {+ vi.spyOn(note_create, "createTemplateNote").mockResolvedValue(undefined);+ draw();++ await add("board_view.create-template");+expect(stored).toEqual([]);+ expect(captions()).toEqual([ "Text", "Markdown" ]);});});@@ -160,7 +191,13 @@ describe("Board properties", () => {act(() => {render(- <BoardProperties api={api} available={AVAILABLE} shown onClose={() => {}} />,+ <BoardProperties+ api={api}+ available={AVAILABLE}+ note={BOARD}+ shown+ onClose={() => {}}+ />,container);});}diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsxindex 813390b451..2795d64c5e 100644--- a/apps/client/src/widgets/collections/board/properties.tsx+++ b/apps/client/src/widgets/collections/board/properties.tsx@@ -4,12 +4,16 @@ import { useCallback, useEffect, useMemo, useState } from "preact/hooks";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";+import note_create from "../../../services/note_create";+import { buildTemplateId } from "@triliumnext/commons";+import { type NoteTypeOption, noteTypeOptionGroupTitle, resolveNoteTypeOptions } from "../../../services/note_types";import ActionButton from "../../react/ActionButton";import Icon from "../../react/Icon";import { type PickerItem, type PickerItemGroup } from "../../dialogs/item_picker";import Modal from "../../react/Modal";import { type SortableItem, SortableCard } from "../../react/SortableCard";+import type FNote from "../../../entities/fnote";import BoardApi from "./api";/**@@ -18,10 +22,12 @@ import BoardApi from "./api";* One card for now, the templates a new card is made from; the dialog is the place the rest of the* board's own settings will be put as they arrive.*/-export default function BoardProperties({ api, available, shown, onClose }: {+export default function BoardProperties({ api, available, note, shown, onClose }: {api: BoardApi,/** Everything a card could be made from, as the board read them. */available: NoteTypeOption[],+ /** The board itself, which is what a template made here is filed under. */+ note: FNote,shown: boolean,onClose: () => void}) {@@ -35,7 +41,7 @@ export default function BoardProperties({ api, available, shown, onClose }: {show={shown}onHidden={onClose}>- <CardTemplates api={api} available={available} shown={shown} />+ <CardTemplates api={api} available={available} shown={shown} note={note} /></Modal>);}@@ -46,11 +52,20 @@ export default function BoardProperties({ api, available, shown, onClose }: {* The order is the reader's to change, since the first of them is what a card is made from until* another is picked, and what the pill in a card's editor leads with.*/-function CardTemplates({ api, available, shown }: {+function CardTemplates({ api, available, note, shown }: {api: BoardApi,available: NoteTypeOption[],+ note: FNote,shown: boolean}) {+ /**+ * What was made here, which the board has yet to read back.+ *+ * A template is a note, and the board learns of one from the change that files it: until that+ * arrives there is nothing to draw the entry from, and it would stand in the stored list+ * without being shown.+ */+ const [ made, setMade ] = useState<NoteTypeOption[]>([]);/*** The list as it stands here, which is what the card is drawn from.*@@ -67,8 +82,11 @@ function CardTemplates({ api, available, shown }: {}}, [ api, shown ]);+ const known = useMemo(+ () => [ ...available, ...made.filter((option) => !available.some((a) => a.id === option.id)) ],+ [ available, made ]);const offered = useMemo(- () => resolveNoteTypeOptions(ids, available), [ available, ids ]);+ () => resolveNoteTypeOptions(ids, known), [ known, ids ]);const items = useMemo(() => offered.map((option) => ({key: option.id,caption: option.title,@@ -94,6 +112,26 @@ function CardTemplates({ api, available, shown }: {: undefined;}, [ available, offered ]);+ /** Makes one under the board and opens it, the reader writing what a card made from it holds. */+ const create = useCallback(async () => {+ const template = await note_create.createTemplateNote(+ note.noteId, t("board_view.new-template-name"));+ if (!template) {+ return undefined;+ }++ const option: NoteTypeOption = {+ id: buildTemplateId(template.noteId),+ title: template.title,+ icon: template.getIcon(),+ group: "user",+ options: { type: template.type, mime: template.mime, templateNoteId: template.noteId }+ };++ setMade((was) => [ ...was, option ]);+ return { key: option.id, caption: option.title, icon: option.icon };+ }, [ note ]);+return (<SortableCardheading={t("board_view.card-templates")}@@ -131,7 +169,7 @@ function CardTemplates({ api, available, shown }: {{label: t("board_view.create-template"),icon: "bx bx-plus",- onCreateItem: () => undefined+ onCreateItem: create}]}/>diff --git a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsxindex 68ffb590a7..244656dce7 100644--- a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx+++ b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx@@ -364,6 +364,36 @@ describe("PopupEditor", () => {expect(document.body.classList.contains("popup-editor-open")).toBe(false);});+ /**+ * The popup is held low on purpose, so the editor's panels and the menus its pickers open float+ * over it. A dialog declaring a layer of its own would cover it, so that dialog gives way for+ * as long as the popup is up, and is put back exactly as it was found.+ */+ it("puts a dialog it stands over underneath it, and back afterwards", async () => {+ const underlying = document.body.appendChild(document.createElement("div"));+ underlying.className = "modal show";+ underlying.style.zIndex = "2000";+ document.body.appendChild(document.createElement("div")).className = "modal-backdrop";++ await openPopup({ noteIdOrPath: "root/n1" });+ expect(underlying.style.zIndex).toBe("1090");++ await act(async () => container.querySelector<HTMLElement>(".hidden-stub")?.click());+ expect(underlying.style.zIndex).toBe("2000");+ });++ /** One standing below it already is left where it is: nothing about it covers the popup. */+ it("leaves a dialog below its own layer alone", async () => {+ const underlying = document.body.appendChild(document.createElement("div"));+ underlying.className = "modal show";+ underlying.style.zIndex = "1055";+ document.body.appendChild(document.createElement("div")).className = "modal-backdrop";++ await openPopup({ noteIdOrPath: "root/n1" });++ expect(underlying.style.zIndex).toBe("1055");+ });+it("raises its own backdrop when it opens over another dialog", async () => {const underlying = document.body.appendChild(document.createElement("div"));underlying.className = "modal show";diff --git a/apps/client/src/widgets/dialogs/PopupEditor.tsx b/apps/client/src/widgets/dialogs/PopupEditor.tsxindex ae7a6bfc8b..5a8c9943a1 100644--- a/apps/client/src/widgets/dialogs/PopupEditor.tsx+++ b/apps/client/src/widgets/dialogs/PopupEditor.tsx@@ -26,6 +26,12 @@ import MobileEditorToolbar from "../type_widgets/text/mobile_editor_toolbar";const isNewLayout = isExperimentalFeatureEnabled("new-layout");+/** The layer the stylesheet gives this popup while it stands over another modal. */+const STACKED_LAYER = 1100;++/** Where a dialog this popup stands over is held while it is up, which is under its backdrop. */+const COVERED_LAYER = 1090;+export default function PopupEditor() {const [ shown, setShown ] = useState(false);const [ stacked, setStacked ] = useState(false);@@ -113,7 +119,34 @@ export default function PopupEditor() {const popupBackdrop = backdrops[backdrops.length - 1] as HTMLElement | undefined;if (!popupBackdrop) return;popupBackdrop.classList.add("popup-editor-backdrop");- return () => popupBackdrop.classList.remove("popup-editor-backdrop");++ /*+ * The stylesheet's stacked layer clears Bootstrap's own dialogs and no more. A dialog that+ * declares a layer of its own stands above it — a confirm or a prompt at 2000, or the+ * properties of a collection that opened this to write a template — and would cover the+ * popup entirely.+ *+ * What gives way is the dialog, not this popup: it is held deliberately low so that the+ * editor's own panels and the menus its pickers open (portalled to the page at 1200) float+ * over it, and raising it above a dialog would put every one of those behind it. Each is+ * put back exactly as it was found, an inline layer of its own included.+ */+ const dialog = modalRef.current;+ const lowered = [ ...document.querySelectorAll<HTMLElement>(".modal.show") ]+ .filter((modal) => modal !== dialog+ && (parseInt(getComputedStyle(modal).zIndex, 10) || 0) >= STACKED_LAYER)+ .map((modal) => {+ const was = modal.style.zIndex;+ modal.style.zIndex = String(COVERED_LAYER);+ return () => { modal.style.zIndex = was; };+ });++ return () => {+ popupBackdrop.classList.remove("popup-editor-backdrop");+ for (const restore of lowered) {+ restore();+ }+ };}, [shown, stacked]);return (