From 29882d50a6edeb27b3637ccb76e3958b964e1437 Mon Sep 17 00:00:00 2001 From: Dominic Gannaway Date: Wed, 16 Oct 2019 11:40:15 +0100 Subject: [PATCH] [react-interactions] Allow event.preventDefault on LegacyPress responder [react-interactions] Allow event.preventDefault on LegacyPress responder --- .../events/src/dom/PressLegacy.js | 17 ++++++++--------- .../dom/__tests__/PressLegacy-test.internal.js | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/packages/react-interactions/events/src/dom/PressLegacy.js b/packages/react-interactions/events/src/dom/PressLegacy.js index d8291750eb6cf..85c7696f8f364 100644 --- a/packages/react-interactions/events/src/dom/PressLegacy.js +++ b/packages/react-interactions/events/src/dom/PressLegacy.js @@ -157,9 +157,10 @@ function createPressEvent( let ctrlKey = false; let metaKey = false; let shiftKey = false; + let nativeEvent; if (event) { - const nativeEvent = (event.nativeEvent: any); + nativeEvent = (event.nativeEvent: any); ({altKey, ctrlKey, metaKey, shiftKey} = nativeEvent); // Only check for one property, checking for all of them is costly. We can assume // if clientX exists, so do the rest. @@ -169,7 +170,7 @@ function createPressEvent( ({clientX, clientY, pageX, pageY, screenX, screenY} = eventObject); } } - return { + const pressEvent = { altKey, buttons: state.buttons, clientX, @@ -189,13 +190,10 @@ function createPressEvent( x: clientX, y: clientY, preventDefault() { - // NO-OP, we should remove this in the future - if (__DEV__) { - warning( - false, - 'preventDefault is not available on event objects created from event responder modules (React Flare). ' + - 'Try wrapping in a conditional, i.e. `if (event.type !== "press") { event.preventDefault() }`', - ); + state.shouldPreventClick = true; + if (nativeEvent) { + pressEvent.defaultPrevented = true; + nativeEvent.preventDefault(); } }, stopPropagation() { @@ -209,6 +207,7 @@ function createPressEvent( } }, }; + return pressEvent; } function dispatchEvent( diff --git a/packages/react-interactions/events/src/dom/__tests__/PressLegacy-test.internal.js b/packages/react-interactions/events/src/dom/__tests__/PressLegacy-test.internal.js index cca2a4333bca4..03a65ea192d79 100644 --- a/packages/react-interactions/events/src/dom/__tests__/PressLegacy-test.internal.js +++ b/packages/react-interactions/events/src/dom/__tests__/PressLegacy-test.internal.js @@ -1131,4 +1131,21 @@ describe.each(environmentTable)('Press responder', hasPointerEvents => { target.pointerup(); target.pointerdown(); }); + + it('event.preventDefault works as expected', () => { + const onPress = jest.fn(e => e.preventDefault()); + const preventDefault = jest.fn(); + const buttonRef = React.createRef(); + + const Component = () => { + const listener = usePress({onPress}); + return