-
Notifications
You must be signed in to change notification settings - Fork 431
Expand file tree
/
Copy pathmodality.js
More file actions
97 lines (76 loc) · 2.82 KB
/
modality.js
File metadata and controls
97 lines (76 loc) · 2.82 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
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
/**
* Adapted from https://github.com/alice/modality
* Version: 1.0.2
*/
if (typeof window !== 'undefined') {
document.addEventListener('DOMContentLoaded', () => {
let hadKeyboardEvent = false;
const keyboardModalityWhitelist = [
'input:not([type])',
'input[type=text]',
'input[type=number]',
'input[type=date]',
'input[type=time]',
'input[type=datetime]',
'textarea',
'[role=textbox]',
'[supports-modality=keyboard]'
].join(',');
let isHandlingKeyboardThrottle;
const matcher = (() => {
const el = document.body;
if (el.matchesSelector) {
return el.matchesSelector;
}
if (el.webkitMatchesSelector) {
return el.webkitMatchesSelector;
}
if (el.mozMatchesSelector) {
return el.mozMatchesSelector;
}
if (el.msMatchesSelector) {
return el.msMatchesSelector;
}
console.error('Couldn\'t find any matchesSelector method on document.body.');
})();
const disableFocusRingByDefault = function () {
const css = 'body:not([modality=keyboard]) :focus { outline: none; }';
const head = document.head || document.getElementsByTagName('head')[0];
const style = document.createElement('style');
style.type = 'text/css';
style.id = 'disable-focus-ring';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.insertBefore(style, head.firstChild);
};
const focusTriggersKeyboardModality = function (el) {
let triggers = false;
if (matcher) {
triggers = matcher.call(el, keyboardModalityWhitelist) &&
matcher.call(el, ':not([readonly])');
}
return triggers;
};
disableFocusRingByDefault();
document.body.addEventListener('keydown', () => {
hadKeyboardEvent = true;
if (isHandlingKeyboardThrottle) {
clearTimeout(isHandlingKeyboardThrottle);
}
isHandlingKeyboardThrottle = setTimeout(() => {
hadKeyboardEvent = false;
}, 100);
}, true);
document.body.addEventListener('focus', e => {
if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {
document.body.setAttribute('modality', 'keyboard');
}
}, true);
document.body.addEventListener('blur', () => {
document.body.removeAttribute('modality');
}, true);
});
}