├── .circleci └── config.yml ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .watchmanconfig ├── .yarnrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── babel.config.js ├── docs └── assets │ ├── android.gif │ ├── banner.png │ └── ios.gif ├── example ├── app.json ├── babel.config.js ├── index.js ├── metro.config.js ├── package.json ├── src │ └── App.tsx ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── lefthook.yml ├── package.json ├── scripts └── bootstrap.js ├── src ├── BottomSheetAdaptiveView.tsx ├── BottomSheetContextProvider.tsx ├── MagicSheetHandlers.ts ├── MagicSheetPortal.tsx ├── __tests__ │ └── index.test.tsx └── index.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:16 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 -------------------------------------------------------------------------------- /.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 | .classpath 35 | .cxx 36 | .gradle 37 | .idea 38 | .project 39 | .settings 40 | local.properties 41 | android.iml 42 | 43 | # Cocoapods 44 | # 45 | example/ios/Pods 46 | 47 | # Ruby 48 | example/vendor/ 49 | 50 | # node.js 51 | # 52 | node_modules/ 53 | npm-debug.log 54 | yarn-debug.log 55 | yarn-error.log 56 | 57 | # BUCK 58 | buck-out/ 59 | \.buckd/ 60 | android/app/libs 61 | android/keystores/debug.keystore 62 | 63 | # Expo 64 | .expo/* 65 | 66 | # generated by bob 67 | lib/ 68 | -------------------------------------------------------------------------------- /.watchmanconfig: -------------------------------------------------------------------------------- 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 it's possible to use [`npm`](https://github.com/npm/cli), the tooling is built around [`yarn`](https://classic.yarnpkg.com/), so you'll have an easier time if you use `yarn` for development. 14 | 15 | While developing, you can run the [example app](/example/) to test your changes. Any changes you make in your library's JavaScript code will be reflected in the example app without a rebuild. If you change any native code, then you'll need to rebuild the example app. 16 | 17 | To start the packager: 18 | 19 | ```sh 20 | yarn example start 21 | ``` 22 | 23 | To run the example app on Android: 24 | 25 | ```sh 26 | yarn example android 27 | ``` 28 | 29 | To run the example app on iOS: 30 | 31 | ```sh 32 | yarn example ios 33 | ``` 34 | 35 | To run the example app on Web: 36 | 37 | ```sh 38 | yarn example web 39 | ``` 40 | 41 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 42 | 43 | ```sh 44 | yarn typescript 45 | yarn lint 46 | ``` 47 | 48 | To fix formatting errors, run the following: 49 | 50 | ```sh 51 | yarn lint --fix 52 | ``` 53 | 54 | Remember to add tests for your change if possible. Run the unit tests by: 55 | 56 | ```sh 57 | yarn test 58 | ``` 59 | ### Commit message convention 60 | 61 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 62 | 63 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 64 | - `feat`: new features, e.g. add new method to the module. 65 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 66 | - `docs`: changes into documentation, e.g. add usage example for the module.. 67 | - `test`: adding or updating tests, e.g. add integration tests using detox. 68 | - `chore`: tooling changes, e.g. change CI config. 69 | 70 | Our pre-commit hooks verify that your commit message matches this format when committing. 71 | 72 | ### Linting and tests 73 | 74 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 75 | 76 | 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. 77 | 78 | Our pre-commit hooks verify that the linter and tests pass when committing. 79 | 80 | ### Publishing to npm 81 | 82 | We use [release-it](https://github.com/release-it/release-it) to make it easier to publish new versions. It handles common tasks like bumping version based on semver, creating tags and releases etc. 83 | 84 | To publish new versions, run the following: 85 | 86 | ```sh 87 | yarn release 88 | ``` 89 | 90 | ### Scripts 91 | 92 | The `package.json` file contains various scripts for common tasks: 93 | 94 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 95 | - `yarn typescript`: type-check files with TypeScript. 96 | - `yarn lint`: lint files with ESLint. 97 | - `yarn test`: run unit tests with Jest. 98 | - `yarn example start`: start the Metro server for the example app. 99 | - `yarn example android`: run the example app on Android. 100 | - `yarn example ios`: run the example app on iOS. 101 | 102 | ### Sending a pull request 103 | 104 | > **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://app.egghead.io/playlists/how-to-contribute-to-an-open-source-project-on-github). 105 | 106 | When you're sending a pull request: 107 | 108 | - Prefer small pull requests focused on one change. 109 | - Verify that linters and tests are passing. 110 | - Review the documentation to make sure it looks good. 111 | - Follow the pull request template when opening a pull request. 112 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 113 | 114 | ## Code of Conduct 115 | 116 | ### Our Pledge 117 | 118 | 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. 119 | 120 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 121 | 122 | ### Our Standards 123 | 124 | Examples of behavior that contributes to a positive environment for our community include: 125 | 126 | - Demonstrating empathy and kindness toward other people 127 | - Being respectful of differing opinions, viewpoints, and experiences 128 | - Giving and gracefully accepting constructive feedback 129 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 130 | - Focusing on what is best not just for us as individuals, but for the overall community 131 | 132 | Examples of unacceptable behavior include: 133 | 134 | - The use of sexualized language or imagery, and sexual attention or 135 | advances of any kind 136 | - Trolling, insulting or derogatory comments, and personal or political attacks 137 | - Public or private harassment 138 | - Publishing others' private information, such as a physical or email 139 | address, without their explicit permission 140 | - Other conduct which could reasonably be considered inappropriate in a 141 | professional setting 142 | 143 | ### Enforcement Responsibilities 144 | 145 | 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. 146 | 147 | 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. 148 | 149 | ### Scope 150 | 151 | 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. 152 | 153 | ### Enforcement 154 | 155 | 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. 156 | 157 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 158 | 159 | ### Enforcement Guidelines 160 | 161 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 162 | 163 | #### 1. Correction 164 | 165 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 166 | 167 | **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. 168 | 169 | #### 2. Warning 170 | 171 | **Community Impact**: A violation through a single incident or series of actions. 172 | 173 | **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. 174 | 175 | #### 3. Temporary Ban 176 | 177 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 178 | 179 | **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. 180 | 181 | #### 4. Permanent Ban 182 | 183 | **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. 184 | 185 | **Consequence**: A permanent ban from any sort of public interaction within the community. 186 | 187 | ### Attribution 188 | 189 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 190 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 191 | 192 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 193 | 194 | [homepage]: https://www.contributor-covenant.org 195 | 196 | For answers to common questions about this code of conduct, see the FAQ at 197 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 198 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Roudain Sarhan 4 | Permission is hereby granted, free of charge, to any person obtaining a copy 5 | of this software and associated documentation files (the "Software"), to deal 6 | in the Software without restriction, including without limitation the rights 7 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the Software is 9 | furnished to do so, subject to the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included in all 12 | copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 20 | SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![React Native Magic Sheet Cover](/docs/assets/banner.png) 2 | 3 | _A Bottom Sheet library that can be called imperatively from anywhere!_ 4 | 5 | ## React Native Magic Sheet :sparkles: 6 | 7 | Inspired by [react-native-magic-modal](https://github.com/GSTJ/react-native-magic-modal/) This library aims to solve the need to declaretively add bottom sheets to our screens by providing an imperative API that can be called from anywhere in the app (even outside of components) to show a fully customizeable bottom sheet with the ability to wait for it to resolve and get a response back. 8 | 9 | This library relies on the modal component of [@gorhom/bottom-sheet](https://gorhom.github.io/react-native-bottom-sheet/modal/) and accepts the same props and children. 10 | 11 | Therefore the setup proccess of [@gorhom/bottom-sheet](https://gorhom.github.io/react-native-bottom-sheet/modal/) should be followed in order for this to work 12 | 13 | (ex: installing gesture handler, reanimated2, and @gorhom/bottom-sheet v4) 14 | 15 | ## 📸 Examples 16 | 17 | | IOS | Android | 18 | | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | 19 | | | | 20 | 21 | ## 🛠 Installation 22 | 23 | ```sh 24 | yarn add react-native-magic-sheet 25 | ``` 26 | 27 | ## ⚙️ Usage 28 | 29 | First, insert a `MagicSheetPortal` in the top of the application and make sure the app is wrapped with GestureHandlerRootView & BottomSheetModalProvider. 30 | 31 | You can add the default props and styles of type BottomSheetProps (optional as you can override the props when calling the sheet later). 32 | 33 | ```js 34 | import {GestureHandlerRootView} from 'react-native-gesture-handler'; 35 | import {BottomSheetModalProvider} from '@gorhom/bottom-sheet'; 36 | import {MagicSheetPortal} from 'react-native-magic-sheet'; 37 | 38 | export default function App() { 39 | return ( 40 | 41 | 42 | 43 | // <-- On the top of the app component hierarchy 44 | // The rest of the app goes here 45 | 46 | 47 | 48 | ); 49 | } 50 | ``` 51 | 52 | Then, you are free to use the `magicSheet` as shown from anywhere you want. 53 | 54 | ```js 55 | import React from 'react'; 56 | import { View, Text, TouchableOpacity } from 'react-native'; 57 | import { magicSheet } from 'react-native-magic-sheet'; 58 | 59 | const PickerSheet = (someProps) => ( 60 | 61 | { 63 | magicSheet.hide({userName: "Rod", id:1}) 64 | }}> // This will hide the sheet, resolve the promise with the passed object 65 | Return user 66 | 67 | 68 | ); 69 | 70 | const handlePickUser = async () => { 71 | // We can call it with or without props, depending on the requirements. 72 | const result = await magicSheet.show(PickerSheet); 73 | 74 | //OR (with props) 75 | const result = await magicSheet.show(() => ); 76 | 77 | console.log(result) 78 | // will show {userName: "Rod", id:1}, or undefined if sheet is dismissed 79 | }; 80 | 81 | export const Screen = () => { 82 | return ( 83 | 84 | 85 | Show sheet 86 | 87 | 88 | ); 89 | }; 90 | ``` 91 | 92 | Alternatively, if we don't care about waiting the resolved value of the promise we can just trigger some action instead. 93 | 94 | ```js 95 | import React from 'react'; 96 | import {View, Text, TouchableOpacity} from 'react-native'; 97 | import {magicSheet} from 'react-native-magic-sheet'; 98 | 99 | const PickerSheet = (props) => ( 100 | 101 | { 103 | magicSheet.hide(); 104 | props.onSelect({userName: "Rod", id:1}) 105 | }}> 106 | Return user 107 | 108 | 109 | ); 110 | 111 | export const Screen = () => { 112 | const [user, setUser] = useState(); 113 | 114 | const handlePickUser = useCallback( 115 | () => { 116 | magicSheet.show( 117 | () => {setUser(value)}}/> 118 | ) 119 | } 120 | ,[]) 121 | 122 | return ( 123 | 124 | 126 | Show sheet 127 | 128 | 129 | ); 130 | }; 131 | ``` 132 | 133 | magicSheet.show( ) can take another optional argument of type BottomSheetProps if we need to override the default props and style of the bottom sheet container 134 | 135 | Example: 136 | ```js 137 | magicSheet.show( 138 | () => , 139 | {backgroundStyle: styles.bottomSheetContainer} 140 | ) 141 | ``` 142 | ## 😬 Notes 143 | 144 | ### Inner components 145 | It's recommended to use the components provided by [@gorhom/bottom-sheet](https://gorhom.github.io/react-native-bottom-sheet/modal/) inside of the bottom sheet as those components are made to adapt to the bottom sheet behavior, especially scrollables and text inputs. 146 | 147 | 148 | ## 👨‍🏫 Contributing 149 | 150 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 151 | 152 | ## ⚖️ License 153 | 154 | [MIT](LICENSE) 155 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /docs/assets/android.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RodSarhan/react-native-magic-sheet/04d7f041e7a9e651414b618a2efb1b1fce640239/docs/assets/android.gif -------------------------------------------------------------------------------- /docs/assets/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RodSarhan/react-native-magic-sheet/04d7f041e7a9e651414b618a2efb1b1fce640239/docs/assets/banner.png -------------------------------------------------------------------------------- /docs/assets/ios.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/RodSarhan/react-native-magic-sheet/04d7f041e7a9e651414b618a2efb1b1fce640239/docs/assets/ios.gif -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-magic-sheet-example", 3 | "displayName": "MagicSheet Example", 4 | "expo": { 5 | "name": "react-native-magic-sheet-example", 6 | "slug": "react-native-magic-sheet-example", 7 | "description": "Example app for react-native-magic-sheet", 8 | "privacy": "public", 9 | "version": "1.0.0", 10 | "platforms": [ 11 | "ios", 12 | "android", 13 | "web" 14 | ], 15 | "ios": { 16 | "supportsTablet": true 17 | }, 18 | "jsEngine": "hermes", 19 | "assetBundlePatterns": [ 20 | "**/*" 21 | ] 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /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 | ], 21 | }; 22 | }; 23 | -------------------------------------------------------------------------------- /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 escape = require('escape-string-regexp'); 3 | const { getDefaultConfig } = require('@expo/metro-config'); 4 | const exclusionList = require('metro-config/src/defaults/exclusionList'); 5 | const pak = require('../package.json'); 6 | 7 | const root = path.resolve(__dirname, '..'); 8 | 9 | const modules = Object.keys({ 10 | ...pak.peerDependencies, 11 | }); 12 | 13 | const defaultConfig = getDefaultConfig(__dirname); 14 | 15 | module.exports = { 16 | ...defaultConfig, 17 | 18 | projectRoot: __dirname, 19 | watchFolders: [root], 20 | 21 | // We need to make sure that only one version is loaded for peerDependencies 22 | // So we block them at the root, and alias them to the versions in example's node_modules 23 | resolver: { 24 | ...defaultConfig.resolver, 25 | 26 | blacklistRE: exclusionList( 27 | modules.map( 28 | (m) => 29 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 30 | ) 31 | ), 32 | 33 | extraNodeModules: modules.reduce((acc, name) => { 34 | acc[name] = path.join(__dirname, 'node_modules', name); 35 | return acc; 36 | }, {}), 37 | }, 38 | }; 39 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-magic-sheet-example", 3 | "description": "Example app for react-native-magic-sheet", 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 | }, 13 | "dependencies": { 14 | "expo": "^45.0.0", 15 | "expo-splash-screen": "~0.15.1", 16 | "react": "17.0.2", 17 | "react-dom": "17.0.2", 18 | "react-native": "0.68.2", 19 | "react-native-web": "0.17.7" 20 | }, 21 | "devDependencies": { 22 | "@babel/core": "^7.12.9", 23 | "@babel/runtime": "^7.9.6", 24 | "babel-loader": "^8.2.5", 25 | "babel-plugin-module-resolver": "^4.0.0", 26 | "babel-preset-expo": "~9.1.0", 27 | "expo-cli": "^5.4.11" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StyleSheet, View, Text } from 'react-native'; 3 | 4 | export default function App() { 5 | return ( 6 | 7 | RN Magic Sheet 8 | 9 | ); 10 | } 11 | 12 | const styles = StyleSheet.create({ 13 | container: { 14 | flex: 1, 15 | alignItems: 'center', 16 | justifyContent: 'center', 17 | }, 18 | box: { 19 | width: 60, 20 | height: 60, 21 | marginVertical: 20, 22 | }, 23 | }); 24 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig", 3 | "compilerOptions": { 4 | // Avoid expo-cli auto-generating a tsconfig 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /lefthook.yml: -------------------------------------------------------------------------------- 1 | pre-commit: 2 | parallel: true 3 | commands: 4 | lint: 5 | files: git diff --name-only @{push} 6 | glob: "*.{js,ts,jsx,tsx}" 7 | run: npx eslint {files} 8 | types: 9 | files: git diff --name-only @{push} 10 | glob: "*.{js,ts, jsx, tsx}" 11 | run: npx tsc --noEmit 12 | commit-msg: 13 | parallel: true 14 | commands: 15 | commitlint: 16 | run: npx commitlint --edit 17 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "react-native-magic-sheet", 3 | "version": "0.4.1", 4 | "description": "test", 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-magic-sheet.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 | "release": "release-it", 30 | "example": "yarn --cwd example", 31 | "bootstrap": "yarn example && yarn && yarn example pods" 32 | }, 33 | "keywords": [ 34 | "react-native", 35 | "ios", 36 | "android" 37 | ], 38 | "repository": "https://github.com/RodSarhan/react-native-magic-sheet", 39 | "author": "Roudain Sarhan (https://github.com/RodSarhan)", 40 | "license": "MIT", 41 | "bugs": { 42 | "url": "https://github.com/RodSarhan/react-native-magic-sheet/issues" 43 | }, 44 | "homepage": "https://github.com/RodSarhan/react-native-magic-sheet#readme", 45 | "publishConfig": { 46 | "registry": "https://registry.npmjs.org/" 47 | }, 48 | "devDependencies": { 49 | "@gorhom/bottom-sheet": "^4", 50 | "@arkweid/lefthook": "^0.7.7", 51 | "@babel/eslint-parser": "^7.18.2", 52 | "@commitlint/config-conventional": "^17.0.2", 53 | "@react-native-community/eslint-config": "^3.0.2", 54 | "@release-it/conventional-changelog": "^5.0.0", 55 | "@types/jest": "^28.1.2", 56 | "@types/react": "~17.0.21", 57 | "@types/react-native": "0.68.0", 58 | "commitlint": "^17.0.2", 59 | "eslint": "^8.4.1", 60 | "eslint-config-prettier": "^8.5.0", 61 | "eslint-plugin-prettier": "^4.0.0", 62 | "jest": "^28.1.1", 63 | "pod-install": "^0.1.0", 64 | "prettier": "^2.0.5", 65 | "react": "17.0.2", 66 | "react-native": "0.68.2", 67 | "react-native-builder-bob": "^0.18.3", 68 | "release-it": "^15.0.0", 69 | "typescript": "^4.5.2" 70 | }, 71 | "resolutions": { 72 | "@types/react": "17.0.21" 73 | }, 74 | "peerDependencies": { 75 | "react": "*", 76 | "react-native": "*", 77 | "@gorhom/bottom-sheet": "^4" 78 | }, 79 | "jest": { 80 | "preset": "react-native", 81 | "modulePathIgnorePatterns": [ 82 | "/example/node_modules", 83 | "/lib/" 84 | ] 85 | }, 86 | "commitlint": { 87 | "extends": [ 88 | "@commitlint/config-conventional" 89 | ] 90 | }, 91 | "release-it": { 92 | "git": { 93 | "commitMessage": "chore: release ${version}", 94 | "tagName": "v${version}" 95 | }, 96 | "npm": { 97 | "publish": true 98 | }, 99 | "github": { 100 | "release": true 101 | }, 102 | "plugins": { 103 | "@release-it/conventional-changelog": { 104 | "preset": "angular" 105 | } 106 | } 107 | }, 108 | "eslintConfig": { 109 | "root": true, 110 | "parser": "@typescript-eslint/parser", 111 | "extends": [ 112 | "@react-native-community", 113 | "prettier" 114 | ], 115 | "rules": { 116 | "prettier/prettier": [ 117 | "error", 118 | { 119 | "quoteProps": "consistent", 120 | "singleQuote": true, 121 | "tabWidth": 2, 122 | "trailingComma": "es5", 123 | "useTabs": false 124 | } 125 | ] 126 | } 127 | }, 128 | "eslintIgnore": [ 129 | "node_modules/", 130 | "lib/" 131 | ], 132 | "prettier": { 133 | "quoteProps": "consistent", 134 | "singleQuote": true, 135 | "tabWidth": 2, 136 | "trailingComma": "es5", 137 | "useTabs": false 138 | }, 139 | "react-native-builder-bob": { 140 | "source": "src", 141 | "output": "lib", 142 | "targets": [ 143 | "commonjs", 144 | "module", 145 | [ 146 | "typescript", 147 | { 148 | "project": "tsconfig.build.json" 149 | } 150 | ] 151 | ] 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | const os = require('os'); 2 | const path = require('path'); 3 | const child_process = require('child_process'); 4 | 5 | const root = path.resolve(__dirname, '..'); 6 | const args = process.argv.slice(2); 7 | const options = { 8 | cwd: process.cwd(), 9 | env: process.env, 10 | stdio: 'inherit', 11 | encoding: 'utf-8', 12 | }; 13 | 14 | if (os.type() === 'Windows_NT') { 15 | options.shell = true; 16 | } 17 | 18 | let result; 19 | 20 | if (process.cwd() !== root || args.length) { 21 | // We're not in the root of the project, or additional arguments were passed 22 | // In this case, forward the command to `yarn` 23 | result = child_process.spawnSync('yarn', args, options); 24 | } else { 25 | // If `yarn` is run without arguments, perform bootstrap 26 | result = child_process.spawnSync('yarn', ['bootstrap'], options); 27 | } 28 | 29 | process.exitCode = result.status; 30 | -------------------------------------------------------------------------------- /src/BottomSheetAdaptiveView.tsx: -------------------------------------------------------------------------------- 1 | import React, { PropsWithChildren } from 'react'; 2 | import { useBottomSheetLayoutContext } from './BottomSheetContextProvider'; 3 | import { BottomSheetView } from '@gorhom/bottom-sheet'; 4 | 5 | export const BottomSheetAdaptiveView: React.FC> = ({ 6 | children, 7 | }) => { 8 | const layoutContext = useBottomSheetLayoutContext(); 9 | 10 | return ( 11 | 12 | {children} 13 | 14 | ); 15 | }; 16 | -------------------------------------------------------------------------------- /src/BottomSheetContextProvider.tsx: -------------------------------------------------------------------------------- 1 | import { useBottomSheetDynamicSnapPoints } from '@gorhom/bottom-sheet'; 2 | import React, { 3 | createContext, 4 | PropsWithChildren, 5 | useContext, 6 | useMemo, 7 | } from 'react'; 8 | 9 | export const BottomSheetLayoutContext = createContext | null>(null); 12 | 13 | export const MagicSheetSnapPointsProvider: React.FC> = ({ 14 | children, 15 | }) => { 16 | const initialSnapPoints = useMemo(() => ['CONTENT_HEIGHT'], []); 17 | const dynamicSnapPointsValues = 18 | useBottomSheetDynamicSnapPoints(initialSnapPoints); 19 | return ( 20 | 21 | {children} 22 | 23 | ); 24 | }; 25 | 26 | export const useBottomSheetLayoutContext = () => 27 | useContext(BottomSheetLayoutContext); 28 | -------------------------------------------------------------------------------- /src/MagicSheetHandlers.ts: -------------------------------------------------------------------------------- 1 | import React, { ReactNode } from 'react'; 2 | import type { BottomSheetModalProps } from '@gorhom/bottom-sheet'; 3 | 4 | export type SheetContent = React.FC | ReactNode; 5 | 6 | export type NewSheetProps = Partial; 7 | 8 | /** 9 | * @description Show a sheet. If a sheet is already present, it will close it first before displaying. 10 | * @param newContent Recieves a function that returns a sheet component. 11 | * @param newProps Recieves {@link NewSheetProps} to override the default configs. 12 | * @returns {Promise} Returns a Promise that resolves with the {@link hide} props when the sheet is closed. If the sheet is dismissed it will resolve to undefined. 13 | */ 14 | const show = async ( 15 | newContent: SheetContent, 16 | newProps?: NewSheetProps 17 | ): Promise => magicSheetRef.current?.show?.(newContent, newProps); 18 | 19 | /** 20 | * @description Hide the current sheet. 21 | * @param args Those args will be passed to the {@link show} resolve function. 22 | * @returns {Promise} Returns a promise that resolves when hide happens. 23 | */ 24 | const hide = async (args?: any): Promise => 25 | magicSheetRef.current?.hide?.(args); 26 | 27 | export interface TMagicSheet { 28 | show: typeof show; 29 | hide: typeof hide; 30 | } 31 | 32 | export const magicSheetRef = React.createRef(); 33 | 34 | /** 35 | * @example 36 | * ```js 37 | * // ... 38 | * import { magicSheet } from 'react-native-magic-sheet'; 39 | * 40 | * // ... 41 | * const ExampleContent = () => ( 42 | * magicSheet.hide("hey")}> 43 | * Test! 44 | * 45 | * ) 46 | * 47 | * const result = await magicSheet.show(ExampleContent or ()=>); 48 | * console.log(result); // Returns 'hey' when the sheet is closed by the TouchableOpacity. 49 | * ``` 50 | */ 51 | export const magicSheet = { 52 | show, 53 | hide, 54 | }; 55 | -------------------------------------------------------------------------------- /src/MagicSheetPortal.tsx: -------------------------------------------------------------------------------- 1 | import React, { 2 | useState, 3 | useImperativeHandle, 4 | useCallback, 5 | useRef, 6 | useMemo, 7 | useEffect, 8 | } from 'react'; 9 | import { BackHandler } from 'react-native'; 10 | import { magicSheetRef } from './MagicSheetHandlers'; 11 | import type { 12 | NewSheetProps, 13 | SheetContent, 14 | TMagicSheet, 15 | } from './MagicSheetHandlers'; 16 | import { 17 | BottomSheetBackdrop, 18 | BottomSheetModal, 19 | type BottomSheetModalProps, 20 | } from '@gorhom/bottom-sheet'; 21 | import { useBottomSheetLayoutContext } from './BottomSheetContextProvider'; 22 | 23 | type ResolveFunction = (props?: any) => void; 24 | 25 | type MagicSheetPortalProps = Partial< 26 | Omit 27 | >; 28 | 29 | /** 30 | * @description A magic portal that should stay on the top of the app component hierarchy for the sheet to be displayed. 31 | */ 32 | export const MagicSheetPortal: React.FC = ( 33 | portalProps 34 | ) => { 35 | const bottomSheetRef = useRef(null); 36 | const [isVisible, setIsVisible] = useState(false); 37 | const [config, setConfig] = useState({}); 38 | const [sheetContent, setSheetContent] = useState(() => <>); 39 | const lastPromiseDidResolve = useRef(true); 40 | const fallbackSnapPoints = useMemo(() => ['50%'], []); 41 | 42 | const layoutContext = useBottomSheetLayoutContext(); 43 | const adaptiveValues = layoutContext 44 | ? { 45 | snapPoints: layoutContext?.animatedSnapPoints, 46 | handleHeight: layoutContext?.animatedHandleHeight, 47 | contentHeight: layoutContext?.animatedContentHeight, 48 | } 49 | : undefined; 50 | 51 | const resolveRef = useRef(() => {}); 52 | 53 | const hide = useCallback(async (props) => { 54 | bottomSheetRef.current?.dismiss(); 55 | resolveRef.current(props); 56 | }, []); 57 | 58 | const renderBackdrop = useCallback( 59 | (props) => ( 60 | 65 | ), 66 | [] 67 | ); 68 | 69 | useImperativeHandle(magicSheetRef, () => ({ 70 | hide: hide, 71 | show: async ( 72 | newContent: SheetContent, 73 | newProps: Partial = {} 74 | ) => { 75 | if (!lastPromiseDidResolve.current) { 76 | resolveRef.current(undefined); 77 | } 78 | setSheetContent(newContent); 79 | setConfig(newProps); 80 | lastPromiseDidResolve.current = false; 81 | bottomSheetRef.current?.present(); 82 | return new Promise((resolve) => { 83 | resolveRef.current = (value) => { 84 | resolve(value); 85 | lastPromiseDidResolve.current = true; 86 | }; 87 | }); 88 | }, 89 | })); 90 | 91 | useEffect(() => { 92 | if (isVisible) { 93 | const backHandler = BackHandler.addEventListener( 94 | 'hardwareBackPress', 95 | () => { 96 | bottomSheetRef.current?.dismiss(); 97 | return true; 98 | } 99 | ); 100 | return () => { 101 | backHandler.remove(); 102 | }; 103 | } else { 104 | return () => {}; 105 | } 106 | }, [isVisible]); 107 | 108 | return ( 109 | { 119 | if (!lastPromiseDidResolve.current) { 120 | resolveRef.current(); 121 | } 122 | config.onDismiss?.(); 123 | setIsVisible(false); 124 | }} 125 | onChange={(index) => { 126 | if (index >= 0) { 127 | setIsVisible(true); 128 | } 129 | if (index <= -1) { 130 | setIsVisible(false); 131 | } 132 | config.onChange?.(index); 133 | }} 134 | style={config.style ?? portalProps.style} 135 | > 136 | {sheetContent} 137 | 138 | ); 139 | }; 140 | -------------------------------------------------------------------------------- /src/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | it.todo('write a test'); 2 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | export { MagicSheetPortal } from './MagicSheetPortal'; 2 | export { magicSheet, NewSheetProps } from './MagicSheetHandlers'; 3 | export { BottomSheetAdaptiveView } from './BottomSheetAdaptiveView'; 4 | export { MagicSheetSnapPointsProvider } from './BottomSheetContextProvider'; 5 | -------------------------------------------------------------------------------- /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-magic-sheet": ["./src/index"] 6 | }, 7 | "allowUnreachableCode": false, 8 | "allowUnusedLabels": false, 9 | "esModuleInterop": true, 10 | "importsNotUsedAsValues": "error", 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 | "noUncheckedIndexedAccess": true, 21 | "noUnusedLocals": true, 22 | "noUnusedParameters": true, 23 | "resolveJsonModule": true, 24 | "skipLibCheck": true, 25 | "strict": true, 26 | "target": "esnext" 27 | } 28 | } 29 | --------------------------------------------------------------------------------