-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js.map
1 lines (1 loc) · 11 KB
/
index.js.map
1
{"version":3,"file":"index.js","sources":["src/helpers/validateInitialValue.ts","src/hooks/useSortable/index.ts"],"sourcesContent":["/**\n * The validator function returns\n * - input array for array or object that can be change to a array\n * - [] for other\n *\n * @param {any} initialValue\n * Value to be validated\n *\n * @return {Array}\n * input array or [] for wrong input\n *\n * @example\n * const validatedInitialValue = validateInitialValue(initialValue);\n */\nexport const validateInitialValue = (initialValue: any): Array<any> => {\n if (\n typeof initialValue === 'object' &&\n initialValue !== null &&\n !Array.isArray(initialValue)\n ) {\n console.log(\n 'you have passed a object when a array is required. It still may work however. Please pass a array.',\n );\n initialValue = [...initialValue];\n }\n if (!Array.isArray(initialValue)) {\n console.log(\n 'you really want to break the validation. Please pass a array as parameter. Defaulting to [].',\n );\n initialValue = [];\n }\n\n return initialValue;\n};\n","import { useEffect, useMemo, useState } from 'react';\nimport { validateInitialValue } from '../../helpers/validateInitialValue';\n\ntype IUseSortable = {\n items: Array<any>;\n requestSort: (key: string, direction: string) => void;\n requestSearch: (search: string, value: string) => void;\n requestBookMark: (id: string | number) => void;\n};\n\ntype Config = {\n key: string;\n direction: string;\n bookMarks: Array<any>;\n search: string;\n value: string;\n};\n\n/**\n * Classic sort & search example to help understand the flow of this npm package\n *\n * @param {Array} initialValue\n * initial sort & search value\n *\n * @param {Config} config\n * initial config for sort & search in initialValue\n *\n * @return {Array}\n * array with sort & search and methods\n *\n * @property {Array} items\n * The current array that sort & search\n *\n * @property {(key: string | number, direction: string) => void} requestSort\n * the request for Sort function that get what Key you want to sort and direction\n * direction can be \"ascending\" or \"descending\"\n * defult value of direction is \"ascending\"\n *\n * @property {(search: string | number, value: string | number) => void} requestSearch\n * the request for Search function that get Search for what Key you want search and value\n *\n * @property {(id: string | number) => void} requestBookMark\n * the request for BookMark function that get what Id you want to book mark and set top of you array\n *\n * @example\n * const ExampleComponent = () => {\n * const myArray = [{\n * id: 1,\n * name: \"Saber\",\n * family: \"Pourrahimi\"\n * ...\n * },\n * {\n * id: 2,\n * name: \"Maryam\",\n * family: \"Mirzayee\"\n * ...\n * }]\n * const { items, requestSort, requestSearch, requestBookMark } = useSortable(myArray);\n *\n * return (\n * <>\n * <table>\n * <tr>\n * <td>Id</td>\n * <td>Name</td>\n * <td>Family</td>\n * </tr>\n * {items.map(el => (\n * <tr onClick={() => requestBookMark(el.id)}>\n * <td>{el.id}</td>\n * <td>{el.name}</td>\n * <td>{el.family}</td>\n * </tr>\n * ))}\n * </table>\n * <button onClick={() => requestSort(\"name\", \"ascending\")}>Sort ascending myArray by name</button>\n * <input onChange={(e) => requestSearch(\"name\", e.target.value)}>Search name in myArray</button>\n * <input onChange={(e) => requestSearch(\"family\", e.target.value)}>Search family in myArray</button>\n * </>\n * )\n * }\n */\nexport const useSortable = (\n items: Array<any>,\n config: Config = {\n bookMarks: [],\n key: '',\n direction: '',\n search: '',\n value: '',\n },\n): IUseSortable => {\n const validatedInitialValue = validateInitialValue(items);\n\n const [sortConfig, setSortConfig] = useState<Config>(config);\n const bookMarkList = JSON.parse(window.localStorage.getItem('book-mark') || '[]');\n\n const sortedItems = useMemo(() => {\n let sortableItems = [...validatedInitialValue];\n if (sortConfig !== null && sortConfig.key !== null) {\n sortableItems.sort((a, b) => {\n if (a[sortConfig.key] < b[sortConfig.key]) {\n return sortConfig.direction === 'ascending' ? -1 : 1;\n }\n if (a[sortConfig.key] > b[sortConfig.key]) {\n return sortConfig.direction === 'ascending' ? 1 : -1;\n }\n return 0;\n });\n }\n if (sortConfig !== null && sortConfig.search && sortConfig.value) {\n sortableItems = sortableItems\n .filter((item) => {\n return item[sortConfig.search]\n .toLowerCase()\n .includes(sortConfig.value.toLowerCase());\n })\n .sort((a, b) => {\n if (\n a[sortConfig.search]\n .toLowerCase()\n .indexOf(sortConfig.value.toLowerCase()) >\n b[sortConfig.search]\n .toLowerCase()\n .indexOf(sortConfig.value.toLowerCase())\n ) {\n return 1;\n } else if (\n a[sortConfig.search]\n .toLowerCase()\n .indexOf(sortConfig.value.toLowerCase()) <\n b[sortConfig.search]\n .toLowerCase()\n .indexOf(sortConfig.value.toLowerCase())\n ) {\n return -1;\n } else {\n if (a[sortConfig.search] > b[sortConfig.search]) return 1;\n else return -1;\n }\n });\n }\n if (sortConfig.bookMarks) {\n sortConfig.bookMarks.forEach((bookMark) => {\n sortableItems.sort((x, y) => {\n return x.id === bookMark ? -1 : y.id === bookMark ? 1 : 0;\n });\n });\n }\n return sortableItems;\n }, [items, sortConfig]);\n\n const requestSort = (key: string, direction: string) => {\n if (\n sortConfig &&\n sortConfig.key === key &&\n sortConfig.direction === 'ascending'\n ) {\n direction = 'descending';\n } else if (!direction) {\n direction = 'ascending';\n }\n const params = new URLSearchParams(window.location.search);\n params.set('sort', key.toString());\n params.set('d', direction);\n const URL =\n params.toString().indexOf('null') > 0\n ? `${window.location.pathname}`\n : `${window.location.pathname}?${params.toString()}`;\n window.history.replaceState({}, '', URL);\n setSortConfig({\n ...sortConfig,\n key: key.toString() && key.toString(),\n direction,\n });\n };\n\n const requestSearch = (search: string, value: string) => {\n setSortConfig({\n ...sortConfig,\n search: search && search.toString(),\n value: value && value.toString(),\n });\n };\n\n const requestBookMark = (id: string | number) => {\n const bookMarks = sortConfig.bookMarks;\n const updatedBookMarks = [\n ...bookMarks.filter((el) => el !== id), // Only add element if it doesn't already exist\n ...(!bookMarks.includes(id) ? [id] : []), // Spread in id only if it doesn't already exist\n ];\n setSortConfig({ ...sortConfig, bookMarks: updatedBookMarks });\n window.localStorage.setItem('book-mark', JSON.stringify(updatedBookMarks));\n };\n\n useEffect(() => {\n const params = new URLSearchParams(window.location.search);\n const URLsort = params.get('sort') || '';\n const URLd = params.get('d') || '';\n requestSort(URLsort, URLd);\n setSortConfig({\n ...sortConfig,\n key: URLsort,\n direction: URLd,\n bookMarks: bookMarkList,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, []);\n\n return { items: sortedItems, requestSort, requestSearch, requestBookMark };\n};\n\nuseSortable.defaultProps = {\n config: {\n bookMarks: [],\n key: '',\n direction: '',\n search: '',\n value: '',\n },\n};\n\nmodule.exports = useSortable;\n\nmodule.exports.default = useSortable;\n"],"names":["validateInitialValue","initialValue","Array","isArray","console","log","useSortable","items","config","bookMarks","key","direction","search","value","requestSort","sortConfig","params","URLSearchParams","window","location","set","toString","URL","indexOf","pathname","history","replaceState","setSortConfig","validatedInitialValue","_a","useState","bookMarkList","JSON","parse","localStorage","getItem","sortedItems","useMemo","sortableItems","sort","a","b","filter","item","toLowerCase","includes","forEach","bookMark","x","y","id","useEffect","URLsort","get","URLd","requestSearch","requestBookMark","updatedBookMarks","el","setItem","stringify","defaultProps","module","exports","default"],"mappings":"8qBAcO,IAAMA,qBAAuB,SAACC,GAkBnC,MAhB0B,iBAAjBA,GACU,OAAjBA,GACCC,MAAMC,QAAQF,KAEfG,QAAQC,IACN,sGAEFJ,iBAAmBA,IAEhBC,MAAMC,QAAQF,KACjBG,QAAQC,IACN,gGAEFJ,EAAe,IAGVA,GCmDIK,YAAc,SACzBC,EACAC,gBAAAA,GACEC,UAAW,GACXC,IAAK,GACLC,UAAW,GACXC,OAAQ,GACRC,MAAO,KA+DW,SAAdC,EAAeJ,EAAaC,GAM9BA,EAJAI,GACAA,EAAWL,MAAQA,GACM,cAAzBK,EAAWJ,UAEC,aACFA,GACE,YAEd,IAAMK,EAAS,IAAIC,gBAAgBC,OAAOC,SAASP,QACnDI,EAAOI,IAAI,OAAQV,EAAIW,YACvBL,EAAOI,IAAI,IAAKT,GAChB,IAAMW,EACgC,EAApCN,EAAOK,WAAWE,QAAQ,QACtB,GAAGL,OAAOC,SAASK,SAChBN,OAAOC,SAASK,aAAYR,EAAOK,WAC5CH,OAAOO,QAAQC,aAAa,GAAI,GAAIJ,GACpCK,uBACKZ,IACHL,IAAKA,EAAIW,YAAcX,EAAIW,WAC3BV,eAjFJ,IAAMiB,EAAwB5B,qBAAqBO,GAE7CsB,EAA8B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