Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[react-interactions] Allow event.preventDefault on LegacyPress responder #17113

Merged
merged 1 commit into from
Oct 17, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 8 additions & 9 deletions packages/react-interactions/events/src/dom/PressLegacy.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -169,7 +170,7 @@ function createPressEvent(
({clientX, clientY, pageX, pageY, screenX, screenY} = eventObject);
}
}
return {
const pressEvent = {
altKey,
buttons: state.buttons,
clientX,
Expand All @@ -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() {
Expand All @@ -209,6 +207,7 @@ function createPressEvent(
}
},
};
return pressEvent;
}

function dispatchEvent(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 <button ref={buttonRef} listeners={listener} />;
};
ReactDOM.render(<Component />, container);

const target = createEventTarget(buttonRef.current);
target.pointerdown();
target.pointerup({preventDefault});
expect(preventDefault).toBeCalled();
});
});