@findlane/browser 0.31.0 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +53 -3
- package/dist/index.js +1 -0
- package/dist/map.d.ts +7 -0
- package/dist/map.js +34 -0
- package/dist/react/cache.d.ts +4 -0
- package/dist/react/cache.js +12 -2
- package/dist/react/components.d.ts +14 -3
- package/dist/react/components.js +24 -7
- package/dist/react/dialog.d.ts +1 -1
- package/dist/react/dialog.js +2 -2
- package/dist/react/index.d.ts +4 -3
- package/dist/react/index.js +3 -2
- package/dist/react/search-provider.d.ts +17 -4
- package/dist/react/search-provider.js +49 -8
- package/dist/react/state.d.ts +9 -0
- package/dist/react/state.js +14 -3
- package/dist/react/store.d.ts +3 -1
- package/dist/react/store.js +14 -3
- package/dist/react/styles.css +20 -0
- package/dist/react/use-autocomplete.d.ts +24 -3
- package/dist/react/use-autocomplete.js +49 -5
- package/dist/react/use-map-search.d.ts +41 -0
- package/dist/react/use-map-search.js +74 -0
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { imageWidth, imageWidths } from "./images.js";
|
|
2
2
|
export { placeholderCss, placeholderUrl, revealCss } from "./placeholder.js";
|
|
3
|
+
export { tilesFor } from "./map.js";
|
|
3
4
|
export type SearchRequest = {
|
|
4
5
|
q?: string;
|
|
5
6
|
/** A sort ID from the index settings, "relevance", or "distance" (with `near`). */
|
|
@@ -19,7 +20,7 @@ export type SearchRequest = {
|
|
|
19
20
|
/** Number fields (up to eight) whose smallest and largest values across the matches to return in
|
|
20
21
|
* `facetStats`, such as a price slider's bounds. Each field's own filter is left out. */
|
|
21
22
|
facetStats?: string[];
|
|
22
|
-
/** Hits per request: 1–50 (default 20). */
|
|
23
|
+
/** Hits per request: 1–50 (default 20). 0 with `clusters`, for an answer with no hits. */
|
|
23
24
|
limit?: number;
|
|
24
25
|
/** Up to 5,000. */
|
|
25
26
|
offset?: number;
|
|
@@ -48,6 +49,24 @@ export type SearchRequest = {
|
|
|
48
49
|
/** Only records inside a box, in degrees, such as a map's visible area. West greater than east crosses the
|
|
49
50
|
* antimeridian. */
|
|
50
51
|
within?: GeoBox;
|
|
52
|
+
/** Only records on a map tile, instead of `near` or `within`. Fixed tiles repeat where a map's box doesn't, so they're answered
|
|
53
|
+
* from the cache, and a record is on exactly one tile of a zoom, so tiles add up. `tilesFor` says which a view needs. The cache
|
|
54
|
+
* may answer with a tile up to 5 minutes old while it refreshes. Needs the index's location field. */
|
|
55
|
+
tile?: MapTile;
|
|
56
|
+
/** Answers with `bounds`, the box around every match rather than only the page, for a map to fly to. */
|
|
57
|
+
bounds?: boolean;
|
|
58
|
+
/** With `tile`: answers with `clusters`, its matches grouped by cell, up to 16 cells a side. `stats` takes up to three number
|
|
59
|
+
* fields, as `facetStats` does. */
|
|
60
|
+
clusters?: {
|
|
61
|
+
cells: MapCells;
|
|
62
|
+
stats?: string[];
|
|
63
|
+
};
|
|
64
|
+
/** With `tile`: the page is each cell's best records (`perCell`, 1 by default, up to 10), by the search's ranking, rather than the
|
|
65
|
+
* top of one list, so hits spread over the map. It takes no `offset`, and `distinct` stays off. */
|
|
66
|
+
spread?: {
|
|
67
|
+
cells: MapCells;
|
|
68
|
+
perCell?: number;
|
|
69
|
+
};
|
|
51
70
|
/** With the index's related results on: false asks for none (0.17.0). */
|
|
52
71
|
related?: boolean;
|
|
53
72
|
/** With the index's `distinct` setting, which shows each product once, such as one of its colours: false
|
|
@@ -68,9 +87,13 @@ export type SearchRequest = {
|
|
|
68
87
|
subindexes?: Record<string, SubindexSearch | true>;
|
|
69
88
|
/** The facet values the query names, such as a category, a brand or a zip, to offer beside the results
|
|
70
89
|
* (0.30.0): `true` for every field of the index's facet matches setting, or `{ fields }` for some of them.
|
|
71
|
-
* They come back in `facetMatches`, in the same search.
|
|
90
|
+
* They come back in `facetMatches`, in the same search. With the setting's `apply`, a match that names a value
|
|
91
|
+
* exactly filters this search (`applied`, and `rewrittenQuery` says which words were searched), so show that
|
|
92
|
+
* it did. `apply` chooses for this search instead (0.32.0): `"never"` for a dropdown, or a filter the shopper
|
|
93
|
+
* took away. */
|
|
72
94
|
facetMatches?: boolean | {
|
|
73
95
|
fields?: string[];
|
|
96
|
+
apply?: "never" | "whole" | "exact";
|
|
74
97
|
};
|
|
75
98
|
};
|
|
76
99
|
/** A subindex's own search, in a search that asks for it. */
|
|
@@ -92,6 +115,27 @@ export type GeoBox = {
|
|
|
92
115
|
east: number;
|
|
93
116
|
west: number;
|
|
94
117
|
};
|
|
118
|
+
/** A map tile, numbered as MapLibre and other web maps number them. */
|
|
119
|
+
export type MapTile = {
|
|
120
|
+
z: number;
|
|
121
|
+
x: number;
|
|
122
|
+
y: number;
|
|
123
|
+
};
|
|
124
|
+
/** Cells a side of a map tile. */
|
|
125
|
+
export type MapCells = 1 | 2 | 4 | 8 | 16;
|
|
126
|
+
/** A group of matches: how many, their average place (where a bubble sits), and the box to zoom to on a click. A box with no size
|
|
127
|
+
* means every record is at one place, such as flats in one building. */
|
|
128
|
+
export type Cluster = {
|
|
129
|
+
count: number;
|
|
130
|
+
lat: number;
|
|
131
|
+
lng: number;
|
|
132
|
+
bounds: GeoBox;
|
|
133
|
+
stats?: Record<string, {
|
|
134
|
+
min: number;
|
|
135
|
+
max: number;
|
|
136
|
+
avg: number;
|
|
137
|
+
}>;
|
|
138
|
+
};
|
|
95
139
|
/** A result. */
|
|
96
140
|
export type SearchHit<T> = {
|
|
97
141
|
id: string;
|
|
@@ -143,6 +187,11 @@ export type SearchResponse<T> = {
|
|
|
143
187
|
sort?: string;
|
|
144
188
|
/** With `near`: the point distances are from, or null when the visitor's location isn't known. */
|
|
145
189
|
near?: GeoPoint | null;
|
|
190
|
+
/** With `bounds`: the box around every match with a place on the map, or null without any. Records past about 85° north or south
|
|
191
|
+
* have none, and matches on both sides of the antimeridian get a box as wide as the map. */
|
|
192
|
+
bounds?: GeoBox | null;
|
|
193
|
+
/** With `clusters`: one for each cell with matches. */
|
|
194
|
+
clusters?: Cluster[];
|
|
146
195
|
/** With the index's `didYouMean` setting: the query with the words typo tolerance corrected, when the
|
|
147
196
|
* results matched some words only by typo ("Showing results for …"), else null. */
|
|
148
197
|
didYouMean?: DidYouMean | null;
|
|
@@ -185,7 +234,8 @@ export type SearchResponse<T> = {
|
|
|
185
234
|
* - `whole`: it took every word of the query. `typed`: where those words are in `q`, as UTF-16 offsets (end
|
|
186
235
|
* exclusive), so they can be set apart.
|
|
187
236
|
* - `link`: where the setting links it, with its values. `filter`: filters for it, to add to a search's `filters`.
|
|
188
|
-
* - `applied`: whether this search used the filter itself;
|
|
237
|
+
* - `applied`: whether this search used the filter itself (0.32.0); its words are then left out of what was
|
|
238
|
+
* searched, as `rewrittenQuery` says. */
|
|
189
239
|
export type FacetMatch = {
|
|
190
240
|
field: string;
|
|
191
241
|
values: string[];
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { defaultImageOrigin, imageHostsHeader, imageHostsOf, imageOriginHeader, imageOriginOf, optimizedImageUrl, preconnect, rememberedImages, rememberImages } from "./images.js";
|
|
2
2
|
export { imageWidth, imageWidths } from "./images.js";
|
|
3
3
|
export { placeholderCss, placeholderUrl, revealCss } from "./placeholder.js";
|
|
4
|
+
export { tilesFor } from "./map.js";
|
|
4
5
|
/** A query suggestion's text in parts: what was typed (`typed: true`) and the rest. */
|
|
5
6
|
export function suggestionParts(suggestion) {
|
|
6
7
|
const [start, end] = suggestion.typed ?? [0, 0];
|
package/dist/map.d.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { GeoBox, MapTile } from "./index.js";
|
|
2
|
+
/** The fixed tiles covering a map's view, from its bounds and zoom, for `tile` in a search. Everyone looking at the
|
|
3
|
+
* same area asks for the same tiles, so they're answered from the cache where a box almost never would be. They're
|
|
4
|
+
* one level above the map's zoom, 1024 pixels wide on screen, which makes at most six on a desktop view.
|
|
5
|
+
* A box whose west is greater than its east crosses the antimeridian, and longitudes past ±180 (a map showing copies
|
|
6
|
+
* of the world) wrap around. */
|
|
7
|
+
export declare function tilesFor(box: GeoBox, zoom: number): MapTile[];
|
package/dist/map.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** Where Web Mercator, and so every tile, stops. */
|
|
2
|
+
const edge = 85.05112878;
|
|
3
|
+
/** More than a view asks for: a box much wider than its zoom gets larger tiles instead. */
|
|
4
|
+
const mostTiles = 16;
|
|
5
|
+
const fractionDown = (lat) => {
|
|
6
|
+
const clamped = Math.max(-edge, Math.min(edge, lat));
|
|
7
|
+
return (1 - Math.log(Math.tan(Math.PI / 4 + clamped * Math.PI / 360)) / Math.PI) / 2;
|
|
8
|
+
};
|
|
9
|
+
/** The fixed tiles covering a map's view, from its bounds and zoom, for `tile` in a search. Everyone looking at the
|
|
10
|
+
* same area asks for the same tiles, so they're answered from the cache where a box almost never would be. They're
|
|
11
|
+
* one level above the map's zoom, 1024 pixels wide on screen, which makes at most six on a desktop view.
|
|
12
|
+
* A box whose west is greater than its east crosses the antimeridian, and longitudes past ±180 (a map showing copies
|
|
13
|
+
* of the world) wrap around. */
|
|
14
|
+
export function tilesFor(box, zoom) {
|
|
15
|
+
const span = box.east >= box.west ? box.east - box.west : box.east + 360 - box.west;
|
|
16
|
+
const west = (((box.west + 180) % 360) + 360) % 360 / 360;
|
|
17
|
+
for (let z = Math.max(0, Math.min(22, Math.floor(zoom) - 1));; z--) {
|
|
18
|
+
const side = 2 ** z;
|
|
19
|
+
const across = Math.floor(west * side);
|
|
20
|
+
// A tile's south and east edges are its neighbours', so a box ending on one doesn't reach the next.
|
|
21
|
+
const lastAcross = Math.max(across, Math.ceil((west + span / 360) * side) - 1);
|
|
22
|
+
const down = Math.floor(fractionDown(box.north) * side);
|
|
23
|
+
const lastDown = Math.max(down, Math.min(side - 1, Math.ceil(fractionDown(box.south) * side) - 1));
|
|
24
|
+
const columns = Math.min(lastAcross - across + 1, side);
|
|
25
|
+
const rows = lastDown - down + 1;
|
|
26
|
+
if (z > 0 && columns * rows > mostTiles)
|
|
27
|
+
continue;
|
|
28
|
+
const tiles = [];
|
|
29
|
+
for (let row = 0; row < rows; row++)
|
|
30
|
+
for (let column = 0; column < columns; column++)
|
|
31
|
+
tiles.push({ z, x: (across + column) % side, y: Math.min(down + row, side - 1) });
|
|
32
|
+
return tiles;
|
|
33
|
+
}
|
|
34
|
+
}
|
package/dist/react/cache.d.ts
CHANGED
|
@@ -9,6 +9,10 @@ export declare function recommendationsKey(objectID: string, request?: Recommend
|
|
|
9
9
|
/** Query suggestion requests that the API answers the same way share a key: the text in lowercase with
|
|
10
10
|
* single spaces, and whether a space ends it (which makes the last word whole). */
|
|
11
11
|
export declare const suggestionsKey: (q: string, limit: number) => string;
|
|
12
|
+
/** A map tile's response, if there's a recent one, and the tile's response: from memory, from the same request in flight, or a
|
|
13
|
+
* new request (useMapSearch). */
|
|
14
|
+
export declare function peekTile<T>(client: SearchBrowserClient, request: SearchRequest): SearchResponse<T> | null;
|
|
15
|
+
export declare function cachedTile<T>(client: SearchBrowserClient, request: SearchRequest, signal?: AbortSignal): Promise<SearchResponse<T>>;
|
|
12
16
|
/** A cached response, if there's a recent one. */
|
|
13
17
|
export declare function peek<T>(client: SearchBrowserClient, request: SearchRequest): SearchResponse<T> | null;
|
|
14
18
|
export declare function peekRecommendations<T>(client: SearchBrowserClient, objectID: string, request?: RecommendationsRequest): RecommendationsResponse<T> | null;
|
package/dist/react/cache.js
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
1
|
import { canonical } from "./state.js";
|
|
2
2
|
const size = 50;
|
|
3
3
|
const maxAge = 5 * 60_000;
|
|
4
|
-
const store = () => ({ responses: new WeakMap(), flights: new WeakMap() });
|
|
4
|
+
const store = (most = size) => ({ most, responses: new WeakMap(), flights: new WeakMap() });
|
|
5
5
|
const searches = store();
|
|
6
|
+
// A map's tiles, apart from searches: a few minutes of panning would push them out.
|
|
7
|
+
const tiles = store(500);
|
|
6
8
|
const recommendations = store();
|
|
7
9
|
const suggestions = store();
|
|
8
10
|
/** Requests the API answers the same way share a key, as at the edge (workers/api/src/edge.ts):
|
|
@@ -38,6 +40,14 @@ function lookup(from, client, key) {
|
|
|
38
40
|
const entry = from.responses.get(client)?.get(key);
|
|
39
41
|
return entry && Date.now() - entry.at < maxAge ? entry.response : null;
|
|
40
42
|
}
|
|
43
|
+
/** A map tile's response, if there's a recent one, and the tile's response: from memory, from the same request in flight, or a
|
|
44
|
+
* new request (useMapSearch). */
|
|
45
|
+
export function peekTile(client, request) {
|
|
46
|
+
return lookup(tiles, client, searchKey(request));
|
|
47
|
+
}
|
|
48
|
+
export function cachedTile(client, request, signal) {
|
|
49
|
+
return shared(tiles, client, searchKey(request), (stop) => client.search(request, { signal: stop }), signal);
|
|
50
|
+
}
|
|
41
51
|
/** A cached response, if there's a recent one. */
|
|
42
52
|
export function peek(client, request) {
|
|
43
53
|
return lookup(searches, client, searchKey(request));
|
|
@@ -109,6 +119,6 @@ function remember(from, client, key, response) {
|
|
|
109
119
|
cache.delete(key);
|
|
110
120
|
cache.set(key, { at: Date.now(), response });
|
|
111
121
|
// A Map keeps insertion order, so the first key is the oldest.
|
|
112
|
-
if (cache.size >
|
|
122
|
+
if (cache.size > from.most)
|
|
113
123
|
cache.delete(cache.keys().next().value);
|
|
114
124
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type MouseEvent, type ReactNode } from "react";
|
|
2
|
-
import { type Banner, type DidYouMean as Correction } from "../index.js";
|
|
2
|
+
import { type Banner, type DidYouMean as Correction, type FacetMatch } from "../index.js";
|
|
3
3
|
import { type Refinement } from "./search-provider.js";
|
|
4
4
|
import type { Hit } from "./state.js";
|
|
5
5
|
import { useAutocomplete, type AutocompleteOptions } from "./use-autocomplete.js";
|
|
@@ -20,6 +20,8 @@ export type SearchBoxProps<T> = AutocompleteOptions<T> & {
|
|
|
20
20
|
renderHit?: (hit: Hit<T>) => ReactNode;
|
|
21
21
|
/** A subindex result's content, by the subindex's name; DefaultHit by default (0.22.0). */
|
|
22
22
|
renderSubindexHit?: (subindex: string, hit: Hit<Record<string, unknown>>) => ReactNode;
|
|
23
|
+
/** A facet match's content; its name and count by default (0.32.0). */
|
|
24
|
+
renderFacetMatch?: (match: FacetMatch) => ReactNode;
|
|
23
25
|
/** Shown when nothing matches (default "No results for “…”"). */
|
|
24
26
|
empty?: (query: string) => ReactNode;
|
|
25
27
|
/** The link to the results page (default "See all N results"). */
|
|
@@ -43,12 +45,12 @@ export declare const resultsHref: (action: string, query: string) => string;
|
|
|
43
45
|
* suggested searches, then the results, "no results", or an error; then a link to the results page.
|
|
44
46
|
* Each kind is a section of one list, which the arrow keys move through. Shared by SearchBox and
|
|
45
47
|
* SearchDialog. */
|
|
46
|
-
export declare function Suggestions<T>({ box, label, action, renderHit, renderSubindexHit, empty, seeAll, labels }: Pick<SearchBoxProps<T>, "action" | "renderHit" | "renderSubindexHit" | "empty" | "seeAll" | "labels"> & {
|
|
48
|
+
export declare function Suggestions<T>({ box, label, action, renderHit, renderSubindexHit, renderFacetMatch, empty, seeAll, labels }: Pick<SearchBoxProps<T>, "action" | "renderHit" | "renderSubindexHit" | "renderFacetMatch" | "empty" | "seeAll" | "labels"> & {
|
|
47
49
|
box: ReturnType<typeof useAutocomplete<T>>;
|
|
48
50
|
label: string;
|
|
49
51
|
}): import("react").JSX.Element;
|
|
50
52
|
/** A search box that suggests results as visitors type. Works on its own with a `publicId`. */
|
|
51
|
-
export declare function SearchBox<T = Record<string, unknown>>({ placeholder, label, action, renderHit, renderSubindexHit, empty, seeAll, labels, className, autoFocus, ...options }: SearchBoxProps<T>): import("react").JSX.Element;
|
|
53
|
+
export declare function SearchBox<T = Record<string, unknown>>({ placeholder, label, action, renderHit, renderSubindexHit, renderFacetMatch, empty, seeAll, labels, className, autoFocus, ...options }: SearchBoxProps<T>): import("react").JSX.Element;
|
|
52
54
|
/** The query input of the surrounding SearchProvider. */
|
|
53
55
|
export declare function SearchInput({ placeholder, label, className, autoFocus }: {
|
|
54
56
|
placeholder?: string;
|
|
@@ -101,6 +103,15 @@ export declare function SortSelect({ options, label, className }: {
|
|
|
101
103
|
label?: string;
|
|
102
104
|
className?: string;
|
|
103
105
|
}): import("react").JSX.Element;
|
|
106
|
+
/** The facet values the query names as buttons that filter by them, with SearchProvider's `facetMatches` (0.32.0).
|
|
107
|
+
* Those the search already applied show as chips in CurrentRefinements instead. Shows nothing when none are left. */
|
|
108
|
+
export declare function FacetMatches({ label, format, className }: {
|
|
109
|
+
/** Text before the buttons. */
|
|
110
|
+
label?: ReactNode;
|
|
111
|
+
/** A button's content (default its name and count). */
|
|
112
|
+
format?: (match: FacetMatch) => ReactNode;
|
|
113
|
+
className?: string;
|
|
114
|
+
}): import("react").JSX.Element | null;
|
|
104
115
|
/** The chosen filters as chips that remove them, and "Clear all". Shows nothing when none are chosen. */
|
|
105
116
|
export declare function CurrentRefinements({ format, clearLabel, className }: {
|
|
106
117
|
/** A chip's text (default the value, or a range like "2019–2021"). */
|
package/dist/react/components.js
CHANGED
|
@@ -5,7 +5,7 @@ import { Highlight } from "./highlight.js";
|
|
|
5
5
|
import { Image, ImageClient } from "./image.js";
|
|
6
6
|
import { messageFor } from "./messages.js";
|
|
7
7
|
import { suggestionParts } from "../index.js";
|
|
8
|
-
import { useCurrentRefinements, useDidYouMean, useHits, useLoadMore, useRefinementList, useSearchBox, useSortBy, } from "./search-provider.js";
|
|
8
|
+
import { useCurrentRefinements, useDidYouMean, useFacetMatches, useHits, useLoadMore, useRefinementList, useSearchBox, useSortBy, } from "./search-provider.js";
|
|
9
9
|
import { useAutocomplete } from "./use-autocomplete.js";
|
|
10
10
|
// The components render plain elements marked with data-findlane-* attributes and no styles of
|
|
11
11
|
// their own; styles.css gives them a default look.
|
|
@@ -27,13 +27,13 @@ export const resultsHref = (action, query) => `${action}${action.includes("?") ?
|
|
|
27
27
|
* suggested searches, then the results, "no results", or an error; then a link to the results page.
|
|
28
28
|
* Each kind is a section of one list, which the arrow keys move through. Shared by SearchBox and
|
|
29
29
|
* SearchDialog. */
|
|
30
|
-
export function Suggestions({ box, label, action, renderHit, renderSubindexHit, empty, seeAll, labels }) {
|
|
30
|
+
export function Suggestions({ box, label, action, renderHit, renderSubindexHit, renderFacetMatch, empty, seeAll, labels }) {
|
|
31
31
|
const { hits, query, total, error, items } = box;
|
|
32
32
|
const text = { ...defaultLabels, ...labels };
|
|
33
|
-
// Consecutive options of one kind make a section, each subindex its own; results get a heading only below others.
|
|
33
|
+
// Consecutive options of one kind make a section, each subindex and facet match field its own; results get a heading only below others.
|
|
34
34
|
const sections = [];
|
|
35
35
|
for (const item of items) {
|
|
36
|
-
const key = item.kind === "subindex" ? `subindex-${item.subindex}` : item.kind;
|
|
36
|
+
const key = item.kind === "subindex" ? `subindex-${item.subindex}` : item.kind === "facetMatch" ? `facetMatch-${item.match.field}` : item.kind;
|
|
37
37
|
const last = sections.at(-1);
|
|
38
38
|
if (last?.key === key)
|
|
39
39
|
last.items.push(item);
|
|
@@ -45,11 +45,19 @@ export function Suggestions({ box, label, action, renderHit, renderSubindexHit,
|
|
|
45
45
|
suggestion: text.suggestions, hit: text.results };
|
|
46
46
|
const heading = (section) => {
|
|
47
47
|
const first = section.items[0];
|
|
48
|
+
if (first.kind === "facetMatch")
|
|
49
|
+
return box.facetMatchLabel(first.match.field);
|
|
48
50
|
if (first.kind !== "subindex")
|
|
49
51
|
return headings[first.kind];
|
|
50
52
|
return box.subindexLabel(first.subindex);
|
|
51
53
|
};
|
|
52
54
|
const option = (item) => {
|
|
55
|
+
if (item.kind === "facetMatch") {
|
|
56
|
+
const href = box.hrefForFacetMatch(item.match);
|
|
57
|
+
const content = renderFacetMatch ? renderFacetMatch(item.match) : (_jsxs(_Fragment, { children: [_jsx("span", { "data-findlane-title": "", children: item.match.label }), _jsx("span", { "data-findlane-count": "", children: number(item.match.count) })] }));
|
|
58
|
+
const key = `${item.match.field}:${item.match.values.join()}`;
|
|
59
|
+
return href ? (_jsx("a", { href: href, tabIndex: -1, "data-findlane-facet-match": item.match.field, ...box.getOptionProps(item.index), children: content }, key)) : (_jsx("div", { "data-findlane-facet-match": item.match.field, ...box.getOptionProps(item.index), children: content }, key));
|
|
60
|
+
}
|
|
53
61
|
if (item.kind === "subindex") {
|
|
54
62
|
const href = box.hrefForSubindex(item);
|
|
55
63
|
const content = renderSubindexHit ? renderSubindexHit(item.subindex, item.hit) : _jsx(DefaultHit, { hit: item.hit });
|
|
@@ -69,15 +77,15 @@ export function Suggestions({ box, label, action, renderHit, renderSubindexHit,
|
|
|
69
77
|
const titled = section.kind !== "hit" || sections.length > 1;
|
|
70
78
|
const headingId = `${box.getListboxProps().id}-${section.key}`;
|
|
71
79
|
return (_jsxs("div", { role: "group", "aria-labelledby": titled ? headingId : undefined, "aria-label": titled ? undefined : label, "data-findlane-section": section.kind, children: [titled && (_jsxs("div", { "data-findlane-section-title": "", id: headingId, role: "presentation", children: [_jsx("span", { children: heading(section) }), section.kind === "recent" && (_jsx("button", { type: "button", tabIndex: -1, "data-findlane-clear": "", onClick: box.clearRecent, children: text.clear }))] })), section.items.map(option)] }, section.key));
|
|
72
|
-
}) })), searching && !error && !hits.length && box.response && (_jsx("p", { "data-findlane-note": "", children: empty ? empty(query) : _jsxs(_Fragment, { children: ["No results for \u201C", query, "\u201D"] }) })), action && searching && total > hits.length && (_jsx("a", { href: resultsHref(action, query), "data-findlane-all": "", onMouseDown: (event) => event.preventDefault(), children: seeAll ? seeAll(total) : `See all ${number(total)} results` }))] }) }));
|
|
80
|
+
}) })), searching && !error && !hits.length && !box.facetMatches.length && box.response && (_jsx("p", { "data-findlane-note": "", children: empty ? empty(query) : _jsxs(_Fragment, { children: ["No results for \u201C", query, "\u201D"] }) })), action && searching && total > hits.length && (_jsx("a", { href: resultsHref(action, query), "data-findlane-all": "", onMouseDown: (event) => event.preventDefault(), children: seeAll ? seeAll(total) : `See all ${number(total)} results` }))] }) }));
|
|
73
81
|
}
|
|
74
82
|
/** A search box that suggests results as visitors type. Works on its own with a `publicId`. */
|
|
75
|
-
export function SearchBox({ placeholder, label = "Search", action, renderHit, renderSubindexHit, empty, seeAll, labels, className, autoFocus, ...options }) {
|
|
83
|
+
export function SearchBox({ placeholder, label = "Search", action, renderHit, renderSubindexHit, renderFacetMatch, empty, seeAll, labels, className, autoFocus, ...options }) {
|
|
76
84
|
// A search chosen from the suggestions goes to the results page, as Enter does.
|
|
77
85
|
const box = useAutocomplete({ ...options,
|
|
78
86
|
onSubmit: options.onSubmit ?? (action ? (query) => window.location.assign(resultsHref(action, query)) : undefined) });
|
|
79
87
|
return (_jsxs("div", { className: className, "data-findlane-searchbox": "", "data-open": box.isOpen || undefined, children: [_jsx("form", { role: "search", action: action, method: "get", onSubmit: (event) => { if (!action)
|
|
80
|
-
event.preventDefault(); }, children: _jsx("input", { type: "search", name: "q", placeholder: placeholder, "aria-label": label, autoFocus: autoFocus, ...box.getInputProps() }) }), box.isOpen && (_jsx(Suggestions, { box: box, label: label, action: action, renderHit: renderHit, renderSubindexHit: renderSubindexHit, empty: empty, seeAll: seeAll, labels: labels }))] }));
|
|
88
|
+
event.preventDefault(); }, children: _jsx("input", { type: "search", name: "q", placeholder: placeholder, "aria-label": label, autoFocus: autoFocus, ...box.getInputProps() }) }), box.isOpen && (_jsx(Suggestions, { box: box, label: label, action: action, renderHit: renderHit, renderSubindexHit: renderSubindexHit, renderFacetMatch: renderFacetMatch, empty: empty, seeAll: seeAll, labels: labels }))] }));
|
|
81
89
|
}
|
|
82
90
|
/** The query input of the surrounding SearchProvider. */
|
|
83
91
|
export function SearchInput({ placeholder, label = "Search", className, autoFocus }) {
|
|
@@ -143,6 +151,15 @@ export function SortSelect({ options, label = "Sort by", className }) {
|
|
|
143
151
|
const { sort, setSort } = useSortBy();
|
|
144
152
|
return (_jsx("select", { className: className, "data-findlane-sort": "", "aria-label": label, value: sort ?? options[0]?.id, onChange: (event) => setSort(event.target.value === options[0]?.id ? undefined : event.target.value), children: options.map((option) => _jsx("option", { value: option.id, children: option.label }, option.id)) }));
|
|
145
153
|
}
|
|
154
|
+
/** The facet values the query names as buttons that filter by them, with SearchProvider's `facetMatches` (0.32.0).
|
|
155
|
+
* Those the search already applied show as chips in CurrentRefinements instead. Shows nothing when none are left. */
|
|
156
|
+
export function FacetMatches({ label, format, className }) {
|
|
157
|
+
const { matches, select } = useFacetMatches();
|
|
158
|
+
const offered = matches.filter((match) => !match.applied);
|
|
159
|
+
if (!offered.length)
|
|
160
|
+
return null;
|
|
161
|
+
return (_jsxs("div", { className: className, "data-findlane-facet-matches": "", children: [label && _jsx("span", { "data-findlane-facet-matches-label": "", children: label }), offered.map((match) => (_jsx("button", { type: "button", "data-field": match.field, onClick: () => select(match), children: format ? format(match) : _jsxs(_Fragment, { children: [match.label, " ", _jsx("span", { "data-findlane-count": "", children: number(match.count) })] }) }, `${match.field}:${match.values.join()}`)))] }));
|
|
162
|
+
}
|
|
146
163
|
/** The chosen filters as chips that remove them, and "Clear all". Shows nothing when none are chosen. */
|
|
147
164
|
export function CurrentRefinements({ format, clearLabel = "Clear all", className }) {
|
|
148
165
|
const { items, clear } = useCurrentRefinements();
|
package/dist/react/dialog.d.ts
CHANGED
|
@@ -10,4 +10,4 @@ export type SearchDialogProps<T> = Omit<SearchBoxProps<T>, "autoFocus"> & {
|
|
|
10
10
|
};
|
|
11
11
|
/** A search button that opens a dialog with a search box, as on docs sites; ⌘K and "/" open it too.
|
|
12
12
|
* The dialog is the browser's own, so focus stays in it and the page behind can't be used. */
|
|
13
|
-
export declare function SearchDialog<T = Record<string, unknown>>({ trigger, shortcuts, footer, placeholder, label, action, renderHit, renderSubindexHit, empty, seeAll, labels, className, ...options }: SearchDialogProps<T>): import("react").JSX.Element;
|
|
13
|
+
export declare function SearchDialog<T = Record<string, unknown>>({ trigger, shortcuts, footer, placeholder, label, action, renderHit, renderSubindexHit, renderFacetMatch, empty, seeAll, labels, className, ...options }: SearchDialogProps<T>): import("react").JSX.Element;
|
package/dist/react/dialog.js
CHANGED
|
@@ -6,7 +6,7 @@ import { useAutocomplete } from "./use-autocomplete.js";
|
|
|
6
6
|
const onMac = () => typeof navigator !== "undefined" && /Mac|iPhone|iPad/.test(navigator.platform);
|
|
7
7
|
/** A search button that opens a dialog with a search box, as on docs sites; ⌘K and "/" open it too.
|
|
8
8
|
* The dialog is the browser's own, so focus stays in it and the page behind can't be used. */
|
|
9
|
-
export function SearchDialog({ trigger, shortcuts = true, footer, placeholder, label = "Search", action, renderHit, renderSubindexHit, empty, seeAll, labels, className, ...options }) {
|
|
9
|
+
export function SearchDialog({ trigger, shortcuts = true, footer, placeholder, label = "Search", action, renderHit, renderSubindexHit, renderFacetMatch, empty, seeAll, labels, className, ...options }) {
|
|
10
10
|
const dialog = useRef(null);
|
|
11
11
|
const [open, setOpen] = useState(false);
|
|
12
12
|
const close = () => dialog.current?.close();
|
|
@@ -59,5 +59,5 @@ export function SearchDialog({ trigger, shortcuts = true, footer, placeholder, l
|
|
|
59
59
|
close();
|
|
60
60
|
}
|
|
61
61
|
},
|
|
62
|
-
}) }) }), box.isOpen && (_jsx(Suggestions, { box: box, label: label, action: action, renderHit: renderHit, renderSubindexHit: renderSubindexHit, empty: empty, seeAll: seeAll, labels: labels }))] })), open && footer && _jsx("div", { "data-findlane-dialog-footer": "", children: footer })] })] }));
|
|
62
|
+
}) }) }), box.isOpen && (_jsx(Suggestions, { box: box, label: label, action: action, renderHit: renderHit, renderSubindexHit: renderSubindexHit, renderFacetMatch: renderFacetMatch, empty: empty, seeAll: seeAll, labels: labels }))] })), open && footer && _jsx("div", { "data-findlane-dialog-footer": "", children: footer })] })] }));
|
|
63
63
|
}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
export { FindlaneProvider, useClient, type ClientOptions } from "./client.js";
|
|
2
2
|
export { useSearch, type UseSearchOptions, type UseSearchResult } from "./use-search.js";
|
|
3
|
-
export {
|
|
3
|
+
export { useMapSearch, type UseMapSearchOptions, type UseMapSearchResult } from "./use-map-search.js";
|
|
4
|
+
export { useAutocomplete, type AutocompleteFacetMatchField, type AutocompleteItem, type AutocompleteOptions, type AutocompleteSubindex } from "./use-autocomplete.js";
|
|
4
5
|
export { useRecommendations, type UseRecommendationsOptions, type UseRecommendationsResult } from "./use-recommendations.js";
|
|
5
6
|
export { Recommendations, type RecommendationsProps } from "./recommendations.js";
|
|
6
7
|
export { ProductView, useProductView } from "./product-view.js";
|
|
7
|
-
export { SearchProvider, useCurrentRefinements, useDidYouMean, useGeoSearch, useHits, useLoadMore, usePagination, useRange, useRefinementList, useSearchBox, useSearchState, useSortBy, useSubindex, useToggle, type Range, type Refinement, type SearchProviderProps, } from "./search-provider.js";
|
|
8
|
-
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, Hits, LoadMore, RefinementList, SearchBox, SearchInput, SortSelect, Stats, type HitsProps, type RefinementListProps, type SearchBoxProps, type SuggestionLabels, } from "./components.js";
|
|
8
|
+
export { SearchProvider, useCurrentRefinements, useDidYouMean, useFacetMatches, useGeoSearch, useHits, useLoadMore, usePagination, useRange, useRefinementList, useSearchBox, useSearchState, useSortBy, useSubindex, useToggle, type Range, type Refinement, type SearchProviderProps, } from "./search-provider.js";
|
|
9
|
+
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, FacetMatches, Hits, LoadMore, RefinementList, SearchBox, SearchInput, SortSelect, Stats, type HitsProps, type RefinementListProps, type SearchBoxProps, type SuggestionLabels, } from "./components.js";
|
|
9
10
|
export { SearchDialog, type SearchDialogProps } from "./dialog.js";
|
|
10
11
|
export { Highlight, Snippet, excerpt, highlightParts, type HighlightProps } from "./highlight.js";
|
|
11
12
|
export { Image, type ImageProps } from "./image.js";
|
package/dist/react/index.js
CHANGED
|
@@ -2,12 +2,13 @@
|
|
|
2
2
|
// @findlane/browser/react: hooks that keep searches (and recommendations) current, and components built on them.
|
|
3
3
|
export { FindlaneProvider, useClient } from "./client.js";
|
|
4
4
|
export { useSearch } from "./use-search.js";
|
|
5
|
+
export { useMapSearch } from "./use-map-search.js";
|
|
5
6
|
export { useAutocomplete } from "./use-autocomplete.js";
|
|
6
7
|
export { useRecommendations } from "./use-recommendations.js";
|
|
7
8
|
export { Recommendations } from "./recommendations.js";
|
|
8
9
|
export { ProductView, useProductView } from "./product-view.js";
|
|
9
|
-
export { SearchProvider, useCurrentRefinements, useDidYouMean, useGeoSearch, useHits, useLoadMore, usePagination, useRange, useRefinementList, useSearchBox, useSearchState, useSortBy, useSubindex, useToggle, } from "./search-provider.js";
|
|
10
|
-
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, Hits, LoadMore, RefinementList, SearchBox, SearchInput, SortSelect, Stats, } from "./components.js";
|
|
10
|
+
export { SearchProvider, useCurrentRefinements, useDidYouMean, useFacetMatches, useGeoSearch, useHits, useLoadMore, usePagination, useRange, useRefinementList, useSearchBox, useSearchState, useSortBy, useSubindex, useToggle, } from "./search-provider.js";
|
|
11
|
+
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, FacetMatches, Hits, LoadMore, RefinementList, SearchBox, SearchInput, SortSelect, Stats, } from "./components.js";
|
|
11
12
|
export { SearchDialog } from "./dialog.js";
|
|
12
13
|
export { Highlight, Snippet, excerpt, highlightParts } from "./highlight.js";
|
|
13
14
|
export { Image } from "./image.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ReactNode } from "react";
|
|
2
|
-
import type { DidYouMean, GeoBox } from "../index.js";
|
|
2
|
+
import type { DidYouMean, FacetMatch, GeoBox, SearchResponse } from "../index.js";
|
|
3
3
|
import { type ClientOptions } from "./client.js";
|
|
4
4
|
import { type ServerResults, type StateChange } from "./store.js";
|
|
5
5
|
import { type Hit, type Near, type SearchConfig, type SearchState } from "./state.js";
|
|
@@ -42,7 +42,7 @@ export declare function useHits<T = Record<string, unknown>>(): {
|
|
|
42
42
|
related: import("../index.js").SearchHit<T>[];
|
|
43
43
|
/** "gte" when `total` is a lower bound (with `countMode: "page"`). */
|
|
44
44
|
totalRelation: "eq" | "gte";
|
|
45
|
-
response:
|
|
45
|
+
response: SearchResponse<T> | null;
|
|
46
46
|
/** The request behind `response`. */
|
|
47
47
|
request: import("../index.js").SearchRequest | null;
|
|
48
48
|
/** How long the search took from request to response, in milliseconds; undefined when the
|
|
@@ -73,8 +73,20 @@ export declare function useDidYouMean({ delay }?: {
|
|
|
73
73
|
didYouMean: DidYouMean | null;
|
|
74
74
|
apply: () => void;
|
|
75
75
|
};
|
|
76
|
+
/** The facet values the query names, with SearchProvider's `facetMatches` (0.32.0), best first. `applied` are those
|
|
77
|
+
* the search filtered by, as the index's setting says; `searched` is then the words it searched. */
|
|
78
|
+
export declare function useFacetMatches(): {
|
|
79
|
+
matches: FacetMatch[];
|
|
80
|
+
applied: FacetMatch[];
|
|
81
|
+
searched: string | undefined;
|
|
82
|
+
isPending: boolean;
|
|
83
|
+
/** Filters by a match, taking its words out of the query, and sends its pick for Analytics. */
|
|
84
|
+
select: (match: FacetMatch) => void;
|
|
85
|
+
/** Takes the applied filters away until the query changes: the search runs on its words, and the matches only show. */
|
|
86
|
+
removeApplied: () => void;
|
|
87
|
+
};
|
|
76
88
|
/** A facet's values with their counts, most common first. Selected values stay listed (at 0 when the
|
|
77
|
-
* query no longer matches them), so they can be removed. */
|
|
89
|
+
* query no longer matches them), so they can be removed. A value a facet match applied counts as selected. */
|
|
78
90
|
export declare function useRefinementList(field: string): {
|
|
79
91
|
items: {
|
|
80
92
|
value: string;
|
|
@@ -132,7 +144,8 @@ export type Refinement = {
|
|
|
132
144
|
label: string;
|
|
133
145
|
remove: () => void;
|
|
134
146
|
};
|
|
135
|
-
/** Everything chosen, as removable items (for chips), and a way to clear it all.
|
|
147
|
+
/** Everything chosen, as removable items (for chips), filters facet matches applied too, and a way to clear it all.
|
|
148
|
+
* The query stays. */
|
|
136
149
|
export declare function useCurrentRefinements(): {
|
|
137
150
|
items: Refinement[];
|
|
138
151
|
clear: () => void;
|
|
@@ -141,11 +141,45 @@ export function useDidYouMean({ delay = 400 } = {}) {
|
|
|
141
141
|
store.update((current) => ({ ...current, q: didYouMean.q, page: 0 })); },
|
|
142
142
|
};
|
|
143
143
|
}
|
|
144
|
+
const appliedMatches = (response) => response?.facetMatches?.filter((match) => match.applied) ?? [];
|
|
145
|
+
const withoutApplied = (state) => ({ ...state, page: 0, unapplied: true });
|
|
146
|
+
/** A state with the matches its results applied as choices of its own: their values chosen, and the words searched. */
|
|
147
|
+
const withAppliedChosen = (response) => (state) => {
|
|
148
|
+
const refinements = { ...state.refinements };
|
|
149
|
+
for (const match of appliedMatches(response))
|
|
150
|
+
refinements[match.field] = match.values;
|
|
151
|
+
return { ...state, page: 0, q: response.rewrittenQuery ?? state.q, refinements };
|
|
152
|
+
};
|
|
153
|
+
/** The facet values the query names, with SearchProvider's `facetMatches` (0.32.0), best first. `applied` are those
|
|
154
|
+
* the search filtered by, as the index's setting says; `searched` is then the words it searched. */
|
|
155
|
+
export function useFacetMatches() {
|
|
156
|
+
const [{ results, pending }, store] = useSnapshot();
|
|
157
|
+
const matches = results?.response.facetMatches ?? [];
|
|
158
|
+
const applied = matches.filter((match) => match.applied);
|
|
159
|
+
return {
|
|
160
|
+
matches,
|
|
161
|
+
applied,
|
|
162
|
+
searched: applied.length ? results?.response.rewrittenQuery ?? "" : undefined,
|
|
163
|
+
isPending: pending,
|
|
164
|
+
/** Filters by a match, taking its words out of the query, and sends its pick for Analytics. */
|
|
165
|
+
select: (match) => {
|
|
166
|
+
store.facetMatchPicked(match);
|
|
167
|
+
store.update((current) => {
|
|
168
|
+
const [start, end] = match.typed ?? [0, 0];
|
|
169
|
+
const q = match.typed ? `${current.q.slice(0, start)} ${current.q.slice(end)}`.replace(/\s+/g, " ").trim() : current.q;
|
|
170
|
+
return withRefinement(match.field, match.values)({ ...current, q });
|
|
171
|
+
});
|
|
172
|
+
},
|
|
173
|
+
/** Takes the applied filters away until the query changes: the search runs on its words, and the matches only show. */
|
|
174
|
+
removeApplied: () => store.update(withoutApplied),
|
|
175
|
+
};
|
|
176
|
+
}
|
|
144
177
|
/** A facet's values with their counts, most common first. Selected values stay listed (at 0 when the
|
|
145
|
-
* query no longer matches them), so they can be removed. */
|
|
178
|
+
* query no longer matches them), so they can be removed. A value a facet match applied counts as selected. */
|
|
146
179
|
export function useRefinementList(field) {
|
|
147
180
|
const [{ state, results }, store] = useSnapshot();
|
|
148
|
-
const
|
|
181
|
+
const applied = appliedMatches(results?.response).filter((match) => match.field === field).flatMap((match) => match.values);
|
|
182
|
+
const selected = [...new Set([...(state.refinements[field] ?? []), ...applied])];
|
|
149
183
|
const counts = results?.response.facets[field] ?? {};
|
|
150
184
|
const items = Object.entries(counts)
|
|
151
185
|
.map(([value, count]) => ({ value, count, selected: selected.includes(value) }))
|
|
@@ -157,10 +191,14 @@ export function useRefinementList(field) {
|
|
|
157
191
|
items,
|
|
158
192
|
selected,
|
|
159
193
|
toggle: (value) => store.update((current) => {
|
|
160
|
-
|
|
161
|
-
|
|
194
|
+
if (applied.includes(value))
|
|
195
|
+
return withoutApplied(current);
|
|
196
|
+
// Another value beside an applied one: the applied one becomes a choice too, and its words stop being searched.
|
|
197
|
+
const chosen = applied.length && results ? withAppliedChosen(results.response)(current) : current;
|
|
198
|
+
const values = chosen.refinements[field] ?? [];
|
|
199
|
+
return withRefinement(field, values.includes(value) ? values.filter((item) => item !== value) : [...values, value])(chosen);
|
|
162
200
|
}),
|
|
163
|
-
clear: () => store.update(withRefinement(field, [])),
|
|
201
|
+
clear: () => store.update((current) => withRefinement(field, [])(applied.length ? withoutApplied(current) : current)),
|
|
164
202
|
};
|
|
165
203
|
}
|
|
166
204
|
/** A number or date range filter. List the field in `filterFields` to keep it in the URL, and in
|
|
@@ -221,10 +259,13 @@ function rangeLabel({ gte, lte }) {
|
|
|
221
259
|
return gte === lte ? `${gte}` : `${gte}–${lte}`;
|
|
222
260
|
return gte !== undefined ? `From ${gte}` : `Until ${lte}`;
|
|
223
261
|
}
|
|
224
|
-
/** Everything chosen, as removable items (for chips), and a way to clear it all.
|
|
262
|
+
/** Everything chosen, as removable items (for chips), filters facet matches applied too, and a way to clear it all.
|
|
263
|
+
* The query stays. */
|
|
225
264
|
export function useCurrentRefinements() {
|
|
226
|
-
const [{ state }, store] = useSnapshot();
|
|
265
|
+
const [{ state, results }, store] = useSnapshot();
|
|
266
|
+
const applied = appliedMatches(results?.response);
|
|
227
267
|
const items = [
|
|
268
|
+
...applied.map((match) => ({ field: match.field, value: match.values, label: match.label, remove: () => store.update(withoutApplied) })),
|
|
228
269
|
...Object.entries(state.refinements).flatMap(([field, values]) => values.map((value) => ({
|
|
229
270
|
field, value, label: value,
|
|
230
271
|
remove: () => store.update((current) => withRefinement(field, (current.refinements[field] ?? []).filter((item) => item !== value))(current)),
|
|
@@ -234,7 +275,7 @@ export function useCurrentRefinements() {
|
|
|
234
275
|
remove: () => store.update(withFilter(field, undefined)),
|
|
235
276
|
})),
|
|
236
277
|
];
|
|
237
|
-
return { items, clear: () => store.update((current) => ({ ...current, page: 0, refinements: {}, filters: {} })) };
|
|
278
|
+
return { items, clear: () => store.update((current) => ({ ...(applied.length ? withoutApplied(current) : current), page: 0, refinements: {}, filters: {} })) };
|
|
238
279
|
}
|
|
239
280
|
/** Adds the next page's hits under the current ones. */
|
|
240
281
|
export function useLoadMore() {
|
package/dist/react/state.d.ts
CHANGED
|
@@ -17,6 +17,8 @@ export type SearchState = {
|
|
|
17
17
|
near?: Near;
|
|
18
18
|
/** Only records inside a box, such as a map's visible area (useGeoSearch). */
|
|
19
19
|
within?: GeoBox;
|
|
20
|
+
/** The shopper took away a filter this query's facet matches applied: they only show, until the query changes (0.32.0). */
|
|
21
|
+
unapplied?: boolean;
|
|
20
22
|
};
|
|
21
23
|
export type SearchConfig = {
|
|
22
24
|
/** Fields to count values for. A facet's own selections don't narrow its counts, so its other
|
|
@@ -44,6 +46,13 @@ export type SearchConfig = {
|
|
|
44
46
|
/** The index's subindexes to search with each query, such as categories to suggest above the results, by
|
|
45
47
|
* name (0.23.0): in the same request, counted as one search. Read them with useSubindex. */
|
|
46
48
|
subindexes?: SearchRequest["subindexes"];
|
|
49
|
+
/** The facet values the query names, with the index's facet matches setting (0.32.0): `true` for every field of
|
|
50
|
+
* it, or `{ fields }` for some. Read them with useFacetMatches, or show them with FacetMatches. With the setting's
|
|
51
|
+
* `apply`, one can filter the search: CurrentRefinements shows it as a chip, and removing that keeps it off
|
|
52
|
+
* until the query changes. */
|
|
53
|
+
facetMatches?: boolean | {
|
|
54
|
+
fields?: string[];
|
|
55
|
+
};
|
|
47
56
|
};
|
|
48
57
|
export declare const emptyState: SearchState;
|
|
49
58
|
/** The API's largest offset. */
|
package/dist/react/state.js
CHANGED
|
@@ -11,8 +11,13 @@ export function planSearch(config, state) {
|
|
|
11
11
|
if (values.length)
|
|
12
12
|
filters[field] = { in: values };
|
|
13
13
|
Object.assign(filters, config.filters);
|
|
14
|
-
//
|
|
15
|
-
const
|
|
14
|
+
// What facet matches ask, in the search that follows the state.
|
|
15
|
+
const matching = config.facetMatches;
|
|
16
|
+
const matchFields = typeof matching === "object" ? matching.fields : undefined;
|
|
17
|
+
const mayApply = (field) => Boolean(matching && !state.unapplied && state.q.trim() && (matchFields?.includes(field) ?? true));
|
|
18
|
+
// Only facets filtered by their selections alone: a fixed filter still narrows its own counts. A facet a match may
|
|
19
|
+
// apply to is counted the same way, so its other values stay listed and can be chosen.
|
|
20
|
+
const disjunctive = facets.filter((field) => (state.refinements[field]?.length || mayApply(field)) && !(field in state.filters) && !(field in (config.filters ?? {})));
|
|
16
21
|
return {
|
|
17
22
|
q: state.q,
|
|
18
23
|
...(state.sort ? { sort: state.sort } : {}),
|
|
@@ -30,6 +35,9 @@ export function planSearch(config, state) {
|
|
|
30
35
|
...(config.context?.length ? { context: config.context } : {}),
|
|
31
36
|
// Subindexes only for a query: a page without words has nothing to suggest.
|
|
32
37
|
...(config.subindexes && state.q.trim() ? { subindexes: config.subindexes } : {}),
|
|
38
|
+
// Only for a query: without words, nothing is named.
|
|
39
|
+
...(matching && state.q.trim() ? { facetMatches: matchFields || state.unapplied
|
|
40
|
+
? { ...(matchFields ? { fields: matchFields } : {}), ...(state.unapplied ? { apply: "never" } : {}) } : true } : {}),
|
|
33
41
|
highlight: true,
|
|
34
42
|
};
|
|
35
43
|
}
|
|
@@ -129,6 +137,7 @@ export function stateFromUrl(search, config) {
|
|
|
129
137
|
page: Number.isInteger(page) && page > 1 ? page - 1 : 0,
|
|
130
138
|
...(near ? { near } : {}),
|
|
131
139
|
...(within ? { within } : {}),
|
|
140
|
+
...(config.facetMatches && params.has("unapplied") ? { unapplied: true } : {}),
|
|
132
141
|
};
|
|
133
142
|
}
|
|
134
143
|
/** The query string for a state, followed by the URL's other parameters. */
|
|
@@ -151,7 +160,9 @@ export function urlFromState(state, config, current = "") {
|
|
|
151
160
|
params.set("near", formatNear(state.near));
|
|
152
161
|
if (state.within)
|
|
153
162
|
params.set("within", [state.within.north, state.within.east, state.within.south, state.within.west].map(coordinate).join(","));
|
|
154
|
-
|
|
163
|
+
if (state.unapplied && config.facetMatches)
|
|
164
|
+
params.set("unapplied", "1");
|
|
165
|
+
const own = new Set(["q", "sort", "page", "near", "within", "unapplied", ...(config.facets ?? []), ...(config.filterFields ?? [])]);
|
|
155
166
|
for (const [key, value] of new URLSearchParams(current))
|
|
156
167
|
if (!own.has(key))
|
|
157
168
|
params.append(key, value);
|
package/dist/react/store.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { DidYouMean, SearchBrowserClient, SearchRequest, SearchResponse } from "../index.js";
|
|
1
|
+
import type { DidYouMean, FacetMatch, SearchBrowserClient, SearchRequest, SearchResponse } from "../index.js";
|
|
2
2
|
import { type Hit, type SearchConfig, type SearchState } from "./state.js";
|
|
3
3
|
/** Results computed on the server (see ssr.ts), so the first render needn't search again. */
|
|
4
4
|
export type ServerResults<T = unknown> = {
|
|
@@ -70,6 +70,8 @@ export declare class SearchStore<T = unknown> {
|
|
|
70
70
|
rule: string;
|
|
71
71
|
position?: number;
|
|
72
72
|
}): void;
|
|
73
|
+
/** Sends a facet match's pick: the query it was named by, and its place among the matches shown. */
|
|
74
|
+
facetMatchPicked(match: FacetMatch): void;
|
|
73
75
|
/** Searches unless the results already answer the current state; with a state, such as the
|
|
74
76
|
* URL's, adopts it first. */
|
|
75
77
|
start(state?: SearchState): void;
|
package/dist/react/store.js
CHANGED
|
@@ -41,10 +41,13 @@ export class SearchStore {
|
|
|
41
41
|
* `push` overrides how it reaches the history, as a map's moves replace the entry. */
|
|
42
42
|
update(change, push) {
|
|
43
43
|
const previous = this.snapshot.state;
|
|
44
|
-
const
|
|
44
|
+
const changed = change(previous);
|
|
45
|
+
// A filter taken away stays away for this query only.
|
|
46
|
+
const state = changed.q !== previous.q && changed.unapplied ? (({ unapplied: _, ...rest }) => rest)(changed) : changed;
|
|
45
47
|
if (canonical(state) === canonical(previous))
|
|
46
48
|
return;
|
|
47
|
-
const
|
|
49
|
+
const rest = (value) => canonical({ ...value, q: "", page: 0, unapplied: undefined });
|
|
50
|
+
const typing = state.q !== previous.q && rest(state) === rest(previous);
|
|
48
51
|
this.set({ state });
|
|
49
52
|
this.onChange?.(state, { push: push ?? !typing });
|
|
50
53
|
this.search(typing);
|
|
@@ -73,7 +76,9 @@ export class SearchStore {
|
|
|
73
76
|
const results = this.snapshot.results;
|
|
74
77
|
const index = results ? results.hits.findIndex((hit) => hit.id === objectID) : -1;
|
|
75
78
|
const related = index < 0 && results ? (results.response.related?.hits ?? []).findIndex((hit) => hit.id === objectID) : -1;
|
|
76
|
-
|
|
79
|
+
// The filters it was found under, those facet matches applied too.
|
|
80
|
+
const applied = results?.response.facetMatches?.filter((match) => match.applied).map((match) => match.filter) ?? [];
|
|
81
|
+
const filters = related < 0 ? Object.assign({}, results?.request.filters, ...applied) : undefined;
|
|
77
82
|
this.client.events.click(objectID, { query: results?.request.q ?? "",
|
|
78
83
|
...(index >= 0 ? { position: (results.request.offset ?? 0) + index + 1 } : {}),
|
|
79
84
|
...(related >= 0 ? { position: related + 1, list: "related" } : {}),
|
|
@@ -84,6 +89,12 @@ export class SearchStore {
|
|
|
84
89
|
this.client.events.bannerClick(banner.rule, { query: this.snapshot.results?.request.q ?? "",
|
|
85
90
|
...(banner.position ? { position: banner.position } : {}) });
|
|
86
91
|
}
|
|
92
|
+
/** Sends a facet match's pick: the query it was named by, and its place among the matches shown. */
|
|
93
|
+
facetMatchPicked(match) {
|
|
94
|
+
const results = this.snapshot.results;
|
|
95
|
+
const place = results?.response.facetMatches?.indexOf(match) ?? -1;
|
|
96
|
+
this.client.events.facetMatch(match, { query: results?.request.q ?? "", ...(place >= 0 ? { position: place + 1 } : {}) });
|
|
97
|
+
}
|
|
87
98
|
/** Searches unless the results already answer the current state; with a state, such as the
|
|
88
99
|
* URL's, adopts it first. */
|
|
89
100
|
start(state) {
|
package/dist/react/styles.css
CHANGED
|
@@ -283,6 +283,26 @@
|
|
|
283
283
|
flex-wrap: wrap;
|
|
284
284
|
gap: 6px;
|
|
285
285
|
}
|
|
286
|
+
:where([data-findlane-facet-matches]) {
|
|
287
|
+
display: flex;
|
|
288
|
+
flex-wrap: wrap;
|
|
289
|
+
align-items: center;
|
|
290
|
+
gap: 0.4em;
|
|
291
|
+
}
|
|
292
|
+
:where([data-findlane-facet-matches]) :where(button) {
|
|
293
|
+
padding: 0.3em 0.75em;
|
|
294
|
+
color: inherit;
|
|
295
|
+
font: inherit;
|
|
296
|
+
font-size: 0.9em;
|
|
297
|
+
background: none;
|
|
298
|
+
border: 1px solid color-mix(in srgb, currentColor 20%, transparent);
|
|
299
|
+
border-radius: 999px;
|
|
300
|
+
cursor: pointer;
|
|
301
|
+
}
|
|
302
|
+
:where([data-findlane-panel] [data-findlane-facet-match]) {
|
|
303
|
+
justify-content: space-between;
|
|
304
|
+
padding: 6px 12px;
|
|
305
|
+
}
|
|
286
306
|
:where([data-findlane-current-refinements]) :where(button) {
|
|
287
307
|
padding: 0.3em 0.75em;
|
|
288
308
|
color: inherit;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type HTMLAttributes, type InputHTMLAttributes } from "react";
|
|
2
|
-
import type { QuerySuggestion } from "../index.js";
|
|
2
|
+
import type { FacetMatch, QuerySuggestion } from "../index.js";
|
|
3
3
|
import type { Hit } from "./state.js";
|
|
4
4
|
import { type ClientOptions } from "./client.js";
|
|
5
5
|
export type AutocompleteOptions<T> = ClientOptions & {
|
|
@@ -38,6 +38,17 @@ export type AutocompleteOptions<T> = ClientOptions & {
|
|
|
38
38
|
* the order given (0.22.0). They're searched in the same request as the results, and count as one search
|
|
39
39
|
* with them. */
|
|
40
40
|
subindexes?: Record<string, AutocompleteSubindex>;
|
|
41
|
+
/** The facet values the query names, as rows above the results, with the index's facet matches setting (0.32.0):
|
|
42
|
+
* the fields to show, by name, in the order given. They come in the same request, and never filter the results
|
|
43
|
+
* shown here. A row goes to the setting's `link`, or its field's `getHref`. */
|
|
44
|
+
facetMatches?: Record<string, AutocompleteFacetMatchField>;
|
|
45
|
+
/** Called when a facet match is chosen, instead of following its link; for client-side routers. */
|
|
46
|
+
onFacetMatch?: (match: FacetMatch) => void;
|
|
47
|
+
};
|
|
48
|
+
/** A field's facet matches in the suggestions: its section's heading (default its name) and a match's page. */
|
|
49
|
+
export type AutocompleteFacetMatchField = {
|
|
50
|
+
label?: string;
|
|
51
|
+
getHref?: (match: FacetMatch) => string | undefined;
|
|
41
52
|
};
|
|
42
53
|
/** A subindex in the suggestions: how many of its results to show (1–10, default 3), the fields to return,
|
|
43
54
|
* its results' pages, and its section's heading (default its name). */
|
|
@@ -70,6 +81,10 @@ export type AutocompleteItem<T> = {
|
|
|
70
81
|
subindex: string;
|
|
71
82
|
hit: Hit<Record<string, unknown>>;
|
|
72
83
|
index: number;
|
|
84
|
+
} | {
|
|
85
|
+
kind: "facetMatch";
|
|
86
|
+
match: FacetMatch;
|
|
87
|
+
index: number;
|
|
73
88
|
};
|
|
74
89
|
type SubindexItem = Extract<AutocompleteItem<unknown>, {
|
|
75
90
|
kind: "subindex";
|
|
@@ -81,7 +96,7 @@ export declare function fillTemplate<T>(template: string, hit: Hit<T>): string |
|
|
|
81
96
|
* sends a click event with its place and the query, and choosing a search a suggestion event, for
|
|
82
97
|
* Analytics (the client's `events` option turns them off, or holds them until consent). With query
|
|
83
98
|
* suggestions, popular or recent searches on, `items` lists the searches before the results, and
|
|
84
|
-
* options are numbered across both. */
|
|
99
|
+
* options are numbered across both. With facet matches on, choosing one sends a facetMatch event. */
|
|
85
100
|
export declare function useAutocomplete<T = Record<string, unknown>>(options?: AutocompleteOptions<T>): {
|
|
86
101
|
/** The client searched, whose index the hits' images are from. */
|
|
87
102
|
client: import("../index.js").SearchBrowserClient;
|
|
@@ -97,8 +112,14 @@ export declare function useAutocomplete<T = Record<string, unknown>>(options?: A
|
|
|
97
112
|
setActiveIndex: import("react").Dispatch<import("react").SetStateAction<number>>;
|
|
98
113
|
close: () => void;
|
|
99
114
|
select: (hit: Hit<T>) => void;
|
|
100
|
-
/** Every option in the order shown: searches, then subindexes' results, then the index's. */
|
|
115
|
+
/** Every option in the order shown: searches, then facet matches, then subindexes' results, then the index's. */
|
|
101
116
|
items: AutocompleteItem<T>[];
|
|
117
|
+
/** The facet values the query names, as the API gave them, best first (0.32.0). */
|
|
118
|
+
facetMatches: FacetMatch[];
|
|
119
|
+
/** A facet match's page: its field's `getHref`, or the setting's link. */
|
|
120
|
+
hrefForFacetMatch: (match: FacetMatch) => string | undefined;
|
|
121
|
+
/** A facet match field's section heading: its `label`, or its name. */
|
|
122
|
+
facetMatchLabel: (field: string) => string;
|
|
102
123
|
/** Each subindex's results, by name (0.22.0). */
|
|
103
124
|
subindexes: Record<string, Hit<Record<string, unknown>>[]>;
|
|
104
125
|
/** A subindex result's page, from its `getHref` or `hrefTemplate`. */
|
|
@@ -18,7 +18,7 @@ const noSuggestions = [];
|
|
|
18
18
|
* sends a click event with its place and the query, and choosing a search a suggestion event, for
|
|
19
19
|
* Analytics (the client's `events` option turns them off, or holds them until consent). With query
|
|
20
20
|
* suggestions, popular or recent searches on, `items` lists the searches before the results, and
|
|
21
|
-
* options are numbered across both. */
|
|
21
|
+
* options are numbered across both. With facet matches on, choosing one sends a facetMatch event. */
|
|
22
22
|
export function useAutocomplete(options = {}) {
|
|
23
23
|
const { limit = 6, fields, filters, sort, minLength = 1, debounceMs, hrefTemplate, onSelect, onSubmit } = options;
|
|
24
24
|
const suggestionLimit = Math.min(Math.max(options.querySuggestions ?? 0, 0), 10);
|
|
@@ -26,6 +26,7 @@ export function useAutocomplete(options = {}) {
|
|
|
26
26
|
const recentLimit = options.recentSearches === true ? 5 : Math.min(Math.max(Number(options.recentSearches) || 0, 0), 10);
|
|
27
27
|
const getHref = options.getHref ?? (hrefTemplate ? (hit) => fillTemplate(hrefTemplate, hit) : undefined);
|
|
28
28
|
const subindexes = Object.entries(options.subindexes ?? {}).slice(0, 5);
|
|
29
|
+
const facetFields = Object.keys(options.facetMatches ?? {}).slice(0, 10);
|
|
29
30
|
const generated = useId();
|
|
30
31
|
const id = options.id ?? `findlane${generated.replace(/:/g, "")}`;
|
|
31
32
|
const [query, setQueryState] = useState(options.defaultQuery ?? "");
|
|
@@ -43,6 +44,8 @@ export function useAutocomplete(options = {}) {
|
|
|
43
44
|
...(subindexes.length ? { subindexes: Object.fromEntries(subindexes.map(([name, sub]) => [name, {
|
|
44
45
|
limit: Math.min(Math.max(sub.limit ?? 3, 1), 10), ...(sub.fields ? { attributesToRetrieve: sub.fields } : {})
|
|
45
46
|
}])) } : {}),
|
|
47
|
+
// Rows only: what's suggested stays what was typed, whatever the setting applies on a results page.
|
|
48
|
+
...(facetFields.length ? { facetMatches: { fields: facetFields, apply: "never" } } : {}),
|
|
46
49
|
}
|
|
47
50
|
: null;
|
|
48
51
|
const search = useSearch(request, {
|
|
@@ -105,17 +108,26 @@ export function useAutocomplete(options = {}) {
|
|
|
105
108
|
for (const item of suggestions)
|
|
106
109
|
searches.push({ kind: "suggestion", q: item.q, typed: item.typed, index: searches.length });
|
|
107
110
|
}
|
|
111
|
+
// Then facet matches, each field a section of its own, best first in it.
|
|
112
|
+
const facetMatches = request ? search.data?.facetMatches ?? [] : [];
|
|
113
|
+
const matched = [];
|
|
114
|
+
for (const field of facetFields)
|
|
115
|
+
for (const match of facetMatches)
|
|
116
|
+
if (match.field === field)
|
|
117
|
+
matched.push({ kind: "facetMatch", match, index: searches.length + matched.length });
|
|
108
118
|
// Then the subindexes' results, each a section of its own, then the index's.
|
|
109
119
|
const subindexHits = {};
|
|
110
120
|
const found = [];
|
|
121
|
+
const first = searches.length + matched.length;
|
|
111
122
|
for (const [name] of subindexes) {
|
|
112
123
|
const answer = search.data?.subindexes?.[name];
|
|
113
124
|
subindexHits[name] = answer && "hits" in answer ? answer.hits : [];
|
|
114
125
|
for (const hit of subindexHits[name])
|
|
115
|
-
found.push({ kind: "subindex", subindex: name, hit, index:
|
|
126
|
+
found.push({ kind: "subindex", subindex: name, hit, index: first + found.length });
|
|
116
127
|
}
|
|
117
|
-
const items = [...searches, ...found,
|
|
118
|
-
...hits.map((hit, position) => ({ kind: "hit", hit, index:
|
|
128
|
+
const items = [...searches, ...matched, ...found,
|
|
129
|
+
...hits.map((hit, position) => ({ kind: "hit", hit, index: first + found.length + position }))];
|
|
130
|
+
const facetMatchHref = (match) => options.facetMatches?.[match.field]?.getHref?.(match) ?? match.link;
|
|
119
131
|
const subindexHref = (item) => {
|
|
120
132
|
const sub = options.subindexes?.[item.subindex];
|
|
121
133
|
return sub?.getHref ? sub.getHref(item.hit) : sub?.hrefTemplate ? fillTemplate(sub.hrefTemplate, item.hit) : undefined;
|
|
@@ -176,6 +188,21 @@ export function useAutocomplete(options = {}) {
|
|
|
176
188
|
if (href)
|
|
177
189
|
window.location.assign(href);
|
|
178
190
|
};
|
|
191
|
+
/** Sends a facet match's pick: the query, and its place among the rows. */
|
|
192
|
+
const matchPicked = (item) => {
|
|
193
|
+
client.events.facetMatch(item.match, { query, position: item.index - searches.length + 1 });
|
|
194
|
+
remember(query);
|
|
195
|
+
close();
|
|
196
|
+
};
|
|
197
|
+
/** Follows a facet match: onFacetMatch gets it, or the browser goes to its page. */
|
|
198
|
+
const visitMatch = (item) => {
|
|
199
|
+
matchPicked(item);
|
|
200
|
+
if (options.onFacetMatch)
|
|
201
|
+
return options.onFacetMatch(item.match);
|
|
202
|
+
const href = facetMatchHref(item.match);
|
|
203
|
+
if (href)
|
|
204
|
+
window.location.assign(href);
|
|
205
|
+
};
|
|
179
206
|
const choose = (index) => {
|
|
180
207
|
const item = items[index];
|
|
181
208
|
if (!item)
|
|
@@ -184,6 +211,8 @@ export function useAutocomplete(options = {}) {
|
|
|
184
211
|
select(item.hit);
|
|
185
212
|
else if (item.kind === "subindex")
|
|
186
213
|
visit(item);
|
|
214
|
+
else if (item.kind === "facetMatch")
|
|
215
|
+
visitMatch(item);
|
|
187
216
|
else
|
|
188
217
|
pick(item);
|
|
189
218
|
};
|
|
@@ -244,8 +273,14 @@ export function useAutocomplete(options = {}) {
|
|
|
244
273
|
setActiveIndex,
|
|
245
274
|
close,
|
|
246
275
|
select,
|
|
247
|
-
/** Every option in the order shown: searches, then subindexes' results, then the index's. */
|
|
276
|
+
/** Every option in the order shown: searches, then facet matches, then subindexes' results, then the index's. */
|
|
248
277
|
items,
|
|
278
|
+
/** The facet values the query names, as the API gave them, best first (0.32.0). */
|
|
279
|
+
facetMatches,
|
|
280
|
+
/** A facet match's page: its field's `getHref`, or the setting's link. */
|
|
281
|
+
hrefForFacetMatch: facetMatchHref,
|
|
282
|
+
/** A facet match field's section heading: its `label`, or its name. */
|
|
283
|
+
facetMatchLabel: (field) => options.facetMatches?.[field]?.label ?? field,
|
|
249
284
|
/** Each subindex's results, by name (0.22.0). */
|
|
250
285
|
subindexes: subindexHits,
|
|
251
286
|
/** A subindex result's page, from its `getHref` or `hrefTemplate`. */
|
|
@@ -329,6 +364,15 @@ export function useAutocomplete(options = {}) {
|
|
|
329
364
|
const item = items[index];
|
|
330
365
|
if (event.defaultPrevented || !item)
|
|
331
366
|
return;
|
|
367
|
+
if (item.kind === "facetMatch") {
|
|
368
|
+
// A link is followed as usual, unless onFacetMatch takes it; one opened in a new tab or window is left to the browser.
|
|
369
|
+
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
370
|
+
return client.events.facetMatch(item.match, { query, position: item.index - searches.length + 1 });
|
|
371
|
+
if (!options.onFacetMatch && event.currentTarget.href)
|
|
372
|
+
return matchPicked(item);
|
|
373
|
+
event.preventDefault();
|
|
374
|
+
return visitMatch(item);
|
|
375
|
+
}
|
|
332
376
|
if (item.kind === "subindex") {
|
|
333
377
|
// A link is followed as usual; one opened in a new tab or window is left to the browser.
|
|
334
378
|
if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { Cluster, GeoBox, MapCells, MapTile } from "../index.js";
|
|
2
|
+
import { type ClientOptions } from "./client.js";
|
|
3
|
+
import { type Hit } from "./state.js";
|
|
4
|
+
export type UseMapSearchOptions = ClientOptions & {
|
|
5
|
+
q?: string;
|
|
6
|
+
filters?: Record<string, unknown>;
|
|
7
|
+
/** A sort ID: which of a cell's records `hits` shows. */
|
|
8
|
+
sort?: string;
|
|
9
|
+
/** Groups of matches, to draw as bubbles (default: 16 cells a side, which on `tilesFor`'s tiles is 64 pixels each). `stats`
|
|
10
|
+
* takes up to three number fields your search settings let visitors filter by. false asks for none. */
|
|
11
|
+
clusters?: {
|
|
12
|
+
cells?: MapCells;
|
|
13
|
+
stats?: string[];
|
|
14
|
+
} | false;
|
|
15
|
+
/** A few records of each area, to draw as pins (default: none): `perCell` of each of `cells` a side (8), up to `limit`
|
|
16
|
+
* (50) a tile, by the search's ranking. These count as records a visitor took; clusters don't. */
|
|
17
|
+
hits?: {
|
|
18
|
+
cells?: MapCells;
|
|
19
|
+
perCell?: number;
|
|
20
|
+
limit?: number;
|
|
21
|
+
attributesToRetrieve?: string[];
|
|
22
|
+
} | false;
|
|
23
|
+
};
|
|
24
|
+
export type UseMapSearchResult<T> = {
|
|
25
|
+
clusters: Cluster[];
|
|
26
|
+
hits: Hit<T>[];
|
|
27
|
+
/** How many records match in the tiles shown. */
|
|
28
|
+
total: number;
|
|
29
|
+
/** The tiles the view needs. */
|
|
30
|
+
tiles: MapTile[];
|
|
31
|
+
/** A tile is on its way. After a zoom or a change of filters, the earlier answer stays until every new tile has arrived. */
|
|
32
|
+
isPending: boolean;
|
|
33
|
+
error: unknown;
|
|
34
|
+
};
|
|
35
|
+
/** Keeps a map's clusters and pins current. Pass the map's view (its bounds and zoom, from a `moveend` listener) or null to not
|
|
36
|
+
* search. It asks for fixed tiles (`tilesFor`), so moving within them asks for nothing, going back answers from memory, and
|
|
37
|
+
* visitors looking at one area share the edge's cache. Outdated requests stop. */
|
|
38
|
+
export declare function useMapSearch<T = Record<string, unknown>>(view: {
|
|
39
|
+
box: GeoBox;
|
|
40
|
+
zoom: number;
|
|
41
|
+
} | null, { q, filters, sort, clusters, hits, publicId, baseUrl, client: given }?: UseMapSearchOptions): UseMapSearchResult<T>;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { tilesFor } from "../map.js";
|
|
4
|
+
import { cachedTile, peekTile } from "./cache.js";
|
|
5
|
+
import { useClient } from "./client.js";
|
|
6
|
+
import { canonical } from "./state.js";
|
|
7
|
+
const tileId = (tile) => `${tile.z}/${tile.x}/${tile.y}`;
|
|
8
|
+
/** Keeps a map's clusters and pins current. Pass the map's view (its bounds and zoom, from a `moveend` listener) or null to not
|
|
9
|
+
* search. It asks for fixed tiles (`tilesFor`), so moving within them asks for nothing, going back answers from memory, and
|
|
10
|
+
* visitors looking at one area share the edge's cache. Outdated requests stop. */
|
|
11
|
+
export function useMapSearch(view, { q, filters, sort, clusters = {}, hits = false, publicId, baseUrl, client: given } = {}) {
|
|
12
|
+
const client = useClient({ publicId, baseUrl, client: given });
|
|
13
|
+
const request = {
|
|
14
|
+
...(q ? { q } : {}), ...(filters ? { filters } : {}), ...(sort ? { sort } : {}),
|
|
15
|
+
limit: hits ? hits.limit ?? 50 : 0,
|
|
16
|
+
...(clusters ? { clusters: { cells: clusters.cells ?? 16, ...(clusters.stats?.length ? { stats: clusters.stats } : {}) } } : {}),
|
|
17
|
+
...(hits ? { spread: { cells: hits.cells ?? 8, ...(hits.perCell ? { perCell: hits.perCell } : {}) } } : {}),
|
|
18
|
+
...(hits && hits.attributesToRetrieve ? { attributesToRetrieve: hits.attributesToRetrieve } : {}),
|
|
19
|
+
};
|
|
20
|
+
const requestKey = canonical(request);
|
|
21
|
+
const needed = view ? tilesFor(view.box, view.zoom) : [];
|
|
22
|
+
const tilesKey = needed.map(tileId).join(",");
|
|
23
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
24
|
+
const tiles = useMemo(() => needed, [tilesKey]);
|
|
25
|
+
const [shown, setShown] = useState({ clusters: [], hits: [], total: 0, isPending: !!view, error: null });
|
|
26
|
+
// What's showing, and the requests the last effect is waiting for.
|
|
27
|
+
const current = useRef({ key: "", z: null, controller: null });
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
const controller = new AbortController();
|
|
30
|
+
const answers = new Map();
|
|
31
|
+
const z = tiles[0]?.z ?? null;
|
|
32
|
+
let waiting = 0;
|
|
33
|
+
const show = () => {
|
|
34
|
+
// Moving at one zoom fills in tile by tile. Otherwise the earlier answer stays until the new one is whole.
|
|
35
|
+
const continuing = current.current.key === requestKey && current.current.z === z;
|
|
36
|
+
if (waiting > 0 && !continuing) {
|
|
37
|
+
setShown((before) => (before.isPending ? before : { ...before, isPending: true }));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
current.current = { ...current.current, key: requestKey, z };
|
|
41
|
+
const found = tiles.flatMap((tile) => answers.get(tileId(tile)) ?? []);
|
|
42
|
+
setShown({ clusters: found.flatMap((answer) => answer.clusters ?? []), hits: found.flatMap((answer) => answer.hits),
|
|
43
|
+
total: found.reduce((sum, answer) => sum + answer.total, 0), isPending: waiting > 0, error: null });
|
|
44
|
+
};
|
|
45
|
+
for (const tile of tiles) {
|
|
46
|
+
const asked = { ...request, tile };
|
|
47
|
+
const known = peekTile(client, asked);
|
|
48
|
+
if (known) {
|
|
49
|
+
answers.set(tileId(tile), known);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
waiting++;
|
|
53
|
+
cachedTile(client, asked, controller.signal).then((answer) => {
|
|
54
|
+
if (controller.signal.aborted)
|
|
55
|
+
return;
|
|
56
|
+
answers.set(tileId(tile), answer);
|
|
57
|
+
waiting--;
|
|
58
|
+
show();
|
|
59
|
+
}, (error) => {
|
|
60
|
+
if (controller.signal.aborted)
|
|
61
|
+
return;
|
|
62
|
+
waiting--;
|
|
63
|
+
setShown((before) => ({ ...before, isPending: waiting > 0, error }));
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
show();
|
|
67
|
+
// Stopped only now, so a tile both views need keeps its request rather than sending it again.
|
|
68
|
+
current.current.controller?.abort();
|
|
69
|
+
current.current.controller = controller;
|
|
70
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
71
|
+
}, [client, requestKey, tiles]);
|
|
72
|
+
useEffect(() => () => current.current.controller?.abort(), []);
|
|
73
|
+
return { ...shown, tiles };
|
|
74
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@findlane/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.33.0",
|
|
4
4
|
"description": "Findlane browser SDK: fast, typo-tolerant public search from the browser with an index's public ID, plus React hooks and components.",
|
|
5
5
|
"keywords": ["findlane", "search", "full-text search", "typo tolerance", "instant search", "ecommerce search", "browser", "react", "autocomplete"],
|
|
6
6
|
"license": "MIT",
|