react-native-reanimated
Version:
More powerful alternative to Animated library for React Native.
69 lines (63 loc) • 2.39 kB
text/typescript
;
import { RuntimeKind } from 'react-native-worklets';
import { IS_JEST, logger, processColorsInProps } from '../common';
import type { InstanceOrElement, StyleProps } from '../commonTypes';
import type {
AnimatedRef,
AnimatedRefOnRN,
AnimatedRefOnUI,
} from '../hook/commonTypes';
import { requestSettledPropsSync } from '../PropsRegistryGarbageCollector';
type SetNativeProps = <TRef extends InstanceOrElement>(
animatedRef: AnimatedRef<TRef>,
updates: StyleProps
) => void;
/**
* Lets you imperatively update component properties. You should always reach
* for
* [useAnimatedStyle](https://docs.swmansion.com/react-native-reanimated/docs/core/useAnimatedStyle)
* and
* [useAnimatedProps](https://docs.swmansion.com/react-native-reanimated/docs/core/useAnimatedProps)
* first when animating styles or properties.
*
* @param animatedRef - An [animated
* ref](https://docs.swmansion.com/react-native-reanimated/docs/core/useAnimatedRef#returns)
* connected to the component you'd want to update.
* @param updates - An object with properties you want to update.
* @see https://docs.swmansion.com/react-native-reanimated/docs/advanced/setNativeProps
*/
export let setNativeProps: SetNativeProps;
function setNativePropsNative(
animatedRef: AnimatedRefOnRN | AnimatedRefOnUI,
updates: StyleProps
) {
'worklet';
if (globalThis.__RUNTIME_KIND === RuntimeKind.ReactNative) {
logger.warn('setNativeProps() can only be used on the UI runtime.');
return;
}
const shadowNodeWrapper = (animatedRef as AnimatedRefOnUI).value;
// The ref is null before it attaches and after its view unmounts.
if (!shadowNodeWrapper) {
logger.warn(
'Tried to call setNativeProps() with an animated ref that is not attached to a view.'
);
return;
}
processColorsInProps(updates);
global._updateProps!([
{ shadowNodeWrapper, updates, isAnimatedProps: false },
]);
requestSettledPropsSync();
}
function setNativePropsJest() {
logger.warn('setNativeProps() is not supported with Jest.');
}
if (IS_JEST) {
setNativeProps = setNativePropsJest;
} else {
// Those assertions are actually correct since on Native platforms `AnimatedRef` is
// mapped as a different function in `serializableMappingCache` and
// TypeScript is not able to infer that.
setNativeProps = setNativePropsNative as unknown as SetNativeProps;
}