Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(text): list the slash commands with the autocomplete list
Elian Doran920143cecdc3
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex e95bf2cd54..2dd624b24f 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1898,24 +1898,17 @@ body.desktop .dropdown-submenu > .dropdown-menu {max-height: min(var(--ck-mention-list-max-height), var(--tn-mention-visible-height, 100vh));}-/* Slash commands */+/* Snippet form */-.ck.ck-slash-command-button {- padding: 0.5em 1em !important;-}--.ck.ck-slash-command-button__text-part,.ck.ck-template-form__text-part {margin-inline-start: 0.5em;line-height: 1.2em !important;}-.ck.ck-slash-command-button__text-part > span,.ck.ck-template-form__text-part > span {line-height: inherit !important;}-.ck.ck-slash-command-button__text-part .ck.ck-slash-command-button__description,.ck.ck-template-form__text-part .ck-template-form__description {display: block;opacity: 0.8;diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.cssindex d9f4d29309..9a2dbd24b7 100644--- a/apps/client/src/stylesheets/theme-next/notes/text.css+++ b/apps/client/src/stylesheets/theme-next/notes/text.css@@ -239,11 +239,6 @@ body.background-effects .ck.ck-balloon-panel.ck-dropdown-menu__nested-menu__panecolor: var(--menu-item-icon-color);}-/* Slash commands */-.ck.ck-slash-command-button__text-part .ck.ck-button__label {- font-weight: bold;-}-/* Separator */:root .ck .ck-list__separator {flex-shrink: 0;diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex ed5190a91f..cf02314ad9 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -1,6 +1,7 @@import "./FormAutocomplete.css";import type { ReferenceElement } from "@floating-ui/dom";+import clsx from "clsx";import type { ComponentChildren, RefObject } from "preact";import { type MutableRef, useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";@@ -184,23 +185,34 @@ export interface AutocompleteListHandle {/*** The dropdown of a {@link FormAutocomplete} for a query typed somewhere else, such as after a `#` in- * a text editor, which keeps the focus and forwards its keys through `handleRef`. It opens with- * nothing highlighted, so Enter stays with the host until an entry is arrowed to.+ * a text editor, which keeps the focus and forwards its keys through `handleRef`. Without+ * `autoActivate` it opens with nothing highlighted, so Enter stays with the host until an entry is+ * arrowed to.*/-export function AutocompleteList({ query, source, anchor, minWidth, renderItem, onPick, handleRef, elementRef }: {+export function AutocompleteList<T = string>({ query, source, schedule, anchor, minWidth, className, autoActivate, keyOf, textOf, renderItem, onPick, handleRef, elementRef }: {query: string;- source(query: string): Promise<string[]>;+ source(query: string): Promise<T[]>;+ /** See `useAutocomplete`'s `schedule`. */+ schedule?(lookUp: () => Promise<void>): void;anchor: DropdownAnchor;/** See {@link FormAutocompleteProps.dropdownMinWidth}. */minWidth?: number;- renderItem?(item: string): ComponentChildren;- onPick(item: string): void;+ /** A class for the dropdown, beside its own. */+ className?: string;+ /** See {@link FormAutocompleteProps.autoActivate}. */+ autoActivate?: boolean;+ /** Tells the entries apart, for an entry that is not a string. Defaults to `String(item)`. */+ keyOf?(item: T): string;+ /** See `useAutocomplete`'s `textOf`. */+ textOf?(item: T): string;+ renderItem?(item: T): ComponentChildren;+ onPick(item: T): void;handleRef: MutableRef<AutocompleteListHandle | null>;elementRef?: PopupProps["elementRef"];}) {// The focus stays where the query is typed, so there is no field to return it to.const inputRef = useRef<HTMLInputElement>(null);- const autocomplete = useAutocomplete({ query, source, onPick, inputRef });+ const autocomplete = useAutocomplete({ query, source, schedule, onPick, inputRef, autoActivate, textOf });// The host shows the list by mounting it and closes it by unmounting it.useEffect(() => autocomplete.open(), []);@@ -211,6 +223,8 @@ export function AutocompleteList({ query, source, anchor, minWidth, renderItem,autocomplete={autocomplete}anchor={anchor}minWidth={minWidth}+ className={className}+ keyOf={keyOf}renderItem={renderItem}elementRef={elementRef}/>@@ -243,12 +257,14 @@ export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocompl* The list of a {@link useAutocomplete}, in a {@link Popup} under `anchor`, which places it again as* the list or the anchor changes size or moves.*/-function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem, isHeading, elementRef }: {- autocomplete: ReturnType<typeof useAutocomplete<string>>;+function AutocompleteDropdown<T>({ autocomplete, anchor, minWidth = 0, className, keyOf = String, renderItem = String, isHeading, elementRef }: {+ autocomplete: ReturnType<typeof useAutocomplete<T>>;anchor: DropdownAnchor | null;minWidth?: number;- renderItem?(item: string): ComponentChildren;- isHeading?(item: string): boolean;+ className?: string;+ keyOf?(item: T): string;+ renderItem?(item: T): ComponentChildren;+ isHeading?(item: T): boolean;elementRef?: PopupProps["elementRef"];}) {const { isShown, items, activeIndex, itemId, pick } = autocomplete;@@ -260,7 +276,7 @@ function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem,return (<Popupanchor={anchor}- className="form-autocomplete-dropdown"+ className={clsx("form-autocomplete-dropdown", className)}elementRef={elementRef}// As wide as the field, or as `minWidth` where that is more.style={{ width: `${Math.max(anchor.getBoundingClientRect().width, minWidth)}px` }}@@ -274,11 +290,11 @@ function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem,>{items.map((item, index) => (isHeading?.(item)- ? <li key={item} className="form-autocomplete-heading" role="presentation">- {renderItem ? renderItem(item) : item}+ ? <li key={keyOf(item)} className="form-autocomplete-heading" role="presentation">+ {renderItem(item)}</li>: <li- key={item}+ key={keyOf(item)}id={itemId(index)}className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}role="option"@@ -286,7 +302,7 @@ function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem,onMouseMove={(e) => autocomplete.hover(index, e)}onClick={() => pick(item)}>- {renderItem ? renderItem(item) : item}+ {renderItem(item)}</li>))}</ul>diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 322921f89d..048889987e 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -18,7 +18,7 @@ import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";import diffAiResponse from "./ai_diff.js";import { buildFontColorConfig, buildTableColorConfig } from "./color_palette.js";-import { createMentionListView, createNoteMentionList } from "./mention_list_view.js";+import { createMentionListView, createNoteMentionList, createSlashCommandList } from "./mention_list_view.js";import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";import { buildToolbarConfig } from "./toolbar.js";@@ -203,7 +203,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi// Mermaid one (generic icon) and the list ones (Title Case titles, normalized to// sentence case).removeCommands: ["insertMermaidCommand", "bulletedList", "numberedList"],- dropdownLimit: Number.MAX_SAFE_INTEGER+ list: createSlashCommandList},snippets: {definitions: opts.templates@@ -313,7 +313,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfilist: () => createNoteMentionList({ allowCreatingNotes: true })}] : [],- // Draws the lists of the `/` and emoji feeds the plugins add.+ // Draws the list of the emoji feed the plugin adds.listView: createMentionListView};diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.css b/apps/client/src/widgets/type_widgets/text/mention_list_view.cssindex f5a56e4f4a..cc08a46647 100644--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.css+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.css@@ -1,5 +1,5 @@/*- * A feed's own rows (attribute names, `/` commands, emoji) are CKEditor buttons, which keep the+ * A feed's own rows (emoji) are CKEditor buttons, which keep the* padding and layout they have in CKEditor's balloon. The menu row draws the highlight, so the* button draws none: `!important` outranks CKEditor's `:hover`, `:focus` and `.ck-on` rules.*/@@ -27,3 +27,58 @@.mention-list-menu > .tn-menu-scroll {max-height: var(--ck-mention-list-max-height);}++/* The `/` palette is long, and the query only narrows it, so it is given more height than a field's list. */+.form-autocomplete-dropdown.slash-command-list > .form-autocomplete-list {+ max-height: var(--ck-mention-list-max-height);+}++.slash-command-list .slash-command {+ --slash-command-icon-size: calc(var(--ck-icon-size, 20px) * 0.8);+ display: flex;+ align-items: center;+ gap: 10px;+}++.slash-command-list .slash-command-icon {+ display: flex;+ flex-shrink: 0;+ align-items: center;+ justify-content: center;+ width: var(--slash-command-icon-size);+ height: var(--slash-command-icon-size);+ /* A snippet's font icon, a little inside the box an svg fills. */+ font-size: calc(var(--slash-command-icon-size) * 0.85);+ line-height: 1;++ & > svg {+ width: 100%;+ height: 100%;+ }++ /* As CKEditor's `ck-icon_inherit-color`: the icons draw in the text's colour. */+ & svg *:not([fill]) {+ fill: currentColor;+ }+}++.slash-command-list .slash-command-text {+ display: flex;+ flex-direction: column;+ min-width: 0;+ line-height: 1.2;+}++.slash-command-list :is(.slash-command-title, .slash-command-description) {+ overflow: hidden;+ text-overflow: ellipsis;+}++.slash-command-list .slash-command-title {+ font-weight: bold;+}++.slash-command-list .slash-command-description {+ font-size: 0.85em;+ opacity: 0.75;+}diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsxindex cedae373d6..1bab62b6bc 100644--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx@@ -1,4 +1,4 @@-import type { MentionHostedListState, MentionListState } from "@triliumnext/ckeditor5";+import type { MentionHostedListState, MentionListState, SlashCommandConfig, SlashCommandDefinition } from "@triliumnext/ckeditor5";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -13,7 +13,7 @@ vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({createNoteFromSuggestion}));-import { createAutocompleteMentionList, createMentionListView, createNoteMentionList } from "./mention_list_view";+import { createAutocompleteMentionList, createMentionListView, createNoteMentionList, createSlashCommandList } from "./mention_list_view";describe("createMentionListView", () => {const views: ReturnType<typeof createMentionListView>[] = [];@@ -36,7 +36,6 @@ describe("createMentionListView", () => {{ item: { id: "/heading" }, marker: "/", render: () => command },{ item: { id: "#plain" }, marker: "#", render: () => undefined }],- className: "ck-mention-list",selectedIndex: 0,caretRect: () => new DOMRect(10, 10, 1, 16),editable: null,@@ -61,7 +60,6 @@ describe("createMentionListView", () => {const menu = view.element;expect(menu?.className).toContain("dropdown-menu");expect(menu?.className).toContain("note-autocomplete-menu");- expect(menu?.classList.contains("ck-mention-list")).toBe(true);expect(rows().map((row) => row.classList.contains("tn-menu-active"))).toEqual([ true, false, false ]);// Each entry as its feed draws it, or by its id.@@ -225,3 +223,38 @@ describe("createAutocompleteMentionList", () => {list.destroy?.();});});++describe("createSlashCommandList", () => {+ const definitions: SlashCommandDefinition[] = [+ { id: "blockQuote", title: "Block quote", description: "Insert a quote.", icon: "<svg class=\"quote\"></svg>" },+ { id: "snippet-0", title: "Greeting", iconClass: "tn-icon bx bx-note", iconColorClass: "use-note-color" }+ ];++ it("lists the palette's entries for the query, opening on the first, and commits the one picked", async () => {+ const search = vi.fn(() => definitions);+ const editor = { plugins: { get: () => ({ search }) } } as unknown as Parameters<NonNullable<SlashCommandConfig["list"]>>[0];+ const list = createSlashCommandList(editor);+ const commit = vi.fn<MentionHostedListState["commit"]>();+ const key = (k: string) => list.handleKeyDown(new KeyboardEvent("keydown", { key: k, cancelable: true }));++ await act(async () => list.show({ query: "q", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ // The list opens, then looks its entries up at once, with no debounce to wait out.+ await act(async () => {});++ expect(search).toHaveBeenLastCalledWith("q");+ expect(list.element?.matches(".form-autocomplete-dropdown.slash-command-list")).toBe(true);+ const [ quote, greeting ] = [ ...(list.element?.querySelectorAll(".form-autocomplete-item") ?? []) ];+ expect(quote.classList.contains("active")).toBe(true);+ expect(quote.querySelector(".slash-command-icon > svg.quote")).not.toBeNull();+ expect(quote.querySelector(".slash-command-title")?.textContent).toBe("Block quote");+ expect(quote.querySelector(".slash-command-description")?.textContent).toBe("Insert a quote.");+ // A snippet's font icon, in its colour, and no description where it has none.+ expect(greeting.querySelector(".slash-command-icon.bx-note.use-note-color")).not.toBeNull();+ expect(greeting.querySelector(".slash-command-description")).toBeNull();++ await act(async () => { key("ArrowDown"); });+ expect(key("Enter")).toBe(true);+ expect(commit).toHaveBeenCalledExactlyOnceWith({ id: "snippet-0", definition: definitions[1] });+ list.destroy?.();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsxindex 8f759d783b..0cd020c2eb 100644--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx@@ -1,19 +1,23 @@import "./mention_list_view.css";-import type { MentionFeedObjectItem, MentionHostedList, MentionListEntry, MentionListState, MentionListView } from "@triliumnext/ckeditor5";+import type { MentionFeedObjectItem, MentionHostedList, MentionListEntry, MentionListState, MentionListView, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem, TriliumSlashCommands } from "@triliumnext/ckeditor5";import clsx from "clsx";import { type ComponentChildren, render } from "preact";import { useLayoutEffect, useRef } from "preact/hooks";import { AutocompleteList, type AutocompleteListHandle } from "../../react/FormAutocomplete";+import Icon from "../../react/Icon";import { NoteMentionList } from "../../react/NoteAutocomplete";import Popup from "../../react/Popup";+import RawHtml from "../../react/RawHtml";/** The least width of an {@link createAutocompleteMentionList} list, whose caret anchor has none. */const AUTOCOMPLETE_MENTION_MIN_WIDTH = 220;+/** The width of the `/` palette, which fits all but the longest descriptions. */+const SLASH_COMMAND_LIST_WIDTH = 350;/**- * Draws a text editor's suggestion list (`/` commands, emoji) as the note+ * Draws a text editor's suggestion list (emoji) as the note* autocomplete's menu, in a {@link Popup} at the caret, for the editor config's `mention.listView`.** `TriliumMentionUI` keeps everything but the drawing: when the list opens and closes, the keys, the@@ -140,6 +144,75 @@ export function createAutocompleteMentionList({ source, renderItem, toMention }:};}+/**+ * Lists the `/` palette's entries for the query as a form field's autocomplete lists its own, for the+ * editor config's `slashCommand.list`, opening on the best match so that Enter runs it.+ */+export function createSlashCommandList(editor: Parameters<NonNullable<SlashCommandConfig["list"]>>[0]): MentionHostedList {+ const palette = editor.plugins.get("TriliumSlashCommands") as TriliumSlashCommands;+ const source = async (query: string) => palette.search(query);+ const container = document.createElement("div");+ const handle: { current: AutocompleteListHandle | null } = { current: null };+ let element: HTMLElement | null = null;++ return {+ show(state) {+ render(<AutocompleteList<SlashCommandDefinition>+ query={state.query}+ source={source}+ schedule={lookUpNow}+ // A new anchor each time the query changes, so it is placed again at the caret.+ anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}+ minWidth={SLASH_COMMAND_LIST_WIDTH}+ className="slash-command-list"+ autoActivate+ keyOf={(definition) => definition.id}+ textOf={(definition) => definition.title}+ renderItem={(definition) => <SlashCommandRow definition={definition} />}+ onPick={(definition) => state.commit(toSlashCommandItem(definition))}+ handleRef={handle}+ elementRef={(el) => { element = el; }}+ />, container);+ },+ hide() {+ render(null, container);+ element = null;+ },+ handleKeyDown: (e) => handle.current?.handleKeyDown(e) ?? false,+ get element() {+ return element;+ },+ destroy() {+ render(null, container);+ element = null;+ }+ };+}++function toSlashCommandItem(definition: SlashCommandDefinition): SlashCommandItem {+ return { id: definition.id, definition };+}++/** Looks the palette's entries up at once: the catalog is in memory, so there is nothing to wait for. */+function lookUpNow(lookUp: () => Promise<void>) {+ void lookUp();+}++/** One entry of the `/` palette: its icon, its title and what it does. */+function SlashCommandRow({ definition }: { definition: SlashCommandDefinition }) {+ return (+ <span className="slash-command">+ {definition.iconClass+ ? <Icon className="slash-command-icon" icon={clsx(definition.iconClass, definition.iconColorClass)} />+ : <RawHtml className="slash-command-icon" html={definition.icon} />}+ <span className="slash-command-text">+ <span className="slash-command-title">{definition.title}</span>+ {definition.description && <span className="slash-command-description">{definition.description}</span>}+ </span>+ </span>+ );+}+/** The mention `MentionCustomization` turns into a reference link to `notePath`. */function toMention(notePath: string) {return { id: `@${notePath}`, notePath };@@ -167,7 +240,7 @@ function MentionMenu({ state, elementRef, scrollsToSelection, onPointerSelect }:anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}elementRef={elementRef}// The pointer moves the highlighted row, so `:hover` marks no second one.- className={clsx("dropdown-menu show tn-dropdown-menu tn-menu-keyboard note-autocomplete-menu mention-list-menu", state.className)}+ className="dropdown-menu show tn-dropdown-menu tn-menu-keyboard note-autocomplete-menu mention-list-menu"><menuref={menuRef}diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Slash Commands.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Slash Commands.htmlindex 084c432d23..1eee532043 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Slash Commands.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Slash Commands.html@@ -14,8 +14,9 @@and press the / key again.</li><li>Use ↑ and ↓ keys to navigate between options.</li><li>By default, the full list of commands is displayed.</li>- <li>To search by title or description, simply start typing for an action.</li>- <li>To trigger an action, press the Enter key.</li>+ <li>To search, simply start typing: commands are found by their title or by+ other names they go by (for example <code>h2</code> for <em>Heading 2</em>).</li>+ <li>To trigger the highlighted action, press Enter or Tab.</li></ul><h2>Integration with other features</h2><p>Apart from the common set of commands, some features are specially integrateddiff --git a/docs/User Guide/User Guide/Note Types/Text/Slash Commands.md b/docs/User Guide/User Guide/Note Types/Text/Slash Commands.mdindex b6d8ecba7e..23afa5cde3 100644--- a/docs/User Guide/User Guide/Note Types/Text/Slash Commands.md+++ b/docs/User Guide/User Guide/Note Types/Text/Slash Commands.md@@ -8,8 +8,8 @@ Slash commands is a feature of <a class="reference-link" href="../Text.md">Text* As the name suggests, to trigger the slash commands simply press the / key to trigger it. Note that this can be anywhere in a paragraph as long as it's not part of the word, if it doesn't show up simply press a space and press the / key again.* Use ↑ and ↓ keys to navigate between options.* By default, the full list of commands is displayed.-* To search by title or description, simply start typing for an action.-* To trigger an action, press the Enter key.+* To search, simply start typing: commands are found by their title or by other names they go by (for example `h2` for _Heading 2_).+* To trigger the highlighted action, press Enter or Tab.## Integration with other featuresdiff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 2f60289219..7613724fb3 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -17,7 +17,7 @@ export type { FileUploadData, FileUploadEvent } from "./plugins/file_upload/fileexport type { PasteTarget } from "./plugins/cuttonote.js";export type { ContentEmbedState } from "./plugins/content_embed/content_embed.js";export type { AttachmentLinkChange } from "./plugins/referencelink.js";-export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";+export type { default as TriliumSlashCommands, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem } from "./plugins/mention/slash_commands.js";export type { MentionHostedFeed, MentionHostedList, MentionHostedListState, MentionListEntry, MentionListState, MentionListView, TriliumMentionFeed } from "./plugins/mention/types.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";diff --git a/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts b/packages/ckeditor5/src/plugins/mention/register_feed.spec.tsindex ded150d07f..84d4684904 100644--- a/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts@@ -2,7 +2,7 @@ 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 { registerHostedMentionFeed, registerMentionFeed } from "./register_feed.js";import type { TriliumMentionFeed } from "./types.js";describe("registerMentionFeed", () => {@@ -46,3 +46,21 @@ describe("registerMentionFeed", () => {expect(warn).toHaveBeenCalledOnce();});});++describe("registerHostedMentionFeed", () => {+ it("appends to mention.hostedFeeds, and refuses a marker either kind of feed holds", async () => {+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});+ const list = () => ({ show() {}, hide() {}, handleKeyDown: () => false, element: null });+ const editor = await createTestEditor([ Essentials, Paragraph ], {+ mention: { feeds: [ { marker: "@", feed: [] } ], hostedFeeds: [ { marker: "#", list } ] }+ });++ registerHostedMentionFeed(editor, { marker: "/", list });+ registerHostedMentionFeed(editor, { marker: "@", list });+ registerHostedMentionFeed(editor, { marker: "/", list });++ expect(editor.config.get("mention.hostedFeeds")?.map((feed) => feed.marker)).toEqual([ "#", "/" ]);+ expect(warn).toHaveBeenCalledTimes(2);+ warn.mockRestore();+ });+});diff --git a/packages/ckeditor5/src/plugins/mention/register_feed.ts b/packages/ckeditor5/src/plugins/mention/register_feed.tsindex a488c43a63..5c764b3c07 100644--- a/packages/ckeditor5/src/plugins/mention/register_feed.ts+++ b/packages/ckeditor5/src/plugins/mention/register_feed.ts@@ -1,6 +1,6 @@import type { Editor } from "ckeditor5";-import type { TriliumMentionFeed } from "./types.js";+import type { MentionHostedFeed, TriliumMentionFeed } from "./types.js";/*** Appends a feed to `mention.feeds`, creating the entry when the host application configured none.@@ -15,12 +15,33 @@ import type { TriliumMentionFeed } from "./types.js";* shadow the other.*/export function registerMentionFeed(editor: Editor, feed: TriliumMentionFeed): void {+ if (isMarkerTaken(editor, feed.marker)) {+ return;+ }+const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];+ editor.config.set("mention.feeds", [ ...feeds, feed ]);+}- if (feeds.some((existing) => existing.marker === feed.marker)) {- console.warn(`[trilium-mention] the "${feed.marker}" marker is already registered; ignoring the duplicate feed.`);+/** {@link registerMentionFeed} for a feed whose list the host runs, in `mention.hostedFeeds`. */+export function registerHostedMentionFeed(editor: Editor, feed: MentionHostedFeed): void {+ if (isMarkerTaken(editor, feed.marker)) {return;}- editor.config.set("mention.feeds", [ ...feeds, feed ]);+ const feeds = editor.config.get("mention.hostedFeeds") ?? [];+ editor.config.set("mention.hostedFeeds", [ ...feeds, feed ]);+}++/** Whether a feed of either kind has `marker` already, which is then warned about. */+function isMarkerTaken(editor: Editor, marker: string) {+ const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];+ const hostedFeeds = editor.config.get("mention.hostedFeeds") ?? [];++ if ([ ...feeds, ...hostedFeeds ].some((existing) => existing.marker === marker)) {+ console.warn(`[trilium-mention] the "${marker}" marker is already registered; ignoring the duplicate feed.`);+ return true;+ }++ return false;}diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.tsindex 0e6689367c..d6d3a5f498 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.spec.ts@@ -3,7 +3,6 @@ import {BlockQuote,BookmarkUI,type ClassicEditor,- ContextualBalloon,type Editor,Essentials,_getModelData as getModelData,@@ -38,11 +37,45 @@ import TriliumSlashCommands, {type SlashCommandDefinition} from "./slash_commands.js";import TriliumMentionUI from "./trilium_mention_ui.js";-import type { TriliumMentionFeed } from "./types.js";+import type { MentionHostedFeed, MentionHostedList } from "./types.js";/** Longer than the mention UI's 100 ms feed debounce. */const AFTER_DEBOUNCE = 160;+/** The query the stub list last showed the palette for, or `null` while it is hidden. */+let shownQuery: string | null = null;++/**+ * A host's list for `slashCommand.list`, as the client's behaves for these tests: it lists the+ * palette's entries for the query as it is shown, and takes the first on Enter.+ */+function createStubList(editor: Editor): MentionHostedList {+ let commit: ((item: { id: string; definition: SlashCommandDefinition }) => void) | null = null;+ let entries: SlashCommandDefinition[] = [];++ return {+ show(state) {+ shownQuery = state.query;+ commit = state.commit;+ entries = editor.plugins.get(TriliumSlashCommands).search(state.query);+ },+ hide() {+ shownQuery = null;+ commit = null;+ entries = [];+ },+ handleKeyDown(event) {+ const [ first ] = entries;+ if (event.key !== "Enter" || !commit || !first) {+ return false;+ }+ commit({ id: first.id, definition: first });+ return true;+ },+ element: null+ };+}+const HEADING_OPTIONS = [{ model: "paragraph", title: "Paragraph" },{ model: "heading2", view: "h2", title: "Heading 2" },@@ -91,31 +124,23 @@ describe("TriliumSlashCommands", () => {async function createEditor(slashCommand: SlashCommandConfig = {}) {editor = await createTestEditor([ Essentials, Paragraph, Heading, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],- { heading: { options: HEADING_OPTIONS }, slashCommand }+ { heading: { options: HEADING_OPTIONS }, slashCommand: { list: createStubList, ...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;+ function slashFeed(): MentionHostedFeed | undefined {+ return editor.config.get("mention.hostedFeeds")?.find((candidate) => candidate.marker === "/");}- async function queryPalette(query: string) {- const feed = slashFeed().feed;-- if (typeof feed !== "function") {- throw new Error("the `/` feed should be a callback");- }+ /** The ids of the palette's entries for `query`, as its list shows them. */+ function paletteIds(query: string) {+ return editor.plugins.get(TriliumSlashCommands).search(query).map((definition) => definition.id);+ }- return await feed.call(editor, query);+ function paletteTitles(query: string) {+ return editor.plugins.get(TriliumSlashCommands).search(query).map((definition) => definition.title);}function type(text: string) {@@ -124,9 +149,10 @@ describe("TriliumSlashCommands", () => {});}- function pressKey(keyCode: number) {+ function pressEnter() {editor.editing.view.document.fire("keydown", {- keyCode,+ keyCode: keyCodes.enter,+ domEvent: new KeyboardEvent("keydown", { key: "Enter" }),preventDefault: () => {},stopPropagation: () => {},domTarget: editor.editing.view.getDomRoot()@@ -138,21 +164,26 @@ describe("TriliumSlashCommands", () => {}beforeEach(async () => {+ shownQuery = null;await createEditor();});- it("registers itself and a `/` feed that opens on the bare marker", () => {+ it("registers itself and a `/` feed that opens on the bare marker, in the host's list", async () => {expect(TriliumSlashCommands.pluginName).toBe("TriliumSlashCommands");expect(editor.plugins.get(TriliumSlashCommands)).toBeInstanceOf(TriliumSlashCommands);- expect(slashFeed().minimumCharacters).toBe(0);- });+ expect(slashFeed()?.minimumCharacters).toBe(0);+ expect(slashFeed()?.list).toBe(createStubList);- it("shows the palette unbounded by default, since the query only ever narrows it", async () => {- // Premium defaulted to `Infinity`; a cap would hide entries no query could then reach.- expect(slashFeed().dropdownLimit).toBe(Infinity);+ type("/quo");+ await settle();+ expect(shownQuery).toBe("quo");+ });- await createEditor({ dropdownLimit: 3 });- expect(slashFeed().dropdownLimit).toBe(3);+ it("registers no feed for a host that gives it no list", async () => {+ editor = await createTestEditor([ Essentials, Paragraph, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]);+ expect(slashFeed()).toBeUndefined();+ // The catalog is still there to be searched.+ expect(paletteIds("")).not.toEqual([]);});describe("catalog", () => {@@ -193,13 +224,13 @@ describe("TriliumSlashCommands", () => {// ...and of the command-backed ones, only the one whose plugin is actually loaded// survives the catalog.- const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);- expect(ids).toContain("/blockQuote");- expect(ids).not.toContain("/codeBlock");- expect(ids.filter((id) => id.startsWith("/heading"))).toEqual([]);+ const ids = paletteIds("");+ expect(ids).toContain("blockQuote");+ expect(ids).not.toContain("codeBlock");+ expect(ids.filter((id) => id.startsWith("heading"))).toEqual([]);// Trilium's own execute-only entries have no command to gate them, so they stay.- expect(ids).toContain("/align-left");+ expect(ids).toContain("align-left");});it("uses a generic icon for a heading level outside h1-h6", async () => {@@ -212,21 +243,21 @@ describe("TriliumSlashCommands", () => {});it("hides entries whose command no plugin registered", async () => {- const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);+ const ids = paletteIds("");// 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");+ 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);+ const ids = paletteIds("");- expect(ids).not.toContain("/blockQuote");- expect(ids).not.toContain("/heading3");- expect(ids).toContain("/heading2");+ expect(ids).not.toContain("blockQuote");+ expect(ids).not.toContain("heading3");+ expect(ids).toContain("heading2");});it("hides an entry whose command is registered but disabled for the current selection", async () => {@@ -236,15 +267,15 @@ describe("TriliumSlashCommands", () => {throw new Error("the editor should register the blockQuote command");}- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/blockQuote");+ expect(paletteIds("")).toContain("blockQuote");// Committing an entry first deletes the `/query`, so an entry whose command would no-op// costs the user their input and returns nothing.blockQuote.forceDisabled("spec");- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).not.toContain("/blockQuote");+ expect(paletteIds("")).not.toContain("blockQuote");blockQuote.clearForceDisabled("spec");- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/blockQuote");+ expect(paletteIds("")).toContain("blockQuote");});it("honours an entry's own isEnabled predicate, which is the only gate an execute-only entry has", () => {@@ -259,14 +290,14 @@ describe("TriliumSlashCommands", () => {});it("orders the catalog as CKEditor's own entries, then Trilium's, then the snippets", async () => {- const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);+ const ids = paletteIds("");// The heading entries lead the defaults; Trilium's own group follows them. Only// execute-only entries are compared, since anything naming a command whose plugin this// editor does not load is filtered out before ordering matters.- expect(ids[0]).toBe("/paragraph");- expect(ids.indexOf("/blockQuote")).toBeLessThan(ids.indexOf("/align-left"));- expect(ids.indexOf("/align-left")).toBeLessThan(ids.indexOf("/anchor"));+ expect(ids[0]).toBe("paragraph");+ expect(ids.indexOf("blockQuote")).toBeLessThan(ids.indexOf("align-left"));+ expect(ids.indexOf("align-left")).toBeLessThan(ids.indexOf("anchor"));});});@@ -286,7 +317,7 @@ describe("TriliumSlashCommands", () => {// The entry runs a file picker rather than naming the command, so `commandName` cannot// gate it and `isEnabled` has to.expect(isSlashCommandEnabled(editor, uploadEntry(editor))).toBe(false);- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).not.toContain("/uploadImage");+ expect(paletteIds("")).not.toContain("uploadImage");editor = await createTestEditor([ Essentials, Paragraph, Image, ImageUpload, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]@@ -294,7 +325,7 @@ describe("TriliumSlashCommands", () => {setModelData(editor.model, "<paragraph>[]</paragraph>");expect(isSlashCommandEnabled(editor, uploadEntry(editor))).toBe(true);- expect((await queryPalette("")).map((item) => (item as { id: string }).id)).toContain("/uploadImage");+ expect(paletteIds("")).toContain("uploadImage");});it("uploads only the picked files whose type `image.upload.types` allows", async () => {@@ -376,7 +407,7 @@ describe("TriliumSlashCommands", () => {async function createSnippetEditor(definitions: SnippetDefinition[] = SNIPPETS) {editor = await createTestEditor([ Essentials, Paragraph, Heading, BlockQuote, MentionEditing, TriliumMentionUI, TriliumSlashCommands, TriliumSnippets ],- { heading: { options: HEADING_OPTIONS }, toolbar: [], slashCommand: {}, snippets: { definitions } }+ { heading: { options: HEADING_OPTIONS }, toolbar: [], slashCommand: { list: createStubList }, snippets: { definitions } });setModelData(editor.model, "<paragraph>[]</paragraph>");}@@ -384,19 +415,19 @@ describe("TriliumSlashCommands", () => {it("lists each snippet after the built-ins, found by its title or the generic aliases", async () => {await createSnippetEditor();- const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);- expect(ids.slice(-2)).toEqual([ "/snippet-0", "/snippet-1" ]);+ const ids = paletteIds("");+ expect(ids.slice(-2)).toEqual([ "snippet-0", "snippet-1" ]);- expect((await queryPalette("greet")).map((item) => (item as { text: string }).text)).toEqual([ "Greeting" ]);+ expect(paletteTitles("greet")).toEqual([ "Greeting" ]);- const byAlias = (await queryPalette("snippet")).map((item) => (item as { text: string }).text);+ const byAlias = paletteTitles("snippet");expect(byAlias).toContain("Greeting");expect(byAlias).toContain("Signature");});it("offers no snippet entries in an editor without the snippets plugin", async () => {- const ids = (await queryPalette("")).map((item) => (item as { id: string }).id);- expect(ids.some((id) => id.startsWith("/snippet-"))).toBe(false);+ const ids = paletteIds("");+ expect(ids.some((id) => id.startsWith("snippet-"))).toBe(false);});it("inserts the snippet content on commit, for string and callback data alike", async () => {@@ -404,18 +435,18 @@ describe("TriliumSlashCommands", () => {type("/greeting");await settle();- pressKey(keyCodes.enter);+ pressEnter();let data = getModelData(editor.model, { withoutSelection: true });expect(data).toContain("Hello there");- expect(data).not.toContain("/greeting");+ expect(data).not.toContain("greeting");// A fresh empty paragraph: right after the inserted content the slash would be// mid-word, and a mid-word `/` deliberately never opens the palette.setModelData(editor.model, "<paragraph>[]</paragraph>");type("/signature");await settle();- pressKey(keyCodes.enter);+ pressEnter();data = getModelData(editor.model, { withoutSelection: true });expect(data).toContain("Sincerely, spec");@@ -426,7 +457,7 @@ describe("TriliumSlashCommands", () => {editor.plugins.get(TriliumSnippets).updateDefinitions([ { title: "Renamed", data: "<p>x</p>" } ]);- const titles = (await queryPalette("")).map((item) => (item as { text: string }).text);+ const titles = paletteTitles("");expect(titles).toContain("Renamed");expect(titles).not.toContain("Greeting");});@@ -440,7 +471,7 @@ describe("TriliumSlashCommands", () => {}insertTemplate.forceDisabled("spec");- expect((await queryPalette("")).map((item) => (item as { text: string }).text)).not.toContain("Greeting");+ expect(paletteTitles("")).not.toContain("Greeting");});});@@ -449,11 +480,11 @@ describe("TriliumSlashCommands", () => {type("/quo");await settle();- pressKey(keyCodes.enter);+ pressEnter();const data = getModelData(editor.model, { withoutSelection: true });expect(data).toContain("<blockQuote>");- expect(data).not.toContain("/quo");+ expect(data).not.toContain("quo");});// The alignment entries are execute-only — they run `alignment` with an argument rather than@@ -462,7 +493,8 @@ describe("TriliumSlashCommands", () => {// Alignment has to be loaded for its command to exist; the entry itself names no// command, so it is the `execute` callback that reaches it.editor = await createTestEditor(- [ Essentials, Paragraph, Alignment, MentionEditing, TriliumMentionUI, TriliumSlashCommands ]+ [ Essentials, Paragraph, Alignment, MentionEditing, TriliumMentionUI, TriliumSlashCommands ],+ { slashCommand: { list: createStubList } });setModelData(editor.model, "<paragraph>[]</paragraph>");const execute = vi.spyOn(editor, "execute");@@ -470,7 +502,7 @@ describe("TriliumSlashCommands", () => {// One word, since the `/` marker pattern stops at a space.type("/Justify");await settle();- pressKey(keyCodes.enter);+ pressEnter();expect(execute).toHaveBeenCalledWith("alignment", { value: "justify" });});@@ -480,7 +512,7 @@ describe("TriliumSlashCommands", () => {await settle();// "Heading 2" is the first configured level, so it is the pre-selected suggestion.- pressKey(keyCodes.enter);+ pressEnter();expect(getModelData(editor.model, { withoutSelection: true })).toContain("<heading2>");});@@ -499,79 +531,11 @@ describe("TriliumSlashCommands", () => {}blockQuote.forceDisabled("spec");- pressKey(keyCodes.enter);+ pressEnter();const data = getModelData(editor.model, { withoutSelection: true });expect(data).not.toContain("<blockQuote>");- expect(data).toContain("/quo");- });- });-- 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");- // Opts into core's `fill: currentColor` rule; without it the glyphs stay black on dark themes.- expect(row.querySelector(".ck-icon")?.classList.contains("ck-icon_inherit-color")).toBe(true);- expect(row.querySelector(".ck-button__label")?.textContent).toBe("Block quote");- expect(row.querySelector(".ck-slash-command-button__description")?.textContent).toBeTruthy();- });-- 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("renders a font-icon chip from iconClass, with and without a colour class", () => {- const renderer = slashFeed().itemRenderer;-- if (!renderer) {- throw new Error("the `/` feed should provide an itemRenderer");- }-- const coloured: SlashCommandDefinition = {- id: "snippet-0", title: "Greeting", iconClass: "tn-icon bx bx-note", iconColorClass: "use-note-color"- };- const colourless: SlashCommandDefinition = { id: "snippet-1", title: "Plain", iconClass: "bx bx-cube" };-- for (const definition of [ coloured, colourless ]) {- const row = renderer({ id: `/${definition.id}`, text: definition.title, definition } as never) as HTMLElement;- const chip = row.querySelector(".ck-icon");-- expect(chip?.classList.contains("ck-slash-command-button__note-icon")).toBe(true);- expect(chip?.querySelector("svg")).toBeNull();- }-- const colouredRow = renderer({ id: "/snippet-0", text: "Greeting", definition: coloured } as never) as HTMLElement;- // The glyph classes go on an inner span, not the chip: the chip's box is sized in em of- // its own font-size, so carrying the enlarged glyph font itself would inflate the row.- const glyph = colouredRow.querySelector(".ck-icon > span");- for (const cls of [ "tn-icon", "bx", "bx-note", "use-note-color" ]) {- expect(glyph?.classList.contains(cls)).toBe(true);- }+ expect(data).toContain("quo");});});@@ -579,8 +543,7 @@ describe("TriliumSlashCommands", () => {type("and/or");await settle();- const balloon = editor.plugins.get(ContextualBalloon);- expect(balloon.visibleView?.element?.classList.contains("ck-mentions") ?? false).toBe(false);+ expect(shownQuery).toBeNull();});});diff --git a/packages/ckeditor5/src/plugins/mention/slash_commands.ts b/packages/ckeditor5/src/plugins/mention/slash_commands.tsindex d7a0ce6ec7..5c41888a88 100644--- a/packages/ckeditor5/src/plugins/mention/slash_commands.ts+++ b/packages/ckeditor5/src/plugins/mention/slash_commands.ts@@ -1,5 +1,3 @@-import "../../theme/slash_commands.css";-import {IconAlignCenter,IconAlignJustify,@@ -55,7 +53,8 @@ import MathUI from "../math/math_ui.js";import { INSERT_MERMAID_COMMAND } from "../mermaid/insert_mermaid_command.js";import type { MermaidSample } from "../mermaid/mermaid_ui.js";import SnippetsEditing from "../snippets/snippetsediting.js";-import { registerMentionFeed } from "./register_feed.js";+import { registerHostedMentionFeed } from "./register_feed.js";+import type { MentionHostedList } from "./types.js";export const SLASH_MARKER = "/";@@ -93,12 +92,19 @@ export interface SlashCommandDefinition {export interface SlashCommandConfig {removeCommands?: string[];- /** How many entries the palette shows at once. Unlimited by default, as premium's was. */- dropdownLimit?: number;+ /**+ * The host's list of the palette, which lists {@link TriliumSlashCommands.search} for the query+ * and commits the entry picked as a {@link SlashCommandItem}. Without it there is no palette.+ */+ list?: ( editor: Editor ) => MentionHostedList;}+/** What a palette's list commits for the entry picked. */+export type SlashCommandItem = MentionFeedObjectItem & { definition: SlashCommandDefinition };+/**- * The `/` command palette, hosted on {@link TriliumMentionUI}.+ * The `/` command palette: its catalog, its matcher and what an entry runs, for the list the host+ * draws in `slashCommand.list`, which {@link TriliumMentionUI} runs as a hosted feed.** 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@@ -107,8 +113,7 @@ export interface SlashCommandConfig {* 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.+ * not a workaround but the same architecture.*/export default class TriliumSlashCommands extends Plugin {@@ -119,22 +124,28 @@ export default class TriliumSlashCommands extends Plugin {constructor(editor: Editor) {super(editor);- registerMentionFeed(editor, {+ const list = editor.config.get("slashCommand.list");+ if (!list) {+ return;+ }++ registerHostedMentionFeed(editor, {marker: SLASH_MARKER,// A bare `/` opens the full palette, as the premium plugin did.minimumCharacters: 0,- // Premium defaulted this to `Infinity` and let the panel scroll. Capping it would hide- // entries the user cannot then reach, since the query only narrows the list.- dropdownLimit: (editor.config.get("slashCommand.dropdownLimit") as number | undefined) ?? Infinity,- feed: (query: string) => matchSlashCommands(this._catalog(), query).map(toFeedItem),- itemRenderer: (item) => renderRow(item as SlashCommandItem),+ list,// The catalog gates on `isEnabled` at query time, but an entry can go stale while the- // panel is open; re-check here so a no-op commit never costs the user their `/query`.+ // list is open; re-check here so a no-op commit never costs the user their `/query`.canCommit: (editorInstance, item) => isSlashCommandEnabled(editorInstance, (item as SlashCommandItem).definition),commit: (editorInstance, item) => runSlashCommand(editorInstance, (item as SlashCommandItem).definition)});}+ /** The entries for what was typed after the `/`, best match first. */+ search(query: string): SlashCommandDefinition[] {+ return matchSlashCommands(this._catalog(), query);+ }+/*** The definitions available in *this* editor right now: the palette CKEditor's own features* contribute, Trilium's own entries, and one per text snippet — minus anything `removeCommands`@@ -185,13 +196,6 @@ export function isSlashCommandEnabled(editor: Editor, definition: SlashCommandDereturn editor.commands.get(definition.commandName)?.isEnabled ?? false;}-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);@@ -768,61 +772,3 @@ function createImageTypeRegExp(types: string[]): RegExp {return new RegExp(`^image\\/(${regExpSafeNames.join("|")})$`);}--/**- * 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");-- if (definition.iconClass) {- // A snippet note's font icon: the same chip, painted by icon-font classes instead of SVG.- // The glyph lives on an inner span: core sizes the chip box in em against the chip's own- // font-size, so enlarging the glyph's font on the chip itself would inflate the chip too.- icon.classList.add("ck-slash-command-button__note-icon");- const glyph = document.createElement("span");- for (const classList of [ definition.iconClass, definition.iconColorClass ]) {- if (classList) {- glyph.classList.add(...classList.split(/\s+/).filter(Boolean));- }- }- icon.append(glyph);- } else if (definition.icon) {- // `ck-icon_inherit-color` opts into core's `*:not([fill]) { fill: currentColor }` rule, as- // `IconView` does — without it the glyphs keep SVG's default black fill on dark themes.- icon.classList.add("ck-icon_inherit-color");- icon.innerHTML = definition.icon;- }-- button.append(icon);-- const textPart = document.createElement("span");- 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.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.tsindex 8501575365..6d5c9d54d7 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts@@ -32,8 +32,6 @@ const MARKER_NAME = "mention";const FEED_DEBOUNCE_MS = 100;const DEFAULT_DROPDOWN_LIMIT = 10;-/** See {@link MentionListState.className}, which `slash_commands.css` styles the `/` rows under. */-const MENTION_LIST_CLASS = "ck-mention-list";/** A configured feed with its compiled trigger pattern. */type Pattern = TriliumMentionFeed & { pattern: RegExp };@@ -479,7 +477,7 @@ export default class TriliumMentionUI extends Plugin {return new DOMRect(left, top, width, height);},editable: this.editor.editing.view.getDomRoot() ?? null,- commit: (item) => this._commitHosted(feed.marker, item)+ commit: (item) => this._commitHosted(feed, item)});}@@ -490,10 +488,10 @@ export default class TriliumMentionUI extends Plugin {}/**- * Replaces the trigger text with a mention of `item`. For a promise, the text stays where it is,- * followed by a live range, until it settles.+ * Replaces the trigger text with a mention of `item`, or hands `item` to the feed's `commit`.+ * For a promise, the text stays where it is, followed by a live range, until it settles.*/- private _commitHosted(markerText: string, item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined>) {+ private _commitHosted(feed: HostedPattern, item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined>) {const editor = this.editor;const model = editor.model;const marker = model.markers.get(MARKER_NAME);@@ -509,10 +507,20 @@ export default class TriliumMentionUI extends Plugin {this._clearDismissal();const insert = (mention: MentionFeedObjectItem | undefined) => {- // The text can have been deleted while a promise was pending.- if (mention && range.root.rootName !== "$graveyard") {- editor.execute("mention", { mention, text: mention.text, marker: markerText, range: range.toRange() });- editor.editing.view.focus();+ // The text can have been deleted while a promise was pending. An item gone stale keeps+ // the text, as in `_commit()`.+ if (mention && range.root.rootName !== "$graveyard" && (feed.canCommit?.(editor, mention) ?? true)) {+ if (feed.commit) {+ // As in `_commit()`: the text goes first, and the focus returns before the+ // callback, which can open a UI that takes it.+ const target = range.toRange();+ model.change((writer) => model.deleteContent(writer.createSelection(target)));+ editor.editing.view.focus();+ feed.commit(editor, mention);+ } else {+ editor.execute("mention", { mention, text: mention.text, marker: feed.marker, range: range.toRange() });+ editor.editing.view.focus();+ }}range.detach();};@@ -597,7 +605,6 @@ export default class TriliumMentionUI extends Plugin {this._listView?.show({entries,- className: MENTION_LIST_CLASS,selectedIndex: this._selectedIndex,caretRect: () => {const { left, top, width, height } = this._caretRect(marker);diff --git a/packages/ckeditor5/src/plugins/mention/types.ts b/packages/ckeditor5/src/plugins/mention/types.tsindex 4dfc9907d5..84cc3b875b 100644--- a/packages/ckeditor5/src/plugins/mention/types.ts+++ b/packages/ckeditor5/src/plugins/mention/types.ts@@ -82,11 +82,6 @@ export interface MentionListEntry {/** What a {@link MentionListView} draws, each time the list or its selection changes. */export interface MentionListState {entries: readonly MentionListEntry[];- /**- * A class for the list, under which the rows of the built-in feeds (the `/` commands) keep the- * layout they have in CKEditor's balloon.- */- className: string;/** The highlighted entry, or `-1` where none is. */selectedIndex: number;/** Where the caret ends the query, in viewport coordinates. */@@ -132,6 +127,10 @@ export interface MentionHostedFeed {allowSpaces?: boolean;/** Creates the list, once per editor. */list( editor: Editor ): MentionHostedList;+ /** See `MentionFeed.canCommit`, for what the list commits. */+ canCommit?: ( editor: Editor, item: MentionFeedObjectItem ) => boolean;+ /** See `MentionFeed.commit`, for what the list commits. */+ commit?: ( editor: Editor, item: MentionFeedObjectItem ) => void;}/** What a {@link MentionHostedList} is shown for, each time the query changes. */@@ -143,8 +142,9 @@ export interface MentionHostedListState {/** The editable element the caret is in. See {@link MentionListState.editable}. */editable: HTMLElement | null;/**- * Replaces the marker and the query with a mention of `item`, as a pick from the list does. For a- * promise, the text stays until it settles, and stays for good where it settles on `undefined`.+ * Replaces the marker and the query with a mention of `item`, or hands `item` to the feed's+ * `commit`, as a pick from the list does. For a promise, the text stays until it settles, and+ * stays for good where it settles on `undefined`.*/commit( item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined> ): void;}diff --git a/packages/ckeditor5/src/theme/slash_commands.css b/packages/ckeditor5/src/theme/slash_commands.cssdeleted file mode 100644index 873baad579..0000000000--- a/packages/ckeditor5/src/theme/slash_commands.css+++ /dev/null@@ -1,115 +0,0 @@-/*- * 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 {- /*- * Premium sized these 250px/200px, which ellipsised a third of the descriptions. At a 280px text- * column all but the longest fit; wider than that buys nothing, since the next-longest message- * is far below it. Capped against the viewport so the balloon still fits a phone screen.- */- --ck-slash-command-button-width: min(350px, 90vw);-- /*- * The text column is what is left of the row: the icon chip and the gaps and padding around it.- * Derived rather than written out, so widening the row above cannot leave the two disagreeing —- * the text would either stop short of the row's edge or overflow it.- */- --ck-slash-command-description-width: calc(var(--ck-slash-command-button-width) - 4.8em);- --tn-slash-command-icon-size: calc(var(--ck-icon-size) * 0.8);-}--:is(.ck-mentions, .ck-mention-list) .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;- width: var(--tn-slash-command-icon-size);- height: var(--tn-slash-command-icon-size);-- /*- * Premium put `ck-icon` on the `<svg>` itself (via `IconView`), so CKEditor's core- * `.ck.ck-icon { width/height: var(--ck-icon-size) }` sized the glyph. Here the class is on- * a wrapping span and the raw `<svg>` — injected via innerHTML from mixed sources (CKEditor- * 20px viewBoxes, 24px boxicons, custom footnote/math art) — is left unconstrained and- * renders at its intrinsic size.- *- * Fill the span's content box rather than re-applying `--ck-icon-size` to the svg:- * the variable is `em`-relative, and the svg carries a larger font-size than the chip, so- * `width: var(--ck-icon-size)` on the svg resolves ~20% bigger than the box it sits in and- * spills over the padding. `100%` ties it to the box the chip already sized.- */- & > svg {- display: block;- width: 100%;- height: 100%;- }-- /* A snippet note's font icon: the same chip, with a glyph instead of an svg. */- &.ck-slash-command-button__note-icon {- display: flex;- align-items: center;- justify-content: center;-- /*- * The glyph is sized on the inner span, never on the chip: the chip's width and height- * use the em-relative `--tn-slash-command-icon-size`, so a bigger font on the chip- * itself would inflate the chip box (and the whole row) along with the glyph. On the- * child, the calc resolves against the chip's untouched font-size, which is also what- * the chip's width resolves against, so 0.85 means 85% of the content box.- */- & > span {- font-size: calc(var(--tn-slash-command-icon-size) * 0.85);- line-height: 1;- }- }- }-- & > .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"] :is(.ck-mentions, .ck-mention-list) .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;- }-}