2 export type MouseDragTrackerDistance = {
7 export type MouseDragTrackerOptions = {
8 down?: (event: MouseEvent, element: HTMLElement) => any;
9 move?: (event: MouseEvent, element: HTMLElement, distance: MouseDragTrackerDistance) => any;
10 up?: (event: MouseEvent, element: HTMLElement, distance: MouseDragTrackerDistance) => any;
13 export class MouseDragTracker {
14 protected container: HTMLElement;
15 protected dragTargetSelector: string;
16 protected options: MouseDragTrackerOptions;
18 protected startX: number = 0;
19 protected startY: number = 0;
20 protected target: HTMLElement|null = null;
22 constructor(container: HTMLElement, dragTargetSelector: string, options: MouseDragTrackerOptions) {
23 this.container = container;
24 this.dragTargetSelector = dragTargetSelector;
25 this.options = options;
27 this.onMouseDown = this.onMouseDown.bind(this);
28 this.onMouseMove = this.onMouseMove.bind(this);
29 this.onMouseUp = this.onMouseUp.bind(this);
30 this.container.addEventListener('mousedown', this.onMouseDown);
34 this.container.removeEventListener('mousedown', this.onMouseDown);
35 this.container.removeEventListener('mouseup', this.onMouseUp);
36 this.container.removeEventListener('mousemove', this.onMouseMove);
39 protected onMouseDown(event: MouseEvent) {
40 this.target = (event.target as HTMLElement).closest(this.dragTargetSelector);
45 this.startX = event.screenX;
46 this.startY = event.screenY;
48 window.addEventListener('mousemove', this.onMouseMove);
49 window.addEventListener('mouseup', this.onMouseUp);
50 if (this.options.down) {
51 this.options.down(event, this.target);
55 protected onMouseMove(event: MouseEvent) {
56 if (this.options.move && this.target) {
57 this.options.move(event, this.target, {
58 x: event.screenX - this.startX,
59 y: event.screenY - this.startY,
64 protected onMouseUp(event: MouseEvent) {
65 window.removeEventListener('mousemove', this.onMouseMove);
66 window.removeEventListener('mouseup', this.onMouseUp);
68 if (this.options.up && this.target) {
69 this.options.up(event, this.target, {
70 x: event.screenX - this.startX,
71 y: event.screenY - this.startY,