Skip to content

Commit

Permalink
feat(js): implement AbstractSwipeDetector base class
Browse files Browse the repository at this point in the history
Introduced the AbstractSwipeDetector abstract class in the swiperia-js package. This class provides a foundational setup for detecting swipe gestures with customizable configurations and callbacks. It leverages core functionalities like point recognition and movement computation imported from swiperia-core. Methods include start, move, and end event handlers to manage swipe lifecycle.
  • Loading branch information
samavati committed Apr 13, 2024
1 parent a2afedd commit 72e958c
Showing 1 changed file with 78 additions and 0 deletions.
78 changes: 78 additions & 0 deletions packages/swiperia-js/src/lib/AbstractSwipeDetector.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import {
type SwipeConfig,
type Point,
type SwipeCallback,
movement,
} from 'swiperia-core';

export abstract class AbstractSwipeDetector {
protected _source: Point = [0, 0];
protected _startTime: number = 0;
protected _callback: SwipeCallback = () => {};
protected _config: SwipeConfig = {
threshold: 10,
preventScrollOnSwipe: false,
allowedTime: 300,
};

constructor(public el: HTMLElement, config?: SwipeConfig) {
if (config) {
this._config = {
...this._config,
...config,
};
}
}

abstract point(e: UIEvent): Point;
protected _start(e: UIEvent) {
const _source = this.point(e);
this._source = _source;
this._startTime = e.timeStamp;
this._callback({
event: e,
type: 'start',
direction: null,
source: _source,
target: _source,
deltaX: 0,
deltaY: 0,
absX: 0,
absY: 0,
velocity: 0,
vxvy: [0, 0],
distance: 0,
});
}

protected _move(e: UIEvent) {
const a = this._source;
const b = this.point(e);
const _duration = (e.timeStamp || 0) - this._startTime;
this._callback({
event: e,
type: 'move',
...movement(a, b, _duration),
});
}

protected _end(e: UIEvent) {
const a = this._source;
const b = this.point(e);
const _duration = (e.timeStamp || 0) - this._startTime;
const _movement = movement(a, b, _duration);
const allowedTime = this._config?.allowedTime || 300;
const threshold = this._config?.threshold || 10;
const constraint =
_duration <= allowedTime && _movement.distance >= threshold;
if (!constraint) return;
this._callback({
event: e,
type: 'end',
..._movement,
});
}

abstract listen(callback: SwipeCallback): void;
abstract destroy(): void;
}

0 comments on commit 72e958c

Please sign in to comment.