├── .circleci └── config.yml ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .husky ├── .npmignore ├── commit-msg └── pre-commit ├── .yarnrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets └── example.gif ├── babel.config.js ├── example ├── app.json ├── babel.config.js ├── index.js ├── metro.config.js ├── package.json ├── src │ └── App.tsx ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── package.json ├── scripts └── bootstrap.js ├── src ├── __tests__ │ └── index.test.tsx ├── index.tsx ├── light-box-modal.tsx ├── light-box.tsx ├── provider.tsx └── utils.tsx ├── tea.yaml ├── tsconfig.build.json ├── tsconfig.json └── yarn.lock /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2.1 2 | 3 | executors: 4 | default: 5 | docker: 6 | - image: circleci/node:10 7 | working_directory: ~/project 8 | 9 | commands: 10 | attach_project: 11 | steps: 12 | - attach_workspace: 13 | at: ~/project 14 | 15 | jobs: 16 | install-dependencies: 17 | executor: default 18 | steps: 19 | - checkout 20 | - attach_project 21 | - restore_cache: 22 | keys: 23 | - dependencies-{{ checksum "package.json" }} 24 | - dependencies- 25 | - restore_cache: 26 | keys: 27 | - dependencies-example-{{ checksum "example/package.json" }} 28 | - dependencies-example- 29 | - run: 30 | name: Install dependencies 31 | command: | 32 | yarn install --cwd example --frozen-lockfile 33 | yarn install --frozen-lockfile 34 | - save_cache: 35 | key: dependencies-{{ checksum "package.json" }} 36 | paths: node_modules 37 | - save_cache: 38 | key: dependencies-example-{{ checksum "example/package.json" }} 39 | paths: example/node_modules 40 | - persist_to_workspace: 41 | root: . 42 | paths: . 43 | 44 | lint: 45 | executor: default 46 | steps: 47 | - attach_project 48 | - run: 49 | name: Lint files 50 | command: | 51 | yarn lint 52 | 53 | typescript: 54 | executor: default 55 | steps: 56 | - attach_project 57 | - run: 58 | name: Typecheck files 59 | command: | 60 | yarn typescript 61 | 62 | unit-tests: 63 | executor: default 64 | steps: 65 | - attach_project 66 | - run: 67 | name: Run unit tests 68 | command: | 69 | yarn test --coverage 70 | - store_artifacts: 71 | path: coverage 72 | destination: coverage 73 | 74 | build-package: 75 | executor: default 76 | steps: 77 | - attach_project 78 | - run: 79 | name: Build package 80 | command: | 81 | yarn prepare 82 | 83 | workflows: 84 | build-and-test: 85 | jobs: 86 | - install-dependencies 87 | - lint: 88 | requires: 89 | - install-dependencies 90 | - typescript: 91 | requires: 92 | - install-dependencies 93 | - unit-tests: 94 | requires: 95 | - install-dependencies 96 | - build-package: 97 | requires: 98 | - install-dependencies 99 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | root = true 6 | 7 | [*] 8 | 9 | indent_style = space 10 | indent_size = 2 11 | 12 | end_of_line = lf 13 | charset = utf-8 14 | trim_trailing_whitespace = true 15 | insert_final_newline = true 16 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.pbxproj -text 2 | # specific for windows script files 3 | *.bat text eol=crlf -------------------------------------------------------------------------------- /.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 | # node.js 48 | # 49 | node_modules/ 50 | npm-debug.log 51 | yarn-debug.log 52 | yarn-error.log 53 | 54 | # BUCK 55 | buck-out/ 56 | \.buckd/ 57 | android/app/libs 58 | android/keystores/debug.keystore 59 | 60 | # Expo 61 | .expo/* 62 | 63 | # generated by bob 64 | lib/ 65 | -------------------------------------------------------------------------------- /.husky/.npmignore: -------------------------------------------------------------------------------- 1 | _ 2 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn commitlint -E HUSKY_GIT_PARAMS 5 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | . "$(dirname "$0")/_/husky.sh" 3 | 4 | yarn lint && yarn typescript 5 | -------------------------------------------------------------------------------- /.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 | 60 | ### Commit message convention 61 | 62 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 63 | 64 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 65 | - `feat`: new features, e.g. add new method to the module. 66 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 67 | - `docs`: changes into documentation, e.g. add usage example for the module.. 68 | - `test`: adding or updating tests, e.g. add integration tests using detox. 69 | - `chore`: tooling changes, e.g. change CI config. 70 | 71 | Our pre-commit hooks verify that your commit message matches this format when committing. 72 | 73 | ### Linting and tests 74 | 75 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 76 | 77 | 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. 78 | 79 | Our pre-commit hooks verify that the linter and tests pass when committing. 80 | 81 | ### Publishing to npm 82 | 83 | 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. 84 | 85 | To publish new versions, run the following: 86 | 87 | ```sh 88 | yarn release 89 | ``` 90 | 91 | ### Scripts 92 | 93 | The `package.json` file contains various scripts for common tasks: 94 | 95 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 96 | - `yarn typescript`: type-check files with TypeScript. 97 | - `yarn lint`: lint files with ESLint. 98 | - `yarn test`: run unit tests with Jest. 99 | - `yarn example start`: start the Metro server for the example app. 100 | - `yarn example android`: run the example app on Android. 101 | - `yarn example ios`: run the example app on iOS. 102 | 103 | ### Sending a pull request 104 | 105 | > **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). 106 | 107 | When you're sending a pull request: 108 | 109 | - Prefer small pull requests focused on one change. 110 | - Verify that linters and tests are passing. 111 | - Review the documentation to make sure it looks good. 112 | - Follow the pull request template when opening a pull request. 113 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 114 | 115 | ## Code of Conduct 116 | 117 | ### Our Pledge 118 | 119 | 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. 120 | 121 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 122 | 123 | ### Our Standards 124 | 125 | Examples of behavior that contributes to a positive environment for our community include: 126 | 127 | - Demonstrating empathy and kindness toward other people 128 | - Being respectful of differing opinions, viewpoints, and experiences 129 | - Giving and gracefully accepting constructive feedback 130 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 131 | - Focusing on what is best not just for us as individuals, but for the overall community 132 | 133 | Examples of unacceptable behavior include: 134 | 135 | - The use of sexualized language or imagery, and sexual attention or 136 | advances of any kind 137 | - Trolling, insulting or derogatory comments, and personal or political attacks 138 | - Public or private harassment 139 | - Publishing others' private information, such as a physical or email 140 | address, without their explicit permission 141 | - Other conduct which could reasonably be considered inappropriate in a 142 | professional setting 143 | 144 | ### Enforcement Responsibilities 145 | 146 | 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. 147 | 148 | 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. 149 | 150 | ### Scope 151 | 152 | 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. 153 | 154 | ### Enforcement 155 | 156 | 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. 157 | 158 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 159 | 160 | ### Enforcement Guidelines 161 | 162 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 163 | 164 | #### 1. Correction 165 | 166 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 167 | 168 | **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. 169 | 170 | #### 2. Warning 171 | 172 | **Community Impact**: A violation through a single incident or series of actions. 173 | 174 | **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. 175 | 176 | #### 3. Temporary Ban 177 | 178 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 179 | 180 | **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. 181 | 182 | #### 4. Permanent Ban 183 | 184 | **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. 185 | 186 | **Consequence**: A permanent ban from any sort of public interaction within the community. 187 | 188 | ### Attribution 189 | 190 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 191 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 192 | 193 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 194 | 195 | [homepage]: https://www.contributor-covenant.org 196 | 197 | For answers to common questions about this code of conduct, see the FAQ at 198 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 199 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 alantoa 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 | ## ⚠️ This package is no longer maintained 2 | 3 | This repository is no longer actively maintained. If you are looking for a more performant solution with an improved API, please check out [**galeria**](https://github.com/nandorojo/galeria). 4 | 5 | The **[galeria](https://github.com/nandorojo/galeria)** package provides better performance and enhanced features, making it a great alternative to continue your project. 6 | 7 | Thank you for your support! 8 | 9 |
10 |

