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

Autocomplete: Implement and use focus outside utility for managing dismissal #3235

Merged
merged 2 commits into from
Nov 9, 2017
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
15 changes: 11 additions & 4 deletions components/autocomplete/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
* External dependencies
*/
import classnames from 'classnames';
import { escapeRegExp, find, filter, map } from 'lodash';
import { escapeRegExp, find, filter, map, flowRight } from 'lodash';

/**
* WordPress dependencies
Expand All @@ -14,11 +14,12 @@ import { keycodes } from '@wordpress/utils';
* Internal dependencies
*/
import './style.scss';
import withFocusOutside from '../higher-order/with-focus-outside';
import Button from '../button';
import Popover from '../popover';
import withInstanceId from '../higher-order/with-instance-id';

const { ENTER, ESCAPE, UP, DOWN, LEFT, RIGHT, TAB } = keycodes;
const { ENTER, ESCAPE, UP, DOWN, LEFT, RIGHT } = keycodes;

/**
* Recursively select the firstChild until hitting a leaf node.
Expand Down Expand Up @@ -136,6 +137,10 @@ export class Autocomplete extends Component {
this.setState( this.constructor.getInitialState() );
}

handleFocusOutside() {
this.reset();
}

// this method is separate so it can be overrided in tests
getCursor( container ) {
const selection = window.getSelection();
Expand Down Expand Up @@ -333,7 +338,6 @@ export class Autocomplete extends Component {

case LEFT:
case RIGHT:
case TAB:
this.reset();
return;

Expand Down Expand Up @@ -436,4 +440,7 @@ export class Autocomplete extends Component {
}
}

export default withInstanceId( Autocomplete );
export default flowRight( [
withInstanceId,
withFocusOutside,
] )( Autocomplete );
22 changes: 18 additions & 4 deletions components/autocomplete/test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,12 @@ import { keycodes } from '@wordpress/utils';
/**
* Internal dependencies
*/
import { Autocomplete } from '../';
import EnhancedAutocomplete, { Autocomplete } from '../';

const { ENTER, ESCAPE, UP, DOWN, SPACE } = keycodes;

jest.useFakeTimers();

