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

refactor: add focus trap to modal component #663

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,10 +97,11 @@ window.initClipboard = () => {

### Modals

1. Install `body-scroll-lock`
1. Install `body-scroll-lock` and `focus-trap`

```bash
yarn add body-scroll-lock
yarn add focus-trap
```

2. Import the modal script in your `resources/js/app.js` file
Expand Down
26 changes: 25 additions & 1 deletion resources/assets/js/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@ import {
clearAllBodyScrollLocks,
} from "body-scroll-lock";

import { createFocusTrap } from "focus-trap";

const Modal = {
previousPaddingRight: undefined,
previousNavPaddingRight: undefined,
trappedElement: null,

defaultSettings: {
reserveScrollBarGap: true,
Expand All @@ -26,7 +29,7 @@ const Modal = {
reserveScrollBarGap: !!settings.reserveScrollBarGap,
});

scrollable.focus();
this.trapFocus(scrollable);
},

onModalClosed(scrollable, settings = Modal.defaultSettings) {
Expand All @@ -40,11 +43,32 @@ const Modal = {

enableBodyScroll(scrollable);

this.releaseTrappedFocus();

if (!document.querySelectorAll("[data-modal]").length) {
clearAllBodyScrollLocks();
}
},

trapFocus(el) {
let trap = createFocusTrap(el, {
escapeDeactivates: false,
allowOutsideClick: true,
});

this.trappedElement = trap.activate();
},

releaseTrappedFocus() {
let trap = this.trappedElement;

if (trap) {
trap.deactivate();
}

this.trappedElement = null;
},

alpine(
extraData = {},
modalName = "",
Expand Down