UNPKG

2.44 kBPlain TextView Raw
1'use strict';
2import {
3 isChromeDebugger,
4 isFabric,
5 isJest,
6 shouldBeUseWeb,
7} from '../PlatformChecker';
8import { dispatchCommand } from './dispatchCommand';
9import type {
10 AnimatedRef,
11 AnimatedRefOnJS,
12 AnimatedRefOnUI,
13} from '../hook/commonTypes';
14import type { Component } from 'react';
15
16type ScrollTo = <T extends Component>(
17 animatedRef: AnimatedRef<T>,
18 x: number,
19 y: number,
20 animated: boolean
21) => void;
22
23/**
24 * Lets you synchronously scroll to a given position of a `ScrollView`.
25 *
26 * @param animatedRef - An [animated ref](https://docs.swmansion.com/react-native-reanimated/docs/core/useAnimatedRef) attached to an `Animated.ScrollView` component.
27 * @param x - The x position you want to scroll to.
28 * @param y - The y position you want to scroll to.
29 * @param animated - Whether the scrolling should be smooth or instant.
30 * @see https://docs.swmansion.com/react-native-reanimated/docs/scroll/scrollTo
31 */
32export let scrollTo: ScrollTo;
33
34function scrollToFabric(
35 animatedRef: AnimatedRefOnJS | AnimatedRefOnUI,
36 x: number,
37 y: number,
38 animated: boolean
39) {
40 'worklet';
41 dispatchCommand(
42 // This assertion is needed to comply to `dispatchCommand` interface
43 animatedRef as unknown as AnimatedRef<Component>,
44 'scrollTo',
45 [x, y, animated]
46 );
47}
48
49function scrollToPaper(
50 animatedRef: AnimatedRefOnJS | AnimatedRefOnUI,
51 x: number,
52 y: number,
53 animated: boolean
54) {
55 'worklet';
56 if (!_WORKLET) {
57 return;
58 }
59
60 const viewTag = animatedRef() as number;
61 global._scrollToPaper!(viewTag, x, y, animated);
62}
63
64function scrollToJest() {
65 console.warn('[Reanimated] scrollTo() is not supported with Jest.');
66}
67
68function scrollToChromeDebugger() {
69 console.warn(
70 '[Reanimated] scrollTo() is not supported with Chrome Debugger.'
71 );
72}
73
74function scrollToDefault() {
75 console.warn(
76 '[Reanimated] scrollTo() is not supported on this configuration.'
77 );
78}
79
80if (!shouldBeUseWeb()) {
81 // Those assertions are actually correct since on Native platforms `AnimatedRef` is
82 // mapped as a different function in `shareableMappingCache` and
83 // TypeScript is not able to infer that.
84 if (isFabric()) {
85 scrollTo = scrollToFabric as unknown as ScrollTo;
86 } else {
87 scrollTo = scrollToPaper as unknown as ScrollTo;
88 }
89} else if (isJest()) {
90 scrollTo = scrollToJest;
91} else if (isChromeDebugger()) {
92 scrollTo = scrollToChromeDebugger;
93} else {
94 scrollTo = scrollToDefault;
95}