summaryrefslogtreecommitdiffstats
path: root/devtools/server/actors/highlighters/accessible.js
blob: 71124239f29e4d9630ed177cd4fa012c725c522e (plain)
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const {
  AutoRefreshHighlighter,
} = require("resource://devtools/server/actors/highlighters/auto-refresh.js");
const {
  CanvasFrameAnonymousContentHelper,
  isNodeValid,
} = require("resource://devtools/server/actors/highlighters/utils/markup.js");
const {
  TEXT_NODE,
  DOCUMENT_NODE,
} = require("resource://devtools/shared/dom-node-constants.js");
const {
  getCurrentZoom,
  setIgnoreLayoutChanges,
} = require("resource://devtools/shared/layout/utils.js");

loader.lazyRequireGetter(
  this,
  ["getBounds", "getBoundsXUL", "Infobar"],
  "resource://devtools/server/actors/highlighters/utils/accessibility.js",
  true
);

/**
 * The AccessibleHighlighter draws the bounds of an accessible object.
 *
 * Usage example:
 *
 * let h = new AccessibleHighlighter(env);
 * h.show(node, { x, y, w, h, [duration] });
 * h.hide();
 * h.destroy();
 *
 * @param {Number} options.x
 *        X coordinate of the top left corner of the accessible object
 * @param {Number} options.y
 *        Y coordinate of the top left corner of the accessible object
 * @param {Number} options.w
 *        Width of the the accessible object
 * @param {Number} options.h
 *        Height of the the accessible object
 * @param {Number} options.duration
 *        Duration of time that the highlighter should be shown.
 * @param {String|null} options.name
 *        Name of the the accessible object
 * @param {String} options.role
 *        Role of the the accessible object
 *
 * Structure:
 * <div class="highlighter-container" aria-hidden="true">
 *   <div class="accessible-root">
 *     <svg class="accessible-elements" hidden="true">
 *       <path class="accessible-bounds" points="..." />
 *     </svg>
 *     <div class="accessible-infobar-container">
 *      <div class="accessible-infobar">
 *        <div class="accessible-infobar-text">
 *          <span class="accessible-infobar-role">Accessible Role</span>
 *          <span class="accessible-infobar-name">Accessible Name</span>
 *        </div>
 *      </div>
 *     </div>
 *   </div>
 * </div>
 */
class AccessibleHighlighter extends AutoRefreshHighlighter {
  constructor(highlighterEnv) {
    super(highlighterEnv);
    this.ID_CLASS_PREFIX = "accessible-";
    this.accessibleInfobar = new Infobar(this);

    this.markup = new CanvasFrameAnonymousContentHelper(
      this.highlighterEnv,
      this._buildMarkup.bind(this)
    );
    this.isReady = this.markup.initialize();

    this.onPageHide = this.onPageHide.bind(this);
    this.onWillNavigate = this.onWillNavigate.bind(this);

    this.highlighterEnv.on("will-navigate", this.onWillNavigate);

    this.pageListenerTarget = highlighterEnv.pageListenerTarget;
    this.pageListenerTarget.addEventListener("pagehide", this.onPageHide);
  }

  /**
   * Static getter that indicates that AccessibleHighlighter supports
   * highlighting in XUL windows.
   */
  static get XULSupported() {
    return true;
  }

  get supportsSimpleHighlighters() {
    return true;
  }

  /**
   * Build highlighter markup.
   *
   * @return {Object} Container element for the highlighter markup.
   */
  _buildMarkup() {
    const container = this.markup.createNode({
      attributes: {
        class: "highlighter-container",
        "aria-hidden": "true",
      },
    });

    const root = this.markup.createNode({
      parent: container,
      attributes: {
        id: "root",
        class:
          "root" +
          (this.highlighterEnv.useSimpleHighlightersForReducedMotion
            ? " use-simple-highlighters"
            : ""),
      },
      prefix: this.ID_CLASS_PREFIX,
    });

    // Build the SVG element.
    const svg = this.markup.createSVGNode({
      nodeType: "svg",
      parent: root,
      attributes: {
        id: "elements",
        width: "100%",
        height: "100%",
        hidden: "true",
      },
      prefix: this.ID_CLASS_PREFIX,
    });

    this.markup.createSVGNode({
      nodeType: "path",
      parent: svg,
      attributes: {
        class: "bounds",
        id: "bounds",
      },
      prefix: this.ID_CLASS_PREFIX,
    });

    // Build the accessible's infobar markup.
    this.accessibleInfobar.buildMarkup(root);

    return container;
  }

  /**
   * Destroy the nodes. Remove listeners.
   */
  destroy() {
    if (this._highlightTimer) {
      clearTimeout(this._highlightTimer);
      this._highlightTimer = null;
    }

    this.highlighterEnv.off("will-navigate", this.onWillNavigate);
    this.pageListenerTarget.removeEventListener("pagehide", this.onPageHide);
    this.pageListenerTarget = null;

    AutoRefreshHighlighter.prototype.destroy.call(this);

    this.accessibleInfobar.destroy();
    this.accessibleInfobar = null;
    this.markup.destroy();
  }

  /**
   * Find an element in highlighter markup.
   *
   * @param  {String} id
   *         Highlighter markup elemet id attribute.
   * @return {DOMNode} Element in the highlighter markup.
   */
  getElement(id) {
    return this.markup.getElement(this.ID_CLASS_PREFIX + id);
  }

