@algolia/autocomplete-core 1.8.3 → 1.9.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 (55) hide show
  1. package/dist/esm/createAutocomplete.js +12 -9
  2. package/dist/esm/createStore.js +4 -5
  3. package/dist/esm/getAutocompleteSetters.d.ts +6 -6
  4. package/dist/esm/getAutocompleteSetters.js +4 -11
  5. package/dist/esm/getCompletion.js +0 -3
  6. package/dist/esm/getDefaultProps.js +6 -22
  7. package/dist/esm/getPropGetters.js +40 -69
  8. package/dist/esm/metadata.js +6 -9
  9. package/dist/esm/onInput.js +25 -34
  10. package/dist/esm/onKeyDown.js +30 -40
  11. package/dist/esm/reshape.d.ts +1 -1
  12. package/dist/esm/reshape.js +17 -19
  13. package/dist/esm/resolve.js +10 -28
  14. package/dist/esm/stateReducer.js +7 -24
  15. package/dist/esm/types/AutocompleteStore.d.ts +1 -3
  16. package/dist/esm/types/AutocompleteSubscribers.d.ts +1 -2
  17. package/dist/esm/types/index.d.ts +16 -11
  18. package/dist/esm/types/index.js +3 -12
  19. package/dist/esm/utils/createCancelablePromise.js +0 -8
  20. package/dist/esm/utils/createConcurrentSafePromise.js +0 -1
  21. package/dist/esm/utils/getActiveItem.d.ts +1 -1
  22. package/dist/esm/utils/getActiveItem.js +4 -12
  23. package/dist/esm/utils/getNextActiveItemId.js +0 -4
  24. package/dist/esm/utils/getNormalizedSources.js +5 -10
  25. package/dist/esm/utils/mapToAlgoliaResponse.d.ts +1 -1
  26. package/dist/esm/utils/mapToAlgoliaResponse.js +4 -6
  27. package/dist/umd/index.development.js +961 -387
  28. package/dist/umd/index.development.js.map +1 -1
  29. package/dist/umd/index.production.js +2 -2
  30. package/dist/umd/index.production.js.map +1 -1
  31. package/package.json +6 -5
  32. package/dist/esm/types/AutocompleteApi.d.ts +0 -15
  33. package/dist/esm/types/AutocompleteApi.js +0 -1
  34. package/dist/esm/types/AutocompleteCollection.d.ts +0 -10
  35. package/dist/esm/types/AutocompleteCollection.js +0 -1
  36. package/dist/esm/types/AutocompleteContext.d.ts +0 -3
  37. package/dist/esm/types/AutocompleteContext.js +0 -1
  38. package/dist/esm/types/AutocompleteEnvironment.d.ts +0 -13
  39. package/dist/esm/types/AutocompleteEnvironment.js +0 -1
  40. package/dist/esm/types/AutocompleteNavigator.d.ts +0 -28
  41. package/dist/esm/types/AutocompleteNavigator.js +0 -1
  42. package/dist/esm/types/AutocompleteOptions.d.ts +0 -185
  43. package/dist/esm/types/AutocompleteOptions.js +0 -1
  44. package/dist/esm/types/AutocompletePlugin.d.ts +0 -43
  45. package/dist/esm/types/AutocompletePlugin.js +0 -1
  46. package/dist/esm/types/AutocompletePropGetters.d.ts +0 -100
  47. package/dist/esm/types/AutocompletePropGetters.js +0 -1
  48. package/dist/esm/types/AutocompleteReshape.d.ts +0 -25
  49. package/dist/esm/types/AutocompleteReshape.js +0 -1
  50. package/dist/esm/types/AutocompleteSetters.d.ts +0 -46
  51. package/dist/esm/types/AutocompleteSetters.js +0 -1
  52. package/dist/esm/types/AutocompleteSource.d.ts +0 -75
  53. package/dist/esm/types/AutocompleteSource.js +0 -1
  54. package/dist/esm/types/AutocompleteState.d.ts +0 -12
  55. package/dist/esm/types/AutocompleteState.js +0 -1
