Skip to content

Commit 3c86e2d

Browse files
committed
[fixed] shouldFocusAfterRender and shouldReturnFocusAfterClose flags.
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.
1 parent 0f2bf9e commit 3c86e2d

File tree

2 files changed

+12
-16
lines changed

2 files changed

+12
-16
lines changed

src/components/ModalPortal.js

+8-16
Original file line numberDiff line numberDiff line change
@@ -139,31 +139,23 @@ export default class ModalPortal extends Component {
139139
// Remove body class
140140
bodyClassList.remove(this.props.bodyOpenClassName);
141141

142-
if (this.shouldReturnFocus()) {
143-
focusManager.returnFocus();
144-
focusManager.teardownScopedFocus();
142+
if (this.props.shouldFocusAfterRender) {
143+
if (this.props.shouldReturnFocusAfterClose) {
144+
focusManager.returnFocus();
145+
focusManager.teardownScopedFocus();
146+
} else {
147+
focusManager.popWithoutFocus();
148+
}
145149
}
146150
};
147151

148-
shouldReturnFocus = () => {
149-
// Don't restore focus to the element that had focus prior to
150-
// the modal's display if:
151-
// 1. Focus was never shifted to the modal in the first place
152-
// (shouldFocusAfterRender = false)
153-
// 2. Explicit direction to not restore focus
154-
return (
155-
this.props.shouldFocusAfterRender ||
156-
this.props.shouldReturnFocusAfterClose
157-
);
158-
};
159-
160152
open = () => {
161153
this.beforeOpen();
162154
if (this.state.afterOpen && this.state.beforeClose) {
163155
clearTimeout(this.closeTimer);
164156
this.setState({ beforeClose: false });
165157
} else {
166-
if (this.shouldReturnFocus()) {
158+
if (this.props.shouldFocusAfterRender) {
167159
focusManager.setupScopedFocus(this.node);
168160
focusManager.markForFocusLater();
169161
}

src/helpers/focusManager.js

+4
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,10 @@ export function returnFocus() {
5252
}
5353
/* eslint-enable no-console */
5454

55+
export function popWithoutFocus() {
56+
focusLaterElements.length > 0 && focusLaterElements.pop();
57+
}
58+
5559
export function setupScopedFocus(element) {
5660
modalElement = element;
5761

0 commit comments

Comments
 (0)