You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.6 KiB

  1. // Like react-motion's Motion, but checks to see if the user prefers
  2. // reduced motion and uses a cross-fade in those cases.
  3. import React from 'react';
  4. import Motion from 'react-motion/lib/Motion';
  5. import PropTypes from 'prop-types';
  6. const stylesToKeep = ['opacity', 'backgroundOpacity'];
  7. let reduceMotion;
  8. const extractValue = (value) => {
  9. // This is either an object with a "val" property or it's a number
  10. return (typeof value === 'object' && value && 'val' in value) ? value.val : value;
  11. };
  12. class OptionalMotion extends React.Component {
  13. static propTypes = {
  14. defaultStyle: PropTypes.object,
  15. style: PropTypes.object,
  16. children: PropTypes.func,
  17. }
  18. render() {
  19. const { style, defaultStyle, children } = this.props;
  20. if (typeof reduceMotion !== 'boolean') {
  21. // This never changes without a page reload, so we can just grab it
  22. // once from the body classes as opposed to using Redux's connect(),
  23. // which would unnecessarily update every state change
  24. reduceMotion = document.body.classList.contains('reduce-motion');
  25. }
  26. if (reduceMotion) {
  27. Object.keys(style).forEach(key => {
  28. if (stylesToKeep.includes(key)) {
  29. return;
  30. }
  31. // If it's setting an x or height or scale or some other value, we need
  32. // to preserve the end-state value without actually animating it
  33. style[key] = defaultStyle[key] = extractValue(style[key]);
  34. });
  35. }
  36. return (
  37. <Motion style={style} defaultStyle={defaultStyle}>
  38. {children}
  39. </Motion>
  40. );
  41. }
  42. }
  43. export default OptionalMotion;