Skip to content

Commit

Permalink
Add focus trap to Modals
Browse files Browse the repository at this point in the history
Fixes #2663
  • Loading branch information
davwheat committed Nov 19, 2021
1 parent 2acab3d commit 08f4bdb
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions js/src/common/components/ModalManager.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import Component from '../Component';
import { createFocusTrap, FocusTrap } from '../utils/focusTrap';

import type Mithril from 'mithril';
import type ModalManagerState from '../states/ModalManagerState';
Expand All @@ -13,7 +14,9 @@ interface IModalManagerAttrs {
* overwrite the previous one.
*/
export default class ModalManager extends Component<IModalManagerAttrs> {
view() {
focusTrap: FocusTrap | undefined;

view(vnode: Mithril.VnodeDOM<IModalManagerAttrs, this>): Mithril.Children {
const modal = this.attrs.state.modal;

return (
Expand All @@ -29,13 +32,19 @@ export default class ModalManager extends Component<IModalManagerAttrs> {
);
}

oncreate(vnode: Mithril.VnodeDOM<IModalManagerAttrs, this>) {
oncreate(vnode: Mithril.VnodeDOM<IModalManagerAttrs, this>): void {
super.oncreate(vnode);

// Ensure the modal state is notified about a closed modal, even when the
// DOM-based Bootstrap JavaScript code triggered the closing of the modal,
// e.g. via ESC key or a click on the modal backdrop.
this.$().on('hidden.bs.modal', this.attrs.state.close.bind(this.attrs.state));

this.focusTrap = createFocusTrap(this.element as HTMLElement);
}

onupdate(vnode: Mithril.VnodeDOM<IModalManagerAttrs, this>): void {
super.onupdate(vnode);
}

animateShow(readyCallback: () => void): void {
Expand All @@ -59,10 +68,14 @@ export default class ModalManager extends Component<IModalManagerAttrs> {
keyboard: dismissible,
})
.modal('show');

if (this.focusTrap) this.focusTrap.activate();
}

animateHide(): void {
// @ts-expect-error: No typings available for Bootstrap modals.
this.$().modal('hide');

if (this.focusTrap) this.focusTrap.deactivate();
}
}

0 comments on commit 08f4bdb

Please sign in to comment.