React Native Lightbox

11 |
12 | 13 |
14 | basic usage 15 |
16 | 17 | ### Todo 18 | - [x] tap to close 19 | - [ ] pinch to zoom (use [Reanimated v2](https://docs.swmansion.com/react-native-reanimated/) & [react-native-gesture-handler v2](https://docs.swmansion.com/react-native-gesture-handler/)) 20 | - [ ] web support (use [photoswipe](https://github.com/dimsemenov/photoswipe) ) 21 | - [ ] photo gallery (use [react-native-pager-view](https://github.com/callstack/react-native-pager-view)) 22 | 23 | 24 | 25 | ### Installation 26 | First you have to follow installation instructions of [Reanimated v2](https://docs.swmansion.com/react-native-reanimated/) and [react-native-gesture-handler v2](https://docs.swmansion.com/react-native-gesture-handler/) 27 | 28 | ```sh 29 | npm install @alantoa/lightbox 30 | ``` 31 | 32 | ### Usage 33 | 34 | ```js 35 | import { LightBoxProvider, LightBox } from '@alantoa/lightbox'; 36 | import { StyleSheet, Image, Dimensions } from 'react-native'; 37 | import * as React from 'react'; 38 | 39 | const { width } = Dimensions.get('window'); 40 | 41 | export default function App() { 42 | return ( 43 | 44 | 49 | 55 | 56 | 57 | ); 58 | } 59 | ``` 60 | 61 | ### Contributing 62 | 63 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 64 | 65 | ### License 66 | 67 | MIT 68 | -------------------------------------------------------------------------------- /assets/example.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alantoa/react-native-lightbox/9f4e1f32887f15d6e408e484135ee6aad4537a2f/assets/example.gif -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@alantoa/lightbox-example", 3 | "displayName": "Lightbox Example", 4 | "expo": { 5 | "name": "@alantoa/lightbox-example", 6 | "slug": "alantoa-lightbox-example", 7 | "description": "Example app for @alantoa/lightbox", 8 | "privacy": "public", 9 | "version": "1.0.0", 10 | "platforms": [ 11 | "ios", 12 | "android", 13 | "web" 14 | ], 15 | "ios": { 16 | "supportsTablet": true 17 | }, 18 | "assetBundlePatterns": [ 19 | "**/*" 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = function (api) { 5 | api.cache(true); 6 | return { 7 | presets: ['babel-preset-expo'], 8 | plugins: [ 9 | [ 10 | 'module-resolver', 11 | { 12 | extensions: ['.tsx', '.ts', '.js', '.json'], 13 | alias: { 14 | // For development, we want to alias the library to the source 15 | [pak.name]: path.join(__dirname, '..', pak.source), 16 | }, 17 | }, 18 | ], 19 | 'react-native-reanimated/plugin', 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 blacklist = require('metro-config/src/defaults/exclusionList'); 3 | const escape = require('escape-string-regexp'); 4 | const pak = require('../package.json'); 5 | 6 | const root = path.resolve(__dirname, '..'); 7 | 8 | const modules = Object.keys({ 9 | ...pak.peerDependencies, 10 | }); 11 | 12 | module.exports = { 13 | projectRoot: __dirname, 14 | watchFolders: [root], 15 | 16 | // We need to make sure that only one version is loaded for peerDependencies 17 | // So we blacklist them at the root, and alias them to the versions in example's node_modules 18 | resolver: { 19 | blacklistRE: blacklist( 20 | modules.map( 21 | (m) => 22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 23 | ) 24 | ), 25 | 26 | extraNodeModules: modules.reduce((acc, name) => { 27 | acc[name] = path.join(__dirname, 'node_modules', name); 28 | return acc; 29 | }, {}), 30 | }, 31 | 32 | transformer: { 33 | getTransformOptions: async () => ({ 34 | transform: { 35 | experimentalImportSupport: false, 36 | inlineRequires: true, 37 | }, 38 | }), 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@alantoa/lightbox-example", 3 | "description": "Example app for @alantoa/lightbox", 4 | "version": "0.0.1", 5 | "main": "index", 6 | "scripts": { 7 | "start": "expo start", 8 | "android": "expo start --android", 9 | "ios": "expo start --ios", 10 | "web": "expo start --web", 11 | "eject": "expo eject" 12 | }, 13 | "dependencies": { 14 | "expo": "^49.0.21", 15 | "expo-status-bar": "~1.6.0", 16 | "react": "18.2.0", 17 | "react-dom": "18.2.0", 18 | "react-native": "0.72.6", 19 | "react-native-gesture-handler": "~2.12.0", 20 | "react-native-reanimated": "~3.3.0", 21 | "react-native-web": "~0.19.6" 22 | }, 23 | "devDependencies": { 24 | "@babel/core": "^7.20.0", 25 | "@types/react-native": "^0.67.7", 26 | "typescript": "^5.1.3" 27 | }, 28 | "resolutions": { 29 | "@types/react": "~17.0.21" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { LightBox, LightBoxProvider, useLightBox } from '@alantoa/lightbox'; 4 | import { Dimensions, SafeAreaView, ScrollView, StyleSheet } from 'react-native'; 5 | import { GestureHandlerRootView } from 'react-native-gesture-handler'; 6 | import Animated, { 7 | interpolate, 8 | useAnimatedStyle, 9 | } from 'react-native-reanimated'; 10 | const { width } = Dimensions.get('window'); 11 | 12 | const AZUKI_IMG_LIST = [ 13 | 'https://plus.unsplash.com/premium_photo-1679470310712-82c0a39cd41d?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDEwNXx4SHhZVE1ITGdPY3x8ZW58MHx8fHx8', 14 | 'https://images.unsplash.com/photo-1698681908648-962c6048ec3e?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDEyfENEd3V3WEpBYkV3fHxlbnwwfHx8fHw%3D', 15 | 'https://images.unsplash.com/photo-1658963654546-593c6ea57ce4?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDIyfENEd3V3WEpBYkV3fHxlbnwwfHx8fHw%3D', 16 | 'https://images.unsplash.com/photo-1698584200770-3838c3690a27?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDQyfENEd3V3WEpBYkV3fHxlbnwwfHx8fHw%3D', 17 | 'https://images.unsplash.com/photo-1619992525255-3bed3879b0d6?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDYyfENEd3V3WEpBYkV3fHxlbnwwfHx8fHw%3D', 18 | 'https://images.unsplash.com/photo-1703343872540-af08e5a6d703?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE5fHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D', 19 | 'https://images.unsplash.com/photo-1699514886400-3df192033292?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDMyOHxKcGc2S2lkbC1Ia3x8ZW58MHx8fHx8', 20 | 'https://plus.unsplash.com/premium_photo-1661808819761-878bc1a39dee?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDI1MnxKcGc2S2lkbC1Ia3x8ZW58MHx8fHx8', 21 | 'https://plus.unsplash.com/premium_photo-1666612440466-25089c980bfd?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDIzN3xKcGc2S2lkbC1Ia3x8ZW58MHx8fHx8', 22 | 'https://images.unsplash.com/photo-1699111259952-47e5c8e8727f?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDE2MnxKcGc2S2lkbC1Ia3x8ZW58MHx8fHx8', 23 | 'https://images.unsplash.com/photo-1694875464862-978a879a1210?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDkyfEpwZzZLaWRsLUhrfHxlbnwwfHx8fHw%3D', 24 | 'https://images.unsplash.com/photo-1700413473936-81b281f88715?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDgxfEpwZzZLaWRsLUhrfHxlbnwwfHx8fHw%3D', 25 | 'https://images.unsplash.com/photo-1624981015247-697f0b9e24a2?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDU2fEpwZzZLaWRsLUhrfHxlbnwwfHx8fHw%3D', 26 | 'https://images.unsplash.com/photo-1551085036-92c80da2bf4a?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDI0fEpwZzZLaWRsLUhrfHxlbnwwfHx8fHw%3D', 27 | 'https://images.unsplash.com/photo-1534757889788-2aea3517f2ef?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDV8SnBnNktpZGwtSGt8fGVufDB8fHx8fA%3D%3D', 28 | 'https://images.unsplash.com/photo-1547471080-19acba333038?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDR8SnBnNktpZGwtSGt8fGVufDB8fHx8fA%3D%3D', 29 | 'https://images.unsplash.com/photo-1702877511807-2cb45e74e0fe?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDYxfHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D', 30 | 'https://images.unsplash.com/photo-1702287055981-24272805c309?w=500&auto=format&fit=crop&q=60&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHx0b3BpYy1mZWVkfDkzfHhIeFlUTUhMZ09jfHxlbnwwfHx8fHw%3D', 31 | ]; 32 | 33 | type ImageCellProps = { 34 | uri: string; 35 | i: number; 36 | }; 37 | 38 | const ImageCell = ({ uri, i }: ImageCellProps) => { 39 | const { animationProgress } = useLightBox(); 40 | 41 | const animatedImageStyle = useAnimatedStyle(() => { 42 | return { 43 | borderRadius: interpolate(animationProgress.value, [0, 1], [12, 0]), 44 | }; 45 | }); 46 | 47 | return ( 48 | 54 | 64 | 65 | ); 66 | }; 67 | 68 | export default function App() { 69 | return ( 70 | 71 | 72 | 73 | 74 | {AZUKI_IMG_LIST.map((uri, i) => ( 75 | 76 | ))} 77 | 78 | 79 | 80 | 81 | ); 82 | } 83 | 84 | const styles = StyleSheet.create({ 85 | container: { 86 | flexDirection: 'row', 87 | flexWrap: 'wrap', 88 | }, 89 | 90 | view: { 91 | flex: 1, 92 | }, 93 | 94 | imageStyle: { 95 | borderRadius: 12, 96 | overflow: 'hidden', 97 | }, 98 | }); 99 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": {}, 3 | "extends": "../tsconfig.json" 4 | } 5 | -------------------------------------------------------------------------------- /example/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const createExpoWebpackConfigAsync = require('@expo/webpack-config'); 3 | const { resolver } = require('./metro.config'); 4 | 5 | const root = path.resolve(__dirname, '..'); 6 | const node_modules = path.join(__dirname, 'node_modules'); 7 | 8 | module.exports = async function (env, argv) { 9 | const config = await createExpoWebpackConfigAsync(env, argv); 10 | 11 | config.module.rules.push({ 12 | test: /\.(js|jsx|ts|tsx)$/, 13 | include: path.resolve(root, 'src'), 14 | use: 'babel-loader', 15 | }); 16 | 17 | // We need to make sure that only one version is loaded for peerDependencies 18 | // So we alias them to the versions in example's node_modules 19 | Object.assign(config.resolve.alias, { 20 | ...resolver.extraNodeModules, 21 | 'react-native-web': path.join(node_modules, 'react-native-web'), 22 | }); 23 | 24 | return config; 25 | }; 26 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@alantoa/lightbox", 3 | "version": "0.3.0", 4 | "description": "@alantoa/lightbox", 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 | "alantoa-lightbox.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 | "pods": "cd example && pod-install --quiet", 32 | "bootstrap": "yarn example && yarn && yarn pods" 33 | }, 34 | "keywords": [ 35 | "react-native", 36 | "ios", 37 | "android" 38 | ], 39 | "repository": "https://github.com/alantoa/react-native-lightbox", 40 | "author": "alantoa (https://github.com/alantoa)", 41 | "license": "MIT", 42 | "bugs": { 43 | "url": "https://github.com/alantoa/react-native-lightbox/issues" 44 | }, 45 | "homepage": "https://github.com/alantoa/react-native-lightbox#readme", 46 | "publishConfig": { 47 | "registry": "https://registry.npmjs.org/" 48 | }, 49 | "devDependencies": { 50 | "@commitlint/config-conventional": "^11.0.0", 51 | "@react-native-community/eslint-config": "^2.0.0", 52 | "@release-it/conventional-changelog": "^2.0.0", 53 | "@types/jest": "^26.0.0", 54 | "@types/react": "~17.0.21", 55 | "@types/react-native": "0.62.13", 56 | "commitlint": "^11.0.0", 57 | "eslint": "^7.2.0", 58 | "eslint-config-prettier": "^7.0.0", 59 | "eslint-plugin-prettier": "^3.1.3", 60 | "husky": "^6.0.0", 61 | "jest": "^26.0.1", 62 | "pod-install": "^0.1.0", 63 | "prettier": "^2.0.5", 64 | "react": "^17.0.2", 65 | "react-native": "0.64.1", 66 | "react-native-builder-bob": "^0.18.0", 67 | "react-native-gesture-handler": "~2.2.0", 68 | "react-native-reanimated": "~2.8.0", 69 | "release-it": "^14.2.2", 70 | "typescript": "^4.1.3" 71 | }, 72 | "peerDependencies": { 73 | "react": "*", 74 | "react-native": "*", 75 | "react-native-gesture-handler": ">=2.0.0", 76 | "react-native-reanimated": ">=2.0.0" 77 | }, 78 | "jest": { 79 | "preset": "react-native", 80 | "modulePathIgnorePatterns": [ 81 | "/example/node_modules", 82 | "/lib/" 83 | ] 84 | }, 85 | "commitlint": { 86 | "extends": [ 87 | "@commitlint/config-conventional" 88 | ] 89 | }, 90 | "release-it": { 91 | "git": { 92 | "commitMessage": "chore: release ${version}", 93 | "tagName": "v${version}" 94 | }, 95 | "npm": { 96 | "publish": true 97 | }, 98 | "github": { 99 | "release": true 100 | }, 101 | "plugins": { 102 | "@release-it/conventional-changelog": { 103 | "preset": "angular" 104 | } 105 | } 106 | }, 107 | "eslintConfig": { 108 | "root": true, 109 | "extends": [ 110 | "@react-native-community", 111 | "prettier" 112 | ], 113 | "rules": { 114 | "prettier/prettier": [ 115 | "error", 116 | { 117 | "quoteProps": "consistent", 118 | "singleQuote": true, 119 | "tabWidth": 2, 120 | "trailingComma": "es5", 121 | "useTabs": false 122 | } 123 | ] 124 | } 125 | }, 126 | "eslintIgnore": [ 127 | "node_modules/", 128 | "lib/" 129 | ], 130 | "prettier": { 131 | "quoteProps": "consistent", 132 | "singleQuote": true, 133 | "tabWidth": 2, 134 | "trailingComma": "es5", 135 | "useTabs": false 136 | }, 137 | "react-native-builder-bob": { 138 | "source": "src", 139 | "output": "lib", 140 | "targets": [ 141 | "commonjs", 142 | "module", 143 | [ 144 | "typescript", 145 | { 146 | "project": "tsconfig.build.json" 147 | } 148 | ] 149 | ] 150 | }, 151 | "resolutions": { 152 | "@types/react": "~17.0.21" 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /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/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | it.todo('write a test'); 2 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | export * from './light-box'; 2 | export * from './provider'; 3 | export * from './light-box-modal'; 4 | -------------------------------------------------------------------------------- /src/light-box-modal.tsx: -------------------------------------------------------------------------------- 1 | import React, { useCallback, useEffect } from 'react'; 2 | import { BackHandler, StyleSheet, useWindowDimensions } from 'react-native'; 3 | import { Gesture, GestureDetector } from 'react-native-gesture-handler'; 4 | import Animated, { 5 | Easing, 6 | Extrapolate, 7 | interpolate, 8 | runOnJS, 9 | useAnimatedStyle, 10 | useSharedValue, 11 | withTiming, 12 | cancelAnimation, 13 | } from 'react-native-reanimated'; 14 | import type { TargetImageInfo } from './light-box'; 15 | import { useLightBox, type AnimationParams } from './provider'; 16 | import { withRubberBandClamp, useVector } from './utils'; 17 | 18 | export type ActiveImageType = AnimationParams & { 19 | layout: TargetImageInfo; 20 | imageElement: JSX.Element; 21 | }; 22 | type LightImageModalProps = { 23 | activeImage: ActiveImageType; 24 | onClose: () => void; 25 | }; 26 | const timingConfig = { 27 | duration: 240, 28 | easing: Easing.bezier(0.33, 0.01, 0, 1), 29 | }; 30 | const maxScale = 6; 31 | export const LightImageModal = ({ 32 | activeImage, 33 | onClose, 34 | }: LightImageModalProps) => { 35 | const { layout, position, imageElement, onLongPress, tapToClose, onTap } = 36 | activeImage; 37 | const { x, y, width, height, imageOpacity } = position; 38 | const { width: targetWidth, height: dimensionHeight } = useWindowDimensions(); 39 | const CENTER = { 40 | x: targetWidth / 2, 41 | y: dimensionHeight / 2, 42 | }; 43 | const scaleFactor = layout.width / targetWidth; 44 | 45 | const targetHeight = layout.height / scaleFactor; 46 | 47 | // const headerHeight = useHeaderHeight(); 48 | const headerHeight = 0; 49 | 50 | const { animationProgress } = useLightBox(); 51 | 52 | const backdropOpacity = useSharedValue(0); 53 | 54 | const offset = useVector(0, 0); 55 | 56 | const scale = useSharedValue(1); 57 | 58 | const translation = useVector(0, 0); 59 | 60 | const origin = useVector(0, 0); 61 | 62 | const adjustedFocal = useVector(0, 0); 63 | 64 | // const originalLayout = useVector(width, 0); 65 | // const layout = useVector(width, 0); 66 | 67 | const targetX = useSharedValue(0); 68 | const targetY = useSharedValue( 69 | (dimensionHeight - targetHeight) / 2 - headerHeight 70 | ); 71 | 72 | const panGesture = Gesture.Pan() 73 | .maxPointers(1) 74 | .minPointers(1) 75 | .minDistance(10) 76 | 77 | .onBegin(() => { 78 | const newWidth = scale.value * layout.width; 79 | const newHeight = scale.value * layout.height; 80 | if ( 81 | offset.x.value < (newWidth - layout.width) / 2 - translation.x.value && 82 | offset.x.value > -(newWidth - layout.width) / 2 - translation.x.value 83 | ) { 84 | cancelAnimation(offset.x); 85 | } 86 | 87 | if ( 88 | offset.y.value < 89 | (newHeight - layout.height) / 2 - translation.y.value && 90 | offset.y.value > -(newHeight - layout.height) / 2 - translation.y.value 91 | ) { 92 | cancelAnimation(offset.y); 93 | } 94 | }) 95 | .onUpdate(({ translationX, translationY }) => { 96 | translation.x.value = translationX; 97 | translation.y.value = translationY; 98 | 99 | scale.value = interpolate( 100 | translation.y.value, 101 | [-200, 0, 200], 102 | [0.65, 1, 0.65], 103 | Extrapolate.CLAMP 104 | ); 105 | 106 | backdropOpacity.value = interpolate( 107 | translation.y.value, 108 | [-100, 0, 100], 109 | [0.2, 1, 0.2], 110 | Extrapolate.CLAMP 111 | ); 112 | }) 113 | .onEnd(() => { 114 | if (Math.abs(translation.y.value) > 40) { 115 | targetX.value = translation.x.value - targetX.value * -1; 116 | targetY.value = translation.y.value - targetY.value * -1; 117 | translation.x.value = 0; 118 | translation.y.value = 0; 119 | animationProgress.value = withTiming(0, timingConfig, () => { 120 | imageOpacity.value = withTiming( 121 | 1, 122 | { 123 | duration: 16, 124 | }, 125 | () => { 126 | runOnJS(onClose)(); 127 | } 128 | ); 129 | }); 130 | backdropOpacity.value = withTiming(0, timingConfig); 131 | } else { 132 | backdropOpacity.value = withTiming(1, timingConfig); 133 | translation.x.value = withTiming(0, timingConfig); 134 | translation.y.value = withTiming(0, timingConfig); 135 | } 136 | scale.value = withTiming(1, timingConfig); 137 | }); 138 | 139 | const imageStyles = useAnimatedStyle(() => { 140 | const interpolateProgress = (range: [number, number]) => 141 | interpolate(animationProgress.value, [0, 1], range, Extrapolate.CLAMP); 142 | 143 | return { 144 | width: interpolateProgress([width.value, targetWidth]), 145 | height: interpolateProgress([height.value, targetHeight]), 146 | transform: [ 147 | { 148 | scale: scale.value, 149 | }, 150 | { 151 | translateX: 152 | offset.x.value + 153 | translation.x.value + 154 | interpolateProgress([x.value, targetX.value]), 155 | }, 156 | { 157 | translateY: 158 | offset.y.value + 159 | translation.y.value + 160 | interpolateProgress([y.value, targetY.value]), 161 | }, 162 | ], 163 | }; 164 | }); 165 | 166 | const backdropStyles = useAnimatedStyle(() => { 167 | return { 168 | opacity: backdropOpacity.value, 169 | }; 170 | }); 171 | const closeModal = useCallback(() => { 172 | 'worklet'; 173 | animationProgress.value = withTiming(0, timingConfig, () => { 174 | imageOpacity.value = withTiming( 175 | 1, 176 | { 177 | duration: 16, 178 | }, 179 | () => { 180 | runOnJS(onClose)(); 181 | } 182 | ); 183 | }); 184 | backdropOpacity.value = withTiming(0, timingConfig); 185 | // eslint-disable-next-line react-hooks/exhaustive-deps 186 | }, []); 187 | useEffect(() => { 188 | requestAnimationFrame(() => { 189 | imageOpacity.value = 0; 190 | }); 191 | animationProgress.value = withTiming(1, timingConfig); 192 | backdropOpacity.value = withTiming(1, timingConfig); 193 | const backhanderListener = BackHandler.addEventListener( 194 | 'hardwareBackPress', 195 | () => { 196 | closeModal(); 197 | return true; 198 | } 199 | ); 200 | return () => { 201 | backhanderListener.remove(); 202 | }; 203 | // eslint-disable-next-line react-hooks/exhaustive-deps 204 | }, []); 205 | const setAdjustedFocal = ({ 206 | focalX, 207 | focalY, 208 | }: Record<'focalX' | 'focalY', number>) => { 209 | 'worklet'; 210 | 211 | adjustedFocal.x.value = focalX - (CENTER.x + offset.x.value); 212 | adjustedFocal.y.value = focalY - (CENTER.y + offset.y.value); 213 | }; 214 | const longPressGesture = Gesture.LongPress() 215 | .enabled(!!onLongPress) 216 | .maxDistance(10) 217 | .onStart(() => { 218 | 'worklet'; 219 | if (onLongPress) { 220 | runOnJS(onLongPress)(); 221 | } 222 | }); 223 | const scaleOffset = useSharedValue(1); 224 | const resetValues = (animated = true) => { 225 | 'worklet'; 226 | 227 | scale.value = animated ? withTiming(1) : 1; 228 | offset.x.value = animated ? withTiming(0) : 0; 229 | offset.y.value = animated ? withTiming(0) : 0; 230 | translation.x.value = animated ? withTiming(0) : 0; 231 | translation.y.value = animated ? withTiming(0) : 0; 232 | }; 233 | const onStart = () => { 234 | 'worklet'; 235 | 236 | offset.x.value = offset.x.value + translation.x.value; 237 | offset.y.value = offset.y.value + translation.y.value; 238 | 239 | translation.x.value = 0; 240 | translation.y.value = 0; 241 | }; 242 | const pinchGesture = Gesture.Pinch() 243 | .onStart(({ focalX, focalY }) => { 244 | 'worklet'; 245 | onStart(); 246 | scaleOffset.value = scale.value; 247 | setAdjustedFocal({ focalX, focalY }); 248 | origin.x.value = adjustedFocal.x.value; 249 | origin.y.value = adjustedFocal.y.value; 250 | }) 251 | .onUpdate(({ scale: s, focalX, focalY, numberOfPointers }) => { 252 | 'worklet'; 253 | if (numberOfPointers !== 2) return; 254 | const nextScale = withRubberBandClamp( 255 | s * scaleOffset.value, 256 | 0.55, 257 | maxScale, 258 | [1, maxScale] 259 | ); 260 | 261 | scale.value = nextScale; 262 | 263 | setAdjustedFocal({ focalX, focalY }); 264 | 265 | translation.x.value = 266 | adjustedFocal.x.value + 267 | ((-1 * nextScale) / scaleOffset.value) * origin.x.value; 268 | translation.y.value = 269 | adjustedFocal.y.value + 270 | ((-1 * nextScale) / scaleOffset.value) * origin.y.value; 271 | }) 272 | .onEnd(() => { 273 | 'worklet'; 274 | if (scale.value < 1) { 275 | resetValues(); 276 | } else { 277 | const sc = Math.min(scale.value, maxScale); 278 | 279 | const newWidth = sc * layout.width; 280 | const newHeight = sc * layout.height; 281 | 282 | const nextTransX = 283 | scale.value > maxScale 284 | ? adjustedFocal.x.value + 285 | ((-1 * maxScale) / scaleOffset.value) * origin.x.value 286 | : translation.x.value; 287 | 288 | const nextTransY = 289 | scale.value > maxScale 290 | ? adjustedFocal.y.value + 291 | ((-1 * maxScale) / scaleOffset.value) * origin.y.value 292 | : translation.y.value; 293 | 294 | const diffX = 295 | nextTransX + offset.x.value - (newWidth - layout.width) / 2; 296 | if (scale.value > maxScale) { 297 | scale.value = withTiming(maxScale); 298 | } 299 | 300 | if (newWidth <= layout.width) { 301 | translation.x.value = withTiming(0); 302 | } else { 303 | let moved; 304 | if (diffX > 0) { 305 | translation.x.value = withTiming(nextTransX - diffX); 306 | moved = true; 307 | } 308 | 309 | if (newWidth + diffX < layout.width) { 310 | translation.x.value = withTiming( 311 | nextTransX + layout.width - (newWidth + diffX) 312 | ); 313 | moved = true; 314 | } 315 | if (!moved) { 316 | translation.x.value = withTiming(nextTransX); 317 | } 318 | } 319 | 320 | const diffY = 321 | nextTransY + offset.y.value - (newHeight - height.value) / 2; 322 | 323 | if (newHeight <= height.value) { 324 | translation.y.value = withTiming(-offset.y.value); 325 | } else { 326 | let moved; 327 | if (diffY > 0) { 328 | translation.y.value = withTiming(nextTransY - diffY); 329 | moved = true; 330 | } 331 | 332 | if (newHeight + diffY < height.value) { 333 | translation.y.value = withTiming( 334 | nextTransY + height.value - (newHeight + diffY) 335 | ); 336 | moved = true; 337 | } 338 | if (!moved) { 339 | translation.y.value = withTiming(nextTransY); 340 | } 341 | } 342 | } 343 | }); 344 | // Todo: add double tab 345 | const doubleTapGesture = Gesture.Tap().numberOfTaps(2).enabled(false); 346 | const tapGesture = Gesture.Tap() 347 | .enabled(tapToClose || !!onTap) 348 | .numberOfTaps(1) 349 | .maxDistance(10) 350 | .onEnd(() => { 351 | if (tapToClose) { 352 | closeModal(); 353 | } 354 | if (onTap) { 355 | runOnJS(onTap)(); 356 | } 357 | }); 358 | return ( 359 | 360 | 361 | 370 | 371 | 372 | {imageElement} 373 | 374 | 375 | 376 | 377 | ); 378 | }; 379 | const styles = StyleSheet.create({ 380 | backdrop: { 381 | ...StyleSheet.absoluteFillObject, 382 | backgroundColor: 'black', 383 | }, 384 | full: { 385 | flex: 1, 386 | }, 387 | }); 388 | -------------------------------------------------------------------------------- /src/light-box.tsx: -------------------------------------------------------------------------------- 1 | import React, { useState } from 'react'; 2 | import { Dimensions, StyleProp, ViewStyle } from 'react-native'; 3 | import { Gesture, GestureDetector } from 'react-native-gesture-handler'; 4 | import Animated, { 5 | measure, 6 | runOnJS, 7 | useAnimatedRef, 8 | useAnimatedStyle, 9 | useSharedValue, 10 | } from 'react-native-reanimated'; 11 | import { AnimationParams, useLightBox } from './provider'; 12 | 13 | export type ImageBoundingClientRect = { 14 | x: Animated.SharedValue; 15 | y: Animated.SharedValue; 16 | width: Animated.SharedValue; 17 | height: Animated.SharedValue; 18 | imageOpacity: Animated.SharedValue; 19 | }; 20 | export type TargetImageInfo = { 21 | width: number; 22 | height: number; 23 | }; 24 | export type LightBoxProps = { 25 | width: number; 26 | height: number; 27 | containerStyle?: StyleProp; 28 | imgLayout?: TargetImageInfo; 29 | alt?: string; 30 | children: JSX.Element; 31 | onLongPress?: () => void; 32 | tapToClose?: boolean; 33 | onTap?: () => void; 34 | /** 35 | * This value must be set when you use the Native Header. 36 | * e.g. 37 | * import { useHeaderHeight } from "@react-navigation/elements"; 38 | * const headerHeight = useHeaderHeight(); 39 | */ 40 | nativeHeaderHeight?: number; 41 | }; 42 | 43 | export const LightBox: React.FC = ({ 44 | width: imgWidth, 45 | height: imgHeight, 46 | containerStyle, 47 | imgLayout, 48 | children, 49 | onLongPress, 50 | tapToClose = true, 51 | onTap, 52 | nativeHeaderHeight = 0, 53 | }) => { 54 | // Todo: add lightboxImage component. 55 | const [targetLayout] = useState(null); 56 | 57 | const animatedRef = useAnimatedRef(); 58 | const opacity = useSharedValue(1); 59 | const lightBox = useLightBox(); 60 | 61 | const styles = useAnimatedStyle(() => { 62 | return { 63 | width: imgWidth, 64 | height: imgHeight, 65 | opacity: opacity.value, 66 | }; 67 | }); 68 | const width = useSharedValue(0); 69 | const height = useSharedValue(0); 70 | const x = useSharedValue(0); 71 | const y = useSharedValue(0); 72 | 73 | const handlePress = () => { 74 | if (!targetLayout && !imgLayout) return; 75 | const position = { imageOpacity: opacity, width, height, x, y }; 76 | 77 | lightBox?.show({ 78 | position, 79 | layout: targetLayout ?? 80 | imgLayout ?? { 81 | width: Dimensions.get('window').width, 82 | height: Dimensions.get('window').width, 83 | }, 84 | imageElement: children, 85 | tapToClose, 86 | onTap, 87 | }); 88 | }; 89 | 90 | const tapGesture = Gesture.Tap().onEnd((_, success) => { 91 | if (!success) return; 92 | const measurements = measure(animatedRef); 93 | width.value = measurements.width; 94 | height.value = measurements.height; 95 | x.value = measurements.pageX; 96 | y.value = measurements.pageY - nativeHeaderHeight; 97 | runOnJS(handlePress)(); 98 | }); 99 | const longPressGesture = Gesture.LongPress() 100 | .enabled(!!onLongPress) 101 | .maxDistance(10) 102 | .onStart(() => { 103 | 'worklet'; 104 | if (onLongPress) { 105 | runOnJS(onLongPress)(); 106 | } 107 | }); 108 | 109 | return ( 110 | 111 | 112 | 113 | {children} 114 | 115 | 116 | 117 | ); 118 | }; 119 | -------------------------------------------------------------------------------- /src/provider.tsx: -------------------------------------------------------------------------------- 1 | import React, { createContext, useContext, useMemo, useState } from 'react'; 2 | import type { ImageStyle } from 'react-native'; 3 | import type { 4 | ImageBoundingClientRect, 5 | LightBoxProps, 6 | TargetImageInfo, 7 | } from './light-box'; 8 | import { ActiveImageType, LightImageModal } from './light-box-modal'; 9 | import { useSharedValue, type SharedValue } from 'react-native-reanimated'; 10 | 11 | export type AnimationParams = Pick< 12 | LightBoxProps, 13 | 'onTap' | 'tapToClose' | 'onLongPress' | 'nativeHeaderHeight' 14 | > & { 15 | layout: TargetImageInfo; 16 | position: ImageBoundingClientRect; 17 | style?: ImageStyle; 18 | imageElement: JSX.Element; 19 | }; 20 | 21 | type LightBoxContextType = { 22 | show: (params: AnimationParams) => void; 23 | animationProgress: SharedValue; 24 | }; 25 | 26 | export const LightBoxContext = createContext( 27 | undefined 28 | ); 29 | 30 | const LightBoxProvider: React.FC<{ 31 | children: JSX.Element | JSX.Element[]; 32 | }> = ({ children }) => { 33 | const animationProgress = useSharedValue(0); 34 | 35 | const [activeImage, setActiveImage] = useState(null); 36 | const value = useMemo( 37 | () => ({ 38 | animationProgress, 39 | show: ({ layout, position, imageElement, ...rest }: AnimationParams) => { 40 | setActiveImage({ 41 | layout, 42 | imageElement, 43 | position, 44 | ...rest, 45 | }); 46 | }, 47 | }), 48 | // eslint-disable-next-line react-hooks/exhaustive-deps 49 | [] 50 | ); 51 | 52 | const onClose = () => { 53 | setActiveImage(null); 54 | }; 55 | return ( 56 | 57 | {children} 58 | {activeImage && ( 59 | 60 | )} 61 | 62 | ); 63 | }; 64 | 65 | const useLightBox = (): LightBoxContextType => { 66 | const lightBox = useContext(LightBoxContext); 67 | if (!lightBox) { 68 | throw new Error( 69 | 'LightBoxContext: `LightBoxContext` is undefined. Seems you forgot to wrap component within the CalendarProvider' 70 | ); 71 | } 72 | return lightBox; 73 | }; 74 | 75 | export { useLightBox, LightBoxProvider }; 76 | -------------------------------------------------------------------------------- /src/utils.tsx: -------------------------------------------------------------------------------- 1 | import type Animated from 'react-native-reanimated'; 2 | import { useSharedValue } from 'react-native-reanimated'; 3 | 4 | /** 5 | * @summary Clamps a node with a lower and upper bound. 6 | * @example 7 | clamp(-1, 0, 100); // 0 8 | clamp(1, 0, 100); // 1 9 | clamp(101, 0, 100); // 100 10 | * @worklet 11 | */ 12 | export const clamp = ( 13 | value: number, 14 | lowerBound: number, 15 | upperBound: number 16 | ) => { 17 | 'worklet'; 18 | return Math.min(Math.max(lowerBound, value), upperBound); 19 | }; 20 | 21 | export const rubberBandClamp = (x: number, coeff: number, dim: number) => { 22 | 'worklet'; 23 | 24 | return (1.0 - 1.0 / ((x * coeff) / dim + 1.0)) * dim; 25 | }; 26 | export const withRubberBandClamp = ( 27 | x: number, 28 | coeff: number, 29 | dim: number, 30 | limits: [number, number] 31 | ) => { 32 | 'worklet'; 33 | let clampedX = clamp(x, limits[0], limits[1]); 34 | let diff = Math.abs(x - clampedX); 35 | let sign = clampedX > x ? -1 : 1; 36 | 37 | return clampedX + sign * rubberBandClamp(diff, coeff, dim); 38 | }; 39 | 40 | /** 41 | * @summary Type representing a vector 42 | * @example 43 | export interface Vector { 44 | x: T; 45 | y: T; 46 | } 47 | */ 48 | export interface Vector { 49 | x: T; 50 | y: T; 51 | } 52 | /** 53 | * @summary Returns a vector of shared values 54 | */ 55 | export const useVector = ( 56 | x1 = 0, 57 | y1?: number 58 | ): Vector> => { 59 | const x = useSharedValue(x1); 60 | const y = useSharedValue(y1 ?? x1); 61 | return { x, y }; 62 | }; 63 | -------------------------------------------------------------------------------- /tea.yaml: -------------------------------------------------------------------------------- 1 | # https://tea.xyz/what-is-this-file 2 | --- 3 | version: 1.0.0 4 | codeOwners: 5 | - '0x5a0f867C828d89036878185710c37e9105548821' 6 | quorum: 1 7 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "extends": "./tsconfig", 4 | "exclude": ["example"] 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "paths": { 5 | "@alantoa/lightbox": ["./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 | "noUnusedLocals": true, 21 | "noUnusedParameters": true, 22 | "resolveJsonModule": true, 23 | "skipLibCheck": true, 24 | "strict": true, 25 | "target": "esnext" 26 | } 27 | } 28 | --------------------------------------------------------------------------------