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/refactor: make the template selection card reusable
Adorian Doranb97ea794638c
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 2291dceb32..1e1bd27a9e 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2522,6 +2522,13 @@"note-types": "Note types","built-in-templates": "Built-in templates"},+ "template_selection": {+ "add-existing": "Add existing template",+ "add-title": "Add a template",+ "create": "Create a new template",+ "new-name": "New template",+ "remove": "Remove from the list"+ },"item_picker": {"title": "Pick an item","search": "Search…",@@ -3437,11 +3444,6 @@"properties-title": "Board properties","card-templates": "Card templates","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 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","collapse-hint": "Double click to collapse",diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex 7e2080a4c1..7a6013bbae 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -823,7 +823,6 @@ 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.css b/apps/client/src/widgets/collections/board/properties.cssdeleted file mode 100644index 0ee3daa19d..0000000000--- a/apps/client/src/widgets/collections/board/properties.css+++ /dev/null@@ -1,13 +0,0 @@-.modal.board-properties-dialog {- /* The name takes what room there is, so the way to remove an entry stands at its trailing edge. */- .board-template-name {- flex-grow: 1;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;- }-- .board-template-remove {- flex-shrink: 0;- }-}diff --git a/apps/client/src/widgets/collections/board/properties.spec.tsx b/apps/client/src/widgets/collections/board/properties.spec.tsxindex 7d42090184..8ab1e3d64b 100644--- a/apps/client/src/widgets/collections/board/properties.spec.tsx+++ b/apps/client/src/widgets/collections/board/properties.spec.tsx@@ -3,10 +3,7 @@ import { render } from "preact";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";@@ -15,30 +12,48 @@ vi.mock("../../../services/i18n", () => ({t: (key: string) => key}));-/** Everything the app could make, as `getNoteTypeOptions` answers with it. */-const AVAILABLE = [- [ "type:text:text/html", "Text", "type" ],- [ "type:code:text/x-markdown", "Markdown", "type" ],- [ "type:canvas:application/json", "Canvas", "type" ],- [ "template:shipped", "Shipped template", "builtin" ],- [ "template:mine", "My template", "user" ]-].map(([ id, title, group ]) => ({- 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;+// The card is the app's and is tested where it lives; what the board answers for is the words it is+// given and where what it holds is written.+vi.mock("../../react/TemplateSelectionCard", () => ({+ default: ({ heading, instruction, note, templates, onChange }: {+ heading: string, instruction: string, note: FNote, templates: string[],+ onChange: (templates: string[]) => void+ }) => (+ <div+ className="templates-stub"+ data-heading={heading}+ data-instruction={instruction}+ data-note={note.noteId}+ data-templates={templates.join(",")}+ onClick={() => onChange([ "type:canvas:application/json" ])}+ />+ )+}));describe("Board properties", () => {let container: HTMLElement;let stored: string[][];- let offered: string[];beforeEach(() => {stored = [];- offered = [ "type:text:text/html", "type:code:text/x-markdown" ];container = document.createElement("div");document.body.appendChild(container);++ const api = {+ getCardTemplateIds: () => [ "type:text:text/html" ],+ setCardTemplateIds: async (ids: string[]) => { stored.push(ids); }+ } as unknown as BoardApi;++ act(() => {+ render(+ <BoardProperties+ api={api}+ note={{ noteId: "board1" } as FNote}+ shown+ onClose={() => {}}+ />,+ container);+ });});afterEach(() => {@@ -58,182 +73,25 @@ describe("Board properties", () => {document.body.classList.remove("modal-open");});- it("lists what the board offers, in the order it stores them", () => {- draw();+ it("holds the card templates, named and explained in the board's own words", () => {+ const card = dialog()?.querySelector<HTMLElement>(".templates-stub");- expect(captions()).toEqual([ "Text", "Markdown" ]);- expect(dialog_()?.querySelector(".tn-card-heading")?.textContent)- .toContain("board_view.card-templates");- expect(dialog_()?.querySelector(".tn-card-description")?.textContent)- .toBe("board_view.card-templates-hint");+ expect(dialog()?.querySelector(".modal-title")?.textContent)+ .toContain("board_view.properties-title");+ expect(card?.dataset.heading).toBe("board_view.card-templates");+ expect(card?.dataset.instruction).toBe("board_view.card-templates-hint");+ // Filed under the board, and drawn from what the board offers now.+ expect(card?.dataset.note).toBe("board1");+ expect(card?.dataset.templates).toBe("type:text:text/html");});- /** The grip leads, so the trailing edge is left to what each entry carries there. */- it("carries the grip at the start of an entry and the way to remove it at the end", () => {- draw();- const [ first ] = segments();-- expect(first.firstElementChild?.className).toContain("tn-sortable-grip");- // Inside what the card draws for an entry, which is the rest of the segment.- expect(first.querySelector(".tn-sortable-content")?.lastElementChild?.className)- .toContain("board-template-remove");- });-- it("stores the order the reader puts them in", () => {- draw();-- press(segments()[0], "ArrowDown", { ctrlKey: true });+ it("writes what the card answers with back to the board", () => {+ act(() => { dialog()?.querySelector<HTMLElement>(".templates-stub")?.click(); });- expect(stored).toEqual([ [ "type:code:text/x-markdown", "type:text:text/html" ] ]);+ expect(stored).toEqual([ [ "type:canvas:application/json" ] ]);});- it("takes an entry away, and leaves the last one alone", () => {- draw();-- act(() => { segments()[0].querySelector<HTMLElement>(".board-template-remove")?.click(); });-- expect(stored).toEqual([ [ "type:code:text/x-markdown" ] ]);- // And gone from the card, which is drawn from the list this dialog holds rather than from- // the board it wrote to.- expect(captions()).toEqual([ "Markdown" ]);-- // Nothing to make a card from is nothing the board could make one with, so the way to- // take the last one away is not offered at all.- offered = [ "type:text:text/html" ];- draw();- expect(segments()[0].querySelector(".board-template-remove")).toBeNull();- });-- describe("adding one", () => {- it("offers the note types and the reader's own templates, and not the app's", async () => {- const picking = vi.spyOn(dialog, "pickSingleItem").mockResolvedValue(null);- draw();-- await add("board_view.add-existing-template");-- const groups = picking.mock.calls.at(-1)?.[0].items as {- key: string, items: { key: string }[]- }[];- expect(groups.map((group) => group.key)).toEqual([ "type", "user" ]);- // What the board already offers is left out, as is everything the app ships.- expect(groups.flatMap((group) => group.items.map((item) => item.key)))- .toEqual([ "type:canvas:application/json", "template:mine" ]);- });-- it("adds what was picked to the end of the list", async () => {- vi.spyOn(dialog, "pickSingleItem")- .mockResolvedValue({ key: "template:mine", caption: "My template" });- draw();-- await add("board_view.add-existing-template");-- expect(stored.at(-1))- .toEqual([ "type:text:text/html", "type:code:text/x-markdown", "template:mine" ]);- expect(captions()).toEqual([ "Text", "Markdown", "My template" ]);- });-- it("adds nothing where the reader backed out of the picker", async () => {- vi.spyOn(dialog, "pickSingleItem").mockResolvedValue(null);- draw();-- await add("board_view.add-existing-template");-- expect(stored).toEqual([]);- expect(captions()).toEqual([ "Text", "Markdown" ]);- });-- /**- * 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([- "board_view.add-existing-template", "board_view.create-template"- ]);-- 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" ]);- });- });-- // #region The dialog, and what the test does to it-- function draw() {- const api = {- getCardTemplateIds: () => offered,- setCardTemplateIds: async (ids: string[]) => { stored.push(ids); }- } as unknown as BoardApi;-- act(() => {- render(- <BoardProperties- api={api}- available={AVAILABLE}- note={BOARD}- shown- onClose={() => {}}- />,- container);- });- }-- function dialog_() {+ function dialog() {return document.querySelector<HTMLElement>(".board-properties-dialog");}-- function segments() {- return [ ...(dialog_()?.querySelectorAll<HTMLElement>(".tn-sortable-segment") ?? []) ];- }-- function captions() {- return segments().map((element) =>- element.querySelector(".board-template-name")?.textContent);- }-- function adders() {- return [ ...(dialog_()?.querySelectorAll<HTMLElement>(".tn-sortable-adder") ?? []) ];- }-- async function add(label: string) {- const button = adders().find((element) => element.textContent === label);- await act(async () => {- button?.click();- await Promise.resolve();- await Promise.resolve();- });- }-- function press(target: Element, key: string, options: KeyboardEventInit = {}) {- act(() => {- target.dispatchEvent(- new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options }));- });- }-- // #endregion});diff --git a/apps/client/src/widgets/collections/board/properties.tsx b/apps/client/src/widgets/collections/board/properties.tsxindex 2795d64c5e..a55062e993 100644--- a/apps/client/src/widgets/collections/board/properties.tsx+++ b/apps/client/src/widgets/collections/board/properties.tsx@@ -1,19 +1,9 @@-import "./properties.css";+import { useCallback } from "preact/hooks";-import { useCallback, useEffect, useMemo, useState } from "preact/hooks";--import dialog from "../../../services/dialog";+import type FNote from "../../../entities/fnote";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 TemplateSelectionCard from "../../react/TemplateSelectionCard";import BoardApi from "./api";/**@@ -22,15 +12,16 @@ 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, note, shown, onClose }: {+export default function BoardProperties({ api, 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}) {+ const store = useCallback(+ (templates: string[]) => api.setCardTemplateIds(templates), [ api ]);+return (<ModalclassName="board-properties-dialog"@@ -41,167 +32,13 @@ export default function BoardProperties({ api, available, note, shown, onClose }show={shown}onHidden={onClose}>- <CardTemplates api={api} available={available} shown={shown} note={note} />+ <TemplateSelectionCard+ heading={t("board_view.card-templates")}+ instruction={t("board_view.card-templates-hint")}+ note={note}+ templates={api.getCardTemplateIds()}+ onChange={store}+ /></Modal>);}--/**- * The templates a new card can be made from, in the order the board stores them.- *- * 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, 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.- *- * Held rather than read from the board on every draw: a change made here is written straight- * through, and the board has nothing to draw this dialog again for, so what is shown would- * otherwise be the list as it was when the dialog opened.- */- const [ ids, setIds ] = useState(() => api.getCardTemplateIds());-- // Read afresh each time the dialog opens, the board having been changed elsewhere meanwhile.- useEffect(() => {- if (shown) {- setIds(api.getCardTemplateIds());- }- }, [ api, shown ]);-- const known = useMemo(- () => [ ...available, ...made.filter((option) => !available.some((a) => a.id === option.id)) ],- [ available, made ]);- const offered = useMemo(- () => resolveNoteTypeOptions(ids, known), [ known, ids ]);- const items = useMemo(() => offered.map((option) => ({- key: option.id,- caption: option.title,- icon: option.icon- })), [ offered ]);-- const store = useCallback((order: SortableItem[]) => {- const next = order.map((item) => item.key);- setIds(next);- api.setCardTemplateIds(next);- }, [ api ]);-- /** Asks which of the ones not already offered to add, and answers with it as an entry. */- const addExisting = useCallback(async () => {- const taken = new Set(offered.map((option) => option.id));- const picked = await dialog.pickSingleItem({- title: t("board_view.add-template-title"),- items: pickable(available, taken)- });-- return picked- ? { key: picked.key, caption: picked.caption, icon: picked.icon }- : 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 (- <SortableCard- heading={t("board_view.card-templates")}- description={t("board_view.card-templates-hint")}- items={items}- onChange={store}- // The grip leads, so the trailing edge is left to what each entry carries there.- gripPlacement="start"- renderItem={(item, index) => (- <>- {item.icon && <Icon icon={item.icon} />}- <span className="board-template-name">{item.caption}</span>-- {/* The last one left is not removable: a board with nothing to make a card- from could make none, so the write behind this refuses it anyway. */}- {items.length > 1 && (- <ActionButton- className="board-template-remove"- icon="bx bx-x"- text={t("board_view.remove-template")}- onClick={(event) => {- event.stopPropagation();- store(items.filter((unused, at) => at !== index));- }}- />- )}- </>- )}- itemCreationButtons={[- {- label: t("board_view.add-existing-template"),- icon: "bx bx-list-plus",- onCreateItem: addExisting- },- {- label: t("board_view.create-template"),- icon: "bx bx-plus",- onCreateItem: create- }- ]}- />- );-}--/**- * What can still be added, as groups for the picker.- *- * The templates the app ships are left out: they are a starting point for a note of one's own- * rather than something a board is set up to make its cards from.- */-function pickable(available: NoteTypeOption[], taken: Set<string>): PickerItemGroup[] {- const groups = new Map<string, PickerItemGroup>();-- for (const option of available) {- if (option.group === "builtin" || taken.has(option.id)) {- continue;- }-- const group = groups.get(option.group) ?? {- key: option.group,- groupHeader: noteTypeOptionGroupTitle(option.group),- items: []- };-- const entry: PickerItem = {- key: option.id, caption: option.title, icon: option.icon- };- group.items.push(entry);- groups.set(option.group, group);- }-- return [ ...groups.values() ];-}diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.css b/apps/client/src/widgets/react/TemplateSelectionCard.cssnew file mode 100644index 0000000000..3df0e806c2--- /dev/null+++ b/apps/client/src/widgets/react/TemplateSelectionCard.css@@ -0,0 +1,11 @@+/* The name takes what room there is, so the way to remove an entry stands at its trailing edge. */+.template-selection-name {+ flex-grow: 1;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.template-selection-remove {+ flex-shrink: 0;+}diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsxnew file mode 100644index 0000000000..dfa6416e3b--- /dev/null+++ b/apps/client/src/widgets/react/TemplateSelectionCard.spec.tsx@@ -0,0 +1,224 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type FNote from "../../entities/fnote";+import dialog from "../../services/dialog";+import note_create from "../../services/note_create";+import { getNoteTypeOptions, type NoteTypeOption } from "../../services/note_types";+import TemplateSelectionCard from "./TemplateSelectionCard";++// i18next is never initialised under test, so every label would read as undefined.+vi.mock("../../services/i18n", () => ({+ t: (key: string) => key+}));++// The listing is the app's and is tested there; the card is handed a short one of each kind.+vi.mock("../../services/note_types", async () => {+ const actual = await vi.importActual<typeof import("../../services/note_types")>(+ "../../services/note_types");+ return { ...actual, getNoteTypeOptions: vi.fn(async () => AVAILABLE) };+});++/** Everything the app could make, as `getNoteTypeOptions` answers with it. */+const AVAILABLE = [+ [ "type:text:text/html", "Text", "type" ],+ [ "type:code:text/x-markdown", "Markdown", "type" ],+ [ "type:canvas:application/json", "Canvas", "type" ],+ [ "template:shipped", "Shipped template", "builtin" ],+ [ "template:mine", "My template", "user" ]+].map(([ id, title, group ]) => ({+ id, title, group, icon: "bx bx-note", options: { type: "text" }+}) as NoteTypeOption);++/** The note a template made here is filed under. */+const OWNER = { noteId: "owner1" } as FNote;++describe("TemplateSelectionCard", () => {+ let container: HTMLElement;+ let stored: string[][];+ let offered: string[];++ beforeEach(() => {+ stored = [];+ offered = [ "type:text:text/html", "type:code:text/x-markdown" ];+ container = document.createElement("div");+ document.body.appendChild(container);+ });++ afterEach(() => {+ render(null, container);+ container.remove();+ });++ it("lists what it is given, in the order it is given them, under the caller's words", async () => {+ await draw();++ expect(captions()).toEqual([ "Text", "Markdown" ]);+ expect(container.querySelector(".tn-card-heading")?.textContent).toContain("What to use");+ expect(container.querySelector(".tn-card-description")?.textContent)+ .toBe("Pick what a new one is made from.");+ });++ /** The grip leads, so the trailing edge is left to what each entry carries there. */+ it("carries the grip at the start of an entry and the way to remove it at the end", async () => {+ await draw();+ const [ first ] = segments();++ expect(first.firstElementChild?.className).toContain("tn-sortable-grip");+ // Inside what the card draws for an entry, which is the rest of the segment.+ expect(first.querySelector(".tn-sortable-content")?.lastElementChild?.className)+ .toContain("template-selection-remove");+ });++ it("stores the order the reader puts them in", async () => {+ await draw();++ press(segments()[0], "ArrowDown", { ctrlKey: true });++ expect(stored).toEqual([ [ "type:code:text/x-markdown", "type:text:text/html" ] ]);+ });++ it("takes an entry away, and leaves the last one alone", async () => {+ await draw();++ act(() => { segments()[0].querySelector<HTMLElement>(".template-selection-remove")?.click(); });++ expect(stored).toEqual([ [ "type:code:text/x-markdown" ] ]);+ // And gone from the card, which is drawn from the list this dialog holds rather than from+ // the board it wrote to.+ expect(captions()).toEqual([ "Markdown" ]);++ // Nothing to make a card from is nothing the board could make one with, so the way to+ // take the last one away is not offered at all.+ offered = [ "type:text:text/html" ];+ await draw();+ expect(segments()[0].querySelector(".template-selection-remove")).toBeNull();+ });++ describe("adding one", () => {+ it("offers the note types and the reader's own templates, and not the app's", async () => {+ const picking = vi.spyOn(dialog, "pickSingleItem").mockResolvedValue(null);+ await draw();++ await add("template_selection.add-existing");++ const groups = picking.mock.calls.at(-1)?.[0].items as {+ key: string, items: { key: string }[]+ }[];+ expect(groups.map((group) => group.key)).toEqual([ "type", "user" ]);+ // What the board already offers is left out, as is everything the app ships.+ expect(groups.flatMap((group) => group.items.map((item) => item.key)))+ .toEqual([ "type:canvas:application/json", "template:mine" ]);+ });++ it("adds what was picked to the end of the list", async () => {+ vi.spyOn(dialog, "pickSingleItem")+ .mockResolvedValue({ key: "template:mine", caption: "My template" });+ await draw();++ await add("template_selection.add-existing");++ expect(stored.at(-1))+ .toEqual([ "type:text:text/html", "type:code:text/x-markdown", "template:mine" ]);+ expect(captions()).toEqual([ "Text", "Markdown", "My template" ]);+ });++ it("adds nothing where the reader backed out of the picker", async () => {+ vi.spyOn(dialog, "pickSingleItem").mockResolvedValue(null);+ await draw();++ await add("template_selection.add-existing");++ expect(stored).toEqual([]);+ expect(captions()).toEqual([ "Text", "Markdown" ]);+ });++ /**+ * 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: "template_selection.new-name",+ type: "text",+ mime: "text/html",+ getIcon: () => "bx bx-note"+ } as unknown as FNote);+ await draw();++ expect(adders().map((button) => button.textContent)).toEqual([+ "template_selection.add-existing", "template_selection.create"+ ]);++ await add("template_selection.create");++ expect(made).toHaveBeenCalledWith("owner1", "template_selection.new-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", "template_selection.new-name" ]);+ });++ it("adds nothing where the template could not be made", async () => {+ vi.spyOn(note_create, "createTemplateNote").mockResolvedValue(undefined);+ await draw();++ await add("template_selection.create");++ expect(stored).toEqual([]);+ expect(captions()).toEqual([ "Text", "Markdown" ]);+ });+ });++ // #region The dialog, and what the test does to it++ /** Drawn, and given the moment it takes to read what a note can be made from. */+ async function draw() {+ await act(async () => {+ render(+ <TemplateSelectionCard+ heading="What to use"+ instruction="Pick what a new one is made from."+ note={OWNER}+ templates={offered}+ onChange={(ids) => stored.push(ids)}+ />,+ container);+ await Promise.resolve();+ });+ }++ function segments() {+ return [ ...container.querySelectorAll<HTMLElement>(".tn-sortable-segment") ];+ }++ function captions() {+ return segments().map((element) =>+ element.querySelector(".template-selection-name")?.textContent);+ }++ function adders() {+ return [ ...container.querySelectorAll<HTMLElement>(".tn-sortable-adder") ];+ }++ async function add(label: string) {+ const button = adders().find((element) => element.textContent === label);+ await act(async () => {+ button?.click();+ await Promise.resolve();+ await Promise.resolve();+ });+ }++ function press(target: Element, key: string, options: KeyboardEventInit = {}) {+ act(() => {+ target.dispatchEvent(+ new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...options }));+ });+ }++ // #endregion+});diff --git a/apps/client/src/widgets/react/TemplateSelectionCard.tsx b/apps/client/src/widgets/react/TemplateSelectionCard.tsxnew file mode 100644index 0000000000..deacc6bf57--- /dev/null+++ b/apps/client/src/widgets/react/TemplateSelectionCard.tsx@@ -0,0 +1,196 @@+import "./TemplateSelectionCard.css";++import { buildTemplateId } from "@triliumnext/commons";+import { useCallback, useEffect, useMemo, useState } from "preact/hooks";++import type FNote from "../../entities/fnote";+import dialog from "../../services/dialog";+import { t } from "../../services/i18n";+import note_create from "../../services/note_create";+import {+ getNoteTypeOptions, type NoteTypeOption, noteTypeOptionGroupTitle, resolveNoteTypeOptions+} from "../../services/note_types";+import { type PickerItem, type PickerItemGroup } from "../dialogs/item_picker";+import ActionButton from "./ActionButton";+import Icon from "./Icon";+import { type SortableItem, SortableCard } from "./SortableCard";++export interface TemplateSelectionCardProps {+ heading: string;+ /** The sentence saying what the templates are for, shown under the heading. */+ instruction: string;+ /** The note the templates belong to, which is what one made here is filed under. */+ note: FNote;+ /** What is offered now, as note type ids, in the order they are offered in. */+ templates: string[];+ /** Said with the whole list whenever the reader changes it. */+ onChange: (templates: string[]) => void;+}++/**+ * The templates something is made from, in the order they are offered in.+ *+ * The order is the reader's to change, since the first of them is what is made until another is+ * picked. Entries are added from what the app can already make, or made here and written straight+ * away; the caller keeps the list and decides what it means.+ *+ * Everything a note can be made from is read by the card itself, so a caller has only to say what+ * it holds now and where a new one belongs.+ */+export default function TemplateSelectionCard({+ heading, instruction, note, templates, onChange+}: TemplateSelectionCardProps) {+ /**+ * The list as it stands here, which is what the card is drawn from.+ *+ * Held rather than read from the caller on every draw: a change is written straight through,+ * and a caller that has nothing to redraw for would otherwise leave the list as it was found.+ */+ const [ ids, setIds ] = useState(templates);+ /** Everything a note can be made from, read once the card is drawn. */+ const [ available, setAvailable ] = useState<NoteTypeOption[]>([]);+ /**+ * What was made here, which the app has yet to read back.+ *+ * A template is a note, and it is known 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[]>([]);++ useEffect(() => setIds(templates), [ templates ]);++ useEffect(() => {+ let listening = true;+ getNoteTypeOptions()+ .then((options) => {+ if (listening) {+ setAvailable(options);+ }+ })+ .catch((e) => console.error("Failed to read what a note can be made from:", e));++ return () => { listening = false; };+ }, []);++ const known = useMemo(+ () => [ ...available, ...made.filter((option) => !available.some((a) => a.id === option.id)) ],+ [ available, made ]);+ const offered = useMemo(() => resolveNoteTypeOptions(ids, known), [ ids, known ]);+ const items = useMemo(() => offered.map((option) => ({+ key: option.id,+ caption: option.title,+ icon: option.icon+ })), [ offered ]);++ const store = useCallback((order: SortableItem[]) => {+ const next = order.map((item) => item.key);+ setIds(next);+ onChange(next);+ }, [ onChange ]);++ /** Asks which of the ones not already offered to add, and answers with it as an entry. */+ const addExisting = useCallback(async () => {+ const taken = new Set(offered.map((option) => option.id));+ const picked = await dialog.pickSingleItem({+ title: t("template_selection.add-title"),+ items: pickable(available, taken)+ });++ return picked+ ? { key: picked.key, caption: picked.caption, icon: picked.icon }+ : undefined;+ }, [ available, offered ]);++ /** Makes one and opens it, the reader writing what a note made from it holds. */+ const create = useCallback(async () => {+ const template = await note_create.createTemplateNote(+ note.noteId, t("template_selection.new-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 (+ <SortableCard+ heading={heading}+ description={instruction}+ items={items}+ onChange={store}+ // The grip leads, so the trailing edge is left to what each entry carries there.+ gripPlacement="start"+ renderItem={(item, index) => (+ <>+ {item.icon && <Icon icon={item.icon} />}+ <span className="template-selection-name">{item.caption}</span>++ {/* The last one left is not removable: nothing offered is nothing that could be+ made, so the caller has none to fall back on. */}+ {items.length > 1 && (+ <ActionButton+ className="template-selection-remove"+ icon="bx bx-x"+ text={t("template_selection.remove")}+ onClick={(event) => {+ event.stopPropagation();+ store(items.filter((unused, at) => at !== index));+ }}+ />+ )}+ </>+ )}+ itemCreationButtons={[+ {+ label: t("template_selection.add-existing"),+ icon: "bx bx-list-plus",+ onCreateItem: addExisting+ },+ {+ label: t("template_selection.create"),+ icon: "bx bx-plus",+ onCreateItem: create+ }+ ]}+ />+ );+}++/**+ * What can still be added, as groups for the picker.+ *+ * The templates the app ships are left out: they are a starting point for a note of one's own+ * rather than something to be made from over and over.+ */+function pickable(available: NoteTypeOption[], taken: Set<string>): PickerItemGroup[] {+ const groups = new Map<string, PickerItemGroup>();++ for (const option of available) {+ if (option.group === "builtin" || taken.has(option.id)) {+ continue;+ }++ const group = groups.get(option.group) ?? {+ key: option.group,+ groupHeader: noteTypeOptionGroupTitle(option.group),+ items: []+ };++ const entry: PickerItem = {+ key: option.id, caption: option.title, icon: option.icon+ };+ group.items.push(entry);+ groups.set(option.group, group);+ }++ return [ ...groups.values() ];+}