Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): pace the note searches as the jQuery plugin did

Elian Doran6e1c35cc3a4a
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
index a2e55eab6f..d6a3e57671 100644
--- a/apps/client/src/services/note_autocomplete.spec.ts
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -1,4 +1,4 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const { getActiveContextNoteId, getInboxTarget, translate, logError } = vi.hoisted(() => ({
getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),
@@ -36,7 +36,7 @@ vi.mock("./ws.js", () => ({
logError
}));
-import noteAutocomplete, { getNoteSuggestions, type Suggestion } from "./note_autocomplete.js";
+import noteAutocomplete, { createSearchScheduler, getNoteSuggestions, type Suggestion } from "./note_autocomplete.js";
import server from "./server.js";
beforeEach(() => {
@@ -158,3 +158,105 @@ describe("autocompleteSourceForCKEditor", () => {
expect(items.map((item) => (item as Suggestion).action)).toEqual([ undefined ]);
});
});
+
+describe("createSearchScheduler", () => {
+ const WINDOW_MS = 50;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ /** A search that records the term it ran for. */
+ function searchFor(ran: string[], term: string, run: () => void | Promise<void> = () => {}) {
+ return () => {
+ ran.push(term);
+ return run();
+ };
+ }
+
+ it("runs the first search of a burst at once, and the last of the rest once typing stops", async () => {
+ const schedule = createSearchScheduler();
+ const ran: string[] = [];
+
+ for (const term of [ "h", "he", "hel", "hell" ]) {
+ schedule(searchFor(ran, term));
+ }
+ // No timer is advanced: an idle input queries on the keystroke itself.
+ expect(ran).toEqual([ "h" ]);
+
+ await vi.runAllTimersAsync();
+ expect(ran).toEqual([ "h", "hell" ]);
+ });
+
+ it("holds the window open while typing continues instead of pacing searches", async () => {
+ const schedule = createSearchScheduler();
+ const ran: string[] = [];
+
+ // Keystrokes arriving closer together than the window: the one that opens the burst
+ // queries at once, and each one after it pushes the pending search back again.
+ schedule(searchFor(ran, "h"));
+ for (const term of [ "he", "hel", "hell" ]) {
+ await vi.advanceTimersByTimeAsync(30);
+ schedule(searchFor(ran, term));
+ }
+ expect(ran).toEqual([ "h" ]);
+
+ await vi.runAllTimersAsync();
+ expect(ran).toEqual([ "h", "hell" ]);
+ });
+
+ it("gives each input its own timer, so one cannot cancel another's pending search", async () => {
+ const first = createSearchScheduler();
+ const second = createSearchScheduler();
+ const ran: string[] = [];
+
+ // The leading-edge search of each burst, so both hold a debounced one afterwards.
+ first(searchFor(ran, "a1"));
+ second(searchFor(ran, "b1"));
+ first(searchFor(ran, "a2"));
+ second(searchFor(ran, "b2"));
+ await vi.runAllTimersAsync();
+
+ expect(ran).toEqual(expect.arrayContaining([ "a2", "b2" ]));
+ });
+
+ it("keeps one search in flight, so a slow one cannot make the rest queue behind it", async () => {
+ const schedule = createSearchScheduler();
+ const ran: string[] = [];
+ let finishFirst = () => {};
+
+ schedule(searchFor(ran, "h", () => new Promise<void>((resolve) => { finishFirst = resolve; })));
+ // Each keystroke opens its own burst, so without single-flight every one of them would
+ // start while the first search is still running.
+ for (const term of [ "he", "hel", "hell", "hello" ]) {
+ await vi.advanceTimersByTimeAsync(WINDOW_MS + 10);
+ schedule(searchFor(ran, term));
+ }
+ expect(ran).toEqual([ "h" ]);
+
+ finishFirst();
+ await vi.runAllTimersAsync();
+ // Only the newest term is searched for; the ones typed past are dropped, not queued.
+ expect(ran).toEqual([ "h", "hello" ]);
+ });
+
+ it("reports a failed search and keeps accepting the next one", async () => {
+ const schedule = createSearchScheduler();
+ const ran: string[] = [];
+
+ schedule(searchFor(ran, "h", async () => { throw new Error("boom"); }));
+ await vi.runAllTimersAsync();
+ // The scheduler awaits the search, so a rejection has to be reported here rather than
+ // left to surface as an unhandled one.
+ expect(logError).toHaveBeenCalledWith(expect.stringContaining("boom"));
+
+ await vi.advanceTimersByTimeAsync(WINDOW_MS + 10);
+ schedule(searchFor(ran, "hi"));
+ // The failure released the slot, rather than wedging the input for good.
+ expect(ran).toEqual([ "h", "hi" ]);
+ });
+});
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 946c755723..c13d0793de 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -8,6 +8,11 @@ import server from "./server.js";
import { escapeHtml } from "./utils.js";
import { logError } from "./ws.js";
+// Short on purpose: a search costs tens of milliseconds, so this exists to merge keystrokes that
+// arrive faster than a person reads a result, not to wait out a slow server. Anything longer is
+// felt on every keystroke typed at a normal pace.
+const SEARCH_DEBOUNCE_MS = 50;
+
/**
* One row of the dropdown: a note from `GET /api/autocomplete`, or a row added by the client.
* A client row sets `action` to its kind and fills in only the fields that kind uses.
@@ -88,6 +93,69 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes = fa
];
}
+/**
+ * Paces one input's searches: the first keystroke after a pause queries immediately, a burst typed
+ * faster than {@link SEARCH_DEBOUNCE_MS} collapses into one search that runs once it stops, and at
+ * most one search is ever outstanding.
+ *
+ * The single-flight part is what keeps a slow search from compounding. The server answers
+ * autocomplete requests one at a time, so firing a second while the first is still running makes
+ * every later keystroke wait out the whole queue ahead of it. Holding the newest term back until
+ * the outstanding search settles paces requests at whatever the server can actually serve, without
+ * the client having to know how slow that is.
+ *
+ * Each input creates its own, so a keystroke in one cannot cancel or delay what another is waiting
+ * on.
+ */
+export function createSearchScheduler() {
+ type Search = () => void | Promise<void>;
+
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
+ let lastCallAt = 0;
+ let running = false;
+ let queued: Search | undefined;
+
+ function start(runSearch: Search) {
+ // Only the newest term is worth searching for, so a search waiting here replaces the one
+ // before it instead of queueing behind it.
+ if (running) {
+ queued = runSearch;
+ return;
+ }
+
+ running = true;
+ void Promise.resolve(runSearch())
+ .catch((e) => logError(`Autocomplete search failed: ${e}`))
+ .finally(() => {
+ running = false;
+ const next = queued;
+ queued = undefined;
+ if (next) {
+ start(next);
+ }
+ });
+ }
+
+ return (runSearch: Search) => {
+ // A newer keystroke supersedes whatever the previous one left waiting, be that a pending
+ // timer or a search held back by the one in flight.
+ clearTimeout(timeoutId);
+ queued = undefined;
+
+ // Measured from the previous keystroke rather than the previous search. Measuring from the
+ // search paces requests at a fixed rate instead of ending the window when typing pauses.
+ const now = Date.now();
+ const startsBurst = now - lastCallAt >= SEARCH_DEBOUNCE_MS;
+ lastCallAt = now;
+
+ if (startsBurst) {
+ start(runSearch);
+ } else {
+ timeoutId = setTimeout(() => start(runSearch), SEARCH_DEBOUNCE_MS);
+ }
+ };
+}
+
async function getInboxTarget() {
try {
return await dateNoteService.getInboxTarget();
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.ts
index beaf2e3072..7934f94522 100644
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts
@@ -260,9 +260,6 @@ describe("autocompleteSource (via dataset)", () => {
});
});
-// Mirrors SEARCH_DEBOUNCE_MS in note_autocomplete.ts, which is internal.
-const DEBOUNCE_MS = 50;
-
describe("source debounce", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -277,104 +274,6 @@ describe("source debounce", () => {
vi.useRealTimers();
});
- it("runs the first search of a burst without waiting", () => {
- const { dataset } = initAndGetSource();
- dataset.source("hi", vi.fn());
- // No timer is advanced: an idle input queries on the keystroke itself.
- expect(server.get).toHaveBeenCalledTimes(1);
- });
-
- it("coalesces the rest of a burst into one search for the final term", async () => {
- const { dataset } = initAndGetSource();
- for (const term of ["h", "he", "hel", "hell"]) {
- dataset.source(term, vi.fn());
- }
- expect(server.get).toHaveBeenCalledTimes(1);
-
- await vi.runAllTimersAsync();
- expect(server.get).toHaveBeenCalledTimes(2);
- expect(server.get).toHaveBeenLastCalledWith(expect.stringContaining("query=hell"));
- });
-
- it("holds the window open while typing continues instead of pacing searches", async () => {
- const { dataset } = initAndGetSource();
- // Keystrokes arriving closer together than the window: the one that opens the burst
- // queries at once, and each one after it pushes the pending search back again.
- dataset.source("h", vi.fn());
- for (const term of ["he", "hel", "hell"]) {
- await vi.advanceTimersByTimeAsync(30);
- dataset.source(term, vi.fn());
- }
- expect(server.get).toHaveBeenCalledTimes(1);
-
- await vi.runAllTimersAsync();
- expect(server.get).toHaveBeenCalledTimes(2);
- expect(server.get).toHaveBeenLastCalledWith(expect.stringContaining("query=hell"));
- });
-
- it("gives each input its own timer, so one cannot cancel another's pending search", async () => {
- const first = initAndGetSource();
- const second = initAndGetSource();
- // The leading-edge search of each burst, so both inputs hold a debounced one afterwards.
- first.dataset.source("a1", vi.fn());
- second.dataset.source("b1", vi.fn());
- // Typing in one input must not drop the search the other is waiting on.
- first.dataset.source("a2", vi.fn());
- second.dataset.source("b2", vi.fn());
- await vi.runAllTimersAsync();
-
- const queries = vi.mocked(server.get).mock.calls.map(([url]) => url);
- expect(queries.some((url) => url.includes("query=a2"))).toBe(true);
- expect(queries.some((url) => url.includes("query=b2"))).toBe(true);
- });
-
- it("keeps one search in flight, so a slow one cannot make the rest queue behind it", async () => {
- const pending: Array<() => void> = [];
- server.get = vi.fn(
- () => new Promise<any[]>((resolve) => pending.push(() => resolve([])))
- ) as typeof server.get;
-
- const { dataset } = initAndGetSource();
- dataset.source("h", vi.fn());
- expect(server.get).toHaveBeenCalledTimes(1);
-
- // Each keystroke opens its own burst, so without single-flight every one of them would
- // reach the server while the first search is still running.
- for (const term of ["he", "hel", "hell", "hello"]) {
- await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 10);
- dataset.source(term, vi.fn());
- }
- expect(server.get).toHaveBeenCalledTimes(1);
-
- pending[0]();
- await vi.runAllTimersAsync();
-
- // Only the newest term is searched for; the ones typed past are dropped, not queued.
- expect(server.get).toHaveBeenCalledTimes(2);
- expect(server.get).toHaveBeenLastCalledWith(expect.stringContaining("query=hello"));
- });
-
- it("reports a failed search and keeps accepting the next one", async () => {
- server.get = vi.fn(async () => {
- throw new Error("boom");
- }) as typeof server.get;
-
- const { dataset } = initAndGetSource();
- dataset.source("h", vi.fn());
- await vi.runAllTimersAsync();
-
- // The scheduler awaits the search, so a rejection has to be reported here rather than
- // left to surface as an unhandled one.
- expect(logError).toHaveBeenCalledWith(expect.stringContaining("boom"));
-
- server.get = vi.fn(async () => []) as typeof server.get;
- await vi.advanceTimersByTimeAsync(DEBOUNCE_MS + 10);
- dataset.source("hi", vi.fn());
-
- // The failure released the slot, rather than wedging the input for good.
- expect(server.get).toHaveBeenCalledTimes(1);
- });
-
it("debounces and skips the search while composing input", async () => {
const { $el, dataset } = initAndGetSource();
// simulate IME composition active
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
index c192032b19..1786fca640 100644
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ b/apps/client/src/services/note_autocomplete_bak.ts
@@ -3,84 +3,15 @@ import commandRegistry from "./command_registry.js";
import dateNoteService from "./date_notes.js";
import froca from "./froca.js";
import { t } from "./i18n.js";
-import { getNoteSuggestions, type Options, type Suggestion } from "./note_autocomplete.js";
+import { createSearchScheduler, getNoteSuggestions, type Options, type Suggestion } from "./note_autocomplete.js";
import noteCreateService from "./note_create.js";
import { escapeHtml } from "./utils.js";
-import { logError } from "./ws.js";
// this key needs to have this value, so it's hit by the tooltip
const SELECTED_NOTE_PATH_KEY = "data-note-path";
const SELECTED_EXTERNAL_LINK_KEY = "data-external-link";
-// Short on purpose: a search costs tens of milliseconds, so this exists to merge keystrokes that
-// arrive faster than a person reads a result, not to wait out a slow server. Anything longer is
-// felt on every keystroke typed at a normal pace.
-const SEARCH_DEBOUNCE_MS = 50;
-
-/**
- * Paces one input's searches: the first keystroke after a pause queries immediately, a burst typed
- * faster than {@link SEARCH_DEBOUNCE_MS} collapses into one search that runs once it stops, and at
- * most one search is ever outstanding.
- *
- * The single-flight part is what keeps a slow search from compounding. The server answers
- * autocomplete requests one at a time, so firing a second while the first is still running makes
- * every later keystroke wait out the whole queue ahead of it. Holding the newest term back until
- * the outstanding search settles paces requests at whatever the server can actually serve, without
- * the client having to know how slow that is.
- *
- * Each input holds its own timer and its own in-flight search, so a keystroke in one cannot cancel
- * or delay what another is waiting on.
- */
-function createSearchScheduler() {
- type Search = () => void | Promise<void>;
-
- let timeoutId: ReturnType<typeof setTimeout> | undefined;
- let lastCallAt = 0;
- let running = false;
- let queued: Search | undefined;
-
- function start(runSearch: Search) {
- // Only the newest term is worth searching for, so a search waiting here replaces the one
- // before it instead of queueing behind it.
- if (running) {
- queued = runSearch;
- return;
- }
-
- running = true;
- void Promise.resolve(runSearch())
- .catch((e) => logError(`Autocomplete search failed: ${e}`))
- .finally(() => {
- running = false;
- const next = queued;
- queued = undefined;
- if (next) {
- start(next);
- }
- });
- }
-
- return (runSearch: Search) => {
- // A newer keystroke supersedes whatever the previous one left waiting, be that a pending
- // timer or a search held back by the one in flight.
- clearTimeout(timeoutId);
- queued = undefined;
-
- // Measured from the previous keystroke rather than the previous search. Measuring from the
- // search paces requests at a fixed rate instead of ending the window when typing pauses.
- const now = Date.now();
- const startsBurst = now - lastCallAt >= SEARCH_DEBOUNCE_MS;
- lastCallAt = now;
-
- if (startsBurst) {
- start(runSearch);
- } else {
- timeoutId = setTimeout(() => start(runSearch), SEARCH_DEBOUNCE_MS);
- }
- };
-}
-
async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void, options: Options = {}) {
// Check if we're in command mode
if (options.isCommandPalette && term.startsWith(">")) {
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 4fd5b0519f..65bcac6917 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -237,6 +237,11 @@ interface UseAutocompleteOptions<T> {
isHeading?(item: T): boolean;
/** The text of an entry, which `autoActivate` matches against the query. Defaults to `String(item)`. */
textOf?(item: T): string;
+ /**
+ * Runs each lookup in place of the default debounce of {@link DEBOUNCE_MS}, for a source that
+ * needs its own pacing. It must be stable across renders.
+ */
+ schedule?(lookUp: () => Promise<void>): void;
}
/**
@@ -245,10 +250,10 @@ interface UseAutocompleteOptions<T> {
* 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.
+ * field's events to the `handle*` functions. Entries are fetched while the list is open, debounced
+ * or paced by `schedule`, 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>) {
+export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled, openOnFocus, openOnEnter, keepOpenOnPick, autoActivate, isHeading, textOf = String, schedule }: UseAutocompleteOptions<T>) {
const [ isOpen, setIsOpen ] = useState(false);
const [ items, setItems ] = useState<T[]>([]);
const [ activeIndex, setActiveIndex ] = useState(-1);
@@ -281,7 +286,10 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
}
const queryId = ++latestQuery.current;
- const timeout = setTimeout(async () => {
+ const lookUp = async () => {
+ // A scheduler can run a lookup that a newer query (or a close) has since superseded.
+ if (latestQuery.current !== queryId) return;
+
const suggestions = await source(query);
// A newer query (or a close) happened while awaiting.
@@ -289,10 +297,16 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
setItems(suggestions);
setActiveIndex(autoActivate ? bestMatchIndex(suggestions, query, isHeading, textOf) : -1);
}
- }, DEBOUNCE_MS);
+ };
+
+ if (schedule) {
+ schedule(lookUp);
+ return;
+ }
+ const timeout = setTimeout(lookUp, DEBOUNCE_MS);
return () => clearTimeout(timeout);
- }, [ isOpen, query, source, autoActivate, isHeading, textOf ]);
+ }, [ isOpen, query, source, autoActivate, isHeading, textOf, schedule ]);
// 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.
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index b15d491a98..a9e37d2928 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -5,14 +5,16 @@ const { getNoteSuggestions } = vi.hoisted(() => ({
getNoteSuggestions: vi.fn<(term: string) => Promise<Suggestion[]>>(async () => [])
}));
-vi.mock("../../services/note_autocomplete", () => ({ getNoteSuggestions }));
+vi.mock("../../services/note_autocomplete", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../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 () => {
@@ -217,6 +219,22 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(rows()).toHaveLength(0);
});
+ it("searches on the first keystroke, and paces the rest of a burst", async () => {
+ const input = await mount();
+
+ for (const term of [ "a", "al", "alp" ]) {
+ await act(async () => {
+ input.value = term;
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ });
+ }
+ // No timer has run, so the debounce of `FormAutocomplete` would not have searched yet.
+ expect(getNoteSuggestions.mock.calls).toEqual([ [ "a" ] ]);
+
+ await settle();
+ expect(getNoteSuggestions.mock.calls).toEqual([ [ "a" ], [ "alp" ] ]);
+ });
+
it("spans the whole field, the buttons included", async () => {
const input = await mount();
const group = input.closest(".input-group");
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 5446f4a23c..74fb7bfacc 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -3,11 +3,11 @@ import "./NoteAutocomplete.css";
import clsx from "clsx";
import type { RefObject } from "preact";
import type { CSSProperties } from "preact/compat";
-import { useCallback, useEffect, useRef, useState } from "preact/hooks";
+import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
-import { getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
+import { createSearchScheduler, getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
import { useAutocomplete } from "./FormAutocomplete";
import { useSyncedRef } from "./hooks";
import Popup from "./Popup";
@@ -50,6 +50,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}, [ text, noteId ]);
const source = useCallback((query: string) => getNoteSuggestions(query), []);
+ const schedule = useMemo(() => createSearchScheduler(), []);
const pickSuggestion = useCallback((suggestion: Suggestion) => {
setValue(suggestion.noteTitle ?? "");
@@ -67,7 +68,8 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
inputRef,
disabled: readOnly,
autoActivate: true,
- textOf: suggestionText
+ textOf: suggestionText,
+ schedule
});
const showButtons = !opts?.hideAllButtons;