@atlaskit/motion
Version:
A set of utilities to apply motion in your application.
48 lines • 1.87 kB
JavaScript
import { useRef, useState } from 'react';
import { fg } from '@atlaskit/platform-feature-flags/fg';
import { isReducedMotion } from '../utils/is-reduced-motion';
import { useLayoutEffect } from '../utils/use-layout-effect';
import { observeResizing } from './observe-resizing';
import { useLegacyResizing } from './use-legacy-resizing';
/**
* Animates observed size changes without measuring during React renders or commits.
* The first observation establishes the initial size without motion. Width and height
* transitions still affect layout; unchanged renders do not schedule measurements.
*/
const useObservedResizing = opts => {
const [element, setElement] = useState(null);
const committed = useRef(opts);
const observer = useRef();
useLayoutEffect(() => {
committed.current = opts;
if (isReducedMotion()) {
var _observer$current;
(_observer$current = observer.current) === null || _observer$current === void 0 ? void 0 : _observer$current.suppress();
}
});
useLayoutEffect(() => {
if (!element || typeof ResizeObserver === 'undefined') {
return;
}
const subscription = observeResizing(element, () => ({
...committed.current,
shouldAnimate: !isReducedMotion()
}));
observer.current = subscription;
return () => {
subscription.disconnect();
observer.current = undefined;
};
}, [element]);
return {
ref: setElement
};
};
export const useResizing = opts => {
const enableObservedResizing = fg('platform-dst-motion-observed-resizing');
const observed = useObservedResizing(opts);
const legacy = useLegacyResizing(opts);
// Only the selected implementation receives an element. The inactive hook
// performs no observations, layout reads, or animation writes.
return fg('platform-dst-motion-uplift') && enableObservedResizing ? observed : legacy;
};