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 emoji as the command palette lists its commands
Elian Doranffd337d7e365
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.cssindex c13a6088e5..0211c67a89 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.css+++ b/apps/client/src/widgets/react/NoteAutocomplete.css@@ -128,6 +128,12 @@color: var(--muted-text-color);}+ /* A character drawn as the icon, such as an emoji, at a glyph's size. */+ .note-suggestion-text-icon {+ justify-content: center;+ width: 1em;+ }+/* An icon drawn as SVG markup, sized and coloured as a font icon's glyph. */.note-suggestion-svg-icon > svg {width: 1em;diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 2465c32180..49487edc88 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -491,6 +491,8 @@ export interface CommandEntry {icon?: string;/** An icon as SVG markup, in place of {@link CommandEntry.icon}. */iconSvg?: string;+ /** A character drawn as the icon, such as an emoji, in place of {@link CommandEntry.icon}. */+ iconText?: string;}/**@@ -529,9 +531,7 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anch<SuggestionOption key={entry.id} autocomplete={autocomplete} index={index}><span><SuggestionRowContent- icon={entry.iconSvg- ? <RawHtml className="tn-icon note-suggestion-svg-icon" html={entry.iconSvg} />- : <Icon icon={entry.icon ?? "bx bx-terminal"} />}+ icon={<CommandIcon entry={entry} />}header={<span className="search-result-title">{entry.title}</span>}details={entry.description && <span className="note-suggestion-description">{entry.description}</span>}/>@@ -543,6 +543,16 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anch);}+function CommandIcon({ entry }: { entry: CommandEntry }) {+ if (entry.iconSvg) {+ return <RawHtml className="tn-icon note-suggestion-svg-icon" html={entry.iconSvg} />;+ }+ if (entry.iconText) {+ return <span className="tn-icon note-suggestion-text-icon">{entry.iconText}</span>;+ }+ return <Icon icon={entry.icon ?? "bx bx-terminal"} />;+}+function commandTitle(entry: CommandEntry) {return entry.title;}diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 048889987e..32f1feb0b2 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, createSlashCommandList } from "./mention_list_view.js";+import { createEmojiList, 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";@@ -183,7 +183,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfiemoji: {definitionsUrl: window.glob.isDev? new URL(import.meta.url).origin + emojiDefinitionsUrl- : emojiDefinitionsUrl+ : emojiDefinitionsUrl,+ list: createEmojiList},syntaxHighlighting: {loadHighlightJs: async () => {@@ -313,7 +314,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfilist: () => createNoteMentionList({ allowCreatingNotes: true })}] : [],- // Draws the list of the emoji feed the plugin adds.+ // Draws the list of any feed a plugin adds through `registerMentionFeed()`.listView: createMentionListView};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 07b6461fad..772f8f3440 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, SlashCommandConfig, SlashCommandDefinition } from "@triliumnext/ckeditor5";+import type { EmojiSuggestion, 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, createSlashCommandList } from "./mention_list_view";+import { createAutocompleteMentionList, createEmojiList, createMentionListView, createNoteMentionList, createSlashCommandList } from "./mention_list_view";describe("createMentionListView", () => {const views: ReturnType<typeof createMentionListView>[] = [];@@ -258,3 +258,35 @@ describe("createSlashCommandList", () => {list.destroy?.();});});++describe("createEmojiList", () => {+ const suggestions: EmojiSuggestion[] = [+ { id: ":grinning face:", title: ":grinning face:", text: "π" },+ { id: ":show-all:", title: "Show all emoji...", text: "grin", opensPicker: true }+ ];++ it("lists the emoji as command rows, the emoji as the icon, and commits the one picked", async () => {+ const search = vi.fn(() => suggestions);+ const editor = { plugins: { get: () => ({ search }) } } as unknown as Parameters<NonNullable<SlashCommandConfig["list"]>>[0];+ const list = createEmojiList(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: "grin", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => {});++ expect(search).toHaveBeenLastCalledWith("grin");+ expect(list.element?.matches(".dropdown-menu.note-autocomplete-menu")).toBe(true);+ const [ grinning, showAll ] = [ ...(list.element?.querySelectorAll(".tn-menu-scroll > .dropdown-item") ?? []) ];+ expect(grinning.classList.contains("tn-menu-active")).toBe(true);+ expect(grinning.querySelector(".tn-icon.note-suggestion-text-icon")?.textContent).toBe("π");+ expect(grinning.querySelector(".search-result-title")?.textContent).toBe(":grinning face:");+ // The entry opening the picker has an icon of its own.+ expect(showAll.querySelector(".tn-icon.bx-smile")).not.toBeNull();+ expect(showAll.querySelector(".search-result-title")?.textContent).toBe("Show all emoji...");++ expect(key("Enter")).toBe(true);+ expect(commit).toHaveBeenCalledExactlyOnceWith(suggestions[0]);+ 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 1581c5eb7c..b2ed62d7d9 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,14 +1,18 @@import "./mention_list_view.css";-import type { MentionFeedObjectItem, MentionHostedList, MentionListEntry, MentionListState, MentionListView, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem, TriliumSlashCommands } from "@triliumnext/ckeditor5";+import type { ReferenceElement } from "@floating-ui/dom";+import type { EmojiSuggestion, MentionFeedObjectItem, MentionHostedList, MentionHostedListState, MentionListEntry, MentionListState, MentionListView, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem, TriliumEmojiMention, TriliumSlashCommands } from "@triliumnext/ckeditor5";import clsx from "clsx";-import { type ComponentChildren, render } from "preact";-import { useLayoutEffect, useRef } from "preact/hooks";+import { type ComponentChildren, render, type VNode } from "preact";+import { type MutableRef, useLayoutEffect, useRef } from "preact/hooks";import { AutocompleteList, type AutocompleteListHandle } from "../../react/FormAutocomplete";import { type CommandEntry, CommandMentionList, NoteMentionList } from "../../react/NoteAutocomplete";import Popup from "../../react/Popup";+/** The editor a list for a plugin's marker is created for. */+type HostEditor = Parameters<NonNullable<SlashCommandConfig["list"]>>[0];+/** The least width of an {@link createAutocompleteMentionList} list, whose caret anchor has none. */const AUTOCOMPLETE_MENTION_MIN_WIDTH = 220;@@ -63,38 +67,17 @@ export function createNoteMentionList({ allowCreatingNotes, preselect }: {allowCreatingNotes?: boolean;preselect?: boolean;} = {}): MentionHostedList {- const container = document.createElement("div");- const handle: { current: AutocompleteListHandle | null } = { current: null };- let element: HTMLDivElement | null = null;-- return {- show(state) {- render(<NoteMentionList- query={state.query}- // A new anchor each time the query changes, so it is placed again at the caret.- anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}- allowCreatingNotes={allowCreatingNotes}- preselect={preselect}- onPick={(notePath) => state.commit(typeof notePath === "string"- ? toMention(notePath)- : notePath.then((path) => path ? toMention(path) : undefined))}- 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;- }- };+ return createHostedList((state, list) => (+ <NoteMentionList+ {...list}+ query={state.query}+ allowCreatingNotes={allowCreatingNotes}+ preselect={preselect}+ onPick={(notePath) => state.commit(typeof notePath === "string"+ ? toMention(notePath)+ : notePath.then((path) => path ? toMention(path) : undefined))}+ />+ ));}/**@@ -107,75 +90,90 @@ export function createAutocompleteMentionList({ source, renderItem, toMention }:renderItem?(item: string): ComponentChildren;toMention(item: string): MentionFeedObjectItem;}): MentionHostedList {- const container = document.createElement("div");- const handle: { current: AutocompleteListHandle | null } = { current: null };- let element: HTMLElement | null = null;-- return {- show(state) {- render(<AutocompleteList- query={state.query}- source={source}- // 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={AUTOCOMPLETE_MENTION_MIN_WIDTH}- renderItem={renderItem}- onPick={(item) => state.commit(toMention(item))}- 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;- }- };+ return createHostedList((state, list) => (+ <AutocompleteList+ {...list}+ query={state.query}+ source={source}+ minWidth={AUTOCOMPLETE_MENTION_MIN_WIDTH}+ renderItem={renderItem}+ onPick={(item) => state.commit(toMention(item))}+ />+ ));}/*** Lists the `/` palette's entries for the query as the command palette lists its commands, 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 {+export function createSlashCommandList(editor: HostEditor): MentionHostedList {const palette = editor.plugins.get("TriliumSlashCommands") as TriliumSlashCommands;const source = async (query: string) => palette.search(query).map(toCommandEntry);++ return createHostedList((state, list) => (+ <CommandMentionList<SlashCommandEntry>+ {...list}+ query={state.query}+ source={source}+ className="slash-command-menu"+ onPick={({ definition }) => state.commit(toSlashCommandItem(definition))}+ />+ ));+}++/**+ * Lists the emoji for the query typed after `:` as the command palette lists its commands, the emoji+ * in place of the icon, for the editor config's `emoji.list`.+ */+export function createEmojiList(editor: HostEditor): MentionHostedList {+ const emoji = editor.plugins.get("TriliumEmojiMention") as TriliumEmojiMention;+ const source = async (query: string) => emoji.search(query).map(toEmojiEntry);++ return createHostedList((state, list) => (+ <CommandMentionList<EmojiEntry>+ {...list}+ query={state.query}+ source={source}+ onPick={({ suggestion }) => state.commit(suggestion)}+ />+ ));+}++/** What a list drawn by {@link createHostedList} is given to draw itself with. */+interface HostedListProps {+ /** At the caret, placed again each time the query changes. */+ anchor: ReferenceElement;+ handleRef: MutableRef<AutocompleteListHandle | null>;+ elementRef(element: HTMLElement | null): void;+}++/**+ * A {@link MentionHostedList} that renders what `draw` returns for each query, and forwards the+ * editor's keys to it.+ */+function createHostedList(draw: (state: MentionHostedListState, list: HostedListProps) => VNode): MentionHostedList {const container = document.createElement("div");- const handle: { current: AutocompleteListHandle | null } = { current: null };+ const handleRef: { current: AutocompleteListHandle | null } = { current: null };let element: HTMLElement | null = null;+ const elementRef = (el: HTMLElement | null) => { element = el; };+ const unmount = () => {+ render(null, container);+ element = null;+ };return {show(state) {- render(<CommandMentionList<SlashCommandEntry>- query={state.query}- source={source}- // A new anchor each time the query changes, so it is placed again at the caret.- anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}- className="slash-command-menu"- onPick={({ definition }) => state.commit(toSlashCommandItem(definition))}- handleRef={handle}- elementRef={(el) => { element = el; }}- />, container);+ // A new anchor each time, so the list is placed again at the caret. Its `contextElement`+ // places it again as the containers around the editor scroll.+ const anchor = { getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined };+ render(draw(state, { anchor, handleRef, elementRef }), container);},- hide() {- render(null, container);- element = null;- },- handleKeyDown: (e) => handle.current?.handleKeyDown(e) ?? false,+ hide: unmount,+ handleKeyDown: (e) => handleRef.current?.handleKeyDown(e) ?? false,get element() {return element;},- destroy() {- render(null, container);- element = null;- }+ destroy: unmount};}@@ -198,6 +196,19 @@ function toCommandEntry(definition: SlashCommandDefinition): SlashCommandEntry {};}+type EmojiEntry = CommandEntry & { suggestion: EmojiSuggestion };++/** An emoji as a command row, the emoji its icon, or the entry that opens the picker. */+function toEmojiEntry(suggestion: EmojiSuggestion): EmojiEntry {+ return {+ id: suggestion.id,+ title: suggestion.title,+ icon: suggestion.opensPicker ? "bx bx-smile" : undefined,+ iconText: suggestion.opensPicker ? undefined : suggestion.text,+ suggestion+ };+}+/** The mention `MentionCustomization` turns into a reference link to `notePath`. */function toMention(notePath: string) {return { id: `@${notePath}`, notePath };diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.htmlindex 4ec6ddae29..1b5823c6a3 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Insert buttons.html@@ -15,9 +15,9 @@be selected via a combo box to the right.</p><p>There is also the possibility of inserting emojis directly by typing <code>:</code> followedby a name of an emoji, triggering the display of a list of emojis. Simply- use the arrow keys to select one and press <kbd>Enter</kbd> to insert it.</p>-<img-src="1_Insert buttons_plus.png" width="272" height="187">+ use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to+ insert it.</p>+<img src="1_Insert buttons_plus.png" width="272" height="187"><h2>Symbols</h2><figure class="image image-style-align-right"><img style="aspect-ratio:346/322;" src="Insert buttons_image.png" width="346"diff --git a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.mdindex 037d375af2..3af8ae26c8 100644--- a/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md+++ b/docs/User Guide/User Guide/Note Types/Text/Insert buttons.md@@ -13,7 +13,7 @@ This feature allows inserting Unicode emoji characters. Simply select a categoryEmojis can also be searched by their English name and the skin tone can be selected via a combo box to the right.-There is also the possibility of inserting emojis directly by typing `:` followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> to insert it.+There is also the possibility of inserting emojis directly by typing `:` followed by a name of an emoji, triggering the display of a list of emojis. Simply use the arrow keys to select one and press <kbd>Enter</kbd> or <kbd>Tab</kbd> to insert it.<img src="1_Insert buttons_plus.png" width="272" height="187">diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 7613724fb3..b995b86619 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -17,6 +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 { default as TriliumEmojiMention, EmojiSuggestion } from "./plugins/mention/emoji_mention.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";diff --git a/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.ts b/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.tsindex e10855bae0..cfa767bab1 100644--- a/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/emoji_mention.spec.ts@@ -1,21 +1,20 @@import {type ClassicEditor,+ type Editor,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 TriliumEmojiMention, { type EmojiSuggestion } from "./emoji_mention.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;@@ -31,6 +30,46 @@ const DEFINITIONS = [skins: [ { emoji: "ππ½", tone: 3, version: 1 } ] }];+/** The query the stub list last showed the emoji for, or `null` while it is hidden. */+let shownQuery: string | null = null;++/**+ * A host's list for `emoji.list`, as the client's behaves for these tests: it lists the emoji for the+ * query as it is shown, opens on the first, moves on ArrowDown and commits on Enter.+ */+function createStubList(editor: Editor): MentionHostedList {+ let commit: ((item: EmojiSuggestion) => void) | null = null;+ let entries: EmojiSuggestion[] = [];+ let index = 0;++ return {+ show(state) {+ shownQuery = state.query;+ commit = state.commit;+ entries = editor.plugins.get(TriliumEmojiMention).search(state.query);+ index = 0;+ },+ hide() {+ shownQuery = null;+ commit = null;+ entries = [];+ },+ handleKeyDown(event) {+ if (event.key === "ArrowDown") {+ index = (index + 1) % entries.length;+ return true;+ }+ const entry = entries[index];+ if (event.key !== "Enter" || !commit || !entry) {+ return false;+ }+ commit(entry);+ return true;+ },+ element: null+ };+}+describe("TriliumEmojiMention", () => {let editor: ClassicEditor;let definitionsUrl: string;@@ -41,7 +80,7 @@ describe("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 }+ emoji: { list: createStubList, ...emojiConfig, definitionsUrl }});await editor.plugins.get(EmojiRepository).isReady();@@ -49,25 +88,12 @@ describe("TriliumEmojiMention", () => {}/** 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;+ function emojiFeed(): MentionHostedFeed | undefined {+ return editor.config.get("mention.hostedFeeds")?.find((candidate) => candidate.marker === ":");}- 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 query(text: string): EmojiSuggestion[] {+ return editor.plugins.get(TriliumEmojiMention).search(text);}function type(text: string) {@@ -76,9 +102,10 @@ describe("TriliumEmojiMention", () => {});}- function pressKey(keyCode: number) {+ function pressKey(key: "ArrowDown" | "Enter") {editor.editing.view.document.fire("keydown", {- keyCode,+ keyCode: 0,+ domEvent: new KeyboardEvent("keydown", { key }),preventDefault: () => {},stopPropagation: () => {},domTarget: editor.editing.view.getDomRoot()@@ -90,6 +117,7 @@ describe("TriliumEmojiMention", () => {}beforeEach(async () => {+ shownQuery = null;definitionsUrl = URL.createObjectURL(new Blob([ JSON.stringify(DEFINITIONS) ], { type: "application/json" }));await createEditor();});@@ -98,26 +126,42 @@ describe("TriliumEmojiMention", () => {URL.revokeObjectURL(definitionsUrl);});- it("registers itself and a `:` feed that needs two characters before opening", () => {+ it("registers itself and a `:` feed in the host's list, which needs two characters before opening", async () => {expect(TriliumEmojiMention.pluginName).toBe("TriliumEmojiMention");expect(TriliumEmojiMention.requires).toContain(EmojiRepository);- expect(emojiFeed().minimumCharacters).toBe(2);+ expect(emojiFeed()?.minimumCharacters).toBe(2);+ expect(emojiFeed()?.list).toBe(createStubList);++ type(":g");+ await settle();+ expect(shownQuery).toBeNull();++ type("r");+ await settle();+ expect(shownQuery).toBe("gr");});- 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("registers no feed for a host that gives it no list", async () => {+ editor = await createTestEditor([ Essentials, Paragraph, MentionEditing, TriliumMentionUI, TriliumEmojiMention ], {+ emoji: { definitionsUrl }+ });+ expect(emojiFeed()).toBeUndefined();+ });++ describe("searching", () => {+ it("lists matching emoji under their `:annotation:`, carrying the character as their text", () => {+ expect(query("grinning")).toEqual([+ { id: ":grinning face:", title: ":grinning face:", text: "π" },+ { id: ":grinning face with big eyes:", title: ":grinning face with big eyes:", text: "π" }]);});- it("returns nothing before the repository has loaded", async () => {+ it("lists nothing before the repository has loaded", () => {const repository = editor.plugins.get(EmojiRepository);const wasReady = repository.isRepositoryReady;repository.isRepositoryReady = false;- expect(await query("grinning")).toEqual([]);+ expect(query("grinning")).toEqual([]);repository.isRepositoryReady = wasReady;});@@ -125,11 +169,15 @@ describe("TriliumEmojiMention", () => {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("ππ½");-+ expect(query("waving")[0].text).toBe("ππ½");// "grinning face" has no toned variant, so the default is used.- expect((await query("grinning face"))[0].text).toBe("π");+ expect(query("grinning face")[0].text).toBe("π");+ });++ it("lists at most the dropdown limit", async () => {+ await createEditor(false, { dropdownLimit: 1 });++ expect(query("grinning").map((emoji) => emoji.text)).toEqual([ "π" ]);});});@@ -138,7 +186,7 @@ describe("TriliumEmojiMention", () => {type(":grin");await settle();- pressKey(keyCodes.enter);+ pressKey("Enter");const data = getModelData(editor.model, { withoutSelection: true });expect(data).toBe("<paragraph>π</paragraph>");@@ -153,59 +201,30 @@ describe("TriliumEmojiMention", () => {await createEditor(true);});- it("gives the last slot to a hand-off entry, keeping the list at the dropdown limit", async () => {+ it("gives the last slot to an entry opening the picker, keeping the list at the dropdown limit", async () => {await createEditor(true, { dropdownLimit: 2 });- const items = await query("grinning");+ const items = query("grinning");expect(items).toHaveLength(2);expect(items[0].text).toBe("π");- expect(items[1].id).toContain("show_all");+ expect(items[1]).toEqual({ id: expect.stringContaining("show_all"), title: "Show all emoji...", text: "grinning", opensPicker: true });});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);+ // The list opens on the first entry, so arrow down onto the picker's entry at the end.+ for (let i = 0; i < query("grinning").length - 1; i++) {+ pressKey("ArrowDown");}- pressKey(keyCodes.enter);+ pressKey("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.tsindex 72ea72377a..bee9ecd43d 100644--- a/packages/ckeditor5/src/plugins/mention/emoji_mention.ts+++ b/packages/ckeditor5/src/plugins/mention/emoji_mention.ts@@ -8,7 +8,8 @@ import {Typing} from "ckeditor5";-import { registerMentionFeed } from "./register_feed.js";+import { registerHostedMentionFeed } from "./register_feed.js";+import type { MentionHostedList } from "./types.js";export const EMOJI_MARKER = ":";@@ -17,8 +18,29 @@ const SHOW_ALL_ID = ":__trilium_show_all_emoji__:";const DROPDOWN_LIMIT = 6;+declare module "@ckeditor/ckeditor5-emoji" {+ interface EmojiConfig {+ /**+ * The host's list of the `:` completion, which lists {@link TriliumEmojiMention.search} for+ * the query and commits the {@link EmojiSuggestion} picked. Without it there is no completion.+ */+ list?: ( editor: Editor ) => MentionHostedList;+ }+}++/** An entry of the `:` completion, as {@link TriliumEmojiMention.search} lists it and its list commits it. */+export interface EmojiSuggestion extends MentionFeedObjectItem {+ /** The emoji, or for the entry that opens the picker, the query it opens the picker on. */+ text: string;+ /** What the row says: the emoji's `:annotation:`, or the picker entry's caption. */+ title: string;+ /** Marks the entry that opens the emoji picker on the query instead of inserting an emoji. */+ opensPicker?: boolean;+}+/**- * The `:smile:` autocomplete, hosted on {@link TriliumMentionUI}.+ * The `:smile:` autocomplete: what it finds and what a pick inserts, for the list the host draws in+ * `emoji.list`, which {@link TriliumMentionUI} runs as a hosted feed.** 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@@ -30,8 +52,8 @@ const DROPDOWN_LIMIT = 6;* 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.+ * feed's own `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 {@@ -48,24 +70,27 @@ export default class TriliumEmojiMention extends Plugin {editor.config.define("emoji", { dropdownLimit: DROPDOWN_LIMIT });- registerMentionFeed(editor, {+ const list = editor.config.get("emoji.list");+ if (!list) {+ return;+ }++ registerHostedMentionFeed(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.+ // a list 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)+ list,+ commit: (editorInstance, item) => this._commit(editorInstance, item as EmojiSuggestion)});}- private get _picker(): EmojiPicker | null {- return this.editor.plugins.has(EmojiPicker) ? this.editor.plugins.get(EmojiPicker) : null;- }-- private _query(query: string): MentionFeedObjectItem[] {+ /**+ * The emoji matching what was typed after the `:`, at most `emoji.dropdownLimit` of them, the+ * last of which opens the picker on the query where the picker is loaded.+ */+ search(query: string): EmojiSuggestion[] {const repository = this.editor.plugins.get(EmojiRepository);if (!repository.isRepositoryReady) {@@ -80,37 +105,28 @@ export default class TriliumEmojiMention extends Plugin {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- }));+ const emojis = repository.getEmojiByQuery(query).map((emoji): EmojiSuggestion => {+ const shortcode = `${EMOJI_MARKER}${emoji.annotation}${EMOJI_MARKER}`;+ return { id: shortcode, title: shortcode, text: emoji.skins[skinTone] ?? emoji.skins.default };+ });- if (!this._picker) {- return emojis;+ if (!picker) {+ return emojis.slice(0, limit);}// 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 } ];+ return [+ ...emojis.slice(0, limit - 1),+ { id: SHOW_ALL_ID, title: this.editor.t("Show all emoji..."), text: query, opensPicker: true }+ ];}- 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 get _picker(): EmojiPicker | null {+ return this.editor.plugins.has(EmojiPicker) ? this.editor.plugins.get(EmojiPicker) : null;}- private _commit(editor: Editor, item: MentionFeedObjectItem) {- if (item.id !== SHOW_ALL_ID) {+ private _commit(editor: Editor, item: EmojiSuggestion) {+ if (!item.opensPicker) {editor.execute("insertText", { text: item.text });return;}