@zengenti/contensis-react-base 3.3.1-beta.3 → 3.3.2-beta.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.
@@ -1,1996 +0,0 @@
1
- import * as log from 'loglevel';
2
- import { takeEvery, select, put, call, all } from '@redux-saga/core/effects';
3
- import { Client } from 'contensis-delivery-api';
4
- import { parse, stringify } from 'query-string';
5
- import mapJson, { jpath } from 'jsonpath-mapper';
6
- import { Op, OrderBy, Query } from 'contensis-core-api';
7
- import merge from 'deepmerge';
8
-
9
- const ACTION_PREFIX = '@SEARCH/';
10
- const APPLY_CONFIG = `${ACTION_PREFIX}APPLY_CONFIG`;
11
- const CLEAR_FILTERS = `${ACTION_PREFIX}CLEAR_FILTERS`;
12
- const DO_SEARCH = `${ACTION_PREFIX}DO_SEARCH`;
13
- const EXECUTE_SEARCH = `${ACTION_PREFIX}EXECUTE_SEARCH`;
14
- const EXECUTE_SEARCH_ERROR = `${ACTION_PREFIX}EXECUTE_SEARCH_ERROR`;
15
- const EXECUTE_SEARCH_PRELOAD = `${ACTION_PREFIX}EXECUTE_SEARCH_PRELOAD`;
16
- const LOAD_FILTERS = `${ACTION_PREFIX}LOAD_FILTERS`;
17
- const LOAD_FILTERS_COMPLETE = `${ACTION_PREFIX}LOAD_FILTERS_COMPLETE`;
18
- const LOAD_FILTERS_ERROR = `${ACTION_PREFIX}LOAD_FILTERS_ERROR`;
19
- const SET_FEATURED_ENTRIES = `${ACTION_PREFIX}SET_FEATURED_ENTRIES`;
20
- const SET_ROUTE_FILTERS = `${ACTION_PREFIX}SET_ROUTE_FILTERS`;
21
- const SET_SEARCH_FILTERS = `${ACTION_PREFIX}SET_SEARCH_FILTERS`;
22
- const SET_SEARCH_ENTRIES = `${ACTION_PREFIX}SET_SEARCH_ENTRIES`;
23
- const SET_SELECTED_FILTER = `${ACTION_PREFIX}SET_SELECTED_FILTER`;
24
- const UPDATE_CURRENT_FACET = `${ACTION_PREFIX}UPDATE_CURRENT_FACET`;
25
- const UPDATE_CURRENT_TAB = `${ACTION_PREFIX}UPDATE_CURRENT_TAB`;
26
- const UPDATE_SORT_ORDER = `${ACTION_PREFIX}UPDATE_SORT_ORDER`;
27
- const UPDATE_PAGE_INDEX = `${ACTION_PREFIX}UPDATE_PAGE_INDEX`;
28
- const UPDATE_PAGE_SIZE = `${ACTION_PREFIX}UPDATE_PAGE_SIZE`;
29
- const UPDATE_SEARCH_TERM = `${ACTION_PREFIX}UPDATE_SEARCH_TERM`;
30
- const UPDATE_SELECTED_FILTERS = `${ACTION_PREFIX}UPDATE_SELECTED_FILTERS`;
31
-
32
- var types = /*#__PURE__*/Object.freeze({
33
- __proto__: null,
34
- APPLY_CONFIG: APPLY_CONFIG,
35
- CLEAR_FILTERS: CLEAR_FILTERS,
36
- DO_SEARCH: DO_SEARCH,
37
- EXECUTE_SEARCH: EXECUTE_SEARCH,
38
- EXECUTE_SEARCH_ERROR: EXECUTE_SEARCH_ERROR,
39
- EXECUTE_SEARCH_PRELOAD: EXECUTE_SEARCH_PRELOAD,
40
- LOAD_FILTERS: LOAD_FILTERS,
41
- LOAD_FILTERS_COMPLETE: LOAD_FILTERS_COMPLETE,
42
- LOAD_FILTERS_ERROR: LOAD_FILTERS_ERROR,
43
- SET_FEATURED_ENTRIES: SET_FEATURED_ENTRIES,
44
- SET_ROUTE_FILTERS: SET_ROUTE_FILTERS,
45
- SET_SEARCH_ENTRIES: SET_SEARCH_ENTRIES,
46
- SET_SEARCH_FILTERS: SET_SEARCH_FILTERS,
47
- SET_SELECTED_FILTER: SET_SELECTED_FILTER,
48
- UPDATE_CURRENT_FACET: UPDATE_CURRENT_FACET,
49
- UPDATE_CURRENT_TAB: UPDATE_CURRENT_TAB,
50
- UPDATE_PAGE_INDEX: UPDATE_PAGE_INDEX,
51
- UPDATE_PAGE_SIZE: UPDATE_PAGE_SIZE,
52
- UPDATE_SEARCH_TERM: UPDATE_SEARCH_TERM,
53
- UPDATE_SELECTED_FILTERS: UPDATE_SELECTED_FILTERS,
54
- UPDATE_SORT_ORDER: UPDATE_SORT_ORDER
55
- });
56
-
57
- const withMappers = (action, mappers) => {
58
- return {
59
- ...action,
60
- mappers
61
- };
62
- };
63
- const triggerSearch = ({
64
- config,
65
- context,
66
- debug,
67
- defaultLang,
68
- excludeIds,
69
- facet,
70
- mapper,
71
- mappers,
72
- params
73
- }) => {
74
- return {
75
- type: DO_SEARCH,
76
- config,
77
- context,
78
- debug,
79
- defaultLang,
80
- excludeIds,
81
- facet,
82
- mapper,
83
- mappers,
84
- params
85
- };
86
- };
87
- const initListing = ({
88
- context,
89
- facet,
90
- mapper,
91
- params
92
- }) => {
93
- return {
94
- type: SET_ROUTE_FILTERS,
95
- context,
96
- facet,
97
- mapper,
98
- params
99
- };
100
- };
101
- const navigate = (path, state) => {
102
- return {
103
- type: '@ROUTING/_SET_ROUTE',
104
- path,
105
- state
106
- };
107
- };
108
- const clearFilters$1 = filterKey => {
109
- return {
110
- type: CLEAR_FILTERS,
111
- filterKey
112
- };
113
- };
114
- const updatePageIndex$1 = (pageIndex, scrollToElement) => {
115
- return {
116
- type: UPDATE_PAGE_INDEX,
117
- pageIndex,
118
- scrollToElement
119
- };
120
- };
121
- const updatePageSize$1 = (pageSize, scrollToElement) => {
122
- return {
123
- type: UPDATE_PAGE_SIZE,
124
- pageSize,
125
- scrollToElement
126
- };
127
- };
128
- const updateCurrentFacet$1 = facet => {
129
- return {
130
- type: UPDATE_CURRENT_FACET,
131
- facet
132
- };
133
- };
134
- const updateCurrentTab$1 = id => {
135
- return {
136
- type: UPDATE_CURRENT_TAB,
137
- id
138
- };
139
- };
140
- const updateSearchTerm$1 = term => {
141
- return {
142
- type: UPDATE_SEARCH_TERM,
143
- term
144
- };
145
- };
146
- const updateSelectedFilters = (filter, key, isUnknownItem = false, scrollToElement) => {
147
- return {
148
- type: UPDATE_SELECTED_FILTERS,
149
- filter,
150
- key,
151
- isUnknownItem,
152
- scrollToElement
153
- };
154
- };
155
- const updateSortOrder$1 = (orderBy, facet) => {
156
- return {
157
- type: UPDATE_SORT_ORDER,
158
- orderBy,
159
- facet
160
- };
161
- };
162
-
163
- var actions = /*#__PURE__*/Object.freeze({
164
- __proto__: null,
165
- clearFilters: clearFilters$1,
166
- initListing: initListing,
167
- navigate: navigate,
168
- triggerSearch: triggerSearch,
169
- updateCurrentFacet: updateCurrentFacet$1,
170
- updateCurrentTab: updateCurrentTab$1,
171
- updatePageIndex: updatePageIndex$1,
172
- updatePageSize: updatePageSize$1,
173
- updateSearchTerm: updateSearchTerm$1,
174
- updateSelectedFilters: updateSelectedFilters,
175
- updateSortOrder: updateSortOrder$1,
176
- withMappers: withMappers
177
- });
178
-
179
- let Context = /*#__PURE__*/function (Context) {
180
- Context["facets"] = "facets";
181
- Context["listings"] = "listings";
182
- Context["minilist"] = "minilist";
183
- return Context;
184
- }({});
185
- // export type Context = 'facets' | 'listings' | 'minilist';
186
-
187
- // Find a fromJS function from global that is dynamically loaded in createStore
188
- // or replace with a stub function for non-immutable gets
189
- const makeFromJS = (returnType = globalThis.STATE_TYPE || 'immutable') => {
190
- var _immutable, _immutable2;
191
- return returnType === 'immutable' ? ((_immutable = globalThis.immutable) === null || _immutable === void 0 ? void 0 : _immutable.fromJSOrdered) || ((_immutable2 = globalThis.immutable) === null || _immutable2 === void 0 ? void 0 : _immutable2.fromJS) || (v => v) : v => v;
192
- };
193
- const getImmutableOrJS = (state, stateKey, fallbackValue, returnType = globalThis.STATE_TYPE || 'immutable') => {
194
- // Find a fromJS function from global that is dynamically loaded in createStore
195
- // or replace with a stub function for non-immutable gets
196
- const fromJS = makeFromJS(returnType);
197
- if (state && 'get' in state && typeof state.get === 'function' && 'getIn' in state && typeof state.getIn === 'function' && 'toJS' in state && typeof state.toJS === 'function') {
198
- if (Array.isArray(stateKey)) return fromJS(state.getIn(stateKey, fallbackValue));
199
- return fromJS(state.get(stateKey, fallbackValue));
200
- }
201
- if (Array.isArray(stateKey) && state && typeof state === 'object') {
202
- const result = jpath(stateKey.join('.'), state);
203
- if (typeof result === 'undefined') return fallbackValue;
204
- return result;
205
- }
206
- const result = state && typeof state === 'object' ? state[stateKey] : undefined;
207
- if (typeof result === 'undefined') return fallbackValue;
208
- return result;
209
- };
210
-
211
- const getSearchContext = state => getImmutableOrJS(state, ['search', 'context'], Context.facets);
212
- const getCurrent = (state, context = Context.facets) => context === Context.facets ? getCurrentFacet(state) : getCurrentListing(state);
213
- const getCurrentFacet = state => getImmutableOrJS(state, ['search', 'currentFacet']);
214
- const getCurrentListing = state => getImmutableOrJS(state, ['search', 'currentListing']);
215
- const getCurrentTab = state => getImmutableOrJS(state, ['search', Context.facets, getCurrentFacet(state), 'tabId'], 0);
216
- const getFacets = (state, returnType) => getImmutableOrJS(state, ['search', Context.facets], {}, returnType);
217
- const getTabFacets = state => Object.fromEntries(Object.entries(getFacets(state, 'js')).filter(([key]) => getImmutableOrJS(getFacets(state), [key, 'tabId'], 0) === getCurrentTab(state)));
218
- const getFacetTitles = state => Object.entries(getFacets(state, 'js')).map(([key, facet = {}]) => {
219
- var _facet$pagingInfo;
220
- return {
221
- isSelected: getCurrentFacet(state) === key,
222
- key,
223
- title: facet.title,
224
- totalCount: (_facet$pagingInfo = facet.pagingInfo) === null || _facet$pagingInfo === void 0 ? void 0 : _facet$pagingInfo.totalCount
225
- };
226
- });
227
- const getFacet = (state, facetName = '', context = Context.facets, returnType) => {
228
- const currentFacet = facetName || getCurrentFacet(state);
229
- return getImmutableOrJS(state, ['search', context, currentFacet], {}, returnType);
230
- };
231
- const getListing = (state, listing = '') => {
232
- const currentListing = listing || getCurrentListing(state);
233
- return getImmutableOrJS(state, ['search', Context.listings, currentListing], {});
234
- };
235
- const getFilters = (state, facet, context = Context.facets, returnType) => {
236
- return getImmutableOrJS(state, ['search', context, facet || getCurrent(state, context), 'filters'], {}, returnType);
237
- };
238
- const getRenderableFilters = (state, facet = '', context = Context.facets) => Object.fromEntries(Object.entries(getFilters(state, facet, context, 'js')).filter(([, f = {}]) => typeof f.renderable !== 'boolean' ? true : f.renderable));
239
- const getFiltersToLoad = (state, facet, context = Context.facets, returnType) => {
240
- const filters = getFilters(state, facet, context, returnType);
241
- const loadedFilters = Object.entries(filters).map(([key, f = {}]) => [key, (f.items || []).filter(i => {
242
- const title = i === null || i === void 0 ? void 0 : i.title;
243
- return typeof title !== 'undefined' && !!title;
244
- }).length > 0 && (f.isError || false) === false]);
245
- return loadedFilters.map(([filterKey, isLoaded]) => !isLoaded ? filterKey : null).filter(f => !!f);
246
- };
247
-
248
- // We lowercase the filter key unless it's an ISO date string where the T must be uppercase
249
- const getSelectedFilters = (state, facet = '', context = Context.facets, returnType) => {
250
- const filters = getFilters(state, facet, context, 'js');
251
- const selectedFilters = Object.fromEntries(Object.entries(filters).map(([key, filter = {}]) => [key, (filter.items || []).filter(item => !!(item.isSelected || false)).map(item => {
252
- const key = (item === null || item === void 0 ? void 0 : item.key) || '';
253
- return key;
254
- })]));
255
- const fromJS = makeFromJS(returnType);
256
- return fromJS(selectedFilters);
257
- };
258
- const getResults = (state, current = '', context = Context.facets, returnType) => {
259
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'results'], [], returnType);
260
- };
261
- const getIsInternalPaging = (state, current, context = Context.facets) => {
262
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'queryParams', 'internalPaging'], false);
263
- };
264
- const getIsLoaded = (state, context = Context.facets, facet) => {
265
- return !!getImmutableOrJS(state, ['search', context, facet || getCurrent(state, context), 'queryDuration'], 0);
266
- };
267
- const getIsLoading = (state, context = Context.facets, facet) => {
268
- return getImmutableOrJS(state, ['search', context, facet || getCurrent(state, context), 'entries', 'isLoading']);
269
- };
270
- const getIsSsr = state => getImmutableOrJS(state, ['search', 'config', 'ssr'], false);
271
- const getFeaturedResults = (state, current = '', context = Context.facets, returnType) => {
272
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'featuredResults'], [], returnType);
273
- };
274
- const getPaging = (state, current = '', context = Context.facets, returnType) => {
275
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo'], {}, returnType);
276
- };
277
- const getPageIndex = (state, current = '', context = Context.facets) => {
278
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'pageIndex']);
279
- };
280
- const getPageSize = (state, current = '', context = Context.facets) => {
281
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'pageSize'], 0 // Defaults to 0 because we want it to fall back to a query param if not defined
282
- );
283
- };
284
- const getPrevPageIndex = (state, current = '', context = Context.facets) => {
285
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'prevPageIndex']);
286
- };
287
- const getPageIsLoading = (state, current = '', context = Context.facets) => {
288
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'isLoading']);
289
- };
290
- const getPagesLoaded = (state, current = '', context = Context.facets) => {
291
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'pagesLoaded'], [], 'js');
292
- };
293
- const getTotalCount = (state, current = '', context = Context.facets) => {
294
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'pagingInfo', 'totalCount']);
295
- };
296
- const getSearchTerm = state => getImmutableOrJS(state, ['search', 'term']);
297
- const getSearchTabs = (state, returnType) => getImmutableOrJS(state, ['search', 'tabs'], [], returnType);
298
- const getQueryParams = (state, current = '', context = Context.facets) => {
299
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'queryParams'], {}, 'js');
300
- };
301
- const getQueryParameter = ({
302
- state,
303
- facet,
304
- context = Context.facets
305
- }, key, ifnull = null) => {
306
- return getImmutableOrJS(getQueryParams(state, facet, context), key, ifnull, 'js');
307
- };
308
- const getCustomApi = (state, current, context = Context.facets, returnType) => {
309
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'customApi'], null, returnType);
310
- };
311
- const getCustomEnv = (state, current, context = Context.facets) => {
312
- return getImmutableOrJS(state, ['search', context, current || getCurrent(state, context), 'env']);
313
- };
314
- const getTabsAndFacets = (state, returnType) => {
315
- const tabs = getSearchTabs(state, 'js');
316
- const facets = getFacets(state, 'js');
317
- const tabsAndFacets = (tabs || []).map((tab = {}) => {
318
- const fieldsToCount = tab.totalCount;
319
- let countFields;
320
- if (typeof fieldsToCount === 'string') countFields = [[fieldsToCount]];
321
- const thisTabFacets = Object.entries(facets).filter(([key]) => getImmutableOrJS(facets, [key, 'tabId'], 0) === tab.id);
322
- const thisTabTotal = thisTabFacets.map(([facetName, facet = {}]) => {
323
- if (!countFields || countFields.find((f = []) => (f === null || f === void 0 ? void 0 : f[0]) === facetName)) return getImmutableOrJS(facet, ['pagingInfo', 'totalCount']);
324
- return 0;
325
- }).reduce((a, b) => a + b, 0);
326
- return {
327
- ...tab,
328
- [Context.facets]: Object.fromEntries(thisTabFacets),
329
- totalCount: thisTabTotal
330
- };
331
- });
332
- const fromJS = makeFromJS(returnType);
333
- return fromJS(tabsAndFacets);
334
- };
335
- const getSearchTotalCount = state => {
336
- const tabsAndFacets = getTabsAndFacets(state, 'js');
337
- const wholeSearchTotal = tabsAndFacets.map((t = {}) => t.totalCount).reduce((a, b) => a + b, 0);
338
- return wholeSearchTotal;
339
- };
340
- const getFacetsTotalCount = state => {
341
- const facets = getFacets(state);
342
- const wholeSearchTotal = Object.entries(facets).map(([, t = {}]) => {
343
- var _t$pagingInfo;
344
- return ((_t$pagingInfo = t.pagingInfo) === null || _t$pagingInfo === void 0 ? void 0 : _t$pagingInfo.totalCount) || 0;
345
- }).reduce((a, b) => a + b, 0);
346
- return wholeSearchTotal;
347
- };
348
-
349
- // An exported copy of the relevant selectors scoped by default to a facets context
350
- const selectFacets = {
351
- getCurrent: getCurrentFacet,
352
- getCurrentTab,
353
- getCustomApi,
354
- getCustomEnv,
355
- getFacet,
356
- getFacetTitles,
357
- getFacets,
358
- getFacetsTotalCount,
359
- getFeaturedResults,
360
- getFilters,
361
- getFiltersToLoad,
362
- getIsLoaded,
363
- getIsLoading,
364
- getPageIndex,
365
- getPageIsLoading,
366
- getPagesLoaded,
367
- getPaging,
368
- getQueryParams: (state, facet) => getQueryParams(state, facet, Context.facets),
369
- getQueryParameter: ({
370
- state,
371
- facet
372
- }, key, ifnull) => getQueryParameter({
373
- state,
374
- facet,
375
- context: Context.facets
376
- }, key, ifnull),
377
- getRenderableFilters,
378
- getResults,
379
- getTabFacets,
380
- getTabsAndFacets,
381
- getTotalCount,
382
- getSearchTabs,
383
- getSearchTerm,
384
- getSearchTotalCount,
385
- getSelectedFilters
386
- };
387
-
388
- // An exported copy of the relevant selectors pre-scoped to a listing context
389
- const selectListing = {
390
- getCurrent: getCurrentListing,
391
- getFeaturedResults: (state, listing = '') => getFeaturedResults(state, listing, Context.listings, 'js'),
392
- getFilters: (state, listing = '') => getFilters(state, listing, Context.listings, 'js'),
393
- getFiltersToLoad: (state, listing = '') => getFiltersToLoad(state, listing, Context.listings),
394
- getListing,
395
- getIsLoaded: state => getIsLoaded(state, Context.listings),
396
- getIsLoading: state => getIsLoading(state, Context.listings),
397
- getPageIndex: (state, listing = '') => getPageIndex(state, listing, Context.listings),
398
- getPaging: (state, listing = '') => getPaging(state, listing, Context.listings, 'js'),
399
- getPageIsLoading: (state, listing = '') => getPageIsLoading(state, listing, Context.listings),
400
- getPagesLoaded: (state, listing = '') => getPagesLoaded(state, listing, Context.listings),
401
- getQueryParams: (state, listing = '') => getQueryParams(state, listing, Context.listings),
402
- getQueryParameter: ({
403
- state,
404
- facet
405
- }, key, ifnull) => getQueryParameter({
406
- state,
407
- facet,
408
- context: Context.listings
409
- }, key, ifnull),
410
- getRenderableFilters: (state, listing = '') => getRenderableFilters(state, listing, Context.listings),
411
- getResults: (state, listing = '') => getResults(state, listing, Context.listings, 'js'),
412
- getSearchTerm,
413
- getTotalCount: (state, listing = '') => getTotalCount(state, listing, Context.listings),
414
- getSelectedFilters: (state, listing = '') => getSelectedFilters(state, listing, Context.listings, 'js')
415
- };
416
- const selectCurrentPath = state => getImmutableOrJS(state, ['routing', 'currentPath']);
417
- const selectCurrentProject = state => getImmutableOrJS(state, ['routing', 'currentProject']);
418
- const selectVersionStatus = state => getImmutableOrJS(state, ['version', 'contensisVersionStatus']);
419
-
420
- var selectors = /*#__PURE__*/Object.freeze({
421
- __proto__: null,
422
- getCurrent: getCurrent,
423
- getCurrentFacet: getCurrentFacet,
424
- getCurrentListing: getCurrentListing,
425
- getCurrentTab: getCurrentTab,
426
- getCustomApi: getCustomApi,
427
- getCustomEnv: getCustomEnv,
428
- getFacet: getFacet,
429
- getFacetTitles: getFacetTitles,
430
- getFacets: getFacets,
431
- getFacetsTotalCount: getFacetsTotalCount,
432
- getFeaturedResults: getFeaturedResults,
433
- getFilters: getFilters,
434
- getFiltersToLoad: getFiltersToLoad,
435
- getIsInternalPaging: getIsInternalPaging,
436
- getIsLoaded: getIsLoaded,
437
- getIsLoading: getIsLoading,
438
- getIsSsr: getIsSsr,
439
- getListing: getListing,
440
- getPageIndex: getPageIndex,
441
- getPageIsLoading: getPageIsLoading,
442
- getPageSize: getPageSize,
443
- getPagesLoaded: getPagesLoaded,
444
- getPaging: getPaging,
445
- getPrevPageIndex: getPrevPageIndex,
446
- getQueryParameter: getQueryParameter,
447
- getQueryParams: getQueryParams,
448
- getRenderableFilters: getRenderableFilters,
449
- getResults: getResults,
450
- getSearchContext: getSearchContext,
451
- getSearchTabs: getSearchTabs,
452
- getSearchTerm: getSearchTerm,
453
- getSearchTotalCount: getSearchTotalCount,
454
- getSelectedFilters: getSelectedFilters,
455
- getTabFacets: getTabFacets,
456
- getTabsAndFacets: getTabsAndFacets,
457
- getTotalCount: getTotalCount,
458
- selectCurrentPath: selectCurrentPath,
459
- selectCurrentProject: selectCurrentProject,
460
- selectFacets: selectFacets,
461
- selectListing: selectListing,
462
- selectVersionStatus: selectVersionStatus
463
- });
464
-
465
- const now = () => {
466
- if (typeof window == 'undefined') {
467
- return Date.now();
468
- }
469
- return window.performance.now();
470
- };
471
-
472
- const getClientConfig = (project, env) => {
473
- let config = DELIVERY_API_CONFIG; /* global DELIVERY_API_CONFIG */
474
- if (project) {
475
- config.projectId = project;
476
- }
477
- if (typeof window != 'undefined' && PROXY_DELIVERY_API /* global PROXY_DELIVERY_API */) {
478
- // ensure a relative url is used to bypass the need for CORS (separate OPTIONS calls)
479
- config.rootUrl = env || '';
480
- config.responseHandler = {
481
- 404: () => null
482
- };
483
- }
484
- return config;
485
- };
486
- class CacheNode {
487
- constructor(key, value) {
488
- this.key = key;
489
- this.value = value;
490
- this.next = null;
491
- this.prev = null;
492
- }
493
- }
494
- class LruCache {
495
- constructor(limit = 100) {
496
- this.map = {};
497
- this.head = null;
498
- this.tail = null;
499
- this.limit = limit || 100;
500
- this.size = 0;
501
- }
502
- get(key) {
503
- if (this.map[key]) {
504
- let value = this.map[key].value;
505
- let node = new CacheNode(key, value);
506
- this.remove(key);
507
- this.setHead(node);
508
- return value;
509
- }
510
- }
511
- set(key, value) {
512
- let node = new CacheNode(key, value);
513
- if (this.map[key]) {
514
- this.remove(key);
515
- } else {
516
- if (this.size >= this.limit) {
517
- delete this.map[this.tail.key];
518
- this.size--;
519
- this.tail = this.tail.prev;
520
- this.tail.next = null;
521
- }
522
- }
523
- this.setHead(node);
524
- }
525
- setHead(node) {
526
- node.next = this.head;
527
- node.prev = null;
528
- if (this.head) {
529
- this.head.prev = node;
530
- }
531
- this.head = node;
532
- if (!this.tail) {
533
- this.tail = node;
534
- }
535
- this.size++;
536
- this.map[node.key] = node;
537
- }
538
- remove(key) {
539
- let node = this.map[key];
540
- if (node.prev) {
541
- node.prev.next = node.next;
542
- } else {
543
- this.head = node.next;
544
- }
545
- if (node.next) {
546
- node.next.prev = node.prev;
547
- } else {
548
- this.tail = node.prev;
549
- }
550
- delete this.map[key];
551
- this.size--;
552
- }
553
- }
554
- class CachedSearch {
555
- constructor() {
556
- this.cache = new LruCache();
557
- this.taxonomyLookup = {};
558
- }
559
- search(query, linkDepth, project, env) {
560
- const client = Client.create(getClientConfig(project, env));
561
- return this.request(project + JSON.stringify(query) + linkDepth.toString(), () => client.entries.search(query, linkDepth));
562
- }
563
- getTaxonomyNodeByPath(path, project, env) {
564
- const client = Client.create(getClientConfig(project, env));
565
- return this.request(`[TAXONOMY NODE] ${path}`, () => client.taxonomy.getNodeByPath({
566
- path: path,
567
- order: 'defined',
568
- childDepth: 2
569
- }).then(node => this.extendTaxonomyNode(node)));
570
- }
571
- request(key, execute) {
572
- if (!this.cache.get(key) || typeof window == 'undefined') {
573
- let promise = execute();
574
- this.cache.set(key, promise);
575
- promise.catch(() => {
576
- this.cache.remove(key);
577
- });
578
- }
579
- return this.cache.get(key);
580
- }
581
- extendTaxonomyNode(node) {
582
- let id = this.getTaxonomyId(node);
583
- this.taxonomyLookup[id] = node.key;
584
- return {
585
- ...node,
586
- id,
587
- children: node.children ? node.children.map(n => this.extendTaxonomyNode(n)) : null
588
- };
589
- }
590
- getTaxonomyId(node) {
591
- if (node.key) {
592
- let parts = node.key.split('/');
593
- return parts[parts.length - 1];
594
- }
595
- return '';
596
- }
597
- fetch(uri, opts = {}) {
598
- return this.request(`[FETCH] ${uri} ${JSON.stringify(opts)}`, () => fetch(uri, opts));
599
- }
600
- }
601
- const cachedSearch = new CachedSearch();
602
-
603
- // eslint-disable-next-line import/default
604
- function fixFreeTextForElastic(s) {
605
- const illegalChars = ['>', '<', '=', '|', '!', '{', '}', '[', ']', '^', '~', '*', '?', ':', '\\', '/'];
606
- const illegalRegEx = new RegExp(illegalChars.map(c => '\\' + c).join('|'), 'g');
607
- s = s.replace(illegalRegEx, '');
608
- // s = s.replace(encodedRegEx, ''); // (m) => '\\\\' + m);
609
-
610
- return s;
611
- }
612
- const timedSearch = async (query, linkDepth = 0, projectId, env) => {
613
- if (!query) return null;
614
- let duration = 0;
615
- const start = now();
616
- const payload = await cachedSearch.search(query, linkDepth, projectId, env);
617
- const end = now();
618
- duration = end - start;
619
- return {
620
- duration,
621
- payload
622
- };
623
- };
624
- const getItemsFromResult = result => {
625
- const {
626
- payload
627
- } = result || {};
628
- if (payload) {
629
- if (Array.isArray(payload)) return payload;
630
- if (Array.isArray(payload.items)) return payload.items;
631
- return payload;
632
- }
633
- return [];
634
- };
635
- const extractQuotedPhrases = searchTerm => {
636
- const pattern = new RegExp(/(?=["'])(?:"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*')/gm);
637
- return (searchTerm.match(pattern) || []).map(match => match.replace(/"/g, ''));
638
- };
639
- const buildUrl = (route, params) => {
640
- const qs = stringify(params);
641
- const path = qs ? `${route}${route.includes('?') ? '&' : '?'}${qs}` : route;
642
- return path;
643
- };
644
-
645
- /**
646
- * Returns all params from the current route query string or static route
647
- * Supply static route argument if reading parameters from the route path
648
- * Supply location argument for the params to be read in SSR
649
- * @param staticRoute Matched static route from react-router 5 or 6
650
- * @param location location object containing at least pathname and search
651
- * @returns Keyed params object
652
- */
653
- const routeParams = (staticRoute, location) => {
654
- var _staticRoute$match;
655
- // match.params is react-router-config/react-router@5 style
656
- // params is supplied with RouteObject in react-router@6
657
- const pathParams = (staticRoute === null || staticRoute === void 0 || (_staticRoute$match = staticRoute.match) === null || _staticRoute$match === void 0 ? void 0 : _staticRoute$match.params) || (staticRoute === null || staticRoute === void 0 ? void 0 : staticRoute.params) || {};
658
- const queryParams = parse(typeof window !== 'undefined' ? window.location.search : (location === null || location === void 0 ? void 0 : location.search) || '');
659
- return {
660
- ...pathParams,
661
- ...queryParams
662
- };
663
- };
664
- const callCustomApi = async (customApi, filters) => {
665
- const apiUri = customApi.uri || '';
666
- let uri = buildUrl(apiUri, filters);
667
- if (!uri) throw new Error('uri is required to use customApi');
668
- if (typeof window == 'undefined') {
669
- if (!uri.startsWith('http')) uri = `http://localhost:3001${uri}`;
670
- const response = await fetch(uri);
671
- return await response.json();
672
- }
673
- const response = await cachedSearch.fetch(uri);
674
- return await response.clone().json();
675
- };
676
- const removeEmptyAttributes = obj => {
677
- Object.entries(obj).forEach(([key, val]) => val && typeof val === 'object' && removeEmptyAttributes(val) || (typeof val === 'undefined' || val === null || val === '') && delete obj[key]);
678
- return obj;
679
- };
680
- const toArray = (obj, seperator = ',') => typeof obj === 'undefined' || obj === null ? obj : Array.isArray(obj) ? obj : obj.split(seperator);
681
-
682
- // assumes array elements are primitive types
683
- const areArraysEqualSets = (a1, a2) => {
684
- const superSet = {};
685
- for (const ai of a1) {
686
- const e = ai + typeof ai;
687
- superSet[e] = 1;
688
- }
689
- for (const ai of a2) {
690
- const e = ai + typeof ai;
691
- if (!superSet[e]) {
692
- return false;
693
- }
694
- superSet[e] = 2;
695
- }
696
- for (const e in superSet) {
697
- if (superSet[e] === 1) {
698
- return false;
699
- }
700
- }
701
- return true;
702
- };
703
-
704
- const searchUriTemplate = {
705
- path: ({
706
- state,
707
- facet
708
- }) => {
709
- const context = getSearchContext(state);
710
- const currentPath = selectCurrentPath(state) || '/search';
711
- if (context !== 'listings') {
712
- const currentFacet = facet || getCurrentFacet(state);
713
- const filters = getSelectedFilters(state, facet, context);
714
- const currentFilter = filters.contentTypeId;
715
-
716
- // Check if we have a filter first
717
- const newPath = (currentFilter === null || currentFilter === void 0 ? void 0 : currentFilter.length) > 0 && currentFacet ? `${currentPath}/${currentFacet}/${currentFilter}` : currentFacet ? `${currentPath}/${currentFacet}` : currentPath;
718
- return newPath;
719
- } else {
720
- return currentPath;
721
- }
722
- },
723
- search: ({
724
- state,
725
- facet,
726
- orderBy,
727
- term,
728
- pageIndex,
729
- pageSize
730
- }) => {
731
- const searchContext = getSearchContext(state);
732
- // Lose stateFilters and currentSearch if a new
733
- // term is passed via an argument
734
- const stateFilters = term ? {} : Object.fromEntries(Object.entries(getSelectedFilters(state, facet, searchContext, 'js')).map(([k, f]) => [k, f === null || f === void 0 ? void 0 : f.join(',')]));
735
- const currentSearch = !term && getImmutableOrJS(state, ['routing', 'location', 'search']);
736
- const currentQs = removeEmptyAttributes(parse(currentSearch));
737
- if (orderBy) currentQs.orderBy = orderBy;
738
- const searchTerm = getSearchTerm(state);
739
- // Use Immutable's merge to merge the stateFilters with any current Qs
740
- // to build the new Qs.
741
- const mergedSearch = removeEmptyAttributes(merge(currentQs, stateFilters));
742
-
743
- // We must handle term === '' separately, because this means the user has cleared the search term
744
- // If this is true, we don't want to fall back to the existing search term. We only want to do that if the
745
- // incoming term is explicitly undefined.
746
- if (typeof term != 'undefined') {
747
- if (term) mergedSearch.term = term;else if (term === '') delete mergedSearch.term;
748
- } else {
749
- if (searchTerm) mergedSearch.term = searchTerm;
750
- }
751
- if (pageIndex) mergedSearch.pageIndex = pageIndex + 1;
752
- if (pageIndex === 0) mergedSearch.pageIndex = undefined;
753
- if (pageSize) mergedSearch.pageSize = pageSize;
754
-
755
- // We don't want these as search params in the url, we just need the search package to see them
756
- return stringify(mergedSearch);
757
- },
758
- hash: ({
759
- state
760
- }) => getImmutableOrJS(state, ['routing', 'location', 'hash'], '').replace('#', '')
761
- };
762
- const mapStateToSearchUri = state => mapJson(state, searchUriTemplate);
763
-
764
- const DataFormats = {
765
- asset: 'asset',
766
- entry: 'entry',
767
- webpage: 'webpage'
768
- };
769
- const FilterExpressionTypes = {
770
- contentType: 'contentType',
771
- field: 'field'
772
- };
773
- const sys = {
774
- allUris: 'sys.allUris',
775
- contentTypeId: 'sys.contentTypeId',
776
- dataFormat: 'sys.dataFormat',
777
- filename: 'sys.properties.filename',
778
- id: 'sys.id',
779
- includeInSearch: 'sys.metadata.includeInSearch',
780
- language: 'sys.language',
781
- uri: 'sys.uri',
782
- versionStatus: 'sys.versionStatus'
783
- };
784
- const Fields = {
785
- entryDescription: 'entryDescription',
786
- entryTitle: 'entryTitle',
787
- keywords: 'keywords',
788
- searchContent: 'searchContent',
789
- sys,
790
- contentTypeId: 'sys.contentTypeId',
791
- wildcard: '*'
792
- };
793
-
794
- const fieldExpression = (field, value, operator = 'equalTo', weight, fuzzySearch = false) => {
795
- if (!field || !value || Array.isArray(value) && value.length === 0) return [];
796
- if (Array.isArray(field))
797
- // If an array of fieldIds have been provided, call self for each fieldId
798
- // to generate expressions that are combined with an 'or' operator
799
- return [Op.or(...field.map(fieldId => fieldExpression(fieldId, value, operator, weight, fuzzySearch)).flat())];
800
- if (operator === 'between') return between(field, value);
801
- if (Array.isArray(value)) return equalToOrIn(field, value, operator, fuzzySearch);else return !weight ? equalToOrIn(field, value, operator, fuzzySearch) : [equalToOrIn(field, value, operator, fuzzySearch)[0].weight(weight)];
802
- };
803
- const contentTypeIdExpression = (contentTypeIds, webpageTemplates, assetTypes) => {
804
- const expressions = [];
805
- if (!contentTypeIds && !webpageTemplates && !assetTypes) return expressions;
806
- if (contentTypeIds && contentTypeIds.length > 0) {
807
- expressions.push(...dataFormatExpression(contentTypeIds, DataFormats.entry));
808
- }
809
- if (webpageTemplates && webpageTemplates.length > 0) {
810
- expressions.push(...dataFormatExpression(webpageTemplates, DataFormats.webpage));
811
- }
812
- if (assetTypes && assetTypes.length > 0) {
813
- expressions.push(...dataFormatExpression(assetTypes, DataFormats.asset));
814
- }
815
- if (expressions.length > 1) return [Op.or(...expressions)];
816
- return expressions;
817
- };
818
- const filterExpressions = (filters, isOptional = false) => {
819
- if (!filters) return [];
820
- const expressions = [];
821
- filters.map(selectedFilter => {
822
- if (selectedFilter.logicOperator === 'and')
823
- // using 'and' logic operator we loop through each filter
824
- // and loop through all values to add an expression for each filter value
825
- selectedFilter.values.forEach(value => expressions.push(...fieldExpression(selectedFilter.key, value, selectedFilter.fieldOperator || 'equalTo')));else if (selectedFilter.logicOperator === 'not') {
826
- const fieldExpressions = fieldExpression(selectedFilter.key, selectedFilter.values, selectedFilter.fieldOperator || 'in');
827
- fieldExpressions.forEach(expr => {
828
- expressions.push(Op.not(expr));
829
- });
830
- }
831
- // using 'or' logic operator we loop over each filter
832
- // and simply add the array of values to an expression with an 'in' operator
833
- else expressions.push(...fieldExpression(selectedFilter.key, selectedFilter.values, selectedFilter.fieldOperator || 'in'));
834
- if (isOptional) expressions.push(Op.not(fieldExpression(selectedFilter.key, true, 'exists')[0]));
835
- });
836
- return expressions;
837
- };
838
- const dataFormatExpression = (contentTypeIds, dataFormat = DataFormats.entry) => {
839
- if (contentTypeIds && contentTypeIds.length > 0) {
840
- /**
841
- * We have an array of contentTypeIds some may be prefixed with a "!"
842
- * to indicate this is a "not" expression
843
- */
844
- const withContentTypeIds = contentTypeIds.filter(c => !c.startsWith('!'));
845
- const notContentTypeIds = contentTypeIds.filter(c => c.startsWith('!')).map(id => id.substring(1));
846
- const andExpr = Op.and();
847
- const dataFormatExpr = fieldExpression(Fields.sys.dataFormat, dataFormat)[0];
848
- const withExpr = fieldExpression(Fields.sys.contentTypeId, withContentTypeIds)[0];
849
- const notExpr = Op.not(fieldExpression(Fields.sys.contentTypeId, notContentTypeIds)[0]);
850
- andExpr.add(dataFormatExpr);
851
- if (withContentTypeIds.length > 0 && withExpr) andExpr.add(withExpr);
852
- if (notContentTypeIds.length > 0 && notExpr) andExpr.add(notExpr);
853
- return [andExpr];
854
- }
855
- return [];
856
- };
857
- const featuredResultsExpression = ({
858
- contentTypeId,
859
- fieldId,
860
- fieldValue = true
861
- } = {}) => {
862
- const expressions = [];
863
- if (contentTypeId) {
864
- expressions.push(...contentTypeIdExpression(Array.isArray(contentTypeId) ? contentTypeId : [contentTypeId]));
865
- }
866
- if (fieldId && fieldValue) {
867
- expressions.push(...fieldExpression(fieldId, fieldValue));
868
- }
869
- return expressions;
870
- };
871
- const languagesExpression = languages => fieldExpression(Fields.sys.language, languages);
872
- const includeInSearchExpressions = (webpageTemplates, includeInSearchFields) => {
873
- const expressions = [];
874
- // Or include this expression if we have explicity specified non-default includeInSearch fields
875
- if (Array.isArray(includeInSearchFields)) expressions.push(...includeInSearchFields.map(includeInSearchField => Op.or(Op.and(Op.exists(includeInSearchField, true), Op.equalTo(includeInSearchField, true)), Op.exists(includeInSearchField, false))));
876
-
877
- // If webpageTemplates have been specified, include this expression
878
- // with the default includeInSearch field from classic Contensis.
879
- if (Array.isArray(webpageTemplates) && webpageTemplates.length > 0) expressions.push(Op.or(Op.and(Op.exists(Fields.sys.includeInSearch, true), Op.equalTo(Fields.sys.includeInSearch, true)), Op.exists(Fields.sys.includeInSearch, false)));
880
- return expressions;
881
- };
882
- const defaultExpressions = versionStatus => {
883
- return [Op.equalTo(Fields.sys.versionStatus, versionStatus)];
884
- };
885
- const includeIdsExpression = includeIds => {
886
- if (Array.isArray(includeIds) && includeIds.length > 0) {
887
- return fieldExpression(Fields.sys.id, includeIds);
888
- } else return [];
889
- };
890
- const excludeIdsExpression = excludeIds => {
891
- if (Array.isArray(excludeIds) && excludeIds.length > 0) {
892
- const [expr] = fieldExpression(Fields.sys.id, excludeIds);
893
- return [Op.not(expr)];
894
- } else return [];
895
- };
896
- const orderByExpression = orderBy => {
897
- let expression;
898
- if (orderBy && orderBy.length > 0) {
899
- expression = OrderBy;
900
- for (const ob of orderBy) {
901
- var _expression, _expression2;
902
- expression = ob.startsWith('-') ? (_expression = expression) === null || _expression === void 0 ? void 0 : _expression.desc(ob.substring(1)) : (_expression2 = expression) === null || _expression2 === void 0 ? void 0 : _expression2.asc(ob);
903
- }
904
- }
905
- return expression;
906
- };
907
- const equalToOrIn = (field, value, operator = 'equalTo', fuzzySearch = false) => {
908
- if (value.length === 0) return [];
909
- if (Array.isArray(value)) {
910
- if (operator === 'equalTo' || operator === 'in') return [Op.in(field, ...value)];
911
- const expressions = value.map(innerValue => {
912
- var _between, _distanceWithin;
913
- switch (operator) {
914
- case 'between':
915
- return (_between = between(field, innerValue)) === null || _between === void 0 ? void 0 : _between[0];
916
- case 'distanceWithin':
917
- return (_distanceWithin = distanceWithin(field, innerValue)) === null || _distanceWithin === void 0 ? void 0 : _distanceWithin[0];
918
- case 'exists':
919
- return Op.exists(field, innerValue);
920
- case 'freeText':
921
- // TODO: Potentially needs further implementation of new options
922
- return Op[operator](field, innerValue, fuzzySearch, undefined);
923
- default:
924
- return Op[operator](field, innerValue);
925
- }
926
- });
927
- return (expressions === null || expressions === void 0 ? void 0 : expressions.length) > 1 ? [Op.or(...expressions)] : expressions || [];
928
- }
929
- switch (operator) {
930
- case 'between':
931
- return between(field, value);
932
- case 'distanceWithin':
933
- return distanceWithin(field, value);
934
- case 'freeText':
935
- // TODO: Potentially needs further implementation of new options
936
- return [Op.freeText(field, value, fuzzySearch, undefined)];
937
- default:
938
- return [Op[operator](field, value)];
939
- }
940
- };
941
- const between = (field, value) => {
942
- const handle = betweenValue => {
943
- const valArr = betweenValue.split('--');
944
- if (valArr.length > 1) {
945
- const [minimum, maximum] = valArr;
946
- return Op.between(field, minimum, maximum);
947
- } else {
948
- // eslint-disable-next-line no-console
949
- console.log(`[search] You have supplied only one value to a "between" operator which must have two values. Your supplied value "${valArr.length && valArr[0]}" has been discarded.`);
950
- return false;
951
- }
952
- };
953
- if (value.length === 0) return [];
954
- if (Array.isArray(value)) return [Op.or(...value.map(handle).filter(bc => bc !== false))];
955
- const op = handle(value);
956
- return op ? [op] : [];
957
- };
958
- const distanceWithin = (field, value) => {
959
- const handle = distanceValue => {
960
- const valArr = distanceValue.split(' ');
961
- if (valArr.length > 1) {
962
- const [lat, lon] = valArr;
963
- return Op.distanceWithin(field, Number(lat), Number(lon), (valArr === null || valArr === void 0 ? void 0 : valArr[2]) || '10mi');
964
- } else {
965
- // eslint-disable-next-line no-console
966
- console.log(`[search] You have supplied only one value to a "distanceWithin" operator which must be made up of "lat,lon,distance". Your supplied value "${valArr.length && valArr[0]}" has been discarded.`);
967
- return false;
968
- }
969
- };
970
- if (value.length === 0) return [];
971
- if (Array.isArray(value)) return [Op.or(...value.map(handle).filter(bc => bc !== false))];
972
- const op = handle(value);
973
- return op ? [op] : [];
974
- };
975
-
976
- /**
977
- * Accept HTTP style objects and map them to
978
- * their equivalent JS client "Op" expressions
979
- * @param {array} where the where array as you'd provide it to the HTTP API
980
- * @returns {array} array of constructed Delivery API Operators
981
- */
982
- const customWhereExpressions = where => {
983
- if (!where || !Array.isArray(where)) return [];
984
-
985
- // Map each clause inside the where array
986
- return where.map(clause => {
987
- let expression;
988
- // Map through each property in the clause so we can
989
- // capture the values required and reconstruct them as
990
- // a Delivery API expression
991
- let operator;
992
- Object.keys(clause).map((key, idx) => {
993
- // The clause may contain only one key
994
- if (idx === 0) operator = key;
995
- const field = clause.field;
996
- const value = clause[Object.keys(clause).find(k => !['field', 'weight'].includes(k)) || ''];
997
- const weight = clause.weight;
998
- if (idx === 0) {
999
- if (operator === 'and' || operator === 'or') {
1000
- // These are array expressions so we can call ourself recursively
1001
- // to map these inner values to expressions
1002
- const recurseExpr = customWhereExpressions(clause[operator]);
1003
- expression = Op[operator](...recurseExpr);
1004
- }
1005
- if (['not'].includes(operator)) {
1006
- // A 'not' expression is an object with only one inner field and inner operator
1007
- Object.keys(value).map((notKey, notIdx) => {
1008
- const innerOperator = notKey;
1009
- const innerValue = value[notKey];
1010
- const innerField = value.field;
1011
- // Map the expression when we've looped and scoped to
1012
- // the second property inside the clause
1013
- if (notIdx === 1) expression = Op.not(makeJsExpression(innerOperator, innerField, innerValue));
1014
- });
1015
- }
1016
- }
1017
- // Map the expression when we've looped and scoped to
1018
- // the second property inside the clause
1019
- operator = Object.keys(clause).find(clauseKey => !['field', 'weight'].includes(clauseKey));
1020
- if (idx === 1) {
1021
- expression = makeJsExpression(operator, field, value);
1022
- if (typeof weight === 'number') expression = expression.weight(weight);
1023
- }
1024
- });
1025
- return expression;
1026
- });
1027
- };
1028
- const makeJsExpression = (operator, field, value) => operator === 'freeText' || operator === 'contains' ? Op[operator](field, value) : operator === 'in' ? Op[operator](field, ...value) : operator === 'exists' ? Op[operator](field, value) : operator === 'between' ? Op[operator](field, value[0], value[1]) : operator === 'distanceWithin' ? Op[operator](field, value === null || value === void 0 ? void 0 : value.lat, value === null || value === void 0 ? void 0 : value.lon, value === null || value === void 0 ? void 0 : value.distance) : Op[operator](field, value);
1029
- const termExpressions = (searchTerm, weightedSearchFields, fuzzySearch, omitSearchFields = []) => {
1030
- if (searchTerm && weightedSearchFields && weightedSearchFields.length > 0) {
1031
- // Extract any phrases in quotes to array
1032
- const quotedPhrases = extractQuotedPhrases(searchTerm);
1033
-
1034
- // Modify the search term to remove any quoted phrases to leave any remaining terms
1035
- let modifiedSearchTerm = searchTerm;
1036
- quotedPhrases.forEach(qp => modifiedSearchTerm = modifiedSearchTerm.replace(qp, '').replace('""', '').trim());
1037
-
1038
- // Push to the operators array to include in the query
1039
- const operators = [];
1040
-
1041
- // Helper functions to generate Op expressions
1042
- const containsOp = (f, term) => fieldExpression(f.fieldId, fixFreeTextForElastic(term), 'contains', f.weight);
1043
- const freeTextOp = (f, term) => fieldExpression(f.fieldId, fixFreeTextForElastic(term), 'freeText', f.weight, fuzzySearch);
1044
-
1045
- // For each weighted search field
1046
- weightedSearchFields.forEach(wsf => {
1047
- // Push to field operators
1048
- const fieldOperators = [];
1049
-
1050
- // Add operator expressions for modified search term
1051
- if (modifiedSearchTerm) {
1052
- if ([Fields.keywords, Fields.sys.filename, Fields.sys.uri].includes(wsf.fieldId)) {
1053
- fieldOperators.push(...containsOp(wsf, modifiedSearchTerm));
1054
- } else {
1055
- if ([Fields.entryTitle].includes(wsf.fieldId)) {
1056
- fieldOperators.push(Op.or(...containsOp(wsf, modifiedSearchTerm), ...freeTextOp(wsf, modifiedSearchTerm)));
1057
- } else {
1058
- fieldOperators.push(...freeTextOp(wsf, modifiedSearchTerm));
1059
- }
1060
- }
1061
- }
1062
-
1063
- // Add operator expressions for any quoted phrases
1064
- quotedPhrases.forEach(qp => fieldOperators.push(...containsOp(wsf, qp)));
1065
-
1066
- // If we are using multiple operators for a field we will
1067
- // wrap each field inside an And operator so we will match
1068
- // all terms/phrases rather than any terms/phrases
1069
- if (fieldOperators.length > 1) {
1070
- operators.push(Op.and(...fieldOperators));
1071
- } else {
1072
- operators.push(...fieldOperators);
1073
- }
1074
- });
1075
-
1076
- // Wrap operators in an Or operator
1077
- const expressions = Op.or().addRange(operators);
1078
- if (!omitSearchFields.find(sf => sf === Fields.searchContent))
1079
- // include "searchContent" field by default unless omitted
1080
- return [expressions.add(Op.freeText(Fields.searchContent, searchTerm, fuzzySearch))];else return [expressions];
1081
- } else if (searchTerm) {
1082
- // Searching without weightedSearchFields defined will fall back
1083
- // to a default set of search fields with arbritary weights set.
1084
-
1085
- const exp = [];
1086
- if (!omitSearchFields.find(sf => sf === Fields.entryTitle)) {
1087
- exp.push(Op.equalTo(Fields.entryTitle, searchTerm).weight(10));
1088
- exp.push(Op.freeText(Fields.entryTitle, searchTerm, fuzzySearch).weight(2));
1089
- }
1090
- if (!omitSearchFields.find(sf => sf === Fields.entryDescription)) exp.push(Op.freeText(Fields.entryDescription, searchTerm, fuzzySearch).weight(2));
1091
- if (!omitSearchFields.find(sf => sf === Fields.keywords)) exp.push(Op.contains(Fields.keywords, searchTerm).weight(2));
1092
- if (!omitSearchFields.find(sf => sf === Fields.sys.uri)) exp.push(Op.contains(Fields.sys.uri, searchTerm).weight(2));
1093
- if (!omitSearchFields.find(sf => sf === Fields.sys.allUris)) exp.push(Op.contains(Fields.sys.allUris, searchTerm));
1094
- if (!omitSearchFields.find(sf => sf === Fields.searchContent)) exp.push(Op.freeText(Fields.searchContent, searchTerm, fuzzySearch));
1095
- return [Op.or(...exp)];
1096
- } else {
1097
- return [];
1098
- }
1099
- };
1100
-
1101
- var expressions = /*#__PURE__*/Object.freeze({
1102
- __proto__: null,
1103
- contentTypeIdExpression: contentTypeIdExpression,
1104
- customWhereExpressions: customWhereExpressions,
1105
- dataFormatExpression: dataFormatExpression,
1106
- defaultExpressions: defaultExpressions,
1107
- excludeIdsExpression: excludeIdsExpression,
1108
- featuredResultsExpression: featuredResultsExpression,
1109
- fieldExpression: fieldExpression,
1110
- filterExpressions: filterExpressions,
1111
- includeIdsExpression: includeIdsExpression,
1112
- includeInSearchExpressions: includeInSearchExpressions,
1113
- languagesExpression: languagesExpression,
1114
- orderByExpression: orderByExpression,
1115
- termExpressions: termExpressions
1116
- });
1117
-
1118
- const filterQuery = (contentTypeIds, versionStatus, customWhere) => {
1119
- const query = new Query(...[...contentTypeIdExpression(contentTypeIds), ...defaultExpressions(versionStatus), ...customWhereExpressions(customWhere)]);
1120
- query.orderBy = OrderBy.asc(Fields.entryTitle);
1121
- query.pageSize = 100;
1122
- return query;
1123
- };
1124
- const searchQuery = ({
1125
- assetTypes,
1126
- contentTypeIds,
1127
- customWhere,
1128
- dynamicOrderBy,
1129
- excludeIds,
1130
- featuredResults,
1131
- fieldLinkDepths,
1132
- fields,
1133
- filters,
1134
- fuzzySearch,
1135
- includeInSearchFields,
1136
- languages,
1137
- pageSize,
1138
- pageIndex,
1139
- omitDefaultSearchFields,
1140
- orderBy,
1141
- searchTerm,
1142
- versionStatus,
1143
- webpageTemplates,
1144
- weightedSearchFields
1145
- }, isFeatured = false) => {
1146
- let expressions = [...termExpressions(searchTerm, weightedSearchFields, fuzzySearch, omitDefaultSearchFields), ...defaultExpressions(versionStatus), ...includeInSearchExpressions(webpageTemplates, includeInSearchFields), ...languagesExpression(languages), ...customWhereExpressions(customWhere), ...excludeIdsExpression(excludeIds)];
1147
- if (isFeatured) expressions = [...expressions, ...featuredResultsExpression(featuredResults)];
1148
- if (!isFeatured || featuredResults && !featuredResults.contentTypeId) expressions = [...expressions, ...filterExpressions(filters), ...contentTypeIdExpression(contentTypeIds, webpageTemplates, assetTypes)];
1149
- const query = new Query(...expressions);
1150
- if (!searchTerm) query.orderBy = orderByExpression(orderBy);
1151
- if (dynamicOrderBy && dynamicOrderBy.length) query.orderBy = orderByExpression(dynamicOrderBy);
1152
- if (Object.keys(fieldLinkDepths || {}).length && !isFeatured) query.fieldLinkDepths = fieldLinkDepths;
1153
- if (fields !== null && fields !== void 0 && fields.length && !isFeatured) query.fields = fields;
1154
- query.pageIndex = isFeatured ? 0 : pageIndex;
1155
- query.pageSize = isFeatured && typeof featuredResults.count === 'number' ? featuredResults.count : pageSize;
1156
- return query;
1157
- };
1158
-
1159
- var queries = /*#__PURE__*/Object.freeze({
1160
- __proto__: null,
1161
- filterQuery: filterQuery,
1162
- searchQuery: searchQuery
1163
- });
1164
-
1165
- const mapEntriesToSearchResults = ({
1166
- mappers,
1167
- mapper,
1168
- context,
1169
- facet
1170
- }, items, state) => {
1171
- const mapperFunc = mapper || mappers && mappers.results;
1172
- return items && typeof mapperFunc === 'function' ? mapperFunc(items, facet, context, state) : [];
1173
- };
1174
- const facetTemplate = {
1175
- type: () => SET_SEARCH_ENTRIES,
1176
- context: 'action.context',
1177
- facet: 'action.facet',
1178
- mappers: 'action.mappers',
1179
- nextFacet: {
1180
- entries: {
1181
- isLoading: () => false,
1182
- isError: () => false
1183
- },
1184
- featuredEntries: {
1185
- isLoading: () => false,
1186
- isError: () => false
1187
- },
1188
- featuredResults: ({
1189
- action,
1190
- featuredResult,
1191
- state
1192
- }) => mapEntriesToSearchResults(action, getItemsFromResult(featuredResult), state),
1193
- queryDuration: 'result.duration',
1194
- pagingInfo: {
1195
- isLoading: () => false,
1196
- pageCount: {
1197
- $path: 'result.payload.pageCount',
1198
- $default: 0
1199
- },
1200
- totalCount: {
1201
- $path: 'result.payload.totalCount',
1202
- $default: 0
1203
- },
1204
- pageSize: {
1205
- $path: 'result.payload.pageSize',
1206
- $default: 0
1207
- },
1208
- pageIndex: 'pageIndex',
1209
- pagesLoaded: {
1210
- $path: 'action.queryParams',
1211
- $formatting: ({
1212
- pageIndex,
1213
- pagesLoaded
1214
- }) => {
1215
- const loaded = [...(pagesLoaded || [])];
1216
- if (isNaN(loaded.find(l => l === pageIndex))) {
1217
- loaded.push(pageIndex);
1218
- }
1219
- return loaded.sort((a, b) => a - b);
1220
- }
1221
- },
1222
- prevPageIndex: 'action.queryParams.prevPageIndex'
1223
- },
1224
- preloaded: {
1225
- $path: 'preload',
1226
- $default: false
1227
- },
1228
- results: ({
1229
- action,
1230
- pageIndex,
1231
- result,
1232
- prevResults,
1233
- state
1234
- }) => {
1235
- const {
1236
- loadMorePaging,
1237
- pagesLoaded,
1238
- prevPageIndex
1239
- } = action.queryParams;
1240
- const results = mapEntriesToSearchResults(action, getItemsFromResult(result), state);
1241
- if (!loadMorePaging) return results;
1242
-
1243
- // add a _pageIndex property to the returned results to help us later
1244
- const nextResults = results.map((r, idx) => ({
1245
- _pageIndex: pageIndex,
1246
- _pagePosition: idx,
1247
- ...r
1248
- }));
1249
- const loadedPages = pagesLoaded || [];
1250
-
1251
- // if pageIndex is found in loadedPages, we have already loaded this page
1252
- if (!isNaN(loadedPages.find(l => l === pageIndex))) return prevResults;
1253
-
1254
- // Determine where we put the results depending on if we
1255
- // are paging forwards, backwards, or doing a new search
1256
- const firstResultSet = pageIndex > prevPageIndex ? prevResults || [] : nextResults;
1257
- const secondResultSet = pageIndex > prevPageIndex ? nextResults : prevResults || [];
1258
- const onlyResultSet = loadedPages.length === 0 ? nextResults : false;
1259
- return onlyResultSet || [...firstResultSet, ...secondResultSet];
1260
- }
1261
- },
1262
- preload: 'action.preload',
1263
- ogState: 'action.ogState',
1264
- debug: 'action.debug'
1265
- };
1266
- const filterTemplate = {
1267
- type: ({
1268
- type
1269
- }) => type || LOAD_FILTERS_COMPLETE,
1270
- context: 'context',
1271
- facetKey: 'facetKey',
1272
- filterKey: 'filterKey',
1273
- nextFilter: {
1274
- isLoading: () => false,
1275
- isError: ({
1276
- type
1277
- }) => type === LOAD_FILTERS_ERROR,
1278
- items: ({
1279
- payload,
1280
- selectedKeys,
1281
- mapper
1282
- }) => {
1283
- if (payload && (payload.items || payload.children)) {
1284
- const items = (payload.items || payload.children).map(item => {
1285
- var _item$sys;
1286
- item.isSelected = selectedKeys === null || selectedKeys === void 0 ? void 0 : selectedKeys.includes((item === null || item === void 0 || (_item$sys = item.sys) === null || _item$sys === void 0 ? void 0 : _item$sys.id) || item.key);
1287
- return item;
1288
- });
1289
- return mapper(items);
1290
- }
1291
- return [];
1292
- }
1293
- },
1294
- error: {
1295
- $path: 'error',
1296
- $disable: e => !e
1297
- }
1298
- };
1299
-
1300
- const filterExpressionMapper = {
1301
- // Expression type: so we can identify how to build the query
1302
- expressionType: ({
1303
- contentTypeId
1304
- }) => contentTypeId ? FilterExpressionTypes.contentType : FilterExpressionTypes.field,
1305
- // Key: so we can target the query to a specific field
1306
- key: 'fieldId',
1307
- // Value: so we can filter a specific field by an array of values
1308
- // e.g. taxonomy key or contentTypeId array
1309
- values: 'selectedValues',
1310
- fieldOperator: 'fieldOperator',
1311
- logicOperator: 'logicOperator'
1312
- };
1313
- const mapFilterToFilterExpression = filter => mapJson(filter, filterExpressionMapper);
1314
-
1315
- const mapFiltersToFilterExpression = (filters, selectedFilters) => {
1316
- if (!selectedFilters || Object.keys(selectedFilters).length === 0) return [];
1317
- const filterExpressions = [];
1318
-
1319
- // Iterate through the keys in selectedFilters and locate
1320
- // the items that are selected and queryable
1321
- Object.entries(selectedFilters).map(([fkey, selectedValues]) => {
1322
- const filter = filters[fkey];
1323
- if (selectedValues && filter) {
1324
- // Where we have a value for a selectedFilter
1325
- // and a filter is found for the current key
1326
- // map the filter to a filterExpression object
1327
- const expr = mapFilterToFilterExpression({
1328
- ...filter,
1329
- selectedValues
1330
- });
1331
- filterExpressions.push(expr);
1332
- }
1333
- });
1334
- return filterExpressions;
1335
- };
1336
-
1337
- const queryParamsTemplate = {
1338
- assetTypes: root => getQueryParameter(root, 'assetTypes', []),
1339
- contentTypeIds: root => getQueryParameter(root, 'contentTypeIds', []),
1340
- customWhere: root => getQueryParameter(root, 'customWhere', []),
1341
- dynamicOrderBy: root => getQueryParameter(root, 'dynamicOrderBy', []),
1342
- env: ({
1343
- state,
1344
- facet,
1345
- context
1346
- }) => getCustomEnv(state, facet, context),
1347
- excludeIds: ({
1348
- action: {
1349
- excludeIds
1350
- }
1351
- }) => {
1352
- // Exclude current route entry id from minilist searches or any supplied ids
1353
- if (excludeIds) return Array.isArray(excludeIds) ? excludeIds : excludeIds.split(',').map(id => id.trim());
1354
- return null;
1355
- },
1356
- featuredResults: root => getQueryParameter(root, 'featuredResults', null),
1357
- fieldLinkDepths: root => getQueryParameter(root, 'fieldLinkDepths', []),
1358
- fields: root => getQueryParameter(root, 'fields', []),
1359
- filters: ({
1360
- state,
1361
- facet,
1362
- context
1363
- }) => {
1364
- const stateFilters = getFilters(state, facet, context, 'js');
1365
- const selectedFilters = getSelectedFilters(state, facet, context, 'js');
1366
- // Use another mapping function to map the filter parameters for the query
1367
- const filterParams = mapFiltersToFilterExpression(stateFilters, selectedFilters);
1368
- return filterParams;
1369
- },
1370
- fuzzySearch: root => getQueryParameter(root, 'fuzzySearch', false),
1371
- includeInSearchFields: root => getQueryParameter(root, 'includeInSearch', []),
1372
- internalPageIndex: ({
1373
- action,
1374
- state
1375
- }) => getPageIndex(state, '', action.context),
1376
- internalPaging: root => getQueryParameter(root, 'internalPaging', false),
1377
- languages: ({
1378
- action
1379
- }) => action.defaultLang ? [action.defaultLang] : [],
1380
- linkDepth: root => getQueryParameter(root, 'linkDepth', 0),
1381
- loadMorePaging: root => getQueryParameter(root, 'loadMorePaging', false),
1382
- omitDefaultSearchFields: root => getQueryParameter(root, 'omitDefaultSearchFields', []),
1383
- orderBy: root => getQueryParameter(root, 'orderBy', []),
1384
- pageIndex: root => {
1385
- const {
1386
- action,
1387
- state
1388
- } = root;
1389
- if (getQueryParameter(root, 'internalPaging', false)) return 0;
1390
- if (action.type === UPDATE_PAGE_INDEX) return action.params.pageIndex;
1391
- return !action.preload ? getPageIndex(state, action.facet, action.context) : 0;
1392
- },
1393
- pageSize: root => {
1394
- const {
1395
- action,
1396
- state
1397
- } = root;
1398
- return getPageSize(state, action.facet, action.context) || getQueryParameter(root, 'pageSize');
1399
- },
1400
- pagesLoaded: ({
1401
- state,
1402
- facet,
1403
- context
1404
- }) => getPagesLoaded(state, facet, context),
1405
- prevPageIndex: ({
1406
- state,
1407
- facet,
1408
- context
1409
- }) => getPrevPageIndex(state, facet, context),
1410
- projectId: ({
1411
- state,
1412
- facet,
1413
- context
1414
- }) => {
1415
- var _getFacet;
1416
- return ((_getFacet = getFacet(state, facet, context, 'js')) === null || _getFacet === void 0 ? void 0 : _getFacet.projectId) || selectCurrentProject(state);
1417
- },
1418
- searchTerm: root => root.context !== Context.minilist || getQueryParameter(root, 'useSearchTerm', false) ? getSearchTerm(root.state) : '',
1419
- selectedFilters: ({
1420
- state,
1421
- facet,
1422
- context
1423
- }) => Object.fromEntries(Object.entries(getSelectedFilters(state, facet, context, 'js')).map(([key, f]) => [key, f === null || f === void 0 ? void 0 : f.join(',')])),
1424
- versionStatus: ({
1425
- state
1426
- }) => selectVersionStatus(state),
1427
- weightedSearchFields: root => {
1428
- const wsf = getQueryParameter(root, 'weightedSearchFields', []);
1429
- const deduped = wsf.filter((v, i, a) => a.findIndex(t => t.fieldId === v.fieldId) === i);
1430
- return deduped;
1431
- // return wsf;
1432
- },
1433
- webpageTemplates: root => getQueryParameter(root, 'webpageTemplates', [])
1434
- };
1435
- const mapStateToQueryParams = sourceJson => mapJson(sourceJson, queryParamsTemplate);
1436
-
1437
- /**
1438
- * 1, Generates all the parameters required to run the search query.
1439
- * 2, Tells us if we should run the search.
1440
- * @param {object} action
1441
- * @param {AppState} state
1442
- * @returns [queryParams, runSearch]
1443
- */
1444
- const generateQueryParams = (action, state) => {
1445
- const {
1446
- context,
1447
- facet
1448
- } = action;
1449
- // Map parameters using state and some additional
1450
- // inputs from the action
1451
- const queryParams = mapStateToQueryParams({
1452
- context,
1453
- facet,
1454
- action,
1455
- state
1456
- });
1457
- return [queryParams, runSearch(action, state, queryParams)];
1458
- };
1459
-
1460
- /**
1461
- * Checks if we have already loaded everything we're asking for and tells us to run the search or not
1462
- * @param action
1463
- * @param state
1464
- */
1465
- const runSearch = (action, state, queryParams) => {
1466
- const {
1467
- context,
1468
- defaultLang,
1469
- facet,
1470
- ogState = state,
1471
- preload,
1472
- ssr
1473
- } = action;
1474
- let willRun = false;
1475
- const facetIsLoaded = defaultLang ? false : getIsLoaded(state, context, facet);
1476
- const stateParams = {
1477
- ...getQueryParams(ogState, facet, context)
1478
- };
1479
- stateParams.pageIndex = getPageIndex(ogState, facet, context);
1480
- stateParams.searchTerm = getSearchTerm(ogState);
1481
- stateParams.pageSize = getPageSize(ogState, facet, context);
1482
- if (context === Context.facets && ssr ||
1483
- // context === Context.minilist ||
1484
- preload || !facetIsLoaded || filterParamsChanged(action) || defaultLang) {
1485
- willRun = true;
1486
- } else {
1487
- // Don't execute the search if the inbound query params
1488
- // are the same as what we already have in state
1489
- Object.entries(stateParams).forEach(([param, value]) => {
1490
- const queryParam = queryParams[param];
1491
- if (JSON.stringify(value) !== JSON.stringify(queryParam)) {
1492
- willRun = true;
1493
- }
1494
- });
1495
- }
1496
- const internalPaging = getIsInternalPaging(ogState, facet, context);
1497
- if (internalPaging && facetIsLoaded) {
1498
- willRun = false;
1499
- }
1500
- return willRun;
1501
- };
1502
-
1503
- /**
1504
- * This will tell us if filter parameters have been
1505
- * changed by some external event such as a route change
1506
- * @param action
1507
- * @returns true or false
1508
- */
1509
- const filterParamsChanged = (action, state) => {
1510
- const {
1511
- context,
1512
- facet,
1513
- params,
1514
- ogState = state
1515
- } = action;
1516
- const selectedFilters = getSelectedFilters(ogState, facet, context, 'js');
1517
- const paramsChanged = Object.entries(selectedFilters).map(([filterKey, selectedValues]) => {
1518
- const inboundValues = params && params[filterKey] && params[filterKey].split(',') || [];
1519
- if (!areArraysEqualSets(selectedValues, inboundValues)) return true;
1520
- });
1521
- return paramsChanged.filter(f => f === true).length > 0;
1522
- };
1523
-
1524
- /* eslint-disable no-console */
1525
- const debugExecuteSearch = (action, state) => {
1526
- const [queryParams, runSearch] = generateQueryParams(action, state);
1527
- console.log('runSearch', runSearch, 'action', action, 'filterParamsChanged', filterParamsChanged(action, state), 'getIsLoaded(state, context, facet)', getIsLoaded(state, action.context, action.facet));
1528
- const stateParams = {
1529
- ...getQueryParams(action.ogState || state, action.facet, action.context),
1530
- pageIndex: getPageIndex(action.ogState || state, action.facet, action.context),
1531
- searchTerm: getSearchTerm(action.ogState || state)
1532
- };
1533
- console.log(stateParams, queryParams);
1534
- console.log('getSelectedFilters', getSelectedFilters(action.ogState || state, action.facet, action.context, 'js'), 'params', action.params);
1535
- };
1536
- const scrollTo = scrollToElement => {
1537
- if (typeof window !== 'undefined') {
1538
- if (typeof scrollToElement === 'number')
1539
- // Used to be Y coordinate, deprecated, because it's not accessible
1540
- console.warn('updatePageIndex arg2 needs string');else if (typeof scrollToElement === 'string') {
1541
- /* Effectively simulates an anchor link. Needed for accessibility, as window.scrollTo
1542
- does not change focus, only scrolls the screen */
1543
- window.location.href = `${location.pathname}${location.search}#${scrollToElement}`;
1544
- }
1545
- }
1546
- };
1547
-
1548
- // *** FILTER ITEM MAPPING ***
1549
-
1550
- // Base mapping, fields that are the same across all mappings
1551
- // to save repeating these elements in every mapper, spread this
1552
- // into your discrete mappings
1553
- const base = {
1554
- contentTypeId: Fields.sys.contentTypeId,
1555
- title: 'entryTitle',
1556
- key: 'sys.id',
1557
- path: 'sys.slug',
1558
- isSelected: 'isSelected'
1559
- };
1560
- const mapEntriesToFilterItems = entries => {
1561
- if (!entries) return [];
1562
- return entries.map(entry => {
1563
- const template = base;
1564
- if (template) {
1565
- return mapJson(entry, template);
1566
- }
1567
- return entry;
1568
- });
1569
- };
1570
-
1571
- const mapQueryParamsToCustomApi = queryParams => {
1572
- const customApiMapping = {
1573
- fieldLinkDepths: ({
1574
- fieldLinkDepths
1575
- }) => JSON.stringify(fieldLinkDepths),
1576
- fields: ({
1577
- fields
1578
- }) => JSON.stringify(fields),
1579
- orderBy: 'orderBy',
1580
- linkDepth: 'linkDepth',
1581
- pageSize: 'pageSize',
1582
- pageIndex: 'pageIndex',
1583
- term: {
1584
- $path: 'searchTerm',
1585
- $disable: t => !t
1586
- },
1587
- versionStatus: 'versionStatus'
1588
- };
1589
- Object.keys(queryParams.selectedFilters).forEach(k => {
1590
- customApiMapping[k] = {
1591
- $path: `selectedFilters.${k}`,
1592
- $disable: f => !f
1593
- };
1594
- });
1595
- return mapJson(queryParams, customApiMapping);
1596
- };
1597
-
1598
- const searchSagas = [takeEvery(CLEAR_FILTERS, clearFilters), takeEvery(DO_SEARCH, doSearch), takeEvery(SET_ROUTE_FILTERS, loadFilters), takeEvery(SET_SEARCH_ENTRIES, preloadOtherFacets), takeEvery(UPDATE_CURRENT_FACET, updateCurrentFacet), takeEvery(UPDATE_CURRENT_TAB, updateCurrentTab), takeEvery(UPDATE_PAGE_INDEX, updatePageIndex), takeEvery(UPDATE_PAGE_SIZE, updatePageSize), takeEvery(UPDATE_SEARCH_TERM, updateSearchTerm), takeEvery(UPDATE_SORT_ORDER, updateSortOrder), takeEvery(UPDATE_SELECTED_FILTERS, applySearchFilter)];
1599
- const toJS = obj => obj && 'toJS' in obj && typeof obj.toJS === 'function' ? obj.toJS() : obj;
1600
- function* setRouteFilters(action) {
1601
- const {
1602
- mappers,
1603
- params,
1604
- listingType,
1605
- defaultLang,
1606
- debug
1607
- } = action;
1608
- const context = listingType ? Context.listings : Context.facets;
1609
- const state = toJS(yield select());
1610
- const ssr = getIsSsr(state);
1611
-
1612
- // Get current facet from params or state
1613
- let currentFacet = params && params.facet || listingType;
1614
-
1615
- // If Listing use listing type (ignore params.facet)
1616
- if (context === Context.listings) {
1617
- currentFacet = listingType;
1618
- }
1619
-
1620
- // Pick the default facet from initialState
1621
- if (!currentFacet) {
1622
- var _Object$keys;
1623
- const tabs = getSearchTabs(state, 'js');
1624
- currentFacet = (tabs === null || tabs === void 0 ? void 0 : tabs[0].defaultFacet) || ((_Object$keys = Object.keys(getFacets(state, 'js'))) === null || _Object$keys === void 0 ? void 0 : _Object$keys[0]) || '';
1625
- }
1626
- const nextAction = {
1627
- type: SET_ROUTE_FILTERS,
1628
- context,
1629
- facet: currentFacet,
1630
- mappers,
1631
- params,
1632
- defaultLang,
1633
- ssr,
1634
- debug
1635
- };
1636
- yield put(nextAction);
1637
-
1638
- // keep track of this state ref for comparing changes to params later
1639
- const ogState = {
1640
- search: state.search
1641
- };
1642
-
1643
- // Using call instead of triggering from the put
1644
- // to allow this exported saga to continue during SSR
1645
- yield call(ensureSearch, {
1646
- ...nextAction,
1647
- ogState
1648
- });
1649
- }
1650
- function* doSearch(action) {
1651
- var _action$params;
1652
- const state = toJS(yield select());
1653
- if (action.config) {
1654
- // If the action contains a config object, we can add this to the
1655
- // state at runtime
1656
- yield put({
1657
- ...action,
1658
- type: APPLY_CONFIG
1659
- });
1660
- }
1661
- const nextAction = {
1662
- ...action,
1663
- type: SET_SEARCH_FILTERS,
1664
- ssr: getIsSsr(state),
1665
- facet: action.facet || ((_action$params = action.params) === null || _action$params === void 0 ? void 0 : _action$params.facet)
1666
- };
1667
- if (nextAction.facet && (action.config || Object.keys(getFacet(state, nextAction.facet, action.context, 'js')).length > 0)) {
1668
- yield put(nextAction);
1669
-
1670
- // keep track of this state ref for comparing changes to params later
1671
- const ogState = {
1672
- search: state.search
1673
- };
1674
- yield call(ensureSearch, {
1675
- ...nextAction,
1676
- ogState
1677
- });
1678
- }
1679
- }
1680
- function* loadFilters(action) {
1681
- const {
1682
- facet: facetKey,
1683
- context,
1684
- mappers = {}
1685
- } = action;
1686
- const filtersToLoad = yield select(getFiltersToLoad, facetKey, context, 'js');
1687
- if (filtersToLoad.length > 0) {
1688
- yield put({
1689
- type: LOAD_FILTERS,
1690
- filtersToLoad,
1691
- facetKey,
1692
- context
1693
- });
1694
- const selectedKeys = yield select(getSelectedFilters, facetKey, context, 'js');
1695
- const facet = yield select(getFacet, facetKey, context, 'js');
1696
- const filters = facet.filters || {};
1697
- const projectId = facet.projectId;
1698
- const filtersToLoadSagas = filters && filtersToLoad.map((filterKey = '') => {
1699
- return call(loadFilter, {
1700
- facetKey,
1701
- filterKey,
1702
- filter: filters[filterKey],
1703
- projectId,
1704
- selectedKeys: selectedKeys[filterKey],
1705
- context,
1706
- mapper: 'filterItems' in mappers && mappers.filterItems || mapEntriesToFilterItems
1707
- });
1708
- });
1709
- if (filtersToLoadSagas) yield all(filtersToLoadSagas);
1710
- }
1711
- }
1712
- function* loadFilter(action) {
1713
- const {
1714
- facetKey,
1715
- filterKey,
1716
- filter,
1717
- projectId,
1718
- selectedKeys,
1719
- context,
1720
- mapper
1721
- } = action;
1722
- const {
1723
- contentTypeId,
1724
- customWhere,
1725
- path
1726
- } = filter;
1727
- const createStateFrom = {
1728
- type: LOAD_FILTERS_COMPLETE,
1729
- context,
1730
- error: undefined,
1731
- facetKey,
1732
- filterKey,
1733
- payload: {},
1734
- selectedKeys,
1735
- mapper
1736
- };
1737
- try {
1738
- if (contentTypeId) {
1739
- const versionStatus = yield select(selectVersionStatus);
1740
- const query = filterQuery(Array.isArray(contentTypeId) ? contentTypeId : [contentTypeId], versionStatus, customWhere);
1741
- const payload = yield cachedSearch.search(query, 0, projectId);
1742
- if (!payload) throw new Error('No payload returned by search');
1743
- if (payload.type === 'error') throw payload;
1744
- createStateFrom.payload = payload;
1745
- }
1746
- if (path) {
1747
- const payload = yield cachedSearch.getTaxonomyNodeByPath(path, projectId);
1748
- if (!payload) throw new Error(`No payload returned for taxonomy path: '${path}'`);
1749
- if (payload.type === 'error') throw payload;
1750
- createStateFrom.payload = payload;
1751
- }
1752
- } catch (error) {
1753
- createStateFrom.type = LOAD_FILTERS_ERROR;
1754
- createStateFrom.error = error;
1755
- }
1756
- const nextAction = mapJson(createStateFrom, filterTemplate);
1757
- yield put(nextAction);
1758
- }
1759
- function* ensureSearch(action) {
1760
- const {
1761
- context,
1762
- facet,
1763
- debug
1764
- } = action;
1765
- try {
1766
- const state = yield select();
1767
- const nextAction = {
1768
- ...action,
1769
- ogState: action.ogState || {
1770
- search: state.search
1771
- }
1772
- };
1773
- const [queryParams, runSearch] = generateQueryParams(nextAction, state);
1774
- if (debug && (debug === true || debug.executeSearch)) debugExecuteSearch(nextAction, state);
1775
- if (runSearch) {
1776
- yield put({
1777
- type: EXECUTE_SEARCH,
1778
- facet,
1779
- context
1780
- });
1781
- yield call(executeSearch, {
1782
- ...nextAction,
1783
- context,
1784
- facet,
1785
- queryParams,
1786
- debug
1787
- });
1788
- }
1789
- } catch (error) {
1790
- // eslint-disable-next-line import/namespace
1791
- log.error(...['Error running search saga:', error, error.stack]);
1792
- }
1793
- }
1794
- function* executeSearch(action) {
1795
- const {
1796
- context,
1797
- facet,
1798
- queryParams,
1799
- mappers
1800
- } = action;
1801
- try {
1802
- const state = yield select();
1803
- let result = {};
1804
- let featuredResult;
1805
- let featuredQuery;
1806
- const customApi = getCustomApi(state, facet, context, 'js');
1807
- if (customApi) {
1808
- const apiParams = typeof mappers === 'object' && typeof mappers.customApi === 'function' && mappers.customApi(queryParams) || mapQueryParamsToCustomApi(queryParams);
1809
- result.payload = yield callCustomApi(customApi, apiParams);
1810
- result.duration = 1;
1811
- } else {
1812
- if (queryParams.featuredResults) {
1813
- featuredQuery = searchQuery(queryParams, true);
1814
- featuredResult = yield timedSearch(featuredQuery, queryParams.linkDepth, queryParams.projectId, queryParams.env);
1815
- // eslint-disable-next-line require-atomic-updates
1816
- queryParams.excludeIds = getItemsFromResult(featuredResult).map(fi => {
1817
- var _fi$sys;
1818
- return fi === null || fi === void 0 || (_fi$sys = fi.sys) === null || _fi$sys === void 0 ? void 0 : _fi$sys.id;
1819
- }).filter(fi => typeof fi === 'string');
1820
- }
1821
- const query = searchQuery(queryParams);
1822
- result = yield timedSearch(query, queryParams.linkDepth, queryParams.projectId, queryParams.env);
1823
- }
1824
- const createStateFrom = {
1825
- action,
1826
- featuredResult,
1827
- pageIndex: queryParams.internalPaging && queryParams.internalPageIndex || queryParams.pageIndex,
1828
- prevResults: getResults(state, facet, action.context, 'js'),
1829
- result,
1830
- state
1831
- };
1832
- const nextAction = mapJson(createStateFrom, facetTemplate);
1833
- yield put(nextAction);
1834
- } catch (error) {
1835
- // eslint-disable-next-line import/namespace
1836
- log.error(...['Error running search saga:', error, error.stack]);
1837
- }
1838
- }
1839
- function* preloadOtherFacets(action) {
1840
- const {
1841
- preload,
1842
- context,
1843
- facet,
1844
- debug
1845
- } = action;
1846
- const state = yield select();
1847
- const currentFacet = getCurrentFacet(state);
1848
- if (!preload && facet === currentFacet && context !== Context.listings) {
1849
- const allFacets = getFacets(state, 'js');
1850
- const otherFacets = Object.keys(allFacets).filter(f => f !== currentFacet);
1851
- yield all(otherFacets.map((preloadFacet = '') => {
1852
- const preloadAction = {
1853
- ...action,
1854
- facet: preloadFacet,
1855
- preload: true
1856
- };
1857
- const [queryParams, runSearch] = generateQueryParams(preloadAction, state);
1858
- if (debug && (debug === true || debug.preloadOtherFacets)) debugExecuteSearch(preloadAction, state);
1859
- return runSearch && call(executeSearch, {
1860
- ...action,
1861
- type: EXECUTE_SEARCH_PRELOAD,
1862
- preload: true,
1863
- facet: preloadFacet,
1864
- queryParams
1865
- });
1866
- }));
1867
- }
1868
- }
1869
- function* updateCurrentTab(action) {
1870
- const {
1871
- id,
1872
- mappers
1873
- } = action;
1874
- const state = yield select();
1875
- const facets = getFacets(state, 'js');
1876
- const tabs = getSearchTabs(state, 'js');
1877
- let nextFacet = tabs === null || tabs === void 0 ? void 0 : tabs[id].currentFacet;
1878
- if (!nextFacet) {
1879
- Object.entries(facets).map(([facetName, facet]) => {
1880
- if (facet.tabId === id && (tabs === null || tabs === void 0 ? void 0 : tabs[id].defaultFacet) === facetName) nextFacet = facetName;
1881
- });
1882
- }
1883
- // If the next Tab does not have a defaultFacet,
1884
- // take the first facet for that tab
1885
- if (!nextFacet) nextFacet = Object.entries(facets).filter(([, f]) => f.tabId === id)[0][0];
1886
- yield put(withMappers(updateCurrentFacet$1(nextFacet), mappers));
1887
- }
1888
- function* clearFilters(action) {
1889
- const {
1890
- mappers
1891
- } = action;
1892
- const uri = yield buildUri({}, mappers);
1893
- yield put(navigate(uri));
1894
- }
1895
- function* updateCurrentFacet(action) {
1896
- const {
1897
- facet,
1898
- mappers
1899
- } = action;
1900
- const pageIndex = yield select(getPageIndex, facet);
1901
- const uri = yield buildUri({
1902
- facet,
1903
- pageIndex
1904
- }, mappers);
1905
- yield put(navigate(uri));
1906
- }
1907
- function* updateSearchTerm(action) {
1908
- const {
1909
- term,
1910
- mappers
1911
- } = action;
1912
- const uri = yield buildUri({
1913
- term
1914
- }, mappers);
1915
- yield put(navigate(uri));
1916
- }
1917
- function* updateSortOrder(action) {
1918
- const {
1919
- orderBy,
1920
- facet,
1921
- mappers
1922
- } = action;
1923
- const uri = yield buildUri({
1924
- orderBy,
1925
- facet
1926
- }, mappers);
1927
- yield put(navigate(uri));
1928
- }
1929
- function* updatePageIndex(action) {
1930
- const {
1931
- pageIndex,
1932
- mappers,
1933
- scrollToElement
1934
- } = action;
1935
- const uri = yield buildUri({
1936
- pageIndex
1937
- }, mappers);
1938
- yield put(navigate(uri));
1939
- if (typeof scrollToElement !== 'undefined') scrollTo(scrollToElement);
1940
- }
1941
- function* updatePageSize(action) {
1942
- const {
1943
- pageSize,
1944
- mappers,
1945
- scrollToElement
1946
- } = action;
1947
- const uri = yield buildUri({
1948
- pageSize
1949
- }, mappers);
1950
- yield put(navigate(uri));
1951
- if (typeof scrollToElement !== 'undefined') scrollTo(scrollToElement);
1952
- }
1953
- function* applySearchFilter(action) {
1954
- const {
1955
- mappers,
1956
- scrollToElement
1957
- } = action;
1958
- const uri = yield buildUri({}, mappers);
1959
- yield put(navigate(uri));
1960
- if (typeof scrollToElement !== 'undefined') scrollTo(scrollToElement);
1961
- }
1962
- function* buildUri({
1963
- facet,
1964
- orderBy,
1965
- pageIndex = 0,
1966
- pageSize,
1967
- term
1968
- }, mappers) {
1969
- const state = yield select();
1970
- const mapUri = (mappers === null || mappers === void 0 ? void 0 : mappers.navigate) || mapStateToSearchUri;
1971
- const uri = mapUri({
1972
- state,
1973
- facet,
1974
- orderBy,
1975
- pageIndex,
1976
- pageSize,
1977
- term
1978
- });
1979
- // return uri;
1980
- return `${uri.path}${uri.search && `?${uri.search}` || ''}${uri.hash && `#${uri.hash}` || ''}`;
1981
- }
1982
- function* triggerMinilistSsr(options) {
1983
- yield call(doSearch, {
1984
- type: DO_SEARCH,
1985
- ...options
1986
- });
1987
- }
1988
- function* triggerListingSsr(options) {
1989
- yield call(setRouteFilters, options);
1990
- }
1991
- function* triggerSearchSsr(options) {
1992
- yield call(setRouteFilters, options);
1993
- }
1994
-
1995
- export { expressions as $, updateSelectedFilters as A, updateSortOrder$1 as B, selectListing as C, mapStateToSearchUri as D, Context as E, selectFacets as F, triggerSearch as G, getFilters as H, toArray as I, UPDATE_SELECTED_FILTERS as J, UPDATE_SEARCH_TERM as K, UPDATE_PAGE_SIZE as L, UPDATE_PAGE_INDEX as M, SET_SEARCH_ENTRIES as N, SET_ROUTE_FILTERS as O, LOAD_FILTERS_COMPLETE as P, LOAD_FILTERS_ERROR as Q, LOAD_FILTERS as R, SET_SEARCH_FILTERS as S, EXECUTE_SEARCH_ERROR as T, UPDATE_SORT_ORDER as U, EXECUTE_SEARCH as V, CLEAR_FILTERS as W, APPLY_CONFIG as X, actions as Y, selectors as Z, types as _, getPageIndex as a, queries as a0, doSearch as a1, setRouteFilters as a2, searchSagas as a3, triggerListingSsr as a4, triggerMinilistSsr as a5, triggerSearchSsr as a6, routeParams as a7, defaultExpressions as a8, contentTypeIdExpression as a9, filterExpressions as aa, termExpressions as ab, orderByExpression as ac, customWhereExpressions as ad, getCurrentTab as b, getFacet as c, getTabFacets as d, getFacetsTotalCount as e, getFacetTitles as f, getCurrentFacet as g, getFeaturedResults as h, getRenderableFilters as i, getIsLoading as j, getPaging as k, getPageIsLoading as l, getResults as m, getSearchTerm as n, getSearchTotalCount as o, getSelectedFilters as p, getQueryParameter as q, getTabsAndFacets as r, getTotalCount as s, clearFilters$1 as t, updateCurrentFacet$1 as u, updateCurrentTab$1 as v, withMappers as w, updatePageIndex$1 as x, updatePageSize$1 as y, updateSearchTerm$1 as z };
1996
- //# sourceMappingURL=sagas-waBQR0Ek.js.map