Skip to content

Commit

Permalink
React events: add a test for focusable descendants (#15457)
Browse files Browse the repository at this point in the history
  • Loading branch information
necolas authored Apr 22, 2019
1 parent 0a8da33 commit 59c7aef
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
15 changes: 6 additions & 9 deletions packages/react-events/src/Focus.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type {
ReactResponderContext,
} from 'shared/ReactTypes';
import {REACT_EVENT_COMPONENT_TYPE} from 'shared/ReactSymbols';
import {getEventCurrentTarget} from './utils.js';

const CAPTURE_PHASE = 2;

Expand Down Expand Up @@ -120,21 +121,17 @@ const FocusResponder = {
if (phase === CAPTURE_PHASE) {
return false;
}

switch (type) {
case 'focus': {
if (!state.isFocused) {
// Limit focus events to the direct child of the event component.
// Browser focus is not expected to bubble.
let currentTarget = (target: any);
if (
currentTarget.parentNode &&
context.isTargetWithinEventComponent(currentTarget.parentNode)
) {
break;
state.focusTarget = getEventCurrentTarget(event, context);
if (state.focusTarget === target) {
dispatchFocusInEvents(context, props, state);
state.isFocused = true;
}
state.focusTarget = currentTarget;
dispatchFocusInEvents(context, props, state);
state.isFocused = true;
}
break;
}
Expand Down
13 changes: 11 additions & 2 deletions packages/react-events/src/__tests__/Focus-test.internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,17 @@ describe('Focus event responder', () => {
});

describe('onFocus', () => {
let onFocus, ref;
let onFocus, ref, innerRef;

beforeEach(() => {
onFocus = jest.fn();
ref = React.createRef();
innerRef = React.createRef();
const element = (
<Focus onFocus={onFocus}>
<div ref={ref} />
<div ref={ref}>
<a ref={innerRef} />
</div>
</Focus>
);
ReactDOM.render(element, container);
Expand All @@ -79,6 +82,12 @@ describe('Focus event responder', () => {
ref.current.dispatchEvent(createFocusEvent('focus'));
expect(onFocus).toHaveBeenCalledTimes(1);
});

it('is not called if descendants of target receive focus', () => {
const target = innerRef.current;
target.dispatchEvent(createFocusEvent('focus'));
expect(onFocus).not.toBeCalled();
});
});

describe('onFocusChange', () => {
Expand Down

0 comments on commit 59c7aef

Please sign in to comment.