]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/ui/framework/helpers/mouse-drag-tracker.ts
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / resources / js / wysiwyg / ui / framework / helpers / mouse-drag-tracker.ts
1
2 export type MouseDragTrackerDistance = {
3     x: number;
4     y: number;
5 }
6
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;
11 }
12
13 export class MouseDragTracker {
14     protected container: HTMLElement;
15     protected dragTargetSelector: string;
16     protected options: MouseDragTrackerOptions;
17
18     protected startX: number = 0;
19     protected startY: number = 0;
20     protected target: HTMLElement|null = null;
21
22     constructor(container: HTMLElement, dragTargetSelector: string, options: MouseDragTrackerOptions) {
23         this.container = container;
24         this.dragTargetSelector = dragTargetSelector;
25         this.options = options;
26
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);
31     }
32
33     teardown() {
34         this.container.removeEventListener('mousedown', this.onMouseDown);
35         this.container.removeEventListener('mouseup', this.onMouseUp);
36         this.container.removeEventListener('mousemove', this.onMouseMove);
37     }
38
39     protected onMouseDown(event: MouseEvent) {
40         this.target = (event.target as HTMLElement).closest(this.dragTargetSelector);
41         if (!this.target) {
42             return;
43         }
44
45         this.startX = event.screenX;
46         this.startY = event.screenY;
47
48         window.addEventListener('mousemove', this.onMouseMove);
49         window.addEventListener('mouseup', this.onMouseUp);
50         if (this.options.down) {
51             this.options.down(event, this.target);
52         }
53     }
54
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,
60             });
61         }
62     }
63
64     protected onMouseUp(event: MouseEvent) {
65         window.removeEventListener('mousemove', this.onMouseMove);
66         window.removeEventListener('mouseup', this.onMouseUp);
67
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,
72             });
73         }
74     }
75
76 }