@findlane/browser 0.31.0 → 0.32.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 +7 -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 +3 -3
- package/dist/react/index.js +2 -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/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -68,9 +68,13 @@ export type SearchRequest = {
|
|
|
68
68
|
subindexes?: Record<string, SubindexSearch | true>;
|
|
69
69
|
/** The facet values the query names, such as a category, a brand or a zip, to offer beside the results
|
|
70
70
|
* (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.
|
|
71
|
+
* They come back in `facetMatches`, in the same search. With the setting's `apply`, a match that names a value
|
|
72
|
+
* exactly filters this search (`applied`, and `rewrittenQuery` says which words were searched), so show that
|
|
73
|
+
* it did. `apply` chooses for this search instead (0.32.0): `"never"` for a dropdown, or a filter the shopper
|
|
74
|
+
* took away. */
|
|
72
75
|
facetMatches?: boolean | {
|
|
73
76
|
fields?: string[];
|
|
77
|
+
apply?: "never" | "whole" | "exact";
|
|
74
78
|
};
|
|
75
79
|
};
|
|
76
80
|
/** A subindex's own search, in a search that asks for it. */
|
|
@@ -185,7 +189,8 @@ export type SearchResponse<T> = {
|
|
|
185
189
|
* - `whole`: it took every word of the query. `typed`: where those words are in `q`, as UTF-16 offsets (end
|
|
186
190
|
* exclusive), so they can be set apart.
|
|
187
191
|
* - `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;
|
|
192
|
+
* - `applied`: whether this search used the filter itself (0.32.0); its words are then left out of what was
|
|
193
|
+
* searched, as `rewrittenQuery` says. */
|
|
189
194
|
export type FacetMatch = {
|
|
190
195
|
field: string;
|
|
191
196
|
values: string[];
|
|
@@ -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,11 @@
|
|
|
1
1
|
export { FindlaneProvider, useClient, type ClientOptions } from "./client.js";
|
|
2
2
|
export { useSearch, type UseSearchOptions, type UseSearchResult } from "./use-search.js";
|
|
3
|
-
export { useAutocomplete, type AutocompleteItem, type AutocompleteOptions, type AutocompleteSubindex } from "./use-autocomplete.js";
|
|
3
|
+
export { useAutocomplete, type AutocompleteFacetMatchField, type AutocompleteItem, type AutocompleteOptions, type AutocompleteSubindex } from "./use-autocomplete.js";
|
|
4
4
|
export { useRecommendations, type UseRecommendationsOptions, type UseRecommendationsResult } from "./use-recommendations.js";
|
|
5
5
|
export { Recommendations, type RecommendationsProps } from "./recommendations.js";
|
|
6
6
|
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";
|
|
7
|
+
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";
|
|
8
|
+
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
9
|
export { SearchDialog, type SearchDialogProps } from "./dialog.js";
|
|
10
10
|
export { Highlight, Snippet, excerpt, highlightParts, type HighlightProps } from "./highlight.js";
|
|
11
11
|
export { Image, type ImageProps } from "./image.js";
|
package/dist/react/index.js
CHANGED
|
@@ -6,8 +6,8 @@ export { useAutocomplete } from "./use-autocomplete.js";
|
|
|
6
6
|
export { useRecommendations } from "./use-recommendations.js";
|
|
7
7
|
export { Recommendations } from "./recommendations.js";
|
|
8
8
|
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";
|
|
9
|
+
export { SearchProvider, useCurrentRefinements, useDidYouMean, useFacetMatches, useGeoSearch, useHits, useLoadMore, usePagination, useRange, useRefinementList, useSearchBox, useSearchState, useSortBy, useSubindex, useToggle, } from "./search-provider.js";
|
|
10
|
+
export { CurrentRefinements, DefaultBanner, DefaultHit, DidYouMean, FacetMatches, 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
13
|
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)
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@findlane/browser",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.32.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",
|