class FakeEditor extends Component {
// we want to change the editor contents manually so don't let react update it
shouldComponentUpdate() {
Expand All @@ -35,9 +37,9 @@ class FakeEditor extends Component {
}
}

function makeAutocompleter( completers ) {
function makeAutocompleter( completers, AutocompleteComponent = Autocomplete ) {
return mount(
<Autocomplete instanceId="1" completers={ completers }>{
<AutocompleteComponent instanceId="1" completers={ completers }>{
( { isExpanded, listBoxId, activeId } ) => (
<FakeEditor
aria-autocomplete="list"
Expand All @@ -46,7 +48,7 @@ function makeAutocompleter( completers ) {
aria-activedescendant={ activeId }
/>
)
}</Autocomplete>
}</AutocompleteComponent>
);
}

Expand Down Expand Up @@ -420,6 +422,18 @@ describe( 'Autocomplete', () => {
} );
} );

it( 'closes by blur', () => {
jest.spyOn( Autocomplete.prototype, 'handleFocusOutside' );

const wrapper = makeAutocompleter( [], EnhancedAutocomplete );
simulateInput( wrapper, [ par( tx( '/' ) ) ] );
wrapper.find( '.fake-editor' ).simulate( 'blur' );

jest.runAllTimers();

expect( Autocomplete.prototype.handleFocusOutside ).toHaveBeenCalled();
} );

it( 'selects by enter', ( done ) => {
const onSelect = jest.fn();
const wrapper = makeAutocompleter( [ { ...slashCompleter, onSelect } ] );
Expand Down
30 changes: 30 additions & 0 deletions components/higher-order/with-focus-outside/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# withFocusOutside

`withFocusOutside` is a React [higher-order component](https://facebook.github.io/react/docs/higher-order-components.html) to enable behavior to occur when focus leaves an element. Since a `blur` event will fire in React even when focus transitions to another element in the same context, this higher-order component encapsulates the logic necessary to determine if focus has truly left the element.

## Usage

Wrap your original component with `withFocusOutside`, defining a `handleFocusOutside` instance method on the component class.

__Note:__ `withFocusOutside` must only be used to wrap the `Component` class.

```jsx
const EnhancedComponent = withFocusOutside(
class extends Component {
handleFocusOutside() {
this.props.onFocusOutside();
}

render() {
return (
<div>
<input />
<input />
</div>
);
}
}
);
```

In the above example, the `handleFocusOutside` function is only called if focus leaves the element, and not if transitioning focus between the two inputs.
58 changes: 58 additions & 0 deletions components/higher-order/with-focus-outside/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';

function withFocusOutside( WrappedComponent ) {
return class extends Component {
constructor() {
super( ...arguments );

this.bindNode = this.bindNode.bind( this );
this.cancelBlurCheck = this.cancelBlurCheck.bind( this );
this.queueBlurCheck = this.queueBlurCheck.bind( this );
}

componentWillUnmount() {
this.cancelBlurCheck();
}

bindNode( node ) {
if ( node ) {
this.node = node;
} else {
delete this.node;
this.cancelBlurCheck();
}
}

queueBlurCheck( event ) {
this.isBlurring = true;
this.blurCheckTimeout = setTimeout( () => {
if ( 'function' === typeof this.node.handleFocusOutside ) {
this.node.handleFocusOutside( event );
}
}, 0 );
}

cancelBlurCheck() {
delete this.isBlurring;
clearTimeout( this.blurCheckTimeout );
}

render() {
return (
<div
onFocus={ this.cancelBlurCheck }
onBlur={ this.queueBlurCheck }
>
<WrappedComponent
ref={ this.bindNode }
{ ...this.props } />
</div>
);
}
};
}

export default withFocusOutside;
73 changes: 73 additions & 0 deletions components/higher-order/with-focus-outside/test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* External dependencies
*/
import { mount } from 'enzyme';

/**
* WordPress dependencies
*/
import { Component } from '@wordpress/element';

/**
* Internal dependencies
*/
import withFocusOutside from '../';

jest.useFakeTimers();

describe( 'withFocusOutside', () => {
const EnhancedComponent = withFocusOutside(
class extends Component {
handleFocusOutside() {
this.props.onFocusOutside();
}

render() {
return (
<div>
<input />
<input />
</div>
);
}
}
);

it( 'should not call handler if focus shifts to element within component', () => {
const callback = jest.fn();
const wrapper = mount( <EnhancedComponent onFocusOutside={ callback } /> );

wrapper.find( 'input' ).at( 0 ).simulate( 'focus' );
wrapper.find( 'input' ).at( 0 ).simulate( 'blur' );
wrapper.find( 'input' ).at( 1 ).simulate( 'focus' );

jest.runAllTimers();

expect( callback ).not.toHaveBeenCalled();
} );

it( 'should call handler if focus doesn\'t shift to element within component', () => {
const callback = jest.fn();
const wrapper = mount( <EnhancedComponent onFocusOutside={ callback } /> );

wrapper.find( 'input' ).at( 0 ).simulate( 'focus' );
wrapper.find( 'input' ).at( 0 ).simulate( 'blur' );

jest.runAllTimers();

expect( callback ).toHaveBeenCalled();
} );

it( 'should cancel check when unmounting while queued', () => {
const callback = jest.fn();
const wrapper = mount( <EnhancedComponent onFocusOutside={ callback } /> );

wrapper.find( 'input' ).at( 0 ).simulate( 'focus' );
wrapper.find( 'input' ).at( 0 ).simulate( 'blur' );
wrapper.unmount();

jest.runAllTimers();

expect( callback ).not.toHaveBeenCalled();
} );
} );
1 change: 1 addition & 0 deletions components/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export { Slot, Fill, Provider as SlotFillProvider } from './slot-fill';
// Higher-Order Components
export { default as navigateRegions } from './higher-order/navigate-regions';
export { default as withAPIData } from './higher-order/with-api-data';
export { default as withFocusOutside } from './higher-order/with-focus-outside';
export { default as withFocusReturn } from './higher-order/with-focus-return';
export { default as withInstanceId } from './higher-order/with-instance-id';
export { default as withSpokenMessages } from './higher-order/with-spoken-messages';