UNPKG

@coreui/react-pro

Version:

UI Components Library for React.js

95 lines (91 loc) 3.42 kB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const SWIPE_THRESHOLD = 40; const POINTER_TYPE_TOUCH = 'touch'; const POINTER_TYPE_PEN = 'pen'; const CLASS_NAME_POINTER_EVENT = 'pointer-event'; /** * Detects horizontal swipe gestures on an element, using Pointer events when * available and falling back to Touch events otherwise. A modified port of the * vanilla `@coreui/coreui` swipe helper. */ class Swipe { constructor(element, callbacks = {}) { this.deltaX = 0; this.supportPointerEvents = Boolean(window.PointerEvent); this.start = (event) => { if (!this.supportPointerEvents) { this.deltaX = event.touches[0].clientX; return; } if (this.eventIsPointerPenTouch(event)) { this.deltaX = event.clientX; } }; this.move = (event) => { this.deltaX = event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.deltaX; }; this.end = (event) => { var _a, _b; if (this.eventIsPointerPenTouch(event)) { this.deltaX = event.clientX - this.deltaX; } this.handleSwipe(); (_b = (_a = this.callbacks).onEnd) === null || _b === void 0 ? void 0 : _b.call(_a); }; this.element = element; this.callbacks = callbacks; if (!element || !Swipe.isSupported()) { return; } this.initEvents(); } static isSupported() { return 'ontouchstart' in document.documentElement || navigator.maxTouchPoints > 0; } dispose() { this.element.removeEventListener('pointerdown', this.start); this.element.removeEventListener('pointerup', this.end); this.element.removeEventListener('touchstart', this.start); this.element.removeEventListener('touchmove', this.move); this.element.removeEventListener('touchend', this.end); this.element.classList.remove(CLASS_NAME_POINTER_EVENT); } handleSwipe() { var _a, _b, _c, _d; const absDeltaX = Math.abs(this.deltaX); if (absDeltaX <= SWIPE_THRESHOLD) { return; } const direction = absDeltaX / this.deltaX; this.deltaX = 0; if (!direction) { return; } if (direction > 0) { (_b = (_a = this.callbacks).onRight) === null || _b === void 0 ? void 0 : _b.call(_a); } else { (_d = (_c = this.callbacks).onLeft) === null || _d === void 0 ? void 0 : _d.call(_c); } } eventIsPointerPenTouch(event) { return (this.supportPointerEvents && (event.pointerType === POINTER_TYPE_PEN || event.pointerType === POINTER_TYPE_TOUCH)); } initEvents() { if (this.supportPointerEvents) { this.element.addEventListener('pointerdown', this.start); this.element.addEventListener('pointerup', this.end); this.element.classList.add(CLASS_NAME_POINTER_EVENT); } else { this.element.addEventListener('touchstart', this.start); this.element.addEventListener('touchmove', this.move); this.element.addEventListener('touchend', this.end); } } } exports.default = Swipe; //# sourceMappingURL=swipe.js.map