@@ -1,47 +1,42 @@
1
- /*! @algolia/autocomplete-core 1.8.3 | MIT License | © Algolia, Inc. and contributors | https://github.com/algolia/autocomplete */
1
+ /*! @algolia/autocomplete-core 1.9.0 | MIT License | © Algolia, Inc. and contributors | https://github.com/algolia/autocomplete */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
4
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
5
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@algolia/autocomplete-core"] = {}));
6
6
  })(this, (function (exports) { 'use strict';
7
7
 
8
- function ownKeys(object, enumerableOnly) {
8
+ function ownKeys$2(object, enumerableOnly) {
9
9
  var keys = Object.keys(object);
10
-
11
10
  if (Object.getOwnPropertySymbols) {
12
11
  var symbols = Object.getOwnPropertySymbols(object);
13
12
  enumerableOnly && (symbols = symbols.filter(function (sym) {
14
13
  return Object.getOwnPropertyDescriptor(object, sym).enumerable;
15
14
  })), keys.push.apply(keys, symbols);
16
15
  }
17
-
18
16
  return keys;
19
17
  }
20
-
21
18
  function _objectSpread2(target) {
22
19
  for (var i = 1; i < arguments.length; i++) {
23
20
  var source = null != arguments[i] ? arguments[i] : {};
24
- i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
25
- _defineProperty(target, key, source[key]);
26
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
21
+ i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) {
22
+ _defineProperty$2(target, key, source[key]);
23
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) {
27
24
  Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
28
25
  });
29
26
  }
30
-
31
27
  return target;
32
28
  }
33
-
34
- function _typeof$1(obj) {
29
+ function _typeof$3(obj) {
35
30
  "@babel/helpers - typeof";
36
31
 
37
- return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
32
+ return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
38
33
  return typeof obj;
39
34
  } : function (obj) {
40
35
  return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
41
- }, _typeof$1(obj);
36
+ }, _typeof$3(obj);
42
37
  }
43
-
44
- function _defineProperty(obj, key, value) {
38
+ function _defineProperty$2(obj, key, value) {
39
+ key = _toPropertyKey$2(key);
45
40
  if (key in obj) {
46
41
  Object.defineProperty(obj, key, {
47
42
  value: value,
@@ -52,35 +47,26 @@
52
47
  } else {
53
48
  obj[key] = value;
54
49
  }
55
-
56
50
  return obj;
57
51
  }
58
-
59
- function _objectWithoutPropertiesLoose(source, excluded) {
52
+ function _objectWithoutPropertiesLoose$1(source, excluded) {
60
53
  if (source == null) return {};
61
54
  var target = {};
62
55
  var sourceKeys = Object.keys(source);
63
56
  var key, i;
64
-
65
57
  for (i = 0; i < sourceKeys.length; i++) {
66
58
  key = sourceKeys[i];
67
59
  if (excluded.indexOf(key) >= 0) continue;
68
60
  target[key] = source[key];
69
61
  }
70
-
71
62
  return target;
72
63
  }
73
-
74
- function _objectWithoutProperties(source, excluded) {
64
+ function _objectWithoutProperties$1(source, excluded) {
75
65
  if (source == null) return {};
76
-
77
- var target = _objectWithoutPropertiesLoose(source, excluded);
78
-
66
+ var target = _objectWithoutPropertiesLoose$1(source, excluded);
79
67
  var key, i;
80
-
81
68
  if (Object.getOwnPropertySymbols) {
82
69
  var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
83
-
84
70
  for (i = 0; i < sourceSymbolKeys.length; i++) {
85
71
  key = sourceSymbolKeys[i];
86
72
  if (excluded.indexOf(key) >= 0) continue;
@@ -88,143 +74,149 @@
88
74
  target[key] = source[key];
89
75
  }
90
76
  }
91
-
92
77
  return target;
93
78
  }
94
-
95
- function _toConsumableArray(arr) {
96
- return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread();
79
+ function _toConsumableArray$2(arr) {
80
+ return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _unsupportedIterableToArray$4(arr) || _nonIterableSpread$2();
97
81
  }
98
-
99
- function _arrayWithoutHoles(arr) {
100
- if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
82
+ function _arrayWithoutHoles$2(arr) {
83
+ if (Array.isArray(arr)) return _arrayLikeToArray$4(arr);
101
84
  }
102
-
103
- function _iterableToArray(iter) {
85
+ function _iterableToArray$2(iter) {
104
86
  if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
105
87
  }
106
-
107
- function _unsupportedIterableToArray$1(o, minLen) {
88
+ function _unsupportedIterableToArray$4(o, minLen) {
108
89
  if (!o) return;
109
- if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
90
+ if (typeof o === "string") return _arrayLikeToArray$4(o, minLen);
110
91
  var n = Object.prototype.toString.call(o).slice(8, -1);
111
92
  if (n === "Object" && o.constructor) n = o.constructor.name;
112
93
  if (n === "Map" || n === "Set") return Array.from(o);
113
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
94
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$4(o, minLen);
114
95
  }
115
-
116
- function _arrayLikeToArray$1(arr, len) {
96
+ function _arrayLikeToArray$4(arr, len) {
117
97
  if (len == null || len > arr.length) len = arr.length;
118
-
119
98
  for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
120
-
121
99
  return arr2;
122
100
  }
123
-
124
- function _nonIterableSpread() {
101
+ function _nonIterableSpread$2() {
125
102
  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
126
103
  }
104
+ function _toPrimitive$2(input, hint) {
105
+ if (typeof input !== "object" || input === null) return input;
106
+ var prim = input[Symbol.toPrimitive];
107
+ if (prim !== undefined) {
108
+ var res = prim.call(input, hint || "default");
109
+ if (typeof res !== "object") return res;
110
+ throw new TypeError("@@toPrimitive must return a primitive value.");
111
+ }
112
+ return (hint === "string" ? String : Number)(input);
113
+ }
114
+ function _toPropertyKey$2(arg) {
115
+ var key = _toPrimitive$2(arg, "string");
116
+ return typeof key === "symbol" ? key : String(key);
117
+ }
127
118
 
128
- function _slicedToArray(arr, i) {
129
- return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
119
+ function createRef(initialValue) {
120
+ return {
121
+ current: initialValue
122
+ };
130
123
  }
131
124
 
132
- function _nonIterableRest() {
133
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
125
+ function debounce(fn, time) {
126
+ var timerId = undefined;
127
+ return function () {
128
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
129
+ args[_key] = arguments[_key];
130
+ }
131
+ if (timerId) {
132
+ clearTimeout(timerId);
133
+ }
134
+ timerId = setTimeout(function () {
135
+ return fn.apply(void 0, args);
136
+ }, time);
137
+ };
134
138
  }
135
139
 
136
- function _unsupportedIterableToArray(o, minLen) {
140
+ function _slicedToArray$1(arr, i) {
141
+ return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$3(arr, i) || _nonIterableRest$1();
142
+ }
143
+ function _nonIterableRest$1() {
144
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
145
+ }
146
+ function _unsupportedIterableToArray$3(o, minLen) {
137
147
  if (!o) return;
138
- if (typeof o === "string") return _arrayLikeToArray(o, minLen);
148
+ if (typeof o === "string") return _arrayLikeToArray$3(o, minLen);
139
149
  var n = Object.prototype.toString.call(o).slice(8, -1);
140
150
  if (n === "Object" && o.constructor) n = o.constructor.name;
141
151
  if (n === "Map" || n === "Set") return Array.from(o);
142
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
152
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$3(o, minLen);
143
153
  }
144
-
145
- function _arrayLikeToArray(arr, len) {
154
+ function _arrayLikeToArray$3(arr, len) {
146
155
  if (len == null || len > arr.length) len = arr.length;
147
-
148
- for (var i = 0, arr2 = new Array(len); i < len; i++) {
149
- arr2[i] = arr[i];
150
- }
151
-
156
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
152
157
  return arr2;
153
158
  }
154
-
155
- function _iterableToArrayLimit(arr, i) {
156
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
157
-
158
- if (_i == null) return;
159
- var _arr = [];
160
- var _n = true;
161
- var _d = false;
162
-
163
- var _s, _e;
164
-
165
- try {
166
- for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) {
167
- _arr.push(_s.value);
168
-
169
- if (i && _arr.length === i) break;
170
- }
171
- } catch (err) {
172
- _d = true;
173
- _e = err;
174
- } finally {
159
+ function _iterableToArrayLimit$1(arr, i) {
160
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
161
+ if (null != _i) {
162
+ var _s,
163
+ _e,
164
+ _x,
165
+ _r,
166
+ _arr = [],
167
+ _n = !0,
168
+ _d = !1;
175
169
  try {
176
- if (!_n && _i["return"] != null) _i["return"]();
170
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
171
+ if (Object(_i) !== _i) return;
172
+ _n = !1;
173
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
174
+ } catch (err) {
175
+ _d = !0, _e = err;
177
176
  } finally {
178
- if (_d) throw _e;
177
+ try {
178
+ if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
179
+ } finally {
180
+ if (_d) throw _e;
181
+ }
179
182
  }
183
+ return _arr;
180
184
  }
181
-
182
- return _arr;
183
185
  }
184
-
185
- function _arrayWithHoles(arr) {
186
+ function _arrayWithHoles$1(arr) {
186
187
  if (Array.isArray(arr)) return arr;
187
188
  }
188
-
189
- function _typeof(obj) {
189
+ function _typeof$2(obj) {
190
190
  "@babel/helpers - typeof";
191
191
 
192
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
192
+ return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
193
193
  return typeof obj;
194
194
  } : function (obj) {
195
195
  return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
196
- }, _typeof(obj);
196
+ }, _typeof$2(obj);
197
197
  }
198
198
  /**
199
199
  * Decycles objects with circular references.
200
200
  * This is used to print cyclic structures in development environment only.
201
201
  */
202
-
203
-
204
202
  function decycle(obj) {
205
203
  var seen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set();
206
-
207
- if (!obj || _typeof(obj) !== 'object') {
204
+ if (!obj || _typeof$2(obj) !== 'object') {
208
205
  return obj;
209
206
  }
210
-
211
207
  if (seen.has(obj)) {
212
208
  return '[Circular]';
213
209
  }
214
-
215
210
  var newSeen = seen.add(obj);
216
-
217
211
  if (Array.isArray(obj)) {
218
212
  return obj.map(function (x) {
219
213
  return decycle(x, newSeen);
220
214
  });
221
215
  }
222
-
223
216
  return Object.fromEntries(Object.entries(obj).map(function (_ref) {
224
- var _ref2 = _slicedToArray(_ref, 2),
225
- key = _ref2[0],
226
- value = _ref2[1];
227
-
217
+ var _ref2 = _slicedToArray$1(_ref, 2),
218
+ key = _ref2[0],
219
+ value = _ref2[1];
228
220
  return [key, decycle(value, newSeen)];
229
221
  }));
230
222
  }
@@ -244,54 +236,749 @@
244
236
  if (state.collections.length === 0) {
245
237
  return 0;
246
238
  }
247
-
248
- return state.collections.reduce(function (sum, collection) {
249
- return sum + collection.items.length;
239
+ return state.collections.reduce(function (sum, collection) {
240
+ return sum + collection.items.length;
241
+ }, 0);
242
+ }
243
+
244
+ /**
245
+ * Throws an error if the condition is not met in development mode.
246
+ * This is used to make development a better experience to provide guidance as
247
+ * to where the error comes from.
248
+ */
249
+ function invariant(condition, message) {
250
+ if (!condition) {
251
+ throw new Error("[Autocomplete] ".concat(typeof message === 'function' ? message() : message));
252
+ }
253
+ }
254
+
255
+ function isPrimitive(obj) {
256
+ return obj !== Object(obj);
257
+ }
258
+ function isEqual(first, second) {
259
+ if (first === second) {
260
+ return true;
261
+ }
262
+ if (isPrimitive(first) || isPrimitive(second) || typeof first === 'function' || typeof second === 'function') {
263
+ return first === second;
264
+ }
265
+ if (Object.keys(first).length !== Object.keys(second).length) {
266
+ return false;
267
+ }
268
+ for (var _i = 0, _Object$keys = Object.keys(first); _i < _Object$keys.length; _i++) {
269
+ var key = _Object$keys[_i];
270
+ if (!(key in second)) {
271
+ return false;
272
+ }
273
+ if (!isEqual(first[key], second[key])) {
274
+ return false;
275
+ }
276
+ }
277
+ return true;
278
+ }
279
+
280
+ var noop = function noop() {};
281
+
282
+ /**
283
+ * Safely runs code meant for browser environments only.
284
+ */
285
+ function safelyRunOnBrowser(callback) {
286
+ if (typeof window !== 'undefined') {
287
+ return callback({
288
+ window: window
289
+ });
290
+ }
291
+ return undefined;
292
+ }
293
+
294
+ var version = '1.9.0';
295
+
296
+ var userAgents = [{
297
+ segment: 'autocomplete-core',
298
+ version: version
299
+ }];
300
+
301
+ var warnCache = {
302
+ current: {}
303
+ };
304
+
305
+ /**
306
+ * Logs a warning if the condition is not met.
307
+ * This is used to log issues in development environment only.
308
+ */
309
+ function warn(condition, message) {
310
+ if (condition) {
311
+ return;
312
+ }
313
+ var sanitizedMessage = message.trim();
314
+ var hasAlreadyPrinted = warnCache.current[sanitizedMessage];
315
+ if (!hasAlreadyPrinted) {
316
+ warnCache.current[sanitizedMessage] = true;
317
+
318
+ // eslint-disable-next-line no-console
319
+ console.warn("[Autocomplete] ".concat(sanitizedMessage));
320
+ }
321
+ }
322
+
323
+ function createClickedEvent(_ref) {
324
+ var item = _ref.item,
325
+ items = _ref.items;
326
+ return {
327
+ index: item.__autocomplete_indexName,
328
+ items: [item],
329
+ positions: [1 + items.findIndex(function (x) {
330
+ return x.objectID === item.objectID;
331
+ })],
332
+ queryID: item.__autocomplete_queryID,
333
+ algoliaSource: ['autocomplete']
334
+ };
335
+ }
336
+
337
+ function _slicedToArray(arr, i) {
338
+ return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest();
339
+ }
340
+ function _nonIterableRest() {
341
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
342
+ }
343
+ function _unsupportedIterableToArray$2(o, minLen) {
344
+ if (!o) return;
345
+ if (typeof o === "string") return _arrayLikeToArray$2(o, minLen);
346
+ var n = Object.prototype.toString.call(o).slice(8, -1);
347
+ if (n === "Object" && o.constructor) n = o.constructor.name;
348
+ if (n === "Map" || n === "Set") return Array.from(o);
349
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$2(o, minLen);
350
+ }
351
+ function _arrayLikeToArray$2(arr, len) {
352
+ if (len == null || len > arr.length) len = arr.length;
353
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
354
+ return arr2;
355
+ }
356
+ function _iterableToArrayLimit(arr, i) {
357
+ var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
358
+ if (null != _i) {
359
+ var _s,
360
+ _e,
361
+ _x,
362
+ _r,
363
+ _arr = [],
364
+ _n = !0,
365
+ _d = !1;
366
+ try {
367
+ if (_x = (_i = _i.call(arr)).next, 0 === i) {
368
+ if (Object(_i) !== _i) return;
369
+ _n = !1;
370
+ } else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
371
+ } catch (err) {
372
+ _d = !0, _e = err;
373
+ } finally {
374
+ try {
375
+ if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
376
+ } finally {
377
+ if (_d) throw _e;
378
+ }
379
+ }
380
+ return _arr;
381
+ }
382
+ }
383
+ function _arrayWithHoles(arr) {
384
+ if (Array.isArray(arr)) return arr;
385
+ }
386
+ /**
387
+ * Determines if a given insights `client` supports the optional call to `init`
388
+ * and the ability to set credentials via extra parameters when sending events.
389
+ */
390
+ function isModernInsightsClient(client) {
391
+ var _split$map = (client.version || '').split('.').map(Number),
392
+ _split$map2 = _slicedToArray(_split$map, 2),
393
+ major = _split$map2[0],
394
+ minor = _split$map2[1];
395
+
396
+ /* eslint-disable @typescript-eslint/camelcase */
397
+ var v3 = major >= 3;
398
+ var v2_4 = major === 2 && minor >= 4;
399
+ var v1_10 = major === 1 && minor >= 10;
400
+ return v3 || v2_4 || v1_10;
401
+ /* eslint-enable @typescript-eslint/camelcase */
402
+ }
403
+
404
+ var _excluded$3 = ["items"],
405
+ _excluded2$1 = ["items"];
406
+ function _typeof$1(obj) {
407
+ "@babel/helpers - typeof";
408
+
409
+ return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
410
+ return typeof obj;
411
+ } : function (obj) {
412
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
413
+ }, _typeof$1(obj);
414
+ }
415
+ function _toConsumableArray$1(arr) {
416
+ return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1();
417
+ }
418
+ function _nonIterableSpread$1() {
419
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
420
+ }
421
+ function _unsupportedIterableToArray$1(o, minLen) {
422
+ if (!o) return;
423
+ if (typeof o === "string") return _arrayLikeToArray$1(o, minLen);
424
+ var n = Object.prototype.toString.call(o).slice(8, -1);
425
+ if (n === "Object" && o.constructor) n = o.constructor.name;
426
+ if (n === "Map" || n === "Set") return Array.from(o);
427
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray$1(o, minLen);
428
+ }
429
+ function _iterableToArray$1(iter) {
430
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
431
+ }
432
+ function _arrayWithoutHoles$1(arr) {
433
+ if (Array.isArray(arr)) return _arrayLikeToArray$1(arr);
434
+ }
435
+ function _arrayLikeToArray$1(arr, len) {
436
+ if (len == null || len > arr.length) len = arr.length;
437
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
438
+ return arr2;
439
+ }
440
+ function _objectWithoutProperties(source, excluded) {
441
+ if (source == null) return {};
442
+ var target = _objectWithoutPropertiesLoose(source, excluded);
443
+ var key, i;
444
+ if (Object.getOwnPropertySymbols) {
445
+ var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
446
+ for (i = 0; i < sourceSymbolKeys.length; i++) {
447
+ key = sourceSymbolKeys[i];
448
+ if (excluded.indexOf(key) >= 0) continue;
449
+ if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
450
+ target[key] = source[key];
451
+ }
452
+ }
453
+ return target;
454
+ }
455
+ function _objectWithoutPropertiesLoose(source, excluded) {
456
+ if (source == null) return {};
457
+ var target = {};
458
+ var sourceKeys = Object.keys(source);
459
+ var key, i;
460
+ for (i = 0; i < sourceKeys.length; i++) {
461
+ key = sourceKeys[i];
462
+ if (excluded.indexOf(key) >= 0) continue;
463
+ target[key] = source[key];
464
+ }
465
+ return target;
466
+ }
467
+ function ownKeys$1(object, enumerableOnly) {
468
+ var keys = Object.keys(object);
469
+ if (Object.getOwnPropertySymbols) {
470
+ var symbols = Object.getOwnPropertySymbols(object);
471
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
472
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
473
+ })), keys.push.apply(keys, symbols);
474
+ }
475
+ return keys;
476
+ }
477
+ function _objectSpread$1(target) {
478
+ for (var i = 1; i < arguments.length; i++) {
479
+ var source = null != arguments[i] ? arguments[i] : {};
480
+ i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) {
481
+ _defineProperty$1(target, key, source[key]);
482
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) {
483
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
484
+ });
485
+ }
486
+ return target;
487
+ }
488
+ function _defineProperty$1(obj, key, value) {
489
+ key = _toPropertyKey$1(key);
490
+ if (key in obj) {
491
+ Object.defineProperty(obj, key, {
492
+ value: value,
493
+ enumerable: true,
494
+ configurable: true,
495
+ writable: true
496
+ });
497
+ } else {
498
+ obj[key] = value;
499
+ }
500
+ return obj;
501
+ }
502
+ function _toPropertyKey$1(arg) {
503
+ var key = _toPrimitive$1(arg, "string");
504
+ return _typeof$1(key) === "symbol" ? key : String(key);
505
+ }
506
+ function _toPrimitive$1(input, hint) {
507
+ if (_typeof$1(input) !== "object" || input === null) return input;
508
+ var prim = input[Symbol.toPrimitive];
509
+ if (prim !== undefined) {
510
+ var res = prim.call(input, hint || "default");
511
+ if (_typeof$1(res) !== "object") return res;
512
+ throw new TypeError("@@toPrimitive must return a primitive value.");
513
+ }
514
+ return (hint === "string" ? String : Number)(input);
515
+ }
516
+ function chunk(item) {
517
+ var chunkSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20;
518
+ var chunks = [];
519
+ for (var i = 0; i < item.objectIDs.length; i += chunkSize) {
520
+ chunks.push(_objectSpread$1(_objectSpread$1({}, item), {}, {
521
+ objectIDs: item.objectIDs.slice(i, i + chunkSize)
522
+ }));
523
+ }
524
+ return chunks;
525
+ }
526
+ function mapToInsightsParamsApi(params) {
527
+ return params.map(function (_ref) {
528
+ var items = _ref.items,
529
+ param = _objectWithoutProperties(_ref, _excluded$3);
530
+ return _objectSpread$1(_objectSpread$1({}, param), {}, {
531
+ objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref2) {
532
+ var objectID = _ref2.objectID;
533
+ return objectID;
534
+ })) || param.objectIDs
535
+ });
536
+ });
537
+ }
538
+ function createSearchInsightsApi(searchInsights) {
539
+ var canSendHeaders = isModernInsightsClient(searchInsights);
540
+ function sendToInsights(method, payloads, items) {
541
+ if (canSendHeaders && typeof items !== 'undefined') {
542
+ var _items$0$__autocomple = items[0].__autocomplete_algoliaCredentials,
543
+ appId = _items$0$__autocomple.appId,
544
+ apiKey = _items$0$__autocomple.apiKey;
545
+ var headers = {
546
+ 'X-Algolia-Application-Id': appId,
547
+ 'X-Algolia-API-Key': apiKey
548
+ };
549
+ searchInsights.apply(void 0, [method].concat(_toConsumableArray$1(payloads), [{
550
+ headers: headers
551
+ }]));
552
+ } else {
553
+ searchInsights.apply(void 0, [method].concat(_toConsumableArray$1(payloads)));
554
+ }
555
+ }
556
+ return {
557
+ /**
558
+ * Initializes Insights with Algolia credentials.
559
+ */
560
+ init: function init(appId, apiKey) {
561
+ searchInsights('init', {
562
+ appId: appId,
563
+ apiKey: apiKey
564
+ });
565
+ },
566
+ /**
567
+ * Sets the user token to attach to events.
568
+ */
569
+ setUserToken: function setUserToken(userToken) {
570
+ searchInsights('setUserToken', userToken);
571
+ },
572
+ /**
573
+ * Sends click events to capture a query and its clicked items and positions.
574
+ *
575
+ * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids-after-search/
576
+ */
577
+ clickedObjectIDsAfterSearch: function clickedObjectIDsAfterSearch() {
578
+ for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) {
579
+ params[_key] = arguments[_key];
580
+ }
581
+ if (params.length > 0) {
582
+ sendToInsights('clickedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items);
583
+ }
584
+ },
585
+ /**
586
+ * Sends click events to capture clicked items.
587
+ *
588
+ * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids/
589
+ */
590
+ clickedObjectIDs: function clickedObjectIDs() {
591
+ for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
592
+ params[_key2] = arguments[_key2];
593
+ }
594
+ if (params.length > 0) {
595
+ sendToInsights('clickedObjectIDs', mapToInsightsParamsApi(params), params[0].items);
596
+ }
597
+ },
598
+ /**
599
+ * Sends click events to capture the filters a user clicks on.
600
+ *
601
+ * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-filters/
602
+ */
603
+ clickedFilters: function clickedFilters() {
604
+ for (var _len3 = arguments.length, params = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
605
+ params[_key3] = arguments[_key3];
606
+ }
607
+ if (params.length > 0) {
608
+ searchInsights.apply(void 0, ['clickedFilters'].concat(params));
609
+ }
610
+ },
611
+ /**
612
+ * Sends conversion events to capture a query and its clicked items.
613
+ *
614
+ * @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids-after-search/
615
+ */
616
+ convertedObjectIDsAfterSearch: function convertedObjectIDsAfterSearch() {
617
+ for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
618
+ params[_key4] = arguments[_key4];
619
+ }
620
+ if (params.length > 0) {
621
+ sendToInsights('convertedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items);
622
+ }
623
+ },
624
+ /**
625
+ * Sends conversion events to capture clicked items.
626
+ *
627
+ * @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids/
628
+ */
629
+ convertedObjectIDs: function convertedObjectIDs() {
630
+ for (var _len5 = arguments.length, params = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
631
+ params[_key5] = arguments[_key5];
632
+ }
633
+ if (params.length > 0) {
634
+ sendToInsights('convertedObjectIDs', mapToInsightsParamsApi(params), params[0].items);
635
+ }
636
+ },
637
+ /**
638
+ * Sends conversion events to capture the filters a user uses when converting.
639
+ *
640
+ * @link https://www.algolia.com/doc/api-reference/api-methods/converted-filters/
641
+ */
642
+ convertedFilters: function convertedFilters() {
643
+ for (var _len6 = arguments.length, params = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
644
+ params[_key6] = arguments[_key6];
645
+ }
646
+ if (params.length > 0) {
647
+ searchInsights.apply(void 0, ['convertedFilters'].concat(params));
648
+ }
649
+ },
650
+ /**
651
+ * Sends view events to capture clicked items.
652
+ *
653
+ * @link https://www.algolia.com/doc/api-reference/api-methods/viewed-object-ids/
654
+ */
655
+ viewedObjectIDs: function viewedObjectIDs() {
656
+ for (var _len7 = arguments.length, params = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) {
657
+ params[_key7] = arguments[_key7];
658
+ }
659
+ if (params.length > 0) {
660
+ params.reduce(function (acc, _ref3) {
661
+ var items = _ref3.items,
662
+ param = _objectWithoutProperties(_ref3, _excluded2$1);
663
+ return [].concat(_toConsumableArray$1(acc), _toConsumableArray$1(chunk(_objectSpread$1(_objectSpread$1({}, param), {}, {
664
+ objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref4) {
665
+ var objectID = _ref4.objectID;
666
+ return objectID;
667
+ })) || param.objectIDs
668
+ })).map(function (payload) {
669
+ return {
670
+ items: items,
671
+ payload: payload
672
+ };
673
+ })));
674
+ }, []).forEach(function (_ref5) {
675
+ var items = _ref5.items,
676
+ payload = _ref5.payload;
677
+ return sendToInsights('viewedObjectIDs', [payload], items);
678
+ });
679
+ }
680
+ },
681
+ /**
682
+ * Sends view events to capture the filters a user uses when viewing.
683
+ *
684
+ * @link https://www.algolia.com/doc/api-reference/api-methods/viewed-filters/
685
+ */
686
+ viewedFilters: function viewedFilters() {
687
+ for (var _len8 = arguments.length, params = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) {
688
+ params[_key8] = arguments[_key8];
689
+ }
690
+ if (params.length > 0) {
691
+ searchInsights.apply(void 0, ['viewedFilters'].concat(params));
692
+ }
693
+ }
694
+ };
695
+ }
696
+
697
+ function createViewedEvents(_ref) {
698
+ var items = _ref.items;
699
+ var itemsByIndexName = items.reduce(function (acc, current) {
700
+ var _acc$current$__autoco;
701
+ acc[current.__autocomplete_indexName] = ((_acc$current$__autoco = acc[current.__autocomplete_indexName]) !== null && _acc$current$__autoco !== void 0 ? _acc$current$__autoco : []).concat(current);
702
+ return acc;
703
+ }, {});
704
+ return Object.keys(itemsByIndexName).map(function (indexName) {
705
+ var items = itemsByIndexName[indexName];
706
+ return {
707
+ index: indexName,
708
+ items: items,
709
+ algoliaSource: ['autocomplete']
710
+ };
711
+ });
712
+ }
713
+
714
+ function isAlgoliaInsightsHit(hit) {
715
+ return hit.objectID && hit.__autocomplete_indexName && hit.__autocomplete_queryID;
716
+ }
717
+
718
+ function _typeof(obj) {
719
+ "@babel/helpers - typeof";
720
+
721
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
722
+ return typeof obj;
723
+ } : function (obj) {
724
+ return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
725
+ }, _typeof(obj);
726
+ }
727
+ function _toConsumableArray(arr) {
728
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
729
+ }
730
+ function _nonIterableSpread() {
731
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
732
+ }
733
+ function _unsupportedIterableToArray(o, minLen) {
734
+ if (!o) return;
735
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
736
+ var n = Object.prototype.toString.call(o).slice(8, -1);
737
+ if (n === "Object" && o.constructor) n = o.constructor.name;
738
+ if (n === "Map" || n === "Set") return Array.from(o);
739
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
740
+ }
741
+ function _iterableToArray(iter) {
742
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
743
+ }
744
+ function _arrayWithoutHoles(arr) {
745
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
746
+ }
747
+ function _arrayLikeToArray(arr, len) {
748
+ if (len == null || len > arr.length) len = arr.length;
749
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
750
+ return arr2;
751
+ }
752
+ function ownKeys(object, enumerableOnly) {
753
+ var keys = Object.keys(object);
754
+ if (Object.getOwnPropertySymbols) {
755
+ var symbols = Object.getOwnPropertySymbols(object);
756
+ enumerableOnly && (symbols = symbols.filter(function (sym) {
757
+ return Object.getOwnPropertyDescriptor(object, sym).enumerable;
758
+ })), keys.push.apply(keys, symbols);
759
+ }
760
+ return keys;
761
+ }
762
+ function _objectSpread(target) {
763
+ for (var i = 1; i < arguments.length; i++) {
764
+ var source = null != arguments[i] ? arguments[i] : {};
765
+ i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
766
+ _defineProperty(target, key, source[key]);
767
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
768
+ Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
769
+ });
770
+ }
771
+ return target;
772
+ }
773
+ function _defineProperty(obj, key, value) {
774
+ key = _toPropertyKey(key);
775
+ if (key in obj) {
776
+ Object.defineProperty(obj, key, {
777
+ value: value,
778
+ enumerable: true,
779
+ configurable: true,
780
+ writable: true
781
+ });
782
+ } else {
783
+ obj[key] = value;
784
+ }
785
+ return obj;
786
+ }
787
+ function _toPropertyKey(arg) {
788
+ var key = _toPrimitive(arg, "string");
789
+ return _typeof(key) === "symbol" ? key : String(key);
790
+ }
791
+ function _toPrimitive(input, hint) {
792
+ if (_typeof(input) !== "object" || input === null) return input;
793
+ var prim = input[Symbol.toPrimitive];
794
+ if (prim !== undefined) {
795
+ var res = prim.call(input, hint || "default");
796
+ if (_typeof(res) !== "object") return res;
797
+ throw new TypeError("@@toPrimitive must return a primitive value.");
798
+ }
799
+ return (hint === "string" ? String : Number)(input);
800
+ }
801
+ var VIEW_EVENT_DELAY = 400;
802
+ var ALGOLIA_INSIGHTS_VERSION = '2.4.0';
803
+ var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js");
804
+ var sendViewedObjectIDs = debounce(function (_ref) {
805
+ var onItemsChange = _ref.onItemsChange,
806
+ items = _ref.items,
807
+ insights = _ref.insights,
808
+ state = _ref.state;
809
+ onItemsChange({
810
+ insights: insights,
811
+ insightsEvents: createViewedEvents({
812
+ items: items
813
+ }).map(function (event) {
814
+ return _objectSpread({
815
+ eventName: 'Items Viewed'
816
+ }, event);
817
+ }),
818
+ state: state
819
+ });
820
+ }, VIEW_EVENT_DELAY);
821
+ function createAlgoliaInsightsPlugin(options) {
822
+ var _getOptions = getOptions(options),
823
+ providedInsightsClient = _getOptions.insightsClient,
824
+ onItemsChange = _getOptions.onItemsChange,
825
+ onSelectEvent = _getOptions.onSelect,
826
+ onActiveEvent = _getOptions.onActive;
827
+ var insightsClient = providedInsightsClient;
828
+ if (!providedInsightsClient) {
829
+ safelyRunOnBrowser(function (_ref2) {
830
+ var window = _ref2.window;
831
+ var pointer = window.AlgoliaAnalyticsObject || 'aa';
832
+ if (typeof pointer === 'string') {
833
+ insightsClient = window[pointer];
834
+ }
835
+ if (!insightsClient) {
836
+ window.AlgoliaAnalyticsObject = pointer;
837
+ if (!window[pointer]) {
838
+ window[pointer] = function () {
839
+ if (!window[pointer].queue) {
840
+ window[pointer].queue = [];
841
+ }
842
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
843
+ args[_key] = arguments[_key];
844
+ }
845
+ window[pointer].queue.push(args);
846
+ };
847
+ }
848
+ window[pointer].version = ALGOLIA_INSIGHTS_VERSION;
849
+ insightsClient = window[pointer];
850
+ loadInsights(window);
851
+ }
852
+ });
853
+ }
854
+ var insights = createSearchInsightsApi(insightsClient);
855
+ var previousItems = createRef([]);
856
+ var debouncedOnStateChange = debounce(function (_ref3) {
857
+ var state = _ref3.state;
858
+ if (!state.isOpen) {
859
+ return;
860
+ }
861
+ var items = state.collections.reduce(function (acc, current) {
862
+ return [].concat(_toConsumableArray(acc), _toConsumableArray(current.items));
863
+ }, []).filter(isAlgoliaInsightsHit);
864
+ if (!isEqual(previousItems.current.map(function (x) {
865
+ return x.objectID;
866
+ }), items.map(function (x) {
867
+ return x.objectID;
868
+ }))) {
869
+ previousItems.current = items;
870
+ if (items.length > 0) {
871
+ sendViewedObjectIDs({
872
+ onItemsChange: onItemsChange,
873
+ items: items,
874
+ insights: insights,
875
+ state: state
876
+ });
877
+ }
878
+ }
250
879
  }, 0);
880
+ return {
881
+ name: 'aa.algoliaInsightsPlugin',
882
+ subscribe: function subscribe(_ref4) {
883
+ var setContext = _ref4.setContext,
884
+ onSelect = _ref4.onSelect,
885
+ onActive = _ref4.onActive;
886
+ insightsClient('addAlgoliaAgent', 'insights-plugin');
887
+ setContext({
888
+ algoliaInsightsPlugin: {
889
+ __algoliaSearchParameters: {
890
+ clickAnalytics: true
891
+ },
892
+ insights: insights
893
+ }
894
+ });
895
+ onSelect(function (_ref5) {
896
+ var item = _ref5.item,
897
+ state = _ref5.state,
898
+ event = _ref5.event;
899
+ if (!isAlgoliaInsightsHit(item)) {
900
+ return;
901
+ }
902
+ onSelectEvent({
903
+ state: state,
904
+ event: event,
905
+ insights: insights,
906
+ item: item,
907
+ insightsEvents: [_objectSpread({
908
+ eventName: 'Item Selected'
909
+ }, createClickedEvent({
910
+ item: item,
911
+ items: previousItems.current
912
+ }))]
913
+ });
914
+ });
915
+ onActive(function (_ref6) {
916
+ var item = _ref6.item,
917
+ state = _ref6.state,
918
+ event = _ref6.event;
919
+ if (!isAlgoliaInsightsHit(item)) {
920
+ return;
921
+ }
922
+ onActiveEvent({
923
+ state: state,
924
+ event: event,
925
+ insights: insights,
926
+ item: item,
927
+ insightsEvents: [_objectSpread({
928
+ eventName: 'Item Active'
929
+ }, createClickedEvent({
930
+ item: item,
931
+ items: previousItems.current
932
+ }))]
933
+ });
934
+ });
935
+ },
936
+ onStateChange: function onStateChange(_ref7) {
937
+ var state = _ref7.state;
938
+ debouncedOnStateChange({
939
+ state: state
940
+ });
941
+ },
942
+ __autocomplete_pluginOptions: options
943
+ };
251
944
  }
252
-
253
- /**
254
- * Throws an error if the condition is not met in development mode.
255
- * This is used to make development a better experience to provide guidance as
256
- * to where the error comes from.
257
- */
258
- function invariant(condition, message) {
259
-
260
- if (!condition) {
261
- throw new Error("[Autocomplete] ".concat(typeof message === 'function' ? message() : message));
262
- }
945
+ function getOptions(options) {
946
+ return _objectSpread({
947
+ onItemsChange: function onItemsChange(_ref8) {
948
+ var insights = _ref8.insights,
949
+ insightsEvents = _ref8.insightsEvents;
950
+ insights.viewedObjectIDs.apply(insights, _toConsumableArray(insightsEvents.map(function (event) {
951
+ return _objectSpread(_objectSpread({}, event), {}, {
952
+ algoliaSource: [].concat(_toConsumableArray(event.algoliaSource || []), ['autocomplete-internal'])
953
+ });
954
+ })));
955
+ },
956
+ onSelect: function onSelect(_ref9) {
957
+ var insights = _ref9.insights,
958
+ insightsEvents = _ref9.insightsEvents;
959
+ insights.clickedObjectIDsAfterSearch.apply(insights, _toConsumableArray(insightsEvents.map(function (event) {
960
+ return _objectSpread(_objectSpread({}, event), {}, {
961
+ algoliaSource: [].concat(_toConsumableArray(event.algoliaSource || []), ['autocomplete-internal'])
962
+ });
963
+ })));
964
+ },
965
+ onActive: noop
966
+ }, options);
263
967
  }
264
-
265
- var noop = function noop() {};
266
-
267
- var version = '1.8.3';
268
-
269
- var userAgents = [{
270
- segment: 'autocomplete-core',
271
- version: version
272
- }];
273
-
274
- var warnCache = {
275
- current: {}
276
- };
277
- /**
278
- * Logs a warning if the condition is not met.
279
- * This is used to log issues in development environment only.
280
- */
281
-
282
- function warn(condition, message) {
283
-
284
- if (condition) {
285
- return;
286
- }
287
-
288
- var sanitizedMessage = message.trim();
289
- var hasAlreadyPrinted = warnCache.current[sanitizedMessage];
290
-
291
- if (!hasAlreadyPrinted) {
292
- warnCache.current[sanitizedMessage] = true; // eslint-disable-next-line no-console
293
-
294
- console.warn("[Autocomplete] ".concat(sanitizedMessage));
968
+ function loadInsights(environment) {
969
+ var errorMessage = "[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete";
970
+ try {
971
+ var script = environment.document.createElement('script');
972
+ script.async = true;
973
+ script.src = ALGOLIA_INSIGHTS_SRC;
974
+ script.onerror = function () {
975
+ // eslint-disable-next-line no-console
976
+ console.error(errorMessage);
977
+ };
978
+ document.body.appendChild(script);
979
+ } catch (cause) {
980
+ // eslint-disable-next-line no-console
981
+ console.error(errorMessage);
295
982
  }
296
983
  }
297
984
 
@@ -312,7 +999,6 @@
312
999
  if (onfinally) {
313
1000
  state.onCancelList.push(onfinally);
314
1001
  }
315
-
316
1002
  return createInternalCancelablePromise(promise.finally(createCallback(onfinally && function () {
317
1003
  state.onCancelList = [];
318
1004
  return onfinally();
@@ -331,24 +1017,20 @@
331
1017
  }
332
1018
  };
333
1019
  }
334
-
335
1020
  function cancelable(promise) {
336
1021
  return createInternalCancelablePromise(promise, {
337
1022
  isCanceled: false,
338
1023
  onCancelList: []
339
1024
  });
340
1025
  }
341
-
342
1026
  function createCallback(onResult, state, fallback) {
343
1027
  if (!onResult) {
344
1028
  return fallback;
345
1029
  }
346
-
347
1030
  return function callback(arg) {
348
1031
  if (state.isCanceled) {
349
1032
  return arg;
350
1033
  }
351
-
352
1034
  return onResult(arg);
353
1035
  };
354
1036
  }
@@ -405,7 +1087,6 @@
405
1087
  if (latestResolvedValue && currentPromiseId < latestResolvedId) {
406
1088
  return latestResolvedValue;
407
1089
  }
408
-
409
1090
  latestResolvedId = currentPromiseId;
410
1091
  latestResolvedValue = x;
411
1092
  return x;
@@ -433,17 +1114,13 @@
433
1114
  if (!itemCount) {
434
1115
  return null;
435
1116
  }
436
-
437
1117
  if (moveAmount < 0 && (baseIndex === null || defaultActiveItemId !== null && baseIndex === 0)) {
438
1118
  return itemCount + moveAmount;
439
1119
  }
440
-
441
1120
  var numericIndex = (baseIndex === null ? -1 : baseIndex) + moveAmount;
442
-
443
1121
  if (numericIndex <= -1 || numericIndex >= itemCount) {
444
1122
  return defaultActiveItemId === null ? null : 0;
445
1123
  }
446
-
447
1124
  return numericIndex;
448
1125
  }
449
1126
 
@@ -451,20 +1128,19 @@
451
1128
  var seenSourceIds = [];
452
1129
  return Promise.resolve(getSources(params)).then(function (sources) {
453
1130
  invariant(Array.isArray(sources), function () {
454
- return "The `getSources` function must return an array of sources but returned type ".concat(JSON.stringify(_typeof$1(sources)), ":\n\n").concat(JSON.stringify(decycle(sources), null, 2));
1131
+ return "The `getSources` function must return an array of sources but returned type ".concat(JSON.stringify(_typeof$3(sources)), ":\n\n").concat(JSON.stringify(decycle(sources), null, 2));
455
1132
  });
456
- return Promise.all(sources // We allow `undefined` and `false` sources to allow users to use
1133
+ return Promise.all(sources
1134
+ // We allow `undefined` and `false` sources to allow users to use
457
1135
  // `Boolean(query) && source` (=> `false`).
458
1136
  // We need to remove these values at this point.
459
1137
  .filter(function (maybeSource) {
460
1138
  return Boolean(maybeSource);
461
1139
  }).map(function (source) {
462
1140
  invariant(typeof source.sourceId === 'string', 'A source must provide a `sourceId` string.');
463
-
464
1141
  if (seenSourceIds.includes(source.sourceId)) {
465
1142
  throw new Error("[Autocomplete] The `sourceId` ".concat(JSON.stringify(source.sourceId), " is not unique."));
466
1143
  }
467
-
468
1144
  seenSourceIds.push(source.sourceId);
469
1145
  var defaultSource = {
470
1146
  getItemInputValue: function getItemInputValue(_ref) {
@@ -484,9 +1160,7 @@
484
1160
  Object.keys(defaultSource).forEach(function (key) {
485
1161
  defaultSource[key].__default = true;
486
1162
  });
487
-
488
1163
  var normalizedSource = _objectSpread2(_objectSpread2({}, defaultSource), source);
489
-
490
1164
  return Promise.resolve(normalizedSource);
491
1165
  }));
492
1166
  });
@@ -506,17 +1180,18 @@
506
1180
  var nextValue = previousValue + collectionsCount;
507
1181
  acc.push(nextValue);
508
1182
  return acc;
509
- }, []); // Based on the accumulated counts, we can infer the index of the suggestion.
1183
+ }, []);
510
1184
 
1185
+ // Based on the accumulated counts, we can infer the index of the suggestion.
511
1186
  var collectionIndex = accumulatedCollectionsCount.reduce(function (acc, current) {
512
1187
  if (current <= state.activeItemId) {
513
1188
  return acc + 1;
514
1189
  }
515
-
516
1190
  return acc;
517
1191
  }, 0);
518
1192
  return state.collections[collectionIndex];
519
1193
  }
1194
+
520
1195
  /**
521
1196
  * Gets the highlighted index relative to a suggestion object (not the absolute
522
1197
  * highlighted index).
@@ -526,37 +1201,28 @@
526
1201
  * ↑
527
1202
  * (absolute: 3, relative: 1)
528
1203
  */
529
-
530
-
531
1204
  function getRelativeActiveItemId(_ref) {
532
1205
  var state = _ref.state,
533
- collection = _ref.collection;
1206
+ collection = _ref.collection;
534
1207
  var isOffsetFound = false;
535
1208
  var counter = 0;
536
1209
  var previousItemsOffset = 0;
537
-
538
1210
  while (isOffsetFound === false) {
539
1211
  var currentCollection = state.collections[counter];
540
-
541
1212
  if (currentCollection === collection) {
542
1213
  isOffsetFound = true;
543
1214
  break;
544
1215
  }
545
-
546
1216
  previousItemsOffset += currentCollection.items.length;
547
1217
  counter++;
548
1218
  }
549
-
550
1219
  return state.activeItemId - previousItemsOffset;
551
1220
  }
552
-
553
1221
  function getActiveItem(state) {
554
1222
  var collection = getCollectionFromActiveItemId(state);
555
-
556
1223
  if (!collection) {
557
1224
  return null;
558
1225
  }
559
-
560
1226
  var item = collection.items[getRelativeActiveItemId({
561
1227
  state: state,
562
1228
  collection: collection
@@ -590,7 +1256,6 @@
590
1256
  function mapToAlgoliaResponse(rawResults) {
591
1257
  var results = rawResults.map(function (result) {
592
1258
  var _hits;
593
-
594
1259
  return _objectSpread2(_objectSpread2({}, result), {}, {
595
1260
  hits: (_hits = result.hits) === null || _hits === void 0 ? void 0 : _hits.map(function (hit) {
596
1261
  // Bring support for the Insights plugin.
@@ -608,7 +1273,6 @@
608
1273
  }).filter(Boolean),
609
1274
  facetHits: results.map(function (result) {
610
1275
  var _facetHits;
611
-
612
1276
  return (_facetHits = result.facetHits) === null || _facetHits === void 0 ? void 0 : _facetHits.map(function (facetHit) {
613
1277
  // Bring support for the highlighting components.
614
1278
  return {
@@ -633,7 +1297,6 @@
633
1297
  },
634
1298
  dispatch: function dispatch(action, payload) {
635
1299
  var prevState = _objectSpread2({}, state);
636
-
637
1300
  state = reducer(state, {
638
1301
  type: action,
639
1302
  props: props,
@@ -650,15 +1313,12 @@
650
1313
 
651
1314
  function getAutocompleteSetters(_ref) {
652
1315
  var store = _ref.store;
653
-
654
1316
  var setActiveItemId = function setActiveItemId(value) {
655
1317
  store.dispatch('setActiveItemId', value);
656
1318
  };
657
-
658
1319
  var setQuery = function setQuery(value) {
659
1320
  store.dispatch('setQuery', value);
660
1321
  };
661
-
662
1322
  var setCollections = function setCollections(rawValue) {
663
1323
  var baseItemId = 0;
664
1324
  var value = rawValue.map(function (collection) {
@@ -674,19 +1334,15 @@
674
1334
  });
675
1335
  store.dispatch('setCollections', value);
676
1336
  };
677
-
678
1337
  var setIsOpen = function setIsOpen(value) {
679
1338
  store.dispatch('setIsOpen', value);
680
1339
  };
681
-
682
1340
  var setStatus = function setStatus(value) {
683
1341
  store.dispatch('setStatus', value);
684
1342
  };
685
-
686
1343
  var setContext = function setContext(value) {
687
1344
  store.dispatch('setContext', value);
688
1345
  };
689
-
690
1346
  return {
691
1347
  setActiveItemId: setActiveItemId,
692
1348
  setQuery: setQuery,
@@ -699,11 +1355,9 @@
699
1355
 
700
1356
  function getDefaultProps(props, pluginSubscribers) {
701
1357
  var _props$id;
702
-
703
1358
  /* eslint-disable no-restricted-globals */
704
1359
  var environment = typeof window !== 'undefined' ? window : {};
705
1360
  /* eslint-enable no-restricted-globals */
706
-
707
1361
  var plugins = props.plugins || [];
708
1362
  return _objectSpread2(_objectSpread2({
709
1363
  debug: false,
@@ -712,6 +1366,7 @@
712
1366
  autoFocus: false,
713
1367
  defaultActiveItemId: null,
714
1368
  stallThreshold: 300,
1369
+ insights: false,
715
1370
  environment: environment,
716
1371
  shouldPanelOpen: function shouldPanelOpen(_ref) {
717
1372
  var state = _ref.state;
@@ -738,36 +1393,30 @@
738
1393
  }, props.initialState),
739
1394
  onStateChange: function onStateChange(params) {
740
1395
  var _props$onStateChange;
741
-
742
1396
  (_props$onStateChange = props.onStateChange) === null || _props$onStateChange === void 0 ? void 0 : _props$onStateChange.call(props, params);
743
1397
  plugins.forEach(function (x) {
744
1398
  var _x$onStateChange;
745
-
746
1399
  return (_x$onStateChange = x.onStateChange) === null || _x$onStateChange === void 0 ? void 0 : _x$onStateChange.call(x, params);
747
1400
  });
748
1401
  },
749
1402
  onSubmit: function onSubmit(params) {
750
1403
  var _props$onSubmit;
751
-
752
1404
  (_props$onSubmit = props.onSubmit) === null || _props$onSubmit === void 0 ? void 0 : _props$onSubmit.call(props, params);
753
1405
  plugins.forEach(function (x) {
754
1406
  var _x$onSubmit;
755
-
756
1407
  return (_x$onSubmit = x.onSubmit) === null || _x$onSubmit === void 0 ? void 0 : _x$onSubmit.call(x, params);
757
1408
  });
758
1409
  },
759
1410
  onReset: function onReset(params) {
760
1411
  var _props$onReset;
761
-
762
1412
  (_props$onReset = props.onReset) === null || _props$onReset === void 0 ? void 0 : _props$onReset.call(props, params);
763
1413
  plugins.forEach(function (x) {
764
1414
  var _x$onReset;
765
-
766
1415
  return (_x$onReset = x.onReset) === null || _x$onReset === void 0 ? void 0 : _x$onReset.call(x, params);
767
1416
  });
768
1417
  },
769
1418
  getSources: function getSources(params) {
770
- return Promise.all([].concat(_toConsumableArray(plugins.map(function (plugin) {
1419
+ return Promise.all([].concat(_toConsumableArray$2(plugins.map(function (plugin) {
771
1420
  return plugin.getSources;
772
1421
  })), [props.getSources]).filter(Boolean).map(function (getSources) {
773
1422
  return getNormalizedSources(getSources, params);
@@ -780,7 +1429,6 @@
780
1429
  source.onSelect(params);
781
1430
  pluginSubscribers.forEach(function (x) {
782
1431
  var _x$onSelect;
783
-
784
1432
  return (_x$onSelect = x.onSelect) === null || _x$onSelect === void 0 ? void 0 : _x$onSelect.call(x, params);
785
1433
  });
786
1434
  },
@@ -788,7 +1436,6 @@
788
1436
  source.onActive(params);
789
1437
  pluginSubscribers.forEach(function (x) {
790
1438
  var _x$onActive;
791
-
792
1439
  return (_x$onActive = x.onActive) === null || _x$onActive === void 0 ? void 0 : _x$onActive.call(x, params);
793
1440
  });
794
1441
  },
@@ -796,7 +1443,6 @@
796
1443
  source.onResolve(params);
797
1444
  pluginSubscribers.forEach(function (x) {
798
1445
  var _x$onResolve;
799
-
800
1446
  return (_x$onResolve = x.onResolve) === null || _x$onResolve === void 0 ? void 0 : _x$onResolve.call(x, params);
801
1447
  });
802
1448
  }
@@ -824,37 +1470,35 @@
824
1470
 
825
1471
  function reshape(_ref) {
826
1472
  var collections = _ref.collections,
827
- props = _ref.props,
828
- state = _ref.state;
1473
+ props = _ref.props,
1474
+ state = _ref.state;
829
1475
  // Sources are grouped by `sourceId` to conveniently pick them via destructuring.
830
1476
  // Example: `const { recentSearchesPlugin } = sourcesBySourceId`
831
1477
  var originalSourcesBySourceId = collections.reduce(function (acc, collection) {
832
- return _objectSpread2(_objectSpread2({}, acc), {}, _defineProperty({}, collection.source.sourceId, _objectSpread2(_objectSpread2({}, collection.source), {}, {
1478
+ return _objectSpread2(_objectSpread2({}, acc), {}, _defineProperty$2({}, collection.source.sourceId, _objectSpread2(_objectSpread2({}, collection.source), {}, {
833
1479
  getItems: function getItems() {
834
1480
  // We provide the resolved items from the collection to the `reshape` prop.
835
1481
  return flatten(collection.items);
836
1482
  }
837
1483
  })));
838
1484
  }, {});
839
-
840
1485
  var _props$plugins$reduce = props.plugins.reduce(function (acc, plugin) {
841
- if (plugin.reshape) {
842
- return plugin.reshape(acc);
843
- }
844
-
845
- return acc;
846
- }, {
847
- sourcesBySourceId: originalSourcesBySourceId,
848
- state: state
849
- }),
850
- sourcesBySourceId = _props$plugins$reduce.sourcesBySourceId;
851
-
1486
+ if (plugin.reshape) {
1487
+ return plugin.reshape(acc);
1488
+ }
1489
+ return acc;
1490
+ }, {
1491
+ sourcesBySourceId: originalSourcesBySourceId,
1492
+ state: state
1493
+ }),
1494
+ sourcesBySourceId = _props$plugins$reduce.sourcesBySourceId;
852
1495
  var reshapeSources = props.reshape({
853
1496
  sourcesBySourceId: sourcesBySourceId,
854
1497
  sources: Object.values(sourcesBySourceId),
855
1498
  state: state
856
- }); // We reconstruct the collections with the items modified by the `reshape` prop.
1499
+ });
857
1500
 
1501
+ // We reconstruct the collections with the items modified by the `reshape` prop.
858
1502
  return flatten(reshapeSources).filter(Boolean).map(function (source) {
859
1503
  return {
860
1504
  source: source,
@@ -866,16 +1510,13 @@
866
1510
  function isDescription(item) {
867
1511
  return Boolean(item.execute);
868
1512
  }
869
-
870
1513
  function isRequesterDescription(description) {
871
1514
  return Boolean(description === null || description === void 0 ? void 0 : description.execute);
872
1515
  }
873
-
874
1516
  function preResolve(itemsOrDescription, sourceId, state) {
875
1517
  if (isRequesterDescription(itemsOrDescription)) {
876
- var contextParameters = itemsOrDescription.requesterId === 'algolia' ? Object.assign.apply(Object, [{}].concat(_toConsumableArray(Object.keys(state.context).map(function (key) {
1518
+ var contextParameters = itemsOrDescription.requesterId === 'algolia' ? Object.assign.apply(Object, [{}].concat(_toConsumableArray$2(Object.keys(state.context).map(function (key) {
877
1519
  var _state$context$key;
878
-
879
1520
  return (_state$context$key = state.context[key]) === null || _state$context$key === void 0 ? void 0 : _state$context$key.__algoliaSearchParameters;
880
1521
  })))) : {};
881
1522
  return _objectSpread2(_objectSpread2({}, itemsOrDescription), {}, {
@@ -890,7 +1531,6 @@
890
1531
  })
891
1532
  });
892
1533
  }
893
-
894
1534
  return {
895
1535
  items: itemsOrDescription,
896
1536
  sourceId: sourceId
@@ -902,19 +1542,16 @@
902
1542
  acc.push(current);
903
1543
  return acc;
904
1544
  }
905
-
906
1545
  var searchClient = current.searchClient,
907
- execute = current.execute,
908
- requesterId = current.requesterId,
909
- requests = current.requests;
1546
+ execute = current.execute,
1547
+ requesterId = current.requesterId,
1548
+ requests = current.requests;
910
1549
  var container = acc.find(function (item) {
911
1550
  return isDescription(current) && isDescription(item) && item.searchClient === searchClient && Boolean(requesterId) && item.requesterId === requesterId;
912
1551
  });
913
-
914
1552
  if (container) {
915
1553
  var _container$items;
916
-
917
- (_container$items = container.items).push.apply(_container$items, _toConsumableArray(requests));
1554
+ (_container$items = container.items).push.apply(_container$items, _toConsumableArray$2(requests));
918
1555
  } else {
919
1556
  var request = {
920
1557
  execute: execute,
@@ -924,18 +1561,16 @@
924
1561
  };
925
1562
  acc.push(request);
926
1563
  }
927
-
928
1564
  return acc;
929
1565
  }, []);
930
1566
  var values = packed.map(function (maybeDescription) {
931
1567
  if (!isDescription(maybeDescription)) {
932
1568
  return Promise.resolve(maybeDescription);
933
1569
  }
934
-
935
1570
  var _ref = maybeDescription,
936
- execute = _ref.execute,
937
- items = _ref.items,
938
- searchClient = _ref.searchClient;
1571
+ execute = _ref.execute,
1572
+ items = _ref.items,
1573
+ searchClient = _ref.searchClient;
939
1574
  return execute({
940
1575
  searchClient: searchClient,
941
1576
  requests: items
@@ -963,7 +1598,7 @@
963
1598
  state: store.getState()
964
1599
  });
965
1600
  invariant(Array.isArray(items), function () {
966
- return "The `getItems` function from source \"".concat(source.sourceId, "\" must return an array of items but returned type ").concat(JSON.stringify(_typeof$1(items)), ":\n\n").concat(JSON.stringify(decycle(items), null, 2), ".\n\nSee: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/sources/#param-getitems");
1601
+ return "The `getItems` function from source \"".concat(source.sourceId, "\" must return an array of items but returned type ").concat(JSON.stringify(_typeof$3(items)), ":\n\n").concat(JSON.stringify(decycle(items), null, 2), ".\n\nSee: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/sources/#param-getitems");
967
1602
  });
968
1603
  invariant(items.every(Boolean), "The `getItems` function from source \"".concat(source.sourceId, "\" must return an array of items but returned ").concat(JSON.stringify(undefined), ".\n\nDid you forget to return items?\n\nSee: https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/sources/#param-getitems"));
969
1604
  return {
@@ -978,29 +1613,25 @@
978
1613
  var runConcurrentSafePromise = createConcurrentSafePromise();
979
1614
  function onInput(_ref) {
980
1615
  var event = _ref.event,
981
- _ref$nextState = _ref.nextState,
982
- nextState = _ref$nextState === void 0 ? {} : _ref$nextState,
983
- props = _ref.props,
984
- query = _ref.query,
985
- refresh = _ref.refresh,
986
- store = _ref.store,
987
- setters = _objectWithoutProperties(_ref, _excluded$2);
988
-
1616
+ _ref$nextState = _ref.nextState,
1617
+ nextState = _ref$nextState === void 0 ? {} : _ref$nextState,
1618
+ props = _ref.props,
1619
+ query = _ref.query,
1620
+ refresh = _ref.refresh,
1621
+ store = _ref.store,
1622
+ setters = _objectWithoutProperties$1(_ref, _excluded$2);
989
1623
  if (lastStalledId) {
990
1624
  props.environment.clearTimeout(lastStalledId);
991
1625
  }
992
-
993
1626
  var setCollections = setters.setCollections,
994
- setIsOpen = setters.setIsOpen,
995
- setQuery = setters.setQuery,
996
- setActiveItemId = setters.setActiveItemId,
997
- setStatus = setters.setStatus;
1627
+ setIsOpen = setters.setIsOpen,
1628
+ setQuery = setters.setQuery,
1629
+ setActiveItemId = setters.setActiveItemId,
1630
+ setStatus = setters.setStatus;
998
1631
  setQuery(query);
999
1632
  setActiveItemId(props.defaultActiveItemId);
1000
-
1001
1633
  if (!query && props.openOnFocus === false) {
1002
1634
  var _nextState$isOpen;
1003
-
1004
1635
  var collections = store.getState().collections.map(function (collection) {
1005
1636
  return _objectSpread2(_objectSpread2({}, collection), {}, {
1006
1637
  items: []
@@ -1010,28 +1641,28 @@
1010
1641
  setCollections(collections);
1011
1642
  setIsOpen((_nextState$isOpen = nextState.isOpen) !== null && _nextState$isOpen !== void 0 ? _nextState$isOpen : props.shouldPanelOpen({
1012
1643
  state: store.getState()
1013
- })); // We make sure to update the latest resolved value of the tracked
1644
+ }));
1645
+
1646
+ // We make sure to update the latest resolved value of the tracked
1014
1647
  // promises to keep late resolving promises from "cancelling" the state
1015
1648
  // updates performed in this code path.
1016
1649
  // We chain with a void promise to respect `onInput`'s expected return type.
1017
-
1018
1650
  var _request = cancelable(runConcurrentSafePromise(collections).then(function () {
1019
1651
  return Promise.resolve();
1020
1652
  }));
1021
-
1022
1653
  return store.pendingRequests.add(_request);
1023
1654
  }
1024
-
1025
1655
  setStatus('loading');
1026
1656
  lastStalledId = props.environment.setTimeout(function () {
1027
1657
  setStatus('stalled');
1028
- }, props.stallThreshold); // We track the entire promise chain triggered by `onInput` before mutating
1658
+ }, props.stallThreshold);
1659
+
1660
+ // We track the entire promise chain triggered by `onInput` before mutating
1029
1661
  // the Autocomplete state to make sure that any state manipulation is based on
1030
1662
  // fresh data regardless of when promises individually resolve.
1031
1663
  // We don't track nested promises and only rely on the full chain resolution,
1032
1664
  // meaning we should only ever manipulate the state once this concurrent-safe
1033
1665
  // promise is resolved.
1034
-
1035
1666
  var request = cancelable(runConcurrentSafePromise(props.getSources(_objectSpread2({
1036
1667
  query: query,
1037
1668
  refresh: refresh,
@@ -1056,11 +1687,11 @@
1056
1687
  });
1057
1688
  }))).then(function (collections) {
1058
1689
  var _nextState$isOpen2;
1059
-
1060
1690
  // Parameters passed to `onInput` could be stale when the following code
1061
1691
  // executes, because `onInput` calls may not resolve in order.
1062
1692
  // If it becomes a problem we'll need to save the last passed parameters.
1063
1693
  // See: https://codesandbox.io/s/agitated-cookies-y290z
1694
+
1064
1695
  setStatus('idle');
1065
1696
  setCollections(collections);
1066
1697
  var isPanelOpen = props.shouldPanelOpen({
@@ -1068,12 +1699,11 @@
1068
1699
  });
1069
1700
  setIsOpen((_nextState$isOpen2 = nextState.isOpen) !== null && _nextState$isOpen2 !== void 0 ? _nextState$isOpen2 : props.openOnFocus && !query && isPanelOpen || isPanelOpen);
1070
1701
  var highlightedItem = getActiveItem(store.getState());
1071
-
1072
1702
  if (store.getState().activeItemId !== null && highlightedItem) {
1073
1703
  var item = highlightedItem.item,
1074
- itemInputValue = highlightedItem.itemInputValue,
1075
- itemUrl = highlightedItem.itemUrl,
1076
- source = highlightedItem.source;
1704
+ itemInputValue = highlightedItem.itemInputValue,
1705
+ itemUrl = highlightedItem.itemUrl,
1706
+ source = highlightedItem.source;
1077
1707
  source.onActive(_objectSpread2({
1078
1708
  event: event,
1079
1709
  item: item,
@@ -1086,7 +1716,6 @@
1086
1716
  }
1087
1717
  }).finally(function () {
1088
1718
  setStatus('idle');
1089
-
1090
1719
  if (lastStalledId) {
1091
1720
  props.environment.clearTimeout(lastStalledId);
1092
1721
  }
@@ -1097,16 +1726,14 @@
1097
1726
  var _excluded$1 = ["event", "props", "refresh", "store"];
1098
1727
  function onKeyDown(_ref) {
1099
1728
  var event = _ref.event,
1100
- props = _ref.props,
1101
- refresh = _ref.refresh,
1102
- store = _ref.store,
1103
- setters = _objectWithoutProperties(_ref, _excluded$1);
1104
-
1729
+ props = _ref.props,
1730
+ refresh = _ref.refresh,
1731
+ store = _ref.store,
1732
+ setters = _objectWithoutProperties$1(_ref, _excluded$1);
1105
1733
  if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
1106
1734
  // eslint-disable-next-line no-inner-declarations
1107
1735
  var triggerScrollIntoView = function triggerScrollIntoView() {
1108
1736
  var nodeItem = props.environment.document.getElementById("".concat(props.id, "-item-").concat(store.getState().activeItemId));
1109
-
1110
1737
  if (nodeItem) {
1111
1738
  if (nodeItem.scrollIntoViewIfNeeded) {
1112
1739
  nodeItem.scrollIntoViewIfNeeded(false);
@@ -1115,16 +1742,13 @@
1115
1742
  }
1116
1743
  }
1117
1744
  }; // eslint-disable-next-line no-inner-declarations
1118
-
1119
-
1120
1745
  var triggerOnActive = function triggerOnActive() {
1121
1746
  var highlightedItem = getActiveItem(store.getState());
1122
-
1123
1747
  if (store.getState().activeItemId !== null && highlightedItem) {
1124
1748
  var item = highlightedItem.item,
1125
- itemInputValue = highlightedItem.itemInputValue,
1126
- itemUrl = highlightedItem.itemUrl,
1127
- source = highlightedItem.source;
1749
+ itemInputValue = highlightedItem.itemInputValue,
1750
+ itemUrl = highlightedItem.itemUrl,
1751
+ source = highlightedItem.source;
1128
1752
  source.onActive(_objectSpread2({
1129
1753
  event: event,
1130
1754
  item: item,
@@ -1137,11 +1761,10 @@
1137
1761
  }
1138
1762
  }; // Default browser behavior changes the caret placement on ArrowUp and
1139
1763
  // ArrowDown.
1764
+ event.preventDefault();
1140
1765
 
1141
-
1142
- event.preventDefault(); // When re-opening the panel, we need to split the logic to keep the actions
1766
+ // When re-opening the panel, we need to split the logic to keep the actions
1143
1767
  // synchronized as `onInput` returns a promise.
1144
-
1145
1768
  if (store.getState().isOpen === false && (props.openOnFocus || Boolean(store.getState().query))) {
1146
1769
  onInput(_objectSpread2({
1147
1770
  event: event,
@@ -1153,10 +1776,10 @@
1153
1776
  store.dispatch(event.key, {
1154
1777
  nextActiveItemId: props.defaultActiveItemId
1155
1778
  });
1156
- triggerOnActive(); // Since we rely on the DOM, we need to wait for all the micro tasks to
1779
+ triggerOnActive();
1780
+ // Since we rely on the DOM, we need to wait for all the micro tasks to
1157
1781
  // finish (which include re-opening the panel) to make sure all the
1158
1782
  // elements are available.
1159
-
1160
1783
  setTimeout(triggerScrollIntoView, 0);
1161
1784
  });
1162
1785
  } else {
@@ -1169,18 +1792,20 @@
1169
1792
  // from removing the query right away because we first want to close the
1170
1793
  // panel.
1171
1794
  event.preventDefault();
1172
- store.dispatch(event.key, null); // Hitting the `Escape` key signals the end of a user interaction with the
1795
+ store.dispatch(event.key, null);
1796
+
1797
+ // Hitting the `Escape` key signals the end of a user interaction with the
1173
1798
  // autocomplete. At this point, we should ignore any requests that are still
1174
1799
  // pending and could reopen the panel once they resolve, because that would
1175
1800
  // result in an unsolicited UI behavior.
1176
-
1177
1801
  store.pendingRequests.cancelAll();
1178
1802
  } else if (event.key === 'Tab') {
1179
- store.dispatch('blur', null); // Hitting the `Escape` key signals the end of a user interaction with the
1803
+ store.dispatch('blur', null);
1804
+
1805
+ // Hitting the `Escape` key signals the end of a user interaction with the
1180
1806
  // autocomplete. At this point, we should ignore any requests that are still
1181
1807
  // pending and could reopen the panel once they resolve, because that would
1182
1808
  // result in an unsolicited UI behavior.
1183
-
1184
1809
  store.pendingRequests.cancelAll();
1185
1810
  } else if (event.key === 'Enter') {
1186
1811
  // No active item, so we let the browser handle the native `onSubmit` form
@@ -1195,20 +1820,17 @@
1195
1820
  if (!props.debug) {
1196
1821
  store.pendingRequests.cancelAll();
1197
1822
  }
1198
-
1199
1823
  return;
1200
- } // This prevents the `onSubmit` event to be sent because an item is
1201
- // highlighted.
1202
-
1824
+ }
1203
1825
 
1826
+ // This prevents the `onSubmit` event to be sent because an item is
1827
+ // highlighted.
1204
1828
  event.preventDefault();
1205
-
1206
1829
  var _ref2 = getActiveItem(store.getState()),
1207
- item = _ref2.item,
1208
- itemInputValue = _ref2.itemInputValue,
1209
- itemUrl = _ref2.itemUrl,
1210
- source = _ref2.source;
1211
-
1830
+ item = _ref2.item,
1831
+ itemInputValue = _ref2.itemInputValue,
1832
+ itemUrl = _ref2.itemUrl,
1833
+ source = _ref2.source;
1212
1834
  if (event.metaKey || event.ctrlKey) {
1213
1835
  if (itemUrl !== undefined) {
1214
1836
  source.onSelect(_objectSpread2({
@@ -1261,7 +1883,6 @@
1261
1883
  });
1262
1884
  return;
1263
1885
  }
1264
-
1265
1886
  onInput(_objectSpread2({
1266
1887
  event: event,
1267
1888
  nextState: {
@@ -1287,24 +1908,22 @@
1287
1908
  }
1288
1909
 
1289
1910
  var _excluded = ["props", "refresh", "store"],
1290
- _excluded2 = ["inputElement", "formElement", "panelElement"],
1291
- _excluded3 = ["inputElement"],
1292
- _excluded4 = ["inputElement", "maxLength"],
1293
- _excluded5 = ["sourceIndex"],
1294
- _excluded6 = ["sourceIndex"],
1295
- _excluded7 = ["item", "source", "sourceIndex"];
1911
+ _excluded2 = ["inputElement", "formElement", "panelElement"],
1912
+ _excluded3 = ["inputElement"],
1913
+ _excluded4 = ["inputElement", "maxLength"],
1914
+ _excluded5 = ["sourceIndex"],
1915
+ _excluded6 = ["sourceIndex"],
1916
+ _excluded7 = ["item", "source", "sourceIndex"];
1296
1917
  function getPropGetters(_ref) {
1297
1918
  var props = _ref.props,
1298
- refresh = _ref.refresh,
1299
- store = _ref.store,
1300
- setters = _objectWithoutProperties(_ref, _excluded);
1301
-
1919
+ refresh = _ref.refresh,
1920
+ store = _ref.store,
1921
+ setters = _objectWithoutProperties$1(_ref, _excluded);
1302
1922
  var getEnvironmentProps = function getEnvironmentProps(providedProps) {
1303
1923
  var inputElement = providedProps.inputElement,
1304
- formElement = providedProps.formElement,
1305
- panelElement = providedProps.panelElement,
1306
- rest = _objectWithoutProperties(providedProps, _excluded2);
1307
-
1924
+ formElement = providedProps.formElement,
1925
+ panelElement = providedProps.panelElement,
1926
+ rest = _objectWithoutProperties$1(providedProps, _excluded2);
1308
1927
  function onMouseDownOrTouchStart(event) {
1309
1928
  // The `onTouchStart`/`onMouseDown` events shouldn't trigger the `blur`
1310
1929
  // handler when it's not an interaction with Autocomplete.
@@ -1313,29 +1932,27 @@
1313
1932
  // (no interaction with the autocomplete, no future state updates)
1314
1933
  // - OR the touched target is the input element (should open the panel)
1315
1934
  var isAutocompleteInteraction = store.getState().isOpen || !store.pendingRequests.isEmpty();
1316
-
1317
1935
  if (!isAutocompleteInteraction || event.target === inputElement) {
1318
1936
  return;
1319
- } // @TODO: support cases where there are multiple Autocomplete instances.
1320
- // Right now, a second instance makes this computation return false.
1321
-
1937
+ }
1322
1938
 
1939
+ // @TODO: support cases where there are multiple Autocomplete instances.
1940
+ // Right now, a second instance makes this computation return false.
1323
1941
  var isTargetWithinAutocomplete = [formElement, panelElement].some(function (contextNode) {
1324
1942
  return isOrContainsNode(contextNode, event.target);
1325
1943
  });
1326
-
1327
1944
  if (isTargetWithinAutocomplete === false) {
1328
- store.dispatch('blur', null); // If requests are still pending when the user closes the panel, they
1945
+ store.dispatch('blur', null);
1946
+
1947
+ // If requests are still pending when the user closes the panel, they
1329
1948
  // could reopen the panel once they resolve.
1330
1949
  // We want to prevent any subsequent query from reopening the panel
1331
1950
  // because it would result in an unsolicited UI behavior.
1332
-
1333
1951
  if (!props.debug) {
1334
1952
  store.pendingRequests.cancelAll();
1335
1953
  }
1336
1954
  }
1337
1955
  }
1338
-
1339
1956
  return _objectSpread2({
1340
1957
  // We do not rely on the native `blur` event of the input to close the
1341
1958
  // panel, but rather on a custom `touchstart`/`mousedown` event outside
@@ -1356,12 +1973,10 @@
1356
1973
  if (store.getState().isOpen === false || inputElement !== props.environment.document.activeElement || event.target === inputElement) {
1357
1974
  return;
1358
1975
  }
1359
-
1360
1976
  inputElement.blur();
1361
1977
  }
1362
1978
  }, rest);
1363
1979
  };
1364
-
1365
1980
  var getRootProps = function getRootProps(rest) {
1366
1981
  return _objectSpread2({
1367
1982
  role: 'combobox',
@@ -1371,18 +1986,15 @@
1371
1986
  'aria-labelledby': "".concat(props.id, "-label")
1372
1987
  }, rest);
1373
1988
  };
1374
-
1375
1989
  var getFormProps = function getFormProps(providedProps) {
1376
1990
  providedProps.inputElement;
1377
- var rest = _objectWithoutProperties(providedProps, _excluded3);
1378
-
1991
+ var rest = _objectWithoutProperties$1(providedProps, _excluded3);
1379
1992
  return _objectSpread2({
1380
1993
  action: '',
1381
1994
  noValidate: true,
1382
1995
  role: 'search',
1383
1996
  onSubmit: function onSubmit(event) {
1384
1997
  var _providedProps$inputE;
1385
-
1386
1998
  event.preventDefault();
1387
1999
  props.onSubmit(_objectSpread2({
1388
2000
  event: event,
@@ -1394,7 +2006,6 @@
1394
2006
  },
1395
2007
  onReset: function onReset(event) {
1396
2008
  var _providedProps$inputE2;
1397
-
1398
2009
  event.preventDefault();
1399
2010
  props.onReset(_objectSpread2({
1400
2011
  event: event,
@@ -1406,10 +2017,8 @@
1406
2017
  }
1407
2018
  }, rest);
1408
2019
  };
1409
-
1410
2020
  var getInputProps = function getInputProps(providedProps) {
1411
2021
  var _props$environment$na;
1412
-
1413
2022
  function onFocus(event) {
1414
2023
  // We want to trigger a query when `openOnFocus` is true
1415
2024
  // because the panel should open with the current query.
@@ -1422,16 +2031,13 @@
1422
2031
  store: store
1423
2032
  }, setters));
1424
2033
  }
1425
-
1426
2034
  store.dispatch('focus', null);
1427
2035
  }
1428
-
1429
2036
  var _ref2 = providedProps || {};
1430
- _ref2.inputElement;
1431
- var _ref2$maxLength = _ref2.maxLength,
1432
- maxLength = _ref2$maxLength === void 0 ? 512 : _ref2$maxLength,
1433
- rest = _objectWithoutProperties(_ref2, _excluded4);
1434
-
2037
+ _ref2.inputElement;
2038
+ var _ref2$maxLength = _ref2.maxLength,
2039
+ maxLength = _ref2$maxLength === void 0 ? 512 : _ref2$maxLength,
2040
+ rest = _objectWithoutProperties$1(_ref2, _excluded4);
1435
2041
  var activeItem = getActiveItem(store.getState());
1436
2042
  var userAgent = ((_props$environment$na = props.environment.navigator) === null || _props$environment$na === void 0 ? void 0 : _props$environment$na.userAgent) || '';
1437
2043
  var shouldFallbackKeyHint = isSamsung(userAgent);
@@ -1488,34 +2094,28 @@
1488
2094
  }
1489
2095
  }, rest);
1490
2096
  };
1491
-
1492
2097
  var getAutocompleteId = function getAutocompleteId(instanceId, sourceId) {
1493
2098
  return typeof sourceId !== 'undefined' ? "".concat(instanceId, "-").concat(sourceId) : instanceId;
1494
2099
  };
1495
-
1496
2100
  var getLabelProps = function getLabelProps(providedProps) {
1497
2101
  var _ref3 = providedProps || {},
1498
- sourceIndex = _ref3.sourceIndex,
1499
- rest = _objectWithoutProperties(_ref3, _excluded5);
1500
-
2102
+ sourceIndex = _ref3.sourceIndex,
2103
+ rest = _objectWithoutProperties$1(_ref3, _excluded5);
1501
2104
  return _objectSpread2({
1502
2105
  htmlFor: "".concat(getAutocompleteId(props.id, sourceIndex), "-input"),
1503
2106
  id: "".concat(getAutocompleteId(props.id, sourceIndex), "-label")
1504
2107
  }, rest);
1505
2108
  };
1506
-
1507
2109
  var getListProps = function getListProps(providedProps) {
1508
2110
  var _ref4 = providedProps || {},
1509
- sourceIndex = _ref4.sourceIndex,
1510
- rest = _objectWithoutProperties(_ref4, _excluded6);
1511
-
2111
+ sourceIndex = _ref4.sourceIndex,
2112
+ rest = _objectWithoutProperties$1(_ref4, _excluded6);
1512
2113
  return _objectSpread2({
1513
2114
  role: 'listbox',
1514
2115
  'aria-labelledby': "".concat(getAutocompleteId(props.id, sourceIndex), "-label"),
1515
2116
  id: "".concat(getAutocompleteId(props.id, sourceIndex), "-list")
1516
2117
  }, rest);
1517
2118
  };
1518
-
1519
2119
  var getPanelProps = function getPanelProps(rest) {
1520
2120
  return _objectSpread2({
1521
2121
  onMouseDown: function onMouseDown(event) {
@@ -1529,13 +2129,11 @@
1529
2129
  }
1530
2130
  }, rest);
1531
2131
  };
1532
-
1533
2132
  var getItemProps = function getItemProps(providedProps) {
1534
2133
  var item = providedProps.item,
1535
- source = providedProps.source,
1536
- sourceIndex = providedProps.sourceIndex,
1537
- rest = _objectWithoutProperties(providedProps, _excluded7);
1538
-
2134
+ source = providedProps.source,
2135
+ sourceIndex = providedProps.sourceIndex,
2136
+ rest = _objectWithoutProperties$1(providedProps, _excluded7);
1539
2137
  return _objectSpread2({
1540
2138
  id: "".concat(getAutocompleteId(props.id, sourceIndex), "-item-").concat(item.__autocomplete_id),
1541
2139
  role: 'option',
@@ -1544,16 +2142,13 @@
1544
2142
  if (item.__autocomplete_id === store.getState().activeItemId) {
1545
2143
  return;
1546
2144
  }
1547
-
1548
2145
  store.dispatch('mousemove', item.__autocomplete_id);
1549
2146
  var activeItem = getActiveItem(store.getState());
1550
-
1551
2147
  if (store.getState().activeItemId !== null && activeItem) {
1552
2148
  var _item = activeItem.item,
1553
- itemInputValue = activeItem.itemInputValue,
1554
- itemUrl = activeItem.itemUrl,
1555
- _source = activeItem.source;
1556
-
2149
+ itemInputValue = activeItem.itemInputValue,
2150
+ itemUrl = activeItem.itemUrl,
2151
+ _source = activeItem.source;
1557
2152
  _source.onActive(_objectSpread2({
1558
2153
  event: event,
1559
2154
  item: _item,
@@ -1578,12 +2173,13 @@
1578
2173
  var itemUrl = source.getItemUrl({
1579
2174
  item: item,
1580
2175
  state: store.getState()
1581
- }); // If `getItemUrl` is provided, it means that the suggestion
2176
+ });
2177
+
2178
+ // If `getItemUrl` is provided, it means that the suggestion
1582
2179
  // is a link, not plain text that aims at updating the query.
1583
2180
  // We can therefore skip the state change because it will update
1584
2181
  // the `activeItemId`, resulting in a UI flash, especially
1585
2182
  // noticeable on mobile.
1586
-
1587
2183
  var runPreCommand = itemUrl ? Promise.resolve() : onInput(_objectSpread2({
1588
2184
  event: event,
1589
2185
  nextState: {
@@ -1608,7 +2204,6 @@
1608
2204
  }
1609
2205
  }, rest);
1610
2206
  };
1611
-
1612
2207
  return {
1613
2208
  getEnvironmentProps: getEnvironmentProps,
1614
2209
  getRootProps: getRootProps,
@@ -1623,11 +2218,10 @@
1623
2218
 
1624
2219
  function getMetadata(_ref) {
1625
2220
  var _, _options$__autocomple, _options$__autocomple2, _options$__autocomple3;
1626
-
1627
2221
  var plugins = _ref.plugins,
1628
- options = _ref.options;
2222
+ options = _ref.options;
1629
2223
  var optionsKey = (_ = (((_options$__autocomple = options.__autocomplete_metadata) === null || _options$__autocomple === void 0 ? void 0 : _options$__autocomple.userAgents) || [])[0]) === null || _ === void 0 ? void 0 : _.segment;
1630
- var extraOptions = optionsKey ? _defineProperty({}, optionsKey, Object.keys(((_options$__autocomple2 = options.__autocomplete_metadata) === null || _options$__autocomple2 === void 0 ? void 0 : _options$__autocomple2.options) || {})) : {};
2224
+ var extraOptions = optionsKey ? _defineProperty$2({}, optionsKey, Object.keys(((_options$__autocomple2 = options.__autocomplete_metadata) === null || _options$__autocomple2 === void 0 ? void 0 : _options$__autocomple2.options) || {})) : {};
1631
2225
  return {
1632
2226
  plugins: plugins.map(function (plugin) {
1633
2227
  return {
@@ -1643,11 +2237,9 @@
1643
2237
  }
1644
2238
  function injectMetadata(_ref3) {
1645
2239
  var _environment$navigato, _environment$navigato2;
1646
-
1647
2240
  var metadata = _ref3.metadata,
1648
- environment = _ref3.environment;
2241
+ environment = _ref3.environment;
1649
2242
  var isMetadataEnabled = (_environment$navigato = environment.navigator) === null || _environment$navigato === void 0 ? void 0 : (_environment$navigato2 = _environment$navigato.userAgent) === null || _environment$navigato2 === void 0 ? void 0 : _environment$navigato2.includes('Algolia Crawler');
1650
-
1651
2243
  if (isMetadataEnabled) {
1652
2244
  var metadataContainer = environment.document.createElement('meta');
1653
2245
  var headRef = environment.document.querySelector('head');
@@ -1661,13 +2253,10 @@
1661
2253
 
1662
2254
  function getCompletion(_ref) {
1663
2255
  var _getActiveItem;
1664
-
1665
2256
  var state = _ref.state;
1666
-
1667
2257
  if (state.isOpen === false || state.activeItemId === null) {
1668
2258
  return null;
1669
2259
  }
1670
-
1671
2260
  return ((_getActiveItem = getActiveItem(state)) === null || _getActiveItem === void 0 ? void 0 : _getActiveItem.itemInputValue) || null;
1672
2261
  }
1673
2262
 
@@ -1679,7 +2268,6 @@
1679
2268
  activeItemId: action.payload
1680
2269
  });
1681
2270
  }
1682
-
1683
2271
  case 'setQuery':
1684
2272
  {
1685
2273
  return _objectSpread2(_objectSpread2({}, state), {}, {
@@ -1687,61 +2275,52 @@
1687
2275
  completion: null
1688
2276
  });
1689
2277
  }
1690
-
1691
2278
  case 'setCollections':
1692
2279
  {
1693
2280
  return _objectSpread2(_objectSpread2({}, state), {}, {
1694
2281
  collections: action.payload
1695
2282
  });
1696
2283
  }
1697
-
1698
2284
  case 'setIsOpen':
1699
2285
  {
1700
2286
  return _objectSpread2(_objectSpread2({}, state), {}, {
1701
2287
  isOpen: action.payload
1702
2288
  });
1703
2289
  }
1704
-
1705
2290
  case 'setStatus':
1706
2291
  {
1707
2292
  return _objectSpread2(_objectSpread2({}, state), {}, {
1708
2293
  status: action.payload
1709
2294
  });
1710
2295
  }
1711
-
1712
2296
  case 'setContext':
1713
2297
  {
1714
2298
  return _objectSpread2(_objectSpread2({}, state), {}, {
1715
2299
  context: _objectSpread2(_objectSpread2({}, state.context), action.payload)
1716
2300
  });
1717
2301
  }
1718
-
1719
2302
  case 'ArrowDown':
1720
2303
  {
1721
2304
  var nextState = _objectSpread2(_objectSpread2({}, state), {}, {
1722
2305
  activeItemId: action.payload.hasOwnProperty('nextActiveItemId') ? action.payload.nextActiveItemId : getNextActiveItemId(1, state.activeItemId, getItemsCount(state), action.props.defaultActiveItemId)
1723
2306
  });
1724
-
1725
2307
  return _objectSpread2(_objectSpread2({}, nextState), {}, {
1726
2308
  completion: getCompletion({
1727
2309
  state: nextState
1728
2310
  })
1729
2311
  });
1730
2312
  }
1731
-
1732
2313
  case 'ArrowUp':
1733
2314
  {
1734
2315
  var _nextState = _objectSpread2(_objectSpread2({}, state), {}, {
1735
2316
  activeItemId: getNextActiveItemId(-1, state.activeItemId, getItemsCount(state), action.props.defaultActiveItemId)
1736
2317
  });
1737
-
1738
2318
  return _objectSpread2(_objectSpread2({}, _nextState), {}, {
1739
2319
  completion: getCompletion({
1740
2320
  state: _nextState
1741
2321
  })
1742
2322
  });
1743
2323
  }
1744
-
1745
2324
  case 'Escape':
1746
2325
  {
1747
2326
  if (state.isOpen) {
@@ -1751,7 +2330,6 @@
1751
2330
  completion: null
1752
2331
  });
1753
2332
  }
1754
-
1755
2333
  return _objectSpread2(_objectSpread2({}, state), {}, {
1756
2334
  activeItemId: null,
1757
2335
  query: '',
@@ -1759,7 +2337,6 @@
1759
2337
  collections: []
1760
2338
  });
1761
2339
  }
1762
-
1763
2340
  case 'submit':
1764
2341
  {
1765
2342
  return _objectSpread2(_objectSpread2({}, state), {}, {
@@ -1768,12 +2345,13 @@
1768
2345
  status: 'idle'
1769
2346
  });
1770
2347
  }
1771
-
1772
2348
  case 'reset':
1773
2349
  {
1774
2350
  return _objectSpread2(_objectSpread2({}, state), {}, {
1775
- activeItemId: // Since we open the panel on reset when openOnFocus=true
2351
+ activeItemId:
2352
+ // Since we open the panel on reset when openOnFocus=true
1776
2353
  // we need to restore the highlighted index to the defaultActiveItemId. (DocSearch use-case)
2354
+
1777
2355
  // Since we close the panel when openOnFocus=false
1778
2356
  // we lose track of the highlighted index. (Query-suggestions use-case)
1779
2357
  action.props.openOnFocus === true ? action.props.defaultActiveItemId : null,
@@ -1781,7 +2359,6 @@
1781
2359
  query: ''
1782
2360
  });
1783
2361
  }
1784
-
1785
2362
  case 'focus':
1786
2363
  {
1787
2364
  return _objectSpread2(_objectSpread2({}, state), {}, {
@@ -1791,33 +2368,28 @@
1791
2368
  })
1792
2369
  });
1793
2370
  }
1794
-
1795
2371
  case 'blur':
1796
2372
  {
1797
2373
  if (action.props.debug) {
1798
2374
  return state;
1799
2375
  }
1800
-
1801
2376
  return _objectSpread2(_objectSpread2({}, state), {}, {
1802
2377
  isOpen: false,
1803
2378
  activeItemId: null
1804
2379
  });
1805
2380
  }
1806
-
1807
2381
  case 'mousemove':
1808
2382
  {
1809
2383
  return _objectSpread2(_objectSpread2({}, state), {}, {
1810
2384
  activeItemId: action.payload
1811
2385
  });
1812
2386
  }
1813
-
1814
2387
  case 'mouseleave':
1815
2388
  {
1816
2389
  return _objectSpread2(_objectSpread2({}, state), {}, {
1817
2390
  activeItemId: action.props.defaultActiveItemId
1818
2391
  });
1819
2392
  }
1820
-
1821
2393
  default:
1822
2394
  invariant(false, "The reducer action ".concat(JSON.stringify(action.type), " is not supported."));
1823
2395
  return state;
@@ -1838,10 +2410,9 @@
1838
2410
  store: store,
1839
2411
  navigator: props.navigator
1840
2412
  }, setters));
1841
-
1842
2413
  function onStoreStateChange(_ref) {
1843
2414
  var prevState = _ref.prevState,
1844
- state = _ref.state;
2415
+ state = _ref.state;
1845
2416
  props.onStateChange(_objectSpread2({
1846
2417
  prevState: prevState,
1847
2418
  state: state,
@@ -1849,7 +2420,6 @@
1849
2420
  navigator: props.navigator
1850
2421
  }, setters));
1851
2422
  }
1852
-
1853
2423
  function refresh() {
1854
2424
  return onInput(_objectSpread2({
1855
2425
  event: new Event('input'),
@@ -1863,10 +2433,14 @@
1863
2433
  store: store
1864
2434
  }, setters));
1865
2435
  }
1866
-
2436
+ if (options.insights && !props.plugins.some(function (plugin) {
2437
+ return plugin.name === 'aa.algoliaInsightsPlugin';
2438
+ })) {
2439
+ var insightsParams = typeof options.insights === 'boolean' ? {} : options.insights;
2440
+ props.plugins.push(createAlgoliaInsightsPlugin(insightsParams));
2441
+ }
1867
2442
  props.plugins.forEach(function (plugin) {
1868
2443
  var _plugin$subscribe;
1869
-
1870
2444
  return (_plugin$subscribe = plugin.subscribe) === null || _plugin$subscribe === void 0 ? void 0 : _plugin$subscribe.call(plugin, _objectSpread2(_objectSpread2({}, setters), {}, {
1871
2445
  navigator: props.navigator,
1872
2446
  refresh: refresh,