├── .eslintignore ├── .eslintrc.json ├── .gitignore ├── .size-limit.js ├── .size-snapshot.json ├── .travis.yml ├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── LICENSE.md ├── README.md ├── index.js ├── jest.config.js ├── lint-staged.config.js ├── package.json ├── prettier.config.js ├── rollup.config.js ├── src ├── FilterResults.tsx ├── InputFilter.tsx ├── behaviorStore.ts └── index.ts ├── test ├── FilterResults.test.tsx ├── InputFilter.test.tsx ├── __snapshots__ │ └── InputFilter.test.tsx.snap ├── behaviorStore.test.ts ├── index.test.tsx └── types.test.tsx ├── tsconfig.base.json ├── tsconfig.json └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": [ 3 | "plugin:@typescript-eslint/recommended", 4 | "plugin:react/recommended", 5 | "prettier", 6 | "prettier/@typescript-eslint" 7 | ], 8 | "parser": "@typescript-eslint/parser", 9 | "parserOptions": { 10 | "ecmaFeatures": { 11 | "jsx": true 12 | }, 13 | "useJSXTextNode": true, 14 | "project": "./tsconfig.json" 15 | }, 16 | "plugins": ["@typescript-eslint", "react-hooks"], 17 | "rules": { 18 | "react-hooks/rules-of-hooks": "error", 19 | "react-hooks/exhaustive-deps": "warn", 20 | "@typescript-eslint/array-type": ["error", "array-simple"], 21 | "@typescript-eslint/no-unused-vars": [ 22 | "error", 23 | { 24 | "argsIgnorePattern": "^_", 25 | "caughtErrorsIgnorePattern": "^_" 26 | } 27 | ], 28 | "@typescript-eslint/explicit-function-return-type": "off" 29 | }, 30 | "settings": { 31 | "react": { 32 | "version": "detect" 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | npm-debug.log 3 | .DS_Store 4 | dist 5 | compiled 6 | -------------------------------------------------------------------------------- /.size-limit.js: -------------------------------------------------------------------------------- 1 | module.exports = [ 2 | { 3 | path: "./dist/react-fuzzy-filter.esm.js", 4 | limit: "5 kB", 5 | }, 6 | { 7 | path: "./dist/react-fuzzy-filter.umd.production.js", 8 | limit: "5 kB", 9 | }, 10 | ]; 11 | -------------------------------------------------------------------------------- /.size-snapshot.json: -------------------------------------------------------------------------------- 1 | { 2 | "./dist/react-fuzzy-filter.umd.production.js": { 3 | "bundled": 20556, 4 | "minified": 13997, 5 | "gzipped": 5019 6 | }, 7 | "./dist/react-fuzzy-filter.umd.development.js": { 8 | "bundled": 20556, 9 | "minified": 13997, 10 | "gzipped": 5019 11 | }, 12 | "./dist/react-fuzzy-filter.cjs.production.js": { 13 | "bundled": 4771, 14 | "minified": 2270, 15 | "gzipped": 937 16 | }, 17 | "./dist/react-fuzzy-filter.cjs.development.js": { 18 | "bundled": 4771, 19 | "minified": 2270, 20 | "gzipped": 937 21 | }, 22 | "dist/react-fuzzy-filter.esm.js": { 23 | "bundled": 4129, 24 | "minified": 2068, 25 | "gzipped": 876, 26 | "treeshaked": { 27 | "rollup": { 28 | "code": 179, 29 | "import_statements": 75 30 | }, 31 | "webpack": { 32 | "code": 1295 33 | } 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | script: npm run $TEST_SUITE 3 | sudo: false 4 | cache: 5 | directories: 6 | - node_modules 7 | node_js: 8 | - 10 9 | env: 10 | matrix: 11 | - TEST_SUITE=lint 12 | - TEST_SUITE=test 13 | - TEST_SUITE=size-limit 14 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## 5.0.1 (2019-4-1) 4 | 5 | Fixed: 6 | 7 | - Removed arrow functions from UMD builds to support older browsers. Thanks @rburak for contributing! 8 | 9 | ## 5.0.0 (2019-3-16) 10 | 11 | Changed: 12 | 13 | - Using react hooks internally. **Breaking:** React peer dependency is now 16.8.0 14 | - 4.x.x branch will continue to release patches, etc. for older versions of React 15 | - Smaller bundle! 16 | 17 | ## 4.3.0 (2019-2-22) 18 | 19 | Added: 20 | 21 | Add typescript definitions and rewrite library with typescript. 22 | 23 | ## 4.2.1 (2019-2-14) 24 | 25 | Fixed: 26 | 27 | - An internal bug was preventing subscriptions from unsubscribing due to `behaviorStore` not returning the unsubscribe function. This bug was introduced in `4.2.0`. Thanks @quietshu for the fix! 28 | 29 | ## 4.2.0 (2019-1-21) 30 | 31 | Improved: 32 | 33 | - Wrapped `valoo` store to store current value so that subscribers can replay the latest event (and have the current state) regardless of component render order. This will also help with async react. 34 | 35 | ## 4.1.0 (2019-1-15) 36 | 37 | Added: 38 | 39 | - `changeInputValue` function is now a named export from the library. This will trigger changing the `InputFilter` input value as well as affect the rendered `FilterResults`. eg. `changeInputValue("new input")` 40 | 41 | ## 4.0.0 (2018-7-24) 42 | 43 | Changed: 44 | 45 | - Use [valoo](https://www.npmjs.com/package/valoo) instead of [rxjs](https://github.com/ReactiveX/rxjs) for state management. 46 | 47 | ## 3.2.0 (2017-5-30) 48 | 49 | Added: 50 | 51 | - Added support for React ^15.5 by using `prop-types` package and prepares for deprecation of PropTypes from React. 52 | 53 | ## 3.1.0 (2017-5-23) 54 | 55 | Added: 56 | 57 | - Allow updating `initialSearch` prop. This provides an escape hook in situations where the `initialSearch` might not be known until right after the first render. 58 | 59 | ## 3.0.0 (2017-4-10) 60 | 61 | Changed: 62 | 63 | - Updated API to remove props and simplify usage. `FilterResults` now expects a function as a child, which receives the matching items as an argument. This provides more flexibility without needing to pass "configuration props". 64 | 65 | Removed: 66 | 67 | - Removed the following props in the API change: `classPrefix`, `wrapper`, `wrapperProps`, and `renderContainer`. 68 | 69 | ## 2.3.0 (2016-8-26) 70 | 71 | Added: 72 | 73 | - Added `debounceTime` prop to `InputFilter`. This specifies the time in milliseconds to debounce the `onChange` event on the input field. [196de58](../../commit/196de58) 74 | 75 | ## 2.2.0 (2016-8-26) 76 | 77 | Added: 78 | 79 | - Added `prefilters` prop to `FilterResults`. Enables prefiltering the items on matching regular expressions. The return of the callback is the list of items to fuzzy search on. This enables "commands" that toggle state or change what is being fuzzy searched on. [bb7d688](../../commit/bb7d688) 80 | 81 | ## 2.1.0 (2016-8-3) 82 | 83 | Added: 84 | 85 | - `renderContainer` callback function on `FilterResults` receives a second argument with the raw filtered items. [commit](../../commit/4f7552f) 86 | 87 | ## 2.0.0 (2016-8-2) 88 | 89 | Changed: 90 | 91 | - Removed `initialSearch` prop from `FilterResults`. It now syncs with `initialSearch` prop from `InputFilter`. [commit](../../commit/eb200b5) 92 | - `onChange` callback for `InputFilter` now can optionally return a string (instead of a boolean). The string overrides the search value passed to `FilterResults`. [commit](../../commit/eb200b5) 93 | 94 | ## 1.1.0 (2016-8-1) 95 | 96 | Added: 97 | 98 | - Optional prop, `renderContainer` added to `FilterResults` component. This is an alternative to using `wrapper`/`wrapperProps` and provides more fine grained control over what is ultimately rendered from `FilterResults`. [commit](../../commit/b2d5866) 99 | 100 | ## 1.0.0 (2016-7-29) 101 | 102 | Initial release 103 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Code of Conduct 2 | 3 | As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 4 | 5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality. 6 | 7 | Examples of unacceptable behavior by participants include: 8 | 9 | * The use of sexualized language or imagery 10 | * Personal attacks 11 | * Trolling or insulting/derogatory comments 12 | * Public or private harassment 13 | * Publishing other's private information, such as physical or electronic 14 | addresses, without explicit permission 15 | * Other unethical or unprofessional conduct 16 | 17 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 18 | 19 | By adopting this Code of Conduct, project maintainers commit themselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team. 20 | 21 | This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. 22 | 23 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 24 | 25 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.3.0, available at [http://contributor-covenant.org/version/1/3/0/][version] 26 | 27 | [homepage]: http://contributor-covenant.org 28 | [version]: http://contributor-covenant.org/version/1/3/0/ 29 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2019 Jonathan Lehman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![npm version](https://img.shields.io/npm/v/react-fuzzy-filter.svg?style=for-the-badge)](https://yarnpkg.com/en/package/react-fuzzy-filter) [![Build Status](https://img.shields.io/badge/ci-travis-green.svg?style=for-the-badge)](https://travis-ci.org/jdlehman/react-fuzzy-filter) [![License](https://img.shields.io/badge/license-mit-red.svg?style=for-the-badge)](LICENSE.md) 2 | 3 | # react-fuzzy-filter 4 | 5 | Fuzzy filter a list of data based on the search value typed in the input field. The list of matching items is made available as an argument to the FilterResults component's child function. 6 | 7 | ReactFuzzyFilter is powered by [`fuse.js`](https://github.com/krisk/Fuse). 8 | 9 | ## Installation 10 | 11 | **npm** 12 | 13 | ```sh 14 | npm install -S react-fuzzy-filter 15 | ``` 16 | 17 | **yarn** 18 | 19 | ```sh 20 | yarn add react-fuzzy-filter 21 | ``` 22 | 23 | ## Example Usage 24 | 25 | The default export of ReactFuzzyFilter is a factory function that returns two components, `InputFilter` and `FilterResults`. `FilterResults` receives the data typed into the `InputFilter` and uses it to fuzzy filter matches in its items. Each item is then rendered via a custom render function. Each invocation of the factory function creates two new "linked" components that can be used anywhere. The components do not need to live in the same component or part of the page. 26 | 27 | ```js 28 | import React, { Component } from "react"; 29 | import fuzzyFilterFactory, { onChangeInputValue } from "react-fuzzy-filter"; 30 | 31 | // these components share state and can even live in different components 32 | const { InputFilter, FilterResults, changeInputValue } = fuzzyFilterFactory(); 33 | 34 | class MyComponent extends Component { 35 | render() { 36 | const items = [ 37 | { name: "first", meta: "first|123", tag: "a" }, 38 | { name: "second", meta: "second|443", tag: "b" }, 39 | { name: "third", meta: "third|623", tag: "a" }, 40 | ]; 41 | const fuseConfig = { 42 | keys: ["meta", "tag"], 43 | }; 44 | const setInputText = () => onChangeInputValue("hello"); 45 | return ( 46 |
47 | 48 |
Any amount of content between
49 | 50 | 51 | {filteredItems => { 52 | return ( 53 |
54 | {filteredItems.map(item => ( 55 |
{item.name}
56 | ))} 57 |
58 | ); 59 | }} 60 |
61 |
62 | ); 63 | } 64 | } 65 | ``` 66 | 67 | ## changeInputValue 68 | 69 | A function that will change the value in the input (outside of user updating `InputFilter` text). This is useful to trigger input value changes eg. a button that resets the `InputFilter` state when clicked. 70 | 71 | ```js 72 | // eg. 73 | changeInputValue("new value"); 74 | ``` 75 | 76 | ## Components 77 | 78 | # InputFilter 79 | 80 | An input field that controls the state used to render the items in `FilterResults`. 81 | 82 | ## Props 83 | 84 | ### classPrefix 85 | 86 | `classPrefix` is a string that is used to prefix the class names in the component. It defaults to `react-fuzzy-filter`. (`react-fuzzy-filter__input`) 87 | 88 | ### initialSearch 89 | 90 | `initialSearch` is an optional string that can override the initial search state when the component is created. Updating this value will also update the input value, meaning it is possible to provide the `initialSearch` from a value that is either async or not known until moments after the first render. 91 | 92 | ### inputProps 93 | 94 | `inputProps` is an object containing additional props to be passed to the input field. 95 | 96 | ### onChange 97 | 98 | `onChange` is an optional callback function that is called BEFORE the value in the input field changes via an `onchange` event. It should return a string, which will then be passed directly to `FilterResults`. This can be used to filter out special inputs (eg: `author:jdlehman`) from fuzzy searching. These special inputs could then be used to change the `items` being passed to `FilterResults`. 99 | 100 | ### debounceTime 101 | 102 | `debounceTime` is an optional number that denotes the time in milliseconds to debounce the `onChange` event on the input field. It defaults to 0. 103 | 104 | # FilterResults 105 | 106 | Collection of fuzzy filtered items (filtered by the `InputFilter`'s value), each being rendered by the custom render function (`children` prop). 107 | 108 | ## Props 109 | 110 | ### fuseConfig 111 | 112 | `fuseConfig` is an object that specifies configuration for [`fuse.js`](https://github.com/krisk/Fuse), the library that is doing the fuzzy searching. The only required key in this object is `keys`, which is an array that specifies the key(s), in the objects to use for comparison. Check out all of the configuration [options](https://github.com/krisk/Fuse#options). 113 | 114 | ### items 115 | 116 | `items` is an array of the objects to be rendered. It defaults to an empty array. 117 | 118 | ### defaultAllItems 119 | 120 | `defaultAllItems` is a boolean that determines whether all items should be shown if the search value is empty. It defaults to true (meaning all items are shown by default). 121 | 122 | ### prefilters 123 | 124 | `prefilters` is an optional array of objects defining how to prefilter the items before they are handed off for fuzzy searching. Each object must have a `regex` key with a regular expression and a `handler` key with a callback function. Each regex match for a prefilter, will cause the corresponding handler to be called. The handler function receives the match as a string, the array of items (might be a subset if another prefilter has already happened), and the Fuse constructor function. The handler must return an array of items (probably a subset of what was passed in). 125 | 126 | It is important to note that each match is stripped out of the search string that will be passed to the final fuzzy filtering with Fuse (after all matching prefilters have been run). This enables "commands" or special keywords to be used to filter the items, but not be used in the fuzzy search itself. Example: `author:jdlehman` might filter all the items that are authored by `jdlehman`, but the string `author:jdlehman` is not used to fuzzy search the filtered items. So a search with `author:jdlehman mySearch` could filter out all items that are not authored by `jdlehman` and then fuzzy search the remaining items with just `mySearch`. 127 | 128 | The author prefilter described above might look like the following: 129 | 130 | ```js 131 | const prefilters = [ 132 | { 133 | regex: /author:\S+/g, 134 | handler: (match, items, Fuse) => { 135 | const name = match.split(":")[1]; 136 | return items.filter(item => item.author === name); 137 | }, 138 | }, 139 | ]; 140 | ``` 141 | 142 | We could also define a prefilter to fuzzy search on a different key then our default Fuse config. Example: `name:Bob` would fuzzy filter for `Bob` on the `name` key. 143 | 144 | ```js 145 | const prefilters = [ 146 | { 147 | regex: /\S+:\S+/g, 148 | handler: (match, items, Fuse) => { 149 | const [key, value] = match.split(":"); 150 | const fuse = new Fuse(items, { keys: [key] }); 151 | return fuse.search(value); 152 | }, 153 | }, 154 | ]; 155 | ``` 156 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | if (process.env.NODE_ENV === "production") { 4 | module.exports = require("./react-fuzzy-filter.cjs.production.js"); 5 | } else { 6 | module.exports = require("./react-fuzzy-filter.cjs.development.js"); 7 | } 8 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | collectCoverageFrom: ["src/**/*.{ts,tsx}"], 3 | transform: { 4 | ".(ts|tsx)": "ts-jest", 5 | }, 6 | testMatch: ["/test/**/?(*.)test.ts?(x)"], 7 | transformIgnorePatterns: ["[/\\\\]node_modules[/\\\\].+\\.(js|jsx)$"], 8 | moduleFileExtensions: ["ts", "tsx", "js", "json"], 9 | }; 10 | -------------------------------------------------------------------------------- /lint-staged.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | "**/*.{ts,tsx}": ["prettier --write", "git add"], 3 | }; 4 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-fuzzy-filter", 3 | "version": "5.0.1", 4 | "description": "Render a subset of a collection with fuzzy searching", 5 | "main": "dist/index.js", 6 | "module": "dist/react-fuzzy-filter.esm.js", 7 | "typings": "dist/index.d.ts", 8 | "scripts": { 9 | "build": "cross-env NODE_ENV=production tsc -p tsconfig.base.json && rollup -c && rimraf compiled && cp-cli ./index.js ./dist/index.js", 10 | "lint:src": "$(yarn bin)/eslint --ext .js,.json,.ts,.tsx src", 11 | "lint:test": "$(yarn bin)/eslint --ext .js,.json,.ts,.tsx test", 12 | "lint": "yarn run lint:src && yarn run lint:test", 13 | "size-limit": "$(yarn bin)/size-limit", 14 | "test": "$(yarn bin)/jest", 15 | "prebuild": "rimraf dist", 16 | "prepublish": "yarn run build" 17 | }, 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/jdlehman/react-fuzzy-filter.git" 21 | }, 22 | "bugs": { 23 | "url": "https://github.com/jdlehman/react-fuzzy-filter/issues" 24 | }, 25 | "keywords": ["react", "react-component", "filter", "fuzzy", "javascript"], 26 | "files": ["dist"], 27 | "author": "Jonathan Lehman ", 28 | "license": "MIT", 29 | "devDependencies": { 30 | "@babel/core": "^7.2.2", 31 | "@babel/types": "^7.3.2", 32 | "@types/debounce": "^1.2.0", 33 | "@types/jest": "^24.0.6", 34 | "@types/react": "^16.8.5", 35 | "@types/react-dom": "^16.8.2", 36 | "@typescript-eslint/eslint-plugin": "^1.4.2", 37 | "babel-core": "^6.26.0", 38 | "babel-plugin-annotate-pure-calls": "^0.4.0", 39 | "babel-plugin-dev-expression": "^0.2.1", 40 | "cp-cli": "^2.0.0", 41 | "cross-env": "^5.2.0", 42 | "eslint": "^5.15.1", 43 | "eslint-config-prettier": "^4.1.0", 44 | "eslint-plugin-react": "^7.12.4", 45 | "eslint-plugin-react-hooks": "^1.5.0", 46 | "husky": "^1.3.1", 47 | "jest": "^24.1.0", 48 | "jsdom": "^14.0.0", 49 | "jsdom-global": "^3.0.2", 50 | "lint-staged": "^8.1.3", 51 | "prettier": "^1.16.4", 52 | "react": "^16.8.3", 53 | "react-dom": "^16.8.3", 54 | "react-test-renderer": "^16.8.3", 55 | "react-testing-library": "^6.0.0", 56 | "rimraf": "^2.6.3", 57 | "rollup": "^1.1.2", 58 | "rollup-plugin-babel": "^4.3.2", 59 | "rollup-plugin-commonjs": "^9.2.0", 60 | "rollup-plugin-node-resolve": "^4.0.0", 61 | "rollup-plugin-replace": "^2.1.0", 62 | "rollup-plugin-size-snapshot": "^0.8.0", 63 | "rollup-plugin-sourcemaps": "^0.4.2", 64 | "rollup-plugin-terser": "^4.0.2", 65 | "size-limit": "^1.3.3", 66 | "ts-jest": "^24.0.0", 67 | "typescript": "^3.3.1" 68 | }, 69 | "peerDependencies": { 70 | "react": "^16.8.0" 71 | }, 72 | "resolutions": { 73 | "handlebars": ">=4.1.2", 74 | "lodash": ">=4.17.13" 75 | }, 76 | "dependencies": { 77 | "debounce": "^1.0.2", 78 | "fuse.js": "^3.1.0", 79 | "tslib": "^1.9.3", 80 | "valoo": "^2.1.0" 81 | }, 82 | "husky": { 83 | "hooks": { 84 | "pre-commit": "lint-staged" 85 | } 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /prettier.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | trailingComma: "es5", 3 | parser: "typescript", 4 | }; 5 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | // adapted from formik: https://github.com/jaredpalmer/formik/blob/master/rollup.config.js 2 | import commonjs from "rollup-plugin-commonjs"; 3 | import replace from "rollup-plugin-replace"; 4 | import resolve from "rollup-plugin-node-resolve"; 5 | import sourceMaps from "rollup-plugin-sourcemaps"; 6 | import babel from "rollup-plugin-babel"; 7 | import { terser } from "rollup-plugin-terser"; 8 | import { sizeSnapshot } from "rollup-plugin-size-snapshot"; 9 | import pkg from "./package.json"; 10 | 11 | const input = "./compiled/index.js"; 12 | const external = id => !id.startsWith(".") && !id.startsWith("/"); 13 | const babelOptions = { 14 | exclude: /node_modules/, 15 | plugins: ["annotate-pure-calls", "dev-expression"], 16 | }; 17 | 18 | const rollupAlias = aliases => ({ 19 | resolveId(importee) { 20 | const alias = aliases[importee]; 21 | return alias ? this.resolveId(alias) : null; 22 | } 23 | }); 24 | 25 | const buildUmd = ({ env }) => ({ 26 | input, 27 | external: ["react", "react-native"], 28 | output: { 29 | name: "ReactFuzzyFilter", 30 | format: "umd", 31 | sourcemap: true, 32 | file: `./dist/react-fuzzy-filter.umd.${env}.js`, 33 | exports: "named", 34 | globals: { 35 | react: "React", 36 | "react-native": "ReactNative", 37 | }, 38 | }, 39 | 40 | plugins: [ 41 | rollupAlias({ 42 | valoo: 'valoo/dist/valoo' 43 | }), 44 | resolve(), 45 | babel(babelOptions), 46 | replace({ 47 | "process.env.NODE_ENV": JSON.stringify(env), 48 | }), 49 | commonjs({ 50 | include: /node_modules/, 51 | namedExports: { 52 | "node_modules/prop-types/index.js": [ 53 | "object", 54 | "oneOfType", 55 | "string", 56 | "node", 57 | "func", 58 | "bool", 59 | "element", 60 | ], 61 | }, 62 | }), 63 | sourceMaps(), 64 | sizeSnapshot(), 65 | env === "production" && 66 | terser({ 67 | sourcemap: true, 68 | output: { comments: false }, 69 | compress: { 70 | keep_infinity: true, 71 | pure_getters: true, 72 | }, 73 | warnings: true, 74 | ecma: 5, 75 | toplevel: false, 76 | }), 77 | ], 78 | }); 79 | 80 | const buildCjs = ({ env }) => ({ 81 | input, 82 | external, 83 | output: { 84 | file: `./dist/${pkg.name}.cjs.${env}.js`, 85 | format: "cjs", 86 | sourcemap: true, 87 | }, 88 | plugins: [ 89 | resolve(), 90 | replace({ 91 | "process.env.NODE_ENV": JSON.stringify(env), 92 | }), 93 | sourceMaps(), 94 | sizeSnapshot(), 95 | env === "production" && 96 | terser({ 97 | sourcemap: true, 98 | output: { comments: false }, 99 | compress: { 100 | keep_infinity: true, 101 | pure_getters: true, 102 | }, 103 | warnings: true, 104 | ecma: 5, 105 | // Compress and/or mangle variables in top level scope. 106 | // @see https://github.com/terser-js/terser 107 | toplevel: true, 108 | }), 109 | ], 110 | }); 111 | 112 | export default [ 113 | buildUmd({ env: "production" }), 114 | buildUmd({ env: "development" }), 115 | buildCjs({ env: "production" }), 116 | buildCjs({ env: "development" }), 117 | { 118 | input, 119 | external, 120 | output: [ 121 | { 122 | file: pkg.module, 123 | format: "esm", 124 | sourcemap: true, 125 | }, 126 | ], 127 | plugins: [resolve(), babel(babelOptions), sizeSnapshot(), sourceMaps()], 128 | }, 129 | ]; 130 | -------------------------------------------------------------------------------- /src/FilterResults.tsx: -------------------------------------------------------------------------------- 1 | import Fuse, { FuseOptions } from "fuse.js"; 2 | import React, { Fragment, useEffect, useState } from "react"; 3 | import { Emitter, Event } from "./behaviorStore"; 4 | 5 | export type PreFilterHandler = ( 6 | match: string, 7 | items: T[], 8 | fuse: typeof Fuse 9 | ) => T[]; 10 | 11 | export interface PreFilter { 12 | regex: RegExp; 13 | handler: PreFilterHandler; 14 | } 15 | export interface FilterResultsProps { 16 | children: (items: T[]) => React.ReactNode; 17 | items: T[]; 18 | defaultAllItems?: boolean; 19 | fuseConfig: FuseOptions; 20 | prefilters?: Array>; 21 | } 22 | 23 | export type FilterResults = React.FunctionComponent>; 24 | 25 | export default function filterResultsFactory( 26 | store: Emitter 27 | ): FilterResults { 28 | const Results: FilterResults = (props: FilterResultsProps) => { 29 | const [searchVal, setSearch] = useState(""); 30 | 31 | useEffect(() => { 32 | const unsubscribe = store.on(({ v }) => { 33 | setSearch(v); 34 | }); 35 | return unsubscribe; 36 | }, []); 37 | 38 | const prefilterItems = (s: string): { items: T[]; search: string } => { 39 | let items = props.items; 40 | (props.prefilters || []).forEach(({ regex, handler }) => { 41 | const matches = s.match(regex) || []; 42 | s = s.replace(regex, "").trim(); 43 | matches.forEach(match => { 44 | items = handler(match, items, Fuse); 45 | }); 46 | }); 47 | return { items, search: s }; 48 | }; 49 | 50 | const filterItems = (s: string): T[] => { 51 | const { items, search } = prefilterItems(s || ""); 52 | if (search.trim() === "") { 53 | return props.defaultAllItems ? items : []; 54 | } else { 55 | const fuse = new Fuse(items, props.fuseConfig); 56 | return fuse.search(search); 57 | } 58 | }; 59 | 60 | const filteredItems = filterItems(searchVal); 61 | // wrap with Fragment to fix type issue 62 | return {props.children(filteredItems)}; 63 | }; 64 | Results.displayName = "FilterResults"; 65 | Results.defaultProps = { 66 | defaultAllItems: true, 67 | prefilters: [], 68 | }; 69 | 70 | return Results; 71 | } 72 | -------------------------------------------------------------------------------- /src/InputFilter.tsx: -------------------------------------------------------------------------------- 1 | import debounce from "debounce"; 2 | import React, { useCallback, useEffect, useState } from "react"; 3 | import { Emitter, Event, EventType } from "./behaviorStore"; 4 | 5 | export interface InputFilterProps { 6 | classPrefix?: string; 7 | initialSearch?: string; 8 | inputProps?: React.InputHTMLAttributes; 9 | onChange?: (value: string) => string; 10 | debounceTime?: number; 11 | } 12 | 13 | export type InputFilter = React.ComponentType; 14 | const defaultProps = { 15 | classPrefix: "react-fuzzy-filter", 16 | debounceTime: 0, 17 | inputProps: {}, 18 | onChange: (value: string) => value, 19 | }; 20 | 21 | export default function inputFilterFactory(store: Emitter): InputFilter { 22 | function updateValue(value: string, onChange: (value: string) => string) { 23 | const overrideValue = onChange(value); 24 | store({ t: EventType.Input, v: overrideValue }); 25 | } 26 | 27 | const Input: React.FunctionComponent = ( 28 | props: InputFilterProps 29 | ) => { 30 | const initialSearch = props.initialSearch || ""; 31 | const onChange = props.onChange || defaultProps.onChange; 32 | const debounceTime = props.debounceTime || defaultProps.debounceTime; 33 | 34 | const [inputValue, setValue] = useState(initialSearch); 35 | const debouncedUpdate = useCallback(debounce(updateValue, debounceTime), [ 36 | debounceTime, 37 | ]); 38 | 39 | useEffect(() => { 40 | const unsubscribe = store.on(({ v, t }) => { 41 | if (t === EventType.External) { 42 | setValue(v); 43 | } 44 | }); 45 | return unsubscribe; 46 | }, []); 47 | 48 | useEffect(() => { 49 | updateValue(initialSearch, onChange); 50 | }, [initialSearch, onChange]); 51 | 52 | const handleChange = ({ 53 | target: { value }, 54 | }: React.ChangeEvent) => { 55 | setValue(value); 56 | if (debounceTime) { 57 | debouncedUpdate(value, onChange); 58 | } else { 59 | updateValue(value, onChange); 60 | } 61 | }; 62 | 63 | return ( 64 | 70 | ); 71 | }; 72 | 73 | Input.displayName = "InputFilter"; 74 | Input.defaultProps = defaultProps; 75 | 76 | return Input; 77 | } 78 | -------------------------------------------------------------------------------- /src/behaviorStore.ts: -------------------------------------------------------------------------------- 1 | import valoo from "valoo"; 2 | 3 | export interface Emitter { 4 | (value: T): void; 5 | on: (fn: (value: T) => void) => valoo.Disposer; 6 | } 7 | 8 | export type Disposer = valoo.Disposer; 9 | 10 | export enum EventType { 11 | Initial = 0, 12 | Input, 13 | External, 14 | } 15 | 16 | export interface Event { 17 | t: EventType; // type 18 | v: string; // value 19 | } 20 | 21 | // emulates BehaviorSubject from rxjs 22 | // (stores current state) and replays it on subscribe 23 | export default function behaviorStore(initialValue: T): Emitter { 24 | const store: valoo.Observable = valoo(initialValue); 25 | let currentState = initialValue; 26 | // save currentState before emitting 27 | const emit = function(value: T) { 28 | currentState = value; 29 | store(value); 30 | } as Emitter; 31 | 32 | // emit currentState on subscribe 33 | // then use default valoo behavior 34 | emit.on = function(fn: (value: T) => void): valoo.Disposer { 35 | fn(currentState); 36 | return store.on(fn); 37 | }; 38 | return emit; 39 | } 40 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import behaviorStore, { Emitter, Event, EventType } from "./behaviorStore"; 2 | import filterResultsFactory from "./FilterResults"; 3 | import inputFilterFactory from "./InputFilter"; 4 | 5 | export { 6 | FilterResults, 7 | FilterResultsProps, 8 | PreFilter, 9 | PreFilterHandler, 10 | } from "./FilterResults"; 11 | export { FuseOptions, FuseResult } from "fuse.js"; 12 | export { InputFilter, InputFilterProps } from "./InputFilter"; 13 | 14 | export default function fuzzyFilterFactory() { 15 | const store: Emitter = behaviorStore({ 16 | t: EventType.Initial, 17 | v: "", 18 | }); 19 | return { 20 | FilterResults: filterResultsFactory(store), 21 | InputFilter: inputFilterFactory(store), 22 | changeInputValue: (value: string) => { 23 | store({ 24 | t: EventType.External, 25 | v: typeof value !== "string" ? "" : value, 26 | }); 27 | }, 28 | }; 29 | } 30 | -------------------------------------------------------------------------------- /test/FilterResults.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { act } from "react-dom/test-utils"; 3 | import { render } from "react-testing-library"; 4 | import behaviorStore, { EventType } from "../src/behaviorStore"; 5 | import filterResultsFactory, { 6 | FilterResults, 7 | PreFilter, 8 | } from "../src/FilterResults"; 9 | import { FuseOptions } from "../src"; 10 | 11 | const filteredResultsSpy = jest.fn().mockImplementation(() =>
); 12 | 13 | interface TestItem { 14 | name: string; 15 | searchData: string; 16 | state: string; 17 | } 18 | 19 | const items: TestItem[] = [ 20 | { name: "one", searchData: "hello", state: "archived" }, 21 | { name: "two", searchData: "hello", state: "" }, 22 | { name: "three", searchData: "goodbye", state: "archived" }, 23 | { name: "four", searchData: "bonjour", state: "enabled" }, 24 | ]; 25 | 26 | const defaultFuseConfig: FuseOptions = { 27 | keys: ["searchData"], 28 | }; 29 | 30 | describe("FilterResults", () => { 31 | let Results: FilterResults; 32 | const store = behaviorStore({ t: EventType.Initial, v: "" }); 33 | beforeEach(() => { 34 | Results = filterResultsFactory(store); 35 | filteredResultsSpy.mockClear(); 36 | }); 37 | 38 | describe("#render", () => { 39 | it("passes filtered items to child function", () => { 40 | render( 41 | 42 | {filteredResultsSpy} 43 | 44 | ); 45 | expect(filteredResultsSpy).lastCalledWith(items); 46 | }); 47 | 48 | it("renders no items with empty search if defaultAllItems is false", () => { 49 | render( 50 | 55 | {filteredResultsSpy} 56 | 57 | ); 58 | expect(filteredResultsSpy).lastCalledWith([]); 59 | }); 60 | }); 61 | 62 | describe("#renderItems", () => { 63 | it("fuzzy filters items by search state", () => { 64 | render( 65 | 66 | {filteredResultsSpy} 67 | 68 | ); 69 | act(() => store({ t: EventType.Initial, v: "hllo" })); 70 | expect(filteredResultsSpy).lastCalledWith([ 71 | { name: "one", searchData: "hello", state: "archived" }, 72 | { name: "two", searchData: "hello", state: "" }, 73 | ]); 74 | 75 | act(() => store({ t: EventType.Initial, v: "godby" })); 76 | expect(filteredResultsSpy).lastCalledWith([ 77 | { name: "three", searchData: "goodbye", state: "archived" }, 78 | ]); 79 | }); 80 | 81 | it("accepts fuse config", () => { 82 | const fuseConfig: FuseOptions = { 83 | id: "name", 84 | keys: ["name"], 85 | }; 86 | render( 87 | 88 | {filteredResultsSpy} 89 | 90 | ); 91 | act(() => store({ t: EventType.Initial, v: "hllo" })); 92 | expect(filteredResultsSpy).lastCalledWith([]); 93 | 94 | act(() => store({ t: EventType.Initial, v: "ree" })); 95 | expect(filteredResultsSpy).lastCalledWith(["three"]); 96 | }); 97 | 98 | it("supports prefilters", () => { 99 | const prefilters: Array> = [ 100 | { 101 | handler: (_filterVal, results, _Fuse) => { 102 | return results.filter(item => item.state === "archived"); 103 | }, 104 | regex: /archived/, 105 | }, 106 | { 107 | handler: (match, results, Fuse) => { 108 | const [key, value] = match.split(":"); 109 | const fuse = new Fuse(results, { keys: [key], threshold: 0.4 }); 110 | return fuse.search(value); 111 | }, 112 | regex: /\S+:\S+/g, 113 | }, 114 | ]; 115 | render( 116 | 121 | {filteredResultsSpy} 122 | 123 | ); 124 | act(() => store({ t: EventType.Initial, v: "archived" })); 125 | expect(filteredResultsSpy).lastCalledWith([ 126 | { name: "one", searchData: "hello", state: "archived" }, 127 | { name: "three", searchData: "goodbye", state: "archived" }, 128 | ]); 129 | 130 | act(() => store({ t: EventType.Initial, v: "archived hello" })); 131 | expect(filteredResultsSpy).lastCalledWith([ 132 | { name: "one", searchData: "hello", state: "archived" }, 133 | ]); 134 | 135 | act(() => store({ t: EventType.Initial, v: "name:two" })); 136 | expect(filteredResultsSpy).lastCalledWith([ 137 | { name: "two", searchData: "hello", state: "" }, 138 | ]); 139 | }); 140 | }); 141 | }); 142 | -------------------------------------------------------------------------------- /test/InputFilter.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { act } from "react-dom/test-utils"; 3 | import { fireEvent, render, wait } from "react-testing-library"; 4 | import behaviorStore, { EventType } from "../src/behaviorStore"; 5 | import inputFilterFactory, { InputFilter } from "../src/InputFilter"; 6 | 7 | describe("InputFilter", () => { 8 | let Input: InputFilter; 9 | const store = behaviorStore({ t: EventType.Initial, v: "" }); 10 | beforeEach(() => { 11 | Input = inputFilterFactory(store); 12 | }); 13 | 14 | describe("#render", () => { 15 | it("renders with defaults", () => { 16 | const utils = render(); 17 | expect(utils.container).toMatchSnapshot(); 18 | }); 19 | 20 | it("sets classPrefix", () => { 21 | const utils = render(); 22 | expect(utils.container).toMatchSnapshot(); 23 | }); 24 | 25 | it("sets inputProps", () => { 26 | const inputProps = { placeholder: "Search" }; 27 | const utils = render(); 28 | const input = utils.getByPlaceholderText("Search"); 29 | expect(input).toMatchSnapshot(); 30 | }); 31 | 32 | it("sets initialSearch", () => { 33 | const utils = render(); 34 | const input = utils.getByValue("first search"); 35 | expect(input).toMatchSnapshot(); 36 | }); 37 | }); 38 | 39 | describe("#onChange", () => { 40 | let input: Element; 41 | let spy: jest.Mock; 42 | beforeEach(() => { 43 | spy = jest.fn().mockImplementation((value: string) => value); 44 | const utils = render( 45 | 46 | ); 47 | input = utils.getByPlaceholderText("Search"); 48 | }); 49 | 50 | it("calls callback with search value", () => { 51 | jest.useFakeTimers(); 52 | fireEvent.change(input, { 53 | target: { value: "my string" }, 54 | }); 55 | act(() => { 56 | jest.runAllTimers(); 57 | }); 58 | wait(() => expect(spy).toHaveBeenCalledWith("my string")); 59 | }); 60 | 61 | it("passes the value to the store", done => { 62 | jest.useFakeTimers(); 63 | const received = ["", "some input"]; 64 | let ptr = 0; 65 | store.on(({ t, v }) => { 66 | expect(v).toEqual(received[ptr]); 67 | expect(t).toEqual(EventType.Input); 68 | ptr++; 69 | if (ptr === 2) { 70 | done(); 71 | } 72 | }); 73 | 74 | fireEvent.change(input, { 75 | target: { value: "some input" }, 76 | }); 77 | act(() => { 78 | jest.runAllTimers(); 79 | }); 80 | }); 81 | }); 82 | }); 83 | -------------------------------------------------------------------------------- /test/__snapshots__/InputFilter.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`InputFilter #render renders with defaults 1`] = ` 4 |
5 | 9 |
10 | `; 11 | 12 | exports[`InputFilter #render sets classPrefix 1`] = ` 13 |
14 | 18 |
19 | `; 20 | 21 | exports[`InputFilter #render sets initialSearch 1`] = ` 22 | 26 | `; 27 | 28 | exports[`InputFilter #render sets inputProps 1`] = ` 29 | 34 | `; 35 | -------------------------------------------------------------------------------- /test/behaviorStore.test.ts: -------------------------------------------------------------------------------- 1 | import behaviorStore from "../src/behaviorStore"; 2 | 3 | describe("behaviorStore", () => { 4 | it("emits state to subscribers", done => { 5 | const store = behaviorStore(2); 6 | const received = [2, 5, 1]; 7 | let ptr = 0; 8 | let ptr2 = 0; 9 | store.on(num => { 10 | expect(num).toEqual(received[ptr]); 11 | ptr++; 12 | }); 13 | store.on(num => { 14 | expect(num).toEqual(received[ptr2]); 15 | ptr2++; 16 | if (ptr === 3) { 17 | done(); 18 | } 19 | }); 20 | store(5); 21 | store(1); 22 | }); 23 | 24 | it("uses the current state on subscribe", done => { 25 | const store = behaviorStore(2); 26 | store(3); 27 | store(5); 28 | store.on(num => { 29 | expect(num).toEqual(5); 30 | done(); 31 | }); 32 | }); 33 | }); 34 | -------------------------------------------------------------------------------- /test/index.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { act } from "react-dom/test-utils"; 3 | import { fireEvent, render } from "react-testing-library"; 4 | import fuzzyFilterFactory, { 5 | FilterResultsProps, 6 | InputFilterProps, 7 | FuseOptions, 8 | } from "../src"; 9 | 10 | interface TestItem { 11 | name: string; 12 | searchData: string; 13 | } 14 | const items: TestItem[] = [ 15 | { name: "one", searchData: "hello" }, 16 | { name: "two", searchData: "hello" }, 17 | { name: "three", searchData: "goodbye" }, 18 | { name: "four", searchData: "bonjour" }, 19 | ]; 20 | 21 | const defaultFuseConfig: FuseOptions = { 22 | keys: ["searchData"], 23 | }; 24 | 25 | function componentFactory( 26 | inputFilterProps: InputFilterProps, 27 | filterResultsProps: FilterResultsProps 28 | ) { 29 | const { InputFilter, FilterResults, changeInputValue } = fuzzyFilterFactory< 30 | TestItem 31 | >(); 32 | function MyComponent() { 33 | return ( 34 |
35 |

Separate Components

36 | 40 |

Any amount of content between

41 | 42 |
43 | ); 44 | } 45 | 46 | return { MyComponent, changeInputValue }; 47 | } 48 | 49 | describe("fuzzyFilterFactory", () => { 50 | let resultsSpy: jest.Mock; 51 | beforeEach(() => { 52 | resultsSpy = jest.fn().mockImplementation(() =>
); 53 | }); 54 | 55 | it("returns FilterResults and InputFilter components", () => { 56 | const { InputFilter, FilterResults } = fuzzyFilterFactory(); 57 | expect(typeof InputFilter).toEqual("function"); 58 | expect(typeof FilterResults).toEqual("function"); 59 | expect(FilterResults.displayName).toEqual("FilterResults"); 60 | expect(InputFilter.displayName).toEqual("InputFilter"); 61 | }); 62 | 63 | it("input controls filter results", () => { 64 | const { MyComponent } = componentFactory( 65 | {}, 66 | { items, fuseConfig: defaultFuseConfig, children: resultsSpy } 67 | ); 68 | const utils = render(); 69 | const input = utils.getByPlaceholderText("Search"); 70 | expect(resultsSpy).toHaveBeenCalledTimes(1); 71 | expect(resultsSpy).toHaveBeenLastCalledWith([ 72 | { name: "one", searchData: "hello" }, 73 | { name: "two", searchData: "hello" }, 74 | { name: "three", searchData: "goodbye" }, 75 | { name: "four", searchData: "bonjour" }, 76 | ]); 77 | 78 | fireEvent.change(input, { 79 | target: { value: "ello" }, 80 | }); 81 | expect(resultsSpy).toHaveBeenCalledTimes(2); 82 | expect(resultsSpy).toHaveBeenLastCalledWith([ 83 | { name: "one", searchData: "hello" }, 84 | { name: "two", searchData: "hello" }, 85 | ]); 86 | 87 | fireEvent.change(input, { 88 | target: { value: "gdbye" }, 89 | }); 90 | expect(resultsSpy).toHaveBeenCalledTimes(3); 91 | expect(resultsSpy).toHaveBeenLastCalledWith([ 92 | { name: "three", searchData: "goodbye" }, 93 | ]); 94 | }); 95 | 96 | it("uses initialSearch", () => { 97 | const { MyComponent } = componentFactory( 98 | { initialSearch: "gdbye" }, 99 | { items, fuseConfig: defaultFuseConfig, children: resultsSpy } 100 | ); 101 | render(); 102 | expect(resultsSpy).toHaveBeenCalledTimes(2); 103 | expect(resultsSpy).toHaveBeenLastCalledWith([ 104 | { name: "three", searchData: "goodbye" }, 105 | ]); 106 | }); 107 | 108 | it("handles external input value changes via changeInputValue function", () => { 109 | const { MyComponent, changeInputValue } = componentFactory( 110 | { initialSearch: "gdbye" }, 111 | { items, fuseConfig: defaultFuseConfig, children: resultsSpy } 112 | ); 113 | render(); 114 | // change value externally 115 | act(() => { 116 | changeInputValue("bonjour"); 117 | }); 118 | expect(resultsSpy).toHaveBeenCalledTimes(3); 119 | expect(resultsSpy).toHaveBeenLastCalledWith([ 120 | { name: "four", searchData: "bonjour" }, 121 | ]); 122 | }); 123 | }); 124 | -------------------------------------------------------------------------------- /test/types.test.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import fuzzyFilterFactory, { FuseOptions, PreFilter } from "../src"; 3 | 4 | interface TestItem { 5 | name: string; 6 | searchData: string; 7 | state: string; 8 | } 9 | const data: TestItem[] = [ 10 | { name: "one", searchData: "hello", state: "archived" }, 11 | { name: "two", searchData: "hello", state: "" }, 12 | { name: "three", searchData: "goodbye", state: "open" }, 13 | { name: "four", searchData: "bonjour", state: "archived" }, 14 | ]; 15 | 16 | const filters: Array> = [ 17 | { 18 | handler: (_filterVal, results, _Fuse) => { 19 | return results.filter(item => item.state === "archived"); 20 | }, 21 | regex: /archived/, 22 | }, 23 | { 24 | handler: (match, results, Fuse) => { 25 | const [key, value] = match.split(":"); 26 | const fuse = new Fuse(results, { keys: [key], threshold: 0.4 }); 27 | return fuse.search(value); 28 | }, 29 | regex: /\S+:\S+/g, 30 | }, 31 | ]; 32 | 33 | it("provides necessary types for usage", () => { 34 | const { InputFilter, FilterResults, changeInputValue } = fuzzyFilterFactory< 35 | TestItem 36 | >(); 37 | const fuseConfig: FuseOptions = { 38 | keys: ["searchData"], 39 | }; 40 | const minimalProps = ( 41 |
42 | 43 | 44 | {items => items.map((item, i) =>
{item.name}
)} 45 |
46 |
47 | ); 48 | const allProps = ( 49 |
50 | 51 | 57 | {items => items.map((item, i) =>
{item.name}
)} 58 |
59 |
60 | ); 61 | 62 | changeInputValue("some string"); 63 | expect(minimalProps).not.toBeNull(); 64 | expect(allProps).not.toBeNull(); 65 | }); 66 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowSyntheticDefaultImports": true, 4 | "declaration": true, 5 | "declarationDir": "dist", 6 | "emitDecoratorMetadata": false, 7 | "experimentalDecorators": false, 8 | "esModuleInterop": true, 9 | "importHelpers": true, 10 | "jsx": "react", 11 | "lib": ["es2015", "dom"], 12 | "module": "esnext", 13 | "moduleResolution": "node", 14 | "noFallthroughCasesInSwitch": true, 15 | "noImplicitAny": true, 16 | "noImplicitReturns": true, 17 | "noImplicitThis": true, 18 | "noUnusedLocals": true, 19 | "noUnusedParameters": true, 20 | "outDir": "compiled", 21 | "pretty": true, 22 | "removeComments": true, 23 | "sourceMap": true, 24 | "strict": true, 25 | "strictNullChecks": true, 26 | "stripInternal": true, 27 | "target": "es5" 28 | }, 29 | "include": ["src"], 30 | "exclude": ["node_modules", "dist"] 31 | } 32 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base.json", 3 | "include": ["src", "test"] 4 | } 5 | --------------------------------------------------------------------------------