use-velocity.mjs 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import { frame } from 'motion-dom';
  2. import { useMotionValueEvent } from '../utils/use-motion-value-event.mjs';
  3. import { useMotionValue } from './use-motion-value.mjs';
  4. /**
  5. * Creates a `MotionValue` that updates when the velocity of the provided `MotionValue` changes.
  6. *
  7. * ```javascript
  8. * const x = useMotionValue(0)
  9. * const xVelocity = useVelocity(x)
  10. * const xAcceleration = useVelocity(xVelocity)
  11. * ```
  12. *
  13. * @public
  14. */
  15. function useVelocity(value) {
  16. const velocity = useMotionValue(value.getVelocity());
  17. const updateVelocity = () => {
  18. const latest = value.getVelocity();
  19. velocity.set(latest);
  20. /**
  21. * If we still have velocity, schedule an update for the next frame
  22. * to keep checking until it is zero.
  23. */
  24. if (latest)
  25. frame.update(updateVelocity);
  26. };
  27. useMotionValueEvent(value, "change", () => {
  28. // Schedule an update to this value at the end of the current frame.
  29. frame.update(updateVelocity, false, true);
  30. });
  31. return velocity;
  32. }
  33. export { useVelocity };