instantsearch.js 4.54.1 → 4.56.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/cjs/components/Breadcrumb/Breadcrumb.js +2 -2
  2. package/cjs/components/Hits/Hits.js +16 -7
  3. package/cjs/components/InfiniteHits/InfiniteHits.js +13 -2
  4. package/cjs/components/RangeInput/RangeInput.js +22 -11
  5. package/cjs/components/RefinementList/RefinementList.js +34 -52
  6. package/cjs/components/Slider/Rheostat.js +163 -249
  7. package/cjs/connectors/autocomplete/connectAutocomplete.js +1 -1
  8. package/cjs/connectors/geo-search/connectGeoSearch.js +1 -1
  9. package/cjs/connectors/hierarchical-menu/connectHierarchicalMenu.js +1 -1
  10. package/cjs/connectors/hits/connectHits.js +1 -1
  11. package/cjs/connectors/infinite-hits/connectInfiniteHits.js +55 -32
  12. package/cjs/connectors/menu/connectMenu.js +1 -1
  13. package/cjs/connectors/numeric-menu/connectNumericMenu.js +1 -1
  14. package/cjs/connectors/rating-menu/connectRatingMenu.js +7 -3
  15. package/cjs/connectors/refinement-list/connectRefinementList.js +1 -1
  16. package/cjs/connectors/toggle-refinement/connectToggleRefinement.js +14 -4
  17. package/cjs/helpers/insights.js +3 -4
  18. package/cjs/lib/InstantSearch.js +20 -6
  19. package/cjs/lib/insights/listener.js +43 -36
  20. package/cjs/lib/routers/history.js +55 -1
  21. package/cjs/lib/stateMappings/simple.js +1 -0
  22. package/cjs/lib/stateMappings/singleIndex.js +1 -0
  23. package/cjs/lib/utils/createSendEventForFacet.js +12 -2
  24. package/cjs/lib/utils/createSendEventForHits.js +34 -11
  25. package/cjs/lib/utils/render-args.js +3 -2
  26. package/cjs/lib/version.js +1 -1
  27. package/cjs/middlewares/createInsightsMiddleware.js +135 -33
  28. package/cjs/middlewares/createMetadataMiddleware.js +17 -5
  29. package/cjs/middlewares/createRouterMiddleware.js +5 -1
  30. package/cjs/widgets/hits/hits.js +1 -2
  31. package/cjs/widgets/hits-per-page/hits-per-page.js +3 -1
  32. package/cjs/widgets/index/index.js +8 -8
  33. package/cjs/widgets/infinite-hits/infinite-hits.js +1 -2
  34. package/dist/instantsearch.development.d.ts +143 -84
  35. package/dist/instantsearch.development.js +770 -584
  36. package/dist/instantsearch.development.js.map +1 -1
  37. package/dist/instantsearch.production.d.ts +143 -84
  38. package/dist/instantsearch.production.min.d.ts +143 -84
  39. package/dist/instantsearch.production.min.js +2 -2
  40. package/dist/instantsearch.production.min.js.map +1 -1
  41. package/es/components/Breadcrumb/Breadcrumb.d.ts +2 -2
  42. package/es/components/Breadcrumb/Breadcrumb.js +2 -2
  43. package/es/components/GeoSearchControls/GeoSearchButton.d.ts +1 -1
  44. package/es/components/GeoSearchControls/GeoSearchControls.d.ts +3 -3
  45. package/es/components/GeoSearchControls/GeoSearchToggle.d.ts +1 -1
  46. package/es/components/Hits/Hits.d.ts +5 -5
  47. package/es/components/Hits/Hits.js +15 -5
  48. package/es/components/InfiniteHits/InfiniteHits.d.ts +3 -2
  49. package/es/components/InfiniteHits/InfiniteHits.js +13 -2
  50. package/es/components/Pagination/Pagination.d.ts +2 -2
  51. package/es/components/RangeInput/RangeInput.d.ts +7 -4
  52. package/es/components/RangeInput/RangeInput.js +22 -11
  53. package/es/components/RefinementList/RefinementList.d.ts +0 -1
  54. package/es/components/RefinementList/RefinementList.js +34 -52
  55. package/es/components/RelevantSort/RelevantSort.d.ts +1 -1
  56. package/es/components/Selector/Selector.d.ts +2 -2
  57. package/es/components/Slider/Rheostat.d.ts +23 -17
  58. package/es/components/Slider/Rheostat.js +163 -249
  59. package/es/components/Slider/Slider.d.ts +1 -1
  60. package/es/connectors/autocomplete/connectAutocomplete.js +1 -1
  61. package/es/connectors/current-refinements/connectCurrentRefinements.d.ts +2 -2
  62. package/es/connectors/dynamic-widgets/connectDynamicWidgets.d.ts +2 -2
  63. package/es/connectors/geo-search/connectGeoSearch.d.ts +7 -7
  64. package/es/connectors/geo-search/connectGeoSearch.js +1 -1
  65. package/es/connectors/hierarchical-menu/connectHierarchicalMenu.js +1 -1
  66. package/es/connectors/hits/connectHits.js +1 -1
  67. package/es/connectors/infinite-hits/connectInfiniteHits.js +56 -33
  68. package/es/connectors/menu/connectMenu.d.ts +2 -2
  69. package/es/connectors/menu/connectMenu.js +1 -1
  70. package/es/connectors/numeric-menu/connectNumericMenu.js +1 -1
  71. package/es/connectors/pagination/connectPagination.d.ts +1 -1
  72. package/es/connectors/range/connectRange.d.ts +3 -3
  73. package/es/connectors/rating-menu/connectRatingMenu.js +7 -3
  74. package/es/connectors/refinement-list/connectRefinementList.d.ts +3 -3
  75. package/es/connectors/refinement-list/connectRefinementList.js +1 -1
  76. package/es/connectors/relevant-sort/connectRelevantSort.d.ts +1 -1
  77. package/es/connectors/toggle-refinement/connectToggleRefinement.js +13 -3
  78. package/es/helpers/insights.d.ts +2 -1
  79. package/es/helpers/insights.js +3 -3
  80. package/es/lib/InstantSearch.d.ts +24 -14
  81. package/es/lib/InstantSearch.js +21 -7
  82. package/es/lib/insights/listener.d.ts +10 -6
  83. package/es/lib/insights/listener.js +42 -36
  84. package/es/lib/routers/history.d.ts +3 -2
  85. package/es/lib/routers/history.js +56 -2
  86. package/es/lib/stateMappings/simple.js +1 -0
  87. package/es/lib/stateMappings/singleIndex.js +1 -0
  88. package/es/lib/utils/createSendEventForFacet.js +12 -2
  89. package/es/lib/utils/createSendEventForHits.d.ts +8 -0
  90. package/es/lib/utils/createSendEventForHits.js +33 -11
  91. package/es/lib/utils/defer.d.ts +2 -2
  92. package/es/lib/utils/render-args.js +3 -2
  93. package/es/lib/version.d.ts +1 -1
  94. package/es/lib/version.js +1 -1
  95. package/es/middlewares/createInsightsMiddleware.d.ts +12 -12
  96. package/es/middlewares/createInsightsMiddleware.js +136 -34
  97. package/es/middlewares/createMetadataMiddleware.d.ts +3 -1
  98. package/es/middlewares/createMetadataMiddleware.js +17 -5
  99. package/es/middlewares/createRouterMiddleware.js +5 -1
  100. package/es/types/insights.d.ts +19 -1
  101. package/es/types/middleware.d.ts +22 -6
  102. package/es/types/router.d.ts +15 -7
  103. package/es/types/widget.d.ts +1 -1
  104. package/es/widgets/dynamic-widgets/dynamic-widgets.d.ts +2 -2
  105. package/es/widgets/geo-search/createHTMLMarker.d.ts +1 -1
  106. package/es/widgets/geo-search/geo-search.d.ts +1 -1
  107. package/es/widgets/hits/hits.js +2 -3
  108. package/es/widgets/hits-per-page/hits-per-page.js +3 -1
  109. package/es/widgets/index/index.d.ts +20 -20
  110. package/es/widgets/index/index.js +8 -8
  111. package/es/widgets/infinite-hits/infinite-hits.js +2 -3
  112. package/es/widgets/panel/panel.d.ts +2 -2
  113. package/es/widgets/range-slider/range-slider.d.ts +1 -1
  114. package/package.json +7 -7
