motion
Version:
The Motion library for the web
45 lines (40 loc) • 1.78 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var React = require('react');
var animateStyle = require('../../dom/animate-style.cjs.js');
var noop = require('../../../utils/noop.cjs.js');
var hasChanged = require('../utils/has-changed.cjs.js');
var options = require('../../dom/utils/options.cjs.js');
function useAnimation(ref, initial, target, options$1, onStart, onComplete) {
const prevTarget = React.useRef(initial);
React.useEffect(() => {
const targetKeyframe = {};
const allKeys = new Set([
...Object.keys(target),
...Object.keys(prevTarget.current),
]);
allKeys.forEach((key) => {
let next = target[key];
if (!hasChanged.hasChanged(next, prevTarget.current[key]))
return;
/**
* TODO: If next is undefined, throw error or record a "base value"
* to animate back down to
*/
targetKeyframe[key] = next;
});
if (Object.keys(targetKeyframe).length && ref.current) {
onStart === null || onStart === void 0 ? void 0 : onStart(targetKeyframe);
const animations = [];
for (const key in targetKeyframe) {
const animation = animateStyle.animateStyle(ref.current, key, targetKeyframe[key], options.getOptions(options$1, key));
animation && animations.push(animation);
}
Promise.all(animations.map((animation) => animation.finished))
.then(() => onComplete === null || onComplete === void 0 ? void 0 : onComplete(targetKeyframe))
.catch(noop.noop);
}
prevTarget.current = target;
});
}
exports.useAnimation = useAnimation;