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: create the initial implementation for card templates
Adorian Doran98e5e65c6c22
diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.tsindex d971fdd929..eeb56a1bd6 100644--- a/apps/client/src/services/note_types.spec.ts+++ b/apps/client/src/services/note_types.spec.ts@@ -73,6 +73,85 @@ function withTemplatesRoot(children: FakeNote[] | null) {};}+describe("getNoteTypeOptions", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ llmFlag.mockReturnValue(false);+ });++ /**+ * What anything offering "make a new note of..." picks from: the note types the tree offers,+ * then the templates the app ships, then the reader's own, each named by an id that outlives+ * the list it came from.+ */+ it("lists the note types the tree offers, then every template", async () => {+ withTemplates([ "userTemplate" ]);+ const restore = withTemplatesRoot([+ fakeTemplate("shipped", [ "template" ], "Shipped"),+ fakeTemplate("notATemplate", [], "Not a template")+ ]);+ const user = buildNote({ id: "userTemplate", title: "Mine", "#template": "" });++ try {+ const options = await noteTypesService.getNoteTypeOptions();++ const types = options.filter(option => option.group === "type");+ expect(types.every(option => option.id.startsWith("type:"))).toBe(true);+ expect(types.some(option => option.id === "type:text:text/html")).toBe(true);+ expect(types.some(option => option.id.startsWith("type:book"))).toBe(false);+ expect(types.some(option => option.id.startsWith("type:image"))).toBe(false);++ // A note under `_templates` that carries no `#template` is not one.+ expect(options.map(option => option.id)).toContain("template:shipped");+ expect(options.map(option => option.id)).not.toContain("template:notATemplate");++ const mine = options.find(option => option.id === `template:${user.noteId}`);+ expect(mine?.group).toBe("user");+ expect(mine?.options).toEqual(expect.objectContaining({ templateNoteId: user.noteId }));++ // A note type is made from its type and mime, which is what `createNote` takes.+ expect(options.find(option => option.id === "type:canvas:application/json")?.options)+ .toEqual({ type: "canvas", mime: "application/json" });+ } finally {+ restore();+ }+ });++ it("offers the chat note type only where that feature is switched on", async () => {+ withTemplates();+ const restore = withTemplatesRoot([]);++ try {+ const isOffered = async () => (await noteTypesService.getNoteTypeOptions())+ .some(option => option.id.startsWith("type:llmChat"));++ expect(await isOffered()).toBe(false);+ llmFlag.mockReturnValue(true);+ expect(await isOffered()).toBe(true);+ } finally {+ restore();+ }+ });++ /** A stored list outlives what it names, and what is gone is left out rather than reported. */+ it("resolves stored ids in their own order, dropping what no longer exists", async () => {+ withTemplates();+ const restore = withTemplatesRoot([]);++ try {+ const available = await noteTypesService.getNoteTypeOptions();+ const offered = noteTypesService.resolveNoteTypeOptions(+ [ "type:canvas:application/json", "template:gone", "type:text:text/html" ],+ available);++ expect(offered.map(option => option.id))+ .toEqual([ "type:canvas:application/json", "type:text:text/html" ]);+ } finally {+ restore();+ }+ });+});+describe("getBlankNoteTypes (via getNoteTypeItems)", () => {beforeEach(() => {vi.clearAllMocks();diff --git a/apps/client/src/services/note_types.ts b/apps/client/src/services/note_types.tsindex 24741f71ae..961b5ac062 100644--- a/apps/client/src/services/note_types.ts+++ b/apps/client/src/services/note_types.ts@@ -1,4 +1,7 @@-import type { TemplatesResponse } from "@triliumnext/commons";+import {+ buildNoteTypeId, buildTemplateId, type NoteType as CommonNoteType, type NoteTypeId,+ type TemplatesResponse+} from "@triliumnext/commons";import type FNote from "../entities/fnote.js";import type { NoteType } from "../entities/fnote.js";@@ -62,6 +65,90 @@ export const NOTE_TYPES: NoteTypeMapping[] = [{ type: "launcher", mime: "", title: t("note_types.launcher"), reserved: true },];+/**+ * One thing a new note can be made from: a blank note type, or a note carrying `#template`.+ *+ * Named by a {@link NoteTypeId}, so that a stored choice outlives the list it was picked from and+ * anything offering the choice, a board's card templates included, speaks of it the same way.+ */+export interface NoteTypeOption {+ id: NoteTypeId;+ title: string;+ /** The icon class, `bx` prefix included. */+ icon: string;+ /** Where it stands in a list the reader picks from. */+ group: NoteTypeOptionGroup;+ /** What `createNote` is given to make one. */+ options: { type: NoteType; mime?: string; templateNoteId?: string };+}++export type NoteTypeOptionGroup = "type" | "builtin" | "user";++/**+ * Everything a new note can be made from: the blank note types, the templates the app ships, and+ * the reader's own.+ *+ * The note types are the ones the tree offers to create, so that anything built on this offers to+ * make what the tree offers to make and nothing else.+ */+export async function getNoteTypeOptions(): Promise<NoteTypeOption[]> {+ const { builtInTemplateNotes, userTemplateNotes } = await loadNoteTypeData();++ const types = NOTE_TYPES+ .filter((mapping) => !mapping.reserved && mapping.type !== "book")+ .filter((mapping) => mapping.type !== "llmChat" || isExperimentalFeatureEnabled("llm"))+ .map<NoteTypeOption>((mapping) => ({+ id: buildNoteTypeId(mapping.type as CommonNoteType, mapping.mime),+ title: mapping.title,+ icon: `bx ${mapping.icon ?? "bx-note"}`,+ group: "type",+ options: { type: mapping.type, mime: mapping.mime }+ }));++ return [+ ...types,+ ...templateOptions(+ builtInTemplateNotes.filter((note) => note.hasLabel("template")), "builtin"),+ ...templateOptions(userTemplateNotes, "user")+ ];+}++/**+ * The options named by the given ids, in that order, leaving out what no longer exists.+ *+ * A stored id outlives what it names: a note type can be dropped from the app and a template note+ * deleted. What is gone is left out rather than reported, so a stored list stays usable.+ */+export function resolveNoteTypeOptions(ids: NoteTypeId[], available: NoteTypeOption[]) {+ const byId = new Map(available.map((option) => [ option.id, option ]));+ return ids.flatMap((id) => {+ const option = byId.get(id);+ return option ? [ option ] : [];+ });+}++/** The name of the group an option stands in, for a list the reader picks from. */+export function noteTypeOptionGroupTitle(group: NoteTypeOptionGroup) {+ switch (group) {+ case "type":+ return t("note_types.note-types");+ case "builtin":+ return t("note_types.built-in-templates");+ default:+ return t("note_type_chooser.templates");+ }+}++function templateOptions(notes: FNote[], group: NoteTypeOptionGroup): NoteTypeOption[] {+ return notes.map((note) => ({+ id: buildTemplateId(note.noteId),+ title: note.title,+ icon: note.getIcon(),+ group,+ options: { type: note.type, mime: note.mime, templateNoteId: note.noteId }+ }));+}+/** The menu item badge used to mark new note types and templates */const NEW_BADGE: MenuItemBadge = {title: t("note_types.new-feature"),@@ -235,5 +322,7 @@ function getBuiltInTemplates(title: string | null, command: TreeCommandNames | uexport default {loadNoteTypeData,buildNoteTypeItems,- getNoteTypeItems+ getNoteTypeItems,+ getNoteTypeOptions,+ resolveNoteTypeOptions};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 902c3b47db..7ec125e368 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2518,7 +2518,10 @@"task-list": "Task List","new-feature": "New","collections": "Collections",- "spreadsheet": "Spreadsheet"+ "spreadsheet": "Spreadsheet",+ "note-types": "Note types",+ "built-in-templates": "Built-in templates",+ "selector-save": "Save"},"protect_note": {"toggle-on": "Protect the note",@@ -3419,6 +3422,10 @@"expand-all-columns": "Expand all columns","show-inbox-column": "Show inbox column","show-archived-notes": "Show archived notes",+ "more-templates": "More templates…",+ "card-template": "Select a card template",+ "templates-title": "Templates offered on this board",+ "templates-hint": "Pick what a new card can be made from. At least one is needed.","collapse-hint": "Double click to collapse","set-limit": "Set limit...","set-limit-ok": "Set limit",diff --git a/apps/client/src/widgets/collections/board/api.spec.ts b/apps/client/src/widgets/collections/board/api.spec.tsindex 4e36eeb274..cc86971df5 100644--- a/apps/client/src/widgets/collections/board/api.spec.ts+++ b/apps/client/src/widgets/collections/board/api.spec.ts@@ -17,6 +17,7 @@ import { BoardViewData } from ".";import BoardApi, { getPendingWrites, PendingColumnWrites } from "./api";import { ColumnMap } from "./data";import { BOARD_TEMPLATE_ID, DEFAULT_COLUMN_ICON, getStatusDefinition, INBOX_COLUMN } from "./columns";+import { DEFAULT_CARD_TEMPLATES } from "./card_templates";vi.mock("../../../services/bulk_action", () => ({executeBulkActions: vi.fn(async () => {})@@ -734,6 +735,112 @@ describe("BoardApi card operations", () => {expect(moveBefore).not.toHaveBeenCalled();});+ /**+ * What a board offers and what it last made a card from live in its own configuration, beside+ * the columns: the templates are the board's, not a column's.+ */+ it("offers the stock templates until the board has its own, and remembers the last used", async () => {+ const { api, saved } = createApi({ columns: [ { value: "To Do" } ] }, [ "To Do" ]);++ expect(api.getCardTemplateIds()).toEqual(DEFAULT_CARD_TEMPLATES);+ expect(api.getLastCardTemplateId()).toBeUndefined();++ await api.setCardTemplateIds([ "type:canvas:application/json", "note:mine" ]);+ expect(saved.at(-1)?.templates).toEqual([ "type:canvas:application/json", "note:mine" ]);+ // Written beside the columns rather than over them.+ expect(saved.at(-1)?.columns).toEqual([ { value: "To Do" } ]);+ expect(api.getCardTemplateIds()).toEqual([ "type:canvas:application/json", "note:mine" ]);++ await api.setLastCardTemplateId("note:mine");+ expect(saved.at(-1)?.template).toBe("note:mine");+ expect(saved.at(-1)?.templates).toEqual([ "type:canvas:application/json", "note:mine" ]);++ // The same one again is not a change, and writing it would refresh the board for nothing.+ const writes = saved.length;+ await api.setLastCardTemplateId("note:mine");+ expect(saved.length).toBe(writes);+ });++ /**+ * A card inserted beside another one is made from the same template as one made in the footer,+ * without the editor it is named in having to know about templates at all.+ */+ it("makes an inserted card from the template last used", async () => {+ const { api } = createBoardWithCards();+ api.setAvailableCardTemplates([+ {+ id: "type:text:text/html", title: "Text", icon: "bx bx-note", group: "type",+ options: { type: "text", mime: "text/html" }+ },+ {+ id: "type:canvas:application/json", title: "Canvas", icon: "bx bx-pen",+ group: "type", options: { type: "canvas", mime: "application/json" }+ }+ ]);+ vi.mocked(note_create.createNote).mockResolvedValue({+ note: buildNote({ title: "Created" }), branch: { branchId: "createdBranch" }+ } as never);++ // Nothing has been used yet, so the first the board offers stands.+ await api.insertRowAtPosition("Done", "branchId", "after");+ expect(note_create.createNote).toHaveBeenLastCalledWith(+ expect.any(String), expect.objectContaining({ type: "text" }));++ await api.setLastCardTemplateId("type:canvas:application/json");+ await api.insertRowAtPosition("Done", "branchId", "after");+ expect(note_create.createNote).toHaveBeenLastCalledWith(+ expect.any(String), expect.objectContaining({ type: "canvas" }));++ // And a card made in the footer, where the editor hands one over, is made from that.+ await api.createNewItem("Done", "Typed");+ expect(note_create.createNote).toHaveBeenLastCalledWith(+ expect.any(String), expect.objectContaining({ type: "canvas" }));+ });++ /** A board with nothing offered could make no card at all, so an empty set is refused. */+ it("refuses to store an empty set of templates", async () => {+ const { api, saved } = createApi(+ { columns: [], templates: [ "type:text:text/html" ] }, []);++ await api.setCardTemplateIds([]);++ expect(saved).toEqual([]);+ expect(api.getCardTemplateIds()).toEqual([ "type:text:text/html" ]);+ });++ /** What the template names is what the note is made from, in the same write as the card. */+ it("makes a card from the template it is given", async () => {+ const { api } = createBoardWithCards();+ vi.mocked(note_create.createNote).mockResolvedValue({+ note: buildNote({ title: "Created" }), branch: { branchId: "createdBranch" }+ } as never);++ await api.createNewItem("Done", "Drawn", "bottom", undefined, {+ id: "type:canvas:application/json",+ title: "Canvas",+ icon: "bx bx-pen",+ group: "type",+ options: { type: "canvas", mime: "application/json" }+ });++ expect(note_create.createNote).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({ type: "canvas", mime: "application/json" }));++ // And the same for a card inserted beside another one.+ await api.insertRowAtPosition("Done", "branchId", "after", {+ id: "note:mine",+ title: "My template",+ icon: "bx bx-star",+ group: "user",+ options: { type: "text", mime: "text/html", templateNoteId: "mine" }+ });++ expect(note_create.createNote).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ templateNoteId: "mine", type: "text" }));+ });+it("hands the editing state straight through to the board", () => {const { api, editing } = createBoardWithCards();diff --git a/apps/client/src/widgets/collections/board/api.ts b/apps/client/src/widgets/collections/board/api.tsindex a3ee5f8105..054b1cd01f 100644--- a/apps/client/src/widgets/collections/board/api.ts+++ b/apps/client/src/widgets/collections/board/api.ts@@ -13,7 +13,9 @@ import note_create from "../../../services/note_create";import server from "../../../services/server";import ws from "../../../services/ws";import toast from "../../../services/toast";+import { type NoteTypeOption, resolveNoteTypeOptions } from "../../../services/note_types";import { BoardColumnData, BoardViewData } from ".";+import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import {type BoardStatusDefinition, canStoreColumnsInDefinition, DEFAULT_COLUMN_ICON,DEFAULT_GROUP_BY, INBOX_COLUMN, INBOX_COLUMN_ICON@@ -171,7 +173,8 @@ export default class BoardApi {* columns share one list of children, so the board's first child is not this column's.*/async createNewItem(- column: string, title: string, placement: CardPlacement = "bottom", icon?: string+ column: string, title: string, placement: CardPlacement = "bottom", icon?: string,+ template: NoteTypeOption | undefined = this.getCurrentCardTemplate()) {const first = placement === "top"? this.byColumn?.get(column)?.[0]?.branch.branchId@@ -182,6 +185,7 @@ export default class BoardApi {activate: false,title,isProtected: this.parentNote.isProtected,+ ...(template?.options ?? {}),attributes: [...this.groupingFor(column),...(icon@@ -554,6 +558,55 @@ export default class BoardApi {this.updateColumn(column, { archived });}+ /**+ * Everything a card could be made from, as the board read them.+ *+ * Held here so that a card made from somewhere other than the editor with the pill in it, an+ * insert beside another card above all, is made from the same template: the alternative is+ * handing every card on the board a list it would redraw for.+ */+ private availableTemplates: NoteTypeOption[] = [];++ setAvailableCardTemplates(templates: NoteTypeOption[]) {+ this.availableTemplates = templates;+ }++ /** What a card is made from now: the one last used, or the first the board offers. */+ getCurrentCardTemplate() {+ return currentCardTemplate(+ resolveNoteTypeOptions(this.getCardTemplateIds(), this.availableTemplates),+ this.getLastCardTemplateId());+ }++ /** The templates the board offers, or the stock set until the reader has picked for it. */+ getCardTemplateIds() {+ const stored = this.viewConfig?.templates;+ return stored?.length ? stored : DEFAULT_CARD_TEMPLATES;+ }++ /** Which of them a new card is made from, until another is picked. */+ getLastCardTemplateId() {+ return this.viewConfig?.template;+ }++ /** Sets what the board offers. An empty set would leave nothing to make a card from. */+ async setCardTemplateIds(templates: string[]) {+ if (!templates.length) {+ return;+ }++ this.storeConfig({ templates });+ }++ /** Remembers what the last card was made from, so the next one is made from it too. */+ async setLastCardTemplateId(template: string) {+ if (template === this.viewConfig?.template) {+ return;+ }++ this.storeConfig({ template });+ }+/** Whether a column is stored as collapsed, which draws it as a strip without its cards. */isColumnCollapsed(column: string) {return !!this.viewConfig?.columns?.find(col => col.value === column)?.collapsed;@@ -801,6 +854,12 @@ export default class BoardApi {* re-renders off the identity of the config it was handed, so an in-place edit would be written* to disk but stay invisible until the view is re-entered.*/+ /** Writes part of the board's own configuration, leaving the rest of it as it stands. */+ private storeConfig(patch: Partial<BoardViewData>) {+ this.viewConfig = { ...this.viewConfig, ...patch };+ this.saveConfig(this.viewConfig);+ }+private storeColumns(columns: BoardColumnData[]) {this.viewConfig = { ...this.viewConfig, columns };this.saveConfig(this.viewConfig);@@ -884,12 +943,14 @@ export default class BoardApi {async insertRowAtPosition(column: string,relativeToBranchId: string,- direction: "before" | "after") {+ direction: "before" | "after",+ template: NoteTypeOption | undefined = this.getCurrentCardTemplate()) {const { note, branch } = await note_create.createNote(this.parentNote.noteId, {activate: false,targetBranchId: relativeToBranchId,target: direction,title: t("board_view.new-item"),+ ...(template?.options ?? {}),attributes: this.groupingFor(column)});diff --git a/apps/client/src/widgets/collections/board/card_template_pill.tsx b/apps/client/src/widgets/collections/board/card_template_pill.tsxnew file mode 100644index 0000000000..0aba9cf3da--- /dev/null+++ b/apps/client/src/widgets/collections/board/card_template_pill.tsx@@ -0,0 +1,70 @@+import { useMemo, useState } from "preact/hooks";++import { t } from "../../../services/i18n";+import Dropdown from "../../react/Dropdown";+import { FormListItem } from "../../react/FormList";+import { type NoteTypeOption } from "../../../services/note_types";++/**+ * What a new card will be made from, standing inside the editor it is named in.+ *+ * The pill is a dropdown of what the board offers, and a way to the dialog that decides what that+ * is. It reports a pick rather than storing one: the board writes what it last used, so that the+ * editor opens on it again.+ */+export default function CardTemplatePill({ offered, current, onSelect, onMore, onOpened, onClosed }: {+ offered: NoteTypeOption[];+ /** The one a card would be made from now, absent while the board is still reading them. */+ current?: NoteTypeOption;+ onSelect: (template: NoteTypeOption) => void;+ /** Opens the dialog that decides which templates the board offers. */+ onMore: () => void;+ /**+ * Said as the dropdown opens and closes. The editor closes on losing focus, and the menu takes+ * focus with it, so it has to be held open for as long as the reader is in it.+ */+ onOpened?: () => void;+ onClosed?: () => void;+}) {+ const [ isShown, setIsShown ] = useState(false);++ // Rebuilt only as the list changes, since a dropdown is torn down and put back up with it.+ const items = useMemo(() => offered.map((template) => (+ <FormListItem+ key={template.id}+ icon={template.icon}+ active={template.id === current?.id}+ onClick={() => onSelect(template)}+ >{template.title}</FormListItem>+ )), [ offered, current, onSelect ]);++ // The name alone stands in the pill: the field already carries the icon the card itself will+ // wear, and a second icon beside it reads as a second thing to pick.+ return (+ <Dropdown+ className="card-template-pill"+ buttonClassName="card-template-pill-button"+ text={<span className="card-template-name">{current?.title ?? ""}</span>}+ title={t("board_view.card-template")}+ noSelectButtonStyle+ noDropdownListStyle+ portalToBody+ onShown={() => {+ setIsShown(true);+ onOpened?.();+ }}+ onHidden={() => {+ setIsShown(false);+ onClosed?.();+ }}+ >+ {isShown && <>+ {items}+ <li><hr className="dropdown-divider" /></li>+ <FormListItem icon="bx bx-list-ul" onClick={onMore}>+ {t("board_view.more-templates")}+ </FormListItem>+ </>}+ </Dropdown>+ );+}diff --git a/apps/client/src/widgets/collections/board/card_templates.spec.ts b/apps/client/src/widgets/collections/board/card_templates.spec.tsnew file mode 100644index 0000000000..42814dea7c--- /dev/null+++ b/apps/client/src/widgets/collections/board/card_templates.spec.ts@@ -0,0 +1,33 @@+import { describe, expect, it } from "vitest";++import { type NoteTypeOption } from "../../../services/note_types";+import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";++/** An option as `getNoteTypeOptions` builds one, cut down to what the board reads. */+function option(id: string, title: string): NoteTypeOption {+ return { id, title, icon: "bx bx-note", group: "type", options: { type: "text" } };+}++describe("what a board makes its cards from", () => {+ it("offers text, Markdown, canvas and a spreadsheet until the reader says otherwise", () => {+ expect(DEFAULT_CARD_TEMPLATES).toEqual([+ "type:text:text/html",+ "type:code:text/x-markdown",+ "type:canvas:application/json",+ "type:spreadsheet:application/json"+ ]);+ });++ /**+ * What the board stored can be gone: switched off in the dialog, or a template note deleted.+ * A card is made from the first thing offered rather than from nothing.+ */+ it("falls back to the first offered template", () => {+ const offered = [ option("type:text:text/html", "Text"), option("note:mine", "Mine") ];++ expect(currentCardTemplate(offered, "note:mine")?.title).toBe("Mine");+ expect(currentCardTemplate(offered, "type:canvas:application/json")?.title).toBe("Text");+ expect(currentCardTemplate(offered, undefined)?.title).toBe("Text");+ expect(currentCardTemplate([], "type:text:text/html")).toBeUndefined();+ });+});diff --git a/apps/client/src/widgets/collections/board/card_templates.ts b/apps/client/src/widgets/collections/board/card_templates.tsnew file mode 100644index 0000000000..87faf7cd37--- /dev/null+++ b/apps/client/src/widgets/collections/board/card_templates.ts@@ -0,0 +1,38 @@+import { buildNoteTypeId } from "@triliumnext/commons";++import { type NoteTypeOption } from "../../../services/note_types";++/**+ * What a board makes its cards from.+ *+ * A card template is a {@link NoteTypeOption} like any other: the list, the ids and the dialog that+ * narrows them down are the app's, and what the board adds is which of them it offers, which it+ * last used, and that a new card is made from that one.+ */+export interface CardTemplates {+ /** What the board offers, in the order it stores them. */+ offered: NoteTypeOption[];+ /** The one a card would be made from now. */+ current?: NoteTypeOption;+ onSelect: (template: NoteTypeOption) => void;+ /** Opens the dialog that decides what the board offers. */+ onMore: () => void;+}++/** What a board offers until the reader says otherwise. */+export const DEFAULT_CARD_TEMPLATES = [+ buildNoteTypeId("text", "text/html"),+ buildNoteTypeId("code", "text/x-markdown"),+ buildNoteTypeId("canvas", "application/json"),+ buildNoteTypeId("spreadsheet", "application/json")+];++/**+ * The template a new card is made from: the one the board last used, or the first it offers.+ *+ * A board whose stored template is no longer offered falls back rather than making nothing: the+ * template may have been switched off, or the note behind it deleted.+ */+export function currentCardTemplate(offered: NoteTypeOption[], stored: string | undefined) {+ return offered.find((template) => template.id === stored) ?? offered[0];+}diff --git a/apps/client/src/widgets/collections/board/column.tsx b/apps/client/src/widgets/collections/board/column.tsxindex 999a53863f..6a392f303d 100644--- a/apps/client/src/widgets/collections/board/column.tsx+++ b/apps/client/src/widgets/collections/board/column.tsx@@ -31,6 +31,8 @@ const FOOTER_QUIET_MS = 5000;const EXPAND_MS = 200;import NoteLink from "../../react/NoteLink";import { BoardActionsContext, BoardDragStateContext, TitleEditor } from ".";+import CardTemplatePill from "./card_template_pill";+import { type CardTemplates } from "./card_templates";import BoardApi from "./api";import Card from "./card";import { DEFAULT_CARD_ICON, DEFAULT_COLUMN_ICON, INBOX_COLUMN } from "./columns";@@ -62,6 +64,7 @@ export default function Column({limit,columnItems,isNew,+ cardTemplates,api,parentNote,isInRelationMode@@ -81,6 +84,8 @@ export default function Column({isActive?: boolean,/** Whether the board is showing every collapsed column at once, which opens this one too. */isPeeked?: boolean,+ /** What a new card is made from, and how the reader picks something else. */+ cardTemplates: CardTemplates,/** Whether the inbox also collects notes deeper than the board's direct children. */nested?: boolean,/** The note limit, absent if disabled. */@@ -495,6 +500,7 @@ export default function Column({{!isCollapsed && <AddNewItemapi={api}+ cardTemplates={cardTemplates}column={column}isCreating={isCreatingNewItem}setIsCreating={setIsCreatingNewItem}@@ -509,9 +515,12 @@ export default function Column({* The editor a new card is named in, opened by the button below the column or by its menu. The* state is the column's rather than this component's, since the menu is raised from the header.*/-function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreating }: {+function AddNewItem({+ column, api, cardTemplates, isCreating, setIsCreating, onCreated, onCreating+}: {column: string,api: BoardApi,+ cardTemplates: CardTemplates,isCreating: boolean,setIsCreating: (isCreating: boolean) => void,/** Names the card just made, which the column reveals once the board has drawn it. */@@ -579,7 +588,8 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreatonCreating();onCreated(await api.createNewItem(column, title, atStart ? "top" : "bottom",- icon !== DEFAULT_CARD_ICON ? icon : undefined));+ icon !== DEFAULT_CARD_ICON ? icon : undefined,+ cardTemplates.current));}}dismiss={() => setIsCreating(false)}mode="multiline" isNewItem@@ -592,6 +602,7 @@ function AddNewItem({ column, api, isCreating, setIsCreating, onCreated, onCreat}}submitTitle={t("board_view.create-new-note")}openPlacements={openCreateCardMenu}+ footer={(hold) => <CardTemplatePill {...cardTemplates} {...hold} />}icon={{current: icon,onSelect: setIcon,diff --git a/apps/client/src/widgets/collections/board/index.css b/apps/client/src/widgets/collections/board/index.cssindex 487c465cfd..233fe34c5d 100644--- a/apps/client/src/widgets/collections/board/index.css+++ b/apps/client/src/widgets/collections/board/index.css@@ -44,6 +44,8 @@--card-icon-size: 1em;--card-icon-inset: 0.42rem;--card-title-inset: 1.9em;+ /* The chip naming what a new card is made from, and the room the field leaves for it. */+ --card-template-pill-height: 1.6em;}/* Lays nothing out: the columns stay the board's own flex items, and Preact has a parent of its own@@ -644,6 +646,51 @@ body.mobile .board-view-container .board-add-column {padding-inline-end: 2.2em;}+/*+ * Room below the text for what stands at the foot of the field, which is the pill naming what a new+ * card will be made from. The pill is laid over that room rather than in the flow, so the field+ * still grows a line at a time as it is typed into.+ */+.board-view-container .title-editor-field.with-footer textarea.form-control,+.board-view-container .title-editor-field.with-footer input.form-control {+ padding-block-end: calc(var(--card-padding) + var(--card-template-pill-height));+}++.board-view-container .title-editor-footer {+ position: absolute;+ inset-inline-start: var(--card-icon-inset);+ inset-block-end: calc(var(--card-padding) / 2);+ max-width: calc(100% - 2 * var(--card-icon-inset));+}++/* A quiet chip rather than a button: it names what the card will be, and is pressed only to change+ it. The name is cut rather than wrapped, the field being one line tall to begin with. */+.board-view-container .card-template-pill .card-template-pill-button {+ display: flex;+ align-items: center;+ gap: 0.3em;+ max-width: 100%;+ height: var(--card-template-pill-height);+ border: 1px solid var(--main-border-color);+ border-radius: 999px;+ padding-inline: 0.5em;+ background-color: transparent;+ color: var(--muted-text-color);+ font-size: 0.85em;+ line-height: 1;+}++.board-view-container .card-template-pill .card-template-pill-button:hover {+ border-color: var(--main-text-color);+ color: var(--main-text-color);+}++.board-view-container .card-template-pill .card-template-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+/* A card or column lands where the reader may not be looking, so it announces itself. */@keyframes board-item-appear {from { opacity: 0; }diff --git a/apps/client/src/widgets/collections/board/index.spec.tsx b/apps/client/src/widgets/collections/board/index.spec.tsxindex f60a99c8aa..4d6f54c556 100644--- a/apps/client/src/widgets/collections/board/index.spec.tsx+++ b/apps/client/src/widgets/collections/board/index.spec.tsx@@ -39,6 +39,26 @@ vi.mock("../../../services/i18n", () => ({// The picker is a Bootstrap dropdown portalled to the page, which happy-dom does not open. What the// board answers for is the icon it shows and what it does with a pick, so the button stands in for// the picker and hands one over when it is pressed.+// What a card can be made from. The listing itself is the app's and is tested there; the board is+// handed a short list of it, the four it offers by default and one it does not.+vi.mock("../../../services/note_types", () => ({+ getNoteTypeOptions: async () => NOTE_TYPE_OPTIONS,+ resolveNoteTypeOptions: (ids: string[], available: { id: string }[]) =>+ ids.flatMap(id => available.filter(option => option.id === id)),+ noteTypeOptionGroupTitle: (group: string) => `group:${group}`,+ default: {}+}));++const NOTE_TYPE_OPTIONS = [+ [ "type:text:text/html", "Text", "text", "text/html" ],+ [ "type:code:text/x-markdown", "Markdown", "code", "text/x-markdown" ],+ [ "type:canvas:application/json", "Canvas", "canvas", "application/json" ],+ [ "type:spreadsheet:application/json", "Spreadsheet", "spreadsheet", "application/json" ],+ [ "type:mermaid:text/mermaid", "Mermaid", "mermaid", "text/mermaid" ]+].map(([ id, title, type, mime ]) => ({+ id, title, icon: "bx bx-note", group: "type" as const, options: { type, mime }+}));+vi.mock("../../react/IconPicker", () => ({IconPickerButton: ({ className, icon, onSelect, onOpened, onClosed }: {className?: string, icon: string, onSelect: (picked: string) => void,@@ -78,6 +98,11 @@ vi.mock("../../../services/bulk_action", () => ({})}));+/** What a card is made from until another template is picked: the first the board offers. */+function textTemplate() {+ return expect.objectContaining({ id: "type:text:text/html" });+}+/** Drains the async chain inside `refresh()` (getBoardData → setByColumn/setColumns). */async function flush() {await new Promise((resolve) => setTimeout(resolve));@@ -1529,7 +1554,7 @@ describe("Board column rename", () => {await flush();});- expect(created).toHaveBeenCalledWith("Doing", "First", "bottom", undefined);+ expect(created).toHaveBeenCalledWith("Doing", "First", "bottom", undefined, textTemplate());expect(slot?.querySelector("textarea")).toBe(editor);expect(editor.value).toBe("");expect(document.activeElement).toBe(editor);@@ -1542,7 +1567,7 @@ describe("Board column rename", () => {});expect(created).toHaveBeenCalledTimes(2);- expect(created).toHaveBeenLastCalledWith("Doing", "Second", "bottom", undefined);+ expect(created).toHaveBeenLastCalledWith("Doing", "Second", "bottom", undefined, textTemplate());});/**@@ -2161,12 +2186,192 @@ describe("Board column rename", () => {await flush();});- expect(created).toHaveBeenCalledWith("Doing", "From the button", "bottom", undefined);+ expect(created).toHaveBeenCalledWith("Doing", "From the button", "bottom", undefined, textTemplate());expect(editor.value).toBe("");expect(slot?.querySelector("textarea")).toBe(editor);expect(document.activeElement).toBe(editor);});+ /**+ * The pill at the foot of the new-card field names what the card will be made from. It offers+ * what the board offers, and picking one is remembered: the next card is made from it, and so+ * is the next editor opened.+ */+ it("makes a card from the template picked in the pill, and remembers it", async () => {+ const { container } = await setup();+ const created = vi.spyOn(BoardApi.prototype, "createNewItem")+ .mockResolvedValue(undefined);+ created.mockClear();+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]+ .querySelector<HTMLElement>(".board-new-item");++ await act(async () => {+ slot?.click();+ await flush();+ });++ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");+ const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");+ if (!editor || !pill) throw new Error("expected the editor and its template pill");++ // The first the board offers, until something else is picked.+ expect(pill.textContent).toContain("Text");++ await act(async () => {+ pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ await flush();+ });++ // The menu is portalled to the page, and the boards this file rendered before left theirs+ // behind, so it is the last one that belongs to the board under test.+ const menu = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ].at(-1);+ const items = [ ...(menu?.querySelectorAll<HTMLElement>(".dropdown-item") ?? []) ];+ expect(items.map(item => item.textContent?.trim())).toEqual([+ "Text", "Markdown", "Canvas", "Spreadsheet", "board_view.more-templates"+ ]);++ await act(async () => {+ items[2].click();+ await flush();+ });++ // Stored on the board, so the next editor opens on it as well.+ expect(saved.at(-1)?.template).toBe("type:canvas:application/json");++ await type(editor, "Drawn");+ await act(async () => {+ editor.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));+ await flush();+ });++ expect(created).toHaveBeenCalledWith("Doing", "Drawn", "bottom", undefined,+ expect.objectContaining({ id: "type:canvas:application/json" }));+ expect(slot?.querySelector(".card-template-pill button")?.textContent).toContain("Canvas");+ });++ /**+ * Opening the pill's menu takes focus off the field: Bootstrap focuses the toggle it opens+ * from. Losing focus is what closes this editor, so the editor would take the menu down with+ * itself the moment it was opened, and the toggle would then find nothing to open.+ */+ it("stays open while the template pill's menu has the focus", async () => {+ const { container } = await setup();+ const created = vi.spyOn(BoardApi.prototype, "createNewItem")+ .mockResolvedValue(undefined);+ created.mockClear();+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]+ .querySelector<HTMLElement>(".board-new-item");++ await act(async () => {+ slot?.click();+ await flush();+ });++ const editor = slot?.querySelector<HTMLTextAreaElement>("textarea");+ const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");+ if (!editor || !pill) throw new Error("expected the editor and its pill");+ await type(editor, "Still here");++ await act(async () => {+ pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ editor.dispatchEvent(new FocusEvent("blur"));+ editor.dispatchEvent(new FocusEvent("focusout", { bubbles: true }));+ await flush();+ });++ expect(slot?.querySelector("textarea")).toBe(editor);+ expect(editor.value).toBe("Still here");+ expect(created).not.toHaveBeenCalled();++ // Once the menu is done with, the field has the focus again.+ await act(async () => {+ $(pill.closest(".dropdown") as HTMLElement).trigger("hide.bs.dropdown");+ await flush();+ });+ expect(document.activeElement).toBe(editor);+ });++ /** The pill's last entry opens the dialog that decides what the board offers. */+ it("opens the templates dialog from the pill, and stores what is ticked", async () => {+ const { container } = await setup();+ const stored = vi.spyOn(BoardApi.prototype, "setCardTemplateIds")+ .mockResolvedValue(undefined);+ const slot = container.querySelectorAll<HTMLElement>(".board-column")[1]+ .querySelector<HTMLElement>(".board-new-item");++ await act(async () => {+ slot?.click();+ await flush();+ });++ const pill = slot?.querySelector<HTMLElement>(".card-template-pill button");+ if (!pill) throw new Error("expected the template pill");+ await act(async () => {+ pill.dispatchEvent(new MouseEvent("pointerdown", { bubbles: true }));+ $(pill.closest(".dropdown") as HTMLElement).trigger("show.bs.dropdown");+ await flush();+ });++ const menus = [ ...document.querySelectorAll<HTMLElement>(".card-template-pill") ];+ const more = [ ...(menus.at(-1)?.querySelectorAll<HTMLElement>(".dropdown-item") ?? []) ]+ .find(item => item.textContent?.includes("more-templates"));+ if (!more) throw new Error("expected a way to the dialog");++ await act(async () => {+ more.click();+ await flush();+ });++ // The last of them: a dialog portalled to the page outlives the board that drew it here,+ // so every board this file has rendered has left one behind.+ const dialog = [ ...document.querySelectorAll<HTMLElement>(".note-type-selector-dialog") ]+ .at(-1);+ expect(dialog).toBeTruthy();++ const boxes = [ ...(dialog?.querySelectorAll<HTMLInputElement>("input[type=checkbox]") ?? []) ];+ // The name carries a suffix of its own, which is what ties the box to its label.+ const named = boxes.map(box => box.getAttribute("name")?.replace(/-[^-]{10}$/, ""));+ // Everything the app can make is listed, with what the board offers already ticked.+ expect(named).toEqual([+ "type:text:text/html",+ "type:code:text/x-markdown",+ "type:canvas:application/json",+ "type:spreadsheet:application/json",+ "type:mermaid:text/mermaid"+ ]);+ expect(boxes.filter(box => box.checked).length).toBe(4);++ // Nothing ticked is nothing a card could be made from, so it cannot be saved.+ await act(async () => {+ for (const box of boxes.filter(box => box.checked)) {+ box.checked = false;+ box.dispatchEvent(new Event("change", { bubbles: true }));+ }+ await flush();+ });+ const save = [ ...(dialog?.querySelectorAll<HTMLButtonElement>("button") ?? []) ]+ .find(button => button.textContent?.includes("selector-save"));+ expect(save?.disabled).toBe(true);++ await act(async () => {+ boxes[4].checked = true;+ boxes[4].dispatchEvent(new Event("change", { bubbles: true }));+ await flush();+ });+ expect(save?.disabled).toBe(false);++ await act(async () => {+ dialog?.querySelector("form")?.dispatchEvent(+ new Event("submit", { bubbles: true, cancelable: true }));+ await flush();+ });+ expect(stored).toHaveBeenCalledWith([ "type:mermaid:text/mermaid" ]);++ stored.mockRestore();+ });+/*** The icon stands inside the field, at its head, and is what the card is made with. It is kept* between cards, unlike the title: a run of cards is often a run of the same kind of card.@@ -2201,7 +2406,7 @@ describe("Board column rename", () => {await flush();});- expect(created).toHaveBeenCalledWith("Doing", "Starred", "bottom", PICKED_ICON);+ expect(created).toHaveBeenCalledWith("Doing", "Starred", "bottom", PICKED_ICON, textTemplate());// The title goes, the icon stays.expect(editor.value).toBe("");expect(slot?.querySelector(".title-editor-icon button")?.className)@@ -2330,7 +2535,7 @@ describe("Board column rename", () => {await flush();});- expect(created).toHaveBeenCalledWith("Doing", "On top", "top", undefined);+ expect(created).toHaveBeenCalledWith("Doing", "On top", "top", undefined, textTemplate());// The field is emptied for the next one, as it is for a card made at the end.expect(editor.value).toBe("");});@@ -2374,7 +2579,7 @@ describe("Board column rename", () => {entries[0]?.handler?.({} as never, {} as never);await flush();});- expect(created).toHaveBeenCalledWith("Doing", "Either end", "top", undefined);+ expect(created).toHaveBeenCalledWith("Doing", "Either end", "top", undefined, textTemplate());expect(editor.value).toBe("");show.mockRestore();diff --git a/apps/client/src/widgets/collections/board/index.tsx b/apps/client/src/widgets/collections/board/index.tsxindex f151736091..16470aa62b 100644--- a/apps/client/src/widgets/collections/board/index.tsx+++ b/apps/client/src/widgets/collections/board/index.tsx@@ -2,7 +2,7 @@ import "./index.css";import clsx from "clsx";-import { createContext, Fragment, TargetedKeyboardEvent } from "preact";+import { ComponentChildren, createContext, Fragment, TargetedKeyboardEvent } from "preact";import { JSX } from "preact/jsx-runtime";import { createPortal, RefObject } from "preact/compat";import {@@ -18,6 +18,10 @@ import type { ShortcutHintDefinition } from "../../../services/shortcut_hints";import toast from "../../../services/toast";import { escapeHtml, isMobile } from "../../../services/utils";import CollectionProperties from "../../note_bars/CollectionProperties";+import {+ getNoteTypeOptions, type NoteTypeOption, resolveNoteTypeOptions+} from "../../../services/note_types";+import NoteTypeSelectorDialog from "../../react/NoteTypeSelectorDialog";import FormTextArea from "../../react/FormTextArea";import FormTextBox from "../../react/FormTextBox";import {@@ -39,13 +43,32 @@ import { movesColumn } from "./drag_geometry";import BoardApi from "./api";import { DEFAULT_COLUMN_ICON, DEFAULT_GROUP_BY, getStatusDefinition, INBOX_COLUMN } from "./columns";import Column from "./column";+import { currentCardTemplate, DEFAULT_CARD_TEMPLATES } from "./card_templates";import ColumnLimitDialog from "./column_limit";import { openBoardContextMenu, openCreateColumnMenu } from "./context_menu";import { applyCardMove, ColumnMap, getBoardData } from "./data";import { useBoardKeyboard } from "./keyboard";+/**+ * What a control standing inside an editor's field calls as it opens and closes.+ *+ * Losing focus is what closes an editor, and a menu takes focus with it: a control that opens one+ * says so, and the editor stays where it is until the menu is done with.+ */+export interface HoldOpen {+ onOpened: () => void;+ onClosed: () => void;+}+export interface BoardViewData {columns?: BoardColumnData[];+ /**+ * What a new card can be made from, as {@link CardTemplate} ids. Absent until the reader picks+ * for the board, which is what `DEFAULT_CARD_TEMPLATES` stands in for.+ */+ templates?: string[];+ /** The one last used, which the next card is made from. */+ template?: string;}export interface BoardColumnData {@@ -244,6 +267,20 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCconst [ isPeekingAll, setIsPeekingAll ] = useState(false);/** Whether the editor a column is named in is open, which the board's own menu also opens. */const [ isCreatingColumn, setIsCreatingColumn ] = useState(false);+ /** Everything a card could be made from, read once: the note types and every template. */+ const [ availableTemplates, setAvailableTemplates ] = useState<NoteTypeOption[]>([]);+ const [ isPickingTemplates, setIsPickingTemplates ] = useState(false);++ useEffect(() => {+ let listening = true;+ getNoteTypeOptions().then((templates) => {+ if (listening) {+ setAvailableTemplates(templates);+ }+ }).catch((e) => console.error("Failed to read what a card can be made from:", e));++ return () => { listening = false; };+ }, []);const selectColumn = useCallback<Dispatch<StateUpdater<string | undefined>>>((column) => {setIsPeekingAll(false);setActiveColumn(column);@@ -334,6 +371,23 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC});}, [ api, selectColumn, inboxEnabled, includeArchived ]);+ // Read from the api rather than from the prop, since a pick moves the api's own copy ahead of+ // the board's; keyed on the prop so that a change from anywhere else is followed too.+ const offeredTemplates = useMemo(+ () => resolveNoteTypeOptions(api.getCardTemplateIds(), availableTemplates),+ [ api, viewConfig, availableTemplates ]);+ // Handed to the api as well, for the cards made from somewhere other than the editor: an+ // insert beside another card reaches for the same template without being given one.+ useEffect(+ () => api.setAvailableCardTemplates(availableTemplates), [ api, availableTemplates ]);++ const cardTemplates = useMemo(() => ({+ offered: offeredTemplates,+ current: currentCardTemplate(offeredTemplates, api.getLastCardTemplateId()),+ onSelect: (template: NoteTypeOption) => api.setLastCardTemplateId(template.id),+ onMore: () => setIsPickingTemplates(true)+ }), [ api, viewConfig, offeredTemplates ]);+const boardActions = useMemo<BoardActions>(() => ({setBranchIdToEdit,setColumnNameToEdit,@@ -694,6 +748,7 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveCkeepCollapsed={storedColumns.get(column)?.keepCollapsed}isActive={activeColumn === column}isPeeked={isPeekingAll}+ cardTemplates={cardTemplates}nested={storedColumns.get(column)?.nested}limit={storedColumns.get(column)?.limit}columnIndex={index}@@ -722,15 +777,26 @@ export default function BoardView({ note: parentNote, noteIds, viewConfig, saveC{/* Where what is being carried is put. Preact draws the layer and neverits contents, so the copy is not among the children it places. */}<div className="board-drag-layer" />- {/* Out of the board and onto the page: the dialog is positioned against- the window, and Bootstrap puts its backdrop on the body, so a stacking+ {/* Out of the board and onto the page: a dialog is positioned against the+ window, and Bootstrap puts its backdrop on the body, so a stackingcontext above the board would trap it underneath. */}{createPortal(- <ColumnLimitDialog- api={api}- column={columnLimitToEdit}- onClose={() => setColumnLimitToEdit(undefined)}- />,+ <>+ <ColumnLimitDialog+ api={api}+ column={columnLimitToEdit}+ onClose={() => setColumnLimitToEdit(undefined)}+ />+ <NoteTypeSelectorDialog+ available={availableTemplates}+ selected={api.getCardTemplateIds()}+ shown={isPickingTemplates}+ title={t("board_view.templates-title")}+ hint={t("board_view.templates-hint")}+ onSave={(ids) => api.setCardTemplateIds(ids)}+ onClose={() => setIsPickingTemplates(false)}+ />+ </>,document.body)}{!isMobile() && (@@ -879,7 +945,8 @@ function AddNewColumn({export function TitleEditor({currentValue, placeholder, save, dismiss, mode, isNewItem, selectOnFocus = true,- saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, openPlacements, icon+ saveAndContinue = false, returnFocusTo, abandon, whenEmpty, submitTitle, openPlacements, icon,+ footer}: {currentValue?: string;placeholder?: string;@@ -903,6 +970,11 @@ export function TitleEditor({whenEmpty?: { title: string, onClick?: () => void };/** Names what the button creates, shown in its tooltip. */submitTitle?: string;+ /**+ * What stands at the foot of the field, inside its own box: the pill naming what a new card+ * will be made from. The field is given room for it.+ */+ footer?: (hold: HoldOpen) => ComponentChildren;/*** The icon shown inside the field, at the leading edge, which opens the picker when pressed.* The caller answers for what a pick does: a card carries it as `iconClass`, and the editor a@@ -938,14 +1010,22 @@ export function TitleEditor({const dismissOnNextRefreshRef = useRef(false);const shouldDismiss = useRef(false);/**- * Whether the icon picker is open, during which the editor stays where it is.+ * Whether something the field carries is open, during which the editor stays where it is.*- * The picker takes focus with it, and losing focus is what closes this editor: it would take- * the picker down with itself. Held in a ref rather than in state because the blur arrives- * before the render a state change would schedule. Focus goes back to the field as the picker- * closes, the blur that would have ended the edit being spent.+ * A menu takes focus with it, and losing focus is what closes this editor: it would take the+ * menu down with itself, which is what the icon picker and the pill naming what a card is made+ * from both do. Held in a ref rather than in state because the blur arrives before the render+ * a state change would schedule; focus goes back to the field as the menu closes, the blur+ * that would have ended the edit being spent.*/- const isPickingIcon = useRef(false);+ const isHoldingOpen = useRef(false);+ const holdOpen = useMemo<HoldOpen>(() => ({+ onOpened: () => { isHoldingOpen.current = true; },+ onClosed: () => {+ isHoldingOpen.current = false;+ inputRef.current?.focus();+ }+ }), []);const held = useRef<number>();/** Where on the screen the finger went down, against which a scroll is told from a hold. */const heldFrom = useRef<{ x: number, y: number }>();@@ -1084,7 +1164,7 @@ export function TitleEditor({}const onBlur = (newValue: string) => {- if (isPickingIcon.current) {+ if (isHoldingOpen.current) {return;}@@ -1127,7 +1207,7 @@ export function TitleEditor({/>);- if (!saveAndContinue && !icon) {+ if (!saveAndContinue && !icon && !footer) {return field;}@@ -1150,7 +1230,10 @@ export function TitleEditor({};return (- <div className={clsx("title-editor-field", { "with-submit": saveAndContinue })}>+ <div className={clsx("title-editor-field", {+ "with-submit": saveAndContinue,+ "with-footer": !!footer+ })}>{/* The press that opens the picker must not take focus out of the field: theblur arrives before the picker reports itself open, and losing focus is whatcloses the editor. */}@@ -1165,11 +1248,7 @@ export function TitleEditor({// A grid of a thousand icons and a search field is a task of its own,// so the board behind it is dimmed rather than left looking pressable.backdrop- onOpened={() => { isPickingIcon.current = true; }}- onClosed={() => {- isPickingIcon.current = false;- inputRef.current?.focus();- }}+ {...holdOpen}/></span>)}@@ -1196,6 +1275,14 @@ export function TitleEditor({/></span>)}+ {/* Inside the field's own box, in the room made for it below the text. The press+ must not take focus out of the field, which is what closes the editor. */}+ {footer && (+ <span+ className="title-editor-footer"+ onMouseDown={(e) => e.preventDefault()}+ >{footer(holdOpen)}</span>+ )}</div>);}diff --git a/apps/client/src/widgets/react/NoteTypeSelectorDialog.css b/apps/client/src/widgets/react/NoteTypeSelectorDialog.cssnew file mode 100644index 0000000000..c4e9293cb4--- /dev/null+++ b/apps/client/src/widgets/react/NoteTypeSelectorDialog.css@@ -0,0 +1,21 @@+:where(:root) {+ --note-type-selector-group-gap: 1.2em;+}++.modal.note-type-selector-dialog {+ .note-type-selector-hint {+ margin-bottom: var(--note-type-selector-group-gap);+ color: var(--muted-text-color);+ }++ section + section {+ margin-top: var(--note-type-selector-group-gap);+ }++ h5 {+ margin-bottom: 0.4em;+ font-size: 1em;+ font-weight: 600;+ color: var(--muted-text-color);+ }+}diff --git a/apps/client/src/widgets/react/NoteTypeSelectorDialog.tsx b/apps/client/src/widgets/react/NoteTypeSelectorDialog.tsxnew file mode 100644index 0000000000..3dfea8df5f--- /dev/null+++ b/apps/client/src/widgets/react/NoteTypeSelectorDialog.tsx@@ -0,0 +1,99 @@+import "./NoteTypeSelectorDialog.css";++import { useEffect, useMemo, useState } from "preact/hooks";++import { t } from "../../services/i18n";+import {+ type NoteTypeOption, type NoteTypeOptionGroup, noteTypeOptionGroupTitle+} from "../../services/note_types";+import Button from "./Button";+import FormCheckbox from "./FormCheckbox";+import Icon from "./Icon";+import Modal from "./Modal";++/**+ * Which of the things a note can be made from a feature offers, ticked off a list of all of them.+ *+ * Written for anything that lets the reader narrow the choice down to what they actually use: a+ * board's card templates are the first, and the dialog knows nothing of boards. Saving an empty+ * selection is refused, since a feature that offers nothing can make nothing.+ */+export default function NoteTypeSelectorDialog({+ available, selected, shown, title, hint, onSave, onClose+}: {+ /** Everything that could be offered, usually `getNoteTypeOptions()`. */+ available: NoteTypeOption[],+ /** What is offered now, which is what the dialog opens on. */+ selected: string[],+ shown: boolean,+ title: string,+ /** A line above the list saying what the choice is for. */+ hint?: string,+ onSave: (ids: string[]) => void,+ onClose: () => void+}) {+ const [ picked, setPicked ] = useState<string[]>(selected);++ // Opened on what is offered now rather than on what was offered when it was first drawn: the+ // dialog is kept mounted and shown by a flag.+ useEffect(() => {+ if (shown) {+ setPicked(selected);+ }+ }, [ shown, selected ]);++ const groups = useMemo(() => {+ const byGroup = new Map<NoteTypeOptionGroup, NoteTypeOption[]>();+ for (const option of available) {+ byGroup.set(option.group, [ ...(byGroup.get(option.group) ?? []), option ]);+ }++ return [ ...byGroup.entries() ];+ }, [ available ]);++ return (+ <Modal+ className="note-type-selector-dialog"+ title={title}+ size="lg"+ scrollable+ // Raised the way every dialog opened from a menu is: the menu's own backdrop stands+ // above the stock modal layer, and would otherwise cover this.+ zIndex={2000}+ show={shown}+ onSubmit={() => {+ onSave(picked);+ onClose();+ }}+ onHidden={onClose}+ footer={<>+ <Button text={t("modal.cancel")} onClick={onClose} />+ <Button+ text={t("note_types.selector-save")}+ keyboardShortcut="Enter"+ kind="primary"+ disabled={!picked.length}+ />+ </>}+ >+ {hint && <p className="note-type-selector-hint">{hint}</p>}++ {groups.map(([ group, options ]) => (+ <section key={group}>+ <h5>{noteTypeOptionGroupTitle(group)}</h5>+ {options.map((option) => (+ <FormCheckbox+ key={option.id}+ name={option.id}+ label={<><Icon icon={option.icon} /> {option.title}</>}+ currentValue={picked.includes(option.id)}+ onChange={(checked) => setPicked((was) => checked+ ? [ ...was, option.id ]+ : was.filter((id) => id !== option.id))}+ />+ ))}+ </section>+ ))}+ </Modal>+ );+}diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 1d73468e30..a543d4b899 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -17,6 +17,7 @@ export * from "./lib/shared_constants.js";export * from "./lib/shared_types.js";export * from "./lib/ws_api.js";export * from "./lib/attribute_names.js";+export * from "./lib/note_type_ids.js";export * from "./lib/promoted_attribute_definition_parser.js";export { default as promotedAttributeDefinitionParser } from "./lib/promoted_attribute_definition_parser.js";export * from "./lib/utils.js";diff --git a/packages/commons/src/lib/note_type_ids.spec.ts b/packages/commons/src/lib/note_type_ids.spec.tsnew file mode 100644index 0000000000..f8dcef5079--- /dev/null+++ b/packages/commons/src/lib/note_type_ids.spec.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from "vitest";++import {+ buildNoteTypeId, buildTemplateId, isNoteTypeId, isTemplateId, parseNoteTypeId, resolveNoteType+} from "./note_type_ids.js";++describe("note type ids", () => {+ /** The mime is part of a type's id: a Markdown note and a code note are both `code`. */+ it("names a note type by its type and mime, and a template by its note", () => {+ expect(buildNoteTypeId("code", "text/x-markdown")).toBe("type:code:text/x-markdown");+ expect(buildNoteTypeId("canvas")).toBe("type:canvas:");+ expect(buildTemplateId("abc123")).toBe("template:abc123");++ expect(isNoteTypeId("type:text:text/html")).toBe(true);+ expect(isNoteTypeId("template:abc123")).toBe(false);+ expect(isTemplateId("template:abc123")).toBe(true);+ });++ it("reads an id back to what it names", () => {+ expect(parseNoteTypeId("type:code:text/x-markdown"))+ .toEqual({ kind: "type", type: "code", mime: "text/x-markdown" });+ // A mime is written even when there is none, so the id round-trips.+ expect(parseNoteTypeId(buildNoteTypeId("canvas")))+ .toEqual({ kind: "type", type: "canvas", mime: undefined });+ expect(parseNoteTypeId("template:abc123"))+ .toEqual({ kind: "template", templateNoteId: "abc123" });+ });++ /**+ * A stored id outlives what it names: a note type can be dropped from the app, and an id can+ * come from a document written by a newer build. Neither is a reason to fail.+ */+ it("answers with nothing for an id it cannot make sense of", () => {+ expect(parseNoteTypeId("type:notAType:text/html")).toBeUndefined();+ expect(parseNoteTypeId("template:")).toBeUndefined();+ expect(parseNoteTypeId("text")).toBeUndefined();+ expect(parseNoteTypeId("")).toBeUndefined();+ expect(resolveNoteType("type:notAType:")).toBeUndefined();+ });++ /** What creating a note from an id asks for, which is what `createNote` takes. */+ it("resolves an id to what a note is created with", () => {+ expect(resolveNoteType("type:canvas:application/json"))+ .toEqual({ type: "canvas", mime: "application/json" });+ expect(resolveNoteType(buildNoteTypeId("text", "text/html")))+ .toEqual({ type: "text", mime: "text/html" });+ expect(resolveNoteType("template:abc123")).toEqual({ templateNoteId: "abc123" });+ });++ /** A mime holds colons of its own in some builds, and the id keeps all of it. */+ it("keeps everything after the type as the mime", () => {+ const id = buildNoteTypeId("code", "text/plain;charset=utf-8");+ expect(parseNoteTypeId(id)).toEqual({+ kind: "type", type: "code", mime: "text/plain;charset=utf-8"+ });+ });+});diff --git a/packages/commons/src/lib/note_type_ids.ts b/packages/commons/src/lib/note_type_ids.tsnew file mode 100644index 0000000000..b700d7e5af--- /dev/null+++ b/packages/commons/src/lib/note_type_ids.ts@@ -0,0 +1,85 @@+import { ALLOWED_NOTE_TYPES, type NoteType } from "./rows.js";++/**+ * Naming what a note is made from, as one string.+ *+ * A feature that lets the reader choose what a new note will be has two kinds of answer to store: a+ * blank note type, and a note carrying `#template`. Both are written here as a single id, so that a+ * stored choice, a menu entry and a request all speak of it the same way.+ *+ * `type:<type>:<mime>` names a blank note type. The mime is part of it because a type alone is not+ * always enough: a Markdown note and a code note are both `code`, and only the mime tells them+ * apart. `template:<noteId>` names a note to be templated from.+ */+export type NoteTypeId = string;++/** What a {@link NoteTypeId} names, once read. */+export type NoteTypeSelection =+ | { kind: "type"; type: NoteType; mime?: string }+ | { kind: "template"; templateNoteId: string };++const TYPE_PREFIX = "type:";+const TEMPLATE_PREFIX = "template:";++/** Names a blank note type. An empty mime is written as such, so the id round-trips. */+export function buildNoteTypeId(type: NoteType, mime?: string): NoteTypeId {+ return `${TYPE_PREFIX}${type}:${mime ?? ""}`;+}++/** Names a note to be templated from. */+export function buildTemplateId(noteId: string): NoteTypeId {+ return `${TEMPLATE_PREFIX}${noteId}`;+}++export function isNoteTypeId(id: NoteTypeId) {+ return id.startsWith(TYPE_PREFIX);+}++export function isTemplateId(id: NoteTypeId) {+ return id.startsWith(TEMPLATE_PREFIX);+}++/**+ * Reads an id back, or answers with nothing where it names something this build does not know.+ *+ * A stored id outlives what it names: a note type can be dropped from the app and a template note+ * deleted, and neither is a reason to fail. The caller decides what to do with an id that resolves+ * to nothing, which is usually to leave it out of what it offers.+ */+export function parseNoteTypeId(id: NoteTypeId): NoteTypeSelection | undefined {+ if (isTemplateId(id)) {+ const noteId = id.slice(TEMPLATE_PREFIX.length);+ return noteId ? { kind: "template", templateNoteId: noteId } : undefined;+ }++ if (!isNoteTypeId(id)) {+ return undefined;+ }++ const rest = id.slice(TYPE_PREFIX.length);+ const separator = rest.indexOf(":");+ const type = separator < 0 ? rest : rest.slice(0, separator);+ const mime = separator < 0 ? "" : rest.slice(separator + 1);++ return (ALLOWED_NOTE_TYPES as readonly string[]).includes(type)+ ? { kind: "type", type: type as NoteType, mime: mime || undefined }+ : undefined;+}++/**+ * What creating a note from an id asks for, which is what `createNote` takes.+ *+ * A template answers with the note to template from; what type the new note ends up with is the+ * template's own, and the caller adds it where it has the template note to hand.+ */+export function resolveNoteType(id: NoteTypeId):+ { type?: NoteType; mime?: string; templateNoteId?: string } | undefined {+ const selection = parseNoteTypeId(id);+ if (!selection) {+ return undefined;+ }++ return selection.kind === "template"+ ? { templateNoteId: selection.templateNoteId }+ : { type: selection.type, mime: selection.mime };+}