Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Edit site: WAAPIfy canvas moving animation #62435

Open
wants to merge 4 commits into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion packages/edit-site/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@
"react-native": "src/index",
"dependencies": {
"@babel/runtime": "^7.16.0",
"@react-spring/web": "^9.4.5",
"@wordpress/a11y": "file:../a11y",
"@wordpress/api-fetch": "file:../api-fetch",
"@wordpress/blob": "file:../blob",
Expand Down
266 changes: 174 additions & 92 deletions packages/edit-site/src/components/layout/animation.js
Original file line number Diff line number Diff line change
@@ -1,125 +1,207 @@
/**
* External dependencies
*/
import { Controller, easings } from '@react-spring/web';

/**
* WordPress dependencies
*/
import { useLayoutEffect, useMemo, useRef } from '@wordpress/element';

function getAbsolutePosition( element ) {
return {
top: element.offsetTop,
left: element.offsetLeft,
};
}

const ANIMATION_DURATION = 400;

/**
* Hook used to compute the styles required to move a div into a new position.
* Animates an element’s placement.
*
* The way this animation works is the following:
* - It first renders the element as if there was no animation.
* - It takes a snapshot of the position of the block to use it
* as a destination point for the animation.
* - It restores the element to the previous position using a CSS transform
* - It uses the "resetAnimation" flag to reset the animation
* from the beginning in order to animate to the new destination point.
* It works on the FLIP principle:
* [First, Last, Invert, Play](https://aerotwist.com/blog/flip-your-animations/)
*
* @param {Object} $1 Options
* @param {*} $1.triggerAnimationOnChange Variable used to trigger the animation if it changes.
* @param {*} $1.triggerAnimationOnChange Variable whose changes trigger the animation.
*/
function useMovingAnimation( { triggerAnimationOnChange } ) {
const ref = useRef();

// Whenever the trigger changes, we need to take a snapshot of the current
// position of the block to use it as a destination point for the animation.
const { previous, prevRect } = useMemo(
() => ( {
previous: ref.current && getAbsolutePosition( ref.current ),
prevRect: ref.current && ref.current.getBoundingClientRect(),
} ),
// Whenever the trigger changes, takes a snapshot of the current rectangle.
const from = useMemo(
() => ref.current?.getBoundingClientRect(),
// eslint-disable-next-line react-hooks/exhaustive-deps
[ triggerAnimationOnChange ]
);

useLayoutEffect( () => {
if ( ! previous || ! ref.current ) {
if (
! from ||
! ref.current ||
! ref.current.animate || // Avoid errors on old UAs.
window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches // They prefer not.
) {
return;
}

// We disable the animation if the user has a preference for reduced
// motion.
const disableAnimation = window.matchMedia(
'(prefers-reduced-motion: reduce)'
).matches;
const animationConfig = flipBox(
{ from, to: ref.current.getBoundingClientRect() },
{ duration: ANIMATION_DURATION, easing: quintInOut }
);

if ( disableAnimation ) {
return;
const control = animate( ref.current, animationConfig );
return () => control.cancel();
}, [ from ] );

return ref;
}

export default useMovingAnimation;

/** @param {number} t */
const linear = ( t ) => t;

/** @param {number} t */
const quintInOut = ( t ) =>
( t *= 2 ) < 1
? 0.5 * t * t * t * t * t
: 0.5 * ( ( t -= 2 ) * t * t * t * t + 2 );

/**
* @param {string} style
*/
function propertyToCamelCase( style ) {
const parts = style.split( '-' );
if ( parts.length === 1 ) {
return parts[ 0 ];
}
return (
parts[ 0 ] +
parts
.slice( 1 )
.map(
/** @param {any} word */ ( word ) =>
word[ 0 ].toUpperCase() + word.slice( 1 )
)
.join( '' )
);
}

/**
* @param {string} css
*/
function asKeyframes( css ) {
// eslint-disable-next-line jsdoc/no-undefined-types
/** @type {Keyframe} */
const keyframe = {};
const parts = css.split( ';' );
for ( const part of parts ) {
const [ property, value ] = part.split( ':' );
if ( ! property || value === undefined ) {
break;
}

const controller = new Controller( {
x: 0,
y: 0,
width: prevRect.width,
height: prevRect.height,
config: {
duration: ANIMATION_DURATION,
easing: easings.easeInOutQuint,
},
onChange( { value } ) {
if ( ! ref.current ) {
return;
}
let { x, y, width, height } = value;
x = Math.round( x );
y = Math.round( y );
width = Math.round( width );
height = Math.round( height );
const finishedMoving = x === 0 && y === 0;
ref.current.style.transformOrigin = 'center center';
ref.current.style.transform = finishedMoving
? null // Set to `null` to explicitly remove the transform.
: `translate3d(${ x }px,${ y }px,0)`;
ref.current.style.width = finishedMoving
? null
: `${ width }px`;
ref.current.style.height = finishedMoving
? null
: `${ height }px`;
},
} );
keyframe[ propertyToCamelCase( property.trim() ) ] = value.trim();
}
return keyframe;
}

/**
* Animates an element, according to the provided configuration.
* @param {Element} element
* @param {AnimationConfig} config
* @param {number} target The target progression — `1` is end, `0` is beginning.
* @param {(() => void) | undefined} callback
*/
const animate = ( element, config, target = 1, callback ) => {
const { delay = 0, duration = 300, css, easing = linear } = config;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this some kind of generic utility you wrote on your own? Do we expect this to be reused elsewhere (block animation maybe as I just copied that one and adapted it to create this file)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pared down Svelte’s internal animate. It would serve for reuse, the block animation could pass a different config (one that operates only on transfrom which should make that one run on the GPU). I’d thought we’d want to try that if this worked well in this instance.


const origin = 1 - target;
const delta = target - origin;
const resolvedDuration = duration * Math.abs( delta );

const keyframes = [];
// `n` must be an integer to ensure a finish accurate to the `target` value.
const n = Math.ceil( resolvedDuration / ( 1000 / 60 ) );

// Generates keyframes ahead of time. Doing so supports custom easing functions.
// Otherwise, if using standard easing functions the plaform’s animate would need
// only the final keyframe. (Well, to avoid an error on some older browsers the
// first keyframe is required too.)
for ( let i = 0; i <= n; i += 1 ) {
const t = origin + delta * easing( i / n );
const styles = css( t, 1 - t );
keyframes.push( asKeyframes( styles ) );
}

const animation = element.animate( keyframes, {
delay,
duration: resolvedDuration,
easing: 'linear', // The actual easing was baked into the keyframes.
} );

ref.current.style.transform = undefined;
const destination = ref.current.getBoundingClientRect();
animation.finished
.then( () => {
callback?.();

const x = Math.round( prevRect.left - destination.left );
const y = Math.round( prevRect.top - destination.top );
const width = destination.width;
const height = destination.height;
if ( target === 1 ) {
animation.cancel();
}
} )
.catch( ( e ) => {
// Error for DOMException: The user aborted a request. This results in two things:
// - startTime is `null`
// - currentTime is `null`
// We can't use the existence of an AbortError as this error and error code is shared
// with other Web APIs such as fetch().

controller.start( {
x: 0,
y: 0,
width,
height,
from: { x, y, width: prevRect.width, height: prevRect.height },
if (
animation.startTime !== null &&
animation.currentTime !== null
) {
throw e;
}
} );

return () => {
controller.stop();
controller.set( {
x: 0,
y: 0,
width: prevRect.width,
height: prevRect.height,
} );
};
}, [ previous, prevRect ] );
return animation;
};

return ref;
}
/**
* @typedef AnimationConfig
* @property {number} [delay] Time before the animation begins in milliseconds.
* @property {number} [duration] Time between the animation’s beginning and end in milliseconds.
* @property {(t: number) => number} [easing] Function to modify the acceleration curve of the animation.
* @property {(t: number, u: number) => string} css Function to compute the CSS rules at a point in the animation’s progression.
*/

export default useMovingAnimation;
/**
* @typedef FlipParams
* @property {number} [delay] Time before the animation begins in milliseconds.
* @property {number | ((len: number) => number)} [duration] Time between the animation’s beginning and end in milliseconds.
* @property {(t: number) => number} [easing] Function to modify the acceleration curve of the animation.
*/

/**
* Provides an animation configuration for animating an element’s placement.
* Adapted from Svelte:
* https://github.com/sveltejs/svelte/blob/main/packages/svelte/src/animate/index.js
* This animates width and height instead of scale as the original does.
* @param {{ from: DOMRect; to: DOMRect }} fromTo
* @param {FlipParams} params
*/
const flipBox = ( { from, to }, params = {} ) => {
const dx = from.left - to.left;
const dy = from.top - to.top;
const dw = from.width - to.width;
const dh = from.height - to.height;
const {
delay = 0,
duration = ( d ) => Math.sqrt( d ) * 120,
easing = linear,
} = params;
return /** @type {AnimationConfig} */ ( {
delay,
duration:
typeof duration === 'function'
? duration( Math.sqrt( dx * dx + dy * dy ) )
: duration,
easing,
css: ( t, u ) => {
const x = u * dx;
const y = u * dy;
const w = u * dw + to.width;
const h = u * dh + to.height;
return `transform: translate3d(${ x }px, ${ y }px,0); width: ${ w }px; height: ${ h }px;`;
},
} );
};
Loading