Skip to content

Build your personal knowledge base with Trilium Notes

refactor(text): run only hosted lists in the mention UI

Elian Doranb4d84355fd0b
diff --git a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md
index 9e9d66f7c3..1d6f95354e 100644
--- a/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md
+++ b/.claude/skills/ckeditor5-plugin-development/references/tooling-and-packaging.md
@@ -154,7 +154,8 @@ keep in sync. `src/index.ts` imports `ckeditor5/ckeditor5.css` and the Trilium t
`apps/client/src/widgets/type_widgets/text/`:
- `config.ts` builds the `EditorConfig` (toolbar from `toolbar.ts`, language, feature config such as
- `syntaxHighlighting`, `moveBlockUp/Down`, mention feeds, etc.).
+ `syntaxHighlighting`, `moveBlockUp/Down`, the `mention.hostedFeeds` whose lists
+ `mention_list_view.tsx` draws, etc.).
- `CKEditorWithWatchdog.tsx` wraps editor creation in the **custom `EditorWatchdog`**
(`packages/ckeditor5/src/custom_watchdog.ts`, re-exported from `@triliumnext/ckeditor5`), which
recreates the editor on a crash while preserving data.
diff --git a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md
index 5c5f885cf8..a1b2a2407f 100644
--- a/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md
+++ b/.claude/skills/ckeditor5-plugin-development/references/ui-and-localization.md
@@ -271,7 +271,7 @@ and exposes a `focus()` method. Add `tabindex: '-1'` and the `ck` class to UI ro
### Custom DOM inside a balloon needs `ck-reset_all-excluded`
-CKEditor wraps every floating UI root — balloons, mention panels, dropdown panels — in
+CKEditor wraps every floating UI root — balloons, dropdown panels — in
`.ck.ck-reset_all`. Its companion rule
```css
@@ -288,11 +288,10 @@ The symptom reads as a missing stylesheet rather than a cascade conflict: the el
classes and keeps every property the reset does **not** name (`display`, `border-radius`, `gap`),
so only some of its styling disappears.
-**Fix:** put `ck-reset_all-excluded` on the outermost custom element — a mention feed
-`itemRenderer` root, a custom `View`'s element, anything wrapped in `MentionDomWrapperView`. The
-`:not()` covers the whole subtree, so one class exempts everything inside it. Do **not**
-out-specify the reset instead: winning a specificity war means restating the borrowed component's
-internals, which then drift from it.
+**Fix:** put `ck-reset_all-excluded` on the outermost custom element — a custom `View`'s element,
+or raw DOM a view wraps. The `:not()` covers the whole subtree, so one class exempts everything
+inside it. Do **not** out-specify the reset instead: winning a specificity war means restating the
+borrowed component's internals, which then drift from it.
Diagnosing this from the sources is a trap — load `ckeditor5.css` *first* in a static test page
and the client rules win, so the bug does not reproduce. Inspect `getComputedStyle` in the real
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 2dd624b24f..34f57e4a4a 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -1290,27 +1290,6 @@ body.mobile .modal-content-with-sidebar > .modal-main > .modal-header > .modal-t
width: auto;
}
-.ck-mentions .ck-button {
- font-size: var(--detail-font-size) !important;
- padding: var(--suggestion-item-padding-block) var(--suggestion-item-padding-inline);
-}
-
-.ck-mentions .ck-button b {
- font-size: var(--detail-font-size) !important;
-}
-
-.ck-mentions {
- --ck-color-list-button-on-background: var(--suggestion-active-background-color);
- --ck-color-list-button-on-background-focus: var(--ck-color-list-button-on-background);
- --ck-color-list-button-on-text: var(--suggestion-active-text-color);
-}
-
-.ck-mentions .ck-button b {
- font-weight: bold !important;
- color: inherit !important;
- vertical-align: baseline !important;
-}
-
.side-checkbox {
display: flex;
align-items: end;
@@ -1880,24 +1859,6 @@ body.desktop .dropdown-submenu > .dropdown-menu {
display: none !important;
}
-.ck.ck-mentions > .ck-list__item {
- max-width: 700px;
-}
-
-.ck.ck-mentions > .ck-list__item .ck-button {
- /* wrap text for very long note path title */
- white-space: normal !important;
-}
-
-/*
- * The panel stays within the viewport: twice `VIEWPORT_MARGIN` in `trilium_mention_ui.ts` narrower
- * than it, and no taller than the space `TriliumMentionUI` measures beside the caret.
- */
-.ck.ck-mention-balloon .ck-mentions {
- max-width: calc(100vw - 2 * 8px);
- max-height: min(var(--ck-mention-list-max-height), var(--tn-mention-visible-height, 100vh));
-}
-
/* Snippet form */
.ck.ck-template-form__text-part {
diff --git a/apps/client/src/stylesheets/theme-next/notes/text.css b/apps/client/src/stylesheets/theme-next/notes/text.css
index 9a2dbd24b7..504452bcff 100644
--- a/apps/client/src/stylesheets/theme-next/notes/text.css
+++ b/apps/client/src/stylesheets/theme-next/notes/text.css
@@ -543,18 +543,6 @@ div.ck-template-form .ck-search__info span:nth-child(2) {
margin-top: var(--ck-input-label-height);
}
-/* Mention list (the autocompletion list for emojis, labels and relations) */
-
-:root .ck-mentions {
- --ck-color-list-button-hover-background: var(--ck-editor-toolbar-dropdown-button-open-background);
- --ck-focus-ring: 1px solid transparent;
-}
-
-/* "Keep on typing to see the emoji" placeholder */
-#mention-list-item-id\:__EMOJI_HINT {
- background: transparent;
-}
-
/*
* FORMS
*/
diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.ts
index f373af9bd3..7793e16d1b 100644
--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts
@@ -5,7 +5,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import imageService from "../../../services/image.js";
import { ensureMimeTypesForHighlighting } from "../../../services/syntax_highlight.js";
import { buildConfig, type BuildEditorOptions, OPEN_SOURCE_LICENSE_KEY } from "./config.js";
-import { createMentionListView } from "./mention_list_view.js";
// Mutable option values, reset before each test (see `beforeEach`).
const optionsState = vi.hoisted(() => ({
@@ -113,7 +112,6 @@ interface DynamicConfig {
mention?: {
feeds: unknown[];
hostedFeeds?: { marker: string; minimumCharacters?: number; allowSpaces?: boolean; list(): unknown }[];
- listView?: unknown;
};
}
@@ -561,8 +559,6 @@ describe("CK config - mention feed", () => {
const off = await buildDynamicConfig();
expect(off.mention?.feeds).toEqual([]);
expect(off.mention?.hostedFeeds).toEqual([]);
- // The `/` and emoji feeds the plugins add are drawn through it all the same.
- expect(off.mention?.listView).toBe(createMentionListView);
optionsState.map["textNoteCompletionEnabled"] = "true";
const config = await buildDynamicConfig();
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 32f1feb0b2..56ac53c09c 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 { createEmojiList, createMentionListView, createNoteMentionList, createSlashCommandList } from "./mention_list_view.js";
+import { createEmojiList, createNoteMentionList, createSlashCommandList } from "./mention_list_view.js";
import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";
import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";
import { buildToolbarConfig } from "./toolbar.js";
@@ -313,9 +313,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
allowSpaces: true,
list: () => createNoteMentionList({ allowCreatingNotes: true })
}
- ] : [],
- // Draws the list of any feed a plugin adds through `registerMentionFeed()`.
- listView: createMentionListView
+ ] : []
};
return {
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.css
index 703bf57fee..a06c76643f 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,33 +1,3 @@
-/*
- * 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.
- */
-.mention-list-menu .dropdown-item:has(> span > .ck-button) {
- /* Outranks the `!important` padding of `.dropdown-item` in the theme. */
- padding: 0 !important;
-}
-
-.mention-list-menu .ck.ck-button.ck-button {
- width: 100%;
- min-height: 0;
- border: 0;
- box-shadow: none !important;
- color: inherit;
- font: inherit;
- text-align: start;
- cursor: inherit;
- background: none !important;
-}
-
-.mention-list-menu {
- max-width: min(700px, calc(100vw - 10px));
-}
-
-.mention-list-menu > .tn-menu-scroll {
- max-height: var(--ck-mention-list-max-height);
-}
-
/*
* The `/` palette, at a width that fits all but the longest descriptions, and given more height than
* a list usually is: it is long, and the query only narrows it.
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.tsx
index 9d74745454..76886d85c4 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 { EmojiSuggestion, MentionHostedListState, MentionListState, SlashCommandConfig, SlashCommandDefinition } from "@triliumnext/ckeditor5";
+import type { EmojiSuggestion, MentionHostedListState, SlashCommandConfig, SlashCommandDefinition } from "@triliumnext/ckeditor5";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -13,128 +13,7 @@ vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({
createNoteFromSuggestion
}));
-import { createAutocompleteMentionList, createEmojiList, createMentionListView, createNoteMentionList, createSlashCommandList } from "./mention_list_view";
-
-describe("createMentionListView", () => {
- const views: ReturnType<typeof createMentionListView>[] = [];
-
- afterEach(() => {
- for (const view of views.splice(0)) view.destroy?.();
- vi.restoreAllMocks();
- });
-
- function stateWith(overrides: Partial<MentionListState> = {}): MentionListState {
- const emoji = document.createElement("span");
- emoji.textContent = "😄 smile";
- const command = document.createElement("button");
- command.className = "ck ck-button ck-slash-command-button";
- command.textContent = "Heading";
-
- return {
- entries: [
- { item: { id: ":smile:" }, marker: ":", render: () => emoji },
- { item: { id: "/heading" }, marker: "/", render: () => command },
- { item: { id: "#plain" }, marker: "#", render: () => undefined }
- ],
- selectedIndex: 0,
- caretRect: () => new DOMRect(10, 10, 1, 16),
- editable: null,
- select: vi.fn(),
- pick: vi.fn(),
- ...overrides
- };
- }
-
- async function show(state: MentionListState) {
- const view = createMentionListView();
- views.push(view);
- await act(async () => view.show(state));
- return view;
- }
-
- const rows = () => [ ...document.querySelectorAll<HTMLElement>(".mention-list-menu .tn-menu-scroll > .dropdown-item") ];
-
- it("draws the entries as the note autocomplete's menu at the caret, the selected one highlighted", async () => {
- const view = await show(stateWith());
-
- const menu = view.element;
- expect(menu?.className).toContain("dropdown-menu");
- expect(menu?.className).toContain("note-autocomplete-menu");
- 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.
- const [ emoji, command, plain ] = rows();
- expect(emoji.textContent).toBe("😄 smile");
- expect(command.querySelector(".ck-slash-command-button")?.textContent).toBe("Heading");
- expect(plain.textContent).toBe("#plain");
-
- await act(async () => view.hide());
- expect(view.element).toBeNull();
- expect(document.querySelector(".mention-list-menu")).toBeNull();
- });
-
- it("follows the caret as a container around the editor scrolls", async () => {
- const scroller = document.createElement("div");
- scroller.style.overflow = "auto";
- const editable = document.createElement("div");
- scroller.append(editable);
- document.body.append(scroller);
- let caretTop = 100;
- // Floating UI reads the viewport and the popup's size, which happy-dom does not lay out.
- vi.spyOn(document.documentElement, "clientWidth", "get").mockReturnValue(1000);
- vi.spyOn(document.documentElement, "clientHeight", "get").mockReturnValue(800);
- vi.spyOn(HTMLElement.prototype, "offsetWidth", "get").mockReturnValue(200);
- vi.spyOn(HTMLElement.prototype, "offsetHeight", "get").mockReturnValue(100);
-
- await show(stateWith({ editable, caretRect: () => new DOMRect(10, caretTop, 1, 16) }));
- const menu = document.querySelector<HTMLElement>(".mention-list-menu");
- await vi.waitFor(() => expect(menu?.style.top).toBe("116px"));
-
- caretTop = 40;
- scroller.dispatchEvent(new Event("scroll"));
- await vi.waitFor(() => expect(menu?.style.top).toBe("56px"));
- scroller.remove();
- });
-
- it("reports the row the pointer moves onto and the one clicked, not a row under a still pointer", async () => {
- const state = stateWith();
- await show(state);
- const [ , second ] = rows();
-
- second.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 5, clientY: 5 }));
- expect(state.select).toHaveBeenCalledWith(1);
-
- vi.mocked(state.select).mockClear();
- second.dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 5, clientY: 5 }));
- expect(state.select).not.toHaveBeenCalled();
-
- second.click();
- expect(state.pick).toHaveBeenCalledWith(1);
-
- const mouseDown = new MouseEvent("mousedown", { bubbles: true, cancelable: true });
- second.dispatchEvent(mouseDown);
- expect(mouseDown.defaultPrevented).toBe(true);
- });
-
- it("scrolls a row the keys select into view, not one the pointer does", async () => {
- const scroll = vi.spyOn(Element.prototype, "scrollIntoView").mockImplementation(() => {});
- const state = stateWith();
- const view = await show(state);
- scroll.mockClear();
-
- await act(async () => view.show({ ...state, selectedIndex: 2 }));
- expect(scroll).toHaveBeenCalledOnce();
- expect(scroll.mock.contexts[0]).toBe(rows()[2]);
-
- scroll.mockClear();
- vi.mocked(state.select).mockImplementation((index) => void view.show({ ...state, selectedIndex: index }));
- await act(async () => {
- rows()[1].dispatchEvent(new MouseEvent("mousemove", { bubbles: true, clientX: 9, clientY: 9 }));
- });
- expect(state.select).toHaveBeenCalledWith(1);
- expect(scroll).not.toHaveBeenCalled();
- });
-});
+import { createAutocompleteMentionList, createEmojiList, createNoteMentionList, createSlashCommandList } from "./mention_list_view";
describe("createNoteMentionList", () => {
beforeEach(() => {
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.tsx
index 868912e12d..1a7fe07549 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,13 @@
import "./mention_list_view.css";
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 type { EmojiSuggestion, MentionFeedObjectItem, MentionHostedList, MentionHostedListState, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem, TriliumEmojiMention, TriliumSlashCommands } from "@triliumnext/ckeditor5";
import clsx from "clsx";
import { type ComponentChildren, render, type VNode } from "preact";
-import { type MutableRef, useLayoutEffect, useRef } from "preact/hooks";
+import type { MutableRef } 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];
@@ -16,49 +15,6 @@ 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;
-/**
- * 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
- * selection and the commit. The menu never takes the focus, which stays in the editor.
- */
-export function createMentionListView(): MentionListView {
- const container = document.createElement("div");
- let element: HTMLDivElement | null = null;
- // Set while the pointer moves the selection, which must not scroll the list under it.
- let selectedByPointer = false;
-
- return {
- show(state) {
- render(<MentionMenu
- state={state}
- elementRef={(el) => { element = el; }}
- scrollsToSelection={() => {
- const scrolls = !selectedByPointer;
- selectedByPointer = false;
- return scrolls;
- }}
- onPointerSelect={(index) => {
- selectedByPointer = true;
- state.select(index);
- }}
- />, container);
- },
- hide() {
- render(null, container);
- element = null;
- },
- get element() {
- return element;
- },
- destroy() {
- render(null, container);
- element = null;
- }
- };
-}
-
/**
* Lists the notes for the query typed after `@` as the note autocomplete does, for the editor config's
* `mention.hostedFeeds`, and mentions the note picked as a reference link.
@@ -217,68 +173,3 @@ function toEmojiEntry(suggestion: EmojiSuggestion): EmojiEntry {
function toMention(notePath: string) {
return { id: `@${notePath}`, notePath };
}
-
-function MentionMenu({ state, elementRef, scrollsToSelection, onPointerSelect }: {
- state: MentionListState;
- elementRef(element: HTMLDivElement | null): void;
- scrollsToSelection(): boolean;
- onPointerSelect(index: number): void;
-}) {
- const menuRef = useRef<HTMLMenuElement>(null);
- const lastPointer = useRef<{ x: number; y: number }>();
- const { entries, selectedIndex } = state;
-
- useLayoutEffect(() => {
- if (!scrollsToSelection() || selectedIndex < 0) return;
- menuRef.current?.querySelectorAll(":scope > .dropdown-item")[selectedIndex]?.scrollIntoView({ block: "nearest" });
- }, [ selectedIndex, entries ]);
-
- return (
- <Popup
- // A new anchor each time the list changes, so it is placed again at the caret as it moves.
- // Its `contextElement` places it again as the containers around the editor scroll.
- anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}
- elementRef={elementRef}
- // The pointer moves the highlighted row, so `:hover` marks no second one.
- className="dropdown-menu show tn-dropdown-menu tn-menu-keyboard note-autocomplete-menu mention-list-menu"
- >
- <menu
- ref={menuRef}
- className="tn-menu-scroll"
- role="listbox"
- // Keeps the focus in the editor, which closes the list without it.
- onMouseDown={(e) => e.preventDefault()}
- >
- {entries.map((entry, index) => (
- <li
- key={`${entry.marker}:${entry.item.id}`}
- className={clsx("dropdown-item", index === selectedIndex && "tn-menu-active")}
- role="option"
- aria-selected={index === selectedIndex}
- onMouseMove={(e) => {
- // A row scrolled under a still pointer does not take the highlight.
- const last = lastPointer.current;
- if (last && last.x === e.clientX && last.y === e.clientY) return;
- lastPointer.current = { x: e.clientX, y: e.clientY };
- if (index !== selectedIndex) onPointerSelect(index);
- }}
- onClick={() => state.pick(index)}
- >
- <EntryContent entry={entry} />
- </li>
- ))}
- </menu>
- </Popup>
- );
-}
-
-/** An entry as its feed's `itemRenderer` draws it, or by its id where the feed has none. */
-function EntryContent({ entry }: { entry: MentionListEntry }) {
- const ref = useRef<HTMLSpanElement>(null);
-
- useLayoutEffect(() => {
- ref.current?.replaceChildren(entry.render() ?? entry.item.id);
- }, [ entry.item, entry.marker ]);
-
- return <span ref={ref} />;
-}
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index b995b86619..fe96970cfb 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -19,7 +19,7 @@ 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 type { MentionHostedFeed, MentionHostedList, MentionHostedListState } from "./plugins/mention/types.js";
export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";
export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";
export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";
diff --git a/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts b/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts
index 84d4684904..c2a02e45a3 100644
--- a/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/register_feed.spec.ts
@@ -1,66 +1,33 @@
-import { type ClassicEditor, Essentials, Paragraph } from "ckeditor5";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { Essentials, Paragraph } from "ckeditor5";
+import { describe, expect, it, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import { registerHostedMentionFeed, registerMentionFeed } from "./register_feed.js";
-import type { TriliumMentionFeed } from "./types.js";
+import { registerHostedMentionFeed } from "./register_feed.js";
-describe("registerMentionFeed", () => {
- let editor: ClassicEditor;
-
- function feeds() {
- return (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
- }
-
- beforeEach(async () => {
- editor = await createTestEditor([ Essentials, Paragraph ]);
- });
-
- it("creates mention.feeds when nothing configured it, then appends to it", () => {
- expect(editor.config.get("mention.feeds")).toBeUndefined();
-
- registerMentionFeed(editor, { marker: ":", feed: [] });
- registerMentionFeed(editor, { marker: "/", feed: [] });
-
- expect(feeds().map((feed) => feed.marker)).toEqual([ ":", "/" ]);
- });
-
- it("preserves feeds the host application configured", async () => {
- editor = await createTestEditor([ Essentials, Paragraph ], {
- mention: { feeds: [ { marker: "@", feed: [] } ] }
- });
-
- registerMentionFeed(editor, { marker: ":", feed: [] });
+describe("registerHostedMentionFeed", () => {
+ const list = () => ({ show() {}, hide() {}, handleKeyDown: () => false, element: null });
- expect(feeds().map((feed) => feed.marker)).toEqual([ "@", ":" ]);
- });
+ it("creates mention.hostedFeeds when nothing configured it, then appends to it", async () => {
+ const editor = await createTestEditor([ Essentials, Paragraph ]);
+ expect(editor.config.get("mention.hostedFeeds")).toBeUndefined();
- it("refuses to register a marker twice, since the second feed would be unreachable", () => {
- const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
-
- registerMentionFeed(editor, { marker: ":", feed: [ "first" ] });
- registerMentionFeed(editor, { marker: ":", feed: [ "second" ] });
+ registerHostedMentionFeed(editor, { marker: ":", list });
+ registerHostedMentionFeed(editor, { marker: "/", list });
- expect(feeds()).toHaveLength(1);
- expect(feeds()[0].feed).toEqual([ "first" ]);
- expect(warn).toHaveBeenCalledOnce();
+ expect(editor.config.get("mention.hostedFeeds")?.map((feed) => feed.marker)).toEqual([ ":", "/" ]);
});
-});
-describe("registerHostedMentionFeed", () => {
- it("appends to mention.hostedFeeds, and refuses a marker either kind of feed holds", async () => {
+ it("keeps the feeds the host configured, and refuses a marker one of them 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 } ] }
+ mention: { hostedFeeds: [ { marker: "#", list } ] }
});
registerHostedMentionFeed(editor, { 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);
+ expect(warn).toHaveBeenCalledOnce();
warn.mockRestore();
});
});
diff --git a/packages/ckeditor5/src/plugins/mention/register_feed.ts b/packages/ckeditor5/src/plugins/mention/register_feed.ts
index 5c764b3c07..b7dda152ce 100644
--- a/packages/ckeditor5/src/plugins/mention/register_feed.ts
+++ b/packages/ckeditor5/src/plugins/mention/register_feed.ts
@@ -1,9 +1,10 @@
import type { Editor } from "ckeditor5";
-import type { MentionHostedFeed, TriliumMentionFeed } from "./types.js";
+import type { MentionHostedFeed } from "./types.js";
/**
- * Appends a feed to `mention.feeds`, creating the entry when the host application configured none.
+ * Appends a feed to `mention.hostedFeeds`, creating the entry when the host application configured
+ * none.
*
* Call this from a plugin **constructor**, not from `init()`: {@link TriliumMentionUI} compiles the
* configured feeds into trigger patterns in its own `init()`, and CKEditor runs every plugin
@@ -14,34 +15,13 @@ import type { MentionHostedFeed, TriliumMentionFeed } from "./types.js";
* feeds sharing a marker would make {@link findMarkerMatch} pick whichever came first and silently
* shadow the other.
*/
-export function registerMentionFeed(editor: Editor, feed: TriliumMentionFeed): void {
- if (isMarkerTaken(editor, feed.marker)) {
- return;
- }
-
- const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
- editor.config.set("mention.feeds", [ ...feeds, 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;
- }
-
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;
+ if (feeds.some((existing) => existing.marker === feed.marker)) {
+ console.warn(`[trilium-mention] the "${feed.marker}" marker is already registered; ignoring the duplicate feed.`);
+ return;
}
- return false;
+ editor.config.set("mention.hostedFeeds", [ ...feeds, feed ]);
}
diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts
index 0d11aae51a..ded793ef2b 100644
--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts
+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts
@@ -1,49 +1,63 @@
import {
type ClassicEditor,
- ContextualBalloon,
Essentials,
_getModelData as getModelData,
keyCodes,
MentionEditing,
type MentionFeedObjectItem,
Paragraph,
- Rect,
- _setModelData as setModelData,
- View
+ _setModelData as setModelData
} from "ckeditor5";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, type Mock, vi } from "vitest";
import { createTestEditor } from "../../../test/editor-kit.js";
-import type { MentionHostedList, MentionHostedListState, MentionListState, MentionListView, TriliumMentionFeed } from "./types.js";
-import TriliumMentionUI, { balloonPositions } from "./trilium_mention_ui.js";
-
-/** Longer than the plugin's 100 ms feed debounce. */
-const AFTER_DEBOUNCE = 160;
+import TriliumMentionUI from "./trilium_mention_ui.js";
+import type { MentionHostedFeed, MentionHostedList, MentionHostedListState } from "./types.js";
+
+/** A host's list as the plugin sees it, recording what it is shown. */
+interface StubList extends MentionHostedList {
+ state: MentionHostedListState | null;
+ show: Mock<(state: MentionHostedListState) => void>;
+ hide: Mock<() => void>;
+ handleKeyDown: Mock<(event: KeyboardEvent) => boolean>;
+ destroy: Mock<() => void>;
+}
+
+/** A list whose element is there while it is shown, as a list showing entries has one. */
+function createStubList(): StubList {
+ const element = document.createElement("div");
+ document.body.append(element);
+
+ const list: StubList = {
+ state: null,
+ show: vi.fn<(state: MentionHostedListState) => void>((state) => { list.state = state; }),
+ hide: vi.fn<() => void>(() => { list.state = null; }),
+ handleKeyDown: vi.fn<(event: KeyboardEvent) => boolean>(() => true),
+ destroy: vi.fn<() => void>(),
+ get element() { return list.state ? element : null; }
+ };
+ return list;
+}
describe("TriliumMentionUI", () => {
let editor: ClassicEditor;
- let labelFeed: ReturnType<typeof vi.fn>;
+ let labels: StubList;
+ let notes: StubList;
- async function createEditor(overrides: Partial<TriliumMentionFeed> = {}, extraConfig: Record<string, unknown> = {}) {
- labelFeed = vi.fn(async (query: string) => (
- [ "alpha", "beta", "gamma" ]
- .filter((name) => name.startsWith(query))
- .map((name) => ({ id: `#${name}`, text: `#${name}` }))
- ));
+ async function createEditor(feeds: Partial<Record<"#" | "@", Partial<MentionHostedFeed>>> = {}, plugins = [ Essentials, Paragraph, MentionEditing, TriliumMentionUI ]) {
+ labels = createStubList();
+ notes = createStubList();
- editor = await createTestEditor([ Essentials, Paragraph, MentionEditing, TriliumMentionUI ], {
+ editor = await createTestEditor(plugins, {
mention: {
- feeds: [ { marker: "#", feed: labelFeed as unknown as TriliumMentionFeed["feed"], minimumCharacters: 0, ...overrides } ]
- },
- ...extraConfig
+ feeds: [],
+ hostedFeeds: [
+ { marker: "#", minimumCharacters: 0, list: () => labels, ...feeds["#"] },
+ { marker: "@", minimumCharacters: 0, allowSpaces: true, list: () => notes, ...feeds["@"] }
+ ]
+ }
});
- }
-
- /** Whether the autocomplete balloon is currently on screen. */
- function isPanelVisible() {
- const balloon = editor.plugins.get(ContextualBalloon);
-
- return balloon.visibleView?.element?.classList.contains("ck-mentions") ?? false;
+ setModelData(editor.model, "<paragraph>[]</paragraph>");
}
/** Types `text` at the caret, producing the `change:data` the text watcher reacts to. */
@@ -64,159 +78,81 @@ describe("TriliumMentionUI", () => {
});
}
- function pressKey(keyCode: number) {
+ /** Presses a key in the editor, and returns whether the plugin kept it from the editor. */
+ function press(keyCode: number) {
+ const domEvent = new KeyboardEvent("keydown");
+ const preventDefault = vi.fn();
editor.editing.view.document.fire("keydown", {
keyCode,
- preventDefault: () => {},
+ domEvent,
+ preventDefault,
stopPropagation: () => {},
domTarget: editor.editing.view.getDomRoot()
});
+ return { domEvent, consumed: preventDefault.mock.calls.length > 0 };
}
- async function settle() {
- await new Promise((resolve) => setTimeout(resolve, AFTER_DEBOUNCE));
+ const text = () => getModelData(editor.model, { withoutSelection: true });
+
+ /** Commits `#alpha` from the open label list, as a pick from it does. */
+ function commitAlpha() {
+ labels.state?.commit({ id: "#alpha", text: "#alpha" });
}
beforeEach(async () => {
await createEditor();
- setModelData(editor.model, "<paragraph>[]</paragraph>");
});
- it("registers itself and requires the contextual balloon", () => {
+ it("shows a marker's list the query typed after it, the caret and the editable", () => {
expect(TriliumMentionUI.pluginName).toBe("TriliumMentionUI");
- expect(TriliumMentionUI.requires).toContain(ContextualBalloon);
- expect(editor.plugins.get(TriliumMentionUI)).toBeInstanceOf(TriliumMentionUI);
- });
-
- it("opens the panel while typing and queries the feed with the text after the marker", async () => {
- type("#al");
- await settle();
-
- expect(labelFeed).toHaveBeenCalledWith("al");
- expect(isPanelVisible()).toBe(true);
- });
-
- it("hides the panel when the feed returns nothing", async () => {
- type("#zzz");
- await settle();
- expect(isPanelVisible()).toBe(false);
+ type("@my no");
+ expect(notes.state?.query).toBe("my no");
+ expect(notes.state?.caretRect().height).toBeGreaterThan(0);
+ expect(notes.state?.editable).toBe(editor.editing.view.getDomRoot());
+ type("te");
+ expect(notes.state?.query).toBe("my note");
+ expect(labels.show).not.toHaveBeenCalled();
});
- it("keeps the panel open, and anchored where it opened, while the query is refined", async () => {
- type("#a");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- const position = editor.plugins.get(ContextualBalloon).view.position;
-
- type("l");
- await settle();
+ it("closes one marker's list when another marker is typed", () => {
+ type("@al");
+ type(" #be");
- expect(labelFeed).toHaveBeenLastCalledWith("al");
- expect(isPanelVisible()).toBe(true);
- // Re-showing reuses the position that already matched, so the panel does not jump.
- expect(editor.plugins.get(ContextualBalloon).view.position).toBe(position);
+ expect(notes.hide).toHaveBeenCalled();
+ expect(notes.state).toBe(null);
+ expect(labels.state?.query).toBe("be");
});
- it("survives another plugin's balloon burying the panel", async () => {
- const balloon = editor.plugins.get(ContextualBalloon);
- const errors: unknown[] = [];
- const onRejection = (event: PromiseRejectionEvent) => errors.push(event.reason);
- window.addEventListener("unhandledrejection", onRejection);
+ it("waits for a feed's minimum characters", async () => {
+ await createEditor({ "#": { minimumCharacters: 2 } });
type("#a");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- // `singleViewMode` hides every other stack, so the mention panel is still registered with
- // the balloon but is no longer the visible view.
- const other = new View(editor.locale);
- other.setTemplate({ tag: "div" });
- other.render();
- balloon.add({ view: other, position: { target: document.body }, singleViewMode: true });
- expect(isPanelVisible()).toBe(false);
-
- // Refining the query must not try to add the panel a second time: `ContextualBalloon.add()`
- // rejects an already-registered view outright, which is the `contextualballoon-add-view-exist`
- // crash upstream's visibility-based guard walks into.
+ expect(labels.state).toBe(null);
type("l");
- await settle();
-
- window.removeEventListener("unhandledrejection", onRejection);
- expect(errors).toEqual([]);
- expect(balloon.hasView(other)).toBe(true);
- });
-
- it("hides the panel on a click outside it", async () => {
- type("#al");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
-
- expect(isPanelVisible()).toBe(false);
- });
-
- it("keeps the panel open when the click lands inside the balloon", async () => {
- type("#al");
- await settle();
-
- const balloonElement = editor.plugins.get(ContextualBalloon).view.element;
- balloonElement?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
-
- expect(isPanelVisible()).toBe(true);
- });
-
- it("caps the list's height to the room the visible viewport leaves beside the caret", async () => {
- type("#al");
- await settle();
-
- const list = document.querySelector<HTMLElement>(".ck-mention-balloon .ck-mentions");
- expect(list).not.toBe(null);
- const height = parseFloat(list?.style.getPropertyValue("--tn-mention-visible-height") ?? "");
- expect(height).toBeGreaterThan(0);
- expect(height).toBeLessThan(window.visualViewport?.height ?? window.innerHeight);
- });
-
- it("positions the panel from the right in a right-to-left UI", async () => {
- await createEditor({}, { language: { ui: "ar" } });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- expect(editor.locale.uiLanguageDirection).toBe("rtl");
-
- type("#al");
- await settle();
-
- expect(isPanelVisible()).toBe(true);
- expect(editor.plugins.get(ContextualBalloon).view.position).toMatch(/^caret_/);
+ expect(labels.state?.query).toBe("al");
});
describe("Escape dismisses without touching the document", () => {
- it("stays hidden across the next keystroke and inserts no sentinel character", async () => {
+ it("stays hidden across the next keystroke and inserts no sentinel character", () => {
type("#al");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- pressKey(keyCodes.esc);
- expect(isPanelVisible()).toBe(false);
+ expect(press(keyCodes.esc).consumed).toBe(true);
+ expect(labels.state).toBe(null);
// The regression the removed pnpm patch caused: dismissing used to insert a U+2002
// en-space, which the attribute lexer then folded into the attribute name.
- const data = getModelData(editor.model, { withoutSelection: true });
- expect(data).not.toContain(" ");
- expect(data).toContain("#al");
+ expect(text()).not.toContain(" ");
+ expect(text()).toContain("#al");
// Upstream reopens here, because its text watcher re-evaluates and the pattern still matches.
type("p");
- await settle();
- expect(isPanelVisible()).toBe(false);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alp");
+ expect(labels.state).toBe(null);
+ expect(text()).toContain("#alp");
});
- it("reopens once the dismissed marker itself is retyped", async () => {
+ it("reopens once the dismissed marker itself is retyped", () => {
type("#al");
- await settle();
- pressKey(keyCodes.esc);
+ press(keyCodes.esc);
// Delete the whole marker, which sends the dismissal's live position to the graveyard.
editor.model.change((writer) => {
@@ -224,17 +160,14 @@ describe("TriliumMentionUI", () => {
});
type("#be");
- await settle();
-
- expect(isPanelVisible()).toBe(true);
+ expect(labels.state?.query).toBe("be");
});
- it("reopens once the block holding the dismissal is replaced wholesale", async () => {
+ it("reopens once the block holding the dismissal is replaced wholesale", () => {
setModelData(editor.model, "<paragraph></paragraph><paragraph>[]</paragraph>");
type("#al");
- await settle();
- pressKey(keyCodes.esc);
+ press(keyCodes.esc);
// One edit drops the dismissed paragraph — sending the dismissal's live position to the
// graveyard — and leaves a fresh marker matching in the block the caret ends up in. The
@@ -250,551 +183,94 @@ describe("TriliumMentionUI", () => {
writer.setSelection(writer.createPositionAt(first, "end"));
}
});
- await settle();
- expect(isPanelVisible()).toBe(true);
+ expect(labels.state?.query).toBe("be");
});
- it("reopens for a different marker typed after the dismissed one", async () => {
+ it("reopens for a different marker typed after the dismissed one", () => {
type("#al");
- await settle();
- pressKey(keyCodes.esc);
+ press(keyCodes.esc);
type(" #be");
- await settle();
-
- expect(isPanelVisible()).toBe(true);
- });
- });
-
- describe("caret moves do not open the panel", () => {
- it("stays closed when the caret is placed inside existing matching text", async () => {
- setModelData(editor.model, "<paragraph>#alpha[]</paragraph>");
-
- moveCaretTo(3);
- await settle();
-
- expect(isPanelVisible()).toBe(false);
- expect(labelFeed).not.toHaveBeenCalled();
- });
-
- it("closes an open panel when the caret moves", async () => {
- type("#al");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- moveCaretTo(1);
- await settle();
-
- expect(isPanelVisible()).toBe(false);
- });
- });
-
- describe("commit keys", () => {
- it("commits the pre-selected item on Enter by default", async () => {
- type("#al");
- await settle();
-
- pressKey(keyCodes.enter);
-
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
- });
-
- it("leaves Enter alone when preselectFirstItem is off and nothing is selected", async () => {
- await createEditor({ preselectFirstItem: false });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#al");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- pressKey(keyCodes.enter);
-
- // Still just the typed text — no suggestion was committed behind the user's back.
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#al<");
- });
-
- it("commits after the user arrows onto an item even when nothing was pre-selected", async () => {
- await createEditor({ preselectFirstItem: false });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#");
- await settle();
-
- pressKey(keyCodes.arrowdown);
- pressKey(keyCodes.enter);
-
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
- });
-
- it("navigates the list with the arrow keys", async () => {
- type("#");
- await settle();
-
- pressKey(keyCodes.arrowdown);
- pressKey(keyCodes.arrowup);
- pressKey(keyCodes.enter);
-
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
+ expect(labels.state?.query).toBe("be");
});
- it("ignores unrelated keys while the panel is open", async () => {
+ it("leaves Escape to the editor while the list shows nothing", () => {
+ Object.defineProperty(labels, "element", { get: () => null });
type("#al");
- await settle();
-
- pressKey(keyCodes.a);
- expect(isPanelVisible()).toBe(true);
+ expect(press(keyCodes.esc).consumed).toBe(false);
+ expect(labels.handleKeyDown).not.toHaveBeenCalled();
});
});
- describe("feed handling", () => {
- it("hides the panel when the feed rejects", async () => {
- await createEditor({ feed: vi.fn(async () => { throw new Error("boom"); }) as unknown as TriliumMentionFeed["feed"] });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#al");
- await settle();
-
- expect(isPanelVisible()).toBe(false);
- });
+ describe("caret moves do not open the list", () => {
+ it("stays closed when the caret is placed inside existing matching text", () => {
+ setModelData(editor.model, "<paragraph>#alpha</paragraph><paragraph>[]</paragraph>");
+ labels.show.mockClear();
- it("filters a static array feed case-insensitively", async () => {
- await createEditor({ feed: [ "#Alpha", "#beta" ] });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#al");
- await settle();
-
- expect(isPanelVisible()).toBe(true);
- pressKey(keyCodes.enter);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#Alpha");
- });
-
- it("honours dropdownLimit", async () => {
- await createEditor({ dropdownLimit: 1 });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#");
- await settle();
-
- const items = editor.plugins.get(ContextualBalloon).visibleView?.element?.querySelectorAll("li");
- expect(items?.length).toBe(1);
+ moveCaretTo(3);
+ expect(labels.show).not.toHaveBeenCalled();
+ expect(labels.state).toBe(null);
});
- it("filters a static array feed of objects by id", async () => {
- await createEditor({ feed: [ { id: "#Alpha", text: "#Alpha" }, { id: "#beta", text: "#beta" } ] });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
+ it("closes an open list when the caret moves", () => {
type("#al");
- await settle();
-
- expect(isPanelVisible()).toBe(true);
- pressKey(keyCodes.enter);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#Alpha");
- });
-
- it("anchors the panel to the caret when the marked text was undone away mid-request", async () => {
- const resolvers: Array<(items: MentionFeedObjectItem[]) => void> = [];
- await createEditor({
- feed: (() => new Promise((resolve) => resolvers.push(resolve))) as unknown as TriliumMentionFeed["feed"]
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- // The undos are invisible to the text watcher, so the in-flight request still resolves
- // against a marker whose range has meanwhile been moved to the graveyard.
- editor.execute("enter");
- type("#al");
- await settle();
- editor.execute("undo");
- editor.execute("undo");
-
- resolvers[0]?.([ { id: "#alpha", text: "#alpha" } ]);
- await settle();
-
- expect(isPanelVisible()).toBe(true);
- });
-
- it("discards an out-of-order response", async () => {
- const resolvers: Array<(items: MentionFeedObjectItem[]) => void> = [];
- await createEditor({
- feed: (() => new Promise((resolve) => resolvers.push(resolve))) as unknown as TriliumMentionFeed["feed"]
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#a");
- await settle();
- type("l");
- await settle();
-
- // Answer the *first* request last; it must not repopulate the panel.
- resolvers[1]?.([ { id: "#alpha", text: "#alpha" } ]);
- resolvers[0]?.([ { id: "#stale", text: "#stale" } ]);
- await settle();
-
- pressKey(keyCodes.enter);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#alpha");
- });
-
- it("discards a stale response even when the newer request has the same query text", async () => {
- const resolvers: Array<(items: MentionFeedObjectItem[]) => void> = [];
- await createEditor({
- feed: (() => new Promise((resolve) => resolvers.push(resolve))) as unknown as TriliumMentionFeed["feed"]
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- // Same query typed twice, so correlating on the text alone cannot tell them apart.
- type("#al");
- await settle();
- editor.model.change((writer) => writer.remove(editor.model.createRangeIn(editor.model.document.getRoot()?.getChild(0) as never)));
- type("#al");
- await settle();
-
- resolvers[1]?.([ { id: "#fresh", text: "#fresh" } ]);
- resolvers[0]?.([ { id: "#stale", text: "#stale" } ]);
- await settle();
-
- pressKey(keyCodes.enter);
- const data = getModelData(editor.model, { withoutSelection: true });
- expect(data).toContain("#fresh");
- expect(data).not.toContain("#stale");
- });
-
- it("does not let an earlier request's rejection close the panel a later one opened", async () => {
- let rejectFirst: (reason: Error) => void = () => {};
- let call = 0;
- await createEditor({
- feed: (() => {
- if (call++ === 0) {
- return new Promise((_resolve, reject) => { rejectFirst = reject; });
- }
- return Promise.resolve([ { id: "#alpha", text: "#alpha" } ]);
- }) as unknown as TriliumMentionFeed["feed"]
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#a");
- await settle();
- type("l");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
- rejectFirst(new Error("boom"));
- await settle();
+ moveCaretTo(1);
- expect(isPanelVisible()).toBe(true);
+ expect(labels.hide).toHaveBeenCalled();
+ expect(labels.state).toBe(null);
});
});
- it("does not re-trigger inside an existing mention", async () => {
- type("#al");
- await settle();
- pressKey(keyCodes.enter);
- await settle();
-
- // The caret now sits right after a committed mention.
- expect(isPanelVisible()).toBe(false);
- });
-
- it("does not open the panel for a caret parked inside an existing mention", async () => {
- setModelData(editor.model, "<paragraph>[]</paragraph><paragraph></paragraph>");
-
+ it("forwards the keys while the list is open, keeping from the editor those it takes", () => {
type("#al");
- await settle();
- pressKey(keyCodes.enter);
- await settle();
- labelFeed.mockClear();
-
- // Inside the committed "#alpha", where the text before the caret still reads "#al".
- moveCaretTo(3);
- await settle();
-
- // An edit elsewhere re-evaluates that text, which must not be treated as a fresh query.
- editor.model.change((writer) => {
- const second = editor.model.document.getRoot()?.getChild(1);
-
- if (second?.is("element")) {
- writer.insertText("x", writer.createPositionAt(second, 0));
- }
- });
- await settle();
-
- expect(isPanelVisible()).toBe(false);
- expect(labelFeed).not.toHaveBeenCalled();
+ const arrow = press(keyCodes.arrowdown);
+ expect(labels.handleKeyDown).toHaveBeenCalledWith(arrow.domEvent);
+ expect(arrow.consumed).toBe(true);
+
+ // Enter with nothing highlighted, say, which the attribute editor saves on.
+ labels.handleKeyDown.mockReturnValue(false);
+ expect(press(keyCodes.enter).consumed).toBe(false);
+
+ // Closed, the list is handed nothing.
+ moveCaretTo(0);
+ labels.handleKeyDown.mockClear();
+ press(keyCodes.arrowdown);
+ expect(labels.handleKeyDown).not.toHaveBeenCalled();
});
- it("tolerates being initialised before MentionEditing registers the mention command", async () => {
- const feed = vi.fn(async () => [ { id: "#alpha", text: "#alpha" } ]);
- editor = await createTestEditor([ Essentials, Paragraph, TriliumMentionUI, MentionEditing ], {
- mention: { feeds: [ { marker: "#", feed: feed as unknown as TriliumMentionFeed["feed"], minimumCharacters: 0 } ] }
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
+ it("closes on a press outside the list's element, and not on one inside it", () => {
type("#al");
- await settle();
-
- expect(isPanelVisible()).toBe(true);
+ labels.element?.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+ expect(labels.state).not.toBe(null);
+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
+ expect(labels.state).toBe(null);
});
- it("hides the panel when the editor becomes read-only", async () => {
+ it("hides the list when the editor becomes read-only", () => {
type("#al");
- await settle();
- expect(isPanelVisible()).toBe(true);
-
editor.enableReadOnlyMode("test");
- expect(isPanelVisible()).toBe(false);
-
+ expect(labels.state).toBe(null);
editor.disableReadOnlyMode("test");
});
- it("renders a custom itemRenderer result", async () => {
- await createEditor({
- itemRenderer: (item) => {
- const element = document.createElement("button");
- element.classList.add("custom-mention-item");
- element.textContent = String(item.id);
-
- return element;
- }
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#al");
- await settle();
-
- expect(editor.plugins.get(ContextualBalloon).visibleView?.element?.querySelector(".custom-mention-item")).toBeTruthy();
- });
-
- it("renders a string itemRenderer result as a button label", async () => {
- await createEditor({ itemRenderer: (item) => `label:${item.id}` });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
-
- type("#al");
- await settle();
-
- expect(editor.plugins.get(ContextualBalloon).visibleView?.element?.textContent).toContain("label:#alpha");
- });
-
- describe("a host's own list view", () => {
- let shown: MentionListState | null;
- let listElement: HTMLElement;
- let view: MentionListView & { show: ReturnType<typeof vi.fn>; hide: ReturnType<typeof vi.fn>; destroy: ReturnType<typeof vi.fn> };
-
- beforeEach(async () => {
- shown = null;
- listElement = document.createElement("div");
- document.body.append(listElement);
- view = {
- show: vi.fn((state: MentionListState) => { shown = state; }),
- hide: vi.fn(() => { shown = null; }),
- destroy: vi.fn(),
- get element() { return shown ? listElement : null; }
- };
- });
-
- async function createWithView(overrides: Partial<TriliumMentionFeed> = {}) {
- await createEditor(overrides, { mention: {
- feeds: [ { marker: "#", feed: labelFeed as unknown as TriliumMentionFeed["feed"], minimumCharacters: 0, ...overrides } ],
- listView: () => view
- } });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- }
-
- const ids = () => shown?.entries.map((entry) => entry.item.id);
-
- it("draws the entries through it instead of the balloon, at the caret", async () => {
- await createWithView({ itemRenderer: (item) => `rendered ${item.id}` });
- type("#a");
- await settle();
-
- expect(isPanelVisible()).toBe(false);
- expect(ids()).toEqual([ "#alpha" ]);
- expect(shown?.selectedIndex).toBe(0);
- expect(shown?.entries[0].marker).toBe("#");
- expect(shown?.entries[0].render()).toBe("rendered #alpha");
- expect(shown?.caretRect().height).toBeGreaterThan(0);
- expect(shown?.editable).toBe(editor.editing.view.getDomRoot());
- });
-
- it("moves the selection with the arrow keys, wrapping, and commits it on Enter", async () => {
- labelFeed.mockImplementation(async () => [ "alpha", "albert" ].map((name) => ({ id: `#${name}`, text: `#${name}` })));
- await createWithView();
- type("#al");
- await settle();
-
- pressKey(keyCodes.arrowdown);
- expect(shown?.selectedIndex).toBe(1);
- pressKey(keyCodes.arrowdown);
- expect(shown?.selectedIndex).toBe(0);
- pressKey(keyCodes.arrowup);
- expect(shown?.selectedIndex).toBe(1);
-
- pressKey(keyCodes.enter);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#albert");
- expect(view.hide).toHaveBeenCalled();
- expect(shown).toBe(null);
- });
-
- it("highlights and commits what the view reports the pointer on", async () => {
- labelFeed.mockImplementation(async () => [ "alpha", "albert" ].map((name) => ({ id: `#${name}`, text: `#${name}` })));
- await createWithView();
- type("#al");
- await settle();
-
- shown?.select(1);
- expect(shown?.selectedIndex).toBe(1);
- shown?.pick(1);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#albert");
- });
-
- it("leaves Enter alone with nothing selected where preselectFirstItem is off", async () => {
- await createWithView({ preselectFirstItem: false });
- type("#al");
- await settle();
- expect(shown?.selectedIndex).toBe(-1);
-
- pressKey(keyCodes.enter);
- expect(getModelData(editor.model, { withoutSelection: true })).toContain("#al<");
- expect(shown).not.toBe(null);
- });
-
- it("closes on Escape, on a press outside its element, and not on one inside it", async () => {
- await createWithView();
- type("#al");
- await settle();
- pressKey(keyCodes.esc);
- expect(shown).toBe(null);
-
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- type("#al");
- await settle();
- expect(shown).not.toBe(null);
-
- listElement.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
- expect(shown).not.toBe(null);
- document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
- expect(shown).toBe(null);
- });
-
- it("is destroyed with the editor", async () => {
- await createWithView();
- await editor.destroy();
- expect(view.destroy).toHaveBeenCalled();
- });
- });
-
- describe("a hosted list", () => {
- let state: MentionHostedListState | null;
- let listElement: HTMLElement;
- let list: MentionHostedList & {
- show: ReturnType<typeof vi.fn>;
- hide: ReturnType<typeof vi.fn>;
- handleKeyDown: ReturnType<typeof vi.fn>;
- destroy: ReturnType<typeof vi.fn>;
- };
-
- beforeEach(async () => {
- state = null;
- listElement = document.createElement("div");
- document.body.append(listElement);
- list = {
- show: vi.fn((shown: MentionHostedListState) => { state = shown; }),
- hide: vi.fn(() => { state = null; }),
- handleKeyDown: vi.fn(() => true),
- destroy: vi.fn(),
- get element() { return state ? listElement : null; }
- };
-
- labelFeed = vi.fn(async () => [ { id: "#alpha", text: "#alpha" } ]);
- editor = await createTestEditor([ Essentials, Paragraph, MentionEditing, TriliumMentionUI ], {
- mention: {
- feeds: [ { marker: "#", feed: labelFeed as unknown as TriliumMentionFeed["feed"], minimumCharacters: 0 } ],
- hostedFeeds: [ { marker: "@", minimumCharacters: 0, allowSpaces: true, list: () => list } ]
- }
- });
- setModelData(editor.model, "<paragraph>[]</paragraph>");
- });
-
- /** Presses a key in the editor, and returns whether the plugin kept it from the editor. */
- function press(keyCode: number) {
- const domEvent = new KeyboardEvent("keydown");
- const preventDefault = vi.fn();
- editor.editing.view.document.fire("keydown", {
- keyCode,
- domEvent,
- preventDefault,
- stopPropagation: () => {},
- domTarget: editor.editing.view.getDomRoot()
- });
- return { domEvent, consumed: preventDefault.mock.calls.length > 0 };
- }
-
- const text = () => getModelData(editor.model, { withoutSelection: true });
-
- it("is shown the query typed after its marker, and closed when the caret leaves it", async () => {
- type("@my no");
- expect(state?.query).toBe("my no");
- expect(state?.caretRect().height).toBeGreaterThan(0);
- expect(state?.editable).toBe(editor.editing.view.getDomRoot());
- type("te");
- expect(state?.query).toBe("my note");
-
- // The feeds are left alone, and their list never opens over the hosted one.
- await settle();
- expect(labelFeed).not.toHaveBeenCalled();
-
- moveCaretTo(0);
- expect(list.hide).toHaveBeenCalled();
- expect(state).toBe(null);
- });
-
- it("takes the keys while it is open, and Escape dismisses it where it shows entries", () => {
- type("@al");
- const arrow = press(keyCodes.arrowdown);
- expect(list.handleKeyDown).toHaveBeenCalledWith(arrow.domEvent);
- expect(arrow.consumed).toBe(true);
-
- list.handleKeyDown.mockReturnValue(false);
- expect(press(keyCodes.enter).consumed).toBe(false);
-
- expect(press(keyCodes.esc).consumed).toBe(true);
- expect(state).toBe(null);
- // Dismissed: typing on does not bring it back.
- type("p");
- expect(state).toBe(null);
- });
-
- it("leaves Escape to the editor while it shows nothing", () => {
- Object.defineProperty(list, "element", { get: () => null });
- type("@al");
-
- expect(press(keyCodes.esc).consumed).toBe(false);
- expect(list.handleKeyDown).not.toHaveBeenCalled();
- });
-
- it("closes on a press outside its element, and not on one inside it", () => {
- type("@al");
- listElement.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
- expect(state).not.toBe(null);
- document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
- expect(state).toBe(null);
- });
-
- it("replaces the trigger text with what it commits, at once or once a promise settles", async () => {
+ describe("committing", () => {
+ it("replaces the trigger text with what the list commits, at once or once a promise settles", async () => {
setModelData(editor.model, "<paragraph>x []</paragraph>");
type("@al");
- state?.commit({ id: "@alpha", text: "@alpha" });
+ notes.state?.commit({ id: "@alpha", text: "@alpha" });
expect(text()).toContain("x <$text");
expect(text()).toContain(">@alpha</$text>");
- expect(state).toBe(null);
+ expect(notes.state).toBe(null);
setModelData(editor.model, "<paragraph>x []</paragraph>");
type("@be");
let resolveCommit: (item: MentionFeedObjectItem | undefined) => void = () => {};
- state?.commit(new Promise((resolve) => { resolveCommit = resolve; }));
+ notes.state?.commit(new Promise((resolve) => { resolveCommit = resolve; }));
// The text stays while the promise is pending, and the list is closed.
expect(text()).toBe("<paragraph>x @be</paragraph>");
- expect(state).toBe(null);
+ expect(notes.state).toBe(null);
resolveCommit({ id: "@beta", text: "@beta" });
await Promise.resolve();
expect(text()).toContain("@beta</$text>");
@@ -802,46 +278,61 @@ describe("TriliumMentionUI", () => {
setModelData(editor.model, "<paragraph>x []</paragraph>");
type("@ga");
- state?.commit(Promise.resolve(undefined));
+ notes.state?.commit(Promise.resolve(undefined));
await Promise.resolve();
expect(text()).toBe("<paragraph>x @ga</paragraph>");
});
- it("is destroyed with the editor", async () => {
- await editor.destroy();
- expect(list.destroy).toHaveBeenCalled();
+ it("hands the item to the feed's commit with the trigger text gone, unless it went stale", async () => {
+ const commit = vi.fn();
+ const canCommit = vi.fn(() => true);
+ await createEditor({ "#": { commit, canCommit } });
+
+ setModelData(editor.model, "<paragraph>x []</paragraph>");
+ type("#al");
+ commitAlpha();
+ expect(commit).toHaveBeenCalledExactlyOnceWith(editor, { id: "#alpha", text: "#alpha" });
+ expect(text()).toBe("<paragraph>x </paragraph>");
+
+ commit.mockClear();
+ canCommit.mockReturnValue(false);
+ type("#be");
+ commitAlpha();
+ expect(commit).not.toHaveBeenCalled();
+ expect(text()).toBe("<paragraph>x #be</paragraph>");
});
- });
-});
-describe("balloonPositions", () => {
- const rect = (left: number, top: number, width: number, height: number) =>
- new Rect({ left, top, width, height, right: left + width, bottom: top + height });
- const viewport = rect(0, 0, 400, 800);
- const balloon = rect(0, 0, 300, 200);
+ it("does not reopen the list right after a committed mention, nor inside one", () => {
+ setModelData(editor.model, "<paragraph>[]</paragraph><paragraph></paragraph>");
+ type("#al");
+ commitAlpha();
+ labels.show.mockClear();
- function place(caret: Rect, ...args: Parameters<typeof balloonPositions>) {
- return balloonPositions(...args).map((position) => position(caret, balloon, viewport));
- }
+ // Inside the committed "#alpha", where the text before the caret still reads "#al".
+ moveCaretTo(3);
+ // An edit elsewhere re-evaluates that text, which must not be treated as a fresh query.
+ editor.model.change((writer) => {
+ const second = editor.model.document.getRoot()?.getChild(1);
- it("slides each corner sideways to keep the panel within the viewport", () => {
- // A caret near the right edge: opening rightward from it would run off the screen.
- const [ se, sw ] = place(rect(350, 100, 1, 20), undefined, "ltr");
- expect(se).toMatchObject({ name: "caret_se", top: 123, left: 400 - 8 - 300 });
- expect(sw).toMatchObject({ name: "caret_sw", left: 51 });
+ if (second?.is("element")) {
+ writer.insertText("x", writer.createPositionAt(second, 0));
+ }
+ });
- // Near the left edge, opening leftward stops at the margin.
- const [ , leftward ] = place(rect(20, 100, 1, 20), undefined, "ltr");
- expect(leftward).toMatchObject({ name: "caret_sw", left: 8 });
+ expect(labels.show).not.toHaveBeenCalled();
+ });
});
- it("offers the corners above first where asked, and the matched one first of all, the others after it", () => {
- const caret = rect(100, 400, 1, 20);
- const names = (...args: Parameters<typeof balloonPositions>) => place(caret, ...args).map((position) => position?.name);
+ it("tolerates being initialised before MentionEditing registers the mention command", async () => {
+ await createEditor({}, [ Essentials, Paragraph, TriliumMentionUI, MentionEditing ]);
+
+ type("#al");
+ expect(labels.state?.query).toBe("al");
+ });
- expect(names(undefined, "ltr")).toEqual([ "caret_se", "caret_sw", "caret_ne", "caret_nw" ]);
- expect(names(undefined, "rtl")).toEqual([ "caret_sw", "caret_se", "caret_nw", "caret_ne" ]);
- expect(names(undefined, "ltr", true)).toEqual([ "caret_ne", "caret_nw", "caret_se", "caret_sw" ]);
- expect(names("caret_nw", "ltr")).toEqual([ "caret_nw", "caret_se", "caret_sw", "caret_ne" ]);
+ it("destroys the lists with the editor", async () => {
+ await editor.destroy();
+ expect(labels.destroy).toHaveBeenCalled();
+ expect(notes.destroy).toHaveBeenCalled();
});
});
diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts
index 6d5c9d54d7..774f5eec92 100644
--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts
+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts
@@ -1,16 +1,9 @@
import {
- ButtonView,
clickOutsideHandler,
- Collection,
- ContextualBalloon,
- type DomOptimalPositionOptions,
- type Editor,
+ DomEmitterMixin,
keyCodes,
type Marker,
- MentionDomWrapperView,
type MentionFeedObjectItem,
- MentionListItemView,
- MentionsView,
ModelLivePosition,
ModelLiveRange,
type ModelPosition,
@@ -21,69 +14,48 @@ import {
} from "ckeditor5";
import { createMarkerPattern, findMarkerMatch, type MarkerMatch } from "./marker_pattern.js";
-import type { MentionHostedFeed, MentionHostedList, MentionListView, TriliumMentionFeed } from "./types.js";
+import type { MentionHostedFeed, MentionHostedList } from "./types.js";
-const VERTICAL_SPACING = 3;
-/** The least gap kept between the panel and an edge of the visible viewport, which `style.css` matches. */
-const VIEWPORT_MARGIN = 8;
-/** Below this the space under the caret is unusable, and the panel opens above it where there is more room. */
-const MIN_LIST_HEIGHT = 150;
const MARKER_NAME = "mention";
-const FEED_DEBOUNCE_MS = 100;
-const DEFAULT_DROPDOWN_LIMIT = 10;
-
-
-/** A configured feed with its compiled trigger pattern. */
-type Pattern = TriliumMentionFeed & { pattern: RegExp };
/** A marker of `mention.hostedFeeds` with its compiled trigger pattern and the host's list. */
-type HostedPattern = MentionHostedFeed & { pattern: RegExp; hostedList: MentionHostedList };
+type Pattern = MentionHostedFeed & { pattern: RegExp; hostedList: MentionHostedList };
/**
- * A drop-in replacement for CKEditor's `MentionUI` that fixes three behaviours we can neither
- * configure nor subclass around, since every interesting member of `MentionUI` is `private`:
+ * A replacement for CKEditor's `MentionUI` that finds the markers typed in the editor and runs the
+ * host's list for each: it reports the query, forwards the keys while the list is open and commits
+ * what the list picks. What a list shows and how it draws it are the host's (`mention.hostedFeeds`).
+ *
+ * It also fixes three behaviours of upstream's, which we can neither configure nor subclass around,
+ * since every interesting member of `MentionUI` is `private`:
*
* 1. **Escape actually dismisses.** Upstream's Escape handler only removes the model marker, but its
* `TextWatcher` re-evaluates the text on the very next keystroke, the pattern still matches, and
- * the panel reopens. Trilium worked around that by *inserting a ` ` en-space* into the document
+ * the list reopens. Trilium worked around that by *inserting a ` ` en-space* into the document
* so the (also patched) pattern could no longer match — which corrupts data: the attribute lexer
* treats only U+0020 as a separator, so `#foo<en-space> #bar` fails to parse and the attribute
* list becomes unsaveable. Here dismissal is state ({@link #_dismissedAt}), not a document edit.
- * 2. **The panel opens on typing only.** `TextWatcher` fires `matched:selection` on any direct caret
+ * 2. **The list opens on typing only.** `TextWatcher` fires `matched:selection` on any direct caret
* move, and upstream listens to plain `matched`, so merely *clicking* into an existing `#myLabel`
- * reopens the panel — and since it also pre-selects the first item, the Enter meant to save the
+ * reopens the list — and since it also pre-selects the first item, the Enter meant to save the
* attributes commits a suggestion instead.
- * 3. **A stale query closes the panel.** See {@link createMarkerPattern}.
+ * 3. **A stale query closes the list.** See {@link createMarkerPattern}.
*
- * Everything else — the balloon, the list views, the `mention` model attribute and its post-fixers,
- * the `mention` command — is reused from upstream unchanged. This plugin replaces `MentionUI` only;
- * pair it with `MentionEditing` rather than the `Mention` façade, which pulls in `MentionUI` too.
+ * The `mention` model attribute, its post-fixers and the `mention` command are reused from upstream
+ * unchanged. Pair this plugin with `MentionEditing` rather than the `Mention` façade, which pulls in
+ * `MentionUI` too.
*/
export default class TriliumMentionUI extends Plugin {
- private readonly _view: MentionsView;
- private readonly _items = new Collection<{ item: MentionFeedObjectItem; marker: string }>();
- private _patterns: Pattern[] = [];
-
- /** The host's drawing of the list, from `mention.listView`, which replaces the balloon. */
- private _listView?: MentionListView;
- /** Whether {@link _listView} is shown. */
- private _listShown = false;
- /** The entry {@link _listView} highlights, or `-1`. */
- private _selectedIndex = -1;
/** The markers whose list the host runs, from `mention.hostedFeeds`. */
- private _hosted: HostedPattern[] = [];
- /** The hosted marker whose list is open, or `null`. */
- private _openHosted: HostedPattern | null = null;
-
- private _balloon?: ContextualBalloon;
- private _feedTimer?: ReturnType<typeof setTimeout>;
-
- /** Monotonic id of the most recently *started* feed request; see {@link _requestFeed}. */
- private _requestId = 0;
+ private _feeds: Pattern[] = [];
+ /** The marker whose list is open, or `null`. */
+ private _open: Pattern | null = null;
+ /** Listens for presses outside the open list, which close it. */
+ private readonly _domEmitter = new (DomEmitterMixin())();
/**
- * Where the marker of the panel the user dismissed with Escape sits, or `null` when nothing is
+ * Where the marker of the list the user dismissed with Escape sits, or `null` when nothing is
* dismissed. Live, so it follows edits and lands in the graveyard if the marker is deleted.
*/
private _dismissedAt: ModelLivePosition | null = null;
@@ -92,48 +64,27 @@ export default class TriliumMentionUI extends Plugin {
return "TriliumMentionUI" as const;
}
- static get requires() {
- return [ ContextualBalloon ];
- }
-
- constructor(editor: Editor) {
- super(editor);
-
- this._view = this._createView();
- editor.config.define("mention", { feeds: [] });
- }
-
init() {
const editor = this.editor;
- this._balloon = editor.plugins.get(ContextualBalloon);
- /* v8 ignore next -- the constructor defines `mention.feeds` as `[]`, so `get()` never returns undefined; the fallback only satisfies the optional return type */
- const feeds = (editor.config.get("mention.feeds") ?? []) as TriliumMentionFeed[];
- this._patterns = feeds.map((feed) => ({ ...feed, pattern: createMarkerPattern(feed.marker, feed) }));
- this._listView = editor.config.get("mention.listView")?.(editor);
- this._hosted = (editor.config.get("mention.hostedFeeds") ?? []).map((feed) => ({
+ this._feeds = (editor.config.get("mention.hostedFeeds") ?? []).map((feed) => ({
...feed,
pattern: createMarkerPattern(feed.marker, feed),
hostedList: feed.list(editor)
}));
editor.editing.view.document.on<ViewDocumentKeyDownEvent>("keydown", (evt, data) => {
- const consumed = this._openHosted
- ? this._handleHostedKeyDown(this._openHosted.hostedList, data.keyCode, data.domEvent)
- : this._isVisible && this._handleKeyDown(data.keyCode);
- if (consumed) {
+ if (this._open && this._handleKeyDown(this._open.hostedList, data.keyCode, data.domEvent)) {
data.preventDefault();
evt.stop(); // Required to override the Enter key.
}
}, { priority: "highest" });
clickOutsideHandler({
- emitter: this._view,
- activator: () => this._isVisible,
- /* v8 ignore next -- `clickOutsideHandler` only calls `contextElements()` once the activator reported the panel visible, and a visible balloon is a rendered one, so its element is never null */
+ emitter: this._domEmitter,
+ activator: () => !!this._open?.hostedList.element,
contextElements: () => {
- const element = this._openHosted?.hostedList.element
- ?? (this._listView ? this._listView.element : this._balloon?.view.element);
+ const element = this._open?.hostedList.element;
return element ? [ element ] : [];
},
callback: () => this._hide()
@@ -146,77 +97,18 @@ export default class TriliumMentionUI extends Plugin {
override destroy() {
super.destroy();
- clearTimeout(this._feedTimer);
this._clearDismissal();
- // Balloon views are not destroyed automatically — see ckeditor5#1341.
- this._view.destroy();
- this._listView?.destroy?.();
- for (const { hostedList } of this._hosted) {
+ this._domEmitter.stopListening();
+ for (const { hostedList } of this._feeds) {
hostedList.destroy?.();
}
}
- private get _isVisible() {
- if (this._openHosted) {
- return !!this._openHosted.hostedList.element;
- }
-
- return this._listView ? this._listShown : this._balloon?.visibleView === this._view;
- }
-
- private _isCurrentRequest(requestId: number) {
- return this._requestId === requestId;
- }
-
- /**
- * Returns whether the key was consumed. Commit keys are deliberately *not* consumed when nothing
- * is selected, so that in the attribute editor — where `preselectFirstItem` is off — Enter still
- * saves instead of being swallowed by an open panel.
- */
- private _handleKeyDown(keyCode: number): boolean {
- if (keyCode === keyCodes.arrowdown || keyCode === keyCodes.arrowup) {
- if (this._listView) {
- this._moveSelection(keyCode === keyCodes.arrowdown ? 1 : -1);
- } else if (keyCode === keyCodes.arrowdown) {
- this._view.selectNext();
- } else {
- this._view.selectPrevious();
- }
- return true;
- }
-
- if (keyCode === keyCodes.esc) {
- this._dismiss();
- return true;
- }
-
- if (keyCode === keyCodes.enter || keyCode === keyCodes.tab) {
- if (this._listView) {
- const entry = this._items.get(this._selectedIndex);
- if (!entry) {
- return false;
- }
-
- this._commit(entry);
- return true;
- }
-
- if (!this._view.selected) {
- return false;
- }
-
- this._view.executeSelected();
- return true;
- }
-
- return false;
- }
-
/**
- * Hands a key to a hosted list, and returns whether it took it. Escape is handled here whatever
- * the host does, so that the dismissal is remembered as it is for a feed's list.
+ * Hands a key to the open list, and returns whether it took it. Escape is handled here whatever
+ * the host does, so that the dismissal is remembered.
*/
- private _handleHostedKeyDown(list: MentionHostedList, keyCode: number, event: KeyboardEvent): boolean {
+ private _handleKeyDown(list: MentionHostedList, keyCode: number, event: KeyboardEvent): boolean {
if (keyCode !== keyCodes.esc) {
return list.handleKeyDown(event);
}
@@ -230,7 +122,7 @@ export default class TriliumMentionUI extends Plugin {
}
/**
- * Hides the panel and remembers that the user rejected *this* marker, so it does not immediately
+ * Hides the list and remembers that the user rejected *this* marker, so it does not immediately
* reopen on the next keystroke. No document mutation is involved.
*/
private _dismiss() {
@@ -238,7 +130,7 @@ export default class TriliumMentionUI extends Plugin {
this._hide();
- /* v8 ignore next -- Escape only reaches here while the panel is visible, and the panel and the marker always come and go together, so there is always a start */
+ /* v8 ignore next -- Escape only reaches here while the list is open, and the list and the marker always come and go together, so there is always a start */
if (start) {
this._clearDismissal();
this._dismissedAt = ModelLivePosition.fromPosition(start, "toPrevious");
@@ -253,7 +145,7 @@ export default class TriliumMentionUI extends Plugin {
/**
* Whether `markerStart` is the marker the user already dismissed. A dismissal whose text has
* since been deleted (its live position landed in the graveyard) is discarded, so retyping the
- * same marker opens the panel again.
+ * same marker opens the list again.
*/
private _isDismissed(markerStart: ModelPosition): boolean {
if (!this._dismissedAt) {
@@ -273,12 +165,12 @@ export default class TriliumMentionUI extends Plugin {
// Returning the match object makes `TextWatcher` merge it into the event data, so the
// handler does not have to re-derive the block text and re-run the patterns.
- const watcher = new TextWatcher(editor.model, (text) => findMarkerMatch<Pattern | HostedPattern>([ ...this._patterns, ...this._hosted ], text) ?? false);
+ const watcher = new TextWatcher(editor.model, (text) => findMarkerMatch(this._feeds, text) ?? false);
- // Only typing opens the panel. `matched:selection` fires on any direct caret move — a click
+ // Only typing opens the list. `matched:selection` fires on any direct caret move — a click
// or an arrow key — and reopening there is the "clicking always triggers an autocomplete"
- // bug; a caret move should close the panel, whose balloon is anchored to a marker the user
- // has just navigated away from.
+ // bug; a caret move closes the list, which is anchored to a marker the user has just
+ // navigated away from.
watcher.on<TriliumMatchedEvent>("matched:data", (evt, data) => this._onTyped(data));
watcher.on("matched:selection", () => this._hide());
watcher.on("unmatched", () => {
@@ -292,7 +184,7 @@ export default class TriliumMentionUI extends Plugin {
}
}
- private _onTyped({ feed, query }: MarkerMatch<Pattern | HostedPattern>) {
+ private _onTyped({ feed, query }: MarkerMatch<Pattern>) {
const model = this.editor.model;
const focus = model.document.selection.focus;
@@ -325,135 +217,11 @@ export default class TriliumMentionUI extends Plugin {
}
});
- if ("hostedList" in feed) {
- this._showHosted(feed, query);
- return;
- }
-
- this._hideHosted();
- const requestId = ++this._requestId;
- clearTimeout(this._feedTimer);
- this._feedTimer = setTimeout(() => void this._requestFeed(feed, query, requestId), FEED_DEBOUNCE_MS);
- }
-
- private async _requestFeed(feed: TriliumMentionFeed, query: string, requestId: number) {
- let items: Array<MentionFeedObjectItem | string>;
-
- try {
- items = typeof feed.feed === "function"
- ? await feed.feed.call(this.editor, query)
- : feed.feed.filter((item) => String(typeof item === "object" ? item.id : item).toLowerCase().includes(query.toLowerCase()));
- } catch {
- // Only the request still in flight may act on a failure. Debouncing bounds how many
- // requests are *started*, not how many are outstanding, so an earlier one rejecting
- // must not tear down the panel a later one has since populated.
- if (this._isCurrentRequest(requestId)) {
- this._hide();
- }
- return;
- }
-
- // Drop out-of-order responses, and responses that arrived after the panel was dismissed or
- // the marker went away. Correlating on the request rather than the query text matters when
- // the same text is retyped, or typed under a different marker: `#al` and `~al` produce equal
- // queries but different feeds, and the stale one would otherwise fill the panel with the
- // wrong suggestions.
- if (!this._isCurrentRequest(requestId) || !this.editor.model.markers.has(MARKER_NAME)) {
- return;
- }
-
- const limit = feed.dropdownLimit ?? this.editor.config.get("mention.dropdownLimit") ?? DEFAULT_DROPDOWN_LIMIT;
-
- this._items.clear();
- for (const item of items.slice(0, limit as number)) {
- this._items.add({ item: typeof item === "object" ? item : { id: item, text: item }, marker: feed.marker });
- }
-
- if (!this._items.length) {
- this._hide();
- return;
- }
-
- this._show(feed);
- }
-
- private _show(feed: TriliumMentionFeed) {
- const marker = this.editor.model.markers.get(MARKER_NAME);
-
- /* v8 ignore next 3 -- `_requestFeed()` already returned unless the marker is still registered, and `_balloon` is assigned in `init()`; the guard only narrows both types */
- if (!marker || !this._balloon) {
- return;
- }
-
- if (this._listView) {
- // Pre-selecting the first item makes Enter always commit *something*; see below.
- this._selectedIndex = (feed.preselectFirstItem ?? true) ? 0 : -1;
- this._listShown = true;
- this._drawList(marker);
- return;
- }
-
- // The add/update decision keys off *membership*, not visibility: `ContextualBalloon.add()`
- // throws `contextualballoon-add-view-exist` for a view that is already registered in any
- // stack, visible or not. Upstream's `MentionUI` branches on visibility here and so crashes
- // as soon as another plugin's balloon (added with `singleViewMode`) buries the panel.
- // Rendered ahead of `ContextualBalloon.add()`, which would otherwise render it, so the height
- // is capped before the first placement measures the panel.
- if (!this._view.isRendered) {
- this._view.render();
- }
- const preferAbove = this._fitToVisibleViewport(marker);
-
- if (!this._balloon.hasView(this._view)) {
- this._balloon.add({
- view: this._view,
- position: this._positionData(marker, preferAbove),
- singleViewMode: true,
- balloonClassName: "ck-mention-balloon"
- });
- } else if (this._isVisible) {
- this._balloon.updatePosition(this._positionData(marker, preferAbove));
- }
-
- this._view.position = this._balloon.view.position;
-
- // Pre-selecting the first item makes Enter always commit *something*. That is right for the
- // note editor, but wrong in the attribute editor, where Enter means "save".
- if (feed.preselectFirstItem ?? true) {
- this._view.selectFirst();
- } else {
- this._view.selected?.removeHighlight();
- this._view.selected = undefined;
- }
- }
-
- private _hide() {
- clearTimeout(this._feedTimer);
- this._hideHosted();
- this._hideFeedList();
-
- if (this.editor.model.markers.has(MARKER_NAME)) {
- this.editor.model.change((writer) => writer.removeMarker(MARKER_NAME));
- }
- }
-
- /** Hides a feed's list, in {@link _listView} or the balloon, and leaves the marker. */
- private _hideFeedList() {
- if (this._listShown) {
- this._listShown = false;
- this._selectedIndex = -1;
- this._listView?.hide();
- }
-
- if (this._balloon?.hasView(this._view)) {
- this._balloon.remove(this._view);
- }
-
- this._view.position = undefined;
+ this._show(feed, query);
}
/** Shows the host's list of `feed` for `query`, in place of any other list. */
- private _showHosted(feed: HostedPattern, query: string) {
+ private _show(feed: Pattern, query: string) {
const marker = this.editor.model.markers.get(MARKER_NAME);
/* v8 ignore next 3 -- `_onTyped()` sets the marker just before calling this; the guard only narrows its type */
@@ -461,15 +229,11 @@ export default class TriliumMentionUI extends Plugin {
return;
}
- // A feed's request still pending would otherwise open its list over this one.
- clearTimeout(this._feedTimer);
- this._requestId++;
- this._hideFeedList();
- if (this._openHosted !== feed) {
- this._hideHosted();
+ if (this._open !== feed) {
+ this._hideList();
}
- this._openHosted = feed;
+ this._open = feed;
feed.hostedList.show({
query,
caretRect: () => {
@@ -477,13 +241,22 @@ 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, item)
+ commit: (item) => this._commit(feed, item)
});
}
- private _hideHosted() {
- const open = this._openHosted;
- this._openHosted = null;
+ private _hide() {
+ this._hideList();
+
+ if (this.editor.model.markers.has(MARKER_NAME)) {
+ this.editor.model.change((writer) => writer.removeMarker(MARKER_NAME));
+ }
+ }
+
+ /** Hides the open list, and leaves the marker. */
+ private _hideList() {
+ const open = this._open;
+ this._open = null;
open?.hostedList.hide();
}
@@ -491,7 +264,7 @@ export default class TriliumMentionUI extends Plugin {
* 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(feed: HostedPattern, item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined>) {
+ private _commit(feed: Pattern, item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined>) {
const editor = this.editor;
const model = editor.model;
const marker = model.markers.get(MARKER_NAME);
@@ -502,16 +275,20 @@ export default class TriliumMentionUI extends Plugin {
return;
}
+ // Everything from the marker up to the caret, not just the marker itself.
const range = ModelLiveRange.fromRange(model.createRange(marker.getStart(), focus));
this._hide();
this._clearDismissal();
const insert = (mention: MentionFeedObjectItem | undefined) => {
- // The text can have been deleted while a promise was pending. An item gone stale keeps
- // the text, as in `_commit()`.
+ // The text can have been deleted while a promise was pending. An item gone stale while
+ // the list was open, such as a `/` command that lost `isEnabled`, keeps the text, which
+ // committing it would delete for nothing.
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
+ // The text goes first, so the callback sees a collapsed selection where the query
+ // was, and the callback runs outside the change block, as some open a balloon
+ // (`/math`, `/anchor`) that needs a settled view. 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)));
@@ -532,154 +309,13 @@ export default class TriliumMentionUI extends Plugin {
}
}
- private _createView(): MentionsView {
- const locale = this.editor.locale;
- const view = new MentionsView(locale);
-
- view.items.bindTo(this._items).using(({ item, marker }) => {
- const listItem = new MentionListItemView(locale);
- const child = this._renderItem(item, marker);
-
- child.delegate("execute").to(listItem);
- listItem.children.add(child);
- listItem.item = item;
- listItem.marker = marker;
- listItem.on("execute", () => view.fire("execute", { item, marker }));
-
- return listItem;
- });
-
- view.on("execute", (evt, data) => this._commit(data));
-
- return view;
- }
-
- /** Replaces the trigger text with `item`, or hands it to its feed's `commit`. */
- private _commit(data: { item: MentionFeedObjectItem; marker: string }) {
- const editor = this.editor;
- const model = editor.model;
- const marker = model.markers.get(MARKER_NAME);
- const focus = model.document.selection.focus;
-
- /* v8 ignore next 3 -- an entry is only committed while the list is visible, which means the marker is registered, and a live selection always has a focus */
- if (!marker || !focus) {
- return;
- }
-
- // Replace everything from the marker up to the caret, not just the marker itself.
- const range = model.createRange(model.createPositionAt(marker.getStart()), model.createPositionAt(focus));
- const feed = this._patterns.find((pattern) => pattern.marker === data.marker);
-
- this._hide();
- this._clearDismissal();
-
- // Bail before deleting anything if the item went stale while it sat in the open panel —
- // a `/` command that lost `isEnabled` as the selection settled. Committing it would drop
- // the trigger text and then no-op, eating what the user typed.
- if (feed?.canCommit && !feed.canCommit(editor, data.item)) {
- return;
- }
-
- if (feed?.commit) {
- // Drop the trigger text first so the callback sees a collapsed selection where the
- // query used to be, and run it outside the change block — some callbacks open a
- // balloon (`/math`, `/anchor`) rather than touching the model, which needs a settled
- // view. Focus is restored *before* the callback for the same reason: one that opens
- // a UI takes focus itself, and must do so last.
- model.change((writer) => model.deleteContent(writer.createSelection(range)));
- editor.editing.view.focus();
- feed.commit(editor, data.item);
- } else {
- editor.execute("mention", { mention: data.item, text: data.item.text, marker: data.marker, range });
- editor.editing.view.focus();
- }
- }
-
- /** Hands the entries and the selection to {@link _listView}, which draws them at the caret. */
- private _drawList(marker: Marker) {
- const entries = this._items.map(({ item, marker: feedMarker }) => ({
- item,
- marker: feedMarker,
- render: () => this._patterns.find((feed) => feed.marker === feedMarker)?.itemRenderer?.(item)
- }));
-
- this._listView?.show({
- entries,
- selectedIndex: this._selectedIndex,
- caretRect: () => {
- const { left, top, width, height } = this._caretRect(marker);
- return new DOMRect(left, top, width, height);
- },
- editable: this.editor.editing.view.getDomRoot() ?? null,
- select: (index) => {
- this._selectedIndex = index;
- this._drawList(marker);
- },
- pick: (index) => {
- const entry = this._items.get(index);
- if (entry) {
- this._commit(entry);
- }
- }
- });
- }
-
- /** Steps the selection of {@link _listView}, wrapping at either end, as `MentionsView` does. */
- private _moveSelection(delta: number) {
- const marker = this.editor.model.markers.get(MARKER_NAME);
- const count = this._items.length;
-
- /* v8 ignore next 3 -- the keys only reach here while the list is shown, which means it has entries and a marker */
- if (!marker || !count) {
- return;
- }
-
- this._selectedIndex = this._selectedIndex < 0
- ? (delta > 0 ? 0 : count - 1)
- : (this._selectedIndex + delta + count) % count;
- this._drawList(marker);
- }
-
- private _renderItem(item: MentionFeedObjectItem, marker: string): MentionDomWrapperView | ButtonView {
- const rendered = this._patterns.find((feed) => feed.marker === marker)?.itemRenderer?.(item);
-
- if (rendered && typeof rendered !== "string") {
- return new MentionDomWrapperView(this.editor.locale, rendered);
- }
-
- const button = new ButtonView(this.editor.locale);
- button.label = rendered ?? item.id;
- button.withText = true;
-
- return button;
- }
-
- /**
- * Caps the list's height to the larger of the spaces above and below the caret in the visible
- * viewport, which on a phone excludes the on-screen keyboard. Returns whether the panel opens above
- * the caret.
- */
- private _fitToVisibleViewport(marker: Marker): boolean {
- const caret = this._caretRect(marker);
- const viewport = window.visualViewport;
- const visibleTop = viewport?.offsetTop ?? 0;
- const visibleBottom = viewport ? viewport.offsetTop + viewport.height : window.innerHeight;
-
- const below = visibleBottom - caret.bottom - VERTICAL_SPACING - VIEWPORT_MARGIN;
- const above = caret.top - visibleTop - VERTICAL_SPACING - VIEWPORT_MARGIN;
- const preferAbove = below < MIN_LIST_HEIGHT && above > below;
-
- this._view.element?.style.setProperty("--tn-mention-visible-height", `${Math.max(preferAbove ? above : below, 0)}px`);
- return preferAbove;
- }
-
- /** The rect the panel is placed against: the end of the marker, or of the selection once it is gone. */
+ /** The rect the list is placed against: the end of the marker, or of the selection once it is gone. */
private _caretRect(marker: Marker): Rect {
const editing = this.editor.editing;
let range = marker.getRange();
- // The marker may already be gone; fall back to the selection so ContextualBalloon
- // can still place a panel here.
+ // The marker can already be gone; fall back to the selection, so the list can still be
+ // placed here.
if (range.start.root.rootName === "$graveyard") {
/* v8 ignore next -- the document selection always holds at least one range, so the `?? range` arm never runs */
range = this.editor.model.document.selection.getFirstRange() ?? range;
@@ -690,26 +326,11 @@ export default class TriliumMentionUI extends Plugin {
return rects[rects.length - 1];
}
-
- private _positionData(marker: Marker, preferAbove: boolean): Partial<DomOptimalPositionOptions> {
- const editing = this.editor.editing;
-
- return {
- target: () => this._caretRect(marker),
- limiter: () => {
- const editable = editing.view.document.selection.editableElement;
-
- /* v8 ignore next -- the editing view selection is inside the root editable whenever the panel is positioned, so the `null` arm only satisfies the limiter's return type */
- return editable ? editing.view.domConverter.mapViewToDom(editable.root) as HTMLElement : null;
- },
- positions: balloonPositions(this._view.position, this.editor.locale.uiLanguageDirection, preferAbove)
- };
- }
}
type TriliumMatchedEvent = {
name: "matched:data";
- args: [ MarkerMatch<Pattern | HostedPattern> & { text: string } ];
+ args: [ MarkerMatch<Pattern> & { text: string } ];
};
function isInExistingMention(position: ModelPosition): boolean {
@@ -727,44 +348,3 @@ function isBeforeExistingMention(markerPosition: ModelPosition): boolean {
const after = markerPosition.nodeAfter;
return !!after && after.is("$text") && after.hasAttribute("mention");
}
-
-/**
- * Balloon placement callbacks, anchored to the caret. Lifted from upstream's
- * `getBalloonPanelPositions()`, which is module-private, with each corner slid sideways to stay
- * within the viewport.
- *
- * The position that matched last comes first, so the panel does not jump as the list grows, but the
- * others follow it, so a panel that no longer fits there can move. `preferAbove` puts the corners
- * above the caret first.
- *
- * Exported for its own tests.
- */
-export function balloonPositions(preferred: string | undefined, uiLanguageDirection: string, preferAbove = false): DomOptimalPositionOptions["positions"] {
- const below = (target: Rect) => target.bottom + VERTICAL_SPACING;
- const above = (target: Rect, balloon: Rect) => target.top - balloon.height - VERTICAL_SPACING;
- const fromCaret = (target: Rect) => target.right;
- const toCaret = (target: Rect, balloon: Rect) => target.right - balloon.width;
-
- const positions: Record<string, DomOptimalPositionOptions["positions"][0]> = {
- caret_se: (target, balloon, viewport) => corner("caret_se", below(target), fromCaret(target), balloon, viewport),
- caret_ne: (target, balloon, viewport) => corner("caret_ne", above(target, balloon), fromCaret(target), balloon, viewport),
- caret_sw: (target, balloon, viewport) => corner("caret_sw", below(target), toCaret(target, balloon), balloon, viewport),
- caret_nw: (target, balloon, viewport) => corner("caret_nw", above(target, balloon), toCaret(target, balloon), balloon, viewport)
- };
-
- const south = uiLanguageDirection !== "rtl" ? [ "caret_se", "caret_sw" ] : [ "caret_sw", "caret_se" ];
- const north = uiLanguageDirection !== "rtl" ? [ "caret_ne", "caret_nw" ] : [ "caret_nw", "caret_ne" ];
- const order = preferAbove ? [ ...north, ...south ] : [ ...south, ...north ];
- if (preferred && order.includes(preferred)) {
- order.splice(order.indexOf(preferred), 1);
- order.unshift(preferred);
- }
-
- return order.map((name) => positions[name]);
-}
-
-function corner(name: string, top: number, left: number, balloon: Rect, viewport: Rect) {
- const fittedLeft = Math.max(viewport.left + VIEWPORT_MARGIN, Math.min(left, viewport.right - VIEWPORT_MARGIN - balloon.width));
-
- return { top, left: fittedLeft, name, config: { withArrow: false } };
-}
diff --git a/packages/ckeditor5/src/plugins/mention/types.ts b/packages/ckeditor5/src/plugins/mention/types.ts
index 84cc3b875b..d541e418f7 100644
--- a/packages/ckeditor5/src/plugins/mention/types.ts
+++ b/packages/ckeditor5/src/plugins/mention/types.ts
@@ -1,111 +1,11 @@
import type { Editor, MentionFeedObjectItem } from "ckeditor5";
-import type { MentionFeed } from "ckeditor5";
/**
- * The extra per-feed knobs {@link TriliumMentionUI} understands, merged into upstream's
- * `MentionFeed` so that `EditorConfig["mention"].feeds` accepts them directly at every call site.
- *
- * The augmentation targets `@ckeditor/ckeditor5-mention` rather than `ckeditor5`, because the
+ * Merged into upstream's `MentionConfig` so that `EditorConfig["mention"]` accepts it at every call
+ * site. The augmentation targets `@ckeditor/ckeditor5-mention` rather than `ckeditor5`, because the
* umbrella package is a pure re-export barrel and augmenting it would declare a new interface
- * instead of merging into the existing one. It lives in this module — reachable from the package
- * entry point via the `TriliumMentionFeed` re-export — rather than in `augmentation.ts`, whose
- * `declare global` block would then leak this package's narrower `glob` type into consumers.
+ * instead of merging into the existing one.
*/
-declare module "@ckeditor/ckeditor5-mention" {
- interface MentionFeed {
- /**
- * Whether the query may contain spaces. Note titles do (`@My meeting notes`), attribute
- * names never do — and allowing them there means `#foo bar baz` keeps matching forever, so
- * the panel can never close on its own. Defaults to `false`.
- */
- allowSpaces?: boolean;
-
- /**
- * Whether the first suggestion is highlighted as soon as the panel opens, so that Enter
- * commits it. Defaults to `true`, matching upstream. The attribute editor turns it off:
- * there Enter means "save the attributes", and a panel that pre-selects an item silently
- * hijacks it.
- */
- preselectFirstItem?: boolean;
-
- /**
- * Whether the picked item can still be committed, checked the instant the user commits it —
- * before the trigger text is removed. Returning `false` closes the panel without touching
- * the document, so the user keeps what they typed. Feeds that omit it always commit.
- *
- * The `/` palette needs it: an entry's command can lose `isEnabled` between the keystroke
- * that listed it and the Enter that commits it, and since committing first deletes the
- * `/query`, an unchecked no-op would eat the input. The query-time filter cannot cover that
- * window, because no keystroke re-runs the feed once the selection has settled.
- */
- canCommit?: ( editor: Editor, item: MentionFeedObjectItem ) => boolean;
-
- /**
- * What to do when the user picks an item, called with the trigger text (the marker and the
- * query) already removed and the selection collapsed in its place.
- *
- * Feeds that omit it fall back to `editor.execute( "mention", … )`, which is what upstream
- * always does and what the `@`/`#`/`~` feeds rely on. Feeds that insert something other than
- * a mention — an emoji, a heading — provide it instead of piggy-backing on the `mention`
- * command, so they neither depend on nor have to work around `CustomMentionCommand`.
- */
- commit?: ( editor: Editor, item: MentionFeedObjectItem ) => void;
- }
-}
-
-/**
- * A mention feed as {@link TriliumMentionUI} consumes it — an alias for the augmented `MentionFeed`
- * that exists to name the Trilium-flavoured shape at call sites.
- */
-export type TriliumMentionFeed = MentionFeed;
-
-declare module "@ckeditor/ckeditor5-mention" {
- interface MentionConfig {
- /**
- * Draws the suggestion list in place of CKEditor's balloon, for a host that draws its own
- * lists. Called once per editor. {@link TriliumMentionUI} still owns when the list opens and
- * closes, which entry is selected, the keys and the commit.
- */
- listView?: ( editor: Editor ) => MentionListView;
- }
-}
-
-/** One entry of the list, as {@link MentionListView.show} receives it. */
-export interface MentionListEntry {
- item: MentionFeedObjectItem;
- /** The marker of the feed the entry comes from, such as `@`. */
- marker: string;
- /** Runs the feed's `itemRenderer`, for an entry the view has no rendering of its own for. */
- render(): HTMLElement | string | undefined;
-}
-
-/** What a {@link MentionListView} draws, each time the list or its selection changes. */
-export interface MentionListState {
- entries: readonly MentionListEntry[];
- /** The highlighted entry, or `-1` where none is. */
- selectedIndex: number;
- /** Where the caret ends the query, in viewport coordinates. */
- caretRect(): DOMRect;
- /**
- * The editable element the caret is in. A view anchored at {@link caretRect} watches the
- * containers around it, so the list follows the caret as they scroll.
- */
- editable: HTMLElement | null;
- /** Highlights an entry, as the pointer moving over it does. */
- select( index: number ): void;
- /** Commits an entry, as a click on it does. */
- pick( index: number ): void;
-}
-
-/** A host's own drawing of the suggestion list. See `mention.listView`. */
-export interface MentionListView {
- show( state: MentionListState ): void;
- hide(): void;
- /** The list's element while it is shown, inside which a press does not close it. */
- readonly element: HTMLElement | null;
- destroy?(): void;
-}
-
declare module "@ckeditor/ckeditor5-mention" {
interface MentionConfig {
/**
@@ -121,15 +21,38 @@ declare module "@ckeditor/ckeditor5-mention" {
/** A marker whose list the host runs. See `mention.hostedFeeds`. */
export interface MentionHostedFeed {
marker: string;
- /** See `MentionFeed.minimumCharacters`. */
+ /**
+ * How many characters must follow the marker before the list opens. `0`, the default, opens it
+ * on the bare marker.
+ */
minimumCharacters?: number;
- /** See `MentionFeed.allowSpaces`. */
+ /**
+ * Whether the query can contain spaces. Note titles do (`@My meeting notes`), attribute names
+ * never do — and allowing them there means `#foo bar baz` keeps matching forever, so the list can
+ * never close on its own. Defaults to `false`.
+ */
allowSpaces?: boolean;
/** Creates the list, once per editor. */
list( editor: Editor ): MentionHostedList;
- /** See `MentionFeed.canCommit`, for what the list commits. */
+ /**
+ * Whether the item the list commits can still be committed, checked before the trigger text is
+ * removed. Returning `false` leaves the document as it is, so the user keeps what they typed.
+ * Feeds that omit it always commit.
+ *
+ * The `/` palette needs it: an entry's command can lose `isEnabled` between the keystroke that
+ * listed it and the Enter that commits it, and since committing first deletes the `/query`, an
+ * unchecked no-op would eat the input.
+ */
canCommit?: ( editor: Editor, item: MentionFeedObjectItem ) => boolean;
- /** See `MentionFeed.commit`, for what the list commits. */
+ /**
+ * What to do with the item the list commits, called with the trigger text (the marker and the
+ * query) already removed and the selection collapsed in its place.
+ *
+ * Feeds that omit it fall back to `editor.execute( "mention", … )`, which is what the `@`, `#` and
+ * `~` feeds rely on. Feeds that insert something other than a mention — an emoji, a heading —
+ * provide it instead of piggy-backing on the `mention` command, so they neither depend on nor
+ * have to work around `CustomMentionCommand`.
+ */
commit?: ( editor: Editor, item: MentionFeedObjectItem ) => void;
}
@@ -139,7 +62,10 @@ export interface MentionHostedListState {
query: string;
/** Where the caret ends the query, in viewport coordinates. */
caretRect(): DOMRect;
- /** The editable element the caret is in. See {@link MentionListState.editable}. */
+ /**
+ * The editable element the caret is in. A list anchored at {@link caretRect} watches the
+ * containers around it, so the list follows the caret as they scroll.
+ */
editable: HTMLElement | null;
/**
* Replaces the marker and the query with a mention of `item`, or hands `item` to the feed's