UNPKG

@ifed/hook

Version:
48 lines 2 kB
function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); } export default function useDraggableScroll(ref) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { direction: 'both' }; if (process.env.NODE_ENV === 'development') { if (_typeof(ref) !== 'object' || typeof ref.current === 'undefined') { console.error('`useDraggableScroll` expects a single ref argument.'); } } var direction = options.direction; var initialPosition = { scrollTop: 0, scrollLeft: 0, mouseX: 0, mouseY: 0 }; var mouseMoveHandler = function mouseMoveHandler(event) { if (ref.current) { var dx = event.clientX - initialPosition.mouseX; var dy = event.clientY - initialPosition.mouseY; if (direction !== 'horizontal') ref.current.scrollTop = initialPosition.scrollTop - dy; if (direction !== 'vertical') ref.current.scrollLeft = initialPosition.scrollLeft - dx; } }; var mouseUpHandler = function mouseUpHandler() { if (ref.current) ref.current.style.cursor = 'grab'; document.removeEventListener('mousemove', mouseMoveHandler); document.removeEventListener('mouseup', mouseUpHandler); }; var onMouseDown = function onMouseDown(event) { if (ref.current) { initialPosition = { scrollLeft: ref.current.scrollLeft, scrollTop: ref.current.scrollTop, mouseX: event.clientX, mouseY: event.clientY }; ref.current.style.cursor = 'grabbing'; ref.current.style.userSelect = 'none'; document.addEventListener('mousemove', mouseMoveHandler); document.addEventListener('mouseup', mouseUpHandler); } }; return { onMouseDown: onMouseDown }; }