@mui/x-charts
Version:
The community edition of MUI X Charts components.
88 lines (86 loc) • 2.79 kB
JavaScript
'use client';
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import useEnhancedEffect from '@mui/utils/useEnhancedEffect';
export const useChartAnimation = ({
params,
store
}) => {
React.useEffect(() => {
store.update(prevState => {
return _extends({}, prevState, {
animation: _extends({}, prevState.animation, {
skip: params.skipAnimation
})
});
});
}, [store, params.skipAnimation]);
const disableAnimation = React.useCallback(() => {
let disableCalled = false;
store.update(prevState => _extends({}, prevState, {
animation: _extends({}, prevState.animation, {
skipAnimationRequests: prevState.animation.skipAnimationRequests + 1
})
}));
return () => {
if (disableCalled) {
return;
}
disableCalled = true;
store.update(prevState => _extends({}, prevState, {
animation: _extends({}, prevState.animation, {
skipAnimationRequests: prevState.animation.skipAnimationRequests - 1
})
}));
};
}, [store]);
useEnhancedEffect(() => {
// Skip animation test/jsdom
const isAnimationDisabledEnvironment = typeof window === 'undefined' || !window?.matchMedia;
if (isAnimationDisabledEnvironment) {
return undefined;
}
let disableAnimationCleanup;
const handleMediaChange = event => {
if (event.matches) {
disableAnimationCleanup = disableAnimation();
} else {
disableAnimationCleanup?.();
}
};
const mql = window.matchMedia('(prefers-reduced-motion)');
handleMediaChange(mql);
mql.addEventListener('change', handleMediaChange);
return () => {
mql.removeEventListener('change', handleMediaChange);
};
}, [disableAnimation, store]);
return {
instance: {
disableAnimation
}
};
};
useChartAnimation.params = {
skipAnimation: true
};
useChartAnimation.getDefaultizedParams = ({
params
}) => _extends({}, params, {
skipAnimation: params.skipAnimation ?? false
});
useChartAnimation.getInitialState = ({
skipAnimation
}) => {
const isAnimationDisabledEnvironment = typeof window === 'undefined' || !window?.matchMedia;
// We use the value of `isAnimationDisabledEnvironment` as the initial value of `skipAnimation` to avoid
// re-rendering the component on environments where matchMedia is not supported, hence skipAnimation will always be true.
const disableAnimations = process.env.NODE_ENV === 'test' ? isAnimationDisabledEnvironment : false;
return {
animation: {
skip: skipAnimation,
// By initializing the skipAnimationRequests to 1, we ensure that the animation is always skipped
skipAnimationRequests: disableAnimations ? 1 : 0
}
};
};