Touch.ts
1 import { Point } from '../Point' 2 3 import { Pointer } from './Pointer' 4 import { WheelDirection } from './WheelDirection' 5 6 export class Touch extends Pointer { 7 private readonly element: HTMLElement 8 private click: number | null 9 private mtime: number 10 private loose: number | null 11 private lastEvent: Event | null 12 13 public constructor(element: HTMLElement | null = null) { 14 super() 15 16 this.click = null 17 this.mtime = 0 18 this.loose = null 19 this.element = element instanceof HTMLElement ? element : document.body 20 21 this.lastEvent = null 22 23 this.listen() 24 } 25 26 public listen(): void { 27 this.element.addEventListener('touchstart', this) 28 this.element.addEventListener('touchmove', this) 29 this.element.addEventListener('touchend', this) 30 } 31 32 public unlisten(): void { 33 this.element.removeEventListener('touchstart', this) 34 this.element.removeEventListener('touchmove', this) 35 this.element.removeEventListener('touchend', this) 36 } 37 38 public handleEvent(e: TouchEvent): void { 39 this.lastEvent = e 40 41 switch (e.type) { 42 case 'touchstart': 43 this.onTouchDown(e) 44 break 45 46 case 'touchmove': 47 this.onTouchMove(e) 48 break 49 50 case 'touchend': 51 this.onTouchUp(e) 52 break 53 } 54 } 55 56 // à faire : trouver une méthode pour éviter un appel à une méthode, comme 57 // dans la classe Keyboard 58 public update(): void { 59 this.mtime += 1 60 } 61 62 // Tant que le bouton est levé 63 public up(): boolean { 64 return this.click === null 65 } 66 67 // Tant que le bouton est baissé 68 public down(): boolean { 69 return this.click !== null 70 } 71 72 // Au moment où le bouton est enfoncé 73 public press(): boolean { 74 return this.click === this.mtime 75 } 76 77 // Au moment où le bouton est levé 78 public release(): boolean { 79 return this.loose === this.mtime 80 } 81 82 // Roulette 83 public wheel(): WheelDirection { 84 // throw new Error('No wheel on touch') 85 86 return WheelDirection.None 87 } 88 89 public getLastEvent(): Event | null { 90 return this.lastEvent 91 } 92 93 private onTouchDown(e: TouchEvent): void { 94 this.onTouchMove(e) 95 this.click = this.mtime 96 } 97 98 private onTouchMove(e: TouchEvent): void { 99 const position = new Point( 100 e.targetTouches[0].pageX - this.element.offsetLeft, 101 e.targetTouches[0].pageY - this.element.offsetTop, 102 ) 103 104 this.setPosition(position) 105 } 106 107 private onTouchUp(_e: TouchEvent): void { 108 this.loose = this.mtime 109 this.click = null 110 } 111 }