Skip to content
This repository has been archived by the owner on Oct 19, 2021. It is now read-only.

fix(modal): set initial focus and conditionally render focus trap #2163

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 38 additions & 23 deletions src/components/Modal/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -225,24 +225,30 @@ export default class Modal extends Component {
}
}

focusButton = focusContainerElement => {
initialFocus = focusContainerElement => {
const primaryFocusElement = focusContainerElement
? focusContainerElement.querySelector(this.props.selectorPrimaryFocus)
: null;
if (primaryFocusElement) {
primaryFocusElement.focus();
return;
return primaryFocusElement;
}
if (this.button && this.button.current) {
this.button.current.focus();
return this.button && this.button.current;
};

focusButton = focusContainerElement => {
const target = this.initialFocus(focusContainerElement);
if (target) {
target.focus();
}
};

componentDidMount() {
if (!this.props.open) {
return;
}
this.focusButton(this.innerModal.current);
if (!this.props.focusTrap) {
this.focusButton(this.innerModal.current);
}
}

handleTransitionEnd = evt => {
Expand All @@ -253,7 +259,9 @@ export default class Modal extends Component {
this.outerModal.current.offsetHeight &&
this.beingOpen
) {
this.focusButton(evt.currentTarget);
if (!this.props.focusTrap) {
this.focusButton(evt.currentTarget);
}
this.beingOpen = false;
}
};
Expand Down Expand Up @@ -349,22 +357,29 @@ export default class Modal extends Component {
</div>
);

return (
<FocusTrap active={open && focusTrap}>
<div
{...other}
onKeyDown={this.handleKeyDown}
onClick={this.handleClick}
onBlur={this.handleBlur}
className={modalClasses}
role="presentation"
tabIndex={-1}
onTransitionEnd={
this.props.open ? this.handleTransitionEnd : undefined
}
ref={this.outerModal}>
{modalBody}
</div>
const modal = (
<div
{...other}
onKeyDown={this.handleKeyDown}
onClick={this.handleClick}
onBlur={this.handleBlur}
className={modalClasses}
role="presentation"
tabIndex={-1}
onTransitionEnd={this.props.open ? this.handleTransitionEnd : undefined}
ref={this.outerModal}>
{modalBody}
</div>
);

return !focusTrap ? (
modal
) : (
// `<FocusTrap>` has `active: true` in its `defaultProps`
<FocusTrap
active={!!open}
focusTrapOptions={{ initialFocus: this.initialFocus }}>
{modal}
</FocusTrap>
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,11 @@ exports[`ModalWrapper should render 1`] = `
<FocusTrap
_createFocusTrap={[Function]}
active={false}
focusTrapOptions={Object {}}
focusTrapOptions={
Object {
"initialFocus": [Function],
}
}
paused={false}
>
<div
Expand Down