use-inverted-scale.mjs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { invariant, warning } from 'motion-utils';
  2. import { useContext } from 'react';
  3. import { MotionContext } from '../context/MotionContext/index.mjs';
  4. import { useMotionValue } from './use-motion-value.mjs';
  5. import { useTransform } from './use-transform.mjs';
  6. // Keep things reasonable and avoid scale: Infinity. In practise we might need
  7. // to add another value, opacity, that could interpolate scaleX/Y [0,0.01] => [0,1]
  8. // to simply hide content at unreasonable scales.
  9. const maxScale = 100000;
  10. const invertScale = (scale) => scale > 0.001 ? 1 / scale : maxScale;
  11. let hasWarned = false;
  12. /**
  13. * Returns a `MotionValue` each for `scaleX` and `scaleY` that update with the inverse
  14. * of their respective parent scales.
  15. *
  16. * This is useful for undoing the distortion of content when scaling a parent component.
  17. *
  18. * By default, `useInvertedScale` will automatically fetch `scaleX` and `scaleY` from the nearest parent.
  19. * By passing other `MotionValue`s in as `useInvertedScale({ scaleX, scaleY })`, it will invert the output
  20. * of those instead.
  21. *
  22. * ```jsx
  23. * const MyComponent = () => {
  24. * const { scaleX, scaleY } = useInvertedScale()
  25. * return <motion.div style={{ scaleX, scaleY }} />
  26. * }
  27. * ```
  28. *
  29. * @deprecated
  30. */
  31. function useInvertedScale(scale) {
  32. let parentScaleX = useMotionValue(1);
  33. let parentScaleY = useMotionValue(1);
  34. const { visualElement } = useContext(MotionContext);
  35. invariant(!!(scale || visualElement), "If no scale values are provided, useInvertedScale must be used within a child of another motion component.");
  36. warning(hasWarned, "useInvertedScale is deprecated and will be removed in 3.0. Use the layout prop instead.");
  37. hasWarned = true;
  38. if (scale) {
  39. parentScaleX = scale.scaleX || parentScaleX;
  40. parentScaleY = scale.scaleY || parentScaleY;
  41. }
  42. else if (visualElement) {
  43. parentScaleX = visualElement.getValue("scaleX", 1);
  44. parentScaleY = visualElement.getValue("scaleY", 1);
  45. }
  46. const scaleX = useTransform(parentScaleX, invertScale);
  47. const scaleY = useTransform(parentScaleY, invertScale);
  48. return { scaleX, scaleY };
  49. }
  50. export { invertScale, useInvertedScale };