@@ -6,37 +6,71 @@ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _ty
6
6
  function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
7
7
  function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
8
8
  function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
9
- function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
10
- function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
11
9
  function _iterableToArrayLimit(arr, i) { var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; if (null != _i) { var _s, _e, _x, _r, _arr = [], _n = !0, _d = !1; try { if (_x = (_i = _i.call(arr)).next, 0 === i) { if (Object(_i) !== _i) return; _n = !1; } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0); } catch (err) { _d = !0, _e = err; } finally { try { if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; } finally { if (_d) throw _e; } } return _arr; } }
12
10
  function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
11
+ function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
12
+ function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
13
+ function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
14
+ function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
15
+ function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
16
+ function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
13
17
  import { getInsightsAnonymousUserTokenInternal } from "../helpers/index.js";
14
- import { warning, noop, getAppIdAndApiKey, find } from "../lib/utils/index.js";
15
- export function createInsightsMiddleware(props) {
16
- var _ref = props || {},
17
- _insightsClient = _ref.insightsClient,
18
- insightsInitParams = _ref.insightsInitParams,
19
- onEvent = _ref.onEvent;
20
- if (_insightsClient !== null && !_insightsClient) {
21
- if (process.env.NODE_ENV === 'development') {
22
- throw new Error("The `insightsClient` option is required if you want userToken to be automatically set in search calls. If you don't want this behaviour, set it to `null`.");
23
- } else {
24
- throw new Error('The `insightsClient` option is required. To disable, set it to `null`.');
25
- }
18
+ import { warning, noop, getAppIdAndApiKey, find, safelyRunOnBrowser } from "../lib/utils/index.js";
19
+ var ALGOLIA_INSIGHTS_VERSION = '2.6.0';
20
+ var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
21
+ export function createInsightsMiddleware() {
22
+ var props = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
23
+ var _insightsClient = props.insightsClient,
24
+ insightsInitParams = props.insightsInitParams,
25
+ onEvent = props.onEvent,
26
+ _props$$$internal = props.$$internal,
27
+ $$internal = _props$$$internal === void 0 ? false : _props$$$internal;
28
+ var potentialInsightsClient = _insightsClient;
29
+ if (!_insightsClient && _insightsClient !== null) {
30
+ safelyRunOnBrowser(function (_ref) {
31
+ var window = _ref.window;
32
+ var pointer = window.AlgoliaAnalyticsObject || 'aa';
33
+ if (typeof pointer === 'string') {
34
+ potentialInsightsClient = window[pointer];
35
+ }
36
+ if (!potentialInsightsClient) {
37
+ window.AlgoliaAnalyticsObject = pointer;
38
+ if (!window[pointer]) {
39
+ window[pointer] = function () {
40
+ if (!window[pointer].queue) {
41
+ window[pointer].queue = [];
42
+ }
43
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
44
+ args[_key] = arguments[_key];
45
+ }
46
+ window[pointer].queue.push(args);
47
+ };
48
+ window[pointer].version = ALGOLIA_INSIGHTS_VERSION;
49
+ window[pointer].shouldAddScript = true;
50
+ }
51
+ potentialInsightsClient = window[pointer];
52
+ }
53
+ });
26
54
  }
27
- var hasInsightsClient = Boolean(_insightsClient);
28
- var insightsClient = _insightsClient === null ? noop : _insightsClient;
55
+ // if still no insightsClient was found, we use a noop
56
+ var insightsClient = potentialInsightsClient || noop;
29
57
  return function (_ref2) {
30
58
  var instantSearchInstance = _ref2.instantSearchInstance;
59
+ // remove existing default insights middleware
60
+ // user-provided insights middleware takes precedence
61
+ var existingInsightsMiddlewares = instantSearchInstance.middleware.filter(function (m) {
62
+ return m.instance.$$type === 'ais.insights' && m.instance.$$internal;
63
+ }).map(function (m) {
64
+ return m.creator;
65
+ });
66
+ instantSearchInstance.unuse.apply(instantSearchInstance, _toConsumableArray(existingInsightsMiddlewares));
31
67
  var _getAppIdAndApiKey = getAppIdAndApiKey(instantSearchInstance.client),
32
68
  _getAppIdAndApiKey2 = _slicedToArray(_getAppIdAndApiKey, 2),
33
69
  appId = _getAppIdAndApiKey2[0],
34
70
  apiKey = _getAppIdAndApiKey2[1];
35
71
 
36
72
  // search-insights.js also throws an error so dev-only clarification is sufficient
37
- if (process.env.NODE_ENV === 'development' && !(appId && apiKey)) {
38
- throw new Error('[insights middleware]: could not extract Algolia credentials from searchClient');
39
- }
73
+ process.env.NODE_ENV === 'development' ? warning(Boolean(appId && apiKey), 'could not extract Algolia credentials from searchClient in insights middleware.') : void 0;
40
74
  var queuedUserToken = undefined;
41
75
  var userTokenBeforeInit = undefined;
42
76
  if (Array.isArray(insightsClient.queue)) {
@@ -66,15 +100,39 @@ export function createInsightsMiddleware(props) {
66
100
  // Otherwise, the `init` call might override it with anonymous user token.
67
101
  userTokenBeforeInit = userToken;
68
102
  });
69
- insightsClient('init', _objectSpread({
70
- appId: appId,
71
- apiKey: apiKey
72
- }, insightsInitParams));
103
+
104
+ // Only `init` if the `insightsInitParams` option is passed or
105
+ // if the `insightsClient` version doesn't supports optional `init` calling.
106
+ if (insightsInitParams || !isModernInsightsClient(insightsClient)) {
107
+ insightsClient('init', _objectSpread({
108
+ appId: appId,
109
+ apiKey: apiKey,
110
+ partial: true
111
+ }, insightsInitParams));
112
+ }
73
113
  var initialParameters;
74
114
  var helper;
75
115
  return {
116
+ $$type: 'ais.insights',
117
+ $$internal: $$internal,
76
118
  onStateChange: function onStateChange() {},
77
- subscribe: function subscribe() {},
119
+ subscribe: function subscribe() {
120
+ if (!insightsClient.shouldAddScript) return;
121
+ var errorMessage = '[insights middleware]: could not load search-insights.js. Please load it manually following https://alg.li/insights-init';
122
+ try {
123
+ var script = document.createElement('script');
124
+ script.async = true;
125
+ script.src = ALGOLIA_INSIGHTS_SRC;
126
+ script.onerror = function () {
127
+ instantSearchInstance.emit('error', new Error(errorMessage));
128
+ };
129
+ document.body.appendChild(script);
130
+ insightsClient.shouldAddScript = false;
131
+ } catch (cause) {
132
+ insightsClient.shouldAddScript = false;
133
+ instantSearchInstance.emit('error', new Error(errorMessage));
134
+ }
135
+ },
78
136
  started: function started() {
79
137
  insightsClient('addAlgoliaAgent', 'insights-middleware');
80
138
  helper = instantSearchInstance.helper;
@@ -85,15 +143,23 @@ export function createInsightsMiddleware(props) {
85
143
  helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread(_objectSpread({}, helper.state), {}, {
86
144
  clickAnalytics: true
87
145
  }));
88
- instantSearchInstance.scheduleSearch();
146
+ if (!$$internal) {
147
+ instantSearchInstance.scheduleSearch();
148
+ }
89
149
  var setUserTokenToSearch = function setUserTokenToSearch(userToken) {
150
+ if (!userToken) {
151
+ return;
152
+ }
153
+ var existingToken = helper.state.userToken;
90
154
  helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread(_objectSpread({}, helper.state), {}, {
91
155
  userToken: userToken
92
156
  }));
93
- instantSearchInstance.scheduleSearch();
157
+ if (existingToken && existingToken !== userToken) {
158
+ instantSearchInstance.scheduleSearch();
159
+ }
94
160
  };
95
161
  var anonymousUserToken = getInsightsAnonymousUserTokenInternal();
96
- if (hasInsightsClient && anonymousUserToken) {
162
+ if (anonymousUserToken) {
97
163
  // When `aa('init', { ... })` is called, it creates an anonymous user token in cookie.
98
164
  // We can set it as userToken.
99
165
  setUserTokenToSearch(anonymousUserToken);
@@ -102,8 +168,10 @@ export function createInsightsMiddleware(props) {
102
168
  // We consider the `userToken` coming from a `init` call to have a higher
103
169
  // importance than the one coming from the queue.
104
170
  if (userTokenBeforeInit) {
171
+ setUserTokenToSearch(userTokenBeforeInit);
105
172
  insightsClient('setUserToken', userTokenBeforeInit);
106
173
  } else if (queuedUserToken) {
174
+ setUserTokenToSearch(queuedUserToken);
107
175
  insightsClient('setUserToken', queuedUserToken);
108
176
  }
109
177
 
@@ -111,16 +179,31 @@ export function createInsightsMiddleware(props) {
111
179
  insightsClient('onUserTokenChange', setUserTokenToSearch, {
112
180
  immediate: true
113
181
  });
182
+ var insightsClientWithLocalCredentials = insightsClient;
183
+ if (isModernInsightsClient(insightsClient)) {
184
+ insightsClientWithLocalCredentials = function insightsClientWithLocalCredentials(method, payload) {
185
+ var extraParams = {
186
+ headers: {
187
+ 'X-Algolia-Application-Id': appId,
188
+ 'X-Algolia-API-Key': apiKey
189
+ }
190
+ };
191
+
192
+ // @ts-ignore we are calling this only when we know that the client actually is correct
193
+ return insightsClient(method, payload, extraParams);
194
+ };
195
+ }
114
196
  instantSearchInstance.sendEventToInsights = function (event) {
115
197
  if (onEvent) {
116
- onEvent(event, _insightsClient);
198
+ onEvent(event, insightsClientWithLocalCredentials);
117
199
  } else if (event.insightsMethod) {
118
- var hasUserToken = Boolean(helper.state.userToken);
119
- if (hasUserToken) {
120
- insightsClient(event.insightsMethod, event.payload);
121
- } else {
122
- process.env.NODE_ENV === 'development' ? warning(false, "\nCannot send event to Algolia Insights because `userToken` is not set.\n\nSee documentation: https://www.algolia.com/doc/guides/building-search-ui/going-further/send-insights-events/js/#setting-the-usertoken\n") : void 0;
200
+ // Source is used to differentiate events sent by instantsearch from those sent manually.
201
+ event.payload.algoliaSource = ['instantsearch'];
202
+ if (event.eventModifier === 'internal') {
203
+ event.payload.algoliaSource.push('instantsearch-internal');
123
204
  }
205
+ insightsClientWithLocalCredentials(event.insightsMethod, event.payload);
206
+ process.env.NODE_ENV === 'development' ? warning(Boolean(helper.state.userToken), "\nCannot send event to Algolia Insights because `userToken` is not set.\n\nSee documentation: https://www.algolia.com/doc/guides/building-search-ui/going-further/send-insights-events/js/#setting-the-usertoken\n") : void 0;
124
207
  } else {
125
208
  process.env.NODE_ENV === 'development' ? warning(false, 'Cannot send event to Algolia Insights because `insightsMethod` option is missing.') : void 0;
126
209
  }
@@ -130,10 +213,29 @@ export function createInsightsMiddleware(props) {
130
213
  insightsClient('onUserTokenChange', undefined);
131
214
  instantSearchInstance.sendEventToInsights = noop;
132
215
  if (helper && initialParameters) {
133
- helper.setState(_objectSpread(_objectSpread({}, helper.state), initialParameters));
216
+ helper.overrideStateWithoutTriggeringChangeEvent(_objectSpread(_objectSpread({}, helper.state), initialParameters));
134
217
  instantSearchInstance.scheduleSearch();
135
218
  }
136
219
  }
137
220
  };
138
221
  };
222
+ }
223
+
224
+ /**
225
+ * Determines if a given insights `client` supports the optional call to `init`
226
+ * and the ability to set credentials via extra parameters when sending events.
227
+ */
228
+ function isModernInsightsClient(client) {
229
+ var _split$map = (client.version || '').split('.').map(Number),
230
+ _split$map2 = _slicedToArray(_split$map, 2),
231
+ major = _split$map2[0],
232
+ minor = _split$map2[1];
233
+
234
+ /* eslint-disable @typescript-eslint/naming-convention */
235
+ var v3 = major >= 3;
236
+ var v2_6 = major === 2 && minor >= 6;
237
+ var v1_10 = major === 1 && minor >= 10;
238
+ /* eslint-enable @typescript-eslint/naming-convention */
239
+
240
+ return v3 || v2_6 || v1_10;
139
241
  }
@@ -7,4 +7,6 @@ export declare function isMetadataEnabled(): boolean;
7
7
  * - widget name
8
8
  * - connector name
9
9
  */
10
- export declare function createMetadataMiddleware(): InternalMiddleware;
10
+ export declare function createMetadataMiddleware({ $$internal, }?: {
11
+ $$internal?: boolean;
12
+ }): InternalMiddleware;
@@ -1,5 +1,5 @@
1
1
  import { createInitArgs, safelyRunOnBrowser } from "../lib/utils/index.js";
2
- function extractPayload(widgets, instantSearchInstance, payload) {
2
+ function extractWidgetPayload(widgets, instantSearchInstance, payload) {
3
3
  var initOptions = createInitArgs(instantSearchInstance, instantSearchInstance.mainIndex, instantSearchInstance._initialUiState);
4
4
  widgets.forEach(function (widget) {
5
5
  var widgetParams = {};
@@ -21,7 +21,7 @@ function extractPayload(widgets, instantSearchInstance, payload) {
21
21
  params: params
22
22
  });
23
23
  if (widget.$$type === 'ais.index') {
24
- extractPayload(widget.getWidgets(), instantSearchInstance, payload);
24
+ extractWidgetPayload(widget.getWidgets(), instantSearchInstance, payload);
25
25
  }
26
26
  });
27
27
  }
@@ -45,8 +45,11 @@ export function isMetadataEnabled() {
45
45
  * - connector name
46
46
  */
47
47
  export function createMetadataMiddleware() {
48
- return function (_ref2) {
49
- var instantSearchInstance = _ref2.instantSearchInstance;
48
+ var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
49
+ _ref2$$$internal = _ref2.$$internal,
50
+ $$internal = _ref2$$$internal === void 0 ? false : _ref2$$$internal;
51
+ return function (_ref3) {
52
+ var instantSearchInstance = _ref3.instantSearchInstance;
50
53
  var payload = {
51
54
  widgets: []
52
55
  };
@@ -54,13 +57,22 @@ export function createMetadataMiddleware() {
54
57
  var refNode = document.querySelector('head');
55
58
  payloadContainer.name = 'instantsearch:widgets';
56
59
  return {
60
+ $$type: 'ais.metadata',
61
+ $$internal: $$internal,
57
62
  onStateChange: function onStateChange() {},
58
63
  subscribe: function subscribe() {
59
64
  // using setTimeout here to delay extraction until widgets have been added in a tick (e.g. Vue)
60
65
  setTimeout(function () {
61
66
  var client = instantSearchInstance.client;
62
67
  payload.ua = client.transporter && client.transporter.userAgent ? client.transporter.userAgent.value : client._ua;
63
- extractPayload(instantSearchInstance.mainIndex.getWidgets(), instantSearchInstance, payload);
68
+ extractWidgetPayload(instantSearchInstance.mainIndex.getWidgets(), instantSearchInstance, payload);
69
+ instantSearchInstance.middleware.forEach(function (middleware) {
70
+ return payload.widgets.push({
71
+ middleware: true,
72
+ type: middleware.instance.$$type,
73
+ internal: middleware.instance.$$internal
74
+ });
75
+ });
64
76
  payloadContainer.content = JSON.stringify(payload);
65
77
  refNode.appendChild(payloadContainer);
66
78
  }, 0);
@@ -12,7 +12,9 @@ export var createRouterMiddleware = function createRouterMiddleware() {
12
12
  var _props$router = props.router,
13
13
  router = _props$router === void 0 ? historyRouter() : _props$router,
14
14
  _props$stateMapping = props.stateMapping,
15
- stateMapping = _props$stateMapping === void 0 ? simpleStateMapping() : _props$stateMapping;
15
+ stateMapping = _props$stateMapping === void 0 ? simpleStateMapping() : _props$stateMapping,
16
+ _props$$$internal = props.$$internal,
17
+ $$internal = _props$$$internal === void 0 ? false : _props$$$internal;
16
18
  return function (_ref) {
17
19
  var instantSearchInstance = _ref.instantSearchInstance;
18
20
  function topLevelCreateURL(nextState) {
@@ -29,6 +31,8 @@ export var createRouterMiddleware = function createRouterMiddleware() {
29
31
  var lastRouteState = undefined;
30
32
  var initialUiState = instantSearchInstance._initialUiState;
31
33
  return {
34
+ $$type: "ais.router({router:".concat(router.$$type || '__unknown__', ", stateMapping:").concat(stateMapping.$$type || '__unknown__', "})"),
35
+ $$internal: $$internal,
32
36
  onStateChange: function onStateChange(_ref2) {
33
37
  var uiState = _ref2.uiState;
34
38
  var routeState = stateMapping.stateToRoute(uiState);
@@ -1,6 +1,24 @@
1
- import type { InsightsMethodMap, InsightsClient as _InsightsClient } from 'search-insights';
1
+ import type { Hit } from './results';
2
+ import type { InsightsMethodMap as _InsightsMethodMap, InsightsClient as _InsightsClient } from 'search-insights';
2
3
  export type { Init as InsightsInit, AddAlgoliaAgent as InsightsAddAlgoliaAgent, SetUserToken as InsightsSetUserToken, GetUserToken as InsightsGetUserToken, OnUserTokenChange as InsightsOnUserTokenChange, } from 'search-insights';
4
+ export type InsightsMethodMap = _InsightsMethodMap;
3
5
  export type InsightsClientMethod = keyof InsightsMethodMap;
6
+ /**
7
+ * Method allowed by the insights middleware.
8
+ */
9
+ export type InsightsMethod = 'clickedObjectIDsAfterSearch' | 'clickedObjectIDs' | 'clickedFilters' | 'convertedObjectIDsAfterSearch' | 'convertedObjectIDs' | 'convertedFilters' | 'viewedObjectIDs' | 'viewedFilters';
10
+ /**
11
+ * The event sent to the insights middleware.
12
+ */
13
+ export type InsightsEvent<TMethod extends InsightsMethod = InsightsMethod> = {
14
+ insightsMethod?: TMethod;
15
+ payload: InsightsMethodMap[TMethod][0];
16
+ widgetType: string;
17
+ eventType: string;
18
+ eventModifier?: string;
19
+ hits?: Hit[];
20
+ attribute?: string;
21
+ };
4
22
  export type InsightsClientPayload = {
5
23
  eventName: string;
6
24
  queryID: string;
@@ -2,15 +2,31 @@ import type InstantSearch from '../lib/InstantSearch';
2
2
  import type { UiState } from './ui-state';
3
3
  import type { AtLeastOne } from './utils';
4
4
  export type MiddlewareDefinition<TUiState extends UiState = UiState> = {
5
- onStateChange(options: {
5
+ /**
6
+ * string to identify the middleware
7
+ */
8
+ $$type: string;
9
+ /**
10
+ * Change handler called on every UiState change
11
+ */
12
+ onStateChange: (options: {
6
13
  uiState: TUiState;
7
- }): void;
8
- subscribe(): void;
9
- started(): void;
10
- unsubscribe(): void;
14
+ }) => void;
15
+ /**
16
+ * Called when the middleware is added to InstantSearch
17
+ */
18
+ subscribe: () => void;
19
+ /**
20
+ * Called when InstantSearch is started
21
+ */
22
+ started: () => void;
23
+ /**
24
+ * Called when the middleware is removed from InstantSearch
25
+ */
26
+ unsubscribe: () => void;
11
27
  };
12
28
  export type MiddlewareOptions = {
13
29
  instantSearchInstance: InstantSearch;
14
30
  };
15
31
  export type InternalMiddleware<TUiState extends UiState = UiState> = (options: MiddlewareOptions) => MiddlewareDefinition<TUiState>;
16
- export type Middleware = (options: MiddlewareOptions) => AtLeastOne<MiddlewareDefinition>;
32
+ export type Middleware<TUiState extends UiState = UiState> = (options: MiddlewareOptions) => AtLeastOne<MiddlewareDefinition<TUiState>>;
@@ -10,30 +10,34 @@ export type Router<TRouteState = UiState> = {
10
10
  * In the case of the history / URL in a browser, the callback will be called
11
11
  * by `onPopState`.
12
12
  */
13
- onUpdate(callback: (route: TRouteState) => void): void;
13
+ onUpdate: (callback: (route: TRouteState) => void) => void;
14
14
  /**
15
15
  * Reads the storage and gets a route object. It does not take parameters,
16
16
  * and should return an object
17
17
  */
18
- read(): TRouteState;
18
+ read: () => TRouteState;
19
19
  /**
20
20
  * Pushes a route object into a storage. Takes the UI state mapped by the state
21
21
  * mapping configured in the mapping
22
22
  */
23
- write(route: TRouteState): void;
23
+ write: (route: TRouteState) => void;
24
24
  /**
25
25
  * Transforms a route object into a URL. It receives an object and should
26
26
  * return a string. It may return an empty string.
27
27
  */
28
- createURL(state: TRouteState): string;
28
+ createURL: (state: TRouteState) => string;
29
29
  /**
30
30
  * Called when InstantSearch is disposed. Used to remove subscriptions.
31
31
  */
32
- dispose(): void;
32
+ dispose: () => void;
33
33
  /**
34
34
  * Called when InstantSearch is started.
35
35
  */
36
36
  start?: () => void;
37
+ /**
38
+ * Identifier for this router. Used to differentiate between routers.
39
+ */
40
+ $$type?: string;
37
41
  };
38
42
  /**
39
43
  * The state mapping is a way to customize the structure before sending it to the router.
@@ -48,11 +52,15 @@ export type StateMapping<TUiState = UiState, TRouteState = TUiState> = {
48
52
  * It should return an object of any form as long as this form can be read by
49
53
  * the `routeToState` function.
50
54
  */
51
- stateToRoute(uiState: TUiState): TRouteState;
55
+ stateToRoute: (uiState: TUiState) => TRouteState;
52
56
  /**
53
57
  * Transforms route object into a UI state representation.
54
58
  * It receives an object that contains the UI state stored by the router.
55
59
  * The format is the output of `stateToRoute`.
56
60
  */
57
- routeToState(routeState: TRouteState): TUiState;
61
+ routeToState: (routeState: TRouteState) => TUiState;
62
+ /**
63
+ * Identifier for this stateMapping. Used to differentiate between stateMappings.
64
+ */
65
+ $$type?: string;
58
66
  };
@@ -24,7 +24,7 @@ type SharedRenderOptions = {
24
24
  };
25
25
  status: InstantSearch['status'];
26
26
  error: InstantSearch['error'];
27
- createURL(state: SearchParameters): string;
27
+ createURL: (state: SearchParameters) => string;
28
28
  };
29
29
  export type InitOptions = SharedRenderOptions & {
30
30
  uiState: UiState;
@@ -14,12 +14,12 @@ export type DynamicWidgetsWidgetParams = {
14
14
  * Function to return a fallback widget when an attribute isn't found in
15
15
  * `widgets`.
16
16
  */
17
- fallbackWidget?(args: {
17
+ fallbackWidget?: (args: {
18
18
  /** The attribute name to create a widget for. */
19
19
  attribute: string;
20
20
  /** CSS Selector or HTMLElement to insert the widget */
21
21
  container: HTMLElement;
22
- }): Widget;
22
+ }) => Widget;
23
23
  };
24
24
  export type DynamicWidgetsWidget = WidgetFactory<DynamicWidgetsWidgetDescription & {
25
25
  $$widgetType: 'ais.dynamicWidgets';
@@ -28,7 +28,7 @@ interface Marker {
28
28
  };
29
29
  latLng: google.maps.LatLng;
30
30
  element: HTMLDivElement;
31
- getPosition(): google.maps.LatLng;
31
+ getPosition: () => google.maps.LatLng;
32
32
  }
33
33
  declare const createHTMLMarker: (googleReference: typeof google) => new (args: HTMLMarkerArguments) => google.maps.OverlayView & Marker;
34
34
  export default createHTMLMarker;
@@ -44,7 +44,7 @@ export type GeoSearchMarker<TOptions> = {
44
44
  * See the documentation for more information:
45
45
  * https://developers.google.com/maps/documentation/javascript/reference/3/#MarkerOptions
46
46
  */
47
- createOptions?(item: GeoHit): TOptions;
47
+ createOptions?: (item: GeoHit) => TOptions;
48
48
  /**
49
49
  * Object that takes an event type (ex: `click`, `mouseover`) as key and a
50
50
  * listener as value. The listener is provided with an object that contains:
@@ -8,7 +8,7 @@ import { cx } from '@algolia/ui-components-shared';
8
8
  import { h, render } from 'preact';
9
9
  import Hits from "../../components/Hits/Hits.js";
10
10
  import connectHits from "../../connectors/hits/connectHits.js";
11
- import { withInsights, withInsightsListener } from "../../lib/insights/index.js";
11
+ import { withInsights } from "../../lib/insights/index.js";
12
12
  import { component } from "../../lib/suit.js";
13
13
  import { prepareTemplateProps } from "../../lib/templating/index.js";
14
14
  import { getContainerNode, createDocumentationMessageGenerator } from "../../lib/utils/index.js";
@@ -17,7 +17,6 @@ var withUsage = createDocumentationMessageGenerator({
17
17
  name: 'hits'
18
18
  });
19
19
  var suit = component('Hits');
20
- var HitsWithInsightsListener = withInsightsListener(Hits);
21
20
  var renderer = function renderer(_ref) {
22
21
  var renderState = _ref.renderState,
23
22
  cssClasses = _ref.cssClasses,
@@ -38,7 +37,7 @@ var renderer = function renderer(_ref) {
38
37
  });
39
38
  return;
40
39
  }
41
- render(h(HitsWithInsightsListener, {
40
+ render(h(Hits, {
42
41
  cssClasses: cssClasses,
43
42
  hits: receivedHits,
44
43
  results: results,
@@ -31,7 +31,9 @@ var renderer = function renderer(_ref) {
31
31
  }, h(Selector, {
32
32
  cssClasses: cssClasses,
33
33
  currentValue: currentValue,
34
- options: items,
34
+ options: items
35
+ // @ts-expect-error: the refine function expects a number, but setValue will call it with a string. We don't want to change the type of the refine function because it's part of the connector API.
36
+ ,
35
37
  setValue: refine
36
38
  })), containerNode);
37
39
  };
@@ -19,39 +19,39 @@ export type IndexWidgetDescription = {
19
19
  export type IndexWidget<TUiState extends UiState = UiState> = Omit<Widget<IndexWidgetDescription & {
20
20
  widgetParams: IndexWidgetParams;
21
21
  }>, 'getWidgetUiState' | 'getWidgetState'> & {
22
- getIndexName(): string;
23
- getIndexId(): string;
24
- getHelper(): Helper | null;
25
- getResults(): SearchResults | null;
26
- getPreviousState(): SearchParameters | null;
27
- getScopedResults(): ScopedResult[];
28
- getParent(): IndexWidget | null;
29
- getWidgets(): Array<Widget | IndexWidget>;
30
- createURL(state: SearchParameters): string;
31
- addWidgets(widgets: Array<Widget | IndexWidget>): IndexWidget;
32
- removeWidgets(widgets: Array<Widget | IndexWidget>): IndexWidget;
33
- init(options: IndexInitOptions): void;
34
- render(options: IndexRenderOptions): void;
35
- dispose(): void;
22
+ getIndexName: () => string;
23
+ getIndexId: () => string;
24
+ getHelper: () => Helper | null;
25
+ getResults: () => SearchResults | null;
26
+ getPreviousState: () => SearchParameters | null;
27
+ getScopedResults: () => ScopedResult[];
28
+ getParent: () => IndexWidget | null;
29
+ getWidgets: () => Array<Widget | IndexWidget>;
30
+ createURL: (state: SearchParameters) => string;
31
+ addWidgets: (widgets: Array<Widget | IndexWidget>) => IndexWidget;
32
+ removeWidgets: (widgets: Array<Widget | IndexWidget>) => IndexWidget;
33
+ init: (options: IndexInitOptions) => void;
34
+ render: (options: IndexRenderOptions) => void;
35
+ dispose: () => void;
36
36
  /**
37
37
  * @deprecated
38
38
  */
39
- getWidgetState(uiState: UiState): UiState;
40
- getWidgetUiState<TSpecificUiState extends UiState = TUiState>(uiState: TSpecificUiState): TSpecificUiState;
41
- getWidgetSearchParameters(searchParameters: SearchParameters, searchParametersOptions: {
39
+ getWidgetState: (uiState: UiState) => UiState;
40
+ getWidgetUiState: <TSpecificUiState extends UiState = TUiState>(uiState: TSpecificUiState) => TSpecificUiState;
41
+ getWidgetSearchParameters: (searchParameters: SearchParameters, searchParametersOptions: {
42
42
  uiState: IndexUiState;
43
- }): SearchParameters;
43
+ }) => SearchParameters;
44
44
  /**
45
45
  * Set this index' UI state back to the state defined by the widgets.
46
46
  * Can only be called after `init`.
47
47
  */
48
- refreshUiState(): void;
48
+ refreshUiState: () => void;
49
49
  /**
50
50
  * Set this index' UI state and search. This is the equivalent of calling
51
51
  * a spread `setUiState` on the InstantSearch instance.
52
52
  * Can only be called after `init`.
53
53
  */
54
- setIndexUiState(indexUiState: TUiState[string] | ((previousIndexUiState: TUiState[string]) => TUiState[string])): void;
54
+ setIndexUiState: (indexUiState: TUiState[string] | ((previousIndexUiState: TUiState[string]) => TUiState[string])) => void;
55
55
  };
56
56
  declare const index: (widgetParams: IndexWidgetParams) => IndexWidget;
57
57
  export default index;
@@ -332,7 +332,7 @@ var index = function index(widgetParams) {
332
332
  // does not have access to lastResults, which it used to in pre-federated
333
333
  // search behavior.
334
334
  helper.lastResults = results;
335
- lastValidSearchParameters = results._state;
335
+ lastValidSearchParameters = results === null || results === void 0 ? void 0 : results._state;
336
336
  });
337
337
 
338
338
  // We compute the render state before calling `init` in a separate loop
@@ -388,16 +388,16 @@ var index = function index(widgetParams) {
388
388
  render: function render(_ref5) {
389
389
  var _this4 = this;
390
390
  var instantSearchInstance = _ref5.instantSearchInstance;
391
- if (!this.getResults()) {
392
- return;
393
- }
394
-
395
391
  // we can't attach a listener to the error event of search, as the error
396
392
  // then would no longer be thrown for global handlers.
397
- if (instantSearchInstance.status === 'error' && !instantSearchInstance.mainHelper.hasPendingRequests()) {
393
+ if (instantSearchInstance.status === 'error' && !instantSearchInstance.mainHelper.hasPendingRequests() && lastValidSearchParameters) {
398
394
  helper.setState(lastValidSearchParameters);
399
395
  }
400
- localWidgets.forEach(function (widget) {
396
+
397
+ // We only render index widgets if there are no results.
398
+ // This makes sure `render` is never called with `results` being `null`.
399
+ var widgetsToRender = this.getResults() ? localWidgets : localWidgets.filter(isIndexWidget);
400
+ widgetsToRender.forEach(function (widget) {
401
401
  if (widget.getRenderState) {
402
402
  var renderState = widget.getRenderState(instantSearchInstance.renderState[_this4.getIndexId()] || {}, createRenderArgs(instantSearchInstance, _this4));
403
403
  storeRenderState({
@@ -407,7 +407,7 @@ var index = function index(widgetParams) {
407
407
  });
408
408
  }
409
409
  });
410
- localWidgets.forEach(function (widget) {
410
+ widgetsToRender.forEach(function (widget) {
411
411
  // At this point, all the variables used below are set. Both `helper`
412
412
  // and `derivedHelper` have been created at the `init` step. The attribute
413
413
  // `lastResults` might be `null` though. It's possible that a stalled render