blob: 6971d691fbfa277778e73a6bef628521b64957cb [file] [log] [blame]
Michail Schwab14302052018-08-03 17:23:35 -04001// Copyright (C) 2018 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15export class DragGestureHandler {
16 private readonly boundOnMouseDown = this.onMouseDown.bind(this);
17 private readonly boundOnMouseMove = this.onMouseMove.bind(this);
18 private readonly boundOnMouseUp = this.onMouseUp.bind(this);
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020019 private clientRect?: DOMRect;
Michail Schwab14302052018-08-03 17:23:35 -040020
21 constructor(
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020022 private element: HTMLElement,
23 private onDrag: (x: number, y: number) => void,
Michail Schwab14302052018-08-03 17:23:35 -040024 private onDragStarted: (x: number, y: number) => void = () => {},
25 private onDragFinished = () => {}) {
26 element.addEventListener('mousedown', this.boundOnMouseDown);
27 }
28
29 private onMouseDown(e: MouseEvent) {
30 document.body.addEventListener('mousemove', this.boundOnMouseMove);
31 document.body.addEventListener('mouseup', this.boundOnMouseUp);
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020032 this.clientRect = this.element.getBoundingClientRect() as DOMRect;
33 this.onDragStarted(
34 e.clientX - this.clientRect.left, e.clientY - this.clientRect.top);
Michail Schwab1c9d51a2018-08-08 12:40:25 -040035
36 // Prevent interactions with other DragGestureHandlers and event listeners
37 e.stopPropagation();
Michail Schwab14302052018-08-03 17:23:35 -040038 }
39
40 private onMouseMove(e: MouseEvent) {
Primiano Tuccif30cd9c2018-08-13 01:53:26 +020041 this.onDrag(
42 e.clientX - this.clientRect!.left, e.clientY - this.clientRect!.top);
Michail Schwab1c9d51a2018-08-08 12:40:25 -040043 e.stopPropagation();
Michail Schwab14302052018-08-03 17:23:35 -040044 }
45
Michail Schwab1c9d51a2018-08-08 12:40:25 -040046 private onMouseUp(e: MouseEvent) {
Michail Schwab14302052018-08-03 17:23:35 -040047 document.body.removeEventListener('mousemove', this.boundOnMouseMove);
48 document.body.removeEventListener('mouseup', this.boundOnMouseUp);
49 this.onDragFinished();
Michail Schwab1c9d51a2018-08-08 12:40:25 -040050 e.stopPropagation();
Michail Schwab14302052018-08-03 17:23:35 -040051 }
52}