-
Notifications
You must be signed in to change notification settings - Fork 499
/
connectMenu.ts
385 lines (341 loc) · 10 KB
/
connectMenu.ts
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import type { SearchResults } from 'algoliasearch-helper';
import type { SendEventForFacet } from '../../lib/utils';
import {
checkRendering,
createDocumentationMessageGenerator,
createSendEventForFacet,
noop,
} from '../../lib/utils';
import type {
Connector,
CreateURL,
RenderOptions,
SortBy,
TransformItems,
Widget,
WidgetRenderState,
} from '../../types';
const withUsage = createDocumentationMessageGenerator({
name: 'menu',
connector: true,
});
const DEFAULT_SORT = ['isRefined', 'name:asc'];
export type MenuItem = {
/**
* The value of the menu item.
*/
value: string;
/**
* Human-readable value of the menu item.
*/
label: string;
/**
* Number of results matched after refinement is applied.
*/
count: number;
/**
* Indicates if the refinement is applied.
*/
isRefined: boolean;
};
export type MenuConnectorParams = {
/**
* Name of the attribute for faceting (eg. "free_shipping").
*/
attribute: string;
/**
* How many facets values to retrieve.
*/
limit?: number;
/**
* Whether to display a button that expands the number of items.
*/
showMore?: boolean;
/**
* How many facets values to retrieve when `toggleShowMore` is called, this value is meant to be greater than `limit` option.
*/
showMoreLimit?: number;
/**
* How to sort refinements. Possible values: `count|isRefined|name:asc|name:desc`.
*
* You can also use a sort function that behaves like the standard Javascript [compareFunction](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#Syntax).
*
* If a facetOrdering is set in the index settings, it is used when sortBy isn't passed
*/
sortBy?: SortBy<SearchResults.HierarchicalFacet>;
/**
* Function to transform the items passed to the templates.
*/
transformItems?: TransformItems<MenuItem>;
};
export type MenuRenderState = {
/**
* The elements that can be refined for the current search results.
*/
items: MenuItem[];
/**
* Creates the URL for a single item name in the list.
*/
createURL: CreateURL<string>;
/**
* Filter the search to item value.
*/
refine(value: string): void;
/**
* True if refinement can be applied.
*/
canRefine: boolean;
/**
* True if the menu is displaying all the menu items.
*/
isShowingMore: boolean;
/**
* Toggles the number of values displayed between `limit` and `showMore.limit`.
*/
toggleShowMore(): void;
/**
* `true` if the toggleShowMore button can be activated (enough items to display more or
* already displaying more than `limit` items)
*/
canToggleShowMore: boolean;
/**
* Send event to insights middleware
*/
sendEvent: SendEventForFacet;
};
export type MenuWidgetDescription = {
$$type: 'ais.menu';
renderState: MenuRenderState;
indexRenderState: {
menu: {
[attribute: string]: WidgetRenderState<
MenuRenderState,
MenuConnectorParams
>;
};
};
indexUiState: {
menu: {
[attribute: string]: string;
};
};
};
export type MenuConnector = Connector<
MenuWidgetDescription,
MenuConnectorParams
>;
/**
* **Menu** connector provides the logic to build a widget that will give the user the ability to choose a single value for a specific facet. The typical usage of menu is for navigation in categories.
*
* This connector provides a `toggleShowMore()` function to display more or less items and a `refine()`
* function to select an item. While selecting a new element, the `refine` will also unselect the
* one that is currently selected.
*
* **Requirement:** the attribute passed as `attribute` must be present in "attributes for faceting" on the Algolia dashboard or configured as attributesForFaceting via a set settings call to the Algolia API.
*/
const connectMenu: MenuConnector = function connectMenu(
renderFn,
unmountFn = noop
) {
checkRendering(renderFn, withUsage());
return (widgetParams) => {
const {
attribute,
limit = 10,
showMore = false,
showMoreLimit = 20,
sortBy = DEFAULT_SORT,
transformItems = ((items) => items) as NonNullable<
MenuConnectorParams['transformItems']
>,
} = widgetParams || {};
if (!attribute) {
throw new Error(withUsage('The `attribute` option is required.'));
}
if (showMore === true && showMoreLimit <= limit) {
throw new Error(
withUsage('The `showMoreLimit` option must be greater than `limit`.')
);
}
type ThisWidget = Widget<
MenuWidgetDescription & { widgetParams: typeof widgetParams }
>;
let sendEvent: MenuRenderState['sendEvent'] | undefined;
let _createURL: MenuRenderState['createURL'] | undefined;
let _refine: MenuRenderState['refine'] | undefined;
// Provide the same function to the `renderFn` so that way the user
// has to only bind it once when `isFirstRendering` for instance
let isShowingMore = false;
let toggleShowMore = () => {};
function createToggleShowMore(
renderOptions: RenderOptions,
widget: ThisWidget
) {
return () => {
isShowingMore = !isShowingMore;
widget.render!(renderOptions);
};
}
function cachedToggleShowMore() {
toggleShowMore();
}
function getLimit() {
return isShowingMore ? showMoreLimit : limit;
}
return {
$$type: 'ais.menu' as const,
init(initOptions) {
const { instantSearchInstance } = initOptions;
renderFn(
{
...this.getWidgetRenderState(initOptions),
instantSearchInstance,
},
true
);
},
render(renderOptions) {
const { instantSearchInstance } = renderOptions;
renderFn(
{
...this.getWidgetRenderState(renderOptions),
instantSearchInstance,
},
false
);
},
dispose({ state }) {
unmountFn();
return state
.removeHierarchicalFacet(attribute)
.setQueryParameter('maxValuesPerFacet', undefined);
},
getRenderState(renderState, renderOptions) {
return {
...renderState,
menu: {
...renderState.menu,
[attribute]: this.getWidgetRenderState(renderOptions),
},
};
},
getWidgetRenderState(renderOptions) {
const { results, createURL, instantSearchInstance, helper } =
renderOptions;
let items: MenuRenderState['items'] = [];
let canToggleShowMore = false;
if (!sendEvent) {
sendEvent = createSendEventForFacet({
instantSearchInstance,
helper,
attribute,
widgetType: this.$$type,
});
}
if (!_createURL) {
_createURL = (facetValue: string) =>
createURL(
helper.state
.resetPage()
.toggleFacetRefinement(attribute, facetValue)
);
}
if (!_refine) {
_refine = function (facetValue: string) {
const [refinedItem] =
helper.getHierarchicalFacetBreadcrumb(attribute);
sendEvent!('click', facetValue ? facetValue : refinedItem);
helper
.toggleFacetRefinement(
attribute,
facetValue ? facetValue : refinedItem
)
.search();
};
}
if (renderOptions.results) {
toggleShowMore = createToggleShowMore(renderOptions, this);
}
if (results) {
const facetValues = results.getFacetValues(attribute, {
sortBy,
facetOrdering: sortBy === DEFAULT_SORT,
});
const facetItems =
facetValues && !Array.isArray(facetValues) && facetValues.data
? facetValues.data
: [];
canToggleShowMore =
showMore && (isShowingMore || facetItems.length > getLimit());
items = transformItems(
facetItems
.slice(0, getLimit())
.map(({ name: label, escapedValue: value, path, ...item }) => ({
...item,
label,
value,
})),
{ results }
);
}
return {
items,
createURL: _createURL,
refine: _refine,
sendEvent,
canRefine: items.length > 0,
widgetParams,
isShowingMore,
toggleShowMore: cachedToggleShowMore,
canToggleShowMore,
};
},
getWidgetUiState(uiState, { searchParameters }) {
const [value] =
searchParameters.getHierarchicalFacetBreadcrumb(attribute);
if (!value) {
return uiState;
}
return {
...uiState,
menu: {
...uiState.menu,
[attribute]: value,
},
};
},
getWidgetSearchParameters(searchParameters, { uiState }) {
const value = uiState.menu && uiState.menu[attribute];
const withFacetConfiguration = searchParameters
.removeHierarchicalFacet(attribute)
.addHierarchicalFacet({
name: attribute,
attributes: [attribute],
});
const currentMaxValuesPerFacet =
withFacetConfiguration.maxValuesPerFacet || 0;
const nextMaxValuesPerFacet = Math.max(
currentMaxValuesPerFacet,
showMore ? showMoreLimit : limit
);
const withMaxValuesPerFacet = withFacetConfiguration.setQueryParameter(
'maxValuesPerFacet',
nextMaxValuesPerFacet
);
if (!value) {
return withMaxValuesPerFacet.setQueryParameters({
hierarchicalFacetsRefinements: {
...withMaxValuesPerFacet.hierarchicalFacetsRefinements,
[attribute]: [],
},
});
}
return withMaxValuesPerFacet.addHierarchicalFacetRefinement(
attribute,
value
);
},
};
};
};
export default connectMenu;