Skip to content

Commit

Permalink
[fixed] shouldFocusAfterRender and shouldReturnFocusAfterClose flags.
Browse files Browse the repository at this point in the history
Both options should work independent.

If shouldFocusAfterRender and shouldReturnFocusAfterClose are true,
the default behavior, it should focus the modal when open and return
the focus to the previous element when close.

If shouldFocusAfterRender is false and shouldReturnFocusAfterClose is true
should be the same as both option true - noop.

If shouldFocusAfterRender is true and shouldReturnFocusAfterClose is false,
then we focus the modal when open and on close we just pop the previous active
element from the focus manager.
  • Loading branch information
diasbruno committed Nov 6, 2017
1 parent 0f2bf9e commit 3c86e2d
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 16 deletions.
24 changes: 8 additions & 16 deletions src/components/ModalPortal.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,31 +139,23 @@ export default class ModalPortal extends Component {
// Remove body class
bodyClassList.remove(this.props.bodyOpenClassName);

if (this.shouldReturnFocus()) {
focusManager.returnFocus();
focusManager.teardownScopedFocus();
if (this.props.shouldFocusAfterRender) {
if (this.props.shouldReturnFocusAfterClose) {
focusManager.returnFocus();
focusManager.teardownScopedFocus();
} else {
focusManager.popWithoutFocus();
}
}
};

shouldReturnFocus = () => {
// Don't restore focus to the element that had focus prior to
// the modal's display if:
// 1. Focus was never shifted to the modal in the first place
// (shouldFocusAfterRender = false)
// 2. Explicit direction to not restore focus
return (
this.props.shouldFocusAfterRender ||
this.props.shouldReturnFocusAfterClose
);
};

open = () => {
this.beforeOpen();
if (this.state.afterOpen && this.state.beforeClose) {
clearTimeout(this.closeTimer);
this.setState({ beforeClose: false });
} else {
if (this.shouldReturnFocus()) {
if (this.props.shouldFocusAfterRender) {
focusManager.setupScopedFocus(this.node);
focusManager.markForFocusLater();
}
Expand Down
4 changes: 4 additions & 0 deletions src/helpers/focusManager.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,10 @@ export function returnFocus() {
}
/* eslint-enable no-console */

export function popWithoutFocus() {
focusLaterElements.length > 0 && focusLaterElements.pop();
}

export function setupScopedFocus(element) {
modalElement = element;

Expand Down

0 comments on commit 3c86e2d

Please sign in to comment.