From a92b7df343e228cdcbefe9e2f40e198ff7e551b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matej=20=C5=A0nuderl?= Date: Thu, 11 Apr 2019 17:27:29 +0200 Subject: [PATCH] feat(focus): focus last element on modal close (#17) --- src/index.tsx | 21 +++++++++------------ stories/components.tsx | 23 ++++++++++++++++++++--- 2 files changed, 29 insertions(+), 15 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index 264b936..aaae553 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -71,7 +71,7 @@ class MicroModal extends React.PureComponent { isControlled = this.props.open !== undefined; modalRef = React.createRef(); containerRef = React.createRef(); - focusedElement?: HTMLElement; + lastElement?: HTMLElement; static getDerivedStateFromProps(props: Props, state: State) { if (props.open !== undefined && props.open !== state.open) { @@ -111,6 +111,7 @@ class MicroModal extends React.PureComponent { }; private onAfterOpen = (): void => { + this.lastElement = document.activeElement as HTMLElement; openContainerRefStack.push(this.containerRef); this.addEventListeners(); this.focusFirstNode(); @@ -150,12 +151,12 @@ class MicroModal extends React.PureComponent { }; private onAfterClose = (): void => { + this.removeEventListeners(); openContainerRefStack.pop(); - if (openContainerRefStack.length > 0) { - focusFirstNode(getLastOpenContainer()); + if (this.lastElement) { + this.lastElement.focus(); + this.lastElement = undefined; } - this.removeEventListeners(); - this.focusedElement = undefined; }; private focusFirstNode(): void { @@ -163,7 +164,7 @@ class MicroModal extends React.PureComponent { return; } - this.focusedElement = focusFirstNode(this.containerRef); + focusFirstNode(this.containerRef); } private removeEventListeners = (): void => { @@ -187,18 +188,15 @@ class MicroModal extends React.PureComponent { private onKeydown = (event: KeyboardEvent): void => { if (this.containerRef === getLastOpenContainer()) { if (event.key === ESCAPE_KEY && this.props.closeOnEscapePress) { + event.stopPropagation(); this.handleClose(); } if (event.key === TAB_KEY) { - this.focusedElement = handleTabPress(this.containerRef, event); + handleTabPress(this.containerRef, event); } } }; - private getOverlayZIndex(): number { - return openContainerRefStack.findIndex(r => r === this.containerRef); - } - private renderContent = ( open: boolean, isClosing: boolean, @@ -239,7 +237,6 @@ class MicroModal extends React.PureComponent { className={baseModalOverlayClassName} style={{ ...OVERLAY_BASE_STYLE, - zIndex: zIndex || this.getOverlayZIndex(), ...restOverlayStyle }} > diff --git a/stories/components.tsx b/stories/components.tsx index bc14f89..36216ca 100644 --- a/stories/components.tsx +++ b/stories/components.tsx @@ -61,9 +61,26 @@ const StoryModalContent = ({ handleClose }: ContentProps) => { const StoryUncontrolledModal = (props: BaseProps) => ( ( - +
+
+ +
+
)} {...props} >