stored-searches.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. var _excluded = ["_highlightResult", "_snippetResult"];
  2. 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; }
  3. 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; }
  4. function isLocalStorageSupported() {
  5. var key = '__TEST_KEY__';
  6. try {
  7. localStorage.setItem(key, '');
  8. localStorage.removeItem(key);
  9. return true;
  10. } catch (error) {
  11. return false;
  12. }
  13. }
  14. function createStorage(key) {
  15. if (isLocalStorageSupported() === false) {
  16. return {
  17. setItem: function setItem() {},
  18. getItem: function getItem() {
  19. return [];
  20. }
  21. };
  22. }
  23. return {
  24. setItem: function setItem(item) {
  25. return window.localStorage.setItem(key, JSON.stringify(item));
  26. },
  27. getItem: function getItem() {
  28. var item = window.localStorage.getItem(key);
  29. return item ? JSON.parse(item) : [];
  30. }
  31. };
  32. }
  33. export function createStoredSearches(_ref) {
  34. var key = _ref.key,
  35. _ref$limit = _ref.limit,
  36. limit = _ref$limit === void 0 ? 5 : _ref$limit;
  37. var storage = createStorage(key);
  38. var items = storage.getItem().slice(0, limit);
  39. return {
  40. add: function add(item) {
  41. var _ref2 = item,
  42. _highlightResult = _ref2._highlightResult,
  43. _snippetResult = _ref2._snippetResult,
  44. hit = _objectWithoutProperties(_ref2, _excluded);
  45. var isQueryAlreadySaved = items.findIndex(function (x) {
  46. return x.objectID === hit.objectID;
  47. });
  48. if (isQueryAlreadySaved > -1) {
  49. items.splice(isQueryAlreadySaved, 1);
  50. }
  51. items.unshift(hit);
  52. items = items.slice(0, limit);
  53. storage.setItem(items);
  54. },
  55. remove: function remove(item) {
  56. items = items.filter(function (x) {
  57. return x.objectID !== item.objectID;
  58. });
  59. storage.setItem(items);
  60. },
  61. getAll: function getAll() {
  62. return items;
  63. }
  64. };
  65. }