UNPKG

zim-fuzzysearch

Version:

Client side fuzzy search combined with seperate configurable result highlighting.

64 lines (63 loc) 2.1 kB
import React from "react"; import Fuse from "fuse.js"; /** * Exposes * @param data custom data to be "full text search enabled". * @param options fuse configuration object. Set which properties should be searchable. * @returns Object: * 1. fuseResult - state of fuse result. Set via doFuseSearch method. * 2. doFuseSearch - method to search given string in configured data structure * 3. groupBy - utility function to group result values. */ export var useFuse = function (options, data) { var _a = React.useState(null), fuseResult = _a[0], setFuseResult = _a[1]; /** * Memoizes the return value and recalculates only if list or options * changes. */ var fuse = React.useMemo(function () { if (!data) return; return new Fuse(data, options); }, [data, options]); /** * Method to init the search from fuse.js * @param search string to be searched */ var doFuseSearch = function (search, reducer, options) { if (!fuse) return; var result = fuse.search(search, options); if (reducer) { var reduced = reducer(result); setFuseResult(reduced); return reduced; } else { setFuseResult(result); return result; } }; /** * Utility function to regroup given object according to given prop name. * @param objectArray Array of arbitrary objects. * @param propName property on which should be regrouped. */ var groupBy = function (objectArray, propName) { return objectArray.reduce(function (acc, obj) { var key = obj[propName]; if (!acc[key]) { acc[key] = []; } acc[key].push(obj); return acc; }, {}); }; return { fuseResult: fuseResult, doFuseSearch: doFuseSearch, groupBy: groupBy, fuse: fuse, resetFuse: function () { return setFuseResult(null); } }; };