Skip to content

Commit 8abf243

Browse files
authored
Ensure touch events are properly handled for pageX and pageY (#15587)
1 parent c7398f3 commit 8abf243

2 files changed

Lines changed: 563 additions & 181 deletions

File tree

packages/react-events/src/Press.js

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -190,14 +190,13 @@ function dispatchLongPressChangeEvent(
190190

191191
function activate(event, context, props, state) {
192192
const nativeEvent: any = event.nativeEvent;
193-
const pageX = nativeEvent.pageX;
194-
const pageY = nativeEvent.pageY;
193+
const {x, y} = getEventPageCoords(nativeEvent);
195194
const wasActivePressed = state.isActivePressed;
196195
state.isActivePressed = true;
197-
if (pageX != null && pageY != null) {
196+
if (x !== null && y !== null) {
198197
state.activationPosition = {
199-
pageX: nativeEvent.pageX,
200-
pageY: nativeEvent.pageY,
198+
pageX: x,
199+
pageY: y,
201200
};
202201
}
203202

@@ -402,12 +401,39 @@ function calculateResponderRegion(target: Element, props: PressProps) {
402401
};
403402
}
404403

404+
function isTouchEvent(nativeEvent: Event): boolean {
405+
return Array.isArray((nativeEvent: any).changedTouches);
406+
}
407+
408+
function getTouchFromPressEvent(nativeEvent: TouchEvent): Touch {
409+
const {changedTouches, touches} = nativeEvent;
410+
return changedTouches.length > 0
411+
? changedTouches[0]
412+
: touches.length > 0
413+
? touches[0]
414+
: (nativeEvent: any);
415+
}
416+
417+
function getEventPageCoords(
418+
nativeEvent: Event,
419+
): {x: null | number, y: null | number} {
420+
let eventObject = (nativeEvent: any);
421+
if (isTouchEvent(eventObject)) {
422+
eventObject = getTouchFromPressEvent(eventObject);
423+
}
424+
const pageX = eventObject.pageX;
425+
const pageY = eventObject.pageY;
426+
return {
427+
x: pageX != null ? pageX : null,
428+
y: pageY != null ? pageY : null,
429+
};
430+
}
431+
405432
function isPressWithinResponderRegion(
406433
nativeEvent: $PropertyType<ReactResponderEvent, 'nativeEvent'>,
407434
state: PressState,
408435
): boolean {
409436
const {responderRegionOnActivation, responderRegionOnDeactivation} = state;
410-
const event = (nativeEvent: any);
411437
let left, top, right, bottom;
412438

413439
if (responderRegionOnActivation != null) {
@@ -423,16 +449,16 @@ function isPressWithinResponderRegion(
423449
bottom = Math.max(bottom, responderRegionOnDeactivation.bottom);
424450
}
425451
}
452+
const {x, y} = getEventPageCoords(((nativeEvent: any): Event));
426453

427454
return (
428455
left != null &&
429456
right != null &&
430457
top != null &&
431458
bottom != null &&
432-
(event.pageX >= left &&
433-
event.pageX <= right &&
434-
event.pageY >= top &&
435-
event.pageY <= bottom)
459+
x !== null &&
460+
y !== null &&
461+
(x >= left && x <= right && y >= top && y <= bottom)
436462
);
437463
}
438464

0 commit comments

Comments
 (0)