@orca-fe/hooks
Version:
React Hooks Collections
89 lines • 2.93 kB
JavaScript
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import { useEventListener, useUpdateEffect } from 'ahooks';
import { useState } from 'react';
import useAnimationFrame from "./useAnimationFrame";
import { getTargetElement } from "./utils/domTarget";
export default function useAutoScroll(target, options = {}) {
var _options$edgeSize = options.edgeSize,
edgeSize = _options$edgeSize === void 0 ? 100 : _options$edgeSize,
realtimeBounds = options.realtimeBounds,
_options$autoTrigger = options.autoTrigger,
autoTrigger = _options$autoTrigger === void 0 ? true : _options$autoTrigger,
_options$scrollableX = options.scrollableX,
scrollableX = _options$scrollableX === void 0 ? true : _options$scrollableX,
_options$scrollableY = options.scrollableY,
scrollableY = _options$scrollableY === void 0 ? true : _options$scrollableY;
var _useState = useState(() => ({
mouse: [0, 0],
bounds: undefined
})),
_useState2 = _slicedToArray(_useState, 1),
_this = _useState2[0];
var rafHandle = useAnimationFrame(() => {
var dom = getTargetElement(target);
if (!dom) return;
if (!_this.bounds) {
_this.bounds = dom.getBoundingClientRect();
}
var _ref = realtimeBounds ? dom.getBoundingClientRect() : _this.bounds,
left = _ref.left,
top = _ref.top,
width = _ref.width,
height = _ref.height;
var x = _this.mouse[0] - left;
var y = _this.mouse[1] - top;
var xEdgeSize = Math.min(edgeSize, width * 0.2);
var yEdgeSize = Math.min(edgeSize, height * 0.2);
var xScrollValue = 0;
var yScrollValue = 0;
if (x < xEdgeSize) {
// 向左移动
xScrollValue = Math.max(-50, 0.1 * Math.round(x - xEdgeSize));
} else if (x > width - xEdgeSize) {
// 向右移动
xScrollValue = Math.min(50, 0.1 * Math.round(x - width + xEdgeSize));
}
if (y < yEdgeSize) {
// 向上移动
yScrollValue = Math.max(-50, 0.1 * Math.round(y - yEdgeSize));
} else if (y > height - yEdgeSize) {
// 向下移动
yScrollValue = Math.min(50, 0.1 * Math.round(y - height + yEdgeSize));
}
if (scrollableX) {
dom.scrollLeft += xScrollValue;
}
if (scrollableY) {
dom.scrollTop += yScrollValue;
}
}, {
manual: true
});
useUpdateEffect(() => {
if (!rafHandle.running) {
_this.bounds = undefined;
}
}, [rafHandle.running]);
useEventListener('mousedown', () => {
var dom = getTargetElement(target);
if (dom) {
_this.bounds = dom.getBoundingClientRect();
}
if (autoTrigger) {
rafHandle.start();
}
}, {
target
});
useEventListener('mouseup', () => {
if (autoTrigger) {
rafHandle.stop();
}
});
useEventListener('mousemove', e => {
var clientX = e.clientX,
clientY = e.clientY;
_this.mouse = [clientX, clientY];
});
return rafHandle;
}