@zengenti/contensis-react-base 4.0.0-beta.2 → 4.0.0-beta.3

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