-
-
Save gadflying/fcbc954a4342161bfe7406759d8a4dc8 to your computer and use it in GitHub Desktop.
Handle composite focus and blur events in React.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react' | |
| import ReactDOM from 'react-dom' | |
| import { Key } from '../utils/keyboardUtils' | |
| export default class FocusManager extends React.Component { | |
| constructor(props) { | |
| super(props) | |
| this._immediateID = null | |
| this.state = { | |
| isManagingFocus: false, | |
| } | |
| } | |
| componentDidMount() { | |
| document.addEventListener('mousedown', this.handleMousedown); | |
| } | |
| componentWillUnmount() { | |
| document.removeEventListener('mousedown', this.handleMousedown); | |
| } | |
| handleMousedown = event => { | |
| const { onBlur } = this.props | |
| const componentNode = ReactDOM.findDOMNode(this) | |
| // only unset focus state and trigger overall blur event | |
| // if mouse down event occurs outside of this component | |
| if (!componentNode.contains(event.target)) { | |
| this.setState({ | |
| isManagingFocus: false, | |
| }, () => { | |
| if (onBlur) { | |
| onBlur(event) | |
| } | |
| }) | |
| } | |
| } | |
| handleKeyDown = event => { | |
| const { onBlur } = this.props | |
| if (event.keyCode === Key.ESCAPE) { | |
| this.setState({ | |
| isManagingFocus: false, | |
| }, () => { | |
| if (onBlur) { | |
| onBlur(event) | |
| } | |
| }) | |
| } | |
| } | |
| handleBlur = event => { | |
| const { onBlur } = this.props | |
| const { isManagingFocus } = this.state | |
| this._immediateID = setImmediate(() => { | |
| if (isManagingFocus) { | |
| this.setState({ | |
| isManagingFocus: false, | |
| }, () => { | |
| if (onBlur) { | |
| onBlur(event) | |
| } | |
| }) | |
| } | |
| }) | |
| } | |
| handleFocus = event => { | |
| const { onFocus } = this.props | |
| const { isManagingFocus } = this.state | |
| clearImmediate(this._immediateID) | |
| if (!isManagingFocus) { | |
| this.setState({ | |
| isManagingFocus: true, | |
| }, () => { | |
| if (onFocus) { | |
| onFocus(event) | |
| } | |
| }) | |
| } | |
| } | |
| render() { | |
| return ( | |
| <div | |
| role="focusManager" | |
| onBlur={this.handleBlur} | |
| onFocus={this.handleFocus} | |
| onKeyDown={this.handleKeyDown} | |
| > | |
| {this.props.children} | |
| </div> | |
| ) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment