UNPKG

2.62 kBPlain TextView Raw
1'use strict';
2import type { ShadowNodeWrapper } from '../commonTypes';
3import {
4 isChromeDebugger,
5 isFabric,
6 isJest,
7 shouldBeUseWeb,
8} from '../PlatformChecker';
9import type {
10 AnimatedRef,
11 AnimatedRefOnJS,
12 AnimatedRefOnUI,
13} from '../hook/commonTypes';
14import type { Component } from 'react';
15
16type DispatchCommand = <T extends Component>(
17 animatedRef: AnimatedRef<T>,
18 commandName: string,
19 args?: unknown[]
20) => void;
21
22/**
23 * Lets you synchronously call a command of a native component.
24 *
25 * @param animatedRef - An [animated ref](https://docs.swmansion.com/react-native-reanimated/docs/core/useAnimatedRef#returns) connected to the component you'd want to call the command on.
26 * @param commandName - The name of the command to dispatch (e.g. `"focus"` or `"scrollToEnd"`).
27 * @param args - An optional array of arguments for the command.
28 * @see https://docs.swmansion.com/react-native-reanimated/docs/advanced/dispatchCommand
29 */
30export let dispatchCommand: DispatchCommand;
31
32function dispatchCommandFabric(
33 animatedRef: AnimatedRefOnJS | AnimatedRefOnUI,
34 commandName: string,
35 args: Array<unknown> = []
36) {
37 'worklet';
38 if (!_WORKLET) {
39 return;
40 }
41
42 const shadowNodeWrapper = animatedRef() as ShadowNodeWrapper;
43 global._dispatchCommandFabric!(shadowNodeWrapper, commandName, args);
44}
45
46function dispatchCommandPaper(
47 animatedRef: AnimatedRefOnJS | AnimatedRefOnUI,
48 commandName: string,
49 args: Array<unknown> = []
50) {
51 'worklet';
52 if (!_WORKLET) {
53 return;
54 }
55
56 const viewTag = animatedRef() as number;
57 global._dispatchCommandPaper!(viewTag, commandName, args);
58}
59
60function dispatchCommandJest() {
61 console.warn('[Reanimated] dispatchCommand() is not supported with Jest.');
62}
63
64function dispatchCommandChromeDebugger() {
65 console.warn(
66 '[Reanimated] dispatchCommand() is not supported with Chrome Debugger.'
67 );
68}
69
70function dispatchCommandDefault() {
71 console.warn(
72 '[Reanimated] dispatchCommand() is not supported on this configuration.'
73 );
74}
75
76if (!shouldBeUseWeb()) {
77 // Those assertions are actually correct since on Native platforms `AnimatedRef` is
78 // mapped as a different function in `shareableMappingCache` and
79 // TypeScript is not able to infer that.
80 if (isFabric()) {
81 dispatchCommand = dispatchCommandFabric as unknown as DispatchCommand;
82 } else {
83 dispatchCommand = dispatchCommandPaper as unknown as DispatchCommand;
84 }
85} else if (isJest()) {
86 dispatchCommand = dispatchCommandJest;
87} else if (isChromeDebugger()) {
88 dispatchCommand = dispatchCommandChromeDebugger;
89} else {
90 dispatchCommand = dispatchCommandDefault;
91}