UNPKG

pithos

Version:

Advanced JavaScript/TypeScript superset providing performance, gestures, animations, and DOM utilities

62 lines 2.6 kB
import { distance, isPinchGesture } from "./touch-utils"; export class TouchGestureHandler { constructor(element = document.body, callbacks) { this.initialDistance = 0; this.centerX = 0; this.centerY = 0; this.isPinching = false; this.isZoomAllowed = false; this.handleTouchStart = (e) => { if (isPinchGesture(e.touches)) { if (this.shouldAllowZoom) { this.isZoomAllowed = this.shouldAllowZoom("pinch", e.target || undefined); if (!this.isZoomAllowed) { return; } } else { this.isZoomAllowed = true; } this.isPinching = true; this.initialDistance = distance(e.touches[0], e.touches[1]); this.centerX = (e.touches[0].clientX + e.touches[1].clientX) / 2; this.centerY = (e.touches[0].clientY + e.touches[1].clientY) / 2; this.onPinchStart?.(); } }; this.handleTouchMove = (e) => { if (isPinchGesture(e.touches) && this.isPinching && this.isZoomAllowed) { e.preventDefault(); const currentDistance = distance(e.touches[0], e.touches[1]); const scaleChange = currentDistance / this.initialDistance; this.onPinchChange?.(scaleChange, this.centerX, this.centerY); } }; this.handleTouchEnd = (e) => { if (!isPinchGesture(e.touches) && this.isPinching) { this.isPinching = false; this.isZoomAllowed = false; this.onPinchEnd?.(); } }; this.element = element; this.onPinchChange = callbacks?.onPinchChange; this.onPinchStart = callbacks?.onPinchStart; this.shouldAllowZoom = callbacks?.shouldAllowZoom; this.element.addEventListener("touchstart", this.handleTouchStart, { passive: false, }); this.element.addEventListener("touchmove", this.handleTouchMove, { passive: false, }); this.element.addEventListener("touchend", this.handleTouchEnd, { passive: false, }); } destroy() { this.element.removeEventListener("touchstart", this.handleTouchStart); this.element.removeEventListener("touchmove", this.handleTouchMove); this.element.removeEventListener("touchend", this.handleTouchEnd); } } //# sourceMappingURL=touch-handler.js.map