Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(text): draw mentions in the note autocomplete's popup
Elian Doranc668609266b1
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.tsindex 5ffc04f5c2..a11a067fa6 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete.spec.ts@@ -159,7 +159,7 @@ describe("getNoteSuggestions", () => {});describe("autocompleteSourceForCKEditor", () => {- it("maps the rows into mention feed items, creation rows first", async () => {+ it("maps the rows into mention feed items, in the note autocomplete's order", async () => {server.get = vi.fn(async () => [ {noteTitle: "Foo",notePathTitle: "Root / Foo",@@ -169,8 +169,8 @@ describe("autocompleteSourceForCKEditor", () => {} ]) as typeof server.get;const items = await noteAutocomplete.autocompleteSourceForCKEditor("Foo");- expect(items.map((item) => (item as Suggestion).action)).toEqual([ "create-note", "create-child-note", undefined ]);- expect(items[2]).toEqual({+ expect(items.map((item) => (item as Suggestion).action)).toEqual([ undefined, "create-note", "create-child-note" ]);+ expect(items[0]).toEqual({action: undefined,noteTitle: "Foo",id: "@Root / Foo",@@ -181,7 +181,7 @@ describe("autocompleteSourceForCKEditor", () => {icon: "bx bx-note"});// A creation row has no path title of its own.- expect(items[0]).toMatchObject({ id: "@undefined", name: "" });+ expect(items[1]).toMatchObject({ id: "@undefined", name: "" });});it("omits the creation rows when the host cannot act on them", async () => {diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex 3bf99d57d9..c35b54318b 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -45,13 +45,12 @@ export interface Options {* Feeds a CKEditor mention. Creation entries are offered only where the editor's host component* implements `createNoteForReferenceLink`, which is what `MentionCustomization` calls to act on* them.+ *+ * The creation entries come last, so a feed using this source sets `dropdownLimit` to+ * `Number.MAX_SAFE_INTEGER`: the plugin's default limit of 10 cuts them off after the notes.*/async function autocompleteSourceForCKEditor(queryText: string, allowCreatingNotes = true): Promise<MentionFeedObjectItem[]> {const rows = await getNoteSuggestions(queryText, { allowCreatingNotes });- // The creation rows go first here: the mention list renders only the first- // `mention.dropdownLimit` items, which a long result list would push them past.- const isCreation = (row: Suggestion) => row.action === "create-note" || row.action === "create-child-note";- rows.sort((a, b) => Number(isCreation(b)) - Number(isCreation(a)));return rows.map((row) => ({action: row.action,diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 74c91cdf37..9817070238 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1903,25 +1903,6 @@ body.desktop .dropdown-submenu > .dropdown-menu {max-height: min(var(--ck-mention-list-max-height), var(--tn-mention-visible-height, 100vh));}-/*- * A note suggestion is an icon beside a note path. Laid out as a row so the two are centred against- * each other: left inline, the icon aligns on the text baseline, and `vertical-align: middle` only- * gets it as far as the x-height — about a pixel below where the capitals it sits beside read as- * centred. The icon carries its own font, so no baseline rule can line the two up in general.- */-.ck.ck-mentions .ck-button.note-mention-suggestion {- display: flex;- align-items: center;- gap: 0.4em;- text-align: start;-}--/* Its own box, so the row centres the glyph itself rather than the line box around it. */-.ck.ck-mentions .ck-button.note-mention-suggestion > .bx {- line-height: 1;- flex-shrink: 0;-}-/* Slash commands */.ck.ck-slash-command-button {diff --git a/apps/client/src/widgets/react/Popup.tsx b/apps/client/src/widgets/react/Popup.tsxindex 2e084b9284..04787cb701 100644--- a/apps/client/src/widgets/react/Popup.tsx+++ b/apps/client/src/widgets/react/Popup.tsx@@ -13,8 +13,11 @@ import { useCallback, useContext, useLayoutEffect, useMemo, useRef } from "preac*/export interface PopupProps extends Pick<HTMLAttributes<HTMLDivElement>, "id" | "className" | "role" | "style" | "tabIndex"| "onClick" | "onPointerMove" | "onContextMenu" | "aria-labelledby"> {- /** What it stands beside: an element, or a point in the viewport such as where a right-click landed. */- anchor: HTMLElement | { x: number, y: number };+ /**+ * What it stands beside: an element, a point in the viewport such as where a right-click landed,+ * or a rect that is no element, such as a text editor's caret.+ */+ anchor: HTMLElement | { x: number, y: number } | ReferenceElement;/*** The side of the anchor it prefers, flipped to the other side where that one has no room.* Below the anchor, lined up with its start, by default.@@ -113,7 +116,7 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapreportPlaced();return;}- const reference = anchor instanceof HTMLElement ? anchor : pointAt(anchor.x, anchor.y);+ const reference = "x" in anchor ? pointAt(anchor.x, anchor.y) : anchor;// A placement settles after the fact, by which time it can have closed.let closed = false;// Places it now, and again whenever its anchor moves or the viewport or it changes size.@@ -127,7 +130,7 @@ export default function Popup({ anchor, placement = "bottom-start", offset: gapclosed = true;stopUpdating();};- }, [ anchor instanceof HTMLElement ? anchor : undefined, anchorX, anchorY, placement, gap, capHeight, placedByStylesheet ]);+ }, [ "x" in anchor ? undefined : anchor, anchorX, anchorY, placement, gap, capHeight, placedByStylesheet ]);const dismiss = useRef(onDismiss);dismiss.current = onDismiss;diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex e873af033f..71fde158d7 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -19,7 +19,7 @@ import froca from "../../../services/froca";import { t } from "../../../services/i18n";import { ATTRIBUTE_HELP_PAGE } from "../../../services/in_app_help";import link from "../../../services/link";-import note_autocomplete, { Suggestion } from "../../../services/note_autocomplete";+import note_autocomplete from "../../../services/note_autocomplete";import note_create from "../../../services/note_create";import server from "../../../services/server";import { isIMEComposing } from "../../../services/shortcuts";@@ -29,6 +29,7 @@ import ActionButton from "../../react/ActionButton";import CKEditor, { CKEditorApi } from "../../react/CKEditor";import HelpDropdown from "../../react/HelpDropdown";import { useLegacyImperativeHandlers, useLegacyWidget, useTriliumEvent } from "../../react/hooks";+import { createMentionListView } from "../../type_widgets/text/mention_list_view";import AttributeHelp from "./AttributeHelp";type AttributeCommandNames = FilteredCommandNames<CommandData>;@@ -45,15 +46,8 @@ const mentionSetup: TriliumMentionFeed[] = [{marker: "@",feed: (queryText) => note_autocomplete.autocompleteSourceForCKEditor(queryText),- itemRenderer: (_item) => {- const item = _item as Suggestion;- const itemElement = document.createElement("button");-- itemElement.innerHTML = `${item.highlightedNotePathTitle} `;-- return itemElement;- },minimumCharacters: 0,+ dropdownLimit: Number.MAX_SAFE_INTEGER,// Relation targets are note titles, which contain spaces.allowSpaces: true,preselectFirstItem: false@@ -309,7 +303,7 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxIconfig={{toolbar: { items: [] },placeholder: t("attribute_editor.placeholder"),- mention: { feeds: mentionSetup },+ mention: { feeds: mentionSetup, listView: createMentionListView },licenseKey: "GPL",language: "en"}}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 218295bd02..ddcd25628a 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -7,7 +7,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";import link from "../../../services/link.js";-import note_autocomplete, { type Suggestion } from "../../../services/note_autocomplete.js";+import note_autocomplete from "../../../services/note_autocomplete.js";import options from "../../../services/options.js";import ActionButton from "../../react/ActionButton.js";import Button from "../../react/Button.js";@@ -19,6 +19,7 @@ import LightboxLink from "../../react/LightboxLink.js";import MaskedIcon from "../../react/MaskedIcon.js";import AddProviderModal, { type LlmProviderConfig, type ProviderStep } from "../options/llm/AddProviderModal.js";import { providerIconUrl } from "../options/llm/provider_icons.js";+import { createMentionListView } from "../text/mention_list_view.js";import { computeContextUsage } from "./chat_context_usage.js";import { insertNewBlock as insertNewBlockCommand, isSelectionInCodeBlock, outdentListItemAtStart } from "./chat_input_editing.js";import { editorHtmlToMarkdown } from "./chat_input_markdown.js";@@ -35,21 +36,8 @@ const mentionFeeds: MentionFeed[] = [{marker: "@",feed: (queryText) => note_autocomplete.autocompleteSourceForCKEditor(queryText, false),- itemRenderer: (rawItem) => {- const item = rawItem as Suggestion;- const itemElement = document.createElement("button");-- const iconElement = document.createElement("span");- iconElement.className = item.icon ?? "bx bx-note";-- itemElement.append(iconElement, document.createTextNode(" "));- const titleContainer = document.createElement("span");- titleContainer.innerHTML = item.highlightedNotePathTitle ?? "";- itemElement.append(...titleContainer.childNodes, document.createTextNode(" "));-- return itemElement;- },minimumCharacters: 0,+ dropdownLimit: Number.MAX_SAFE_INTEGER,// Note titles contain spaces, so the query must be allowed to as well.allowSpaces: true}@@ -325,7 +313,7 @@ export default function ChatInputBar({extraPlugins: ckEditor.plugins,toolbar: { items: [] },placeholder: t("llm_chat.placeholder"),- mention: { feeds: mentionFeeds },+ mention: { feeds: mentionFeeds, listView: createMentionListView },licenseKey: "GPL"}}// The strings the box shows of its own — the link balloon it raises on Ctrl+K —diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 2002d7bfe9..4ea470368c 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -6,6 +6,7 @@ import imageService from "../../../services/image.js";import noteAutocompleteService from "../../../services/note_autocomplete.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(() => ({@@ -103,12 +104,6 @@ function baseOpts(overrides: Partial<BuildEditorOptions> = {}): BuildEditorOptio};}-interface MentionSuggestion {- icon?: string;- action?: string;- highlightedNotePathTitle?: string;-}-/** The dynamically-attached config members that CKEditor's `EditorConfig` type doesn't declare. */interface DynamicConfig {renderShortcut(shortcut: string): string;@@ -124,9 +119,11 @@ interface DynamicConfig {feeds: {marker: string;minimumCharacters: number;+ dropdownLimit?: number;feed(queryText: string): Promise<unknown>;- itemRenderer(item: MentionSuggestion): HTMLElement;+ itemRenderer?: unknown;}[];+ listView?: unknown;};}@@ -570,40 +567,27 @@ describe("CK config - lazy loaders", () => {});describe("CK config - mention feed", () => {- it("is omitted when note completion is disabled", async () => {- const config = await buildDynamicConfig();- expect(config.mention).toBeUndefined();- });+ it("draws the list as the note autocomplete's, with the @ feed only when note completion is enabled", async () => {+ const off = await buildDynamicConfig();+ expect(off.mention?.feeds).toEqual([]);+ // The `/` and emoji feeds the plugins add are drawn through it all the same.+ expect(off.mention?.listView).toBe(createMentionListView);- it("builds the @-mention feed and renders suggestions when note completion is enabled", async () => {optionsState.map["textNoteCompletionEnabled"] = "true";const config = await buildDynamicConfig();+ expect(config.mention?.listView).toBe(createMentionListView);const feedConfig = config.mention?.feeds[0];if (!feedConfig) throw new Error("expected the mention feed to be configured");expect(feedConfig.marker).toBe("@");expect(feedConfig.minimumCharacters).toBe(0);+ // The creation rows come after every note.+ expect(feedConfig.dropdownLimit).toBe(Number.MAX_SAFE_INTEGER);+ // The view draws a note as the note autocomplete does, so the feed renders nothing itself.+ expect(feedConfig.itemRenderer).toBeUndefined();await feedConfig.feed("query-text");expect(noteAutocompleteService.autocompleteSourceForCKEditor).toHaveBeenCalledWith("query-text");-- // A normal note suggestion keeps its own icon and renders its highlighted title.- const noteItem = feedConfig.itemRenderer({ icon: "bx bx-folder", action: "open", highlightedNotePathTitle: "<b>Hello</b>" });- expect(noteItem.tagName).toBe("BUTTON");- expect((noteItem.firstChild as HTMLElement).className).toBe("bx bx-folder");- expect(noteItem.querySelector("b")?.textContent).toBe("Hello");-- // The row is exactly the icon and a wrapped title: the stylesheet lays the two out against- // each other, which it cannot do if the title is spread into the button as loose nodes.- expect(noteItem.className).toBe("note-mention-suggestion");- expect(noteItem.childNodes).toHaveLength(2);- const title = noteItem.querySelector(".note-mention-suggestion-title");- expect(title?.textContent).toBe("Hello");-- // A "create note" suggestion with no icon/title gets the plus icon and an empty title.- const createItem = feedConfig.itemRenderer({ action: "create-note" });- expect((createItem.firstChild as HTMLElement).className).toBe("bx bx-plus");- expect(createItem.querySelector("b")).toBeNull();});});diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 9ab5bf598a..181a5e6f8e 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -8,7 +8,7 @@ import { t } from "../../../services/i18n.js";import imageService from "../../../services/image.js";import { getMermaidConfig } from "../../../services/mermaid.js";import { default as mimeTypesService, getHighlightJsNameForMime } from "../../../services/mime_types.js";-import noteAutocompleteService, { type Suggestion } from "../../../services/note_autocomplete.js";+import noteAutocompleteService from "../../../services/note_autocomplete.js";import options from "../../../services/options.js";import { sanitizeNoteContentHtml } from "../../../services/sanitize_content.js";import { ensureMimeTypesForHighlighting, isSyntaxHighlightEnabled } from "../../../services/syntax_highlight.js";@@ -19,6 +19,7 @@ import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";import diffAiResponse from "./ai_diff.js";import { buildFontColorConfig, buildTableColorConfig } from "./color_palette.js";+import { createMentionListView } from "./mention_list_view.js";import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";import { buildToolbarConfig } from "./toolbar.js";@@ -302,45 +303,20 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConficonfig.typing = { transformations: buildTransformationsConfig(contentLanguage) };- // Mention customisation.- if (options.get("textNoteCompletionEnabled") === "true") {- config.mention = {- feeds: [- {- marker: "@",- feed: (queryText: string) => noteAutocompleteService.autocompleteSourceForCKEditor(queryText),- itemRenderer: (item) => {- const suggestion = item as Suggestion;- const itemElement = document.createElement("button");- itemElement.className = "note-mention-suggestion";-- const iconElement = document.createElement("span");- // Choose appropriate icon based on action- let iconClass = suggestion.icon ?? "bx bx-note";- if (suggestion.action === "create-note") {- iconClass = "bx bx-plus";- } else if (suggestion.action === "create-child-note") {- iconClass = "bx bx-subdirectory-right";- }- iconElement.className = iconClass;-- // The title keeps a wrapper of its own rather than being spread into the- // button: the row lays the icon out against the title as a whole (see the- // `note-mention-suggestion` rule), which it cannot do over loose text nodes.- const titleContainer = document.createElement("span");- titleContainer.className = "note-mention-suggestion-title";- titleContainer.innerHTML = suggestion.highlightedNotePathTitle ?? "";- itemElement.append(iconElement, titleContainer);-- return itemElement;- },- minimumCharacters: 0,- // Note titles contain spaces, so the query must be allowed to as well.- allowSpaces: true- }- ],- };- }+ // Set without the `@` feed too: the `/` and emoji feeds the plugins add are drawn through it.+ config.mention = {+ feeds: options.get("textNoteCompletionEnabled") === "true" ? [+ {+ marker: "@",+ feed: (queryText: string) => noteAutocompleteService.autocompleteSourceForCKEditor(queryText),+ minimumCharacters: 0,+ dropdownLimit: Number.MAX_SAFE_INTEGER,+ // Note titles contain spaces, so the query must be allowed to as well.+ allowSpaces: true+ }+ ] : [],+ listView: createMentionListView+ };return {...config,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.cssnew file mode 100644index 0000000000..7f92b1fc71--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.css@@ -0,0 +1,24 @@+/*+ * A feed's own rows (attribute names, `/` commands, emoji) are CKEditor buttons. The menu row draws+ * the highlight and the padding, so the button draws neither: its own `:hover` and `:focus` rules+ * outweigh a plain class pair, hence the repeated class.+ */+.mention-list-menu .ck.ck-button.ck-button {+ width: 100%;+ min-height: 0;+ padding: 0;+ border: 0;+ box-shadow: none;+ color: inherit;+ font: inherit;+ cursor: inherit;+ background: none;+}++.mention-list-menu {+ max-width: min(700px, calc(100vw - 10px));+}++.mention-list-menu > .tn-menu-scroll {+ max-height: var(--ck-mention-list-max-height);+}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.tsxnew file mode 100644index 0000000000..c88277e496--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx@@ -0,0 +1,104 @@+import type { MentionListState } from "@triliumnext/ckeditor5";+import { act } from "preact/test-utils";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createMentionListView } 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 command = document.createElement("button");+ command.className = "ck ck-button ck-slash-command-button";+ command.textContent = "Heading";++ return {+ entries: [+ // The `@` feed's items carry the note autocomplete's fields beside the mention's own.+ { item: { id: "@Alpha", highlightedNotePathTitle: "<b>Al</b>pha", icon: "bx bx-file" } as MentionListState["entries"][0]["item"], marker: "@", render: () => undefined },+ { item: { id: "/heading" }, marker: "/", render: () => command },+ { item: { id: "#plain" }, marker: "#", render: () => undefined }+ ],+ className: "ck-mention-list",+ selectedIndex: 0,+ caretRect: () => new DOMRect(10, 10, 1, 16),+ 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(menu?.classList.contains("ck-mention-list")).toBe(true);+ expect(rows().map((row) => row.classList.contains("tn-menu-active"))).toEqual([ true, false, false ]);++ // A note as the note autocomplete draws it, the rest as their feeds do, or by their id.+ const [ note, command, plain ] = rows();+ expect(note.querySelector(".tn-icon")?.className).toContain("bx-file");+ expect(note.querySelector(".search-result-title")?.innerHTML).toBe("<b>Al</b>pha");+ 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("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();+ });+});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.tsxnew file mode 100644index 0000000000..6a9f6d3f2d--- /dev/null+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx@@ -0,0 +1,133 @@+import "./mention_list_view.css";++import type { MentionListEntry, MentionListState, MentionListView } from "@triliumnext/ckeditor5";+import clsx from "clsx";+import { render } from "preact";+import { useLayoutEffect, useRef } from "preact/hooks";++import type { Suggestion } from "../../../services/note_autocomplete";+import { renderNoteSuggestion } from "../../react/NoteAutocomplete";+import Popup from "../../react/Popup";++/**+ * Draws a text editor's suggestion list (`@` notes, `#`/`~` attributes, `/` commands, 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;+ }+ };+}++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?.children[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.+ anchor={{ getBoundingClientRect: state.caretRect }}+ elementRef={elementRef}+ // The pointer moves the highlighted row, so `:hover` marks no second one.+ className={clsx("dropdown-menu show tn-dropdown-menu tn-menu-keyboard note-autocomplete-menu mention-list-menu", state.className)}+ >+ <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>+ );+}++/**+ * A note as the note autocomplete draws it, and any other entry as its feed's `itemRenderer` does, or+ * by its id where the feed has none.+ */+function EntryContent({ entry }: { entry: MentionListEntry }) {+ const ref = useRef<HTMLSpanElement>(null);++ useLayoutEffect(() => {+ const host = ref.current;+ if (!host) return;++ if (isNoteSuggestion(entry.item)) {+ // The row's content itself, as the note autocomplete lays it out in its `<span>`.+ host.replaceChildren(...renderNoteSuggestion(entry.item).childNodes);+ } else {+ host.replaceChildren(entry.render() ?? entry.item.id);+ }+ }, [ entry.item, entry.marker ]);++ return <span ref={ref} />;+}++function isNoteSuggestion(item: MentionListEntry["item"]): item is MentionListEntry["item"] & Suggestion {+ return "highlightedNotePathTitle" in item;+}diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 9aa1d36be8..52d9137478 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -18,7 +18,7 @@ export type { PasteTarget } from "./plugins/cuttonote.js";export type { ContentEmbedState } from "./plugins/content_embed/content_embed.js";export type { AttachmentLinkChange } from "./plugins/referencelink.js";export type { SlashCommandConfig, SlashCommandDefinition } from "./plugins/mention/slash_commands.js";-export type { TriliumMentionFeed } from "./plugins/mention/types.js";+export type { MentionListEntry, MentionListState, MentionListView, TriliumMentionFeed } from "./plugins/mention/types.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";export { default as TriliumAiAssistant } from "./plugins/ai_assistant/ai_assistant.js";diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.tsindex 7cadba3dd7..db643f3600 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts@@ -14,7 +14,7 @@ import {import { beforeEach, describe, expect, it, vi } from "vitest";import { createTestEditor } from "../../../test/editor-kit.js";-import type { TriliumMentionFeed } from "./types.js";+import type { MentionListState, MentionListView, TriliumMentionFeed } from "./types.js";import TriliumMentionUI, { balloonPositions } from "./trilium_mention_ui.js";/** Longer than the plugin's 100 ms feed debounce. */@@ -574,6 +574,113 @@ describe("TriliumMentionUI", () => {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);+ });++ 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("balloonPositions", () => {diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.tsindex 69bfec26ff..29ba40efa4 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts@@ -20,7 +20,7 @@ import {} from "ckeditor5";import { createMarkerPattern, findMarkerMatch, type MarkerMatch } from "./marker_pattern.js";-import type { TriliumMentionFeed } from "./types.js";+import type { MentionListView, TriliumMentionFeed } 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. */@@ -31,6 +31,9 @@ const MARKER_NAME = "mention";const FEED_DEBOUNCE_MS = 100;const DEFAULT_DROPDOWN_LIMIT = 10;+/** See {@link MentionListState.className}, which `slash_commands.css` styles the `/` rows under. */+const MENTION_LIST_CLASS = "ck-mention-list";+/** A configured feed with its compiled trigger pattern. */type Pattern = TriliumMentionFeed & { pattern: RegExp };@@ -60,6 +63,13 @@ export default class TriliumMentionUI extends Plugin {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;+private _balloon?: ContextualBalloon;private _feedTimer?: ReturnType<typeof setTimeout>;@@ -94,6 +104,7 @@ export default class TriliumMentionUI extends Plugin {/* 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);editor.editing.view.document.on<ViewDocumentKeyDownEvent>("keydown", (evt, data) => {if (this._isVisible && this._handleKeyDown(data.keyCode)) {@@ -106,7 +117,10 @@ export default class TriliumMentionUI extends Plugin {emitter: this._view,activator: () => this._isVisible,/* v8 ignore next -- `clickOutsideHandler` only calls `contextElements()` once the activator reported the panel visible, and a visible balloon is a rendered one, so its element is never null */- contextElements: () => (this._balloon?.view.element ? [ this._balloon.view.element ] : []),+ contextElements: () => {+ const element = this._listView ? this._listView.element : this._balloon?.view.element;+ return element ? [ element ] : [];+ },callback: () => this._hide()});@@ -121,10 +135,11 @@ export default class TriliumMentionUI extends Plugin {this._clearDismissal();// Balloon views are not destroyed automatically — see ckeditor5#1341.this._view.destroy();+ this._listView?.destroy?.();}private get _isVisible() {- return this._balloon?.visibleView === this._view;+ return this._listView ? this._listShown : this._balloon?.visibleView === this._view;}private _isCurrentRequest(requestId: number) {@@ -137,13 +152,14 @@ export default class TriliumMentionUI extends Plugin {* saves instead of being swallowed by an open panel.*/private _handleKeyDown(keyCode: number): boolean {- if (keyCode === keyCodes.arrowdown) {- this._view.selectNext();- return true;- }-- if (keyCode === keyCodes.arrowup) {- this._view.selectPrevious();+ 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;}@@ -153,6 +169,16 @@ export default class TriliumMentionUI extends Plugin {}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;}@@ -314,6 +340,14 @@ export default class TriliumMentionUI extends Plugin {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@@ -351,6 +385,12 @@ export default class TriliumMentionUI extends Plugin {private _hide() {clearTimeout(this._feedTimer);+ if (this._listShown) {+ this._listShown = false;+ this._selectedIndex = -1;+ this._listView?.hide();+ }+if (this._balloon?.hasView(this._view)) {this._balloon.remove(this._view);}@@ -379,47 +419,95 @@ export default class TriliumMentionUI extends Plugin {return listItem;});- view.on("execute", (evt, data) => {- const editor = this.editor;- const model = editor.model;- const marker = model.markers.get(MARKER_NAME);- const focus = model.document.selection.focus;+ view.on("execute", (evt, data) => this._commit(data));- /* v8 ignore next 3 -- the list only fires "execute" while the panel is visible, which means the marker is registered, and a live selection always has a focus */- if (!marker || !focus) {- return;- }+ return view;+ }- // 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);+ /** 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;- this._hide();- this._clearDismissal();+ /* 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;+ }- // 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;- }+ // 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);- 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();+ 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,+ className: MENTION_LIST_CLASS,+ selectedIndex: this._selectedIndex,+ caretRect: () => {+ const { left, top, width, height } = this._caretRect(marker);+ return new DOMRect(left, top, width, height);+ },+ select: (index) => {+ this._selectedIndex = index;+ this._drawList(marker);+ },+ pick: (index) => {+ const entry = this._items.get(index);+ if (entry) {+ this._commit(entry);+ }}});+ }- return view;+ /** 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 {diff --git a/packages/ckeditor5/src/plugins/mention/types.ts b/packages/ckeditor5/src/plugins/mention/types.tsindex 3bce10c451..3d8d46e30b 100644--- a/packages/ckeditor5/src/plugins/mention/types.ts+++ b/packages/ckeditor5/src/plugins/mention/types.ts@@ -58,3 +58,50 @@ declare module "@ckeditor/ckeditor5-mention" {* 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[];+ /**+ * A class for the list, under which the rows of the built-in feeds (the `/` commands) keep the+ * layout they have in CKEditor's balloon.+ */+ className: string;+ /** The highlighted entry, or `-1` where none is. */+ selectedIndex: number;+ /** Where the caret ends the query, in viewport coordinates. */+ caretRect(): DOMRect;+ /** 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;+}diff --git a/packages/ckeditor5/src/theme/slash_commands.css b/packages/ckeditor5/src/theme/slash_commands.cssindex 78ef1f25d2..6a8d117827 100644--- a/packages/ckeditor5/src/theme/slash_commands.css+++ b/packages/ckeditor5/src/theme/slash_commands.css@@ -23,7 +23,7 @@--ck-slash-command-description-width: calc(var(--ck-slash-command-button-width) - 4.8em);}-.ck-mentions .ck.ck-button.ck-slash-command-button {+:is(.ck-mentions, .ck-mention-list) .ck.ck-button.ck-slash-command-button {display: flex;justify-content: flex-start;width: var(--ck-slash-command-button-width);@@ -103,7 +103,7 @@}}-[dir="rtl"] .ck-mentions .ck.ck-button.ck-slash-command-button {+[dir="rtl"] :is(.ck-mentions, .ck-mention-list) .ck.ck-button.ck-slash-command-button {& .ck.ck-icon {margin: 0 0 0 var(--ck-spacing-small);}