-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfocus-outline-manager.js
84 lines (71 loc) · 2.05 KB
/
focus-outline-manager.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
// Copyright (c) 2012 The Chromium Authors, Vladimirs. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* focus-outline-manager
*
* Watch users keyboard input and manage the focus outline visibility
*/
/**
* The class name to set on the document element.
* @const
*/
var CLASS_NAME = 'focus-outline-hidden';
/**
* This class sets a CSS class name on the HTML element when a user presses the
* tab key. It removes the class name when the user clicks anywhere.
*
* This allows you to write CSS like this:
*
* html.focus-outline-hidden *:focus {
* outline: none;
* }
*
* And the outline will only be shown if the user uses the keyboard to get to it.
*
* @constructor
*/
function FocusOutlineManager () {
var that = this;
document.addEventListener('keydown', function (e) {
that.focusByKeyboard = true;
}, true);
document.addEventListener('mousedown', function (e) {
that.focusByKeyboard = false;
}, true);
document.addEventListener('focus', function (event) {
// Update visibility only when focus is actually changed.
that.updateVisibility();
}, true);
document.addEventListener('focusout', function (event) {
window.setTimeout(function () {
if (!document.hasFocus()) {
that.focusByKeyboard = true;
that.updateVisibility();
}
}, 0);
});
this.updateVisibility();
}
FocusOutlineManager.prototype = {
/**
* Whether focus change is triggered by TAB key.
* @type {boolean}
* @private
*/
focusByKeyboard: true,
updateVisibility: function () {
this.hidden = !this.focusByKeyboard;
},
/**
* Whether the focus outline should be hidden.
* @type {boolean}
*/
set hidden(hidden) {
document.documentElement.classList.toggle(CLASS_NAME, hidden);
},
get hidden() {
return document.documentElement.classList.contains(CLASS_NAME);
}
};
new FocusOutlineManager();