Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(notes): build the empty note switcher from the insert menu
Elian Doran66297e55b2f3
diff --git a/apps/client/src/services/note_types.ts b/apps/client/src/services/note_types.tsindex 3e0823371d..a3dc31da93 100644--- a/apps/client/src/services/note_types.ts+++ b/apps/client/src/services/note_types.ts@@ -322,35 +322,31 @@ function getCodeLanguageItems(command?: TreeCommandNames): MenuItem<TreeCommandN];}-function getUserTemplates(command: TreeCommandNames | undefined, templateNotes: FNote[], newTemplates: Set<string>) {- if (templateNotes.length === 0) {- return [];- }-- const items: MenuItem<TreeCommandNames>[] = [- {- title: t("note_type_chooser.templates"),- kind: "header"- }- ];-- for (const templateNote of templateNotes) {- const item: MenuItem<TreeCommandNames> = {- // A menu renders titles as HTML.- title: escapeHtml(templateNote.title),- uiIcon: templateNote.getIcon(),- command,- type: templateNote.type,- templateNoteId: templateNote.noteId- };+/**+ * The rows of the built-in templates of `group`, or of the user's own templates for `"user"`, as+ * the note type menu lists them.+ */+function getTemplateItems(data: NoteTypeData, group: BuiltInTemplateGroup | "user", command?: TreeCommandNames) {+ return group === "user"+ ? getUserTemplateRows(command, data.userTemplateNotes, data.newTemplates)+ : getBuiltInTemplates(command, data.builtInTemplateNotes, group, data.newTemplates);+}- if (newTemplates.has(templateNote.noteId)) {- item.badges = [NEW_BADGE];- }+function getUserTemplates(command: TreeCommandNames | undefined, templateNotes: FNote[], newTemplates: Set<string>) {+ const header: MenuItem<TreeCommandNames> = { title: t("note_type_chooser.templates"), kind: "header" };+ return withLeading(header, getUserTemplateRows(command, templateNotes, newTemplates));+}- items.push(item);- }- return items;+function getUserTemplateRows(command: TreeCommandNames | undefined, templateNotes: FNote[], newTemplates: Set<string>) {+ return templateNotes.map<MenuItem<TreeCommandNames>>((templateNote) => ({+ // A menu renders titles as HTML.+ title: escapeHtml(templateNote.title),+ uiIcon: templateNote.getIcon(),+ command,+ type: templateNote.type,+ templateNoteId: templateNote.noteId,+ ...(newTemplates.has(templateNote.noteId) && { badges: [ NEW_BADGE ] })+ }));}async function getBuiltInTemplateNotes() {@@ -363,7 +359,7 @@ async function getBuiltInTemplateNotes() {return await templatesRoot.getChildNotes();}-type BuiltInTemplateGroup = "collection" | "snippet" | "aiQuickAction" | "other";+export type BuiltInTemplateGroup = "collection" | "snippet" | "aiQuickAction" | "other";/** The group of the note type menus a built-in template stands in, told by the labels it carries. */function builtInTemplateGroup(templateNote: FNote): BuiltInTemplateGroup {@@ -415,6 +411,8 @@ export default {loadNoteTypeData,buildNoteTypeItems,getNoteTypeItems,+ getCodeLanguageItems,+ getTemplateItems,getNoteTypeOptions,resolveNoteTypeOptions};diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex 074c5161ff..4d69174b47 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2855,11 +2855,11 @@"created_on": "Created on <Value />","last_modified": "Modified on <Value />","note_type_switcher_label": "Switch from {{type}} to:",- "note_type_switcher_others": "Other note type","note_type_switcher_templates": "Template","note_type_switcher_collection": "Collection","edited_notes": "Notes edited on this day",- "promoted_attributes": "Promoted attributes"+ "promoted_attributes": "Promoted attributes",+ "note_type_switcher_all": "All types"},"search_result": {"no_notes_found": "No notes have been found for given search parameters.",diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsxindex e5bcc3bd1f..7e7d4813d7 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx@@ -1,168 +1,136 @@-import { render } from "preact";+import { type ComponentChildren, render } from "preact";import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";-// Rendering TemplateNoteTypes pulls in BadgeWithDropdown → Dropdown, which wires real Bootstrap;-// a fake instance is enough since only the menu contents are asserted (same prelude as Dropdown.spec).-vi.mock("bootstrap", () => ({- Dropdown: { getOrCreateInstance: () => ({ show() {}, hide() {}, update() {}, dispose() {}, _menu: null }) },- Tooltip: Object.assign(class {}, { getInstance: () => null })-}));--// Stub only the Bootstrap-Tooltip hook (it drives the jQuery tooltip plugin, absent under happy-dom);-// the rest of the hooks module — notably useTriliumEvent — stays real.-const tooltipStub = vi.hoisted(() => ({ showTooltip: () => {}, hideTooltip: () => {} }));-vi.mock("../react/hooks", async (importOriginal) => ({- ...(await importOriginal<typeof import("../react/hooks")>()),- useTooltip: () => tooltipStub-}));-import Component from "../../components/component.js";-import type FNote from "../../entities/fnote.js";+import type { MenuCommandItem, MenuItem } from "../../menus/context_menu.js";+import type { TreeCommandNames } from "../../menus/tree_context_menu.js";+import attributes from "../../services/attributes.js";+import type { NoteTypeData } from "../../services/note_types.js";import server from "../../services/server.js";import { buildNote } from "../../test/easy-froca.js";import { ParentComponent } from "../react/react_utils.js";-import NoteTypeSwitcher, { TemplateNoteTypes, useBuiltinTemplates } from "./NoteTypeSwitcher.js";--// happy-dom has no ResizeObserver; Dropdown only needs observe/disconnect to exist.-class ResizeObserverStub {- observe() {}- unobserve() {}- disconnect() {}-}-globalThis.ResizeObserver = globalThis.ResizeObserver ?? (ResizeObserverStub as unknown as typeof ResizeObserver);+import NoteTypeSwitcher, { NoteTypeBadges, toSwitcherItems, useNoteTypeData } from "./NoteTypeSwitcher.js";-let container: HTMLDivElement;+let container: HTMLDivElement | undefined;afterEach(() => {- act(() => render(null, container));- container.remove();-});--function mountHook() {- const host = new Component();- let templates: { builtinTemplates: FNote[]; collectionTemplates: FNote[] } | undefined;-- function Harness() {- templates = useBuiltinTemplates();- return null;- }-- container = document.createElement("div");- document.body.appendChild(container);- act(() => render(<ParentComponent.Provider value={host}><Harness /></ParentComponent.Provider>, container));-- return { host, getTemplates: () => templates };-}--// The hook resolves the root note, re-renders, then resolves the children — each async step-// needs its own act() round so the intermediate state commits and the next effect fires.-async function flush() {- for (let i = 0; i < 3; i++) {- await act(async () => { await new Promise((resolve) => setTimeout(resolve)); });+ if (container) {+ const mounted = container;+ act(() => render(null, mounted));+ mounted.remove();+ container = undefined;}-}+ vi.restoreAllMocks();+});describe("NoteTypeSwitcher", () => {it("offers a switch on a text note, and stays away from code notes", () => {- // The switcher resolves the built-in templates through froca on mount.- buildNote({ id: "_templates", title: "Templates" });-- expect(renderSwitcher(buildNote({ id: "textNote", title: "Note", type: "text" }))).not.toBeNull();- expect(renderSwitcher(buildNote({ id: "codeNote", title: "Script", type: "code", mime: "application/javascript;env=backend" }))).toBeNull();- });-});--function renderSwitcher(note: FNote) {- if (container?.isConnected) {- act(() => render(null, container));- container.remove();- }-- const host = new Component();- container = document.createElement("div");- document.body.appendChild(container);- act(() => render(- <ParentComponent.Provider value={host}><NoteTypeSwitcher note={note} /></ParentComponent.Provider>,- container- ));- return container.querySelector(".note-type-switcher");-}--describe("TemplateNoteTypes", () => {- it("re-resolves user templates on frocaReloaded (fresh FNote refs after unlock)", async () => {- buildNote({ id: "userTemplate1", title: "[protected]" });- const serverGetSpy = vi.spyOn(server, "get").mockResolvedValue({ templateNoteIds: [ "userTemplate1" ], newTemplateNoteIds: [] });-- const host = new Component();- container = document.createElement("div");- document.body.appendChild(container);- act(() => render(- <ParentComponent.Provider value={host}>- <TemplateNoteTypes noteId="someNote" builtinTemplates={[]} />- </ParentComponent.Provider>,- container- ));- await flush();- expect(serverGetSpy).toHaveBeenCalledWith("search-templates");-- // Unlock rebuilds froca: same noteId, new FNote instance with the decrypted title.- buildNote({ id: "userTemplate1", title: "Meeting Notes" });- serverGetSpy.mockClear();- await act(async () => { await host.handleEvent("frocaReloaded", {}); });- await flush();- expect(serverGetSpy).toHaveBeenCalledWith("search-templates");-- // The dropdown renders its items only while open; opening is driven by Bootstrap's event.- const dropdown = container.querySelector(".dropdown");- expect(dropdown).not.toBeNull();- await act(async () => {- if (dropdown) window.$(dropdown).children("button:not([aria-expanded=true])").trigger("click");- });- expect(document.body.textContent).toContain("Meeting Notes");- expect(document.body.textContent).not.toContain("[protected]");-- serverGetSpy.mockRestore();+ expect(mount(<NoteTypeSwitcher note={buildNote({ id: "textNote", title: "Note", type: "text" })} />)+ .querySelector(".note-type-switcher")).not.toBeNull();+ expect(mount(<NoteTypeSwitcher note={buildNote({ id: "codeNote", title: "Script", type: "code", mime: "application/javascript;env=backend" })} />)+ .querySelector(".note-type-switcher")).toBeNull();});-});-describe("useBuiltinTemplates", () => {- it("swaps to fresh FNote refs on frocaReloaded (protected template titles decrypt after unlock)", async () => {- // Locked protected session: the built-in template titles are the encrypted placeholder.+ it("offers Markdown and Canvas as pills, and the code languages, collections, templates and the rest from dropdowns", async () => {buildNote({id: "_templates",title: "Templates",children: [- { id: "_templateA", title: "[protected]", "#template": "" },- { id: "_templateB", title: "[protected]", "#template": "", "#collection": "" }+ { id: "_board", title: "Board", "#template": "", "#collection": "" },+ { id: "_meeting", title: "Meeting", "#template": "" }]});+ vi.spyOn(server, "get").mockResolvedValue({ templateNoteIds: [], newTemplateNoteIds: [] });- const { host, getTemplates } = mountHook();+ const host = mount(<NoteTypeBadges noteId="someNote" />);await flush();- const stale = getTemplates();- expect(stale?.builtinTemplates.map((note) => note.title)).toEqual([ "[protected]" ]);- expect(stale?.collectionTemplates.map((note) => note.title)).toEqual([ "[protected]" ]);+ const icons = [ ...host.querySelectorAll(".ext-badge > .bx:first-child, .ext-badge .bx:not(.arrow)") ]+ .map((icon) => [ ...icon.classList ].find((name) => name !== "bx"));+ expect(icons).toEqual([ "bxl-markdown", "bx-pen", "bx-code", "bx-book", "bx-copy-alt", "bx-dots-vertical-rounded" ]);+ });+});- // Unlocking rebuilds froca from scratch: same noteIds, brand-new FNote instances,- // now with decrypted titles. The old instances stay orphaned in the hook's state- // unless frocaReloaded triggers a re-resolve.- buildNote({- id: "_templates",- title: "Templates",- children: [- { id: "_templateA", title: "Grid View", "#template": "" },- { id: "_templateB", title: "Board", "#template": "", "#collection": "" }- ]- });+describe("toSwitcherItems", () => {+ it("switches the note to the row's note type or template, keeping rows of their own and leaving out what the note is or cannot become", () => {+ const put = vi.spyOn(server, "put").mockResolvedValue({});+ const setRelation = vi.spyOn(attributes, "setRelation").mockResolvedValue(undefined);+ const configure = vi.fn();+ const row = (item: Partial<MenuCommandItem<TreeCommandNames>>): MenuItem<TreeCommandNames> =>+ ({ title: item.type ?? "row", command: "insertNoteAfter", ...item });++ const items = toSwitcherItems([+ row({ type: "text" }),+ row({ type: "code", mime: "text/plain", items: [ row({ type: "code", mime: "text/x-python" }), { kind: "separator" }, row({ title: "Configure", handler: configure }) ] }),+ { kind: "separator" },+ row({ title: "More", items: [ row({ type: "search" }), row({ type: "webView", mime: "" }) ] }),+ row({ title: "Meeting", type: "text", templateNoteId: "_meeting" })+ ], "someNote");++ const commandItems = (list: MenuItem<unknown>[]) => list.filter((item): item is MenuCommandItem<unknown> => !("kind" in item));+ const run = (item: MenuCommandItem<unknown> | undefined) => item?.handler?.(item, new MouseEvent("click"));+ const [ code, more, template ] = commandItems(items);++ // Text is what the note already is, and a text note does not become a saved search.+ expect(commandItems(items).map((item) => item.title)).toEqual([ "code", "More", "Meeting" ]);+ expect(commandItems(more.items ?? []).map((item) => item.title)).toEqual([ "webView" ]);+ expect(commandItems(items).every((item) => item.command === undefined)).toBe(true);++ const [ python, configureRow ] = commandItems(code.items ?? []);+ run(python);+ expect(put).toHaveBeenCalledWith("notes/someNote/type", { type: "code", mime: "text/x-python" });+ run(configureRow);+ expect(configure).toHaveBeenCalled();+ run(template);+ expect(setRelation).toHaveBeenCalledWith("someNote", "template", "_meeting");+ expect(put).toHaveBeenCalledTimes(1);+ });+});- await act(async () => { await host.handleEvent("frocaReloaded", {}); });+describe("useNoteTypeData", () => {+ it("loads the templates again on frocaReloaded, for fresh FNote refs after a protected session starts", async () => {+ buildNote({ id: "_templates", title: "Templates" });+ buildNote({ id: "userTemplate1", title: "[protected]" });+ const serverGet = vi.spyOn(server, "get").mockResolvedValue({ templateNoteIds: [ "userTemplate1" ], newTemplateNoteIds: [] });++ const host = new Component();+ let data: NoteTypeData | undefined;+ function Harness() {+ data = useNoteTypeData();+ return null;+ }+ mount(<Harness />, host);await flush();+ expect(data?.userTemplateNotes.map((note) => note.title)).toEqual([ "[protected]" ]);- const fresh = getTemplates();- expect(fresh?.builtinTemplates.map((note) => note.title)).toEqual([ "Grid View" ]);- expect(fresh?.collectionTemplates.map((note) => note.title)).toEqual([ "Board" ]);- expect(fresh?.builtinTemplates[0]).not.toBe(stale?.builtinTemplates[0]);+ // Entering the protected session rebuilds froca: same noteId, a new FNote with the decrypted title.+ buildNote({ id: "userTemplate1", title: "Meeting Notes" });+ serverGet.mockClear();+ await act(async () => { await host.handleEvent("frocaReloaded", {}); });+ await flush();+ expect(serverGet).toHaveBeenCalledWith("search-templates");+ expect(data?.userTemplateNotes.map((note) => note.title)).toEqual([ "Meeting Notes" ]);});});++function mount(content: ComponentChildren, host = new Component()) {+ if (container) {+ const mounted = container;+ act(() => render(null, mounted));+ mounted.remove();+ }+ const element = document.createElement("div");+ container = element;+ document.body.appendChild(element);+ act(() => render(<ParentComponent.Provider value={host}>{content}</ParentComponent.Provider>, element));+ return element;+}++// Loading resolves the templates root, then its children and the user's templates; each async step+// needs its own act() round so that the state commits.+async function flush() {+ for (let i = 0; i < 3; i++) {+ await act(async () => { await new Promise((resolve) => setTimeout(resolve)); });+ }+}diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsxindex 775ea197a4..c696f5836e 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx@@ -1,42 +1,29 @@import "./NoteTypeSwitcher.css";-import { NoteType, type TemplatesResponse } from "@triliumnext/commons";-import { useEffect, useMemo, useState } from "preact/hooks";+import type { NoteType } from "@triliumnext/commons";+import { useEffect, useState } from "preact/hooks";import FNote from "../../entities/fnote";+import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";+import type { TreeCommandNames } from "../../menus/tree_context_menu";import attributes from "../../services/attributes";-import { isExperimentalFeatureEnabled } from "../../services/experimental_features";-import froca from "../../services/froca";import { t } from "../../services/i18n";-import { NOTE_TYPES, NoteTypeMapping } from "../../services/note_types";+import note_types, { MARKDOWN_NOTE_TYPE_MIME, NOTE_TYPES, type NoteTypeData } from "../../services/note_types";import server from "../../services/server";import { Badge, BadgeWithDropdown } from "../react/Badge";-import { FormDropdownDivider, FormListItem } from "../react/FormList";import { useNoteProperty, useNoteSavedData, useTriliumEvent } from "../react/hooks";import { onWheelHorizontalScroll } from "../widget_utils";-const SWITCHER_PINNED_NOTE_TYPES = new Set<NoteType>([ "text", "code", "book", "canvas" ]);+/** The note types offered as a pill of their own, each a single click away. */+const PINNED_NOTE_TYPES: { type: NoteType, mime?: string }[] = [+ { type: "code", mime: MARKDOWN_NOTE_TYPE_MIME },+ { type: "canvas" }+];export default function NoteTypeSwitcher({ note }: { note?: FNote | null }) {const blob = useNoteSavedData(note?.noteId);const currentNoteType = useNoteProperty(note, "type");- const { pinnedNoteTypes, restNoteTypes } = useMemo(() => {- const pinnedNoteTypes: NoteTypeMapping[] = [];- const restNoteTypes: NoteTypeMapping[] = [];- for (const noteType of NOTE_TYPES) {- if (noteType.reserved || noteType.type === "book") continue;- if (noteType.type === "search") continue;- if (noteType.type === "llmChat" && !isExperimentalFeatureEnabled("llm")) continue;- if (SWITCHER_PINNED_NOTE_TYPES.has(noteType.type)) {- pinnedNoteTypes.push(noteType);- } else {- restNoteTypes.push(noteType);- }- }- return { pinnedNoteTypes, restNoteTypes };- }, []);- const currentNoteTypeData = useMemo(() => NOTE_TYPES.find(t => t.type === currentNoteType), [ currentNoteType ]);- const { builtinTemplates, collectionTemplates } = useBuiltinTemplates();+ const currentNoteTypeData = NOTE_TYPES.find(t => t.type === currentNoteType);// Code notes fill the pane with their editor and carry no inline title, so the switcher has// nowhere to sit above them.@@ -48,150 +35,120 @@ export default function NoteTypeSwitcher({ note }: { note?: FNote | null }) {{note && blob?.length === 0 && (<><div className="intro">{t("note_title.note_type_switcher_label", { type: currentNoteTypeData?.title.toLocaleLowerCase() })}</div>- {pinnedNoteTypes.map(noteType => noteType.type !== currentNoteType && (- <Badge- key={noteType.type}- text={noteType.title}- icon={`bx ${noteType.icon}`}- onClick={() => switchNoteType(note.noteId, noteType)}- />- ))}- {collectionTemplates.length > 0 && <CollectionNoteTypes noteId={note.noteId} collectionTemplates={collectionTemplates} />}- {builtinTemplates.length > 0 && <TemplateNoteTypes noteId={note.noteId} builtinTemplates={builtinTemplates} />}- {restNoteTypes.length > 0 && <MoreNoteTypes noteId={note.noteId} restNoteTypes={restNoteTypes} />}+ <NoteTypeBadges noteId={note.noteId} /></>)}</div>);}-function MoreNoteTypes({ noteId, restNoteTypes }: { noteId: string, restNoteTypes: NoteTypeMapping[] }) {- return (- <BadgeWithDropdown- text={t("note_title.note_type_switcher_others")}- icon="bx bx-dots-vertical-rounded"- >- {restNoteTypes.map(noteType => (- <FormListItem- key={noteType.type}- icon={`bx ${noteType.icon}`}- onClick={() => switchNoteType(noteId, noteType)}- >{noteType.title}</FormListItem>- ))}- </BadgeWithDropdown>- );-}+/**+ * The pills offering what the note can become. Their dropdowns are built from the menu the note+ * tree inserts notes from, so that both offer the same note types and templates, grouped the same+ * way and with the same filter.+ */+export function NoteTypeBadges({ noteId }: { noteId: string }) {+ const data = useNoteTypeData();+ if (!data) return null;++ const userTemplates = note_types.getTemplateItems(data, "user");+ const otherTemplates = note_types.getTemplateItems(data, "other");+ const codeLanguages = toSwitcherItems(note_types.getCodeLanguageItems(), noteId);+ const collections = toSwitcherItems(note_types.getTemplateItems(data, "collection"), noteId);+ const templates = toSwitcherItems(userTemplates.length > 0 && otherTemplates.length > 0+ ? [ ...userTemplates, { kind: "separator" }, ...otherTemplates ]+ : [ ...userTemplates, ...otherTemplates ], noteId);+ const others = toSwitcherItems(note_types.buildNoteTypeItems(data), noteId);-function CollectionNoteTypes({ noteId, collectionTemplates }: { noteId: string, collectionTemplates: FNote[] }) {return (- <BadgeWithDropdown- text={t("note_title.note_type_switcher_collection")}- icon="bx bx-book"- >- {collectionTemplates.map(collectionTemplate => (- <FormListItem- key={collectionTemplate.noteId}- icon={collectionTemplate.getIcon()}- onClick={() => setTemplate(noteId, collectionTemplate.noteId)}- >{collectionTemplate.title}</FormListItem>- ))}- </BadgeWithDropdown>+ <>+ {PINNED_NOTE_TYPES.map(({ type, mime }) => {+ const noteType = NOTE_TYPES.find((nt) => nt.type === type && (mime === undefined || nt.mime === mime));+ return noteType && (+ <Badge+ key={`${type}-${mime}`}+ text={noteType.title}+ icon={`bx ${noteType.icon}`}+ onClick={() => switchNoteType(noteId, noteType.type, noteType.mime)}+ />+ );+ })}+ <BadgeWithDropdown+ text={t("note_types.code")}+ icon="bx bx-code"+ dropdownProps={{ items: codeLanguages, filterable: true }}+ />+ {collections.length > 0 && (+ <BadgeWithDropdown+ text={t("note_title.note_type_switcher_collection")}+ icon="bx bx-book"+ dropdownProps={{ items: collections }}+ />+ )}+ {templates.length > 0 && (+ <BadgeWithDropdown+ text={t("note_title.note_type_switcher_templates")}+ icon="bx bx-copy-alt"+ dropdownProps={{ items: templates, filterable: true }}+ />+ )}+ <BadgeWithDropdown+ text={t("note_title.note_type_switcher_all")}+ icon="bx bx-dots-vertical-rounded"+ dropdownProps={{ items: others, filterable: true }}+ />+ </>);}-export function TemplateNoteTypes({ noteId, builtinTemplates }: { noteId: string, builtinTemplates: FNote[] }) {- const [ userTemplates, setUserTemplates ] = useState<FNote[]>([]);+/**+ * The templates the switcher's menus are built from, loaded again when a note gains or loses+ * `#template` and after froca reloads, which replaces every `FNote` (e.g. a protected template's+ * title changes once the protected session is entered).+ */+export function useNoteTypeData() {+ const [ data, setData ] = useState<NoteTypeData>();- async function refreshTemplates() {- const { templateNoteIds } = await server.get<TemplatesResponse>("search-templates");- const templateNotes = await froca.getNotes(templateNoteIds);- setUserTemplates(templateNotes);+ function refresh() {+ note_types.loadNoteTypeData().then(setData);}- // First load.- useEffect(() => {- refreshTemplates();- }, []);+ useEffect(refresh, []);- // React to external changes.useTriliumEvent("entitiesReloaded", ({ loadResults }) => {if (loadResults.getAttributeRows().some(attr => attr.type === "label" && attr.name === "template")) {- refreshTemplates();+ refresh();}});- // Swap to fresh FNote refs after a full froca reload (e.g. entering a protected session- // clears the cache and creates new instances — old refs are orphaned with stale titles,- // leaving protected templates stuck at "[protected]" after unlock).- useTriliumEvent("frocaReloaded", () => {- refreshTemplates();- });+ useTriliumEvent("frocaReloaded", refresh);- return (- <BadgeWithDropdown- text={t("note_title.note_type_switcher_templates")}- icon="bx bx-copy-alt"- >- {userTemplates.map(template => <TemplateItem key={template.noteId} noteId={noteId} template={template} />)}- {userTemplates.length > 0 && <FormDropdownDivider />}- {builtinTemplates.map(template => <TemplateItem key={template.noteId} noteId={noteId} template={template} />)}- </BadgeWithDropdown>- );+ return data;}-function TemplateItem({ noteId, template }: { noteId: string, template: FNote }) {- return (- <FormListItem- icon={template.getIcon()}- onClick={() => setTemplate(noteId, template.noteId)}- >{template.title}</FormListItem>- );-}--function switchNoteType(noteId: string, { type, mime }: NoteTypeMapping) {- return server.put(`notes/${noteId}/type`, { type, mime });+/** Blank note types a text note is not switched to: the type it already has, and a saved search. */+const NOT_SWITCHED_TO = new Set<string>([ "text", "search" ]);++/**+ * The note type menu's rows, each switching the note to what it creates: a note type changes the+ * note's type, a template becomes the note's `~template`. A row with a handler of its own keeps it.+ */+export function toSwitcherItems(items: MenuItem<TreeCommandNames>[], noteId: string): MenuItem<unknown>[] {+ return items.flatMap((item): MenuItem<unknown>[] => {+ if ("kind" in item) return [ item ];+ const { command, handler, items: subItems, ...rest } = item;+ if (subItems) return [ { ...rest, items: toSwitcherItems(subItems, noteId) } ];+ if (handler) return [ { ...rest, handler: (_, e) => handler(item, e) } ];+ if (!item.templateNoteId && item.type && NOT_SWITCHED_TO.has(item.type)) return [];+ return [ { ...rest, handler: () => void switchTo(noteId, item) } ];+ });}-function setTemplate(noteId: string, templateId: string) {- return attributes.setRelation(noteId, "template", templateId);+function switchTo(noteId: string, { type, mime, templateNoteId }: MenuCommandItem<TreeCommandNames>) {+ if (templateNoteId) return attributes.setRelation(noteId, "template", templateNoteId);+ if (type) return switchNoteType(noteId, type, mime);}-export function useBuiltinTemplates() {- const [ templates, setTemplates ] = useState<{- builtinTemplates: FNote[];- collectionTemplates: FNote[];- }>({- builtinTemplates: [],- collectionTemplates: []- });-- async function loadBuiltinTemplates() {- const templatesRoot = await froca.getNote("_templates");- if (!templatesRoot) return;- const childNotes = await templatesRoot.getChildNotes();- const builtinTemplates: FNote[] = [];- const collectionTemplates: FNote[] = [];- for (const childNote of childNotes) {- if (!childNote.hasLabel("template")) continue;- if (childNote.hasLabel("collection")) {- collectionTemplates.push(childNote);- } else {- builtinTemplates.push(childNote);- }- }- setTemplates({ builtinTemplates, collectionTemplates });- }-- useEffect(() => {- loadBuiltinTemplates();- }, []);-- // Swap to fresh FNote refs after a full froca reload (e.g. entering a protected session- // clears the cache and creates new instances — old refs are orphaned with stale titles,- // leaving protected templates stuck at "[protected]" after unlock).- useTriliumEvent("frocaReloaded", () => {- loadBuiltinTemplates();- });-- return templates;+function switchNoteType(noteId: string, type: string, mime?: string) {+ return server.put(`notes/${noteId}/type`, { type, mime });}diff --git a/apps/client/src/widgets/react/Badge.tsx b/apps/client/src/widgets/react/Badge.tsxindex 93ca432bc8..6b68b100d2 100644--- a/apps/client/src/widgets/react/Badge.tsx+++ b/apps/client/src/widgets/react/Badge.tsx@@ -145,7 +145,7 @@ function htmlToText(html: string) {}export function BadgeWithDropdown({ text, children, tooltip, className, dropdownProps, ...props }: BadgeProps & {- children: ComponentChildren,+ children?: ComponentChildren,dropdownProps?: Partial<DropdownProps>}) {return (diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.htmlindex deb5b0f046..e7d3e84676 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.html@@ -43,7 +43,19 @@ class="image"><h3>New note type switcher</h3><p>When a new <a class="reference-link" href="#root/_help_iPIMuisry3hd">Text</a> noteis created, a note type switcher will appear below the <em>Inline title</em>.- Apart from changing the note type, it's also possible to apply a <a href="#root/_help_KC1HB96bqqHX">template</a>.</p>+ Apart from changing the note type, it's also possible to apply a <a href="#root/_help_KC1HB96bqqHX">template</a>:</p>+<ul>+ <li><em>Markdown</em> and <em>Canvas</em> switch the note to that type in one+ click.</li>+ <li><em>Code</em> lists the enabled code languages.</li>+ <li><em>Collection</em> and <em>Template</em> list the collections and the templates.</li>+ <li><em>All types</em> offers everything at once, the shortcuts above included:+ the same menu as <em>Insert note after</em> in the <a class="reference-link"+ href="#root/_help_YtSN43OrfzaA">Note tree contextual menu</a>, with every+ note type and template grouped the same way.</li>+</ul>+<p>Typing while the <em>Code</em>, <em>Template</em> or <em>All types</em> menu+ is open narrows it down to the matching entries.</p><p>The switcher will disappear as soon as a text is entered.</p><img src="6_New Layout_image.png"width="735" height="143">diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.mdindex 45cd78a2cd..1f72ca0b29 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/New Layout.md@@ -25,7 +25,14 @@ Depending on the note type, the inline title will also present some more interac### New note type switcher-When a new <a class="reference-link" href="../../Note%20Types/Text.md">Text</a> note is created, a note type switcher will appear below the _Inline title_. Apart from changing the note type, it's also possible to apply a [template](../../Advanced%20Usage/Templates.md).+When a new <a class="reference-link" href="../../Note%20Types/Text.md">Text</a> note is created, a note type switcher will appear below the _Inline title_. Apart from changing the note type, it's also possible to apply a [template](../../Advanced%20Usage/Templates.md):++* _Markdown_ and _Canvas_ switch the note to that type in one click.+* _Code_ lists the enabled code languages.+* _Collection_ and _Template_ list the collections and the templates.+* _All types_ offers everything at once, the shortcuts above included: the same menu as _Insert note after_ in the <a class="reference-link" href="Note%20Tree/Note%20tree%20contextual%20menu.md">Note tree contextual menu</a>, with every note type and template grouped the same way.++Typing while the _Code_, _Template_ or _All types_ menu is open narrows it down to the matching entries.The switcher will disappear as soon as a text is entered.