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(autocomplete): point the editors at the hosted list's highlighted entry
Elian Doranfe44fdd6e804
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex a30f8386a3..f0f33d73fc 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -192,7 +192,7 @@ const CARET_LIST_MIN_WIDTH = 220;* a text editor, which keeps the focus and forwards its keys through `handleRef`. It opens with* nothing highlighted, so Enter stays with the host until an entry is arrowed to.*/-export function AutocompleteList({ query, source, anchor, renderItem, onPick, handleRef, elementRef }: {+export function AutocompleteList({ query, source, anchor, renderItem, onPick, handleRef, elementRef, onActiveDescendant }: {query: string;source(query: string): Promise<string[]>;anchor: DropdownAnchor;@@ -200,6 +200,8 @@ export function AutocompleteList({ query, source, anchor, renderItem, onPick, haonPick(item: string): void;handleRef: MutableRef<AutocompleteListHandle | null>;elementRef?: PopupProps["elementRef"];+ /** Called with the id of the highlighted entry's element, or `null` while none is highlighted. */+ onActiveDescendant?(id: string | null): void;}) {// The focus stays where the query is typed, so there is no field to return it to.const inputRef = useRef<HTMLInputElement>(null);@@ -207,7 +209,7 @@ export function AutocompleteList({ query, source, anchor, renderItem, onPick, ha// The host shows the list by mounting it and closes it by unmounting it.useEffect(() => autocomplete.open(), []);- useForwardedKeys(autocomplete, handleRef);+ useForwardedKeys(autocomplete, handleRef, onActiveDescendant);return (<AutocompleteDropdown@@ -223,9 +225,22 @@ export function AutocompleteList({ query, source, anchor, renderItem, onPick, ha/*** Takes the keys forwarded from where a list's query is typed. Tab takes the highlighted entry, as- * Enter does, where a field leaves Tab to move the focus.+ * Enter does, where a field leaves Tab to move the focus. Reports the highlighted entry's element id+ * to `onActiveDescendant`, for the host to point its `aria-activedescendant` at, as a field's+ * `comboboxProps` do.*/-export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocomplete<T>>, handleRef: MutableRef<AutocompleteListHandle | null>) {+export function useForwardedKeys<T>(+ autocomplete: ReturnType<typeof useAutocomplete<T>>,+ handleRef: MutableRef<AutocompleteListHandle | null>,+ onActiveDescendant?: (id: string | null) => void+) {+ const { isShown, activeIndex, itemId } = autocomplete;+ const activeId = isShown && activeIndex >= 0 ? itemId(activeIndex) : null;+ const onActiveDescendantRef = useRef(onActiveDescendant);+ onActiveDescendantRef.current = onActiveDescendant;+ useEffect(() => onActiveDescendantRef.current?.(activeId), [ activeId ]);+ useEffect(() => () => onActiveDescendantRef.current?.(null), []);+useLayoutEffect(() => {handleRef.current = {handleKeyDown(e) {diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 140acb9ffa..25b456c4d7 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -439,7 +439,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,* creation row: `onPick` then receives a promise, settling on `undefined` where the creation is* canceled.*/-export function NoteMentionList({ query, anchor, allowCreatingNotes, parentNotePath, preselect = true, onPick, handleRef, elementRef }: {+export function NoteMentionList({ query, anchor, allowCreatingNotes, parentNotePath, preselect = true, onPick, handleRef, elementRef, onActiveDescendant }: {query: string;anchor: PopupProps["anchor"];allowCreatingNotes?: boolean;@@ -450,6 +450,8 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, parentNotePonPick(notePath: string | Promise<string | undefined>): void;handleRef: MutableRef<AutocompleteListHandle | null>;elementRef?: PopupProps["elementRef"];+ /** Called with the id of the highlighted entry's element, or `null` while none is highlighted. */+ onActiveDescendant?(id: string | null): void;}) {// The focus stays where the query is typed, so there is no field to return it to.const inputRef = useRef<HTMLInputElement>(null);@@ -476,7 +478,7 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, parentNoteP// The host shows the list by mounting it and closes it by unmounting it.useEffect(() => autocomplete.open(), []);- useForwardedKeys(autocomplete, handleRef);+ useForwardedKeys(autocomplete, handleRef, onActiveDescendant);return autocomplete.isShown && (<NoteSuggestionPopup anchor={anchor} elementRef={elementRef} className="note-mention-menu">@@ -505,7 +507,7 @@ export interface CommandEntry {* command palette lists its own after a `>`. The host keeps the focus and forwards its keys through* `handleRef`. It opens on the best match, so Enter takes it, unless `preselect` is off.*/-export function CommandMentionList<T extends CommandEntry>({ query, source, anchor, className, preselect = true, onPick, handleRef, elementRef }: {+export function CommandMentionList<T extends CommandEntry>({ query, source, anchor, className, preselect = true, onPick, handleRef, elementRef, onActiveDescendant }: {query: string;/** The entries for a query, looked up as soon as it changes, with no debounce. */source(query: string): Promise<T[]>;@@ -517,6 +519,8 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anchonPick(entry: T): void;handleRef: MutableRef<AutocompleteListHandle | null>;elementRef?: PopupProps["elementRef"];+ /** Called with the id of the highlighted entry's element, or `null` while none is highlighted. */+ onActiveDescendant?(id: string | null): void;}) {// The focus stays where the query is typed, so there is no field to return it to.const inputRef = useRef<HTMLInputElement>(null);@@ -524,7 +528,7 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anch// The host shows the list by mounting it and closes it by unmounting it.useEffect(() => autocomplete.open(), []);- useForwardedKeys(autocomplete, handleRef);+ useForwardedKeys(autocomplete, handleRef, onActiveDescendant);return autocomplete.isShown && (<NoteSuggestionPopup anchor={anchor} elementRef={elementRef} className={className}>@@ -557,6 +561,8 @@ export interface HostedListProps {anchor: ReferenceElement;handleRef: MutableRef<AutocompleteListHandle | null>;elementRef(element: HTMLElement | null): void;+ /** Points the editor at the highlighted entry, through the state's `setActiveDescendant()`. */+ onActiveDescendant(id: string | null): void;}/**@@ -564,16 +570,19 @@ export interface HostedListProps {* `mention.hostedFeeds` or CodeMirror's `hostedMention()`. It renders what `draw` returns for each* query, at the caret, and forwards the editor's keys to it.*/-export function createHostedList<S extends { caretRect(): DOMRect; editable: HTMLElement | null }>(+export function createHostedList<S extends { caretRect(): DOMRect; editable: HTMLElement | null; setActiveDescendant(id: string | null): void }>(draw: (state: S, list: HostedListProps) => VNode) {const container = document.createElement("div");const handleRef: { current: AutocompleteListHandle | null } = { current: null };let element: HTMLElement | null = null;const elementRef = (el: HTMLElement | null) => { element = el; };+ let shown: S | null = null;+ const onActiveDescendant = (id: string | null) => shown?.setActiveDescendant(id);const unmount = () => {render(null, container);element = null;+ shown = null;};return {@@ -581,7 +590,8 @@ export function createHostedList<S extends { caretRect(): DOMRect; editable: HTM// A new anchor each time, so the list is placed again at the caret. Its `contextElement`// places it again as the containers around the editor scroll.const anchor = { getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined };- render(draw(state, { anchor, handleRef, elementRef }), container);+ shown = state;+ render(draw(state, { anchor, handleRef, elementRef, onActiveDescendant }), container);},hide: unmount,handleKeyDown: (e: KeyboardEvent) => handleRef.current?.handleKeyDown(e) ?? false,diff --git a/apps/client/src/widgets/search_field_editor.spec.tsx b/apps/client/src/widgets/search_field_editor.spec.tsxindex 2928848e50..854f10bca3 100644--- a/apps/client/src/widgets/search_field_editor.spec.tsx+++ b/apps/client/src/widgets/search_field_editor.spec.tsx@@ -64,12 +64,18 @@ describe("createSearchFieldEditor", () => {await press("Enter");expect(onEnter).toHaveBeenCalledOnce();+ expect(activeDescendant()).toBe(null);await press("ArrowDown");await press("ArrowDown");+ // The field points assistive technology at the row the arrows reached.+ const active = document.querySelector(".form-autocomplete-dropdown [aria-selected=true]");+ expect(active?.textContent).toBe("bookmark");+ await vi.waitFor(() => expect(activeDescendant()).toBe(active?.id));await press("Enter");await vi.waitFor(() => expect(text()).toBe("#bookmark"));expect(onEnter).toHaveBeenCalledOnce();+ expect(activeDescendant()).toBe(null);});it("lists the rest of the syntax as the command palette lists its commands, and opens on what a pick leaves to complete", async () => {@@ -110,6 +116,10 @@ describe("createSearchFieldEditor", () => {function text() {return editor?.state.doc.toString();}++ function activeDescendant() {+ return editor?.contentDOM.getAttribute("aria-activedescendant") ?? null;+ }});function menuRows(menu: string) {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 bd362c8792..488a633351 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@@ -27,21 +27,27 @@ describe("createNoteMentionList", () => {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 }));+ const setActiveDescendant = vi.fn<MentionHostedListState["setActiveDescendant"]>();+ await act(async () => list.show({ query: "al", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit, setActiveDescendant }));await act(async () => { await vi.advanceTimersByTimeAsync(300); });- return { list, commit };+ return { list, commit, setActiveDescendant };}it("lists the notes for the query, and mentions the one picked by its path", async () => {- const { list, commit } = await open();+ const { list, commit, setActiveDescendant } = await open();expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { allowCreatingNotes: true, limit: 10 });expect(list.element?.textContent).toContain("Alpha");+ // The editor is pointed at the row the list opens on.+ const active = list.element?.querySelector("[aria-selected=true]");+ expect(active?.id).toBeTruthy();+ expect(setActiveDescendant).toHaveBeenLastCalledWith(active?.id);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(setActiveDescendant).toHaveBeenLastCalledWith(null);expect(list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }))).toBe(false);list.destroy?.();});@@ -70,7 +76,7 @@ describe("createNoteMentionList", () => {const commit = vi.fn<MentionHostedListState["commit"]>();// The editor is reused for the next note, so the parent is read as the list is shown.editedNotePath = "root/second";- await act(async () => list.show({ query: "al", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => list.show({ query: "al", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit, setActiveDescendant: vi.fn() }));await act(async () => { await vi.advanceTimersByTimeAsync(300); });list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }));@@ -98,7 +104,7 @@ describe("createAutocompleteMentionList", () => {const commit = vi.fn<MentionHostedListState["commit"]>();const key = (k: string) => list.handleKeyDown(new KeyboardEvent("keydown", { key: k, cancelable: true }));- await act(async () => list.show({ query: "ab", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => list.show({ query: "ab", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit, setActiveDescendant: vi.fn() }));await act(async () => { await vi.advanceTimersByTimeAsync(300); });expect(source).toHaveBeenLastCalledWith("ab");@@ -133,7 +139,7 @@ describe("createSlashCommandList", () => {const commit = vi.fn<MentionHostedListState["commit"]>();const key = (k: string) => list.handleKeyDown(new KeyboardEvent("keydown", { key: k, cancelable: true }));- await act(async () => list.show({ query: "q", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => list.show({ query: "q", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit, setActiveDescendant: vi.fn() }));// The list opens, then looks its entries up at once, with no debounce to wait out.await act(async () => {});@@ -159,7 +165,7 @@ describe("createSlashCommandList", () => {const editor = { plugins: { get: () => ({ search }) } } as unknown as Parameters<NonNullable<SlashCommandConfig["list"]>>[0];const list = createSlashCommandList(editor);const commit = vi.fn<MentionHostedListState["commit"]>();- const show = (query: string) => list.show({ query, caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit });+ const show = (query: string) => list.show({ query, caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit, setActiveDescendant: vi.fn() });await act(async () => show(""));await act(async () => {});@@ -187,7 +193,7 @@ describe("createEmojiList", () => {const commit = vi.fn<MentionHostedListState["commit"]>();const key = (k: string) => list.handleKeyDown(new KeyboardEvent("keydown", { key: k, cancelable: true }));- await act(async () => list.show({ query: "grin", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => list.show({ query: "grin", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit, setActiveDescendant: vi.fn() }));await act(async () => {});expect(search).toHaveBeenLastCalledWith("grin");diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.tsindex 47dd466b81..952d189fab 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.spec.ts@@ -248,6 +248,24 @@ describe("TriliumMentionUI", () => {expect(labels.state).toBe(null);});+ it("points the editable at the entry the open list highlights, and at none once it closes", () => {+ const root = editor.editing.view.getDomRoot();+ type("#al");+ const open = labels.state;++ open?.setActiveDescendant("row-1");+ expect(root?.getAttribute("aria-activedescendant")).toBe("row-1");+ open?.setActiveDescendant(null);+ expect(root?.hasAttribute("aria-activedescendant")).toBe(false);++ open?.setActiveDescendant("row-2");+ document.body.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));+ expect(root?.hasAttribute("aria-activedescendant")).toBe(false);+ // A list that has closed points at nothing.+ open?.setActiveDescendant("row-3");+ expect(root?.hasAttribute("aria-activedescendant")).toBe(false);+ });+it("hides the list when the editor becomes read-only", () => {type("#al");editor.enableReadOnlyMode("test");diff --git a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.tsindex aa22fc42f5..84189e1083 100644--- a/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts+++ b/packages/ckeditor5/src/plugins/mention/trilium_mention_ui.ts@@ -51,6 +51,8 @@ export default class TriliumMentionUI extends Plugin {private _feeds: Pattern[] = [];/** The marker whose list is open, or `null`. */private _open: Pattern | null = null;+ /** The id the editable's `aria-activedescendant` holds, or `null` while it holds none. */+ private _activeDescendant: string | null = null;/** Listens for presses outside the open list, which close it. */private readonly _domEmitter = new (DomEmitterMixin())();@@ -243,7 +245,12 @@ export default class TriliumMentionUI extends Plugin {},/* v8 ignore next -- a live editor's editing view always has its DOM root, so the `?? null` arm never runs */editable: this.editor.editing.view.getDomRoot() ?? null,- commit: (item) => this._commit(feed, item)+ commit: (item) => this._commit(feed, item),+ setActiveDescendant: (id) => {+ if (this._open === feed) {+ this._setActiveDescendant(id);+ }+ }});}@@ -259,9 +266,34 @@ export default class TriliumMentionUI extends Plugin {private _hideList() {const open = this._open;this._open = null;+ this._setActiveDescendant(null);open?.hostedList.hide();}+ /** Sets the root editable's `aria-activedescendant` through the view, whose renderer owns its attributes. */+ private _setActiveDescendant(id: string | null) {+ if (id === this._activeDescendant) {+ return;+ }++ const view = this.editor.editing.view;+ const root = view.document.getRoot();++ /* v8 ignore next 3 -- a live editor's editing view always has its root, so the guard only narrows its type */+ if (!root) {+ return;+ }++ this._activeDescendant = id;+ view.change((writer) => {+ if (id) {+ writer.setAttribute("aria-activedescendant", id, root);+ } else {+ writer.removeAttribute("aria-activedescendant", root);+ }+ });+ }+/*** Replaces the trigger text with a mention of `item`, or hands `item` to the feed's `commit`.* For a promise, the text stays where it is, followed by a live range, until it settles.diff --git a/packages/ckeditor5/src/plugins/mention/types.ts b/packages/ckeditor5/src/plugins/mention/types.tsindex d541e418f7..9861d1aa58 100644--- a/packages/ckeditor5/src/plugins/mention/types.ts+++ b/packages/ckeditor5/src/plugins/mention/types.ts@@ -73,6 +73,11 @@ export interface MentionHostedListState {* stays for good where it settles on `undefined`.*/commit( item: MentionFeedObjectItem | Promise<MentionFeedObjectItem | undefined> ): void;+ /**+ * Points the editable at the list's highlighted entry through `aria-activedescendant`, by the+ * id of the entry's element, or at none for `null`. Once the list closes, it points at none.+ */+ setActiveDescendant( id: string | null ): void;}/** A host's list for a marker in `mention.hostedFeeds`. */diff --git a/packages/codemirror/src/extensions/hosted_completion.spec.ts b/packages/codemirror/src/extensions/hosted_completion.spec.tsindex 2db82922d1..cbc877dfe8 100644--- a/packages/codemirror/src/extensions/hosted_completion.spec.ts+++ b/packages/codemirror/src/extensions/hosted_completion.spec.ts@@ -189,6 +189,34 @@ describe("hostedCompletion", () => {expect(list.destroy).toHaveBeenCalledOnce();});+ it("points the editor at the entry the open list highlights, and at none once it closes", async () => {+ const { shown } = build();+ type("@");+ await vi.waitFor(() => expect(shown()).toBeDefined());+ const open = shown();+ const activeDescendant = () => editor?.contentDOM.getAttribute("aria-activedescendant");++ open?.setActiveDescendant("row-1");+ expect(activeDescendant()).toBe("row-1");+ open?.setActiveDescendant(null);+ expect(activeDescendant()).toBe(null);++ open?.setActiveDescendant("row-2");+ type(" ");+ expect(activeDescendant()).toBe(null);+ // A list that has closed points at nothing.+ open?.setActiveDescendant("row-3");+ expect(activeDescendant()).toBe(null);++ type("@");+ await vi.waitFor(() => expect(shown()).not.toBe(open));+ shown()?.setActiveDescendant("row-4");+ const dom = editor?.contentDOM;+ editor?.destroy();+ editor = undefined;+ expect(dom?.hasAttribute("aria-activedescendant")).toBe(false);+ });+it("places the list at the caret, or at the editor where the caret has no place on screen", async () => {const { shown, placed } = build();type("@");diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.tsindex 5dfe819132..0c743a619e 100644--- a/packages/codemirror/src/extensions/hosted_completion.ts+++ b/packages/codemirror/src/extensions/hosted_completion.ts@@ -16,6 +16,11 @@ export interface HostedCompletionState<M extends HostedCompletionMatch> {editable: HTMLElement;/** Replaces what stands between the match's `from` and the caret with `text`, as a pick does. */commit(text: string): void;+ /**+ * Points the editor at the list's highlighted entry through `aria-activedescendant`, by the id+ * of the entry's element, or at none for `null`. Once the list closes, it points at none.+ */+ setActiveDescendant(id: string | null): void;}/** A host's list for {@link hostedCompletion}. */@@ -110,6 +115,7 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, list}destroy() {+ this.setActiveDescendant(null);this.list.hide();this.list.destroy?.();}@@ -144,7 +150,12 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listmatch: found.match,caretRect: () => (showing ? measured : caretRect(this.view)),editable: this.view.dom,- commit: (text) => this.commit(found.from, text)+ commit: (text) => this.commit(found.from, text),+ setActiveDescendant: (id) => {+ if (this.from === found.from) {+ this.setActiveDescendant(id);+ }+ }});showing = false;}@@ -172,8 +183,18 @@ export function hostedCompletion<M extends HostedCompletionMatch>({ match, listthis.from = -1;this.before = "";+ this.setActiveDescendant(null);this.list.hide();}++ /** Set on `contentDOM` directly: CodeMirror removes only the attributes it set itself. */+ private setActiveDescendant(id: string | null) {+ if (id) {+ this.view.contentDOM.setAttribute("aria-activedescendant", id);+ } else {+ this.view.contentDOM.removeAttribute("aria-activedescendant");+ }+ }}, {eventHandlers: {keydown(event) {