UNPKG

turnstone-recent-searches

Version:

A plugin for the Turnstone React component. Display Recent Searches in the default listbox.

76 lines (75 loc) 2.72 kB
var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); import React, { useCallback } from "react"; const RecentSearchesPlugin = React.forwardRef((props, ref) => { const { Component, componentProps, pluginIndex, render, ratio = 1, id, name = "Recent Searches", storageKey = "recentSearches", limit = 10 } = props; const { defaultListbox = [], onSelect } = componentProps; const recentSearches = useCallback(() => { return JSON.parse(localStorage.getItem(storageKey)) || []; }, [storageKey]); const addToRecentSearches = useCallback((itemToAdd) => { const searches = [itemToAdd, ...recentSearches().filter((item) => item._displayField !== itemToAdd._displayField)]; localStorage.setItem(storageKey, JSON.stringify(searches.slice(0, limit))); }, [storageKey, limit, recentSearches]); const buildDefaultListBox = () => { return [{ id, name, displayField: "_displayField", data: () => Promise.resolve(recentSearches()), ratio }, ...defaultListbox]; }; const handleSelect = useCallback((selectedResult, displayField) => { if (selectedResult) { if (typeof selectedResult === "string") { selectedResult = { _displayField: selectedResult }; } else { selectedResult._displayField = selectedResult[displayField]; } addToRecentSearches(selectedResult); } if (typeof onSelect === "function") onSelect(selectedResult, displayField); }, [addToRecentSearches, onSelect]); const newComponentProps = __spreadProps(__spreadValues({}, componentProps), { defaultListbox: buildDefaultListBox(), defaultListboxIsImmutable: false, onSelect: handleSelect }); return render(Component, newComponentProps, pluginIndex + 1, ref); }); RecentSearchesPlugin.displayName = "RecentSearchesPlugin"; export { RecentSearchesPlugin as default };