UNPKG

react-native-reanimated

Version:

More powerful alternative to Animated library for React Native.

703 lines (652 loc) • 23.4 kB
'use strict'; import { defineAnimation, withSpring, withTiming } from "../animation/index.js"; import { interpolateMatrix, prepareMatrixInterpolation } from "../animation/transformationMatrix/matrixUtils.js"; import { convertToRGBA, isColor, rgbaArrayToRGBAColor } from "../Colors.js"; import { logger, processBoxShadow, processColorsInProps } from "../common/index.js"; import { Easing } from "../Easing.js"; import { interpolateColor } from "../interpolateColor.js"; import { AnimationConfigBuilder } from "./animationBuilder/index.js"; const DEFAULT_DURATION = 500; /** * Used to configure the `.defaultTransitionType()` shared transition modifier. * * @experimental */ export let SharedTransitionType = /*#__PURE__*/function (SharedTransitionType) { /** * Use the regular or custom animation, except during iOS back navigation. * During iOS back navigation, use the progress animation controlled by the * screen transition. */ SharedTransitionType["ANIMATION"] = "animation"; /** * Always use the progress animation. During iOS back navigation, the screen * transition controls progress. Otherwise, the builder settings, such as * `.duration()` or `.springify()`, control progress. */ SharedTransitionType["PROGRESS_ANIMATION"] = "progressAnimation"; return SharedTransitionType; }({}); /** * Values passed to shared transition animation worklets: the snapshot of the * source view (`current*`), the snapshot of the target view (`target*`) and the * window size. Per-side and per-corner border values are present only when one * of the views sets them. */ /** * A function that defines a custom shared transition animation. It receives the * source/target values and should return an object containing animations for * each property. */ /** * A function that defines a progress-based shared transition animation. It * receives the source/target values along with the progress (0-1) and should * return the interpolated style values. */ // `globalOrigin*` and `transformMatrix` repeat `origin*` and `transform`. const ALIAS_NAMES = ['GlobalOriginX', 'GlobalOriginY', 'TransformMatrix']; const GEOMETRY_KEYS = ['originX', 'originY', 'width', 'height', 'transform', 'transformOrigin']; function isEqual(a, b) { 'worklet'; if (a === b) { return true; } if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) { return false; } const aRecord = a; const bRecord = b; const keys = Object.keys(aRecord); return keys.length === Object.keys(bRecord).length && keys.every(key => isEqual(aRecord[key], bRecord[key])); } // A transparent color takes the RGB of the other color, as in // `interpolateColor`, so that the fade does not pass through gray. function matchTransparentColor(color, otherColor) { 'worklet'; if (!isColor(color) || !isColor(otherColor) || convertToRGBA(color)[3] !== 0) { return color; } const [red, green, blue] = convertToRGBA(otherColor); return rgbaArrayToRGBAColor([red, green, blue, 0]); } function getChangedStyles(values) { 'worklet'; const record = values; const changed = []; for (const currentKey in record) { if (!currentKey.startsWith('current')) { continue; } const name = currentKey.slice('current'.length); const current = record[currentKey]; const target = record['target' + name]; if (ALIAS_NAMES.includes(name) || isEqual(current, target)) { continue; } const isColorStyle = name.endsWith('Color'); changed.push({ key: name[0].toLowerCase() + name.slice(1), current: isColorStyle ? matchTransparentColor(current, target) : current, target: isColorStyle ? matchTransparentColor(target, current) : target }); } return changed; } function interpolateValue(progress, current, target) { 'worklet'; if (typeof current === 'number' && typeof target === 'number') { return current + progress * (target - current); } if (typeof current === 'string' && typeof target === 'string') { if (current.endsWith('%') && target.endsWith('%')) { const from = parseFloat(current); return `${from + progress * (parseFloat(target) - from)}%`; } return interpolateColor(progress, [0, 1], [current, target]); } if (Array.isArray(current) && Array.isArray(target)) { return current.map((item, index) => interpolateValue(progress, item, target[index])); } if (typeof current === 'object' && typeof target === 'object' && current !== null && target !== null) { const currentRecord = current; const targetRecord = target; const result = {}; for (const key in currentRecord) { result[key] = interpolateValue(progress, currentRecord[key], targetRecord[key]); } return result; } return progress < 1 ? current : target; } // The clip of the moving view, in the coordinates of the window. A custom animation that does not animate it gets the // default animation, so that the moving view stays clipped like the ancestors of the shared views. const CLIP_KEYS = ['clipOriginX', 'clipOriginY', 'clipWidth', 'clipHeight', 'clipBorderRadius']; // The native side moves the clip keys that an animation does not set with this progress. const CLIP_PROGRESS_KEY = 'sharedTransitionClipProgress'; function defaultProgressAnimation(values, progress) { 'worklet'; const style = {}; for (const { key, current, target } of getChangedStyles(values)) { if (CLIP_KEYS.includes(key)) { continue; } if (key === 'transform') { const matrix = interpolateMatrix(progress, prepareMatrixInterpolation(current.matrix, target.matrix)); style.transform = [{ matrix }]; } else { style[key] = interpolateValue(progress, current, target); } } return style; } // Reanimated 3 animated `transformMatrix`, which Fabric does not read. function withTransformMatrixAsTransform(style) { 'worklet'; if (style.transformMatrix === undefined) { return style; } const { transformMatrix, ...rest } = style; return { ...rest, transform: [{ matrix: transformMatrix }] }; } function withProcessedBoxShadow(style) { 'worklet'; if (style.boxShadow === undefined) { return style; } const processed = { ...style }; processed.boxShadow = processBoxShadow(style.boxShadow); return processed; } // Only `fadeContent()` adds the content opacity to the values. function getContentOpacityChange(values) { 'worklet'; const record = values; const current = record.currentContentOpacity; const target = record.targetContentOpacity; return typeof current === 'number' && typeof target === 'number' && current !== target ? { current, target } : undefined; } function getInitialStyle(styles) { 'worklet'; const initialValues = {}; for (const { key, current } of styles) { initialValues[key] = key === 'transform' ? [current] : current; } return initialValues; } // The snapshot leaves out a border corner or side that neither view sets, so // it starts from the shorthand that the view renders. function getSourceValue(record, key) { 'worklet'; const current = record['current' + key[0].toUpperCase() + key.slice(1)]; if (current !== undefined || !key.startsWith('border')) { return current; } const property = ['Radius', 'Width', 'Color'].find(suffix => key.endsWith(suffix)); return property ? record['currentBorder' + property] : undefined; } function getCustomInitialStyle(values, animations) { 'worklet'; const record = values; const styles = getChangedStyles(values); for (const key in animations) { const current = getSourceValue(record, key); if (current !== undefined && !styles.some(style => style.key === key)) { styles.push({ key, current }); } } return getInitialStyle(styles); } function mapAnimations(value, mapAnimation) { 'worklet'; // An animation created on the React Native runtime arrives as its definition. if (typeof value === 'function') { return mapAnimation(value()); } if (Array.isArray(value)) { return value.map(item => mapAnimations(item, mapAnimation)); } if (typeof value !== 'object' || value === null) { return value; } if ('onFrame' in value) { return mapAnimation(value); } const record = value; const result = {}; for (const key in record) { result[key] = mapAnimations(record[key], mapAnimation); } return result; } function progressDrivenAnimations(values, initialStyle, progressAnimation, createDriver) { 'worklet'; const frame = { timestamp: -1, style: initialStyle }; const styleAt = (timestamp, progress) => { if (frame.timestamp !== timestamp) { frame.timestamp = timestamp; frame.style = progressAnimation(values, progress); } return frame.style; }; const animations = {}; for (const key in initialStyle) { animations[key] = defineAnimation(0, () => { 'worklet'; const driver = createDriver(); return { isHigherOrder: true, onStart: (animation, _value, timestamp) => { driver.onStart(driver, 0, timestamp, undefined); animation.current = initialStyle[key]; }, onFrame: (animation, timestamp) => { const finished = driver.onFrame(driver, timestamp); animation.current = styleAt(timestamp, driver.current)[key]; return finished; }, current: initialStyle[key] }; }); } return animations; } export class SharedTransition extends AnimationConfigBuilder { static presetName = 'SharedTransition'; transitionType = SharedTransitionType.ANIMATION; static createInstance() { return new SharedTransition(); } /** * Fades the children of the shared view out while it moves, and fades the * children of the target view in when it lands. The shared view itself stays * visible. Use it when the two views have different children. Can be chained * alongside other [layout animation * modifiers](https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/glossary#layout-animation-modifier). * * @param config - When the fade-out ends and how long the fade-in lasts. */ static fadeContent(config) { const instance = this.createInstance(); return instance.fadeContent(config); } fadeContent(config = {}) { const { fadeOut, fadeIn } = validFadeContentConfig(config); this.fadeContentV = { fadeOut: { end: validFadeOutEnd(validOptions('fadeOut', fadeOut)?.end) }, fadeIn: { duration: validFadeInDuration(validOptions('fadeIn', fadeIn)?.duration) } }; return this; } buildContentFade() { if (!this.fadeContentV) { return undefined; } const { fadeOut, fadeIn } = this.fadeContentV; return { fadeIn: this.buildContentFadeIn(fadeIn?.duration ?? (this.durationV ?? DEFAULT_DURATION) / 2), fadeOutEnd: fadeOut?.end ?? 1 }; } /** * Tells if the built animation aims at the current geometry of the target in * each frame. Custom animations and timed progress animations use the * geometry that the target has when they start, and move with a scroll of the * target. This is used internally by the layout animations system. */ followsTarget() { return this.transitionType !== SharedTransitionType.PROGRESS_ANIMATION && !this.customAnimationFactory; } buildContentFadeIn(duration) { const config = { duration, easing: Easing.out(Easing.quad), reduceMotion: this.reduceMotionV }; const fadeIn = values => { 'worklet'; const { targetOpacity } = values; return { initialValues: { opacity: 0 }, animations: { opacity: withTiming(targetOpacity ?? 1, config) } }; }; return fadeIn; } /** * Creates a shared transition with a custom animation worklet. The worklet * receives the source and target values and returns the animations for each * property. */ static custom(customAnimationFactory) { return new SharedTransition().custom(customAnimationFactory); } /** Uses a custom animation worklet. See {@link SharedTransition.custom}. */ custom(customAnimationFactory) { this.customAnimationFactory = customAnimationFactory; return this; } /** * Creates a shared transition with a progress-based animation worklet. See * {@link SharedTransition#progressAnimation}. */ static progressAnimation(progressAnimationFactory) { return new SharedTransition().progressAnimation(progressAnimationFactory); } /** * Creates a shared transition with the given default transition type. See * {@link SharedTransition#defaultTransitionType}. */ static defaultTransitionType(transitionType) { return new SharedTransition().defaultTransitionType(transitionType); } /** * Defines a progress-based animation for the shared transition. The worklet * receives the source and target values along with the progress (0-1) and * returns the interpolated style values. Without it, every property is * interpolated linearly. */ progressAnimation(progressAnimationFactory) { this.progressAnimationFactory = progressAnimationFactory; return this; } /** * Sets the default transition type for the shared transition. * * - `SharedTransitionType.ANIMATION` - Uses the regular or custom animation, * except during iOS back navigation, when the screen transition controls * the progress animation. * - `SharedTransitionType.PROGRESS_ANIMATION` - Uses the progress animation for * all transitions. The screen transition controls progress during iOS back * navigation; otherwise, the builder settings control progress. * * @param transitionType - The transition type to use. */ defaultTransitionType(transitionType) { this.transitionType = transitionType; return this; } /** Not supported. A shared transition starts from the source view. */ static withInitialValues(_values) { warnUnsupportedModifier('withInitialValues'); return this.createInstance(); } /** Not supported. A shared transition starts from the source view. */ withInitialValues(_values) { warnUnsupportedModifier('withInitialValues'); return this; } /** Not supported. A shared transition ends at the target view. */ static withTargetValues(_values) { warnUnsupportedModifier('withTargetValues'); return this.createInstance(); } /** Not supported. A shared transition ends at the target view. */ withTargetValues(_values) { warnUnsupportedModifier('withTargetValues'); return this; } /** Not supported. A shared transition animates the transform of the view. */ static rotate(_degree) { warnUnsupportedModifier('rotate'); return this.createInstance(); } /** Not supported. A shared transition animates the transform of the view. */ rotate(_degree) { warnUnsupportedModifier('rotate'); return this; } getAnimationAndConfig() { const [animation, config] = super.getAnimationAndConfig(); if (config.duration === undefined && !this.isPhysicsBasedSpring()) { config.duration = DEFAULT_DURATION; } return [animation, config]; } build = () => { const delayFunction = this.getDelayFunction(); const [animation, config] = this.getAnimationAndConfig(); const delay = this.getDelay(); const customAnimationFactory = this.customAnimationFactory; const progressAnimation = this.getStyleProgressAnimation(); const fadeContentOpacity = target => { 'worklet'; return delayFunction(delay, animation(target, { ...config, overshootClamping: true })); }; if (this.transitionType === SharedTransitionType.PROGRESS_ANIMATION) { return layoutAnimationValues => { 'worklet'; const values = layoutAnimationValues; const timedProgressAnimation = (_values, progress) => { 'worklet'; const style = progressAnimation(values, progress); return values.currentClipOriginX === undefined ? style : { ...style, [CLIP_PROGRESS_KEY]: progress }; }; const initialValues = timedProgressAnimation(values, 0); return { initialValues, animations: progressDrivenAnimations(values, initialValues, timedProgressAnimation, () => delayFunction(delay, animation(1, config))) }; }; } if (customAnimationFactory) { return layoutAnimationValues => { 'worklet'; const values = layoutAnimationValues; const animations = withTransformMatrixAsTransform(customAnimationFactory(values)); const delayedAnimations = mapAnimations(animations, customAnimation => delayFunction(delay, customAnimation)); const contentOpacity = getContentOpacityChange(values); if (contentOpacity && animations.contentOpacity === undefined) { delayedAnimations.contentOpacity = fadeContentOpacity(contentOpacity.target); } const initialValues = getCustomInitialStyle(values, animations); if (values.currentClipOriginX !== undefined) { const clipClock = changedClipKeysOf(values).some(key => delayedAnimations[key] === undefined); Object.assign(delayedAnimations, clipClock ? progressDrivenAnimations(values, { [CLIP_PROGRESS_KEY]: 0 }, (_values, progress) => { 'worklet'; return { [CLIP_PROGRESS_KEY]: progress }; }, () => delayFunction(delay, animation(1, config))) : { [CLIP_PROGRESS_KEY]: 1 }); initialValues[CLIP_PROGRESS_KEY] = clipClock ? 0 : 1; } return { initialValues, animations: delayedAnimations }; }; } return layoutAnimationValues => { 'worklet'; const values = layoutAnimationValues; const animateValue = target => { if (Array.isArray(target)) { return target.map(animateValue); } if (typeof target === 'object' && target !== null) { const targetRecord = target; const result = {}; for (const key in targetRecord) { result[key] = animateValue(targetRecord[key]); } return result; } return delayFunction(delay, animation(target, config)); }; // The native side moves the clip and the opacity with the geometry. const isGeometry = key => GEOMETRY_KEYS.includes(key) || CLIP_KEYS.includes(key) || key === 'opacity'; const changed = getChangedStyles(values); const nonGeometry = changed.filter(({ key }) => !isGeometry(key)); const hasGeometryChanges = changed.some(({ key }) => isGeometry(key)); // Equal geometry needs a clock only to hold the start during the delay. The clamp keeps a fade-only spring // from ending after its fade. const geometryClock = hasGeometryChanges || delay > 0 ? () => delayFunction(delay, animation(1, hasGeometryChanges ? config : { ...config, overshootClamping: true })) : undefined; const animations = geometryClock ? progressDrivenAnimations(values, { sharedTransitionGeometryProgress: 0 }, (_values, progress) => { 'worklet'; return { sharedTransitionGeometryProgress: progress }; }, geometryClock) : { sharedTransitionGeometryProgress: 1 }; for (const { key, target } of nonGeometry) { if (key === 'contentOpacity') { animations[key] = fadeContentOpacity(target); continue; } animations[key] = animateValue(target); } return { initialValues: { ...getInitialStyle(nonGeometry), sharedTransitionGeometryProgress: geometryClock ? 0 : 1 }, animations }; }; }; // `withSpring` uses `duration` and `dampingRatio` in place of `damping`, `mass` and `stiffness`. isPhysicsBasedSpring() { return this.type === withSpring && !this.dampingRatioV && !!(this.dampingV || this.massV || this.stiffnessV); } getStyleProgressAnimation() { const progressAnimation = this.progressAnimationFactory ?? defaultProgressAnimation; return (values, progress) => { 'worklet'; let style = progressAnimation(values, progress); const contentOpacity = getContentOpacityChange(values); if (contentOpacity && style.contentOpacity === undefined) { style = { ...style, contentOpacity: interpolateValue(progress, contentOpacity.current, contentOpacity.target) }; } // Animated styles process only the colors of individually animated shadows. return withProcessedBoxShadow(withTransformMatrixAsTransform(style)); }; } /** * Gets the progress animation used for transitions that follow the screen * transition progress. This is used internally by the layout animations * system. */ getProgressAnimation() { const styleProgressAnimation = this.getStyleProgressAnimation(); return (values, progress) => { 'worklet'; // Native progress transitions apply the style without the color processing of animated styles. const style = styleProgressAnimation(values, progress); processColorsInProps(style); return style; }; } } function changedClipKeysOf(values) { 'worklet'; return getChangedStyles(values).map(({ key }) => key).filter(key => CLIP_KEYS.includes(key)); } function warnUnsupportedModifier(name) { logger.warnOnce(`SharedTransition: ${name}() is not supported and has no effect.`, 0); } function isOptionsObject(value) { return typeof value === 'object' && value !== null && !Array.isArray(value); } function validFadeContentConfig(config) { if (isOptionsObject(config)) { return config; } logger.warnOnce(`fadeContent: the config must be an object, got ${describeValue(config)}. The defaults are used.`, 0); return {}; } function validOptions(name, options) { if (options === undefined || isOptionsObject(options)) { return options; } logger.warnOnce(`fadeContent: ${name} must be an object, got ${describeValue(options)}. The defaults are used.`, 0); return undefined; } function validFadeOutEnd(end) { if (end === undefined || typeof end === 'number' && end > 0 && end <= 1) { return end; } logger.warnOnce(`fadeContent: fadeOut.end must be more than 0 and at most 1, got ${describeValue(end)}. The default 1 is used.`, 0); return undefined; } function validFadeInDuration(duration) { if (duration === undefined || typeof duration === 'number' && Number.isFinite(duration) && duration >= 0) { return duration; } logger.warnOnce(`fadeContent: fadeIn.duration must be a finite number of milliseconds, 0 or more, got ${describeValue(duration)}. The default is used.`, 0); return undefined; } function describeValue(value) { return typeof value === 'string' || Array.isArray(value) ? JSON.stringify(value) : String(value); } //# sourceMappingURL=SharedTransition.js.map