-
Notifications
You must be signed in to change notification settings - Fork 229
/
index.js
345 lines (295 loc) · 10.9 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
const MicroModal = (() => {
'use strict'
const FOCUSABLE_ELEMENTS = [
'a[href]',
'area[href]',
'input:not([disabled]):not([type="hidden"]):not([aria-hidden])',
'select:not([disabled]):not([aria-hidden])',
'textarea:not([disabled]):not([aria-hidden])',
'button:not([disabled]):not([aria-hidden])',
'iframe',
'object',
'embed',
'[contenteditable]',
'[tabindex]:not([tabindex^="-"])'
]
class Modal {
constructor ({
targetModal,
triggers = [],
onShow = () => { },
onClose = () => { },
openTrigger = 'data-micromodal-trigger',
closeTrigger = 'data-micromodal-close',
openClass = 'is-open',
disableScroll = false,
disableFocus = false,
awaitCloseAnimation = false,
awaitOpenAnimation = false,
debugMode = false
}) {
// Save a reference of the modal
this.modal = document.getElementById(targetModal)
// Save a reference to the passed config
this.config = { debugMode, disableScroll, openTrigger, closeTrigger, openClass, onShow, onClose, awaitCloseAnimation, awaitOpenAnimation, disableFocus }
// Register click events only if pre binding eventListeners
if (triggers.length > 0) this.registerTriggers(...triggers)
// pre bind functions for event listeners
this.onClick = this.onClick.bind(this)
this.onKeydown = this.onKeydown.bind(this)
}
/**
* Loops through all openTriggers and binds click event
* @param {array} triggers [Array of node elements]
* @return {void}
*/
registerTriggers (...triggers) {
triggers.filter(Boolean).forEach(trigger => {
trigger.addEventListener('click', event => this.showModal(event))
})
}
showModal (event = null) {
this.activeElement = document.activeElement
this.modal.setAttribute('aria-hidden', 'false')
this.modal.classList.add(this.config.openClass)
this.scrollBehaviour('disable')
this.addEventListeners()
if (this.config.awaitOpenAnimation) {
const handler = () => {
this.modal.removeEventListener('animationend', handler, false)
this.setFocusToFirstNode()
}
this.modal.addEventListener('animationend', handler, false)
} else {
this.setFocusToFirstNode()
}
this.config.onShow(this.modal, this.activeElement, event)
}
closeModal (event = null) {
const modal = this.modal
this.modal.setAttribute('aria-hidden', 'true')
this.removeEventListeners()
this.scrollBehaviour('enable')
if (this.activeElement && this.activeElement.focus) {
this.activeElement.focus()
}
this.config.onClose(this.modal, this.activeElement, event)
if (this.config.awaitCloseAnimation) {
const openClass = this.config.openClass // <- old school ftw
this.modal.addEventListener('animationend', function handler () {
modal.classList.remove(openClass)
modal.removeEventListener('animationend', handler, false)
}, false)
} else {
modal.classList.remove(this.config.openClass)
}
}
closeModalById (targetModal) {
this.modal = document.getElementById(targetModal)
if (this.modal) this.closeModal()
}
scrollBehaviour (toggle) {
if (!this.config.disableScroll) return
const body = document.querySelector('body')
switch (toggle) {
case 'enable':
Object.assign(body.style, { overflow: '' })
break
case 'disable':
Object.assign(body.style, { overflow: 'hidden' })
break
default:
}
}
addEventListeners () {
this.modal.addEventListener('touchstart', this.onClick)
this.modal.addEventListener('click', this.onClick)
document.addEventListener('keydown', this.onKeydown)
}
removeEventListeners () {
this.modal.removeEventListener('touchstart', this.onClick)
this.modal.removeEventListener('click', this.onClick)
document.removeEventListener('keydown', this.onKeydown)
}
/**
* Handles all click events from the modal.
* Closes modal if a target matches the closeTrigger attribute.
* @param {*} event Click Event
*/
onClick (event) {
if (
event.target.hasAttribute(this.config.closeTrigger) ||
event.target.parentNode.hasAttribute(this.config.closeTrigger)
) {
event.preventDefault()
event.stopPropagation()
this.closeModal(event)
}
}
onKeydown (event) {
if (event.keyCode === 27) this.closeModal(event) // esc
if (event.keyCode === 9) this.retainFocus(event) // tab
}
getFocusableNodes () {
const nodes = this.modal.querySelectorAll(FOCUSABLE_ELEMENTS)
return Array(...nodes)
}
/**
* Tries to set focus on a node which is not a close trigger
* if no other nodes exist then focuses on first close trigger
*/
setFocusToFirstNode () {
if (this.config.disableFocus) return
const focusableNodes = this.getFocusableNodes()
// no focusable nodes
if (focusableNodes.length === 0) return
// remove nodes on whose click, the modal closes
// could not think of a better name :(
const nodesWhichAreNotCloseTargets = focusableNodes.filter(node => {
return !node.hasAttribute(this.config.closeTrigger)
})
if (nodesWhichAreNotCloseTargets.length > 0) nodesWhichAreNotCloseTargets[0].focus()
if (nodesWhichAreNotCloseTargets.length === 0) focusableNodes[0].focus()
}
retainFocus (event) {
let focusableNodes = this.getFocusableNodes()
// no focusable nodes
if (focusableNodes.length === 0) return
/**
* Filters nodes which are hidden to prevent
* focus leak outside modal
*/
focusableNodes = focusableNodes.filter(node => {
return (node.offsetParent !== null)
})
// if disableFocus is true
if (!this.modal.contains(document.activeElement)) {
focusableNodes[0].focus()
} else {
const focusedItemIndex = focusableNodes.indexOf(document.activeElement)
if (event.shiftKey && focusedItemIndex === 0) {
focusableNodes[focusableNodes.length - 1].focus()
event.preventDefault()
}
if (!event.shiftKey && focusableNodes.length > 0 && focusedItemIndex === focusableNodes.length - 1) {
focusableNodes[0].focus()
event.preventDefault()
}
}
}
}
/**
* Modal prototype ends.
* Here on code is responsible for detecting and
* auto binding event handlers on modal triggers
*/
// Keep a reference to the opened modal
let activeModal = null
/**
* Generates an associative array of modals and it's
* respective triggers
* @param {array} triggers An array of all triggers
* @param {string} triggerAttr The data-attribute which triggers the module
* @return {array}
*/
const generateTriggerMap = (triggers, triggerAttr) => {
const triggerMap = []
triggers.forEach(trigger => {
const targetModal = trigger.attributes[triggerAttr].value
if (triggerMap[targetModal] === undefined) triggerMap[targetModal] = []
triggerMap[targetModal].push(trigger)
})
return triggerMap
}
/**
* Validates whether a modal of the given id exists
* in the DOM
* @param {number} id The id of the modal
* @return {boolean}
*/
const validateModalPresence = id => {
if (!document.getElementById(id)) {
console.warn(`MicroModal: \u2757Seems like you have missed %c'${ id }'`, 'background-color: #f8f9fa;color: #50596c;font-weight: bold;', 'ID somewhere in your code. Refer example below to resolve it.')
console.warn('%cExample:', 'background-color: #f8f9fa;color: #50596c;font-weight: bold;', `<div class="modal" id="${ id }"></div>`)
return false
}
}
/**
* Validates if there are modal triggers present
* in the DOM
* @param {array} triggers An array of data-triggers
* @return {boolean}
*/
const validateTriggerPresence = triggers => {
if (triggers.length <= 0) {
console.warn('MicroModal: \u2757Please specify at least one %c\'micromodal-trigger\'', 'background-color: #f8f9fa;color: #50596c;font-weight: bold;', 'data attribute.')
console.warn('%cExample:', 'background-color: #f8f9fa;color: #50596c;font-weight: bold;', '<a href="#" data-micromodal-trigger="my-modal"></a>')
return false
}
}
/**
* Checks if triggers and their corresponding modals
* are present in the DOM
* @param {array} triggers Array of DOM nodes which have data-triggers
* @param {array} triggerMap Associative array of modals and their triggers
* @return {boolean}
*/
const validateArgs = (triggers, triggerMap) => {
validateTriggerPresence(triggers)
if (!triggerMap) return true
for (const id in triggerMap) validateModalPresence(id)
return true
}
/**
* Binds click handlers to all modal triggers
* @param {object} config [description]
* @return void
*/
const init = config => {
// Create an config object with default openTrigger
const options = Object.assign({}, { openTrigger: 'data-micromodal-trigger' }, config)
// Collects all the nodes with the trigger
const triggers = [...document.querySelectorAll(`[${ options.openTrigger }]`)]
// Makes a mappings of modals with their trigger nodes
const triggerMap = generateTriggerMap(triggers, options.openTrigger)
// Checks if modals and triggers exist in dom
if (options.debugMode === true && validateArgs(triggers, triggerMap) === false) return
// For every target modal creates a new instance
for (const key in triggerMap) {
const value = triggerMap[key]
options.targetModal = key
options.triggers = [...value]
activeModal = new Modal(options) // eslint-disable-line no-new
}
}
/**
* Shows a particular modal
* @param {string} targetModal [The id of the modal to display]
* @param {object} config [The configuration object to pass]
* @return {void}
*/
const show = (targetModal, config) => {
const options = config || {}
options.targetModal = targetModal
// Checks if modals and triggers exist in dom
if (options.debugMode === true && validateModalPresence(targetModal) === false) return
// clear events in case previous modal wasn't closed
if (activeModal) activeModal.removeEventListeners()
// stores reference to active modal
activeModal = new Modal(options) // eslint-disable-line no-new
activeModal.showModal()
}
/**
* Closes the active modal
* @param {string} targetModal [The id of the modal to close]
* @return {void}
*/
const close = targetModal => {
targetModal ? activeModal.closeModalById(targetModal) : activeModal.closeModal()
}
return { init, show, close }
})()
export default MicroModal
if (typeof window !== 'undefined') {
window.MicroModal = MicroModal
}