Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
refactor(client): extract the geo map's entry dropdown as FormEntryAutocomplete
Elian Doran4ef660df4f64
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.cssindex 29a4bca3e6..74fda6f22d 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.css+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css@@ -62,64 +62,9 @@visibility: visible;}-/* The dropdown is portalled to the body, so these are not scoped under .geo-map-container. */-.form-autocomplete-dropdown .geo-search-entry {- display: flex;- /* The icon sits on the first line of a row that runs to two. */- align-items: flex-start;- gap: 6px;- overflow: hidden;-}--.form-autocomplete-dropdown .geo-search-entry .tn-icon {- flex-shrink: 0;- opacity: 0.7;- line-height: 1.4;-}--/* Overrides the single-line ellipsis in FormAutocomplete.css, so an address can wrap. */-.form-autocomplete-dropdown .form-autocomplete-item:has(.geo-search-entry) {- white-space: normal;- padding-block: 6px;-}--.form-autocomplete-dropdown .geo-search-entry-lines {- display: flex;- flex-direction: column;- min-width: 0;- flex: 1;-}--.form-autocomplete-dropdown .geo-search-entry-distance {- flex-shrink: 0;- align-self: center;- padding-inline-start: 8px;- font-size: 0.85em;- font-variant-numeric: tabular-nums;- opacity: 0.6;-}--.form-autocomplete-dropdown .geo-search-entry-address {- font-size: 0.85em;- opacity: 0.7;- /* Two lines at most: a Nominatim address can run to five. */- display: -webkit-box;- -webkit-line-clamp: 2;- line-clamp: 2;- -webkit-box-orient: vertical;- overflow: hidden;-}--/* The geocoder row and its reports are set apart from the places they produce. */-.form-autocomplete-dropdown .geo-search-entry-geocode,-.form-autocomplete-dropdown .geo-search-entry-info {+/* The dropdown is portalled to the body, so this is not scoped under .geo-map-container. The rest of+ a row's shape is the shared entry's (see FormEntryAutocomplete.css). */+.form-autocomplete-dropdown .geo-search-entry-geocode {font-style: italic;opacity: 0.85;}--/* A report is not a choice, so it neither highlights nor takes a pointer. */-.form-autocomplete-dropdown .form-autocomplete-item:has(.geo-search-entry-info) {- cursor: default;- background: none;- color: inherit;-}diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsxindex 04a4a0992f..0270904c1a 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx@@ -141,8 +141,8 @@ function entries() {/** What a row is called: the first line of a place, and the whole of any other row. */function nameOf(row: HTMLElement) {- return row.querySelector(".geo-search-entry-name")?.textContent- ?? row.querySelector(".geo-search-entry-lines")?.textContent+ return row.querySelector(".form-autocomplete-entry-name")?.textContent+ ?? row.querySelector(".form-autocomplete-entry-lines")?.textContent?? row.textContent;}@@ -431,7 +431,7 @@ describe("geo map SearchBox", () => {const detailOf = (name: string) => rows().find((row) => nameOf(row) === name)- ?.querySelector(".geo-search-entry-address")?.textContent;+ ?.querySelector(".form-autocomplete-entry-detail")?.textContent;await type(container, "tokyo");// What is about to leave the map, said where it is read rather than in a setting somewhere.@@ -456,8 +456,8 @@ describe("geo map SearchBox", () => {await pick(0);const lines = entries().map((entry) => [- entry.querySelector(".geo-search-entry-name")?.textContent,- entry.querySelector(".geo-search-entry-address")?.textContent+ entry.querySelector(".form-autocomplete-entry-name")?.textContent,+ entry.querySelector(".form-autocomplete-entry-detail")?.textContent]);expect(lines).toEqual([[ "Tokyo", "Ōta, Japan" ],@@ -472,7 +472,7 @@ describe("geo map SearchBox", () => {await type(container, "tokyo");const distances = () => entries().map((entry) =>- entry.querySelector(".geo-search-entry-distance")?.textContent ?? null);+ entry.querySelector(".form-autocomplete-entry-trailing")?.textContent ?? null);// The note is on the other side of the world from the view, which is in Corfu.const [ tokyoTrip, geocoderRow ] = distances();diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsxindex 45121e6eb4..c4b5f8916d 100644--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx@@ -2,7 +2,6 @@ import "./SearchBox.css";import clsx from "clsx";import type { Map as MapLibreGLMap } from "maplibre-gl";-import type { TargetedKeyboardEvent } from "preact";import { useCallback, useContext, useRef, useState } from "preact/hooks";import type FNote from "../../../entities/fnote";@@ -11,7 +10,7 @@ import { logError } from "../../../services/ws";import { getMeasurementSystem } from "../../../utils/formatters";import { formatDistance } from "../../../utils/units";import { filterTokens, matchesFilter } from "../../react/filter";-import FormAutocomplete from "../../react/FormAutocomplete";+import FormEntryAutocomplete, { type AutocompleteEntry } from "../../react/FormEntryAutocomplete";import Icon from "../../react/Icon";import OverlayToolbar, { OverlayToolbarButton } from "../../react/OverlayToolbar";import { type Bounds, parseCoordinates, pointPlace } from "./coordinates";@@ -53,19 +52,10 @@ interface SearchBoxProps {onPickResult(picked: { results: SearchResult[]; index: number } | null): void;}-/**- * One row of the result list. `key` identifies it, since `FormAutocomplete` items are strings and two- * rows can read the same.- */-type SearchEntry = {- key: string;- label: string;- /** A boxicons class, as `FNote.getIcon()` gives it. Headings have none. */- icon?: string;+/** One row of the result list, drawn by `FormEntryAutocomplete` from what it carries. */+type SearchEntry = AutocompleteEntry & {/** How far the place is from the middle of the map, in metres. */distance?: number;- /** A second line under the first: the address that places a place, or whose answer a row is. */- detail?: string;} & (/*** A note of the map's own. `center` is where it is measured from, absent for a GPX track, which@@ -80,7 +70,7 @@ type SearchEntry = {* typed rather than something found for them.*/| { kind: "point"; center: [number, number]; result: GeoSearchResult }- /** Names the run of rows below it; not a choice (see `isHeading` on FormAutocomplete). */+ /** Names the run of rows below it; not a choice. */| { kind: "heading" }/** Runs the geocoder for `query`. */| { kind: "geocode"; query: string }@@ -111,51 +101,38 @@ 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.*- * `FormAutocomplete` handles the debounce, the stale-response guard, keyboard navigation and a- * dropdown portalled out of the map's scrolling container. `keepOpenOnPick` keeps the list up so the- * geocoder row can replace itself with results, so closing it after a marker or place is taken is- * this component's job — see `dismissed`.+ * `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`).*/export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {const map = useContext(ParentMap);const [ query, setQuery ] = useState("");const [ geocodeRun, setGeocodeRun ] = useState<GeocodeRun>();- // Empties the list once a marker or place has been taken, which is what closes the dropdown under- // `keepOpenOnPick`. Typing again clears it.- const [ dismissed, setDismissed ] = useState(false);const inputRef = useRef<HTMLInputElement>(null);- const entriesByKey = useRef(new Map<string, SearchEntry>());// Discards a run superseded by a later one, since each reports through the same state.const latestRun = useRef(0);const provider = GEOCODING_PROVIDERS[DEFAULT_GEOCODING_PROVIDER_NAME];- const source = useCallback(async (currentQuery: string) => {- const trimmed = currentQuery.trim();- if (dismissed || trimmed.length < MIN_QUERY_LENGTH) {- entriesByKey.current = new Map();- return [];- }-+ const entries = useCallback(async (currentQuery: string) => {// Measured from the middle of what the map is showing, at the moment the list is built: two// places of the same name are told apart by which of them is at hand.const origin = map ? map.getCenter().toArray() : null;- const { places, notice } = geocodeEntries(geocodeRun, trimmed, provider.name);- const found = [ ...matchMarkers(notes, trimmed), ...places ]+ const { places, notice } = geocodeEntries(geocodeRun, currentQuery, provider.name);+ const found = [ ...matchMarkers(notes, currentQuery), ...places ].map((entry) => withDistance(entry, origin));// Above the groups rather than sorted into them: a reader who typed a point named where// they were going, and what a search turned up answers a different question.- const point = pointEntry(trimmed);- const entries = [+ const point = pointEntry(currentQuery);++ return [...(point ? [ withDistance(point, origin) ] : []),...grouped(found),...(notice ? [ notice ] : [])];- entriesByKey.current = new Map(entries.map((entry) => [ entry.key, entry ]));- return entries.map((entry) => entry.key);- }, [ notes, geocodeRun, dismissed, map, provider ]);+ }, [ notes, geocodeRun, map, provider ]);const changeQuery = useCallback((newQuery: string) => {- setDismissed(false);setQuery(newQuery);// Emptying the field is how the search is taken back off the map, pin and all.if (!newQuery.trim()) {@@ -180,25 +157,6 @@ export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {}}, [ provider, map ]);- /**- * Puts the rows back on offer, so a query that was right can be looked at again without being- * retyped: the field is come back to, or Enter is pressed on it with nothing 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.- */- const offerRowsAgain = useCallback(() => {- if (!entriesByKey.current.size) {- setDismissed(false);- }- }, []);-- const offerRowsOnEnter = useCallback((e: TargetedKeyboardEvent<HTMLInputElement>) => {- if (e.key === "Enter") {- offerRowsAgain();- }- }, [ offerRowsAgain ]);-/** Empties the field, which is also what takes a searched place off the map (see `changeQuery`). */const clearSearch = useCallback(() => {changeQuery("");@@ -206,78 +164,39 @@ export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {inputRef.current?.focus();}, [ changeQuery ]);- const pickEntry = useCallback((key: string) => {- const entry = entriesByKey.current.get(key);- if (!entry || !map) return;+ const pickEntry = useCallback((entry: SearchEntry, offered: SearchEntry[]) => {+ if (!map) return;if (entry.kind === "geocode") {runGeocoder(entry.query);} else if (entry.kind === "marker" || entry.kind === "place" || entry.kind === "point") {- setDismissed(true);-// The whole of what was offered, so the map can step through the rest of it once the// list has stood down (see ResultNavigator).- const results = walkableResults(entriesByKey.current);+ const results = walkableResults(offered);const index = results.findIndex((result) => keyOf(result) === entry.key);onPickResult({ results, index });frameResult(map, results[index]);}}, [ map, runGeocoder, onPickResult ]);- const isHeading = useCallback(- (key: string) => entriesByKey.current.get(key)?.kind === "heading", []);-- const renderEntry = useCallback((key: string) => {- const entry = entriesByKey.current.get(key);- if (!entry) return key;-- if (entry.kind === "heading") {- return entry.label;- }-- // Two lines: what the row is, and under it what places it — the address of a place, and the- // geocoder's name on the rows that are its to answer for.- const [ name, detail ] = entry.kind === "place"- ? [ entry.result.name, describePlace(entry.result) ]- : [ entry.label, entry.detail ];-- return (- <span className={`geo-search-entry geo-search-entry-${entry.kind}`}>- <Icon icon={entry.icon} />- <span className="geo-search-entry-lines">- <span className="geo-search-entry-name">{name}</span>- {detail && <span className="geo-search-entry-address">{detail}</span>}- </span>- {entry.distance !== undefined &&- <span className="geo-search-entry-distance">- {formatDistance(entry.distance, getMeasurementSystem())}- </span>}- </span>- );- }, []);-// The map failed to initialize, e.g. WebGL is unavailable (see map.tsx).if (!map) return null;return (<OverlayToolbar className="geo-search-toolbar" titlePosition="bottom"><Icon icon="bx bx-search" className="geo-search-icon" />- <FormAutocomplete+ <FormEntryAutocompleteclassName="geo-search-input"inputRef={inputRef}currentValue={query}onChange={changeQuery}onPick={pickEntry}- source={source}- renderItem={renderEntry}- isHeading={isHeading}+ entries={entries}+ minQueryLength={MIN_QUERY_LENGTH}dropdownMinWidth={RESULT_LIST_WIDTH}autoActivateopenOnFocusopenOnEnter- keepOpenOnPick- onFocus={offerRowsAgain}- onKeyDown={offerRowsOnEnter}placeholder={t("geo-map.search-placeholder")}aria-label={t("geo-map.search")}/>@@ -298,10 +217,10 @@ export default function SearchBox({ notes, onPickResult }: SearchBoxProps) {* The rows that stand somewhere on the map, in the order they were offered — the headings and the* geocoder's own rows being neither results nor anywhere.*/-function walkableResults(entries: Map<string, SearchEntry>): SearchResult[] {+function walkableResults(entries: SearchEntry[]): SearchResult[] {const results: SearchResult[] = [];- for (const entry of entries.values()) {+ for (const entry of entries) {if (entry.kind === "marker") {results.push({ kind: "note", noteId: entry.noteId, center: entry.center, bounds: entry.bounds });} else if (entry.kind === "place" || entry.kind === "point") {@@ -327,7 +246,8 @@ function withDistance(entry: SearchEntry, origin: [number, number] | null): Searreturn entry;}- return { ...entry, distance: metresBetween(origin, center) };+ const distance = metresBetween(origin, center);+ return { ...entry, distance, trailing: formatDistance(distance, getMeasurementSystem()) };}/** The great-circle metres between two `[lng, lat]` points. */@@ -424,6 +344,8 @@ function geocodeEntries(run: GeocodeRun | undefined, query: string, provider: stlabel: t("geo-map.search-online", { query }),detail: provider,icon: "bx bx-search-alt",+ className: "geo-search-entry-geocode",+ keepsListOpen: true,query}};@@ -474,7 +396,7 @@ function grouped(entries: SearchEntry[]): SearchEntry[] {}function headingEntry(key: string, label: string): SearchEntry {- return { kind: "heading", key: `heading:${key}`, label };+ return { kind: "heading", key: `heading:${key}`, label, heading: true };}/**@@ -499,11 +421,13 @@ function pointEntry(query: string): SearchEntry | null {};}+/** Two lines: what the place is called, and under it the address that places it. */function placeEntry(result: GeoSearchResult): SearchEntry {return {kind: "place",key: `place:${result.id}`,- label: result.label,+ label: result.name,+ detail: describePlace(result),icon: result.icon ?? DEFAULT_PLACE_ICON,center: [ result.lng, result.lat ],result@@ -512,5 +436,5 @@ function placeEntry(result: GeoSearchResult): SearchEntry {/** A row that reports on the geocoder rather than offering a place. */function infoEntry(label: string, icon: string, detail: string): SearchEntry {- return { kind: "info", key: STATUS_KEY, label, icon, detail };+ return { kind: "info", key: STATUS_KEY, label, icon, detail, inert: true };}diff --git a/apps/client/src/widgets/react/FormEntryAutocomplete.css b/apps/client/src/widgets/react/FormEntryAutocomplete.cssnew file mode 100644index 0000000000..c600370fff--- /dev/null+++ b/apps/client/src/widgets/react/FormEntryAutocomplete.css@@ -0,0 +1,59 @@+/* The dropdown is portalled to the body, so these are not scoped to the field. */+.form-autocomplete-dropdown .form-autocomplete-entry {+ display: flex;+ /* The icon sits on the first line of a row that runs to two. */+ align-items: flex-start;+ gap: 6px;+ overflow: hidden;+}++.form-autocomplete-dropdown .form-autocomplete-entry .tn-icon {+ flex-shrink: 0;+ opacity: 0.7;+ line-height: 1.4;+}++/* Overrides the single-line ellipsis in FormAutocomplete.css, so a detail line can wrap. */+.form-autocomplete-dropdown .form-autocomplete-item:has(.form-autocomplete-entry) {+ white-space: normal;+ padding-block: 6px;+}++.form-autocomplete-dropdown .form-autocomplete-entry-lines {+ display: flex;+ flex-direction: column;+ min-width: 0;+ flex: 1;+}++.form-autocomplete-dropdown .form-autocomplete-entry-detail {+ font-size: 0.85em;+ opacity: 0.7;+ /* Two lines at most: a Nominatim address can run to five. */+ display: -webkit-box;+ -webkit-line-clamp: 2;+ line-clamp: 2;+ -webkit-box-orient: vertical;+ overflow: hidden;+}++.form-autocomplete-dropdown .form-autocomplete-entry-trailing {+ flex-shrink: 0;+ align-self: center;+ padding-inline-start: 8px;+ font-size: 0.85em;+ font-variant-numeric: tabular-nums;+ opacity: 0.6;+}++.form-autocomplete-dropdown .form-autocomplete-entry-inert {+ font-style: italic;+ opacity: 0.85;+}++/* A row that reports is not a choice, so it neither highlights nor takes a pointer. */+.form-autocomplete-dropdown .form-autocomplete-item:has(.form-autocomplete-entry-inert) {+ cursor: default;+ background: none;+ color: inherit;+}diff --git a/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsx b/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsxnew file mode 100644index 0000000000..e56bf366c8--- /dev/null+++ b/apps/client/src/widgets/react/FormEntryAutocomplete.spec.tsx@@ -0,0 +1,192 @@+/**+ * 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";++import { renderInto } from "../../test/render";+import FormEntryAutocomplete, { type AutocompleteEntry } from "./FormEntryAutocomplete";++/** A row that reports a pick, standing for a marker or a package. */+function choice(key: string, extra: Partial<AutocompleteEntry> = {}): AutocompleteEntry {+ return { key, label: key, ...extra };+}++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.+ */+function renderField(entries: AutocompleteEntry[], { minQueryLength = 1, openOnEnter = false } = {}) {+ picked = [];+ const asked: string[] = [];++ function Host() {+ const [ value, setValue ] = useState("");++ return (+ <FormEntryAutocomplete+ 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) })}+ minQueryLength={minQueryLength}+ openOnEnter={openOnEnter}+ openOnFocus+ />+ );+ }++ act(() => { renderInto(<Host />); });++ return { asked };+}++/** Lets the debounced lookup run. */+async function settle() {+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+}++function field() {+ const input = document.querySelector<HTMLInputElement>("input.entries");+ if (!input) throw new Error("the field was not rendered");+ return input;+}++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.+ await act(async () => {+ input.value = text;+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await settle();+}++async function press(key: string) {+ await act(async () => {+ field().dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true }));+ });+ await settle();+}++function rows() {+ return [ ...document.querySelectorAll<HTMLElement>(".form-autocomplete-dropdown li") ];+}++async function click(index: number) {+ await act(async () => { rows()[index].click(); });+ await settle();+}++beforeEach(() => {+ vi.useFakeTimers();+ document.body.innerHTML = "";+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe("FormEntryAutocomplete", () => {+ it("draws a row from what it carries, and names a heading without offering it", async () => {+ renderField([+ { key: "heading", label: "Nearby", heading: true },+ choice("a", { label: "Corfu", icon: "bx bx-map", detail: "Greece", trailing: "2 km" })+ ]);++ await type("corfu");++ const [ heading, entry ] = rows();+ expect(heading.className).toContain("form-autocomplete-heading");+ expect(heading.textContent).toBe("Nearby");+ expect(entry.querySelector(".form-autocomplete-entry-name")?.textContent).toBe("Corfu");+ expect(entry.querySelector(".form-autocomplete-entry-detail")?.textContent).toBe("Greece");+ expect(entry.querySelector(".form-autocomplete-entry-trailing")?.textContent).toBe("2 km");+ expect(entry.querySelector(".bx-map")).not.toBeNull();+ });++ it("asks for rows only once the query is long enough", async () => {+ const { asked } = renderField([ choice("a") ], { minQueryLength: 3 });++ await type("co");+ expect(rows()).toEqual([]);+ expect(asked).toEqual([]);++ await type("corfu");+ expect(asked).toEqual([ "corfu" ]);+ });++ it("reports a picked row whole, along with everything the list was offering", async () => {+ renderField([ choice("a"), choice("b") ]);++ await type("c");+ await click(1);++ 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 () => {+ renderField([ choice("a") ]);+ await type("c");++ await click(0);+ expect(rows()).toEqual([]);++ await type("co");+ expect(rows()).toHaveLength(1);+ });++ it("leaves the list up for a row that starts something rather than settling it", async () => {+ renderField([ choice("search", { keepsListOpen: true }) ]);+ await type("c");++ await click(0);++ expect(picked).toHaveLength(1);+ expect(rows()).toHaveLength(1);+ });++ it("takes no pick from a row that only reports", async () => {+ renderField([ choice("status", { inert: true }) ]);+ await type("c");++ await click(0);++ expect(picked).toEqual([]);+ 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 () => {+ renderField([ choice("a") ], { openOnEnter: true });+ await type("c");+ await click(0);++ await press("Enter");+ expect(rows()).toHaveLength(1);++ await click(0);+ expect(rows()).toEqual([]);++ // Coming back to the field is asking for what it was offering, no key being pressed.+ 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 () => {+ renderField([ choice("a") ]);+ await type("c");+ await click(0);++ await press("Enter");++ expect(rows()).toEqual([]);+ });+});diff --git a/apps/client/src/widgets/react/FormEntryAutocomplete.tsx b/apps/client/src/widgets/react/FormEntryAutocomplete.tsxnew file mode 100644index 0000000000..a157ec3f44--- /dev/null+++ b/apps/client/src/widgets/react/FormEntryAutocomplete.tsx@@ -0,0 +1,149 @@+import "./FormEntryAutocomplete.css";++import clsx from "clsx";+import type { ComponentChildren, TargetedFocusEvent, TargetedKeyboardEvent } from "preact";+import { useCallback, useRef, useState } from "preact/hooks";++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.+ */+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. */+ detail?: string;+ /** Drawn at the trailing edge of the row — how far off a place stands. */+ trailing?: ComponentChildren;+ /** Names the run of rows below it rather than offering a choice of its own. */+ heading?: boolean;+ /** Reports rather than offers: picking it does nothing and leaves the list as it stands. */+ 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.+ */+ keepsListOpen?: boolean;+ /** Added to the row's class, for the kinds a host draws differently. */+ className?: string;+}++type FormAutocompleteProps = Parameters<typeof FormAutocomplete>[0];++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}. */+ entries(query: string): Promise<T[]>;+ /** Receives a picked row, along with everything the list was offering at the time. */+ onPick(entry: T, offered: T[]): void;+ /** Shorter queries list nothing. One by default, so an empty field offers 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`.+ *+ * 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.+ */+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.+ const [ dismissed, setDismissed ] = useState(false);+ const offered = useRef(new Map<string, T>());++ const source = useCallback(async (query: string) => {+ const trimmed = query.trim();+ if (dismissed || trimmed.length < minQueryLength) {+ offered.current = new Map();+ return [];+ }++ const rows = await entries(trimmed);+ offered.current = new Map(rows.map((row) => [ row.key, row ]));+ return rows.map((row) => row.key);+ }, [ entries, dismissed, minQueryLength ]);++ const changeQuery = useCallback((newValue: string) => {+ setDismissed(false);+ onChange(newValue);+ }, [ onChange ]);++ const pick = useCallback((key: string) => {+ const entry = offered.current.get(key);+ if (!entry || entry.inert) return;++ if (!entry.keepsListOpen) {+ setDismissed(true);+ }+ onPick(entry, [ ...offered.current.values() ]);+ }, [ 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.+ */+ const offerRowsAgain = useCallback(() => {+ if (!offered.current.size) {+ setDismissed(false);+ }+ }, []);++ const handleFocus = useCallback((e: TargetedFocusEvent<HTMLInputElement>) => {+ offerRowsAgain();+ onFocus?.(e);+ }, [ 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.+ if (openOnEnter && e.key === "Enter") {+ offerRowsAgain();+ }+ onKeyDown?.(e);+ }, [ openOnEnter, offerRowsAgain, onKeyDown ]);++ const isHeading = useCallback((key: string) => !!offered.current.get(key)?.heading, []);++ const renderItem = useCallback((key: string) => {+ const entry = offered.current.get(key);+ if (!entry) return key;+ if (entry.heading) return entry.label;++ return (+ <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>}+ </span>+ {entry.trailing !== undefined &&+ <span className="form-autocomplete-entry-trailing">{entry.trailing}</span>}+ </span>+ );+ }, []);++ return (+ <FormAutocomplete+ {...restProps}+ onChange={changeQuery}+ onFocus={handleFocus}+ onKeyDown={handleKeyDown}+ openOnEnter={openOnEnter}+ source={source}+ onPick={pick}+ renderItem={renderItem}+ isHeading={isHeading}+ keepOpenOnPick+ />+ );+}