UNPKG

@dvcol/common-utils

Version:

Typescript library for common utility functions and constants

45 lines (43 loc) 1.61 kB
// lib/common/utils/touch.utils.ts var SwipeDirection = { Up: "up", Down: "down", Left: "left", Right: "right" }; var ignoreSwipe = ({ start, end, ignore = true } = {}, axis = "x") => { if (!start || !end || !ignore) return false; return start[axis] !== end[axis]; }; var getDiff = (touch, scroll = {}) => { const x = touch.start.clientX - touch.end.clientX; const y = touch.start.clientY - touch.end.clientY; if (!scroll.start || !scroll.end) return { x, y }; return { x: x + (scroll.start.x - scroll.end.x), y: y + (scroll.start.y - scroll.end.y) }; }; var handleSwipeUpDown = ({ start, end }, { horizontal = 0, up = 20, down = 20 } = {}, scroll = {}) => { if (!start || !end || ignoreSwipe(scroll, "y")) return; const { x, y } = getDiff({ start, end }, scroll); if (horizontal && Math.abs(x) >= horizontal) return; if (y < -Math.abs(down)) return SwipeDirection.Down; if (y > Math.abs(up)) return SwipeDirection.Up; }; var handleSwipeLeftRight = ({ start, end }, { vertical = 0, left = 50, right = -50 } = {}, scroll = {}) => { if (!start || !end || ignoreSwipe(scroll, "x")) return; const { x, y } = getDiff({ start, end }, scroll); if (vertical && Math.abs(y) >= vertical) return; if (x < -Math.abs(right)) return SwipeDirection.Right; if (x > Math.abs(left)) return SwipeDirection.Left; }; var handleSwipe = (touch, tolerances = {}, scroll = {}) => { return handleSwipeLeftRight(touch, tolerances, scroll) ?? handleSwipeUpDown(touch, tolerances, scroll); }; export { SwipeDirection, handleSwipeUpDown, handleSwipeLeftRight, handleSwipe };