From 3c86e2d6e57ca220df52e2716677a80e83981c88 Mon Sep 17 00:00:00 2001 From: Bruno Dias Date: Mon, 6 Nov 2017 14:58:16 -0300 Subject: [PATCH] [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. --- src/components/ModalPortal.js | 24 ++++++++---------------- src/helpers/focusManager.js | 4 ++++ 2 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/components/ModalPortal.js b/src/components/ModalPortal.js index 434a9990..823d3681 100644 --- a/src/components/ModalPortal.js +++ b/src/components/ModalPortal.js @@ -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(); } diff --git a/src/helpers/focusManager.js b/src/helpers/focusManager.js index d3cecdc8..9d00ebb2 100644 --- a/src/helpers/focusManager.js +++ b/src/helpers/focusManager.js @@ -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;