touch.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  6. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  7. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  8. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  9. return c > 3 && r && Object.defineProperty(target, key, r), r;
  10. };
  11. import * as DomUtils from './dom.js';
  12. import * as arrays from '../common/arrays.js';
  13. import { memoize } from '../common/decorators.js';
  14. import { Disposable, toDisposable } from '../common/lifecycle.js';
  15. import { LinkedList } from '../common/linkedList.js';
  16. export var EventType;
  17. (function (EventType) {
  18. EventType.Tap = '-monaco-gesturetap';
  19. EventType.Change = '-monaco-gesturechange';
  20. EventType.Start = '-monaco-gesturestart';
  21. EventType.End = '-monaco-gesturesend';
  22. EventType.Contextmenu = '-monaco-gesturecontextmenu';
  23. })(EventType || (EventType = {}));
  24. export class Gesture extends Disposable {
  25. constructor() {
  26. super();
  27. this.dispatched = false;
  28. this.targets = new LinkedList();
  29. this.ignoreTargets = new LinkedList();
  30. this.activeTouches = {};
  31. this.handle = null;
  32. this._lastSetTapCountTime = 0;
  33. this._register(DomUtils.addDisposableListener(document, 'touchstart', (e) => this.onTouchStart(e), { passive: false }));
  34. this._register(DomUtils.addDisposableListener(document, 'touchend', (e) => this.onTouchEnd(e)));
  35. this._register(DomUtils.addDisposableListener(document, 'touchmove', (e) => this.onTouchMove(e), { passive: false }));
  36. }
  37. static addTarget(element) {
  38. if (!Gesture.isTouchDevice()) {
  39. return Disposable.None;
  40. }
  41. if (!Gesture.INSTANCE) {
  42. Gesture.INSTANCE = new Gesture();
  43. }
  44. const remove = Gesture.INSTANCE.targets.push(element);
  45. return toDisposable(remove);
  46. }
  47. static ignoreTarget(element) {
  48. if (!Gesture.isTouchDevice()) {
  49. return Disposable.None;
  50. }
  51. if (!Gesture.INSTANCE) {
  52. Gesture.INSTANCE = new Gesture();
  53. }
  54. const remove = Gesture.INSTANCE.ignoreTargets.push(element);
  55. return toDisposable(remove);
  56. }
  57. static isTouchDevice() {
  58. // `'ontouchstart' in window` always evaluates to true with typescript's modern typings. This causes `window` to be
  59. // `never` later in `window.navigator`. That's why we need the explicit `window as Window` cast
  60. return 'ontouchstart' in window || navigator.maxTouchPoints > 0;
  61. }
  62. dispose() {
  63. if (this.handle) {
  64. this.handle.dispose();
  65. this.handle = null;
  66. }
  67. super.dispose();
  68. }
  69. onTouchStart(e) {
  70. const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
  71. if (this.handle) {
  72. this.handle.dispose();
  73. this.handle = null;
  74. }
  75. for (let i = 0, len = e.targetTouches.length; i < len; i++) {
  76. const touch = e.targetTouches.item(i);
  77. this.activeTouches[touch.identifier] = {
  78. id: touch.identifier,
  79. initialTarget: touch.target,
  80. initialTimeStamp: timestamp,
  81. initialPageX: touch.pageX,
  82. initialPageY: touch.pageY,
  83. rollingTimestamps: [timestamp],
  84. rollingPageX: [touch.pageX],
  85. rollingPageY: [touch.pageY]
  86. };
  87. const evt = this.newGestureEvent(EventType.Start, touch.target);
  88. evt.pageX = touch.pageX;
  89. evt.pageY = touch.pageY;
  90. this.dispatchEvent(evt);
  91. }
  92. if (this.dispatched) {
  93. e.preventDefault();
  94. e.stopPropagation();
  95. this.dispatched = false;
  96. }
  97. }
  98. onTouchEnd(e) {
  99. const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
  100. const activeTouchCount = Object.keys(this.activeTouches).length;
  101. for (let i = 0, len = e.changedTouches.length; i < len; i++) {
  102. const touch = e.changedTouches.item(i);
  103. if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
  104. console.warn('move of an UNKNOWN touch', touch);
  105. continue;
  106. }
  107. const data = this.activeTouches[touch.identifier], holdTime = Date.now() - data.initialTimeStamp;
  108. if (holdTime < Gesture.HOLD_DELAY
  109. && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
  110. && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
  111. const evt = this.newGestureEvent(EventType.Tap, data.initialTarget);
  112. evt.pageX = arrays.tail(data.rollingPageX);
  113. evt.pageY = arrays.tail(data.rollingPageY);
  114. this.dispatchEvent(evt);
  115. }
  116. else if (holdTime >= Gesture.HOLD_DELAY
  117. && Math.abs(data.initialPageX - arrays.tail(data.rollingPageX)) < 30
  118. && Math.abs(data.initialPageY - arrays.tail(data.rollingPageY)) < 30) {
  119. const evt = this.newGestureEvent(EventType.Contextmenu, data.initialTarget);
  120. evt.pageX = arrays.tail(data.rollingPageX);
  121. evt.pageY = arrays.tail(data.rollingPageY);
  122. this.dispatchEvent(evt);
  123. }
  124. else if (activeTouchCount === 1) {
  125. const finalX = arrays.tail(data.rollingPageX);
  126. const finalY = arrays.tail(data.rollingPageY);
  127. const deltaT = arrays.tail(data.rollingTimestamps) - data.rollingTimestamps[0];
  128. const deltaX = finalX - data.rollingPageX[0];
  129. const deltaY = finalY - data.rollingPageY[0];
  130. // We need to get all the dispatch targets on the start of the inertia event
  131. const dispatchTo = [...this.targets].filter(t => data.initialTarget instanceof Node && t.contains(data.initialTarget));
  132. this.inertia(dispatchTo, timestamp, // time now
  133. Math.abs(deltaX) / deltaT, // speed
  134. deltaX > 0 ? 1 : -1, // x direction
  135. finalX, // x now
  136. Math.abs(deltaY) / deltaT, // y speed
  137. deltaY > 0 ? 1 : -1, // y direction
  138. finalY // y now
  139. );
  140. }
  141. this.dispatchEvent(this.newGestureEvent(EventType.End, data.initialTarget));
  142. // forget about this touch
  143. delete this.activeTouches[touch.identifier];
  144. }
  145. if (this.dispatched) {
  146. e.preventDefault();
  147. e.stopPropagation();
  148. this.dispatched = false;
  149. }
  150. }
  151. newGestureEvent(type, initialTarget) {
  152. const event = document.createEvent('CustomEvent');
  153. event.initEvent(type, false, true);
  154. event.initialTarget = initialTarget;
  155. event.tapCount = 0;
  156. return event;
  157. }
  158. dispatchEvent(event) {
  159. if (event.type === EventType.Tap) {
  160. const currentTime = (new Date()).getTime();
  161. let setTapCount = 0;
  162. if (currentTime - this._lastSetTapCountTime > Gesture.CLEAR_TAP_COUNT_TIME) {
  163. setTapCount = 1;
  164. }
  165. else {
  166. setTapCount = 2;
  167. }
  168. this._lastSetTapCountTime = currentTime;
  169. event.tapCount = setTapCount;
  170. }
  171. else if (event.type === EventType.Change || event.type === EventType.Contextmenu) {
  172. // tap is canceled by scrolling or context menu
  173. this._lastSetTapCountTime = 0;
  174. }
  175. if (event.initialTarget instanceof Node) {
  176. for (const ignoreTarget of this.ignoreTargets) {
  177. if (ignoreTarget.contains(event.initialTarget)) {
  178. return;
  179. }
  180. }
  181. for (const target of this.targets) {
  182. if (target.contains(event.initialTarget)) {
  183. target.dispatchEvent(event);
  184. this.dispatched = true;
  185. }
  186. }
  187. }
  188. }
  189. inertia(dispatchTo, t1, vX, dirX, x, vY, dirY, y) {
  190. this.handle = DomUtils.scheduleAtNextAnimationFrame(() => {
  191. const now = Date.now();
  192. // velocity: old speed + accel_over_time
  193. const deltaT = now - t1;
  194. let delta_pos_x = 0, delta_pos_y = 0;
  195. let stopped = true;
  196. vX += Gesture.SCROLL_FRICTION * deltaT;
  197. vY += Gesture.SCROLL_FRICTION * deltaT;
  198. if (vX > 0) {
  199. stopped = false;
  200. delta_pos_x = dirX * vX * deltaT;
  201. }
  202. if (vY > 0) {
  203. stopped = false;
  204. delta_pos_y = dirY * vY * deltaT;
  205. }
  206. // dispatch translation event
  207. const evt = this.newGestureEvent(EventType.Change);
  208. evt.translationX = delta_pos_x;
  209. evt.translationY = delta_pos_y;
  210. dispatchTo.forEach(d => d.dispatchEvent(evt));
  211. if (!stopped) {
  212. this.inertia(dispatchTo, now, vX, dirX, x + delta_pos_x, vY, dirY, y + delta_pos_y);
  213. }
  214. });
  215. }
  216. onTouchMove(e) {
  217. const timestamp = Date.now(); // use Date.now() because on FF e.timeStamp is not epoch based.
  218. for (let i = 0, len = e.changedTouches.length; i < len; i++) {
  219. const touch = e.changedTouches.item(i);
  220. if (!this.activeTouches.hasOwnProperty(String(touch.identifier))) {
  221. console.warn('end of an UNKNOWN touch', touch);
  222. continue;
  223. }
  224. const data = this.activeTouches[touch.identifier];
  225. const evt = this.newGestureEvent(EventType.Change, data.initialTarget);
  226. evt.translationX = touch.pageX - arrays.tail(data.rollingPageX);
  227. evt.translationY = touch.pageY - arrays.tail(data.rollingPageY);
  228. evt.pageX = touch.pageX;
  229. evt.pageY = touch.pageY;
  230. this.dispatchEvent(evt);
  231. // only keep a few data points, to average the final speed
  232. if (data.rollingPageX.length > 3) {
  233. data.rollingPageX.shift();
  234. data.rollingPageY.shift();
  235. data.rollingTimestamps.shift();
  236. }
  237. data.rollingPageX.push(touch.pageX);
  238. data.rollingPageY.push(touch.pageY);
  239. data.rollingTimestamps.push(timestamp);
  240. }
  241. if (this.dispatched) {
  242. e.preventDefault();
  243. e.stopPropagation();
  244. this.dispatched = false;
  245. }
  246. }
  247. }
  248. Gesture.SCROLL_FRICTION = -0.005;
  249. Gesture.HOLD_DELAY = 700;
  250. Gesture.CLEAR_TAP_COUNT_TIME = 400; // ms
  251. __decorate([
  252. memoize
  253. ], Gesture, "isTouchDevice", null);