├── .prettierignore ├── .gitignore ├── .prettierrc.json ├── tsconfig.json ├── lib ├── missing-types.d.ts └── index.ts ├── rollup.config.js ├── package.json ├── demo └── index.html ├── README.md ├── dist ├── PointerTracker-min.js ├── index.d.ts ├── PointerTracker.mjs └── PointerTracker.js └── LICENSE /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .vscode 3 | .rpt2_cache 4 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "strict": true, 5 | "target": "es2017", 6 | "module": "esnext", 7 | "moduleResolution": "node", 8 | "noUnusedLocals": true, 9 | "sourceMap": true, 10 | "declaration": true, 11 | "allowJs": false, 12 | "baseUrl": "." 13 | }, 14 | } 15 | -------------------------------------------------------------------------------- /lib/missing-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google Inc. All Rights Reserved. 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 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | // TypeScript, you make me sad. 14 | // https://github.com/Microsoft/TypeScript/issues/18756 15 | interface Window { 16 | PointerEvent: typeof PointerEvent; 17 | Touch: typeof Touch; 18 | } 19 | 20 | interface PointerEvent { 21 | getCoalescedEvents(): PointerEvent[]; 22 | } 23 | 24 | interface HTMLElementEventMap { 25 | pointerrawupdate: PointerEvent; 26 | } 27 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google Inc. All Rights Reserved. 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 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | import typescript from 'rollup-plugin-typescript2'; 14 | import { terser } from 'rollup-plugin-terser'; 15 | 16 | const esm = { 17 | plugins: [typescript({ useTsconfigDeclarationDir: false })], 18 | input: 'lib/index.ts', 19 | output: { 20 | file: 'dist/PointerTracker.mjs', 21 | format: 'esm', 22 | }, 23 | }; 24 | 25 | const umd = { 26 | input: 'dist/PointerTracker.mjs', 27 | output: [ 28 | { 29 | file: 'dist/PointerTracker.js', 30 | format: 'umd', 31 | name: 'PointerTracker', 32 | }, 33 | { 34 | plugins: [ 35 | terser({ 36 | compress: { ecma: 6 }, 37 | }), 38 | ], 39 | file: 'dist/PointerTracker-min.js', 40 | format: 'umd', 41 | name: 'PointerTracker', 42 | }, 43 | ], 44 | }; 45 | 46 | export default [esm, umd]; 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "pointer-tracker", 3 | "version": "2.5.3", 4 | "description": "Track mouse/touch/pointer events through one interface", 5 | "main": "dist/PointerTracker.js", 6 | "module": "dist/PointerTracker.mjs", 7 | "types": "dist/index.d.ts", 8 | "exports": { 9 | ".": { 10 | "require": "./dist/PointerTracker.js", 11 | "import": "./dist/PointerTracker.mjs" 12 | }, 13 | "./dist/*": "./dist/*", 14 | "./package.json": "./package.json" 15 | }, 16 | "scripts": { 17 | "build": "rm -rf dist && rollup -c" 18 | }, 19 | "repository": { 20 | "type": "git", 21 | "url": "git+https://github.com/GoogleChromeLabs/pointer-tracker.git" 22 | }, 23 | "keywords": [ 24 | "pointer", 25 | "touch", 26 | "mouse", 27 | "event" 28 | ], 29 | "author": "Jake Archibald", 30 | "license": "Apache-2.0", 31 | "bugs": { 32 | "url": "https://github.com/GoogleChromeLabs/pointer-tracker/issues" 33 | }, 34 | "homepage": "https://github.com/GoogleChromeLabs/pointer-tracker#readme", 35 | "devDependencies": { 36 | "husky": "^7.0.2", 37 | "lint-staged": "^11.1.2", 38 | "prettier": "^2.3.2", 39 | "rollup": "^2.56.3", 40 | "rollup-plugin-terser": "^7.0.2", 41 | "rollup-plugin-typescript2": "^0.30.0", 42 | "typescript": "^4.3.5" 43 | }, 44 | "dependencies": {}, 45 | "husky": { 46 | "hooks": { 47 | "pre-commit": "lint-staged" 48 | } 49 | }, 50 | "lint-staged": { 51 | "*.{js,css,md,ts}": "prettier --write" 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /demo/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Simple painting app 7 | 25 | 26 | 27 | 79 | 80 | 81 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PointerTracker 2 | 3 | Track mouse/touch/pointer events for a given element. 4 | 5 | ## API 6 | 7 | ### PointerTracker 8 | 9 | ```js 10 | import PointerTracker from 'pointer-tracker'; 11 | 12 | const pointerTracker = new PointerTracker(element, { 13 | start(pointer, event) { 14 | // Called when a pointer is pressed/touched within the element. 15 | // 16 | // pointer - The new pointer. This pointer isn't included in this.currentPointers or 17 | // this.startPointers yet. 18 | // 19 | // event - The event related to this pointer. 20 | // 21 | // Return true from this callback if you're interested in further events about this pointer, 22 | // such as 'move' and 'end'. 23 | }, 24 | move(previousPointers, changedPointers, event) { 25 | // Called when pointers have moved. 26 | // 27 | // previousPointers - The state of the pointers before this event. This contains the same number 28 | // of pointers, in the same order, as this.currentPointers and this.startPointers. 29 | // 30 | // changedPointers - The pointers that have changed since the last move callback. 31 | // 32 | // event - The event related to the pointer changes. 33 | }, 34 | end(pointer, event, cancelled) { 35 | // Called when a pointer is released. 36 | // 37 | // pointer - The final state of the pointer that ended. This pointer is now absent from 38 | // this.currentPointers and this.startPointers. 39 | // 40 | // event - The event related to this pointer. 41 | // 42 | // cancelled - True if the event was cancelled. Actions are cancelled when the OS takes over 43 | // pointer events, for actions such as scrolling. 44 | }, 45 | // Avoid pointer events in favour of touch and mouse events? 46 | // 47 | // Even if the browser supports pointer events, you may want to force the browser to use 48 | // mouse/touch fallbacks, to work around bugs such as 49 | // https://bugs.webkit.org/show_bug.cgi?id=220196. 50 | // 51 | // The default is false. 52 | avoidPointerEvents: false, 53 | // Use raw pointer updates? Pointer events are usually synchronised to requestAnimationFrame. 54 | // However, if you're targeting a desynchronised canvas, then faster 'raw' updates are better. 55 | // 56 | // This feature only applies to pointer events. The default is false. 57 | rawUpdates: false, 58 | }); 59 | 60 | // State of the tracked pointers when they were pressed/touched. 61 | pointerTracker.startPointers; 62 | // Latest state of the tracked pointers. Contains the same number of pointers, and in the same order 63 | // as this.startPointers. 64 | pointerTracker.currentPointers; 65 | // Remove all listeners. Call this when you're done tracking. 66 | pointerTracker.stop(); 67 | ``` 68 | 69 | ### Pointer 70 | 71 | ```js 72 | const pointer = pointerTracker.currentPointers[0]; 73 | 74 | // x offset from the top of the document 75 | pointer.pageX; 76 | // y offset from the top of the document 77 | pointer.pageY; 78 | // x offset from the top of the viewport 79 | pointer.clientX; 80 | // y offset from the top of the viewport 81 | pointer.clientY; 82 | // Unique ID for this pointer 83 | pointer.id; 84 | // The platform object used to create this Pointer 85 | pointer.nativePointer; 86 | // Returns an expanded set of Pointers for high-resolution inputs. 87 | const pointers = pointer.getCoalesced(); 88 | ``` 89 | 90 | ## Demo 91 | 92 | [A simple painting app](https://pointer-tracker-demo.glitch.me/) ([code](https://glitch.com/edit/#!/pointer-tracker-demo?path=public/index.html)). 93 | 94 | ## Files 95 | 96 | - `lib/index.ts` - Original TypeScript. 97 | - `dist/PointerTracker.mjs` - JS module. Default exports PointerTracker. 98 | - `dist/PointerTracker.js` - UMD JS. Exposes PointerTracker on the global by default. 99 | - `dist/PointerTracker-min.js` - Minified UMD JS. ~900 bytes brotli'd. 100 | -------------------------------------------------------------------------------- /dist/PointerTracker-min.js: -------------------------------------------------------------------------------- 1 | !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PointerTracker=t()}(this,(function(){"use strict";class e{constructor(e){this.id=-1,this.nativePointer=e,this.pageX=e.pageX,this.pageY=e.pageY,this.clientX=e.clientX,this.clientY=e.clientY,self.Touch&&e instanceof Touch?this.id=e.identifier:t(e)&&(this.id=e.pointerId)}getCoalesced(){if("getCoalescedEvents"in this.nativePointer){const t=this.nativePointer.getCoalescedEvents().map(t=>new e(t));if(t.length>0)return t}return[this]}}const t=e=>"pointerId"in e,n=e=>"changedTouches"in e,i=()=>{};return class{constructor(s,{start:r=(()=>!0),move:o=i,end:h=i,rawUpdates:d=!1,avoidPointerEvents:a=!1}={}){this._element=s,this.startPointers=[],this.currentPointers=[],this._excludeFromButtonsCheck=new Set,this._pointerStart=n=>{if(t(n)&&0===n.buttons)this._excludeFromButtonsCheck.add(n.pointerId);else if(!(1&n.buttons))return;const i=new e(n);if(!this.currentPointers.some(e=>e.id===i.id)&&this._triggerPointerStart(i,n))if(t(n)){(n.target&&"setPointerCapture"in n.target?n.target:this._element).setPointerCapture(n.pointerId),this._element.addEventListener(this._rawUpdates?"pointerrawupdate":"pointermove",this._move),this._element.addEventListener("pointerup",this._pointerEnd),this._element.addEventListener("pointercancel",this._pointerEnd)}else window.addEventListener("mousemove",this._move),window.addEventListener("mouseup",this._pointerEnd)},this._touchStart=t=>{for(const n of Array.from(t.changedTouches))this._triggerPointerStart(new e(n),t)},this._move=i=>{if(!(n(i)||t(i)&&this._excludeFromButtonsCheck.has(i.pointerId)||0!==i.buttons))return void this._pointerEnd(i);const s=this.currentPointers.slice(),r=n(i)?Array.from(i.changedTouches).map(t=>new e(t)):[new e(i)],o=[];for(const e of r){const t=this.currentPointers.findIndex(t=>t.id===e.id);-1!==t&&(o.push(e),this.currentPointers[t]=e)}0!==o.length&&this._moveCallback(s,o,i)},this._triggerPointerEnd=(e,t)=>{if(!n(t)&&1&t.buttons)return!1;const i=this.currentPointers.findIndex(t=>t.id===e.id);if(-1===i)return!1;this.currentPointers.splice(i,1),this.startPointers.splice(i,1),this._excludeFromButtonsCheck.delete(e.id);const s=!("mouseup"===t.type||"touchend"===t.type||"pointerup"===t.type);return this._endCallback(e,t,s),!0},this._pointerEnd=n=>{if(this._triggerPointerEnd(new e(n),n))if(t(n)){if(this.currentPointers.length)return;this._element.removeEventListener(this._rawUpdates?"pointerrawupdate":"pointermove",this._move),this._element.removeEventListener("pointerup",this._pointerEnd),this._element.removeEventListener("pointercancel",this._pointerEnd)}else window.removeEventListener("mousemove",this._move),window.removeEventListener("mouseup",this._pointerEnd)},this._touchEnd=t=>{for(const n of Array.from(t.changedTouches))this._triggerPointerEnd(new e(n),t)},this._startCallback=r,this._moveCallback=o,this._endCallback=h,this._rawUpdates=d&&"onpointerrawupdate"in window,self.PointerEvent&&!a?this._element.addEventListener("pointerdown",this._pointerStart):(this._element.addEventListener("mousedown",this._pointerStart),this._element.addEventListener("touchstart",this._touchStart),this._element.addEventListener("touchmove",this._move),this._element.addEventListener("touchend",this._touchEnd),this._element.addEventListener("touchcancel",this._touchEnd))}stop(){this._element.removeEventListener("pointerdown",this._pointerStart),this._element.removeEventListener("mousedown",this._pointerStart),this._element.removeEventListener("touchstart",this._touchStart),this._element.removeEventListener("touchmove",this._move),this._element.removeEventListener("touchend",this._touchEnd),this._element.removeEventListener("touchcancel",this._touchEnd),this._element.removeEventListener(this._rawUpdates?"pointerrawupdate":"pointermove",this._move),this._element.removeEventListener("pointerup",this._pointerEnd),this._element.removeEventListener("pointercancel",this._pointerEnd),window.removeEventListener("mousemove",this._move),window.removeEventListener("mouseup",this._pointerEnd)}_triggerPointerStart(e,t){return!!this._startCallback(e,t)&&(this.currentPointers.push(e),this.startPointers.push(e),!0)}}})); 2 | -------------------------------------------------------------------------------- /dist/index.d.ts: -------------------------------------------------------------------------------- 1 | declare class Pointer { 2 | /** x offset from the top of the document */ 3 | pageX: number; 4 | /** y offset from the top of the document */ 5 | pageY: number; 6 | /** x offset from the top of the viewport */ 7 | clientX: number; 8 | /** y offset from the top of the viewport */ 9 | clientY: number; 10 | /** Unique ID for this pointer */ 11 | id: number; 12 | /** The platform object used to create this Pointer */ 13 | nativePointer: Touch | PointerEvent | MouseEvent; 14 | constructor(nativePointer: Touch | PointerEvent | MouseEvent); 15 | /** 16 | * Returns an expanded set of Pointers for high-resolution inputs. 17 | */ 18 | getCoalesced(): Pointer[]; 19 | } 20 | declare type PointerType = Pointer; 21 | export { PointerType as Pointer }; 22 | export declare type InputEvent = TouchEvent | PointerEvent | MouseEvent; 23 | declare type StartCallback = (pointer: Pointer, event: InputEvent) => boolean; 24 | declare type MoveCallback = (previousPointers: Pointer[], changedPointers: Pointer[], event: InputEvent) => void; 25 | declare type EndCallback = (pointer: Pointer, event: InputEvent, cancelled: boolean) => void; 26 | interface PointerTrackerOptions { 27 | /** 28 | * Called when a pointer is pressed/touched within the element. 29 | * 30 | * @param pointer The new pointer. This pointer isn't included in this.currentPointers or 31 | * this.startPointers yet. 32 | * @param event The event related to this pointer. 33 | * 34 | * @returns Whether you want to track this pointer as it moves. 35 | */ 36 | start?: StartCallback; 37 | /** 38 | * Called when pointers have moved. 39 | * 40 | * @param previousPointers The state of the pointers before this event. This contains the same 41 | * number of pointers, in the same order, as this.currentPointers and this.startPointers. 42 | * @param changedPointers The pointers that have changed since the last move callback. 43 | * @param event The event related to the pointer changes. 44 | */ 45 | move?: MoveCallback; 46 | /** 47 | * Called when a pointer is released. 48 | * 49 | * @param pointer The final state of the pointer that ended. This pointer is now absent from 50 | * this.currentPointers and this.startPointers. 51 | * @param event The event related to this pointer. 52 | * @param cancelled Was the action cancelled? Actions are cancelled when the OS takes over pointer 53 | * events, for actions such as scrolling. 54 | */ 55 | end?: EndCallback; 56 | /** 57 | * Avoid pointer events in favour of touch and mouse events? 58 | * 59 | * Even if the browser supports pointer events, you may want to force the browser to use 60 | * mouse/touch fallbacks, to work around bugs such as 61 | * https://bugs.webkit.org/show_bug.cgi?id=220196. 62 | */ 63 | avoidPointerEvents?: boolean; 64 | /** 65 | * Use raw pointer updates? Pointer events are usually synchronised to requestAnimationFrame. 66 | * However, if you're targeting a desynchronised canvas, then faster 'raw' updates are better. 67 | * 68 | * This feature only applies to pointer events. 69 | */ 70 | rawUpdates?: boolean; 71 | } 72 | /** 73 | * Track pointers across a particular element 74 | */ 75 | export default class PointerTracker { 76 | private _element; 77 | /** 78 | * State of the tracked pointers when they were pressed/touched. 79 | */ 80 | readonly startPointers: Pointer[]; 81 | /** 82 | * Latest state of the tracked pointers. Contains the same number of pointers, and in the same 83 | * order as this.startPointers. 84 | */ 85 | readonly currentPointers: Pointer[]; 86 | private _startCallback; 87 | private _moveCallback; 88 | private _endCallback; 89 | private _rawUpdates; 90 | /** 91 | * Firefox has a bug where touch-based pointer events have a `buttons` of 0, when this shouldn't 92 | * happen. https://bugzilla.mozilla.org/show_bug.cgi?id=1729440 93 | * 94 | * Usually we treat `buttons === 0` as no-longer-pressed. This set allows us to exclude these 95 | * buggy Firefox events. 96 | */ 97 | private _excludeFromButtonsCheck; 98 | /** 99 | * Track pointers across a particular element 100 | * 101 | * @param element Element to monitor. 102 | * @param options 103 | */ 104 | constructor(_element: HTMLElement, { start, move, end, rawUpdates, avoidPointerEvents, }?: PointerTrackerOptions); 105 | /** 106 | * Remove all listeners. 107 | */ 108 | stop(): void; 109 | /** 110 | * Call the start callback for this pointer, and track it if the user wants. 111 | * 112 | * @param pointer Pointer 113 | * @param event Related event 114 | * @returns Whether the pointer is being tracked. 115 | */ 116 | private _triggerPointerStart; 117 | /** 118 | * Listener for mouse/pointer starts. 119 | * 120 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 121 | */ 122 | private _pointerStart; 123 | /** 124 | * Listener for touchstart. 125 | * Only used if the browser doesn't support pointer events. 126 | */ 127 | private _touchStart; 128 | /** 129 | * Listener for pointer/mouse/touch move events. 130 | */ 131 | private _move; 132 | /** 133 | * Call the end callback for this pointer. 134 | * 135 | * @param pointer Pointer 136 | * @param event Related event 137 | */ 138 | private _triggerPointerEnd; 139 | /** 140 | * Listener for mouse/pointer ends. 141 | * 142 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 143 | */ 144 | private _pointerEnd; 145 | /** 146 | * Listener for touchend. 147 | * Only used if the browser doesn't support pointer events. 148 | */ 149 | private _touchEnd; 150 | } 151 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /dist/PointerTracker.mjs: -------------------------------------------------------------------------------- 1 | class Pointer { 2 | constructor(nativePointer) { 3 | /** Unique ID for this pointer */ 4 | this.id = -1; 5 | this.nativePointer = nativePointer; 6 | this.pageX = nativePointer.pageX; 7 | this.pageY = nativePointer.pageY; 8 | this.clientX = nativePointer.clientX; 9 | this.clientY = nativePointer.clientY; 10 | if (self.Touch && nativePointer instanceof Touch) { 11 | this.id = nativePointer.identifier; 12 | } 13 | else if (isPointerEvent(nativePointer)) { 14 | // is PointerEvent 15 | this.id = nativePointer.pointerId; 16 | } 17 | } 18 | /** 19 | * Returns an expanded set of Pointers for high-resolution inputs. 20 | */ 21 | getCoalesced() { 22 | if ('getCoalescedEvents' in this.nativePointer) { 23 | const events = this.nativePointer 24 | .getCoalescedEvents() 25 | .map((p) => new Pointer(p)); 26 | // Firefox sometimes returns an empty list here. I'm not sure it's doing the right thing. 27 | // https://github.com/w3c/pointerevents/issues/409 28 | if (events.length > 0) 29 | return events; 30 | } 31 | return [this]; 32 | } 33 | } 34 | const isPointerEvent = (event) => 'pointerId' in event; 35 | const isTouchEvent = (event) => 'changedTouches' in event; 36 | const noop = () => { }; 37 | /** 38 | * Track pointers across a particular element 39 | */ 40 | class PointerTracker { 41 | /** 42 | * Track pointers across a particular element 43 | * 44 | * @param element Element to monitor. 45 | * @param options 46 | */ 47 | constructor(_element, { start = () => true, move = noop, end = noop, rawUpdates = false, avoidPointerEvents = false, } = {}) { 48 | this._element = _element; 49 | /** 50 | * State of the tracked pointers when they were pressed/touched. 51 | */ 52 | this.startPointers = []; 53 | /** 54 | * Latest state of the tracked pointers. Contains the same number of pointers, and in the same 55 | * order as this.startPointers. 56 | */ 57 | this.currentPointers = []; 58 | /** 59 | * Firefox has a bug where touch-based pointer events have a `buttons` of 0, when this shouldn't 60 | * happen. https://bugzilla.mozilla.org/show_bug.cgi?id=1729440 61 | * 62 | * Usually we treat `buttons === 0` as no-longer-pressed. This set allows us to exclude these 63 | * buggy Firefox events. 64 | */ 65 | this._excludeFromButtonsCheck = new Set(); 66 | /** 67 | * Listener for mouse/pointer starts. 68 | * 69 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 70 | */ 71 | this._pointerStart = (event) => { 72 | if (isPointerEvent(event) && event.buttons === 0) { 73 | // This is the buggy Firefox case. See _excludeFromButtonsCheck. 74 | this._excludeFromButtonsCheck.add(event.pointerId); 75 | } 76 | else if (!(event.buttons & 1 /* LeftMouseOrTouchOrPenDown */)) { 77 | return; 78 | } 79 | const pointer = new Pointer(event); 80 | // If we're already tracking this pointer, ignore this event. 81 | // This happens with mouse events when multiple buttons are pressed. 82 | if (this.currentPointers.some((p) => p.id === pointer.id)) 83 | return; 84 | if (!this._triggerPointerStart(pointer, event)) 85 | return; 86 | // Add listeners for additional events. 87 | // The listeners may already exist, but no harm in adding them again. 88 | if (isPointerEvent(event)) { 89 | const capturingElement = event.target && 'setPointerCapture' in event.target 90 | ? event.target 91 | : this._element; 92 | capturingElement.setPointerCapture(event.pointerId); 93 | this._element.addEventListener(this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move); 94 | this._element.addEventListener('pointerup', this._pointerEnd); 95 | this._element.addEventListener('pointercancel', this._pointerEnd); 96 | } 97 | else { 98 | // MouseEvent 99 | window.addEventListener('mousemove', this._move); 100 | window.addEventListener('mouseup', this._pointerEnd); 101 | } 102 | }; 103 | /** 104 | * Listener for touchstart. 105 | * Only used if the browser doesn't support pointer events. 106 | */ 107 | this._touchStart = (event) => { 108 | for (const touch of Array.from(event.changedTouches)) { 109 | this._triggerPointerStart(new Pointer(touch), event); 110 | } 111 | }; 112 | /** 113 | * Listener for pointer/mouse/touch move events. 114 | */ 115 | this._move = (event) => { 116 | if (!isTouchEvent(event) && 117 | (!isPointerEvent(event) || 118 | !this._excludeFromButtonsCheck.has(event.pointerId)) && 119 | event.buttons === 0 /* None */) { 120 | // This happens in a number of buggy cases where the browser failed to deliver a pointerup 121 | // or pointercancel. If we see the pointer moving without any buttons down, synthesize an end. 122 | // https://github.com/w3c/pointerevents/issues/407 123 | // https://github.com/w3c/pointerevents/issues/408 124 | this._pointerEnd(event); 125 | return; 126 | } 127 | const previousPointers = this.currentPointers.slice(); 128 | const changedPointers = isTouchEvent(event) 129 | ? Array.from(event.changedTouches).map((t) => new Pointer(t)) 130 | : [new Pointer(event)]; 131 | const trackedChangedPointers = []; 132 | for (const pointer of changedPointers) { 133 | const index = this.currentPointers.findIndex((p) => p.id === pointer.id); 134 | if (index === -1) 135 | continue; // Not a pointer we're tracking 136 | trackedChangedPointers.push(pointer); 137 | this.currentPointers[index] = pointer; 138 | } 139 | if (trackedChangedPointers.length === 0) 140 | return; 141 | this._moveCallback(previousPointers, trackedChangedPointers, event); 142 | }; 143 | /** 144 | * Call the end callback for this pointer. 145 | * 146 | * @param pointer Pointer 147 | * @param event Related event 148 | */ 149 | this._triggerPointerEnd = (pointer, event) => { 150 | // Main button still down? 151 | // With mouse events, you get a mouseup per mouse button, so the left button might still be down. 152 | if (!isTouchEvent(event) && 153 | event.buttons & 1 /* LeftMouseOrTouchOrPenDown */) { 154 | return false; 155 | } 156 | const index = this.currentPointers.findIndex((p) => p.id === pointer.id); 157 | // Not a pointer we're interested in? 158 | if (index === -1) 159 | return false; 160 | this.currentPointers.splice(index, 1); 161 | this.startPointers.splice(index, 1); 162 | this._excludeFromButtonsCheck.delete(pointer.id); 163 | // The event.type might be a 'move' event due to workarounds for weird mouse behaviour. 164 | // See _move for details. 165 | const cancelled = !(event.type === 'mouseup' || 166 | event.type === 'touchend' || 167 | event.type === 'pointerup'); 168 | this._endCallback(pointer, event, cancelled); 169 | return true; 170 | }; 171 | /** 172 | * Listener for mouse/pointer ends. 173 | * 174 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 175 | */ 176 | this._pointerEnd = (event) => { 177 | if (!this._triggerPointerEnd(new Pointer(event), event)) 178 | return; 179 | if (isPointerEvent(event)) { 180 | if (this.currentPointers.length) 181 | return; 182 | this._element.removeEventListener(this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move); 183 | this._element.removeEventListener('pointerup', this._pointerEnd); 184 | this._element.removeEventListener('pointercancel', this._pointerEnd); 185 | } 186 | else { 187 | // MouseEvent 188 | window.removeEventListener('mousemove', this._move); 189 | window.removeEventListener('mouseup', this._pointerEnd); 190 | } 191 | }; 192 | /** 193 | * Listener for touchend. 194 | * Only used if the browser doesn't support pointer events. 195 | */ 196 | this._touchEnd = (event) => { 197 | for (const touch of Array.from(event.changedTouches)) { 198 | this._triggerPointerEnd(new Pointer(touch), event); 199 | } 200 | }; 201 | this._startCallback = start; 202 | this._moveCallback = move; 203 | this._endCallback = end; 204 | this._rawUpdates = rawUpdates && 'onpointerrawupdate' in window; 205 | // Add listeners 206 | if (self.PointerEvent && !avoidPointerEvents) { 207 | this._element.addEventListener('pointerdown', this._pointerStart); 208 | } 209 | else { 210 | this._element.addEventListener('mousedown', this._pointerStart); 211 | this._element.addEventListener('touchstart', this._touchStart); 212 | this._element.addEventListener('touchmove', this._move); 213 | this._element.addEventListener('touchend', this._touchEnd); 214 | this._element.addEventListener('touchcancel', this._touchEnd); 215 | } 216 | } 217 | /** 218 | * Remove all listeners. 219 | */ 220 | stop() { 221 | this._element.removeEventListener('pointerdown', this._pointerStart); 222 | this._element.removeEventListener('mousedown', this._pointerStart); 223 | this._element.removeEventListener('touchstart', this._touchStart); 224 | this._element.removeEventListener('touchmove', this._move); 225 | this._element.removeEventListener('touchend', this._touchEnd); 226 | this._element.removeEventListener('touchcancel', this._touchEnd); 227 | this._element.removeEventListener(this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move); 228 | this._element.removeEventListener('pointerup', this._pointerEnd); 229 | this._element.removeEventListener('pointercancel', this._pointerEnd); 230 | window.removeEventListener('mousemove', this._move); 231 | window.removeEventListener('mouseup', this._pointerEnd); 232 | } 233 | /** 234 | * Call the start callback for this pointer, and track it if the user wants. 235 | * 236 | * @param pointer Pointer 237 | * @param event Related event 238 | * @returns Whether the pointer is being tracked. 239 | */ 240 | _triggerPointerStart(pointer, event) { 241 | if (!this._startCallback(pointer, event)) 242 | return false; 243 | this.currentPointers.push(pointer); 244 | this.startPointers.push(pointer); 245 | return true; 246 | } 247 | } 248 | 249 | export { PointerTracker as default }; 250 | -------------------------------------------------------------------------------- /dist/PointerTracker.js: -------------------------------------------------------------------------------- 1 | (function (global, factory) { 2 | typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 3 | typeof define === 'function' && define.amd ? define(factory) : 4 | (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.PointerTracker = factory()); 5 | }(this, (function () { 'use strict'; 6 | 7 | class Pointer { 8 | constructor(nativePointer) { 9 | /** Unique ID for this pointer */ 10 | this.id = -1; 11 | this.nativePointer = nativePointer; 12 | this.pageX = nativePointer.pageX; 13 | this.pageY = nativePointer.pageY; 14 | this.clientX = nativePointer.clientX; 15 | this.clientY = nativePointer.clientY; 16 | if (self.Touch && nativePointer instanceof Touch) { 17 | this.id = nativePointer.identifier; 18 | } 19 | else if (isPointerEvent(nativePointer)) { 20 | // is PointerEvent 21 | this.id = nativePointer.pointerId; 22 | } 23 | } 24 | /** 25 | * Returns an expanded set of Pointers for high-resolution inputs. 26 | */ 27 | getCoalesced() { 28 | if ('getCoalescedEvents' in this.nativePointer) { 29 | const events = this.nativePointer 30 | .getCoalescedEvents() 31 | .map((p) => new Pointer(p)); 32 | // Firefox sometimes returns an empty list here. I'm not sure it's doing the right thing. 33 | // https://github.com/w3c/pointerevents/issues/409 34 | if (events.length > 0) 35 | return events; 36 | } 37 | return [this]; 38 | } 39 | } 40 | const isPointerEvent = (event) => 'pointerId' in event; 41 | const isTouchEvent = (event) => 'changedTouches' in event; 42 | const noop = () => { }; 43 | /** 44 | * Track pointers across a particular element 45 | */ 46 | class PointerTracker { 47 | /** 48 | * Track pointers across a particular element 49 | * 50 | * @param element Element to monitor. 51 | * @param options 52 | */ 53 | constructor(_element, { start = () => true, move = noop, end = noop, rawUpdates = false, avoidPointerEvents = false, } = {}) { 54 | this._element = _element; 55 | /** 56 | * State of the tracked pointers when they were pressed/touched. 57 | */ 58 | this.startPointers = []; 59 | /** 60 | * Latest state of the tracked pointers. Contains the same number of pointers, and in the same 61 | * order as this.startPointers. 62 | */ 63 | this.currentPointers = []; 64 | /** 65 | * Firefox has a bug where touch-based pointer events have a `buttons` of 0, when this shouldn't 66 | * happen. https://bugzilla.mozilla.org/show_bug.cgi?id=1729440 67 | * 68 | * Usually we treat `buttons === 0` as no-longer-pressed. This set allows us to exclude these 69 | * buggy Firefox events. 70 | */ 71 | this._excludeFromButtonsCheck = new Set(); 72 | /** 73 | * Listener for mouse/pointer starts. 74 | * 75 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 76 | */ 77 | this._pointerStart = (event) => { 78 | if (isPointerEvent(event) && event.buttons === 0) { 79 | // This is the buggy Firefox case. See _excludeFromButtonsCheck. 80 | this._excludeFromButtonsCheck.add(event.pointerId); 81 | } 82 | else if (!(event.buttons & 1 /* LeftMouseOrTouchOrPenDown */)) { 83 | return; 84 | } 85 | const pointer = new Pointer(event); 86 | // If we're already tracking this pointer, ignore this event. 87 | // This happens with mouse events when multiple buttons are pressed. 88 | if (this.currentPointers.some((p) => p.id === pointer.id)) 89 | return; 90 | if (!this._triggerPointerStart(pointer, event)) 91 | return; 92 | // Add listeners for additional events. 93 | // The listeners may already exist, but no harm in adding them again. 94 | if (isPointerEvent(event)) { 95 | const capturingElement = event.target && 'setPointerCapture' in event.target 96 | ? event.target 97 | : this._element; 98 | capturingElement.setPointerCapture(event.pointerId); 99 | this._element.addEventListener(this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move); 100 | this._element.addEventListener('pointerup', this._pointerEnd); 101 | this._element.addEventListener('pointercancel', this._pointerEnd); 102 | } 103 | else { 104 | // MouseEvent 105 | window.addEventListener('mousemove', this._move); 106 | window.addEventListener('mouseup', this._pointerEnd); 107 | } 108 | }; 109 | /** 110 | * Listener for touchstart. 111 | * Only used if the browser doesn't support pointer events. 112 | */ 113 | this._touchStart = (event) => { 114 | for (const touch of Array.from(event.changedTouches)) { 115 | this._triggerPointerStart(new Pointer(touch), event); 116 | } 117 | }; 118 | /** 119 | * Listener for pointer/mouse/touch move events. 120 | */ 121 | this._move = (event) => { 122 | if (!isTouchEvent(event) && 123 | (!isPointerEvent(event) || 124 | !this._excludeFromButtonsCheck.has(event.pointerId)) && 125 | event.buttons === 0 /* None */) { 126 | // This happens in a number of buggy cases where the browser failed to deliver a pointerup 127 | // or pointercancel. If we see the pointer moving without any buttons down, synthesize an end. 128 | // https://github.com/w3c/pointerevents/issues/407 129 | // https://github.com/w3c/pointerevents/issues/408 130 | this._pointerEnd(event); 131 | return; 132 | } 133 | const previousPointers = this.currentPointers.slice(); 134 | const changedPointers = isTouchEvent(event) 135 | ? Array.from(event.changedTouches).map((t) => new Pointer(t)) 136 | : [new Pointer(event)]; 137 | const trackedChangedPointers = []; 138 | for (const pointer of changedPointers) { 139 | const index = this.currentPointers.findIndex((p) => p.id === pointer.id); 140 | if (index === -1) 141 | continue; // Not a pointer we're tracking 142 | trackedChangedPointers.push(pointer); 143 | this.currentPointers[index] = pointer; 144 | } 145 | if (trackedChangedPointers.length === 0) 146 | return; 147 | this._moveCallback(previousPointers, trackedChangedPointers, event); 148 | }; 149 | /** 150 | * Call the end callback for this pointer. 151 | * 152 | * @param pointer Pointer 153 | * @param event Related event 154 | */ 155 | this._triggerPointerEnd = (pointer, event) => { 156 | // Main button still down? 157 | // With mouse events, you get a mouseup per mouse button, so the left button might still be down. 158 | if (!isTouchEvent(event) && 159 | event.buttons & 1 /* LeftMouseOrTouchOrPenDown */) { 160 | return false; 161 | } 162 | const index = this.currentPointers.findIndex((p) => p.id === pointer.id); 163 | // Not a pointer we're interested in? 164 | if (index === -1) 165 | return false; 166 | this.currentPointers.splice(index, 1); 167 | this.startPointers.splice(index, 1); 168 | this._excludeFromButtonsCheck.delete(pointer.id); 169 | // The event.type might be a 'move' event due to workarounds for weird mouse behaviour. 170 | // See _move for details. 171 | const cancelled = !(event.type === 'mouseup' || 172 | event.type === 'touchend' || 173 | event.type === 'pointerup'); 174 | this._endCallback(pointer, event, cancelled); 175 | return true; 176 | }; 177 | /** 178 | * Listener for mouse/pointer ends. 179 | * 180 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 181 | */ 182 | this._pointerEnd = (event) => { 183 | if (!this._triggerPointerEnd(new Pointer(event), event)) 184 | return; 185 | if (isPointerEvent(event)) { 186 | if (this.currentPointers.length) 187 | return; 188 | this._element.removeEventListener(this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move); 189 | this._element.removeEventListener('pointerup', this._pointerEnd); 190 | this._element.removeEventListener('pointercancel', this._pointerEnd); 191 | } 192 | else { 193 | // MouseEvent 194 | window.removeEventListener('mousemove', this._move); 195 | window.removeEventListener('mouseup', this._pointerEnd); 196 | } 197 | }; 198 | /** 199 | * Listener for touchend. 200 | * Only used if the browser doesn't support pointer events. 201 | */ 202 | this._touchEnd = (event) => { 203 | for (const touch of Array.from(event.changedTouches)) { 204 | this._triggerPointerEnd(new Pointer(touch), event); 205 | } 206 | }; 207 | this._startCallback = start; 208 | this._moveCallback = move; 209 | this._endCallback = end; 210 | this._rawUpdates = rawUpdates && 'onpointerrawupdate' in window; 211 | // Add listeners 212 | if (self.PointerEvent && !avoidPointerEvents) { 213 | this._element.addEventListener('pointerdown', this._pointerStart); 214 | } 215 | else { 216 | this._element.addEventListener('mousedown', this._pointerStart); 217 | this._element.addEventListener('touchstart', this._touchStart); 218 | this._element.addEventListener('touchmove', this._move); 219 | this._element.addEventListener('touchend', this._touchEnd); 220 | this._element.addEventListener('touchcancel', this._touchEnd); 221 | } 222 | } 223 | /** 224 | * Remove all listeners. 225 | */ 226 | stop() { 227 | this._element.removeEventListener('pointerdown', this._pointerStart); 228 | this._element.removeEventListener('mousedown', this._pointerStart); 229 | this._element.removeEventListener('touchstart', this._touchStart); 230 | this._element.removeEventListener('touchmove', this._move); 231 | this._element.removeEventListener('touchend', this._touchEnd); 232 | this._element.removeEventListener('touchcancel', this._touchEnd); 233 | this._element.removeEventListener(this._rawUpdates ? 'pointerrawupdate' : 'pointermove', this._move); 234 | this._element.removeEventListener('pointerup', this._pointerEnd); 235 | this._element.removeEventListener('pointercancel', this._pointerEnd); 236 | window.removeEventListener('mousemove', this._move); 237 | window.removeEventListener('mouseup', this._pointerEnd); 238 | } 239 | /** 240 | * Call the start callback for this pointer, and track it if the user wants. 241 | * 242 | * @param pointer Pointer 243 | * @param event Related event 244 | * @returns Whether the pointer is being tracked. 245 | */ 246 | _triggerPointerStart(pointer, event) { 247 | if (!this._startCallback(pointer, event)) 248 | return false; 249 | this.currentPointers.push(pointer); 250 | this.startPointers.push(pointer); 251 | return true; 252 | } 253 | } 254 | 255 | return PointerTracker; 256 | 257 | }))); 258 | -------------------------------------------------------------------------------- /lib/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2020 Google Inc. All Rights Reserved. 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 | * http://www.apache.org/licenses/LICENSE-2.0 7 | * Unless required by applicable law or agreed to in writing, software 8 | * distributed under the License is distributed on an "AS IS" BASIS, 9 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 10 | * See the License for the specific language governing permissions and 11 | * limitations under the License. 12 | */ 13 | const enum Buttons { 14 | None, 15 | LeftMouseOrTouchOrPenDown, 16 | } 17 | 18 | class Pointer { 19 | /** x offset from the top of the document */ 20 | pageX: number; 21 | /** y offset from the top of the document */ 22 | pageY: number; 23 | /** x offset from the top of the viewport */ 24 | clientX: number; 25 | /** y offset from the top of the viewport */ 26 | clientY: number; 27 | /** Unique ID for this pointer */ 28 | id: number = -1; 29 | /** The platform object used to create this Pointer */ 30 | nativePointer: Touch | PointerEvent | MouseEvent; 31 | 32 | constructor(nativePointer: Touch | PointerEvent | MouseEvent) { 33 | this.nativePointer = nativePointer; 34 | this.pageX = nativePointer.pageX; 35 | this.pageY = nativePointer.pageY; 36 | this.clientX = nativePointer.clientX; 37 | this.clientY = nativePointer.clientY; 38 | 39 | if (self.Touch && nativePointer instanceof Touch) { 40 | this.id = nativePointer.identifier; 41 | } else if (isPointerEvent(nativePointer)) { 42 | // is PointerEvent 43 | this.id = nativePointer.pointerId; 44 | } 45 | } 46 | 47 | /** 48 | * Returns an expanded set of Pointers for high-resolution inputs. 49 | */ 50 | getCoalesced(): Pointer[] { 51 | if ('getCoalescedEvents' in this.nativePointer) { 52 | const events = this.nativePointer 53 | .getCoalescedEvents() 54 | .map((p) => new Pointer(p)); 55 | // Firefox sometimes returns an empty list here. I'm not sure it's doing the right thing. 56 | // https://github.com/w3c/pointerevents/issues/409 57 | if (events.length > 0) return events; 58 | // Otherwise, Firefox falls through… 59 | } 60 | return [this]; 61 | } 62 | } 63 | 64 | // Export the typing, but keep the class private. 65 | type PointerType = Pointer; 66 | export { PointerType as Pointer }; 67 | 68 | const isPointerEvent = (event: any): event is PointerEvent => 69 | 'pointerId' in event; 70 | 71 | const isTouchEvent = (event: any): event is TouchEvent => 72 | 'changedTouches' in event; 73 | 74 | const noop = () => {}; 75 | 76 | export type InputEvent = TouchEvent | PointerEvent | MouseEvent; 77 | type StartCallback = (pointer: Pointer, event: InputEvent) => boolean; 78 | type MoveCallback = ( 79 | previousPointers: Pointer[], 80 | changedPointers: Pointer[], 81 | event: InputEvent, 82 | ) => void; 83 | type EndCallback = ( 84 | pointer: Pointer, 85 | event: InputEvent, 86 | cancelled: boolean, 87 | ) => void; 88 | 89 | interface PointerTrackerOptions { 90 | /** 91 | * Called when a pointer is pressed/touched within the element. 92 | * 93 | * @param pointer The new pointer. This pointer isn't included in this.currentPointers or 94 | * this.startPointers yet. 95 | * @param event The event related to this pointer. 96 | * 97 | * @returns Whether you want to track this pointer as it moves. 98 | */ 99 | start?: StartCallback; 100 | /** 101 | * Called when pointers have moved. 102 | * 103 | * @param previousPointers The state of the pointers before this event. This contains the same 104 | * number of pointers, in the same order, as this.currentPointers and this.startPointers. 105 | * @param changedPointers The pointers that have changed since the last move callback. 106 | * @param event The event related to the pointer changes. 107 | */ 108 | move?: MoveCallback; 109 | /** 110 | * Called when a pointer is released. 111 | * 112 | * @param pointer The final state of the pointer that ended. This pointer is now absent from 113 | * this.currentPointers and this.startPointers. 114 | * @param event The event related to this pointer. 115 | * @param cancelled Was the action cancelled? Actions are cancelled when the OS takes over pointer 116 | * events, for actions such as scrolling. 117 | */ 118 | end?: EndCallback; 119 | /** 120 | * Avoid pointer events in favour of touch and mouse events? 121 | * 122 | * Even if the browser supports pointer events, you may want to force the browser to use 123 | * mouse/touch fallbacks, to work around bugs such as 124 | * https://bugs.webkit.org/show_bug.cgi?id=220196. 125 | */ 126 | avoidPointerEvents?: boolean; 127 | /** 128 | * Use raw pointer updates? Pointer events are usually synchronised to requestAnimationFrame. 129 | * However, if you're targeting a desynchronised canvas, then faster 'raw' updates are better. 130 | * 131 | * This feature only applies to pointer events. 132 | */ 133 | rawUpdates?: boolean; 134 | } 135 | 136 | /** 137 | * Track pointers across a particular element 138 | */ 139 | export default class PointerTracker { 140 | /** 141 | * State of the tracked pointers when they were pressed/touched. 142 | */ 143 | readonly startPointers: Pointer[] = []; 144 | /** 145 | * Latest state of the tracked pointers. Contains the same number of pointers, and in the same 146 | * order as this.startPointers. 147 | */ 148 | readonly currentPointers: Pointer[] = []; 149 | 150 | private _startCallback: StartCallback; 151 | private _moveCallback: MoveCallback; 152 | private _endCallback: EndCallback; 153 | private _rawUpdates: boolean; 154 | 155 | /** 156 | * Firefox has a bug where touch-based pointer events have a `buttons` of 0, when this shouldn't 157 | * happen. https://bugzilla.mozilla.org/show_bug.cgi?id=1729440 158 | * 159 | * Usually we treat `buttons === 0` as no-longer-pressed. This set allows us to exclude these 160 | * buggy Firefox events. 161 | */ 162 | private _excludeFromButtonsCheck = new Set(); 163 | 164 | /** 165 | * Track pointers across a particular element 166 | * 167 | * @param element Element to monitor. 168 | * @param options 169 | */ 170 | constructor( 171 | private _element: HTMLElement, 172 | { 173 | start = () => true, 174 | move = noop, 175 | end = noop, 176 | rawUpdates = false, 177 | avoidPointerEvents = false, 178 | }: PointerTrackerOptions = {}, 179 | ) { 180 | this._startCallback = start; 181 | this._moveCallback = move; 182 | this._endCallback = end; 183 | this._rawUpdates = rawUpdates && 'onpointerrawupdate' in window; 184 | 185 | // Add listeners 186 | if (self.PointerEvent && !avoidPointerEvents) { 187 | this._element.addEventListener('pointerdown', this._pointerStart); 188 | } else { 189 | this._element.addEventListener('mousedown', this._pointerStart); 190 | this._element.addEventListener('touchstart', this._touchStart); 191 | this._element.addEventListener('touchmove', this._move); 192 | this._element.addEventListener('touchend', this._touchEnd); 193 | this._element.addEventListener('touchcancel', this._touchEnd); 194 | } 195 | } 196 | 197 | /** 198 | * Remove all listeners. 199 | */ 200 | stop() { 201 | this._element.removeEventListener('pointerdown', this._pointerStart); 202 | this._element.removeEventListener('mousedown', this._pointerStart); 203 | this._element.removeEventListener('touchstart', this._touchStart); 204 | this._element.removeEventListener('touchmove', this._move); 205 | this._element.removeEventListener('touchend', this._touchEnd); 206 | this._element.removeEventListener('touchcancel', this._touchEnd); 207 | this._element.removeEventListener( 208 | this._rawUpdates ? 'pointerrawupdate' : 'pointermove', 209 | this._move, 210 | ); 211 | this._element.removeEventListener('pointerup', this._pointerEnd); 212 | this._element.removeEventListener('pointercancel', this._pointerEnd); 213 | window.removeEventListener('mousemove', this._move); 214 | window.removeEventListener('mouseup', this._pointerEnd); 215 | } 216 | 217 | /** 218 | * Call the start callback for this pointer, and track it if the user wants. 219 | * 220 | * @param pointer Pointer 221 | * @param event Related event 222 | * @returns Whether the pointer is being tracked. 223 | */ 224 | private _triggerPointerStart(pointer: Pointer, event: InputEvent): boolean { 225 | if (!this._startCallback(pointer, event)) return false; 226 | this.currentPointers.push(pointer); 227 | this.startPointers.push(pointer); 228 | return true; 229 | } 230 | 231 | /** 232 | * Listener for mouse/pointer starts. 233 | * 234 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 235 | */ 236 | private _pointerStart = (event: PointerEvent | MouseEvent) => { 237 | if (isPointerEvent(event) && event.buttons === 0) { 238 | // This is the buggy Firefox case. See _excludeFromButtonsCheck. 239 | this._excludeFromButtonsCheck.add(event.pointerId); 240 | } else if (!(event.buttons & Buttons.LeftMouseOrTouchOrPenDown)) { 241 | return; 242 | } 243 | const pointer = new Pointer(event); 244 | // If we're already tracking this pointer, ignore this event. 245 | // This happens with mouse events when multiple buttons are pressed. 246 | if (this.currentPointers.some((p) => p.id === pointer.id)) return; 247 | 248 | if (!this._triggerPointerStart(pointer, event)) return; 249 | 250 | // Add listeners for additional events. 251 | // The listeners may already exist, but no harm in adding them again. 252 | if (isPointerEvent(event)) { 253 | const capturingElement = 254 | event.target && 'setPointerCapture' in event.target 255 | ? event.target 256 | : this._element; 257 | 258 | capturingElement.setPointerCapture(event.pointerId); 259 | this._element.addEventListener( 260 | this._rawUpdates ? 'pointerrawupdate' : 'pointermove', 261 | this._move, 262 | ); 263 | this._element.addEventListener('pointerup', this._pointerEnd); 264 | this._element.addEventListener('pointercancel', this._pointerEnd); 265 | } else { 266 | // MouseEvent 267 | window.addEventListener('mousemove', this._move); 268 | window.addEventListener('mouseup', this._pointerEnd); 269 | } 270 | }; 271 | 272 | /** 273 | * Listener for touchstart. 274 | * Only used if the browser doesn't support pointer events. 275 | */ 276 | private _touchStart = (event: TouchEvent) => { 277 | for (const touch of Array.from(event.changedTouches)) { 278 | this._triggerPointerStart(new Pointer(touch), event); 279 | } 280 | }; 281 | 282 | /** 283 | * Listener for pointer/mouse/touch move events. 284 | */ 285 | private _move = (event: PointerEvent | MouseEvent | TouchEvent) => { 286 | if ( 287 | !isTouchEvent(event) && 288 | (!isPointerEvent(event) || 289 | !this._excludeFromButtonsCheck.has(event.pointerId)) && 290 | event.buttons === Buttons.None 291 | ) { 292 | // This happens in a number of buggy cases where the browser failed to deliver a pointerup 293 | // or pointercancel. If we see the pointer moving without any buttons down, synthesize an end. 294 | // https://github.com/w3c/pointerevents/issues/407 295 | // https://github.com/w3c/pointerevents/issues/408 296 | this._pointerEnd(event); 297 | return; 298 | } 299 | const previousPointers = this.currentPointers.slice(); 300 | const changedPointers = isTouchEvent(event) 301 | ? Array.from(event.changedTouches).map((t) => new Pointer(t)) 302 | : [new Pointer(event)]; 303 | const trackedChangedPointers = []; 304 | 305 | for (const pointer of changedPointers) { 306 | const index = this.currentPointers.findIndex((p) => p.id === pointer.id); 307 | if (index === -1) continue; // Not a pointer we're tracking 308 | trackedChangedPointers.push(pointer); 309 | this.currentPointers[index] = pointer; 310 | } 311 | 312 | if (trackedChangedPointers.length === 0) return; 313 | 314 | this._moveCallback(previousPointers, trackedChangedPointers, event); 315 | }; 316 | 317 | /** 318 | * Call the end callback for this pointer. 319 | * 320 | * @param pointer Pointer 321 | * @param event Related event 322 | */ 323 | private _triggerPointerEnd = ( 324 | pointer: Pointer, 325 | event: InputEvent, 326 | ): boolean => { 327 | // Main button still down? 328 | // With mouse events, you get a mouseup per mouse button, so the left button might still be down. 329 | if ( 330 | !isTouchEvent(event) && 331 | event.buttons & Buttons.LeftMouseOrTouchOrPenDown 332 | ) { 333 | return false; 334 | } 335 | const index = this.currentPointers.findIndex((p) => p.id === pointer.id); 336 | // Not a pointer we're interested in? 337 | if (index === -1) return false; 338 | 339 | this.currentPointers.splice(index, 1); 340 | this.startPointers.splice(index, 1); 341 | this._excludeFromButtonsCheck.delete(pointer.id); 342 | 343 | // The event.type might be a 'move' event due to workarounds for weird mouse behaviour. 344 | // See _move for details. 345 | const cancelled = !( 346 | event.type === 'mouseup' || 347 | event.type === 'touchend' || 348 | event.type === 'pointerup' 349 | ); 350 | 351 | this._endCallback(pointer, event, cancelled); 352 | return true; 353 | }; 354 | 355 | /** 356 | * Listener for mouse/pointer ends. 357 | * 358 | * @param event This will only be a MouseEvent if the browser doesn't support pointer events. 359 | */ 360 | private _pointerEnd = (event: PointerEvent | MouseEvent) => { 361 | if (!this._triggerPointerEnd(new Pointer(event), event)) return; 362 | 363 | if (isPointerEvent(event)) { 364 | if (this.currentPointers.length) return; 365 | this._element.removeEventListener( 366 | this._rawUpdates ? 'pointerrawupdate' : 'pointermove', 367 | this._move, 368 | ); 369 | this._element.removeEventListener('pointerup', this._pointerEnd); 370 | this._element.removeEventListener('pointercancel', this._pointerEnd); 371 | } else { 372 | // MouseEvent 373 | window.removeEventListener('mousemove', this._move); 374 | window.removeEventListener('mouseup', this._pointerEnd); 375 | } 376 | }; 377 | 378 | /** 379 | * Listener for touchend. 380 | * Only used if the browser doesn't support pointer events. 381 | */ 382 | private _touchEnd = (event: TouchEvent) => { 383 | for (const touch of Array.from(event.changedTouches)) { 384 | this._triggerPointerEnd(new Pointer(touch), event); 385 | } 386 | }; 387 | } 388 | --------------------------------------------------------------------------------