Skip to content

Commit

Permalink
[fixed] Don't steal focus from a descendent when rendering (reactjs#222)
Browse files Browse the repository at this point in the history
  • Loading branch information
conlanpatrek authored and claydiffrient committed Sep 14, 2016
1 parent 8e767e9 commit 5429f7c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
9 changes: 8 additions & 1 deletion lib/components/ModalPortal.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ var ModalPortal = module.exports = React.createClass({
},

focusContent: function() {
this.refs.content.focus();
// Don't steal focus from inner elements
if (!this.contentHasFocus()) {
this.refs.content.focus();
}
},

closeWithTimeout: function() {
Expand Down Expand Up @@ -166,6 +169,10 @@ var ModalPortal = module.exports = React.createClass({
return !this.props.isOpen && !this.state.beforeClose;
},

contentHasFocus() {
return document.activeElement === this.refs.content || this.refs.content.contains(document.activeElement);
},

buildClassName: function(which, additional) {
var className = CLASS_NAMES[which].base;
if (this.state.afterOpen)
Expand Down
8 changes: 8 additions & 0 deletions specs/Modal.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,14 @@ describe('Modal', function () {
});
});

it('does not focus the modal content when a descendent is already focused', function() {
var input = React.DOM.input({ className: 'focus_input', ref: function(el) { el && el.focus(); } });
renderModal({isOpen: true}, input, function () {
strictEqual(document.activeElement, document.querySelector('.focus_input'));
unmountModal();
});
});

it('handles case when child has no tabbable elements', function() {
var component = renderModal({isOpen: true}, 'hello');
assert.doesNotThrow(function() {
Expand Down

0 comments on commit 5429f7c

Please sign in to comment.