import {ClientZoom} from "../utils/ClientZoom"; import {createEffectsOfReaction} from "@peryl/react-compose"; export function useDragHorizontalScroll(getEl: () => HTMLElement | null | undefined, config?: { onDragStart: () => void, onDragEnd: () => void }) { const staticState = { isDragging: false, el: null as null | undefined | HTMLElement, start: { x: 0, left: 0, width: 0, }, move: { x: 0 } }; const { effects, effectWatch } = createEffectsOfReaction(); const handler = { mousedown: (e: MouseEvent) => { const { clientX } = ClientZoom.getClientPosition(e); staticState.isDragging = false; staticState.start = { x: clientX, left: staticState.el!.scrollLeft, width: staticState.el!.scrollWidth, }; document.documentElement.addEventListener('mousemove', handler.mousemove, true); document.documentElement.addEventListener('mouseup', handler.mouseup, true); }, mousemove: (e: MouseEvent) => { const { clientX } = ClientZoom.getClientPosition(e); staticState.move.x = clientX; const durX = staticState.move.x - staticState.start.x; if (!staticState.isDragging) { if (Math.abs(durX) > 5) { staticState.isDragging = true; config?.onDragStart(); } } if (!staticState.isDragging) { return; } staticState.el!.scrollLeft = staticState.start.left - durX; }, mouseup: () => { config?.onDragEnd(); document.documentElement.removeEventListener('mousemove', handler.mousemove, true); document.documentElement.removeEventListener('mouseup', handler.mouseup, true); }, onWheel: (e: WheelEvent) => { e.stopPropagation(); e.preventDefault(); const el = e.currentTarget as HTMLElement; const delta = e.deltaX + e.deltaY; el.scrollLeft += delta; }, }; effectWatch(() => getEl(), el => { if (!!staticState.el) { staticState.el.removeEventListener('mousedown', handler.mousedown); staticState.el.removeEventListener('wheel', handler.onWheel); } staticState.el = el; if (!staticState.el) {return;} staticState.el.addEventListener('mousedown', handler.mousedown); staticState.el.addEventListener('wheel', handler.onWheel); }); effects.push(() => { if (!!staticState.el) { staticState.el.removeEventListener('mousedown', handler.mousedown); staticState.el.removeEventListener('wheel', handler.onWheel); } }); return effects.clear; }