react-native-reanimated
Version:
More powerful alternative to Animated library for React Native.
389 lines (380 loc) • 17 kB
JavaScript
'use strict';
import { Fragment } from 'react';
import { checkStyleOverwriting, maybeBuild } from "../animationBuilder.js";
import { IS_ANDROID, IS_IOS, IS_JEST, logger } from "../common/index.js";
import { LayoutAnimationType, ReduceMotion } from "../commonTypes.js";
import { SkipEnteringContext } from "../component/LayoutAnimationConfig.js";
import ReanimatedAnimatedComponent from '../css/component/AnimatedComponent';
import { getStaticFeatureFlag } from "../featureFlags/index.js";
import { isSharedValue } from "../isSharedValue.js";
import { SharedTransition } from "../layoutReanimation/SharedTransition.js";
import { PropsRegistryGarbageCollector } from '../PropsRegistryGarbageCollector';
import { ReducedMotionManager } from '../ReducedMotion';
import { updateLayoutAnimations } from '../UpdateLayoutAnimations';
import { InlinePropManager } from "./InlinePropManager.js";
import jsPropsUpdater from './JSPropsUpdater';
import { NativeEventsManager } from "./NativeEventsManager.js";
import { PropsFilter } from "./PropsFilter.js";
import { filterStyles, flattenArray, normalizeTextProp } from "./utils.js";
import { jsx as _jsx } from "react/jsx-runtime";
let id = 0;
const FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS = getStaticFeatureFlag('FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS') && !getStaticFeatureFlag('USE_ANIMATION_BACKEND');
export default class AnimatedComponent extends ReanimatedAnimatedComponent {
_animatedStyles = [];
_prevAnimatedStyles = [];
_animatedProps = [];
_prevAnimatedProps = [];
_isFirstRender = true;
jestAnimatedStyle = {
value: {}
};
jestAnimatedProps = {
value: {}
};
_InlinePropManager = new InlinePropManager();
_PropsFilter = new PropsFilter();
static contextType = SkipEnteringContext;
reanimatedID = id++;
constructor(ChildComponent, props, displayName, options, context) {
super(ChildComponent, props);
this._options = options;
this._displayName = displayName;
if (FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS) {
this.state = {};
}
if (IS_JEST) {
this.jestAnimatedStyle = {
value: {}
};
this.jestAnimatedProps = {
value: {}
};
}
if (this.props.nativeID == null) {
this._configureSharedTransition(true);
}
if (__DEV__ && this.props.entering && this.props.nativeID != null) {
logger.warn(`${displayName}: The entering animation does not run on a component with its own \`nativeID\`.`);
}
this._configureEnteringAnimation(context);
}
componentDidMount() {
super.componentDidMount();
// It exists only on native platforms. We initialize it here because the ref to the animated component is available only post-mount
this._NativeEventsManager = new NativeEventsManager(this, this._options);
this._NativeEventsManager?.attachEvents();
this._updateAnimatedStylesAndProps();
this._InlinePropManager.attachInlineProps(this, this._getViewInfo());
if (FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS) {
const viewTag = this.getComponentViewTag();
if (viewTag !== -1) {
PropsRegistryGarbageCollector.registerView(viewTag, this);
}
}
if (this._options?.jsProps?.length) {
jsPropsUpdater.registerComponent(this, this._options.jsProps);
}
if (IS_IOS && !this._isFirstRender) {
this._configureEnteringAnimation();
}
this._configureLayoutAnimation(LayoutAnimationType.LAYOUT, this.props.layout);
this._configureLayoutAnimation(LayoutAnimationType.EXITING, this.props.exiting);
this._isFirstRender = false;
this._syncReducedMotionListener();
}
componentWillUnmount() {
ReducedMotionManager.listeners.delete(this._onReducedMotionChange);
super.componentWillUnmount();
this._NativeEventsManager?.detachEvents();
this._detachStyles();
this._InlinePropManager.detachInlineProps();
if (FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS) {
const viewTag = this.getComponentViewTag();
if (viewTag !== -1) {
PropsRegistryGarbageCollector.unregisterView(viewTag);
}
}
if (this._options?.jsProps?.length) {
jsPropsUpdater.unregisterComponent(this);
}
}
_syncStylePropsBackToReact(props, style) {
if (!FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS) {
return;
}
this.setState(state => ({
settledProps: {
...state.settledProps,
...props
},
settledStyle: {
...state.settledStyle,
...style
}
}));
// TODO(future): revert changes when animated styles are detached
}
_detachHostBindings(previousViewInfo) {
const viewTag = previousViewInfo.viewTag;
this._detachStyles(viewTag);
this._InlinePropManager.detachInlineProps();
// Nested components share a tag and the collector keeps the first one,
// so only release the entry when it is ours.
if (FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS && PropsRegistryGarbageCollector.viewsMap.get(viewTag) === this) {
PropsRegistryGarbageCollector.unregisterView(viewTag);
}
if (this._options?.jsProps?.length) {
jsPropsUpdater.unregisterComponent(this);
}
}
_attachHostBindings() {
this._NativeEventsManager?.updateEvents();
// Configs registered so far, including this update's from the snapshot,
// went to the previous tag.
this._configureLayoutAnimation(LayoutAnimationType.LAYOUT, this.props.layout);
this._configureLayoutAnimation(LayoutAnimationType.EXITING, this.props.exiting);
this._sharedTransition = undefined;
this._configureSharedTransition();
if (FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS) {
const viewTag = this.getComponentViewTag();
if (viewTag !== -1) {
PropsRegistryGarbageCollector.registerView(viewTag, this);
}
}
if (this._options?.jsProps?.length) {
jsPropsUpdater.registerComponent(this, this._options.jsProps);
}
this._updateAnimatedStylesAndProps();
this._InlinePropManager.attachInlineProps(this, this._getViewInfo());
}
_detachStyles(viewTag = this.getComponentViewTag()) {
if (viewTag === -1) {
return;
}
// A style change in the same update has already moved the attached
// styles to the previous lists, so detach from both.
for (const style of [...this._prevAnimatedStyles, ...this._animatedStyles]) {
style.viewDescriptors.remove(viewTag);
}
for (const animatedProp of [...this._prevAnimatedProps, ...this._animatedProps]) {
animatedProp?.viewDescriptors?.remove(viewTag);
}
}
setNativeProps(props) {
if (this._options?.setNativeProps) {
this._options.setNativeProps(this._componentRef, props);
} else {
this._componentRef?.setNativeProps?.(props);
}
}
_handleAnimatedStylesUpdate(prevStyles, currentStyles, jestAnimatedStyleOrProps) {
const {
viewTag,
shadowNodeWrapper
} = this._getViewInfo();
const newStyles = new Set(currentStyles);
const isStyleAttached = style => style.viewDescriptors.has(viewTag);
// remove old styles
if (prevStyles) {
// in most of the cases, views have only a single animated style and it remains unchanged
const hasOneSameStyle = currentStyles.length === 1 && prevStyles.length === 1 && currentStyles[0] === prevStyles[0];
if (hasOneSameStyle && isStyleAttached(prevStyles[0])) {
return;
}
// otherwise, remove each style that is not present in new styles
for (const prevStyle of prevStyles) {
const isPresent = currentStyles.some(style => {
if (style === prevStyle && isStyleAttached(style)) {
newStyles.delete(style);
return true;
}
return false;
});
if (!isPresent) {
prevStyle.viewDescriptors.remove(viewTag);
}
}
}
newStyles.forEach(style => {
style.viewDescriptors.add({
tag: viewTag,
shadowNodeWrapper
}, style.styleUpdaterContainer);
if (IS_JEST) {
/**
* We need to connect Jest's TestObject instance whose contains just
* props object with the updateProps() function where we update the
* properties of the component. We can't update props object directly
* because TestObject contains a copy of props - look at render
* function: const props = this._filterNonAnimatedProps(this.props);
*/
Object.assign(jestAnimatedStyleOrProps.value, style.initial.value);
style.jestAnimatedValues.current = jestAnimatedStyleOrProps;
}
});
}
_updateAnimatedStylesAndProps() {
this._handleAnimatedStylesUpdate(this._prevAnimatedStyles, this._animatedStyles, this.jestAnimatedStyle);
this._handleAnimatedStylesUpdate(this._prevAnimatedProps, this._animatedProps, this.jestAnimatedProps);
}
componentDidUpdate() {
this._refreshComponentRef();
this._NativeEventsManager?.updateEvents();
this._updateAnimatedStylesAndProps();
this._InlinePropManager.attachInlineProps(this, this._getViewInfo());
this._syncReducedMotionListener();
}
_updateStyles(props) {
const filteredStyles = filterStyles(flattenArray(props.style ?? []));
this._prevAnimatedStyles = this._animatedStyles;
this._animatedStyles = filteredStyles.animatedStyles;
const filteredAnimatedProps = filterStyles(flattenArray(props.animatedProps ?? []));
this._prevAnimatedProps = this._animatedProps;
this._animatedProps = filteredAnimatedProps.animatedStyles;
if (filteredAnimatedProps.cssStyle) {
if (__DEV__ && filteredStyles.cssStyle) {
logger.warn('AnimatedComponent: CSS properties cannot be used in style and animatedProps at the same time. Using properties from the style object.');
this._cssStyle = filteredStyles.cssStyle;
return;
}
// Add all remaining props to cssStyle object
// (e.g. SVG components are styled via top level props, not via style object)
const mergedProps = {
...props,
...filteredAnimatedProps.cssStyle
};
delete mergedProps.style;
delete mergedProps.animatedProps;
this._cssStyle = mergedProps;
} else {
this._cssStyle = filteredStyles.cssStyle ?? {};
}
}
// Native moves the entering config to the view when it inserts a view with
// the Reanimated native ID, so a view with its own `nativeID` never gets it.
_configureEnteringAnimation(context = this.context) {
if (!context?.current && this.props.nativeID == null) {
this._configureLayoutAnimation(LayoutAnimationType.ENTERING, this.props.entering);
}
}
_configureLayoutAnimation(type, currentConfig, previousConfig) {
if (currentConfig === previousConfig) {
return;
}
if (__DEV__ && currentConfig && type !== LayoutAnimationType.LAYOUT && this.props.style && !this._hasWarnedAboutLayoutAnimationStyleOverwriting) {
const onWarn = () => this._hasWarnedAboutLayoutAnimationStyleOverwriting = true;
checkStyleOverwriting(currentConfig, this.props.style, this._displayName, onWarn);
}
updateLayoutAnimations(type === LayoutAnimationType.ENTERING ? this.reanimatedID : this.getComponentViewTag(), type, currentConfig && maybeBuild(currentConfig));
}
_onReducedMotionChange = () => this._configureSharedTransition();
_syncReducedMotionListener() {
if (getStaticFeatureFlag('ENABLE_SHARED_ELEMENT_TRANSITIONS') && this.props.sharedTransitionTag) {
if (!ReducedMotionManager.listeners.has(this._onReducedMotionChange)) {
ReducedMotionManager.listeners.add(this._onReducedMotionChange);
this._configureSharedTransition();
}
} else {
ReducedMotionManager.listeners.delete(this._onReducedMotionChange);
}
}
_configureSharedTransition(useNativeId) {
if (!getStaticFeatureFlag('ENABLE_SHARED_ELEMENT_TRANSITIONS')) {
return;
}
const sharedTransition = this.props.sharedTransitionTag ? this.props.sharedTransitionStyle ?? (this._defaultSharedTransition ??= new SharedTransition()) : undefined;
const reduceMotion = sharedTransition?.getReduceMotion();
const sharedTransitionTag = reduceMotion === ReduceMotion.Always || reduceMotion === ReduceMotion.System && ReducedMotionManager.jsValue ? undefined : this.props.sharedTransitionTag;
if (!sharedTransitionTag || !sharedTransition) {
this._sharedTransition = sharedTransition;
if (this._sharedTransitionTag) {
for (const nativeId of useNativeId ? [true] : [true, false]) {
updateLayoutAnimations(nativeId ? this.reanimatedID : this.getComponentViewTag(), nativeId ? LayoutAnimationType.SHARED_ELEMENT_TRANSITION_NATIVE_ID : LayoutAnimationType.SHARED_ELEMENT_TRANSITION, undefined);
if (!IS_ANDROID) {
updateLayoutAnimations(nativeId ? this.reanimatedID : this.getComponentViewTag(), nativeId ? LayoutAnimationType.SHARED_ELEMENT_TRANSITION_PROGRESS_NATIVE_ID : LayoutAnimationType.SHARED_ELEMENT_TRANSITION_PROGRESS, undefined);
}
}
this._sharedTransitionTag = undefined;
}
return;
}
if (this._sharedTransition === sharedTransition && this._sharedTransitionTag === sharedTransitionTag && this._sharedTransitionFadeContent === sharedTransition.fadeContentV) {
return;
}
updateLayoutAnimations(useNativeId ? this.reanimatedID : this.getComponentViewTag(), useNativeId ? LayoutAnimationType.SHARED_ELEMENT_TRANSITION_NATIVE_ID : LayoutAnimationType.SHARED_ELEMENT_TRANSITION, maybeBuild(sharedTransition), undefined, sharedTransitionTag, sharedTransition.buildContentFade?.(), sharedTransition.callbackV, sharedTransition.followsTarget?.());
if (!IS_ANDROID) {
updateLayoutAnimations(useNativeId ? this.reanimatedID : this.getComponentViewTag(), useNativeId ? LayoutAnimationType.SHARED_ELEMENT_TRANSITION_PROGRESS_NATIVE_ID : LayoutAnimationType.SHARED_ELEMENT_TRANSITION_PROGRESS, sharedTransition.getProgressAnimation(), undefined, undefined);
}
this._sharedTransition = sharedTransition;
this._sharedTransitionTag = sharedTransitionTag;
this._sharedTransitionFadeContent = sharedTransition.fadeContentV;
}
// Android pulls the mounting transaction inside the React commit, so the
// configs for this update must be published here, not in componentDidUpdate.
getSnapshotBeforeUpdate(prevProps) {
this._configureLayoutAnimation(LayoutAnimationType.LAYOUT, this.props.layout, prevProps.layout);
this._configureLayoutAnimation(LayoutAnimationType.EXITING, this.props.exiting, prevProps.exiting);
this._configureSharedTransition();
// `getSnapshotBeforeUpdate` has to return value which is not `undefined`.
return null;
}
render() {
const filteredProps = this._PropsFilter.filterNonAnimatedProps(this);
if (IS_JEST) {
filteredProps.jestAnimatedStyle = this.jestAnimatedStyle;
filteredProps.jestAnimatedProps = this.jestAnimatedProps;
}
const skipEntering = this.context?.current;
let nativeID, jestProps;
if (IS_JEST) {
jestProps = {
jestInlineStyle: this.props.style && filterOutAnimatedStyles(this.props.style),
jestAnimatedStyle: this.jestAnimatedStyle,
jestAnimatedProps: this.jestAnimatedProps
};
} else if (!skipEntering || this._sharedTransitionTag) {
nativeID = `${this.reanimatedID}`;
}
if (this.ChildComponent.displayName === 'Text' && isSharedValue(this.props.children)) {
filteredProps.children = normalizeTextProp(filteredProps.children);
}
// TODO: Remove need for this \/\/\/\/.
// RNSVG expects Gradient elem to have stops passed as children. When we want to animate them,
// we provide them using `gradient` prop.
// Hack below gets rid of RNSVG warnings about not having children.
if (this.ChildComponent.displayName === 'RadialGradient' || this.ChildComponent.displayName === 'LinearGradient') {
if (filteredProps.children === undefined) {
filteredProps.children = /*#__PURE__*/_jsx(Fragment, {});
}
}
if (FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS && this.state.settledStyle) {
return super.render({
...filteredProps,
nativeID: filteredProps.nativeID ?? nativeID,
...this.state.settledProps,
style: [...flattenArray(filteredProps.style), this.state.settledStyle],
...jestProps
});
}
return super.render({
...filteredProps,
nativeID: filteredProps.nativeID ?? nativeID,
...jestProps
});
}
}
function filterOutAnimatedStyles(style) {
if (!style) {
return style;
}
if (!Array.isArray(style)) {
return style?.viewDescriptors ? {} : style;
}
return style.filter(styleElement => !(styleElement && 'viewDescriptors' in styleElement)).map(styleElement => {
if (Array.isArray(styleElement)) {
return filterOutAnimatedStyles(styleElement);
}
return styleElement;
});
}
//# sourceMappingURL=AnimatedComponent.native.js.map