├── .eslintignore ├── .eslintrc ├── .github ├── ISSUE_TEMPLATE.md ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── PULL_REQUEST_TEMPLATE.md └── workflows │ ├── chromatic.yml │ └── ci.yml ├── .gitignore ├── .husky ├── .gitignore ├── pre-commit └── pre-push ├── .prettierignore ├── .prettierrc ├── .storybook ├── main.js ├── preview-head.html └── preview.js ├── .yarnclean ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── babel.config.js ├── codecov.yml ├── docs ├── API.md ├── Data.md ├── Filtering.md ├── Methods.md ├── README.md ├── Rendering.md ├── Upgrading.md └── Usage.md ├── example ├── .eslintrc ├── index.html ├── package.json ├── public │ ├── examples.css │ └── favicon.ico ├── raw-loader.d.ts ├── src │ ├── components │ │ ├── Anchor.tsx │ │ ├── CodeSample.tsx │ │ ├── Context.tsx │ │ ├── ExampleSection.tsx │ │ ├── GitHubLogo.tsx │ │ ├── GithubStarsButton.tsx │ │ ├── Markdown.tsx │ │ ├── Page.tsx │ │ ├── PageFooter.tsx │ │ ├── PageHeader.tsx │ │ ├── PageMenu.tsx │ │ ├── ScrollSpy.tsx │ │ ├── Section.tsx │ │ └── Title.tsx │ ├── data.ts │ ├── examples │ │ ├── AsyncExample.tsx │ │ ├── BasicBehaviorsExample.tsx │ │ ├── BasicExample.tsx │ │ ├── CustomFilteringExample.tsx │ │ ├── CustomSelectionsExample.tsx │ │ ├── FilteringExample.tsx │ │ ├── FormExample.tsx │ │ ├── InputSizeExample.tsx │ │ ├── LabelKeyExample.tsx │ │ ├── MenuAlignExample.tsx │ │ ├── PaginationExample.tsx │ │ ├── PositionFixedExample.tsx │ │ ├── PublicMethodsExample.tsx │ │ ├── RenderingExample.js │ │ └── SelectionsExample.tsx │ ├── index.tsx │ ├── sections │ │ ├── AsyncSection.tsx │ │ ├── BasicSection.tsx │ │ ├── BehaviorsSection.tsx │ │ ├── CustomSelectionsSection.tsx │ │ ├── FilteringSection.tsx │ │ ├── PublicMethodsSection.tsx │ │ └── RenderingSection.tsx │ └── util │ │ └── getIdFromTitle.ts ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── jest.config.js ├── jest.setup.js ├── package.json ├── rollup.config.js ├── scripts ├── buildCSS.js ├── buildModules.js └── deployExample.js ├── src ├── behaviors │ ├── async.tsx │ ├── item.tsx │ └── token.tsx ├── components │ ├── AsyncTypeahead │ │ ├── AsyncTypeahead.test.tsx │ │ ├── AsyncTypeahead.tsx │ │ └── index.ts │ ├── ClearButton │ │ ├── ClearButton.stories.tsx │ │ ├── ClearButton.test.tsx │ │ ├── ClearButton.tsx │ │ ├── __snapshots__ │ │ │ └── ClearButton.test.tsx.snap │ │ └── index.ts │ ├── Highlighter │ │ ├── Highlighter.stories.tsx │ │ ├── Highlighter.test.tsx │ │ ├── Highlighter.tsx │ │ └── index.ts │ ├── Hint │ │ ├── Hint.stories.tsx │ │ ├── Hint.test.tsx │ │ ├── Hint.tsx │ │ ├── __snapshots__ │ │ │ └── Hint.test.tsx.snap │ │ └── index.ts │ ├── Input │ │ ├── Input.stories.tsx │ │ ├── Input.test.tsx │ │ ├── Input.tsx │ │ ├── __snapshots__ │ │ │ └── Input.test.tsx.snap │ │ └── index.ts │ ├── Loader │ │ ├── Loader.stories.tsx │ │ ├── Loader.test.tsx │ │ ├── Loader.tsx │ │ ├── __snapshots__ │ │ │ └── Loader.test.tsx.snap │ │ └── index.ts │ ├── Menu │ │ ├── Menu.stories.tsx │ │ ├── Menu.test.tsx │ │ ├── Menu.tsx │ │ ├── __snapshots__ │ │ │ └── Menu.test.tsx.snap │ │ └── index.ts │ ├── MenuItem │ │ ├── BaseMenuItem.stories.tsx │ │ ├── MenuItem.stories.tsx │ │ ├── MenuItem.test.tsx │ │ ├── MenuItem.tsx │ │ ├── __snapshots__ │ │ │ └── MenuItem.test.tsx.snap │ │ └── index.ts │ ├── Overlay │ │ ├── Overlay.stories.tsx │ │ ├── Overlay.test.tsx │ │ ├── Overlay.tsx │ │ ├── __snapshots__ │ │ │ └── Overlay.test.tsx.snap │ │ ├── index.ts │ │ └── useOverlay.ts │ ├── RootClose │ │ ├── RootClose.tsx │ │ ├── index.ts │ │ └── useRootClose.ts │ ├── Token │ │ ├── Token.stories.tsx │ │ ├── Token.test.tsx │ │ ├── Token.tsx │ │ ├── __snapshots__ │ │ │ └── Token.test.tsx.snap │ │ └── index.ts │ ├── Typeahead │ │ ├── Typeahead.stories.tsx │ │ ├── Typeahead.test.tsx │ │ ├── Typeahead.tsx │ │ ├── __snapshots__ │ │ │ └── Typeahead.test.tsx.snap │ │ └── index.ts │ ├── TypeaheadInputMulti │ │ ├── TypeaheadInputMulti.stories.tsx │ │ ├── TypeaheadInputMulti.test.tsx │ │ ├── TypeaheadInputMulti.tsx │ │ ├── __snapshots__ │ │ │ └── TypeaheadInputMulti.test.tsx.snap │ │ └── index.ts │ ├── TypeaheadInputSingle │ │ ├── TypeaheadInputSingle.stories.tsx │ │ ├── TypeaheadInputSingle.test.tsx │ │ ├── TypeaheadInputSingle.tsx │ │ ├── __snapshots__ │ │ │ └── TypeaheadInputSingle.test.tsx.snap │ │ └── index.ts │ └── TypeaheadMenu │ │ ├── TypeaheadMenu.stories.tsx │ │ ├── TypeaheadMenu.test.tsx │ │ ├── TypeaheadMenu.tsx │ │ ├── __snapshots__ │ │ └── TypeaheadMenu.test.tsx.snap │ │ └── index.ts ├── constants.ts ├── core │ ├── Context.tsx │ ├── Typeahead.tsx │ ├── TypeaheadManager.tsx │ ├── TypeaheadState.test.tsx │ └── TypeaheadState.ts ├── index.ts ├── propTypes.ts ├── tests │ ├── data.ts │ ├── helpers.tsx │ ├── index.test.ts │ └── props.ts ├── types.ts └── utils │ ├── addCustomOption.test.ts │ ├── addCustomOption.ts │ ├── defaultFilterBy.test.ts │ ├── defaultFilterBy.ts │ ├── defaultSelectHint.test.ts │ ├── defaultSelectHint.ts │ ├── getDisplayName.test.tsx │ ├── getDisplayName.ts │ ├── getHintText.test.ts │ ├── getHintText.ts │ ├── getInputProps.test.ts │ ├── getInputProps.ts │ ├── getInputText.test.ts │ ├── getInputText.ts │ ├── getIsOnlyResult.test.ts │ ├── getIsOnlyResult.ts │ ├── getMatchBounds.test.ts │ ├── getMatchBounds.ts │ ├── getMenuItemId.test.ts │ ├── getMenuItemId.ts │ ├── getOptionLabel.test.ts │ ├── getOptionLabel.ts │ ├── getOptionProperty.test.ts │ ├── getOptionProperty.ts │ ├── getStringLabelKey.test.ts │ ├── getStringLabelKey.ts │ ├── getTruncatedOptions.test.ts │ ├── getTruncatedOptions.ts │ ├── getUpdatedActiveIndex.test.ts │ ├── getUpdatedActiveIndex.ts │ ├── hasOwnProperty.ts │ ├── index.ts │ ├── isSelectable.test.ts │ ├── isSelectable.ts │ ├── isShown.test.ts │ ├── isShown.ts │ ├── nodash.test.ts │ ├── nodash.ts │ ├── preventInputBlur.test.ts │ ├── preventInputBlur.ts │ ├── propsWithBsClassName.test.ts │ ├── propsWithBsClassName.ts │ ├── size.test.ts │ ├── size.ts │ ├── stripDiacritics.test.ts │ ├── stripDiacritics.ts │ ├── validateSelectedPropChange.test.ts │ ├── validateSelectedPropChange.ts │ ├── warn.test.ts │ └── warn.ts ├── styles ├── Typeahead.bs5.scss └── Typeahead.scss ├── tsconfig.json └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | css 2 | cjs 3 | dist 4 | es 5 | example/package-example.js 6 | example/public/prism.min.js 7 | lib 8 | types 9 | **/node_modules 10 | -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "env": { 3 | "browser": true, 4 | "jest": true 5 | }, 6 | "extends": [ 7 | "@ericgio/eslint-config-react", 8 | "plugin:@typescript-eslint/recommended", 9 | "plugin:react-hooks/recommended", 10 | "prettier" 11 | ], 12 | "globals": {}, 13 | "parser": "@typescript-eslint/parser", 14 | "plugins": ["@typescript-eslint"], 15 | "settings": { 16 | "import/resolver": { 17 | "node": { 18 | "extensions": [".js", ".jsx", ".ts", ".tsx"] 19 | } 20 | } 21 | }, 22 | "rules": { 23 | "@typescript-eslint/no-shadow": 2, 24 | "@typescript-eslint/no-unused-vars": [ 25 | 2, 26 | { "vars": "all", "args": "after-used", "ignoreRestSiblings": true } 27 | ], 28 | "@typescript-eslint/no-use-before-define": ["error"], 29 | "react/jsx-filename-extension": [ 30 | 1, 31 | { 32 | "extensions": [".js", ".jsx", ".tsx"] 33 | } 34 | ], 35 | "react/jsx-fragments": [2, "syntax"], 36 | "react/static-property-placement": [2, "static public field"], 37 | 38 | "@typescript-eslint/ban-ts-comment": "off", 39 | "@typescript-eslint/explicit-module-boundary-types": "off", 40 | "import/extensions": "off", 41 | "react/jsx-no-bind": "off", 42 | 43 | // Turn off the following rules since they conflict with the TS version. 44 | "no-shadow": "off", 45 | "no-use-before-define": "off" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 23 | 24 | 25 | 26 | ### Version 27 | 28 | 29 | 30 | ### Steps to reproduce 31 | 32 | 33 | 34 | ### Expected Behavior 35 | 36 | 37 | 38 | ### Actual Behavior 39 | 40 | 41 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: bug 6 | assignees: '' 7 | 8 | --- 9 | 10 | 23 | ### Version 24 | 25 | 26 | 27 | ### Steps to reproduce 28 | 29 | 34 | 35 | ### Expected Behavior 36 | 37 | 38 | 39 | ### Actual Behavior 40 | 41 | 42 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: feature request 6 | assignees: '' 7 | 8 | --- 9 | 10 | 21 | 22 | **Is your feature request related to a problem? Please describe.** 23 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 24 | 25 | **Describe the solution you'd like** 26 | A clear and concise description of what you want to happen. 27 | 28 | **How is this solution useful to others?** 29 | Does your feature address a common use case? Does it provide a more generalized way to solve the type of problem you're encountering? 30 | 31 | **Describe alternatives you've considered** 32 | A clear and concise description of any alternative solutions or features you've considered. 33 | 34 | **Additional context** 35 | Add any other context, sample code, or screenshots about the feature request here. 36 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | 11 | 12 | **What issue does this pull request resolve?** 13 | 14 | 15 | **What changes did you make?** 16 | 17 | 18 | **Is there anything that requires more attention while reviewing?** 19 | -------------------------------------------------------------------------------- /.github/workflows/chromatic.yml: -------------------------------------------------------------------------------- 1 | name: Chromatic 2 | on: 3 | push: 4 | pull_request: 5 | branches: [$default_branch] 6 | jobs: 7 | chromatic-deployment: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - name: Checkout repository 11 | uses: actions/checkout@v2 12 | with: 13 | fetch-depth: 0 # 👈 Required to retrieve git history w/actions v2 14 | - name: Install dependencies 15 | run: yarn 16 | - name: Publish to Chromatic 17 | uses: chromaui/action@v1 18 | with: 19 | token: ${{ secrets.GITHUB_TOKEN }} 20 | projectToken: ${{ secrets.CHROMATIC_PROJECT_TOKEN }} 21 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | push: 4 | pull_request: 5 | branches: [$default_branch] 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | node-version: [18.x, 20.x] 12 | steps: 13 | - uses: actions/checkout@v2 14 | - name: Use Node.js ${{ matrix.node-version }} 15 | uses: actions/setup-node@v2 16 | with: 17 | node-version: ${{ matrix.node-version }} 18 | - run: yarn install --frozen-lockfile 19 | - run: yarn install:example --frozen-lockfile 20 | - run: yarn ci 21 | - uses: codecov/codecov-action@v1 22 | - run: yarn build 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | cjs/ 2 | coverage/ 3 | css/ 4 | dist/ 5 | es/ 6 | lib/ 7 | node_modules/ 8 | types/ 9 | 10 | .DS_Store 11 | .coveralls.yml 12 | build-storybook.log 13 | example/package-example.js 14 | npm-debug.log 15 | tsconfig.tsbuildinfo 16 | yarn-error.log 17 | -------------------------------------------------------------------------------- /.husky/.gitignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint-staged 5 | -------------------------------------------------------------------------------- /.husky/pre-push: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn run check 5 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .github 2 | .husky 3 | cjs 4 | coverage 5 | css 6 | dist 7 | docs 8 | es 9 | example/package-example.js 10 | example/public/prism.min.js 11 | lib 12 | types 13 | **/node_modules 14 | README.md 15 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "bracketSameLine": true, 3 | "jsxSingleQuote": false, 4 | "singleQuote": true, 5 | "trailingComma": "es5" 6 | } 7 | -------------------------------------------------------------------------------- /.storybook/main.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | stories: ['../src/**/*.stories.mdx', '../src/**/*.stories.@(js|jsx|ts|tsx)'], 3 | addons: [ 4 | '@storybook/addon-links', 5 | '@storybook/addon-essentials', 6 | '@storybook/addon-a11y', 7 | '@storybook/preset-scss', 8 | ], 9 | core: { 10 | builder: 'webpack5', 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /.storybook/preview-head.html: -------------------------------------------------------------------------------- 1 | 6 | 7 | 12 | -------------------------------------------------------------------------------- /.storybook/preview.js: -------------------------------------------------------------------------------- 1 | import '../styles/Typeahead.scss'; 2 | import '../styles/Typeahead.bs5.scss'; 3 | 4 | export const parameters = { 5 | actions: { argTypesRegex: '^on[A-Z].*' }, 6 | controls: { 7 | matchers: { 8 | color: /(background|color)$/i, 9 | date: /Date$/, 10 | }, 11 | }, 12 | }; 13 | -------------------------------------------------------------------------------- /.yarnclean: -------------------------------------------------------------------------------- 1 | @emotion/core/types 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | This project adheres to [semantic versioning](http://semver.org/). Each release is documented on the [releases](https://github.com/ericgio/react-bootstrap-typeahead/releases) page. 4 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015–present Eric Giovanola 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,no-template-curly-in-string */ 2 | 3 | // `ignore` option doesn't support wildcard for extension. 4 | // https://github.com/babel/babel/issues/12008 5 | const moduleIgnore = [ 6 | '**/*.stories.tsx', 7 | '**/*.test.tsx', 8 | '**/*.test.ts', 9 | 'src/tests/*', 10 | 'src/types.ts', 11 | ]; 12 | 13 | module.exports = { 14 | presets: [ 15 | ['@babel/preset-env', { modules: false }], 16 | '@babel/preset-typescript', 17 | '@babel/preset-react', 18 | ], 19 | plugins: [ 20 | '@babel/plugin-proposal-class-properties', 21 | '@babel/plugin-proposal-export-default-from', 22 | 'dev-expression', 23 | [ 24 | 'transform-imports', 25 | { 26 | lodash: { 27 | transform: 'lodash/${member}', 28 | preventFullImport: true, 29 | }, 30 | }, 31 | ], 32 | ], 33 | env: { 34 | cjs: { 35 | plugins: [ 36 | '@babel/transform-runtime', 37 | '@babel/transform-modules-commonjs', 38 | ], 39 | ignore: moduleIgnore, 40 | }, 41 | es: { 42 | plugins: ['@babel/transform-runtime'], 43 | ignore: moduleIgnore, 44 | }, 45 | production: { 46 | plugins: ['transform-react-remove-prop-types'], 47 | }, 48 | test: { 49 | plugins: [ 50 | '@babel/transform-runtime', 51 | '@babel/transform-modules-commonjs', 52 | ], 53 | }, 54 | }, 55 | }; 56 | -------------------------------------------------------------------------------- /codecov.yml: -------------------------------------------------------------------------------- 1 | coverage: 2 | status: 3 | project: 4 | default: 5 | target: auto 6 | threshold: 0.1% 7 | patch: off 8 | 9 | comment: off 10 | -------------------------------------------------------------------------------- /docs/Data.md: -------------------------------------------------------------------------------- 1 | # Data 2 | `react-bootstrap-typeahead` accepts an array of either strings or objects. If you pass in objects, each one should have a string property to be used as the label for display. By default, the key is named `label`, but you can specify a different key via the `labelKey` prop. If you pass an array of strings, the `labelKey` prop will be ignored. 3 | 4 | The component will throw an error if any options are something other than a string or object with a valid `labelKey`. 5 | 6 | The following are valid data structures: 7 | 8 | ### `Array` 9 | ```jsx 10 | var options = [ 11 | 'John', 12 | 'Miles', 13 | 'Charles', 14 | 'Herbie', 15 | ]; 16 | ``` 17 | 18 | ### `Array` (w/default `labelKey`) 19 | ```jsx 20 | var options = [ 21 | {id: 1, label: 'John'}, 22 | {id: 2, label: 'Miles'}, 23 | {id: 3, label: 'Charles'}, 24 | {id: 4, label: 'Herbie'}, 25 | ]; 26 | ``` 27 | 28 | ### `Array` (w/custom `labelKey`) 29 | In this case, you would need to set `labelKey="name"` on the component. 30 | 31 | ```jsx 32 | var options = [ 33 | {id: 1, name: 'John'}, 34 | {id: 2, name: 'Miles'}, 35 | {id: 3, name: 'Charles'}, 36 | {id: 4, name: 'Herbie'}, 37 | ]; 38 | ``` 39 | 40 | ## Duplicate Data 41 | You may have unexpected results if your data contains duplicate options. For this reason, it is highly recommended that you pass in objects with unique identifiers (eg: an id) if possible. 42 | 43 | ## Data Sources 44 | The component simply handles rendering and selection of the data that is passed in. It is agnostic about the data source, which should be handled separately. The [`AsyncTypeahead`](API.md#asynctypeahead) component is provided to help in cases where data is being fetched asynchronously from an endpoint. 45 | 46 | [Next: Filtering](Filtering.md) 47 | -------------------------------------------------------------------------------- /docs/Filtering.md: -------------------------------------------------------------------------------- 1 | # Filtering 2 | By default, the component will filter results based on a case-insensitive string match between the input string and the `labelKey` property of each option (or the option itself, if an array of strings is passed). You can customize the filtering a few ways: 3 | 4 | ### `caseSensitive: boolean` (default: `false`) 5 | Setting to `true` changes the string match to be, you guessed it, case-sensitive. Defaults to `false`. 6 | ```jsx 7 | 11 | ``` 12 | 13 | ### `ignoreDiacritics: boolean` (default: `true`) 14 | By default, the component ignores accents and other diacritical marks when performing string matches. Set this prop to `false` to override that setting and perform a strict match. 15 | ```jsx 16 | 20 | ``` 21 | 22 | ### `filterBy` 23 | The `filterBy` prop can be used in one of two ways: to specify `option` properties that should be searched or to pass a custom callback. 24 | 25 | #### `Array` 26 | By default, the filtering algorithm only searches the field that corresponds to `labelKey`. However, you can pass an array of additional fields to search: 27 | ```jsx 28 | 32 | ``` 33 | The field corresponding to `labelKey` is always searched (once), whether or not you specify it. 34 | 35 | #### `(option: Object|string, props: Object) => boolean` 36 | You can also pass your own callback to take complete control over how the filtering works. Note that the `caseSensitive` and `ignoreDiacritics` props will be ignored in this case, since you are now completely overriding the algorithm. 37 | 38 | ```jsx 39 | { 42 | /* Your own filtering code goes here. */ 43 | }} 44 | /> 45 | ``` 46 | You can disable filtering completely by passing a function that returns `true`: 47 | 48 | ```jsx 49 | true} 52 | /> 53 | ``` 54 | 55 | [Next: Rendering](Rendering.md) 56 | -------------------------------------------------------------------------------- /docs/Methods.md: -------------------------------------------------------------------------------- 1 | # Public Methods 2 | To access the component's public methods, pass a ref to your typeahead then access the ref in your code: 3 | ```jsx 4 | const ref = React.createRef(); 5 | 6 | <> 7 | 11 | 14 | 15 | ``` 16 | 17 | Name | Description 18 | ---- | ----------- 19 | `blur()` | Blurs the input. 20 | `clear()` | Resets the typeahead component. Clears both text and selection(s). 21 | `focus()` | Focuses the input. 22 | `getInput()` | Provides access to the component's input node. 23 | `hideMenu()` | Hides the menu. 24 | `toggleMenu()` | Shows the menu if it is currently hidden; hides the menu if it is currently shown. 25 | 26 | [Next: API](API.md) 27 | -------------------------------------------------------------------------------- /docs/README.md: -------------------------------------------------------------------------------- 1 | # Table of Contents 2 | - [Upgrade Guide](Upgrading.md) 3 | - [Basic Usage](Usage.md) 4 | - [Data](Data.md) 5 | - [Filtering](Filtering.md) 6 | - [Rendering](Rendering.md) 7 | - [Public Methods](Methods.md) 8 | - [API](API.md) 9 | -------------------------------------------------------------------------------- /docs/Usage.md: -------------------------------------------------------------------------------- 1 | # Basic Usage 2 | The typeahead behaves similarly to other form elements. It requires an array of data options to be filtered and displayed. 3 | ```jsx 4 | { 6 | // Handle selections... 7 | }} 8 | options={[ /* Array of objects or strings */ ]} 9 | /> 10 | ``` 11 | 12 | ### Single & Multi-Selection 13 | The component provides single-selection by default, but also supports multi-selection. Simply set the `multiple` prop and the component turns into a tokenizer: 14 | 15 | ```jsx 16 | { 19 | // Handle selections... 20 | }} 21 | options={[...]} 22 | /> 23 | ``` 24 | 25 | ### Controlled vs. Uncontrolled 26 | Similar to other form elements, the typeahead can be [controlled](https://facebook.github.io/react/docs/forms.html#controlled-components) or [uncontrolled](https://facebook.github.io/react/docs/forms.html#uncontrolled-components). Use the `selected` prop to control it via the parent, or `defaultSelected` to optionally set defaults and then allow the component to control itself. Note that the *selections* can be controlled, not the input value. 27 | 28 | #### Controlled (Recommended) 29 | ```jsx 30 | { 32 | this.setState({selected}); 33 | }} 34 | options={[...]} 35 | selected={this.state.selected} 36 | /> 37 | ``` 38 | 39 | #### Uncontrolled 40 | ```jsx 41 | { 44 | // Handle selections... 45 | }} 46 | options={[...]} 47 | /> 48 | ``` 49 | 50 | [Next: Data](Data.md) 51 | -------------------------------------------------------------------------------- /example/.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["../.eslintrc"], 3 | "rules": { 4 | "@typescript-eslint/no-var-requires": "off", 5 | "import/no-extraneous-dependencies": "off", 6 | "sort-keys": "off" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /example/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 11 | 12 | React Bootstrap Typeahead Example 13 | 14 | 15 |
16 | 17 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-bootstrap-typeahead-examples", 3 | "version": "1.0.0", 4 | "main": "src/index.js", 5 | "license": "MIT", 6 | "private": false, 7 | "dependencies": { 8 | "marked": "^4.0.16", 9 | "prismjs": "^1.28.0", 10 | "react-bootstrap": "^2.4.0", 11 | "react-waypoint": "^10.1.0" 12 | }, 13 | "scripts": { 14 | "build": "webpack --mode production", 15 | "start": "webpack --mode development -w --progress" 16 | }, 17 | "devDependencies": { 18 | "@babel/core": "^7.18.2", 19 | "@babel/preset-env": "^7.18.2", 20 | "@babel/preset-react": "^7.17.12", 21 | "@babel/preset-typescript": "^7.17.12", 22 | "@types/marked": "^4.0.3", 23 | "@types/prismjs": "^1.26.0", 24 | "babel-loader": "^8.2.5", 25 | "babel-plugin-prismjs": "^2.1.0", 26 | "circular-dependency-plugin": "^5.2.2", 27 | "css-loader": "^6.7.1", 28 | "raw-loader": "^4.0.2", 29 | "sass-loader": "^13.0.0", 30 | "style-loader": "^3.3.1", 31 | "terser-webpack-plugin": "^5.3.3", 32 | "webpack": "^5.76.0", 33 | "webpack-cli": "^4.9.2" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /example/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ericgio/react-bootstrap-typeahead/924627376275c78988718230c0438748ff673a6d/example/public/favicon.ico -------------------------------------------------------------------------------- /example/raw-loader.d.ts: -------------------------------------------------------------------------------- 1 | declare module '!raw-loader!*' { 2 | const contents: string; 3 | export = contents; 4 | } 5 | -------------------------------------------------------------------------------- /example/src/components/Anchor.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | 3 | interface AnchorProps { 4 | children: ReactNode; 5 | id: string; 6 | } 7 | 8 | const Anchor = ({ children, id }: AnchorProps) => ( 9 | <> 10 | 11 | 12 | # 13 | {children} 14 | 15 | 16 | ); 17 | 18 | export default Anchor; 19 | -------------------------------------------------------------------------------- /example/src/components/CodeSample.tsx: -------------------------------------------------------------------------------- 1 | import Prism from 'prismjs'; 2 | import React, { useEffect, useRef } from 'react'; 3 | 4 | const START_STR = '/* example-start */'; 5 | const END_STR = '/* example-end */'; 6 | 7 | function getExampleCode(str: string) { 8 | return str.slice( 9 | str.indexOf(START_STR) + START_STR.length + 1, 10 | str.indexOf(END_STR) 11 | ); 12 | } 13 | 14 | interface CodeSampleProps { 15 | children: string; 16 | } 17 | 18 | const CodeSample = ({ children }: CodeSampleProps) => { 19 | const ref = useRef(null); 20 | 21 | useEffect(() => { 22 | if (ref.current) { 23 | Prism.highlightElement(ref.current); 24 | } 25 | }, []); 26 | 27 | return ( 28 |
29 |       {getExampleCode(children)}
30 |     
31 | ); 32 | }; 33 | 34 | export default CodeSample; 35 | -------------------------------------------------------------------------------- /example/src/components/Context.tsx: -------------------------------------------------------------------------------- 1 | import { createContext, useContext } from 'react'; 2 | 3 | const noop = () => {}; 4 | 5 | interface ExampleContextType { 6 | onAfter: (href: string) => void; 7 | onBefore: (href: string) => void; 8 | } 9 | 10 | const ExampleContext = createContext({ 11 | onAfter: noop, 12 | onBefore: noop, 13 | }); 14 | 15 | export const useExampleContext = () => useContext(ExampleContext); 16 | 17 | export default ExampleContext; 18 | -------------------------------------------------------------------------------- /example/src/components/ExampleSection.tsx: -------------------------------------------------------------------------------- 1 | import React, { ReactNode, useState } from 'react'; 2 | import { Button } from 'react-bootstrap'; 3 | 4 | import CodeSample from './CodeSample'; 5 | 6 | interface ExampleSectionProps { 7 | children: ReactNode; 8 | code: string; 9 | } 10 | 11 | const ExampleSection = ({ children, code }: ExampleSectionProps) => { 12 | const [isOpen, setIsOpen] = useState(false); 13 | 14 | return ( 15 |
16 |
17 |
18 |
Example
19 | 26 |
27 | {children} 28 |
29 | {isOpen ? {code} : null} 30 |
31 | ); 32 | }; 33 | 34 | export default ExampleSection; 35 | -------------------------------------------------------------------------------- /example/src/components/GitHubLogo.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | const DATA = 4 | 'M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 ' + 5 | '0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.' + 6 | '13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.' + 7 | '07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.' + 8 | '08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.' + 9 | '09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 ' + 10 | '1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 ' + 11 | '1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0 0 16 8c0-4.42-3.58-8-8-8z'; 12 | 13 | interface GitHubLogoProps { 14 | size?: number; 15 | style?: React.CSSProperties; 16 | } 17 | 18 | const GitHubLogo = ({ size = 24, ...props }: GitHubLogoProps) => ( 19 | 27 | 28 | 29 | ); 30 | 31 | export default GitHubLogo; 32 | -------------------------------------------------------------------------------- /example/src/components/GithubStarsButton.tsx: -------------------------------------------------------------------------------- 1 | import React, { useEffect, useRef } from 'react'; 2 | 3 | const AUTHOR_REPO = 'ericgio/react-bootstrap-typeahead'; 4 | 5 | const GitHubStarsButton = () => { 6 | const ref = useRef(null); 7 | 8 | // Set size to large on initial render. 9 | useEffect(() => { 10 | if (ref.current) { 11 | ref.current.dataset.size = 'large'; 12 | } 13 | }, []); 14 | 15 | return ( 16 | 24 | Star 25 | 26 | ); 27 | }; 28 | 29 | export default GitHubStarsButton; 30 | -------------------------------------------------------------------------------- /example/src/components/Markdown.tsx: -------------------------------------------------------------------------------- 1 | import { marked } from 'marked'; 2 | import React from 'react'; 3 | 4 | marked.setOptions({ 5 | breaks: true, 6 | gfm: true, 7 | pedantic: false, 8 | smartLists: true, 9 | smartypants: false, 10 | }); 11 | 12 | interface MarkdownProps { 13 | children: string; 14 | } 15 | 16 | const Markdown = ({ children }: MarkdownProps) => ( 17 |
22 | ); 23 | 24 | export default Markdown; 25 | -------------------------------------------------------------------------------- /example/src/components/Page.tsx: -------------------------------------------------------------------------------- 1 | import React, { Children, useState } from 'react'; 2 | import { Col, Container, Nav, Row } from 'react-bootstrap'; 3 | 4 | import ExampleContext from './Context'; 5 | import PageFooter from './PageFooter'; 6 | import PageHeader from './PageHeader'; 7 | import PageMenu from './PageMenu'; 8 | 9 | import getIdFromTitle from '../util/getIdFromTitle'; 10 | 11 | interface PageProps { 12 | children: JSX.Element[]; 13 | } 14 | 15 | const Page = ({ children }: PageProps) => { 16 | const [activeHref, setActiveHref] = useState(window.location.hash); 17 | 18 | const hrefs: string[] = []; 19 | const sections: string[] = []; 20 | 21 | Children.forEach(children, (child) => { 22 | const { title } = child.props; 23 | hrefs.push(`#${getIdFromTitle(title)}`); 24 | sections.push(title); 25 | }); 26 | 27 | const handleMenuItemClick = (href: string) => { 28 | window.location.hash = href; 29 | setActiveHref(href); 30 | }; 31 | 32 | const onAfter = (href: string) => setActiveHref(href); 33 | 34 | const onBefore = (href: string) => { 35 | const index = hrefs.indexOf(href) - 1; 36 | setActiveHref(hrefs[index]); 37 | }; 38 | 39 | return ( 40 | 41 |
42 | 43 | 44 | 45 | {children} 46 | 47 | 48 | {sections.map((title: string) => { 49 | const href = `#${getIdFromTitle(title)}`; 50 | return ( 51 | 52 | handleMenuItemClick(href)}> 55 | {title} 56 | 57 | 58 | ); 59 | })} 60 | 61 | 62 | 63 | 64 | 65 |
66 |
67 | ); 68 | }; 69 | 70 | export default Page; 71 | -------------------------------------------------------------------------------- /example/src/components/PageFooter.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Container } from 'react-bootstrap'; 3 | 4 | import GithubStarsButton from './GithubStarsButton'; 5 | 6 | import pkg from '../../../package.json'; 7 | 8 | const AUTHOR_GITHUB_URL = 'https://github.com/ericgio'; 9 | const BASE_GITHUB_URL = `${AUTHOR_GITHUB_URL}/react-bootstrap-typeahead`; 10 | const BOOTSTRAP_VERSION = '4.4.1'; 11 | 12 | const authorLink = ( 13 | 14 | Eric Giovanola 15 | 16 | ); 17 | 18 | const currentYear = new Date().getFullYear(); 19 | const footerLinks = [ 20 | { href: BASE_GITHUB_URL, label: 'GitHub' }, 21 | { href: `${BASE_GITHUB_URL}/issues`, label: 'Issues' }, 22 | { href: `${BASE_GITHUB_URL}/releases`, label: 'Releases' }, 23 | ]; 24 | 25 | const licenseLink = ( 26 | 30 | MIT 31 | 32 | ); 33 | 34 | const versionLink = ( 35 | 39 | v{pkg.version} 40 | 41 | ); 42 | 43 | const bsLink = ( 44 | 48 | v{BOOTSTRAP_VERSION} 49 | 50 | ); 51 | 52 | const PageFooter = () => ( 53 |
54 | 55 | 64 |
    65 |
  • 66 | Copyright © {currentYear} {authorLink} 67 |
  • 68 |
  • License: {licenseLink}
  • 69 |
  • Version: {versionLink}
  • 70 |
  • Bootstrap Version: {bsLink}
  • 71 |
72 | 73 |
74 |
75 | ); 76 | 77 | export default PageFooter; 78 | -------------------------------------------------------------------------------- /example/src/components/PageHeader.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Container, Nav, Navbar } from 'react-bootstrap'; 3 | import pkg from '../../../package.json'; 4 | 5 | import GitHubLogo from './GitHubLogo'; 6 | 7 | const GITHUB_URL = 'https://github.com/ericgio/react-bootstrap-typeahead'; 8 | 9 | const PageHeader = () => ( 10 | 11 | 12 | React Bootstrap Typeahead 13 | 14 | 15 | 16 | 17 | 18 | 19 | 32 | 33 | 34 | 35 | ); 36 | 37 | export default PageHeader; 38 | -------------------------------------------------------------------------------- /example/src/components/PageMenu.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Nav } from 'react-bootstrap'; 3 | 4 | interface PageMenuProps { 5 | children: React.ReactNode; 6 | } 7 | 8 | const PageMenu = (props: PageMenuProps) => ( 9 |
10 | 11 | 12 | Back to top 13 | 14 |
15 | ); 16 | 17 | export default PageMenu; 18 | -------------------------------------------------------------------------------- /example/src/components/ScrollSpy.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Waypoint } from 'react-waypoint'; 3 | 4 | interface ScrollSpyProps { 5 | href: string; 6 | onBefore: (href: string) => void; 7 | onAfter: (href: string) => void; 8 | } 9 | 10 | const ScrollSpy = ({ href, onBefore, onAfter }: ScrollSpyProps) => ( 11 | 14 | previousPosition === Waypoint.above && onBefore(href) 15 | } 16 | onLeave={({ currentPosition }) => 17 | currentPosition === Waypoint.above && onAfter(href) 18 | } 19 | topOffset={10} 20 | /> 21 | ); 22 | 23 | export default ScrollSpy; 24 | -------------------------------------------------------------------------------- /example/src/components/Section.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import Anchor from './Anchor'; 4 | import { useExampleContext } from './Context'; 5 | import ScrollSpy from './ScrollSpy'; 6 | 7 | import getIdFromTitle from '../util/getIdFromTitle'; 8 | 9 | interface SectionProps { 10 | children: React.ReactNode; 11 | title: string; 12 | } 13 | 14 | const Section = ({ children, title }: SectionProps) => { 15 | const { onAfter, onBefore } = useExampleContext(); 16 | const id = getIdFromTitle(title); 17 | 18 | return ( 19 |
20 | 21 |

22 | {title} 23 |

24 | {children} 25 |
26 | ); 27 | }; 28 | 29 | export default Section; 30 | -------------------------------------------------------------------------------- /example/src/components/Title.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import Anchor from './Anchor'; 4 | 5 | import getIdFromTitle from '../util/getIdFromTitle'; 6 | 7 | interface TitleProps { 8 | children: string; 9 | } 10 | 11 | const Title = ({ children }: TitleProps) => ( 12 |

13 | {children} 14 |

15 | ); 16 | 17 | export default Title; 18 | -------------------------------------------------------------------------------- /example/src/examples/AsyncExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved,camelcase */ 2 | 3 | import React, { useState } from 'react'; 4 | import { AsyncTypeahead } from 'react-bootstrap-typeahead'; 5 | 6 | interface Item { 7 | avatar_url: string; 8 | id: string; 9 | login: string; 10 | } 11 | 12 | interface Response { 13 | items: Item[]; 14 | } 15 | 16 | /* example-start */ 17 | const SEARCH_URI = 'https://api.github.com/search/users'; 18 | 19 | const AsyncExample = () => { 20 | const [isLoading, setIsLoading] = useState(false); 21 | const [options, setOptions] = useState([]); 22 | 23 | const handleSearch = (query: string) => { 24 | setIsLoading(true); 25 | 26 | fetch(`${SEARCH_URI}?q=${query}+in:login&page=1&per_page=50`) 27 | .then((resp) => resp.json()) 28 | .then(({ items }: Response) => { 29 | setOptions(items); 30 | setIsLoading(false); 31 | }); 32 | }; 33 | 34 | // Bypass client-side filtering by returning `true`. Results are already 35 | // filtered by the search endpoint, so no need to do it again. 36 | const filterBy = () => true; 37 | 38 | return ( 39 | ( 49 | <> 50 | {option.login} 59 | {option.login} 60 | 61 | )} 62 | /> 63 | ); 64 | }; 65 | /* example-end */ 66 | 67 | export default AsyncExample; 68 | -------------------------------------------------------------------------------- /example/src/examples/BasicBehaviorsExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { ChangeEvent, useReducer } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | import options from '../data'; 8 | 9 | interface State { 10 | disabled: boolean; 11 | dropup: boolean; 12 | flip: boolean; 13 | highlightOnlyResult: boolean; 14 | minLength: number; 15 | open?: boolean; 16 | } 17 | 18 | interface Action { 19 | checked: boolean; 20 | name: keyof State; 21 | } 22 | 23 | /* example-start */ 24 | const initialState = { 25 | disabled: false, 26 | dropup: false, 27 | flip: false, 28 | highlightOnlyResult: false, 29 | minLength: 0, 30 | open: undefined, 31 | }; 32 | 33 | function reducer(state: State, { checked, name }: Action) { 34 | switch (name) { 35 | case 'minLength': 36 | return { 37 | ...state, 38 | [name]: checked ? 2 : 0, 39 | }; 40 | case 'open': 41 | return { 42 | ...state, 43 | [name]: checked ?? undefined, 44 | }; 45 | default: 46 | return { 47 | ...state, 48 | [name]: checked, 49 | }; 50 | break; 51 | } 52 | } 53 | 54 | function getCheckboxes({ 55 | disabled, 56 | dropup, 57 | flip, 58 | highlightOnlyResult, 59 | minLength, 60 | open, 61 | }: State) { 62 | return [ 63 | { checked: disabled, label: 'Disable the input', name: 'disabled' }, 64 | { checked: dropup, label: 'Dropup menu', name: 'dropup' }, 65 | { 66 | checked: flip, 67 | label: 'Flip the menu position when it reaches the viewport bounds', 68 | name: 'flip', 69 | }, 70 | { 71 | checked: !!minLength, 72 | label: 'Require minimum input before showing results (2 chars)', 73 | name: 'minLength', 74 | }, 75 | { 76 | checked: highlightOnlyResult, 77 | label: 'Highlight the only result', 78 | name: 'highlightOnlyResult', 79 | }, 80 | { checked: !!open, label: 'Force the menu to stay open', name: 'open' }, 81 | ]; 82 | } 83 | 84 | function BasicBehaviorsExample() { 85 | const [state, dispatch] = useReducer(reducer, initialState); 86 | 87 | function onChange(e: ChangeEvent) { 88 | const { checked, name } = e.target; 89 | 90 | dispatch({ 91 | checked, 92 | name: name as keyof State, 93 | }); 94 | } 95 | 96 | return ( 97 | <> 98 | 105 | 106 | {getCheckboxes(state).map((props) => ( 107 | 114 | ))} 115 | 116 | 117 | ); 118 | } 119 | /* example-end */ 120 | 121 | export default BasicBehaviorsExample; 122 | -------------------------------------------------------------------------------- /example/src/examples/BasicExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | import options from '../data'; 8 | 9 | /* example-start */ 10 | const BasicExample = () => { 11 | const [singleSelections, setSingleSelections] = useState([]); 12 | const [multiSelections, setMultiSelections] = useState([]); 13 | 14 | return ( 15 | <> 16 | 17 | Single Selection 18 | 26 | 27 | 28 | Multiple Selections 29 | 38 | 39 | 40 | ); 41 | }; 42 | /* example-end */ 43 | 44 | export default BasicExample; 45 | -------------------------------------------------------------------------------- /example/src/examples/CustomFilteringExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | import options, { Option } from '../data'; 8 | 9 | /* example-start */ 10 | const CustomFilteringExample = () => { 11 | const [filterBy, setFilterBy] = useState('callback'); 12 | 13 | const radios = [ 14 | { label: 'Use callback', value: 'callback' }, 15 | { label: 'Use data fields', value: 'fields' }, 16 | ]; 17 | 18 | const filterByCallback = (option: Option, props) => 19 | option.capital.toLowerCase().indexOf(props.text.toLowerCase()) !== -1 || 20 | option.name.toLowerCase().indexOf(props.text.toLowerCase()) !== -1; 21 | 22 | const filterByFields = ['capital', 'name']; 23 | 24 | return ( 25 | <> 26 | ( 33 |
34 | {option.name} 35 |
36 | Capital: {option.capital} 37 |
38 |
39 | )} 40 | /> 41 | 42 | {radios.map(({ label, value }) => ( 43 | setFilterBy(value)} 49 | type="radio" 50 | value={value} 51 | /> 52 | ))} 53 | 54 | 55 | ); 56 | }; 57 | /* example-end */ 58 | 59 | export default CustomFilteringExample; 60 | -------------------------------------------------------------------------------- /example/src/examples/CustomSelectionsExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | import { Typeahead } from 'react-bootstrap-typeahead'; 5 | 6 | /* example-start */ 7 | const CustomSelectionsExample = () => ( 8 | 16 | ); 17 | /* example-end */ 18 | 19 | export default CustomSelectionsExample; 20 | -------------------------------------------------------------------------------- /example/src/examples/FilteringExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | /* example-start */ 8 | const options = [ 9 | 'Warsaw', 10 | 'Kraków', 11 | 'Łódź', 12 | 'Wrocław', 13 | 'Poznań', 14 | 'Gdańsk', 15 | 'Szczecin', 16 | 'Bydgoszcz', 17 | 'Lublin', 18 | 'Katowice', 19 | 'Białystok', 20 | 'Gdynia', 21 | 'Częstochowa', 22 | 'Radom', 23 | 'Sosnowiec', 24 | 'Toruń', 25 | 'Kielce', 26 | 'Gliwice', 27 | 'Zabrze', 28 | 'Bytom', 29 | 'Olsztyn', 30 | 'Bielsko-Biała', 31 | 'Rzeszów', 32 | 'Ruda Śląska', 33 | 'Rybnik', 34 | ]; 35 | 36 | const FilteringExample = () => { 37 | const [caseSensitive, setCaseSensitive] = useState(false); 38 | const [ignoreDiacritics, setIgnoreDiacritics] = useState(true); 39 | 40 | return ( 41 | <> 42 | 49 | 50 | setCaseSensitive(e.target.checked)} 55 | type="checkbox" 56 | /> 57 | setIgnoreDiacritics(!e.target.checked)} 62 | type="checkbox" 63 | /> 64 | 65 | 66 | ); 67 | }; 68 | /* example-end */ 69 | 70 | export default FilteringExample; 71 | -------------------------------------------------------------------------------- /example/src/examples/FormExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import { sortBy } from 'lodash'; 4 | import React, { useState } from 'react'; 5 | import { Button, Form, InputGroup } from 'react-bootstrap'; 6 | import { Typeahead } from 'react-bootstrap-typeahead'; 7 | 8 | import options, { Option } from '../data'; 9 | 10 | /* example-start */ 11 | const getIndex = () => Math.floor(Math.random() * options.length); 12 | 13 | const FormExample = () => { 14 | const [index, setIndex] = useState(getIndex()); 15 | const [selected, setSelected] = useState([]); 16 | 17 | const state = options[index]; 18 | 19 | let isInvalid; 20 | let isValid; 21 | 22 | if (selected.length) { 23 | const isMatch = selected[0].name === state.name; 24 | 25 | isInvalid = !isMatch; 26 | isValid = isMatch; 27 | } 28 | 29 | return ( 30 | <> 31 | 32 | 33 | The capital of {state.name} is 34 | 44 | 52 | 53 | 54 | 55 | ); 56 | }; 57 | /* example-end */ 58 | 59 | export default FormExample; 60 | -------------------------------------------------------------------------------- /example/src/examples/InputSizeExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | import options from '../data'; 8 | 9 | /* example-start */ 10 | type Size = 'sm' | 'lg' | undefined; 11 | 12 | interface Radio { 13 | label: string; 14 | value: Size; 15 | } 16 | 17 | const radios: Radio[] = [ 18 | { label: 'Small', value: 'sm' }, 19 | { label: 'Default', value: undefined }, 20 | { label: 'Large', value: 'lg' }, 21 | ]; 22 | 23 | const InputSizeExample = () => { 24 | const [size, setSize] = useState(); 25 | 26 | return ( 27 | <> 28 | 35 | 36 | {radios.map(({ label, value }) => ( 37 | setSize(value)} 43 | type="radio" 44 | value={value} 45 | /> 46 | ))} 47 | 48 | 49 | ); 50 | }; 51 | /* example-end */ 52 | 53 | export default InputSizeExample; 54 | -------------------------------------------------------------------------------- /example/src/examples/LabelKeyExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved,import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | import { Typeahead } from 'react-bootstrap-typeahead'; 5 | 6 | /* example-start */ 7 | interface Option { 8 | firstName: string; 9 | lastName: string; 10 | } 11 | 12 | const options: Option[] = [ 13 | { firstName: 'Art', lastName: 'Blakey' }, 14 | { firstName: 'John', lastName: 'Coltrane' }, 15 | { firstName: 'Miles', lastName: 'Davis' }, 16 | { firstName: 'Herbie', lastName: 'Hancock' }, 17 | { firstName: 'Charlie', lastName: 'Parker' }, 18 | { firstName: 'Tony', lastName: 'Williams' }, 19 | ]; 20 | 21 | const LabelKeyExample = () => ( 22 | `${option.firstName} ${option.lastName}`} 25 | options={options} 26 | placeholder="Who's the coolest cat?" 27 | /> 28 | ); 29 | /* example-end */ 30 | 31 | export default LabelKeyExample; 32 | -------------------------------------------------------------------------------- /example/src/examples/MenuAlignExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | import options from '../data'; 8 | 9 | /* example-start */ 10 | const MenuAlignExample = () => { 11 | const [align, setAlign] = useState('justify'); 12 | 13 | const radios = [ 14 | { label: 'Justify (default)', value: 'justify' }, 15 | { label: 'Align left', value: 'left' }, 16 | { label: 'Align right', value: 'right' }, 17 | ]; 18 | 19 | return ( 20 | <> 21 | 28 | 29 | {radios.map(({ label, value }) => ( 30 | setAlign(value)} 36 | type="radio" 37 | value={value} 38 | /> 39 | ))} 40 | 41 | 42 | ); 43 | }; 44 | /* example-end */ 45 | 46 | export default MenuAlignExample; 47 | -------------------------------------------------------------------------------- /example/src/examples/PaginationExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved,no-console */ 2 | 3 | import { range } from 'lodash'; 4 | import React, { useState } from 'react'; 5 | import { Form } from 'react-bootstrap'; 6 | import { Typeahead } from 'react-bootstrap-typeahead'; 7 | 8 | /* example-start */ 9 | const options = range(0, 1000).map((o) => `Item ${o}`); 10 | 11 | const PaginationExample = () => { 12 | const [paginate, setPaginate] = useState(true); 13 | 14 | return ( 15 | <> 16 | console.log('Results paginated')} 19 | options={options} 20 | paginate={paginate} 21 | placeholder="Pick a number..." 22 | /> 23 | 24 | setPaginate(!!e.target.checked)} 29 | type="checkbox" 30 | /> 31 | 32 | 33 | ); 34 | }; 35 | /* example-end */ 36 | 37 | export default PaginationExample; 38 | -------------------------------------------------------------------------------- /example/src/examples/PositionFixedExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Form } from 'react-bootstrap'; 5 | import { Typeahead } from 'react-bootstrap-typeahead'; 6 | 7 | import options from '../data'; 8 | 9 | /* example-start */ 10 | const PositionFixedExample = () => { 11 | const [positionFixed, setPositionFixed] = useState(true); 12 | 13 | return ( 14 | <> 15 |
22 |
23 | 30 |
31 |
32 | 33 | setPositionFixed(e.target.checked)} 38 | type="checkbox" 39 | /> 40 | 41 | 42 | ); 43 | }; 44 | /* example-end */ 45 | 46 | export default PositionFixedExample; 47 | -------------------------------------------------------------------------------- /example/src/examples/PublicMethodsExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React, { useRef } from 'react'; 4 | import { 5 | Button as RBButton, 6 | ButtonProps, 7 | ButtonToolbar, 8 | } from 'react-bootstrap'; 9 | import { Typeahead } from 'react-bootstrap-typeahead'; 10 | 11 | import options from '../data'; 12 | 13 | const Button = (props: ButtonProps) => ( 14 | 15 | ); 16 | 17 | /* example-start */ 18 | const PublicMethodsExample = () => { 19 | const ref = useRef(null); 20 | 21 | return ( 22 | <> 23 | 32 | 33 | 34 | 35 | 42 | 43 | 44 | 45 | ); 46 | }; 47 | /* example-end */ 48 | 49 | export default PublicMethodsExample; 50 | -------------------------------------------------------------------------------- /example/src/examples/SelectionsExample.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved,no-console */ 2 | 3 | import React, { ChangeEvent } from 'react'; 4 | import { Typeahead } from 'react-bootstrap-typeahead'; 5 | 6 | import options from '../data'; 7 | 8 | /* example-start */ 9 | const SelectionsExample = () => ( 10 | ) => { 16 | console.log(text, e); 17 | }} 18 | options={options} 19 | placeholder="Choose a state..." 20 | /> 21 | ); 22 | /* example-end */ 23 | 24 | export default SelectionsExample; 25 | -------------------------------------------------------------------------------- /example/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { render } from 'react-dom'; 3 | 4 | import Page from './components/Page'; 5 | 6 | import AsyncSection from './sections/AsyncSection'; 7 | import BasicSection from './sections/BasicSection'; 8 | import BehaviorsSection from './sections/BehaviorsSection'; 9 | import CustomSelectionsSection from './sections/CustomSelectionsSection'; 10 | import FilteringSection from './sections/FilteringSection'; 11 | import PublicMethodsSection from './sections/PublicMethodsSection'; 12 | import RenderingSection from './sections/RenderingSection'; 13 | 14 | import '../../styles/Typeahead.scss'; 15 | import '../../styles/Typeahead.bs5.scss'; 16 | 17 | render( 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | , 29 | document.getElementById('root') 30 | ); 31 | -------------------------------------------------------------------------------- /example/src/sections/AsyncSection.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | 5 | import AsyncExample from '../examples/AsyncExample'; 6 | import AsyncExampleCode from '!raw-loader!../examples/AsyncExample'; 7 | 8 | import ExampleSection from '../components/ExampleSection'; 9 | import Markdown from '../components/Markdown'; 10 | import Section from '../components/Section'; 11 | 12 | interface AsyncSectionProps { 13 | title: string; 14 | } 15 | 16 | const AsyncSection = (props: AsyncSectionProps) => ( 17 |
18 | 19 | You can use the `AsyncTypeahead` component for asynchronous searches. It 20 | debounces user input and includes an optional query cache to avoid making 21 | the same request more than once in basic cases. 22 | 23 | 24 | 25 | 26 |
27 | ); 28 | 29 | export default AsyncSection; 30 | -------------------------------------------------------------------------------- /example/src/sections/BasicSection.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | 5 | import BasicExample from '../examples/BasicExample'; 6 | import BasicExampleCode from '!raw-loader!../examples/BasicExample'; 7 | 8 | import ExampleSection from '../components/ExampleSection'; 9 | import Markdown from '../components/Markdown'; 10 | import Section from '../components/Section'; 11 | 12 | interface BasicSectionProps { 13 | title: string; 14 | } 15 | 16 | const BasicSection = (props: BasicSectionProps) => ( 17 |
18 | 19 | The typeahead allows single-selection by default. Setting the `multiple` 20 | prop turns the component into a tokenizer, allowing multiple selections. 21 | 22 | 23 | 24 | 25 |
26 | ); 27 | 28 | export default BasicSection; 29 | -------------------------------------------------------------------------------- /example/src/sections/CustomSelectionsSection.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | 5 | import CustomSelectionsExample from '../examples/CustomSelectionsExample'; 6 | import CustomSelectionsExampleCode from '!raw-loader!../examples/CustomSelectionsExample'; 7 | 8 | import ExampleSection from '../components/ExampleSection'; 9 | import Markdown from '../components/Markdown'; 10 | import Section from '../components/Section'; 11 | 12 | interface CustomSelectionsProps { 13 | title: string; 14 | } 15 | 16 | const CustomSelections = (props: CustomSelectionsProps) => ( 17 |
18 | 19 | Setting the `allowNew` prop provides the ability to create new options for 20 | the data set. You can change the label displayed before the custom option 21 | in the menu by using the `newSelectionPrefix` prop. 22 | 23 | 24 | 25 | 26 |
27 | ); 28 | 29 | export default CustomSelections; 30 | -------------------------------------------------------------------------------- /example/src/sections/FilteringSection.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | 5 | import CustomFilteringExample from '../examples/CustomFilteringExample'; 6 | import FilteringExample from '../examples/FilteringExample'; 7 | import FilteringExampleCode from '!raw-loader!../examples/FilteringExample'; 8 | import CustomFilteringExampleCode from '!raw-loader!../examples/CustomFilteringExample'; 9 | 10 | import ExampleSection from '../components/ExampleSection'; 11 | import Markdown from '../components/Markdown'; 12 | import Section from '../components/Section'; 13 | import Title from '../components/Title'; 14 | 15 | interface FilteringSectionProps { 16 | title: string; 17 | } 18 | 19 | const FilteringSection = (props: FilteringSectionProps) => ( 20 |
21 | 22 | By default, the typeahead is not case-sensitive and ignores diacritical 23 | marks when filtering. You can change these behaviors using the 24 | `caseSensitive` and `ignoreDiacritics` props. 25 | 26 | 27 | 28 | 29 | Custom Filtering 30 | 31 | Using the `filterBy` prop, you can either specify your own callback or an 32 | array of fields on your data object by which to filter. 33 | 34 | 35 | 36 | 37 |
38 | ); 39 | 40 | export default FilteringSection; 41 | -------------------------------------------------------------------------------- /example/src/sections/PublicMethodsSection.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | 5 | import PublicMethodsExample from '../examples/PublicMethodsExample'; 6 | import PublicMethodsExampleCode from '!raw-loader!../examples/PublicMethodsExample'; 7 | 8 | import ExampleSection from '../components/ExampleSection'; 9 | import Markdown from '../components/Markdown'; 10 | import Section from '../components/Section'; 11 | 12 | interface PublicMethodsSectionProps { 13 | title: string; 14 | } 15 | 16 | const PublicMethodsSection = (props: PublicMethodsSectionProps) => ( 17 |
18 | 19 | The `clear`, `focus`, and `blur` methods are exposed for programmatic 20 | control of the typeahead. 21 | 22 | 23 | 24 | 25 |
26 | ); 27 | 28 | export default PublicMethodsSection; 29 | -------------------------------------------------------------------------------- /example/src/sections/RenderingSection.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable import/no-unresolved */ 2 | 3 | import React from 'react'; 4 | 5 | import LabelKeyExample from '../examples/LabelKeyExample'; 6 | import RenderingExample from '../examples/RenderingExample'; 7 | 8 | import LabelKeyExampleCode from '!raw-loader!../examples/LabelKeyExample'; 9 | import RenderingExampleCode from '!raw-loader!../examples/RenderingExample'; 10 | 11 | import ExampleSection from '../components/ExampleSection'; 12 | import Markdown from '../components/Markdown'; 13 | import Section from '../components/Section'; 14 | import Title from '../components/Title'; 15 | 16 | interface RenderingSectionProps { 17 | title: string; 18 | } 19 | 20 | const RenderingSection = (props: RenderingSectionProps) => ( 21 |
22 | 23 | You can customize how the typeahead looks and behaves by using the 24 | provided rendering hooks. 25 | 26 | 27 | 28 | 29 | LabelKey 30 | 31 | The `labelKey` prop accepts a callback allowing you to transform your data 32 | and return a compound string rather than just a single data field. 33 | 34 | 35 | 36 | 37 |
38 | ); 39 | 40 | export default RenderingSection; 41 | -------------------------------------------------------------------------------- /example/src/util/getIdFromTitle.ts: -------------------------------------------------------------------------------- 1 | export default (title: string) => 2 | title.toLocaleLowerCase().split(' ').join('-'); 3 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "allowJs": true, 4 | "baseUrl": "src", 5 | "checkJs": true, 6 | "declaration": true, 7 | "emitDeclarationOnly": false, 8 | "esModuleInterop": true, 9 | "forceConsistentCasingInFileNames": true, 10 | "isolatedModules": true, 11 | "jsx": "react", 12 | "module": "esnext", 13 | "moduleResolution": "node", 14 | "noEmit": false, 15 | "outDir": "types", 16 | "removeComments": true, 17 | "resolveJsonModule": true, 18 | "skipLibCheck": true, 19 | "strict": true, 20 | "target": "esnext", 21 | "types": ["./raw-loader.d.ts"] 22 | }, 23 | "include": ["**/*.ts", "**/*.tsx"], 24 | "exclude": ["node_modules", "public", "**/*.js"] 25 | } 26 | -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | const CircularDependencyPlugin = require('circular-dependency-plugin'); 4 | const TerserPlugin = require('terser-webpack-plugin'); 5 | 6 | module.exports = (env, argv) => { 7 | return { 8 | entry: path.join(__dirname, 'src/index.tsx'), 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.(ts|js)x?$/, 13 | exclude: /node_modules/, 14 | use: { 15 | loader: 'babel-loader', 16 | options: { 17 | presets: [ 18 | '@babel/preset-env', 19 | '@babel/preset-react', 20 | '@babel/preset-typescript', 21 | ], 22 | plugins: [ 23 | [ 24 | 'prismjs', 25 | { 26 | languages: ['jsx', 'tsx'], 27 | theme: 'okaidia', 28 | css: true, 29 | }, 30 | ], 31 | ], 32 | }, 33 | }, 34 | }, 35 | { 36 | test: /\.css$/, 37 | use: ['style-loader', 'css-loader'], 38 | }, 39 | { 40 | test: /\.scss$/, 41 | use: ['style-loader', 'css-loader', 'sass-loader'], 42 | }, 43 | ], 44 | }, 45 | optimization: { 46 | minimizer: [ 47 | new TerserPlugin({ 48 | extractComments: false, 49 | terserOptions: { 50 | output: { 51 | comments: false, 52 | }, 53 | }, 54 | }), 55 | ], 56 | }, 57 | output: { 58 | filename: 'package-example.js', 59 | path: path.resolve('.'), 60 | }, 61 | plugins: [ 62 | new CircularDependencyPlugin({ 63 | allowAsyncCycles: false, 64 | cwd: process.cwd(), 65 | exclude: /node_modules/, 66 | failOnError: true, 67 | }), 68 | ], 69 | resolve: { 70 | alias: { 71 | 'react-bootstrap-typeahead': path.resolve( 72 | __dirname, 73 | '..', 74 | 'src/index.ts' 75 | ), 76 | }, 77 | extensions: ['.ts', '.tsx', '.js'], 78 | }, 79 | stats: { 80 | warnings: argv.mode !== 'production', 81 | }, 82 | }; 83 | }; 84 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | coveragePathIgnorePatterns: [ 3 | '/node_modules/', 4 | '/src/propTypes', 5 | ], 6 | setupFilesAfterEnv: ['./jest.setup.js'], 7 | testEnvironment: 'jsdom', 8 | testMatch: ['**/?(*.)+(spec|test).[jt]s?(x)'], 9 | testPathIgnorePatterns: [ 10 | '/node_modules', 11 | '/cjs', 12 | '/es', 13 | '/example', 14 | '/types', 15 | ], 16 | }; 17 | -------------------------------------------------------------------------------- /jest.setup.js: -------------------------------------------------------------------------------- 1 | import { toHaveNoViolations } from 'jest-axe'; 2 | import '@testing-library/jest-dom/extend-expect'; 3 | 4 | expect.extend(toHaveNoViolations); 5 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys, @typescript-eslint/no-var-requires */ 2 | 3 | const babel = require('@rollup/plugin-babel').default; 4 | const commonjs = require('@rollup/plugin-commonjs'); 5 | const { nodeResolve } = require('@rollup/plugin-node-resolve'); 6 | const replace = require('@rollup/plugin-replace'); 7 | const { terser } = require('rollup-plugin-terser'); 8 | 9 | const { name } = require('./package.json'); 10 | 11 | const globals = { 12 | react: 'React', 13 | 'react-dom': 'ReactDOM', 14 | }; 15 | 16 | const extensions = ['.ts', '.tsx', '.js', '.jsx']; 17 | 18 | const getUmdConfig = (isProd) => ({ 19 | input: './src/index.ts', 20 | output: { 21 | file: `./dist/${name}${isProd ? '.min' : ''}.js`, 22 | format: 'umd', 23 | globals, 24 | name: 'ReactBootstrapTypeahead', 25 | }, 26 | external: Object.keys(globals), 27 | plugins: [ 28 | nodeResolve({ 29 | extensions, 30 | }), 31 | commonjs({ 32 | include: /node_modules/, 33 | }), 34 | babel({ 35 | babelHelpers: 'bundled', 36 | exclude: /node_modules/, 37 | extensions, 38 | }), 39 | replace({ 40 | 'process.env.NODE_ENV': JSON.stringify( 41 | isProd ? 'production' : 'development' 42 | ), 43 | preventAssignment: true, 44 | }), 45 | isProd ? terser() : null, 46 | ], 47 | }); 48 | 49 | module.exports = [false, true].map(getUmdConfig); 50 | -------------------------------------------------------------------------------- /scripts/buildCSS.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* eslint-disable import/no-extraneous-dependencies */ 4 | /* eslint-disable no-console */ 5 | /* eslint-disable @typescript-eslint/no-var-requires */ 6 | 7 | const chalk = require('chalk'); 8 | const fs = require('fs'); 9 | const path = require('path'); 10 | const sass = require('sass'); 11 | 12 | const ROOT = path.join(__dirname, '..'); 13 | const OUT_DIR = path.join(ROOT, 'css'); 14 | const STYLES_DIR = path.join(ROOT, 'styles'); 15 | 16 | console.log(chalk.cyan('Building CSS files...\n')); 17 | 18 | // Create the output directory if it doesn't exist. 19 | if (!fs.existsSync(OUT_DIR)) { 20 | fs.mkdirSync(OUT_DIR); 21 | } 22 | 23 | fs.readdirSync(STYLES_DIR).forEach((filename) => { 24 | const file = path.join(STYLES_DIR, filename); 25 | 26 | // Include the .scss files in the package by simply copying them over. 27 | fs.copyFileSync(file, path.join(OUT_DIR, filename)); 28 | 29 | // Output both expanded and minified versions. 30 | ['compressed', 'expanded'].forEach((style) => { 31 | // Get the base filename. 32 | let name = filename.replace('.scss', ''); 33 | if (style === 'compressed') { 34 | // Denote minified CSS. 35 | name += '.min'; 36 | } 37 | 38 | const result = sass.compile(file, { style }); 39 | 40 | fs.writeFileSync(path.join(OUT_DIR, `${name}.css`), result.css); 41 | }); 42 | }); 43 | 44 | console.log(chalk.cyan('Done.\n')); 45 | -------------------------------------------------------------------------------- /scripts/buildModules.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* eslint-disable @typescript-eslint/no-var-requires */ 4 | /* eslint-disable import/no-extraneous-dependencies */ 5 | /* eslint-disable no-console */ 6 | 7 | const chalk = require('chalk'); 8 | const execa = require('execa'); 9 | const path = require('path'); 10 | 11 | const shell = (cmd) => 12 | execa(cmd, { 13 | shell: true, 14 | stdio: ['pipe', 'pipe', 'inherit'], 15 | }); 16 | 17 | const srcRoot = path.join(__dirname, '../src'); 18 | const start = Date.now(); 19 | 20 | function buildModules() { 21 | const commands = []; 22 | ['cjs', 'es'].forEach((env) => { 23 | commands.push( 24 | shell( 25 | `yarn babel ${srcRoot} -x ".ts,.tsx,.js,.jsx" --out-dir ${env} --env-name "${env}"` 26 | ) 27 | ); 28 | }); 29 | return Promise.all(commands); 30 | } 31 | 32 | Promise.resolve() 33 | .then(() => { 34 | console.log(chalk.cyan('Transpiling modules...\n')); 35 | }) 36 | .then(buildModules) 37 | .then(() => { 38 | const seconds = (Date.now() - start) / 1000; 39 | console.log(chalk.green(`Finished building modules in ${seconds}s\n`)); 40 | }); 41 | -------------------------------------------------------------------------------- /scripts/deployExample.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | /* eslint-disable import/no-extraneous-dependencies */ 4 | /* eslint-disable no-console */ 5 | /* eslint-disable @typescript-eslint/no-var-requires */ 6 | 7 | const ghpages = require('gh-pages'); 8 | const { version } = require('../package.json'); 9 | 10 | /** 11 | * Don't publish pre-release versions, as denoted by the presence of a hyphen 12 | * in the version number, (eg: 3.0.0-rc.1). 13 | * 14 | * See: https://semver.org/#spec-item-9 15 | */ 16 | if (version.split('-').length === 1) { 17 | ghpages.publish('example', { 18 | message: `v${version}`, 19 | src: '{index.html,package-example.js,public/*}', 20 | }); 21 | } else { 22 | console.log( 23 | `Skipped deploying examples for pre-release version: v${version}` 24 | ); 25 | } 26 | -------------------------------------------------------------------------------- /src/behaviors/item.tsx: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types'; 2 | import React, { 3 | ComponentType, 4 | HTMLProps, 5 | MouseEvent, 6 | MouseEventHandler, 7 | useCallback, 8 | useEffect, 9 | useRef, 10 | } from 'react'; 11 | import scrollIntoView from 'scroll-into-view-if-needed'; 12 | 13 | import { useTypeaheadContext } from '../core/Context'; 14 | import { 15 | getDisplayName, 16 | getMenuItemId, 17 | preventInputBlur, 18 | warn, 19 | } from '../utils'; 20 | 21 | import { optionType } from '../propTypes'; 22 | import { Option } from '../types'; 23 | 24 | const propTypes = { 25 | option: optionType.isRequired, 26 | position: PropTypes.number, 27 | }; 28 | 29 | export interface UseItemProps extends HTMLProps { 30 | onClick?: MouseEventHandler; 31 | option: Option; 32 | position: number; 33 | } 34 | 35 | export function useItem({ 36 | label, 37 | onClick, 38 | option, 39 | position, 40 | ...props 41 | }: UseItemProps) { 42 | const { 43 | activeIndex, 44 | id, 45 | isOnlyResult, 46 | onActiveItemChange, 47 | onInitialItemChange, 48 | onMenuItemClick, 49 | setItem, 50 | } = useTypeaheadContext(); 51 | 52 | const itemRef = useRef(null); 53 | 54 | useEffect(() => { 55 | if (position === 0) { 56 | onInitialItemChange(option); 57 | } 58 | }); 59 | 60 | useEffect(() => { 61 | if (position === activeIndex) { 62 | onActiveItemChange(option); 63 | 64 | // Automatically scroll the menu as the user keys through it. 65 | const node = itemRef.current; 66 | 67 | node && 68 | scrollIntoView(node, { 69 | boundary: node.parentNode as Element, 70 | scrollMode: 'if-needed', 71 | }); 72 | } 73 | }, [activeIndex, onActiveItemChange, option, position]); 74 | 75 | const handleClick = useCallback( 76 | (e: MouseEvent) => { 77 | onMenuItemClick(option, e); 78 | onClick && onClick(e); 79 | }, 80 | [onClick, onMenuItemClick, option] 81 | ); 82 | 83 | const active = isOnlyResult || activeIndex === position; 84 | 85 | // Update the item's position in the item stack. 86 | setItem(option, position); 87 | 88 | return { 89 | ...props, 90 | active, 91 | 'aria-label': label, 92 | 'aria-selected': active, 93 | id: getMenuItemId(id, position), 94 | onClick: handleClick, 95 | onMouseDown: preventInputBlur, 96 | ref: itemRef, 97 | role: 'option', 98 | }; 99 | } 100 | 101 | /* istanbul ignore next */ 102 | export function withItem>( 103 | Component: ComponentType 104 | ) { 105 | warn( 106 | false, 107 | 'Warning: `withItem` is deprecated and will be removed in the next ' + 108 | 'major version. Use `useItem` instead.' 109 | ); 110 | 111 | const WrappedMenuItem = (props: T) => ( 112 | 113 | ); 114 | 115 | WrappedMenuItem.displayName = `withItem(${getDisplayName(Component)})`; 116 | WrappedMenuItem.propTypes = propTypes; 117 | 118 | return WrappedMenuItem; 119 | } 120 | -------------------------------------------------------------------------------- /src/behaviors/token.tsx: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types'; 2 | import React, { 3 | ComponentType, 4 | FocusEvent, 5 | FocusEventHandler, 6 | HTMLProps, 7 | KeyboardEvent, 8 | MouseEvent, 9 | MouseEventHandler, 10 | useState, 11 | } from 'react'; 12 | 13 | import { useRootClose } from '../components/RootClose'; 14 | import { getDisplayName, isFunction, warn } from '../utils'; 15 | 16 | import { optionType } from '../propTypes'; 17 | import { Option, OptionHandler } from '../types'; 18 | 19 | export interface UseTokenProps extends Omit, 'onBlur'> { 20 | // `onBlur` is typed more generically because it's passed to `useRootClose`, 21 | // which passes a generic event to the callback. 22 | onBlur?: (event: Event) => void; 23 | onClick?: MouseEventHandler; 24 | onFocus?: FocusEventHandler; 25 | onRemove?: OptionHandler; 26 | option: Option; 27 | } 28 | 29 | const propTypes = { 30 | onBlur: PropTypes.func, 31 | onClick: PropTypes.func, 32 | onFocus: PropTypes.func, 33 | onRemove: PropTypes.func, 34 | option: optionType.isRequired, 35 | }; 36 | 37 | export function useToken({ 38 | onBlur, 39 | onClick, 40 | onFocus, 41 | onRemove, 42 | option, 43 | ...props 44 | }: UseTokenProps) { 45 | const [active, setActive] = useState(false); 46 | 47 | const handleBlur = (e: Event) => { 48 | setActive(false); 49 | onBlur && onBlur(e); 50 | }; 51 | 52 | const handleClick = (e: MouseEvent) => { 53 | setActive(true); 54 | onClick && onClick(e); 55 | }; 56 | 57 | const handleFocus = (e: FocusEvent) => { 58 | setActive(true); 59 | onFocus && onFocus(e); 60 | }; 61 | 62 | const handleRemove = () => { 63 | onRemove && onRemove(option); 64 | }; 65 | 66 | const handleKeyDown = (e: KeyboardEvent) => { 67 | if (e.key === 'Backspace' && active) { 68 | // Prevent browser from going back. 69 | e.preventDefault(); 70 | handleRemove(); 71 | } 72 | }; 73 | 74 | const attachRef = useRootClose(handleBlur, { 75 | ...props, 76 | disabled: !active, 77 | }); 78 | 79 | return { 80 | active, 81 | onBlur: handleBlur, 82 | onClick: handleClick, 83 | onFocus: handleFocus, 84 | onKeyDown: handleKeyDown, 85 | onRemove: isFunction(onRemove) ? handleRemove : undefined, 86 | ref: attachRef, 87 | }; 88 | } 89 | 90 | /* istanbul ignore next */ 91 | export function withToken>( 92 | Component: ComponentType 93 | ) { 94 | warn( 95 | false, 96 | 'Warning: `withToken` is deprecated and will be removed in the next ' + 97 | 'major version. Use `useToken` instead.' 98 | ); 99 | 100 | const displayName = `withToken(${getDisplayName(Component)})`; 101 | 102 | const WrappedToken = (props: T) => ( 103 | 104 | ); 105 | 106 | WrappedToken.displayName = displayName; 107 | WrappedToken.propTypes = propTypes; 108 | 109 | return WrappedToken; 110 | } 111 | -------------------------------------------------------------------------------- /src/components/AsyncTypeahead/AsyncTypeahead.tsx: -------------------------------------------------------------------------------- 1 | import React, { forwardRef } from 'react'; 2 | import { useAsync, UseAsyncProps } from '../../behaviors/async'; 3 | import TypeaheadComponent from '../Typeahead'; 4 | import Typeahead from '../../core/Typeahead'; 5 | 6 | const AsyncTypeahead = forwardRef((props, ref) => ( 7 | 8 | )); 9 | 10 | export default AsyncTypeahead; 11 | -------------------------------------------------------------------------------- /src/components/AsyncTypeahead/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './AsyncTypeahead'; 2 | export * from './AsyncTypeahead'; 3 | -------------------------------------------------------------------------------- /src/components/ClearButton/ClearButton.stories.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,import/no-extraneous-dependencies */ 2 | 3 | import React from 'react'; 4 | import { Meta, Story } from '@storybook/react'; 5 | 6 | import ClearButton, { ClearButtonProps } from './ClearButton'; 7 | 8 | export default { 9 | title: 'Components/ClearButton', 10 | component: ClearButton, 11 | } as Meta; 12 | 13 | const Template: Story = (args) => ; 14 | 15 | export const Default = Template.bind({}); 16 | Default.args = {}; 17 | 18 | export const Large = Template.bind({}); 19 | Large.args = { 20 | size: 'lg', 21 | }; 22 | -------------------------------------------------------------------------------- /src/components/ClearButton/ClearButton.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import * as stories from './ClearButton.stories'; 4 | 5 | import { 6 | composeStories, 7 | fireEvent, 8 | generateSnapshots, 9 | render, 10 | screen, 11 | userEvent, 12 | } from '../../tests/helpers'; 13 | 14 | const { Default, Large } = composeStories(stories); 15 | 16 | describe('', () => { 17 | generateSnapshots(stories); 18 | 19 | it('renders a default clear button', () => { 20 | render(); 21 | expect(screen.getByRole('button').className).toBe( 22 | 'close btn-close rbt-close' 23 | ); 24 | }); 25 | 26 | it('renders a large clear button', () => { 27 | render(); 28 | expect(screen.getByRole('button').className).toContain('rbt-close-lg'); 29 | }); 30 | 31 | it('registers a click', async () => { 32 | const user = userEvent.setup(); 33 | const onClick = jest.fn(); 34 | render(); 35 | 36 | const button = screen.getByRole('button'); 37 | await user.click(button); 38 | 39 | expect(onClick).toHaveBeenCalledTimes(1); 40 | }); 41 | 42 | it('prevents the default backspace behavior', () => { 43 | const onKeyDown = jest.fn(); 44 | let isDefault; 45 | 46 | render(); 47 | 48 | const button = screen.getByRole('button'); 49 | 50 | isDefault = fireEvent.keyDown(button, { 51 | key: 'Backspace', 52 | }); 53 | 54 | expect(onKeyDown).toHaveBeenCalledTimes(1); 55 | expect(isDefault).toBe(false); 56 | 57 | isDefault = fireEvent.keyDown(button, { 58 | key: 'Enter', 59 | }); 60 | 61 | expect(onKeyDown).toHaveBeenCalledTimes(2); 62 | expect(isDefault).toBe(true); 63 | }); 64 | }); 65 | -------------------------------------------------------------------------------- /src/components/ClearButton/ClearButton.tsx: -------------------------------------------------------------------------------- 1 | import cx from 'classnames'; 2 | import PropTypes from 'prop-types'; 3 | import React, { HTMLProps, KeyboardEvent, MouseEvent } from 'react'; 4 | 5 | import type { Size } from '../../types'; 6 | import { isSizeLarge, isSizeSmall } from '../../utils'; 7 | 8 | import { sizeType } from '../../propTypes'; 9 | 10 | const propTypes = { 11 | label: PropTypes.string, 12 | onClick: PropTypes.func, 13 | onKeyDown: PropTypes.func, 14 | size: sizeType, 15 | }; 16 | 17 | export interface ClearButtonProps 18 | extends Omit, 'size'> { 19 | label?: string; 20 | size?: Size; 21 | } 22 | 23 | /** 24 | * ClearButton 25 | * 26 | * http://getbootstrap.com/css/#helper-classes-close 27 | */ 28 | const ClearButton = ({ 29 | className, 30 | label = 'Clear', 31 | onClick, 32 | onKeyDown, 33 | size, 34 | ...props 35 | }: ClearButtonProps): JSX.Element => ( 36 | 66 | ); 67 | 68 | ClearButton.propTypes = propTypes; 69 | 70 | export default ClearButton; 71 | -------------------------------------------------------------------------------- /src/components/ClearButton/__snapshots__/ClearButton.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` Default story renders snapshot 1`] = ` 4 | 21 | `; 22 | 23 | exports[` Large story renders snapshot 1`] = ` 24 | 41 | `; 42 | -------------------------------------------------------------------------------- /src/components/ClearButton/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './ClearButton'; 2 | export * from './ClearButton'; 3 | -------------------------------------------------------------------------------- /src/components/Highlighter/Highlighter.stories.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,import/no-extraneous-dependencies */ 2 | 3 | import React from 'react'; 4 | import { Story, Meta } from '@storybook/react'; 5 | 6 | import Highlighter, { HighlighterProps } from './Highlighter'; 7 | 8 | export default { 9 | title: 'Components/Highlighter', 10 | component: Highlighter, 11 | } as Meta; 12 | 13 | const Template: Story = (args) => ; 14 | 15 | const children = 'This is a sentence.'; 16 | 17 | export const Default = Template.bind({}); 18 | Default.args = { 19 | children, 20 | search: '', 21 | }; 22 | 23 | export const Highlighted = Template.bind({}); 24 | Highlighted.args = { 25 | children, 26 | search: 'sent', 27 | }; 28 | -------------------------------------------------------------------------------- /src/components/Highlighter/Highlighter.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import Highlighter from './Highlighter'; 4 | import { render } from '../../tests/helpers'; 5 | 6 | function getMatches(nodes: NodeListOf) { 7 | const arr = Array.from(nodes) as Element[]; 8 | return arr.filter((node) => node.tagName === 'MARK'); 9 | } 10 | 11 | describe('', () => { 12 | it('does not highlight text when there is no search string', () => { 13 | const { container } = render( 14 | California 15 | ); 16 | 17 | const nodes = container.childNodes; 18 | expect(nodes).toHaveLength(1); 19 | expect(nodes.item(0)).toHaveTextContent('California'); 20 | expect(getMatches(nodes)).toHaveLength(0); 21 | }); 22 | 23 | it('does not highlight text when there is no match', () => { 24 | const { container } = render( 25 | California 26 | ); 27 | 28 | expect(getMatches(container.childNodes)).toHaveLength(0); 29 | }); 30 | 31 | it('handles an empty child string', () => { 32 | // Explicitly set a string as the child. 33 | // eslint-disable-next-line react/jsx-curly-brace-presence 34 | const { container } = render({''}); 35 | 36 | expect(container.childNodes.item(0)).toHaveTextContent(''); 37 | }); 38 | 39 | it('highlights text within a string', () => { 40 | const { container } = render( 41 | California 42 | ); 43 | 44 | const nodes = container.childNodes; 45 | const matches = getMatches(nodes); 46 | 47 | // Output: [Cal, i, forn, i, a] 48 | expect(nodes.length).toBe(5); 49 | expect(nodes.item(0)).toHaveTextContent('Cal'); 50 | 51 | expect(matches.length).toBe(2); 52 | expect(matches[0]).toHaveTextContent('i'); 53 | expect(matches[0]).toHaveClass('rbt-highlight-text'); 54 | }); 55 | 56 | it('highlights text at the beginning of a string', () => { 57 | const { container } = render( 58 | California 59 | ); 60 | 61 | const nodes = container.childNodes; 62 | const matches = getMatches(nodes); 63 | 64 | // Output: [Cal, ifornia] 65 | expect(nodes).toHaveLength(2); 66 | expect(nodes.item(0)).toHaveTextContent('Cal'); 67 | 68 | expect(matches).toHaveLength(1); 69 | expect(matches[0]).toHaveTextContent('Cal'); 70 | }); 71 | 72 | it('adds custom classnames to the highlighted children', () => { 73 | const { container } = render( 74 | 75 | California 76 | 77 | ); 78 | 79 | expect(getMatches(container.childNodes)[0]).toHaveClass('foo'); 80 | }); 81 | }); 82 | -------------------------------------------------------------------------------- /src/components/Highlighter/Highlighter.tsx: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types'; 2 | import React from 'react'; 3 | 4 | import { getMatchBounds } from '../../utils'; 5 | 6 | const propTypes = { 7 | children: PropTypes.string.isRequired, 8 | highlightClassName: PropTypes.string, 9 | search: PropTypes.string.isRequired, 10 | }; 11 | 12 | export interface HighlighterProps { 13 | children: string; 14 | highlightClassName?: string; 15 | search: string; 16 | } 17 | 18 | /** 19 | * Stripped-down version of https://github.com/helior/react-highlighter 20 | * 21 | * Results are already filtered by the time the component is used internally so 22 | * we can safely ignore case and diacritical marks for the purposes of matching. 23 | */ 24 | const Highlighter = ({ 25 | children, 26 | highlightClassName = 'rbt-highlight-text', 27 | search, 28 | }: HighlighterProps) => { 29 | if (!search || !children) { 30 | return <>{children}; 31 | } 32 | 33 | let matchCount = 0; 34 | let remaining = children; 35 | 36 | const highlighterChildren = []; 37 | 38 | while (remaining) { 39 | const bounds = getMatchBounds(remaining, search); 40 | 41 | // No match anywhere in the remaining string, stop. 42 | if (!bounds) { 43 | highlighterChildren.push(remaining); 44 | break; 45 | } 46 | 47 | // Capture the string that leads up to a match. 48 | const nonMatch = remaining.slice(0, bounds.start); 49 | if (nonMatch) { 50 | highlighterChildren.push(nonMatch); 51 | } 52 | 53 | // Capture the matching string. 54 | const match = remaining.slice(bounds.start, bounds.end); 55 | highlighterChildren.push( 56 | 57 | {match} 58 | 59 | ); 60 | matchCount += 1; 61 | 62 | // And if there's anything left over, continue the loop. 63 | remaining = remaining.slice(bounds.end); 64 | } 65 | 66 | return <>{highlighterChildren}; 67 | }; 68 | 69 | Highlighter.propTypes = propTypes; 70 | 71 | export default Highlighter; 72 | -------------------------------------------------------------------------------- /src/components/Highlighter/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Highlighter'; 2 | export * from './Highlighter'; 3 | -------------------------------------------------------------------------------- /src/components/Hint/Hint.stories.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,import/no-extraneous-dependencies */ 2 | 3 | import React, { useState } from 'react'; 4 | import { Story, Meta } from '@storybook/react'; 5 | 6 | import Hint, { HintProps } from './Hint'; 7 | import { HintProvider, noop } from '../../tests/helpers'; 8 | 9 | export default { 10 | title: 'Components/Hint', 11 | component: Hint, 12 | } as Meta; 13 | 14 | const Template: Story = (args) => { 15 | const [inputNode, setInputNode] = useState(null); 16 | 17 | return ( 18 | 19 | 20 | 26 | 27 | 28 | ); 29 | }; 30 | 31 | export const Default = Template.bind({}); 32 | Default.args = {}; 33 | -------------------------------------------------------------------------------- /src/components/Hint/Hint.test.tsx: -------------------------------------------------------------------------------- 1 | import * as stories from './Hint.stories'; 2 | import { generateSnapshots } from '../../tests/helpers'; 3 | 4 | describe('', () => { 5 | generateSnapshots(stories); 6 | }); 7 | -------------------------------------------------------------------------------- /src/components/Hint/__snapshots__/Hint.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` Default story renders snapshot 1`] = ` 4 |
7 | 11 | 19 |
20 | `; 21 | -------------------------------------------------------------------------------- /src/components/Hint/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Hint'; 2 | export * from './Hint'; 3 | -------------------------------------------------------------------------------- /src/components/Input/Input.stories.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,import/no-extraneous-dependencies */ 2 | 3 | import React from 'react'; 4 | import { Story, Meta } from '@storybook/react'; 5 | 6 | import Input, { InputProps } from './Input'; 7 | 8 | export default { 9 | title: 'Components/Input', 10 | component: Input, 11 | } as Meta; 12 | 13 | const Template: Story = (args) => ; 14 | 15 | export const Default = Template.bind({}); 16 | Default.args = {}; 17 | -------------------------------------------------------------------------------- /src/components/Input/Input.test.tsx: -------------------------------------------------------------------------------- 1 | import * as stories from './Input.stories'; 2 | import { generateSnapshots } from '../../tests/helpers'; 3 | 4 | describe('', () => { 5 | generateSnapshots(stories); 6 | }); 7 | -------------------------------------------------------------------------------- /src/components/Input/Input.tsx: -------------------------------------------------------------------------------- 1 | import cx from 'classnames'; 2 | import React, { forwardRef, HTMLAttributes } from 'react'; 3 | 4 | export type InputProps = HTMLAttributes; 5 | 6 | const Input = forwardRef((props, ref) => ( 7 | 12 | )); 13 | 14 | export default Input; 15 | -------------------------------------------------------------------------------- /src/components/Input/__snapshots__/Input.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` Default story renders snapshot 1`] = ` 4 | 7 | `; 8 | -------------------------------------------------------------------------------- /src/components/Input/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Input'; 2 | export * from './Input'; 3 | -------------------------------------------------------------------------------- /src/components/Loader/Loader.stories.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,import/no-extraneous-dependencies */ 2 | 3 | import React from 'react'; 4 | import { Story, Meta } from '@storybook/react'; 5 | 6 | import Loader, { LoaderProps } from './Loader'; 7 | 8 | export default { 9 | title: 'Components/Loader', 10 | component: Loader, 11 | } as Meta; 12 | 13 | const Template: Story = (args) => ; 14 | 15 | export const Default = Template.bind({}); 16 | Default.args = {}; 17 | -------------------------------------------------------------------------------- /src/components/Loader/Loader.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import * as stories from './Loader.stories'; 4 | 5 | import { 6 | composeStories, 7 | generateSnapshots, 8 | render, 9 | screen, 10 | } from '../../tests/helpers'; 11 | 12 | const { Default } = composeStories(stories); 13 | 14 | describe('', () => { 15 | generateSnapshots(stories); 16 | 17 | it('renders a loading indicator', () => { 18 | render(); 19 | 20 | expect(screen.getByRole('status')).toHaveClass( 21 | 'rbt-loader spinner-border spinner-border-sm' 22 | ); 23 | expect(screen.getByText('Loading...')).toBeTruthy(); 24 | }); 25 | 26 | it('renders a custom label for accessibility', () => { 27 | render(); 28 | expect(screen.getByText('Waiting...')).toBeTruthy(); 29 | }); 30 | }); 31 | -------------------------------------------------------------------------------- /src/components/Loader/Loader.tsx: -------------------------------------------------------------------------------- 1 | import PropTypes from 'prop-types'; 2 | import React from 'react'; 3 | 4 | const propTypes = { 5 | label: PropTypes.string, 6 | }; 7 | 8 | export interface LoaderProps { 9 | label?: string; 10 | } 11 | 12 | const Loader = ({ label = 'Loading...' }: LoaderProps) => ( 13 |
14 | {label} 15 |
16 | ); 17 | 18 | Loader.propTypes = propTypes; 19 | 20 | export default Loader; 21 | -------------------------------------------------------------------------------- /src/components/Loader/__snapshots__/Loader.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` Default story renders snapshot 1`] = ` 4 |
8 | 11 | Loading... 12 | 13 |
14 | `; 15 | -------------------------------------------------------------------------------- /src/components/Loader/index.ts: -------------------------------------------------------------------------------- 1 | export { default } from './Loader'; 2 | export * from './Loader'; 3 | -------------------------------------------------------------------------------- /src/components/Menu/Menu.stories.tsx: -------------------------------------------------------------------------------- 1 | /* eslint-disable sort-keys,import/no-extraneous-dependencies */ 2 | 3 | import React from 'react'; 4 | import { Story, Meta } from '@storybook/react'; 5 | 6 | import Menu, { MenuProps } from './Menu'; 7 | import MenuItem from '../MenuItem'; 8 | 9 | const options = [{ label: 'Item 1' }, { label: 'Item 2' }, { label: 'Item 3' }]; 10 | 11 | // TODO: Caused by `isRequiredForA11y` validator. 12 | // @ts-ignore 13 | export default { 14 | title: 'Components/Menu', 15 | component: Menu, 16 | } as Meta; 17 | 18 | const children = options.map((o, idx) => ( 19 | 20 | {o.label} 21 | 22 | )); 23 | 24 | const Template: Story = (args) => ( 25 | 32 | ); 33 | 34 | export const Default = Template.bind({}); 35 | Default.args = { 36 | children, 37 | id: 'default-menu', 38 | }; 39 | 40 | export const Empty = Template.bind({}); 41 | Empty.args = { 42 | id: 'empty-menu', 43 | }; 44 | 45 | export const HeaderAndDivider = Template.bind({}); 46 | HeaderAndDivider.args = { 47 | children: ( 48 | <> 49 | This is a menu header 50 | 51 | 52 | {options[0].label} 53 | 54 | 55 | ), 56 | id: 'header-and-divider', 57 | }; 58 | -------------------------------------------------------------------------------- /src/components/Menu/Menu.test.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | import * as stories from './Menu.stories'; 4 | 5 | import { 6 | composeStories, 7 | fireEvent, 8 | getItems, 9 | getMenu, 10 | generateSnapshots, 11 | render, 12 | screen, 13 | } from '../../tests/helpers'; 14 | 15 | const { Default, Empty, HeaderAndDivider } = composeStories(stories); 16 | 17 | describe('', () => { 18 | generateSnapshots(stories); 19 | 20 | it('renders a basic menu with menu items', () => { 21 | render(); 22 | 23 | expect(getMenu()).toHaveClass('rbt-menu dropdown-menu'); 24 | expect(getItems()).toHaveLength(3); 25 | }); 26 | 27 | it('sets the maxHeight and other styles', () => { 28 | render(); 29 | 30 | const menu = getMenu(); 31 | expect(menu).toHaveStyle('background-color: red'); 32 | expect(menu).toHaveStyle('max-height: 100px'); 33 | }); 34 | 35 | it('renders an empty label when there are no children', () => { 36 | const emptyLabel = 'No matches.'; 37 | render(); 38 | 39 | const items = getItems(); 40 | expect(items).toHaveLength(1); 41 | expect(items[0]).toHaveClass('disabled'); 42 | expect(items[0]).toHaveTextContent(emptyLabel); 43 | }); 44 | 45 | it('adds an aria-label attribute to the menu', () => { 46 | render(); 47 | expect(getMenu()).toHaveAttribute('aria-label', 'custom-label'); 48 | }); 49 | 50 | it('prevents the input from blurring on mousedown', () => { 51 | render(); 52 | 53 | // `false` means e.preventDefault was called. 54 | expect(fireEvent.mouseDown(screen.getByRole('listbox'))).toBe(false); 55 | }); 56 | 57 | it('checks the menu header and divider', () => { 58 | render(); 59 | 60 | const header = screen.getByRole('heading'); 61 | expect(header.tagName).toBe('DIV'); 62 | expect(header).toHaveClass('dropdown-header'); 63 | expect(header).toHaveTextContent('This is a menu header'); 64 | 65 | const divider = screen.getByRole('separator'); 66 | expect(divider.tagName).toBe('DIV'); 67 | expect(divider).toHaveClass('dropdown-divider'); 68 | }); 69 | }); 70 | -------------------------------------------------------------------------------- /src/components/Menu/Menu.tsx: -------------------------------------------------------------------------------- 1 | import cx from 'classnames'; 2 | import PropTypes from 'prop-types'; 3 | import React, { Children, HTMLProps, ReactNode, Ref } from 'react'; 4 | 5 | import { BaseMenuItem } from '../MenuItem'; 6 | 7 | import { preventInputBlur } from '../../utils'; 8 | import { checkPropType, isRequiredForA11y } from '../../propTypes'; 9 | 10 | const MenuDivider = () =>
; 11 | 12 | const MenuHeader = (props: HTMLProps) => ( 13 | // eslint-disable-next-line jsx-a11y/role-has-required-aria-props 14 |
15 | ); 16 | 17 | const propTypes = { 18 | 'aria-label': PropTypes.string, 19 | /** 20 | * Message to display in the menu if there are no valid results. 21 | */ 22 | emptyLabel: PropTypes.node, 23 | /** 24 | * Needed for accessibility. 25 | */ 26 | id: checkPropType( 27 | PropTypes.oneOfType([PropTypes.number, PropTypes.string]), 28 | isRequiredForA11y 29 | ), 30 | /** 31 | * Maximum height of the dropdown menu. 32 | */ 33 | maxHeight: PropTypes.string, 34 | }; 35 | 36 | export interface MenuProps extends HTMLProps { 37 | emptyLabel?: ReactNode; 38 | innerRef?: Ref; 39 | maxHeight?: string; 40 | } 41 | 42 | /** 43 | * Menu component that handles empty state when passed a set of results. 44 | */ 45 | const Menu = ({ 46 | emptyLabel = 'No matches found.', 47 | innerRef, 48 | maxHeight = '300px', 49 | style, 50 | ...props 51 | }: MenuProps) => { 52 | const children = 53 | Children.count(props.children) === 0 ? ( 54 | 55 | {emptyLabel} 56 | 57 | ) : ( 58 | props.children 59 | ); 60 | 61 | return ( 62 | /* eslint-disable jsx-a11y/interactive-supports-focus */ 63 |
79 | {children} 80 |
81 | /* eslint-enable jsx-a11y/interactive-supports-focus */ 82 | ); 83 | }; 84 | 85 | Menu.propTypes = propTypes; 86 | Menu.Divider = MenuDivider; 87 | Menu.Header = MenuHeader; 88 | 89 | export default Menu; 90 | -------------------------------------------------------------------------------- /src/components/Menu/__snapshots__/Menu.test.tsx.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[` Default story renders snapshot 1`] = ` 4 | 39 | `; 40 | 41 | exports[` Empty story renders snapshot 1`] = ` 42 | 57 | `; 58 | 59 | exports[` HeaderAndDivider story renders snapshot 1`] = ` 60 |