• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5cr.define('cr.ui', function() {
6
7  /**
8   * The class name to set on the document element.
9   * @const
10   */
11  var CLASS_NAME = 'focus-outline-visible';
12
13  /**
14   * This class sets a CSS class name on the HTML element of |doc| when the user
15   * presses the tab key. It removes the class name when the user clicks
16   * anywhere.
17   *
18   * This allows you to write CSS like this:
19   *
20   * html.focus-outline-visible my-element:focus {
21   *   outline: 5px auto -webkit-focus-ring-color;
22   * }
23   *
24   * And the outline will only be shown if the user uses the keyboard to get to
25   * it.
26   *
27   * @param {Document} doc The document to attach the focus outline manager to.
28   * @constructor
29   */
30  function FocusOutlineManager(doc) {
31    this.classList_ = doc.documentElement.classList;
32    var self = this;
33    doc.addEventListener('keydown', function(e) {
34      if (e.keyCode == 9)  // Tab
35        self.visible = true;
36    }, true);
37
38    doc.addEventListener('mousedown', function(e) {
39      self.visible = false;
40    }, true);
41  }
42
43  FocusOutlineManager.prototype = {
44    /**
45     * Whether the focus outline should be visible.
46     * @type {boolean}
47     */
48    set visible(visible) {
49      if (visible)
50        this.classList_.add(CLASS_NAME);
51      else
52        this.classList_.remove(CLASS_NAME);
53    },
54    get visible() {
55      this.classList_.contains(CLASS_NAME);
56    }
57  };
58
59  /**
60   * Array of Document and FocusOutlineManager pairs.
61   * @type {Array}
62   */
63  var docsToManager = [];
64
65  /**
66   * Gets a per document sigleton focus outline manager.
67   * @param {Document} doc The document to get the |FocusOutlineManager| for.
68   * @return {FocusOutlineManager} The per document singleton focus outline
69   *     manager.
70   */
71  FocusOutlineManager.forDocument = function(doc) {
72    for (var i = 0; i < docsToManager.length; i++) {
73      if (doc == docsToManager[i][0])
74        return docsToManager[i][1];
75    }
76    var manager = new FocusOutlineManager(doc);
77    docsToManager.push([doc, manager]);
78    return manager;
79  };
80
81  return {
82    FocusOutlineManager: FocusOutlineManager
83  };
84});
85