@findlane/browser 0.26.0 → 0.27.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/images.d.ts +13 -0
- package/dist/images.js +33 -0
- package/dist/index.d.ts +18 -1
- package/dist/index.js +20 -0
- package/dist/placeholder.d.ts +3 -0
- package/dist/placeholder.js +153 -0
- package/dist/react/client.d.ts +2 -0
- package/dist/react/client.js +4 -0
- package/dist/react/components.d.ts +5 -2
- package/dist/react/components.js +11 -8
- package/dist/react/image.d.ts +25 -0
- package/dist/react/image.js +46 -0
- package/dist/react/index.d.ts +1 -0
- package/dist/react/index.js +1 -0
- package/dist/react/recommendations.js +12 -11
- package/dist/react/search-provider.js +2 -1
- package/dist/react/use-autocomplete.d.ts +2 -0
- package/dist/react/use-autocomplete.js +2 -0
- package/package.json +1 -1
package/dist/images.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** The widths the image Worker makes, in pixels. Any other width is rounded up to one of these, so a
|
|
2
|
+
* page's images share cached copies, and asking for odd widths can't make endless new ones. */
|
|
3
|
+
export declare const imageWidths: readonly [48, 64, 96, 128, 160, 192, 256, 320, 384, 480, 640, 768, 960, 1280, 1600];
|
|
4
|
+
/** The smallest made width that's at least `width`; the largest one past it. */
|
|
5
|
+
export declare function imageWidth(width: number): 48 | 64 | 96 | 128 | 160 | 192 | 256 | 320 | 384 | 480 | 640 | 768 | 960 | 1280 | 1600;
|
|
6
|
+
/** The header the API's public answers carry while an index has optimized images on: the image hosts its
|
|
7
|
+
* owner allows, comma-separated. */
|
|
8
|
+
export declare const imageHostsHeader = "x-findlane-images";
|
|
9
|
+
/** The hosts an `x-findlane-images` header names; empty without one. */
|
|
10
|
+
export declare function imageHostsOf(header: string | null | undefined): Set<string>;
|
|
11
|
+
/** An image's optimized address: `src` resized to `width` (rounded up to a made width) by the image Worker
|
|
12
|
+
* at `apiOrigin`, or null when `src` isn't an http(s) address on one of `hosts`. */
|
|
13
|
+
export declare function optimizedImageUrl(apiOrigin: string, publicId: string, hosts: Set<string>, src: unknown, width: number): string | null;
|
package/dist/images.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// Optimized images (0.27.0): an index's record images, resized and re-encoded at the edge
|
|
2
|
+
// (workers/images), from the hosts its owner allows. Shared by the client, the React Image component,
|
|
3
|
+
// the search widget and the image Worker, so all of them ask for the same few widths.
|
|
4
|
+
/** The widths the image Worker makes, in pixels. Any other width is rounded up to one of these, so a
|
|
5
|
+
* page's images share cached copies, and asking for odd widths can't make endless new ones. */
|
|
6
|
+
export const imageWidths = [48, 64, 96, 128, 160, 192, 256, 320, 384, 480, 640, 768, 960, 1280, 1600];
|
|
7
|
+
/** The smallest made width that's at least `width`; the largest one past it. */
|
|
8
|
+
export function imageWidth(width) {
|
|
9
|
+
return imageWidths.find((made) => made >= width) ?? imageWidths[imageWidths.length - 1];
|
|
10
|
+
}
|
|
11
|
+
/** The header the API's public answers carry while an index has optimized images on: the image hosts its
|
|
12
|
+
* owner allows, comma-separated. */
|
|
13
|
+
export const imageHostsHeader = "x-findlane-images";
|
|
14
|
+
/** The hosts an `x-findlane-images` header names; empty without one. */
|
|
15
|
+
export function imageHostsOf(header) {
|
|
16
|
+
return new Set((header ?? "").split(",").map((host) => host.trim().toLowerCase()).filter(Boolean));
|
|
17
|
+
}
|
|
18
|
+
/** An image's optimized address: `src` resized to `width` (rounded up to a made width) by the image Worker
|
|
19
|
+
* at `apiOrigin`, or null when `src` isn't an http(s) address on one of `hosts`. */
|
|
20
|
+
export function optimizedImageUrl(apiOrigin, publicId, hosts, src, width) {
|
|
21
|
+
if (typeof src !== "string" || !hosts.size)
|
|
22
|
+
return null;
|
|
23
|
+
let url;
|
|
24
|
+
try {
|
|
25
|
+
url = new URL(src);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
if ((url.protocol !== "https:" && url.protocol !== "http:") || !hosts.has(url.hostname.toLowerCase()))
|
|
31
|
+
return null;
|
|
32
|
+
return `${apiOrigin}/img/${publicId}?url=${encodeURIComponent(src)}&w=${imageWidth(width)}`;
|
|
33
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export { imageWidth, imageWidths } from "./images.js";
|
|
2
|
+
export { placeholderUrl } from "./placeholder.js";
|
|
1
3
|
export type SearchRequest = {
|
|
2
4
|
q?: string;
|
|
3
5
|
/** A sort ID from the index settings, "relevance", or "distance" (with `near`). */
|
|
@@ -107,6 +109,10 @@ export type SearchHit<T> = {
|
|
|
107
109
|
};
|
|
108
110
|
/** A rule pinned it at its place (0.19.0). */
|
|
109
111
|
pinned?: true;
|
|
112
|
+
/** With optimized images on (0.27.0): its image's placeholder, a ThumbHash in base64, which `placeholderUrl`
|
|
113
|
+
* draws, and React's `Image` shows while the image loads. Absent until it's made, a few minutes after the
|
|
114
|
+
* record is written. */
|
|
115
|
+
placeholder?: string;
|
|
110
116
|
};
|
|
111
117
|
export type SearchResponse<T> = {
|
|
112
118
|
hits: SearchHit<T>[];
|
|
@@ -236,6 +242,7 @@ export type RecommendationHit<T> = {
|
|
|
236
242
|
id: string;
|
|
237
243
|
score: number | null;
|
|
238
244
|
record: T;
|
|
245
|
+
placeholder?: string;
|
|
239
246
|
};
|
|
240
247
|
/** A Bought together pick: `count` is the orders in the last year that had both products. */
|
|
241
248
|
export type TogetherHit<T> = RecommendationHit<T> & {
|
|
@@ -265,6 +272,7 @@ export type ProductList<T = Record<string, unknown>> = {
|
|
|
265
272
|
hits: {
|
|
266
273
|
id: string;
|
|
267
274
|
record: T;
|
|
275
|
+
placeholder?: string;
|
|
268
276
|
}[];
|
|
269
277
|
/** The list's filters and sort, for a "See all" link to the same products as a search. */
|
|
270
278
|
browse: {
|
|
@@ -412,12 +420,22 @@ export declare class SearchBrowserClient {
|
|
|
412
420
|
readonly recentSearches: RecentSearches;
|
|
413
421
|
private popular;
|
|
414
422
|
private test;
|
|
423
|
+
/** The hosts the index's images may be loaded from resized, from the API's last answer (x-findlane-images). */
|
|
424
|
+
private imageHosts;
|
|
415
425
|
constructor(options: BrowserClientOptions);
|
|
416
426
|
/** The signed key searches send: the one given, or the function's, asked for again 30 seconds before it
|
|
417
427
|
* expires, or at once when `fresh`. */
|
|
418
428
|
private signedKey;
|
|
419
429
|
private post;
|
|
420
430
|
private get;
|
|
431
|
+
/** Each answer says which hosts the index's images may be loaded from resized; refusals say nothing. */
|
|
432
|
+
private noteImages;
|
|
433
|
+
/** Optimized images (0.27.0): a record image's address, resized to `width` pixels (rounded up to one of
|
|
434
|
+
* `imageWidths`) and sent as WebP from the API's own address, when the index has optimized images on and the
|
|
435
|
+
* image is on a host it allows; otherwise `src` as it is. Known from the first answer on, so build image
|
|
436
|
+
* addresses from results, not before the first search. Load them with `crossorigin="anonymous"`, which
|
|
437
|
+
* shares the connection searches use. React's `Image` does all of this. */
|
|
438
|
+
imageUrl(src: string, width: number): string;
|
|
421
439
|
/** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
|
|
422
440
|
* would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. */
|
|
423
441
|
warm(): void;
|
|
@@ -465,4 +483,3 @@ export declare class SearchBrowserClient {
|
|
|
465
483
|
* for are left out. Without IDs, all of its lists, in the owner's order. Not counted as searches. */
|
|
466
484
|
lists<T = Record<string, unknown>>(ids?: string[], options?: ListOptions): Promise<List<T>[]>;
|
|
467
485
|
}
|
|
468
|
-
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { imageHostsHeader, imageHostsOf, optimizedImageUrl } from "./images.js";
|
|
2
|
+
export { imageWidth, imageWidths } from "./images.js";
|
|
3
|
+
export { placeholderUrl } from "./placeholder.js";
|
|
1
4
|
/** A query suggestion's text in parts: what was typed (`typed: true`) and the rest. */
|
|
2
5
|
export function suggestionParts(suggestion) {
|
|
3
6
|
const [start, end] = suggestion.typed ?? [0, 0];
|
|
@@ -285,6 +288,8 @@ export class SearchBrowserClient {
|
|
|
285
288
|
recentSearches;
|
|
286
289
|
popular = new Map();
|
|
287
290
|
test;
|
|
291
|
+
/** The hosts the index's images may be loaded from resized, from the API's last answer (x-findlane-images). */
|
|
292
|
+
imageHosts = new Set();
|
|
288
293
|
constructor(options) {
|
|
289
294
|
if (!/^pub_[a-f0-9]{32}$/.test(options.publicId))
|
|
290
295
|
throw new Error("A valid public index ID (pub_…) is required");
|
|
@@ -324,6 +329,7 @@ export class SearchBrowserClient {
|
|
|
324
329
|
body: JSON.stringify(signing ? { ...request, signedKey: await signing } : request),
|
|
325
330
|
signal,
|
|
326
331
|
});
|
|
332
|
+
this.noteImages(response);
|
|
327
333
|
const data = await response.json();
|
|
328
334
|
if (!response.ok) {
|
|
329
335
|
if (signing && !renewed && response.status === 401 && data.expired && typeof this.signer == "function")
|
|
@@ -336,11 +342,25 @@ export class SearchBrowserClient {
|
|
|
336
342
|
async get(path, params, signal) {
|
|
337
343
|
const query = new URLSearchParams(params).toString();
|
|
338
344
|
const response = await this.fetcher(`${this.url}/${path}${query ? `?${query}` : ""}`, { method: "GET", signal });
|
|
345
|
+
this.noteImages(response);
|
|
339
346
|
const data = await response.json();
|
|
340
347
|
if (!response.ok)
|
|
341
348
|
throw new FindlaneError(response.status, data.error ?? `HTTP ${response.status}`);
|
|
342
349
|
return data;
|
|
343
350
|
}
|
|
351
|
+
/** Each answer says which hosts the index's images may be loaded from resized; refusals say nothing. */
|
|
352
|
+
noteImages(response) {
|
|
353
|
+
if (response.ok)
|
|
354
|
+
this.imageHosts = imageHostsOf(response.headers?.get(imageHostsHeader));
|
|
355
|
+
}
|
|
356
|
+
/** Optimized images (0.27.0): a record image's address, resized to `width` pixels (rounded up to one of
|
|
357
|
+
* `imageWidths`) and sent as WebP from the API's own address, when the index has optimized images on and the
|
|
358
|
+
* image is on a host it allows; otherwise `src` as it is. Known from the first answer on, so build image
|
|
359
|
+
* addresses from results, not before the first search. Load them with `crossorigin="anonymous"`, which
|
|
360
|
+
* shares the connection searches use. React's `Image` does all of this. */
|
|
361
|
+
imageUrl(src, width) {
|
|
362
|
+
return optimizedImageUrl(this.origin, this.publicId, this.imageHosts, src, width) ?? src;
|
|
363
|
+
}
|
|
344
364
|
/** Opens the connection to the API before the first search needs it, as a preconnect hint in the page
|
|
345
365
|
* would: call it when the shopper focuses a search box. Once per page; nothing outside a browser. */
|
|
346
366
|
warm() {
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** A hit's `placeholder` (a ThumbHash in base64) drawn as a PNG data URL, about 32 pixels on its longer side, to show
|
|
2
|
+
* stretched to the image's box while the image loads; null for one that can't be read. */
|
|
3
|
+
export declare function placeholderUrl(placeholder: string | null | undefined): string | null;
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
// Image placeholders (0.27.0): a hit's `placeholder`, a ThumbHash of its image, drawn as a small PNG to show while the
|
|
2
|
+
// image loads. The decoding below is ThumbHash's own (https://github.com/evanw/thumbhash, thumbHashToRGBA and
|
|
3
|
+
// rgbaToDataURL), typed:
|
|
4
|
+
//
|
|
5
|
+
// Copyright (c) 2023 Evan Wallace
|
|
6
|
+
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
|
|
7
|
+
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
|
|
8
|
+
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
|
|
9
|
+
// to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above
|
|
10
|
+
// copyright notice and this permission notice shall be included in all copies or substantial portions of the
|
|
11
|
+
// Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. (MIT License)
|
|
12
|
+
function thumbHashToRGBA(hash) {
|
|
13
|
+
const { PI, min, max, cos, round } = Math;
|
|
14
|
+
const header24 = hash[0] | (hash[1] << 8) | (hash[2] << 16);
|
|
15
|
+
const header16 = hash[3] | (hash[4] << 8);
|
|
16
|
+
const l_dc = (header24 & 63) / 63;
|
|
17
|
+
const p_dc = ((header24 >> 6) & 63) / 31.5 - 1;
|
|
18
|
+
const q_dc = ((header24 >> 12) & 63) / 31.5 - 1;
|
|
19
|
+
const l_scale = ((header24 >> 18) & 31) / 31;
|
|
20
|
+
const hasAlpha = header24 >> 23;
|
|
21
|
+
const p_scale = ((header16 >> 3) & 63) / 63;
|
|
22
|
+
const q_scale = ((header16 >> 9) & 63) / 63;
|
|
23
|
+
const isLandscape = header16 >> 15;
|
|
24
|
+
const lx = max(3, isLandscape ? hasAlpha ? 5 : 7 : header16 & 7);
|
|
25
|
+
const ly = max(3, isLandscape ? header16 & 7 : hasAlpha ? 5 : 7);
|
|
26
|
+
const a_dc = hasAlpha ? (hash[5] & 15) / 15 : 1;
|
|
27
|
+
const a_scale = (hash[5] >> 4) / 15;
|
|
28
|
+
// The varying factors, saturation boosted 1.25 times to make up for quantization.
|
|
29
|
+
const ac_start = hasAlpha ? 6 : 5;
|
|
30
|
+
let ac_index = 0;
|
|
31
|
+
const decodeChannel = (nx, ny, scale) => {
|
|
32
|
+
const ac = [];
|
|
33
|
+
for (let cy = 0; cy < ny; cy++)
|
|
34
|
+
for (let cx = cy ? 0 : 1; cx * ny < nx * (ny - cy); cx++)
|
|
35
|
+
ac.push((((hash[ac_start + (ac_index >> 1)] >> ((ac_index++ & 1) << 2)) & 15) / 7.5 - 1) * scale);
|
|
36
|
+
return ac;
|
|
37
|
+
};
|
|
38
|
+
const l_ac = decodeChannel(lx, ly, l_scale);
|
|
39
|
+
const p_ac = decodeChannel(3, 3, p_scale * 1.25);
|
|
40
|
+
const q_ac = decodeChannel(3, 3, q_scale * 1.25);
|
|
41
|
+
const a_ac = hasAlpha ? decodeChannel(5, 5, a_scale) : [];
|
|
42
|
+
const ratio = aspectRatio(hash);
|
|
43
|
+
const w = round(ratio > 1 ? 32 : 32 * ratio);
|
|
44
|
+
const h = round(ratio > 1 ? 32 / ratio : 32);
|
|
45
|
+
const rgba = new Uint8Array(w * h * 4);
|
|
46
|
+
const fx = [];
|
|
47
|
+
const fy = [];
|
|
48
|
+
for (let y = 0, i = 0; y < h; y++) {
|
|
49
|
+
for (let x = 0; x < w; x++, i += 4) {
|
|
50
|
+
let l = l_dc, p = p_dc, q = q_dc, a = a_dc;
|
|
51
|
+
for (let cx = 0, n = max(lx, hasAlpha ? 5 : 3); cx < n; cx++)
|
|
52
|
+
fx[cx] = cos(PI / w * (x + 0.5) * cx);
|
|
53
|
+
for (let cy = 0, n = max(ly, hasAlpha ? 5 : 3); cy < n; cy++)
|
|
54
|
+
fy[cy] = cos(PI / h * (y + 0.5) * cy);
|
|
55
|
+
for (let cy = 0, j = 0; cy < ly; cy++)
|
|
56
|
+
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx * ly < lx * (ly - cy); cx++, j++)
|
|
57
|
+
l += l_ac[j] * fx[cx] * fy2;
|
|
58
|
+
for (let cy = 0, j = 0; cy < 3; cy++) {
|
|
59
|
+
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 3 - cy; cx++, j++) {
|
|
60
|
+
const f = fx[cx] * fy2;
|
|
61
|
+
p += p_ac[j] * f;
|
|
62
|
+
q += q_ac[j] * f;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (hasAlpha)
|
|
66
|
+
for (let cy = 0, j = 0; cy < 5; cy++)
|
|
67
|
+
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 5 - cy; cx++, j++)
|
|
68
|
+
a += a_ac[j] * fx[cx] * fy2;
|
|
69
|
+
const b = l - 2 / 3 * p;
|
|
70
|
+
const r = (3 * l - b + q) / 2;
|
|
71
|
+
const g = r - q;
|
|
72
|
+
rgba[i] = max(0, 255 * min(1, r));
|
|
73
|
+
rgba[i + 1] = max(0, 255 * min(1, g));
|
|
74
|
+
rgba[i + 2] = max(0, 255 * min(1, b));
|
|
75
|
+
rgba[i + 3] = max(0, 255 * min(1, a));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return { w, h, rgba };
|
|
79
|
+
}
|
|
80
|
+
function aspectRatio(hash) {
|
|
81
|
+
const header = hash[3];
|
|
82
|
+
const hasAlpha = hash[2] & 0x80;
|
|
83
|
+
const isLandscape = hash[4] & 0x80;
|
|
84
|
+
const lx = isLandscape ? hasAlpha ? 5 : 7 : header & 7;
|
|
85
|
+
const ly = isLandscape ? header & 7 : hasAlpha ? 5 : 7;
|
|
86
|
+
return lx / ly;
|
|
87
|
+
}
|
|
88
|
+
const crcTable = [0, 498536548, 997073096, 651767980, 1994146192, 1802195444, 1303535960, 1342533948, -306674912, -267414716,
|
|
89
|
+
-690576408, -882789492, -1687895376, -2032938284, -1609899400, -1111625188];
|
|
90
|
+
/** An uncompressed PNG of the pixels, as a data URL. */
|
|
91
|
+
function rgbaToDataURL(w, h, rgba) {
|
|
92
|
+
const row = w * 4 + 1;
|
|
93
|
+
const idat = 6 + h * (5 + row);
|
|
94
|
+
const bytes = [137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0, w >> 8, w & 255, 0, 0, h >> 8, h & 255, 8, 6, 0, 0, 0,
|
|
95
|
+
0, 0, 0, 0, idat >>> 24, (idat >> 16) & 255, (idat >> 8) & 255, idat & 255, 73, 68, 65, 84, 120, 1];
|
|
96
|
+
let a = 1, b = 0;
|
|
97
|
+
for (let y = 0, i = 0, end = row - 1; y < h; y++, end += row - 1) {
|
|
98
|
+
bytes.push(y + 1 < h ? 0 : 1, row & 255, row >> 8, ~row & 255, (row >> 8) ^ 255, 0);
|
|
99
|
+
for (b = (b + a) % 65521; i < end; i++) {
|
|
100
|
+
const u = rgba[i] & 255;
|
|
101
|
+
bytes.push(u);
|
|
102
|
+
a = (a + u) % 65521;
|
|
103
|
+
b = (b + a) % 65521;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
bytes.push(b >> 8, b & 255, a >> 8, a & 255, 0, 0, 0, 0, 0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130);
|
|
107
|
+
for (let [start, end] of [[12, 29], [37, 41 + idat]]) {
|
|
108
|
+
let c = ~0;
|
|
109
|
+
for (let i = start; i < end; i++) {
|
|
110
|
+
c ^= bytes[i];
|
|
111
|
+
c = (c >>> 4) ^ crcTable[c & 15];
|
|
112
|
+
c = (c >>> 4) ^ crcTable[c & 15];
|
|
113
|
+
}
|
|
114
|
+
c = ~c;
|
|
115
|
+
bytes[end++] = c >>> 24;
|
|
116
|
+
bytes[end++] = (c >> 16) & 255;
|
|
117
|
+
bytes[end++] = (c >> 8) & 255;
|
|
118
|
+
bytes[end++] = c & 255;
|
|
119
|
+
}
|
|
120
|
+
let binary = "";
|
|
121
|
+
for (const byte of bytes)
|
|
122
|
+
binary += String.fromCharCode(byte);
|
|
123
|
+
return "data:image/png;base64," + btoa(binary);
|
|
124
|
+
}
|
|
125
|
+
/** Placeholders drawn already, by hash: a page shows the same few dozen again as the shopper types. */
|
|
126
|
+
const drawn = new Map();
|
|
127
|
+
const drawnLimit = 500;
|
|
128
|
+
/** A hit's `placeholder` (a ThumbHash in base64) drawn as a PNG data URL, about 32 pixels on its longer side, to show
|
|
129
|
+
* stretched to the image's box while the image loads; null for one that can't be read. */
|
|
130
|
+
export function placeholderUrl(placeholder) {
|
|
131
|
+
if (!placeholder)
|
|
132
|
+
return null;
|
|
133
|
+
const known = drawn.get(placeholder);
|
|
134
|
+
if (known !== undefined)
|
|
135
|
+
return known;
|
|
136
|
+
let url = null;
|
|
137
|
+
try {
|
|
138
|
+
const binary = atob(placeholder);
|
|
139
|
+
const hash = Uint8Array.from(binary, (char) => char.charCodeAt(0));
|
|
140
|
+
if (hash.length >= 5 && hash.length <= 48) {
|
|
141
|
+
const { w, h, rgba } = thumbHashToRGBA(hash);
|
|
142
|
+
if (w > 0 && h > 0)
|
|
143
|
+
url = rgbaToDataURL(w, h, rgba);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
catch {
|
|
147
|
+
url = null;
|
|
148
|
+
}
|
|
149
|
+
if (drawn.size >= drawnLimit)
|
|
150
|
+
drawn.delete(drawn.keys().next().value);
|
|
151
|
+
drawn.set(placeholder, url);
|
|
152
|
+
return url;
|
|
153
|
+
}
|
package/dist/react/client.d.ts
CHANGED
|
@@ -12,4 +12,6 @@ export type ClientOptions = {
|
|
|
12
12
|
export declare function FindlaneProvider({ children, ...options }: ClientOptions & Pick<BrowserClientOptions, "signedKey"> & {
|
|
13
13
|
children: ReactNode;
|
|
14
14
|
}): import("react").JSX.Element;
|
|
15
|
+
/** The FindlaneProvider's client, or null outside one. */
|
|
16
|
+
export declare function useProvidedClient(): SearchBrowserClient | null;
|
|
15
17
|
export declare function useClient(options?: ClientOptions): SearchBrowserClient;
|
package/dist/react/client.js
CHANGED
|
@@ -21,6 +21,10 @@ export function FindlaneProvider({ children, ...options }) {
|
|
|
21
21
|
throw new Error("FindlaneProvider needs a publicId or a client");
|
|
22
22
|
return _jsx(ClientContext.Provider, { value: client, children: children });
|
|
23
23
|
}
|
|
24
|
+
/** The FindlaneProvider's client, or null outside one. */
|
|
25
|
+
export function useProvidedClient() {
|
|
26
|
+
return useContext(ClientContext);
|
|
27
|
+
}
|
|
24
28
|
export function useClient(options = {}) {
|
|
25
29
|
const own = useOwnClient(options);
|
|
26
30
|
const provided = useContext(ClientContext);
|
|
@@ -3,9 +3,12 @@ import { type Banner, type DidYouMean as Correction } 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";
|
|
6
|
-
/** A hit's image and title, for records with `image` and `title` (or `name`) fields.
|
|
7
|
-
|
|
6
|
+
/** A hit's image and title, for records with `image` and `title` (or `name`) fields. The image is resized to
|
|
7
|
+
* `imageWidth` (40 pixels, as styles.css shows it) when the index has optimized images on, with its placeholder
|
|
8
|
+
* shown until it loads. */
|
|
9
|
+
export declare function DefaultHit<T>({ hit, imageWidth }: {
|
|
8
10
|
hit: Hit<T>;
|
|
11
|
+
imageWidth?: number;
|
|
9
12
|
}): import("react").JSX.Element;
|
|
10
13
|
export type SearchBoxProps<T> = AutocompleteOptions<T> & {
|
|
11
14
|
placeholder?: string;
|
package/dist/react/components.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
3
|
import { useState } from "react";
|
|
4
4
|
import { Highlight } from "./highlight.js";
|
|
5
|
+
import { Image, ImageClient } from "./image.js";
|
|
5
6
|
import { messageFor } from "./messages.js";
|
|
6
7
|
import { suggestionParts } from "../index.js";
|
|
7
8
|
import { useCurrentRefinements, useDidYouMean, useHits, useLoadMore, useRefinementList, useSearchBox, useSortBy, } from "./search-provider.js";
|
|
@@ -9,12 +10,14 @@ import { useAutocomplete } from "./use-autocomplete.js";
|
|
|
9
10
|
// The components render plain elements marked with data-findlane-* attributes and no styles of
|
|
10
11
|
// their own; styles.css gives them a default look.
|
|
11
12
|
const number = (value) => value.toLocaleString("en-US");
|
|
12
|
-
/** A hit's image and title, for records with `image` and `title` (or `name`) fields.
|
|
13
|
-
|
|
13
|
+
/** A hit's image and title, for records with `image` and `title` (or `name`) fields. The image is resized to
|
|
14
|
+
* `imageWidth` (40 pixels, as styles.css shows it) when the index has optimized images on, with its placeholder
|
|
15
|
+
* shown until it loads. */
|
|
16
|
+
export function DefaultHit({ hit, imageWidth = 40 }) {
|
|
14
17
|
const record = (hit.record ?? {});
|
|
15
18
|
const image = typeof record.image === "string" ? record.image : null;
|
|
16
19
|
const field = ["title", "name"].find((name) => name in record || hit.highlights?.[name] !== undefined);
|
|
17
|
-
return (_jsxs(_Fragment, { children: [image && _jsx(
|
|
20
|
+
return (_jsxs(_Fragment, { children: [image && _jsx(Image, { src: image, width: imageWidth, placeholder: hit.placeholder, "data-findlane-image": "" }), _jsx("span", { "data-findlane-title": "", children: field ? _jsx(Highlight, { hit: hit, field: field }) : hit.id })] }));
|
|
18
21
|
}
|
|
19
22
|
const defaultLabels = { recent: "Recent searches", popular: "Popular searches", suggestions: "Searches",
|
|
20
23
|
results: "Results", clear: "Clear", remove: "Remove" };
|
|
@@ -62,11 +65,11 @@ export function Suggestions({ box, label, action, renderHit, renderSubindexHit,
|
|
|
62
65
|
? suggestionParts(item).map((part, at) => part.typed ? _jsx("span", { children: part.text }, at) : _jsx("b", { children: part.text }, at))
|
|
63
66
|
: item.q }), item.kind === "recent" && (_jsx("button", { type: "button", tabIndex: -1, "aria-label": `${text.remove} ${item.q}`, "data-findlane-remove": "", onClick: (event) => { event.stopPropagation(); box.removeRecent(item.q); }, children: "\u00D7" }))] }, `${item.kind}:${item.q}`));
|
|
64
67
|
};
|
|
65
|
-
return (_jsxs("div", { "data-findlane-panel": "", children: [error ? _jsx("p", { "data-findlane-note": "", children: messageFor(error) }) : null, items.length > 0 && (_jsx("div", { ...box.getListboxProps({ "aria-label": label }), children: sections.map((section) => {
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
68
|
+
return (_jsx(ImageClient, { client: box.client, children: _jsxs("div", { "data-findlane-panel": "", children: [error ? _jsx("p", { "data-findlane-note": "", children: messageFor(error) }) : null, items.length > 0 && (_jsx("div", { ...box.getListboxProps({ "aria-label": label }), children: sections.map((section) => {
|
|
69
|
+
const titled = section.kind !== "hit" || sections.length > 1;
|
|
70
|
+
const headingId = `${box.getListboxProps().id}-${section.key}`;
|
|
71
|
+
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` }))] }) }));
|
|
70
73
|
}
|
|
71
74
|
/** A search box that suggests results as visitors type. Works on its own with a `publicId`. */
|
|
72
75
|
export function SearchBox({ placeholder, label = "Search", action, renderHit, renderSubindexHit, empty, seeAll, labels, className, autoFocus, ...options }) {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { type ImgHTMLAttributes, type ReactNode } from "react";
|
|
2
|
+
import type { SearchBrowserClient } from "../index.js";
|
|
3
|
+
/** The client the Images inside show their index's images for: SearchProvider, SearchBox and Recommendations
|
|
4
|
+
* give theirs, which may not be a FindlaneProvider's. */
|
|
5
|
+
export declare function ImageClient({ client, children }: {
|
|
6
|
+
client: SearchBrowserClient;
|
|
7
|
+
children: ReactNode;
|
|
8
|
+
}): import("react").JSX.Element;
|
|
9
|
+
export type ImageProps = Omit<ImgHTMLAttributes<HTMLImageElement>, "src" | "srcSet" | "width" | "crossOrigin"> & {
|
|
10
|
+
/** The image's address, such as a hit's `record.image`. Nothing is shown without one. */
|
|
11
|
+
src: string | null | undefined;
|
|
12
|
+
/** The width it's shown at, in CSS pixels. It's resized to this, and to twice this for sharp screens. */
|
|
13
|
+
width: number;
|
|
14
|
+
/** The client whose index the image is from: by default the surrounding SearchProvider's, SearchBox's or
|
|
15
|
+
* Recommendations', else the FindlaneProvider's. */
|
|
16
|
+
client?: SearchBrowserClient;
|
|
17
|
+
/** The hit's `placeholder`: a soft preview of the image, shown behind it until it loads, fitted as
|
|
18
|
+
* `object-fit: contain` fits the image (set `backgroundSize` in `style` for another fit). */
|
|
19
|
+
placeholder?: string | null;
|
|
20
|
+
};
|
|
21
|
+
/** A record's image (0.27.0): resized to its width (and twice that for sharp screens) and sent as WebP when the
|
|
22
|
+
* index has optimized images on and the image is on a host it allows (SearchBrowserClient.imageUrl); otherwise
|
|
23
|
+
* the image as it is, with its placeholder behind it until it loads. Lazy by default; if the resized image fails
|
|
24
|
+
* to load, the original is loaded instead. */
|
|
25
|
+
export declare function Image({ src, width, client: given, placeholder, alt, loading, decoding, onError, onLoad, style, ...rest }: ImageProps): import("react").JSX.Element | null;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
|
+
import { createContext, useContext, useState } from "react";
|
|
4
|
+
import { placeholderUrl } from "../placeholder.js";
|
|
5
|
+
import { useProvidedClient } from "./client.js";
|
|
6
|
+
const ImageClientContext = createContext(null);
|
|
7
|
+
/** The client the Images inside show their index's images for: SearchProvider, SearchBox and Recommendations
|
|
8
|
+
* give theirs, which may not be a FindlaneProvider's. */
|
|
9
|
+
export function ImageClient({ client, children }) {
|
|
10
|
+
return _jsx(ImageClientContext.Provider, { value: client, children: children });
|
|
11
|
+
}
|
|
12
|
+
/** A record's image (0.27.0): resized to its width (and twice that for sharp screens) and sent as WebP when the
|
|
13
|
+
* index has optimized images on and the image is on a host it allows (SearchBrowserClient.imageUrl); otherwise
|
|
14
|
+
* the image as it is, with its placeholder behind it until it loads. Lazy by default; if the resized image fails
|
|
15
|
+
* to load, the original is loaded instead. */
|
|
16
|
+
export function Image({ src, width, client: given, placeholder, alt = "", loading = "lazy", decoding = "async", onError, onLoad, style, ...rest }) {
|
|
17
|
+
const shown = useContext(ImageClientContext);
|
|
18
|
+
const provided = useProvidedClient();
|
|
19
|
+
const client = given ?? shown ?? provided;
|
|
20
|
+
// The address whose resized image didn't load: it shows as it is from then on.
|
|
21
|
+
const [failed, setFailed] = useState(null);
|
|
22
|
+
// The address that has loaded, whose placeholder is gone.
|
|
23
|
+
const [loaded, setLoaded] = useState(null);
|
|
24
|
+
if (!src)
|
|
25
|
+
return null;
|
|
26
|
+
const one = client && failed !== src ? client.imageUrl(src, width) : src;
|
|
27
|
+
const optimized = one !== src;
|
|
28
|
+
const two = optimized ? client.imageUrl(src, width * 2) : one;
|
|
29
|
+
const preview = loaded === one ? null : placeholderUrl(placeholder);
|
|
30
|
+
const behind = preview
|
|
31
|
+
? { backgroundImage: `url("${preview}")`, backgroundSize: "contain", backgroundPosition: "center", backgroundRepeat: "no-repeat" }
|
|
32
|
+
: undefined;
|
|
33
|
+
return (_jsx("img", { ...rest, src: one, srcSet: two !== one ? `${one} 1x, ${two} 2x` : undefined, width: width, alt: alt, loading: loading, decoding: decoding, style: behind ? { ...behind, ...style } : style,
|
|
34
|
+
// Searches are sent without credentials, so an image sent without them comes over the same connection.
|
|
35
|
+
crossOrigin: optimized ? "anonymous" : undefined,
|
|
36
|
+
// An image the browser had already shows at once, so its placeholder goes as soon as it's drawn.
|
|
37
|
+
ref: preview ? (node) => { if (node?.complete && node.naturalWidth)
|
|
38
|
+
setLoaded(one); } : undefined, onLoad: (event) => {
|
|
39
|
+
setLoaded(one);
|
|
40
|
+
onLoad?.(event);
|
|
41
|
+
}, onError: (event) => {
|
|
42
|
+
if (optimized)
|
|
43
|
+
setFailed(src);
|
|
44
|
+
onError?.(event);
|
|
45
|
+
} }));
|
|
46
|
+
}
|
package/dist/react/index.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export { SearchProvider, useCurrentRefinements, useDidYouMean, useGeoSearch, use
|
|
|
8
8
|
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, Hits, LoadMore, RefinementList, SearchBox, SearchInput, SortSelect, Stats, type HitsProps, type RefinementListProps, type SearchBoxProps, type SuggestionLabels, } from "./components.js";
|
|
9
9
|
export { SearchDialog, type SearchDialogProps } from "./dialog.js";
|
|
10
10
|
export { Highlight, Snippet, excerpt, highlightParts, type HighlightProps } from "./highlight.js";
|
|
11
|
+
export { Image, type ImageProps } from "./image.js";
|
|
11
12
|
export { messageFor } from "./messages.js";
|
|
12
13
|
export { emptyState, stateFromUrl, urlFromState, type Hit, type Near, type SearchConfig, type SearchState, type UrlParams, } from "./state.js";
|
|
13
14
|
export type { ServerResults, StateChange } from "./store.js";
|
package/dist/react/index.js
CHANGED
|
@@ -10,5 +10,6 @@ export { SearchProvider, useCurrentRefinements, useDidYouMean, useGeoSearch, use
|
|
|
10
10
|
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, Hits, LoadMore, RefinementList, SearchBox, SearchInput, SortSelect, Stats, } from "./components.js";
|
|
11
11
|
export { SearchDialog } from "./dialog.js";
|
|
12
12
|
export { Highlight, Snippet, excerpt, highlightParts } from "./highlight.js";
|
|
13
|
+
export { Image } from "./image.js";
|
|
13
14
|
export { messageFor } from "./messages.js";
|
|
14
15
|
export { emptyState, stateFromUrl, urlFromState, } from "./state.js";
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
3
|
import { useClient } from "./client.js";
|
|
4
4
|
import { DefaultHit, onLink } from "./components.js";
|
|
5
|
+
import { ImageClient } from "./image.js";
|
|
5
6
|
import { fillTemplate } from "./use-autocomplete.js";
|
|
6
7
|
import { useRecommendations } from "./use-recommendations.js";
|
|
7
8
|
const headings = { goesWith: "Goes well with", similar: "Similar products", together: "Frequently bought together" };
|
|
@@ -25,15 +26,15 @@ export function Recommendations({ objectID, list = "goesWith", fill, title, rend
|
|
|
25
26
|
return null;
|
|
26
27
|
// A heading that says what most of the list is.
|
|
27
28
|
const heading = title === undefined ? headings[fill && own.length * 2 < items.length ? fill : list] : title;
|
|
28
|
-
return (_jsxs("section", { className: className, "data-findlane-recommendations": list, children: [heading !== null && _jsx("h2", { "data-findlane-recommendations-title": "", children: heading }), _jsx("ol", { "data-findlane-hits": "", children: items.map(({ hit, source }, index) => {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
29
|
+
return (_jsx(ImageClient, { client: client, children: _jsxs("section", { className: className, "data-findlane-recommendations": list, children: [heading !== null && _jsx("h2", { "data-findlane-recommendations-title": "", children: heading }), _jsx("ol", { "data-findlane-hits": "", children: items.map(({ hit, source }, index) => {
|
|
30
|
+
const href = getHref ? getHref(hit) : hrefTemplate ? fillTemplate(hrefTemplate, hit) : undefined;
|
|
31
|
+
const content = render ? render(hit, index) : _jsx(DefaultHit, { hit: hit, imageWidth: 240 });
|
|
32
|
+
// A click, and a middle click that opens the link in a new tab.
|
|
33
|
+
const clicked = (event) => {
|
|
34
|
+
if (!event.defaultPrevented && onLink(event))
|
|
35
|
+
client.events.click(hit.id, { list: source, from: objectID, position: index + 1 });
|
|
36
|
+
};
|
|
37
|
+
return (_jsx("li", { "data-findlane-source": source, onClick: clicked, onAuxClick: (event) => { if (event.button === 1)
|
|
38
|
+
clicked(event); }, children: href ? _jsx("a", { href: href, "data-findlane-link": "", children: content }) : content }, hit.id));
|
|
39
|
+
}) })] }) }));
|
|
39
40
|
}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { jsx as _jsx } from "react/jsx-runtime";
|
|
3
3
|
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useState, useSyncExternalStore, } from "react";
|
|
4
4
|
import { useClient } from "./client.js";
|
|
5
|
+
import { ImageClient } from "./image.js";
|
|
5
6
|
import { SearchStore } from "./store.js";
|
|
6
7
|
import { canonical, emptyState, isRange, maxOffset, stateFromUrl, urlFromState, } from "./state.js";
|
|
7
8
|
const StoreContext = createContext(null);
|
|
@@ -49,7 +50,7 @@ export function SearchProvider(props) {
|
|
|
49
50
|
store.adopt(state);
|
|
50
51
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
51
52
|
}, [store, stateKey]);
|
|
52
|
-
return _jsx(StoreContext.Provider, { value: store, children: children });
|
|
53
|
+
return _jsx(StoreContext.Provider, { value: store, children: _jsx(ImageClient, { client: client, children: children }) });
|
|
53
54
|
}
|
|
54
55
|
function useStore() {
|
|
55
56
|
const store = useContext(StoreContext);
|
|
@@ -83,6 +83,8 @@ export declare function fillTemplate<T>(template: string, hit: Hit<T>): string |
|
|
|
83
83
|
* suggestions, popular or recent searches on, `items` lists the searches before the results, and
|
|
84
84
|
* options are numbered across both. */
|
|
85
85
|
export declare function useAutocomplete<T = Record<string, unknown>>(options?: AutocompleteOptions<T>): {
|
|
86
|
+
/** The client searched, whose index the hits' images are from. */
|
|
87
|
+
client: import("../index.js").SearchBrowserClient;
|
|
86
88
|
query: string;
|
|
87
89
|
setQuery: (value: string) => void;
|
|
88
90
|
hits: import("../index.js").SearchHit<T>[];
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@findlane/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.27.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",
|