Project

General

Profile

1
import {Directive, EventEmitter, HostListener, Input, Output} from '@angular/core';
2
import 'rxjs/add/observable/fromEvent';
3
import 'rxjs/add/operator/delay';
4
import 'rxjs/add/operator/do';
5

    
6
@Directive({
7
  selector: '[long-click]'
8
})
9

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