├── .circleci └── config.yml ├── .editorconfig ├── .gitattributes ├── .gitignore ├── .yarnrc ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── babel.config.js ├── example ├── app.json ├── babel.config.js ├── index.js ├── metro.config.js ├── package.json ├── src │ ├── App.js │ └── App.tsx ├── tsconfig.json ├── webpack.config.js └── yarn.lock ├── package.json ├── scripts └── bootstrap.js ├── src ├── __tests__ │ ├── index.test.js │ └── index.test.tsx ├── index.js └── 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: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 | .idea 35 | .gradle 36 | local.properties 37 | android.iml 38 | 39 | # Cocoapods 40 | # 41 | example/ios/Pods 42 | 43 | # node.js 44 | # 45 | node_modules/ 46 | npm-debug.log 47 | yarn-debug.log 48 | yarn-error.log 49 | 50 | # BUCK 51 | buck-out/ 52 | \.buckd/ 53 | android/app/libs 54 | android/keystores/debug.keystore 55 | 56 | # Expo 57 | .expo/* 58 | 59 | # generated by bob 60 | lib/ 61 | -------------------------------------------------------------------------------- /.yarnrc: -------------------------------------------------------------------------------- 1 | # Override Yarn command so we can automatically setup the repo on running `yarn` 2 | 3 | yarn-path "scripts/bootstrap.js" 4 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We want this community to be friendly and respectful to each other. Please follow it in all your interactions with the project. 4 | 5 | ## Development workflow 6 | 7 | To get started with the project, run `yarn` in the root directory to install the required dependencies for each package: 8 | 9 | ```sh 10 | yarn 11 | ``` 12 | 13 | While developing, you can run the [example app](/example/) to test your changes. 14 | 15 | To start the packager: 16 | 17 | ```sh 18 | yarn example start 19 | ``` 20 | 21 | To run the example app on Android: 22 | 23 | ```sh 24 | yarn example android 25 | ``` 26 | 27 | To run the example app on iOS: 28 | 29 | ```sh 30 | yarn example ios 31 | ``` 32 | 33 | Make sure your code passes TypeScript and ESLint. Run the following to verify: 34 | 35 | ```sh 36 | yarn typescript 37 | yarn lint 38 | ``` 39 | 40 | To fix formatting errors, run the following: 41 | 42 | ```sh 43 | yarn lint --fix 44 | ``` 45 | 46 | Remember to add tests for your change if possible. Run the unit tests by: 47 | 48 | ```sh 49 | yarn test 50 | ``` 51 | 52 | To edit the Objective-C files, open `example/ios/AnchorExample.xcworkspace` in XCode and find the source files at `Pods > Development Pods > @nandorojo/anchor`. 53 | 54 | To edit the Kotlin files, open `example/android` in Android studio and find the source files at `nandorojoanchor` under `Android`. 55 | 56 | ### Commit message convention 57 | 58 | We follow the [conventional commits specification](https://www.conventionalcommits.org/en) for our commit messages: 59 | 60 | - `fix`: bug fixes, e.g. fix crash due to deprecated method. 61 | - `feat`: new features, e.g. add new method to the module. 62 | - `refactor`: code refactor, e.g. migrate from class components to hooks. 63 | - `docs`: changes into documentation, e.g. add usage example for the module.. 64 | - `test`: adding or updating tests, e.g. add integration tests using detox. 65 | - `chore`: tooling changes, e.g. change CI config. 66 | 67 | Our pre-commit hooks verify that your commit message matches this format when committing. 68 | 69 | ### Linting and tests 70 | 71 | [ESLint](https://eslint.org/), [Prettier](https://prettier.io/), [TypeScript](https://www.typescriptlang.org/) 72 | 73 | We use [TypeScript](https://www.typescriptlang.org/) for type checking, [ESLint](https://eslint.org/) with [Prettier](https://prettier.io/) for linting and formatting the code, and [Jest](https://jestjs.io/) for testing. 74 | 75 | Our pre-commit hooks verify that the linter and tests pass when committing. 76 | 77 | ### Scripts 78 | 79 | The `package.json` file contains various scripts for common tasks: 80 | 81 | - `yarn bootstrap`: setup project by installing all dependencies and pods. 82 | - `yarn typescript`: type-check files with TypeScript. 83 | - `yarn lint`: lint files with ESLint. 84 | - `yarn test`: run unit tests with Jest. 85 | - `yarn example start`: start the Metro server for the example app. 86 | - `yarn example android`: run the example app on Android. 87 | - `yarn example ios`: run the example app on iOS. 88 | 89 | ### Sending a pull request 90 | 91 | > **Working on your first pull request?** You can learn how from this _free_ series: [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). 92 | 93 | When you're sending a pull request: 94 | 95 | - Prefer small pull requests focused on one change. 96 | - Verify that linters and tests are passing. 97 | - Review the documentation to make sure it looks good. 98 | - Follow the pull request template when opening a pull request. 99 | - For pull requests that change the API or implementation, discuss with maintainers first by opening an issue. 100 | 101 | ## Code of Conduct 102 | 103 | ### Our Pledge 104 | 105 | We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. 106 | 107 | We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. 108 | 109 | ### Our Standards 110 | 111 | Examples of behavior that contributes to a positive environment for our community include: 112 | 113 | - Demonstrating empathy and kindness toward other people 114 | - Being respectful of differing opinions, viewpoints, and experiences 115 | - Giving and gracefully accepting constructive feedback 116 | - Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience 117 | - Focusing on what is best not just for us as individuals, but for the overall community 118 | 119 | Examples of unacceptable behavior include: 120 | 121 | - The use of sexualized language or imagery, and sexual attention or 122 | advances of any kind 123 | - Trolling, insulting or derogatory comments, and personal or political attacks 124 | - Public or private harassment 125 | - Publishing others' private information, such as a physical or email 126 | address, without their explicit permission 127 | - Other conduct which could reasonably be considered inappropriate in a 128 | professional setting 129 | 130 | ### Enforcement Responsibilities 131 | 132 | Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. 133 | 134 | Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. 135 | 136 | ### Scope 137 | 138 | This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. 139 | 140 | ### Enforcement 141 | 142 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at [INSERT CONTACT METHOD]. All complaints will be reviewed and investigated promptly and fairly. 143 | 144 | All community leaders are obligated to respect the privacy and security of the reporter of any incident. 145 | 146 | ### Enforcement Guidelines 147 | 148 | Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: 149 | 150 | #### 1. Correction 151 | 152 | **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. 153 | 154 | **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. 155 | 156 | #### 2. Warning 157 | 158 | **Community Impact**: A violation through a single incident or series of actions. 159 | 160 | **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. 161 | 162 | #### 3. Temporary Ban 163 | 164 | **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. 165 | 166 | **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. 167 | 168 | #### 4. Permanent Ban 169 | 170 | **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. 171 | 172 | **Consequence**: A permanent ban from any sort of public interaction within the community. 173 | 174 | ### Attribution 175 | 176 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, 177 | available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. 178 | 179 | Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity). 180 | 181 | [homepage]: https://www.contributor-covenant.org 182 | 183 | For answers to common questions about this code of conduct, see the FAQ at 184 | https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations. 185 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Fernando Rojo 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 | # React Native Anchor 🦅 2 | 3 | Anchor links and scroll-to utilities for React Native (+ Web). It has zero dependencies. 4 | 5 | ## Installation 6 | 7 | ```sh 8 | yarn add @nandorojo/anchor 9 | ``` 10 | 11 | If you're using react-native-web, you'll need at least version 0.15.3. 12 | 13 | This works great to scroll to errors in Formik forms. See the [`ScrollToField` component](#formik-error-usage). 14 | 15 | ## Usage 16 | 17 | This is the simplest usage: 18 | 19 | ```jsx 20 | import React from 'react' 21 | import { ScrollTo, Target, ScrollView } from '@nandorojo/anchor' 22 | import { View, Text } from 'react-native' 23 | 24 | export default function App() { 25 | return ( 26 | 27 | 28 | 29 | Scroll to bottom content 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | ) 38 | } 39 | ``` 40 | 41 | - [Expo Snack example](https://snack.expo.io/@nandorojo/anxious-chip) (iOS and Android only, since Expo Snack uses an outdated react-native-web version) 42 | - [CodeSandbox example](https://codesandbox.io/s/empty-sky-8nhnb?file=/src/App.js) (web) 43 | 44 | The library exports a `ScrollView` and `FlatList` component you can use as drop-in replacements for the react-native ones. 45 | 46 | Note that the scroll to will only work if you use this library's scrollable components, or if you use a custom scrollable with the `AnchorProvider`, as shown in the example below. 47 | 48 | ### Use custom scrollables 49 | 50 | If you want to use your own scrollable, that's fine. You'll just have to do 2 things: 51 | 52 | 1. Wrap them with the `AnchorProvider` 53 | 2. Register the scrollable with `useRegisterScroller` 54 | 55 | That's all the exported `ScrollView` does for you. 56 | 57 | ```tsx 58 | import { AnchorProvider, useRegisterScrollable } from '@nandorojo/anchor' 59 | import { ScrollView } from 'react-native' 60 | 61 | export default function Provider() { 62 | return ( 63 | 64 | 65 | 66 | ) 67 | } 68 | 69 | // make sure this is the child of AnchorProvider 70 | function MyComponent() { 71 | const { register } = useRegisterScroller() 72 | 73 | return ( 74 | 75 | 76 | 77 | ) 78 | } 79 | ``` 80 | 81 | If you need `horizontal` scrolling, make sure you pass the `horizontal` prop to both the `AnchorProvider`, and the `ScrollView`. 82 | 83 | ```tsx 84 | import { AnchorProvider, useRegisterScrollable } from '@nandorojo/anchor' 85 | import { ScrollView } from 'react-native' 86 | 87 | export default function Provider() { 88 | return ( 89 | 90 | 91 | 92 | ) 93 | } 94 | 95 | // make sure this is the child of AnchorProvider 96 | function MyComponent() { 97 | const { register } = useRegisterScroller() 98 | 99 | return ( 100 | 101 | 102 | 103 | ) 104 | } 105 | ``` 106 | 107 | ## Trigger a scroll-to event 108 | 109 | There are a few options for triggering a scroll-to event. The basic premise is the same as HTML anchor links. You need 1) a target to scroll to, and 2) something to trigger the scroll. 110 | 111 | The simplest way to make a target is to use the `Target` component. 112 | 113 | Each target needs a **unique** `name` prop. The name indicates where to scroll. 114 | 115 | ```jsx 116 | import { ScrollView, Target } from '@nandorojo/anchor' 117 | 118 | export default function App() { 119 | return ( 120 | 121 | 122 | 123 | 124 | 125 | ) 126 | } 127 | ``` 128 | 129 | Next, we need a way to scroll to that target. The easiest way is to use the `ScrollTo` component: 130 | 131 | ```jsx 132 | import { ScrollView, Target } from '@nandorojo/anchor' 133 | import { Text, View } from 'react-native' 134 | 135 | export default function App() { 136 | return ( 137 | 138 | 139 | Click me to scroll down 140 | 141 | 142 | 143 | 144 | 145 | 146 | ) 147 | } 148 | ``` 149 | 150 | ### Create a custom `scrollTo` component 151 | 152 | If you don't want to use the `ScrollTo` component, you can also rely on the `useScrollTo` with a custom pressable. 153 | 154 | ```jsx 155 | import { ScrollView, Target } from '@nandorojo/anchor' 156 | import { Text, View } from 'react-native' 157 | 158 | function CustomScrollTo() { 159 | const { scrollTo } = useScrollTo() 160 | 161 | const onPress = () => { 162 | scrollTo('scrollhere') // required: target name 163 | 164 | // you can also pass these optional parameters: 165 | scrollTo('scrollhere', { 166 | animated: true, // default true 167 | offset: -10 // offset to scroll to, default -10 pts 168 | }) 169 | } 170 | 171 | return Scroll down 172 | } 173 | 174 | export default function App() { 175 | return ( 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | ) 184 | } 185 | ``` 186 | 187 | ### `useRegisterTarget()` 188 | 189 | The basic usage for determing the target to scroll to is using the `Target` component. 190 | 191 | However, if you want to use a custom component as your target, you'll use the `useRegisterTarget` hook. 192 | 193 | ```jsx 194 | import { ScrollTo, useRegisterTarget, ScrollView } from '@nandorojo/anchor'; 195 | import { View } from 'react-native' 196 | 197 | function BottomContent() { 198 | const { register } = useRegisterTarget() 199 | 200 | const ref = register('bottom-content') // use a unique name here 201 | 202 | return 203 | } 204 | 205 | function App() { 206 | return ( 207 | 208 | Scroll to bottom content 209 | 210 | 211 | 212 | ); 213 | } 214 | ``` 215 | 216 | ## Web usage 217 | 218 | ### Smooth Scrolling 219 | 220 | This works with web (react-native-web 0.15.3 or higher). 221 | 222 | To support iOS browsers, you should polyfill the smooth scroll API. 223 | 224 | ```sh 225 | yarn add smoothscroll-polyfill 226 | ``` 227 | 228 | Then at the root of your app (`App.js`, or `pages/_app.js` for Next.js) call this: 229 | 230 | ```jsx 231 | import { Platform } from 'react-native' 232 | 233 | if (Platform.OS === 'web' && typeof window !== 'undefined') { 234 | require('smoothscroll-polyfill').polyfill() 235 | } 236 | ``` 237 | 238 | ### Patch 239 | 240 | `react-native-web`'s resolution for scroll position is currently wrong. 241 | 242 | Until this issue is closed (https://github.com/necolas/react-native-web/issues/2109), I'll be using this patch with `patch-package`: 243 | 244 |
245 | 246 | Click me to view patch 247 | 248 | 249 | ```diff 250 | diff --git a/node_modules/@nandorojo/anchor/lib/module/index.js b/node_modules/@nandorojo/anchor/lib/module/index.js 251 | index 6decdc0..d27b884 100644 252 | --- a/node_modules/@nandorojo/anchor/lib/module/index.js 253 | +++ b/node_modules/@nandorojo/anchor/lib/module/index.js 254 | @@ -1,7 +1,7 @@ 255 | function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } 256 | 257 | import * as React from 'react'; 258 | -import { View, ScrollView as NativeScrollView, FlatList as NativeFlatList, findNodeHandle, Pressable } from 'react-native'; 259 | +import { View, ScrollView as NativeScrollView, FlatList as NativeFlatList, findNodeHandle, Pressable, Platform } from 'react-native'; 260 | const { 261 | createContext, 262 | forwardRef, 263 | @@ -130,7 +130,10 @@ const useCreateAnchorsContext = ({ 264 | return new Promise(resolve => { 265 | var _targetRefs$current, _targetRefs$current2; 266 | 267 | - const node = scrollRef.current && findNodeHandle(scrollRef.current); 268 | + const node = Platform.select({ 269 | + default: scrollRef.current, 270 | + web: scrollRef.current && scrollRef.current.getInnerViewNode && scrollRef.current.getInnerViewNode() 271 | + }) 272 | 273 | if (!node) { 274 | return resolve({ 275 | diff --git a/node_modules/@nandorojo/anchor/src/index.js b/node_modules/@nandorojo/anchor/src/index.js 276 | index 7259856..80fc63c 100644 277 | --- a/node_modules/@nandorojo/anchor/src/index.js 278 | +++ b/node_modules/@nandorojo/anchor/src/index.js 279 | @@ -1,5 +1,5 @@ 280 | import * as React from 'react'; 281 | -import { View, ScrollView as NativeScrollView, FlatList as NativeFlatList, findNodeHandle, Pressable, } from 'react-native'; 282 | +import { View, ScrollView as NativeScrollView, FlatList as NativeFlatList, findNodeHandle, Pressable, Platform } from 'react-native'; 283 | const { createContext, forwardRef, useContext, useMemo, useRef, useImperativeHandle, } = React; 284 | // from react-merge-refs (avoid dependency) 285 | function mergeRefs(refs) { 286 | @@ -109,7 +109,11 @@ const useCreateAnchorsContext = ({ horizontal, }) => { 287 | horizontal, 288 | scrollTo: (name, { animated = true, offset = -10 } = {}) => { 289 | return new Promise((resolve) => { 290 | - const node = scrollRef.current && findNodeHandle(scrollRef.current); 291 | + const node = Platform.select({ 292 | + default: scrollRef.current, 293 | + web: scrollRef.current && scrollRef.current.getInnerViewRef() 294 | + }) 295 | + // const node = scrollRef.current && findNodeHandle(scrollRef.current); 296 | if (!node) { 297 | return resolve({ 298 | success: false, 299 | 300 | ``` 301 |
302 | 303 | ### Gotchas 304 | 305 | One thing to keep in mind: the parent view of a `ScrollView` on web **must** have a fixed height. Otherwise, the `ScrollView` will just use window scrolling. This is a common source of confusion on web, and it took me a while to learn. 306 | 307 | Typically, it's solved by doing this: 308 | 309 | ```jsx 310 | import { View, ScrollView } from 'react-native' 311 | 312 | export default function App() { 313 | return ( 314 | 315 | 316 | 317 | ) 318 | } 319 | ``` 320 | 321 | By wrapping `ScrollView` with a `flex: 1` View, we are confining its parent's size. If this doesn't solve it, try giving your parent `View` a fixed `height`: 322 | 323 | ```jsx 324 | import { View, ScrollView, Platform } from 'react-native' 325 | 326 | export default function App() { 327 | return ( 328 | 329 | 330 | 331 | ) 332 | } 333 | ``` 334 | 335 | ## Imports 336 | 337 | ```js 338 | import { 339 | AnchorProvider, 340 | ScrollView, 341 | FlatList, 342 | useRegisterTarget, 343 | useScrollTo, 344 | ScrollTo, 345 | Target, 346 | useRegisterScroller, 347 | useAnchors 348 | } from '@nandorojo/anchor' 349 | ``` 350 | 351 | ### `ScrollTo` 352 | 353 | ```jsx 354 | const Trigger = () => ( 355 | 362 | ) 363 | ``` 364 | 365 | #### Props 366 | 367 | - `target` **required** unique string indicating the `name` of the `Target` to scroll to 368 | - `options` optional dictionary 369 | - `animated = true` whether the scroll should animate or not 370 | - `offset = -10` a number in pixels to offset the scroll by. By default, it scrolls 10 pixels above the content. 371 | 372 | ### `Target` 373 | 374 | ```js 375 | const ContentToScrollTo = () => 376 | ``` 377 | 378 | #### Props 379 | 380 | - `name` required, unique string that identifies this View to scroll to 381 | - it only needs to be unique _within_ a given ScrollView. You can reuse names for different scrollables, but I'd avoid doing that. 382 | 383 | ### `useScrollTo` 384 | 385 | A react hook that returns a `scrollTo(name, options?)` function. This serves as an alternative to the [`ScrollTo`](#ScrollTo) component. 386 | 387 | The first argument is required. It's a string that corresponds to your target's unique `name` prop. 388 | 389 | The second argument is an optional `options` object, which is identical to the [`ScrollTo`](#ScrollTo) component's `options` prop. 390 | 391 | ```jsx 392 | import { ScrollView, Target } from '@nandorojo/anchor' 393 | import { Text, View } from 'react-native' 394 | 395 | function CustomScrollTo() { 396 | const { scrollTo } = useScrollTo() 397 | 398 | const onPress = () => { 399 | scrollTo('scrollhere') // required: target name 400 | 401 | // you can also pass these optional parameters: 402 | scrollTo('scrollhere', { 403 | animated: true, // default true 404 | offset: -10 // offset to scroll to, default -10 pts 405 | }) 406 | } 407 | 408 | return Scroll down 409 | } 410 | 411 | export default function App() { 412 | return ( 413 | 414 | 415 | 416 | 417 | 418 | 419 | 420 | ) 421 | } 422 | ``` 423 | 424 | ### `useRegisterScroller` 425 | 426 | A hook that returns a `register` function. This is an alternative option to using the `ScrollView` or `FlatList` components provided by this library. 427 | 428 | Note that, to use this, you must first wrap the scrollable with `AnchorProvider`. It's probably easier to just use the exported `ScrollView`, but it's your call. 429 | 430 | ```tsx 431 | import { AnchorProvider, useRegisterScrollable } from '@nandorojo/anchor' 432 | import { ScrollView } from 'react-native' 433 | 434 | // make sure this is the child of AnchorProvider 435 | function MyComponent() { 436 | const { register } = useRegisterScroller() 437 | 438 | return ( 439 | 440 | 441 | 442 | ) 443 | } 444 | 445 | export default function Provider() { 446 | return ( 447 | 448 | 449 | 450 | ) 451 | } 452 | ``` 453 | 454 | ### `useAnchors` 455 | 456 | If you need to control a `ScrollView` or `FlatList` from outside of their scope: 457 | 458 | ```jsx 459 | import React from 'react' 460 | import { useAnchors, ScrollView } from '@nandorojo/anchor' 461 | 462 | export default function App() { 463 | const anchors = useAnchors() 464 | 465 | const onPress = () => { 466 | anchors.current?.scrollTo('list') 467 | } 468 | 469 | return ( 470 | 471 | 472 | 473 | ) 474 | } 475 | ``` 476 | 477 | ## Formik Error Usage 478 | 479 | 1. Create a `ScrollToField` component: 480 | 481 | ```tsx 482 | import React, { useEffect, useRef } from 'react' 483 | import { Target, useScrollTo } from '@nandorojo/anchor' 484 | import { useFormikContext } from 'formik' 485 | 486 | function isObject(value?: object) { 487 | return value && typeof value === 'object' && value.constructor === Object 488 | } 489 | 490 | function getRecursiveName(object?: object): string { 491 | if (!object || !isObject(object)) { 492 | return '' 493 | } 494 | const currentKey = Object.keys(object)[0] 495 | if (!currentKey) { 496 | return '' 497 | } 498 | if (!getRecursiveName(object[currentKey])) { 499 | return currentKey 500 | } 501 | return currentKey + '.' + getRecursiveName(object[currentKey]) 502 | } 503 | 504 | export function ScrollToField({ name }: { name: string }) { 505 | const { submitCount, errors } = useFormikContext() 506 | 507 | const { scrollTo } = useScrollTo() 508 | const previousSubmitCount = useRef(submitCount) 509 | const errorPath = getRecursiveName(errors) 510 | 511 | useEffect( 512 | function scrollOnSubmissionError() { 513 | if (!errorPath) return 514 | 515 | if (submitCount > previousSubmitCount.current && name) { 516 | if (name === errorPath) { 517 | scrollTo(name).then((didScroll) => console.log('[scroll-to-field] did scroll', name, didScroll)) 518 | } 519 | } 520 | previousSubmitCount.current = submitCount 521 | }, 522 | [errorPath, errors, name, scrollTo, submitCount] 523 | ) 524 | 525 | return 526 | } 527 | ``` 528 | 529 | 2. Add it alongside your field: 530 | 531 | ```tsx 532 | const InputField = ({ name }) => { 533 | const [{ value }] = useField(name) 534 | 535 | return ( 536 | 537 | 538 | 539 | 540 | ) 541 | } 542 | ``` 543 | 544 | ## Contributing 545 | 546 | See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow. 547 | 548 | ## License 549 | 550 | MIT 551 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: ['module:metro-react-native-babel-preset'], 3 | }; 4 | -------------------------------------------------------------------------------- /example/app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@nandorojo/anchor-example", 3 | "displayName": "Anchor Example", 4 | "expo": { 5 | "name": "@nandorojo/anchor-example", 6 | "slug": "nandorojo-anchor-example", 7 | "description": "Example app for @nandorojo/anchor", 8 | "privacy": "public", 9 | "version": "1.0.0", 10 | "platforms": [ 11 | "ios", 12 | "android", 13 | "web" 14 | ], 15 | "ios": { 16 | "supportsTablet": true 17 | }, 18 | "assetBundlePatterns": [ 19 | "**/*" 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /example/babel.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const pak = require('../package.json'); 3 | 4 | module.exports = function (api) { 5 | api.cache(true); 6 | 7 | return { 8 | presets: ['babel-preset-expo'], 9 | plugins: [ 10 | [ 11 | 'module-resolver', 12 | { 13 | extensions: ['.tsx', '.ts', '.js', '.json'], 14 | alias: { 15 | // For development, we want to alias the library to the source 16 | [pak.name]: path.join(__dirname, '..', pak.source), 17 | }, 18 | }, 19 | ], 20 | ], 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/blacklist'); 3 | const escape = require('escape-string-regexp'); 4 | const pak = require('../package.json'); 5 | 6 | const root = path.resolve(__dirname, '..'); 7 | 8 | const modules = Object.keys({ 9 | ...pak.peerDependencies, 10 | }); 11 | 12 | module.exports = { 13 | projectRoot: __dirname, 14 | watchFolders: [root], 15 | 16 | // We need to make sure that only one version is loaded for peerDependencies 17 | // So we blacklist them at the root, and alias them to the versions in example's node_modules 18 | resolver: { 19 | blacklistRE: blacklist( 20 | modules.map( 21 | (m) => 22 | new RegExp(`^${escape(path.join(root, 'node_modules', m))}\\/.*$`) 23 | ) 24 | ), 25 | 26 | extraNodeModules: modules.reduce((acc, name) => { 27 | acc[name] = path.join(__dirname, 'node_modules', name); 28 | return acc; 29 | }, {}), 30 | }, 31 | 32 | transformer: { 33 | getTransformOptions: async () => ({ 34 | transform: { 35 | experimentalImportSupport: false, 36 | inlineRequires: true, 37 | }, 38 | }), 39 | }, 40 | }; 41 | -------------------------------------------------------------------------------- /example/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@nandorojo/anchor-example", 3 | "description": "Example app for @nandorojo/anchor", 4 | "version": "0.0.1", 5 | "private": true, 6 | "main": "index", 7 | "scripts": { 8 | "android": "expo start --android", 9 | "ios": "expo start --ios", 10 | "web": "expo start --web", 11 | "start": "expo start", 12 | "test": "jest" 13 | }, 14 | "dependencies": { 15 | "expo": "^40.0.0", 16 | "expo-splash-screen": "~0.8.1", 17 | "react": "16.13.1", 18 | "react-dom": "16.13.1", 19 | "react-native": "0.63.4", 20 | "react-native-unimodules": "~0.12.0", 21 | "react-native-web": "~0.14.9" 22 | }, 23 | "devDependencies": { 24 | "@babel/core": "~7.12.10", 25 | "@babel/runtime": "^7.9.6", 26 | "babel-plugin-module-resolver": "^4.0.0", 27 | "babel-preset-expo": "8.3.0", 28 | "expo-cli": "^4.0.13" 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /example/src/App.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { StyleSheet, View, Text, useWindowDimensions } from 'react-native'; 3 | import { Target, ScrollView, Anchor } from '@nandorojo/anchor'; 4 | export default function App() { 5 | const { height } = useWindowDimensions(); 6 | return (React.createElement(View, { style: [styles.container, { height }] }, 7 | React.createElement(ScrollView, { style: styles.container }, 8 | React.createElement(Target, { name: "top" }), 9 | React.createElement(View, { style: styles.box }), 10 | React.createElement(Anchor, { target: "1" }, 11 | React.createElement(Text, null, "Scroll to 1")), 12 | React.createElement(Anchor, { target: "2" }, 13 | React.createElement(Text, null, "Scroll to 2")), 14 | React.createElement(View, { style: styles.box }), 15 | React.createElement(Target, { name: "1" }, 16 | React.createElement(Text, null, "Here is 1")), 17 | React.createElement(View, { style: styles.box }), 18 | React.createElement(Target, { name: "2" }, 19 | React.createElement(Text, null, "Here is 2")), 20 | React.createElement(View, { style: styles.box }), 21 | React.createElement(View, { style: styles.box }), 22 | React.createElement(View, { style: styles.box }), 23 | React.createElement(View, { style: styles.box }), 24 | React.createElement(View, { style: styles.box }), 25 | React.createElement(View, { style: styles.box }), 26 | React.createElement(Anchor, { target: "top" }, 27 | React.createElement(Text, null, "Scroll to top"))))); 28 | } 29 | const styles = StyleSheet.create({ 30 | container: { 31 | flex: 1, 32 | }, 33 | box: { 34 | width: 150, 35 | height: 300, 36 | backgroundColor: 'blue', 37 | }, 38 | }); 39 | -------------------------------------------------------------------------------- /example/src/App.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | 3 | import { StyleSheet, View, Text, useWindowDimensions } from 'react-native'; 4 | import { Target, ScrollView, Anchor } from '@nandorojo/anchor'; 5 | 6 | export default function App() { 7 | const { height } = useWindowDimensions(); 8 | 9 | return ( 10 | 11 | 12 | 13 | 14 | 15 | Scroll to 1 16 | 17 | 18 | Scroll to 2 19 | 20 | 21 | 22 | Here is 1 23 | 24 | 25 | 26 | Here is 2 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | Scroll to top 36 | 37 | 38 | 39 | ); 40 | } 41 | 42 | const styles = StyleSheet.create({ 43 | container: { 44 | flex: 1, 45 | }, 46 | box: { 47 | width: 150, 48 | height: 300, 49 | backgroundColor: 'blue', 50 | }, 51 | }); 52 | -------------------------------------------------------------------------------- /example/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "jsx": "react-native", 4 | "target": "esnext", 5 | "lib": ["esnext"], 6 | "allowJs": true, 7 | "skipLibCheck": true, 8 | "noEmit": true, 9 | "allowSyntheticDefaultImports": true, 10 | "resolveJsonModule": true, 11 | "esModuleInterop": true, 12 | "moduleResolution": "node", 13 | "paths": { 14 | "@nandorojo/anchors": ["../../src/index"] 15 | }, 16 | "baseUrl": "./" 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /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": "@nandorojo/anchor", 3 | "version": "0.4.0", 4 | "description": "🦅 Anchor links and scroll-to utilities for React Native (+ Web).", 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 | "nandorojo-anchor.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/nandorojo/anchor", 40 | "author": "Fernando Rojo (https://github.com/nandorojo)", 41 | "license": "MIT", 42 | "bugs": { 43 | "url": "https://github.com/nandorojo/anchor/issues" 44 | }, 45 | "homepage": "https://github.com/nandorojo/anchor#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": "^16.9.53", 55 | "@types/react-dom": "^16.9.8", 56 | "@types/react-native": "^0.63.30", 57 | "commitlint": "^11.0.0", 58 | "eslint": "^7.2.0", 59 | "eslint-config-prettier": "^7.0.0", 60 | "eslint-plugin-prettier": "^3.1.3", 61 | "husky": "^4.2.5", 62 | "jest": "^26.0.1", 63 | "pod-install": "^0.1.0", 64 | "prettier": "^2.0.5", 65 | "react-native-builder-bob": "^0.18.1", 66 | "release-it": "^14.2.2", 67 | "typescript": "^4.2.3" 68 | }, 69 | "peerDependencies": { 70 | "react": "*", 71 | "react-native": "*" 72 | }, 73 | "jest": { 74 | "preset": "react-native", 75 | "modulePathIgnorePatterns": [ 76 | "/example/node_modules", 77 | "/lib/" 78 | ] 79 | }, 80 | "husky": { 81 | "hooks": { 82 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", 83 | "pre-commit": "yarn typescript" 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 | "extends": [ 111 | "@react-native-community", 112 | "prettier" 113 | ], 114 | "rules": { 115 | "prettier/prettier": [ 116 | "error", 117 | { 118 | "quoteProps": "consistent", 119 | "singleQuote": true, 120 | "tabWidth": 2, 121 | "trailingComma": "es5", 122 | "useTabs": false 123 | } 124 | ] 125 | } 126 | }, 127 | "eslintIgnore": [ 128 | "node_modules/", 129 | "lib/" 130 | ], 131 | "prettier": { 132 | "quoteProps": "consistent", 133 | "singleQuote": true, 134 | "tabWidth": 2, 135 | "trailingComma": "es5", 136 | "useTabs": false 137 | }, 138 | "react-native-builder-bob": { 139 | "source": "src", 140 | "output": "lib", 141 | "targets": [ 142 | "commonjs", 143 | "module", 144 | [ 145 | "typescript", 146 | { 147 | "project": "tsconfig.build.json" 148 | } 149 | ] 150 | ] 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /scripts/bootstrap.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const child_process = require('child_process'); 3 | 4 | const root = path.resolve(__dirname, '..'); 5 | const args = process.argv.slice(2); 6 | const options = { 7 | cwd: process.cwd(), 8 | env: process.env, 9 | stdio: 'inherit', 10 | encoding: 'utf-8', 11 | }; 12 | 13 | let result; 14 | 15 | if (process.cwd() !== root || args.length) { 16 | // We're not in the root of the project, or additional arguments were passed 17 | // In this case, forward the command to `yarn` 18 | result = child_process.spawnSync('yarn', args, options); 19 | } else { 20 | // If `yarn` is run without arguments, perform bootstrap 21 | result = child_process.spawnSync('yarn', ['bootstrap'], options); 22 | } 23 | 24 | process.exitCode = result.status; 25 | -------------------------------------------------------------------------------- /src/__tests__/index.test.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | it.todo('write a test'); 3 | -------------------------------------------------------------------------------- /src/__tests__/index.test.tsx: -------------------------------------------------------------------------------- 1 | it.todo('write a test'); 2 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { View, ScrollView as NativeScrollView, FlatList as NativeFlatList, findNodeHandle, Pressable, } from 'react-native'; 3 | const { createContext, forwardRef, useContext, useMemo, useRef, useImperativeHandle, } = React; 4 | // from react-merge-refs (avoid dependency) 5 | function mergeRefs(refs) { 6 | return (value) => { 7 | refs.forEach((ref) => { 8 | if (typeof ref === 'function') { 9 | ref(value); 10 | } 11 | else if (ref != null) { 12 | ref.current = value; 13 | } 14 | }); 15 | }; 16 | } 17 | function getScrollableNode(ref) { 18 | if (ref.current == null) { 19 | return null; 20 | } 21 | if ('scrollTo' in ref.current || 22 | 'scrollToOffset' in ref.current || 23 | 'scrollResponderScrollTo' in ref.current) { 24 | // This is already a scrollable node. 25 | return ref.current; 26 | } 27 | else if ('getScrollResponder' in ref.current) { 28 | // If the view is a wrapper like FlatList, SectionList etc. 29 | // We need to use `getScrollResponder` to get access to the scroll responder 30 | return ref.current.getScrollResponder(); 31 | } 32 | else if ('getNode' in ref.current) { 33 | // When a `ScrollView` is wraped in `Animated.createAnimatedComponent` 34 | // we need to use `getNode` to get the ref to the actual scrollview. 35 | // Note that `getNode` is deprecated in newer versions of react-native 36 | // this is why we check if we already have a scrollable node above. 37 | return ref.current.getNode(); 38 | } 39 | else { 40 | return ref.current; 41 | } 42 | } 43 | /** 44 | * If you need to control a `ScrollView` or `FlatList` from outside of their scope: 45 | * 46 | * ```jsx 47 | * import React from 'react' 48 | * import { useAnchors, ScrollView } from '@nandorojo/anchor' 49 | * 50 | * export default function App() { 51 | * const anchors = useAnchors() 52 | * 53 | * const onPress = () => { 54 | * anchors.current?.scrollTo('list') 55 | * } 56 | * 57 | * return ( 58 | * 59 | * 60 | * 61 | * ) 62 | * } 63 | * ``` 64 | */ 65 | const useAnchors = () => { 66 | const ref = useRef(null); 67 | return ref; 68 | }; 69 | const AnchorsContext = createContext({ 70 | targetRefs: { 71 | current: {}, 72 | }, 73 | scrollRef: { 74 | current: null, 75 | }, 76 | registerTargetRef: () => { 77 | // no-op 78 | }, 79 | registerScrollRef: () => { 80 | // no-op 81 | }, 82 | horizontal: false, 83 | scrollTo: () => { 84 | return new Promise((resolve) => resolve({ 85 | success: false, 86 | message: 'Missing @nandorojo/anchor provider.', 87 | })); 88 | }, 89 | }); 90 | const useAnchorsContext = () => useContext(AnchorsContext); 91 | const useCreateAnchorsContext = ({ horizontal, }) => { 92 | const targetRefs = useRef({}); 93 | const scrollRef = useRef(); 94 | return useMemo(() => { 95 | return { 96 | targetRefs, 97 | scrollRef: scrollRef, 98 | registerTargetRef: (target, ref) => { 99 | targetRefs.current = { 100 | ...targetRefs.current, 101 | [target]: ref, 102 | }; 103 | }, 104 | registerScrollRef: (ref) => { 105 | if (ref) { 106 | scrollRef.current = ref; 107 | } 108 | }, 109 | horizontal, 110 | scrollTo: (name, { animated = true, offset = -10 } = {}) => { 111 | return new Promise((resolve) => { 112 | const node = scrollRef.current && findNodeHandle(scrollRef.current); 113 | if (!node) { 114 | return resolve({ 115 | success: false, 116 | message: 'Scroll ref does not exist. Will not scroll to view.', 117 | }); 118 | } 119 | if (!targetRefs.current?.[name]) { 120 | resolve({ 121 | success: false, 122 | message: 'Anchor ref ' + 123 | name + 124 | ' does not exist. It will not scroll. Please make sure to use the ScrollView provided by @nandorojo/anchors, or use the registerScrollRef function for your own ScrollView.', 125 | }); 126 | } 127 | targetRefs.current?.[name].measureLayout(node, (left, top) => { 128 | requestAnimationFrame(() => { 129 | const scrollY = top; 130 | const scrollX = left; 131 | const scrollable = getScrollableNode(scrollRef); 132 | let scrollTo = horizontal ? scrollX : scrollY; 133 | scrollTo += offset; 134 | scrollTo = Math.max(scrollTo, 0); 135 | const key = horizontal ? 'x' : 'y'; 136 | if ('scrollTo' in scrollable) { 137 | scrollable.scrollTo({ 138 | [key]: scrollTo, 139 | animated, 140 | }); 141 | } 142 | else if ('scrollToOffset' in scrollable) { 143 | scrollable.scrollToOffset({ 144 | offset: scrollTo, 145 | animated, 146 | }); 147 | } 148 | else if ('scrollResponderScrollTo' in scrollable) { 149 | scrollable.scrollResponderScrollTo({ 150 | [key]: scrollTo, 151 | animated, 152 | }); 153 | } 154 | resolve({ success: true }); 155 | }); 156 | }, () => { 157 | resolve({ 158 | success: false, 159 | message: 'Failed to measure target node.', 160 | }); 161 | }); 162 | }); 163 | }, 164 | }; 165 | }, [horizontal]); 166 | }; 167 | function useRegisterTarget() { 168 | const { registerTargetRef } = useAnchorsContext(); 169 | return useMemo(() => ({ 170 | register: (name) => { 171 | return (ref) => registerTargetRef(name, ref); 172 | }, 173 | }), [registerTargetRef]); 174 | } 175 | function useScrollTo() { 176 | const { scrollTo } = useAnchorsContext(); 177 | return useMemo(() => ({ 178 | scrollTo, 179 | // scrollTo: ( 180 | // name: Anchor, 181 | // { animated = true, offset = -10 }: ScrollToOptions = {} 182 | // ) => { 183 | // return new Promise< 184 | // { success: true } | { success: false; message: string } 185 | // >((resolve) => { 186 | // const node = 187 | // scrollRef.current && findNodeHandle(scrollRef.current as any); 188 | // if (!node) { 189 | // return resolve({ 190 | // success: false, 191 | // message: 'Scroll ref does not exist. Will not scroll to view.', 192 | // }); 193 | // } 194 | // if (!targetRefs.current?.[name]) { 195 | // resolve({ 196 | // success: false, 197 | // message: 198 | // 'Anchor ref ' + 199 | // name + 200 | // ' does not exist. It will not scroll. Please make sure to use the ScrollView provided by @nandorojo/anchors, or use the registerScrollRef function for your own ScrollView.', 201 | // }); 202 | // } 203 | // targetRefs.current?.[name].measureLayout( 204 | // node, 205 | // (left, top) => { 206 | // requestAnimationFrame(() => { 207 | // const scrollY = top; 208 | // const scrollX = left; 209 | // const scrollable = getScrollableNode( 210 | // scrollRef 211 | // ) as ScrollableWrapper; 212 | // let scrollTo = horizontal ? scrollX : scrollY; 213 | // scrollTo += offset; 214 | // scrollTo = Math.max(scrollTo, 0); 215 | // const key = horizontal ? 'x' : 'y'; 216 | // if ('scrollTo' in scrollable) { 217 | // scrollable.scrollTo({ 218 | // [key]: scrollTo, 219 | // animated, 220 | // }); 221 | // } else if ('scrollToOffset' in scrollable) { 222 | // scrollable.scrollToOffset({ 223 | // offset: scrollTo, 224 | // animated, 225 | // }); 226 | // } else if ('scrollResponderScrollTo' in scrollable) { 227 | // scrollable.scrollResponderScrollTo({ 228 | // [key]: scrollTo, 229 | // animated, 230 | // }); 231 | // } 232 | // resolve({ success: true }); 233 | // }); 234 | // }, 235 | // () => { 236 | // resolve({ 237 | // success: false, 238 | // message: 'Failed to measure target node.', 239 | // }); 240 | // } 241 | // ); 242 | // }); 243 | // }, 244 | }), [scrollTo]); 245 | } 246 | function useRegisterScroller() { 247 | const { registerScrollRef } = useAnchorsContext(); 248 | return { registerScrollRef }; 249 | } 250 | function AnchorProvider({ children, horizontal, anchors, }) { 251 | const value = useCreateAnchorsContext({ horizontal }); 252 | useImperativeHandle(anchors, () => ({ 253 | scrollTo: (...props) => { 254 | return value.scrollTo(...props); 255 | }, 256 | })); 257 | return (React.createElement(AnchorsContext.Provider, { value: value }, children)); 258 | } 259 | /** 260 | * Identical to the normal React Native `ScrollView`, except that it allows scrolling to anchor links. 261 | * 262 | * If you use this component, you don't need to use the `AnchorProvider`. It implements it for you. 263 | */ 264 | const ScrollView = forwardRef(function ScrollView({ horizontal = false, anchors, ...props }, ref) { 265 | return (React.createElement(AnchorProvider, { anchors: anchors, horizontal: horizontal }, 266 | React.createElement(AnchorsContext.Consumer, null, ({ registerScrollRef }) => (React.createElement(NativeScrollView, Object.assign({ horizontal: horizontal }, props, { ref: mergeRefs([registerScrollRef, ref]) })))))); 267 | }); 268 | /** 269 | * Identical to the normal React Native flatlist, except that it allows scrolling to anchor links. 270 | * 271 | * If you use this component, you don't need to use the `AnchorProvider`. 272 | * 273 | * One important difference: if you want to use the `ref`, pass it to `flatListRef` instead of `ref`. 274 | */ 275 | function FlatList({ flatListRef, horizontal = false, anchors, ...props }) { 276 | return (React.createElement(AnchorProvider, { anchors: anchors, horizontal: horizontal }, 277 | React.createElement(AnchorsContext.Consumer, null, ({ registerScrollRef }) => (React.createElement(NativeFlatList, Object.assign({}, props, { horizontal: horizontal, ref: mergeRefs([registerScrollRef, flatListRef || null]) })))))); 278 | } 279 | function ScrollTo({ target, onPress, options, onRequestScrollTo, ...props }) { 280 | const { scrollTo } = useScrollTo(); 281 | return (React.createElement(Pressable, Object.assign({}, props, { onPress: async (e) => { 282 | onPress?.(e); 283 | const result = await scrollTo(target, options); 284 | onRequestScrollTo?.(result); 285 | } }))); 286 | } 287 | const Target = forwardRef(function Target({ name, ...props }, ref) { 288 | const { register } = useRegisterTarget(); 289 | return React.createElement(View, Object.assign({}, props, { ref: mergeRefs([register(name), ref]) })); 290 | }); 291 | export { AnchorProvider, ScrollView, FlatList, useRegisterTarget, useScrollTo, ScrollTo, Target, ScrollTo as Anchor, useRegisterScroller, useAnchors, }; 292 | // } 293 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import * as React from 'react'; 2 | import { 3 | View, 4 | Text, 5 | ScrollView as NativeScrollView, 6 | FlatList as NativeFlatList, 7 | FlatListProps, 8 | Pressable, 9 | Platform, 10 | } from 'react-native'; 11 | import type { 12 | ComponentProps, 13 | MutableRefObject, 14 | LegacyRef, 15 | ReactNode, 16 | RefObject, 17 | RefCallback, 18 | } from 'react'; 19 | 20 | const { 21 | createContext, 22 | forwardRef, 23 | useContext, 24 | useMemo, 25 | useRef, 26 | useImperativeHandle, 27 | } = React; 28 | 29 | // from react-merge-refs (avoid dependency) 30 | function mergeRefs( 31 | refs: Array | LegacyRef> 32 | ): RefCallback { 33 | return (value) => { 34 | refs.forEach((ref) => { 35 | if (typeof ref === 'function') { 36 | ref(value); 37 | } else if (ref != null) { 38 | (ref as MutableRefObject).current = value; 39 | } 40 | }); 41 | }; 42 | } 43 | 44 | // type Props = { 45 | // anchors: Anchors; 46 | // }; 47 | 48 | type Unpromisify = T extends Promise ? R : T; 49 | 50 | /** 51 | * The following is taken/edited from `useScrollToTop` from `@react-navigation/native` 52 | */ 53 | type ScrollOptions = { y?: number; animated?: boolean }; 54 | 55 | type ScrollableView = 56 | | { scrollToTop(): void } 57 | | { scrollTo(options: ScrollOptions): void } 58 | | { scrollToOffset(options: { offset?: number; animated?: boolean }): void } 59 | | { scrollResponderScrollTo(options: ScrollOptions): void }; 60 | 61 | type ScrollableWrapper = 62 | | { getScrollResponder(): ReactNode } 63 | | { getNode(): ScrollableView } 64 | | ScrollableView; 65 | 66 | function getScrollableNode(ref: RefObject) { 67 | if (ref.current == null) { 68 | return null; 69 | } 70 | 71 | if (typeof ref.current !== 'object' && typeof ref.current !== 'function') { 72 | return null; 73 | } 74 | 75 | if ( 76 | 'scrollTo' in ref.current || 77 | 'scrollToOffset' in ref.current || 78 | 'scrollResponderScrollTo' in ref.current 79 | ) { 80 | // This is already a scrollable node. 81 | return ref.current; 82 | } else if ('getScrollResponder' in ref.current) { 83 | // If the view is a wrapper like FlatList, SectionList etc. 84 | // We need to use `getScrollResponder` to get access to the scroll responder 85 | return ref.current.getScrollResponder(); 86 | } else if ('getNode' in ref.current) { 87 | // When a `ScrollView` is wraped in `Animated.createAnimatedComponent` 88 | // we need to use `getNode` to get the ref to the actual scrollview. 89 | // Note that `getNode` is deprecated in newer versions of react-native 90 | // this is why we check if we already have a scrollable node above. 91 | return ref.current.getNode(); 92 | } else { 93 | return ref.current; 94 | } 95 | } 96 | /** 97 | * End of react-navigation code. 98 | */ 99 | 100 | type ScrollToOptions = { 101 | animated?: boolean; 102 | /** 103 | * A number that determines how far from the content you want to scroll. 104 | * 105 | * Default: `-10`, which means it scrolls to 10 pixels before the content. 106 | */ 107 | offset?: number; 108 | /** 109 | * If you're using a `ScrollView` or `FlatList` imported from this library, you can ignore this field. 110 | */ 111 | // horizontal?: boolean; 112 | }; 113 | 114 | export interface Anchors {} 115 | 116 | export type AnchorsRef = { 117 | scrollTo: ( 118 | name: Anchor, 119 | options?: ScrollToOptions 120 | ) => Promise<{ success: true } | { success: false; message: string }>; 121 | }; 122 | 123 | /** 124 | * If you need to control a `ScrollView` or `FlatList` from outside of their scope: 125 | * 126 | * ```jsx 127 | * import React from 'react' 128 | * import { useAnchors, ScrollView } from '@nandorojo/anchor' 129 | * 130 | * export default function App() { 131 | * const anchors = useAnchors() 132 | * 133 | * const onPress = () => { 134 | * anchors.current?.scrollTo('list') 135 | * } 136 | * 137 | * return ( 138 | * 139 | * 140 | * 141 | * ) 142 | * } 143 | * ``` 144 | */ 145 | const useAnchors = () => { 146 | const ref = useRef(null); 147 | 148 | return ref; 149 | }; 150 | 151 | // @ts-expect-error 152 | type Anchor = Anchors['anchor'] extends string ? Anchors['anchor'] : string; 153 | 154 | // export default function createAnchors() { 155 | type AnchorsContext = { 156 | targetRefs: RefObject>; 157 | scrollRef: RefObject; 158 | registerTargetRef: (name: Anchor, ref: View | Text) => void; 159 | registerScrollRef: (ref: ScrollableWrapper | null) => void; 160 | horizontal: ComponentProps['horizontal']; 161 | scrollTo: AnchorsRef['scrollTo']; 162 | }; 163 | 164 | const AnchorsContext = createContext({ 165 | targetRefs: { 166 | current: {} as any, 167 | }, 168 | scrollRef: { 169 | current: null as any, 170 | }, 171 | registerTargetRef: () => { 172 | // no-op 173 | }, 174 | registerScrollRef: () => { 175 | // no-op 176 | }, 177 | horizontal: false, 178 | scrollTo: () => { 179 | return new Promise((resolve) => 180 | resolve({ 181 | success: false, 182 | message: 'Missing @nandorojo/anchor provider.', 183 | }) 184 | ); 185 | }, 186 | }); 187 | 188 | const useAnchorsContext = () => useContext(AnchorsContext); 189 | 190 | const useCreateAnchorsContext = ({ 191 | horizontal, 192 | }: Pick): AnchorsContext => { 193 | const targetRefs = useRef>({}); 194 | const scrollRef = useRef(); 195 | 196 | return useMemo(() => { 197 | return { 198 | targetRefs, 199 | scrollRef: scrollRef as RefObject, 200 | registerTargetRef: (target, ref) => { 201 | targetRefs.current = { 202 | ...targetRefs.current, 203 | [target]: ref, 204 | }; 205 | }, 206 | registerScrollRef: (ref) => { 207 | if (ref) { 208 | scrollRef.current = ref; 209 | } 210 | }, 211 | horizontal, 212 | scrollTo: ( 213 | name: Anchor, 214 | { animated = true, offset = -10 }: ScrollToOptions = {} 215 | ) => { 216 | return new Promise< 217 | { success: true } | { success: false; message: string } 218 | >((resolve) => { 219 | try { 220 | const node = Platform.select({ 221 | default: scrollRef.current, 222 | web: 223 | scrollRef.current && 224 | // @ts-ignore 225 | scrollRef.current.getInnerViewNode && 226 | // @ts-ignore 227 | scrollRef.current.getInnerViewNode(), 228 | }); 229 | if (!node) { 230 | return resolve({ 231 | success: false, 232 | message: 'Scroll ref does not exist. Will not scroll to view.', 233 | }); 234 | } 235 | if (!targetRefs.current?.[name]) { 236 | resolve({ 237 | success: false, 238 | message: 239 | 'Anchor ref ' + 240 | name + 241 | ' does not exist. It will not scroll. Please make sure to use the ScrollView provided by @nandorojo/anchors, or use the registerScrollRef function for your own ScrollView.', 242 | }); 243 | } 244 | targetRefs.current?.[name].measureLayout( 245 | node, 246 | (left, top) => { 247 | requestAnimationFrame(() => { 248 | const scrollY = top; 249 | const scrollX = left; 250 | const scrollable = getScrollableNode( 251 | scrollRef as RefObject 252 | ) as ScrollableWrapper; 253 | 254 | let scrollTo = horizontal ? scrollX : scrollY; 255 | scrollTo += offset; 256 | scrollTo = Math.max(scrollTo, 0); 257 | const key = horizontal ? 'x' : 'y'; 258 | 259 | if (!scrollable) { 260 | return resolve({ 261 | success: false, 262 | message: 'Scrollable not detected. Will not scroll.', 263 | }); 264 | } 265 | 266 | try { 267 | if ('scrollTo' in scrollable) { 268 | scrollable.scrollTo({ 269 | [key]: scrollTo, 270 | animated, 271 | }); 272 | } else if ('scrollToOffset' in scrollable) { 273 | scrollable.scrollToOffset({ 274 | offset: scrollTo, 275 | animated, 276 | }); 277 | } else if ('scrollResponderScrollTo' in scrollable) { 278 | scrollable.scrollResponderScrollTo({ 279 | [key]: scrollTo, 280 | animated, 281 | }); 282 | } 283 | } catch (error) { 284 | return resolve({ 285 | success: false, 286 | message: 'Failed to scroll for an unknown reason.', 287 | }); 288 | } 289 | resolve({ success: true }); 290 | }); 291 | }, 292 | () => { 293 | resolve({ 294 | success: false, 295 | message: 'Failed to measure target node.', 296 | }); 297 | } 298 | ); 299 | } catch (error: any) { 300 | resolve({ 301 | success: false, 302 | message: [ 303 | 'Failed to measure target node.', 304 | error && 'message' in error && error.message, 305 | ] 306 | .filter(Boolean) 307 | .join(' '), 308 | }); 309 | } 310 | }); 311 | }, 312 | }; 313 | }, [horizontal]); 314 | }; 315 | 316 | function useRegisterTarget() { 317 | const { registerTargetRef } = useAnchorsContext(); 318 | 319 | return useMemo( 320 | () => ({ 321 | register: (name: Anchor) => { 322 | return (ref: View) => registerTargetRef(name, ref); 323 | }, 324 | }), 325 | [registerTargetRef] 326 | ); 327 | } 328 | 329 | function useScrollTo() { 330 | const { scrollTo } = useAnchorsContext(); 331 | 332 | return useMemo( 333 | () => ({ 334 | scrollTo, 335 | }), 336 | [scrollTo] 337 | ); 338 | } 339 | 340 | function useRegisterScroller() { 341 | const { registerScrollRef } = useAnchorsContext(); 342 | 343 | return { registerScrollRef }; 344 | } 345 | 346 | function AnchorProvider({ 347 | children, 348 | horizontal, 349 | anchors, 350 | }: { children: ReactNode; anchors?: RefObject } & Pick< 351 | AnchorsContext, 352 | 'horizontal' 353 | >) { 354 | const value = useCreateAnchorsContext({ horizontal }); 355 | 356 | useImperativeHandle(anchors, () => ({ 357 | scrollTo: (...props) => { 358 | return value.scrollTo(...props); 359 | }, 360 | })); 361 | 362 | return ( 363 | {children} 364 | ); 365 | } 366 | 367 | /** 368 | * Identical to the normal React Native `ScrollView`, except that it allows scrolling to anchor links. 369 | * 370 | * If you use this component, you don't need to use the `AnchorProvider`. It implements it for you. 371 | */ 372 | const ScrollView = forwardRef< 373 | NativeScrollView, 374 | ComponentProps & { 375 | children?: ReactNode; 376 | } & Pick, 'anchors'> 377 | >(function ScrollView({ horizontal = false, anchors, ...props }, ref) { 378 | return ( 379 | 380 | 381 | {({ registerScrollRef }) => ( 382 | 387 | )} 388 | 389 | 390 | ); 391 | }); 392 | 393 | /** 394 | * Identical to the normal React Native flatlist, except that it allows scrolling to anchor links. 395 | * 396 | * If you use this component, you don't need to use the `AnchorProvider`. 397 | * 398 | * One important difference: if you want to use the `ref`, pass it to `flatListRef` instead of `ref`. 399 | */ 400 | function FlatList({ 401 | flatListRef, 402 | horizontal = false, 403 | anchors, 404 | ...props 405 | }: FlatListProps & { flatListRef?: RefObject } & Pick< 406 | ComponentProps, 407 | 'anchors' 408 | >) { 409 | return ( 410 | 411 | 412 | {({ registerScrollRef }) => ( 413 | 418 | )} 419 | 420 | 421 | ); 422 | } 423 | 424 | function ScrollTo({ 425 | target, 426 | onPress, 427 | options, 428 | onRequestScrollTo, 429 | ...props 430 | }: { 431 | children?: ReactNode; 432 | target: Anchor; 433 | options?: ScrollToOptions; 434 | onRequestScrollTo?: ( 435 | props: Unpromisify['scrollTo']>> 436 | ) => void; 437 | } & ComponentProps) { 438 | const { scrollTo } = useScrollTo(); 439 | 440 | return ( 441 | { 444 | onPress?.(e); 445 | const result = await scrollTo(target, options); 446 | onRequestScrollTo?.(result); 447 | }} 448 | /> 449 | ); 450 | } 451 | 452 | const Target = forwardRef< 453 | View, 454 | { name: Anchor; children?: ReactNode } & ComponentProps 455 | >(function Target({ name, ...props }, ref) { 456 | const { register } = useRegisterTarget(); 457 | 458 | return ; 459 | }); 460 | 461 | const AnchorsConsumer = AnchorsContext.Consumer; 462 | 463 | export { 464 | AnchorProvider, 465 | ScrollView, 466 | FlatList, 467 | useRegisterTarget, 468 | useScrollTo, 469 | ScrollTo, 470 | Target, 471 | ScrollTo as Anchor, 472 | useRegisterScroller, 473 | useAnchors, 474 | AnchorsConsumer, 475 | }; 476 | // } 477 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | 2 | { 3 | "extends": "./tsconfig", 4 | "exclude": ["example"] 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": "./", 4 | "paths": { 5 | "@nandorojo/anchor": ["./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 | --------------------------------------------------------------------------------