| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @emails react-core |
| 8 | */ |
| 9 | |
| 10 | 'use strict'; |
| 11 | |
| 12 | /** |
| 13 | * Touch events state machine. |
| 14 | * |
| 15 | * Keeps track of the active pointers and allows them to be reflected in touch events. |
| 16 | */ |
| 17 | |
| 18 | const activeTouches = new Map(); |
| 19 | |
| 20 | export function addTouch(touch) { |
| 21 | const identifier = touch.identifier; |
| 22 | const target = touch.target; |
| 23 | if (!activeTouches.has(target)) { |
| 24 | activeTouches.set(target, new Map()); |
| 25 | } |
| 26 | if (activeTouches.get(target).get(identifier)) { |
| 27 | // Do not allow existing touches to be overwritten |
| 28 | console.error( |
| 29 | 'Touch with identifier %s already exists. Did not record touch start.', |
| 30 | identifier, |
| 31 | ); |
| 32 | } else { |
| 33 | activeTouches.get(target).set(identifier, touch); |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | export function updateTouch(touch) { |
| 38 | const identifier = touch.identifier; |
| 39 | const target = touch.target; |
| 40 | if (activeTouches.get(target) != null) { |
| 41 | activeTouches.get(target).set(identifier, touch); |
| 42 | } else { |
| 43 | console.error( |
| 44 | 'Touch with identifier %s does not exist. Cannot record touch move without a touch start.', |
| 45 | identifier, |
| 46 | ); |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | export function removeTouch(touch) { |
| 51 | const identifier = touch.identifier; |
| 52 | const target = touch.target; |
| 53 | if (activeTouches.get(target) != null) { |
| 54 | if (activeTouches.get(target).has(identifier)) { |
| 55 | activeTouches.get(target).delete(identifier); |
| 56 | } else { |
| 57 | console.error( |
| 58 | 'Touch with identifier %s does not exist. Cannot record touch end without a touch start.', |
| 59 | identifier, |
| 60 | ); |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | export function getTouches() { |
| 66 | const touches = []; |
| 67 | activeTouches.forEach((_, target) => { |
| 68 | touches.push(...getTargetTouches(target)); |
| 69 | }); |
| 70 | return touches; |
| 71 | } |
| 72 | |
| 73 | export function getTargetTouches(target) { |
| 74 | if (activeTouches.get(target) != null) { |
| 75 | return Array.from(activeTouches.get(target).values()); |
| 76 | } |
| 77 | return []; |
| 78 | } |
| 79 | |
| 80 | export function clear() { |
| 81 | activeTouches.clear(); |
| 82 | } |