@zengenti/contensis-react-base 3.0.0-beta.7 → 3.0.0-beta.70

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