UNPKG

@daysnap/utils

Version:
88 lines (83 loc) 2.07 kB
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// src/createSwipeHandlers.ts function getPoint(event) { if ("touches" in event) { const touch = event.touches[0] || event.changedTouches[0]; return touch ? [touch.pageX, touch.pageY] : null; } return [event.pageX, event.pageY]; } function getDirection(dx, dy) { const absX = Math.abs(dx); const absY = Math.abs(dy); if (absX === 0 && absY === 0) { return "none"; } if (absX >= absY) { return dx >= 0 ? "right" : "left"; } return dy >= 0 ? "down" : "up"; } function createSwipeHandlers(listener, options = {}) { const threshold = Math.max(_nullishCoalesce(options.threshold, () => ( 0)), 0); let startPoint = null; let endPoint = null; const handleCancel = () => { startPoint = null; endPoint = null; }; const handleStart = (event) => { const point = getPoint(event); if (!point) { return; } startPoint = point; endPoint = point; }; const handleMove = (event) => { if (!startPoint) { return; } const point = getPoint(event); if (!point) { return; } endPoint = point; }; const handleEnd = (event) => { if (!startPoint || !endPoint) { return; } if (event) { endPoint = getPoint(event) || endPoint; } const [sx, sy] = startPoint; const [ex, ey] = endPoint; const dx = ex - sx; const dy = ey - sy; const absX = Math.abs(dx); const absY = Math.abs(dy); handleCancel(); if (Math.max(absX, absY) < threshold) { return; } listener({ sx, sy, ex, ey, dx, dy, absX, absY, direction: getDirection(dx, dy) }); }; return { handleStart, handleMove, handleEnd, handleCancel }; } var createSwipeHandler = createSwipeHandlers; exports.createSwipeHandlers = createSwipeHandlers; exports.createSwipeHandler = createSwipeHandler;