1
0
mirror of https://github.com/chinchang/web-maker.git synced 2025-07-12 09:36:32 +02:00

port focus trapping in modal

This commit is contained in:
Kushagra Gour
2018-06-22 14:21:29 +05:30
parent 0807c10b0b
commit 2e90fa9ae1
2 changed files with 33 additions and 0 deletions

View File

@ -7,6 +7,10 @@ export default class Modal extends Component {
}
componentWillUnmount() {
window.removeEventListener('keydown', this.onKeyDownHandler.bind(this));
if (this.focusGrabber) {
this.focusGrabber.remove();
this.focusGrabber = null;
}
}
onKeyDownHandler(e) {
if (e.keyCode === 27) {
@ -28,6 +32,21 @@ export default class Modal extends Component {
setTimeout(() => {
this.overlayEl.querySelector('.js-modal__close-btn').focus();
}, 0);
/* We insert a dummy hidden input which will take focus as soon as focus
escapes the modal, instead of focus going outside modal because modal
is last focusable element. */
this.focusGrabber = document.createElement('input');
this.focusGrabber.setAttribute(
'style',
'height:0;opacity:0;overflow:hidden;width:0;'
);
setTimeout(() => {
document.body.appendChild(this.focusGrabber);
}, 10);
} else {
this.focusGrabber.remove();
this.focusGrabber = null;
}
}
}

View File

@ -463,6 +463,20 @@ export default class App extends Component {
this.closeSavedItemsPane();
}
});
// Basic Focus trapping
window.addEventListener('focusin', e => {
if (document.body.classList.contains('overlay-visible')) {
const modal = $('.is-modal-visible');
if (!modal) {
return;
}
if (!modal.contains(e.target)) {
e.preventDefault();
modal.querySelector('.js-modal__close-btn').focus();
}
}
});
}
closeAllOverlays() {