Skip to content

Build your personal knowledge base with Trilium Notes

feat(geomap): group items by close or far

Elian Doran9927e877b4b3
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 234428c9ec..0f90076536 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2959,7 +2959,10 @@
"search-online": "Search online for \"{{- query}}\"",
"searching-online": "Searching online…",
"no-places-found": "No places found",
- "search-failed": "Couldn't search for places"
+ "search-failed": "Couldn't search for places",
+ "results-nearby": "Nearby",
+ "results-far": "Far away",
+ "add-place-as-marker": "Add as marker"
},
"embedded_note": {
"open-note": "Open note",
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.css b/apps/client/src/widgets/collections/geomap/SearchBox.css
index c00990a6bf..7722301e43 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.css
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.css
@@ -101,6 +101,12 @@ body.mobile .geo-map-container .geo-search-toolbar {
opacity: 0.85;
}
+/* A heading names the rows under it and reads as the dropdown's own furniture rather than as one of
+ the entries, so it keeps none of the room a row's mark and distance are given. */
+.form-autocomplete-dropdown .geo-search-heading {
+ display: block;
+}
+
/* 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;
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
index cd2ee70c81..7941f3e01e 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.spec.tsx
@@ -113,17 +113,28 @@ async function type(container: HTMLElement, text: string) {
await settle();
}
-/** The dropdown is portalled to the body, so look for it there rather than in the container. */
+/**
+ * Every row of the list, headings included. The dropdown is portalled to the body, so it is looked
+ * for there rather than in the container.
+ */
+function rows() {
+ return [ ...document.querySelectorAll<HTMLElement>(".form-autocomplete-dropdown li") ];
+}
+
+/** The rows that can be taken, which is every row but the headings. */
function entries() {
- return [ ...document.querySelectorAll<HTMLElement>(".form-autocomplete-dropdown .form-autocomplete-item") ];
+ return rows().filter((row) => row.classList.contains("form-autocomplete-item"));
+}
+
+/** 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
+ ?? row.textContent;
}
-/** What each row is called: the first line of a place, and the whole of any other row. */
function labels() {
- return entries().map((entry) =>
- entry.querySelector(".geo-search-entry-name")?.textContent
- ?? entry.querySelector(".geo-search-entry-lines")?.textContent
- ?? entry.textContent);
+ return rows().map(nameOf);
}
/** Presses a key in the field, as the reader reaching for the keyboard rather than the pointer. */
@@ -134,6 +145,16 @@ async function press(container: HTMLElement, key: string) {
await settle();
}
+/** Picks the row that reads as the given name, the list standing in distance order rather than a
+ * settled one. */
+async function pickNamed(name: string) {
+ const row = rows().find((candidate) => nameOf(candidate) === name);
+ if (!row) throw new Error(`the list offers no "${name}": ${labels().join(", ")}`);
+
+ await act(async () => { row.click(); });
+ await settle();
+}
+
/** Picks a row and lets whatever it started settle. */
async function pick(index: number) {
await act(async () => { entries()[index].click(); });
@@ -184,8 +205,8 @@ describe("geo map SearchBox", () => {
// answered with the one at hand.
viewport: [ [ VIEWPORT.west, VIEWPORT.south ], [ VIEWPORT.east, VIEWPORT.north ] ]
});
- // The row is replaced by what it found, the markers still standing above it.
- expect(labels()).toEqual([ "Tokyo trip", "Tokyo" ]);
+ // The row is replaced by what it found, standing among the map's own notes.
+ expect([ ...labels() ].sort()).toEqual([ "Tokyo", "Tokyo trip" ]);
});
it("flies to a marker, and closes the list rather than leaving it open over the map", async () => {
@@ -271,8 +292,8 @@ describe("geo map SearchBox", () => {
const container = renderSearchBox(fakeMap(), mapNotes());
await type(container, "tokyo");
- await pick(1);
- await pick(1);
+ await pickNamed("geo-map.search-online(tokyo)");
+ await pickNamed("Tokyo");
const pin = () => container.querySelector<HTMLElement>(".place-marker");
expect(pin()?.dataset.center).toBe(`${TOKYO.lng},${TOKYO.lat}`);
@@ -393,6 +414,43 @@ describe("geo map SearchBox", () => {
expect(field(container).value).toBe("Tokyo, Japan");
});
+ it("puts what is at hand under one heading and what is far off under another, nearest first", async () => {
+ // Half of Corfu away, a good way up the coast, and another country entirely.
+ mockGeocoder([
+ { id: "near", label: "Jumbo, Corfu", name: "Jumbo", lat: CENTRE.lat + 0.09, lng: CENTRE.lng },
+ { id: "far", label: "Jumbo, Ohio", name: "Jumbo", lat: 40.4, lng: -82.9 }
+ ]);
+ const container = renderSearchBox(fakeMap(), [
+ buildNote({ title: "Jumbo receipt", "#geolocation": `${CENTRE.lat + 0.04},${CENTRE.lng}` })
+ ]);
+
+ await type(container, "jumbo");
+ await pickNamed("geo-map.search-online(jumbo)");
+
+ expect(labels()).toEqual([
+ "geo-map.results-nearby",
+ // The note is nearer than the shop, and the shop nearer than the one across the ocean.
+ "Jumbo receipt",
+ "Jumbo",
+ "geo-map.results-far",
+ "Jumbo"
+ ]);
+ // A heading names the rows below it rather than offering anything, so it is not among the
+ // rows that can be taken.
+ expect(entries().map(nameOf)).toEqual([ "Jumbo receipt", "Jumbo", "Jumbo" ]);
+ });
+
+ it("leaves the headings off where every result is on one side of the line", async () => {
+ mockGeocoder([ TOKYO ]);
+ const container = renderSearchBox(fakeMap(), []);
+
+ await type(container, "tokyo");
+ await pickNamed("geo-map.search-online(tokyo)");
+
+ // Nothing at hand to tell it apart from: one name over one run of rows says nothing.
+ expect(labels()).toEqual([ "Tokyo" ]);
+ });
+
it("takes the pin off the map once the field is emptied", async () => {
mockGeocoder([ TOKYO ]);
const container = renderSearchBox(fakeMap(), []);
diff --git a/apps/client/src/widgets/collections/geomap/SearchBox.tsx b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
index 184426a0ac..996cdec452 100644
--- a/apps/client/src/widgets/collections/geomap/SearchBox.tsx
+++ b/apps/client/src/widgets/collections/geomap/SearchBox.tsx
@@ -12,7 +12,7 @@ import { formatDistance } from "../../../utils/units";
import FormAutocomplete from "../../react/FormAutocomplete";
import Icon from "../../react/Icon";
import OverlayToolbar from "../../react/OverlayToolbar";
-import { DEFAULT_GEOCODING_PROVIDER_NAME, type GeoBounds, GEOCODING_PROVIDERS, type GeoSearchResult } from "./geocoding";
+import { DEFAULT_GEOCODING_PROVIDER_NAME, type GeoBounds, GEOCODING_PROVIDERS, type GeoSearchResult, SEARCH_RADIUS_M } from "./geocoding";
import { ParentMap } from "./map";
import { LOCATION_ATTRIBUTE, parseLocation } from "./Markers";
import PlaceMarker from "./PlaceMarker";
@@ -65,8 +65,8 @@ interface SearchBoxProps {
type SearchEntry = {
key: string;
label: string;
- /** A boxicons class, as `FNote.getIcon()` gives it. */
- icon: string;
+ /** A boxicons class, as `FNote.getIcon()` gives it. Headings have none. */
+ icon?: string;
/** How far the place is from the middle of the map, in metres. */
distance?: number;
} & (
@@ -82,6 +82,8 @@ type SearchEntry = {
bounds?: GeoSearchResult["bounds"];
outline?: GeoSearchResult["outline"];
}
+ /** Names the run of rows below it; not a choice (see `isHeading` on FormAutocomplete). */
+ | { kind: "heading" }
/** Runs the geocoder for `query`. */
| { kind: "geocode"; query: string }
/** Reports on a geocoder run; picking it does nothing. */
@@ -147,8 +149,10 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
// 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 entries = [ ...matchMarkers(notes, trimmed), ...geocodeEntries(geocodeRun, trimmed) ]
+ const { places, notice } = geocodeEntries(geocodeRun, trimmed);
+ const found = [ ...matchMarkers(notes, trimmed), ...places ]
.map((entry) => withDistance(entry, origin));
+ const entries = [ ...byDistance(found), ...(notice ? [ notice ] : []) ];
entriesByKey.current = new Map(entries.map((entry) => [ entry.key, entry ]));
return entries.map((entry) => entry.key);
}, [ notes, geocodeRun, dismissed, map ]);
@@ -214,10 +218,17 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
}
}, [ map, runGeocoder ]);
+ 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;
+ }
+
// A place reads over two lines: what it is called, and the address that places it. Every
// other row is one thing said once.
const address = entry.kind === "place" ? addressOf(entry.label, entry.name) : null;
@@ -259,6 +270,7 @@ export default function SearchBox({ notes, isDarkTheme }: SearchBoxProps) {
onPick={pickEntry}
source={source}
renderItem={renderEntry}
+ isHeading={isHeading}
dropdownMinWidth={RESULT_LIST_WIDTH}
autoActivate
keepOpenOnPick
@@ -336,31 +348,69 @@ function matchMarkers(notes: FNote[], query: string): SearchEntry[] {
}
/**
- * What the list offers below the markers: the results of a run answering this query, or the row that
- * starts one. Typing never reaches the provider — picking that row is the only thing that does.
+ * What the geocoder has to offer for this query: the places a run answering it found, and whatever
+ * has to be said about the run — the row that starts one, or a word on how the last one went.
+ *
+ * The two are separated because they belong in different parts of the list: places are sorted in
+ * among the map's own notes, and a notice stands at the foot whatever the distances say.
*/
-function geocodeEntries(run: GeocodeRun | undefined, query: string): SearchEntry[] {
+function geocodeEntries(run: GeocodeRun | undefined, query: string): {
+ places: SearchEntry[];
+ notice: SearchEntry | null;
+} {
if (run?.query !== query) {
- return [ {
- kind: "geocode",
- key: "geocode",
- label: t("geo-map.search-online", { query }),
- icon: "bx bx-search-alt",
- query
- } ];
+ return {
+ places: [],
+ notice: {
+ kind: "geocode",
+ key: "geocode",
+ label: t("geo-map.search-online", { query }),
+ icon: "bx bx-search-alt",
+ query
+ }
+ };
}
if (run.status === "loading") {
- return [ infoEntry(t("geo-map.searching-online"), "bx bx-loader-alt") ];
+ return { places: [], notice: infoEntry(t("geo-map.searching-online"), "bx bx-loader-alt") };
}
if (run.status === "failed") {
- return [ infoEntry(t("geo-map.search-failed"), "bx bx-error-circle") ];
+ return { places: [], notice: infoEntry(t("geo-map.search-failed"), "bx bx-error-circle") };
}
if (!run.results.length) {
- return [ infoEntry(t("geo-map.no-places-found"), "bx bx-info-circle") ];
+ return { places: [], notice: infoEntry(t("geo-map.no-places-found"), "bx bx-info-circle") };
}
- return run.results;
+ return { places: run.results, notice: null };
+}
+
+/**
+ * The places found, nearest first, under headings that say which are at hand and which are not — a
+ * shop down the road and one on another continent are both answers to the same name, and the list
+ * used to run them together.
+ *
+ * Headings only where there is something on both sides of {@link SEARCH_RADIUS_M}: one name over one
+ * run of rows distinguishes it from nothing.
+ */
+function byDistance(entries: SearchEntry[]): SearchEntry[] {
+ const sorted = [ ...entries ].sort((a, b) => (a.distance ?? Infinity) - (b.distance ?? Infinity));
+ const atHand = sorted.filter((entry) => (entry.distance ?? Infinity) <= SEARCH_RADIUS_M);
+ const further = sorted.slice(atHand.length);
+
+ if (!atHand.length || !further.length) {
+ return sorted;
+ }
+
+ return [
+ headingEntry("nearby", t("geo-map.results-nearby")),
+ ...atHand,
+ headingEntry("far", t("geo-map.results-far")),
+ ...further
+ ];
+}
+
+function headingEntry(key: string, label: string): SearchEntry {
+ return { kind: "heading", key: `heading:${key}`, label };
}
function placeEntry(result: GeoSearchResult): SearchEntry {
diff --git a/apps/client/src/widgets/collections/geomap/geocoding.ts b/apps/client/src/widgets/collections/geomap/geocoding.ts
index 36c1b4df95..1d3296302a 100644
--- a/apps/client/src/widgets/collections/geomap/geocoding.ts
+++ b/apps/client/src/widgets/collections/geomap/geocoding.ts
@@ -1,5 +1,15 @@
import { nominatim } from "./nominatim";
+/**
+ * How much ground counts as here: what a search treats as the area around the reader, and what a
+ * result is called nearby for standing within.
+ *
+ * A map zoomed into a neighbourhood shows a few hundred metres across, and a search restricted to
+ * exactly that answers nothing for a shop three streets away. What the reader means by searching from
+ * where they are standing is the town they are looking at, not the block.
+ */
+export const SEARCH_RADIUS_M = 25_000;
+
/** A rectangle of ground, as `[[west, south], [east, north]]`. */
export type GeoBounds = [[number, number], [number, number]];
diff --git a/apps/client/src/widgets/collections/geomap/nominatim.ts b/apps/client/src/widgets/collections/geomap/nominatim.ts
index 2250e3ae75..2d82064ee2 100644
--- a/apps/client/src/widgets/collections/geomap/nominatim.ts
+++ b/apps/client/src/widgets/collections/geomap/nominatim.ts
@@ -1,5 +1,5 @@
import { getCurrentLanguage } from "../../../services/i18n";
-import type { GeoBounds, GeocodingProvider, GeoSearchOptions, GeoSearchResult } from "./geocoding";
+import { type GeoBounds, type GeocodingProvider, type GeoSearchOptions, type GeoSearchResult, SEARCH_RADIUS_M } from "./geocoding";
const NOMINATIM_URL = "https://nominatim.openstreetmap.org/search";
const NOMINATIM_LOOKUP_URL = "https://nominatim.openstreetmap.org/lookup";
@@ -16,14 +16,6 @@ const OSM_TYPE_PREFIX: Record<string, string> = { node: "N", way: "W", relation:
/** The kinds of OSM object that can enclose ground. A node is a single point and has no boundary. */
const OSM_TYPES_WITH_A_BOUNDARY = new Set([ "way", "relation" ]);
-/**
- * The least ground a search treats as here, as a half-span in metres.
- *
- * A map zoomed into a neighbourhood shows a few hundred metres across, and a search restricted to
- * exactly that answers nothing for a shop three streets away. What the reader means by searching from
- * where they are standing is the town they are looking at, not the block.
- */
-const MIN_SEARCH_RADIUS_M = 25_000;
/** Metres to a degree of latitude, the same the world over. A degree of longitude is this shortened
* by the cosine of the latitude. */
@@ -192,7 +184,7 @@ function toBounds(boundingbox: string[] | undefined): GeoSearchResult["bounds"]
* first. Sent without `bounded` on the wider pass, so a place is ranked up for being in view rather
* than a place out of view being refused.
*
- * Grown to at least {@link MIN_SEARCH_RADIUS_M} about its middle, since a view of one neighbourhood
+ * Grown to at least {@link SEARCH_RADIUS_M} about its middle, since a view of one neighbourhood
* restricts a search to that neighbourhood and answers nothing for the next street over.
*
* A view running the other way round has been panned across the antimeridian, which no pair of
@@ -210,7 +202,7 @@ function toViewbox(viewport: GeoBounds | undefined) {
const middleLat = (south + north) / 2;
const middleLng = (west + east) / 2;
- const latitudePad = MIN_SEARCH_RADIUS_M / METRES_PER_DEGREE;
+ const latitudePad = SEARCH_RADIUS_M / METRES_PER_DEGREE;
// A degree of longitude shortens towards the poles, where it is short enough that padding by one
// would reach around the world; the cosine is floored to keep the padding finite.
const longitudePad = latitudePad / Math.max(Math.cos(middleLat * Math.PI / 180), 0.01);
diff --git a/apps/client/src/widgets/react/FormAutocomplete.css b/apps/client/src/widgets/react/FormAutocomplete.css
index 0da26bafa6..44029a3a41 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.css
+++ b/apps/client/src/widgets/react/FormAutocomplete.css
@@ -44,3 +44,18 @@
color: var(--active-item-text-color);
background-color: var(--active-item-background-color);
}
+
+/* A heading over the entries below it, not one of them (see `isHeading`). */
+.form-autocomplete-dropdown .form-autocomplete-heading {
+ padding: 8px 8px 2px;
+ font-size: 0.8em;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.04em;
+ opacity: 0.55;
+ cursor: default;
+}
+
+.form-autocomplete-dropdown .form-autocomplete-heading:first-child {
+ padding-top: 2px;
+}
diff --git a/apps/client/src/widgets/react/FormAutocomplete.spec.tsx b/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
index 6c56f32edc..f451cd91af 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.spec.tsx
@@ -5,7 +5,7 @@
*/
import { afterEach, describe, expect, it } from "vitest";
-import { computeDropdownPosition } from "./FormAutocomplete";
+import { computeDropdownPosition, stepOver } from "./FormAutocomplete";
/** The room the placement keeps between the list and the edge of the screen. */
const MARGIN = 8;
@@ -31,6 +31,26 @@ afterEach(() => {
}
});
+describe("stepping through a list with headings in it", () => {
+ const items = [ "Nearby", "a", "b", "Far away", "c" ];
+ const isHeading = (item: string) => item === "Nearby" || item === "Far away";
+
+ it("steps over the headings, in either direction, wrapping at the ends", () => {
+ // Opening the list lands on the first entry that can be taken, not on the heading over it.
+ expect(stepOver(items, -1, 1, isHeading)).toBe(1);
+ expect(stepOver(items, 1, 1, isHeading)).toBe(2);
+ // Past the last of one group is the first of the next, the heading between them stepped over.
+ expect(stepOver(items, 2, 1, isHeading)).toBe(4);
+ // And round the end, back to the top.
+ expect(stepOver(items, 4, 1, isHeading)).toBe(1);
+ expect(stepOver(items, 1, -1, isHeading)).toBe(4);
+ });
+
+ it("highlights nothing in a list that is headings alone", () => {
+ expect(stepOver([ "Nearby" ], -1, 1, isHeading)).toBe(-1);
+ });
+});
+
describe("computeDropdownPosition", () => {
it("hangs the list under the field, at the field's own width", () => {
setViewport(1200, 800);
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index f5c92e5547..0f6fc84869 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -57,6 +57,11 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
* the whole field instead of only the stretch of it left over for typing.
*/
leading?: ComponentChildren;
+ /**
+ * Marks an entry as a heading over the ones below it rather than a choice of its own: it takes no
+ * click, is stepped over on the way through the list, and is never what Enter takes.
+ */
+ isHeading?(item: string): boolean;
/**
* The least the list is drawn at, in pixels, for a field too narrow for what its entries have to
* say — a search box in the corner of a map offering whole addresses. The field's own width is
@@ -80,7 +85,7 @@ interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
* The dropdown is portalled to the body and positioned over everything else, so it is not clipped
* by scrolling ancestors. Selecting a suggestion reports it through `onChange`, exactly like typing.
*/
-export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, onPick, keepOpenOnPick, renderItem, leading, autoActivate, dropdownMinWidth, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {
+export default function FormAutocomplete({ currentValue, onChange, source, openOnFocus, onPick, keepOpenOnPick, renderItem, leading, autoActivate, isHeading, dropdownMinWidth, inputRef, onBlur, onKeyDown, ...restProps }: FormAutocompleteProps) {
const ownInputRef = useRef<HTMLInputElement>(null);
const inputEl = inputRef ?? ownInputRef;
const fieldRef = useRef<HTMLDivElement>(null);
@@ -120,12 +125,12 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
// A newer query (or a close) happened while awaiting.
if (latestQuery.current === queryId) {
setItems(suggestions);
- setActiveIndex(autoActivate ? bestMatchIndex(suggestions, currentValue) : -1);
+ setActiveIndex(autoActivate ? bestMatchIndex(suggestions, currentValue, isHeading) : -1);
}
}, DEBOUNCE_MS);
return () => clearTimeout(timeout);
- }, [ isOpen, currentValue, source, autoActivate ]);
+ }, [ isOpen, currentValue, source, autoActivate, isHeading ]);
// 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.
@@ -161,6 +166,10 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
}, [ isOpen, items.length, inputEl, dropdownMinWidth ]);
function selectItem(item: string) {
+ if (isHeading?.(item)) {
+ return;
+ }
+
(onPick ?? onChange)(item);
if (keepOpenOnPick) {
// Nothing is highlighted until the refreshed entries arrive, so Enter cannot take twice
@@ -183,7 +192,7 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
setIsOpen(true);
} else {
const delta = e.key === "ArrowDown" ? 1 : -1;
- setActiveIndex((index) => (index + delta + items.length) % items.length);
+ setActiveIndex((index) => stepOver(items, index, delta, isHeading));
}
break;
@@ -257,17 +266,21 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
onMouseDown={(e) => e.preventDefault()}
>
{items.map((item, index) => (
- <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>
+ 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)}
@@ -276,17 +289,38 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
}
/**
- * Which entry a list opens on: the one the field's text names, or the first, so that a field whose
- * text stands for a choice already made opens on it and one being typed into opens on its best
- * candidate. Matched the way the sources filter — ignoring case and surrounding space.
+ * Which entry a list opens on: the one the field's text names, or the first that can be taken, so
+ * that a field whose text stands for a choice already made opens on it and one being typed into
+ * opens on its best candidate. Matched the way the sources filter — ignoring case and surrounding
+ * space.
*/
-function bestMatchIndex(items: string[], text: string) {
- if (!items.length) {
- return -1;
- }
+function bestMatchIndex(items: string[], text: string, isHeading?: (item: string) => boolean) {
+ const canBeTaken = (item: string) => !isHeading?.(item);
const trimmed = text.trim().toLowerCase();
- const exact = items.findIndex((item) => item.toLowerCase() === trimmed);
- return exact >= 0 ? exact : 0;
+ const exact = items.findIndex((item) => canBeTaken(item) && item.toLowerCase() === trimmed);
+
+ return exact >= 0 ? exact : items.findIndex(canBeTaken);
+}
+
+/**
+ * The next entry that can be taken, in the direction asked for, wrapping at either end and stepping
+ * over the headings in between. Nothing to step to — a list of headings alone — leaves nothing
+ * highlighted.
+ *
+ * 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) {
+ let index = from;
+
+ for (let step = 0; step < items.length; step++) {
+ index = (index + delta + items.length) % items.length;
+ if (!isHeading?.(items[index])) {
+ return index;
+ }
+ }
+
+ return -1;
}
/**