UNPKG

@algolia/autocomplete-core

Version:

Core primitives for building autocomplete experiences.

1,346 lines (1,306 loc) 103 kB
/*! @algolia/autocomplete-core 1.19.1 | MIT License | © Algolia, Inc. and contributors | https://github.com/algolia/autocomplete */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global["@algolia/autocomplete-core"] = {})); })(this, (function (exports) { 'use strict'; function ownKeys$2(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread2(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$2(Object(source), !0).forEach(function (key) { _defineProperty$2(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _typeof$3(obj) { "@babel/helpers - typeof"; return _typeof$3 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$3(obj); } function _defineProperty$2(obj, key, value) { key = _toPropertyKey$2(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutPropertiesLoose$1(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function _objectWithoutProperties$1(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose$1(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _toConsumableArray$2(arr) { return _arrayWithoutHoles$2(arr) || _iterableToArray$2(arr) || _unsupportedIterableToArray$4(arr) || _nonIterableSpread$2(); } function _arrayWithoutHoles$2(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$4(arr); } function _iterableToArray$2(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _unsupportedIterableToArray$4(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$4(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$4(o, minLen); } function _arrayLikeToArray$4(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; } function _nonIterableSpread$2() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray$4(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _toPrimitive$2(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); } function _toPropertyKey$2(arg) { var key = _toPrimitive$2(arg, "string"); return typeof key === "symbol" ? key : String(key); } function createRef(initialValue) { return { current: initialValue }; } function debounce(fn, time) { var timerId = undefined; return function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (timerId) { clearTimeout(timerId); } timerId = setTimeout(function () { return fn.apply(void 0, args); }, time); }; } function _slicedToArray$1(arr, i) { return _arrayWithHoles$1(arr) || _iterableToArrayLimit$1(arr, i) || _unsupportedIterableToArray$3(arr, i) || _nonIterableRest$1(); } function _nonIterableRest$1() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray$3(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$3(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$3(o, minLen); } function _arrayLikeToArray$3(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; } function _iterableToArrayLimit$1(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; } } function _arrayWithHoles$1(arr) { if (Array.isArray(arr)) return arr; } function _typeof$2(obj) { "@babel/helpers - typeof"; return _typeof$2 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$2(obj); } /** * Decycles objects with circular references. * This is used to print cyclic structures in development environment only. */ function decycle(obj) { var seen = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : new Set(); if (!obj || _typeof$2(obj) !== 'object') { return obj; } if (seen.has(obj)) { return '[Circular]'; } var newSeen = seen.add(obj); if (Array.isArray(obj)) { return obj.map(function (x) { return decycle(x, newSeen); }); } return Object.fromEntries(Object.entries(obj).map(function (_ref) { var _ref2 = _slicedToArray$1(_ref, 2), key = _ref2[0], value = _ref2[1]; return [key, decycle(value, newSeen)]; })); } function flatten(values) { return values.reduce(function (a, b) { return a.concat(b); }, []); } var autocompleteId = 0; function generateAutocompleteId() { return "autocomplete-".concat(autocompleteId++); } function getItemsCount(state) { if (state.collections.length === 0) { return 0; } return state.collections.reduce(function (sum, collection) { return sum + collection.items.length; }, 0); } /** * Throws an error if the condition is not met in development mode. * This is used to make development a better experience to provide guidance as * to where the error comes from. */ function invariant(condition, message) { if (!condition) { throw new Error("[Autocomplete] ".concat(typeof message === 'function' ? message() : message)); } } function isPrimitive(obj) { return obj !== Object(obj); } function isEqual(first, second) { if (first === second) { return true; } if (isPrimitive(first) || isPrimitive(second) || typeof first === 'function' || typeof second === 'function') { return first === second; } if (Object.keys(first).length !== Object.keys(second).length) { return false; } for (var _i = 0, _Object$keys = Object.keys(first); _i < _Object$keys.length; _i++) { var key = _Object$keys[_i]; if (!(key in second)) { return false; } if (!isEqual(first[key], second[key])) { return false; } } return true; } var noop = function noop() {}; /** * Safely runs code meant for browser environments only. */ function safelyRunOnBrowser(callback) { if (typeof window !== 'undefined') { return callback({ window: window }); } return undefined; } var version = '1.19.1'; var userAgents = [{ segment: 'autocomplete-core', version: version }]; var warnCache = { current: {} }; /** * Logs a warning if the condition is not met. * This is used to log issues in development environment only. */ function warn(condition, message) { if (condition) { return; } var sanitizedMessage = message.trim(); var hasAlreadyPrinted = warnCache.current[sanitizedMessage]; if (!hasAlreadyPrinted) { warnCache.current[sanitizedMessage] = true; // eslint-disable-next-line no-console console.warn("[Autocomplete] ".concat(sanitizedMessage)); } } function createClickedEvent(_ref) { var item = _ref.item, _ref$items = _ref.items, items = _ref$items === void 0 ? [] : _ref$items; return { index: item.__autocomplete_indexName, items: [item], positions: [1 + items.findIndex(function (x) { return x.objectID === item.objectID; })], queryID: item.__autocomplete_queryID, algoliaSource: ['autocomplete'] }; } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray$2(arr, i) || _nonIterableRest(); } 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."); } function _unsupportedIterableToArray$2(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$2(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$2(o, minLen); } function _arrayLikeToArray$2(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; } 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; } } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } /** * Determines if a given insights `client` supports the optional call to `init` * and the ability to set credentials via extra parameters when sending events. */ function isModernInsightsClient(client) { var _split$map = (client.version || '').split('.').map(Number), _split$map2 = _slicedToArray(_split$map, 2), major = _split$map2[0], minor = _split$map2[1]; /* eslint-disable @typescript-eslint/camelcase */ var v3 = major >= 3; var v2_4 = major === 2 && minor >= 4; var v1_10 = major === 1 && minor >= 10; return v3 || v2_4 || v1_10; /* eslint-enable @typescript-eslint/camelcase */ } var _excluded$3 = ["items"], _excluded2$1 = ["items"]; function _typeof$1(obj) { "@babel/helpers - typeof"; return _typeof$1 = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof$1(obj); } function _toConsumableArray$1(arr) { return _arrayWithoutHoles$1(arr) || _iterableToArray$1(arr) || _unsupportedIterableToArray$1(arr) || _nonIterableSpread$1(); } function _nonIterableSpread$1() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray$1(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray$1(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$1(o, minLen); } function _iterableToArray$1(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles$1(arr) { if (Array.isArray(arr)) return _arrayLikeToArray$1(arr); } function _arrayLikeToArray$1(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; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function ownKeys$1(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread$1(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys$1(Object(source), !0).forEach(function (key) { _defineProperty$1(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$1(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty$1(obj, key, value) { key = _toPropertyKey$1(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey$1(arg) { var key = _toPrimitive$1(arg, "string"); return _typeof$1(key) === "symbol" ? key : String(key); } function _toPrimitive$1(input, hint) { if (_typeof$1(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof$1(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); } function chunk(item) { var chunkSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20; var chunks = []; for (var i = 0; i < item.objectIDs.length; i += chunkSize) { chunks.push(_objectSpread$1(_objectSpread$1({}, item), {}, { objectIDs: item.objectIDs.slice(i, i + chunkSize) })); } return chunks; } function mapToInsightsParamsApi(params) { return params.map(function (_ref) { var items = _ref.items, param = _objectWithoutProperties(_ref, _excluded$3); return _objectSpread$1(_objectSpread$1({}, param), {}, { objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref2) { var objectID = _ref2.objectID; return objectID; })) || param.objectIDs }); }); } function createSearchInsightsApi(searchInsights) { var canSendHeaders = isModernInsightsClient(searchInsights); function sendToInsights(method, payloads, items) { if (canSendHeaders && typeof items !== 'undefined') { var _items$0$__autocomple = items[0].__autocomplete_algoliaCredentials, appId = _items$0$__autocomple.appId, apiKey = _items$0$__autocomple.apiKey; var headers = { 'X-Algolia-Application-Id': appId, 'X-Algolia-API-Key': apiKey }; searchInsights.apply(void 0, [method].concat(_toConsumableArray$1(payloads), [{ headers: headers }])); } else { searchInsights.apply(void 0, [method].concat(_toConsumableArray$1(payloads))); } } return { /** * Initializes Insights with Algolia credentials. */ init: function init(appId, apiKey) { searchInsights('init', { appId: appId, apiKey: apiKey }); }, /** * Sets the authenticated user token to attach to events. * Unsets the authenticated token by passing `undefined`. * * @link https://www.algolia.com/doc/api-reference/api-methods/set-authenticated-user-token/ */ setAuthenticatedUserToken: function setAuthenticatedUserToken(authenticatedUserToken) { searchInsights('setAuthenticatedUserToken', authenticatedUserToken); }, /** * Sets the user token to attach to events. */ setUserToken: function setUserToken(userToken) { searchInsights('setUserToken', userToken); }, /** * Sends click events to capture a query and its clicked items and positions. * * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids-after-search/ */ clickedObjectIDsAfterSearch: function clickedObjectIDsAfterSearch() { for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) { params[_key] = arguments[_key]; } if (params.length > 0) { sendToInsights('clickedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items); } }, /** * Sends click events to capture clicked items. * * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-object-ids/ */ clickedObjectIDs: function clickedObjectIDs() { for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { params[_key2] = arguments[_key2]; } if (params.length > 0) { sendToInsights('clickedObjectIDs', mapToInsightsParamsApi(params), params[0].items); } }, /** * Sends click events to capture the filters a user clicks on. * * @link https://www.algolia.com/doc/api-reference/api-methods/clicked-filters/ */ clickedFilters: function clickedFilters() { for (var _len3 = arguments.length, params = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { params[_key3] = arguments[_key3]; } if (params.length > 0) { searchInsights.apply(void 0, ['clickedFilters'].concat(params)); } }, /** * Sends conversion events to capture a query and its clicked items. * * @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids-after-search/ */ convertedObjectIDsAfterSearch: function convertedObjectIDsAfterSearch() { for (var _len4 = arguments.length, params = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { params[_key4] = arguments[_key4]; } if (params.length > 0) { sendToInsights('convertedObjectIDsAfterSearch', mapToInsightsParamsApi(params), params[0].items); } }, /** * Sends conversion events to capture clicked items. * * @link https://www.algolia.com/doc/api-reference/api-methods/converted-object-ids/ */ convertedObjectIDs: function convertedObjectIDs() { for (var _len5 = arguments.length, params = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { params[_key5] = arguments[_key5]; } if (params.length > 0) { sendToInsights('convertedObjectIDs', mapToInsightsParamsApi(params), params[0].items); } }, /** * Sends conversion events to capture the filters a user uses when converting. * * @link https://www.algolia.com/doc/api-reference/api-methods/converted-filters/ */ convertedFilters: function convertedFilters() { for (var _len6 = arguments.length, params = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { params[_key6] = arguments[_key6]; } if (params.length > 0) { searchInsights.apply(void 0, ['convertedFilters'].concat(params)); } }, /** * Sends view events to capture clicked items. * * @link https://www.algolia.com/doc/api-reference/api-methods/viewed-object-ids/ */ viewedObjectIDs: function viewedObjectIDs() { for (var _len7 = arguments.length, params = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { params[_key7] = arguments[_key7]; } if (params.length > 0) { params.reduce(function (acc, _ref3) { var items = _ref3.items, param = _objectWithoutProperties(_ref3, _excluded2$1); return [].concat(_toConsumableArray$1(acc), _toConsumableArray$1(chunk(_objectSpread$1(_objectSpread$1({}, param), {}, { objectIDs: (items === null || items === void 0 ? void 0 : items.map(function (_ref4) { var objectID = _ref4.objectID; return objectID; })) || param.objectIDs })).map(function (payload) { return { items: items, payload: payload }; }))); }, []).forEach(function (_ref5) { var items = _ref5.items, payload = _ref5.payload; return sendToInsights('viewedObjectIDs', [payload], items); }); } }, /** * Sends view events to capture the filters a user uses when viewing. * * @link https://www.algolia.com/doc/api-reference/api-methods/viewed-filters/ */ viewedFilters: function viewedFilters() { for (var _len8 = arguments.length, params = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { params[_key8] = arguments[_key8]; } if (params.length > 0) { searchInsights.apply(void 0, ['viewedFilters'].concat(params)); } } }; } function createViewedEvents(_ref) { var items = _ref.items; var itemsByIndexName = items.reduce(function (acc, current) { var _acc$current$__autoco; acc[current.__autocomplete_indexName] = ((_acc$current$__autoco = acc[current.__autocomplete_indexName]) !== null && _acc$current$__autoco !== void 0 ? _acc$current$__autoco : []).concat(current); return acc; }, {}); return Object.keys(itemsByIndexName).map(function (indexName) { var items = itemsByIndexName[indexName]; return { index: indexName, items: items, algoliaSource: ['autocomplete'] }; }); } function isAlgoliaInsightsHit(hit) { return hit.objectID && hit.__autocomplete_indexName && hit.__autocomplete_queryID; } function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } 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."); } 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); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } 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; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; } function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); } 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); } var VIEW_EVENT_DELAY = 400; var ALGOLIA_INSIGHTS_VERSION = '2.15.0'; var ALGOLIA_INSIGHTS_SRC = "https://cdn.jsdelivr.net/npm/search-insights@".concat(ALGOLIA_INSIGHTS_VERSION, "/dist/search-insights.min.js"); var sendViewedObjectIDs = debounce(function (_ref) { var onItemsChange = _ref.onItemsChange, items = _ref.items, insights = _ref.insights, state = _ref.state; onItemsChange({ insights: insights, insightsEvents: createViewedEvents({ items: items }).map(function (event) { return _objectSpread({ eventName: 'Items Viewed' }, event); }), state: state }); }, VIEW_EVENT_DELAY); function createAlgoliaInsightsPlugin(options) { var _getOptions = getOptions(options), providedInsightsClient = _getOptions.insightsClient, insightsInitParams = _getOptions.insightsInitParams, onItemsChange = _getOptions.onItemsChange, onSelectEvent = _getOptions.onSelect, onActiveEvent = _getOptions.onActive, __autocomplete_clickAnalytics = _getOptions.__autocomplete_clickAnalytics; var insightsClient = providedInsightsClient; if (!providedInsightsClient) { safelyRunOnBrowser(function (_ref2) { var window = _ref2.window; var pointer = window.AlgoliaAnalyticsObject || 'aa'; if (typeof pointer === 'string') { insightsClient = window[pointer]; } if (!insightsClient) { window.AlgoliaAnalyticsObject = pointer; if (!window[pointer]) { window[pointer] = function () { if (!window[pointer].queue) { window[pointer].queue = []; } for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } window[pointer].queue.push(args); }; } window[pointer].version = ALGOLIA_INSIGHTS_VERSION; insightsClient = window[pointer]; loadInsights(window); } }); } // We return an empty plugin if `insightsClient` is still undefined at // this stage, which can happen in server environments. if (!insightsClient) { return {}; } if (insightsInitParams) { insightsClient('init', _objectSpread({ partial: true }, insightsInitParams)); } var insights = createSearchInsightsApi(insightsClient); var previousItems = createRef([]); var debouncedOnStateChange = debounce(function (_ref3) { var state = _ref3.state; if (!state.isOpen) { return; } var items = state.collections.reduce(function (acc, current) { return [].concat(_toConsumableArray(acc), _toConsumableArray(current.items)); }, []).filter(isAlgoliaInsightsHit); if (!isEqual(previousItems.current.map(function (x) { return x.objectID; }), items.map(function (x) { return x.objectID; }))) { previousItems.current = items; if (items.length > 0) { sendViewedObjectIDs({ onItemsChange: onItemsChange, items: items, insights: insights, state: state }); } } }, 0); return { name: 'aa.algoliaInsightsPlugin', subscribe: function subscribe(_ref4) { var setContext = _ref4.setContext, onSelect = _ref4.onSelect, onActive = _ref4.onActive; function setInsightsContext(userToken) { setContext({ algoliaInsightsPlugin: { __algoliaSearchParameters: _objectSpread(_objectSpread({}, __autocomplete_clickAnalytics ? { clickAnalytics: true } : {}), userToken ? { userToken: normalizeUserToken(userToken) } : {}), insights: insights } }); } insightsClient('addAlgoliaAgent', 'insights-plugin'); setInsightsContext(); // Handles user token changes insightsClient('onUserTokenChange', function (userToken) { setInsightsContext(userToken); }); insightsClient('getUserToken', null, function (_error, userToken) { setInsightsContext(userToken); }); onSelect(function (_ref5) { var item = _ref5.item, state = _ref5.state, event = _ref5.event, source = _ref5.source; if (!isAlgoliaInsightsHit(item)) { return; } onSelectEvent({ state: state, event: event, insights: insights, item: item, insightsEvents: [_objectSpread({ eventName: 'Item Selected' }, createClickedEvent({ item: item, items: source.getItems().filter(isAlgoliaInsightsHit) }))] }); }); onActive(function (_ref6) { var item = _ref6.item, source = _ref6.source, state = _ref6.state, event = _ref6.event; if (!isAlgoliaInsightsHit(item)) { return; } onActiveEvent({ state: state, event: event, insights: insights, item: item, insightsEvents: [_objectSpread({ eventName: 'Item Active' }, createClickedEvent({ item: item, items: source.getItems().filter(isAlgoliaInsightsHit) }))] }); }); }, onStateChange: function onStateChange(_ref7) { var state = _ref7.state; debouncedOnStateChange({ state: state }); }, __autocomplete_pluginOptions: options }; } function getAlgoliaSources() { var _context$algoliaInsig; var algoliaSourceBase = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var context = arguments.length > 1 ? arguments[1] : undefined; return [].concat(_toConsumableArray(algoliaSourceBase), ['autocomplete-internal'], _toConsumableArray((_context$algoliaInsig = context.algoliaInsightsPlugin) !== null && _context$algoliaInsig !== void 0 && _context$algoliaInsig.__automaticInsights ? ['autocomplete-automatic'] : [])); } function getOptions(options) { return _objectSpread({ onItemsChange: function onItemsChange(_ref8) { var insights = _ref8.insights, insightsEvents = _ref8.insightsEvents, state = _ref8.state; insights.viewedObjectIDs.apply(insights, _toConsumableArray(insightsEvents.map(function (event) { return _objectSpread(_objectSpread({}, event), {}, { algoliaSource: getAlgoliaSources(event.algoliaSource, state.context) }); }))); }, onSelect: function onSelect(_ref9) { var insights = _ref9.insights, insightsEvents = _ref9.insightsEvents, state = _ref9.state; insights.clickedObjectIDsAfterSearch.apply(insights, _toConsumableArray(insightsEvents.map(function (event) { return _objectSpread(_objectSpread({}, event), {}, { algoliaSource: getAlgoliaSources(event.algoliaSource, state.context) }); }))); }, onActive: noop, __autocomplete_clickAnalytics: true }, options); } function loadInsights(environment) { var errorMessage = "[Autocomplete]: Could not load search-insights.js. Please load it manually following https://alg.li/insights-autocomplete"; try { var script = environment.document.createElement('script'); script.async = true; script.src = ALGOLIA_INSIGHTS_SRC; script.onerror = function () { // eslint-disable-next-line no-console console.error(errorMessage); }; document.body.appendChild(script); } catch (cause) { // eslint-disable-next-line no-console console.error(errorMessage); } } /** * While `search-insights` supports both string and number user tokens, * the Search API only accepts strings. This function normalizes the user token. */ function normalizeUserToken(userToken) { return typeof userToken === 'number' ? userToken.toString() : userToken; } function checkOptions(options) { "development" !== 'production' ? warn(!options.debug, 'The `debug` option is meant for development debugging and should not be used in production.') : void 0; } function createInternalCancelablePromise(promise, initialState) { var state = initialState; return { then: function then(onfulfilled, onrejected) { return createInternalCancelablePromise(promise.then(createCallback(onfulfilled, state, promise), createCallback(onrejected, state, promise)), state); }, catch: function _catch(onrejected) { return createInternalCancelablePromise(promise.catch(createCallback(onrejected, state, promise)), state); }, finally: function _finally(onfinally) { if (onfinally) { state.onCancelList.push(onfinally); } return createInternalCancelablePromise(promise.finally(createCallback(onfinally && function () { state.onCancelList = []; return onfinally(); }, state, promise)), state); }, cancel: function cancel() { state.isCanceled = true; var callbacks = state.onCancelList; state.onCancelList = []; callbacks.forEach(function (callback) { callback(); }); }, isCanceled: function isCanceled() { return state.isCanceled === true; } }; } function cancelable(promise) { return createInternalCancelablePromise(promise, { isCanceled: false, onCancelList: [] }); } function createCallback(onResult, state, fallback) { if (!onResult) { return fallback; } return function callback(arg) { if (state.isCanceled) { return arg; } return onResult(arg); }; } // Ensures multiple callers sync to the same promise. var _hasWaitPromiseResolved = true; var _waitPromise; function createCancelablePromiseList() { var list = []; return { add: function add(cancelablePromise) { list.push(cancelablePromise); return cancelablePromise.finally(function () { list = list.filter(function (item) { return item !== cancelablePromise; }); }); }, cancelAll: function cancelAll() { list.forEach(function (promise) { return promise.cancel(); }); }, isEmpty: function isEmpty() { return list.length === 0; }, wait: function wait(timeout) { // Reuse promise if already exists. Keeps multiple callers subscribed to the same promise. if (!_hasWaitPromiseResolved) { return _waitPromise; } // Creates a promise which either resolves after all pending requests complete // or the timeout is reached (if provided). Whichever comes first. _hasWaitPromiseResolved = false; _waitPromise = !timeout ? Promise.all(list) : Promise.race([Promise.all(list), new Promise(function (resolve) { return setTimeout(resolve, timeout); })]); return _waitPromise.then(function () { _hasWaitPromiseResolved = true; }); } }; } /** * Creates a runner that executes promises in a concurrent-safe way. * * This is useful to prevent older promises to resolve after a newer promise, * otherwise resulting in stale resolved values. */ function createConcurrentSafePromise() { var basePromiseId = -1; var latestResolvedId = -1; var latestResolvedValue = undefined; return function runConcurrentSafePromise(promise) { basePromiseId++; var currentPromiseId = basePromiseId; return Promise.resolve(promise).then(function (x) { // The promise might take too long to resolve and get outdated. This would // result in resolving stale values. // When this happens, we ignore the promise value and return the one // coming from the latest resolved value. // // +----------------------------------+ // | 100ms | // | run(1) +---> R1 | // | 300ms | // | run(2) +-------------> R2 (SKIP) | // | 200ms | // | run(3) +--------> R3 | // +----------------------------------+ if (latestResolvedValue && currentPromiseId < latestResolvedId) { return latestResolvedValue; } latestResolvedId = currentPromiseId; latestResolvedValue = x; return x; }); }; } /** * Returns the next active item ID from the current state. * * We allow circular keyboard navigation from the base index. * The base index can either be `null` (nothing is highlighted) or `0` * (the first item is highlighted). * The base index is allowed to get assigned `null` only if * `props.defaultActiveItemId` is `null`. This pattern allows to "stop" * by the actual query before navigating to other suggestions as seen on * Google or Amazon. * * @param moveAmount The offset to increment (or decrement) the last index * @param baseIndex The current index to compute the next index from * @param itemCount The number of items * @param defaultActiveItemId The default active index to fallback to */ function getNextActiveItemId(moveAmount, baseIndex, itemCount, defaultActiveItemId) { if (!itemCount) { return null; } if (moveAmount < 0 && (baseIndex === null || defaultActiveItemId !== null && baseIndex === 0)) { return itemCount + moveAmount; } var numericIndex = (baseIndex === null ? -1 : baseIndex) + moveAmount; if (numericIndex <= -1 || numericIndex >= itemCount) { return defaultActiveItemId === null ? null : 0; } return numericIndex; } function getNormalizedSources(getSources, params) { var seenSourceIds = []; return Promise.resolve(getSources(params)).then(function (sources) { invariant(Array.isArray(sources), function () { 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)); }); return Promise.all(sources // We allow `undefined` and `false` sources to allow users to use // `Boolean(query) && source` (=> `false`). // We need to remove these values at this point. .filter(function (maybeSource) { return Boolean(maybeSource); }).map(function (source) { invariant(typeof source.sourceId === 'string', 'A source must provide a `sourceId` string.'); if (seenSourceIds.includes(source.sourceId)) { throw new Error("[Autocomplete] The `sourceId` ".concat(JSON.stringify(source.sourceId), " is not unique.")); } seenSourceIds.push(source.sourceId); var defaultSource = { getItemInputValue: function getItemInputValue(_ref) { var state = _ref.state; return state.query; }, getItemUrl: function getItemUrl() { return undefined; }, onSelect: function onSelect(_ref2) { var setIsOpen = _ref2.setIsOpen; setIsOpen(false); }, onActive: noop, onResolve: noop }; Object.keys(defaultSource).forEach(function (key) { defaultSource[key].__default = true; }); var normalizedSource = _objectSpread2(_objectSpread2({}, defaultSource), source); return Promise.resolve(normalizedSource); })); }); } /** * If a plugin is configured to await a submit event, this returns a promise * for either the max timeout value found or until it completes. * Otherwise, return undefined. */ var getPluginSubmitPromise = function getPluginSubmitPromise(plugins, pendingRequests) { var waitUntilComplete = false; var timeouts = []; var _iterator = _createForOfIteratorHelper(plugins), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var _plugin$__autocomplet, _plugin$__autocomplet2, _plugin$__autocomplet3; var plugin = _step.value; var value = (_plugin$__autocomplet = plugin.__autocomplete_pluginOptions) === null || _plugin$__autocomplet === void 0 ? void 0 : (_plugin$__autocomplet2 = (_plugin$__autocomplet3 = _plugin$__autocomplet).awaitSubmit) === null || _plugin$__autocomplet2 === void 0 ? void 0 : _plugin$__autocomplet2.call(_plugin$__autocomplet3); if (typeof value === 'number') { timeouts.push(value); } else if (value === true) { waitUntilComplete = true; break; // break loop as bool overrides num array below } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (waitUntilComplete) { return pendingRequests.wait(); } else if (timeouts.length > 0) { return pendingRequests.wait(Math.max.apply(Math, timeouts)); } return undefined; }; // We don't have access to the autocomplete source when we call `onKeyDown` // or `onClick` because those are native browser events. // However, we can get the source from the suggestion index. function getCollectionFromActiveItemId(state) { // Given 3 sources with respectively 1, 2 and 3 suggestions: [1, 2, 3] // We want to get the accumulated counts: // [1, 1 + 2, 1 + 2 + 3] = [1, 3, 3 + 3] = [1, 3, 6] var accumulatedCollectionsCount = state.collections.map(function (collections) { return collections.items.length; }).reduce(function (acc, collectionsCount, index) { var previousValue = acc[index - 1] || 0; var nextValue = previousValue + collectionsCount; acc.push(nextValue); return acc; }, []); // Based on the accumulated counts, we can infer the index of the suggestion. var col