Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add default Modal component #181

Open
wants to merge 1 commit 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
2 changes: 2 additions & 0 deletions assets/scripts/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ const CSS_CLASS = Object.freeze({
// Custom js events
const CUSTOM_EVENT = Object.freeze({
RESIZE_END: 'loco.resizeEnd',
VISIT_START: 'visit.start',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I assume VISIT_START is named this way based on SWUP's visit:start hook?

Visit started: transition to a new page begins.

MODAL_OPEN: 'modal.open',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There should be an equivalent MODAL_CLOSE custom event.

// ...
})

Expand Down
1 change: 1 addition & 0 deletions assets/scripts/modules.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export {default as Example} from './modules/Example';
export {default as Load} from './modules/Load';
export {default as Modal} from './modules/Modal';
export {default as Scroll} from './modules/Scroll';
7 changes: 7 additions & 0 deletions assets/scripts/modules/Load.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { module } from 'modujs';
import modularLoad from 'modularload';
import { CUSTOM_EVENT } from '../config';

export default class extends module {
constructor(m) {
Expand All @@ -14,6 +15,12 @@ export default class extends module {
}
});

load.on('loading', (transition, oldContainer) => {
const args = { transition, oldContainer };
// Dispatch custom event
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// Dispatch custom event

Useless comment.

window.dispatchEvent(new CustomEvent(CUSTOM_EVENT.VISIT_START, { detail: args }))
});

load.on('loaded', (transition, oldContainer, newContainer) => {
this.call('destroy', oldContainer, 'app');
this.call('update', newContainer, 'app');
Expand Down
195 changes: 195 additions & 0 deletions assets/scripts/modules/Modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import { createFocusTrap } from 'focus-trap'
import { module as Module } from 'modujs'
import { $html } from '../utils/dom'
import { CUSTOM_EVENT } from '../config'

/**
* Generic component to display a modal.
*
*/
Comment on lines +6 to +9
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please provide an example(s) of the HTML needed to use this module as well as information on how to sub-class this base class, including which hooks are available (such as this.onBeforeInit).

export default class Modal extends Module {
/**
* Creates a new Modal.
*
* @param {object} options - The module options.
* @param {string} options.dataName - The module data attribute name.
* @throws {TypeError} If the class does not have an active CSS class defined.
*/

static CLASS = {
EL: 'is-open',
HTML: 'has-modal-open',
}
Comment on lines +19 to +22
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
static CLASS = {
EL: 'is-open',
HTML: 'has-modal-open',
}
static OPEN_CLASS = {
EL: 'is-open',
HTML: 'has-modal-open',
}

CLASS is too generic and meaningless given its very specific use case.

I recommend OPEN_CLASS or something to that effect.


constructor(options) {
Comment on lines +11 to +24
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
/**
* Creates a new Modal.
*
* @param {object} options - The module options.
* @param {string} options.dataName - The module data attribute name.
* @throws {TypeError} If the class does not have an active CSS class defined.
*/
static CLASS = {
EL: 'is-open',
HTML: 'has-modal-open',
}
constructor(options) {
static CLASS = {
EL: 'is-open',
HTML: 'has-modal-open',
}
/**
* Creates a new Modal.
*
* @param {object} options - The module options.
* @param {string} options.dataName - The module data attribute name.
*/
constructor(options) {

Misplaced block comment and no related error to the @throws.

super(options)

// Data
this.moduleName = options.name
this.dataName = this.getData('name') || options.dataName
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
this.dataName = this.getData('name') || options.dataName
this.dataName = options.dataName || this.getData('name')

I think the constructor's option.dataName parameter should have precedence over the options.el's attribute given the class' purpose is to decorate the base element.


// Bindings
this.toggle = this.toggle.bind(this)
this.onModalOpen = this.onModalOpen.bind(this)
this.onVisitStart = this.onVisitStart.bind(this)

// UI
this.$togglers = document.querySelectorAll(`[data-${this.dataName}-toggler]`)
this.$focusTrapTargets = Array.from(this.el.querySelectorAll(`[data-${this.dataName}-target]`))

// Focus trap options
this.focusTrapOptions = {
/**
* There is a delay between when the class is applied
* and when the element is focusable
*/
checkCanFocusTrap: (trapContainers) => {
const results = trapContainers.map((trapContainer) => {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (
getComputedStyle(trapContainer).visibility !==
'hidden'
) {
resolve()
clearInterval(interval)
}
}, 5)
})
})

// Return a promise that resolves when all the trap containers are able to receive focus
return Promise.all(results)
},

onActivate: () => {
this.el.classList.add(Modal.CLASS.EL)
$html.classList.add(Modal.CLASS.HTML)
$html.classList.add('has-'+this.dataName+'-open')
this.el.setAttribute('aria-hidden', false)
this.isOpen = true

this.onActivate?.();
},

onPostActivate: () => {
this.$togglers.forEach(($toggler) => {
$toggler.setAttribute('aria-expanded', true)
})
},

onDeactivate: () => {
this.el.classList.remove(Modal.CLASS.EL)
$html.classList.remove(Modal.CLASS.HTML)
$html.classList.remove('has-'+this.dataName+'-open')
this.el.setAttribute('aria-hidden', true)
this.isOpen = false

this.onDeactivate?.();
},

onPostDeactivate: () => {
this.$togglers.forEach(($toggler) => {
$toggler.setAttribute('aria-expanded', false)
})
},

clickOutsideDeactivates: true,
}

this.isOpen = false
}

/////////////////
// Lifecycle
/////////////////
init() {
this.onBeforeInit?.()

this.focusTrap = createFocusTrap(
this.$focusTrapTargets.length > 0 ? this.$focusTrapTargets : [this.el],
this.focusTrapOptions
)
Comment on lines +36 to +112
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
// UI
this.$togglers = document.querySelectorAll(`[data-${this.dataName}-toggler]`)
this.$focusTrapTargets = Array.from(this.el.querySelectorAll(`[data-${this.dataName}-target]`))
// Focus trap options
this.focusTrapOptions = {
/**
* There is a delay between when the class is applied
* and when the element is focusable
*/
checkCanFocusTrap: (trapContainers) => {
const results = trapContainers.map((trapContainer) => {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (
getComputedStyle(trapContainer).visibility !==
'hidden'
) {
resolve()
clearInterval(interval)
}
}, 5)
})
})
// Return a promise that resolves when all the trap containers are able to receive focus
return Promise.all(results)
},
onActivate: () => {
this.el.classList.add(Modal.CLASS.EL)
$html.classList.add(Modal.CLASS.HTML)
$html.classList.add('has-'+this.dataName+'-open')
this.el.setAttribute('aria-hidden', false)
this.isOpen = true
this.onActivate?.();
},
onPostActivate: () => {
this.$togglers.forEach(($toggler) => {
$toggler.setAttribute('aria-expanded', true)
})
},
onDeactivate: () => {
this.el.classList.remove(Modal.CLASS.EL)
$html.classList.remove(Modal.CLASS.HTML)
$html.classList.remove('has-'+this.dataName+'-open')
this.el.setAttribute('aria-hidden', true)
this.isOpen = false
this.onDeactivate?.();
},
onPostDeactivate: () => {
this.$togglers.forEach(($toggler) => {
$toggler.setAttribute('aria-expanded', false)
})
},
clickOutsideDeactivates: true,
}
this.isOpen = false
}
/////////////////
// Lifecycle
/////////////////
init() {
this.onBeforeInit?.()
this.focusTrap = createFocusTrap(
this.$focusTrapTargets.length > 0 ? this.$focusTrapTargets : [this.el],
this.focusTrapOptions
)
// UI
this.$togglers = document.querySelectorAll(`[data-${this.dataName}-toggler]`)
this.$focusTrapTargets = Array.from(this.el.querySelectorAll(`[data-${this.dataName}-target]`))
this.isOpen = false
}
getFocusTrapOptions() {
return {
/**
* There is a delay between when the class is applied
* and when the element is focusable
*/
checkCanFocusTrap: (trapContainers) => {
const results = trapContainers.map((trapContainer) => {
return new Promise((resolve) => {
const interval = setInterval(() => {
if (
getComputedStyle(trapContainer).visibility !==
'hidden'
) {
resolve()
clearInterval(interval)
}
}, 5)
})
})
// Return a promise that resolves when all the trap containers are able to receive focus
return Promise.all(results)
},
onActivate: () => {
this.el.classList.add(Modal.CLASS.EL)
$html.classList.add(Modal.CLASS.HTML)
$html.classList.add('has-'+this.dataName+'-open')
this.el.setAttribute('aria-hidden', false)
this.isOpen = true
this.onActivate?.();
},
onPostActivate: () => {
this.$togglers.forEach(($toggler) => {
$toggler.setAttribute('aria-expanded', true)
})
},
onDeactivate: () => {
this.el.classList.remove(Modal.CLASS.EL)
$html.classList.remove(Modal.CLASS.HTML)
$html.classList.remove('has-'+this.dataName+'-open')
this.el.setAttribute('aria-hidden', true)
this.isOpen = false
this.onDeactivate?.();
},
onPostDeactivate: () => {
this.$togglers.forEach(($toggler) => {
$toggler.setAttribute('aria-expanded', false)
})
},
clickOutsideDeactivates: true,
}
}
/////////////////
// Lifecycle
/////////////////
init() {
this.onBeforeInit?.()
this.focusTrap = createFocusTrap(
this.$focusTrapTargets.length > 0 ? this.$focusTrapTargets : [this.el],
this.getFocusTrapOptions()
)

this.focusTrapOptions should be moved to a separate method, something like this.getFocusTrapOptions which would be easier to override/extend in a sub-class.


this.bindEvents()

this.onInit?.()
}

