123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- import raf from "rc-util/es/raf";
- import * as React from 'react';
- function smoothScrollOffset(offset) {
- return Math.floor(Math.pow(offset, 0.5));
- }
- export function getPageXY(e, horizontal) {
- var obj = 'touches' in e ? e.touches[0] : e;
- return obj[horizontal ? 'pageX' : 'pageY'] - window[horizontal ? 'scrollX' : 'scrollY'];
- }
- export default function useScrollDrag(inVirtual, componentRef, onScrollOffset) {
- React.useEffect(function () {
- var ele = componentRef.current;
- if (inVirtual && ele) {
- var mouseDownLock = false;
- var rafId;
- var _offset;
- var stopScroll = function stopScroll() {
- raf.cancel(rafId);
- };
- var continueScroll = function continueScroll() {
- stopScroll();
- rafId = raf(function () {
- onScrollOffset(_offset);
- continueScroll();
- });
- };
- var clearDragState = function clearDragState() {
- mouseDownLock = false;
- stopScroll();
- };
- var onMouseDown = function onMouseDown(e) {
- // Skip if element set draggable
- if (e.target.draggable || e.button !== 0) {
- return;
- }
- // Skip if nest List has handled this event
- var event = e;
- if (!event._virtualHandled) {
- event._virtualHandled = true;
- mouseDownLock = true;
- }
- };
- var onMouseMove = function onMouseMove(e) {
- if (mouseDownLock) {
- var mouseY = getPageXY(e, false);
- var _ele$getBoundingClien = ele.getBoundingClientRect(),
- top = _ele$getBoundingClien.top,
- bottom = _ele$getBoundingClien.bottom;
- if (mouseY <= top) {
- var diff = top - mouseY;
- _offset = -smoothScrollOffset(diff);
- continueScroll();
- } else if (mouseY >= bottom) {
- var _diff = mouseY - bottom;
- _offset = smoothScrollOffset(_diff);
- continueScroll();
- } else {
- stopScroll();
- }
- }
- };
- ele.addEventListener('mousedown', onMouseDown);
- ele.ownerDocument.addEventListener('mouseup', clearDragState);
- ele.ownerDocument.addEventListener('mousemove', onMouseMove);
- ele.ownerDocument.addEventListener('dragend', clearDragState);
- return function () {
- ele.removeEventListener('mousedown', onMouseDown);
- ele.ownerDocument.removeEventListener('mouseup', clearDragState);
- ele.ownerDocument.removeEventListener('mousemove', onMouseMove);
- ele.ownerDocument.removeEventListener('dragend', clearDragState);
- stopScroll();
- };
- }
- }, [inVirtual]);
- }
|