Project

General

Profile

1
import {Directive, EventEmitter, HostListener, Input, Output} from '@angular/core';
2

    
3
@Directive({
4
  selector: '[long-click]'
5
})
6

    
7
export class LongClick {
8
  
9
  @Input() duration: number = 500;
10
  
11
  @Output() onLongPress: EventEmitter<any> = new EventEmitter();
12
  @Output() onLongPressing: EventEmitter<any> = new EventEmitter();
13
  @Output() onLongPressEnd: EventEmitter<any> = new EventEmitter();
14
  
15
  private pressing: boolean;
16
  private longPressing: boolean;
17
  private timeout: any;
18
  private mouseX: number = 0;
19
  private mouseY: number = 0;
20
  
21
  @HostListener('mousedown', ['$event'])
22
  onMouseDown(event) {
23
    // don't do right/middle clicks
24
    if (event.which !== 1) return;
25
    
26
    this.mouseX = event.clientX;
27
    this.mouseY = event.clientY;
28
    
29
    this.pressing = true;
30
    this.longPressing = false;
31
    
32
    this.timeout = setTimeout(() => {
33
      this.longPressing = true;
34
      this.onLongPress.emit(event);
35
      this.loop(event);
36
    }, this.duration);
37
    
38
    this.loop(event);
39
  }
40
  
41
  @HostListener('mousemove', ['$event'])
42
  onMouseMove(event) {
43
    if (this.pressing && !this.longPressing) {
44
      const xThres = (event.clientX - this.mouseX) > 10;
45
      const yThres = (event.clientY - this.mouseY) > 10;
46
      if (xThres || yThres) {
47
        this.endPress();
48
      }
49
    }
50
  }
51
  
52
  loop(event) {
53
    if (this.longPressing) {
54
      this.timeout = setTimeout(() => {
55
        this.onLongPressing.emit(event);
56
        this.loop(event);
57
      }, 50);
58
    }
59
  }
60
  
61
  endPress() {
62
    clearTimeout(this.timeout);
63
    this.longPressing = false;
64
    this.pressing = false;
65
    this.onLongPressEnd.emit(true);
66
  }
67
  
68
  @HostListener('mouseup')
69
  onMouseUp() {
70
    this.endPress();
71
  }
72
}
(3-3/3)