├── .circleci
└── config.yml
├── .editorconfig
├── .gitattributes
├── .github
├── ISSUE_TEMPLATE.md
├── PULL_REQUEST_TEMPLATE.md
└── stale.yml
├── .gitignore
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── babel.config.js
├── commitlint.config.js
├── config
└── header.js
├── example
├── .expo-shared
│ └── assets.json
├── App.tsx
├── app.json
├── assets
│ ├── card-back.png
│ ├── card-front.png
│ ├── icon.png
│ ├── placeholder.jpg
│ └── splash.png
├── babel.config.js
├── components
│ ├── Carousel.tsx
│ ├── CarouselItem.tsx
│ ├── Handle.tsx
│ └── Transaction.tsx
├── package-lock.json
├── package.json
├── screens
│ ├── Home.tsx
│ ├── HorizontalFlatListExample.tsx
│ └── SectionListExample.tsx
├── tsconfig.json
└── utils
│ └── index.ts
├── gifs
├── bank.gif
└── maps.gif
├── package-lock.json
├── package.json
├── src
├── __tests__
│ └── index.test.tsx
└── index.tsx
└── tsconfig.json
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | version: 2.1
2 | orbs:
3 | node: circleci/node@1.1.6
4 | jobs:
5 | lint-and-ts:
6 | executor:
7 | name: node/default
8 | steps:
9 | - checkout
10 | - node/with-cache:
11 | steps:
12 | - run: npm install
13 | - run: npm run lint
14 | - run: npm run typescript
15 | workflows:
16 | build-and-test:
17 | jobs:
18 | - lint-and-ts
19 |
20 |
--------------------------------------------------------------------------------
/.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 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | ### Current Behavior
2 |
3 | - What code are you running and what is happening?
4 | - Include a screenshot if it makes sense.
5 |
6 | ### Expected Behavior
7 |
8 | - What do you expect should be happening?
9 | - Include a screenshot or a video if it makes sense.
10 |
11 | ### How to reproduce
12 |
13 | - You must provide a way to reproduce the problem.
14 | - Either re-create the bug on [Snack](https://snack.expo.io) or link to a GitHub repository with code that reproduces the bug.
15 | - Explain how to run the example app and any steps that we need to take to reproduce the issue from the example app, with as much details as possible.
16 |
17 | ### Your Environment
18 |
19 | | | version
20 | | ---------------- | -------
21 | | Platform (Android, iOS or both) |
22 | | react-native-scroll-bottom-sheet |
23 | | react-native |
24 | | react-native-gesture-handler |
25 | | react-native-reanimated |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | Please provide enough information so that others can review your pull request:
2 |
3 | ## Motivation
4 |
5 | Explain the **motivation** for making this change. What existing problem does the pull request solve?
6 |
7 |
--------------------------------------------------------------------------------
/.github/stale.yml:
--------------------------------------------------------------------------------
1 | # Number of days of inactivity before an issue becomes stale
2 | daysUntilStale: 90
3 | # Number of days of inactivity before a stale issue is closed
4 | daysUntilClose: 15
5 | # Issues with these labels will never be considered stale
6 | exemptLabels:
7 | - bug
8 | - security
9 | # Label to use when marking an issue as stale
10 | staleLabel: wontfix
11 | # Comment to post when marking an issue as stale. Set to `false` to disable
12 | markComment: >
13 | This issue has been automatically marked as stale because it has not had
14 | recent activity. It will be closed if no further activity occurs. Thank you
15 | for your contributions.
16 | # Comment to post when closing a stale issue. Set to `false` to disable
17 | closeComment: >
18 | Closing this issue after a prolonged period of inactivity. If this is still present in the latest release, please feel free to create a new issue with up-to-date information.
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # OSX
2 | #
3 | .DS_Store
4 |
5 | # XDE
6 | .expo/
7 |
8 | # VSCode
9 | .vscode/
10 | jsconfig.json
11 |
12 | # node.js
13 | #
14 | node_modules/
15 | npm-debug.log
16 | yarn-debug.log
17 | yarn-error.log
18 |
19 | # BUCK
20 | buck-out/
21 | \.buckd/
22 | android/app/libs
23 | android/keystores/debug.keystore
24 |
25 | # generated by bob
26 | lib/
27 |
--------------------------------------------------------------------------------
/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 bootstrap` in the root directory to install the required dependencies for each package:
8 |
9 | ```sh
10 | yarn bootstrap
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 android
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 | ### Commit message convention
53 |
54 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages:
55 |
56 | - `fix`: bug fixes, e.g. fix crash due to deprecated method.
57 | - `feat`: new features, e.g. add new method to the module.
58 | - `refactor`: code refactor, e.g. migrate from class components to hooks.
59 | - `docs`: changes into documentation, e.g. add usage example for the module..
60 | - `test`: adding or updating tests, eg add integration tests using detox.
61 | - `chore`: tooling changes, e.g. change CI config.
62 |
63 | Our pre-commit hooks verify that your commit message matches this format when committing.
64 |
65 | ### Linting and tests
66 |
67 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/)
68 |
69 | 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.
70 |
71 | Our pre-commit hooks verify that the linter and tests pass when committing.
72 |
73 | ### Scripts
74 |
75 | The `package.json` file contains various scripts for common tasks:
76 |
77 | - `yarn bootstrap`: setup project by installing all dependencies and pods.
78 | - `yarn typescript`: type-check files with TypeScript.
79 | - `yarn lint`: lint files with ESLint.
80 | - `yarn test`: run unit tests with Jest.
81 | - `yarn example start`: start the Metro server for the example app.
82 | - `yarn example android`: run the example app on Android.
83 | - `yarn example ios`: run the example app on iOS.
84 |
85 | ### Sending a pull request
86 |
87 | > **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).
88 |
89 | When you're sending a pull request:
90 |
91 | - Prefer small pull requests focused on one change.
92 | - Verify that linters and tests are passing.
93 | - Review the documentation to make sure it looks good.
94 | - Follow the pull request template when opening a pull request.
95 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue.
96 |
97 | ## Code of Conduct
98 |
99 | ### Our Pledge
100 |
101 | 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.
102 |
103 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
104 |
105 | ### Our Standards
106 |
107 | Examples of behavior that contributes to a positive environment for our community include:
108 |
109 | - Demonstrating empathy and kindness toward other people
110 | - Being respectful of differing opinions, viewpoints, and experiences
111 | - Giving and gracefully accepting constructive feedback
112 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
113 | - Focusing on what is best not just for us as individuals, but for the overall community
114 |
115 | Examples of unacceptable behavior include:
116 |
117 | - The use of sexualized language or imagery, and sexual attention or
118 | advances of any kind
119 | - Trolling, insulting or derogatory comments, and personal or political attacks
120 | - Public or private harassment
121 | - Publishing others' private information, such as a physical or email
122 | address, without their explicit permission
123 | - Other conduct which could reasonably be considered inappropriate in a
124 | professional setting
125 |
126 | ### Enforcement Responsibilities
127 |
128 | 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.
129 |
130 | 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.
131 |
132 | ### Scope
133 |
134 | 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.
135 |
136 | ### Enforcement
137 |
138 | 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.
139 |
140 | All community leaders are obligated to respect the privacy and security of the reporter of any incident.
141 |
142 | ### Enforcement Guidelines
143 |
144 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
145 |
146 | #### 1. Correction
147 |
148 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
149 |
150 | **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.
151 |
152 | #### 2. Warning
153 |
154 | **Community Impact**: A violation through a single incident or series of actions.
155 |
156 | **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.
157 |
158 | #### 3. Temporary Ban
159 |
160 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
161 |
162 | **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.
163 |
164 | #### 4. Permanent Ban
165 |
166 | **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.
167 |
168 | **Consequence**: A permanent ban from any sort of public interaction within the community.
169 |
170 | ### Attribution
171 |
172 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
173 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
174 |
175 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
176 |
177 | [homepage]: https://www.contributor-covenant.org
178 |
179 | For answers to common questions about this code of conduct, see the FAQ at
180 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
181 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Raul Gomez Acuna
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 | # Scroll Bottom Sheet
2 | [](https://www.npmjs.com/package/react-native-scroll-bottom-sheet)
3 | [](https://bundlephobia.com/result?p=react-native-scroll-bottom-sheet)
4 | 
5 | [](https://github.com/rgommezz/react-native-scroll-bottom-sheet/blob/master/LICENSE)
6 |
7 | Cross platform scrollable bottom sheet with virtualisation support and fully native animations, that integrates with all core scrollable components from React Native: [FlatList](https://reactnative.dev/docs/flatlist), [ScrollView](https://reactnative.dev/docs/scrollview) and [SectionList](https://reactnative.dev/docs/sectionlist). Also, it's 100% compatible with Expo.
8 |
9 |
10 |
11 |  |  |
12 | :---------------------:|:------------------:|
13 |
14 |
15 |
16 | ## Features
17 | - **:electron: Virtualisation support**: `FlatList` and `SectionList` components are 1st class citizens, as well as `ScrollView`
18 | - **:fire: Performant**: runs at 60 FPS even on low grade Android devices
19 | - **:white_check_mark: Horizontal mode**: allows for nice implementation of Google or Apple Maps bottom sheets types, where you have several horizontal lists embedded
20 | - **:gear: Minimalistic**: exposes a set of fundamental props to easily control its behaviour, supporting both Timing and Spring animations
21 | - **:point_down: Support for interruptions**: animations can be interrupted anytime smoothly without sudden jumps
22 | - **:sunglasses: Imperative snapping**: for cases where you need to close the bottom sheet by pressing an external touchable
23 | - **:rocket: Animate all the things**: you can animate other elements on the screen based on the bottom sheet position
24 | - **:muscle: No native dependencies**: fully implemented in JS land, thanks to the powerful [Gesture Handler](https://github.com/software-mansion/react-native-gesture-handler) and [Reanimated](https://github.com/software-mansion/react-native-reanimated) libraries
25 | - **:iphone: Expo compatible**: no need to eject to enjoy this component!
26 | - **:hammer_and_wrench: TS definitions**: For those of you like me who can't look back to start a project in plain JS
27 |
28 | ## Installation
29 |
30 | #### npm
31 |
32 | ```sh
33 | npm i react-native-scroll-bottom-sheet
34 | ```
35 |
36 | #### yarn
37 | ```sh
38 | yarn add react-native-scroll-bottom-sheet
39 | ```
40 |
41 | If you don't use Expo, you also need to install [react-native-gesture-handler](https://github.com/software-mansion/react-native-gesture-handler) and [react-native-reanimated](https://github.com/software-mansion/react-native-reanimated) libraries along with this one.
42 |
43 | It's recommended you install a version of gesture handler equal or higher than `1.6.0`, and for reanimated, equal or higher than `1.7.0`. Otherwise you may run into unexpected errors. This library is also compatible with reanimated 2.x, starting with `react-native-reanimated: 2.0.0-alpha.4`.
44 |
45 | ## Usage
46 |
47 | The below is an example using the core `FlatList` from React Native as the scrollable component.
48 |
49 | ```tsx
50 | import React from 'react';
51 | import { Dimensions, StyleSheet, Text, View } from 'react-native';
52 | import ScrollBottomSheet from 'react-native-scroll-bottom-sheet';
53 |
54 | const windowHeight = Dimensions.get('window').height;
55 |
56 | function Example() {
57 | return (
58 |
59 | // If you are using TS, that'll infer the renderItem `item` type
60 | componentType="FlatList"
61 | snapPoints={[128, '50%', windowHeight - 200]}
62 | initialSnapIndex={2}
63 | renderHandle={() => (
64 |
65 |
66 |
67 | )}
68 | data={Array.from({ length: 200 }).map((_, i) => String(i))}
69 | keyExtractor={i => i}
70 | renderItem={({ item }) => (
71 |
72 | {`Item ${item}`}
73 |
74 | )}
75 | contentContainerStyle={styles.contentContainerStyle}
76 | />
77 |
78 | );
79 | }
80 |
81 | const styles = StyleSheet.create({
82 | container: {
83 | flex: 1,
84 | },
85 | contentContainerStyle: {
86 | padding: 16,
87 | backgroundColor: '#F3F4F9',
88 | },
89 | header: {
90 | alignItems: 'center',
91 | backgroundColor: 'white',
92 | paddingVertical: 20,
93 | borderTopLeftRadius: 20,
94 | borderTopRightRadius: 20
95 | },
96 | panelHandle: {
97 | width: 40,
98 | height: 2,
99 | backgroundColor: 'rgba(0,0,0,0.3)',
100 | borderRadius: 4
101 | },
102 | item: {
103 | padding: 20,
104 | justifyContent: 'center',
105 | backgroundColor: 'white',
106 | alignItems: 'center',
107 | marginVertical: 10,
108 | },
109 | });
110 | ```
111 |
112 | ## Props
113 | There are 2 types of props this component receives: explicit and inherited.
114 |
115 | ### Explicit
116 | This is the list of exclusive props that are meant to be used to customise the bottom sheet behaviour.
117 |
118 |
119 | | Name | Required | Type | Description |
120 | | ------------------------- | -------- | ------- | ------------|
121 | | `componentType` | yes | `string ` | 'FlatList', 'ScrollView', or 'SectionList' |
122 | | `snapPoints` | yes | `Array` | Array of numbers and/or percentages that indicate the different resting positions of the bottom sheet (in dp or %), **starting from the top**. If a percentage is used, that would translate to the relative amount of the total window height. If you want that percentage to be calculated based on the parent available space instead, for example to account for safe areas or navigation bars, use it in combination with `topInset` prop |
123 | | `initialSnapIndex` | yes | `number` | Index that references the initial resting position of the drawer, **starting from the top** |
124 | | `renderHandle` | yes | `() => React.ReactNode` | Render prop for the handle, should return a React Element |
125 | | `onSettle` | no | `(index: number) => void` | Callback that is executed right after the bottom sheet settles in one of the snapping points. The new index is provided on the callback |
126 | | `animationType` | no | `string` | `timing` (default) or `spring` |
127 | | `animationConfig` | no | `TimingConfig` or `SpringConfig` | Timing or Spring configuration for the animation. If `animationType` is `timing`, it uses by default a timing configuration with a duration of 250ms and easing fn `Easing.inOut(Easing.linear)`. If `animationType` is `spring`, it uses [this default spring configuration](https://github.com/rgommezz/react-native-scroll-bottom-sheet/blob/master/src/index.tsx#L77). You can partially override any parameter from the animation config as per your needs |
128 | | `animatedPosition` | no | `Animated.Value` | Animated value that tracks the position of the drawer, being: 0 => closed, 1 => fully opened |
129 | | `topInset` | no | `number` | This value is useful to provide an offset (in dp) when applying percentages for snapping points |
130 | | `innerRef` | no | `RefObject` | Ref to the inner scrollable component (ScrollView, FlatList or SectionList), so that you can call its imperative methods. For instance, calling `scrollTo` on a ScrollView. In order to so, you have to use `getNode` as well, since it's wrapped into an _animated_ component: `ref.current.getNode().scrollTo({y: 0, animated: true})` |
131 | | `containerStyle` | no | `StyleProp` | Style to be applied to the container (Handle and Content) |
132 | | `friction` | no | `number` | Factor of resistance when the gesture is released. A value of 0 offers maximum * acceleration, whereas 1 acts as the opposite. Defaults to 0.95 |
133 | | `enableOverScroll` | no | `boolean` | Allow drawer to be dragged beyond lowest snap point |
134 |
135 |
136 | ### Inherited
137 | Depending on the value of `componentType` chosen, the bottom sheet component will inherit its underlying props, being one of
138 | [FlatListProps](https://reactnative.dev/docs/flatlist#props), [ScrollViewProps](https://reactnative.dev/docs/scrollview#props) or [SectionListProps](https://reactnative.dev/docs/sectionlist#props), so that you can tailor the scrollable content behaviour as per your needs.
139 |
140 | ## Methods
141 |
142 | #### `snapTo(index)`
143 |
144 | Imperative method to snap to a specific index, i.e.
145 |
146 | ```js
147 | bottomSheetRef.current.snapTo(0)
148 | ```
149 |
150 | `bottomSheetRef` refers to the [`ref`](https://reactjs.org/docs/react-api.html#reactcreateref) passed to the `ScrollBottomSheet` component.
151 |
152 | ## Compatibility table
153 | You may add some touchable components inside the bottom sheet or several `FlatList` widgets for horizontal mode. Unfortunately, not all _interactable_ React Native components are compatible with this library. This is due to some limitations on `react-native-gesture-handler`, which this library uses behind the scenes. For that, please follow this compatibility table:
154 |
155 | | Import | Touchable | Flatlist |
156 | | ------------------------- | -------- | ------- |
157 | | react-native | iOS | 🚫 |
158 | | react-native-gesture-handler | Android | Android, iOS|
159 |
160 | ### Touchables
161 | As you can see on the table, for any touchable component (`TouchableOpacity`, `TouchableHighlight`, ...) you need to have different imports depending on the platform. The below is a snippet you may find useful to abstract that into a component.
162 |
163 | ```js
164 | import React from "react";
165 | import { Platform, TouchableOpacity } from "react-native";
166 | import { TouchableOpacity as RNGHTouchableOpacity } from "react-native-gesture-handler";
167 |
168 | const BottomSheetTouchable = (props) => {
169 | if (Platform.OS === "android") {
170 | return (
171 |
172 | );
173 | }
174 |
175 | return
176 | };
177 |
178 | export default BottomSheetTouchable;
179 | ```
180 |
181 | ### Horizontal Mode
182 | For this mode to work properly, **you have to import `FlatList` from react-native-gesture-handler** instead of react-native.
183 |
184 | ```js
185 | import { FlatList } from 'react-native-gesture-handler';
186 |
187 | ...
188 | ```
189 |
190 | ## Limitations
191 | At the moment, the component does not support updating snap points via state, something you may want to achieve when changing device orientation for instance. A temporary workaround is to leverage React keys to force a re-mount of the component. This is some illustrative code to give you an idea how you could handle an orientation change with keys:
192 |
193 | ```js
194 | import { useDimensions } from '@react-native-community/hooks'
195 |
196 | const useOrientation = () => {
197 | const { width, height } = useDimensions().window;
198 |
199 | if (height > width) {
200 | return 'portrait'
201 | }
202 |
203 | return 'landscape'
204 | }
205 |
206 | const OrientationAwareBS = () => {
207 | const orientation = useOrientation();
208 | const snapPoints = {
209 | portrait: [...],
210 | landscape: [...]
211 | }
212 |
213 | return (
214 |
221 | );
222 | }
223 | ```
224 |
225 | ## Example
226 | There is an Expo example application that you can play with to get a good grasp on the different customisation options. In case of Android, you can directly open the project [here](https://expo.io/@rgommezz/react-native-scroll-bottom-sheet-example). For iOS, head to the [example folder](https://github.com/rgommezz/react-native-scroll-bottom-sheet/tree/master/example) and run the project locally:
227 |
228 | ```bash
229 | $ npm install
230 |
231 | $ npm start
232 | ```
233 |
234 | ## Typescript
235 | The library has been written in Typescript, so you'll get type checking and autocompletion if you use it as well.
236 |
237 | ## License
238 |
239 | MIT © [Raul Gomez Acuna](https://raulgomez.io/)
240 |
241 | If you found this project interesting, please consider following me on [twitter](https://twitter.com/rgommezz)
242 |
--------------------------------------------------------------------------------
/babel.config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | module.exports = {
10 | presets: ['module:metro-react-native-babel-preset'],
11 | };
12 |
--------------------------------------------------------------------------------
/commitlint.config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | module.exports = {
10 | extends: ['@commitlint/config-conventional'],
11 | };
12 |
--------------------------------------------------------------------------------
/config/header.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
--------------------------------------------------------------------------------
/example/.expo-shared/assets.json:
--------------------------------------------------------------------------------
1 | {
2 | "12bb71342c6255bbf50437ec8f4441c083f47cdb74bd89160c15e4f43e52a1cb": true,
3 | "40b842e832070c58deac6aa9e08fa459302ee3f9da492c7e77d93d2fbf4a56fd": true
4 | }
5 |
--------------------------------------------------------------------------------
/example/App.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import * as React from 'react';
10 | import { AntDesign } from '@expo/vector-icons';
11 | import { NavigationContainer } from '@react-navigation/native';
12 | import { createStackNavigator } from '@react-navigation/stack';
13 | import Home from './screens/Home';
14 | import SectionListExample from './screens/SectionListExample';
15 | import HorizontalFlatListExample from './screens/HorizontalFlatListExample';
16 |
17 | export type HomeStackParamsList = {
18 | Home: undefined;
19 | SectionListExample: undefined;
20 | HorizontalFlatListExample: undefined;
21 | };
22 |
23 | const Stack = createStackNavigator();
24 |
25 | function App() {
26 | return (
27 |
28 |
29 |
34 | (
39 |
45 | ),
46 | }}
47 | name="SectionListExample"
48 | component={SectionListExample}
49 | />
50 |
55 |
56 |
57 | );
58 | }
59 |
60 | export default App;
61 |
--------------------------------------------------------------------------------
/example/app.json:
--------------------------------------------------------------------------------
1 | {
2 | "expo": {
3 | "name": "react-native-scroll-bottom-sheet-example",
4 | "slug": "react-native-scroll-bottom-sheet-example",
5 | "description": "Example application that showcases the power of the library with 2 examples: a banking style app and maps bottom sheet with horizontal lists/carousels embedded",
6 | "privacy": "public",
7 | "platforms": [
8 | "ios",
9 | "android",
10 | "web"
11 | ],
12 | "version": "1.2.0",
13 | "orientation": "portrait",
14 | "icon": "./assets/icon.png",
15 | "splash": {
16 | "image": "./assets/splash.png",
17 | "resizeMode": "contain",
18 | "backgroundColor": "#ffffff"
19 | },
20 | "updates": {
21 | "fallbackToCacheTimeout": 0
22 | },
23 | "assetBundlePatterns": [
24 | "**/*"
25 | ],
26 | "ios": {
27 | "supportsTablet": true
28 | }
29 | }
30 | }
31 |
--------------------------------------------------------------------------------
/example/assets/card-back.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/example/assets/card-back.png
--------------------------------------------------------------------------------
/example/assets/card-front.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/example/assets/card-front.png
--------------------------------------------------------------------------------
/example/assets/icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/example/assets/icon.png
--------------------------------------------------------------------------------
/example/assets/placeholder.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/example/assets/placeholder.jpg
--------------------------------------------------------------------------------
/example/assets/splash.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/example/assets/splash.png
--------------------------------------------------------------------------------
/example/babel.config.js:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | module.exports = function (api) {
10 | api.cache(true);
11 | return {
12 | presets: ['babel-preset-expo'],
13 | };
14 | };
15 |
--------------------------------------------------------------------------------
/example/components/Carousel.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import * as React from 'react';
10 | import CarouselItem from './CarouselItem';
11 | import { StyleSheet, Text, View } from 'react-native';
12 | import Faker from 'faker';
13 | import { FlatList } from 'react-native-gesture-handler';
14 |
15 | const Carousel: React.FC<{ index: number }> = React.memo(
16 | ({ index }) => {
17 | const renderItem = React.useCallback(() => , []);
18 |
19 | return (
20 |
21 | {`Popular in ${Faker.address.city()}`}
22 | String(i))}
27 | horizontal
28 | keyExtractor={j => `row-${index}-item-${j}`}
29 | renderItem={renderItem}
30 | />
31 |
32 | );
33 | },
34 | () => true
35 | );
36 |
37 | const styles = StyleSheet.create({
38 | row: {
39 | backgroundColor: 'white',
40 | marginBottom: 16,
41 | paddingVertical: 16,
42 | borderTopWidth: 1,
43 | borderBottomWidth: 1,
44 | borderTopColor: '#E0E0E0',
45 | borderBottomColor: '#E0E0E0',
46 | },
47 | title: {
48 | marginBottom: 16,
49 | paddingHorizontal: 16,
50 | fontSize: 18,
51 | fontWeight: 'bold',
52 | },
53 | });
54 |
55 | export default Carousel;
56 |
--------------------------------------------------------------------------------
/example/components/CarouselItem.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import * as React from 'react';
10 | import { Dimensions, StyleSheet, View } from 'react-native';
11 | import { Card } from 'react-native-paper';
12 | import { generateRandomIntFromInterval } from '../utils';
13 |
14 | const { width: windowWidth } = Dimensions.get('window');
15 |
16 | const CarouselItem: React.FC = React.memo(
17 | () => {
18 | const [withPlaceholder, setPlaceholder] = React.useState(false);
19 | return (
20 |
21 |
22 | setPlaceholder(true)}
25 | source={
26 | withPlaceholder
27 | ? require('../assets/placeholder.jpg')
28 | : {
29 | uri: `https://picsum.photos/id/${generateRandomIntFromInterval(
30 | 0,
31 | 300
32 | )}/${Math.floor(windowWidth)}`,
33 | }
34 | }
35 | />
36 |
37 |
38 | );
39 | },
40 | () => true
41 | );
42 |
43 | export default CarouselItem;
44 |
45 | const styles = StyleSheet.create({
46 | item: {
47 | paddingHorizontal: 4,
48 | paddingVertical: 8,
49 | },
50 | imageStyle: {
51 | width: (windowWidth - 32) / 1.5,
52 | height: 150,
53 | resizeMode: 'cover',
54 | },
55 | });
56 |
--------------------------------------------------------------------------------
/example/components/Handle.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import * as React from 'react';
10 | import { StyleProp, StyleSheet, View, ViewStyle } from 'react-native';
11 |
12 | interface Props {
13 | style?: StyleProp;
14 | }
15 |
16 | const Handle: React.FC = ({ children, style }) => (
17 |
18 | {children || }
19 |
20 | );
21 |
22 | export default Handle;
23 |
24 | const styles = StyleSheet.create({
25 | header: {
26 | alignItems: 'center',
27 | backgroundColor: 'white',
28 | paddingVertical: 20,
29 | borderTopLeftRadius: 20,
30 | borderTopRightRadius: 20,
31 | shadowColor: '#000',
32 | shadowOffset: {
33 | width: 0,
34 | height: -10,
35 | },
36 | shadowOpacity: 0.1,
37 | shadowRadius: 5.0,
38 | elevation: 16,
39 | },
40 | panelHandle: {
41 | width: 40,
42 | height: 6,
43 | backgroundColor: 'rgba(0,0,0,0.3)',
44 | borderRadius: 4,
45 | marginBottom: 10,
46 | },
47 | });
48 |
--------------------------------------------------------------------------------
/example/components/Transaction.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import React from 'react';
10 | import { ListItemData } from '../utils';
11 | import { List } from 'react-native-paper';
12 | import { Text } from 'react-native';
13 |
14 | const Transaction = React.memo(
15 | ({ title, subtitle, amount, iconColor }: ListItemData) => (
16 | }
20 | right={() => (
21 | {amount}
22 | )}
23 | />
24 | ),
25 | () => true
26 | );
27 |
28 | export default Transaction;
29 |
--------------------------------------------------------------------------------
/example/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": "node_modules/expo/AppEntry.js",
3 | "scripts": {
4 | "start": "expo start",
5 | "android": "expo start --android",
6 | "ios": "expo start --ios",
7 | "web": "expo start --web",
8 | "eject": "expo eject"
9 | },
10 | "dependencies": {
11 | "@react-native-community/masked-view": "0.1.10",
12 | "@react-navigation/native": "^5.3.2",
13 | "@react-navigation/stack": "^5.3.5",
14 | "date-fns": "^2.13.0",
15 | "expo": "^38.0.0",
16 | "faker": "^4.1.0",
17 | "react": "16.11.0",
18 | "react-dom": "16.11.0",
19 | "react-native": "https://github.com/expo/react-native/archive/sdk-38.0.2.tar.gz",
20 | "react-native-credit-card": "^0.1.9",
21 | "react-native-gesture-handler": "~1.6.0",
22 | "react-native-maps": "0.27.1",
23 | "react-native-paper": "^3.10.1",
24 | "react-native-reanimated": "~1.9.0",
25 | "react-native-safe-area-context": "~3.0.7",
26 | "react-native-screens": "~2.9.0",
27 | "react-native-scroll-bottom-sheet": "^0.7.0",
28 | "react-native-web": "~0.11.7"
29 | },
30 | "devDependencies": {
31 | "@babel/core": "^7.8.6",
32 | "@types/faker": "^4.1.12",
33 | "@types/react": "~16.9.41",
34 | "@types/react-native": "~0.62.13",
35 | "babel-preset-expo": "^8.2.3",
36 | "typescript": "~3.9.5"
37 | },
38 | "private": true
39 | }
40 |
--------------------------------------------------------------------------------
/example/screens/Home.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import * as React from 'react';
10 | import { View, StyleSheet } from 'react-native';
11 | import { StackNavigationProp } from '@react-navigation/stack';
12 | import { HomeStackParamsList } from '../App';
13 | import { Button } from 'react-native-paper';
14 |
15 | interface Props {
16 | navigation: StackNavigationProp;
17 | }
18 |
19 | const Home: React.FC = ({ navigation }) => {
20 | return (
21 |
22 |
23 |
31 |
32 |
40 |
41 | );
42 | };
43 |
44 | const styles = StyleSheet.create({
45 | container: {
46 | flex: 1,
47 | padding: 16,
48 | backgroundColor: 'white',
49 | },
50 | firstButton: {
51 | marginBottom: 32,
52 | },
53 | });
54 |
55 | export default Home;
56 |
--------------------------------------------------------------------------------
/example/screens/HorizontalFlatListExample.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import * as React from 'react';
10 | import { Dimensions, Platform, StyleSheet, View } from 'react-native';
11 | import { StackNavigationProp } from '@react-navigation/stack';
12 | import { HomeStackParamsList } from '../App';
13 | import ScrollBottomSheet from 'react-native-scroll-bottom-sheet';
14 | import { MaterialCommunityIcons, Ionicons } from '@expo/vector-icons';
15 | import MapView from 'react-native-maps';
16 | import Animated, {
17 | Extrapolate,
18 | interpolate,
19 | Value,
20 | } from 'react-native-reanimated';
21 | import Handle from '../components/Handle';
22 | import Carousel from '../components/Carousel';
23 | import { TouchableRipple } from 'react-native-paper';
24 |
25 | interface Props {
26 | navigation: StackNavigationProp<
27 | HomeStackParamsList,
28 | 'HorizontalFlatListExample'
29 | >;
30 | }
31 |
32 | const initialRegion = {
33 | latitudeDelta: 0.02,
34 | longitudeDelta: 0.02,
35 | latitude: 51.5142431,
36 | longitude: -0.1255756,
37 | };
38 | const { height: windowHeight } = Dimensions.get('window');
39 | const snapPointsFromTop = [96, '50%', windowHeight - 128];
40 |
41 | const HorizontalFlatListExample: React.FC = ({ navigation }) => {
42 | const bottomSheetRef = React.useRef | null>(null);
43 |
44 | const animatedPosition = React.useRef(new Value(0));
45 | const opacity = interpolate(animatedPosition.current, {
46 | inputRange: [0, 1],
47 | outputRange: [0, 0.75],
48 | extrapolate: Extrapolate.CLAMP,
49 | });
50 |
51 | const renderRow = React.useCallback(
52 | ({ index }) => ,
53 | []
54 | );
55 |
56 | return (
57 |
58 |
62 |
69 |
70 | {
73 | bottomSheetRef.current?.snapTo(2);
74 | }}
75 | borderless
76 | >
77 |
83 |
84 | {Platform.OS === 'ios' && (
85 | {
88 | navigation.goBack();
89 | }}
90 | borderless
91 | >
92 |
98 |
99 | )}
100 |
101 |
102 | ref={bottomSheetRef}
103 | componentType="FlatList"
104 | topInset={24}
105 | animatedPosition={animatedPosition.current}
106 | snapPoints={snapPointsFromTop}
107 | initialSnapIndex={2}
108 | renderHandle={() => }
109 | keyExtractor={i => `row-${i}`}
110 | initialNumToRender={5}
111 | contentContainerStyle={styles.contentContainerStyle}
112 | data={Array.from({ length: 100 }).map((_, i) => String(i))}
113 | renderItem={renderRow}
114 | />
115 |
116 | );
117 | };
118 |
119 | const styles = StyleSheet.create({
120 | container: {
121 | flex: 1,
122 | },
123 | contentContainerStyle: {
124 | backgroundColor: '#F3F4F9',
125 | },
126 | mapStyle: {
127 | width: Dimensions.get('window').width,
128 | height: Dimensions.get('window').height,
129 | },
130 | iconContainer: {
131 | position: 'absolute',
132 | top: 32,
133 | width: 48,
134 | height: 48,
135 | borderRadius: 24,
136 | justifyContent: 'center',
137 | alignItems: 'center',
138 | },
139 | icon: {
140 | paddingTop: Platform.OS === 'ios' ? 4 : 0,
141 | paddingLeft: Platform.OS === 'ios' ? 2 : 0,
142 | },
143 | panelHandle: {
144 | width: 40,
145 | height: 6,
146 | backgroundColor: 'rgba(0,0,0,0.3)',
147 | borderRadius: 4,
148 | marginBottom: 10,
149 | },
150 | });
151 |
152 | export default HorizontalFlatListExample;
153 |
--------------------------------------------------------------------------------
/example/screens/SectionListExample.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import React from 'react';
10 | import Constants from 'expo-constants';
11 | import { FontAwesome5, Ionicons } from '@expo/vector-icons';
12 | import { Dimensions, Platform, StyleSheet, Text, View } from 'react-native';
13 | import { Colors, ProgressBar } from 'react-native-paper';
14 | import ScrollBottomSheet from 'react-native-scroll-bottom-sheet';
15 | import { StackNavigationProp } from '@react-navigation/stack';
16 | import { HomeStackParamsList } from '../App';
17 | import { createMockData, ListItemData } from '../utils';
18 | import Handle from '../components/Handle';
19 | import Transaction from '../components/Transaction';
20 | import Animated, {
21 | concat,
22 | Easing,
23 | Extrapolate,
24 | interpolate,
25 | Value,
26 | } from 'react-native-reanimated';
27 |
28 | interface Props {
29 | navigation: StackNavigationProp;
30 | }
31 |
32 | const { height: windowHeight, width: windowWidth } = Dimensions.get('window');
33 | const { statusBarHeight } = Constants;
34 | const navBarHeight = 56;
35 |
36 | const sections = createMockData();
37 |
38 | const SectionListExample: React.FC = () => {
39 | const snapPointsFromTop = [96, '45%', windowHeight - 264];
40 | const animatedPosition = React.useRef(new Value(0.5));
41 | const handleLeftRotate = concat(
42 | interpolate(animatedPosition.current, {
43 | inputRange: [0, 0.4, 1],
44 | outputRange: [25, 0, 0],
45 | extrapolate: Extrapolate.CLAMP,
46 | }),
47 | 'deg'
48 | );
49 | const handleRightRotate = concat(
50 | interpolate(animatedPosition.current, {
51 | inputRange: [0, 0.4, 1],
52 | outputRange: [-25, 0, 0],
53 | extrapolate: Extrapolate.CLAMP,
54 | }),
55 | 'deg'
56 | );
57 | const cardScale = interpolate(animatedPosition.current, {
58 | inputRange: [0, 0.6, 1],
59 | outputRange: [1, 1, 0.9],
60 | extrapolate: Extrapolate.CLAMP,
61 | });
62 |
63 | const renderSectionHeader = React.useCallback(
64 | ({ section }) => (
65 |
66 | {section.title}
67 |
68 | ),
69 | []
70 | );
71 |
72 | const renderItem = React.useCallback(
73 | ({ item }) => ,
74 | []
75 | );
76 |
77 | return (
78 |
79 |
80 | £
81 | 4,345
82 |
83 |
88 |
92 |
93 |
94 |
95 |
96 |
97 | Account
98 |
99 |
100 |
101 |
102 |
103 | Pin
104 |
105 |
106 |
107 |
108 |
109 | Freeze
110 |
111 |
112 |
113 |
114 |
115 | Top up
116 |
117 |
118 |
119 | enableOverScroll
120 | removeClippedSubviews={Platform.OS === 'android' && sections.length > 0}
121 | componentType="SectionList"
122 | topInset={statusBarHeight + navBarHeight}
123 | animatedPosition={animatedPosition.current}
124 | snapPoints={snapPointsFromTop}
125 | initialSnapIndex={1}
126 | animationConfig={{
127 | easing: Easing.inOut(Easing.linear),
128 | }}
129 | renderHandle={() => (
130 |
131 |
140 |
149 |
150 | )}
151 | contentContainerStyle={styles.contentContainerStyle}
152 | stickySectionHeadersEnabled
153 | sections={sections}
154 | keyExtractor={i => i.id}
155 | renderSectionHeader={renderSectionHeader}
156 | renderItem={renderItem}
157 | />
158 |
159 | );
160 | };
161 |
162 | const styles = StyleSheet.create({
163 | container: {
164 | flex: 1,
165 | padding: 16,
166 | alignItems: 'center',
167 | },
168 | contentContainerStyle: {
169 | backgroundColor: 'white',
170 | },
171 | handle: {
172 | position: 'absolute',
173 | width: 22,
174 | height: 4,
175 | backgroundColor: '#BDBDBD',
176 | borderRadius: 4,
177 | marginTop: 17,
178 | },
179 | card: {
180 | width: windowWidth - 128,
181 | height: (windowWidth - 128) / 1.57,
182 | alignSelf: 'center',
183 | resizeMode: 'cover',
184 | borderRadius: 8,
185 | },
186 | section: {
187 | paddingVertical: 8,
188 | paddingHorizontal: 16,
189 | backgroundColor: '#F3F4F9',
190 | borderWidth: 0.5,
191 | borderColor: '#B7BECF',
192 | },
193 | row: {
194 | marginTop: 24,
195 | width: windowWidth - 128,
196 | flexDirection: 'row',
197 | alignItems: 'center',
198 | justifyContent: 'space-between',
199 | },
200 | balanceContainer: {
201 | flexDirection: 'row',
202 | alignItems: 'center',
203 | justifyContent: 'center',
204 | marginBottom: 16,
205 | },
206 | balance: {
207 | fontWeight: 'bold',
208 | fontSize: 32,
209 | },
210 | progressBar: {
211 | width: windowWidth - 256,
212 | marginBottom: 24,
213 | borderRadius: 4,
214 | },
215 | action: {
216 | height: 48,
217 | width: 48,
218 | justifyContent: 'center',
219 | alignItems: 'center',
220 | borderRadius: 24,
221 | backgroundColor: '#81D4FA',
222 | marginBottom: 8,
223 | },
224 | poundSign: {
225 | fontWeight: 'bold',
226 | fontSize: 18,
227 | paddingTop: 8,
228 | },
229 | });
230 |
231 | export default SectionListExample;
232 |
--------------------------------------------------------------------------------
/example/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "allowSyntheticDefaultImports": true,
4 | "jsx": "react-native",
5 | "lib": ["dom", "esnext"],
6 | "moduleResolution": "node",
7 | "noEmit": true,
8 | "skipLibCheck": true,
9 | "resolveJsonModule": true,
10 | "strict": true
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/example/utils/index.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import { format, parse, subDays } from 'date-fns';
10 | import Faker from 'faker';
11 |
12 | export function generateRandomIntFromInterval(min: number, max: number) {
13 | return Math.floor(Math.random() * (max - min + 1) + min);
14 | }
15 |
16 | export interface ListItemData {
17 | id: string;
18 | title: string;
19 | subtitle: string;
20 | amount: string;
21 | iconColor: string;
22 | }
23 |
24 | export const createMockData = () => {
25 | const elementsByDate: {
26 | [key: string]: ListItemData[];
27 | } = {};
28 | const today = new Date();
29 | Array.from({ length: 200 }).forEach((_, index) => {
30 | const date = format(
31 | subDays(today, generateRandomIntFromInterval(0, 30)),
32 | 'yyyy LL d'
33 | );
34 | const amount = (generateRandomIntFromInterval(100, 10000) / 100).toFixed(2);
35 | const randomEntry = {
36 | id: String(index),
37 | title: Faker.commerce.productName(),
38 | subtitle: Faker.commerce.productMaterial(),
39 | amount,
40 | iconColor: `rgb(${generateRandomIntFromInterval(
41 | 0,
42 | 255
43 | )}, ${generateRandomIntFromInterval(
44 | 0,
45 | 255
46 | )}, ${generateRandomIntFromInterval(0, 255)})`,
47 | };
48 | if (Array.isArray(elementsByDate[date])) {
49 | elementsByDate[date].push(randomEntry);
50 | } else {
51 | elementsByDate[date] = [randomEntry];
52 | }
53 | });
54 |
55 | return Object.entries(elementsByDate)
56 | .map(([key, data]) => ({
57 | title: key,
58 | data,
59 | }))
60 | .sort((a, b) => {
61 | return (
62 | parse(b.title, 'yyyy LL d', new Date()).getTime() -
63 | parse(a.title, 'yyyy LL d', new Date()).getTime()
64 | );
65 | })
66 | .map(item => ({
67 | ...item,
68 | title: format(parse(item.title, 'yyyy LL d', new Date()), 'ccc d MMM'),
69 | }));
70 | };
71 |
--------------------------------------------------------------------------------
/gifs/bank.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/gifs/bank.gif
--------------------------------------------------------------------------------
/gifs/maps.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/rgommezz/react-native-scroll-bottom-sheet/eef584cb08894a0d876101d686926a6eff41ac6f/gifs/maps.gif
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-native-scroll-bottom-sheet",
3 | "version": "0.7.0",
4 | "description": "Cross platform scrollable bottom sheet with virtualization support, running at 60 FPS and fully implemented in JS land",
5 | "main": "lib/commonjs/index.js",
6 | "module": "lib/module/index.js",
7 | "types": "lib/typescript/index.d.ts",
8 | "react-native": "src/index.tsx",
9 | "files": [
10 | "src",
11 | "lib"
12 | ],
13 | "scripts": {
14 | "test": "jest",
15 | "typescript": "tsc --noEmit",
16 | "lint": "eslint --ext .js,.ts,.tsx .",
17 | "prepare": "bob build",
18 | "release": "release-it",
19 | "example": "yarn --cwd example"
20 | },
21 | "keywords": [
22 | "react-native",
23 | "react",
24 | "ios",
25 | "android",
26 | "bottom-sheet",
27 | "bottomsheet",
28 | "cross-platform",
29 | "60FPS"
30 | ],
31 | "repository": "https://github.com/rgommezz/react-native-scroll-bottom-sheet",
32 | "author": "Raul Gomez Acuña (https://github.com/rgommezz)",
33 | "license": "MIT",
34 | "bugs": {
35 | "url": "https://github.com/rgommezz/react-native-scroll-bottom-sheet/issues"
36 | },
37 | "homepage": "https://github.com/rgommezz/react-native-scroll-bottom-sheet#readme",
38 | "peerDependencies": {
39 | "react": "*",
40 | "react-native": "*",
41 | "react-native-gesture-handler": "*",
42 | "react-native-reanimated": "*"
43 | },
44 | "devDependencies": {
45 | "@commitlint/config-conventional": "^8.3.4",
46 | "@react-native-community/bob": "^0.10.1",
47 | "@react-native-community/eslint-config": "^0.0.7",
48 | "@release-it/conventional-changelog": "^1.1.0",
49 | "@types/jest": "^25.1.2",
50 | "@types/react": "^16.9.19",
51 | "@types/react-native": "0.61.10",
52 | "commitlint": "^8.3.4",
53 | "eslint": "^6.8.0",
54 | "eslint-config-prettier": "^6.10.0",
55 | "eslint-plugin-header": "^3.0.0",
56 | "eslint-plugin-prettier": "^3.1.2",
57 | "husky": "^4.0.1",
58 | "jest": "^25.1.0",
59 | "prettier": "^2.0.5",
60 | "react": "~16.9.0",
61 | "react-native": "^0.62.2",
62 | "react-native-gesture-handler": "^1.6.1",
63 | "react-native-reanimated": "^1.8.0",
64 | "release-it": "^12.6.3",
65 | "typescript": "^3.7.5"
66 | },
67 | "jest": {
68 | "preset": "react-native",
69 | "modulePathIgnorePatterns": [
70 | "/example/node_modules",
71 | "/lib/"
72 | ]
73 | },
74 | "husky": {
75 | "hooks": {
76 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS",
77 | "pre-commit": "yarn lint && yarn typescript"
78 | }
79 | },
80 | "eslintConfig": {
81 | "extends": [
82 | "@react-native-community",
83 | "prettier"
84 | ],
85 | "plugins": [
86 | "header"
87 | ],
88 | "rules": {
89 | "header/header": [
90 | 2,
91 | "block",
92 | [
93 | "*",
94 | " * Copyright (c) 2020 Raul Gomez Acuna",
95 | " *",
96 | " * This source code is licensed under the MIT license found in the",
97 | " * LICENSE file in the root directory of this source tree.",
98 | " *",
99 | " "
100 | ]
101 | ],
102 | "@typescript-eslint/no-unused-vars": "off",
103 | "prettier/prettier": [
104 | "error",
105 | {
106 | "arrowParens": "avoid",
107 | "singleQuote": true,
108 | "tabWidth": 2,
109 | "trailingComma": "es5",
110 | "useTabs": false
111 | }
112 | ]
113 | }
114 | },
115 | "eslintIgnore": [
116 | "node_modules/",
117 | "lib/"
118 | ],
119 | "prettier": {
120 | "arrowParens": "avoid",
121 | "singleQuote": true,
122 | "tabWidth": 2,
123 | "trailingComma": "es5",
124 | "useTabs": false
125 | },
126 | "release-it": {
127 | "git": {
128 | "commitMessage": "chore: release %s",
129 | "tagName": "v%s"
130 | },
131 | "npm": {
132 | "publish": true
133 | },
134 | "github": {
135 | "release": true
136 | },
137 | "plugins": {
138 | "@release-it/conventional-changelog": {
139 | "preset": "angular"
140 | }
141 | }
142 | },
143 | "@react-native-community/bob": {
144 | "source": "src",
145 | "output": "lib",
146 | "targets": [
147 | "commonjs",
148 | "module",
149 | "typescript"
150 | ]
151 | },
152 | "dependencies": {
153 | "utility-types": "^3.10.0"
154 | }
155 | }
156 |
--------------------------------------------------------------------------------
/src/__tests__/index.test.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | it.todo('write a test');
10 |
--------------------------------------------------------------------------------
/src/index.tsx:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (c) 2020 Raul Gomez Acuna
3 | *
4 | * This source code is licensed under the MIT license found in the
5 | * LICENSE file in the root directory of this source tree.
6 | *
7 | */
8 |
9 | import React, { Component, RefObject } from 'react';
10 | import {
11 | Dimensions,
12 | FlatList,
13 | FlatListProps,
14 | Platform,
15 | ScrollView,
16 | ScrollViewProps,
17 | SectionList,
18 | SectionListProps,
19 | StyleSheet,
20 | View,
21 | ViewStyle,
22 | } from 'react-native';
23 | import Animated, {
24 | abs,
25 | add,
26 | and,
27 | call,
28 | Clock,
29 | clockRunning,
30 | cond,
31 | Easing as EasingDeprecated,
32 | // @ts-ignore: this property is only present in Reanimated 2
33 | EasingNode,
34 | eq,
35 | event,
36 | Extrapolate,
37 | greaterOrEq,
38 | greaterThan,
39 | multiply,
40 | not,
41 | onChange,
42 | or,
43 | set,
44 | startClock,
45 | stopClock,
46 | sub,
47 | spring,
48 | timing,
49 | Value,
50 | } from 'react-native-reanimated';
51 | import {
52 | NativeViewGestureHandler,
53 | PanGestureHandler,
54 | PanGestureHandlerProperties,
55 | State as GestureState,
56 | TapGestureHandler,
57 | } from 'react-native-gesture-handler';
58 | import { Assign } from 'utility-types';
59 |
60 | const {
61 | interpolate: interpolateDeprecated,
62 | // @ts-ignore: this property is only present in Reanimated 2
63 | interpolateNode,
64 | } = Animated;
65 |
66 | const interpolate: typeof interpolateDeprecated =
67 | interpolateNode ?? interpolateDeprecated;
68 |
69 | const Easing: typeof EasingDeprecated = EasingNode ?? EasingDeprecated;
70 |
71 | const FlatListComponentType = 'FlatList' as const;
72 | const ScrollViewComponentType = 'ScrollView' as const;
73 | const SectionListComponentType = 'SectionList' as const;
74 | const TimingAnimationType = 'timing' as const;
75 | const SpringAnimationType = 'spring' as const;
76 |
77 | const DEFAULT_SPRING_PARAMS = {
78 | damping: 50,
79 | mass: 0.3,
80 | stiffness: 121.6,
81 | overshootClamping: true,
82 | restSpeedThreshold: 0.3,
83 | restDisplacementThreshold: 0.3,
84 | };
85 |
86 | const { height: windowHeight } = Dimensions.get('window');
87 | const IOS_NORMAL_DECELERATION_RATE = 0.998;
88 | const ANDROID_NORMAL_DECELERATION_RATE = 0.985;
89 | const DEFAULT_ANIMATION_DURATION = 250;
90 | const DEFAULT_EASING = Easing.inOut(Easing.linear);
91 | const imperativeScrollOptions = {
92 | [FlatListComponentType]: {
93 | method: 'scrollToIndex',
94 | args: {
95 | index: 0,
96 | viewPosition: 0,
97 | viewOffset: 1000,
98 | animated: true,
99 | },
100 | },
101 | [ScrollViewComponentType]: {
102 | method: 'scrollTo',
103 | args: {
104 | x: 0,
105 | y: 0,
106 | animated: true,
107 | },
108 | },
109 | [SectionListComponentType]: {
110 | method: 'scrollToLocation',
111 | args: {
112 | itemIndex: 0,
113 | sectionIndex: 0,
114 | viewPosition: 0,
115 | viewOffset: 1000,
116 | animated: true,
117 | },
118 | },
119 | };
120 |
121 | type AnimatedScrollableComponent = FlatList | ScrollView | SectionList;
122 |
123 | type FlatListOption = Assign<
124 | { componentType: typeof FlatListComponentType },
125 | FlatListProps
126 | >;
127 | type ScrollViewOption = Assign<
128 | { componentType: typeof ScrollViewComponentType },
129 | ScrollViewProps
130 | >;
131 | type SectionListOption = Assign<
132 | { componentType: typeof SectionListComponentType },
133 | SectionListProps
134 | >;
135 |
136 | interface TimingParams {
137 | clock: Animated.Clock;
138 | from: Animated.Node;
139 | to: Animated.Node;
140 | position: Animated.Value;
141 | finished: Animated.Value;
142 | frameTime: Animated.Value;
143 | velocity: Animated.Node;
144 | }
145 |
146 | type CommonProps = {
147 | /**
148 | * Array of numbers that indicate the different resting positions of the bottom sheet (in dp or %), starting from the top.
149 | * If a percentage is used, that would translate to the relative amount of the total window height.
150 | * For instance, if 50% is used, that'd be windowHeight * 0.5. If you wanna take into account safe areas during
151 | * the calculation, such as status bars and notches, please use 'topInset' prop
152 | */
153 | snapPoints: Array;
154 | /**
155 | * Index that references the initial resting position of the drawer, starting from the top
156 | */
157 | initialSnapIndex: number;
158 | /**
159 | * Render prop for the handle
160 | */
161 | renderHandle: () => React.ReactNode;
162 | /**
163 | * Callback that is executed right after the drawer settles on one of the snapping points.
164 | * The new index is provided on the callback
165 | * @param index
166 | */
167 | onSettle?: (index: number) => void;
168 | /**
169 | * Animated value that tracks the position of the drawer, being:
170 | * 0 => closed
171 | * 1 => fully opened
172 | */
173 | animatedPosition?: Animated.Value;
174 | /**
175 | * This value is useful if you want to take into consideration safe area insets
176 | * when applying percentages for snapping points. We recommend using react-native-safe-area-context
177 | * library for that.
178 | * @see https://github.com/th3rdwave/react-native-safe-area-context#usage, insets.top
179 | */
180 | topInset: number;
181 | /**
182 | * Reference to FlatList, ScrollView or SectionList in order to execute its imperative methods.
183 | */
184 | innerRef: RefObject;
185 | /*
186 | * Style to be applied to the container.
187 | */
188 | containerStyle?: Animated.AnimateStyle;
189 | /*
190 | * Factor of resistance when the gesture is released. A value of 0 offers maximum
191 | * acceleration, whereas 1 acts as the opposite. Defaults to 0.95
192 | */
193 | friction: number;
194 | /*
195 | * Allow drawer to be dragged beyond lowest snap point
196 | */
197 | enableOverScroll: boolean;
198 | };
199 |
200 | type TimingAnimationProps = {
201 | animationType: typeof TimingAnimationType;
202 | /**
203 | * Configuration for the timing reanimated function
204 | */
205 | animationConfig?: Partial;
206 | };
207 |
208 | type SpringAnimationProps = {
209 | animationType: typeof SpringAnimationType;
210 | /**
211 | * Configuration for the spring reanimated function
212 | */
213 | animationConfig?: Partial;
214 | };
215 |
216 | type Props = CommonProps &
217 | (FlatListOption | ScrollViewOption | SectionListOption) &
218 | (TimingAnimationProps | SpringAnimationProps);
219 |
220 | export class ScrollBottomSheet extends Component> {
221 | static defaultProps = {
222 | topInset: 0,
223 | friction: 0.95,
224 | animationType: 'timing',
225 | innerRef: React.createRef(),
226 | enableOverScroll: false,
227 | };
228 |
229 | /**
230 | * Gesture Handler references
231 | */
232 | private masterDrawer = React.createRef();
233 | private drawerHandleRef = React.createRef();
234 | private drawerContentRef = React.createRef();
235 | private scrollComponentRef = React.createRef();
236 |
237 | /**
238 | * ScrollView prop
239 | */
240 | private onScrollBeginDrag: ScrollViewProps['onScrollBeginDrag'];
241 | /**
242 | * Pan gesture handler events for drawer handle and content
243 | */
244 | private onHandleGestureEvent: PanGestureHandlerProperties['onGestureEvent'];
245 | private onDrawerGestureEvent: PanGestureHandlerProperties['onGestureEvent'];
246 | /**
247 | * Main Animated Value that drives the top position of the UI drawer at any point in time
248 | */
249 | private translateY: Animated.Node;
250 | /**
251 | * Animated value that keeps track of the position: 0 => closed, 1 => opened
252 | */
253 | private position: Animated.Node;
254 | /**
255 | * Flag to indicate imperative snapping
256 | */
257 | private isManuallySetValue: Animated.Value = new Value(0);
258 | /**
259 | * Manual snapping amount
260 | */
261 | private manualYOffset: Animated.Value = new Value(0);
262 | /**
263 | * Keeps track of the current index
264 | */
265 | private nextSnapIndex: Animated.Value;
266 | /**
267 | * Deceleration rate of the scroll component. This is used only on Android to
268 | * compensate the unexpected glide it gets sometimes.
269 | */
270 | private decelerationRate: Animated.Value;
271 | private prevSnapIndex = -1;
272 | private dragY = new Value(0);
273 | private prevDragY = new Value(0);
274 | private tempDestSnapPoint = new Value(0);
275 | private isAndroid = new Value(Number(Platform.OS === 'android'));
276 | private animationClock = new Clock();
277 | private animationPosition = new Value(0);
278 | private animationFinished = new Value(0);
279 | private animationFrameTime = new Value(0);
280 | private velocityY = new Value(0);
281 | private lastStartScrollY: Animated.Value = new Value(0);
282 | private prevTranslateYOffset: Animated.Value;
283 | private translationY: Animated.Value;
284 | private destSnapPoint = new Value(0);
285 |
286 | private lastSnap: Animated.Value;
287 | private dragWithHandle = new Value(0);
288 | private scrollUpAndPullDown = new Value(0);
289 | private didGestureFinish: Animated.Node<0 | 1>;
290 | private didScrollUpAndPullDown: Animated.Node;
291 | private setTranslationY: Animated.Node;
292 | private extraOffset: Animated.Node;
293 | private calculateNextSnapPoint: (
294 | i?: number
295 | ) => number | Animated.Node;
296 |
297 | private scrollComponent: React.ComponentType<
298 | FlatListProps | ScrollViewProps | SectionListProps
299 | >;
300 |
301 | convertPercentageToDp = (str: string) =>
302 | (Number(str.split('%')[0]) * (windowHeight - this.props.topInset)) / 100;
303 |
304 | constructor(props: Props) {
305 | super(props);
306 | const { initialSnapIndex, animationType } = props;
307 |
308 | const animationDriver = animationType === 'timing' ? 0 : 1;
309 | const animationDuration =
310 | (props.animationType === 'timing' && props.animationConfig?.duration) ||
311 | DEFAULT_ANIMATION_DURATION;
312 |
313 | const ScrollComponent = this.getScrollComponent();
314 | // @ts-ignore
315 | this.scrollComponent = Animated.createAnimatedComponent(ScrollComponent);
316 |
317 | const snapPoints = this.getNormalisedSnapPoints();
318 | const openPosition = snapPoints[0];
319 | const closedPosition = this.props.enableOverScroll
320 | ? windowHeight
321 | : snapPoints[snapPoints.length - 1];
322 | const initialSnap = snapPoints[initialSnapIndex];
323 | this.nextSnapIndex = new Value(initialSnapIndex);
324 |
325 | const initialDecelerationRate = Platform.select({
326 | android:
327 | props.initialSnapIndex === 0 ? ANDROID_NORMAL_DECELERATION_RATE : 0,
328 | ios: IOS_NORMAL_DECELERATION_RATE,
329 | });
330 | this.decelerationRate = new Value(initialDecelerationRate);
331 |
332 | const handleGestureState = new Value(-1);
333 | const handleOldGestureState = new Value(-1);
334 | const drawerGestureState = new Value(-1);
335 | const drawerOldGestureState = new Value(-1);
336 |
337 | const lastSnapInRange = new Value(1);
338 | this.prevTranslateYOffset = new Value(initialSnap);
339 | this.translationY = new Value(initialSnap);
340 |
341 | this.lastSnap = new Value(initialSnap);
342 |
343 | this.onHandleGestureEvent = event([
344 | {
345 | nativeEvent: {
346 | translationY: this.dragY,
347 | oldState: handleOldGestureState,
348 | state: handleGestureState,
349 | velocityY: this.velocityY,
350 | },
351 | },
352 | ]);
353 | this.onDrawerGestureEvent = event([
354 | {
355 | nativeEvent: {
356 | translationY: this.dragY,
357 | oldState: drawerOldGestureState,
358 | state: drawerGestureState,
359 | velocityY: this.velocityY,
360 | },
361 | },
362 | ]);
363 | this.onScrollBeginDrag = event([
364 | {
365 | nativeEvent: {
366 | contentOffset: { y: this.lastStartScrollY },
367 | },
368 | },
369 | ]);
370 |
371 | const didHandleGestureBegin = eq(handleGestureState, GestureState.ACTIVE);
372 |
373 | const isAnimationInterrupted = and(
374 | or(
375 | eq(handleGestureState, GestureState.BEGAN),
376 | eq(drawerGestureState, GestureState.BEGAN),
377 | and(
378 | eq(this.isAndroid, 0),
379 | eq(animationDriver, 1),
380 | or(
381 | eq(drawerGestureState, GestureState.ACTIVE),
382 | eq(handleGestureState, GestureState.ACTIVE)
383 | )
384 | )
385 | ),
386 | clockRunning(this.animationClock)
387 | );
388 |
389 | this.didGestureFinish = or(
390 | and(
391 | eq(handleOldGestureState, GestureState.ACTIVE),
392 | eq(handleGestureState, GestureState.END)
393 | ),
394 | and(
395 | eq(drawerOldGestureState, GestureState.ACTIVE),
396 | eq(drawerGestureState, GestureState.END)
397 | )
398 | );
399 |
400 | // Function that determines if the last snap point is in the range {snapPoints}
401 | // In the case of interruptions in the middle of an animation, we'll get
402 | // lastSnap values outside the range
403 | const isLastSnapPointInRange = (i: number = 0): Animated.Node =>
404 | i === snapPoints.length
405 | ? lastSnapInRange
406 | : cond(
407 | eq(this.lastSnap, snapPoints[i]),
408 | [set(lastSnapInRange, 1)],
409 | isLastSnapPointInRange(i + 1)
410 | );
411 |
412 | const scrollY = [
413 | set(lastSnapInRange, 0),
414 | isLastSnapPointInRange(),
415 | cond(
416 | or(
417 | didHandleGestureBegin,
418 | and(
419 | this.isManuallySetValue,
420 | not(eq(this.manualYOffset, snapPoints[0]))
421 | )
422 | ),
423 | [set(this.dragWithHandle, 1), 0]
424 | ),
425 | cond(
426 | // This is to account for a continuous scroll on the drawer from a snap point
427 | // Different than top, bringing the drawer to the top position, so that if we
428 | // change scroll direction without releasing the gesture, it doesn't pull down the drawer again
429 | and(
430 | eq(this.dragWithHandle, 1),
431 | greaterThan(snapPoints[0], add(this.lastSnap, this.dragY)),
432 | and(not(eq(this.lastSnap, snapPoints[0])), lastSnapInRange)
433 | ),
434 | [
435 | set(this.lastSnap, snapPoints[0]),
436 | set(this.dragWithHandle, 0),
437 | this.lastStartScrollY,
438 | ],
439 | cond(eq(this.dragWithHandle, 1), 0, this.lastStartScrollY)
440 | ),
441 | ];
442 |
443 | this.didScrollUpAndPullDown = cond(
444 | and(
445 | greaterOrEq(this.dragY, this.lastStartScrollY),
446 | greaterThan(this.lastStartScrollY, 0)
447 | ),
448 | set(this.scrollUpAndPullDown, 1)
449 | );
450 |
451 | this.setTranslationY = cond(
452 | and(
453 | not(this.dragWithHandle),
454 | not(greaterOrEq(this.dragY, this.lastStartScrollY))
455 | ),
456 | set(this.translationY, sub(this.dragY, this.lastStartScrollY)),
457 | set(this.translationY, this.dragY)
458 | );
459 |
460 | this.extraOffset = cond(
461 | eq(this.scrollUpAndPullDown, 1),
462 | this.lastStartScrollY,
463 | 0
464 | );
465 | const endOffsetY = add(
466 | this.lastSnap,
467 | this.translationY,
468 | multiply(1 - props.friction, this.velocityY)
469 | );
470 |
471 | this.calculateNextSnapPoint = (i = 0): Animated.Node | number =>
472 | i === snapPoints.length
473 | ? this.tempDestSnapPoint
474 | : cond(
475 | greaterThan(
476 | abs(sub(this.tempDestSnapPoint, endOffsetY)),
477 | abs(sub(add(snapPoints[i], this.extraOffset), endOffsetY))
478 | ),
479 | [
480 | set(this.tempDestSnapPoint, add(snapPoints[i], this.extraOffset)),
481 | set(this.nextSnapIndex, i),
482 | this.calculateNextSnapPoint(i + 1),
483 | ],
484 | this.calculateNextSnapPoint(i + 1)
485 | );
486 |
487 | const runAnimation = ({
488 | clock,
489 | from,
490 | to,
491 | position,
492 | finished,
493 | velocity,
494 | frameTime,
495 | }: TimingParams) => {
496 | const state = {
497 | finished,
498 | velocity: new Value(0),
499 | position,
500 | time: new Value(0),
501 | frameTime,
502 | };
503 |
504 | const timingConfig = {
505 | duration: animationDuration,
506 | easing:
507 | (props.animationType === 'timing' && props.animationConfig?.easing) ||
508 | DEFAULT_EASING,
509 | toValue: new Value(0),
510 | };
511 |
512 | const springConfig = {
513 | ...DEFAULT_SPRING_PARAMS,
514 | ...((props.animationType === 'spring' && props.animationConfig) || {}),
515 | toValue: new Value(0),
516 | };
517 |
518 | return [
519 | cond(and(not(clockRunning(clock)), not(eq(finished, 1))), [
520 | // If the clock isn't running, we reset all the animation params and start the clock
521 | set(state.finished, 0),
522 | set(state.velocity, velocity),
523 | set(state.time, 0),
524 | set(state.position, from),
525 | set(state.frameTime, 0),
526 | set(timingConfig.toValue, to),
527 | set(springConfig.toValue, to),
528 | startClock(clock),
529 | ]),
530 | // We run the step here that is going to update position
531 | cond(
532 | eq(animationDriver, 0),
533 | timing(clock, state, timingConfig),
534 | spring(clock, state, springConfig)
535 | ),
536 | cond(
537 | state.finished,
538 | [
539 | call([this.nextSnapIndex], ([value]) => {
540 | if (value !== this.prevSnapIndex) {
541 | this.props.onSettle?.(value);
542 | }
543 | this.prevSnapIndex = value;
544 | }),
545 | // Resetting appropriate values
546 | set(drawerOldGestureState, GestureState.END),
547 | set(handleOldGestureState, GestureState.END),
548 | set(this.prevTranslateYOffset, state.position),
549 | cond(eq(this.scrollUpAndPullDown, 1), [
550 | set(
551 | this.prevTranslateYOffset,
552 | sub(this.prevTranslateYOffset, this.lastStartScrollY)
553 | ),
554 | set(this.lastStartScrollY, 0),
555 | set(this.scrollUpAndPullDown, 0),
556 | ]),
557 | cond(eq(this.destSnapPoint, snapPoints[0]), [
558 | set(this.dragWithHandle, 0),
559 | ]),
560 | set(this.isManuallySetValue, 0),
561 | set(this.manualYOffset, 0),
562 | stopClock(clock),
563 | this.prevTranslateYOffset,
564 | ],
565 | // We made the block return the updated position,
566 | state.position
567 | ),
568 | ];
569 | };
570 |
571 | const translateYOffset = cond(
572 | isAnimationInterrupted,
573 | [
574 | // set(prevTranslateYOffset, animationPosition) should only run if we are
575 | // interrupting an animation when the drawer is currently in a different
576 | // position than the top
577 | cond(
578 | or(
579 | this.dragWithHandle,
580 | greaterOrEq(abs(this.prevDragY), this.lastStartScrollY)
581 | ),
582 | set(this.prevTranslateYOffset, this.animationPosition)
583 | ),
584 | set(this.animationFinished, 1),
585 | set(this.translationY, 0),
586 | // Resetting appropriate values
587 | set(drawerOldGestureState, GestureState.END),
588 | set(handleOldGestureState, GestureState.END),
589 | // By forcing that frameTime exceeds duration, it has the effect of stopping the animation
590 | set(this.animationFrameTime, add(animationDuration, 1000)),
591 | set(this.velocityY, 0),
592 | stopClock(this.animationClock),
593 | this.prevTranslateYOffset,
594 | ],
595 | cond(
596 | or(
597 | this.didGestureFinish,
598 | this.isManuallySetValue,
599 | clockRunning(this.animationClock)
600 | ),
601 | [
602 | runAnimation({
603 | clock: this.animationClock,
604 | from: cond(
605 | this.isManuallySetValue,
606 | this.prevTranslateYOffset,
607 | add(this.prevTranslateYOffset, this.translationY)
608 | ),
609 | to: this.destSnapPoint,
610 | position: this.animationPosition,
611 | finished: this.animationFinished,
612 | frameTime: this.animationFrameTime,
613 | velocity: this.velocityY,
614 | }),
615 | ],
616 | [
617 | set(this.animationFrameTime, 0),
618 | set(this.animationFinished, 0),
619 | // @ts-ignore
620 | this.prevTranslateYOffset,
621 | ]
622 | )
623 | );
624 |
625 | this.translateY = interpolate(
626 | add(translateYOffset, this.dragY, multiply(scrollY, -1)),
627 | {
628 | inputRange: [openPosition, closedPosition],
629 | outputRange: [openPosition, closedPosition],
630 | extrapolate: Extrapolate.CLAMP,
631 | }
632 | );
633 |
634 | this.position = interpolate(this.translateY, {
635 | inputRange: [openPosition, snapPoints[snapPoints.length - 1]],
636 | outputRange: [1, 0],
637 | extrapolate: Extrapolate.CLAMP,
638 | });
639 | }
640 |
641 | private getNormalisedSnapPoints = () => {
642 | return this.props.snapPoints.map(p => {
643 | if (typeof p === 'string') {
644 | return this.convertPercentageToDp(p);
645 | } else if (typeof p === 'number') {
646 | return p;
647 | }
648 |
649 | throw new Error(
650 | `Invalid type for value ${p}: ${typeof p}. It should be either a percentage string or a number`
651 | );
652 | });
653 | };
654 |
655 | private getScrollComponent = () => {
656 | switch (this.props.componentType) {
657 | case 'FlatList':
658 | return FlatList;
659 | case 'ScrollView':
660 | return ScrollView;
661 | case 'SectionList':
662 | return SectionList;
663 | default:
664 | throw new Error(
665 | 'Component type not supported: it should be one of `FlatList`, `ScrollView` or `SectionList`'
666 | );
667 | }
668 | };
669 |
670 | snapTo = (index: number) => {
671 | const snapPoints = this.getNormalisedSnapPoints();
672 | this.isManuallySetValue.setValue(1);
673 | this.manualYOffset.setValue(snapPoints[index]);
674 | this.nextSnapIndex.setValue(index);
675 | };
676 |
677 | render() {
678 | const {
679 | renderHandle,
680 | snapPoints,
681 | initialSnapIndex,
682 | componentType,
683 | onSettle,
684 | animatedPosition,
685 | containerStyle,
686 | ...rest
687 | } = this.props;
688 | const AnimatedScrollableComponent = this.scrollComponent;
689 | const normalisedSnapPoints = this.getNormalisedSnapPoints();
690 | const initialSnap = normalisedSnapPoints[initialSnapIndex];
691 |
692 | const Content = (
693 |
703 |
710 | {renderHandle()}
711 |
712 |
719 |
720 |
725 |
739 |
740 |
741 |
742 | {this.props.animatedPosition && (
743 |
749 | )}
750 |
756 | {
775 | // This prevents the scroll glide from happening on Android when pulling down with inertia.
776 | // It's not perfect, but does the job for now
777 | const { method, args } = imperativeScrollOptions[
778 | this.props.componentType
779 | ];
780 | // @ts-ignore
781 | const node = this.props.innerRef.current?.getNode();
782 |
783 | if (
784 | node &&
785 | node[method] &&
786 | ((this.props.componentType === 'FlatList' &&
787 | (this.props?.data?.length || 0) > 0) ||
788 | (this.props.componentType === 'SectionList' &&
789 | this.props.sections.length > 0) ||
790 | this.props.componentType === 'ScrollView')
791 | ) {
792 | node[method](args);
793 | }
794 | })
795 | ),
796 | set(this.dragY, 0),
797 | set(this.velocityY, 0),
798 | set(
799 | this.lastSnap,
800 | sub(
801 | this.destSnapPoint,
802 | cond(
803 | eq(this.scrollUpAndPullDown, 1),
804 | this.lastStartScrollY,
805 | 0
806 | )
807 | )
808 | ),
809 | call([this.lastSnap], ([value]) => {
810 | // This is the TapGHandler trick
811 | // @ts-ignore
812 | this.masterDrawer?.current?.setNativeProps({
813 | maxDeltaY: value - this.getNormalisedSnapPoints()[0],
814 | });
815 | }),
816 | set(
817 | this.decelerationRate,
818 | cond(
819 | eq(this.isAndroid, 1),
820 | cond(
821 | eq(this.lastSnap, normalisedSnapPoints[0]),
822 | ANDROID_NORMAL_DECELERATION_RATE,
823 | 0
824 | ),
825 | IOS_NORMAL_DECELERATION_RATE
826 | )
827 | ),
828 | ])
829 | )}
830 | />
831 | {
840 | // This is the TapGHandler trick
841 | // @ts-ignore
842 | this.masterDrawer?.current?.setNativeProps({
843 | maxDeltaY: value - this.getNormalisedSnapPoints()[0],
844 | });
845 | }),
846 | ],
847 | [set(this.nextSnapIndex, 0)]
848 | ),
849 | ])}
850 | />
851 |
852 | );
853 |
854 | // On Android, having an intermediary view with pointerEvents="box-none", breaks the
855 | // waitFor logic
856 | if (Platform.OS === 'android') {
857 | return (
858 |
864 | {Content}
865 |
866 | );
867 | }
868 |
869 | // On iOS, We need to wrap the content on a view with PointerEvents box-none
870 | // So that we can start scrolling automatically when reaching the top without
871 | // Stopping the gesture
872 | return (
873 |
878 |
879 | {Content}
880 |
881 |
882 | );
883 | }
884 | }
885 |
886 | export default ScrollBottomSheet;
887 |
888 | const styles = StyleSheet.create({
889 | container: {
890 | flex: 1,
891 | },
892 | });
893 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "exclude": ["./example"],
3 | "compilerOptions": {
4 | "baseUrl": ".",
5 | "paths": {
6 | "react-native-scroll-bottom-sheet": ["./src/index"]
7 | },
8 | "allowUnreachableCode": false,
9 | "allowUnusedLabels": false,
10 | "esModuleInterop": true,
11 | "forceConsistentCasingInFileNames": true,
12 | "jsx": "react",
13 | "lib": ["esnext"],
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 |
--------------------------------------------------------------------------------