  /**
   * Check if node is a valid element, document or text node.
   *
   * @override  AutoRefreshHighlighter.prototype._isNodeValid
   * @param  {DOMNode} node
   *         The node to highlight.
   * @return {Boolean} whether or not node is valid.
   */
  _isNodeValid(node) {
    return (
      super._isNodeValid(node) ||
      isNodeValid(node, TEXT_NODE) ||
      isNodeValid(node, DOCUMENT_NODE)
    );
  }

  /**
   * Show the highlighter on a given accessible.
   *
   * @return {Boolean} True if accessible is highlighted, false otherwise.
   */
  _show() {
    if (this._highlightTimer) {
      clearTimeout(this._highlightTimer);
      this._highlightTimer = null;
    }

    const { duration } = this.options;
    const shown = this._update();
    if (shown) {
      this.emit("highlighter-event", { options: this.options, type: "shown" });
      if (duration) {
        this._highlightTimer = setTimeout(() => {
          this.hide();
        }, duration);
      }
    }

    return shown;
  }

  /**
   * Update and show accessible bounds for a current accessible.
   *
   * @return {Boolean} True if accessible is highlighted, false otherwise.
   */
  _update() {
    let shown = false;
    setIgnoreLayoutChanges(true);

    if (this._updateAccessibleBounds()) {
      this._showAccessibleBounds();

      this.accessibleInfobar.show();

      shown = true;
    } else {
      // Nothing to highlight (0px rectangle like a <script> tag for instance)
      this.hide();
    }

    setIgnoreLayoutChanges(
      false,
      this.highlighterEnv.window.document.documentElement
    );

    return shown;
  }

  /**
   * Hide the highlighter.
   */
  _hide() {
    setIgnoreLayoutChanges(true);
    this._hideAccessibleBounds();
    this.accessibleInfobar.hide();
    setIgnoreLayoutChanges(
      false,
      this.highlighterEnv.window.document.documentElement
    );
  }

  /**
   * Public API method to temporarily hide accessible bounds for things like
   * color contrast calculation.
   */
  hideAccessibleBounds() {
    if (this.getElement("elements").hasAttribute("hidden")) {
      return;
    }

    this._hideAccessibleBounds();
    this._shouldRestoreBoundsVisibility = true;
  }

  /**
   * Public API method to show accessible bounds in case they were temporarily
   * hidden.
   */
  showAccessibleBounds() {
    if (this._shouldRestoreBoundsVisibility) {
      this._showAccessibleBounds();
    }
  }

  /**
   * Hide the accessible bounds container.
   */
  _hideAccessibleBounds() {
    this._shouldRestoreBoundsVisibility = null;
    setIgnoreLayoutChanges(true);
    this.getElement("elements").setAttribute("hidden", "true");
    setIgnoreLayoutChanges(
      false,
      this.highlighterEnv.window.document.documentElement
    );
  }

  /**
   * Show the accessible bounds container.
   */
  _showAccessibleBounds() {
    this._shouldRestoreBoundsVisibility = null;
    if (!this.currentNode || !this.highlighterEnv.window) {
      return;
    }

    setIgnoreLayoutChanges(true);
    this.getElement("elements").removeAttribute("hidden");
    setIgnoreLayoutChanges(
      false,
      this.highlighterEnv.window.document.documentElement
    );
  }

  /**
   * Get current accessible bounds.
   *
   * @return {Object|null} Returns, if available, positioning and bounds
   *                       information for the accessible object.
   */
  get _bounds() {
    let { win, options } = this;
    let getBoundsFn = getBounds;
    if (this.options.isXUL) {
      // Zoom level for the top level browser window does not change and only
      // inner frames do. So we need to get the zoom level of the current node's
      // parent window.
      let zoom = getCurrentZoom(this.currentNode);
      zoom *= zoom;
      options = { ...options, zoom };
      getBoundsFn = getBoundsXUL;
      win = this.win.parent.ownerGlobal;
    }

    return getBoundsFn(win, options);
  }

  /**
   * Update accessible bounds for a current accessible. Re-draw highlighter
   * markup.
   *
   * @return {Boolean} True if accessible is highlighted, false otherwise.
   */
  _updateAccessibleBounds() {
    const bounds = this._bounds;
    if (!bounds) {
      this._hide();
      return false;
    }

    const boundsEl = this.getElement("bounds");
    const { left, right, top, bottom } = bounds;
    const path = `M${left},${top} L${right},${top} L${right},${bottom} L${left},${bottom} L${left},${top}`;
    boundsEl.setAttribute("d", path);

    // Un-zoom the root wrapper if the page was zoomed.
    const rootId = this.ID_CLASS_PREFIX + "elements";
    this.markup.scaleRootElement(this.currentNode, rootId);

    return true;
  }

  /**
   * Hide highlighter on page hide.
   */
  onPageHide({ target }) {
    // If a pagehide event is triggered for current window's highlighter, hide
    // the highlighter.
    if (target.defaultView === this.win) {
      this.hide();
    }
  }

  /**
   * Hide highlighter on navigation.
   */
  onWillNavigate({ isTopLevel }) {
    if (isTopLevel) {
      this.hide();
    }
  }
}

exports.AccessibleHighlighter = AccessibleHighlighter;