info.mjs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { progress, velocityPerSecond } from 'motion-utils';
  2. /**
  3. * A time in milliseconds, beyond which we consider the scroll velocity to be 0.
  4. */
  5. const maxElapsed = 50;
  6. const createAxisInfo = () => ({
  7. current: 0,
  8. offset: [],
  9. progress: 0,
  10. scrollLength: 0,
  11. targetOffset: 0,
  12. targetLength: 0,
  13. containerLength: 0,
  14. velocity: 0,
  15. });
  16. const createScrollInfo = () => ({
  17. time: 0,
  18. x: createAxisInfo(),
  19. y: createAxisInfo(),
  20. });
  21. const keys = {
  22. x: {
  23. length: "Width",
  24. position: "Left",
  25. },
  26. y: {
  27. length: "Height",
  28. position: "Top",
  29. },
  30. };
  31. function updateAxisInfo(element, axisName, info, time) {
  32. const axis = info[axisName];
  33. const { length, position } = keys[axisName];
  34. const prev = axis.current;
  35. const prevTime = info.time;
  36. axis.current = element[`scroll${position}`];
  37. axis.scrollLength = element[`scroll${length}`] - element[`client${length}`];
  38. axis.offset.length = 0;
  39. axis.offset[0] = 0;
  40. axis.offset[1] = axis.scrollLength;
  41. axis.progress = progress(0, axis.scrollLength, axis.current);
  42. const elapsed = time - prevTime;
  43. axis.velocity =
  44. elapsed > maxElapsed
  45. ? 0
  46. : velocityPerSecond(axis.current - prev, elapsed);
  47. }
  48. function updateScrollInfo(element, info, time) {
  49. updateAxisInfo(element, "x", info, time);
  50. updateAxisInfo(element, "y", info, time);
  51. info.time = time;
  52. }
  53. export { createScrollInfo, updateScrollInfo };