From 44838bb8246b66b639c9c7df1b469cc76f6dc5ec Mon Sep 17 00:00:00 2001 From: Riad Benguella Date: Mon, 22 Jul 2019 12:03:01 +0200 Subject: [PATCH] Fix animation retriggered on each change --- .../components/block-list/moving-animation.js | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/packages/block-editor/src/components/block-list/moving-animation.js b/packages/block-editor/src/components/block-list/moving-animation.js index adc9ddb01c009e..99a25024ed465f 100644 --- a/packages/block-editor/src/components/block-list/moving-animation.js +++ b/packages/block-editor/src/components/block-list/moving-animation.js @@ -6,7 +6,7 @@ import { useSpring, interpolate } from 'react-spring/web.cjs'; /** * WordPress dependencies */ -import { useState, useLayoutEffect } from '@wordpress/element'; +import { useState, useLayoutEffect, useReducer } from '@wordpress/element'; import { useReducedMotion } from '@wordpress/compose'; /** @@ -29,18 +29,16 @@ import { useReducedMotion } from '@wordpress/compose'; */ function useMovingAnimation( ref, isSelected, enableAnimation, triggerAnimationOnChange ) { const prefersReducedMotion = useReducedMotion() || ! enableAnimation; - const [ resetAnimation, setResetAnimation ] = useState( false ); + const [ triggeredAnimation, triggerAnimation ] = useReducer( ( state = 0 ) => state + 1 ); + const [ finishedAnimation, endAnimation ] = useReducer( ( state = 0 ) => state + 1 ); const [ transform, setTransform ] = useState( { x: 0, y: 0 } ); const previous = ref.current ? ref.current.getBoundingClientRect() : null; - // This effect should be before the animation computation effect - // otherwise we might have a race condition causing the animation - // to not run. useLayoutEffect( () => { - if ( resetAnimation ) { - setResetAnimation( false ); + if ( triggeredAnimation ) { + endAnimation(); } - }, [ resetAnimation ] ); + }, [ triggeredAnimation ] ); useLayoutEffect( () => { if ( prefersReducedMotion ) { return; @@ -54,7 +52,7 @@ function useMovingAnimation( ref, isSelected, enableAnimation, triggerAnimationO ref.current.style.transform = newTransform.x === 0 && newTransform.y === 0 ? undefined : `translate3d(${ newTransform.x }px,${ newTransform.y }px,0)`; - setResetAnimation( true ); + triggerAnimation(); setTransform( newTransform ); }, [ triggerAnimationOnChange ] ); const animationProps = useSpring( { @@ -63,7 +61,7 @@ function useMovingAnimation( ref, isSelected, enableAnimation, triggerAnimationO x: 0, y: 0, }, - reset: resetAnimation, + reset: triggeredAnimation !== finishedAnimation, config: { mass: 5, tension: 2000, friction: 200 }, immediate: prefersReducedMotion, } );