Skip to content

Build your personal knowledge base with Trilium Notes

fix(client): pick from the rows on display when lookups resolve out of order

Claude3d14a28e5ab7
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index c4b5f8916d..0b6bf5ebe8 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -52,7 +52,7 @@ interface SearchBoxProps {
onPickResult(picked: { results: SearchResult[]; index: number } | null): void;
}
-/** One row of the result list, drawn by `FormEntryAutocomplete` from what it carries. */
+/** One row of the result list, as `FormEntryAutocomplete` renders it. */
type SearchEntry = AutocompleteEntry & {
/** How far the place is from the middle of the map, in metres. */
distance?: number;
@@ -70,7 +70,7 @@ type SearchEntry = AutocompleteEntry & {
* typed rather than something found for them.
*/
| { kind: "point"; center: [number, number]; result: GeoSearchResult }
- /** Names the run of rows below it; not a choice. */
+ /** A header for the rows below it, which cannot be picked. */
| { kind: "heading" }
/** Runs the geocoder for `query`. */
| { kind: "geocode"; query: string }
@@ -101,9 +101,9 @@ interface GeocodeRun {
* Enter takes it — `autoActivate`, as the attribute pickers use it. From a field holding nothing but
* a name, that is: Enter, which runs the geocoder, and Enter again, which takes what it found.
*
- * `FormEntryAutocomplete` handles the debounce, the stale-response guard, keyboard navigation, a
- * dropdown portalled out of the map's scrolling container, and standing the list down once a row has
- * been taken — the geocoder row saying it starts something rather than settling it (`keepsListOpen`).
+ * `FormEntryAutocomplete` handles the debounce, stale responses, keyboard navigation, a dropdown
+ * portalled out of the map's scrolling container, and emptying the list after a pick. The geocoder
+ * row sets `keepsListOpen`, since picking it runs a search.
*/
export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {
const map = useContext(ParentMap);
@@ -421,7 +421,7 @@ function pointEntry(query: string): SearchEntry | null {
};
}
-/** Two lines: what the place is called, and under it the address that places it. */
+/** The place's name, with its address as the detail line. */
function placeEntry(result: GeoSearchResult): SearchEntry {
return {
kind: "place",
diff --git a/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsx b/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsx
index e56bf366c8..3ff4b0bd4d 100644
--- a/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsx
@@ -1,7 +1,3 @@
-/**
- * The dropdown whose rows are objects: what a row is drawn as, what picking it reports, and when the
- * list stands down and comes back.
- */
import { useCallback, useState } from "preact/hooks";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -9,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { renderInto } from "../../test/render";
import FormEntryAutocomplete, { type AutocompleteEntry } from "./FormEntryAutocomplete";
-/** A row that reports a pick, standing for a marker or a package. */
+/** A pickable row. */
function choice(key: string, extra: Partial<AutocompleteEntry> = {}): AutocompleteEntry {
return { key, label: key, ...extra };
}
@@ -17,10 +13,13 @@ function choice(key: string, extra: Partial<AutocompleteEntry> = {}): Autocomple
let picked: { entry: AutocompleteEntry; offered: string[] }[] = [];
/**
- * Renders the field over a fixed set of rows, and reports what the query was asked for so a test can
- * tell a lookup that ran from one that was never made.
+ * Renders the field over `entries` and returns `asked`, the queries `entries` was called with, so
+ * a test can tell whether a lookup ran.
*/
-function renderField(entries: AutocompleteEntry[], { minQueryLength = 1, openOnEnter = false } = {}) {
+function renderField(
+ entries: AutocompleteEntry[] | ((query: string) => Promise<AutocompleteEntry[]>),
+ { minQueryLength = 1, openOnEnter = false } = {}
+) {
picked = [];
const asked: string[] = [];
@@ -32,8 +31,13 @@ function renderField(entries: AutocompleteEntry[], { minQueryLength = 1, openOnE
className="entries"
currentValue={value}
onChange={setValue}
- entries={useCallback(async (query: string) => { asked.push(query); return entries; }, [])}
- onPick={(entry, offered) => picked.push({ entry, offered: offered.map((row) => row.key) })}
+ entries={useCallback(async (query: string) => {
+ asked.push(query);
+ return typeof entries === "function" ? entries(query) : entries;
+ }, [])}
+ onPick={(entry, offered) => {
+ picked.push({ entry, offered: offered.map((row) => row.key) });
+ }}
minQueryLength={minQueryLength}
openOnEnter={openOnEnter}
openOnFocus
@@ -59,7 +63,7 @@ function field() {
async function type(text: string) {
const input = field();
- // Two acts: the field has to re-render as open before the effect that schedules the lookup runs.
+ // Two acts: the field re-renders as open before the effect that schedules the lookup runs.
await act(async () => {
input.value = text;
input.dispatchEvent(new Event("input", { bubbles: true }));
@@ -94,7 +98,7 @@ afterEach(() => {
});
describe("FormEntryAutocomplete", () => {
- it("draws a row from what it carries, and names a heading without offering it", async () => {
+ it("renders a row's fields, and a heading row", async () => {
renderField([
{ key: "heading", label: "Nearby", heading: true },
choice("a", { label: "Corfu", icon: "bx bx-map", detail: "Greece", trailing: "2 km" })
@@ -131,7 +135,7 @@ describe("FormEntryAutocomplete", () => {
expect(picked).toEqual([ { entry: { key: "b", label: "b" }, offered: [ "a", "b" ] } ]);
});
- it("stands the list down once a row is taken, and puts it back when the query moves on", async () => {
+ it("empties the list after a pick and lists rows again when the query changes", async () => {
renderField([ choice("a") ]);
await type("c");
@@ -142,7 +146,7 @@ describe("FormEntryAutocomplete", () => {
expect(rows()).toHaveLength(1);
});
- it("leaves the list up for a row that starts something rather than settling it", async () => {
+ it("keeps the list open after picking a keepsListOpen row", async () => {
renderField([ choice("search", { keepsListOpen: true }) ]);
await type("c");
@@ -152,7 +156,7 @@ describe("FormEntryAutocomplete", () => {
expect(rows()).toHaveLength(1);
});
- it("takes no pick from a row that only reports", async () => {
+ it("ignores a pick of an inert row", async () => {
renderField([ choice("status", { inert: true }) ]);
await type("c");
@@ -162,7 +166,7 @@ describe("FormEntryAutocomplete", () => {
expect(rows()[0].querySelector(".form-autocomplete-entry-inert")).not.toBeNull();
});
- it("puts the rows back when the field is come back to, and on Enter where Enter opens the list", async () => {
+ it("lists the rows again on focus, and on Enter with openOnEnter", async () => {
renderField([ choice("a") ], { openOnEnter: true });
await type("c");
await click(0);
@@ -173,14 +177,32 @@ describe("FormEntryAutocomplete", () => {
await click(0);
expect(rows()).toEqual([]);
- // Coming back to the field is asking for what it was offering, no key being pressed.
+ // Focus alone lists the rows again.
await act(async () => { field().blur(); });
await act(async () => { field().focus(); });
await settle();
expect(rows()).toHaveLength(1);
});
- it("leaves Enter alone where the list is not opened by it", async () => {
+ it("picks from the rows on display when an older lookup resolves last", async () => {
+ const pending = new Map<string, (rows: AutocompleteEntry[]) => void>();
+ renderField((query) => new Promise((resolve) => pending.set(query, resolve)));
+
+ await type("a");
+ await type("ab");
+ await act(async () => { pending.get("ab")?.([ choice("ab-row") ]); });
+ await settle();
+ await act(async () => { pending.get("a")?.([ choice("a-row") ]); });
+ await settle();
+
+ expect(rows().map((row) => row.textContent)).toEqual([ "ab-row" ]);
+ await click(0);
+ expect(picked).toEqual([
+ { entry: { key: "ab-row", label: "ab-row" }, offered: [ "ab-row" ] }
+ ]);
+ });
+
+ it("leaves Enter to the form without openOnEnter", async () => {
renderField([ choice("a") ]);
await type("c");
await click(0);
diff --git a/apps/client/src/widgets/react/FormEntryAutocomplete.tsx b/apps/client/src/widgets/react/FormEntryAutocomplete.tsx
index a157ec3f44..836885f6f3 100644
--- a/apps/client/src/widgets/react/FormEntryAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormEntryAutocomplete.tsx
@@ -8,60 +8,64 @@ import FormAutocomplete from "./FormAutocomplete";
import Icon from "./Icon";
/**
- * One row of the dropdown. `key` identifies it, since `FormAutocomplete` items are strings and two
- * rows can read the same.
+ * One row of the dropdown. `key` identifies the row to `FormAutocomplete`, whose items are
+ * strings, since two rows can have the same label.
*/
export interface AutocompleteEntry {
key: string;
label: string;
/** A boxicons class, as `FNote.getIcon()` gives it. */
icon?: string;
- /** A second line under the label: the address that places a place, what a package says of itself. */
+ /** A second line under the label, such as a place's address. */
detail?: string;
- /** Drawn at the trailing edge of the row — how far off a place stands. */
+ /** Content at the trailing edge of the row, such as a distance. */
trailing?: ComponentChildren;
- /** Names the run of rows below it rather than offering a choice of its own. */
+ /** Marks a header for the rows below it. A header cannot be picked. */
heading?: boolean;
- /** Reports rather than offers: picking it does nothing and leaves the list as it stands. */
+ /** Marks a status row. Picking it calls nothing and leaves the list open. */
inert?: boolean;
/**
- * Leaves the list up once this row is picked, for a row that starts something rather than
- * settling it — the one that runs a search, which then replaces it with what it found.
+ * Keeps the list open after this row is picked, for a row that starts a search whose results
+ * replace it.
*/
keepsListOpen?: boolean;
- /** Added to the row's class, for the kinds a host draws differently. */
+ /** An extra class on the row, for kinds of row a host styles differently. */
className?: string;
}
type FormAutocompleteProps = Parameters<typeof FormAutocomplete>[0];
+type ReplacedProps = "source" | "onPick" | "renderItem" | "isHeading" | "keepOpenOnPick";
+
interface FormEntryAutocompleteProps<T extends AutocompleteEntry>
- extends Omit<FormAutocompleteProps, "source" | "onPick" | "renderItem" | "isHeading" | "keepOpenOnPick"> {
- /** Provides the rows for a query, already trimmed and past {@link minQueryLength}. */
+ extends Omit<FormAutocompleteProps, ReplacedProps> {
+ /** Returns the rows for a query, which is trimmed and at least {@link minQueryLength} long. */
entries(query: string): Promise<T[]>;
- /** Receives a picked row, along with everything the list was offering at the time. */
+ /** Called with the picked row and every row the list held when it was picked. */
onPick(entry: T, offered: T[]): void;
- /** Shorter queries list nothing. One by default, so an empty field offers nothing. */
+ /** The shortest query that calls `entries`. Defaults to 1, so an empty field lists nothing. */
minQueryLength?: number;
}
/**
- * A {@link FormAutocomplete} whose rows are objects rather than strings: each carries what it reads
- * as and what picking it means, and comes back whole to `onPick`.
+ * A {@link FormAutocomplete} whose rows are {@link AutocompleteEntry} objects rather than strings.
+ * `onPick` receives the whole entry.
*
- * Picking a row is taken as the end of the search and stands the list down, so that a field holding
- * what was chosen is not also covered by the list it was chosen from. The rows come back when the
- * query changes, when the field is come back to, and on Enter where `openOnEnter` asks for it — a
- * query that was right is looked at again without being retyped. A row that starts something rather
- * than settling it says so with `keepsListOpen`, and is free to replace itself with its results.
+ * Picking a row sets `dismissed`, which empties the list so it does not cover the field. A query
+ * change, a focus, or Enter when `openOnEnter` is set clears `dismissed` and lists the rows again.
+ * A row with `keepsListOpen` leaves `dismissed` unset.
*/
-export default function FormEntryAutocomplete<T extends AutocompleteEntry>({ entries, onPick, minQueryLength = 1, onChange, onFocus, onKeyDown, openOnEnter, ...restProps }: FormEntryAutocompleteProps<T>) {
- // Empties the list once a row has been taken, which is what closes the dropdown under
- // `keepOpenOnPick`. Typing again clears it.
+export default function FormEntryAutocomplete<T extends AutocompleteEntry>({
+ entries, onPick, minQueryLength = 1, onChange, onFocus, onKeyDown, openOnEnter, ...restProps
+}: FormEntryAutocompleteProps<T>) {
+ // While set, `source` returns no rows, which closes the dropdown under `keepOpenOnPick`.
const [ dismissed, setDismissed ] = useState(false);
const offered = useRef(new Map<string, T>());
+ // `FormAutocomplete` displays only the latest lookup, so only that one may set `offered`.
+ const latestLookup = useRef(0);
const source = useCallback(async (query: string) => {
+ const lookup = ++latestLookup.current;
const trimmed = query.trim();
if (dismissed || trimmed.length < minQueryLength) {
offered.current = new Map();
@@ -69,7 +73,9 @@ export default function FormEntryAutocomplete<T extends AutocompleteEntry>({ ent
}
const rows = await entries(trimmed);
- offered.current = new Map(rows.map((row) => [ row.key, row ]));
+ if (lookup === latestLookup.current) {
+ offered.current = new Map(rows.map((row) => [ row.key, row ]));
+ }
return rows.map((row) => row.key);
}, [ entries, dismissed, minQueryLength ]);
@@ -89,8 +95,8 @@ export default function FormEntryAutocomplete<T extends AutocompleteEntry>({ ent
}, [ onPick ]);
/**
- * Puts the rows back on offer. Only where there is nothing on offer, since the Enter that takes
- * a row arrives here too and would otherwise undo the dismissal it has just caused.
+ * Clears `dismissed` when the list is empty. The Enter that picks a row also reaches this, and
+ * must not clear the `dismissed` that the pick just set.
*/
const offerRowsAgain = useCallback(() => {
if (!offered.current.size) {
@@ -104,8 +110,7 @@ export default function FormEntryAutocomplete<T extends AutocompleteEntry>({ ent
}, [ offerRowsAgain, onFocus ]);
const handleKeyDown = useCallback((e: TargetedKeyboardEvent<HTMLInputElement>) => {
- // Enter opens the list where the host asked for it, so it brings back rows a pick sent away
- // as well. Where it does not, Enter belongs to the form around the field.
+ // Without `openOnEnter`, Enter is left to the surrounding form.
if (openOnEnter && e.key === "Enter") {
offerRowsAgain();
}
@@ -120,11 +125,16 @@ export default function FormEntryAutocomplete<T extends AutocompleteEntry>({ ent
if (entry.heading) return entry.label;
return (
- <span className={clsx("form-autocomplete-entry", entry.inert && "form-autocomplete-entry-inert", entry.className)}>
+ <span className={clsx(
+ "form-autocomplete-entry",
+ entry.inert && "form-autocomplete-entry-inert",
+ entry.className
+ )}>
<Icon icon={entry.icon} />
<span className="form-autocomplete-entry-lines">
<span className="form-autocomplete-entry-name">{entry.label}</span>
- {entry.detail && <span className="form-autocomplete-entry-detail">{entry.detail}</span>}
+ {entry.detail &&
+ <span className="form-autocomplete-entry-detail">{entry.detail}</span>}
</span>
{entry.trailing !== undefined &&
<span className="form-autocomplete-entry-trailing">{entry.trailing}</span>}