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
fix(ckeditor): list text snippets in the slash command palette (closes #10762)
Elian Doran3981344cb60b
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex e3bd18b925..567787eb03 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -13,6 +13,8 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";+import TriliumSnippets from "../snippets/snippets.js";+import type { SnippetDefinition } from "../snippets/snippetsconfig.js";import TriliumSlashCommands, {buildDefaultSlashCommands,matchSlashCommands,@@ -228,6 +230,89 @@ describe("TriliumSlashCommands", () => {});});+ describe("snippets", () => {+ const SNIPPETS: SnippetDefinition[] = [+ {+ title: "Greeting",+ data: "<p>Hello there</p>",+ description: "A friendly hello",+ iconClass: "tn-icon bx bx-note",+ iconColorClass: "use-note-color"+ },+ { title: "Signature", data: () => "<p>Sincerely, spec</p>" }+ ];++ async function createSnippetEditor(definitions: SnippetDefinition[] = SNIPPETS) {+ editor = await createTestEditor(+ [ Essentials, Paragraph, Heading, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands, TriliumSnippets ],+ { heading: { options: HEADING_OPTIONS }, toolbar: [], slashCommand: {}, snippets: { definitions } }+ );+ setModelData(editor.model, "<paragraph>[]</paragraph>");+ }++ it("lists each snippet after the built-ins, found by its title or the generic aliases", async () => {+ await createSnippetEditor();++ const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);+ expect(ids.slice(-2)).toEqual([ "/snippet-0", "/snippet-1" ]);++ expect((await queryPalette("greet")).map((item) => (item as { text: string }).text)).toEqual([ "Greeting" ]);++ const byAlias = (await queryPalette("snippet")).map((item) => (item as { text: string }).text);+ expect(byAlias).toContain("Greeting");+ expect(byAlias).toContain("Signature");+ });++ it("offers no snippet entries in an editor without the snippets plugin", async () => {+ const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);+ expect(ids.some((id) => id.startsWith("/snippet-"))).toBe(false);+ });++ it("inserts the snippet content on commit, for string and callback data alike", async () => {+ await createSnippetEditor();++ type("/greeting");+ await settle();+ pressKey(keyCodes.enter);++ let data = getModelData(editor.model, { withoutSelection: true });+ expect(data).toContain("Hello there");+ expect(data).not.toContain("/greeting");++ // A fresh empty paragraph: right after the inserted content the slash would be+ // mid-word, and a mid-word `/` deliberately never opens the palette.+ setModelData(editor.model, "<paragraph>[]</paragraph>");+ type("/signature");+ await settle();+ pressKey(keyCodes.enter);++ data = getModelData(editor.model, { withoutSelection: true });+ expect(data).toContain("Sincerely, spec");+ });++ it("reflects updateDefinitions() on the next query, since the catalog is rebuilt per keystroke", async () => {+ await createSnippetEditor();++ editor.plugins.get(TriliumSnippets).updateDefinitions([ { title: "Renamed", data: "<p>x</p>" } ]);++ const titles = (await queryPalette("")).map((item) => (item as { text: string }).text);+ expect(titles).toContain("Renamed");+ expect(titles).not.toContain("Greeting");+ });++ it("hides snippets while the insertTemplate command is disabled, like any command-gated entry", async () => {+ await createSnippetEditor();+ const insertTemplate = editor.commands.get("insertTemplate");++ if (!insertTemplate) {+ throw new Error("the snippets plugin should register the insertTemplate command");+ }++ insertTemplate.forceDisabled("spec");+ expect((await queryPalette("")).map((item) => (item as { text: string }).text)).not.toContain("Greeting");+ });+ });+describe("execution", () => {it("runs a commandName entry and removes the trigger text", async () => {type("/quo");@@ -302,6 +387,8 @@ describe("TriliumSlashCommands", () => {// Without this the base button styles hide the label, leaving a title-less row.expect(row.classList.contains("ck-button_with-text")).toBe(true);expect(row.querySelector(".ck-icon")?.innerHTML).toContain("<svg");+ // Opts into core's `fill: currentColor` rule; without it the glyphs stay black on dark themes.+ expect(row.querySelector(".ck-icon")?.classList.contains("ck-icon_inherit-color")).toBe(true);expect(row.querySelector(".ck-button__label")?.textContent).toBe("Block quote");expect(row.querySelector(".ck-slash-command-button__description")?.textContent).toBeTruthy();});@@ -318,6 +405,35 @@ describe("TriliumSlashCommands", () => {expect(row.querySelector(".ck-slash-command-button__description")).toBeNull();});++ it("renders a font-icon chip from iconClass, with and without a colour class", () => {+ const renderer = slashFeed().itemRenderer;++ if (!renderer) {+ throw new Error("the `/` feed should provide an itemRenderer");+ }++ const coloured: SlashCommandDefinition = {+ id: "snippet-0", title: "Greeting", iconClass: "tn-icon bx bx-note", iconColorClass: "use-note-color"+ };+ const colourless: SlashCommandDefinition = { id: "snippet-1", title: "Plain", iconClass: "bx bx-cube" };++ for (const definition of [ coloured, colourless ]) {+ const row = renderer({ id: `/${definition.id}`, text: definition.title, definition } as never) as HTMLElement;+ const chip = row.querySelector(".ck-icon");++ expect(chip?.classList.contains("ck-slash-command-button__note-icon")).toBe(true);+ expect(chip?.querySelector("svg")).toBeNull();+ }++ const colouredRow = renderer({ id: "/snippet-0", text: "Greeting", definition: coloured } as never) as HTMLElement;+ // The glyph classes go on an inner span, not the chip: the chip's box is sized in em of+ // its own font-size, so carrying the enlarged glyph font itself would inflate the row.+ const glyph = colouredRow.querySelector(".ck-icon > span");+ for (const cls of [ "tn-icon", "bx", "bx-note", "use-note-color" ]) {+ expect(glyph?.classList.contains(cls)).toBe(true);+ }+ });});it("does not open the palette on a mid-word slash", async () => {diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex 892ac26a6d..678fe6101f 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -17,6 +17,7 @@ import {} from "@ckeditor/ckeditor5-icons";import { type Editor, type MentionFeedObjectItem, Plugin } from "ckeditor5";+import SnippetsEditing from "../snippets/snippetsediting.js";import { registerMentionFeed } from "./register_feed.js";export const SLASH_MARKER = "/";@@ -32,8 +33,15 @@ export interface SlashCommandDefinition {description?: string;/** Extra words the entry can be found by, beyond its title. */aliases?: string[];- /** Raw SVG markup. */- icon: string;+ /** Raw SVG markup. Ignored when {@link iconClass} is set. */+ icon?: string;+ /**+ * A font-icon class list (e.g. `"tn-icon bx bx-note"`) rendered as a `<span>` instead of+ * {@link icon}'s SVG markup — the form snippet notes carry their icons in.+ */+ iconClass?: string;+ /** Optional colour class applied alongside {@link iconClass} (from the note's `#color` label). */+ iconColorClass?: string;/** The editor command to run. Entries naming a command that is not loaded are hidden. */commandName?: string;/** Runs instead of `commandName`, for entries that need arguments or open a UI. */@@ -102,7 +110,7 @@ export default class TriliumSlashCommands extends Plugin {const config = (editor.config.get("slashCommand") ?? {}) as SlashCommandConfig;const removed = new Set(config.removeCommands ?? []);- return [ ...buildDefaultSlashCommands(editor), ...(config.extraCommands ?? []) ]+ return [ ...buildDefaultSlashCommands(editor), ...(config.extraCommands ?? []), ...buildSnippetSlashCommands(editor) ].filter((definition) => !removed.has(definition.id)).filter((definition) => isSlashCommandEnabled(editor, definition));}@@ -261,6 +269,32 @@ export function buildDefaultSlashCommands(editor: Editor): SlashCommandDefinitio];}+/**+ * 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+ * query, the definitions are read live from {@link SnippetsEditing} — snippet changes pushed via+ * `TriliumSnippets.updateDefinitions()` appear in the palette without any re-registration.+ */+function buildSnippetSlashCommands(editor: Editor): SlashCommandDefinition[] {+ if (!editor.plugins.has(SnippetsEditing)) {+ return [];+ }++ return Array.from(editor.plugins.get(SnippetsEditing).definitions, (snippet, index) => ({+ id: `snippet-${index}`,+ title: snippet.title,+ description: snippet.description,+ // Beyond its own title, every snippet is findable under the feature's generic names.+ aliases: [ "snippet", "template" ],+ iconClass: snippet.iconClass,+ iconColorClass: snippet.iconColorClass,+ // Gates the entry on `insertTemplate` (read-only mode disables it); `execute` still wins at+ // commit time, since the command needs the snippet's content as its argument.+ commandName: "insertTemplate",+ execute: (target: Editor) => target.execute("insertTemplate", snippet.data)+ }));+}+function buildHeadingSlashCommands(editor: Editor): SlashCommandDefinition[] {const options = (editor.config.get("heading.options") ?? []) as Array<{ model: string; title: string }>;const icons: Record<string, string> = {@@ -313,7 +347,26 @@ function renderRow(item: SlashCommandItem): HTMLElement {const icon = document.createElement("span");icon.classList.add("ck", "ck-icon");- icon.innerHTML = definition.icon;++ 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.+ icon.classList.add("ck-slash-command-button__note-icon");+ const glyph = document.createElement("span");+ for (const classList of [ definition.iconClass, definition.iconColorClass ]) {+ if (classList) {+ glyph.classList.add(...classList.split(/\s+/).filter(Boolean));+ }+ }+ icon.append(glyph);+ } else if (definition.icon) {+ // `ck-icon_inherit-color` opts into core's `*:not([fill]) { fill: currentColor }` rule, as+ // `IconView` does — without it the glyphs keep SVG's default black fill on dark themes.+ icon.classList.add("ck-icon_inherit-color");+ icon.innerHTML = definition.icon;+ }+button.append(icon);const textPart = document.createElement("span");diff --git a/packages/ckeditor5/src/theme/slash_commands.css b/packages/ckeditor5/src/theme/slash_commands.cssindex 39f81cdde8..713bf551ef 100644--- a/packages/ckeditor5/src/theme/slash_commands.css+++ b/packages/ckeditor5/src/theme/slash_commands.css@@ -44,6 +44,25 @@width: 100%;height: 100%;}++ /* A snippet note's font icon: the same chip, with a glyph instead of an svg. */+ &.ck-slash-command-button__note-icon {+ display: flex;+ align-items: center;+ justify-content: center;++ /*+ * The glyph is sized on the inner span, never on the chip: core's `.ck.ck-icon`+ * width/height use the em-relative `--ck-icon-size`, so a bigger font on the chip+ * itself would inflate the chip box (and the whole row) along with the glyph. On the+ * child, the calc resolves against the chip's untouched font-size, which is also what+ * `width: var(--ck-icon-size)` resolved against — so 0.85 means 85% of the content box.+ */+ & > span {+ font-size: calc(var(--ck-icon-size) * 0.85);+ line-height: 1;+ }+ }}& > .ck-slash-command-button__text-part {