-
Notifications
You must be signed in to change notification settings - Fork 124
/
focus-ring.js
347 lines (300 loc) · 7.95 KB
/
focus-ring.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
346
347
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory() :
typeof define === 'function' && define.amd ? define(factory) :
(factory());
}(this, (function () { 'use strict';
/**
* Module export
*
* @param {Element} el
* @return {ClassList}
*/
var index = function (el) {
return new ClassList(el);
};
/**
* Initialize a new ClassList for the given element
*
* @param {Element} el DOM Element
*/
function ClassList(el) {
if (!el || el.nodeType !== 1) {
throw new Error('A DOM Element reference is required');
}
this.el = el;
this.classList = el.classList;
}
/**
* Check token validity
*
* @param token
* @param [method]
*/
function checkToken(token, method) {
method = method || 'a method';
if (typeof token != 'string') {
throw new TypeError(
'Failed to execute \'' + method + '\' on \'ClassList\': ' +
'the token provided (\'' + token + '\') is not a string.'
);
}
if (token === "") {
throw new SyntaxError(
'Failed to execute \'' + method + '\' on \'ClassList\': ' +
'the token provided must not be empty.'
);
}
if (/\s/.test(token)) {
throw new Error(
'Failed to execute \'' + method + '\' on \'ClassList\': ' +
'the token provided (\'' + token + '\') contains HTML space ' +
'characters, which are not valid in tokens.'
);
}
}
/**
* Return an array of the class names on the element.
*
* @return {Array}
*/
ClassList.prototype.toArray = function () {
var str = (this.el.getAttribute('class') || '').replace(/^\s+|\s+$/g, '');
var classes = str.split(/\s+/);
if ('' === classes[0]) { classes.shift(); }
return classes;
};
/**
* Add the given `token` to the class list if it's not already present.
*
* @param {String} token
*/
ClassList.prototype.add = function (token) {
var classes, index, updated;
checkToken(token, 'add');
if (this.classList) {
this.classList.add(token);
}
else {
// fallback
classes = this.toArray();
index = classes.indexOf(token);
if (index === -1) {
classes.push(token);
this.el.setAttribute('class', classes.join(' '));
}
}
return;
};
/**
* Check if the given `token` is in the class list.
*
* @param {String} token
* @return {Boolean}
*/
ClassList.prototype.contains = function (token) {
checkToken(token, 'contains');
return this.classList ?
this.classList.contains(token) :
this.toArray().indexOf(token) > -1;
};
/**
* Remove any class names that match the given `token`, when present.
*
* @param {String|RegExp} token
*/
ClassList.prototype.remove = function (token) {
var arr, classes, i, index, len;
if ('[object RegExp]' == Object.prototype.toString.call(token)) {
arr = this.toArray();
for (i = 0, len = arr.length; i < len; i++) {
if (token.test(arr[i])) {
this.remove(arr[i]);
}
}
}
else {
checkToken(token, 'remove');
if (this.classList) {
this.classList.remove(token);
}
else {
// fallback
classes = this.toArray();
index = classes.indexOf(token);
if (index > -1) {
classes.splice(index, 1);
this.el.setAttribute('class', classes.join(' '));
}
}
}
return;
};
/**
* Toggle the `token` in the class list. Optionally force state via `force`.
*
* Native `classList` is not used as some browsers that support `classList` do
* not support `force`. Avoiding `classList` altogether keeps this function
* simple.
*
* @param {String} token
* @param {Boolean} [force]
* @return {Boolean}
*/
ClassList.prototype.toggle = function (token, force) {
checkToken(token, 'toggle');
var hasToken = this.contains(token);
var method = hasToken ? (force !== true && 'remove') : (force !== false && 'add');
if (method) {
this[method](token);
}
return (typeof force == 'boolean' ? force : !hasToken);
};
/**
* https://github.com/WICG/focus-ring
*/
function init() {
var hadKeyboardEvent = false;
var elWithFocusRing;
var inputTypesWhitelist = {
'text': true,
'search': true,
'url': true,
'tel': true,
'email': true,
'password': true,
'number': true,
'date': true,
'month': true,
'week': true,
'time': true,
'datetime': true,
'datetime-local': true,
};
/**
* Computes whether the given element should automatically trigger the
* `focus-ring` class being added, i.e. whether it should always match
* `:focus-ring` when focused.
* @param {Element} el
* @return {boolean}
*/
function focusTriggersKeyboardModality(el) {
var type = el.type;
var tagName = el.tagName;
if (tagName == 'INPUT' && inputTypesWhitelist[type] && !el.readonly)
return true;
if (tagName == 'TEXTAREA' && !el.readonly)
return true;
if (el.contentEditable == 'true')
return true;
return false;
}
/**
* Add the `focus-ring` class to the given element if it was not added by
* the author.
* @param {Element} el
*/
function addFocusRingClass(el) {
if (index(el).contains('focus-ring'))
return;
index(el).add('focus-ring');
el.setAttribute('data-focus-ring-added', '');
}
/**
* Remove the `focus-ring` class from the given element if it was not
* originally added by the author.
* @param {Element} el
*/
function removeFocusRingClass(el) {
if (!el.hasAttribute('data-focus-ring-added'))
return;
index(el).remove('focus-ring');
el.removeAttribute('data-focus-ring-added');
}
/**
* On `keydown`, set `hadKeyboardEvent`, add `focus-ring` class if the
* key was Tab.
* @param {Event} e
*/
function onKeyDown(e) {
if (e.altKey || e.ctrlKey || e.metaKey)
return;
if (e.keyCode != 9)
return;
hadKeyboardEvent = true;
}
/**
* On `focus`, add the `focus-ring` class to the target if:
* - the target received focus as a result of keyboard navigation
* - the event target is an element that will likely require interaction
* via the keyboard (e.g. a text box)
* @param {Event} e
*/
function onFocus(e) {
if (e.target == document)
return;
if (hadKeyboardEvent || focusTriggersKeyboardModality(e.target)) {
addFocusRingClass(e.target);
hadKeyboardEvent = false;
}
}
/**
* On `blur`, remove the `focus-ring` class from the target.
* @param {Event} e
*/
function onBlur(e) {
if (e.target == document)
return;
removeFocusRingClass(e.target);
}
/**
* When the window regains focus, restore the focus-ring class to the element
* to which it was previously applied.
*/
function onWindowFocus() {
if (document.activeElement == elWithFocusRing)
addFocusRingClass(elWithFocusRing);
elWithFocusRing = null;
}
/**
* When switching windows, keep track of the focused element if it has a
* focus-ring class.
*/
function onWindowBlur() {
if (index(document.activeElement).contains('focus-ring')) {
// Keep a reference to the element to which the focus-ring class is applied
// so the focus-ring class can be restored to it if the window regains
// focus after being blurred.
elWithFocusRing = document.activeElement;
}
}
document.addEventListener('keydown', onKeyDown, true);
document.addEventListener('focus', onFocus, true);
document.addEventListener('blur', onBlur, true);
window.addEventListener('focus', onWindowFocus, true);
window.addEventListener('blur', onWindowBlur, true);
index(document.body).add('js-focus-ring');
}
/**
* Subscription when the DOM is ready
* @param {Function} callback
*/
function onDOMReady(callback) {
if (document.readyState === 'complete') {
callback();
} else {
var loaded = false;
/**
* Callback wrapper for check loaded state
*/
function load() {
if (!loaded) {
loaded = true;
callback();
}
}
document.addEventListener('DOMContentLoaded', load, false);
window.addEventListener('load', load, false);
}
}
onDOMReady(init);
})));