useOriginScroll.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import { useRef } from 'react';
  2. export default (function (isScrollAtTop, isScrollAtBottom, isScrollAtLeft, isScrollAtRight) {
  3. // Do lock for a wheel when scrolling
  4. var lockRef = useRef(false);
  5. var lockTimeoutRef = useRef(null);
  6. function lockScroll() {
  7. clearTimeout(lockTimeoutRef.current);
  8. lockRef.current = true;
  9. lockTimeoutRef.current = setTimeout(function () {
  10. lockRef.current = false;
  11. }, 50);
  12. }
  13. // Pass to ref since global add is in closure
  14. var scrollPingRef = useRef({
  15. top: isScrollAtTop,
  16. bottom: isScrollAtBottom,
  17. left: isScrollAtLeft,
  18. right: isScrollAtRight
  19. });
  20. scrollPingRef.current.top = isScrollAtTop;
  21. scrollPingRef.current.bottom = isScrollAtBottom;
  22. scrollPingRef.current.left = isScrollAtLeft;
  23. scrollPingRef.current.right = isScrollAtRight;
  24. return function (isHorizontal, delta) {
  25. var smoothOffset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  26. var originScroll = isHorizontal ?
  27. // Pass origin wheel when on the left
  28. delta < 0 && scrollPingRef.current.left ||
  29. // Pass origin wheel when on the right
  30. delta > 0 && scrollPingRef.current.right // Pass origin wheel when on the top
  31. : delta < 0 && scrollPingRef.current.top ||
  32. // Pass origin wheel when on the bottom
  33. delta > 0 && scrollPingRef.current.bottom;
  34. if (smoothOffset && originScroll) {
  35. // No need lock anymore when it's smooth offset from touchMove interval
  36. clearTimeout(lockTimeoutRef.current);
  37. lockRef.current = false;
  38. } else if (!originScroll || lockRef.current) {
  39. lockScroll();
  40. }
  41. return !lockRef.current && originScroll;
  42. };
  43. });