This repository has been archived by the owner on Dec 19, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InstantSearchProvider.tsx
323 lines (298 loc) · 10.9 KB
/
InstantSearchProvider.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
import { useSafeLayoutEffect } from '@chakra-ui/react';
import { ALGOLIA_APP_ID, IFIXIT_ORIGIN } from '@config/env';
import { CLIENT_OPTIONS } from '@helpers/algolia-helpers';
import {
destylizeDeviceItemType,
getFacetWidgetType,
isValidRefinementListValue,
stylizeDeviceItemType,
} from '@helpers/product-list-helpers';
import { useAuthenticatedUser } from '@ifixit/auth-sdk';
import { assertNever } from '@ifixit/helpers';
import { usePrevious } from '@ifixit/ui';
import { FacetWidgetType } from '@models/product-list';
import { useFacets } from '@templates/product-list/sections/FilterableProductsSection/facets/useFacets';
import algoliasearch from 'algoliasearch/lite';
import { history } from 'instantsearch.js/es/lib/routers';
import { RouterProps } from 'instantsearch.js/es/middlewares';
import { UiState } from 'instantsearch.js/es/types';
import { useRouter } from 'next/router';
import * as React from 'react';
import {
InstantSearch,
InstantSearchServerState,
InstantSearchSSRProvider,
} from 'react-instantsearch-hooks-web';
import { useSearchCache } from './useSearchCache';
type InstantSearchProviderProps = React.PropsWithChildren<AlgoliaProps>;
export type AlgoliaProps = {
url: string;
indexName: string;
serverState?: Partial<InstantSearchServerState>;
apiKey: string;
};
type RouteState = Partial<{
q: string;
p: number;
filter: Record<string, any>;
}>;
type IndexUiState = Record<string, any>;
export function InstantSearchProvider({
children,
url,
indexName,
serverState,
apiKey,
}: InstantSearchProviderProps) {
const user = useAuthenticatedUser();
const algoliaApiKey = user.data?.algoliaApiKeyProducts || apiKey;
const previousApiKey = usePrevious(algoliaApiKey);
const algoliaClient = React.useMemo(() => {
return algoliasearch(ALGOLIA_APP_ID, algoliaApiKey, CLIENT_OPTIONS);
}, [algoliaApiKey]);
const resetKey = useSearchStateForceResetKey();
const facets = useFacets();
const routing: RouterProps<UiState, RouteState> = {
stateMapping: {
stateToRoute(uiState) {
const indexUiState = uiState[indexName];
if (!indexUiState) {
return {};
}
const routeState: RouteState = {};
if (indexUiState.query) {
routeState.q = indexUiState.query;
}
if (indexUiState.page) {
routeState.p = indexUiState.page;
}
if (indexUiState.refinementList) {
routeState.filter = indexUiState.refinementList;
}
if (indexUiState.menu) {
routeState.filter = {
...routeState.filter,
...indexUiState.menu,
};
}
return routeState;
},
routeToState(routeState: RouteState) {
const stateObject: IndexUiState = {};
if (routeState.q != null) {
stateObject.query = routeState.q;
}
if (routeState.p != null) {
stateObject.page = routeState.p;
}
const filter = routeState.filter;
if (filter != null) {
stateObject.menu = {};
stateObject.refinementList = {};
Object.keys(filter).forEach((attribute) => {
const widgetType = getFacetWidgetType(attribute);
switch (widgetType) {
case FacetWidgetType.Menu: {
stateObject.menu[attribute] = filter[attribute];
break;
}
case FacetWidgetType.RefinementList: {
stateObject.refinementList[attribute] =
filter[attribute];
break;
}
default: {
return assertNever(widgetType);
}
}
});
}
return {
[indexName]: stateObject,
};
},
},
router: history({
getLocation() {
if (typeof window === 'undefined') {
return new URL(url) as unknown as Location;
}
return window.location;
},
createURL({ qsModule, routeState, location }) {
const baseUrl = getBaseOrigin(location);
const pathParts = location.pathname
.split('/')
.filter((part) => part !== '');
const partsOrTools = pathParts.length >= 1 ? pathParts[0] : '';
const deviceHandle = pathParts.length >= 2 ? pathParts[1] : '';
let path = '';
if (partsOrTools) {
path += `/${partsOrTools}`;
if (deviceHandle) {
path += `/${deviceHandle}`;
const raw: string | string[] | undefined =
routeState.filter?.['facet_tags.Item Type'];
const itemType = Array.isArray(raw) ? raw[0] : raw;
if (itemType?.length) {
const encodedItemType = encodeURIComponent(
stylizeDeviceItemType(itemType)
);
path += `/${encodedItemType}`;
}
}
}
const filterCopy = { ...routeState.filter };
if (partsOrTools && deviceHandle) {
// Item Type is the slug on device pages, not in the query.
delete filterCopy['facet_tags.Item Type'];
}
const { q, p, filter, ...otherParams } = qsModule.parse(
location.search,
{
ignoreQueryPrefix: true,
}
);
const queryString = qsModule.stringify(
{
...otherParams,
...routeState,
filter: filterCopy,
},
{
addQueryPrefix: true,
arrayFormat: 'indices',
}
);
return `${baseUrl}${path}${queryString}`;
},
parseURL({ qsModule, location }) {
const pathParts = location.pathname
.split('/')
.filter((part) => part !== '');
const deviceHandle = pathParts.length >= 2 ? pathParts[1] : '';
const itemType = pathParts.length >= 3 ? pathParts[2] : '';
const { q, p, filter } = qsModule.parse(location.search, {
ignoreQueryPrefix: true,
});
const filterObject =
typeof filter === 'object' && !Array.isArray(filter)
? filter
: {};
Object.entries(filterObject).forEach(([attribute, value]) => {
if (!facets.includes(attribute)) {
delete filterObject[attribute];
return;
}
const widgetType = getFacetWidgetType(attribute);
switch (widgetType) {
case FacetWidgetType.Menu: {
if (isValidRefinementListValue(value)) {
filterObject[attribute] = (value as string[])[0];
} else if (typeof value !== 'string') {
delete filterObject[attribute];
}
break;
}
case FacetWidgetType.RefinementList: {
if (!isValidRefinementListValue(value)) {
delete filterObject[attribute];
}
break;
}
default: {
return assertNever(widgetType);
}
}
});
if (deviceHandle && itemType) {
filterObject['facet_tags.Item Type'] = destylizeDeviceItemType(
decodeURIComponent(itemType)
).trim();
}
return {
q: String(q || ''),
p: typeof p === 'string' ? parseInt(p) : undefined,
filter: filterObject,
};
},
}),
};
return (
<InstantSearchSSRProvider {...serverState}>
<InstantSearch
searchClient={algoliaClient}
indexName={indexName}
routing={routing}
key={resetKey}
>
<RefreshSearchResults
apiKey={algoliaApiKey}
prevApiKey={previousApiKey}
/>
{children}
</InstantSearch>
</InstantSearchSSRProvider>
);
}
type RefreshSearchResultsProps = {
apiKey: string;
prevApiKey: string | undefined;
};
/**
* Refreshes search results if the API key changes
* (but only refreshes once for each api key change).
*/
function RefreshSearchResults({
apiKey,
prevApiKey,
}: RefreshSearchResultsProps): null {
const { refresh } = useSearchCache();
useSafeLayoutEffect(() => {
const isFirstRender = !prevApiKey;
const hasApiKeyChanged = prevApiKey !== apiKey;
if (hasApiKeyChanged && !isFirstRender) {
refresh();
}
}, [apiKey, prevApiKey]);
return null;
}
function getBaseOrigin(location: Location): string {
if (typeof window === 'undefined' && IFIXIT_ORIGIN) {
// On the server, use the IFIXIT_ORIGIN url
// This ensures that the SSR produces the correct links on Vercel
// (where the Host header doesn't match the page URL.)
const publicOrigin = new URL(IFIXIT_ORIGIN);
return publicOrigin.origin;
}
return location.origin;
}
const useSearchStateForceResetKey = () => {
const router = useRouter();
const historyChangeCount = React.useRef(0);
// Currently, Algolia routing does not play well with Next.js routing, since Next.js
// is not aware of url changes that happens without interacting with its builtin router.
// To make popstate work (i.e. whenever the browser back button is pressed), we do a
// a full page reload as a workaround.
// This should be only a temporary workaround until Algolia routing is fixed.
useSafeLayoutEffect(() => {
const handleRouteChange = () => {
// When the back button is pressed, the popstate event is fired, and
// Algolia tries to re-render the page (although in a broken state).
// To avoid seeing this broken re-render we hide the page while we wait for
// the page to be reloaded.
window.document.body.hidden = true;
window.location.reload();
};
const beforeHistoryChange = () => {
historyChangeCount.current++;
};
window.addEventListener('popstate', handleRouteChange);
router.events.on('beforeHistoryChange', beforeHistoryChange);
return () => {
window.removeEventListener('popstate', handleRouteChange);
router.events.off('beforeHistoryChange', beforeHistoryChange);
};
}, [router]);
return historyChangeCount.current;
};