Skip to content

Build your personal knowledge base with Trilium Notes

refactor(ckeditor5): fold the extra slash commands into the palette

Elian Doran94a50ca6da6a
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 38ed65c3e0..1e5fe671c3 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -1,4 +1,4 @@
-import { buildExtraCommands, type EditorConfig, getCkLocale, SnippetDefinition } from "@triliumnext/ckeditor5";
+import { type EditorConfig, getCkLocale, SnippetDefinition } from "@triliumnext/ckeditor5";
import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en.json?url";
import { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";
import i18next from "i18next";
@@ -172,12 +172,11 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
copy: copyTextWithToast
},
slashCommand: {
- // Drop CKEditor's built-in slash commands whose title/icon we re-define in
- // buildExtraCommands: the Mermaid one (generic icon) and the list ones
- // (Title Case titles, normalized to sentence case).
+ // Drop CKEditor's built-in slash commands whose title/icon the palette re-defines: the
+ // Mermaid one (generic icon) and the list ones (Title Case titles, normalized to
+ // sentence case).
removeCommands: ["insertMermaidCommand", "bulletedList", "numberedList", "todoList"],
- dropdownLimit: Number.MAX_SAFE_INTEGER,
- extraCommands: buildExtraCommands((key) => t(key), SAMPLE_DIAGRAMS)
+ dropdownLimit: Number.MAX_SAFE_INTEGER
},
snippets: {
definitions: opts.templates
diff --git a/packages/ckeditor5/src/extra_slash_commands.spec.ts b/packages/ckeditor5/src/extra_slash_commands.spec.ts
deleted file mode 100644
index 4fbcce8dff..0000000000
--- a/packages/ckeditor5/src/extra_slash_commands.spec.ts
+++ /dev/null
@@ -1,367 +0,0 @@
-import { describe, expect, it, vi } from "vitest";
-
-import buildExtraCommands from "./extra_slash_commands.js";
-
-// Minimal fake editor that records execute() calls and supports plugin lookup.
-function makeFakeEditor() {
- const pluginInstances = new Map<unknown, unknown>();
- const executeSpy = vi.fn();
-
- const editor = {
- execute: executeSpy,
- plugins: {
- get: (key: unknown) => pluginInstances.get(key)
- },
- _pluginInstances: pluginInstances
- };
-
- return { editor, executeSpy, pluginInstances };
-}
-
-describe("buildExtraCommands", () => {
- // The host translator, which i18next-style echoes back a key it has no entry for. Every message
- // therefore falls back to its English id, which is what these assertions pin.
- const t = (key: string) => key;
-
- it("returns an array", () => {
- const commands = buildExtraCommands(t);
- expect(Array.isArray(commands)).toBe(true);
- expect(commands.length).toBeGreaterThan(0);
- });
-
- it("includes the collapsible command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "collapsible");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Collapsible block");
- expect(cmd?.commandName).toBe("collapsible");
- expect(cmd?.description).toBe("Insert a toggleable section that hides/shows content on click.");
- expect(Array.isArray(cmd?.aliases)).toBe(true);
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the footnote command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "footnote");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Footnote");
- expect(cmd?.commandName).toBe("InsertFootnote");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the datetime command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "datetime");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Insert date/time");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the internal-link command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "internal-link");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Internal link");
- expect(Array.isArray(cmd?.aliases)).toBe(true);
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the include-note command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "include-note");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Include note");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the page-break command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "page-break");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Page break");
- expect(cmd?.commandName).toBe("pageBreak");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the markdown-import command", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "markdown-import");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Markdown import");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes the anchor command with execute function", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "anchor");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Anchor");
- expect(Array.isArray(cmd?.aliases)).toBe(true);
- expect(typeof cmd?.execute).toBe("function");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("anchor execute defers _showFormView via setTimeout", async () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "anchor");
- expect(cmd?.execute).toBeDefined();
-
- vi.useFakeTimers();
- const showFormView = vi.fn();
- const { editor, pluginInstances } = makeFakeEditor();
-
- // Import BookmarkUI dynamically to get the class reference.
- const { BookmarkUI } = await import("ckeditor5");
- pluginInstances.set(BookmarkUI, { _showFormView: showFormView });
-
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
-
- // Should not have been called yet (deferred via setTimeout).
- expect(showFormView).not.toHaveBeenCalled();
-
- vi.runAllTimers();
- expect(showFormView).toHaveBeenCalledOnce();
-
- vi.useRealTimers();
- });
-
- describe("math command", () => {
- it("is present with execute function and icon", async () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "math");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Math equation");
- expect(typeof cmd?.execute).toBe("function");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("execute calls MathUI._showUI()", async () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "math");
-
- const { default: MathUI } = await import("./plugins/math/math_ui.js");
- const showUI = vi.fn();
- const { editor, pluginInstances } = makeFakeEditor();
- pluginInstances.set(MathUI, { _showUI: showUI });
-
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(showUI).toHaveBeenCalledOnce();
- });
- });
-
- describe("list commands", () => {
- it("includes bulletedList with commandName and icon", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "bulletedList");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Bulleted list");
- expect(cmd?.commandName).toBe("bulletedList");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes numberedList with commandName and icon", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "numberedList");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Numbered list");
- expect(cmd?.commandName).toBe("numberedList");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("includes todoList with commandName and icon", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "todoList");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("To-do list");
- expect(cmd?.commandName).toBe("todoList");
- expect(cmd?.icon).toBeTruthy();
- });
- });
-
- describe("alignment commands", () => {
- it("includes align-left with execute function", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-left");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Align left");
- expect(typeof cmd?.execute).toBe("function");
- expect(cmd?.icon).toBeTruthy();
- });
-
- it("align-left execute calls editor.execute with alignment left", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-left");
- const { editor, executeSpy } = makeFakeEditor();
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(executeSpy).toHaveBeenCalledWith("alignment", { value: "left" });
- });
-
- it("includes align-center with execute function", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-center");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Align center");
- expect(typeof cmd?.execute).toBe("function");
- });
-
- it("align-center execute calls editor.execute with alignment center", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-center");
- const { editor, executeSpy } = makeFakeEditor();
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(executeSpy).toHaveBeenCalledWith("alignment", { value: "center" });
- });
-
- it("includes align-right with execute function", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-right");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Align right");
- expect(typeof cmd?.execute).toBe("function");
- });
-
- it("align-right execute calls editor.execute with alignment right", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-right");
- const { editor, executeSpy } = makeFakeEditor();
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(executeSpy).toHaveBeenCalledWith("alignment", { value: "right" });
- });
-
- it("includes align-justify with execute function", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-justify");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Justify");
- expect(typeof cmd?.execute).toBe("function");
- });
-
- it("align-justify execute calls editor.execute with alignment justify", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "align-justify");
- const { editor, executeSpy } = makeFakeEditor();
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(executeSpy).toHaveBeenCalledWith("alignment", { value: "justify" });
- });
- });
-
- describe("admonition commands", () => {
- // `t` echoes the key back here, so every title falls back to its English message id.
- const ENGLISH_TITLES = { note: "Note", tip: "Tip", important: "Important", caution: "Caution", warning: "Warning" };
-
- it("includes one command per admonition type with execute function", async () => {
- const { ADMONITION_TYPE_NAMES } = await import("./plugins/admonition/admonition_command.js");
- const commands = buildExtraCommands(t);
- for (const keyword of ADMONITION_TYPE_NAMES) {
- const cmd = commands.find((c) => c.id === keyword);
- expect(cmd, `admonition command for ${keyword}`).toBeDefined();
- expect(typeof cmd?.execute).toBe("function");
- expect(cmd?.icon).toBeTruthy();
- expect(cmd?.description).toBe("Insert a new admonition");
- expect(cmd?.aliases).toContain("box");
- expect(cmd?.title).toBe(ENGLISH_TITLES[keyword]);
- }
- });
-
- // Built before any editor exists, so the titles go through `translateMessage()` rather than
- // `editor.t()` — same message ids, same derived keys.
- it("translates the titles through the host translator", () => {
- const commands = buildExtraCommands((key) => (key === "text-editor.ck.warning" ? "Avertisment" : key));
-
- expect(commands.find((c) => c.id === "warning")?.title).toBe("Avertisment");
- expect(commands.find((c) => c.id === "note")?.title).toBe(ENGLISH_TITLES.note);
- });
-
- it("admonition execute calls editor.execute('admonition') with the keyword", async () => {
- const { ADMONITION_TYPE_NAMES } = await import("./plugins/admonition/admonition_command.js");
- const commands = buildExtraCommands(t);
-
- for (const keyword of ADMONITION_TYPE_NAMES) {
- const cmd = commands.find((c) => c.id === keyword);
- const { editor, executeSpy } = makeFakeEditor();
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(executeSpy).toHaveBeenCalledWith("admonition", { forceValue: keyword });
- }
- });
- });
-
- describe("mermaid commands", () => {
- it("includes a blank mermaid command when no samples given", () => {
- const commands = buildExtraCommands(t);
- const cmd = commands.find((c) => c.id === "mermaid");
- expect(cmd).toBeDefined();
- expect(cmd?.title).toBe("Mermaid diagram");
- expect(cmd?.commandName).toBeTruthy();
- expect(cmd?.icon).toBeTruthy();
- expect(cmd?.description).toBe("Insert an empty Mermaid diagram");
- });
-
- it("includes no sample commands when mermaidSamples is empty", () => {
- const commands = buildExtraCommands(t, []);
- const sampleCmds = commands.filter((c) => String(c.id).startsWith("mermaid-sample-"));
- expect(sampleCmds).toHaveLength(0);
- });
-
- it("generates one command per sample with correct id and title", () => {
- const samples = [
- { name: "Flowchart", content: "flowchart LR\n A --> B" },
- { name: "Sequence", content: "sequenceDiagram\n A ->> B: hi" }
- ];
- const commands = buildExtraCommands(t, samples);
-
- const cmd0 = commands.find((c) => c.id === "mermaid-sample-0");
- expect(cmd0).toBeDefined();
- expect(cmd0?.title).toBe("Mermaid diagram: Flowchart");
- expect(cmd0?.description).toBe("Insert a \"Flowchart\" Mermaid diagram template");
- expect(cmd0?.aliases).toContain("Flowchart");
- expect(cmd0?.icon).toBeTruthy();
-
- const cmd1 = commands.find((c) => c.id === "mermaid-sample-1");
- expect(cmd1).toBeDefined();
- expect(cmd1?.title).toBe("Mermaid diagram: Sequence");
- });
-
- it("sample command execute calls editor.execute with INSERT_MERMAID_COMMAND and source", async () => {
- const { INSERT_MERMAID_COMMAND } = await import("./plugins/mermaid/insert_mermaid_command.js");
- const samples = [
- { name: "Flowchart", content: "flowchart LR\n A --> B" }
- ];
- const commands = buildExtraCommands(t, samples);
- const cmd = commands.find((c) => c.id === "mermaid-sample-0");
- expect(typeof cmd?.execute).toBe("function");
-
- const { editor, executeSpy } = makeFakeEditor();
- cmd?.execute?.(editor as unknown as import("ckeditor5").Editor);
- expect(executeSpy).toHaveBeenCalledWith(INSERT_MERMAID_COMMAND, { source: "flowchart LR\n A --> B" });
- });
-
- // The sample name is interpolated into the translation, not concatenated onto it, so a
- // locale that has an entry decides where the name goes.
- it("substitutes the sample name into the localized title and description", () => {
- const samples = [{ name: "MyDiagram", content: "graph TD\n A" }];
- const translations: Record<string, string> = {
- "text-editor.ck.mermaid-diagram-0": "Diagramă %0",
- "text-editor.ck.insert-a-0-mermaid-diagram-template": "Șablon Mermaid „%0”"
- };
- const commands = buildExtraCommands((key) => translations[key] ?? key, samples);
- const cmd = commands.find((c) => c.id === "mermaid-sample-0");
-
- expect(cmd?.title).toBe("Diagramă MyDiagram");
- expect(cmd?.description).toBe("Șablon Mermaid „MyDiagram”");
- });
- });
-
- // Every string these definitions show is looked up, and each lookup lands under the prefix the
- // English catalog is keyed by — a definition that hardcoded its text would ask for nothing.
- it("resolves every title and description to a text-editor.ck key", () => {
- const keys: string[] = [];
-
- buildExtraCommands((key) => {
- keys.push(key);
- return key;
- }, [ { name: "Flowchart", content: "graph TD\n A" } ]);
-
- expect(keys.length).toBeGreaterThan(0);
- expect(keys.filter((key) => !key.startsWith("text-editor.ck."))).toEqual([]);
- });
-});
diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.ts
deleted file mode 100644
index 2b1749ce68..0000000000
--- a/packages/ckeditor5/src/extra_slash_commands.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-import type { Editor } from 'ckeditor5';
-import insertFootnoteIcon from './icons/insert-footnote.svg?raw';
-import { IconPageBreak, IconAlignLeft, IconAlignCenter, IconAlignRight, IconAlignJustify, IconBulletedList, IconNumberedList, IconTodoList } from "@ckeditor/ckeditor5-icons";
-import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
-import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
-import bxCommentError from "boxicons/svg/regular/bx-comment-error.svg?raw";
-import bxErrorCircle from "boxicons/svg/regular/bx-error-circle.svg?raw";
-import bxError from "boxicons/svg/regular/bx-error.svg?raw";
-import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from './plugins/insert_date_time.js';
-import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from './plugins/internallink.js';
-import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from './plugins/includenote.js';
-import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from './plugins/markdownimport.js';
-import { getAdmonitionTitle } from "./plugins/admonition/admonition_ui.js";
-import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "./plugins/admonition/admonition_command.js";
-import { translateMessage } from "./messages.js";
-import collapsibleIcon from './icons/collapsible.svg?raw';
-import dateTimeIcon from './icons/date-time.svg?raw';
-import internalLinkIcon from './icons/trilium.svg?raw';
-import noteIcon from './icons/note.svg?raw';
-import importMarkdownIcon from './icons/markdown-mark.svg?raw';
-import mathIcon from './icons/math.svg?raw';
-import MathUI from './plugins/math/math_ui.js';
-import { INSERT_MERMAID_COMMAND } from './plugins/mermaid/insert_mermaid_command.js';
-import type { MermaidSample } from './plugins/mermaid/mermaid_ui.js';
-import { BookmarkUI } from "ckeditor5";
-import bxBookmark from "boxicons/svg/regular/bx-bookmark.svg?raw";
-import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
-import type { SlashCommandDefinition } from './plugins/mention/slash_commands.js';
-
-/**
- * Resolves a full i18next key to the localized string. Supplied by the client, which owns i18n.
- *
- * The definitions below do not name keys themselves: they pass English message ids to a
- * {@link MessageTranslateFn}, which derives the key. This is the host translator that lookup ends
- * at.
- */
-export type SlashTranslateFn = (key: string) => string;
-
-/**
- * Translates one English message id, substituting `%0`, `%1`, … with `values`.
- *
- * The same contract as the `editor.t()` a plugin would call, which these definitions cannot: they
- * are built before any editor exists.
- */
-type MessageTranslateFn = (message: string, ...values: string[]) => string;
-
-export default function buildExtraCommands(
- translate: SlashTranslateFn,
- mermaidSamples: MermaidSample[] = []
-): SlashCommandDefinition[] {
- const t: MessageTranslateFn = (message, ...values) => translateMessage(translate, message, values);
-
- return [
- ...buildListExtraCommands(t),
- ...buildAlignmentExtraCommands(t),
- ...buildAdmonitionExtraCommands(t),
- ...buildMermaidCommands(t, mermaidSamples),
- {
- id: "collapsible",
- title: t("Collapsible block"),
- description: t("Insert a toggleable section that hides/shows content on click."),
- aliases: [ "details", "fold", "toggle" ],
- icon: collapsibleIcon,
- commandName: "collapsible"
- },
- {
- id: 'footnote',
- title: t("Footnote"),
- description: t("Create a new footnote and reference it here"),
- icon: insertFootnoteIcon,
- commandName: "InsertFootnote"
- },
- {
- id: "datetime",
- title: t("Insert date/time"),
- description: t("Insert the current date and time"),
- icon: dateTimeIcon,
- commandName: INSERT_DATE_TIME_COMMAND
- },
- {
- id: "internal-link",
- title: t("Internal link"),
- description: t("Insert a link to another Trilium note"),
- aliases: [ "internal link", "trilium link", "reference link" ],
- icon: internalLinkIcon,
- commandName: INTERNAL_LINK_COMMAND
- },
- {
- id: "math",
- title: t("Math equation"),
- description: t("Insert a math equation"),
- aliases: [ "latex", "equation" ],
- icon: mathIcon,
- execute: (editor: Editor) => editor.plugins.get(MathUI)._showUI()
- },
- {
- id: "include-note",
- title: t("Include note"),
- description: t("Display the content of another note in this note"),
- icon: noteIcon,
- commandName: INCLUDE_NOTE_COMMAND
- },
- {
- id: "page-break",
- title: t("Page break"),
- description: t("Insert a page break (for printing)"),
- icon: IconPageBreak,
- commandName: "pageBreak"
- },
- {
- id: "markdown-import",
- title: t("Markdown import"),
- description: t("Import Markdown from the clipboard"),
- icon: importMarkdownIcon,
- commandName: MARKDOWN_IMPORT_COMMAND
- },
- {
- id: "anchor",
- title: t("Anchor"),
- description: t("Insert an anchor for internal linking"),
- aliases: [ "bookmark" ],
- icon: bxBookmark,
- execute: (editor: Editor) => {
- // Defer to the next event loop tick so the slash command fully finishes
- // its DOM/selection cleanup; _showFormView needs the view and mapper to
- // be in a settled state for balloon positioning.
- setTimeout(() => (editor.plugins.get(BookmarkUI) as any)._showFormView(), 0);
- }
- }
- ];
-}
-
-// Replaces CKEditor's built-in `bulletedList`/`numberedList`/`todoList` slash
-// commands (removed via `removeCommands`), whose titles are Title Case, with
-// sentence-case equivalents that run the same commands.
-function buildListExtraCommands(t: MessageTranslateFn): SlashCommandDefinition[] {
- return [
- {
- id: "bulletedList",
- title: t("Bulleted list"),
- description: t("Create a bulleted list"),
- icon: IconBulletedList,
- commandName: "bulletedList"
- },
- {
- id: "numberedList",
- title: t("Numbered list"),
- description: t("Create a numbered list"),
- icon: IconNumberedList,
- commandName: "numberedList"
- },
- {
- id: "todoList",
- title: t("To-do list"),
- description: t("Create a to-do list"),
- icon: IconTodoList,
- commandName: "todoList"
- }
- ];
-}
-
-function buildMermaidCommands(t: MessageTranslateFn, samples: MermaidSample[]): SlashCommandDefinition[] {
- // The blank diagram. Replaces CKEditor's built-in `insertMermaidCommand`
- // slash command (removed via `removeCommands`), which uses a generic icon.
- const blank: SlashCommandDefinition = {
- id: "mermaid",
- title: t("Mermaid diagram"),
- description: t("Insert an empty Mermaid diagram"),
- aliases: [ "mermaid", "diagram", "flowchart" ],
- icon: bxNetworkChart,
- commandName: INSERT_MERMAID_COMMAND
- };
-
- const templates = samples.map((sample, index) => ({
- id: `mermaid-sample-${index}`,
- // The sample name is a placeholder rather than an appended string, so a locale can put the
- // name where its grammar wants it. It arrives already localized, from `mermaid.samples`.
- title: t("Mermaid diagram: %0", sample.name),
- description: t("Insert a \"%0\" Mermaid diagram template", sample.name),
- aliases: [ "mermaid", "diagram", sample.name ],
- icon: bxNetworkChart,
- // Inserts a mermaid block pre-filled with the sample source (see insertMermaidCommand).
- execute: (editor: Editor) => editor.execute(INSERT_MERMAID_COMMAND, { source: sample.content })
- }));
-
- return [ blank, ...templates ];
-}
-
-function buildAlignmentExtraCommands(t: MessageTranslateFn): SlashCommandDefinition[] {
- return [
- {
- id: "align-left",
- title: t("Align left"),
- description: t("Align text to the left"),
- icon: IconAlignLeft,
- execute: (editor: Editor) => editor.execute("alignment", { value: "left" }),
- },
- {
- id: "align-center",
- title: t("Align center"),
- description: t("Align text to the center"),
- icon: IconAlignCenter,
- execute: (editor: Editor) => editor.execute("alignment", { value: "center" }),
- },
- {
- id: "align-right",
- title: t("Align right"),
- description: t("Align text to the right"),
- icon: IconAlignRight,
- execute: (editor: Editor) => editor.execute("alignment", { value: "right" }),
- },
- {
- id: "align-justify",
- title: t("Justify"),
- description: t("Justify text alignment"),
- icon: IconAlignJustify,
- execute: (editor: Editor) => editor.execute("alignment", { value: "justify" }),
- }
- ];
-}
-
-function buildAdmonitionExtraCommands(t: MessageTranslateFn): SlashCommandDefinition[] {
- const commands: SlashCommandDefinition[] = [];
- const admonitionIcons: Record<AdmonitionType, string> = {
- note: bxInfoCircle,
- tip: bxBulb,
- important: bxCommentError,
- caution: bxErrorCircle,
- warning: bxError,
- };
-
- for (const type of ADMONITION_TYPE_NAMES) {
- commands.push({
- id: type,
- title: getAdmonitionTitle(t, type),
- description: t("Insert a new admonition"),
- icon: admonitionIcons[type],
- execute: (editor: Editor) => editor.execute("admonition", { forceValue: type }),
- aliases: [ "box" ]
- });
- }
- return commands;
-}
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 437cbd4974..421c184f01 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -14,7 +14,6 @@ export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/menti
export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
-export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
export { MESSAGE_KEY_PREFIX, MESSAGE_OVERRIDES, slugify } from "./messages.js";
export * from "./utils.js";
diff --git a/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts b/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts
index 2553941085..0ad40dcb1f 100644
--- a/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts
+++ b/packages/ckeditor5/src/plugins/admonition/admonition_ui.ts
@@ -112,8 +112,7 @@ export default class AdmonitionUI extends Plugin {
* `t()` call: that is how the messages this package owns are discovered (see `messages.ts`) and a
* title tucked away in a table would be invisible to translators.
*
- * @param t the editor's translation function (`editor.t`), or the host translator where no editor
- * exists yet — see `translateMessage()`.
+ * @param t the editor's translation function (`editor.t`).
* @param type the admonition type; an unrecognized one has no title and is returned as-is.
*/
export function getAdmonitionTitle(t: (message: string) => string, type: AdmonitionType): string {
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
index ab28f91b3b..0294d5b159 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -1,7 +1,10 @@
import {
+ Alignment,
BlockQuote,
+ BookmarkUI,
type ClassicEditor,
ContextualBalloon,
+ type Editor,
Essentials,
_getModelData as getModelData,
Heading,
@@ -13,10 +16,18 @@ import {
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
+import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";
+import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from "../insert_date_time.js";
+import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";
+import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";
+import MathUI from "../math/math_ui.js";
+import { INSERT_MERMAID_COMMAND } from "../mermaid/insert_mermaid_command.js";
import TriliumSnippets from "../snippets/snippets.js";
import type { SnippetDefinition } from "../snippets/snippetsconfig.js";
import TriliumSlashCommands, {
buildDefaultSlashCommands,
+ buildTriliumSlashCommands,
+ isSlashCommandEnabled,
matchSlashCommands,
type SlashCommandConfig,
type SlashCommandDefinition
@@ -176,7 +187,13 @@ describe("TriliumSlashCommands", () => {
.toEqual([ "blockQuote", "codeBlock", "insertTable", "horizontalLine", "indent", "outdent" ]);
// ...and of those, only the one whose plugin is actually loaded survives the catalog.
- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toEqual([ "/blockQuote" ]);
+ const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);
+ expect(ids).toContain("/blockQuote");
+ expect(ids).not.toContain("/codeBlock");
+ expect(ids.filter((id) => id.startsWith("/heading"))).toEqual([]);
+
+ // Trilium's own execute-only entries have no command to gate them, so they stay.
+ expect(ids).toContain("/align-left");
});
it("uses a generic icon for a heading level outside h1-h6", async () => {
@@ -224,26 +241,26 @@ describe("TriliumSlashCommands", () => {
expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/blockQuote");
});
- it("honours an entry's own isEnabled predicate, which is the only gate an execute-only entry has", async () => {
+ it("honours an entry's own isEnabled predicate, which is the only gate an execute-only entry has", () => {
const isEnabled = vi.fn(() => false);
- await createEditor({
- extraCommands: [ { id: "custom", title: "Custom thing", icon: "<svg/>", execute: () => {}, isEnabled } ]
- });
+ const definition: SlashCommandDefinition = { id: "custom", title: "Custom thing", icon: "<svg/>", execute: () => {}, isEnabled };
- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).not.toContain("/custom");
+ expect(isSlashCommandEnabled(editor, definition)).toBe(false);
expect(isEnabled).toHaveBeenCalledWith(editor);
isEnabled.mockReturnValue(true);
- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/custom");
+ expect(isSlashCommandEnabled(editor, definition)).toBe(true);
});
- it("appends extraCommands after the defaults, without gating them on a command", async () => {
- await createEditor({
- extraCommands: [ { id: "custom", title: "Custom thing", icon: "<svg/>", execute: () => {} } ]
- });
+ it("orders the catalog as CKEditor's own entries, then Trilium's, then the snippets", async () => {
const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);
- expect(ids[ids.length - 1]).toBe("/custom");
+ // The heading entries lead the defaults; Trilium's own group follows them. Only
+ // execute-only entries are compared, since anything naming a command whose plugin this
+ // editor does not load is filtered out before ordering matters.
+ expect(ids[0]).toBe("/paragraph");
+ expect(ids.indexOf("/blockQuote")).toBeLessThan(ids.indexOf("/align-left"));
+ expect(ids.indexOf("/align-left")).toBeLessThan(ids.indexOf("/anchor"));
});
});
@@ -342,15 +359,23 @@ describe("TriliumSlashCommands", () => {
expect(data).not.toContain("/quo");
});
+ // The alignment entries are execute-only — they run `alignment` with an argument rather than
+ // naming a command — so committing one exercises the `execute` path end to end.
it("runs an entry's own execute callback, with the editor as its argument", async () => {
- const execute = vi.fn();
- await createEditor({ extraCommands: [ { id: "custom", title: "Custom thing", icon: "<svg/>", execute } ] });
+ // Alignment has to be loaded for its command to exist; the entry itself names no
+ // command, so it is the `execute` callback that reaches it.
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, Alignment, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]
+ );
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ const execute = vi.spyOn(editor, "execute");
- type("/custom");
+ // One word, since the `/` marker pattern stops at a space.
+ type("/Justify");
await settle();
pressKey(keyCodes.enter);
- expect(execute).toHaveBeenCalledExactlyOnceWith(editor);
+ expect(execute).toHaveBeenCalledWith("alignment", { value: "justify" });
});
it("passes the level to the heading command rather than executing an id", async () => {
@@ -461,3 +486,149 @@ describe("TriliumSlashCommands", () => {
expect(balloon.visibleView?.element?.classList.contains("ck-mentions") ?? false).toBe(false);
});
});
+
+/**
+ * The palette entries for Trilium's own features. These used to be built by the host and injected
+ * through `slashCommand.extraCommands`, and were tested against a bare translator function; they are
+ * built from the editor now, so the definitions come from a real one.
+ */
+describe("buildTriliumSlashCommands", () => {
+ let editor: ClassicEditor;
+
+ /** Records `execute()` calls and serves plugin lookups, standing in for the *target* editor. */
+ function makeFakeEditor() {
+ const pluginInstances = new Map<unknown, unknown>();
+ const executeSpy = vi.fn();
+ const fake = {
+ execute: executeSpy,
+ plugins: { get: (key: unknown) => pluginInstances.get(key) }
+ } as unknown as Editor;
+ return { fake, executeSpy, pluginInstances };
+ }
+
+ beforeEach(async () => {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],
+ { mermaid: { samples: [ { name: "Flowchart", content: "graph TD;" } ] } }
+ );
+ });
+
+ function definition(id: string) {
+ const found = buildTriliumSlashCommands(editor).find((entry) => entry.id === id);
+ if (!found) throw new Error(`no palette entry with id "${id}"`);
+ return found;
+ }
+
+ // One case per entry rather than a test each: the shape is identical, only the data differs.
+ it.each([
+ [ "collapsible", "Collapsible block", "collapsible" ],
+ [ "footnote", "Footnote", "InsertFootnote" ],
+ [ "datetime", "Insert date/time", INSERT_DATE_TIME_COMMAND ],
+ [ "internal-link", "Internal link", INTERNAL_LINK_COMMAND ],
+ [ "include-note", "Include note", INCLUDE_NOTE_COMMAND ],
+ [ "page-break", "Page break", "pageBreak" ],
+ [ "markdown-import", "Markdown import", MARKDOWN_IMPORT_COMMAND ],
+ [ "bulletedList", "Bulleted list", "bulletedList" ],
+ [ "numberedList", "Numbered list", "numberedList" ],
+ [ "todoList", "To-do list", "todoList" ],
+ [ "mermaid", "Mermaid diagram", INSERT_MERMAID_COMMAND ]
+ ])("defines %s, running its command with an icon and a description", (id, title, commandName) => {
+ const entry = definition(id);
+
+ expect(entry.title).toBe(title);
+ expect(entry.commandName).toBe(commandName);
+ expect(entry.description).toBeTruthy();
+ expect(entry.icon).toContain("<svg");
+ });
+
+ it.each([
+ [ "align-left", "left" ],
+ [ "align-center", "center" ],
+ [ "align-right", "right" ],
+ [ "align-justify", "justify" ]
+ ])("%s runs the alignment command with value %s", (id, value) => {
+ const { fake, executeSpy } = makeFakeEditor();
+
+ definition(id).execute?.(fake);
+
+ expect(executeSpy).toHaveBeenCalledWith("alignment", { value });
+ });
+
+ it("defines one entry per admonition type, each applying its own type", () => {
+ const { fake, executeSpy } = makeFakeEditor();
+
+ for (const type of [ "note", "tip", "important", "caution", "warning" ]) {
+ const entry = definition(type);
+ expect(entry.icon).toContain("<svg");
+ expect(entry.aliases).toContain("box");
+
+ entry.execute?.(fake);
+ expect(executeSpy).toHaveBeenCalledWith("admonition", { forceValue: type });
+ }
+ });
+
+ it("opens the math balloon rather than running a command", () => {
+ const { fake, pluginInstances } = makeFakeEditor();
+ const showUI = vi.fn();
+ pluginInstances.set(MathUI, { _showUI: showUI });
+
+ definition("math").execute?.(fake);
+
+ expect(showUI).toHaveBeenCalledOnce();
+ });
+
+ // The balloon needs the view and mapper settled, which they are not until the slash command has
+ // finished its own DOM and selection cleanup.
+ it("defers the anchor form to the next tick", async () => {
+ vi.useFakeTimers();
+ try {
+ const { fake, pluginInstances } = makeFakeEditor();
+ const showFormView = vi.fn();
+ pluginInstances.set(BookmarkUI, { _showFormView: showFormView });
+
+ definition("anchor").execute?.(fake);
+ expect(showFormView).not.toHaveBeenCalled();
+
+ vi.runAllTimers();
+ expect(showFormView).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ // The samples come from `mermaid.samples`, which the editor already carries for the Mermaid UI —
+ // it was passed to the builder separately back when the host built these definitions.
+ it("builds one entry per Mermaid sample, inserting that sample's source", () => {
+ const { fake, executeSpy } = makeFakeEditor();
+ const sample = definition("mermaid-sample-0");
+
+ expect(sample.title).toBe("Mermaid diagram: Flowchart");
+ expect(sample.description).toBe("Insert a \"Flowchart\" Mermaid diagram template");
+ expect(sample.aliases).toContain("Flowchart");
+
+ sample.execute?.(fake);
+ expect(executeSpy).toHaveBeenCalledWith(INSERT_MERMAID_COMMAND, { source: "graph TD;" });
+ });
+
+ it("carries no sample entries when the editor configures none", async () => {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]
+ );
+
+ const ids = buildTriliumSlashCommands(editor).map((entry) => entry.id);
+ expect(ids).toContain("mermaid");
+ expect(ids.filter((id) => id.startsWith("mermaid-sample-"))).toEqual([]);
+ });
+
+ // The reason these moved out of the host: the host translator only ever resolved Trilium's own
+ // catalog, so strings CKEditor already translates — "Align left", "Page break" — stayed English.
+ it("translates through the editor, so CKEditor's own strings resolve too", async () => {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],
+ { translations: [ {}, { en: { dictionary: { "Align left": "Aliniază la stânga", "Page break": "Întrerupere de pagină" } } } ] }
+ );
+
+ expect(definition("align-left").title).toBe("Aliniază la stânga");
+ expect(definition("page-break").title).toBe("Întrerupere de pagină");
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
index c0a343341e..dbfc14a2db 100644
--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -1,6 +1,11 @@
import "../../theme/slash_commands.css";
import {
+ IconAlignCenter,
+ IconAlignJustify,
+ IconAlignLeft,
+ IconAlignRight,
+ IconBulletedList,
IconCodeBlock,
IconHeading1,
IconHeading2,
@@ -10,13 +15,39 @@ import {
IconHeading6,
IconHorizontalLine,
IconIndent,
+ IconNumberedList,
IconOutdent,
+ IconPageBreak,
IconParagraph,
IconQuote,
- IconTable
+ IconTable,
+ IconTodoList
} from "@ckeditor/ckeditor5-icons";
-import { type Editor, type MentionFeedObjectItem, Plugin } from "ckeditor5";
-
+import bxBookmark from "boxicons/svg/regular/bx-bookmark.svg?raw";
+import bxBulb from "boxicons/svg/regular/bx-bulb.svg?raw";
+import bxCommentError from "boxicons/svg/regular/bx-comment-error.svg?raw";
+import bxError from "boxicons/svg/regular/bx-error.svg?raw";
+import bxErrorCircle from "boxicons/svg/regular/bx-error-circle.svg?raw";
+import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
+import bxNetworkChart from "boxicons/svg/regular/bx-network-chart.svg?raw";
+import { BookmarkUI, type Editor, type MentionFeedObjectItem, Plugin } from "ckeditor5";
+
+import collapsibleIcon from "../../icons/collapsible.svg?raw";
+import dateTimeIcon from "../../icons/date-time.svg?raw";
+import insertFootnoteIcon from "../../icons/insert-footnote.svg?raw";
+import importMarkdownIcon from "../../icons/markdown-mark.svg?raw";
+import mathIcon from "../../icons/math.svg?raw";
+import noteIcon from "../../icons/note.svg?raw";
+import internalLinkIcon from "../../icons/trilium.svg?raw";
+import { ADMONITION_TYPE_NAMES, type AdmonitionType } from "../admonition/admonition_command.js";
+import { getAdmonitionTitle } from "../admonition/admonition_ui.js";
+import { COMMAND_NAME as INCLUDE_NOTE_COMMAND } from "../includenote.js";
+import { COMMAND_NAME as INSERT_DATE_TIME_COMMAND } from "../insert_date_time.js";
+import { COMMAND_NAME as INTERNAL_LINK_COMMAND } from "../internallink.js";
+import { COMMAND_NAME as MARKDOWN_IMPORT_COMMAND } from "../markdownimport.js";
+import MathUI from "../math/math_ui.js";
+import { INSERT_MERMAID_COMMAND } from "../mermaid/insert_mermaid_command.js";
+import type { MermaidSample } from "../mermaid/mermaid_ui.js";
import SnippetsEditing from "../snippets/snippetsediting.js";
import { registerMentionFeed } from "./register_feed.js";
@@ -55,7 +86,6 @@ export interface SlashCommandDefinition {
}
export interface SlashCommandConfig {
- extraCommands?: SlashCommandDefinition[];
removeCommands?: string[];
/** How many entries the palette shows at once. Unlimited by default, as premium's was. */
dropdownLimit?: number;
@@ -72,8 +102,7 @@ export interface SlashCommandConfig {
*
* CKEditor built the premium plugin on `Mention` themselves, so hosting `/` on a mention feed is
* not a workaround but the same architecture. What is reimplemented here is the palette: the
- * catalog, the matcher and the row rendering. The definitions Trilium already hand-authored in
- * `extra_slash_commands.ts` are consumed unchanged via `slashCommand.extraCommands`.
+ * catalog, the matcher and the row rendering.
*/
export default class TriliumSlashCommands extends Plugin {
@@ -101,16 +130,16 @@ export default class TriliumSlashCommands extends Plugin {
}
/**
- * The definitions available in *this* editor right now: the built-in palette plus the configured
- * extras, minus anything `removeCommands` names and anything that does not apply to the current
- * selection.
+ * The definitions available in *this* editor right now: the palette CKEditor's own features
+ * contribute, Trilium's own entries, and one per text snippet — minus anything `removeCommands`
+ * names and anything that does not apply to the current selection.
*/
private _catalog(): SlashCommandDefinition[] {
const editor = this.editor;
const config = (editor.config.get("slashCommand") ?? {}) as SlashCommandConfig;
const removed = new Set(config.removeCommands ?? []);
- return [ ...buildDefaultSlashCommands(editor), ...(config.extraCommands ?? []), ...buildSnippetSlashCommands(editor) ]
+ return [ ...buildDefaultSlashCommands(editor), ...buildTriliumSlashCommands(editor), ...buildSnippetSlashCommands(editor) ]
.filter((definition) => !removed.has(definition.id))
.filter((definition) => isSlashCommandEnabled(editor, definition));
}
@@ -134,7 +163,7 @@ declare module "ckeditor5" {
* predicate on every keystroke in `getMatchingCommands()`, so entries appear and disappear as the
* selection moves.
*/
-function isSlashCommandEnabled(editor: Editor, definition: SlashCommandDefinition): boolean {
+export function isSlashCommandEnabled(editor: Editor, definition: SlashCommandDefinition): boolean {
if (definition.isEnabled) {
return definition.isEnabled(editor);
}
@@ -269,6 +298,215 @@ export function buildDefaultSlashCommands(editor: Editor): SlashCommandDefinitio
];
}
+/**
+ * The palette entries for Trilium's own features, plus the handful that replace a CKEditor built-in
+ * whose title or icon Trilium re-authors (the lists, the blank Mermaid diagram).
+ *
+ * These used to be built by the host and injected through `slashCommand.extraCommands`, because
+ * premium `SlashCommand` owned the palette and config was the only way in. Trilium owns it now, so
+ * they are built here like every other group — which is also what lets them use `editor.t()`: the
+ * host translator resolved only Trilium's catalog, leaving strings such as "Align left" and "Page
+ * break" in English even though CKEditor ships translations for them.
+ */
+export function buildTriliumSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ ...buildListSlashCommands(editor),
+ ...buildAlignmentSlashCommands(editor),
+ ...buildAdmonitionSlashCommands(editor),
+ ...buildMermaidSlashCommands(editor),
+ {
+ id: "collapsible",
+ title: t("Collapsible block"),
+ description: t("Insert a toggleable section that hides/shows content on click."),
+ aliases: [ "details", "fold", "toggle" ],
+ icon: collapsibleIcon,
+ commandName: "collapsible"
+ },
+ {
+ id: "footnote",
+ title: t("Footnote"),
+ description: t("Create a new footnote and reference it here"),
+ icon: insertFootnoteIcon,
+ commandName: "InsertFootnote"
+ },
+ {
+ id: "datetime",
+ title: t("Insert date/time"),
+ description: t("Insert the current date and time"),
+ icon: dateTimeIcon,
+ commandName: INSERT_DATE_TIME_COMMAND
+ },
+ {
+ id: "internal-link",
+ title: t("Internal link"),
+ description: t("Insert a link to another Trilium note"),
+ aliases: [ "internal link", "trilium link", "reference link" ],
+ icon: internalLinkIcon,
+ commandName: INTERNAL_LINK_COMMAND
+ },
+ {
+ id: "math",
+ title: t("Math equation"),
+ description: t("Insert a math equation"),
+ aliases: [ "latex", "equation" ],
+ icon: mathIcon,
+ execute: (target: Editor) => target.plugins.get(MathUI)._showUI()
+ },
+ {
+ id: "include-note",
+ title: t("Include note"),
+ description: t("Display the content of another note in this note"),
+ icon: noteIcon,
+ commandName: INCLUDE_NOTE_COMMAND
+ },
+ {
+ id: "page-break",
+ title: t("Page break"),
+ description: t("Insert a page break (for printing)"),
+ icon: IconPageBreak,
+ commandName: "pageBreak"
+ },
+ {
+ id: "markdown-import",
+ title: t("Markdown import"),
+ description: t("Import Markdown from the clipboard"),
+ icon: importMarkdownIcon,
+ commandName: MARKDOWN_IMPORT_COMMAND
+ },
+ {
+ id: "anchor",
+ title: t("Anchor"),
+ description: t("Insert an anchor for internal linking"),
+ aliases: [ "bookmark" ],
+ icon: bxBookmark,
+ execute: (target: Editor) => {
+ // Defer to the next event loop tick so the slash command fully finishes its
+ // DOM/selection cleanup; _showFormView needs the view and mapper to be in a settled
+ // state for balloon positioning.
+ setTimeout(() => (target.plugins.get(BookmarkUI) as unknown as { _showFormView(): void })._showFormView(), 0);
+ }
+ }
+ ];
+}
+
+// Replaces CKEditor's built-in `bulletedList`/`numberedList`/`todoList` slash commands (removed via
+// `removeCommands`), whose titles are Title Case, with sentence-case equivalents that run the same
+// commands.
+function buildListSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ {
+ id: "bulletedList",
+ title: t("Bulleted list"),
+ description: t("Create a bulleted list"),
+ icon: IconBulletedList,
+ commandName: "bulletedList"
+ },
+ {
+ id: "numberedList",
+ title: t("Numbered list"),
+ description: t("Create a numbered list"),
+ icon: IconNumberedList,
+ commandName: "numberedList"
+ },
+ {
+ id: "todoList",
+ title: t("To-do list"),
+ description: t("Create a to-do list"),
+ icon: IconTodoList,
+ commandName: "todoList"
+ }
+ ];
+}
+
+function buildMermaidSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+ const samples = (editor.config.get("mermaid.samples") ?? []) as MermaidSample[];
+
+ // The blank diagram. Replaces CKEditor's built-in `insertMermaidCommand` slash command (removed
+ // via `removeCommands`), which uses a generic icon.
+ const blank: SlashCommandDefinition = {
+ id: "mermaid",
+ title: t("Mermaid diagram"),
+ description: t("Insert an empty Mermaid diagram"),
+ aliases: [ "mermaid", "diagram", "flowchart" ],
+ icon: bxNetworkChart,
+ commandName: INSERT_MERMAID_COMMAND
+ };
+
+ const templates = samples.map((sample, index) => ({
+ id: `mermaid-sample-${index}`,
+ // The sample name is a placeholder rather than an appended string, so a locale can put the
+ // name where its grammar wants it. It arrives already localized, from `mermaid.samples`.
+ title: t("Mermaid diagram: %0", sample.name),
+ description: t("Insert a \"%0\" Mermaid diagram template", sample.name),
+ aliases: [ "mermaid", "diagram", sample.name ],
+ icon: bxNetworkChart,
+ // Inserts a mermaid block pre-filled with the sample source (see insertMermaidCommand).
+ execute: (target: Editor) => target.execute(INSERT_MERMAID_COMMAND, { source: sample.content })
+ }));
+
+ return [ blank, ...templates ];
+}
+
+function buildAlignmentSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ {
+ id: "align-left",
+ title: t("Align left"),
+ description: t("Align text to the left"),
+ icon: IconAlignLeft,
+ execute: (target: Editor) => target.execute("alignment", { value: "left" })
+ },
+ {
+ id: "align-center",
+ title: t("Align center"),
+ description: t("Align text to the center"),
+ icon: IconAlignCenter,
+ execute: (target: Editor) => target.execute("alignment", { value: "center" })
+ },
+ {
+ id: "align-right",
+ title: t("Align right"),
+ description: t("Align text to the right"),
+ icon: IconAlignRight,
+ execute: (target: Editor) => target.execute("alignment", { value: "right" })
+ },
+ {
+ id: "align-justify",
+ title: t("Justify"),
+ description: t("Justify text alignment"),
+ icon: IconAlignJustify,
+ execute: (target: Editor) => target.execute("alignment", { value: "justify" })
+ }
+ ];
+}
+
+function buildAdmonitionSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+ const icons: Record<AdmonitionType, string> = {
+ note: bxInfoCircle,
+ tip: bxBulb,
+ important: bxCommentError,
+ caution: bxErrorCircle,
+ warning: bxError
+ };
+
+ return ADMONITION_TYPE_NAMES.map((type) => ({
+ id: type,
+ title: getAdmonitionTitle(t, type),
+ description: t("Insert a new admonition"),
+ icon: icons[type],
+ execute: (target: Editor) => target.execute("admonition", { forceValue: type }),
+ aliases: [ "box" ]
+ }));
+}
+
/**
* One palette entry per text snippet, restoring premium behaviour: premium `SlashCommand` listed the
* premium `Template` plugin's definitions alongside the built-ins. Since `_catalog()` runs on every
@@ -356,7 +594,7 @@ function renderRow(item: SlashCommandItem): HTMLElement {
if (definition.iconClass) {
// A snippet note's font icon: the same chip, painted by icon-font classes instead of SVG.
// The glyph lives on an inner span: core sizes the chip box in em against the chip's own
- // font-size, so enlarging the glyph's font on the chip itself would inflate the chip too.
+ // font-size, so enlarging the glyph's font on the chip itself would inflate the chip too.
icon.classList.add("ck-slash-command-button__note-icon");
const glyph = document.createElement("span");
for (const classList of [ definition.iconClass, definition.iconColorClass ]) {