Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): list the suggestions of the note autocomplete

Elian Doranbf87b2295ae5
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.ts
index 7087af7c8a..beaf2e3072 100644
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts
@@ -232,53 +232,6 @@ describe("autocompleteSource (via dataset)", () => {
expect(rows.every((r) => r.action !== "search-notes")).toBe(true);
});
- it("renders a note suggestion via the template (default icon, no attribute snippet)", () => {
- const { dataset } = initAndGetSource();
- const html = dataset.templates.suggestion({ highlightedNotePathTitle: "Title" });
- expect(html).toContain("note-suggestion");
- expect(html).toContain("bx bx-note");
- expect(html).toContain("Title");
- expect(html).not.toContain("search-result-attributes");
- });
-
- it("renders a note suggestion with explicit icon and attribute snippet", () => {
- const { dataset } = initAndGetSource();
- const html = dataset.templates.suggestion({
- highlightedNotePathTitle: "T",
- icon: "bx bx-star",
- highlightedAttributeSnippet: "#color=red"
- });
- expect(html).toContain("bx bx-star");
- expect(html).toContain("search-result-attributes");
- expect(html).toContain("#color=red");
- });
-
- it("never renders a content snippet, whatever the suggestion carries", () => {
- // The dropdown lists notes matched by title and attributes, so a body excerpt would
- // suggest a content match that fast search never made.
- const { dataset } = initAndGetSource();
- const html = dataset.templates.suggestion({
- highlightedNotePathTitle: "T",
- highlightedContentSnippet: "some <b>matched</b> content"
- });
- expect(html).not.toContain("search-result-content");
- expect(html).not.toContain("matched");
- });
-
- it("renders search-notes, create-note and external-link suggestion icons/classes", () => {
- const { dataset } = initAndGetSource();
- expect(dataset.templates.suggestion({ action: "search-notes", highlightedNotePathTitle: "S" }))
- .toContain("search-notes-action");
- expect(dataset.templates.suggestion({ action: "search-notes", highlightedNotePathTitle: "S" }))
- .toContain("bx bx-search");
- expect(dataset.templates.suggestion({ action: "create-note", highlightedNotePathTitle: "C" }))
- .toContain("bx bx-plus");
- expect(dataset.templates.suggestion({ action: "create-child-note", highlightedNotePathTitle: "C" }))
- .toContain("bx bx-subdirectory-right");
- expect(dataset.templates.suggestion({ action: "external-link", highlightedNotePathTitle: "E" }))
- .toContain("bx bx-link-external");
- });
-
it("renders a command suggestion with description and shortcut", () => {
const { dataset } = initAndGetSource();
const html = dataset.templates.suggestion({
@@ -724,21 +677,6 @@ describe("initNoteAutocomplete wiring", () => {
$el.trigger("autocomplete:closed");
expect($el.attr("data-note-path")).toBe("root/keep");
});
-
- it("autocomplete:opened closes the dropdown for a readonly input", () => {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el);
- $el.attr("readonly", "readonly");
- $el.trigger("autocomplete:opened");
- expect(lastCommandWith("close")).toBe(true);
- });
-
- it("autocomplete:opened does nothing for a non-readonly input", () => {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el);
- $el.trigger("autocomplete:opened");
- expect(lastCommandWith("close")).toBe(false);
- });
});
describe("autocomplete:selected handler", () => {
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
index c4c8a10b20..c192032b19 100644
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ b/apps/client/src/services/note_autocomplete_bak.ts
@@ -329,35 +329,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
html += '</div>';
return html;
}
- // Add special class for search-notes action
- const actionClass = suggestion.action === "search-notes" ? "search-notes-action" : "";
-
- // Choose appropriate icon based on action
- let iconClass = suggestion.icon ?? "bx bx-note";
- if (suggestion.action === "search-notes") {
- iconClass = "bx bx-search";
- } else if (suggestion.action === "create-note") {
- iconClass = "bx bx-plus";
- } else if (suggestion.action === "create-child-note") {
- iconClass = "bx bx-subdirectory-right";
- } else if (suggestion.action === "external-link") {
- iconClass = "bx bx-link-external";
- }
-
- // Simplified HTML structure without nested divs
- let html = `<div class="note-suggestion ${actionClass}">`;
- html += `<span class="icon ${escapeHtml(iconClass)}"></span>`;
- html += `<span class="text">`;
- html += `<span class="search-result-title">${suggestion.highlightedNotePathTitle}</span>`;
-
- // Add attribute snippet inline if available
- if (suggestion.highlightedAttributeSnippet) {
- html += `<span class="search-result-attributes">${suggestion.highlightedAttributeSnippet}</span>`;
- }
-
- html += `</span>`;
- html += `</div>`;
- return html;
}
},
// we can't cache identical searches because notes can be created / renamed, new recent notes can be added
@@ -434,12 +405,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
}
});
- $el.on("autocomplete:opened", () => {
- if ($el.attr("readonly")) {
- $el.autocomplete("close");
- }
- });
-
// clear any event listener added in previous invocation of this function
$el.off("autocomplete:noteselected");
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 28698efe00..4fd5b0519f 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -1,6 +1,6 @@
import "./FormAutocomplete.css";
-import type { ComponentChildren, TargetedKeyboardEvent } from "preact";
+import type { ComponentChildren, RefObject } from "preact";
import { createPortal, type CSSProperties } from "preact/compat";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
@@ -106,19 +106,164 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
const ownInputRef = useRef<HTMLInputElement>(null);
const inputEl = inputRef ?? ownInputRef;
const fieldRef = useRef<HTMLDivElement>(null);
- const dropdownRef = useRef<HTMLUListElement>(null);
+ const [ position, setPosition ] = useState<CSSProperties>();
+ const isDisabled = !!(restProps.readOnly || restProps.disabled);
+
+ const autocomplete = useAutocomplete({
+ query: currentValue,
+ source,
+ onPick: onPick ?? onChange,
+ inputRef: inputEl,
+ disabled: isDisabled,
+ openOnFocus,
+ openOnEnter,
+ keepOpenOnPick,
+ autoActivate,
+ isHeading
+ });
+ const { isOpen, items, activeIndex, setActiveIndex, itemId, pick } = autocomplete;
+
+ // Keep the dropdown glued to the input.
+ useLayoutEffect(() => {
+ if (!isOpen || !items.length) {
+ return;
+ }
+
+ const reposition = () => {
+ // The wrapper where there is one, so a field carrying chips is spanned whole.
+ const anchor = fieldRef.current ?? inputEl.current;
+ if (anchor) {
+ setPosition(computeDropdownPosition(anchor, dropdownMinWidth));
+ }
+ };
+
+ reposition();
+ window.addEventListener("resize", reposition);
+ // Capture: the input may live inside a scrolling container rather than the document.
+ window.addEventListener("scroll", reposition, true);
+ return () => {
+ window.removeEventListener("resize", reposition);
+ window.removeEventListener("scroll", reposition, true);
+ };
+ }, [ isOpen, items.length, inputEl, dropdownMinWidth ]);
+
+ const field = (
+ <FormTextBox
+ // Keyed for the sake of a field carrying chips, which are keyed themselves: keyed and
+ // unkeyed siblings together are matched up by position as the chips grow, which rebuilds
+ // the box rather than keeping it — and a rebuilt box is one the focus has left.
+ key="field"
+ {...restProps}
+ inputRef={inputEl}
+ currentValue={currentValue}
+ onChange={(newValue) => {
+ onChange(newValue);
+ autocomplete.handleInput();
+ }}
+ onFocus={(e) => {
+ autocomplete.handleFocus();
+ onFocus?.(e);
+ }}
+ onBlur={(newValue) => {
+ autocomplete.handleBlur();
+ onBlur?.(newValue);
+ }}
+ onKeyDown={(e) => {
+ autocomplete.handleKeyDown(e);
+ onKeyDown?.(e);
+ }}
+ {...autocomplete.comboboxProps}
+ />
+ );
+
+ return (
+ <>
+ {leading !== undefined || trailing !== undefined
+ ? <div ref={fieldRef} className="tn-field form-autocomplete-field">{leading}{field}{trailing}</div>
+ : field}
+
+ {isOpen && items.length > 0 && position && createPortal(
+ <ul
+ className="form-autocomplete-dropdown"
+ role="listbox"
+ style={position}
+ // Keeps the input focused, so the blur handler does not close the dropdown
+ // before the click lands on an item.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {items.map((item, index) => (
+ isHeading?.(item)
+ ? <li key={item} className="form-autocomplete-heading" role="presentation">
+ {renderItem ? renderItem(item) : item}
+ </li>
+ : <li
+ key={item}
+ id={itemId(index)}
+ className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
+ role="option"
+ aria-selected={index === activeIndex}
+ onMouseEnter={() => setActiveIndex(index)}
+ onClick={() => pick(item)}
+ >
+ {renderItem ? renderItem(item) : item}
+ </li>
+ ))}
+ </ul>,
+ document.body)}
+ </>
+ );
+}
+
+interface UseAutocompleteOptions<T> {
+ /** The text in the field, which `source` is queried with. */
+ query: string;
+ /** See {@link FormAutocompleteProps.source}. */
+ source(query: string): Promise<T[]>;
+ /** Called with the entry picked by click or Enter. */
+ onPick(item: T): void;
+ /** The field, which keeps the focus once an entry is picked. */
+ inputRef: RefObject<HTMLInputElement>;
+ /** Keeps the list closed, for a read-only or disabled field. */
+ disabled?: boolean;
+ /** See {@link FormAutocompleteProps.openOnFocus}. */
+ openOnFocus?: boolean;
+ /** See {@link FormAutocompleteProps.openOnEnter}. */
+ openOnEnter?: boolean;
+ /** See {@link FormAutocompleteProps.keepOpenOnPick}. */
+ keepOpenOnPick?: boolean;
+ /** See {@link FormAutocompleteProps.autoActivate}. */
+ autoActivate?: boolean;
+ /** See {@link FormAutocompleteProps.isHeading}. */
+ isHeading?(item: T): boolean;
+ /** The text of an entry, which `autoActivate` matches against the query. Defaults to `String(item)`. */
+ textOf?(item: T): string;
+}
+
+/**
+ * The behavior of a combobox, without its markup: when the list opens and closes, which entry is
+ * highlighted, and what the keys do. The focus stays in the field, which points at the highlighted
+ * entry through `aria-activedescendant`.
+ *
+ * The host renders the list from `items`, gives each entry the id `itemId(index)`, and passes the
+ * field's events to the `handle*` functions. Entries are fetched debounced while the list is open,
+ * and a response to a superseded query is discarded.
+ */
+export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled, openOnFocus, openOnEnter, keepOpenOnPick, autoActivate, isHeading, textOf = String }: UseAutocompleteOptions<T>) {
const [ isOpen, setIsOpen ] = useState(false);
- const [ items, setItems ] = useState<string[]>([]);
+ const [ items, setItems ] = useState<T[]>([]);
const [ activeIndex, setActiveIndex ] = useState(-1);
- const [ position, setPosition ] = useState<CSSProperties>();
// Discards responses of queries that were superseded while in flight.
const latestQuery = useRef(0);
- const isDisabled = !!(restProps.readOnly || restProps.disabled);
// Names the entries so the field can point at the highlighted one: focus stays in the box, so
// that pointer is all a screen reader has to go on.
const itemIdPrefix = useUniqueName("autocomplete-item");
- const activeItemId = activeIndex >= 0 ? `${itemIdPrefix}-${activeIndex}` : undefined;
+ const itemId = useCallback((index: number) => `${itemIdPrefix}-${index}`, [ itemIdPrefix ]);
+ const isShown = isOpen && items.length > 0;
+
+ const open = useCallback(() => {
+ if (!disabled) setIsOpen(true);
+ }, [ disabled ]);
const close = useCallback(() => {
// Invalidates in-flight queries too, so a late response cannot repopulate a closed dropdown.
@@ -137,17 +282,17 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
const queryId = ++latestQuery.current;
const timeout = setTimeout(async () => {
- const suggestions = await source(currentValue);
+ const suggestions = await source(query);
// A newer query (or a close) happened while awaiting.
if (latestQuery.current === queryId) {
setItems(suggestions);
- setActiveIndex(autoActivate ? bestMatchIndex(suggestions, currentValue, isHeading) : -1);
+ setActiveIndex(autoActivate ? bestMatchIndex(suggestions, query, isHeading, textOf) : -1);
}
}, DEBOUNCE_MS);
return () => clearTimeout(timeout);
- }, [ isOpen, currentValue, source, autoActivate, isHeading ]);
+ }, [ isOpen, query, source, autoActivate, isHeading, textOf ]);
// Keep the highlighted entry in sight: it can be picked out on opening, or arrowed past the
// bottom of a list taller than the room the dropdown was given.
@@ -155,39 +300,15 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
if (activeIndex < 0) return;
// `nearest` scrolls the list by as little as it takes, and not at all while the entry is
// already in view — so hovering down a visible list never moves it under the pointer.
- dropdownRef.current?.children[activeIndex]?.scrollIntoView({ block: "nearest" });
- }, [ activeIndex, items ]);
-
- // Keep the dropdown glued to the input.
- useLayoutEffect(() => {
- if (!isOpen || !items.length) {
- return;
- }
-
- const reposition = () => {
- // The wrapper where there is one, so a field carrying chips is spanned whole.
- const anchor = fieldRef.current ?? inputEl.current;
- if (anchor) {
- setPosition(computeDropdownPosition(anchor, dropdownMinWidth));
- }
- };
-
- reposition();
- window.addEventListener("resize", reposition);
- // Capture: the input may live inside a scrolling container rather than the document.
- window.addEventListener("scroll", reposition, true);
- return () => {
- window.removeEventListener("resize", reposition);
- window.removeEventListener("scroll", reposition, true);
- };
- }, [ isOpen, items.length, inputEl, dropdownMinWidth ]);
+ document.getElementById(itemId(activeIndex))?.scrollIntoView({ block: "nearest" });
+ }, [ activeIndex, items, itemId ]);
- function selectItem(item: string) {
+ function pick(item: T) {
if (isHeading?.(item)) {
return;
}
- (onPick ?? onChange)(item);
+ onPick(item);
if (keepOpenOnPick) {
// Nothing is highlighted until the refreshed entries arrive, so Enter cannot take twice
// what the list is about to stop offering.
@@ -195,18 +316,16 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
} else {
close();
}
- inputEl.current?.focus();
+ inputRef.current?.focus();
}
- function handleKeyDown(e: TargetedKeyboardEvent<HTMLInputElement>) {
- const isDropdownShown = isOpen && items.length > 0;
-
+ function handleKeyDown(e: KeyboardEvent) {
switch (e.key) {
case "ArrowDown":
case "ArrowUp":
e.preventDefault();
- if (!isDropdownShown) {
- setIsOpen(true);
+ if (!isShown) {
+ open();
} else {
const delta = e.key === "ArrowDown" ? 1 : -1;
setActiveIndex((index) => stepOver(items, index, delta, isHeading));
@@ -214,18 +333,18 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
break;
case "Enter":
- if (isDropdownShown && activeIndex >= 0) {
+ if (isShown && activeIndex >= 0) {
// Consume the key so it does not also reach the surrounding form or dialog.
e.preventDefault();
e.stopPropagation();
- selectItem(items[activeIndex]);
- } else if (openOnEnter && !isDisabled) {
- setIsOpen(true);
+ pick(items[activeIndex]);
+ } else if (openOnEnter) {
+ open();
}
break;
case "Escape":
- if (isDropdownShown) {
+ if (isShown) {
// Only dismiss the dropdown; a surrounding popup keeps its own Escape handling.
e.stopPropagation();
close();
@@ -236,80 +355,33 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
close();
break;
}
-
- onKeyDown?.(e);
}
- const field = (
- <FormTextBox
- // Keyed for the sake of a field carrying chips, which are keyed themselves: keyed and
- // unkeyed siblings together are matched up by position as the chips grow, which rebuilds
- // the box rather than keeping it — and a rebuilt box is one the focus has left.
- key="field"
- {...restProps}
- inputRef={inputEl}
- currentValue={currentValue}
- onChange={(newValue) => {
- onChange(newValue);
- if (!isDisabled) {
- setIsOpen(true);
- }
- }}
- onFocus={(e) => {
- if (openOnFocus && !isDisabled) {
- setIsOpen(true);
- }
- onFocus?.(e);
- }}
- onBlur={(newValue) => {
- close();
- onBlur?.(newValue);
- }}
- onKeyDown={handleKeyDown}
- role="combobox"
- aria-expanded={isOpen && items.length > 0}
- aria-autocomplete="list"
- aria-activedescendant={activeItemId}
- />
- );
-
- return (
- <>
- {leading !== undefined || trailing !== undefined
- ? <div ref={fieldRef} className="tn-field form-autocomplete-field">{leading}{field}{trailing}</div>
- : field}
-
- {isOpen && items.length > 0 && position && createPortal(
- <ul
- ref={dropdownRef}
- className="form-autocomplete-dropdown"
- role="listbox"
- style={position}
- // Keeps the input focused, so the blur handler does not close the dropdown
- // before the click lands on an item.
- onMouseDown={(e) => e.preventDefault()}
- >
- {items.map((item, index) => (
- isHeading?.(item)
- ? <li key={item} className="form-autocomplete-heading" role="presentation">
- {renderItem ? renderItem(item) : item}
- </li>
- : <li
- key={item}
- id={`${itemIdPrefix}-${index}`}
- className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
- role="option"
- aria-selected={index === activeIndex}
- onMouseEnter={() => setActiveIndex(index)}
- onClick={() => selectItem(item)}
- >
- {renderItem ? renderItem(item) : item}
- </li>
- ))}
- </ul>,
- document.body)}
- </>
- );
+ return {
+ isOpen,
+ isShown,
+ items,
+ activeIndex,
+ setActiveIndex,
+ itemId,
+ open,
+ close,
+ pick,
+ /** Call once the field's text has changed. */
+ handleInput: open,
+ handleFocus() {
+ if (openOnFocus) open();
+ },
+ handleBlur: close,
+ handleKeyDown,
+ /** The field's combobox attributes. */
+ comboboxProps: {
+ role: "combobox",
+ "aria-expanded": isShown,
+ "aria-autocomplete": "list",
+ "aria-activedescendant": activeIndex >= 0 ? itemId(activeIndex) : undefined
+ } as const
+ };
}
/**
@@ -318,10 +390,10 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
* opens on its best candidate. Matched the way the sources filter — ignoring case and surrounding
* space.
*/
-function bestMatchIndex(items: string[], text: string, isHeading?: (item: string) => boolean) {
- const canBeTaken = (item: string) => !isHeading?.(item);
+function bestMatchIndex<T>(items: T[], text: string, isHeading: ((item: T) => boolean) | undefined, textOf: (item: T) => string) {
+ const canBeTaken = (item: T) => !isHeading?.(item);
const trimmed = text.trim().toLowerCase();
- const exact = items.findIndex((item) => canBeTaken(item) && item.toLowerCase() === trimmed);
+ const exact = items.findIndex((item) => canBeTaken(item) && textOf(item).toLowerCase() === trimmed);
return exact >= 0 ? exact : items.findIndex(canBeTaken);
}
@@ -334,7 +406,7 @@ function bestMatchIndex(items: string[], text: string, isHeading?: (item: string
* Exported for its own tests, the alternative being to drive a dropdown by keystrokes to find out
* which row a heading was skipped for.
*/
-export function stepOver(items: string[], from: number, delta: number, isHeading?: (item: string) => boolean) {
+export function stepOver<T>(items: T[], from: number, delta: number, isHeading?: (item: T) => boolean) {
let index = from;
for (let step = 0; step < items.length; step++) {
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.css
new file mode 100644
index 0000000000..c4dfe810db
--- /dev/null
+++ b/apps/client/src/widgets/react/NoteAutocomplete.css
@@ -0,0 +1,14 @@
+/* The styles `autocomplete.js` set inline on its suggestion list. */
+.algolia-autocomplete .aa-dropdown-menu,
+.algolia-autocomplete .aa-suggestions {
+ display: block;
+}
+
+.algolia-autocomplete .aa-suggestion {
+ white-space: nowrap;
+ cursor: pointer;
+
+ > * {
+ white-space: normal;
+ }
+}
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 3bcfcf57cd..ec4fda789c 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -1,10 +1,18 @@
import { act } from "preact/test-utils";
-import { describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+const { getNoteSuggestions } = vi.hoisted(() => ({
+ getNoteSuggestions: vi.fn<(term: string) => Promise<Suggestion[]>>(async () => [])
+}));
+
+vi.mock("../../services/note_autocomplete", () => ({ getNoteSuggestions }));
+
+import type { Suggestion } from "../../services/note_autocomplete";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
import NoteAutocomplete, { type NoteAutocompleteProps } from "./NoteAutocomplete";
+
async function render(props: NoteAutocompleteProps = {}) {
let container = document.createElement("div");
await act(async () => {
@@ -105,3 +113,142 @@ describe("NoteAutocomplete", () => {
expect(onBlur).toHaveBeenLastCalledWith("");
});
});
+
+describe("NoteAutocomplete's suggestion list", () => {
+ const notes: Suggestion[] = [
+ { notePath: "root/a", noteTitle: "Alpha", notePathTitle: "Alpha", highlightedNotePathTitle: "<b>Al</b>pha", icon: "bx bx-file" },
+ { notePath: "root/x/b", noteTitle: "Beta", notePathTitle: "X / Beta", highlightedNotePathTitle: "X / Beta",
+ highlightedAttributeSnippet: "#tag" }
+ ];
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ getNoteSuggestions.mockReset();
+ getNoteSuggestions.mockResolvedValue(notes);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ async function mount(props: NoteAutocompleteProps = {}) {
+ let input: HTMLInputElement | null = null;
+ await act(async () => {
+ input = renderInto(<NoteAutocomplete {...props} />).querySelector("input");
+ });
+ if (!input) throw new Error("no input rendered");
+ return input as HTMLInputElement;
+ }
+
+ /** Lets the debounced lookup run and the popup place itself. */
+ async function settle() {
+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });
+ }
+
+ async function type(input: HTMLInputElement, text: string) {
+ await act(async () => {
+ input.value = text;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ await settle();
+ }
+
+ async function press(input: HTMLInputElement, key: string) {
+ await act(async () => {
+ input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
+ });
+ await settle();
+ }
+
+ function rows() {
+ return [ ...document.querySelectorAll<HTMLElement>(".algolia-autocomplete .aa-dropdown-menu .aa-suggestion") ];
+ }
+
+ it("lists the notes in the plugin's markup, the first one highlighted", async () => {
+ const input = await mount();
+ await type(input, "al");
+
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al");
+ const [ alpha, beta ] = rows();
+ expect(rows()).toHaveLength(2);
+ expect(alpha.closest(".aa-suggestions")?.parentElement?.className).toBe("aa-dataset-0");
+ expect(alpha.className).toBe("aa-suggestion aa-cursor");
+ expect(alpha.querySelector(".note-suggestion .icon")?.className).toBe("icon bx bx-file");
+ expect(alpha.querySelector(".search-result-title")?.innerHTML).toBe("<b>Al</b>pha");
+ expect(beta.querySelector(".icon")?.className).toBe("icon bx bx-note");
+ expect(beta.querySelector(".search-result-attributes")?.textContent).toBe("#tag");
+ expect(input.getAttribute("aria-expanded")).toBe("true");
+ expect(input.getAttribute("aria-activedescendant")).toBe(alpha.id);
+ });
+
+ it("gives each kind of row its icon, and never shows a content snippet", async () => {
+ getNoteSuggestions.mockResolvedValue([
+ { action: "search-notes", highlightedNotePathTitle: "S" },
+ { action: "create-note", highlightedNotePathTitle: "C" },
+ { action: "create-child-note", highlightedNotePathTitle: "C" },
+ { action: "external-link", highlightedNotePathTitle: "E" },
+ // The list matches by title and attributes, so a body excerpt would suggest a content
+ // match that fast search never made.
+ { notePath: "root/c", highlightedNotePathTitle: "T", highlightedContentSnippet: "some <b>matched</b> content" } as Suggestion
+ ]);
+ const input = await mount();
+ await type(input, "x");
+
+ expect(rows().map((row) => row.querySelector(".icon")?.className)).toEqual([
+ "icon bx bx-search", "icon bx bx-plus", "icon bx bx-subdirectory-right", "icon bx bx-link-external", "icon bx bx-note"
+ ]);
+ expect(rows()[0].querySelector(".note-suggestion")?.classList.contains("search-notes-action")).toBe(true);
+ expect(rows()[4].textContent).toBe("T");
+ });
+
+ it("picks the highlighted note with Enter, and reports it", async () => {
+ const onChange = vi.fn();
+ const noteIdChanged = vi.fn();
+ const input = await mount({ onChange, noteIdChanged });
+ await type(input, "b");
+ await press(input, "ArrowDown");
+ expect(rows()[1].classList.contains("aa-cursor")).toBe(true);
+
+ await press(input, "Enter");
+ expect(onChange).toHaveBeenCalledWith(notes[1]);
+ expect(noteIdChanged).toHaveBeenCalledWith("b");
+ expect(input.value).toBe("Beta");
+ expect(input.dataset.notePath).toBe("root/x/b");
+ expect(rows()).toHaveLength(0);
+ });
+
+ it("picks a clicked note", async () => {
+ const noteIdChanged = vi.fn();
+ const input = await mount({ noteIdChanged });
+ await type(input, "a");
+
+ await act(async () => { rows()[0].click(); });
+ expect(noteIdChanged).toHaveBeenCalledWith("a");
+ expect(input.value).toBe("Alpha");
+ });
+
+ it("reports a selection cleared by emptying the field", async () => {
+ const onChange = vi.fn();
+ const noteIdChanged = vi.fn();
+ const input = await mount({ onChange, noteIdChanged });
+ await type(input, "a");
+ await press(input, "Enter");
+
+ await type(input, "");
+ await act(async () => { input.dispatchEvent(new Event("change", { bubbles: true })); });
+ expect(onChange).toHaveBeenLastCalledWith(null);
+ expect(noteIdChanged).toHaveBeenLastCalledWith(undefined);
+ expect(input.dataset.notePath).toBe("");
+ });
+
+ it("closes on Escape, and stays closed in a read-only field", async () => {
+ const input = await mount();
+ await type(input, "a");
+ await press(input, "Escape");
+ expect(rows()).toHaveLength(0);
+
+ const readOnly = await mount({ readOnly: true });
+ await press(readOnly, "ArrowDown");
+ expect(rows()).toHaveLength(0);
+ });
+});
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 922e99a31c..8aca13e3e5 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -1,12 +1,17 @@
+import "./NoteAutocomplete.css";
+
import clsx from "clsx";
import type { RefObject } from "preact";
import type { CSSProperties } from "preact/compat";
-import { useEffect, useState } from "preact/hooks";
+import { useCallback, useEffect, useState } from "preact/hooks";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
-import type { Options, Suggestion } from "../../services/note_autocomplete";
+import { getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
+import { useAutocomplete } from "./FormAutocomplete";
import { useSyncedRef } from "./hooks";
+import Popup from "./Popup";
+import RawHtml from "./RawHtml";
export interface NoteAutocompleteProps {
id?: string;
@@ -28,7 +33,7 @@ export interface NoteAutocompleteProps {
tabIndex?: number;
}
-export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, containerStyle, opts, onTextChange, onKeyDown, onBlur, noteId, readOnly, tabIndex }: NoteAutocompleteProps) {
+export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex }: NoteAutocompleteProps) {
const inputRef = useSyncedRef<HTMLInputElement>(externalInputRef);
const [ value, setValue ] = useState("");
const [ notePath, setNotePath ] = useState("");
@@ -43,6 +48,27 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
}, [ text, noteId ]);
+ const source = useCallback((query: string) => getNoteSuggestions(query), []);
+
+ const pickSuggestion = useCallback((suggestion: Suggestion) => {
+ setValue(suggestion.noteTitle ?? "");
+ setNotePath(suggestion.notePath ?? "");
+ onChange?.(suggestion);
+ if (noteIdChanged && suggestion.notePath) {
+ noteIdChanged(lastSegment(suggestion.notePath));
+ }
+ }, [ onChange, noteIdChanged ]);
+
+ const autocomplete = useAutocomplete({
+ query: value,
+ source,
+ onPick: pickSuggestion,
+ inputRef,
+ disabled: readOnly,
+ autoActivate: true,
+ textOf: suggestionText
+ });
+
const showButtons = !opts?.hideAllButtons;
const showGoToButton = showButtons && !opts?.hideGoToSelectedNoteButton;
@@ -62,13 +88,30 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
spellcheck={false}
dir="auto"
data-note-path={notePath}
+ {...autocomplete.comboboxProps}
onInput={(e) => {
const newValue = e.currentTarget.value;
setValue(newValue);
+ autocomplete.handleInput();
onTextChange?.(newValue);
}}
- onKeyDown={onKeyDown}
- onBlur={() => onBlur?.(value.trim() ? notePath.split("/").at(-1) ?? "" : "")}
+ onChange={(e) => {
+ // Emptying the field clears the selection.
+ if (e.currentTarget.value) return;
+ setNotePath("");
+ onChange?.(null);
+ // The callers tell a cleared selection by `undefined` (`noteId ?? "root"`),
+ // which the prop's type does not admit.
+ noteIdChanged?.(undefined as unknown as string);
+ }}
+ onKeyDown={(e) => {
+ autocomplete.handleKeyDown(e);
+ onKeyDown?.(e);
+ }}
+ onBlur={() => {
+ autocomplete.handleBlur();
+ onBlur?.(value.trim() ? lastSegment(notePath) : "");
+ }}
/>
{showGoToButton && (
@@ -92,6 +135,78 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
title={t("note_autocomplete.clear-text-field")}
/>
</>}
+
+ {autocomplete.isShown && inputRef.current && (
+ <Popup
+ anchor={inputRef.current}
+ placement="bottom-start"
+ capHeight={false}
+ className="algolia-autocomplete"
+ // The list spans the input, as `autocomplete.js` sized it.
+ style={{ width: `${inputRef.current.getBoundingClientRect().width}px` }}
+ escapeDismisses={false}
+ onDismiss={autocomplete.close}
+ >
+ <span
+ className="aa-dropdown-menu"
+ role="listbox"
+ // Keeps the input focused, so its blur does not close the list before the
+ // click lands on a suggestion.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ <div className="aa-dataset-0">
+ <span className="aa-suggestions">
+ {autocomplete.items.map((suggestion, index) => (
+ <div
+ key={`${suggestion.action ?? ""}:${suggestion.notePath ?? index}`}
+ id={autocomplete.itemId(index)}
+ className={clsx("aa-suggestion", index === autocomplete.activeIndex && "aa-cursor")}
+ role="option"
+ aria-selected={index === autocomplete.activeIndex}
+ onMouseEnter={() => autocomplete.setActiveIndex(index)}
+ onClick={() => autocomplete.pick(suggestion)}
+ >
+ <NoteSuggestion suggestion={suggestion} />
+ </div>
+ ))}
+ </span>
+ </div>
+ </span>
+ </Popup>
+ )}
</div>
);
}
+
+/** One row of the list, in the markup of the jQuery plugin's suggestion template. */
+function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
+ return (
+ <div className={clsx("note-suggestion", suggestion.action === "search-notes" && "search-notes-action")}>
+ <span className={clsx("icon", suggestionIcon(suggestion))} />
+ <span className="text">
+ <RawHtml className="search-result-title" html={suggestion.highlightedNotePathTitle ?? ""} />
+ {suggestion.highlightedAttributeSnippet && (
+ <RawHtml className="search-result-attributes" html={suggestion.highlightedAttributeSnippet} />
+ )}
+ </span>
+ </div>
+ );
+}
+
+function suggestionIcon(suggestion: Suggestion) {
+ switch (suggestion.action) {
+ case "search-notes": return "bx bx-search";
+ case "create-note": return "bx bx-plus";
+ case "create-child-note": return "bx bx-subdirectory-right";
+ case "external-link": return "bx bx-link-external";
+ default: return suggestion.icon ?? "bx bx-note";
+ }
+}
+
+function suggestionText(suggestion: Suggestion) {
+ return suggestion.noteTitle ?? "";
+}
+
+function lastSegment(notePath: string) {
+ return notePath.split("/").at(-1) ?? "";
+}
diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
index 49008c3128..661a252f46 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
@@ -35,22 +35,13 @@ export default function NoteAutocomplete({ inputRef: externalInputRef, text, onC
noteIdChanged(noteId);
}
};
- const changeListener = (e) => {
- if (!ref.current?.value) {
- autoCompleteListener(e, null);
- }
- };
$autoComplete
- .on("autocomplete:noteselected", autoCompleteListener)
.on("autocomplete:externallinkselected", autoCompleteListener)
- .on("autocomplete:commandselected", autoCompleteListener)
- .on("change", changeListener);
+ .on("autocomplete:commandselected", autoCompleteListener);
return () => {
$autoComplete
- .off("autocomplete:noteselected", autoCompleteListener)
.off("autocomplete:externallinkselected", autoCompleteListener)
- .off("autocomplete:commandselected", autoCompleteListener)
- .off("change", changeListener);
+ .off("autocomplete:commandselected", autoCompleteListener);
};
}
}, [opts, container?.current, onChange, noteIdChanged])