-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsemanticForms.js
More file actions
62 lines (52 loc) · 2.36 KB
/
Copy pathsemanticForms.js
File metadata and controls
62 lines (52 loc) · 2.36 KB
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
const { createKeyboardShortcut, shortcutListener } = require('./lib/keyboardShortcuts.js')
const { enhanceInput, handleUndoRedo } = require('./lib/inputEnhancements.js')
const semanticForms = () => {
// do some feature detection so none of the JS executes if the browser is too old
if (typeof document.getElementsByClassName !== 'function' || typeof document.querySelector !== 'function' || !document.body.classList || !window.MutationObserver) {
console.warn('semantic-forms was loaded into an unsupported browser and will not execute.')
return
}
// custom keyboard shortcut listener
const keyboardShortcuts = []
document.addEventListener('keydown', (e) => shortcutListener(e, keyboardShortcuts))
// progressively enhance form elements that have the semanticForms class
const forms = document.querySelectorAll('form.semanticForms:not(.semanticFormsActive), table.semanticForms:not(.semanticFormsActive)')
for (const form of forms) {
form.classList.add('semanticFormsActive')
if (form.classList.contains('lowFlow')) continue
// update each input in the semantic form
const inputs = Array.from(form.querySelectorAll('input, textarea, select'))
for (const input of inputs) {
enhanceInput(input, form)
// handle keyboard shortcuts
if (input.getAttribute('data-focus-key') !== null) {
const shortcut = createKeyboardShortcut(input, keyboardShortcuts)
keyboardShortcuts.push(shortcut)
}
}
}
// prevents multiple listeners
document.removeEventListener('keydown', handleUndoRedo)
document.addEventListener('keydown', handleUndoRedo)
// monitor changes to the DOM and enhance new semanticForms forms that get added
if (!window.semanticFormsObserver) {
window.semanticFormsObserver = new window.MutationObserver(mutations => {
let stop = false
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeName === 'FORM' || node?.querySelector?.('form')) {
semanticForms()
stop = true
}
}
if (stop) break
}
})
window.semanticFormsObserver.observe(document.body, { attributes: false, childList: true, characterData: false, subtree: true })
}
semanticForms.reinitialize = form => {
form.classList.remove('semanticFormsActive')
semanticForms()
}
}
module.exports = semanticForms