destroy() {
this.focusTrap?.deactivate?.({
returnFocus: false,
})

this.unbindEvents()

this.onDestroy?.()

super.destroy()
}

/////////////////
// Events
/////////////////
bindEvents() {
window.addEventListener(CUSTOM_EVENT.VISIT_START, this.onVisitStart)
window.addEventListener(CUSTOM_EVENT.MODAL_OPEN, this.onModalOpen)

this.$togglers.forEach(($toggler) => {
$toggler.addEventListener('click', this.toggle)
})
}

unbindEvents() {
window.removeEventListener(CUSTOM_EVENT.VISIT_START, this.onVisitStart)
window.removeEventListener(CUSTOM_EVENT.MODAL_OPEN, this.onModalOpen)

this.$togglers.forEach(($toggler) => {
$toggler.removeEventListener('click', this.toggle)
})
}

/////////////////
// Callbacks
/////////////////
onVisitStart() {
// Close the modal on page change
this.close()
}

onModalOpen(event) {
// Close the modal if another one is opened
if (event.detail !== this.el) {
this.close()
}
}

/////////////////
// Methods
/////////////////
toggle(event) {
if (this.el.classList.contains(Modal.CLASS.EL)) {
this.close(event)
} else {
this.open(event)
}
}

open(args) {
if (this.isOpen) return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (this.isOpen) return
if (this.isOpen) {
return
}

The compiler is going to minify this anyway, might as well maximize readability.


this.focusTrap?.activate?.()

this.onOpen?.(args)

window.dispatchEvent(new CustomEvent(CUSTOM_EVENT.MODAL_OPEN, { detail: this.el }))
}

