@findlane/browser 0.32.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 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
@@ -96,6 +115,27 @@ export type GeoBox = {
96
115
  east: number;
97
116
  west: number;
98
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
+ };
99
139
  /** A result. */
100
140
  export type SearchHit<T> = {
101
141
  id: string;
@@ -147,6 +187,11 @@ export type SearchResponse<T> = {
147
187
  sort?: string;
148
188
  /** With `near`: the point distances are from, or null when the visitor's location isn't known. */
149
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[];
150
195
  /** With the index's `didYouMean` setting: the query with the words typo tolerance corrected, when the
151
196
  * results matched some words only by typo ("Showing results for …"), else null. */
152
197
  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 { 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
+ }
@@ -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;
@@ -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 > size)
122
+ if (cache.size > from.most)
113
123
  cache.delete(cache.keys().next().value);
114
124
  }
@@ -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";
@@ -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,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.32.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",