@coreui/vue
Version:
UI Components Library for Vue.js
91 lines (89 loc) • 3.03 kB
JavaScript
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 {
element;
callbacks;
deltaX = 0;
supportPointerEvents = Boolean(window.PointerEvent);
constructor(element, callbacks = {}) {
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);
}
start = (event) => {
if (!this.supportPointerEvents) {
this.deltaX = event.touches[0].clientX;
return;
}
if (this.eventIsPointerPenTouch(event)) {
this.deltaX = event.clientX;
}
};
move = (event) => {
this.deltaX =
event.touches && event.touches.length > 1 ? 0 : event.touches[0].clientX - this.deltaX;
};
end = (event) => {
if (this.eventIsPointerPenTouch(event)) {
this.deltaX = event.clientX - this.deltaX;
}
this.handleSwipe();
this.callbacks.onEnd?.();
};
handleSwipe() {
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) {
this.callbacks.onRight?.();
}
else {
this.callbacks.onLeft?.();
}
}
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);
}
}
}
export { Swipe as default };
//# sourceMappingURL=swipe.js.map