Skip to content

Commit

Permalink
feat(Modal): Add trapFocus prop (#2073)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyletsang committed Jan 12, 2021
1 parent 7d13d5b commit 6e0fd56
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 7 deletions.
1 change: 1 addition & 0 deletions docs/lib/Components/ModalsPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,7 @@ const ModalsPage = () => {
returnFocusAfterClose: PropTypes.bool, // defaults to true
// container to append the modal to
container: PropTypes.oneOfType([PropTypes.string, PropTypes.func, DOMElement]),
trapFocus: PropTypes.bool // Traps focus within modal
}`}
</PrismCode>
</pre>
Expand Down
18 changes: 12 additions & 6 deletions src/Modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ const propTypes = {
]),
unmountOnClose: PropTypes.bool,
returnFocusAfterClose: PropTypes.bool,
container: targetPropType
container: targetPropType,
trapFocus: PropTypes.bool
};

const propsToOmit = Object.keys(propTypes);
Expand All @@ -86,7 +87,8 @@ const defaultProps = {
},
unmountOnClose: true,
returnFocusAfterClose: true,
container: 'body'
container: 'body',
trapFocus: false
};

class Modal extends React.Component {
Expand Down Expand Up @@ -171,20 +173,24 @@ class Modal extends React.Component {
}

trapFocus (ev) {
if (!this.props.trapFocus) {
return;
}

if (!this._element) //element is not attached
return ;
return;

if (this._dialog && this._dialog.parentNode === ev.target) // initial focus when the Modal is opened
return ;
return;

if (this.modalIndex < (Modal.openCount - 1)) // last opened modal
return ;
return;

const children = this.getFocusableChildren();

for (let i = 0; i < children.length; i++) { // focus is already inside the Modal
if (children[i] === ev.target)
return ;
return;
}

if (children.length > 0) { // otherwise focus the first focusable element in the Modal
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/Modal.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -1170,7 +1170,7 @@ describe('Modal', () => {
const MockComponent = () => (
<>
<Button className={'first'}>Focused</Button>
<Modal isOpen={true}>
<Modal isOpen={true} trapFocus>
<ModalBody>
Something else to see
<Button className={'focus'}>focusable element</Button>
Expand Down
1 change: 1 addition & 0 deletions types/lib/Modal.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export interface ModalProps extends React.HTMLAttributes<HTMLElement> {
returnFocusAfterClose?: boolean;
container?: string | HTMLElement | React.RefObject<HTMLElement>;
innerRef?: React.Ref<HTMLElement>;
trapFocus?: boolean;
}

declare class Modal extends React.Component<ModalProps> {}
Expand Down

0 comments on commit 6e0fd56

Please sign in to comment.