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): offer custom CSS, widget and backend script notes in the Code menu
Elian Doran2cd478da68de
diff --git a/apps/client/src/menus/context_menu.ts b/apps/client/src/menus/context_menu.tsindex 1ad3858188..887be4081f 100644--- a/apps/client/src/menus/context_menu.ts+++ b/apps/client/src/menus/context_menu.ts@@ -3,6 +3,7 @@ import { Tooltip } from "bootstrap";import { h, JSX, render } from "preact";import note_tooltip from "../services/note_tooltip.js";+import type { NotePresetId } from "../services/note_presets.js";import utils from "../services/utils.js";import { suspendModalFocusTraps } from "../widgets/react/modal_focustrap";@@ -57,6 +58,8 @@ export interface MenuCommandItem<T> {iconColorClass?: string;badges?: MenuItemBadge[];templateNoteId?: string;+ /** The scripting preset the item creates a note from, adding a label and content to its type. */+ notePreset?: NotePresetId;enabled?: boolean;handler?: MenuHandler<T>;items?: MenuItem<T>[] | null;diff --git a/apps/client/src/menus/tree_context_menu.ts b/apps/client/src/menus/tree_context_menu.tsindex 84d7a8af6f..fbd91f121d 100644--- a/apps/client/src/menus/tree_context_menu.ts+++ b/apps/client/src/menus/tree_context_menu.ts@@ -13,6 +13,7 @@ import dialogService from "../services/dialog.js";import froca from "../services/froca.js";import { t } from "../services/i18n.js";import noteCreateService from "../services/note_create.js";+import { notePresetOptions } from "../services/note_presets.js";import noteTypesService from "../services/note_types.js";import server from "../services/server.js";import toastService from "../services/toast.js";@@ -363,7 +364,7 @@ export async function handleTreeContextMenuSelect(item: MenuCommandItem<TreeCommandNames>,ctx: TreeContextMenuContext) {- const { command, type, mime, templateNoteId } = item;+ const { command, type, mime, templateNoteId, notePreset } = item;const resolved = resolveContext(ctx);const { note, branch, notePath, component, selectedOrActiveBranchIds, selectedOrActiveNoteIds } = resolved;@@ -381,6 +382,7 @@ export async function handleTreeContextMenuSelect(mime,isProtected: parentNote?.isProtected ?? false,templateNoteId,+ ...notePresetOptions(notePreset),noteContext: resolved.noteContext});} else if (command === "insertChildNote") {@@ -389,6 +391,7 @@ export async function handleTreeContextMenuSelect(mime,isProtected: note.isProtected,templateNoteId,+ ...notePresetOptions(notePreset),noteContext: resolved.noteContext});} else if (command === "openNoteInSplit") {diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.tsindex 872c051ae9..f9638268f3 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete.spec.ts@@ -315,6 +315,13 @@ describe("createNoteFromSuggestion", () => {await createNoteFromSuggestion({ action: "create-child-note", noteTitle: "X", parentNoteId: "p" });expect(createNote).toHaveBeenCalledWith("chosen/path", expect.objectContaining({ type: "code", mime: "text/x-python" }));++ // A preset adds its label to the type it names.+ chooseNoteType.mockResolvedValue({ success: true, noteType: "code", mime: "text/css", notePreset: "appCss", notePath: "chosen/path" });+ await createNoteFromSuggestion({ action: "create-child-note", noteTitle: "X", parentNoteId: "p" });+ expect(createNote).toHaveBeenLastCalledWith("chosen/path", expect.objectContaining({+ type: "code", mime: "text/css", attributes: [ { type: "label", name: "appCss", value: "" } ]+ }));});it.each([diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex cce9d9f097..d16df7e8fc 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -5,6 +5,7 @@ import commandRegistry from "./command_registry.js";import dateNoteService from "./date_notes.js";import { t } from "./i18n.js";import noteCreateService from "./note_create.js";+import { notePresetOptions } from "./note_presets.js";import server from "./server.js";import { escapeHtml } from "./utils.js";import { logError } from "./ws.js";@@ -112,7 +113,9 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes, all* need not be.*/export async function createNoteFromSuggestion(suggestion: Suggestion, childParentNotePath?: string | null) {- const { success, noteType, mime, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();+ const {+ success, noteType, mime, templateNoteId, notePreset, notePath, cloneToNoteIds+ } = await noteCreateService.chooseNoteType();if (!success) {return;}@@ -130,6 +133,7 @@ export async function createNoteFromSuggestion(suggestion: Suggestion, childParetype: noteType,mime,templateNoteId,+ ...notePresetOptions(notePreset),cloneToNoteIds});diff --git a/apps/client/src/services/note_create.spec.ts b/apps/client/src/services/note_create.spec.tsindex b4d740e438..5caf5613d4 100644--- a/apps/client/src/services/note_create.spec.ts+++ b/apps/client/src/services/note_create.spec.ts@@ -346,6 +346,21 @@ describe("createNoteWithTypePrompt", () => {);});+ it("creates a note from a chosen preset with the label it owns", async () => {+ setActiveContext(true);+ triggerCommand.mockImplementation((_name: string, data: any) => {+ data.callback({ success: true, noteType: "code", mime: "text/css", notePreset: "appCss" });+ });++ await noteCreateService.createNoteWithTypePrompt("parent", {});++ expect(server.post).toHaveBeenCalledWith(+ `notes/parent/children?target=into&targetBranchId=`,+ expect.objectContaining({ type: "code", mime: "text/css", attributes: [ { type: "label", name: "appCss", value: "" } ] }),+ undefined+ );+ });+it("falls back to the passed parentNotePath when the chooser returns none", async () => {setActiveContext(true);triggerCommand.mockImplementation((_name: string, data: any) => {diff --git a/apps/client/src/services/note_create.ts b/apps/client/src/services/note_create.tsindex ecac21c0b1..9a7b01461b 100644--- a/apps/client/src/services/note_create.ts+++ b/apps/client/src/services/note_create.ts@@ -9,6 +9,7 @@ import type { ChooseNoteTypeResponse } from "../widgets/dialogs/note_type_chooseimport branchService from "./branches.js";import froca from "./froca.js";import { t } from "./i18n.js";+import { notePresetOptions } from "./note_presets.js";import protectedSessionHolder from "./protected_session_holder.js";import server from "./server.js";import toastService from "./toast.js";@@ -151,7 +152,9 @@ async function chooseNoteType() {}async function createNoteWithTypePrompt(parentNotePath: string, options: CreateNoteOpts = {}) {- const { success, noteType, mime, templateNoteId, notePath, cloneToNoteIds } = await chooseNoteType();+ const {+ success, noteType, mime, templateNoteId, notePreset, notePath, cloneToNoteIds+ } = await chooseNoteType();if (!success) {return;@@ -161,6 +164,7 @@ async function createNoteWithTypePrompt(parentNotePath: string, options: CreateNoptions.mime = mime;options.templateNoteId = templateNoteId;options.cloneToNoteIds = cloneToNoteIds;+ Object.assign(options, notePresetOptions(notePreset));return await createNote(notePath || parentNotePath, options);}diff --git a/apps/client/src/services/note_presets.spec.ts b/apps/client/src/services/note_presets.spec.tsnew file mode 100644index 0000000000..2612ebb205--- /dev/null+++ b/apps/client/src/services/note_presets.spec.ts@@ -0,0 +1,72 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import { applyNotePreset, getNotePresetItems, notePresetOptions } from "./note_presets.js";+import server from "./server.js";++vi.mock("./i18n.js", () => ({+ t: (key: string) => key+}));++afterEach(() => {+ vi.restoreAllMocks();+});++const BACKEND_MIME = "application/javascript;env=backend";++describe("notePresetOptions", () => {+ it("gives each preset its language and an owned label, and a widget its skeleton", () => {+ expect(notePresetOptions(undefined)).toEqual({});+ expect(notePresetOptions("appCss")).toEqual({+ type: "code",+ mime: "text/css",+ content: "",+ attributes: [ { type: "label", name: "appCss", value: "" } ]+ });+ expect(notePresetOptions("backendScript")).toEqual({+ type: "code", mime: BACKEND_MIME, content: "", attributes: []+ });++ const widget = notePresetOptions("widget");+ expect(widget).toMatchObject({+ type: "code",+ mime: "text/jsx",+ attributes: [ { type: "label", name: "widget", value: "" } ]+ });+ expect(widget.content).toContain(`import { defineWidget } from "trilium:preact";`);+ expect(widget.content).toContain(`parent: "center-pane"`);+ expect(widget.content).toContain("<span>note_types.widget-preset-sample</span>");+ });+});++describe("getNotePresetItems", () => {+ it("offers one row per preset, carrying the command and what the row creates", () => {+ const row = (notePreset: string, title: string, uiIcon: string, mime: string) =>+ ({ title, uiIcon, command: "insertChildNote", type: "code", mime, notePreset });++ expect(getNotePresetItems("insertChildNote")).toEqual([+ row("appCss", "active_content_badges.type_app_css", "bx bxs-file-css", "text/css"),+ row("widget", "active_content_badges.type_widget", "bx bxs-widget", "text/jsx"),+ row("backendScript", "active_content_badges.type_backend_script", "bx bx-server",+ BACKEND_MIME)+ ]);+ });+});++describe("applyNotePreset", () => {+ it("switches the type, then writes the content and the label, if any", async () => {+ const put = vi.spyOn(server, "put").mockResolvedValue({});++ await applyNotePreset("someNote", "widget");+ expect(put.mock.calls.map(([ url ]) => url)).toEqual([+ "notes/someNote/type", "notes/someNote/data", "notes/someNote/set-attribute"+ ]);+ expect(put.mock.calls[0][1]).toEqual({ type: "code", mime: "text/jsx" });+ expect(put.mock.calls[1][1]).toEqual({ content: expect.stringContaining("defineWidget") });+ expect(put.mock.calls[2][1]).toMatchObject({ type: "label", name: "widget", value: "" });++ put.mockClear();+ await applyNotePreset("someNote", "backendScript");+ expect(put).toHaveBeenCalledExactlyOnceWith(+ "notes/someNote/type", { type: "code", mime: BACKEND_MIME });+ });+});diff --git a/apps/client/src/services/note_presets.ts b/apps/client/src/services/note_presets.tsnew file mode 100644index 0000000000..6113a80fc9--- /dev/null+++ b/apps/client/src/services/note_presets.ts@@ -0,0 +1,92 @@+import type { MenuItem } from "../menus/context_menu.js";+import type { TreeCommandNames } from "../menus/tree_context_menu.js";+import { setLabel } from "./attributes.js";+import { t } from "./i18n.js";+import type { CreateNoteOpts } from "./note_create.js";+import server from "./server.js";++/**+ * Code notes made ready for a scripting role: the language, the label that gives the role and, for+ * a widget, a skeleton to start from. The note owns the label, so removing it turns the role off.+ *+ * Titles and content are resolved when used, as `note_create.ts` imports this module before the+ * translations are loaded.+ */+const NOTE_PRESETS = {+ appCss: {+ titleKey: "active_content_badges.type_app_css",+ icon: "bx bxs-file-css",+ mime: "text/css",+ label: "appCss"+ },+ widget: {+ titleKey: "active_content_badges.type_widget",+ icon: "bx bxs-widget",+ mime: "text/jsx",+ label: "widget",+ content: () => [+ `import { defineWidget } from "trilium:preact";`,+ "",+ "export default defineWidget({",+ ` parent: "center-pane",`,+ ` render: () => <span>${t("note_types.widget-preset-sample")}</span>`,+ "});",+ ""+ ].join("\n")+ },+ backendScript: {+ titleKey: "active_content_badges.type_backend_script",+ icon: "bx bx-server",+ mime: "application/javascript;env=backend"+ }+} satisfies Record<string, NotePreset>;++export type NotePresetId = keyof typeof NOTE_PRESETS;++interface NotePreset {+ titleKey: string;+ /** The icon class, `bx` prefix included. */+ icon: string;+ mime: string;+ label?: string;+ content?: () => string;+}++/** What `createNote` is given to make a note of the preset, or nothing without one. */+export function notePresetOptions(+ id: NotePresetId | undefined+): Pick<CreateNoteOpts, "type" | "mime" | "content" | "attributes"> {+ if (!id) return {};+ const preset: NotePreset = NOTE_PRESETS[id];+ return {+ type: "code",+ mime: preset.mime,+ content: preset.content?.() ?? "",+ attributes: preset.label ? [ { type: "label", name: preset.label, value: "" } ] : []+ };+}++/** Turns an existing, empty note into one of the preset. */+export async function applyNotePreset(noteId: string, id: NotePresetId) {+ const { mime, content, attributes } = notePresetOptions(id);+ await server.put(`notes/${noteId}/type`, { type: "code", mime });+ if (content) await server.put(`notes/${noteId}/data`, { content });+ for (const { name, value } of attributes ?? []) {+ await setLabel(noteId, name, value);+ }+}++/** The note type menu's rows, one per preset. */+export function getNotePresetItems(command?: TreeCommandNames): MenuItem<TreeCommandNames>[] {+ return (Object.keys(NOTE_PRESETS) as NotePresetId[]).map((id) => {+ const preset: NotePreset = NOTE_PRESETS[id];+ return {+ title: t(preset.titleKey),+ uiIcon: preset.icon,+ command,+ type: "code",+ mime: preset.mime,+ notePreset: id+ };+ });+}diff --git a/apps/client/src/services/note_types.spec.ts b/apps/client/src/services/note_types.spec.tsindex bb37e0c64f..31614730a4 100644--- a/apps/client/src/services/note_types.spec.ts+++ b/apps/client/src/services/note_types.spec.ts@@ -456,6 +456,36 @@ describe("new template badges", () => {}});+ it("puts the scripting presets at the top of Code, above its languages", async () => {+ withTemplates();+ const restore = withTemplatesRoot([ fakeTemplate("tpl-code-snippet", [ "template", "snippet" ], "Code snippet") ]);+ const key = (i: any) => i.notePreset ?? i.templateNoteId ?? i.mime ?? i.kind;+ const original = options.get("codeNotesMimeTypes");+ try {+ options.set("codeNotesMimeTypes", JSON.stringify([ "text/x-python" ]));+ const data = await noteTypesService.loadNoteTypeData();+ const menu: any[] = noteTypesService.buildNoteTypeItems(data, "insertChildNote" as never);++ const code = menu.find((i) => i.type === "code" && i.mime === "text/plain");+ expect(code.items.map(key)).toEqual([+ "appCss", "widget", "backendScript",+ "separator",+ "text/plain", "text/x-python",+ "separator",+ undefined+ ]);+ expect(code.items.slice(0, 3).every((i: any) => i.command === "insertChildNote")).toBe(true);++ // Neither the top level nor More offers them a second time.+ const more = menu.find((i) => i.title === "note_types.more");+ expect([ ...menu, ...more.items ].some((i) => i.notePreset)).toBe(false);+ expect(more.items.map(key).slice(-2)).toEqual([ "separator", "tpl-code-snippet" ]);+ } finally {+ options.set("codeNotesMimeTypes", original);+ restore();+ }+ });+it("groups the note types of the menu by kind, common ones first, and offers each exactly once", async () => {withTemplates();const restore = withTemplatesRoot([ fakeTemplate("tpl-ai", [ "template", "aiQuickAction" ], "AI quick action") ]);@@ -473,7 +503,8 @@ describe("new template badges", () => {]);// No creatable type is left out or offered twice, at the top level and under More.- const offered = [ ...menu, ...menu.at(-1).items ].filter((i) => i.command && !i.templateNoteId).map(key);+ const offered = [ ...menu, ...menu.at(-1).items ]+ .filter((i) => i.command && !i.templateNoteId && !i.notePreset).map(key);const creatable = selectableNoteTypes(false).filter((nt) => nt.type !== "book").map((nt) => (nt.mime === "text/x-markdown" ? "markdown" : nt.type));expect([ ...offered ].sort()).toEqual([ ...creatable, "noteMap", "search" ].sort());@@ -554,7 +585,8 @@ describe("new template badges", () => {const code = codeRow(noteTypesService.buildNoteTypeItems(data, "insertChildNote" as never));// The row still makes a plain text code note of its own.expect(code.command).toBe("insertChildNote");- const languages = code.items.filter((i: any) => i.mime);+ // The scripting presets lead the submenu; the languages follow them.+ const languages = code.items.filter((i: any) => i.mime && !i.notePreset);// Plain text is always enabled; Markdown has an entry of its own.expect(languages.map((i: any) => i.mime)).toEqual([ "text/plain", "text/x-python" ]);expect(languages.every((i: any) => i.type === "code" && i.command === "insertChildNote")).toBe(true);diff --git a/apps/client/src/services/note_types.ts b/apps/client/src/services/note_types.tsindex 71892df0a2..2ae35d1398 100644--- a/apps/client/src/services/note_types.ts+++ b/apps/client/src/services/note_types.ts@@ -9,6 +9,7 @@ import type { NoteType } from "../entities/fnote.js";import type { MenuCommandItem, MenuItem, MenuItemBadge, MenuSeparatorItem } from "../menus/context_menu.js";import type { TreeCommandNames } from "../menus/tree_context_menu.js";import { isExperimentalFeatureEnabled } from "./experimental_features.js";+import { getNotePresetItems } from "./note_presets.js";import froca from "./froca.js";import { t } from "./i18n.js";import mimeTypes from "./mime_types.js";@@ -253,7 +254,14 @@ function buildNoteTypeItems(data: NoteTypeData, command?: TreeCommandNames) {...builtIn("snippet"),...(isExperimentalFeatureEnabled("llm") ? builtIn("aiQuickAction") : [])];- items.push({ title: t("note_types.more"), uiIcon: "bx bx-dots-horizontal-rounded", items: [ ...inGroup(MORE_GROUP), ...withLeading(SEPARATOR, editorTemplates) ] });+ items.push({+ title: t("note_types.more"),+ uiIcon: "bx bx-dots-horizontal-rounded",+ items: [+ ...inGroup(MORE_GROUP),+ ...withLeading(SEPARATOR, editorTemplates)+ ]+ });items.push(...getUserTemplates(command, userTemplateNotes, newTemplates));return items;@@ -303,9 +311,9 @@ function getBlankNoteTypes(command?: TreeCommandNames): MenuCommandItem<TreeComm}/**- * The code languages enabled in the code note options, Markdown aside since it has an entry of its- * own, then a row to configure them. The options are read again each time, so a language enabled- * since the last menu is offered.+ * The scripting presets, then the code languages enabled in the code note options, Markdown aside+ * since it has an entry of its own, then a row to configure them. The options are read again each+ * time, so a language enabled since the last menu is offered.*/function getCodeLanguageItems(command?: TreeCommandNames): MenuItem<TreeCommandNames>[] {mimeTypes.loadMimeTypes();@@ -320,6 +328,8 @@ function getCodeLanguageItems(command?: TreeCommandNames): MenuItem<TreeCommandN}));return [+ ...getNotePresetItems(command),+ SEPARATOR,...languages,SEPARATOR,{diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex ac6729160e..9a28759ef9 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2580,7 +2580,8 @@"spreadsheet": "Spreadsheet","note-types": "Note types","built-in-templates": "Built-in templates",- "more": "More"+ "more": "More",+ "widget-preset-sample": "Hello from a widget"},"template_selection": {"add-existing": "Add existing template",diff --git a/apps/client/src/widgets/dialogs/note_type_chooser.tsx b/apps/client/src/widgets/dialogs/note_type_chooser.tsxindex 3b95419281..6a7590de4b 100644--- a/apps/client/src/widgets/dialogs/note_type_chooser.tsx+++ b/apps/client/src/widgets/dialogs/note_type_chooser.tsx@@ -4,6 +4,7 @@ import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";import type { TreeCommandNames } from "../../menus/tree_context_menu";import { t } from "../../services/i18n";import type { Suggestion } from "../../services/note_autocomplete";+import type { NotePresetId } from "../../services/note_presets";import note_types from "../../services/note_types";import FormGroup from "../react/FormGroup";import { useTriliumEvent } from "../react/hooks";@@ -17,6 +18,7 @@ export interface ChooseNoteTypeResponse {/** The MIME type of the note, for a code note of a given language. */mime?: string;templateNoteId?: string;+ notePreset?: NotePresetId;notePath?: string;/** Extra parents to clone the created note into, from the template's default parents. */cloneToNoteIds?: string[];@@ -72,6 +74,7 @@ export default function NoteTypeChooserDialogComponent() {noteType: item.type,mime: item.mime,templateNoteId: item.templateNoteId,+ notePreset: item.notePreset,notePath: parentNote?.notePath});setShown(false);diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsxindex 7e7d4813d7..1fde3b7492 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.spec.tsx@@ -53,7 +53,7 @@ describe("NoteTypeSwitcher", () => {});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", () => {+ it("switches the note to the row's note type, template or preset, keeping rows of their own and leaving out what the note is or cannot become", async () => {const put = vi.spyOn(server, "put").mockResolvedValue({});const setRelation = vi.spyOn(attributes, "setRelation").mockResolvedValue(undefined);const configure = vi.fn();@@ -65,15 +65,16 @@ describe("toSwitcherItems", () => {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" })+ row({ title: "Meeting", type: "text", templateNoteId: "_meeting" }),+ row({ title: "Custom CSS", type: "code", mime: "text/css", notePreset: "appCss" })], "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);+ const [ code, more, template, preset ] = 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(items).map((item) => item.title)).toEqual([ "code", "More", "Meeting", "Custom CSS" ]);expect(commandItems(more.items ?? []).map((item) => item.title)).toEqual([ "webView" ]);expect(commandItems(items).every((item) => item.command === undefined)).toBe(true);@@ -85,6 +86,12 @@ describe("toSwitcherItems", () => {run(template);expect(setRelation).toHaveBeenCalledWith("someNote", "template", "_meeting");expect(put).toHaveBeenCalledTimes(1);++ // A preset gives the note its type, then its label.+ run(preset);+ await vi.waitFor(() => expect(put).toHaveBeenCalledTimes(3));+ expect(put).toHaveBeenNthCalledWith(2, "notes/someNote/type", { type: "code", mime: "text/css" });+ expect(put).toHaveBeenNthCalledWith(3, "notes/someNote/set-attribute", expect.objectContaining({ name: "appCss" }), undefined);});});diff --git a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsxindex c696f5836e..3d435defae 100644--- a/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx+++ b/apps/client/src/widgets/layout/NoteTypeSwitcher.tsx@@ -8,6 +8,7 @@ import type { MenuCommandItem, MenuItem } from "../../menus/context_menu";import type { TreeCommandNames } from "../../menus/tree_context_menu";import attributes from "../../services/attributes";import { t } from "../../services/i18n";+import { applyNotePreset } from "../../services/note_presets";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";@@ -131,7 +132,8 @@ 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.+ * note's type, a template becomes the note's `~template`, a preset sets the type, label and content+ * of its own. 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>[] => {@@ -144,8 +146,12 @@ export function toSwitcherItems(items: MenuItem<TreeCommandNames>[], noteId: str});}-function switchTo(noteId: string, { type, mime, templateNoteId }: MenuCommandItem<TreeCommandNames>) {+function switchTo(+ noteId: string,+ { type, mime, templateNoteId, notePreset }: MenuCommandItem<TreeCommandNames>+) {if (templateNoteId) return attributes.setRelation(noteId, "template", templateNoteId);+ if (notePreset) return applyNotePreset(noteId, notePreset);if (type) return switchNoteType(noteId, type, mime);}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 e7d3e84676..0771b155ee 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@@ -47,7 +47,8 @@ class="image"><ul><li><em>Markdown</em> and <em>Canvas</em> switch the note to that type in oneclick.</li>- <li><em>Code</em> lists the enabled code languages.</li>+ <li><em>Code</em> lists the scripting notes (<em>Custom CSS</em>, <em>Widget</em> and <em>Backend script</em>),+ then 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"diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.htmlindex e43c2d30ec..416addc8cd 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.html@@ -44,6 +44,10 @@<li><strong>Insert note after</strong><ul><li>Allows easy creation of a note with a specified <a href="#root/_help_KSZ04uQ2D1St">note type</a>.</li>+ <li>The <em>Code</em> submenu starts with the scripting notes, each a code note+ set up for its role: <em>Custom CSS</em> (with <code>#appCss</code>), <em>Widget</em> (with <code>#widget</code> and+ a starting skeleton) and <em>Backend script</em>. The enabled code languages+ follow.</li><li><a class="reference-link" href="#root/_help_GTwFsgaA0lCt">Collections</a> aregrouped in the <em>Collection</em> submenu. The note types created less often,the <a class="reference-link" href="#root/_help_B2ORr7OVEZtc">Snippets</a> anddiff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.htmlindex a5d9d3914d..adcf61a98f 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Backend scripts.html@@ -20,7 +20,9 @@in memory. Whereas on the client, notes have to be manually loaded first.</p><h2>Creating a backend script</h2><p>Create a new <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> note- and select the language <em>JavaScript (Trilium backend)</em>.</p>+ and select the language <em>JavaScript (Trilium backend)</em>, or choose <em>Insert child note</em> → <em>Code</em> → <em>Backend script</em> in+ the <a class="reference-link" href="#root/_help_YtSN43OrfzaA">Note tree contextual menu</a>,+ which does both in one step.</p><h2>Running backend scripts</h2><p>Backend scripts can be either run manually (via the Execute button onthe script page), or they can be triggered on certain events.</p>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.htmlindex dbdbeae89f..95c3fe2151 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.html@@ -17,6 +17,11 @@<p>Wherever possible, widget examples will be both in the legacy and Preactformat.</p><h2>Creating a custom widget</h2>+<p>The quickest way is <em>Insert child note</em> → <em>Code</em> → <em>Widget</em> in+ the <a class="reference-link" href="#root/_help_YtSN43OrfzaA">Note tree contextual menu</a>.+ It creates a JSX note with the <code>#widget</code> label and a minimal Preact+ widget to start from.</p>+<p>To set one up by hand instead:</p><ol><li>Create a <a class="reference-link" href="#root/_help_6f9hih2hXXZk">Code</a> note.</li><li>Set the language to:diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Custom app-wide CSS.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Custom app-wide CSS.htmlindex a16bba12d7..45dfaed761 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Custom app-wide CSS.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Custom app-wide CSS.html@@ -1,5 +1,9 @@<p>It is possible to provide a CSS file to be used regardless of the themeset by the user.</p>+<p>The quickest way to create one is <em>Insert child note</em> → <em>Code</em> → <em>Custom CSS</em> in+ the <a class="reference-link" href="#root/_help_YtSN43OrfzaA">Note tree contextual menu</a>,+ which creates a CSS note that already has the <code>#appCss</code> label.+ To set one up by hand instead:</p><figure class="table"><table><thead>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 1f72ca0b29..5a9835238b 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@@ -28,7 +28,7 @@ Depending on the note type, the inline title will also present some more interacWhen 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.+* _Code_ lists the scripting notes (_Custom CSS_, _Widget_ and _Backend script_), then 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.diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.mdindex 9ad38bb96a..bb3ad779fe 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/UI Elements/Note Tree/Note tree contextual menu.md@@ -24,6 +24,7 @@ The contextual menu can operate:* Will focus the note tree on this note. See <a class="reference-link" href="../../Navigation/Note%20Hoisting.md">Note Hoisting</a> for more information.* **Insert note after*** Allows easy creation of a note with a specified [note type](../../../Note%20Types.md).+ * The _Code_ submenu starts with the scripting notes, each a code note set up for its role: _Custom CSS_ (with `#appCss`), _Widget_ (with `#widget` and a starting skeleton) and _Backend script_. The enabled code languages follow.* <a class="reference-link" href="../../../Collections.md">Collections</a> are grouped in the _Collection_ submenu. The note types created less often, the <a class="reference-link" href="../../../Advanced%20Usage/Snippets.md">Snippets</a> and the AI quick action are in the _More_ submenu.* <a class="reference-link" href="../../../Advanced%20Usage/Templates.md">Templates</a> will also be present (if any) at the end of the list.* To find an entry quickly, type into the search box at the top of the submenu, or just start typing while the submenu is open. The submenu then lists every matching entry, including those inside its own submenus (such as a code language or a collection), each with the submenu it comes from. Use <kbd>↑</kbd> and <kbd>↓</kbd> to pick a match, <kbd>Enter</kbd> to create it, and <kbd>Esc</kbd> to clear the search.diff --git a/docs/User Guide/User Guide/Scripting/Backend scripts.md b/docs/User Guide/User Guide/Scripting/Backend scripts.mdindex 89b06e1fc3..c14c4ccf45 100644--- a/docs/User Guide/User Guide/Scripting/Backend scripts.md+++ b/docs/User Guide/User Guide/Scripting/Backend scripts.md@@ -14,7 +14,7 @@ However, the main benefit of backend scripts is that they have easier access to## Creating a backend script-Create a new <a class="reference-link" href="../Note%20Types/Code.md">Code</a> note and select the language _JavaScript (Trilium backend)_.+Create a new <a class="reference-link" href="../Note%20Types/Code.md">Code</a> note and select the language _JavaScript (Trilium backend)_, or choose _Insert child note_ → _Code_ → _Backend script_ in the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree/Note%20tree%20contextual%20menu.md">Note tree contextual menu</a>, which does both in one step.## Running backend scriptsdiff --git a/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.md b/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.mdindex 1a1f900458..a6484de206 100644--- a/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.md+++ b/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.md@@ -13,6 +13,10 @@ Wherever possible, widget examples will be both in the legacy and Preact format.## Creating a custom widget+The quickest way is _Insert child note_ → _Code_ → _Widget_ in the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree/Note%20tree%20contextual%20menu.md">Note tree contextual menu</a>. It creates a JSX note with the `#widget` label and a minimal Preact widget to start from.++To set one up by hand instead:+1. Create a <a class="reference-link" href="../../Note%20Types/Code.md">Code</a> note.2. Set the language to:1. JavaScript (frontend) for legacy widgets using jQuery.diff --git a/docs/User Guide/User Guide/Theme development/Custom app-wide CSS.md b/docs/User Guide/User Guide/Theme development/Custom app-wide CSS.mdindex 9530377530..0dedb4d1a5 100644--- a/docs/User Guide/User Guide/Theme development/Custom app-wide CSS.md+++ b/docs/User Guide/User Guide/Theme development/Custom app-wide CSS.md@@ -1,6 +1,8 @@# Custom app-wide CSSIt is possible to provide a CSS file to be used regardless of the theme set by the user.+The quickest way to create one is _Insert child note_ → _Code_ → _Custom CSS_ in the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20Tree/Note%20tree%20contextual%20menu.md">Note tree contextual menu</a>, which creates a CSS note that already has the `#appCss` label. To set one up by hand instead:+| | || --- | --- ||  | Start by creating a new note and changing the note type to CSS |