├── .circleci
└── config.yml
├── .editorconfig
├── .gitattributes
├── .github
├── actions
│ └── setup
│ │ └── action.yml
└── workflows
│ └── ci.yml
├── .gitignore
├── .nvmrc
├── .yarnrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── example
├── app.json
├── babel.config.js
├── index.js
├── metro.config.js
├── package.json
├── src
│ ├── Advanced.tsx
│ ├── App.tsx
│ └── logo.png
├── tsconfig.json
├── webpack.config.js
└── yarn.lock
├── package.json
├── scripts
└── bootstrap.js
├── src
├── AnimatedSurface.tsx
├── Autocomplete.tsx
├── AutocompleteContext.tsx
├── AutocompleteFlatList.tsx
├── AutocompleteItem.tsx
├── AutocompleteScrollView.tsx
├── PortalContent.native.tsx
├── PortalContent.tsx
├── PositionedSurface.tsx
├── createAutocompleteScrollable.tsx
├── icon.tsx
├── index.tsx
├── mergeRefs.tsx
├── shared.tsx
├── useAutomaticScroller.native.ts
├── useAutomaticScroller.ts
├── useComponentDimensions.tsx
├── useHighlighted.tsx
├── useKeyboardHeight.native.tsx
├── useKeyboardHeight.tsx
├── useLatest.ts
├── usePosition.native.tsx
├── usePosition.tsx
└── usePressOutside.tsx
├── tsconfig.build.json
├── tsconfig.json
└── yarn.lock
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 |
3 | executors:
4 | default:
5 | docker:
6 | - image: circleci/node:10
7 | working_directory: ~/project
8 |
9 | commands:
10 | attach_project:
11 | steps:
12 | - attach_workspace:
13 | at: ~/project
14 |
15 | jobs:
16 | install-dependencies:
17 | executor: default
18 | steps:
19 | - checkout
20 | - attach_project
21 | - restore_cache:
22 | keys:
23 | - dependencies-{{ checksum "package.json" }}
24 | - dependencies-
25 | - restore_cache:
26 | keys:
27 | - dependencies-example-{{ checksum "example/package.json" }}
28 | - dependencies-example-
29 | - run:
30 | name: Install dependencies
31 | command: |
32 | yarn install --cwd example --frozen-lockfile
33 | yarn install --frozen-lockfile
34 | - save_cache:
35 | key: dependencies-{{ checksum "package.json" }}
36 | paths: node_modules
37 | - save_cache:
38 | key: dependencies-example-{{ checksum "example/package.json" }}
39 | paths: example/node_modules
40 | - persist_to_workspace:
41 | root: .
42 | paths: .
43 |
44 | lint:
45 | executor: default
46 | steps:
47 | - attach_project
48 | - run:
49 | name: Lint files
50 | command: |
51 | yarn lint
52 |
53 | typescript:
54 | executor: default
55 | steps:
56 | - attach_project
57 | - run:
58 | name: Typecheck files
59 | command: |
60 | yarn typescript
61 |
62 | unit-tests:
63 | executor: default
64 | steps:
65 | - attach_project
66 | - run:
67 | name: Run unit tests
68 | command: |
69 | yarn test --coverage
70 | - store_artifacts:
71 | path: coverage
72 | destination: coverage
73 |
74 | build-package:
75 | executor: default
76 | steps:
77 | - attach_project
78 | - run:
79 | name: Build package
80 | command: |
81 | yarn prepare
82 |
83 | workflows:
84 | build-and-test:
85 | jobs:
86 | - install-dependencies
87 | - lint:
88 | requires:
89 | - install-dependencies
90 | - typescript:
91 | requires:
92 | - install-dependencies
93 | - unit-tests:
94 | requires:
95 | - install-dependencies
96 | - build-package:
97 | requires:
98 | - install-dependencies
99 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # EditorConfig helps developers define and maintain consistent
2 | # coding styles between different editors and IDEs
3 | # editorconfig.org
4 |
5 | root = true
6 |
7 | [*]
8 |
9 | indent_style = space
10 | indent_size = 2
11 |
12 | end_of_line = lf
13 | charset = utf-8
14 | trim_trailing_whitespace = true
15 | insert_final_newline = true
16 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | *.pbxproj -text
2 | # specific for windows script files
3 | *.bat text eol=crlf
--------------------------------------------------------------------------------
/.github/actions/setup/action.yml:
--------------------------------------------------------------------------------
1 | name: Setup
2 | description: Setup Node.js and install dependencies
3 |
4 | runs:
5 | using: composite
6 | steps:
7 | - name: Setup Node.js
8 | uses: actions/setup-node@v3
9 | with:
10 | node-version-file: .nvmrc
11 |
12 | - name: Cache dependencies
13 | id: yarn-cache
14 | uses: actions/cache@v3
15 | with:
16 | path: |
17 | **/node_modules
18 | key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
19 | restore-keys: |
20 | ${{ runner.os }}-yarn-
21 |
22 | - name: Install dependencies
23 | if: steps.yarn-cache.outputs.cache-hit != 'true'
24 | run: |
25 | yarn install --cwd example --frozen-lockfile
26 | yarn install --frozen-lockfile
27 | shell: bash
28 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches:
6 | - main
7 | pull_request:
8 | branches:
9 | - main
10 |
11 | jobs:
12 | lint:
13 | runs-on: ubuntu-latest
14 | steps:
15 | - name: Checkout
16 | uses: actions/checkout@v3
17 |
18 | - name: Setup
19 | uses: ./.github/actions/setup
20 |
21 | - name: Lint files
22 | run: yarn lint
23 |
24 | - name: Typecheck files
25 | run: yarn typecheck
26 |
27 | test:
28 | runs-on: ubuntu-latest
29 | steps:
30 | - name: Checkout
31 | uses: actions/checkout@v3
32 |
33 | - name: Setup
34 | uses: ./.github/actions/setup
35 |
36 | - name: Run unit tests
37 | run: yarn test --maxWorkers=2 --coverage
38 |
39 | build:
40 | runs-on: ubuntu-latest
41 | steps:
42 | - name: Checkout
43 | uses: actions/checkout@v3
44 |
45 | - name: Setup
46 | uses: ./.github/actions/setup
47 |
48 | - name: Build package
49 | run: yarn prepack
50 | release:
51 | runs-on: ubuntu-latest
52 | if: github.ref == 'refs/heads/master'
53 | steps:
54 | - name: Checkout
55 | uses: actions/checkout@v3
56 | with:
57 | fetch-depth: 0
58 | - name: Setup
59 | uses: ./.github/actions/setup
60 | - name: git config
61 | run: |
62 | git config user.name "${GITHUB_ACTOR}"
63 | git config user.email "${GITHUB_ACTOR}@users.noreply.github.com"
64 | - run: echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" >> .npmrc
65 | - run: yarn release
66 | env:
67 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
68 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # Xcode
13 | #
14 | build/
15 | *.pbxuser
16 | !default.pbxuser
17 | *.mode1v3
18 | !default.mode1v3
19 | *.mode2v3
20 | !default.mode2v3
21 | *.perspectivev3
22 | !default.perspectivev3
23 | xcuserdata
24 | *.xccheckout
25 | *.moved-aside
26 | DerivedData
27 | *.hmap
28 | *.ipa
29 | *.xcuserstate
30 | project.xcworkspace
31 |
32 | # Android/IJ
33 | #
34 | .idea
35 | .gradle
36 | local.properties
37 | android.iml
38 |
39 | # Cocoapods
40 | #
41 | example/ios/Pods
42 |
43 | # node.js
44 | #
45 | node_modules/
46 | npm-debug.log
47 | yarn-debug.log
48 | yarn-error.log
49 |
50 | # BUCK
51 | buck-out/
52 | \.buckd/
53 | android/app/libs
54 | android/keystores/debug.keystore
55 |
56 | # Expo
57 | .expo/*
58 |
59 | # generated by bob
60 | lib/
61 |
62 | .env
63 |
--------------------------------------------------------------------------------
/.nvmrc:
--------------------------------------------------------------------------------
1 | 16.18.1
--------------------------------------------------------------------------------
/.yarnrc:
--------------------------------------------------------------------------------
1 | # Override Yarn command so we can automatically setup the repo on running `yarn`
2 |
3 | yarn-path "scripts/bootstrap.js"
4 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project.
4 |
5 | ## Development workflow
6 |
7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn
11 | ```
12 |
13 | While developing, you can run the [example app](/example/) to test your changes.
14 |
15 | To start the packager:
16 |
17 | ```sh
18 | yarn example start
19 | ```
20 |
21 | To run the example app on Android:
22 |
23 | ```sh
24 | yarn example android
25 | ```
26 |
27 | To run the example app on iOS:
28 |
29 | ```sh
30 | yarn example ios
31 | ```
32 |
33 | Make sure your code passes TypeScript and ESLint. Run the following to verify:
34 |
35 | ```sh
36 | yarn typescript
37 | yarn lint
38 | ```
39 |
40 | To fix formatting errors, run the following:
41 |
42 | ```sh
43 | yarn lint --fix
44 | ```
45 |
46 | Remember to add tests for your change if possible. Run the unit tests by:
47 |
48 | ```sh
49 | yarn test
50 | ```
51 |
52 | To edit the Objective-C files, open `example/ios/PaperAutocompleteExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > react-native-paper-autocomplete`.
53 |
54 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `reactnativepaperautocomplete` under `Android`.
55 |
56 | ### Commit message convention
57 |
58 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
59 |
60 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
61 | - `feat`: new features, e.g. add new method to the module.
62 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
63 | - `docs`: changes into documentation, e.g. add usage example for the module..
64 | - `test`: adding or updating tests, e.g. add integration tests using detox.
65 | - `chore`: tooling changes, e.g. change CI config.
66 |
67 | Our pre-commit hooks verify that your commit message matches this format when committing.
68 |
69 | ### Linting and tests
70 |
71 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
72 |
73 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing.
74 |
75 | Our pre-commit hooks verify that the linter and tests pass when committing.
76 |
77 | ### Scripts
78 |
79 | The `package.json` file contains various scripts for common tasks:
80 |
81 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
82 | - `yarn typescript`: type-check files with TypeScript.
83 | - `yarn lint`: lint files with ESLint.
84 | - `yarn test`: run unit tests with Jest.
85 | - `yarn example start`: start the Metro server for the example app.
86 | - `yarn example android`: run the example app on Android.
87 | - `yarn example ios`: run the example app on iOS.
88 |
89 | ### Sending a pull request
90 |
91 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github).
92 |
93 | When you're sending a pull request:
94 |
95 | - Prefer small pull requests focused on one change.
96 | - Verify that linters and tests are passing.
97 | - Review the documentation to make sure it looks good.
98 | - Follow the pull request template when opening a pull request.
99 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
100 |
101 | ## Code of Conduct
102 |
103 | ### Our Pledge
104 |
105 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
106 |
107 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
108 |
109 | ### Our Standards
110 |
111 | Examples of behavior that contributes to a positive environment for our community include:
112 |
113 | - Demonstrating empathy and kindness toward other people
114 | - Being respectful of differing opinions, viewpoints, and experiences
115 | - Giving and gracefully accepting constructive feedback
116 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
117 | - Focusing on what is best not just for us as individuals, but for the overall community
118 |
119 | Examples of unacceptable behavior include:
120 |
121 | - The use of sexualized language or imagery, and sexual attention or
122 | advances of any kind
123 | - Trolling, insulting or derogatory comments, and personal or political attacks
124 | - Public or private harassment
125 | - Publishing others' private information, such as a physical or email
126 | address, without their explicit permission
127 | - Other conduct which could reasonably be considered inappropriate in a
128 | professional setting
129 |
130 | ### Enforcement Responsibilities
131 |
132 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
133 |
134 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
135 |
136 | ### Scope
137 |
138 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
139 |
140 | ### Enforcement
141 |
142 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly.
143 |
144 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
145 |
146 | ### Enforcement Guidelines
147 |
148 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
149 |
150 | #### 1. Correction
151 |
152 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
153 |
154 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
155 |
156 | #### 2. Warning
157 |
158 | **Community Impact**: A violation through a single incident or series of actions.
159 |
160 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
161 |
162 | #### 3. Temporary Ban
163 |
164 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
165 |
166 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
167 |
168 | #### 4. Permanent Ban
169 |
170 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
171 |
172 | **Consequence**: A permanent ban from any sort of public interaction within the community.
173 |
174 | ### Attribution
175 |
176 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
177 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
178 |
179 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
180 |
181 | [homepage]: https://www.contributor-covenant.org
182 |
183 | For answers to common questions about this code of conduct, see the FAQ at
184 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
185 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Richard Lindhout
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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | react-native-paper-autocomplete (⚠️ in beta)
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 | Great autocomplete package for React Native Paper with great web support.
23 | - Uses re-animated to be smooth on iOS/Android/Web
24 | - Keyboard support (Arrow down/up/end/start)
25 | - Single + multiple
26 | - Async connect with backend
27 | - Grouped results
28 | - Great web support (scrollable while open)
29 |
30 | ## Installation
31 |
32 |
33 | ```sh
34 | yarn add react-native-paper-autocomplete
35 | ```
36 | or
37 | ```sh
38 | npm install react-native-paper-autocomplete
39 | ```
40 |
41 | ## Simple
42 |
43 | ```jsx
44 | const options = [
45 | { value: 1, label: 'Ruben von der Vein' },
46 | { value: 2, label: 'Pjotr Versjuurre' },
47 | { value: 3, label: 'Bjart von Klef' },
48 | { value: 4, label: 'Riesjard Lindhoe' }
49 | ]
50 | function Single() {
51 | return (
52 |
53 | {
55 | console.log({ newValue })
56 | }}
57 | value={options[0]}
58 | options={options}
59 | inputProps={{
60 | placeholder: 'Select user',
61 | // ...all other props which are available in react native paper
62 | }}
63 | />
64 |
65 | )
66 | }
67 |
68 | function Multi() {
69 | return (
70 |
71 | {
74 | console.log({ newValue })
75 | }}
76 | value={[options[0], options[1]]}
77 | options={options}
78 | inputProps={{
79 | placeholder: 'Select user',
80 | // ...all other props which are available in react native paper
81 | }}
82 | />
83 |
84 | )
85 | }
86 | ```
87 |
88 |
89 | ## Advanced
90 |
91 | ```jsx
92 |
93 |
94 | function Multi() {
95 | const [options, setOptions] = React.useState([
96 | { id: 1, name: 'Ruben von der Vein', gender: 'girl' },
97 | { id: 2, name: 'Pjotr Versjuurre', gender: 'boy' },
98 | { id: 3, name: 'Bjart von Klef', gender: 'boy' },
99 | { id: 4, name: 'Riesjard Lindhoe', gender: 'boy' }
100 | ])
101 | const onEndReached = () => {
102 | // fetch more items (paginated) e.g:
103 | const response = api.fetch(...)
104 | setOptions(prev => [...prev, response.data])
105 | }
106 |
107 | return (
108 |
109 | item.name}
112 | getOptionValue={(item) => item.id}
113 | onChange={(newValue)=>{
114 | console.log({ newValue })
115 | }}
116 | value={[options[0], options[1]]}
117 | options={options}
118 | // if you want to group on something
119 | groupBy={(option) => option.gender}
120 | inputProps={{
121 | placeholder: 'Select user',
122 | // ...all other props which are available in react native paper
123 | onChangeText: (search) => {
124 | // Load from your backend
125 | },
126 | }}
127 |
128 | listProps={{
129 | onEndReached
130 | // + other FlatList props or SectionList if you specify groupBy
131 | }}
132 | />
133 |
134 | )
135 | }
136 | ```
137 |
138 |
139 | ## Custom scrollable containers
140 | * If your autocomplete is inside a `ScrollView` use `AutocompleteScrollView` instead of the native ScrollView
141 | * If your autocomplete is inside a `FlatList` use `AutocompleteFlatList` instead of the native FlatList
142 |
143 | * If you're using another scrollable component, make sure it has te same api as the scrollView and supports the
144 | following properties: `ref, scrollEventThrottle, keyboardShouldPersistTaps, onScroll`
145 |
146 | ### Example of custom scrollable container with autocomplete support
147 |
148 | ```tsx
149 | import CustomScrollView from '../CustomScrollView'
150 | import { createAutocompleteScrollable } from 'react-native-paper-autocomplete'
151 | const AnimatedCustomScrollView = createAutocompleteScrollable(CustomScrollView)
152 | ```
153 |
154 |
155 |
156 | ## Contributing
157 |
158 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.
159 |
160 | ## License
161 |
162 | MIT
163 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | presets: ['module:metro-react-native-babel-preset'],
3 | };
4 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-paper-autocomplete-example",
3 | "displayName": "PaperAutocomplete Example",
4 | "expo": {
5 | "name": "react-native-paper-autocomplete-example",
6 | "slug": "react-native-paper-autocomplete-example",
7 | "description": "Example app for react-native-paper-autocomplete",
8 | "privacy": "public",
9 | "version": "1.0.0",
10 | "platforms": [
11 | "ios",
12 | "android",
13 | "web"
14 | ],
15 | "ios": {
16 | "supportsTablet": true
17 | },
18 | "assetBundlePatterns": [
19 | "**/*"
20 | ]
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const pak = require('../package.json');
3 |
4 | module.exports = function (api) {
5 | api.cache(true);
6 |
7 | return {
8 | presets: ['babel-preset-expo'],
9 | plugins: [
10 | [
11 | 'module-resolver',
12 | {
13 | extensions: ['.tsx', '.ts', '.js', '.json'],
14 | alias: {
15 | // For development, we want to alias the library to the source
16 | [pak.name]: path.join(__dirname, '..', pak.source),
17 | },
18 | },
19 | ],
20 | 'react-native-reanimated/plugin',
21 | ],
22 | };
23 | };
24 |
--------------------------------------------------------------------------------
/example/index.js:
--------------------------------------------------------------------------------
1 | import { registerRootComponent } from 'expo';
2 |
3 | import App from './src/App';
4 |
5 | // registerRootComponent calls AppRegistry.registerComponent('main', () => App);
6 | // It also ensures that whether you load the app in the Expo client or in a native build,
7 | // the environment is set up appropriately
8 | registerRootComponent(App);
9 |
--------------------------------------------------------------------------------
/example/metro.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const blacklist = require('metro-config/src/defaults/blacklist');
3 | const escape = require('escape-string-regexp');
4 | const pak = require('../package.json');
5 |
6 | const root = path.resolve(__dirname, '..');
7 |
8 | const modules = Object.keys({
9 | ...pak.peerDependencies,
10 | });
11 |
12 | module.exports = {
13 | projectRoot: __dirname,
14 | watchFolders: [root],
15 |
16 | // We need to make sure that only one version is loaded for peerDependencies
17 | // So we blacklist them at the root, and alias them to the versions in example's node_modules
18 | resolver: {
19 | blacklistRE: blacklist(
20 | modules.map(
21 | (m) =>
22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`)
23 | )
24 | ),
25 |
26 | extraNodeModules: modules.reduce((acc, name) => {
27 | acc[name] = path.join(__dirname, 'node_modules', name);
28 | return acc;
29 | }, {}),
30 | },
31 |
32 | transformer: {
33 | getTransformOptions: async () => ({
34 | transform: {
35 | experimentalImportSupport: false,
36 | inlineRequires: true,
37 | },
38 | }),
39 | },
40 | };
41 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-paper-autocomplete-example",
3 | "description": "Example app for react-native-paper-autocomplete",
4 | "version": "0.0.1",
5 | "private": true,
6 | "main": "index",
7 | "scripts": {
8 | "android": "expo start --android",
9 | "ios": "expo start --ios",
10 | "web": "expo start --web",
11 | "start": "expo start",
12 | "test": "jest"
13 | },
14 | "dependencies": {
15 | "expo": "^44.0.0",
16 | "expo-splash-screen": "~0.14.0",
17 | "react": "17.0.1",
18 | "react-dom": "17.0.1",
19 | "react-native": "0.64.3",
20 | "react-native-gesture-handler": "~2.1.0",
21 | "react-native-paper": "^4.11.1",
22 | "react-native-reanimated": "~2.3.1",
23 | "react-native-unimodules": "~0.15.0",
24 | "react-native-web": "^0.17.5"
25 | },
26 | "devDependencies": {
27 | "@babel/core": "^7.12.9",
28 | "@babel/runtime": "^7.9.6",
29 | "babel-plugin-module-resolver": "^4.0.0",
30 | "babel-preset-expo": "9.0.1",
31 | "expo-cli": "^4.0.13"
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/example/src/Advanced.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { Image } from 'react-native';
3 |
4 | import { Autocomplete } from '../../src/index';
5 |
6 | type ItemType = {
7 | id: number;
8 | name: string;
9 | gender: 'girl' | 'boy';
10 | icon: any;
11 | };
12 |
13 | function Advanced({
14 | textInputMode,
15 | multiple,
16 | }: {
17 | textInputMode: 'flat' | 'outlined';
18 | multiple: boolean;
19 | }) {
20 | const [options] = React.useState([
21 | {
22 | id: 1,
23 | name: 'Jannette Jansen',
24 | gender: 'girl',
25 | icon: 'emoticon',
26 | },
27 | {
28 | id: 2,
29 | name: 'Peter Lansen',
30 | gender: 'boy',
31 | icon: 'emoticon',
32 | },
33 | { id: 3, name: 'Rick der Zwaan', gender: 'boy', icon: 'emoticon' },
34 | { id: 4, name: 'Billy Shilly', gender: 'boy', icon: 'emoticon' },
35 | {
36 | id: 5,
37 | name: 'Jan Jansen',
38 | gender: 'boy',
39 | icon: (iconProps: any) => (
40 |
50 | ),
51 | },
52 | ]);
53 | const [value, setValue] = React.useState(multiple ? [] : null);
54 | const onEndReached = () => {
55 | // fetch more items (paginated) e.g:
56 | // const response = api.fetch(...)
57 | // setOptions((prev) => [...prev, response.data]);
58 | };
59 |
60 | return (
61 | //@ts-ignore
62 |
63 | multiple={multiple}
64 | getOptionLabel={(item) => item.name}
65 | getOptionValue={(item) => item.id}
66 | getOptionIcon={(item) => item.icon}
67 | //@ts-ignore
68 | onChange={setValue}
69 | value={value}
70 | options={options}
71 | // if you want to group on something
72 | groupBy={(option) => option.gender}
73 | inputProps={{
74 | // dense: true, // TODO: fix multiple height with chips!
75 | mode: textInputMode,
76 | placeholder: 'Select user',
77 | // ...all other props which are available in react native paper
78 | onChangeText: (_) => {
79 | // Load from your backend
80 | },
81 | style: {
82 | backgroundColor: 'transparent',
83 | },
84 | }}
85 | listProps={{
86 | onEndReached,
87 | // + other FlatList props or SectionList if you specify groupBy
88 | }}
89 | />
90 | );
91 | }
92 | export default React.memo(Advanced);
93 |
--------------------------------------------------------------------------------
/example/src/App.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import Advanced from './Advanced';
3 | import {
4 | StyleSheet,
5 | // ScrollView,
6 | View,
7 | Linking,
8 | Image,
9 | Platform,
10 | } from 'react-native';
11 | import Animated from 'react-native-reanimated';
12 | import {
13 | Title,
14 | Button,
15 | Text,
16 | Provider as PaperProvider,
17 | useTheme,
18 | overlay,
19 | Paragraph,
20 | Appbar,
21 | } from 'react-native-paper';
22 | import { AutocompleteScrollView } from '../../src';
23 |
24 | function AppInner() {
25 | const theme = useTheme();
26 | const backgroundColor =
27 | theme.dark && theme.mode === 'adaptive'
28 | ? overlay(3, theme.colors.surface)
29 | : (theme.colors.surface as any);
30 | return (
31 | <>
32 |
33 |
34 |
35 |
42 |
43 |
44 |
45 | react-native-paper-autocomplete
46 |
47 |
48 | The autocomplete package you wished for on all platforms (iOS,
49 | Android, web) brought to you by
50 | Linking.openURL('https://webridge.nl')}
52 | style={styles.underline}
53 | >
54 | webRidge
55 |
56 |
57 |
58 |
59 |
65 | Linking.openURL(
66 | 'https://github.com/web-ridge/react-native-paper-autocomplete'
67 | )
68 | }
69 | >
70 | GitHub
71 |
72 |
73 |
74 |
75 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
101 |
102 | >
103 | );
104 | }
105 |
106 | function Enter() {
107 | return ;
108 | }
109 |
110 | // function Row({ children }: { children: any }) {
111 | // return {children} ;
112 | // }
113 | //
114 | // function Label({ children }: { children: string }) {
115 | // const theme = useTheme();
116 | // return (
117 | // {children}
118 | // );
119 | // }
120 |
121 | export default function App() {
122 | return (
123 |
124 |
129 |
130 |
131 |
132 | );
133 | }
134 |
135 | function TwitterFollowButton({ userName }: { userName: string }) {
136 | return (
137 | Linking.openURL(`https://twitter.com/${userName}`)}
143 | >
144 | @{userName}
145 |
146 | );
147 | }
148 |
149 | const styles = StyleSheet.create({
150 | underline: { textDecorationLine: 'underline' },
151 | logo: { width: 56, height: 56, marginRight: 24 },
152 | titleContainer: {
153 | flexDirection: 'row',
154 | alignItems: 'center',
155 | marginBottom: 12,
156 | },
157 | twitterButton: { marginBottom: 16 },
158 | // root: { flex: 1 },
159 | content: {
160 | width: '100%',
161 | maxWidth: 600,
162 | marginTop: 12,
163 | padding: 12,
164 | alignSelf: 'center',
165 | },
166 | contentInline: {
167 | padding: 0,
168 | height: 600,
169 | },
170 | contentShadow: {
171 | shadowColor: '#000',
172 | shadowOffset: {
173 | width: 0,
174 | height: 2,
175 | },
176 | shadowOpacity: 0.15,
177 | shadowRadius: 3.84,
178 | elevation: 3,
179 | },
180 | switchContainer: {
181 | flexDirection: 'row',
182 | marginTop: 24,
183 | alignItems: 'center',
184 | },
185 | switchSpace: { flex: 1 },
186 | switchLabel: { fontSize: 16 },
187 | buttons: { flexDirection: 'row', flexWrap: 'wrap', marginTop: 24 },
188 | pickButton: { marginTop: 6 },
189 | buttonSeparator: { width: 6 },
190 | enter: { height: 12 },
191 | label: { width: 100, fontSize: 16 },
192 | row: { paddingTop: 12, paddingBottom: 12, flexDirection: 'row' },
193 | });
194 |
--------------------------------------------------------------------------------
/example/src/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/web-ridge/react-native-paper-autocomplete/cdd1d00ee3e6e4d73accfec7a5e2ae2cde133ba7/example/src/logo.png
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "jsx": "react-native",
4 | "target": "esnext",
5 | "lib": [
6 | "esnext"
7 | ],
8 | "allowJs": true,
9 | "skipLibCheck": true,
10 | "noEmit": true,
11 | "allowSyntheticDefaultImports": true,
12 | "resolveJsonModule": true,
13 | "esModuleInterop": true,
14 | "moduleResolution": "node"
15 | },
16 | "extends": "expo/tsconfig.base"
17 | }
18 |
--------------------------------------------------------------------------------
/example/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const createExpoWebpackConfigAsync = require('@expo/webpack-config');
3 | const { resolver } = require('./metro.config');
4 |
5 | const root = path.resolve(__dirname, '..');
6 | const node_modules = path.join(__dirname, 'node_modules');
7 |
8 | module.exports = async function (env, argv) {
9 | const config = await createExpoWebpackConfigAsync(env, argv);
10 |
11 | config.module.rules.push({
12 | test: /\.(js|jsx|ts|tsx)$/,
13 | include: path.resolve(root, 'src'),
14 | use: 'babel-loader',
15 | });
16 |
17 | // We need to make sure that only one version is loaded for peerDependencies
18 | // So we alias them to the versions in example's node_modules
19 | Object.assign(config.resolve.alias, {
20 | ...resolver.extraNodeModules,
21 | 'react-native-web': path.join(node_modules, 'react-native-web'),
22 | });
23 |
24 | return config;
25 | };
26 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-paper-autocomplete",
3 | "version": "0.12.0",
4 | "description": "Great autocomplete package for React Native Paper",
5 | "main": "lib/commonjs/index",
6 | "module": "lib/module/index",
7 | "types": "lib/typescript/index.d.ts",
8 | "react-native": "src/index",
9 | "source": "src/index",
10 | "files": [
11 | "src",
12 | "lib",
13 | "android",
14 | "ios",
15 | "cpp",
16 | "react-native-paper-autocomplete.podspec",
17 | "!lib/typescript/example",
18 | "!android/build",
19 | "!ios/build",
20 | "!**/__tests__",
21 | "!**/__fixtures__",
22 | "!**/__mocks__"
23 | ],
24 | "scripts": {
25 | "test": "jest",
26 | "typescript": "tsc --noEmit",
27 | "lint": "eslint \"**/*.{js,ts,tsx}\"",
28 | "prepare": "bob build",
29 | "example": "yarn --cwd example",
30 | "pods": "cd example && pod-install --quiet",
31 | "release": "release-it --ci --github.autoGenerate",
32 | "bootstrap": "yarn example && yarn && yarn pods",
33 | "typecheck": "tsc --noEmit",
34 | "prepack": "bob build"
35 | },
36 | "keywords": [
37 | "react-native",
38 | "ios",
39 | "android"
40 | ],
41 | "repository": "https://github.com/web-ridge/react-native-paper-autocomplete",
42 | "author": "Richard Lindhout (https://github.com/web-ridge)",
43 | "license": "MIT",
44 | "bugs": {
45 | "url": "https://github.com/web-ridge/react-native-paper-autocomplete/issues"
46 | },
47 | "homepage": "https://github.com/web-ridge/react-native-paper-autocomplete#readme",
48 | "publishConfig": {
49 | "registry": "https://registry.npmjs.org/"
50 | },
51 | "devDependencies": {
52 | "@commitlint/config-conventional": "^11.0.0",
53 | "@react-native-community/eslint-config": "^2.0.0",
54 | "@release-it/conventional-changelog": "^2.0.0",
55 | "@types/color": "^3.0.1",
56 | "@types/jest": "^26.0.0",
57 | "@types/react": "^17.0.38",
58 | "@types/react-dom": "^17.0.11",
59 | "@types/react-native": "^0.66.11",
60 | "add": "^2.0.6",
61 | "commitlint": "^11.0.0",
62 | "eslint": "^7.2.0",
63 | "eslint-config-prettier": "^7.0.0",
64 | "eslint-plugin-prettier": "^3.1.3",
65 | "husky": "^4.2.5",
66 | "jest": "^26.0.1",
67 | "pod-install": "^0.1.0",
68 | "prettier": "^2.0.5",
69 | "react": "16.13.1",
70 | "react-dom": "^17.0.2",
71 | "react-native": "0.63.4",
72 | "react-native-builder-bob": "^",
73 | "react-native-gesture-handler": "^2.1.0",
74 | "react-native-paper": "^5.7.0",
75 | "react-native-reanimated": "^2.3.1",
76 | "release-it": "^14.2.2",
77 | "typescript": "^4.1.3",
78 | "yarn": "^1.22.17"
79 | },
80 | "peerDependencies": {
81 | "react": "*",
82 | "react-native": "*",
83 | "react-native-paper": "*",
84 | "react-native-reanimated": "*"
85 | },
86 | "jest": {
87 | "preset": "react-native",
88 | "modulePathIgnorePatterns": [
89 | "/example/node_modules",
90 | "/lib/"
91 | ]
92 | },
93 | "husky": {
94 | "hooks": {
95 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
96 | "pre-commit": "yarn lint && yarn typescript"
97 | }
98 | },
99 | "commitlint": {
100 | "extends": [
101 | "@commitlint/config-conventional"
102 | ]
103 | },
104 | "release-it": {
105 | "git": {
106 | "commitMessage": "chore: release ${version}",
107 | "tagName": "v${version}"
108 | },
109 | "npm": {
110 | "publish": true
111 | },
112 | "github": {
113 | "release": true
114 | },
115 | "plugins": {
116 | "@release-it/conventional-changelog": {
117 | "preset": "angular"
118 | }
119 | }
120 | },
121 | "eslintConfig": {
122 | "root": true,
123 | "extends": [
124 | "@react-native-community",
125 | "prettier"
126 | ],
127 | "rules": {
128 | "prettier/prettier": [
129 | "error",
130 | {
131 | "quoteProps": "consistent",
132 | "singleQuote": true,
133 | "tabWidth": 2,
134 | "trailingComma": "es5",
135 | "useTabs": false
136 | }
137 | ]
138 | }
139 | },
140 | "eslintIgnore": [
141 | "node_modules/",
142 | "lib/"
143 | ],
144 | "prettier": {
145 | "quoteProps": "consistent",
146 | "singleQuote": true,
147 | "tabWidth": 2,
148 | "trailingComma": "es5",
149 | "useTabs": false
150 | },
151 | "react-native-builder-bob": {
152 | "source": "src",
153 | "output": "lib",
154 | "targets": [
155 | "commonjs",
156 | "module",
157 | [
158 | "typescript",
159 | {
160 | "project": "tsconfig.build.json"
161 | }
162 | ]
163 | ]
164 | },
165 | "dependencies": {
166 | "color": "3.1.3"
167 | }
168 | }
169 |
--------------------------------------------------------------------------------
/scripts/bootstrap.js:
--------------------------------------------------------------------------------
1 | const path = require('path');
2 | const child_process = require('child_process');
3 |
4 | const root = path.resolve(__dirname, '..');
5 | const args = process.argv.slice(2);
6 | const options = {
7 | cwd: process.cwd(),
8 | env: process.env,
9 | stdio: 'inherit',
10 | encoding: 'utf-8',
11 | };
12 |
13 | let result;
14 |
15 | if (process.cwd() !== root || args.length) {
16 | // We're not in the root of the project, or additional arguments were passed
17 | // In this case, forward the command to `yarn`
18 | result = child_process.spawnSync('yarn', args, options);
19 | } else {
20 | // If `yarn` is run without arguments, perform bootstrap
21 | result = child_process.spawnSync('yarn', ['bootstrap'], options);
22 | }
23 |
24 | process.exitCode = result.status;
25 |
--------------------------------------------------------------------------------
/src/AnimatedSurface.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import Animated from 'react-native-reanimated';
3 | import { useTheme, overlay, shadow } from 'react-native-paper';
4 | import type { ViewStyle } from 'react-native';
5 |
6 | const AnimatedSurface = React.forwardRef(
7 | (
8 | {
9 | elevation = 4,
10 | style,
11 | children,
12 | }: {
13 | elevation?: number;
14 | style?: ViewStyle;
15 | children: any;
16 | },
17 | forwardedRef: React.Ref
18 | ) => {
19 | const theme = useTheme();
20 | const { dark: isDarkTheme, mode, colors } = theme;
21 |
22 | return (
23 |
37 | {children}
38 |
39 | );
40 | }
41 | );
42 |
43 | export default Animated.createAnimatedComponent(AnimatedSurface);
44 |
--------------------------------------------------------------------------------
/src/Autocomplete.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import {
3 | TextInputProps,
4 | View,
5 | ViewStyle,
6 | StyleSheet,
7 | TextInput as NativeTextInput,
8 | TextInputFocusEventData,
9 | NativeSyntheticEvent,
10 | FlatList,
11 | SectionList,
12 | // useWindowDimensions,
13 | FlatListProps,
14 | } from 'react-native';
15 | import {
16 | ActivityIndicator,
17 | Chip,
18 | IconButton,
19 | List,
20 | TextInput,
21 | useTheme,
22 | } from 'react-native-paper';
23 | import Color from 'color';
24 |
25 | import useLatest from './useLatest';
26 | import useAutomaticScroller from './useAutomaticScroller';
27 | import AutocompleteItem from './AutocompleteItem';
28 | import type { IconSource } from './icon';
29 | import useHighlighted from './useHighlighted';
30 | import PortalContent from './PortalContent';
31 | import useComponentDimensions from './useComponentDimensions';
32 | import PositionedSurface from './PositionedSurface';
33 | import Animated, {
34 | DerivedValue,
35 | SharedValue,
36 | useAnimatedRef,
37 | useAnimatedStyle,
38 | useDerivedValue,
39 | } from 'react-native-reanimated';
40 | import { useAutocomplete } from './AutocompleteContext';
41 |
42 | // https://ej2.syncfusion.com/react/documentation/drop-down-list/accessibility/
43 |
44 | type PaperInputProps = React.ComponentProps;
45 |
46 | export function getFlatListItemLayout(
47 | _: any[] | undefined | null,
48 | index: number
49 | ) {
50 | return {
51 | length: 63,
52 | offset: 63 * index,
53 | index,
54 | };
55 | }
56 |
57 | // const AnimatedTextInput = createElement(TextInput);
58 | export interface FilterOptionsParams {
59 | isFocusedAndValueIsSameAsSearch: boolean;
60 | inputValue: string;
61 | getOptionLabel: (option: ItemT) => string;
62 | getOptionDescription?: (option: ItemT) => string;
63 | }
64 |
65 | export interface AutocompleteBaseProps {
66 | testID?: string;
67 | loading?: boolean;
68 | listProps?: Omit<
69 | FlatListProps,
70 | 'data' | 'renderItem' | 'ref' | 'keyExtractor' | 'extraData'
71 | >;
72 | inputProps?: PaperInputProps;
73 | ListComponent?: any;
74 | options: ReadonlyArray | null | undefined;
75 | groupBy?: (option: ItemT) => string;
76 | renderInput?: (params: TextInputProps) => any;
77 | style?: ViewStyle;
78 | disableInputPrefixIcon?: boolean;
79 | getOptionLabel?: (option: ItemT) => string;
80 | getOptionDescription?: (option: ItemT) => string | number;
81 | getOptionValue?: (option: ItemT) => string | number;
82 | getOptionIcon?: (option: ItemT) => IconSource;
83 | filterOptions?: (
84 | a: ReadonlyArray | null | undefined,
85 | {
86 | isFocusedAndValueIsSameAsSearch,
87 | inputValue,
88 | getOptionLabel,
89 | getOptionDescription,
90 | }: FilterOptionsParams
91 | ) => ReadonlyArray | null | undefined;
92 | }
93 |
94 | export interface AutocompleteMultipleProps
95 | extends AutocompleteBaseProps {
96 | multiple: true;
97 | value: ItemT[] | null | undefined;
98 | onChange: (v: ItemT[]) => void;
99 | }
100 |
101 | export interface AutocompleteSingleProps
102 | extends AutocompleteBaseProps {
103 | multiple?: undefined | false;
104 | value: ItemT | null | undefined;
105 | onChange: (v: ItemT | undefined) => void;
106 | }
107 |
108 | export function defaultFilterOptions(
109 | a: ReadonlyArray | null | undefined,
110 | {
111 | isFocusedAndValueIsSameAsSearch,
112 | inputValue,
113 | getOptionLabel,
114 | getOptionDescription,
115 | }: FilterOptionsParams
116 | ) {
117 | if (isFocusedAndValueIsSameAsSearch) {
118 | return a;
119 | }
120 | return a?.filter((o) => {
121 | const oAny = o as any;
122 | if (!inputValue) {
123 | return true;
124 | }
125 | const search = inputValue.toLowerCase();
126 | const label = getOptionLabel(oAny) || '';
127 | const description = getOptionDescription?.(oAny) || '';
128 | return (
129 | label.toLowerCase().includes(search) ||
130 | description.toLowerCase().includes(search)
131 | );
132 | });
133 | }
134 |
135 | function removeSelected(
136 | a: ReadonlyArray | null | undefined,
137 | {
138 | value: rValue,
139 | multiple,
140 | getOptionValue,
141 | }: {
142 | value: ItemT | ItemT[] | null | undefined;
143 | multiple: boolean | undefined;
144 | getOptionValue: (option: ItemT) => string | number;
145 | }
146 | ) {
147 | return a?.filter((o) => {
148 | let selected = multiple
149 | ? (rValue as ItemT[])?.some(
150 | (v) => getOptionValue(v) === getOptionValue(o)
151 | )
152 | : rValue && getOptionValue(rValue as ItemT) === getOptionValue(o);
153 |
154 | return !selected;
155 | });
156 | }
157 |
158 | export default function Autocomplete(
159 | props: AutocompleteMultipleProps | AutocompleteSingleProps
160 | ) {
161 | // const window = useWindowDimensions();
162 | const theme = useTheme();
163 | const { scrollableRef, scrollX, scrollY } = useAutocomplete();
164 | const {
165 | testID,
166 | loading,
167 | ListComponent,
168 | inputProps: { onChangeText, defaultValue, ...inputProps } = {},
169 | listProps,
170 | groupBy,
171 | multiple,
172 | options,
173 | style,
174 | value,
175 | getOptionValue = (option: ItemT) =>
176 | (option as any).id || (option as any).key || (option as any).value,
177 | getOptionLabel = (option: ItemT) =>
178 | (option as any).label || (option as any).name || (option as any).title,
179 | getOptionDescription = (option: ItemT) => (option as any).description,
180 | getOptionIcon = (option: ItemT) => (option as any).icon,
181 | filterOptions = (a, b) => defaultFilterOptions(a, b),
182 | } = props;
183 | const { value: values, onChange: onChangeMultiple } =
184 | props as AutocompleteMultipleProps;
185 | const { value: singleValue, onChange: onChangeSingle } =
186 | props as AutocompleteSingleProps;
187 |
188 | const inputContainerDimensions = useComponentDimensions();
189 | const chipsDimensions = useComponentDimensions();
190 |
191 | const chipContainerRef = useAnimatedRef();
192 | const inputContainerRef = useAnimatedRef();
193 | const inputRef = React.useRef(null);
194 | const [inputValue, setInputValue] = React.useState(defaultValue || '');
195 | const [visible, setVisible] = React.useState(false);
196 | const [focused, setFocused] = React.useState(false);
197 |
198 | const getOptionLabelRef = useLatest(getOptionLabel);
199 | React.useEffect(() => {
200 | if (!multiple) {
201 | if (singleValue) {
202 | setInputValue(getOptionLabelRef.current(singleValue));
203 | } else {
204 | setInputValue('');
205 | }
206 | }
207 | }, [getOptionLabelRef, multiple, singleValue]);
208 |
209 | const changeText = (v: string) => {
210 | // setVisible(true);
211 | setInputValue(v);
212 | onChangeText?.(v);
213 | };
214 | const blur = (_: NativeSyntheticEvent) => {
215 | // console.log('blur', e);
216 | // setVisible(false);
217 | setFocused(false);
218 | };
219 | const focus = (_: NativeSyntheticEvent) => {
220 | setVisible(true);
221 | setFocused(true);
222 | };
223 |
224 | const filterOptionsRef = useLatest(filterOptions);
225 | const groupByRef = useLatest(groupBy);
226 | const getOptionValueRef = useLatest(getOptionValue);
227 | const getOptionDescriptionRef = useLatest(getOptionDescription);
228 |
229 | const isFocusedAndValueIsSameAsSearch =
230 | (singleValue && focused && inputValue === getOptionLabel(singleValue)) ||
231 | false;
232 |
233 | // console.log({
234 | // singleValue,
235 | // focused,
236 | // inputValue,
237 | // inputValueCompareTo: singleValue && getOptionLabel(singleValue),
238 | // isFocusedAndValueIsSameAsSearch,
239 | // });
240 |
241 | const data = React.useMemo(
242 | () =>
243 | filterOptionsRef.current(
244 | removeSelected(options, {
245 | value,
246 | multiple,
247 | getOptionValue: getOptionValueRef.current,
248 | }),
249 | {
250 | isFocusedAndValueIsSameAsSearch,
251 | getOptionLabel: getOptionLabelRef.current,
252 | getOptionDescription: getOptionDescriptionRef.current,
253 | inputValue,
254 | }
255 | ),
256 | [
257 | isFocusedAndValueIsSameAsSearch,
258 | filterOptionsRef,
259 | inputValue,
260 | value,
261 | multiple,
262 | options,
263 | getOptionValueRef,
264 | getOptionLabelRef,
265 | getOptionDescriptionRef,
266 | ]
267 | );
268 |
269 | const { highlightedIndex, handleKeyPress } = useHighlighted({
270 | inputValue,
271 | setInputValue,
272 | data,
273 | multiple,
274 | values,
275 | onChangeMultiple,
276 | onChangeSingle,
277 | inputRef,
278 | setVisible,
279 | });
280 |
281 | const sections = React.useMemo(() => {
282 | if (!groupByRef || !groupByRef.current) {
283 | return [];
284 | }
285 | let grouped: { [key: string]: ItemT[] } = {};
286 | data?.forEach((o) => {
287 | const key = groupByRef.current!(o);
288 | const current = grouped[key];
289 | if (current) {
290 | current.push(o);
291 | } else {
292 | grouped[key] = [o];
293 | }
294 | });
295 |
296 | return Object.keys(grouped).map((k) => ({
297 | title: k,
298 | data: grouped[k],
299 | }));
300 | }, [data, groupByRef]);
301 |
302 | const press = React.useCallback(
303 | (o: ItemT) => {
304 | if (multiple) {
305 | inputRef.current?.focus();
306 | onChangeMultiple([...(values || []), o]);
307 | setInputValue('');
308 | } else {
309 | onChangeSingle(o);
310 | setVisible(false);
311 | }
312 | },
313 | [multiple, setInputValue, onChangeMultiple, onChangeSingle, values]
314 | );
315 |
316 | const remove = React.useCallback(
317 | (o: ItemT) => {
318 | if (multiple) {
319 | const excludeCurrent = (values || []).filter(
320 | (vo) => getOptionValueRef.current(vo) !== getOptionValueRef.current(o)
321 | );
322 | onChangeMultiple(excludeCurrent);
323 | }
324 | },
325 | [getOptionValueRef, multiple, onChangeMultiple, values]
326 | );
327 |
328 | const automaticScrollProps = useAutomaticScroller({
329 | highlightedIndex,
330 | sections,
331 | groupBy,
332 | });
333 |
334 | const minimalDropdownWidth = 250;
335 | const dropdownWidth = inputContainerDimensions.width;
336 | const remainingSpace = useDerivedValue(
337 | () => inputContainerDimensions.width.value - chipsDimensions.width.value,
338 | [inputContainerDimensions.width, chipsDimensions.width]
339 | );
340 |
341 | const shouldEnter = useDerivedValue(
342 | () =>
343 | chipsDimensions.height.value > 45 ||
344 | remainingSpace.value < minimalDropdownWidth,
345 | [chipsDimensions.height, remainingSpace]
346 | );
347 | const hasMultipleValue = multiple && (values || []).length > 0;
348 |
349 | // const animatedInputStyle = useAnimatedStyle(() => {
350 | // return {
351 | // height: hasMultipleValue
352 | // ? shouldEnter
353 | // ? chipsDimensions.height.value + 36 + 46
354 | // : chipsDimensions.height.value + 36
355 | // : undefined,
356 | // };
357 | // }, [chipsDimensions.height, hasMultipleValue, shouldEnter]);
358 | const highlightedColor = React.useMemo(
359 | () =>
360 | theme.dark
361 | ? Color(theme.colors.onBackground).alpha(0.2).rgb().string()
362 | : Color(theme.colors.onBackground).alpha(0.1).rgb().string(),
363 | [theme.dark, theme.colors.onBackground]
364 | );
365 |
366 | const innerListProps = {
367 | testID: `${testID}-autocomplete-list`,
368 | keyboardDismissMode: 'on-drag',
369 | keyboardShouldPersistTaps: 'handled',
370 | contentInsetAdjustmentBehavior: 'always',
371 | renderItem: ({
372 | item,
373 | index,
374 | section,
375 | }: {
376 | item: ItemT;
377 | index: number;
378 | section?: any;
379 | }) => {
380 | const key = getOptionValue(item);
381 | let realIndex = index;
382 | if (section) {
383 | // what the hell...
384 | const sectionIndex = sections.indexOf(section);
385 | const indexesBefore = sections
386 | .filter((_, i) => i < sectionIndex)
387 | .reduce((a, b) => a + b.data.length, 0);
388 | realIndex = indexesBefore + index;
389 | }
390 | return (
391 |
392 | testID={`${testID}-autocomplete-item-${key}`}
393 | key={key}
394 | highlightedColor={highlightedColor}
395 | title={getOptionLabel(item)}
396 | description={getOptionDescription(item)}
397 | icon={getOptionIcon(item)}
398 | selected={highlightedIndex === realIndex}
399 | onPress={press}
400 | option={item}
401 | />
402 | );
403 | },
404 | keyExtractor: (item: ItemT) => getOptionValue(item),
405 | extraData: { highlightedIndex },
406 | ...automaticScrollProps,
407 | };
408 |
409 | const SectionListComponent = ListComponent ? ListComponent : SectionList;
410 | const FinalListComponent = ListComponent ? ListComponent : FlatList;
411 |
412 | const inputStyle = (inputProps as any)?.style;
413 | const backgroundColor = React.useMemo(() => {
414 | if (inputStyle) {
415 | const flattenStyle = StyleSheet.flatten(inputStyle);
416 | if (flattenStyle.backgroundColor) {
417 | return flattenStyle.backgroundColor;
418 | }
419 | }
420 | return theme.colors.background;
421 | }, [theme, inputStyle]);
422 | const onPressOutside = React.useCallback(() => {
423 | setVisible(false);
424 | }, [setVisible]);
425 |
426 | // console.log({
427 | // visible,
428 | // inputDim: inputContainerDimensions.dimensions,
429 | // chipsDimensions,
430 | // shouldEnter,
431 | // });
432 |
433 | const textInputIcon = singleValue ? getOptionIcon(singleValue) : undefined;
434 | return (
435 |
436 |
441 | 0 ? ' ' : ''}
447 | left={
448 | textInputIcon && !props.disableInputPrefixIcon ? (
449 |
450 | ) : undefined
451 | }
452 | {...inputProps}
453 | style={[inputProps.style, styles.full]}
454 | // @ts-ignore web only props
455 | accessibilityHasPopup={true}
456 | render={(params) => {
457 | return (
458 |
469 | );
470 | }}
471 | />
472 | {(multiple && visible) || (!multiple && value) ? (
473 | {
479 | setVisible(false);
480 | setInputValue('');
481 | if (multiple) {
482 | onChangeMultiple([]);
483 | } else {
484 | onChangeSingle(undefined);
485 | }
486 | }}
487 | />
488 | ) : null}
489 | {
494 | if (visible) {
495 | inputRef.current?.blur();
496 | setVisible(false);
497 | } else {
498 | inputRef.current?.focus();
499 | setVisible(true);
500 | }
501 | }}
502 | />
503 |
504 | {multiple && (
505 |
512 | {values?.map((o) => (
513 | remove(o)}
516 | style={styles.chip}
517 | icon={getOptionIcon(o)}
518 | >
519 | {getOptionLabel(o)}
520 |
521 | ))}
522 |
523 | )}
524 | {loading ? : null}
525 | {visible ? (
526 |
527 |
536 | {groupBy ? (
537 |
538 | {...listProps}
539 | {...innerListProps}
540 | sections={sections}
541 | renderSectionHeader={({ section: { title } }: any) => (
542 | {title}
543 | )}
544 | onScrollToIndexFailed={(info: any) => {
545 | // TODO: make sure everything uses fixed heights so this error won't be there
546 | // e.g.: getItemLayout={getSectionListItemLayout}
547 | console.error(info);
548 | }}
549 | />
550 | ) : (
551 |
552 | {...listProps}
553 | {...innerListProps}
554 | getItemLayout={getFlatListItemLayout}
555 | data={data}
556 | />
557 | )}
558 |
559 |
560 | ) : null}
561 |
562 | );
563 | }
564 |
565 | const AnimatedNativeInput = Animated.createAnimatedComponent(NativeTextInput);
566 | const NativeTextInputWithAnimatedStyles = React.forwardRef(
567 | (
568 | {
569 | shouldEnter,
570 | chipsHeight,
571 | chipsWidth,
572 | style,
573 | multiple,
574 | ...rest
575 | }: TextInputProps & {
576 | multiple: boolean | undefined;
577 | shouldEnter: DerivedValue;
578 | chipsHeight: SharedValue;
579 | chipsWidth: SharedValue;
580 | },
581 | forwardedRef: any
582 | ) => {
583 | const originalStyle = StyleSheet.flatten(style);
584 |
585 | const orgTop = Number(originalStyle.paddingTop) || 0;
586 | const orgLeft = Number(originalStyle.paddingLeft) || 0;
587 | const height = Number(originalStyle.height) || 0;
588 | const animatedStyle = useAnimatedStyle(() => {
589 | if (!multiple) {
590 | return {};
591 | }
592 | const addTop = shouldEnter.value ? chipsHeight.value + 18 : 18;
593 |
594 | return {
595 | paddingTop: orgTop + addTop,
596 | paddingLeft: orgLeft + (shouldEnter.value ? 0 : chipsWidth.value),
597 | height: height + addTop,
598 | };
599 | }, [multiple, orgLeft, orgTop, shouldEnter, chipsHeight, chipsWidth]);
600 |
601 | return (
602 |
607 | );
608 | }
609 | );
610 |
611 | const styles = StyleSheet.create({
612 | modalBackground: {
613 | flex: 1,
614 | },
615 | menu: {
616 | position: 'relative',
617 | },
618 | chipsWrapper: {
619 | flexDirection: 'row',
620 | position: 'absolute',
621 | flexWrap: 'wrap',
622 | top: 32,
623 | left: 12,
624 | },
625 | chip: { marginRight: 6, marginBottom: 6, flexShrink: 1 },
626 |
627 | inputContainer: { alignItems: 'center', flexDirection: 'row' },
628 | full: { flex: 1 },
629 | closeButton: {
630 | position: 'absolute',
631 | bottom: 6,
632 | right: 36,
633 | },
634 | arrowIconButton: {
635 | position: 'absolute',
636 | bottom: 5,
637 | right: 0,
638 | },
639 | loading: { position: 'absolute', right: 12, top: 24 },
640 | });
641 |
--------------------------------------------------------------------------------
/src/AutocompleteContext.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import Animated, { useSharedValue } from 'react-native-reanimated';
3 |
4 | type AutocompleteContextType = {
5 | scrollableRef: React.RefObject;
6 | scrollX: Animated.SharedValue;
7 | scrollY: Animated.SharedValue;
8 | };
9 | export const AutocompleteContext = React.createContext(
10 | undefined as any
11 | );
12 |
13 | export function useAutocomplete() {
14 | let values = React.useContext(AutocompleteContext);
15 | if (!values) {
16 | console.warn(
17 | '[react-native-paper-autocomplete] your autocomplete is currently not wrapped inside a supported ' +
18 | 'autocomplete scrollable, this could result in unexpected behavior and bugs. If this is inside a ' +
19 | 'non-scrollable container you can ignore this message'
20 | );
21 | }
22 | const zero = useSharedValue(0);
23 | const fallbackValues = React.useMemo(() => {
24 | const fb: AutocompleteContextType = {
25 | scrollableRef: { current: null },
26 | scrollX: zero,
27 | scrollY: zero,
28 | };
29 | return fb;
30 | }, [zero]);
31 |
32 | return values || fallbackValues;
33 | }
34 |
--------------------------------------------------------------------------------
/src/AutocompleteFlatList.tsx:
--------------------------------------------------------------------------------
1 | import Animated from 'react-native-reanimated';
2 | import { AutocompleteContext } from './AutocompleteContext';
3 | import type { FlatListProps } from 'react-native';
4 | import * as React from 'react';
5 | import { useScrollableProps } from './shared';
6 |
7 | function AutocompleteFlatList(rest: FlatListProps, ref: any) {
8 | const { scrollableRef, scrollX, scrollY, scrollableProps } =
9 | useScrollableProps(rest, ref);
10 | const Flat = Animated.FlatList as any;
11 | return (
12 |
13 |
14 |
15 | );
16 | }
17 |
18 | export default React.forwardRef(AutocompleteFlatList);
19 |
--------------------------------------------------------------------------------
/src/AutocompleteItem.tsx:
--------------------------------------------------------------------------------
1 | import { List } from 'react-native-paper';
2 | import * as React from 'react';
3 | import type { IconSource } from './icon';
4 |
5 | function AutocompleteItem({
6 | testID,
7 | selected,
8 | title,
9 | description,
10 | icon,
11 | option,
12 | onPress,
13 | highlightedColor,
14 | }: {
15 | testID: string;
16 | selected: boolean;
17 | title: string | number;
18 | description: string | number | undefined;
19 | icon: IconSource | undefined;
20 | option: T;
21 | onPress: (o: T) => void;
22 | highlightedColor: string;
23 | }) {
24 | return (
25 |
35 | : undefined
36 | }
37 | title={title}
38 | description={description}
39 | style={
40 | selected
41 | ? {
42 | backgroundColor: highlightedColor,
43 | }
44 | : undefined
45 | }
46 | onPress={() => {
47 | onPress(option);
48 | }}
49 | />
50 | );
51 | }
52 |
53 | export default React.memo(AutocompleteItem) as typeof AutocompleteItem;
54 |
--------------------------------------------------------------------------------
/src/AutocompleteScrollView.tsx:
--------------------------------------------------------------------------------
1 | import Animated from 'react-native-reanimated';
2 | import { AutocompleteContext } from './AutocompleteContext';
3 | import type { ScrollViewProps } from 'react-native';
4 | import * as React from 'react';
5 | import { useScrollableProps } from './shared';
6 |
7 | function AutocompleteScrollView(rest: ScrollViewProps, ref: any) {
8 | const { scrollableRef, scrollX, scrollY, scrollableProps } =
9 | useScrollableProps(rest, ref);
10 | return (
11 |
12 |
13 |
14 | );
15 | }
16 | export default React.forwardRef(AutocompleteScrollView);
17 |
--------------------------------------------------------------------------------
/src/PortalContent.native.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { Portal } from 'react-native-paper';
3 | import { StyleSheet, TouchableOpacity } from 'react-native';
4 |
5 | export default function PortalContent({
6 | children,
7 | onPressOutside,
8 | }: {
9 | children: any;
10 | visible: boolean;
11 | onPressOutside: () => void;
12 | }) {
13 | return (
14 |
15 | {children}
16 |
20 |
21 | );
22 | }
23 |
--------------------------------------------------------------------------------
/src/PortalContent.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import usePressOutside from './usePressOutside';
3 | import { View, StyleSheet } from 'react-native';
4 | import { Portal } from 'react-native-paper';
5 |
6 | export default function PortalContent({
7 | children,
8 | visible,
9 | onPressOutside,
10 | }: {
11 | children: any;
12 | visible: boolean;
13 | onPressOutside: () => void;
14 | }) {
15 | const ref = React.useRef(null);
16 | usePressOutside(ref, onPressOutside);
17 |
18 | if (!visible) {
19 | return null;
20 | }
21 | return (
22 |
23 |
35 | {children}
36 |
37 |
38 | );
39 | }
40 |
--------------------------------------------------------------------------------
/src/PositionedSurface.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import {
3 | StyleSheet,
4 | Platform,
5 | useWindowDimensions,
6 | ScrollView,
7 | } from 'react-native';
8 | import Animated, {
9 | SharedValue,
10 | useAnimatedStyle,
11 | useDerivedValue,
12 | // FadeInDown,
13 | } from 'react-native-reanimated';
14 | import usePosition from './usePosition';
15 | import AnimatedSurface from './AnimatedSurface';
16 | import type { MD3DarkTheme } from 'react-native-paper';
17 | import useKeyboardHeight from './useKeyboardHeight';
18 |
19 | const SCROLLING_PADDING = 120;
20 |
21 | export default function PositionedSurface({
22 | scrollableRef,
23 | inputContainerRef,
24 | children,
25 | theme,
26 | dropdownWidth,
27 | inputContainerHeight,
28 | scrollX,
29 | scrollY,
30 | }: {
31 | scrollableRef: React.RefObject;
32 | inputContainerRef: React.RefObject;
33 | scrollX: SharedValue;
34 | scrollY: SharedValue;
35 | dropdownWidth: SharedValue;
36 | inputContainerHeight: SharedValue;
37 | children: any;
38 | theme: typeof MD3DarkTheme;
39 | }) {
40 | const dimensions = useWindowDimensions();
41 | const keyboardHeight = useKeyboardHeight(dimensions);
42 | const position = usePosition({
43 | inputContainerRef,
44 | scrollX,
45 | scrollY,
46 | });
47 |
48 | const translateX = useDerivedValue(
49 | () => position.value.x - scrollX.value,
50 | [position, scrollX]
51 | );
52 |
53 | const translateY = useDerivedValue(
54 | () => position.value.y + inputContainerHeight.value - scrollY.value,
55 | [position, inputContainerHeight, scrollY]
56 | );
57 | const isWeb = Platform.OS === 'web';
58 |
59 | React.useLayoutEffect(() => {
60 | if (isWeb) {
61 | return;
62 | }
63 |
64 | const timerId = setTimeout(() => {
65 | const scrollable = scrollableRef.current as any as ScrollView;
66 | if (!scrollable?.scrollTo) {
67 | console.debug(
68 | '[react-native-paper-autocomplete] no scrollView to scroll in'
69 | );
70 | }
71 | scrollable?.scrollTo?.({
72 | x: position.value.x, // - TODO: inputContainer.width?
73 | y: position.value.y - SCROLLING_PADDING,
74 | animated: true,
75 | });
76 | }, 100);
77 | return () => clearTimeout(timerId);
78 | }, [position.value, isWeb, scrollableRef]);
79 |
80 | const animatedStyle = useAnimatedStyle(() => {
81 | if (isWeb) {
82 | return {
83 | transform: [
84 | {
85 | translateY: translateY.value,
86 | },
87 | {
88 | translateX: translateX.value,
89 | },
90 | ],
91 | };
92 | }
93 | return {
94 | // transform is buggy at least on iOS at inital re-render
95 | top: translateY.value,
96 | left: translateX.value,
97 | };
98 | }, [dropdownWidth, translateX, translateY]);
99 | const animatedSurfaceStyle = useAnimatedStyle(() => {
100 | return {
101 | maxHeight:
102 | dimensions.height - keyboardHeight.value - SCROLLING_PADDING * 2,
103 | };
104 | }, [dimensions.height - keyboardHeight.value]);
105 |
106 | return (
107 |
111 |
122 | {children}
123 |
124 |
125 | );
126 | }
127 |
128 | const styles = StyleSheet.create({
129 | surface: { zIndex: 100 },
130 | });
131 |
--------------------------------------------------------------------------------
/src/createAutocompleteScrollable.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { useScrollableProps, AutocompleteScrollableProps } from './shared';
3 | import { AutocompleteContext } from './AutocompleteContext';
4 |
5 | export default function createAutocompleteScrollable<
6 | T extends React.ComponentType
7 | >(WrappedComponent: T): React.ComponentType {
8 | return React.forwardRef(function (rest, ref) {
9 | const { scrollableRef, scrollX, scrollY, scrollableProps } =
10 | useScrollableProps(rest, ref);
11 | const WW = WrappedComponent as any;
12 | return (
13 |
14 |
15 |
16 | );
17 | }) as any;
18 | }
19 |
--------------------------------------------------------------------------------
/src/icon.tsx:
--------------------------------------------------------------------------------
1 | // copied from react-native-paper
2 |
3 | import type React from 'react';
4 | import type { ImageSourcePropType } from 'react-native';
5 | declare type IconSourceBase = string | ImageSourcePropType;
6 | export declare type IconSource =
7 | | IconSourceBase
8 | | Readonly<{
9 | source: IconSourceBase;
10 | direction: 'rtl' | 'ltr' | 'auto';
11 | }>
12 | | ((
13 | props: IconProps & {
14 | color: string;
15 | }
16 | ) => React.ReactNode);
17 | declare type IconProps = {
18 | size: number;
19 | allowFontScaling?: boolean;
20 | };
21 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | export { default as Autocomplete, defaultFilterOptions } from './Autocomplete';
2 | export type {
3 | FilterOptionsParams,
4 | AutocompleteBaseProps,
5 | AutocompleteMultipleProps,
6 | AutocompleteSingleProps,
7 | } from './Autocomplete';
8 | export { default as AutocompleteScrollView } from './AutocompleteScrollView';
9 | export { default as AutocompleteFlatList } from './AutocompleteFlatList';
10 | export { default as createAutocompleteScrollable } from './createAutocompleteScrollable';
11 |
--------------------------------------------------------------------------------
/src/mergeRefs.tsx:
--------------------------------------------------------------------------------
1 | import type * as React from 'react';
2 |
3 | export function mergeRefs(
4 | refs: Array | React.LegacyRef>
5 | ): React.RefCallback {
6 | return (value) => {
7 | refs.forEach((ref) => {
8 | if (typeof ref === 'function') {
9 | ref(value);
10 | } else if (ref != null) {
11 | (ref as React.MutableRefObject).current = value;
12 | }
13 | });
14 | };
15 | }
16 |
--------------------------------------------------------------------------------
/src/shared.tsx:
--------------------------------------------------------------------------------
1 | import {
2 | runOnJS,
3 | useAnimatedRef,
4 | useAnimatedScrollHandler,
5 | useSharedValue,
6 | } from 'react-native-reanimated';
7 | import type {
8 | NativeScrollEvent,
9 | NativeSyntheticEvent,
10 | ScrollViewProps,
11 | } from 'react-native';
12 | import { mergeRefs } from './mergeRefs';
13 |
14 | export type AutocompleteScrollableProps = {
15 | ref?: any;
16 | scrollEventThrottle?: number | undefined; // null
17 | keyboardShouldPersistTaps?:
18 | | boolean
19 | | 'always'
20 | | 'never'
21 | | 'handled'
22 | | undefined;
23 | onScroll?:
24 | | ((event: NativeSyntheticEvent) => void)
25 | | undefined;
26 | };
27 |
28 | export function useScrollableProps({ onScroll }: ScrollViewProps, ref: any) {
29 | const scrollableRef = useAnimatedRef();
30 | const scrollX = useSharedValue(0);
31 | const scrollY = useSharedValue(0);
32 | const scrollHandler = useAnimatedScrollHandler((e) => {
33 | const { x, y } = e.contentOffset;
34 | scrollX.value = x;
35 | scrollY.value = y;
36 |
37 | if (onScroll) {
38 | // https://github.com/software-mansion/react-native-reanimated/issues/2426
39 | runOnJS(onScroll)({ nativeEvent: e } as any);
40 | }
41 | });
42 | const scrollableProps: AutocompleteScrollableProps = {
43 | ref: mergeRefs([scrollableRef, ref]),
44 | scrollEventThrottle: 16,
45 | keyboardShouldPersistTaps: 'handled',
46 | onScroll: scrollHandler,
47 | };
48 | return { scrollableRef, scrollX, scrollY, scrollableProps };
49 | }
50 |
--------------------------------------------------------------------------------
/src/useAutomaticScroller.native.ts:
--------------------------------------------------------------------------------
1 | export default function useAutomaticScroller() {
2 | return {};
3 | }
4 |
--------------------------------------------------------------------------------
/src/useAutomaticScroller.ts:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import type { FlatList, SectionList } from 'react-native';
3 | import useLatest from './useLatest';
4 |
5 | export default function useAutomaticScroller({
6 | highlightedIndex,
7 | sections,
8 | groupBy,
9 | }: {
10 | highlightedIndex: number;
11 | sections: { title: string; data: ItemT[] }[];
12 | groupBy?: (option: ItemT) => string;
13 | }) {
14 | const viewableItems = React.useRef([]);
15 | const isSectionList = !!groupBy;
16 | const flatListRef = React.useRef(null);
17 | const sectionListRef = React.useRef(null);
18 | const sectionsRef = useLatest(sections);
19 |
20 | const onViewableItemsChanged = React.useCallback(
21 | (p: any) => {
22 | viewableItems.current = p.viewableItems;
23 | },
24 | [viewableItems]
25 | );
26 |
27 | React.useEffect(() => {
28 | if (isSectionList) {
29 | const viewAbleIndexes = viewableItems.current
30 | .map(({ index, section }) => {
31 | const sectionIndex = sectionsRef.current.indexOf(section);
32 | const indexesBefore = sectionsRef.current
33 | .filter((_, i) => i < sectionIndex)
34 | .reduce((a, b) => a + b.data.length, 0);
35 | if (index === null || index === undefined) {
36 | return null;
37 | }
38 | return {
39 | sectionIndex: sectionsRef.current.indexOf(section),
40 | index: index,
41 | realIndex: indexesBefore + (index || 0),
42 | };
43 | })
44 | .filter((n) => n);
45 | const isViewable = viewAbleIndexes
46 | .map((vi) => vi!.index)
47 | .includes(highlightedIndex);
48 |
49 | if (!isViewable) {
50 | const scrollParams = findSectionScrollParams({
51 | sections: sectionsRef.current,
52 | highlightedIndex,
53 | });
54 |
55 | sectionListRef.current?.scrollToLocation(scrollParams);
56 | }
57 | } else {
58 | const isViewable = viewableItems.current
59 | .map((vi) => vi.index)
60 | .includes(highlightedIndex);
61 | if (isViewable) {
62 | return;
63 | }
64 | flatListRef.current?.scrollToIndex({
65 | index: highlightedIndex,
66 | animated: false,
67 | });
68 | }
69 | }, [highlightedIndex, sectionsRef, flatListRef, isSectionList]);
70 |
71 | return {
72 | onViewableItemsChanged,
73 | ref: (isSectionList ? sectionListRef : flatListRef) as any,
74 | };
75 | }
76 |
77 | function findSectionScrollParams({
78 | sections,
79 | highlightedIndex,
80 | }: {
81 | sections: any[];
82 | highlightedIndex: number;
83 | }) {
84 | let i = 0;
85 | for (let sectionIndex = 0; sectionIndex < sections.length; sectionIndex++) {
86 | const section = sections[sectionIndex];
87 | for (let itemIndex = 0; itemIndex < section.data.length; itemIndex++) {
88 | if (i === highlightedIndex) {
89 | return {
90 | itemIndex,
91 | sectionIndex,
92 | animated: false,
93 | };
94 | }
95 | i++;
96 | }
97 | }
98 | return {
99 | itemIndex: 0,
100 | sectionIndex: 0,
101 | animated: false,
102 | };
103 | }
104 |
--------------------------------------------------------------------------------
/src/useComponentDimensions.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { SharedValue, useSharedValue } from 'react-native-reanimated';
3 | import type { LayoutChangeEvent } from 'react-native';
4 |
5 | export type AnimatedComponentDimensions = {
6 | width: SharedValue;
7 | height: SharedValue;
8 | };
9 |
10 | export default function useComponentDimensions() {
11 | const width = useSharedValue(0);
12 | const height = useSharedValue(0);
13 |
14 | const onLayout = React.useCallback(
15 | (e: LayoutChangeEvent) => {
16 | const layout = e.nativeEvent.layout;
17 |
18 | width.value = layout.width;
19 | height.value = layout.height;
20 | //
21 | // return Animated.event(
22 | // [
23 | // {
24 | // nativeEvent: {
25 | // layout: {
26 | // width,
27 | // height,
28 | // },
29 | // },
30 | // },
31 | // ],
32 | // {
33 | // useNativeDriver: true,
34 | // }
35 | // );
36 | },
37 | [width, height]
38 | );
39 | // console.log('useComponentDimensions', dimensions);
40 | return {
41 | onLayout,
42 | width,
43 | height,
44 | };
45 | }
46 |
--------------------------------------------------------------------------------
/src/useHighlighted.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import type {
3 | NativeSyntheticEvent,
4 | TextInput as NativeTextInput,
5 | TextInputKeyPressEventData,
6 | } from 'react-native';
7 | import useLatest from './useLatest';
8 | import type { Dispatch, SetStateAction, MutableRefObject } from 'react';
9 |
10 | export default function useHighlighted({
11 | inputValue,
12 | setInputValue,
13 | data,
14 | multiple,
15 | values,
16 | onChangeMultiple,
17 | onChangeSingle,
18 |
19 | inputRef,
20 | setVisible,
21 | }: {
22 | values: ItemT[] | null | undefined;
23 | inputValue: string;
24 | setInputValue: Dispatch>;
25 | data: readonly ItemT[] | null | undefined;
26 | multiple: undefined | boolean;
27 | onChangeMultiple: (v: ItemT[]) => void;
28 | onChangeSingle: (v: ItemT | undefined) => void;
29 |
30 | inputRef: MutableRefObject;
31 | setVisible: Dispatch>;
32 | }) {
33 | const [highlightedIndex, setHighlightedIndex] = React.useState(0);
34 | const highlightedRef = useLatest(highlightedIndex);
35 | const previousData = usePrevious(data);
36 |
37 | React.useEffect(() => {
38 | if (previousData) {
39 | const previousItem = previousData[highlightedRef.current];
40 | const currentItem = data?.indexOf(previousItem);
41 |
42 | if (currentItem && currentItem >= 0) {
43 | setHighlightedIndex(currentItem);
44 | return;
45 | }
46 | }
47 |
48 | const exists = data?.[highlightedRef.current];
49 | if (exists) {
50 | return;
51 | }
52 | const before = data?.[highlightedRef.current - 1];
53 | if (before) {
54 | setHighlightedIndex((prev) => prev - 1);
55 | return;
56 | }
57 | setHighlightedIndex(0);
58 | }, [data, previousData, setHighlightedIndex, highlightedRef]);
59 |
60 | const removeLast = React.useCallback(() => {
61 | if (multiple) {
62 | onChangeMultiple(
63 | (values || []).filter((_, i: number) => i !== (values || []).length - 1)
64 | );
65 | }
66 | }, [multiple, onChangeMultiple, values]);
67 |
68 | const pressHighlighted = React.useCallback(() => {
69 | if (multiple) {
70 | const selectedOption = data?.[highlightedRef.current];
71 | if (selectedOption) {
72 | onChangeMultiple([...(values || []), selectedOption]);
73 | }
74 | setInputValue('');
75 | } else {
76 | const selectedOption = data?.[highlightedRef.current];
77 | onChangeSingle(selectedOption);
78 | inputRef.current?.blur();
79 | setVisible(false);
80 | }
81 | }, [
82 | data,
83 | inputRef,
84 | setInputValue,
85 | setVisible,
86 | highlightedRef,
87 | multiple,
88 | onChangeMultiple,
89 | onChangeSingle,
90 | values,
91 | ]);
92 |
93 | const dataRef = useLatest(data);
94 | const handleKeyPress = React.useCallback(
95 | (e: NativeSyntheticEvent) => {
96 | const dataLength = dataRef.current?.length || 0;
97 | const lastIndex = dataLength - 1;
98 | const key = e.nativeEvent.key;
99 | switch (key) {
100 | case 'Backspace':
101 | if (inputValue === '') {
102 | removeLast();
103 | }
104 | break;
105 | case 'Enter':
106 | if (dataLength === 0) {
107 | return;
108 | }
109 | pressHighlighted();
110 | break;
111 | case 'ArrowDown':
112 | if ((dataLength || 0) - 1 >= highlightedRef.current + 1) {
113 | setHighlightedIndex((prev) => prev + 1);
114 | } else {
115 | setHighlightedIndex(0);
116 | }
117 | break;
118 | case 'ArrowUp':
119 | if (highlightedRef.current >= 1) {
120 | setHighlightedIndex((prev) => prev - 1);
121 | } else {
122 | setHighlightedIndex(lastIndex);
123 | }
124 | break;
125 | case 'Home':
126 | setHighlightedIndex(0);
127 | break;
128 | case 'End':
129 | if (dataLength > 0) {
130 | setHighlightedIndex(lastIndex);
131 | }
132 | break;
133 | default:
134 | }
135 | },
136 | [dataRef, highlightedRef, inputValue, pressHighlighted, removeLast]
137 | );
138 |
139 | return {
140 | handleKeyPress,
141 | highlightedIndex,
142 | };
143 | }
144 |
145 | function usePrevious(
146 | value: T
147 | ): React.MutableRefObject['current'] {
148 | const ref = React.useRef();
149 | React.useLayoutEffect(() => {
150 | ref.current = value;
151 | }, [value]);
152 | return ref.current;
153 | }
154 |
--------------------------------------------------------------------------------
/src/useKeyboardHeight.native.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { Keyboard, KeyboardEvent } from 'react-native';
3 | import { useSharedValue } from 'react-native-reanimated';
4 |
5 | function useKeyboardHeight(_: { width: number; height: number }) {
6 | const keyboardHeight = useSharedValue(0);
7 | React.useEffect(() => {
8 | const keyboardDidShow = (frames: KeyboardEvent) => {
9 | keyboardHeight.value = frames.endCoordinates.height;
10 | };
11 |
12 | const keyboardDidHide = () => {
13 | keyboardHeight.value = 0;
14 | };
15 | const keyboardDidShowListener = Keyboard.addListener(
16 | 'keyboardDidShow',
17 | keyboardDidShow
18 | );
19 | const keyboardDidHideListener = Keyboard.addListener(
20 | 'keyboardDidHide',
21 | keyboardDidHide
22 | );
23 |
24 | // cleanup function
25 | return () => {
26 | keyboardDidShowListener.remove();
27 | keyboardDidHideListener.remove();
28 | };
29 | }, [keyboardHeight]);
30 |
31 | return keyboardHeight;
32 | }
33 |
34 | export default useKeyboardHeight;
35 |
--------------------------------------------------------------------------------
/src/useKeyboardHeight.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { useSharedValue } from 'react-native-reanimated';
3 |
4 | function useKeyboardHeight(dimensions: { width: number; height: number }) {
5 | const isTouchDevice = window.matchMedia('(pointer: coarse)').matches;
6 |
7 | // If it's a touch device we conclude that half of the screen will be used by virtual keyboard
8 | const keyboardHeight = useSharedValue(
9 | isTouchDevice ? dimensions.height / 2 : 0
10 | );
11 |
12 | React.useEffect(() => {
13 | // is this api is implemented yet, otherwise we fallback on behaviour above
14 | const virtualKeyboard = (navigator as any).virtualKeyboard;
15 | if (virtualKeyboard) {
16 | const handler = (event: any) => {
17 | const { height } = event.target;
18 | keyboardHeight.value = height;
19 | };
20 | virtualKeyboard.addEventListener('geometrychanged', handler);
21 | return () => {
22 | virtualKeyboard.removeEventListener('geometrychanged', handler);
23 | };
24 | }
25 | return undefined;
26 | }, [keyboardHeight]);
27 | return keyboardHeight;
28 | }
29 |
30 | export default useKeyboardHeight;
31 |
--------------------------------------------------------------------------------
/src/useLatest.ts:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | export default function useLatest(value: T): { readonly current: T } {
4 | const ref = React.useRef(value);
5 | ref.current = value;
6 | return ref;
7 | }
8 |
--------------------------------------------------------------------------------
/src/usePosition.native.tsx:
--------------------------------------------------------------------------------
1 | import type * as React from 'react';
2 | import Animated, {
3 | measure,
4 | useAnimatedReaction,
5 | SharedValue,
6 | useSharedValue,
7 | useDerivedValue,
8 | } from 'react-native-reanimated';
9 |
10 | export default function usePosition({
11 | inputContainerRef,
12 | scrollX,
13 | scrollY,
14 | }: {
15 | scrollX: SharedValue;
16 | scrollY: SharedValue;
17 | inputContainerRef: React.RefObject;
18 | }) {
19 | const measuredValue = useSharedValue<{
20 | width: number;
21 | height: number;
22 | x: number;
23 | y: number;
24 | pageX: number;
25 | pageY: number;
26 | }>({
27 | width: 0,
28 | height: 0,
29 | x: 0,
30 | y: 0,
31 | pageX: 0,
32 | pageY: 0,
33 | });
34 |
35 | // TODO: make this simple with measure function directly in useDerivedValue
36 | // https://github.com/software-mansion/react-native-reanimated/issues/2779
37 | useAnimatedReaction(
38 | () => {
39 | return measure(inputContainerRef);
40 | },
41 | (measured) => {
42 | measuredValue.value = {
43 | ...measured,
44 | pageY: measured.pageY + scrollY.value,
45 | pageX: measured.pageX + scrollX.value,
46 | };
47 | }
48 | );
49 | return useDerivedValue(() => {
50 | return {
51 | x: measuredValue.value.pageX + measuredValue.value.x,
52 | y: measuredValue.value.pageY + measuredValue.value.y,
53 | };
54 | }, [measuredValue, scrollX, scrollY]);
55 | }
56 |
--------------------------------------------------------------------------------
/src/usePosition.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 | import { useLayoutEffect } from 'react';
3 | import Animated, {
4 | SharedValue,
5 | useDerivedValue,
6 | useSharedValue,
7 | } from 'react-native-reanimated';
8 |
9 | export default function usePosition({
10 | inputContainerRef,
11 | scrollX,
12 | scrollY,
13 | }: {
14 | scrollX: SharedValue;
15 | scrollY: SharedValue;
16 | inputContainerRef: React.RefObject;
17 | }) {
18 | const [initial] = React.useState(
19 | getXYFromRef(inputContainerRef, { scrollX, scrollY })
20 | );
21 | const x = useSharedValue(initial.x);
22 | const y = useSharedValue(initial.y);
23 |
24 | useLayoutEffect(() => {
25 | const coordinates = getXYFromRef(inputContainerRef, { scrollX, scrollY });
26 | x.value = coordinates.x;
27 | y.value = coordinates.y;
28 | });
29 |
30 | return useDerivedValue(() => {
31 | return {
32 | x: x.value,
33 | y: y.value,
34 | };
35 | }, [x, y]);
36 | }
37 |
38 | function getXYFromRef(
39 | ref: React.RefObject,
40 | {
41 | scrollX,
42 | scrollY,
43 | }: {
44 | scrollX: SharedValue;
45 | scrollY: SharedValue;
46 | }
47 | ) {
48 | const { x, y } = getBoundingClientRect(ref.current as any);
49 | return {
50 | x: x + scrollX.value + (window?.scrollX || 0),
51 | y: y + scrollY.value + (window?.scrollY || 0),
52 | };
53 | }
54 |
55 | function getBoundingClientRect(node: HTMLElement) {
56 | if (node) {
57 | const isElement = node.nodeType === 1; /* Node.ELEMENT_NODE */
58 | if (isElement && typeof node.getBoundingClientRect === 'function') {
59 | return node.getBoundingClientRect();
60 | }
61 | }
62 | return { x: 0, y: 0 };
63 | }
64 |
--------------------------------------------------------------------------------
/src/usePressOutside.tsx:
--------------------------------------------------------------------------------
1 | import * as React from 'react';
2 |
3 | export default function usePressOutside(
4 | ref: React.MutableRefObject,
5 | handler: () => void
6 | ) {
7 | React.useEffect(
8 | () => {
9 | const listener = (event: any) => {
10 | // Do nothing if clicking ref's element or descendent elements
11 | // console.log({ current: ref.current, handler, event });
12 | if (!ref.current || ref.current.contains(event.target)) {
13 | return;
14 | }
15 |
16 | handler();
17 | };
18 | document.addEventListener('mousedown', listener);
19 | document.addEventListener('touchstart', listener);
20 | return () => {
21 | document.removeEventListener('mousedown', listener);
22 | document.removeEventListener('touchstart', listener);
23 | };
24 | },
25 | // Add ref and handler to effect dependencies
26 | // It's worth noting that because passed in handler is a new ...
27 | // ... function on every render that will cause this effect ...
28 | // ... callback/cleanup to run every render. It's not a big deal ...
29 | // ... but to optimize you can wrap handler in useCallback before ...
30 | // ... passing it into this hook.
31 | [ref, handler]
32 | );
33 | }
34 |
--------------------------------------------------------------------------------
/tsconfig.build.json:
--------------------------------------------------------------------------------
1 |
2 | {
3 | "extends": "./tsconfig",
4 | "exclude": ["example"]
5 | }
6 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "baseUrl": "./",
4 | "paths": {
5 | "react-native-paper-autocomplete": ["./src/index"]
6 | },
7 | "allowUnreachableCode": false,
8 | "allowUnusedLabels": false,
9 | "esModuleInterop": true,
10 | "importsNotUsedAsValues": "error",
11 | "forceConsistentCasingInFileNames": true,
12 | "jsx": "react",
13 | "lib": ["esnext","dom"],
14 | "module": "esnext",
15 | "moduleResolution": "node",
16 | "noFallthroughCasesInSwitch": true,
17 | "noImplicitReturns": true,
18 | "noImplicitUseStrict": false,
19 | "noStrictGenericChecks": false,
20 | "noUnusedLocals": true,
21 | "noUnusedParameters": true,
22 | "resolveJsonModule": true,
23 | "skipLibCheck": true,
24 | "strict": true,
25 | "target": "esnext"
26 | }
27 | }
28 |
--------------------------------------------------------------------------------