@findlane/browser 0.32.0 → 0.34.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 +59 -1
- package/dist/index.js +1 -0
- package/dist/map.d.ts +15 -0
- package/dist/map.js +51 -0
- package/dist/react/cache.d.ts +4 -0
- package/dist/react/cache.js +12 -2
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.js +1 -0
- package/dist/react/use-map-search.d.ts +46 -0
- package/dist/react/use-map-search.js +95 -0
- package/package.json +7 -4
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 { clusterFor, 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?: ClusterStat[];
|
|
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
|
|
@@ -96,6 +115,40 @@ export type GeoBox = {
|
|
|
96
115
|
east: number;
|
|
97
116
|
west: number;
|
|
98
117
|
};
|
|
118
|
+
/** A map library's own bounds object, which `tilesFor` and `useMapSearch` also read: MapLibre's, Mapbox's or Leaflet's. */
|
|
119
|
+
export type MapBounds = {
|
|
120
|
+
getNorth(): number;
|
|
121
|
+
getSouth(): number;
|
|
122
|
+
getEast(): number;
|
|
123
|
+
getWest(): number;
|
|
124
|
+
};
|
|
125
|
+
/** A map tile, numbered as MapLibre and other web maps number them. */
|
|
126
|
+
export type MapTile = {
|
|
127
|
+
z: number;
|
|
128
|
+
x: number;
|
|
129
|
+
y: number;
|
|
130
|
+
};
|
|
131
|
+
/** Cells a side of a map tile. */
|
|
132
|
+
export type MapCells = 1 | 2 | 4 | 8 | 16;
|
|
133
|
+
/** A number field in clusters' stats, by its name. With `gt`, values at or below it are left out of the stat, such as a price of 0
|
|
134
|
+
* that means no price (0.34.0). Those records stay in the cluster's `count` and on the map. */
|
|
135
|
+
export type ClusterStat = string | {
|
|
136
|
+
field: string;
|
|
137
|
+
gt?: number;
|
|
138
|
+
};
|
|
139
|
+
/** 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
|
|
140
|
+
* means every record is at one place, such as flats in one building. `stats` leaves out a field no record has a value of. */
|
|
141
|
+
export type Cluster = {
|
|
142
|
+
count: number;
|
|
143
|
+
lat: number;
|
|
144
|
+
lng: number;
|
|
145
|
+
bounds: GeoBox;
|
|
146
|
+
stats?: Record<string, {
|
|
147
|
+
min: number;
|
|
148
|
+
max: number;
|
|
149
|
+
avg: number;
|
|
150
|
+
}>;
|
|
151
|
+
};
|
|
99
152
|
/** A result. */
|
|
100
153
|
export type SearchHit<T> = {
|
|
101
154
|
id: string;
|
|
@@ -147,6 +200,11 @@ export type SearchResponse<T> = {
|
|
|
147
200
|
sort?: string;
|
|
148
201
|
/** With `near`: the point distances are from, or null when the visitor's location isn't known. */
|
|
149
202
|
near?: GeoPoint | null;
|
|
203
|
+
/** With `bounds`: the box around every match with a place on the map, or null without any. Records past about 85° north or south
|
|
204
|
+
* have none, and matches on both sides of the antimeridian get a box as wide as the map. */
|
|
205
|
+
bounds?: GeoBox | null;
|
|
206
|
+
/** With `clusters`: one for each cell with matches. */
|
|
207
|
+
clusters?: Cluster[];
|
|
150
208
|
/** With the index's `didYouMean` setting: the query with the words typo tolerance corrected, when the
|
|
151
209
|
* results matched some words only by typo ("Showing results for …"), else null. */
|
|
152
210
|
didYouMean?: DidYouMean | null;
|
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 { clusterFor, 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,15 @@
|
|
|
1
|
+
import type { Cluster, GeoBox, MapBounds, MapTile } from "./index.js";
|
|
2
|
+
/** A box from a plain one or a map library's own bounds object (MapLibre, Mapbox, Leaflet). */
|
|
3
|
+
export declare function plainBox(box: GeoBox | MapBounds): GeoBox;
|
|
4
|
+
/** The fixed tiles covering a map's view, from its bounds and zoom, for `tile` in a search. Everyone looking at the
|
|
5
|
+
* same area asks for the same tiles, so they're answered from the cache where a box almost never would be. They're
|
|
6
|
+
* one level above the map's zoom, 1024 pixels wide on screen, which makes at most six on a desktop view.
|
|
7
|
+
* A box whose west is greater than its east crosses the antimeridian, and longitudes past ±180 (a map showing copies
|
|
8
|
+
* of the world) wrap around. */
|
|
9
|
+
export declare function tilesFor(bounds: GeoBox | MapBounds, zoom: number): MapTile[];
|
|
10
|
+
/** The cluster a record is in, from the clusters of its tile, for one marker an area. Give `clusters` and `spread` the same
|
|
11
|
+
* `cells`. Edges are rounded, so comparing a place with `bounds` directly misses records on an edge. */
|
|
12
|
+
export declare function clusterFor<C extends Cluster>(place: {
|
|
13
|
+
lat: number;
|
|
14
|
+
lng: number;
|
|
15
|
+
}, clusters: readonly C[]): C | undefined;
|
package/dist/map.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
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
|
+
/** A box from a plain one or a map library's own bounds object (MapLibre, Mapbox, Leaflet). */
|
|
10
|
+
export function plainBox(box) {
|
|
11
|
+
const plain = "getNorth" in box ? { north: box.getNorth(), south: box.getSouth(), east: box.getEast(), west: box.getWest() } : box;
|
|
12
|
+
if (![plain.north, plain.south, plain.east, plain.west].every(Number.isFinite))
|
|
13
|
+
throw new TypeError("A map's box needs north, south, east and west in degrees, or getNorth() and the like");
|
|
14
|
+
return plain;
|
|
15
|
+
}
|
|
16
|
+
/** The fixed tiles covering a map's view, from its bounds and zoom, for `tile` in a search. Everyone looking at the
|
|
17
|
+
* same area asks for the same tiles, so they're answered from the cache where a box almost never would be. They're
|
|
18
|
+
* one level above the map's zoom, 1024 pixels wide on screen, which makes at most six on a desktop view.
|
|
19
|
+
* A box whose west is greater than its east crosses the antimeridian, and longitudes past ±180 (a map showing copies
|
|
20
|
+
* of the world) wrap around. */
|
|
21
|
+
export function tilesFor(bounds, zoom) {
|
|
22
|
+
const box = plainBox(bounds);
|
|
23
|
+
const span = box.east >= box.west ? box.east - box.west : box.east + 360 - box.west;
|
|
24
|
+
const west = (((box.west + 180) % 360) + 360) % 360 / 360;
|
|
25
|
+
for (let z = Math.max(0, Math.min(22, Math.floor(zoom) - 1));; z--) {
|
|
26
|
+
const side = 2 ** z;
|
|
27
|
+
const across = Math.floor(west * side);
|
|
28
|
+
// A tile's south and east edges are its neighbours', so a box ending on one doesn't reach the next.
|
|
29
|
+
const lastAcross = Math.max(across, Math.ceil((west + span / 360) * side) - 1);
|
|
30
|
+
const down = Math.floor(fractionDown(box.north) * side);
|
|
31
|
+
const lastDown = Math.max(down, Math.min(side - 1, Math.ceil(fractionDown(box.south) * side) - 1));
|
|
32
|
+
const columns = Math.min(lastAcross - across + 1, side);
|
|
33
|
+
const rows = lastDown - down + 1;
|
|
34
|
+
if (z > 0 && columns * rows > mostTiles)
|
|
35
|
+
continue;
|
|
36
|
+
const tiles = [];
|
|
37
|
+
for (let row = 0; row < rows; row++)
|
|
38
|
+
for (let column = 0; column < columns; column++)
|
|
39
|
+
tiles.push({ z, x: (across + column) % side, y: Math.min(down + row, side - 1) });
|
|
40
|
+
return tiles;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** How far a place can be from a cluster's edge and still be in it: edges are rounded to six decimals, on a grid of about a
|
|
44
|
+
* centimeter, and records' places aren't. */
|
|
45
|
+
const margin = 0.000001;
|
|
46
|
+
/** The cluster a record is in, from the clusters of its tile, for one marker an area. Give `clusters` and `spread` the same
|
|
47
|
+
* `cells`. Edges are rounded, so comparing a place with `bounds` directly misses records on an edge. */
|
|
48
|
+
export function clusterFor(place, clusters) {
|
|
49
|
+
return clusters.find(({ bounds }) => place.lat <= bounds.north + margin && place.lat >= bounds.south - margin
|
|
50
|
+
&& place.lng <= bounds.east + margin && place.lng >= bounds.west - margin);
|
|
51
|
+
}
|
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
|
}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export { FindlaneProvider, useClient, type ClientOptions } from "./client.js";
|
|
2
2
|
export { useSearch, type UseSearchOptions, type UseSearchResult } from "./use-search.js";
|
|
3
|
+
export { useMapSearch, type UseMapSearchOptions, type UseMapSearchResult } from "./use-map-search.js";
|
|
3
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";
|
package/dist/react/index.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
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";
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Cluster, ClusterStat, GeoBox, MapBounds, 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: a name, or `{ field, gt }` to leave out values at
|
|
11
|
+
* or below `gt`. false asks for none. */
|
|
12
|
+
clusters?: {
|
|
13
|
+
cells?: MapCells;
|
|
14
|
+
stats?: ClusterStat[];
|
|
15
|
+
} | false;
|
|
16
|
+
/** A few records of each area, to draw as pins (default: none): `perCell` of each of `cells` a side (8), up to `limit`
|
|
17
|
+
* (50) a tile, by the search's ranking. These count as records a visitor took; clusters don't. */
|
|
18
|
+
hits?: {
|
|
19
|
+
cells?: MapCells;
|
|
20
|
+
perCell?: number;
|
|
21
|
+
limit?: number;
|
|
22
|
+
attributesToRetrieve?: string[];
|
|
23
|
+
} | false;
|
|
24
|
+
};
|
|
25
|
+
export type UseMapSearchResult<T> = {
|
|
26
|
+
clusters: Cluster[];
|
|
27
|
+
hits: Hit<T>[];
|
|
28
|
+
/** How many records match in the tiles shown. A tile reaches past the view, so this can be more than the view holds: count
|
|
29
|
+
* the clusters in sight for that. */
|
|
30
|
+
total: number;
|
|
31
|
+
/** The tiles the view needs. */
|
|
32
|
+
tiles: MapTile[];
|
|
33
|
+
/** A tile is on its way. After a zoom or a change of filters, the earlier answer stays until every new tile has arrived. */
|
|
34
|
+
isPending: boolean;
|
|
35
|
+
/** Why a tile of this view failed. What the other tiles found still shows, and the next move asks for the failed one again. */
|
|
36
|
+
error: unknown;
|
|
37
|
+
/** Asks again for the tiles that failed, for a "Try again" button. */
|
|
38
|
+
retry: () => void;
|
|
39
|
+
};
|
|
40
|
+
/** 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
|
|
41
|
+
* search. It asks for fixed tiles (`tilesFor`), so moving within them asks for nothing, going back answers from memory, and
|
|
42
|
+
* visitors looking at one area share the edge's cache. Outdated requests stop. */
|
|
43
|
+
export declare function useMapSearch<T = Record<string, unknown>>(view: {
|
|
44
|
+
box: GeoBox | MapBounds;
|
|
45
|
+
zoom: number;
|
|
46
|
+
} | null, { q, filters, sort, clusters, hits, publicId, baseUrl, client: given }?: UseMapSearchOptions): UseMapSearchResult<T>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
3
|
+
import { plainBox, 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 box = view && plainBox(view.box);
|
|
22
|
+
const needed = view && box ? tilesFor(box, view.zoom) : [];
|
|
23
|
+
const tilesKey = needed.map(tileId).join(",");
|
|
24
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
25
|
+
const tiles = useMemo(() => needed, [tilesKey]);
|
|
26
|
+
const wanted = `${requestKey}\n${tilesKey}`;
|
|
27
|
+
const [shown, setShown] = useState({ answers: "", clusters: [], hits: [], total: 0, isPending: !!view, error: null });
|
|
28
|
+
const [attempt, setAttempt] = useState(0);
|
|
29
|
+
const retry = useCallback(() => setAttempt((count) => count + 1), []);
|
|
30
|
+
// What's showing, the requests the last effect is waiting for, and whether a tile of it failed.
|
|
31
|
+
const current = useRef({ key: "", z: null, controller: null, failed: false });
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
const controller = new AbortController();
|
|
34
|
+
const answers = new Map();
|
|
35
|
+
const z = tiles[0]?.z ?? null;
|
|
36
|
+
let waiting = 0;
|
|
37
|
+
let failure = null;
|
|
38
|
+
current.current.failed = false;
|
|
39
|
+
const show = () => {
|
|
40
|
+
// Moving at one zoom fills in tile by tile. Otherwise the earlier answer stays until the new one is whole.
|
|
41
|
+
const continuing = current.current.key === requestKey && current.current.z === z;
|
|
42
|
+
if (waiting > 0 && !continuing) {
|
|
43
|
+
setShown((before) => (before.isPending ? before : { ...before, isPending: true }));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
current.current = { ...current.current, key: requestKey, z };
|
|
47
|
+
const found = tiles.flatMap((tile) => answers.get(tileId(tile)) ?? []);
|
|
48
|
+
setShown({ answers: wanted, clusters: found.flatMap((answer) => answer.clusters ?? []), hits: found.flatMap((answer) => answer.hits),
|
|
49
|
+
total: found.reduce((sum, answer) => sum + answer.total, 0), isPending: waiting > 0, error: failure });
|
|
50
|
+
};
|
|
51
|
+
for (const tile of tiles) {
|
|
52
|
+
const asked = { ...request, tile };
|
|
53
|
+
const known = peekTile(client, asked);
|
|
54
|
+
if (known) {
|
|
55
|
+
answers.set(tileId(tile), known);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
waiting++;
|
|
59
|
+
cachedTile(client, asked, controller.signal).then((answer) => {
|
|
60
|
+
if (controller.signal.aborted)
|
|
61
|
+
return;
|
|
62
|
+
answers.set(tileId(tile), answer);
|
|
63
|
+
waiting--;
|
|
64
|
+
show();
|
|
65
|
+
}, (error) => {
|
|
66
|
+
if (controller.signal.aborted)
|
|
67
|
+
return;
|
|
68
|
+
waiting--;
|
|
69
|
+
failure = error;
|
|
70
|
+
current.current.failed = true;
|
|
71
|
+
show();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
show();
|
|
75
|
+
// Stopped only now, so a tile both views need keeps its request rather than sending it again.
|
|
76
|
+
current.current.controller?.abort();
|
|
77
|
+
current.current.controller = controller;
|
|
78
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
79
|
+
}, [client, requestKey, tiles, attempt]);
|
|
80
|
+
useEffect(() => () => current.current.controller?.abort(), []);
|
|
81
|
+
// A move within the same tiles needs nothing new, except what failed. By the box's edges, not the view object: a view made
|
|
82
|
+
// anew each render isn't a move, and would ask again without end.
|
|
83
|
+
const place = box && view ? `${box.north},${box.south},${box.east},${box.west},${view.zoom}` : "";
|
|
84
|
+
const lastPlace = useRef(place);
|
|
85
|
+
useEffect(() => {
|
|
86
|
+
if (lastPlace.current === place)
|
|
87
|
+
return;
|
|
88
|
+
lastPlace.current = place;
|
|
89
|
+
if (current.current.failed)
|
|
90
|
+
retry();
|
|
91
|
+
}, [place, retry]);
|
|
92
|
+
const { answers, ...result } = shown;
|
|
93
|
+
// Until its effect has run, a new view's render still holds the last answer: it's on its way.
|
|
94
|
+
return { ...result, isPending: shown.isPending || (!!view && answers !== wanted), tiles, retry };
|
|
95
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@findlane/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.34.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",
|
|
@@ -11,15 +11,18 @@
|
|
|
11
11
|
"exports": {
|
|
12
12
|
".": {
|
|
13
13
|
"types": "./dist/index.d.ts",
|
|
14
|
-
"import": "./dist/index.js"
|
|
14
|
+
"import": "./dist/index.js",
|
|
15
|
+
"default": "./dist/index.js"
|
|
15
16
|
},
|
|
16
17
|
"./react": {
|
|
17
18
|
"types": "./dist/react/index.d.ts",
|
|
18
|
-
"import": "./dist/react/index.js"
|
|
19
|
+
"import": "./dist/react/index.js",
|
|
20
|
+
"default": "./dist/react/index.js"
|
|
19
21
|
},
|
|
20
22
|
"./react/ssr": {
|
|
21
23
|
"types": "./dist/react/ssr.d.ts",
|
|
22
|
-
"import": "./dist/react/ssr.js"
|
|
24
|
+
"import": "./dist/react/ssr.js",
|
|
25
|
+
"default": "./dist/react/ssr.js"
|
|
23
26
|
},
|
|
24
27
|
"./react/styles.css": "./dist/react/styles.css",
|
|
25
28
|
"./package.json": "./package.json"
|