Skip to content

Build your personal knowledge base with Trilium Notes

refactor(ckeditor): own the mention autocomplete, and host `/` and `:` on it

Elian Doran52d17ef27a71
diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx
index 601ec14934..f1030e7ae0 100644
--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx
+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx
@@ -1,6 +1,6 @@
import "./AttributeEditor.css";
-import type { AttributeEditor as CKEditorAttributeEditor, MentionFeed, ModelElement, ModelNode, ModelPosition } from "@triliumnext/ckeditor5";
+import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, TriliumMentionFeed } from "@triliumnext/ckeditor5";
import { AttributeType } from "@triliumnext/commons";
import { createPortal } from "preact/compat";
import { MutableRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from "preact/hooks";
@@ -29,7 +29,9 @@ import AttributeHelp, { ATTRIBUTE_HELP_PAGE } from "./AttributeHelp";
type AttributeCommandNames = FilteredCommandNames<CommandData>;
-const mentionSetup: MentionFeed[] = [
+// `preselectFirstItem: false` throughout: in this editor Enter means "save the attributes", so an
+// open panel must not silently swallow it into committing whichever suggestion happens to be first.
+const mentionSetup: TriliumMentionFeed[] = [
{
marker: "@",
feed: (queryText) => note_autocomplete.autocompleteSourceForCKEditor(queryText),
@@ -41,7 +43,10 @@ const mentionSetup: MentionFeed[] = [
return itemElement;
},
- minimumCharacters: 0
+ minimumCharacters: 0,
+ // Relation targets are note titles, which contain spaces.
+ allowSpaces: true,
+ preselectFirstItem: false
},
{
marker: "#",
@@ -55,7 +60,8 @@ const mentionSetup: MentionFeed[] = [
};
});
},
- minimumCharacters: 0
+ minimumCharacters: 0,
+ preselectFirstItem: false
},
{
marker: "~",
@@ -69,7 +75,8 @@ const mentionSetup: MentionFeed[] = [
};
});
},
- minimumCharacters: 0
+ minimumCharacters: 0,
+ preselectFirstItem: false
}
];
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index 810874aefd..5a18b0b199 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -286,13 +286,13 @@ describe("CK config - mention feed", () => {
describe("CK config - disabled plugins", () => {
it("removes the emoji and slash-command plugins based on their option toggles", async () => {
const disabled = await buildConfig(baseOpts());
- expect(disabled.removePlugins).toContain("EmojiMention");
- expect(disabled.removePlugins).toContain("SlashCommand");
+ expect(disabled.removePlugins).toContain("TriliumEmojiMention");
+ expect(disabled.removePlugins).toContain("TriliumSlashCommands");
optionsState.map["textNoteEmojiCompletionEnabled"] = "true";
optionsState.map["textNoteSlashCommandsEnabled"] = "true";
const enabled = await buildConfig(baseOpts());
- expect(enabled.removePlugins).not.toContain("EmojiMention");
- expect(enabled.removePlugins).not.toContain("SlashCommand");
+ expect(enabled.removePlugins).not.toContain("TriliumEmojiMention");
+ expect(enabled.removePlugins).not.toContain("TriliumSlashCommands");
});
});
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 0675c6bd2b..d32dab89f3 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -251,7 +251,9 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
return itemElement;
},
- minimumCharacters: 0
+ minimumCharacters: 0,
+ // Note titles contain spaces, so the query must be allowed to as well.
+ allowSpaces: true
}
],
};
@@ -304,11 +306,11 @@ function getDisabledPlugins() {
const disabledPlugins: string[] = [];
if (options.get("textNoteEmojiCompletionEnabled") !== "true") {
- disabledPlugins.push("EmojiMention");
+ disabledPlugins.push("TriliumEmojiMention");
}
if (options.get("textNoteSlashCommandsEnabled") !== "true") {
- disabledPlugins.push("SlashCommand");
+ disabledPlugins.push("TriliumSlashCommands");
}
return disabledPlugins;
diff --git a/packages/ckeditor5/src/extra_slash_commands.ts b/packages/ckeditor5/src/extra_slash_commands.ts
index c51f652f76..e90280ea57 100644
--- a/packages/ckeditor5/src/extra_slash_commands.ts
+++ b/packages/ckeditor5/src/extra_slash_commands.ts
@@ -1,5 +1,4 @@
import type { Editor } from 'ckeditor5';
-import type { SlashCommandEditorConfig } from 'ckeditor5-premium-features';
import { icons as footnoteIcons } from '@triliumnext/ckeditor5-footnotes';
import { IconPageBreak, IconAlignLeft, IconAlignCenter, IconAlignRight, IconAlignJustify, IconBulletedList, IconNumberedList, IconTodoList } from "@ckeditor/ckeditor5-icons";
import bxInfoCircle from "boxicons/svg/regular/bx-info-circle.svg?raw";
@@ -22,8 +21,7 @@ import { INSERT_MERMAID_COMMAND, type MermaidSample } from '@triliumnext/ckedito
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";
-
-type SlashCommandDefinition = SlashCommandEditorConfig["extraCommands"][number];
+import type { SlashCommandDefinition } from './plugins/mention/slash_commands.js';
/**
* Translation function supplied by the client (which owns i18n). Resolves the
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 3fb4e69c2f..3d6a1bc301 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -9,6 +9,8 @@ import "./translation_overrides.js";
export { default as EditorWatchdog } from "./custom_watchdog";
export { CHAT_INPUT_PLUGINS, loadPremiumPlugins } from "./plugins.js";
export type { EditorConfig, MentionFeed, MentionFeedObjectItem, ModelNode, ModelPosition, ModelElement, ModelText, WatchdogConfig, WatchdogState } from "ckeditor5";
+export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";
+export type { TriliumMentionFeed } from "./plugins/mention/types.js";
export type { TemplateDefinition } from "ckeditor5-premium-features";
export { default as buildExtraCommands } from "./extra_slash_commands.js";
export { default as getCkLocale } from "./i18n.js";
diff --git a/packages/ckeditor5/src/plugins.spec.ts b/packages/ckeditor5/src/plugins.spec.ts
index 76d58863cc..0b95befa76 100644
--- a/packages/ckeditor5/src/plugins.spec.ts
+++ b/packages/ckeditor5/src/plugins.spec.ts
@@ -95,11 +95,14 @@ describe("loadPremiumPlugins", () => {
}
});
- it("includes SlashCommand, Template, and FormatPainter", async () => {
+ it("includes Template and FormatPainter, but not SlashCommand", async () => {
const { SlashCommand, Template, FormatPainter } = await import("ckeditor5-premium-features");
const plugins = await loadPremiumPlugins();
- expect(plugins).toContain(SlashCommand);
expect(plugins).toContain(Template);
expect(plugins).toContain(FormatPainter);
+
+ // `SlashCommand` requires the `Mention` façade, which would load upstream's `MentionUI`
+ // alongside `TriliumMentionUI`; `TriliumSlashCommands` provides `/` instead.
+ expect(plugins).not.toContain(SlashCommand);
});
});
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index 3eb2b0bd50..135a073d95 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -1,4 +1,4 @@
-import { Autoformat, AutoLink, BlockQuote, BlockToolbar, Bold, CKFinderUploadAdapter, Clipboard, Code, CodeBlock, Enter, Font, FontBackgroundColor, FontColor, GeneralHtmlSupport, Heading, HeadingButtonsUI, HorizontalLine, Image, ImageCaption, ImageInline, ImageResize, ImageStyle, ImageToolbar, ImageUpload, Alignment, Indent, IndentBlock, Italic, Link, List, ListProperties, Mention, PageBreak, Paragraph, ParagraphButtonUI, PasteFromOffice, PictureEditing, RemoveFormat, SelectAll, ShiftEnter, SpecialCharacters, SpecialCharactersEssentials, Strikethrough, Style, Subscript, Superscript, Table, TableCaption, TableCellProperties, TableColumnResize, TableProperties, TableSelection, TableToolbar, TextPartLanguage, TextTransformation, TodoList, Typing, Underline, Undo, Bookmark, EmojiMention, EmojiPicker, FindAndReplaceEditing } from "ckeditor5";
+import { Autoformat, AutoLink, BlockQuote, BlockToolbar, Bold, CKFinderUploadAdapter, Clipboard, Code, CodeBlock, Enter, Font, FontBackgroundColor, FontColor, GeneralHtmlSupport, Heading, HeadingButtonsUI, HorizontalLine, Image, ImageCaption, ImageInline, ImageResize, ImageStyle, ImageToolbar, ImageUpload, Alignment, Indent, IndentBlock, Italic, Link, List, ListProperties, MentionEditing, PageBreak, Paragraph, ParagraphButtonUI, PasteFromOffice, PictureEditing, RemoveFormat, SelectAll, ShiftEnter, SpecialCharacters, SpecialCharactersEssentials, Strikethrough, Style, Subscript, Superscript, Table, TableCaption, TableCellProperties, TableColumnResize, TableProperties, TableSelection, TableToolbar, TextPartLanguage, TextTransformation, TodoList, Typing, Underline, Undo, Bookmark, EmojiPicker, FindAndReplaceEditing } from "ckeditor5";
// Premium features loaded dynamically to improve initial load time
// import { SlashCommand, Template, FormatPainter } from "ckeditor5-premium-features";
import type { Plugin } from "ckeditor5";
@@ -13,6 +13,9 @@ import RemoveFormatLinksPlugin from "./plugins/remove_format_links.js";
import IndentBlockShortcutPlugin from "./plugins/indent_block_shortcut.js";
import MarkdownImportPlugin from "./plugins/markdownimport.js";
import MentionCustomization from "./plugins/mention_customization.js";
+import TriliumEmojiMention from "./plugins/mention/emoji_mention.js";
+import TriliumMentionUI from "./plugins/mention/trilium_mention_ui.js";
+import TriliumSlashCommands from "./plugins/mention/slash_commands.js";
import IncludeNote from "./plugins/includenote.js";
import LinkEmbed from "./plugins/link_embed/link_embed.js";
import Uploadfileplugin from "./plugins/file_upload/uploadfileplugin.js";
@@ -107,9 +110,13 @@ export const CORE_PLUGINS: typeof Plugin[] = [
Clipboard, Enter, SelectAll,
ShiftEnter, Typing, Undo,
Paragraph,
- Mention,
+
+ // `MentionEditing` + `TriliumMentionUI` rather than the `Mention` façade: the façade also pulls
+ // in upstream's `MentionUI`, which `TriliumMentionUI` replaces. See its doc comment for why.
+ MentionEditing,
// Trilium plugins
+ TriliumMentionUI,
MentionCustomization,
ReferenceLink
];
@@ -134,10 +141,13 @@ export const CHAT_INPUT_PLUGINS: typeof Plugin[] = [
* This avoids loading ~6 seconds of premium features code during initial app startup.
*/
export async function loadPremiumPlugins(): Promise<(typeof Plugin)[]> {
- const { SlashCommand, Template, FormatPainter } = await import('ckeditor5-premium-features');
+ // `SlashCommand` is deliberately not among them: it `requires` the `Mention` façade, which loads
+ // upstream's `MentionUI` next to `TriliumMentionUI` and leaves the two fighting over the same
+ // balloon. `TriliumSlashCommands` provides `/` instead, for premium and GPL builds alike.
+ const { Template, FormatPainter } = await import('ckeditor5-premium-features');
// Also load the CSS when premium features are used
await import('ckeditor5-premium-features/ckeditor5-premium-features.css');
- return [SlashCommand, Template, FormatPainter];
+ return [Template, FormatPainter];
}
/**
@@ -200,8 +210,12 @@ export const COMMON_PLUGINS: typeof Plugin[] = [
TextPartLanguage,
Style,
Bookmark,
- EmojiMention,
+ // Upstream's `EmojiMention` is replaced by `TriliumEmojiMention` for the same reason as
+ // `SlashCommand` — it `requires` the `Mention` façade. `EmojiPicker` and `EmojiRepository` do
+ // not, so the picker and the emoji data stay upstream's.
EmojiPicker,
+ TriliumEmojiMention,
+ TriliumSlashCommands,
...TRILIUM_PLUGINS,
...EXTERNAL_PLUGINS
diff --git a/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.ts b/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.ts
new file mode 100644
index 0000000000..e10855bae0
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.ts
@@ -0,0 +1,211 @@
+import {
+ type ClassicEditor,
+ EmojiPicker,
+ EmojiRepository,
+ Essentials,
+ _getModelData as getModelData,
+ keyCodes,
+ MentionEditing,
+ type MentionFeedObjectItem,
+ Paragraph,
+ _setModelData as setModelData
+} from "ckeditor5";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import TriliumEmojiMention from "./emoji_mention.js";
+import TriliumMentionUI from "./trilium_mention_ui.js";
+import type { TriliumMentionFeed } from "./types.js";
+
+/** Longer than the mention UI's 100 ms feed debounce. */
+const AFTER_DEBOUNCE = 160;
+
+/**
+ * A stand-in for the CDN emoji database, in the shape `EmojiRepository` parses. Kept to a handful of
+ * entries so the spec exercises our glue rather than the 400 kB production definitions.
+ */
+const DEFINITIONS = [
+ { annotation: "grinning face", emoji: "😀", group: 0, order: 1, version: 1, shortcodes: [ "grinning" ] },
+ { annotation: "grinning face with big eyes", emoji: "😃", group: 0, order: 2, version: 1, shortcodes: [ "smiley" ] },
+ { annotation: "waving hand", emoji: "👋", group: 1, order: 3, version: 1, shortcodes: [ "wave" ],
+ skins: [ { emoji: "👋🏽", tone: 3, version: 1 } ] }
+];
+
+describe("TriliumEmojiMention", () => {
+ let editor: ClassicEditor;
+ let definitionsUrl: string;
+
+ async function createEditor(withPicker = false, emojiConfig: Record<string, unknown> = {}) {
+ const plugins = [ Essentials, Paragraph, MentionEditing, TriliumMentionUI, TriliumEmojiMention ];
+
+ editor = await createTestEditor(withPicker ? [ ...plugins, EmojiPicker ] : plugins, {
+ // `definitionsUrl` must survive every override, or the repository silently falls back to
+ // the real CDN and the spec starts asserting against the production emoji database.
+ emoji: { ...emojiConfig, definitionsUrl }
+ });
+
+ await editor.plugins.get(EmojiRepository).isReady();
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ }
+
+ /** The `:` feed the plugin registered, as the mention UI sees it. */
+ function emojiFeed(): TriliumMentionFeed {
+ const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
+ const feed = feeds.find((candidate) => candidate.marker === ":");
+
+ if (!feed) {
+ throw new Error("the plugin did not register a `:` feed");
+ }
+
+ return feed;
+ }
+
+ async function query(text: string): Promise<MentionFeedObjectItem[]> {
+ const feed = emojiFeed().feed;
+
+ if (typeof feed !== "function") {
+ throw new Error("the `:` feed should be a callback");
+ }
+
+ return await feed.call(editor, text) as MentionFeedObjectItem[];
+ }
+
+ function type(text: string) {
+ editor.model.change((writer) => {
+ editor.model.insertContent(writer.createText(text), editor.model.document.selection.getFirstPosition());
+ });
+ }
+
+ function pressKey(keyCode: number) {
+ editor.editing.view.document.fire("keydown", {
+ keyCode,
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ domTarget: editor.editing.view.getDomRoot()
+ });
+ }
+
+ async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, AFTER_DEBOUNCE));
+ }
+
+ beforeEach(async () => {
+ definitionsUrl = URL.createObjectURL(new Blob([ JSON.stringify(DEFINITIONS) ], { type: "application/json" }));
+ await createEditor();
+ });
+
+ afterEach(() => {
+ URL.revokeObjectURL(definitionsUrl);
+ });
+
+ it("registers itself and a `:` feed that needs two characters before opening", () => {
+ expect(TriliumEmojiMention.pluginName).toBe("TriliumEmojiMention");
+ expect(TriliumEmojiMention.requires).toContain(EmojiRepository);
+ expect(emojiFeed().minimumCharacters).toBe(2);
+ });
+
+ describe("querying", () => {
+ it("returns matching emoji as `:annotation:` items carrying the character as their text", async () => {
+ expect(await query("grinning")).toEqual([
+ { id: ":grinning face:", text: "😀" },
+ { id: ":grinning face with big eyes:", text: "😃" }
+ ]);
+ });
+
+ it("returns nothing before the repository has loaded", async () => {
+ const repository = editor.plugins.get(EmojiRepository);
+ const wasReady = repository.isRepositoryReady;
+ repository.isRepositoryReady = false;
+
+ expect(await query("grinning")).toEqual([]);
+
+ repository.isRepositoryReady = wasReady;
+ });
+
+ it("honours the configured skin tone, falling back to the default variant", async () => {
+ await createEditor(false, { skinTone: "medium" });
+
+ const items = await query("waving");
+ expect(items[0].text).toBe("👋🏽");
+
+ // "grinning face" has no toned variant, so the default is used.
+ expect((await query("grinning face"))[0].text).toBe("😀");
+ });
+ });
+
+ describe("insertion", () => {
+ it("inserts the emoji as plain text, not as a mention or a reference link", async () => {
+ type(":grin");
+ await settle();
+
+ pressKey(keyCodes.enter);
+
+ const data = getModelData(editor.model, { withoutSelection: true });
+ expect(data).toBe("<paragraph>😀</paragraph>");
+ // The bug this plugin exists to fix: upstream's handler was orphaned by the `mention`
+ // command swap, so picking an emoji inserted a `#undefined` reference link instead.
+ expect(data).not.toContain("undefined");
+ });
+ });
+
+ describe("with the emoji picker loaded", () => {
+ beforeEach(async () => {
+ await createEditor(true);
+ });
+
+ it("gives the last slot to a hand-off entry, keeping the list at the dropdown limit", async () => {
+ await createEditor(true, { dropdownLimit: 2 });
+
+ const items = await query("grinning");
+ expect(items).toHaveLength(2);
+ expect(items[0].text).toBe("😀");
+ expect(items[1].id).toContain("show_all");
+ });
+
+ it("hands the query over to the picker instead of inserting anything", async () => {
+ const picker = editor.plugins.get(EmojiPicker);
+ const showUI = vi.spyOn(picker, "showUI").mockImplementation(() => {});
+
+ const items = await query("grinning");
+ expect(items[items.length - 1].id).toContain("show_all");
+
+ type(":grinning");
+ await settle();
+
+ // The first item is pre-selected, so arrow down onto the hand-off entry at the end.
+ for (let i = 0; i < items.length - 1; i++) {
+ pressKey(keyCodes.arrowdown);
+ }
+ pressKey(keyCodes.enter);
+
+ expect(showUI).toHaveBeenCalledExactlyOnceWith("grinning");
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe("<paragraph></paragraph>");
+ });
+ });
+
+ describe("row rendering", () => {
+ function render(item: MentionFeedObjectItem): HTMLElement {
+ const renderer = emojiFeed().itemRenderer;
+
+ if (!renderer) {
+ throw new Error("the `:` feed should provide an itemRenderer");
+ }
+
+ return renderer(item) as HTMLElement;
+ }
+
+ it("labels an emoji row with the character and its shortcode", () => {
+ const row = render({ id: ":grinning face:", text: "😀" });
+
+ expect(row.querySelector(".ck-button__label")?.textContent).toBe("😀 :grinning face:");
+ });
+
+ it("labels the hand-off row with its own caption", async () => {
+ await createEditor(true);
+ const items = await query("grinning");
+ const row = render(items[items.length - 1]);
+
+ expect(row.querySelector(".ck-button__label")?.textContent).toBe("Show all emoji...");
+ });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/mention/emoji_mention.ts b/packages/ckeditor5/src/plugins/mention/emoji_mention.ts
new file mode 100644
index 0000000000..72ea72377a
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/emoji_mention.ts
@@ -0,0 +1,130 @@
+import {
+ type Editor,
+ EmojiPicker,
+ EmojiRepository,
+ type EmojiSkinToneId,
+ type MentionFeedObjectItem,
+ Plugin,
+ Typing
+} from "ckeditor5";
+
+import { registerMentionFeed } from "./register_feed.js";
+
+export const EMOJI_MARKER = ":";
+
+/** The trailing entry that hands the query over to the full emoji picker. */
+const SHOW_ALL_ID = ":__trilium_show_all_emoji__:";
+
+const DROPDOWN_LIMIT = 6;
+
+/**
+ * The `:smile:` autocomplete, hosted on {@link TriliumMentionUI}.
+ *
+ * Upstream ships this as `EmojiMention`, which we cannot use: it `requires` the `Mention` façade and
+ * so drags in upstream's `MentionUI` next to ours, leaving the text editor with two panels fighting
+ * over the same balloon. It was also broken here regardless of that — it binds its insert-as-text
+ * handler to the `mention` command in `init()`, but `MentionCustomization` replaces that command in
+ * `afterInit()`, so the handler ended up bound to a discarded instance and picking an emoji fell
+ * through to `CustomMentionCommand`, which inserted a `#undefined` reference link.
+ *
+ * Only that ~60 lines of glue is reimplemented here. The emoji data, the query engine and the picker
+ * remain upstream's: `EmojiRepository` requires just `EmojiUtils`, and `EmojiPicker` never touches
+ * `Mention`, so neither pulls a second autocomplete UI into the editor. Insertion goes through the
+ * feed's own {@link TriliumMentionFeed.commit} callback rather than the `mention` command, so there
+ * is no listener left to be orphaned by a command swap.
+ */
+export default class TriliumEmojiMention extends Plugin {
+
+ static get pluginName() {
+ return "TriliumEmojiMention" as const;
+ }
+
+ static get requires() {
+ return [ EmojiRepository, Typing ];
+ }
+
+ constructor(editor: Editor) {
+ super(editor);
+
+ editor.config.define("emoji", { dropdownLimit: DROPDOWN_LIMIT });
+
+ registerMentionFeed(editor, {
+ marker: EMOJI_MARKER,
+ // `:` is common in ordinary prose ("note: see below"). The marker pattern already
+ // requires whitespace before it, and two more characters keep a bare `:` from opening
+ // a panel over every colon the user types.
+ minimumCharacters: 2,
+ dropdownLimit: editor.config.get("emoji.dropdownLimit") as number,
+ feed: (query: string) => this._query(query),
+ itemRenderer: (item) => this._renderItem(item),
+ commit: (editorInstance, item) => this._commit(editorInstance, item)
+ });
+ }
+
+ private get _picker(): EmojiPicker | null {
+ return this.editor.plugins.has(EmojiPicker) ? this.editor.plugins.get(EmojiPicker) : null;
+ }
+
+ private _query(query: string): MentionFeedObjectItem[] {
+ const repository = this.editor.plugins.get(EmojiRepository);
+
+ if (!repository.isRepositoryReady) {
+ return [];
+ }
+
+ // The picker owns the skin tone once it is loaded — the user can change it there, and that
+ // choice is not written back to the config.
+ // `EmojiRepository` defines `emoji.skinTone` (defaulting to `"default"`), so the config read
+ // never comes back empty.
+ const picker = this._picker;
+ const skinTone = picker ? picker.skinTone : this.editor.config.get("emoji.skinTone") as EmojiSkinToneId;
+ const limit = this.editor.config.get("emoji.dropdownLimit") as number;
+
+ const emojis = repository.getEmojiByQuery(query).map((emoji) => ({
+ id: `${EMOJI_MARKER}${emoji.annotation}${EMOJI_MARKER}`,
+ text: emoji.skins[skinTone] ?? emoji.skins.default
+ }));
+
+ if (!this._picker) {
+ return emojis;
+ }
+
+ // One slot is given up to the hand-off entry, so the list length stays at the limit.
+ return [ ...emojis.slice(0, limit - 1), { id: SHOW_ALL_ID, text: query } ];
+ }
+
+ private _renderItem(item: MentionFeedObjectItem): HTMLElement {
+ const button = document.createElement("button");
+ button.type = "button";
+ button.tabIndex = -1;
+ button.classList.add("ck", "ck-button", "ck-button_with-text");
+
+ const label = document.createElement("span");
+ label.classList.add("ck", "ck-button__label");
+ label.textContent = item.id === SHOW_ALL_ID
+ ? this.editor.t("Show all emoji...")
+ : `${item.text} ${item.id}`;
+
+ button.append(label);
+ return button;
+ }
+
+ private _commit(editor: Editor, item: MentionFeedObjectItem) {
+ if (item.id !== SHOW_ALL_ID) {
+ editor.execute("insertText", { text: item.text });
+ return;
+ }
+
+ const picker = this._picker;
+
+ /* v8 ignore next 3 -- the hand-off entry is only ever added to the feed while `EmojiPicker` is loaded, so it cannot be picked when the plugin is absent */
+ if (!picker) {
+ return;
+ }
+
+ picker.showUI(item.text);
+ // The picker renders into the balloon during `showUI()`; focusing it has to wait until that
+ // view exists. Mirrors upstream `EmojiMention`.
+ setTimeout(() => picker.emojiPickerView?.focus());
+ }
+}
diff --git a/packages/ckeditor5/src/plugins/mention/marker_pattern.spec.ts b/packages/ckeditor5/src/plugins/mention/marker_pattern.spec.ts
new file mode 100644
index 0000000000..fc6067f259
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/marker_pattern.spec.ts
@@ -0,0 +1,121 @@
+import { env } from "ckeditor5";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createMarkerPattern, findMarkerMatch } from "./marker_pattern.js";
+
+/** Convenience: the query the pattern extracts, or `null` when it does not match. */
+function query(pattern: RegExp, text: string) {
+ return pattern.exec(text)?.[2] ?? null;
+}
+
+describe("createMarkerPattern", () => {
+ const unicodePropertiesSupported = env.features.isRegExpUnicodePropertySupported;
+
+ afterEach(() => {
+ env.features.isRegExpUnicodePropertySupported = unicodePropertiesSupported;
+ });
+
+ it("matches a marker at the start of the block, after a space and after opening punctuation", () => {
+ const pattern = createMarkerPattern("#");
+
+ expect(query(pattern, "#foo")).toBe("foo");
+ expect(query(pattern, "bar #foo")).toBe("foo");
+ expect(query(pattern, "(#foo")).toBe("foo");
+ expect(query(pattern, "\"#foo")).toBe("foo");
+ // The bare marker is enough when `minimumCharacters` is 0.
+ expect(query(pattern, "#")).toBe("");
+ });
+
+ it("does not match a marker glued to preceding word characters", () => {
+ const pattern = createMarkerPattern("#");
+
+ expect(query(pattern, "foo#bar")).toBeNull();
+ expect(query(pattern, "a#")).toBeNull();
+ });
+
+ it("opens after '=' so a marker can follow an attribute assignment", () => {
+ expect(query(createMarkerPattern("~"), "#foo=~bar")).toBe("bar");
+ });
+
+ it("stops matching once the query would contain '=' — past an assignment we are in a value", () => {
+ expect(query(createMarkerPattern("#"), "#foo=bar")).toBeNull();
+ expect(query(createMarkerPattern("@", { allowSpaces: true }), "@foo=bar")).toBeNull();
+ });
+
+ it("stops matching at a space unless the feed allows spaces", () => {
+ expect(query(createMarkerPattern("#"), "#foo bar")).toBeNull();
+ expect(query(createMarkerPattern("@", { allowSpaces: true }), "@My meeting notes")).toBe("My meeting notes");
+ });
+
+ it("honours minimumCharacters", () => {
+ const pattern = createMarkerPattern("@", { minimumCharacters: 2 });
+
+ expect(query(pattern, "@")).toBeNull();
+ expect(query(pattern, "@a")).toBeNull();
+ expect(query(pattern, "@ab")).toBe("ab");
+ });
+
+ it("escapes characters that are special inside a character class", () => {
+ for (const marker of [ "]", "\\", "^", "-", "@", "#", "~", "$", "." ]) {
+ const pattern = createMarkerPattern(marker);
+
+ expect(query(pattern, `${marker}foo`)).toBe("foo");
+ }
+ });
+
+ it("falls back to an ASCII opening set where Unicode property escapes are unsupported", () => {
+ env.features.isRegExpUnicodePropertySupported = true;
+ // U+201C is `\p{Pi}`, so it only opens a marker while the property escapes are available.
+ expect(query(createMarkerPattern("#"), "“#foo")).toBe("foo");
+
+ env.features.isRegExpUnicodePropertySupported = false;
+ const pattern = createMarkerPattern("#");
+
+ expect(query(pattern, "“#foo")).toBeNull();
+
+ // Everything the ASCII set does spell out keeps working.
+ expect(query(pattern, "#foo")).toBe("foo");
+ expect(query(pattern, "bar #foo")).toBe("foo");
+ expect(query(pattern, "(#foo")).toBe("foo");
+ expect(query(pattern, "[#foo")).toBe("foo");
+ expect(query(pattern, "{#foo")).toBe("foo");
+ expect(query(pattern, "\"#foo")).toBe("foo");
+ expect(query(createMarkerPattern("~"), "#foo=~bar")).toBe("bar");
+ expect(query(pattern, "foo#bar")).toBeNull();
+ });
+
+ it("no longer needs a sentinel character to stop matching", () => {
+ // The removed pnpm patch excluded U+2002 from the query so an inserted en-space could break
+ // the match. Nothing is special about it any more — it is just an ordinary space.
+ expect(query(createMarkerPattern("#"), "#foo ")).toBeNull();
+ });
+});
+
+describe("findMarkerMatch", () => {
+ const feeds = [
+ { marker: "#", pattern: createMarkerPattern("#") },
+ { marker: "~", pattern: createMarkerPattern("~") },
+ { marker: "@", pattern: createMarkerPattern("@", { allowSpaces: true }) }
+ ];
+
+ it("returns the feed whose marker is closest to the caret", () => {
+ expect(findMarkerMatch(feeds, "#foo ~bar")).toMatchObject({ query: "bar", feed: { marker: "~" } });
+ expect(findMarkerMatch(feeds, "~foo #bar")).toMatchObject({ query: "bar", feed: { marker: "#" } });
+ });
+
+ it("prefers the nearest marker even when an earlier space-allowing feed also matches", () => {
+ // `@` allows spaces, so `@foo #bar` matches for both feeds; `#` is nearer the caret.
+ expect(findMarkerMatch(feeds, "@foo #bar")).toMatchObject({ query: "bar", feed: { marker: "#" } });
+ });
+
+ it("returns null when no feed matches", () => {
+ expect(findMarkerMatch(feeds, "plain text")).toBeNull();
+ expect(findMarkerMatch(feeds, "foo#bar")).toBeNull();
+ // The marker is present but the query broke the pattern.
+ expect(findMarkerMatch(feeds, "#foo bar")).toBeNull();
+ });
+
+ it("matches a marker sitting at offset 0", () => {
+ expect(findMarkerMatch(feeds, "#foo")).toMatchObject({ query: "foo", feed: { marker: "#" } });
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/mention/marker_pattern.ts b/packages/ckeditor5/src/plugins/mention/marker_pattern.ts
new file mode 100644
index 0000000000..26f930ba24
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/marker_pattern.ts
@@ -0,0 +1,88 @@
+import { env } from "ckeditor5";
+
+export interface MarkerPatternOptions {
+ /**
+ * How many characters must follow the marker before the panel may open. `0` means the bare
+ * marker is enough.
+ */
+ minimumCharacters?: number;
+ /**
+ * Whether the query may contain spaces. Note titles do (`@My meeting notes`), attribute names
+ * never do — and allowing them there means `#foo bar baz` keeps matching forever, so the panel
+ * can never close on its own.
+ */
+ allowSpaces?: boolean;
+}
+
+/**
+ * Builds the regular expression deciding whether the text before the caret should open the
+ * autocomplete panel, and what the query is.
+ *
+ * This replaces upstream's `createRegExp()` (`mentionui.ts`), which hardcodes the query as `.` —
+ * matching everything including spaces, so a query never stops matching and the panel only ever
+ * closes when the feed returns nothing. `=` is excluded from the query unconditionally: past an
+ * assignment we are inside an attribute *value*, not a name.
+ *
+ * The pattern has three groups:
+ * - `0` (non-capturing): the opening sequence — start of block, space, `=` or opening punctuation,
+ * - `1`: the marker,
+ * - `2`: the query typed so far, up to the caret (`$`).
+ */
+export function createMarkerPattern(marker: string, { minimumCharacters = 0, allowSpaces = false }: MarkerPatternOptions = {}): RegExp {
+ // Upstream allows a space or an opening punctuation character before the marker; Trilium adds
+ // `=` so a marker can open right after an attribute assignment (`#foo=~bar`).
+ const opening = env.features.isRegExpUnicodePropertySupported ? "=\\p{Ps}\\p{Pi}\"'" : "=\\(\\[{\"'";
+ const quantifier = minimumCharacters === 0 ? "*" : `{${minimumCharacters},}`;
+ const query = allowSpaces ? "[^=]" : "[^\\s=]";
+
+ // The `u` flag applies strict escaping rules — escaping a character that does not need it
+ // throws — so the marker goes into a character class, where only these four need escaping.
+ const escapedMarker = marker.replace(/[\]\\^-]/g, "\\$&");
+
+ return new RegExp(`(?:^|[ ${opening}])([${escapedMarker}])(${query}${quantifier})$`, "u");
+}
+
+export interface FeedPattern {
+ marker: string;
+ pattern: RegExp;
+}
+
+export interface MarkerMatch<T extends FeedPattern> {
+ feed: T;
+ /** The text typed after the marker, up to the caret. */
+ query: string;
+}
+
+/**
+ * Finds which feed the text before the caret triggers, if any.
+ *
+ * When several markers are present the one closest to the caret wins — equivalently, the one with
+ * the shortest query, since the marker sits immediately before its query. Mirrors upstream's
+ * `getLastValidMarkerInText()` + `requestFeedText()`, both of which are module-private.
+ */
+export function findMarkerMatch<T extends FeedPattern>(feeds: readonly T[], text: string): MarkerMatch<T> | null {
+ let best: MarkerMatch<T> | null = null;
+
+ for (const feed of feeds) {
+ const markerOffset = text.lastIndexOf(feed.marker);
+
+ if (markerOffset < 0) {
+ continue;
+ }
+
+ // Include the character before the marker so the opening group has something to match;
+ // at offset 0 the `^` alternative applies instead.
+ const tail = markerOffset === 0 ? text : text.substring(markerOffset - 1);
+ const query = feed.pattern.exec(tail)?.[2];
+
+ if (query === undefined) {
+ continue;
+ }
+
+ if (!best || query.length < best.query.length) {
+ best = { feed, query };
+ }
+ }
+
+ return best;
+}
diff --git a/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts b/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts
new file mode 100644
index 0000000000..ded150d07f
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts
@@ -0,0 +1,48 @@
+import { type ClassicEditor, Essentials, Paragraph } from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import { registerMentionFeed } from "./register_feed.js";
+import type { TriliumMentionFeed } from "./types.js";
+
+describe("registerMentionFeed", () => {
+ let editor: ClassicEditor;
+
+ function feeds() {
+ return (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
+ }
+
+ beforeEach(async () => {
+ editor = await createTestEditor([ Essentials, Paragraph ]);
+ });
+
+ it("creates mention.feeds when nothing configured it, then appends to it", () => {
+ expect(editor.config.get("mention.feeds")).toBeUndefined();
+
+ registerMentionFeed(editor, { marker: ":", feed: [] });
+ registerMentionFeed(editor, { marker: "/", feed: [] });
+
+ expect(feeds().map((feed) => feed.marker)).toEqual([ ":", "/" ]);
+ });
+
+ it("preserves feeds the host application configured", async () => {
+ editor = await createTestEditor([ Essentials, Paragraph ], {
+ mention: { feeds: [ { marker: "@", feed: [] } ] }
+ });
+
+ registerMentionFeed(editor, { marker: ":", feed: [] });
+
+ expect(feeds().map((feed) => feed.marker)).toEqual([ "@", ":" ]);
+ });
+
+ it("refuses to register a marker twice, since the second feed would be unreachable", () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ registerMentionFeed(editor, { marker: ":", feed: [ "first" ] });
+ registerMentionFeed(editor, { marker: ":", feed: [ "second" ] });
+
+ expect(feeds()).toHaveLength(1);
+ expect(feeds()[0].feed).toEqual([ "first" ]);
+ expect(warn).toHaveBeenCalledOnce();
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/mention/register_feed.ts b/packages/ckeditor5/src/plugins/mention/register_feed.ts
new file mode 100644
index 0000000000..a488c43a63
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/register_feed.ts
@@ -0,0 +1,26 @@
+import type { Editor } from "ckeditor5";
+
+import type { TriliumMentionFeed } from "./types.js";
+
+/**
+ * Appends a feed to `mention.feeds`, creating the entry when the host application configured none.
+ *
+ * Call this from a plugin **constructor**, not from `init()`: {@link TriliumMentionUI} compiles the
+ * configured feeds into trigger patterns in its own `init()`, and CKEditor runs every plugin
+ * constructor before any `init()`, so the constructor is the only hook guaranteed to be early
+ * enough regardless of the order the plugins appear in.
+ *
+ * A feed whose marker is already taken is dropped with a warning rather than registered twice — two
+ * feeds sharing a marker would make {@link findMarkerMatch} pick whichever came first and silently
+ * shadow the other.
+ */
+export function registerMentionFeed(editor: Editor, feed: TriliumMentionFeed): void {
+ const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
+
+ if (feeds.some((existing) => existing.marker === feed.marker)) {
+ console.warn(`[trilium-mention] the "${feed.marker}" marker is already registered; ignoring the duplicate feed.`);
+ return;
+ }
+
+ editor.config.set("mention.feeds", [ ...feeds, feed ]);
+}
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
new file mode 100644
index 0000000000..568f37ecd9
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts
@@ -0,0 +1,270 @@
+import {
+ BlockQuote,
+ type ClassicEditor,
+ ContextualBalloon,
+ Essentials,
+ _getModelData as getModelData,
+ Heading,
+ keyCodes,
+ MentionEditing,
+ Paragraph,
+ _setModelData as setModelData
+} from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import TriliumSlashCommands, {
+ buildDefaultSlashCommands,
+ matchSlashCommands,
+ type SlashCommandConfig,
+ type SlashCommandDefinition
+} from "./slash_commands.js";
+import TriliumMentionUI from "./trilium_mention_ui.js";
+import type { TriliumMentionFeed } from "./types.js";
+
+/** Longer than the mention UI's 100 ms feed debounce. */
+const AFTER_DEBOUNCE = 160;
+
+const HEADING_OPTIONS = [
+ { model: "paragraph", title: "Paragraph" },
+ { model: "heading2", view: "h2", title: "Heading 2" },
+ { model: "heading3", view: "h3", title: "Heading 3" }
+];
+
+describe("matchSlashCommands", () => {
+ const definitions: SlashCommandDefinition[] = [
+ { id: "table", title: "Table", icon: "", aliases: [ "grid" ] },
+ { id: "codeBlock", title: "Code block", icon: "", aliases: [ "snippet" ] },
+ { id: "toc", title: "Table of contents", icon: "", aliases: [ "outline" ] },
+ { id: "quote", title: "Block quote", icon: "" }
+ ];
+
+ it("returns the whole catalog, in order, for an empty query", () => {
+ expect(matchSlashCommands(definitions, "").map((d) => d.id)).toEqual([ "table", "codeBlock", "toc", "quote" ]);
+ expect(matchSlashCommands(definitions, " ").map((d) => d.id)).toEqual([ "table", "codeBlock", "toc", "quote" ]);
+ });
+
+ it("ranks title prefixes above alias prefixes, and both above substring matches", () => {
+ // "Table"/"Table of contents" start with it; "Block quote" only contains it.
+ expect(matchSlashCommands(definitions, "table").map((d) => d.id)).toEqual([ "table", "toc" ]);
+
+ // `grid` is an alias of Table; `Code block` merely contains "d".
+ expect(matchSlashCommands(definitions, "gri").map((d) => d.id)).toEqual([ "table" ]);
+
+ // Title prefix (Code block) beats alias substring (outline).
+ expect(matchSlashCommands(definitions, "co").map((d) => d.id)).toEqual([ "codeBlock", "toc" ]);
+
+ // Last resort: only an alias contains it, and not at its start ("outline").
+ expect(matchSlashCommands(definitions, "line").map((d) => d.id)).toEqual([ "toc" ]);
+ });
+
+ it("matches case-insensitively and ignores surrounding whitespace", () => {
+ expect(matchSlashCommands(definitions, " BLOCK ").map((d) => d.id)).toEqual([ "quote", "codeBlock" ]);
+ });
+
+ it("returns nothing when there is no match", () => {
+ expect(matchSlashCommands(definitions, "zzz")).toEqual([]);
+ });
+});
+
+describe("TriliumSlashCommands", () => {
+ let editor: ClassicEditor;
+
+ async function createEditor(slashCommand: SlashCommandConfig = {}) {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, Heading, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],
+ { heading: { options: HEADING_OPTIONS }, slashCommand }
+ );
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ }
+
+ /** The `/` feed the plugin registered, as the mention UI sees it. */
+ function slashFeed(): TriliumMentionFeed {
+ const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
+ const feed = feeds.find((candidate) => candidate.marker === "/");
+
+ if (!feed) {
+ throw new Error("the plugin did not register a `/` feed");
+ }
+
+ return feed;
+ }
+
+ async function queryPalette(query: string) {
+ const feed = slashFeed().feed;
+
+ if (typeof feed !== "function") {
+ throw new Error("the `/` feed should be a callback");
+ }
+
+ return await feed.call(editor, query);
+ }
+
+ function type(text: string) {
+ editor.model.change((writer) => {
+ editor.model.insertContent(writer.createText(text), editor.model.document.selection.getFirstPosition());
+ });
+ }
+
+ function pressKey(keyCode: number) {
+ editor.editing.view.document.fire("keydown", {
+ keyCode,
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ domTarget: editor.editing.view.getDomRoot()
+ });
+ }
+
+ async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, AFTER_DEBOUNCE));
+ }
+
+ beforeEach(async () => {
+ await createEditor();
+ });
+
+ it("registers itself and a `/` feed that opens on the bare marker", () => {
+ expect(TriliumSlashCommands.pluginName).toBe("TriliumSlashCommands");
+ expect(editor.plugins.get(TriliumSlashCommands)).toBeInstanceOf(TriliumSlashCommands);
+ expect(slashFeed().minimumCharacters).toBe(0);
+ });
+
+ describe("catalog", () => {
+ it("derives heading entries from heading.options, so the palette matches the configured levels", () => {
+ const defaults = buildDefaultSlashCommands(editor).map((definition) => definition.id);
+
+ // Trilium reserves heading1 for the note title, so it is absent from the options.
+ expect(defaults.slice(0, 3)).toEqual([ "paragraph", "heading2", "heading3" ]);
+ expect(defaults).not.toContain("heading1");
+ });
+
+ it("falls back to a heading-free palette in an editor that configures neither headings nor slash commands", async () => {
+ editor = await createTestEditor(
+ [ Essentials, Paragraph, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]
+ );
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ // No `heading.options` to derive from, so the palette carries no headings at all...
+ expect(buildDefaultSlashCommands(editor).map((definition) => definition.id))
+ .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" ]);
+ });
+
+ it("uses a generic icon for a heading level outside h1-h6", async () => {
+ await createEditor();
+ editor.config.set("heading.options", [ { model: "headingCustom", title: "Custom heading" } ]);
+
+ const [ custom ] = buildDefaultSlashCommands(editor);
+ expect(custom.id).toBe("headingCustom");
+ expect(custom.icon).toBeTruthy();
+ });
+
+ it("hides entries whose command no plugin registered", async () => {
+ const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);
+
+ // BlockQuote is loaded in this editor; CodeBlock and Table are not.
+ expect(ids).toContain("/blockQuote");
+ expect(ids).not.toContain("/codeBlock");
+ expect(ids).not.toContain("/insertTable");
+ });
+
+ it("drops entries named by removeCommands", async () => {
+ await createEditor({ removeCommands: [ "blockQuote", "heading3" ] });
+ const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);
+
+ expect(ids).not.toContain("/blockQuote");
+ expect(ids).not.toContain("/heading3");
+ expect(ids).toContain("/heading2");
+ });
+
+ it("appends extraCommands after the defaults, without gating them on a command", async () => {
+ await createEditor({
+ extraCommands: [ { id: "custom", title: "Custom thing", icon: "<svg/>", execute: () => {} } ]
+ });
+ const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);
+
+ expect(ids[ids.length - 1]).toBe("/custom");
+ });
+ });
+
+ describe("execution", () => {
+ it("runs a commandName entry and removes the trigger text", async () => {
+ type("/quo");
+ await settle();
+
+ pressKey(keyCodes.enter);
+
+ const data = getModelData(editor.model, { withoutSelection: true });
+ expect(data).toContain("<blockQuote>");
+ expect(data).not.toContain("/quo");
+ });
+
+ 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 } ] });
+
+ type("/custom");
+ await settle();
+ pressKey(keyCodes.enter);
+
+ expect(execute).toHaveBeenCalledExactlyOnceWith(editor);
+ });
+
+ it("passes the level to the heading command rather than executing an id", async () => {
+ type("/heading");
+ await settle();
+
+ // "Heading 2" is the first configured level, so it is the pre-selected suggestion.
+ pressKey(keyCodes.enter);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("<heading2>");
+ });
+ });
+
+ describe("row rendering", () => {
+ function render(query: string, index = 0) {
+ const items = matchSlashCommands(buildDefaultSlashCommands(editor), query);
+ const renderer = slashFeed().itemRenderer;
+
+ if (!renderer) {
+ throw new Error("the `/` feed should provide an itemRenderer");
+ }
+
+ return renderer({ id: `/${items[index].id}`, text: items[index].title, definition: items[index] } as never) as HTMLElement;
+ }
+
+ it("renders the icon, title and description with premium's class names, so the theme still applies", () => {
+ const row = render("block quote");
+
+ expect(row.classList.contains("ck-slash-command-button")).toBe(true);
+ // 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");
+ expect(row.querySelector(".ck-button__label")?.textContent).toBe("Block quote");
+ expect(row.querySelector(".ck-slash-command-button__description")?.textContent).toBeTruthy();
+ });
+
+ it("omits the description element for an entry that has none", () => {
+ const renderer = slashFeed().itemRenderer;
+
+ if (!renderer) {
+ throw new Error("the `/` feed should provide an itemRenderer");
+ }
+
+ const definition: SlashCommandDefinition = { id: "bare", title: "Bare", icon: "<svg/>" };
+ const row = renderer({ id: "/bare", text: "Bare", definition } as never) as HTMLElement;
+
+ expect(row.querySelector(".ck-slash-command-button__description")).toBeNull();
+ });
+ });
+
+ it("does not open the palette on a mid-word slash", async () => {
+ type("and/or");
+ await settle();
+
+ const balloon = editor.plugins.get(ContextualBalloon);
+ expect(balloon.visibleView?.element?.classList.contains("ck-mentions") ?? false).toBe(false);
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
new file mode 100644
index 0000000000..2745f75042
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts
@@ -0,0 +1,297 @@
+import "../../theme/slash_commands.css";
+
+import {
+ IconCodeBlock,
+ IconHeading1,
+ IconHeading2,
+ IconHeading3,
+ IconHeading4,
+ IconHeading5,
+ IconHeading6,
+ IconHorizontalLine,
+ IconIndent,
+ IconOutdent,
+ IconParagraph,
+ IconQuote,
+ IconTable
+} from "@ckeditor/ckeditor5-icons";
+import { type Editor, type MentionFeedObjectItem, Plugin } from "ckeditor5";
+
+import { registerMentionFeed } from "./register_feed.js";
+
+export const SLASH_MARKER = "/";
+
+const DROPDOWN_LIMIT = 10;
+
+/**
+ * One entry of the `/` palette. Structurally the same shape premium `SlashCommand` accepted, so the
+ * definitions in `extra_slash_commands.ts` carry over unchanged.
+ */
+export interface SlashCommandDefinition {
+ /** Stable identifier, also what `slashCommand.removeCommands` matches against. */
+ id: string;
+ title: string;
+ description?: string;
+ /** Extra words the entry can be found by, beyond its title. */
+ aliases?: string[];
+ /** Raw SVG markup. */
+ icon: 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. */
+ execute?: (editor: Editor) => void;
+}
+
+export interface SlashCommandConfig {
+ extraCommands?: SlashCommandDefinition[];
+ removeCommands?: string[];
+}
+
+/**
+ * The `/` command palette, hosted on {@link TriliumMentionUI}.
+ *
+ * This replaces premium `SlashCommand`, which was the only remaining plugin forcing the `Mention`
+ * façade — and therefore upstream's `MentionUI` — into the text editor alongside ours. Two mention
+ * UIs sharing `mention.feeds` fight over the same `ContextualBalloon`: whichever adds its view
+ * second buries the other, and the buried one then throws `contextualballoon-add-view-exist` on its
+ * next keystroke.
+ *
+ * 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`.
+ */
+export default class TriliumSlashCommands extends Plugin {
+
+ static get pluginName() {
+ return "TriliumSlashCommands" as const;
+ }
+
+ constructor(editor: Editor) {
+ super(editor);
+
+ registerMentionFeed(editor, {
+ marker: SLASH_MARKER,
+ // A bare `/` opens the full palette, as the premium plugin did.
+ minimumCharacters: 0,
+ dropdownLimit: DROPDOWN_LIMIT,
+ feed: (query: string) => matchSlashCommands(this._catalog(), query).map(toFeedItem),
+ itemRenderer: (item) => renderRow(item as SlashCommandItem),
+ commit: (editorInstance, item) => runSlashCommand(editorInstance, (item as SlashCommandItem).definition)
+ });
+ }
+
+ /**
+ * The definitions available in *this* editor: the built-in palette plus the configured extras,
+ * minus anything `removeCommands` names and anything whose command is not loaded.
+ */
+ 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 ?? []) ]
+ .filter((definition) => !removed.has(definition.id))
+ // An entry naming a command no plugin registered would throw on execute. Entries with
+ // their own `execute` are the caller's responsibility, exactly as upstream treated
+ // `extraCommands`.
+ .filter((definition) => !definition.commandName || !!editor.commands.get(definition.commandName));
+ }
+}
+
+type SlashCommandItem = MentionFeedObjectItem & { definition: SlashCommandDefinition };
+
+function toFeedItem(definition: SlashCommandDefinition): SlashCommandItem {
+ // Upstream requires a feed item's `id` to start with the marker.
+ return { id: `${SLASH_MARKER}${definition.id}`, text: definition.title, definition };
+}
+
+function runSlashCommand(editor: Editor, definition: SlashCommandDefinition) {
+ if (definition.execute) {
+ definition.execute(editor);
+ return;
+ }
+
+ /* v8 ignore next 3 -- `_catalog()` drops every definition that has neither `execute` nor a registered `commandName`, so one or the other is always present here */
+ if (definition.commandName) {
+ editor.execute(definition.commandName);
+ }
+}
+
+/**
+ * Ranks `definitions` against what the user typed after the `/`.
+ *
+ * Prefix matches sort above substring matches so that `/co` offers "Code block" before "Table of
+ * contents", and title matches above alias matches so an entry is found by its own name first.
+ * Ordering within a tier is the catalog order, which is deliberate: the defaults come first and the
+ * hand-authored Trilium entries follow.
+ */
+export function matchSlashCommands(definitions: SlashCommandDefinition[], query: string): SlashCommandDefinition[] {
+ const needle = query.trim().toLowerCase();
+
+ if (!needle) {
+ return definitions;
+ }
+
+ const ranked: Array<{ definition: SlashCommandDefinition; rank: number }> = [];
+
+ for (const definition of definitions) {
+ const title = definition.title.toLowerCase();
+ const aliases = (definition.aliases ?? []).map((alias) => alias.toLowerCase());
+ let rank: number | null = null;
+
+ if (title.startsWith(needle)) {
+ rank = 0;
+ } else if (aliases.some((alias) => alias.startsWith(needle))) {
+ rank = 1;
+ } else if (title.includes(needle)) {
+ rank = 2;
+ } else if (aliases.some((alias) => alias.includes(needle))) {
+ rank = 3;
+ }
+
+ if (rank !== null) {
+ ranked.push({ definition, rank });
+ }
+ }
+
+ // `sort` is stable in every engine we target, so equal ranks keep their catalog order.
+ return ranked.sort((a, b) => a.rank - b.rank).map((entry) => entry.definition);
+}
+
+/**
+ * The subset of premium's built-in palette that applies to Trilium. Entries Trilium re-authors with
+ * better icons or sentence-case titles (the lists, Mermaid) live in `extra_slash_commands.ts` and
+ * are deliberately absent here; so are the ones for plugins Trilium never loads (CKBox, CKFinder,
+ * HTML embed).
+ *
+ * Headings are derived from `heading.options` rather than hardcoded, so the palette automatically
+ * matches the configured levels — Trilium omits `heading1`, which is reserved for the note title.
+ */
+export function buildDefaultSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const t = editor.locale.t;
+
+ return [
+ ...buildHeadingSlashCommands(editor),
+ {
+ id: "blockQuote",
+ title: t("Block quote"),
+ description: t("Quote a passage from another source."),
+ aliases: [ "quote", "citation" ],
+ icon: IconQuote,
+ commandName: "blockQuote"
+ },
+ {
+ id: "codeBlock",
+ title: t("Code block"),
+ description: t("Insert a block of preformatted code."),
+ aliases: [ "snippet", "pre" ],
+ icon: IconCodeBlock,
+ commandName: "codeBlock"
+ },
+ {
+ id: "insertTable",
+ title: t("Table"),
+ description: t("Insert a table."),
+ aliases: [ "grid" ],
+ icon: IconTable,
+ commandName: "insertTable"
+ },
+ {
+ id: "horizontalLine",
+ title: t("Horizontal line"),
+ description: t("Insert a horizontal rule."),
+ aliases: [ "divider", "separator", "rule" ],
+ icon: IconHorizontalLine,
+ commandName: "horizontalLine"
+ },
+ {
+ id: "indent",
+ title: t("Indent"),
+ description: t("Increase the indentation of the current block."),
+ icon: IconIndent,
+ commandName: "indent"
+ },
+ {
+ id: "outdent",
+ title: t("Outdent"),
+ description: t("Decrease the indentation of the current block."),
+ icon: IconOutdent,
+ commandName: "outdent"
+ }
+ ];
+}
+
+function buildHeadingSlashCommands(editor: Editor): SlashCommandDefinition[] {
+ const options = (editor.config.get("heading.options") ?? []) as Array<{ model: string; title: string }>;
+ const icons: Record<string, string> = {
+ heading1: IconHeading1,
+ heading2: IconHeading2,
+ heading3: IconHeading3,
+ heading4: IconHeading4,
+ heading5: IconHeading5,
+ heading6: IconHeading6
+ };
+
+ return options.map((option) => {
+ if (option.model === "paragraph") {
+ return {
+ id: "paragraph",
+ title: option.title,
+ description: editor.locale.t("Turn the current block into a paragraph."),
+ aliases: [ "text", "body" ],
+ icon: IconParagraph,
+ commandName: "paragraph"
+ };
+ }
+
+ return {
+ id: option.model,
+ title: option.title,
+ description: editor.locale.t("Turn the current block into a heading."),
+ aliases: [ "title", option.model.replace("heading", "h") ],
+ icon: icons[option.model] ?? IconHeading2,
+ // `heading` takes the level as an argument, so it cannot use `commandName`.
+ execute: (target: Editor) => target.execute("heading", { value: option.model })
+ };
+ });
+}
+
+/**
+ * Renders one palette row: icon, title and description. The class names match premium's, so the
+ * overrides Trilium already carries in `style.css` and the Next theme keep applying unchanged.
+ */
+function renderRow(item: SlashCommandItem): HTMLElement {
+ const { definition } = item;
+
+ const button = document.createElement("button");
+ button.type = "button";
+ button.tabIndex = -1;
+ // `ck-button_with-text` is load-bearing, not cosmetic: the base button styles hide
+ // `.ck-button__label` outright without it, which leaves the row showing its description and no
+ // title at all.
+ button.classList.add("ck", "ck-button", "ck-button_with-text", "ck-slash-command-button");
+
+ const icon = document.createElement("span");
+ icon.classList.add("ck", "ck-icon");
+ icon.innerHTML = definition.icon;
+ button.append(icon);
+
+ const textPart = document.createElement("span");
+ textPart.classList.add("ck", "ck-slash-command-button__text-part");
+
+ const label = document.createElement("span");
+ label.classList.add("ck", "ck-button__label");
+ label.textContent = definition.title;
+ textPart.append(label);
+
+ if (definition.description) {
+ const description = document.createElement("span");
+ description.classList.add("ck", "ck-slash-command-button__description");
+ description.textContent = definition.description;
+ textPart.append(description);
+ }
+
+ button.append(textPart);
+ return button;
+}
diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts
new file mode 100644
index 0000000000..062a652ee4
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts
@@ -0,0 +1,516 @@
+import {
+ type ClassicEditor,
+ ContextualBalloon,
+ Essentials,
+ _getModelData as getModelData,
+ keyCodes,
+ MentionEditing,
+ type MentionFeedObjectItem,
+ Paragraph,
+ _setModelData as setModelData,
+ View
+} from "ckeditor5";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { createTestEditor } from "../../../test/editor-kit.js";
+import type { TriliumMentionFeed } from "./types.js";
+import TriliumMentionUI from "./trilium_mention_ui.js";
+
+/** Longer than the plugin's 100 ms feed debounce. */
+const AFTER_DEBOUNCE = 160;
+
+describe("TriliumMentionUI", () => {
+ let editor: ClassicEditor;
+ let labelFeed: ReturnType<typeof vi.fn>;
+
+ async function createEditor(overrides: Partial<TriliumMentionFeed> = {}, extraConfig: Record<string, unknown> = {}) {
+ labelFeed = vi.fn(async (query: string) => (
+ [ "alpha", "beta", "gamma" ]
+ .filter((name) => name.startsWith(query))
+ .map((name) => ({ id: `#${name}`, text: `#${name}` }))
+ ));
+
+ editor = await createTestEditor([ Essentials, Paragraph, MentionEditing, TriliumMentionUI ], {
+ mention: {
+ feeds: [ { marker: "#", feed: labelFeed as unknown as TriliumMentionFeed["feed"], minimumCharacters: 0, ...overrides } ]
+ },
+ ...extraConfig
+ });
+ }
+
+ /** Whether the autocomplete balloon is currently on screen. */
+ function isPanelVisible() {
+ const balloon = editor.plugins.get(ContextualBalloon);
+
+ return balloon.visibleView?.element?.classList.contains("ck-mentions") ?? false;
+ }
+
+ /** Types `text` at the caret, producing the `change:data` the text watcher reacts to. */
+ function type(text: string) {
+ editor.model.change((writer) => {
+ editor.model.insertContent(writer.createText(text), editor.model.document.selection.getFirstPosition());
+ });
+ }
+
+ /** Moves the caret to `offset` in the first paragraph, as a click would. */
+ function moveCaretTo(offset: number) {
+ editor.model.change((writer) => {
+ const paragraph = editor.model.document.getRoot()?.getChild(0);
+
+ if (paragraph?.is("element")) {
+ writer.setSelection(writer.createPositionAt(paragraph, offset));
+ }
+ });
+ }
+
+ function pressKey(keyCode: number) {
+ editor.editing.view.document.fire("keydown", {
+ keyCode,
+ preventDefault: () => {},
+ stopPropagation: () => {},
+ domTarget: editor.editing.view.getDomRoot()
+ });
+ }
+
+ async function settle() {
+ await new Promise((resolve) => setTimeout(resolve, AFTER_DEBOUNCE));
+ }
+
+ beforeEach(async () => {
+ await createEditor();
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ });
+
+ it("registers itself and requires the contextual balloon", () => {
+ expect(TriliumMentionUI.pluginName).toBe("TriliumMentionUI");
+ expect(TriliumMentionUI.requires).toContain(ContextualBalloon);
+ expect(editor.plugins.get(TriliumMentionUI)).toBeInstanceOf(TriliumMentionUI);
+ });
+
+ it("opens the panel while typing and queries the feed with the text after the marker", async () => {
+ type("#al");
+ await settle();
+
+ expect(labelFeed).toHaveBeenCalledWith("al");
+ expect(isPanelVisible()).toBe(true);
+ });
+
+ it("hides the panel when the feed returns nothing", async () => {
+ type("#zzz");
+ await settle();
+
+ expect(isPanelVisible()).toBe(false);
+ });
+
+ it("keeps the panel open, and anchored where it opened, while the query is refined", async () => {
+ type("#a");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ const position = editor.plugins.get(ContextualBalloon).view.position;
+
+ type("l");
+ await settle();
+
+ expect(labelFeed).toHaveBeenLastCalledWith("al");
+ expect(isPanelVisible()).toBe(true);
+ // Re-showing reuses the position that already matched, so the panel does not jump.
+ expect(editor.plugins.get(ContextualBalloon).view.position).toBe(position);
+ });
+
+ it("survives another plugin's balloon burying the panel", async () => {
+ const balloon = editor.plugins.get(ContextualBalloon);
+ const errors: unknown[] = [];
+ const onRejection = (event: PromiseRejectionEvent) => errors.push(event.reason);
+ window.addEventListener("unhandledrejection", onRejection);
+
+ type("#a");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ // `singleViewMode` hides every other stack, so the mention panel is still registered with
+ // the balloon but is no longer the visible view.
+ const other = new View(editor.locale);
+ other.setTemplate({ tag: "div" });
+ other.render();
+ balloon.add({ view: other, position: { target: document.body }, singleViewMode: true });
+ expect(isPanelVisible()).toBe(false);
+
+ // Refining the query must not try to add the panel a second time: `ContextualBalloon.add()`
+ // rejects an already-registered view outright, which is the `contextualballoon-add-view-exist`
+ // crash upstream's visibility-based guard walks into.
+ type("l");
+ await settle();
+
+ window.removeEventListener("unhandledrejection", onRejection);
+ expect(errors).toEqual([]);
+ expect(balloon.hasView(other)).toBe(true);
+ });
+
+ it("hides the panel on a click outside it", async () => {
+ type("#al");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+
+ expect(isPanelVisible()).toBe(false);
+ });
+
+ it("keeps the panel open when the click lands inside the balloon", async () => {
+ type("#al");
+ await settle();
+
+ const balloonElement = editor.plugins.get(ContextualBalloon).view.element;
+ balloonElement?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+
+ expect(isPanelVisible()).toBe(true);
+ });
+
+ it("positions the panel from the right in a right-to-left UI", async () => {
+ await createEditor({}, { language: { ui: "ar" } });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+ expect(editor.locale.uiLanguageDirection).toBe("rtl");
+
+ type("#al");
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ expect(editor.plugins.get(ContextualBalloon).view.position).toMatch(/^caret_/);
+ });
+
+ describe("Escape dismisses without touching the document", () => {
+ it("stays hidden across the next keystroke and inserts no sentinel character", async () => {
+ type("#al");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ pressKey(keyCodes.esc);
+ expect(isPanelVisible()).toBe(false);
+
+ // The regression the removed pnpm patch caused: dismissing used to insert a U+2002
+ // en-space, which the attribute lexer then folded into the attribute name.
+ const data = getModelData(editor.model, { withoutSelection: true });
+ expect(data).not.toContain(" ");
+ expect(data).toContain("#al");
+
+ // Upstream reopens here, because its text watcher re-evaluates and the pattern still matches.
+ type("p");
+ await settle();
+ expect(isPanelVisible()).toBe(false);
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alp");
+ });
+
+ it("reopens once the dismissed marker itself is retyped", async () => {
+ type("#al");
+ await settle();
+ pressKey(keyCodes.esc);
+
+ // Delete the whole marker, which sends the dismissal's live position to the graveyard.
+ editor.model.change((writer) => {
+ writer.remove(writer.createRangeIn(editor.model.document.getRoot()?.getChild(0) as never));
+ });
+
+ type("#be");
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ });
+
+ it("reopens once the block holding the dismissal is replaced wholesale", async () => {
+ setModelData(editor.model, "<paragraph></paragraph><paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+ pressKey(keyCodes.esc);
+
+ // One edit drops the dismissed paragraph — sending the dismissal's live position to the
+ // graveyard — and leaves a fresh marker matching in the block the caret ends up in. The
+ // text watcher sees a match, not an unmatch, so only the graveyard check can recover.
+ editor.model.change((writer) => {
+ const root = editor.model.document.getRoot();
+ const first = root?.getChild(0);
+ const second = root?.getChild(1);
+
+ if (first?.is("element") && second) {
+ writer.insertText("#be", writer.createPositionAt(first, 0));
+ writer.remove(second);
+ writer.setSelection(writer.createPositionAt(first, "end"));
+ }
+ });
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ });
+
+ it("reopens for a different marker typed after the dismissed one", async () => {
+ type("#al");
+ await settle();
+ pressKey(keyCodes.esc);
+
+ type(" #be");
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ });
+ });
+
+ describe("caret moves do not open the panel", () => {
+ it("stays closed when the caret is placed inside existing matching text", async () => {
+ setModelData(editor.model, "<paragraph>#alpha[]</paragraph>");
+
+ moveCaretTo(3);
+ await settle();
+
+ expect(isPanelVisible()).toBe(false);
+ expect(labelFeed).not.toHaveBeenCalled();
+ });
+
+ it("closes an open panel when the caret moves", async () => {
+ type("#al");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ moveCaretTo(1);
+ await settle();
+
+ expect(isPanelVisible()).toBe(false);
+ });
+ });
+
+ describe("commit keys", () => {
+ it("commits the pre-selected item on Enter by default", async () => {
+ type("#al");
+ await settle();
+
+ pressKey(keyCodes.enter);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
+ });
+
+ it("leaves Enter alone when preselectFirstItem is off and nothing is selected", async () => {
+ await createEditor({ preselectFirstItem: false });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ pressKey(keyCodes.enter);
+
+ // Still just the typed text — no suggestion was committed behind the user's back.
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#al<");
+ });
+
+ it("commits after the user arrows onto an item even when nothing was pre-selected", async () => {
+ await createEditor({ preselectFirstItem: false });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#");
+ await settle();
+
+ pressKey(keyCodes.arrowdown);
+ pressKey(keyCodes.enter);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
+ });
+
+ it("navigates the list with the arrow keys", async () => {
+ type("#");
+ await settle();
+
+ pressKey(keyCodes.arrowdown);
+ pressKey(keyCodes.arrowup);
+ pressKey(keyCodes.enter);
+
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
+ });
+
+ it("ignores unrelated keys while the panel is open", async () => {
+ type("#al");
+ await settle();
+
+ pressKey(keyCodes.a);
+
+ expect(isPanelVisible()).toBe(true);
+ });
+ });
+
+ describe("feed handling", () => {
+ it("hides the panel when the feed rejects", async () => {
+ await createEditor({ feed: vi.fn(async () => { throw new Error("boom"); }) as unknown as TriliumMentionFeed["feed"] });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+
+ expect(isPanelVisible()).toBe(false);
+ });
+
+ it("filters a static array feed case-insensitively", async () => {
+ await createEditor({ feed: [ "#Alpha", "#beta" ] });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ pressKey(keyCodes.enter);
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#Alpha");
+ });
+
+ it("honours dropdownLimit", async () => {
+ await createEditor({ dropdownLimit: 1 });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#");
+ await settle();
+
+ const items = editor.plugins.get(ContextualBalloon).visibleView?.element?.querySelectorAll("li");
+ expect(items?.length).toBe(1);
+ });
+
+ it("filters a static array feed of objects by id", async () => {
+ await createEditor({ feed: [ { id: "#Alpha", text: "#Alpha" }, { id: "#beta", text: "#beta" } ] });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ pressKey(keyCodes.enter);
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#Alpha");
+ });
+
+ it("anchors the panel to the caret when the marked text was undone away mid-request", async () => {
+ const resolvers: Array<(items: MentionFeedObjectItem[]) => void> = [];
+ await createEditor({
+ feed: (() => new Promise((resolve) => resolvers.push(resolve))) as unknown as TriliumMentionFeed["feed"]
+ });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ // The undos are invisible to the text watcher, so the in-flight request still resolves
+ // against a marker whose range has meanwhile been moved to the graveyard.
+ editor.execute("enter");
+ type("#al");
+ await settle();
+ editor.execute("undo");
+ editor.execute("undo");
+
+ resolvers[0]?.([ { id: "#alpha", text: "#alpha" } ]);
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ });
+
+ it("discards an out-of-order response", async () => {
+ const resolvers: Array<(items: MentionFeedObjectItem[]) => void> = [];
+ await createEditor({
+ feed: (() => new Promise((resolve) => resolvers.push(resolve))) as unknown as TriliumMentionFeed["feed"]
+ });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#a");
+ await settle();
+ type("l");
+ await settle();
+
+ // Answer the *first* request last; it must not repopulate the panel.
+ resolvers[1]?.([ { id: "#alpha", text: "#alpha" } ]);
+ resolvers[0]?.([ { id: "#stale", text: "#stale" } ]);
+ await settle();
+
+ pressKey(keyCodes.enter);
+ expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
+ });
+ });
+
+ it("does not re-trigger inside an existing mention", async () => {
+ type("#al");
+ await settle();
+ pressKey(keyCodes.enter);
+ await settle();
+
+ // The caret now sits right after a committed mention.
+ expect(isPanelVisible()).toBe(false);
+ });
+
+ it("does not open the panel for a caret parked inside an existing mention", async () => {
+ setModelData(editor.model, "<paragraph>[]</paragraph><paragraph></paragraph>");
+
+ type("#al");
+ await settle();
+ pressKey(keyCodes.enter);
+ await settle();
+ labelFeed.mockClear();
+
+ // Inside the committed "#alpha", where the text before the caret still reads "#al".
+ moveCaretTo(3);
+ await settle();
+
+ // An edit elsewhere re-evaluates that text, which must not be treated as a fresh query.
+ editor.model.change((writer) => {
+ const second = editor.model.document.getRoot()?.getChild(1);
+
+ if (second?.is("element")) {
+ writer.insertText("x", writer.createPositionAt(second, 0));
+ }
+ });
+ await settle();
+
+ expect(isPanelVisible()).toBe(false);
+ expect(labelFeed).not.toHaveBeenCalled();
+ });
+
+ it("tolerates being initialised before MentionEditing registers the mention command", async () => {
+ const feed = vi.fn(async () => [ { id: "#alpha", text: "#alpha" } ]);
+ editor = await createTestEditor([ Essentials, Paragraph, TriliumMentionUI, MentionEditing ], {
+ mention: { feeds: [ { marker: "#", feed: feed as unknown as TriliumMentionFeed["feed"], minimumCharacters: 0 } ] }
+ });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+
+ expect(isPanelVisible()).toBe(true);
+ });
+
+ it("hides the panel when the editor becomes read-only", async () => {
+ type("#al");
+ await settle();
+ expect(isPanelVisible()).toBe(true);
+
+ editor.enableReadOnlyMode("test");
+ expect(isPanelVisible()).toBe(false);
+
+ editor.disableReadOnlyMode("test");
+ });
+
+ it("renders a custom itemRenderer result", async () => {
+ await createEditor({
+ itemRenderer: (item) => {
+ const element = document.createElement("button");
+ element.classList.add("custom-mention-item");
+ element.textContent = String(item.id);
+
+ return element;
+ }
+ });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+
+ expect(editor.plugins.get(ContextualBalloon).visibleView?.element?.querySelector(".custom-mention-item")).toBeTruthy();
+ });
+
+ it("renders a string itemRenderer result as a button label", async () => {
+ await createEditor({ itemRenderer: (item) => `label:${item.id}` });
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
+
+ type("#al");
+ await settle();
+
+ expect(editor.plugins.get(ContextualBalloon).visibleView?.element?.textContent).toContain("label:#alpha");
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts
new file mode 100644
index 0000000000..893db56238
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts
@@ -0,0 +1,499 @@
+import {
+ ButtonView,
+ clickOutsideHandler,
+ Collection,
+ ContextualBalloon,
+ type DomOptimalPositionOptions,
+ type Editor,
+ keyCodes,
+ type Marker,
+ MentionDomWrapperView,
+ type MentionFeedObjectItem,
+ MentionListItemView,
+ MentionsView,
+ ModelLivePosition,
+ type ModelPosition,
+ Plugin,
+ Rect,
+ TextWatcher,
+ type ViewDocumentKeyDownEvent
+} from "ckeditor5";
+
+import { createMarkerPattern, findMarkerMatch, type MarkerMatch } from "./marker_pattern.js";
+import type { TriliumMentionFeed } from "./types.js";
+
+const VERTICAL_SPACING = 3;
+const MARKER_NAME = "mention";
+const FEED_DEBOUNCE_MS = 100;
+const DEFAULT_DROPDOWN_LIMIT = 10;
+
+/** A configured feed with its compiled trigger pattern. */
+type Pattern = TriliumMentionFeed & { pattern: RegExp };
+
+/**
+ * A drop-in replacement for CKEditor's `MentionUI` that fixes three behaviours we can neither
+ * configure nor subclass around, since every interesting member of `MentionUI` is `private`:
+ *
+ * 1. **Escape actually dismisses.** Upstream's Escape handler only removes the model marker, but its
+ * `TextWatcher` re-evaluates the text on the very next keystroke, the pattern still matches, and
+ * the panel reopens. Trilium worked around that by *inserting a ` ` en-space* into the document
+ * so the (also patched) pattern could no longer match — which corrupts data: the attribute lexer
+ * treats only U+0020 as a separator, so `#foo<en-space> #bar` fails to parse and the attribute
+ * list becomes unsaveable. Here dismissal is state ({@link #_dismissedAt}), not a document edit.
+ * 2. **The panel opens on typing only.** `TextWatcher` fires `matched:selection` on any direct caret
+ * move, and upstream listens to plain `matched`, so merely *clicking* into an existing `#myLabel`
+ * reopens the panel — and since it also pre-selects the first item, the Enter meant to save the
+ * attributes commits a suggestion instead.
+ * 3. **A stale query closes the panel.** See {@link createMarkerPattern}.
+ *
+ * Everything else — the balloon, the list views, the `mention` model attribute and its post-fixers,
+ * the `mention` command — is reused from upstream unchanged. This plugin replaces `MentionUI` only;
+ * pair it with `MentionEditing` rather than the `Mention` façade, which pulls in `MentionUI` too.
+ */
+export default class TriliumMentionUI extends Plugin {
+
+ private readonly _view: MentionsView;
+ private readonly _items = new Collection<{ item: MentionFeedObjectItem; marker: string }>();
+ private _patterns: Pattern[] = [];
+
+ private _balloon?: ContextualBalloon;
+ private _lastRequestedQuery?: string;
+ private _feedTimer?: ReturnType<typeof setTimeout>;
+
+ /**
+ * Where the marker of the panel the user dismissed with Escape sits, or `null` when nothing is
+ * dismissed. Live, so it follows edits and lands in the graveyard if the marker is deleted.
+ */
+ private _dismissedAt: ModelLivePosition | null = null;
+
+ static get pluginName() {
+ return "TriliumMentionUI" as const;
+ }
+
+ static get requires() {
+ return [ ContextualBalloon ];
+ }
+
+ constructor(editor: Editor) {
+ super(editor);
+
+ this._view = this._createView();
+ editor.config.define("mention", { feeds: [] });
+ }
+
+ init() {
+ const editor = this.editor;
+ this._balloon = editor.plugins.get(ContextualBalloon);
+
+ /* v8 ignore next -- the constructor defines `mention.feeds` as `[]`, so `get()` never returns undefined; the fallback only satisfies the optional return type */
+ const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
+ this._patterns = feeds.map((feed) => ({ ...feed, pattern: createMarkerPattern(feed.marker, feed) }));
+
+ editor.editing.view.document.on<ViewDocumentKeyDownEvent>("keydown", (evt, data) => {
+ if (this._isVisible && this._handleKeyDown(data.keyCode)) {
+ data.preventDefault();
+ evt.stop(); // Required to override the Enter key.
+ }
+ }, { priority: "highest" });
+
+ clickOutsideHandler({
+ emitter: this._view,
+ activator: () => this._isVisible,
+ /* v8 ignore next -- `clickOutsideHandler` only calls `contextElements()` once the activator reported the panel visible, and a visible balloon is a rendered one, so its element is never null */
+ contextElements: () => (this._balloon?.view.element ? [ this._balloon.view.element ] : []),
+ callback: () => this._hide()
+ });
+
+ this._setupTextWatcher();
+ this.listenTo(editor, "change:isReadOnly", () => this._hide());
+ }
+
+ override destroy() {
+ super.destroy();
+
+ clearTimeout(this._feedTimer);
+ this._clearDismissal();
+ // Balloon views are not destroyed automatically — see ckeditor5#1341.
+ this._view.destroy();
+ }
+
+ private get _isVisible() {
+ return this._balloon?.visibleView === this._view;
+ }
+
+ /**
+ * Returns whether the key was consumed. Commit keys are deliberately *not* consumed when nothing
+ * is selected, so that in the attribute editor — where `preselectFirstItem` is off — Enter still
+ * saves instead of being swallowed by an open panel.
+ */
+ private _handleKeyDown(keyCode: number): boolean {
+ if (keyCode === keyCodes.arrowdown) {
+ this._view.selectNext();
+ return true;
+ }
+
+ if (keyCode === keyCodes.arrowup) {
+ this._view.selectPrevious();
+ return true;
+ }
+
+ if (keyCode === keyCodes.esc) {
+ this._dismiss();
+ return true;
+ }
+
+ if (keyCode === keyCodes.enter || keyCode === keyCodes.tab) {
+ if (!this._view.selected) {
+ return false;
+ }
+
+ this._view.executeSelected();
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Hides the panel and remembers that the user rejected *this* marker, so it does not immediately
+ * reopen on the next keystroke. No document mutation is involved.
+ */
+ private _dismiss() {
+ const start = this.editor.model.markers.get(MARKER_NAME)?.getStart();
+
+ this._hide();
+
+ /* v8 ignore next -- Escape only reaches here while the panel is visible, and the panel and the marker always come and go together, so there is always a start */
+ if (start) {
+ this._clearDismissal();
+ this._dismissedAt = ModelLivePosition.fromPosition(start, "toPrevious");
+ }
+ }
+
+ private _clearDismissal() {
+ this._dismissedAt?.detach();
+ this._dismissedAt = null;
+ }
+
+ /**
+ * Whether `markerStart` is the marker the user already dismissed. A dismissal whose text has
+ * since been deleted (its live position landed in the graveyard) is discarded, so retyping the
+ * same marker opens the panel again.
+ */
+ private _isDismissed(markerStart: ModelPosition): boolean {
+ if (!this._dismissedAt) {
+ return false;
+ }
+
+ if (this._dismissedAt.root.rootName === "$graveyard") {
+ this._clearDismissal();
+ return false;
+ }
+
+ return this._dismissedAt.toPosition().isEqual(markerStart);
+ }
+
+ private _setupTextWatcher() {
+ const editor = this.editor;
+
+ // Returning the match object makes `TextWatcher` merge it into the event data, so the
+ // handler does not have to re-derive the block text and re-run the patterns.
+ const watcher = new TextWatcher(editor.model, (text) => findMarkerMatch(this._patterns, text) ?? false);
+
+ // Only typing opens the panel. `matched:selection` fires on any direct caret move — a click
+ // or an arrow key — and reopening there is the "clicking always triggers an autocomplete"
+ // bug; a caret move should close the panel, whose balloon is anchored to a marker the user
+ // has just navigated away from.
+ watcher.on<TriliumMatchedEvent>("matched:data", (evt, data) => this._onTyped(data));
+ watcher.on("matched:selection", () => this._hide());
+ watcher.on("unmatched", () => {
+ this._clearDismissal();
+ this._hide();
+ });
+
+ const command = editor.commands.get("mention");
+ if (command) {
+ watcher.bind("isEnabled").to(command);
+ }
+ }
+
+ private _onTyped({ feed, query }: MarkerMatch<Pattern>) {
+ const model = this.editor.model;
+ const focus = model.document.selection.focus;
+
+ /* v8 ignore next 3 -- the document selection of a live editor always has a focus; the guard only narrows the type for the `getShiftedBy()` calls below */
+ if (!focus) {
+ return;
+ }
+
+ const start = focus.getShiftedBy(-(feed.marker.length + query.length));
+ const end = focus.getShiftedBy(-query.length);
+
+ // Never re-trigger inside an existing mention — mirrors upstream's `isPositionInExistingMention`.
+ if (isInExistingMention(focus) || isBeforeExistingMention(start)) {
+ this._hide();
+ return;
+ }
+
+ if (this._isDismissed(start)) {
+ return;
+ }
+
+ const range = model.createRange(start, end);
+ const existing = model.markers.get(MARKER_NAME);
+
+ model.change((writer) => {
+ if (existing) {
+ writer.updateMarker(existing, { range });
+ } else {
+ writer.addMarker(MARKER_NAME, { range, usingOperation: false, affectsData: false });
+ }
+ });
+
+ this._lastRequestedQuery = query;
+ clearTimeout(this._feedTimer);
+ this._feedTimer = setTimeout(() => void this._requestFeed(feed, query), FEED_DEBOUNCE_MS);
+ }
+
+ private async _requestFeed(feed: TriliumMentionFeed, query: string) {
+ let items: Array<MentionFeedObjectItem | string>;
+
+ try {
+ items = typeof feed.feed === "function"
+ ? await feed.feed.call(this.editor, query)
+ : feed.feed.filter((item) => String(typeof item === "object" ? item.id : item).toLowerCase().includes(query.toLowerCase()));
+ } catch {
+ this._hide();
+ return;
+ }
+
+ // Drop out-of-order responses, and responses that arrived after the panel was dismissed or
+ // the marker went away.
+ if (this._lastRequestedQuery !== query || !this.editor.model.markers.has(MARKER_NAME)) {
+ return;
+ }
+
+ const limit = feed.dropdownLimit ?? this.editor.config.get("mention.dropdownLimit") ?? DEFAULT_DROPDOWN_LIMIT;
+
+ this._items.clear();
+ for (const item of items.slice(0, limit as number)) {
+ this._items.add({ item: typeof item === "object" ? item : { id: item, text: item }, marker: feed.marker });
+ }
+
+ if (!this._items.length) {
+ this._hide();
+ return;
+ }
+
+ this._show(feed);
+ }
+
+ private _show(feed: TriliumMentionFeed) {
+ const marker = this.editor.model.markers.get(MARKER_NAME);
+
+ /* v8 ignore next 3 -- `_requestFeed()` already returned unless the marker is still registered, and `_balloon` is assigned in `init()`; the guard only narrows both types */
+ if (!marker || !this._balloon) {
+ return;
+ }
+
+ // The add/update decision keys off *membership*, not visibility: `ContextualBalloon.add()`
+ // throws `contextualballoon-add-view-exist` for a view that is already registered in any
+ // stack, visible or not. Upstream's `MentionUI` branches on visibility here and so crashes
+ // as soon as another plugin's balloon (added with `singleViewMode`) buries the panel.
+ if (!this._balloon.hasView(this._view)) {
+ this._balloon.add({
+ view: this._view,
+ position: this._positionData(marker),
+ singleViewMode: true,
+ balloonClassName: "ck-mention-balloon"
+ });
+ } else if (this._isVisible) {
+ this._balloon.updatePosition(this._positionData(marker));
+ }
+
+ this._view.position = this._balloon.view.position;
+
+ // Pre-selecting the first item makes Enter always commit *something*. That is right for the
+ // note editor, but wrong in the attribute editor, where Enter means "save".
+ if (feed.preselectFirstItem ?? true) {
+ this._view.selectFirst();
+ } else {
+ this._view.selected?.removeHighlight();
+ this._view.selected = undefined;
+ }
+ }
+
+ private _hide() {
+ clearTimeout(this._feedTimer);
+
+ if (this._balloon?.hasView(this._view)) {
+ this._balloon.remove(this._view);
+ }
+
+ if (this.editor.model.markers.has(MARKER_NAME)) {
+ this.editor.model.change((writer) => writer.removeMarker(MARKER_NAME));
+ }
+
+ this._view.position = undefined;
+ }
+
+ private _createView(): MentionsView {
+ const locale = this.editor.locale;
+ const view = new MentionsView(locale);
+
+ view.items.bindTo(this._items).using(({ item, marker }) => {
+ const listItem = new MentionListItemView(locale);
+ const child = this._renderItem(item, marker);
+
+ child.delegate("execute").to(listItem);
+ listItem.children.add(child);
+ listItem.item = item;
+ listItem.marker = marker;
+ listItem.on("execute", () => view.fire("execute", { item, marker }));
+
+ return listItem;
+ });
+
+ view.on("execute", (evt, data) => {
+ const editor = this.editor;
+ const model = editor.model;
+ const marker = model.markers.get(MARKER_NAME);
+ const focus = model.document.selection.focus;
+
+ /* v8 ignore next 3 -- the list only fires "execute" while the panel is visible, which means the marker is registered, and a live selection always has a focus */
+ if (!marker || !focus) {
+ return;
+ }
+
+ // Replace everything from the marker up to the caret, not just the marker itself.
+ const range = model.createRange(model.createPositionAt(marker.getStart()), model.createPositionAt(focus));
+
+ this._hide();
+ this._clearDismissal();
+
+ const commit = this._patterns.find((feed) => feed.marker === data.marker)?.commit;
+
+ if (commit) {
+ // Drop the trigger text first so the callback sees a collapsed selection where the
+ // query used to be, and run it outside the change block — some callbacks open a
+ // balloon (`/math`, `/anchor`) rather than touching the model, which needs a settled
+ // view. Focus is restored *before* the callback for the same reason: one that opens
+ // a UI takes focus itself, and must do so last.
+ model.change((writer) => model.deleteContent(writer.createSelection(range)));
+ editor.editing.view.focus();
+ commit(editor, data.item);
+ } else {
+ editor.execute("mention", { mention: data.item, text: data.item.text, marker: data.marker, range });
+ editor.editing.view.focus();
+ }
+ });
+
+ return view;
+ }
+
+ private _renderItem(item: MentionFeedObjectItem, marker: string): MentionDomWrapperView | ButtonView {
+ const rendered = this._patterns.find((feed) => feed.marker === marker)?.itemRenderer?.(item);
+
+ if (rendered && typeof rendered !== "string") {
+ return new MentionDomWrapperView(this.editor.locale, rendered);
+ }
+
+ const button = new ButtonView(this.editor.locale);
+ button.label = rendered ?? item.id;
+ button.withText = true;
+
+ return button;
+ }
+
+ private _positionData(marker: Marker): Partial<DomOptimalPositionOptions> {
+ const editing = this.editor.editing;
+
+ return {
+ target: () => {
+ let range = marker.getRange();
+
+ // The marker may already be gone; fall back to the selection so ContextualBalloon
+ // can still place a panel here.
+ if (range.start.root.rootName === "$graveyard") {
+ /* v8 ignore next -- the document selection always holds at least one range, so the `?? range` arm never runs */
+ range = this.editor.model.document.selection.getFirstRange() ?? range;
+ }
+
+ const viewRange = editing.mapper.toViewRange(range);
+ const rects = Rect.getDomRangeRects(editing.view.domConverter.viewRangeToDom(viewRange));
+
+ return rects[rects.length - 1];
+ },
+ limiter: () => {
+ const editable = editing.view.document.selection.editableElement;
+
+ /* v8 ignore next -- the editing view selection is inside the root editable whenever the panel is positioned, so the `null` arm only satisfies the limiter's return type */
+ return editable ? editing.view.domConverter.mapViewToDom(editable.root) as HTMLElement : null;
+ },
+ positions: balloonPositions(this._view.position, this.editor.locale.uiLanguageDirection)
+ };
+ }
+}
+
+type TriliumMatchedEvent = {
+ name: "matched:data";
+ args: [ MarkerMatch<Pattern> & { text: string } ];
+};
+
+function isInExistingMention(position: ModelPosition): boolean {
+ // The text watcher runs before selection attributes are refreshed, so `selection.hasAttribute`
+ // is not usable here — see ckeditor5-engine#1723.
+ if (position.textNode?.hasAttribute("mention")) {
+ return true;
+ }
+
+ const before = position.nodeBefore;
+ return !!before && before.is("$text") && before.hasAttribute("mention");
+}
+
+function isBeforeExistingMention(markerPosition: ModelPosition): boolean {
+ const after = markerPosition.nodeAfter;
+ return !!after && after.is("$text") && after.hasAttribute("mention");
+}
+
+/**
+ * Balloon placement callbacks, anchored to the caret. Lifted from upstream's
+ * `getBalloonPanelPositions()`, which is module-private.
+ */
+function balloonPositions(preferred: string | undefined, uiLanguageDirection: string): DomOptimalPositionOptions["positions"] {
+ const positions: Record<string, DomOptimalPositionOptions["positions"][0]> = {
+ caret_se: (target) => ({
+ top: target.bottom + VERTICAL_SPACING,
+ left: target.right,
+ name: "caret_se",
+ config: { withArrow: false }
+ }),
+ caret_ne: (target, balloon) => ({
+ top: target.top - balloon.height - VERTICAL_SPACING,
+ left: target.right,
+ name: "caret_ne",
+ config: { withArrow: false }
+ }),
+ caret_sw: (target, balloon) => ({
+ top: target.bottom + VERTICAL_SPACING,
+ left: target.right - balloon.width,
+ name: "caret_sw",
+ config: { withArrow: false }
+ }),
+ caret_nw: (target, balloon) => ({
+ top: target.top - balloon.height - VERTICAL_SPACING,
+ left: target.right - balloon.width,
+ name: "caret_nw",
+ config: { withArrow: false }
+ })
+ };
+
+ // Stick to the position that already matched, so the panel does not jump as the list grows.
+ if (preferred && preferred in positions) {
+ return [ positions[preferred] ];
+ }
+
+ return uiLanguageDirection !== "rtl"
+ ? [ positions.caret_se, positions.caret_sw, positions.caret_ne, positions.caret_nw ]
+ : [ positions.caret_sw, positions.caret_se, positions.caret_nw, positions.caret_ne ];
+}
diff --git a/packages/ckeditor5/src/plugins/mention/types.ts b/packages/ckeditor5/src/plugins/mention/types.ts
new file mode 100644
index 0000000000..d6ac2dcff1
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/mention/types.ts
@@ -0,0 +1,48 @@
+import type { Editor, MentionFeedObjectItem } from "ckeditor5";
+import type { MentionFeed } from "ckeditor5";
+
+/**
+ * The extra per-feed knobs {@link TriliumMentionUI} understands, merged into upstream's
+ * `MentionFeed` so that `EditorConfig["mention"].feeds` accepts them directly at every call site.
+ *
+ * The augmentation targets `@ckeditor/ckeditor5-mention` rather than `ckeditor5`, because the
+ * umbrella package is a pure re-export barrel and augmenting it would declare a new interface
+ * instead of merging into the existing one. It lives in this module — reachable from the package
+ * entry point via the `TriliumMentionFeed` re-export — rather than in `augmentation.ts`, whose
+ * `declare global` block would then leak this package's narrower `glob` type into consumers.
+ */
+declare module "@ckeditor/ckeditor5-mention" {
+ interface MentionFeed {
+ /**
+ * Whether the query may contain spaces. Note titles do (`@My meeting notes`), attribute
+ * names never do — and allowing them there means `#foo bar baz` keeps matching forever, so
+ * the panel can never close on its own. Defaults to `false`.
+ */
+ allowSpaces?: boolean;
+
+ /**
+ * Whether the first suggestion is highlighted as soon as the panel opens, so that Enter
+ * commits it. Defaults to `true`, matching upstream. The attribute editor turns it off:
+ * there Enter means "save the attributes", and a panel that pre-selects an item silently
+ * hijacks it.
+ */
+ preselectFirstItem?: boolean;
+
+ /**
+ * What to do when the user picks an item, called with the trigger text (the marker and the
+ * query) already removed and the selection collapsed in its place.
+ *
+ * Feeds that omit it fall back to `editor.execute( "mention", … )`, which is what upstream
+ * always does and what the `@`/`#`/`~` feeds rely on. Feeds that insert something other than
+ * a mention — an emoji, a heading — provide it instead of piggy-backing on the `mention`
+ * command, so they neither depend on nor have to work around `CustomMentionCommand`.
+ */
+ commit?: ( editor: Editor, item: MentionFeedObjectItem ) => void;
+ }
+}
+
+/**
+ * A mention feed as {@link TriliumMentionUI} consumes it — an alias for the augmented `MentionFeed`
+ * that exists to name the Trilium-flavoured shape at call sites.
+ */
+export type TriliumMentionFeed = MentionFeed;
diff --git a/packages/ckeditor5/src/plugins/mention_customization.spec.ts b/packages/ckeditor5/src/plugins/mention_customization.spec.ts
index fdae624d30..250ac11499 100644
--- a/packages/ckeditor5/src/plugins/mention_customization.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention_customization.spec.ts
@@ -3,13 +3,14 @@ import {
_setModelData as setModelData,
ClassicEditor,
Essentials,
- Mention,
+ MentionEditing,
Paragraph
} from "ckeditor5";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../test/editor-kit.js";
import { installGlobMock } from "../../test/globals-test-kit.js";
+import TriliumMentionUI from "./mention/trilium_mention_ui.js";
import MentionCustomization from "./mention_customization.js";
import ReferenceLink from "./referencelink.js";
@@ -31,16 +32,18 @@ describe("MentionCustomization", () => {
editor = await createTestEditor([
Essentials,
Paragraph,
- Mention,
+ MentionEditing,
+ TriliumMentionUI,
ReferenceLink,
MentionCustomization
]);
});
- it("loads the plugin, requires Mention and overrides the mention command", () => {
+ it("loads the plugin, requires the mention editing/UI pair and overrides the mention command", () => {
expect(editor.plugins.get(MentionCustomization)).toBeInstanceOf(MentionCustomization);
expect(MentionCustomization.pluginName).toBe("MentionCustomization");
- expect(MentionCustomization.requires).toContain(Mention);
+ expect(MentionCustomization.requires).toContain(MentionEditing);
+ expect(MentionCustomization.requires).toContain(TriliumMentionUI);
expect(editor.commands.get("mention")).toBeDefined();
});
diff --git a/packages/ckeditor5/src/plugins/mention_customization.ts b/packages/ckeditor5/src/plugins/mention_customization.ts
index 6b844a5f61..6fff23ed0d 100644
--- a/packages/ckeditor5/src/plugins/mention_customization.ts
+++ b/packages/ckeditor5/src/plugins/mention_customization.ts
@@ -1,4 +1,6 @@
-import { Command, Mention, Plugin, ModelRange, type ModelSelectable } from "ckeditor5";
+import { Command, MentionEditing, Plugin, ModelRange, type ModelSelectable } from "ckeditor5";
+
+import TriliumMentionUI from "./mention/trilium_mention_ui.js";
/**
* Overrides the actions taken by the Mentions plugin (triggered by `@` in the text editor, or `~` & `#` in the attribute editor):
@@ -10,7 +12,7 @@ import { Command, Mention, Plugin, ModelRange, type ModelSelectable } from "cked
export default class MentionCustomization extends Plugin {
static get requires() {
- return [ Mention ];
+ return [ MentionEditing, TriliumMentionUI ];
}
public static get pluginName() {
diff --git a/packages/ckeditor5/src/theme/slash_commands.css b/packages/ckeditor5/src/theme/slash_commands.css
new file mode 100644
index 0000000000..139c750184
--- /dev/null
+++ b/packages/ckeditor5/src/theme/slash_commands.css
@@ -0,0 +1,67 @@
+/*
+ * Layout for the `/` command palette rows rendered by `TriliumSlashCommands`.
+ *
+ * Ported from the premium `SlashCommand` stylesheet, which we no longer load. The class names are
+ * kept identical on purpose: Trilium's own overrides in `apps/client/src/stylesheets/style.css` and
+ * in the Next theme already target them, and community (GPL) builds never loaded the premium CSS at
+ * all — so this also gives them a styled palette for the first time.
+ */
+
+:root {
+ --ck-slash-command-button-width: 250px;
+ --ck-slash-command-description-width: 200px;
+}
+
+.ck-mentions .ck.ck-button.ck-slash-command-button {
+ display: flex;
+ justify-content: flex-start;
+ width: var(--ck-slash-command-button-width);
+ padding: calc(0.2 * var(--ck-line-height-base) * var(--ck-font-size-base));
+
+ & .ck.ck-icon {
+ flex-shrink: 0;
+ box-sizing: initial;
+ margin: 0 var(--ck-spacing-small) 0 0;
+ padding: 5px;
+ border-radius: 2px;
+ color: var(--ck-color-base-text);
+ background-color: var(--ck-color-base-background);
+ }
+
+ & > .ck-slash-command-button__text-part {
+ display: flex;
+ flex-direction: column;
+ margin-left: var(--ck-spacing-small);
+
+ & > span {
+ width: var(--ck-slash-command-description-width);
+ overflow: hidden;
+ line-height: 1.2em;
+ text-overflow: ellipsis;
+ }
+
+ & > .ck-button__label {
+ font-weight: bold;
+ }
+
+ & > .ck-slash-command-button__description {
+ font-size: var(--ck-font-size-small);
+ opacity: 0.75;
+ }
+ }
+
+ &.ck-on > .ck-slash-command-button__text-part > span {
+ color: var(--ck-color-list-button-on-text);
+ }
+}
+
+[dir="rtl"] .ck-mentions .ck.ck-button.ck-slash-command-button {
+ & .ck.ck-icon {
+ margin: 0 0 0 var(--ck-spacing-small);
+ }
+
+ & > .ck-slash-command-button__text-part {
+ margin-right: var(--ck-spacing-small);
+ margin-left: 0;
+ }
+}
diff --git a/patches/@ckeditor__ckeditor5-mention.patch b/patches/@ckeditor__ckeditor5-mention.patch
deleted file mode 100644
index efb61721b5..0000000000
--- a/patches/@ckeditor__ckeditor5-mention.patch
+++ /dev/null
@@ -1,37 +0,0 @@
-diff --git a/dist/index.js b/dist/index.js
-index 2ad1db419fd67377a6ee0af0b76124891fdd6318..2dc0de85ffc625e2fb20a96effebca4c664f7fb1 100644
---- a/dist/index.js
-+++ b/dist/index.js
-@@ -595,7 +595,19 @@ var MentionUI = class extends Plugin {
- if (data.keyCode == keyCodes.arrowdown) this._mentionsView.selectNext();
- if (data.keyCode == keyCodes.arrowup) this._mentionsView.selectPrevious();
- if (commitKeys.includes(data.keyCode)) this._mentionsView.executeSelected();
-- if (data.keyCode == keyCodes.esc) this._hideUIAndRemoveMarker();
-+ if (data.keyCode == keyCodes.esc) {
-+ this._hideUIAndRemoveMarker();
-+
-+ editor.model.change(writer => {
-+ // insert a zero-width space as a special marker that we don't want a mention active anymore
-+ // see e.g. https://github.com/zadam/trilium/issues/4692
-+ const insertPosition = editor.model.document.selection.getLastPosition();
-+
-+ if (insertPosition !== null) {
-+ writer.insertText('\u2002', insertPosition);
-+ }
-+ });
-+ }
- }
- }, { priority: "highest" });
- clickOutsideHandler({
-@@ -979,9 +991,8 @@ function getLastValidMarkerInText(feedsWithPattern, text) {
- function createRegExp(marker, minimumCharacters) {
- const numberOfCharacters = minimumCharacters == 0 ? "*" : `{${minimumCharacters},}`;
- const openAfterCharacters = env.features.isRegExpUnicodePropertySupported ? "\\p{Ps}\\p{Pi}\"'" : "\\(\\[{\"'";
-- const mentionCharacters = ".";
-- marker = marker.replace(/[.*+?^${}()\-|[\]\\]/g, "\\$&");
-- const pattern = `(?:^|[ ${openAfterCharacters}])(${marker})(${mentionCharacters}${numberOfCharacters})$`;
-+ const mentionCharacters = "^=\u2002";
-+ const pattern = `(?:^|[= ${openAfterCharacters}])([${marker}])([${mentionCharacters}]${numberOfCharacters})$`;
- return new RegExp(pattern, "u");
- }
- /**
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7c35d045e5..0a6e168893 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -82,7 +82,6 @@ overrides:
extract-zip>yauzl: 3.4.0
patchedDependencies:
- '@ckeditor/ckeditor5-mention': 91c41ee286960cf306640d976142aa98e286415096d5731828d796ac574fdbe8
'@excalidraw/[email protected]': 859531a8ff622291b895d36bcd33e07ced6fcb3bcc90631ccaf776789b03f0c2
'@maplibre/[email protected]': c30b921f19820021e9c5c23d64378cbdf3dfba379cd4b5daff8a3f1f8b3578d5
[email protected]: 124bf3dd7f7c9674e69724570d6727af9dea5b99a30a56a6e4573a95c49c4402
@@ -14413,7 +14412,7 @@ snapshots:
dependencies:
'@ckeditor/ckeditor5-core': 48.3.1
'@ckeditor/ckeditor5-icons': 48.3.1
- '@ckeditor/ckeditor5-mention': 48.3.1(patch_hash=91c41ee286960cf306640d976142aa98e286415096d5731828d796ac574fdbe8)
+ '@ckeditor/ckeditor5-mention': 48.3.1
'@ckeditor/ckeditor5-typing': 48.3.1
'@ckeditor/ckeditor5-ui': 48.3.1
'@ckeditor/ckeditor5-utils': 48.3.1
@@ -14693,7 +14692,7 @@ snapshots:
'@ckeditor/ckeditor5-utils': 48.3.1
'@ckeditor/ckeditor5-widget': 48.3.1
- '@ckeditor/[email protected](patch_hash=91c41ee286960cf306640d976142aa98e286415096d5731828d796ac574fdbe8)':
+ '@ckeditor/[email protected]':
dependencies:
'@ckeditor/ckeditor5-core': 48.3.1
'@ckeditor/ckeditor5-engine': 48.3.1
@@ -14708,7 +14707,7 @@ snapshots:
'@ckeditor/ckeditor5-engine': 48.3.1
'@ckeditor/ckeditor5-icons': 48.3.1
'@ckeditor/ckeditor5-image': 48.3.1
- '@ckeditor/ckeditor5-mention': 48.3.1(patch_hash=91c41ee286960cf306640d976142aa98e286415096d5731828d796ac574fdbe8)
+ '@ckeditor/ckeditor5-mention': 48.3.1
'@ckeditor/ckeditor5-ui': 48.3.1
'@ckeditor/ckeditor5-utils': 48.3.1
'@ckeditor/ckeditor5-widget': 48.3.1
@@ -14842,7 +14841,7 @@ snapshots:
'@ckeditor/ckeditor5-core': 48.3.1
'@ckeditor/ckeditor5-heading': 48.3.1
'@ckeditor/ckeditor5-icons': 48.3.1
- '@ckeditor/ckeditor5-mention': 48.3.1(patch_hash=91c41ee286960cf306640d976142aa98e286415096d5731828d796ac574fdbe8)
+ '@ckeditor/ckeditor5-mention': 48.3.1
'@ckeditor/ckeditor5-style': 48.3.1
'@ckeditor/ckeditor5-template': 48.3.1
'@ckeditor/ckeditor5-ui': 48.3.1
@@ -21572,7 +21571,7 @@ snapshots:
'@ckeditor/ckeditor5-list': 48.3.1
'@ckeditor/ckeditor5-markdown-gfm': 48.3.1([email protected])
'@ckeditor/ckeditor5-media-embed': 48.3.1
- '@ckeditor/ckeditor5-mention': 48.3.1(patch_hash=91c41ee286960cf306640d976142aa98e286415096d5731828d796ac574fdbe8)
+ '@ckeditor/ckeditor5-mention': 48.3.1
'@ckeditor/ckeditor5-minimap': 48.3.1
'@ckeditor/ckeditor5-page-break': 48.3.1
'@ckeditor/ckeditor5-paragraph': 48.3.1
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index 58b00e128e..a5dcd40402 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -110,7 +110,6 @@ ignoredOptionalDependencies:
- "@anthropic-ai/claude-agent-sdk-*"
patchedDependencies:
- "@ckeditor/ckeditor5-mention": patches/@ckeditor__ckeditor5-mention.patch
'@maplibre/[email protected]': patches/@[email protected]
'@excalidraw/[email protected]': patches/@[email protected]