UNPKG

@dvcol/svelte-utils

Version:

Svelte library for common utility functions and constants

64 lines (63 loc) 2.2 kB
import { handleSwipe } from '@dvcol/common-utils/common/touch'; const percentRegex = /(\d+)%/; const toTolerances = ({ container, ...tolerances } = {}) => { if (!tolerances || !Object.keys(tolerances)?.length) return undefined; return Object.entries(tolerances).reduce((acc, [key, value]) => { if (typeof value === 'number') { acc[key] = value; } else { const percent = Number.parseFloat(value); if (!percentRegex.test(value) || !container) { if (!container) console.warn('[SwipeHandler] Node is missing or undefined, value will be used as number', value); acc[key] = Number.parseFloat(value); } else if (['horizontal', 'left', 'right'].includes(key)) { acc[key] = (container.clientWidth * percent) / 100; } else { acc[key] = (container.clientHeight * percent) / 100; } } return acc; }, {}); }; /** * Register touch events handler for swipe detection. * @param onSwipe * @param onTouchStart * @param onTouchEnd * @param tolerances * @param scroll */ export const useSwipe = ({ onSwipe, onTouchStart, onTouchEnd } = {}, tolerances, scroll) => { let scrollStart = $state({ x: window.scrollX, y: window.scrollY }); let touchStart = $state(); return { ontouchstart: e => { touchStart = e; scrollStart = { x: window.scrollX, y: window.scrollY }; return onTouchStart?.(e); }, ontouchend: e => { const start = touchStart?.targetTouches?.[0]; const end = e.changedTouches?.[0]; if (!start || !end) return onTouchEnd?.(e); const swipe = handleSwipe({ start, end, }, toTolerances(tolerances), { start: scrollStart, end: { x: window.scrollX, y: window.scrollY }, ...scroll, }); if (swipe) onSwipe?.(swipe); touchStart = undefined; return onTouchEnd?.(e); }, }; };