close(args) {
if (!this.isOpen) return
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if (!this.isOpen) return
if (!this.isOpen) {
return
}

The compiler is going to minify this anyway, might as well maximize readability.


this.focusTrap?.deactivate?.()

this.onClose?.(args)
}
}
52 changes: 52 additions & 0 deletions assets/styles/components/_modal.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// ==========================================================================
// Components / Modal
// ==========================================================================

.c-modal {
position: fixed;
top: 0;
left: 0;
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100dvh;
max-width: inherit;
max-height: 100lvh;
margin: 0;
padding: 0 var(--grid-margin);
background: transparent;
border: none;
visibility: hidden;
pointer-events: none;
overflow: hidden;

// Backdrop
&::before {
content: "";
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: color(darkest, 0.5);
z-index: -1;
}

html.is-first-loaded & {
transition: visibility speed(normal);
}

&.is-open {
pointer-events: auto;
visibility: visible;
transition-duration: 0s;
}
}

.c-modal_inner {
width: 100%;
max-width: rem(500px);
padding: $unit-small;
background-color: color(lightest);
}
1 change: 1 addition & 0 deletions assets/styles/main.scss
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
@import "components/text";
@import "components/button";
@import "components/form";
@import "components/modal";

// Utilities
// ==========================================================================
Expand Down
36 changes: 30 additions & 6 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"build": "node --no-warnings build/build.js"
},
"dependencies": {
"focus-trap": "^7.5.4",
"locomotive-scroll": "^5.0.0-beta.13",
"modujs": "^1.4.2",
"modularload": "^1.2.6",
Expand Down
Loading