Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(text): list @-mentions with the note autocomplete itself
Elian Doran1454fbd8264d
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.tsindex aabdba4c6b..eac4bc86d4 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete.spec.ts@@ -54,7 +54,7 @@ vi.mock("./ws.js", () => ({}));import type { CommandDefinition } from "./command_registry.js";-import noteAutocomplete, { createNoteFromSuggestion, createSearchScheduler, getCommandSuggestions, getNoteSuggestions, recentNoteGroup, type Suggestion } from "./note_autocomplete.js";+import { createNoteFromSuggestion, createSearchScheduler, getCommandSuggestions, getNoteSuggestions, recentNoteGroup, type Suggestion } from "./note_autocomplete.js";import server from "./server.js";beforeEach(() => {@@ -158,42 +158,6 @@ describe("getNoteSuggestions", () => {});});-describe("autocompleteSourceForCKEditor", () => {- 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",- notePath: "root/abc",- highlightedNotePathTitle: "<b>Foo</b>",- icon: "bx bx-note"- } ]) as typeof server.get;-- const items = await noteAutocomplete.autocompleteSourceForCKEditor("Foo");- 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",- name: "Root / Foo",- link: "#root/abc",- notePath: "root/abc",- highlightedNotePathTitle: "<b>Foo</b>",- icon: "bx bx-note"- });- // A creation row has no path title of its own.- expect(items[1]).toMatchObject({ id: "@undefined", name: "" });- });-- it("omits the creation rows when the host cannot act on them", async () => {- server.get = vi.fn(async () => [- { noteTitle: "Foo", notePathTitle: "Root / Foo", notePath: "root/abc" }- ]) as typeof server.get;-- const items = await noteAutocomplete.autocompleteSourceForCKEditor("Foo", false);- expect(items.map((item) => (item as Suggestion).action)).toEqual([ undefined ]);- });-});-describe("createSearchScheduler", () => {const WINDOW_MS = 50;diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex e3ce5533c5..5318d648c7 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -1,4 +1,3 @@-import type { MentionFeedObjectItem } from "@triliumnext/ckeditor5";import type { AutocompleteResult, InboxTargetResponse } from "@triliumnext/commons";import appContext from "../components/app_context.js";@@ -42,29 +41,6 @@ export interface Options {isCommandPalette?: boolean;}-/**- * 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 });-- return rows.map((row) => ({- action: row.action,- noteTitle: row.noteTitle,- id: `@${row.notePathTitle}`,- name: row.notePathTitle || "",- link: `#${row.notePath}`,- notePath: row.notePath,- highlightedNotePathTitle: row.highlightedNotePathTitle,- icon: row.icon- }));-}-export interface NoteSuggestionOptions {/** Adds the two note-creation rows last, after the notes and the search row, for a non-blank term. */allowCreatingNotes?: boolean;@@ -286,7 +262,3 @@ function buildCreateNoteTitle(term: string, target: InboxTargetResponse | null)return t("note_autocomplete.create-note-into", { term: escapeHtml(term), parentTitle: escapeHtml(target.title) });}--export default {- autocompleteSourceForCKEditor-};diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex 772444fd3f..d32b67a265 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -21,7 +21,7 @@ import type { NoteSuggestionOptions, Suggestion } from "../../services/note_autoimport { collectShortcutHints } from "../../services/shortcut_hints";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";-import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, renderNoteSuggestion } from "./NoteAutocomplete";+import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList, type NoteMentionListHandle, renderNoteSuggestion } from "./NoteAutocomplete";import { ParentComponent } from "./react_utils";async function render(props: NoteAutocompleteProps = {}) {@@ -1108,3 +1108,108 @@ describe("NoteAutocomplete's suggestion list", () => {expect(rows()).toHaveLength(0);});});++describe("NoteMentionList", () => {+ const notes: Suggestion[] = [+ { notePath: "root/a", noteTitle: "Alpha", notePathTitle: "Alpha", highlightedNotePathTitle: "<b>Al</b>pha", icon: "bx bx-file" },+ { notePath: "root/b", noteTitle: "Beta", notePathTitle: "Beta", highlightedNotePathTitle: "Beta" }+ ];+ const createRow: Suggestion = { action: "create-note", noteTitle: "al", highlightedNotePathTitle: "Create note" };+ const anchor = { getBoundingClientRect: () => new DOMRect(10, 10, 1, 16) };++ beforeEach(() => {+ vi.useFakeTimers();+ getNoteSuggestions.mockReset();+ getNoteSuggestions.mockResolvedValue(notes);+ createNoteFromSuggestion.mockReset();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ /** Shows the list for `query` where nothing has the focus, as a text editor's caret does. */+ async function show(query: string, props: Partial<Parameters<typeof NoteMentionList>[0]> = {}) {+ const onPick = vi.fn();+ const handleRef = createRef<NoteMentionListHandle>() as { current: NoteMentionListHandle | null };+ const host = document.createElement("div");+ const draw = async (text: string) => {+ await act(async () => {+ preactRender(<NoteMentionList query={text} anchor={anchor} onPick={onPick} handleRef={handleRef} {...props} />, host);+ });+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ };+ await draw(query);+ const press = async (key: string) => {+ const event = new KeyboardEvent("keydown", { key, cancelable: true });+ let taken = false;+ await act(async () => { taken = handleRef.current?.handleKeyDown(event) ?? false; });+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ return taken;+ };+ return { onPick, draw, press, unmount: () => act(() => preactRender(null, host)) };+ }++ const rows = () => [ ...document.querySelectorAll<HTMLElement>(".note-autocomplete-menu > .tn-menu-scroll > .dropdown-item") ];++ it("lists the notes for the query as the field does, and again as the query changes", async () => {+ const { draw, unmount } = await show("al", { allowCreatingNotes: true });++ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true });+ expect(rows().map((row) => row.querySelector(".search-result-title")?.innerHTML)).toEqual([ "<b>Al</b>pha", "Beta" ]);+ expect(rows()[0].querySelector(".tn-icon")?.className).toContain("bx-file");++ await draw("alp");+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("alp", { allowCreatingNotes: true });+ expect(rows()).toHaveLength(2);+ await unmount();+ });++ it("takes the highlighted note on Tab as on Enter", async () => {+ const { onPick, press, unmount } = await show("al");++ expect(await press("Tab")).toBe(true);+ expect(onPick).toHaveBeenCalledExactlyOnceWith("root/a");+ await unmount();+ });++ it("takes the keys while it shows notes, and reports the path of the one Enter or a click picks", async () => {+ const { onPick, press, unmount } = await show("al");++ expect(rows()[0].classList.contains("tn-menu-active")).toBe(true);+ expect(await press("ArrowDown")).toBe(true);+ expect(rows()[1].classList.contains("tn-menu-active")).toBe(true);+ expect(await press("Enter")).toBe(true);+ expect(onPick).toHaveBeenCalledExactlyOnceWith("root/b");+ // Picked, the list is closed and the keys are the editor's again.+ expect(rows()).toHaveLength(0);+ expect(await press("ArrowDown")).toBe(false);+ await unmount();++ const clicked = await show("al");+ await act(async () => rows()[0].click());+ expect(clicked.onPick).toHaveBeenCalledExactlyOnceWith("root/a");+ await clicked.unmount();+ });++ it("leaves Enter to the editor with nothing highlighted where it opens without a preselection", async () => {+ const { onPick, press, unmount } = await show("al", { preselect: false });++ expect(rows().some((row) => row.classList.contains("tn-menu-active"))).toBe(false);+ expect(await press("Enter")).toBe(false);+ expect(onPick).not.toHaveBeenCalled();+ await unmount();+ });++ it("creates the note of a creation row, and reports its path once created", async () => {+ getNoteSuggestions.mockResolvedValue([ createRow ]);+ createNoteFromSuggestion.mockResolvedValueOnce("root/inbox/created");+ const { onPick, press, unmount } = await show("al", { allowCreatingNotes: true });++ // With no note to open, the list opens on the creation row.+ expect(await press("Enter")).toBe(true);+ expect(createNoteFromSuggestion).toHaveBeenCalledWith(createRow);+ expect(await onPick.mock.calls[0]?.[0]).toBe("root/inbox/created");+ await unmount();+ });+});diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 71deeb871a..87339bf2e2 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -21,7 +21,7 @@ import FormToggle from "./FormToggle";import { useContextualShortcutHints, useSyncedRef } from "./hooks";import Icon from "./Icon";import OverlayControlGroup from "./OverlayControlGroup";-import Popup from "./Popup";+import Popup, { type PopupProps } from "./Popup";import RawHtml from "./RawHtml";import { renderShortcutKbds } from "./shortcut_kbd";@@ -408,14 +408,11 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,)}</>, container.current): showsList && anchor && (- <Popup+ <NoteSuggestionPopupanchor={anchor}// Rendered in the field's modal so the list stacks above it: the note picker// raises its modal (2000) over `.tn-popup` in the body (1200).container={anchor.closest<HTMLElement>(".modal") ?? undefined}- placement="bottom-start"- // 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"// The list spans the whole field, buttons included, and widens past a narrow one.style={{ width: `${Math.max(anchor.getBoundingClientRect().width, DROPDOWN_MIN_WIDTH)}px` }}escapeDismisses={false}@@ -426,17 +423,96 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,searchingFor={isSearchingFullText ? value : undefined}className="tn-menu-scroll"/>- </Popup>+ </NoteSuggestionPopup>)}</div>);}+/** Drives a {@link NoteMentionList} from where its query is typed. */+export interface NoteMentionListHandle {+ /** Handles a key pressed where the query is typed, and returns whether the list took it. */+ handleKeyDown(e: KeyboardEvent): boolean;+}+/**- * The list of suggestions as the rows of a menu, so it looks like the app's other dropdowns, whether- * in the popup or in a host's container. With `searchingFor`, the query of a search in progress, it- * shows a row saying so in place of the suggestions.+ * The note autocomplete's list for a query typed somewhere else, such as after an `@` in a text+ * editor, which keeps the focus and forwards its keys through `handleRef`. It lists what the field+ * lists for the query, and reports the path of the note picked, creating the note first for a+ * creation row: `onPick` then receives a promise, settling on `undefined` where the creation is+ * canceled.*/+export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect = true, onPick, handleRef, elementRef }: {+ query: string;+ anchor: PopupProps["anchor"];+ allowCreatingNotes?: boolean;+ /** Opens the list with an entry highlighted, so that Enter takes it. */+ preselect?: boolean;+ onPick(notePath: string | Promise<string | undefined>): void;+ handleRef: MutableRef<NoteMentionListHandle | null>;+ elementRef?: PopupProps["elementRef"];+}) {+ // The focus stays where the query is typed, so there is no field to return it to.+ const inputRef = useRef<HTMLInputElement>(null);+ const source = useCallback((term: string) => getNoteSuggestions(term, { allowCreatingNotes }), [ allowCreatingNotes ]);+ const schedule = useMemo(() => createSearchScheduler(), []);++ const autocomplete = useAutocomplete({+ query,+ source,+ onPick: (suggestion: Suggestion) => {+ if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {+ onPick(createNoteFromSuggestion(suggestion));+ } else if (suggestion.notePath) {+ onPick(suggestion.notePath);+ }+ },+ inputRef,+ autoActivate: preselect,+ textOf: suggestionText,+ fallbackIndex: createWhenNoNote,+ schedule+ });++ // The host shows the list by mounting it and closes it by unmounting it.+ useEffect(() => autocomplete.open(), []);++ useLayoutEffect(() => {+ handleRef.current = {+ handleKeyDown(e) {+ if (!autocomplete.isShown) return false;+ const highlighted = autocomplete.items[autocomplete.activeIndex];+ // Tab takes the highlighted note, as Enter does, where a field leaves Tab to move the focus.+ if (e.key === "Tab" && highlighted) {+ e.preventDefault();+ autocomplete.pick(highlighted);+ return true;+ }+ autocomplete.handleKeyDown(e);+ return e.defaultPrevented;+ }+ };+ });++ return autocomplete.isShown && (+ <NoteSuggestionPopup anchor={anchor} elementRef={elementRef}>+ <NoteSuggestionMenu autocomplete={autocomplete} className="tn-menu-scroll" />+ </NoteSuggestionPopup>+ );+}++/** The popup the suggestions are listed in, below `anchor` where there is room. */+function NoteSuggestionPopup({ className, ...props }: PopupProps) {+ return (+ <Popup+ placement="bottom-start"+ {...props}+ // 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", className)}+ />+ );+}+/*** Lists the keys of a list with a search footer in the shortcut hints pane, which the footer's button* opens. Only such a list adds hints, as they replace whatever the host registered.@@ -456,6 +532,11 @@ function SearchFooterShortcutHints({ allowFullSearch }: { allowFullSearch: boolereturn null;}+/**+ * The list of suggestions as the rows of a menu, so it looks like the app's other dropdowns, whether+ * in the popup or in a host's container. With `searchingFor`, the query of a search in progress, it+ * shows a row saying so in place of the suggestions.+ */function NoteSuggestionMenu({ autocomplete, searchingFor, className }: {autocomplete: ReturnType<typeof useAutocomplete<Suggestion>>;searchingFor?: string;@@ -598,7 +679,7 @@ function noNotesRow(): Suggestion {}/** Whether a line goes above the row at `index`: the first of a group, after the rows of another. */-export function startsGroup(items: Suggestion[], index: number) {+function startsGroup(items: Suggestion[], index: number) {return index > 0 && rowGroup(items[index]) !== rowGroup(items[index - 1]);}diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex 71fde158d7..3d39f3fa6f 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -1,7 +1,7 @@import "../../attribute_widgets/attribute_name_suggestion.css";import "./AttributeEditor.css";-import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, TriliumMentionFeed } from "@triliumnext/ckeditor5";+import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, MentionHostedFeed, TriliumMentionFeed } from "@triliumnext/ckeditor5";import { AttributeType } from "@triliumnext/commons";import clsx from "clsx";import { createPortal } from "preact/compat";@@ -14,13 +14,10 @@ import contextMenu from "../../../menus/context_menu";import attribute_parser, { Attribute } from "../../../services/attribute_parser";import attribute_renderer from "../../../services/attribute_renderer";import attributes, { isBuiltinAttribute } from "../../../services/attributes";-import dateNoteService from "../../../services/date_notes";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 from "../../../services/note_autocomplete";-import note_create from "../../../services/note_create";import server from "../../../services/server";import { isIMEComposing } from "../../../services/shortcuts";import { escapeQuotes, getErrorMessage } from "../../../services/utils";@@ -29,7 +26,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 { createMentionListView, createNoteMentionList } from "../../type_widgets/text/mention_list_view";import AttributeHelp from "./AttributeHelp";type AttributeCommandNames = FilteredCommandNames<CommandData>;@@ -43,15 +40,6 @@ const BLINK_DURATION = 300;// `preselectFirstItem: false` throughout: in this editor Enter means "save the attributes", so an// open panel must not silently swallow it into committing whichever suggestion happens to be first.const mentionSetup: TriliumMentionFeed[] = [- {- marker: "@",- feed: (queryText) => note_autocomplete.autocompleteSourceForCKEditor(queryText),- minimumCharacters: 0,- dropdownLimit: Number.MAX_SAFE_INTEGER,- // Relation targets are note titles, which contain spaces.- allowSpaces: true,- preselectFirstItem: false- },{marker: "#",feed: (queryText) => fetchAttributeNames("label", queryText),@@ -68,12 +56,20 @@ const mentionSetup: TriliumMentionFeed[] = [}];+const hostedMentions: MentionHostedFeed[] = [+ {+ marker: "@",+ minimumCharacters: 0,+ // Relation targets are note titles, which contain spaces.+ allowSpaces: true,+ list: () => createNoteMentionList({ allowCreatingNotes: true, preselect: false })+ }+];interface AttributeEditorProps {api: MutableRef<AttributeEditorImperativeHandlers | null>;note: FNote;componentId: string;- notePath?: string | null;ntxId?: string | null;hidden?: boolean;/**@@ -90,7 +86,7 @@ export interface AttributeEditorImperativeHandlers {renderOwnedAttributes(ownedAttributes: FAttribute[]): Promise<void>;}-export default function AttributeEditor({ api, note, componentId, notePath, ntxId, hidden, hideHelpButton }: AttributeEditorProps) {+export default function AttributeEditor({ api, note, componentId, ntxId, hidden, hideHelpButton }: AttributeEditorProps) {const [ currentValue, setCurrentValue ] = useState("");const [ error, setError ] = useState<unknown>();const [ needsSaving, setNeedsSaving ] = useState(false);@@ -244,19 +240,8 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxIconst title = note ? note.title : "[missing]";$el.text(title);- },- createNoteForReferenceLink: async (title: string, intoInbox: boolean) => {- const parentNotePath = intoInbox ? await dateNoteService.getInboxNotePath() : notePath;- if (!parentNotePath) return;-- const result = await note_create.createNoteWithTypePrompt(parentNotePath, {- activate: false,- title- });-- return result?.note?.getBestNotePathString();}- }), [ notePath ]));+ }), []));// Keyboard shortcutsuseTriliumEvent("addNewLabel", ({ ntxId: eventNtxId }) => {@@ -303,7 +288,7 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxIconfig={{toolbar: { items: [] },placeholder: t("attribute_editor.placeholder"),- mention: { feeds: mentionSetup, listView: createMentionListView },+ mention: { feeds: mentionSetup, hostedFeeds: hostedMentions, 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 ddcd25628a..8e5d9ca9a0 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -1,13 +1,12 @@import "./ChatInputBar.css";-import type { AttributeEditor as CKEditorAttributeEditor, CKTextEditor, MentionFeed } from "@triliumnext/ckeditor5";+import type { AttributeEditor as CKEditorAttributeEditor, CKTextEditor, MentionHostedFeed } from "@triliumnext/ckeditor5";import type { DISPLAYABLE_LOCALE_IDS, LlmReasoningEffort } from "@triliumnext/commons";import { Fragment } from "preact";import { useCallback, useEffect, useRef, useState } from "preact/hooks";import { t } from "../../../services/i18n.js";import link from "../../../services/link.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,7 +18,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 { createNoteMentionList } 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";@@ -32,14 +31,13 @@ import { type AttachmentBlock, type UseLlmChatReturn } from "./useLlmChat.js";const READ_ONLY_LOCK = "llm-chat-streaming";-const mentionFeeds: MentionFeed[] = [+const hostedMentions: MentionHostedFeed[] = [{marker: "@",- feed: (queryText) => note_autocomplete.autocompleteSourceForCKEditor(queryText, false),minimumCharacters: 0,- dropdownLimit: Number.MAX_SAFE_INTEGER,// Note titles contain spaces, so the query must be allowed to as well.- allowSpaces: true+ allowSpaces: true,+ list: () => createNoteMentionList()}];@@ -313,7 +311,7 @@ export default function ChatInputBar({extraPlugins: ckEditor.plugins,toolbar: { items: [] },placeholder: t("llm_chat.placeholder"),- mention: { feeds: mentionFeeds, listView: createMentionListView },+ mention: { feeds: [], hostedFeeds: hostedMentions },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/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex 5e4e01fb0b..134190025d 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -16,7 +16,6 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import { consumeBookmark } from "../../../services/bookmark_jump";import { getUploadBoxSize } from "../../../services/content_renderer";-import dateNoteService from "../../../services/date_notes";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import link, { parseNavigationStateFromUrl } from "../../../services/link";@@ -214,19 +213,6 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextrenderLinkMention(container, metadata, editable) {linkEmbedService.renderMentionPreview(container, metadata, editable);},- // Creating notes in @-completion- async createNoteForReferenceLink(title: string, intoInbox: boolean) {- const notePath = intoInbox ? await dateNoteService.getInboxNotePath() : noteContext?.notePath;- if (!notePath) return;-- const resp = await note_create.createNoteWithTypePrompt(notePath, {- activate: false,- title- });-- if (!resp || !resp.note) return;- return resp.note.getBestNotePathString();- },// Keyboard shortcutasync followLinkUnderCursorCommand() {const editor = await waitForEditor();diff --git a/apps/client/src/widgets/type_widgets/text/config.spec.ts b/apps/client/src/widgets/type_widgets/text/config.spec.tsindex 4ea470368c..f373af9bd3 100644--- a/apps/client/src/widgets/type_widgets/text/config.spec.ts+++ b/apps/client/src/widgets/type_widgets/text/config.spec.ts@@ -3,7 +3,6 @@ import { DISPLAYABLE_LOCALE_IDS, IMAGE_MIMES, LOCALES, SANITIZER_DEFAULT_ALLOWEDimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";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";@@ -27,7 +26,9 @@ const catalogState = vi.hoisted(() => ({vi.mock("../../../services/i18n.js", () => ({t: (key: string) => catalogState.entries[key] ?? key,// Read while the AI assistant's Translate submenu is built, which every config goes through.- getAvailableLocales: () => []+ getAvailableLocales: () => [],+ // Awaited by `command_registry.ts` as it loads, through the `@` list's note autocomplete.+ translationsInitializedPromise: Promise.resolve()}));vi.mock("i18next", () => ({default: {@@ -77,12 +78,6 @@ vi.mock("../../../services/image.js", () => ({}}));-vi.mock("../../../services/note_autocomplete.js", () => ({- default: {- autocompleteSourceForCKEditor: vi.fn(async () => [])- }-}));-// Keep the real module, but skip the actual theme/mime loading the lazy loader would trigger.vi.mock("../../../services/syntax_highlight.js", async (importOriginal) => ({...(await importOriginal<typeof import("../../../services/syntax_highlight.js")>()),@@ -116,13 +111,8 @@ interface DynamicConfig {mermaid: { lazyLoad(): Promise<unknown> };syntaxHighlighting: { loadHighlightJs(): Promise<{ default: unknown }> };mention?: {- feeds: {- marker: string;- minimumCharacters: number;- dropdownLimit?: number;- feed(queryText: string): Promise<unknown>;- itemRenderer?: unknown;- }[];+ feeds: unknown[];+ hostedFeeds?: { marker: string; minimumCharacters?: number; allowSpaces?: boolean; list(): unknown }[];listView?: unknown;};}@@ -567,27 +557,18 @@ describe("CK config - lazy loaders", () => {});describe("CK config - mention feed", () => {- it("draws the list as the note autocomplete's, with the @ feed only when note completion is enabled", async () => {+ it("lists notes after @ as the note autocomplete does, only when note completion is enabled", async () => {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();- 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");+ const hosted = config.mention?.hostedFeeds?.[0];+ expect(hosted).toMatchObject({ marker: "@", minimumCharacters: 0, allowSpaces: true });+ expect(hosted?.list()).toEqual(expect.objectContaining({ show: expect.any(Function), handleKeyDown: expect.any(Function) }));});});diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 181a5e6f8e..322921f89d 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -8,7 +8,6 @@ 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 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,7 +18,7 @@ import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";import diffAiResponse from "./ai_diff.js";import { buildFontColorConfig, buildTableColorConfig } from "./color_palette.js";-import { createMentionListView } from "./mention_list_view.js";+import { createMentionListView, createNoteMentionList } from "./mention_list_view.js";import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";import { buildToolbarConfig } from "./toolbar.js";@@ -303,18 +302,18 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConficonfig.typing = { transformations: buildTransformationsConfig(contentLanguage) };- // Set without the `@` feed too: the `/` and emoji feeds the plugins add are drawn through it.config.mention = {- feeds: options.get("textNoteCompletionEnabled") === "true" ? [+ feeds: [],+ hostedFeeds: 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+ allowSpaces: true,+ list: () => createNoteMentionList({ allowCreatingNotes: true })}] : [],+ // Draws the lists of the `/` and emoji feeds the plugins add.listView: createMentionListView};diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsxindex ba625dc241..5e4c587b41 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,8 +1,19 @@-import type { MentionListState } from "@triliumnext/ckeditor5";+import type { MentionHostedListState, MentionListState } from "@triliumnext/ckeditor5";import { act } from "preact/test-utils";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { createMentionListView } from "./mention_list_view";+const { getNoteSuggestions, createNoteFromSuggestion } = vi.hoisted(() => ({+ getNoteSuggestions: vi.fn(async () => [ { notePath: "root/a", noteTitle: "Alpha", highlightedNotePathTitle: "Alpha" } ]),+ createNoteFromSuggestion: vi.fn()+}));++vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../../../services/note_autocomplete")>()),+ getNoteSuggestions,+ createNoteFromSuggestion+}));++import { createMentionListView, createNoteMentionList } from "./mention_list_view";describe("createMentionListView", () => {const views: ReturnType<typeof createMentionListView>[] = [];@@ -13,14 +24,15 @@ describe("createMentionListView", () => {});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: [- // 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: ":smile:" }, marker: ":", render: () => emoji },{ item: { id: "/heading" }, marker: "/", render: () => command },{ item: { id: "#plain" }, marker: "#", render: () => undefined }],@@ -52,10 +64,9 @@ describe("createMentionListView", () => {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");+ // 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");@@ -64,24 +75,6 @@ describe("createMentionListView", () => {expect(document.querySelector(".mention-list-menu")).toBeNull();});- it("separates the notes from the creation rows as the note autocomplete does, and scrolls past the line", async () => {- const scroll = vi.spyOn(Element.prototype, "scrollIntoView").mockImplementation(() => {});- const entry = (id: string, action?: string) => ({- item: { id, action, highlightedNotePathTitle: id } as MentionListState["entries"][0]["item"],- marker: "@",- render: () => undefined- });- const state = stateWith({ entries: [ entry("@Alpha"), entry("@create", "create-note"), entry("@child", "create-child-note") ] });- const view = await show(state);-- const children = [ ...document.querySelectorAll(".mention-list-menu .tn-menu-scroll > *") ];- expect(children.map((child) => child.className)).toEqual([ "dropdown-item tn-menu-active", "dropdown-divider", "dropdown-item", "dropdown-item" ]);-- scroll.mockClear();- await act(async () => view.show({ ...state, selectedIndex: 2 }));- expect(scroll.mock.contexts[0]).toBe(rows()[2]);- });-it("follows the caret as a container around the editor scrolls", async () => {const scroller = document.createElement("div");scroller.style.overflow = "auto";@@ -144,3 +137,50 @@ describe("createMentionListView", () => {expect(scroll).not.toHaveBeenCalled();});});++describe("createNoteMentionList", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ async function open() {+ const list = createNoteMentionList({ allowCreatingNotes: true });+ const commit = vi.fn<MentionHostedListState["commit"]>();+ await act(async () => list.show({ query: "al", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ return { list, commit };+ }++ it("lists the notes for the query, and mentions the one picked by its path", async () => {+ const { list, commit } = await open();++ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true });+ expect(list.element?.textContent).toContain("Alpha");+ expect(list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }))).toBe(true);+ expect(commit).toHaveBeenCalledExactlyOnceWith({ id: "@root/a", notePath: "root/a" });++ await act(async () => list.hide());+ expect(list.element).toBeNull();+ expect(list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }))).toBe(false);+ list.destroy?.();+ });++ it("mentions a note it creates once it is created, and nothing where the creation is canceled", async () => {+ getNoteSuggestions.mockResolvedValue([ { action: "create-note", noteTitle: "al", highlightedNotePathTitle: "Create" } ] as never);+ createNoteFromSuggestion.mockResolvedValueOnce("root/inbox/al").mockResolvedValueOnce(undefined);++ const created = await open();+ created.list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }));+ expect(await created.commit.mock.calls[0]?.[0]).toEqual({ id: "@root/inbox/al", notePath: "root/inbox/al" });+ created.list.destroy?.();++ const canceled = await open();+ canceled.list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }));+ expect(await canceled.commit.mock.calls[0]?.[0]).toBeUndefined();+ canceled.list.destroy?.();+ });+});diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsxindex 84545759b1..3f0a19d76b 100644--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx@@ -1,19 +1,16 @@import "./mention_list_view.css";-import type { MentionListEntry, MentionListState, MentionListView } from "@triliumnext/ckeditor5";+import type { MentionHostedList, 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 { FormDropdownDivider } from "../../react/FormList";-import { renderNoteSuggestion, startsGroup } from "../../react/NoteAutocomplete";+import { NoteMentionList, type NoteMentionListHandle } 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`.+ * Draws a text editor's suggestion list (`#`/`~` 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.@@ -54,6 +51,53 @@ export function createMentionListView(): MentionListView {};}+/**+ * 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.+ */+export function createNoteMentionList({ allowCreatingNotes, preselect }: {+ allowCreatingNotes?: boolean;+ preselect?: boolean;+} = {}): MentionHostedList {+ const container = document.createElement("div");+ const handle: { current: NoteMentionListHandle | null } = { current: null };+ let element: HTMLDivElement | null = null;++ return {+ show(state) {+ render(<NoteMentionList+ query={state.query}+ // A new anchor each time the query changes, so it is placed again at the caret.+ anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}+ allowCreatingNotes={allowCreatingNotes}+ preselect={preselect}+ onPick={(notePath) => state.commit(typeof notePath === "string"+ ? toMention(notePath)+ : notePath.then((path) => path ? toMention(path) : undefined))}+ handleRef={handle}+ elementRef={(el) => { element = el; }}+ />, container);+ },+ hide() {+ render(null, container);+ element = null;+ },+ handleKeyDown: (e) => handle.current?.handleKeyDown(e) ?? false,+ get element() {+ return element;+ },+ destroy() {+ render(null, container);+ element = null;+ }+ };+}++/** The mention `MentionCustomization` turns into a reference link to `notePath`. */+function toMention(notePath: string) {+ return { id: `@${notePath}`, notePath };+}+function MentionMenu({ state, elementRef, scrollsToSelection, onPointerSelect }: {state: MentionListState;elementRef(element: HTMLDivElement | null): void;@@ -63,8 +107,6 @@ function MentionMenu({ state, elementRef, scrollsToSelection, onPointerSelect }:const menuRef = useRef<HTMLMenuElement>(null);const lastPointer = useRef<{ x: number; y: number }>();const { entries, selectedIndex } = state;- // Grouped as the note autocomplete groups its rows; any other feed's entries form one group.- const suggestions = entries.map(({ item }) => (isNoteSuggestion(item) ? item : {}));useLayoutEffect(() => {if (!scrollsToSelection() || selectedIndex < 0) return;@@ -87,8 +129,7 @@ function MentionMenu({ state, elementRef, scrollsToSelection, onPointerSelect }:// Keeps the focus in the editor, which closes the list without it.onMouseDown={(e) => e.preventDefault()}>- {entries.map((entry, index) => [- startsGroup(suggestions, index) && <FormDropdownDivider key={`divider-${index}`} />,+ {entries.map((entry, index) => (<likey={`${entry.marker}:${entry.item.id}`}className={clsx("dropdown-item", index === selectedIndex && "tn-menu-active")}@@ -105,34 +146,19 @@ function MentionMenu({ state, elementRef, scrollsToSelection, onPointerSelect }:><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.- */+/** 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(() => {- 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);- }+ ref.current?.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/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex c94e58f1bd..ca8ea4d05b 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -42,7 +42,6 @@ declare global {*/formatDateTime(date: Date, format?: string): string;loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;- createNoteForReferenceLink(title: string, intoInbox: boolean): Promise<string | undefined>;loadEmbeddedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;loadEmbeddedAttachment(attachmentId: string,diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 52d9137478..2f60289219 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 { MentionListEntry, MentionListState, MentionListView, TriliumMentionFeed } from "./plugins/mention/types.js";+export type { MentionHostedFeed, MentionHostedList, MentionHostedListState, MentionListEntry, MentionListState, MentionListView, TriliumMentionFeed } from "./plugins/mention/types.js";export { default as TriliumSnippets } from "./plugins/snippets/snippets.js";export type { SnippetDefinition } from "./plugins/snippets/snippetsconfig.js";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 a4e2b8f5bb..0d11aae51a 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 { MentionListState, MentionListView, TriliumMentionFeed } from "./types.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. */@@ -682,6 +682,136 @@ describe("TriliumMentionUI", () => {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 () => {+ setModelData(editor.model, "<paragraph>x []</paragraph>");+ type("@al");+ state?.commit({ id: "@alpha", text: "@alpha" });+ expect(text()).toContain("x <$text");+ expect(text()).toContain(">@alpha</$text>");+ expect(state).toBe(null);++ setModelData(editor.model, "<paragraph>x []</paragraph>");+ type("@be");+ let resolveCommit: (item: MentionFeedObjectItem | undefined) => void = () => {};+ 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);+ resolveCommit({ id: "@beta", text: "@beta" });+ await Promise.resolve();+ expect(text()).toContain("@beta</$text>");+ expect(text()).not.toContain("@be<");++ setModelData(editor.model, "<paragraph>x []</paragraph>");+ type("@ga");+ 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();+ });+ });});describe("balloonPositions", () => {diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.tsindex 3920e62efa..8501575365 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts@@ -12,6 +12,7 @@ import {MentionListItemView,MentionsView,ModelLivePosition,+ ModelLiveRange,type ModelPosition,Plugin,Rect,@@ -20,7 +21,7 @@ import {} from "ckeditor5";import { createMarkerPattern, findMarkerMatch, type MarkerMatch } from "./marker_pattern.js";-import type { MentionListView, TriliumMentionFeed } from "./types.js";+import type { MentionHostedFeed, MentionHostedList, 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. */@@ -37,6 +38,9 @@ const MENTION_LIST_CLASS = "ck-mention-list";/** 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 };+/*** 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`:@@ -69,6 +73,10 @@ export default class TriliumMentionUI extends Plugin {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>;@@ -105,9 +113,17 @@ export default class TriliumMentionUI extends Plugin {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) => ({+ ...feed,+ pattern: createMarkerPattern(feed.marker, feed),+ hostedList: feed.list(editor)+ }));editor.editing.view.document.on<ViewDocumentKeyDownEvent>("keydown", (evt, data) => {- if (this._isVisible && this._handleKeyDown(data.keyCode)) {+ const consumed = this._openHosted+ ? this._handleHostedKeyDown(this._openHosted.hostedList, data.keyCode, data.domEvent)+ : this._isVisible && this._handleKeyDown(data.keyCode);+ if (consumed) {data.preventDefault();evt.stop(); // Required to override the Enter key.}@@ -118,7 +134,8 @@ export default class TriliumMentionUI extends Plugin {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: () => {- const element = this._listView ? this._listView.element : this._balloon?.view.element;+ const element = this._openHosted?.hostedList.element+ ?? (this._listView ? this._listView.element : this._balloon?.view.element);return element ? [ element ] : [];},callback: () => this._hide()@@ -136,9 +153,16 @@ export default class TriliumMentionUI extends Plugin {// Balloon views are not destroyed automatically — see ckeditor5#1341.this._view.destroy();this._listView?.destroy?.();+ for (const { hostedList } of this._hosted) {+ hostedList.destroy?.();+ }}private get _isVisible() {+ if (this._openHosted) {+ return !!this._openHosted.hostedList.element;+ }+return this._listView ? this._listShown : this._balloon?.visibleView === this._view;}@@ -190,6 +214,23 @@ export default class TriliumMentionUI extends Plugin {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.+ */+ private _handleHostedKeyDown(list: MentionHostedList, keyCode: number, event: KeyboardEvent): boolean {+ if (keyCode !== keyCodes.esc) {+ return list.handleKeyDown(event);+ }++ if (!list.element) {+ return false;+ }++ this._dismiss();+ return true;+ }+/*** Hides the panel and remembers that the user rejected *this* marker, so it does not immediately* reopen on the next keystroke. No document mutation is involved.@@ -234,7 +275,7 @@ 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(this._patterns, text) ?? false);+ const watcher = new TextWatcher(editor.model, (text) => findMarkerMatch<Pattern | HostedPattern>([ ...this._patterns, ...this._hosted ], text) ?? false);// Only typing opens the panel. `matched:selection` fires on any direct caret move — a click// or an arrow key — and reopening there is the "clicking always triggers an autocomplete"@@ -253,7 +294,7 @@ export default class TriliumMentionUI extends Plugin {}}- private _onTyped({ feed, query }: MarkerMatch<Pattern>) {+ private _onTyped({ feed, query }: MarkerMatch<Pattern | HostedPattern>) {const model = this.editor.model;const focus = model.document.selection.focus;@@ -286,6 +327,12 @@ 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);@@ -384,7 +431,16 @@ export default class TriliumMentionUI extends Plugin {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;@@ -395,11 +451,77 @@ export default class TriliumMentionUI extends Plugin {this._balloon.remove(this._view);}- if (this.editor.model.markers.has(MARKER_NAME)) {- this.editor.model.change((writer) => writer.removeMarker(MARKER_NAME));+ this._view.position = undefined;+ }++ /** Shows the host's list of `feed` for `query`, in place of any other list. */+ private _showHosted(feed: HostedPattern, 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 */+ if (!marker) {+ return;}- this._view.position = undefined;+ // 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();+ }++ this._openHosted = feed;+ feed.hostedList.show({+ query,+ caretRect: () => {+ const { left, top, width, height } = this._caretRect(marker);+ return new DOMRect(left, top, width, height);+ },+ editable: this.editor.editing.view.getDomRoot() ?? null,+ commit: (item) => this._commitHosted(feed.marker, item)+ });+ }++ private _hideHosted() {+ const open = this._openHosted;+ this._openHosted = null;+ open?.hostedList.hide();+ }++ /**+ * Replaces the trigger text with a mention of `item`. For a promise, the text stays where it is,+ * followed by a live range, until it settles.+ */+ private _commitHosted(markerText: string, item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined>) {+ const editor = this.editor;+ const model = editor.model;+ const marker = model.markers.get(MARKER_NAME);+ const focus = model.document.selection.focus;++ // A pick arriving after the list closed, such as a click racing a caret move.+ if (!marker || !focus) {+ return;+ }++ 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.+ if (mention && range.root.rootName !== "$graveyard") {+ editor.execute("mention", { mention, text: mention.text, marker: markerText, range: range.toRange() });+ editor.editing.view.focus();+ }+ range.detach();+ };++ if (item instanceof Promise) {+ void item.then(insert, () => range.detach());+ } else {+ insert(item);+ }}private _createView(): MentionsView {@@ -580,7 +702,7 @@ export default class TriliumMentionUI extends Plugin {type TriliumMatchedEvent = {name: "matched:data";- args: [ MarkerMatch<Pattern> & { text: string } ];+ args: [ MarkerMatch<Pattern | HostedPattern> & { text: string } ];};function isInExistingMention(position: ModelPosition): boolean {diff --git a/packages/ckeditor5/src/plugins/mention/types.ts b/packages/ckeditor5/src/plugins/mention/types.tsindex 0941cd7639..4dfc9907d5 100644--- a/packages/ckeditor5/src/plugins/mention/types.ts+++ b/packages/ckeditor5/src/plugins/mention/types.ts@@ -110,3 +110,55 @@ export interface MentionListView {readonly element: HTMLElement | null;destroy?(): void;}++declare module "@ckeditor/ckeditor5-mention" {+ interface MentionConfig {+ /**+ * Markers whose list the host runs entirely: what it lists, how it draws it, which entry is+ * highlighted and what a pick means. {@link TriliumMentionUI} only reports the query typed+ * after the marker, forwards the keys while the list is open and commits what the host hands+ * back.+ */+ hostedFeeds?: MentionHostedFeed[];+ }+}++/** A marker whose list the host runs. See `mention.hostedFeeds`. */+export interface MentionHostedFeed {+ marker: string;+ /** See `MentionFeed.minimumCharacters`. */+ minimumCharacters?: number;+ /** See `MentionFeed.allowSpaces`. */+ allowSpaces?: boolean;+ /** Creates the list, once per editor. */+ list( editor: Editor ): MentionHostedList;+}++/** What a {@link MentionHostedList} is shown for, each time the query changes. */+export interface MentionHostedListState {+ /** The text typed after the marker, up to the caret. */+ query: string;+ /** Where the caret ends the query, in viewport coordinates. */+ caretRect(): DOMRect;+ /** The editable element the caret is in. See {@link MentionListState.editable}. */+ editable: HTMLElement | null;+ /**+ * Replaces the marker and the query with a mention of `item`, as a pick from the list does. For a+ * promise, the text stays until it settles, and stays for good where it settles on `undefined`.+ */+ commit( item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined> ): void;+}++/** A host's list for a marker in `mention.hostedFeeds`. */+export interface MentionHostedList {+ show( state: MentionHostedListState ): void;+ hide(): void;+ /**+ * Handles a key pressed in the editor while the list is open, other than Escape, which closes it.+ * Returns whether the list took the key, which then reaches the editor no further.+ */+ handleKeyDown( event: KeyboardEvent ): boolean;+ /** The list's element while it shows entries, inside which a press does not close it. */+ readonly element: HTMLElement | null;+ destroy?(): void;+}diff --git a/packages/ckeditor5/src/plugins/mention_customization.spec.ts b/packages/ckeditor5/src/plugins/mention_customization.spec.tsindex cfa5fadccd..3a5ffbc338 100644--- a/packages/ckeditor5/src/plugins/mention_customization.spec.ts+++ b/packages/ckeditor5/src/plugins/mention_customization.spec.ts@@ -16,13 +16,10 @@ import ReferenceLink from "./referencelink.js";describe("MentionCustomization", () => {let editor: ClassicEditor;- let createNoteForReferenceLink: ReturnType<typeof vi.fn>;beforeEach(async () => {- createNoteForReferenceLink = vi.fn(async () => "createdNotePath");installGlobMock({getComponentByEl: () => ({- createNoteForReferenceLink,loadReferenceLinkTitle: vi.fn(async () => {})}),getReferenceLinkTitle: vi.fn(async () => "Some title"),@@ -80,28 +77,6 @@ describe("MentionCustomization", () => {expect(getModelData(editor.model)).toContain("noteAbc");});- it.each([- { action: "create-note", intoInbox: true },- { action: "create-child-note", intoInbox: false }- ])("creates a note then inserts the reference link for a $action mention", async ({ action, intoInbox }) => {- setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");-- editor.execute("mention", {- mention: { id: "@Brand new note", action, noteTitle: "Brand new note" },- marker: "@"- });-- expect(createNoteForReferenceLink).toHaveBeenCalledWith("Brand new note", intoInbox);-- // Wait for the createNoteForReferenceLink promise (and the chained- // getReferenceLinkTitle promise from the referenceLink command) to resolve.- await Promise.resolve();- await Promise.resolve();-- expect(getModelData(editor.model)).toContain("<reference");- expect(getModelData(editor.model)).toContain("createdNotePath");- });-it("uses the provided range instead of the current selection when inserting a reference", async () => {setModelData(editor.model, "<paragraph>[]foobar</paragraph>");diff --git a/packages/ckeditor5/src/plugins/mention_customization.ts b/packages/ckeditor5/src/plugins/mention_customization.tsindex cf87183763..de6239a36c 100644--- a/packages/ckeditor5/src/plugins/mention_customization.ts+++ b/packages/ckeditor5/src/plugins/mention_customization.ts@@ -6,8 +6,7 @@ import TriliumMentionUI from "./mention/trilium_mention_ui.js";* Overrides the actions taken by the Mentions plugin (triggered by `@` in the text editor, or `~` & `#` in the attribute editor):** - Auto-completes attributes and relations in the attribute editor.- * - Triggers the modal to create notes.- * - Inserts a reference link when a mention is selected.+ * - Inserts a reference link when a note is mentioned.*/export default class MentionCustomization extends Plugin {@@ -38,8 +37,6 @@ interface MentionOpts {interface MentionAttribute {id: string;- action?: "create-note" | "create-child-note";- noteTitle: string;notePath: string;}@@ -58,17 +55,6 @@ class CustomMentionCommand extends Command {model.insertContent( writer.createText( mention.id, {} ), range );});}- else if (mention.action === 'create-note' || mention.action === 'create-child-note') {- const editorEl = this.editor.editing.view.getDomRoot();- const component = glob.getComponentByEl<EditorComponent>(editorEl);- const intoInbox = mention.action === 'create-note';-- component.createNoteForReferenceLink(mention.noteTitle, intoInbox).then(notePath => {- if (notePath) {- this.insertReference(range, notePath);- }- });- }else {this.insertReference(range, mention.notePath);}