summaryrefslogtreecommitdiffstats
path: root/devtools/client/accessibility/components/Accessible.js
blob: 02467ccaab453ea29a61dc8fb1013a80bccaac78 (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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
/* 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";

/* global EVENTS, gTelemetry */

// React & Redux
const {
  createFactory,
  Component,
} = require("resource://devtools/client/shared/vendor/react.js");
const {
  div,
  span,
} = require("resource://devtools/client/shared/vendor/react-dom-factories.js");
const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js");
const {
  findDOMNode,
} = require("resource://devtools/client/shared/vendor/react-dom.js");
const {
  connect,
} = require("resource://devtools/client/shared/vendor/react-redux.js");

const {
  TREE_ROW_HEIGHT,
  ORDERED_PROPS,
  ACCESSIBLE_EVENTS,
  VALUE_FLASHING_DURATION,
} = require("resource://devtools/client/accessibility/constants.js");
const {
  L10N,
} = require("resource://devtools/client/accessibility/utils/l10n.js");
const {
  flashElementOn,
  flashElementOff,
} = require("resource://devtools/client/inspector/markup/utils.js");
const {
  updateDetails,
} = require("resource://devtools/client/accessibility/actions/details.js");
const {
  select,
  unhighlight,
} = require("resource://devtools/client/accessibility/actions/accessibles.js");

const VirtualizedTree = createFactory(
  require("resource://devtools/client/shared/components/VirtualizedTree.js")
);
// Reps
const {
  REPS,
  MODE,
} = require("resource://devtools/client/shared/components/reps/index.js");
const { Rep, ElementNode, Accessible: AccessibleRep, Obj } = REPS;

const {
  translateNodeFrontToGrip,
} = require("resource://devtools/client/inspector/shared/utils.js");

loader.lazyRequireGetter(
  this,
  "openContentLink",
  "resource://devtools/client/shared/link.js",
  true
);

const TELEMETRY_NODE_INSPECTED_COUNT =
  "devtools.accessibility.node_inspected_count";

const TREE_DEPTH_PADDING_INCREMENT = 20;

class AccessiblePropertyClass extends Component {
  static get propTypes() {
    return {
      accessibleFrontActorID: PropTypes.string,
      object: PropTypes.any,
      focused: PropTypes.bool,
      children: PropTypes.func,
    };
  }

  componentDidUpdate({
    object: prevObject,
    accessibleFrontActorID: prevAccessibleFrontActorID,
  }) {
    const { accessibleFrontActorID, object, focused } = this.props;
    // Fast check if row is focused or if the value did not update.
    if (
      focused ||
      accessibleFrontActorID !== prevAccessibleFrontActorID ||
      prevObject === object ||
      (object && prevObject && typeof object === "object")
    ) {
      return;
    }

    this.flashRow();
  }

  flashRow() {
    const row = findDOMNode(this);
    flashElementOn(row);
    if (this._flashMutationTimer) {
      clearTimeout(this._flashMutationTimer);
      this._flashMutationTimer = null;
    }
    this._flashMutationTimer = setTimeout(() => {
      flashElementOff(row);
    }, VALUE_FLASHING_DURATION);
  }

  render() {
    return this.props.children();
  }
}

const AccessibleProperty = createFactory(AccessiblePropertyClass);

class Accessible extends Component {
  static get propTypes() {
    return {
      accessibleFront: PropTypes.object,
      dispatch: PropTypes.func.isRequired,
      nodeFront: PropTypes.object,
      items: PropTypes.array,
      labelledby: PropTypes.string.isRequired,
      parents: PropTypes.object,
      relations: PropTypes.object,
      toolbox: PropTypes.object.isRequired,
      toolboxHighlighter: PropTypes.object.isRequired,
      highlightAccessible: PropTypes.func.isRequired,
      unhighlightAccessible: PropTypes.func.isRequired,
    };
  }

  constructor(props) {
    super(props);

    this.state = {
      expanded: new Set(),
      active: null,
      focused: null,
    };

    this.onAccessibleInspected = this.onAccessibleInspected.bind(this);
    this.renderItem = this.renderItem.bind(this);
    this.update = this.update.bind(this);
  }

  // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
  UNSAFE_componentWillMount() {
    window.on(
      EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED,
      this.onAccessibleInspected
    );
  }

  // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507
  UNSAFE_componentWillReceiveProps({ accessibleFront }) {
    const oldAccessibleFront = this.props.accessibleFront;

    if (oldAccessibleFront) {
      if (
        accessibleFront &&
        accessibleFront.actorID === oldAccessibleFront.actorID
      ) {
        return;
      }
      ACCESSIBLE_EVENTS.forEach(event =>
        oldAccessibleFront.off(event, this.update)
      );
    }

    if (accessibleFront) {
      ACCESSIBLE_EVENTS.forEach(event =>
        accessibleFront.on(event, this.update)
      );
    }
  }

  componentDidUpdate(prevProps) {
    if (
      this.props.accessibleFront &&
      !this.props.accessibleFront.isDestroyed() &&
      this.props.accessibleFront !== prevProps.accessibleFront
    ) {
      window.emit(EVENTS.PROPERTIES_UPDATED);
    }
  }

  componentWillUnmount() {
    window.off(
      EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED,
      this.onAccessibleInspected
    );

    const { accessibleFront } = this.props;
    if (accessibleFront) {
      ACCESSIBLE_EVENTS.forEach(event =>
        accessibleFront.off(event, this.update)
      );
    }
  }

  onAccessibleInspected() {
    const { props } = this.refs;
    if (props) {
      props.refs.tree.focus();
    }
  }

  update() {
    const { dispatch, accessibleFront } = this.props;
    if (accessibleFront.isDestroyed()) {
      return;
    }

    dispatch(updateDetails(accessibleFront));
  }

  setExpanded(item, isExpanded) {
    const { expanded } = this.state;

    if (isExpanded) {
      expanded.add(item.path);
    } else {
      expanded.delete(item.path);
    }

    this.setState({ expanded });
  }

  async showHighlighter(nodeFront) {
    if (!this.props.toolboxHighlighter) {
      return;
    }

    await this.props.toolboxHighlighter.highlight(nodeFront);
  }

  async hideHighlighter() {
    if (!this.props.toolboxHighlighter) {
      return;
    }

    await this.props.toolboxHighlighter.unhighlight();
  }

  showAccessibleHighlighter(accessibleFront) {
    this.props.dispatch(unhighlight());
    this.props.highlightAccessible(accessibleFront);
  }

  hideAccessibleHighlighter(accessibleFront) {
    this.props.dispatch(unhighlight());
    this.props.unhighlightAccessible(accessibleFront);
  }

  async selectNode(nodeFront, reason = "accessibility") {
    if (gTelemetry) {
      gTelemetry.scalarAdd(TELEMETRY_NODE_INSPECTED_COUNT, 1);
    }

    if (!this.props.toolbox) {
      return;
    }

    const inspector = await this.props.toolbox.selectTool("inspector");
    inspector.selection.setNodeFront(nodeFront, reason);
  }

  async selectAccessible(accessibleFront) {
    if (!accessibleFront) {
      return;
    }

    await this.props.dispatch(select(accessibleFront));

    const { props } = this.refs;
    if (props) {
      props.refs.tree.blur();
    }
    await this.setState({ active: null, focused: null });

    window.emit(EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED);
  }

  openLink(link, e) {
    openContentLink(link);
  }

  renderItem(item, depth, focused, arrow, expanded) {
    const object = item.contents;
    const valueProps = {
      object,
      mode: MODE.TINY,
      title: "Object",
      openLink: this.openLink,
    };

    if (isNodeFront(object)) {
      valueProps.defaultRep = ElementNode;
      valueProps.onDOMNodeMouseOut = () => this.hideHighlighter();
      valueProps.onDOMNodeMouseOver = () =>
        this.showHighlighter(this.props.nodeFront);

      valueProps.inspectIconTitle = L10N.getStr(
        "accessibility.accessible.selectNodeInInspector.title"
      );
      valueProps.onInspectIconClick = () =>
        this.selectNode(this.props.nodeFront);
    } else if (isAccessibleFront(object)) {
      const target = findAccessibleTarget(this.props.relations, object.actor);
      valueProps.defaultRep = AccessibleRep;
      valueProps.onAccessibleMouseOut = () =>
        this.hideAccessibleHighlighter(target);
      valueProps.onAccessibleMouseOver = () =>
        this.showAccessibleHighlighter(target);
      valueProps.inspectIconTitle = L10N.getStr(
        "accessibility.accessible.selectElement.title"
      );
      valueProps.onInspectIconClick = (obj, e) => {
        e.stopPropagation();
        this.selectAccessible(target);
      };
      valueProps.separatorText = "";
    } else if (item.name === "relations") {
      valueProps.defaultRep = Obj;
    } else {
      valueProps.noGrip = true;
    }

    const classList = ["node", "object-node"];
    if (focused) {
      classList.push("focused");
    }

    const depthPadding = depth * TREE_DEPTH_PADDING_INCREMENT;

    return AccessibleProperty(
      {
        object,
        focused,
        accessibleFrontActorID: this.props.accessibleFront.actorID,
      },
      () =>
        div(
          {
            className: classList.join(" "),
            style: {
              paddingInlineStart: depthPadding,
              inlineSize: `calc(var(--accessibility-properties-item-width) - ${depthPadding}px)`,
            },
            onClick: e => {
              if (e.target.classList.contains("theme-twisty")) {
                this.setExpanded(item, !expanded);
              }
            },
          },
          arrow,
          span({ className: "object-label" }, item.name),
          span({ className: "object-delimiter" }, ":"),
          span({ className: "object-value" }, Rep(valueProps) || "")
        )
    );
  }

  render() {
    const { expanded, active, focused } = this.state;
    const { items, parents, accessibleFront, labelledby } = this.props;

    if (accessibleFront) {
      return VirtualizedTree({
        ref: "props",
        key: "accessible-properties",
        itemHeight: TREE_ROW_HEIGHT,
        getRoots: () => items,
        getKey: item => item.path,
        getParent: item => parents.get(item),
        getChildren: item => item.children,
        isExpanded: item => expanded.has(item.path),
        onExpand: item => this.setExpanded(item, true),
        onCollapse: item => this.setExpanded(item, false),
        onFocus: item => {
          if (this.state.focused !== item.path) {
            this.setState({ focused: item.path });
          }
        },
        onActivate: item => {
          if (item == null) {
            this.setState({ active: null });
          } else if (this.state.active !== item.path) {
            this.setState({ active: item.path });
          }
        },
        focused: findByPath(focused, items),
        active: findByPath(active, items),
        renderItem: this.renderItem,
        labelledby,
      });
    }

    return div(
      { className: "info" },
      L10N.getStr("accessibility.accessible.notAvailable")
    );
  }
}

/**
 * Match accessibility object from relations targets to the grip that's being activated.
 * @param  {Object} relations  Object containing relations grouped by type and targets.
 * @param  {String} actorID    Actor ID to match to the relation target.
 * @return {Object}            Accessible front that matches the relation target.
 */
const findAccessibleTarget = (relations, actorID) => {
  for (const relationType in relations) {
    let targets = relations[relationType];
    targets = Array.isArray(targets) ? targets : [targets];
    for (const target of targets) {
      if (target.actorID === actorID) {
        return target;
      }
    }
  }

  return null;
};

/**
 * Find an item based on a given path.
 * @param  {String} path
 *         Key of the item to be looked up.
 * @param  {Array}  items
 *         Accessibility properties array.
 * @return {Object?}
 *         Possibly found item.
 */
const findByPath = (path, items) => {
  for (const item of items) {
    if (item.path === path) {
      return item;
    }

    const found = findByPath(path, item.children);
    if (found) {
      return found;
    }
  }
  return null;
};

/**
 * Check if a given property is a DOMNode front.
 * @param  {Object?} value A property to check for being a DOMNode.
 * @return {Boolean}       A flag that indicates whether a property is a DOMNode.
 */
const isNodeFront = value => value && value.typeName === "domnode";

/**
 * Check if a given property is an Accessible front.
 * @param  {Object?} value A property to check for being an Accessible.
 * @return {Boolean}       A flag that indicates whether a property is an Accessible.
 */
const isAccessibleFront = value => value && value.typeName === "accessible";

/**
 * While waiting for a reps fix in https://github.com/firefox-devtools/reps/issues/92,
 * translate accessibleFront to a grip-like object that can be used with an Accessible
 * rep.
 *
 * @params  {accessibleFront} accessibleFront
 *          The AccessibleFront for which we want to create a grip-like object.
 * @returns {Object} a grip-like object that can be used with Reps.
 */
const translateAccessibleFrontToGrip = accessibleFront => ({
  actor: accessibleFront.actorID,
  typeName: accessibleFront.typeName,
  preview: {
    name: accessibleFront.name,
    role: accessibleFront.role,
    // All the grid containers are assumed to be in the Accessibility tree.
    isConnected: true,
  },
});

const translateNodeFrontToGripWrapper = nodeFront => ({
  ...translateNodeFrontToGrip(nodeFront),
  typeName: nodeFront.typeName,
});

/**
 * Build props ingestible by VirtualizedTree component.
 * @param  {Object} props      Component properties to be processed.
 * @param  {String} parentPath Unique path that is used to identify a Tree Node.
 * @return {Object}            Processed properties.
 */
const makeItemsForDetails = (props, parentPath) =>
  Object.getOwnPropertyNames(props).map(name => {
    let children = [];
    const path = `${parentPath}/${name}`;
    let contents = props[name];

    if (contents) {
      if (isNodeFront(contents)) {
        contents = translateNodeFrontToGripWrapper(contents);
        name = "DOMNode";
      } else if (isAccessibleFront(contents)) {
        contents = translateAccessibleFrontToGrip(contents);
      } else if (Array.isArray(contents) || typeof contents === "object") {
        children = makeItemsForDetails(contents, path);
      }
    }

    return { name, path, contents, children };
  });

const makeParentMap = items => {
  const map = new WeakMap();

  function _traverse(item) {
    if (item.children.length) {
      for (const child of item.children) {
        map.set(child, item);
        _traverse(child);
      }
    }
  }

  items.forEach(_traverse);
  return map;
};

const mapStateToProps = ({ details }) => {
  const {
    accessible: accessibleFront,
    DOMNode: nodeFront,
    relations,
  } = details;
  if (!accessibleFront || !nodeFront) {
    return {};
  }

  const items = makeItemsForDetails(
    ORDERED_PROPS.reduce((props, key) => {
      if (key === "DOMNode") {
        props.nodeFront = nodeFront;
      } else if (key === "relations") {
        props.relations = relations;
      } else {
        props[key] = accessibleFront[key];
      }

      return props;
    }, {}),
    ""
  );
  const parents = makeParentMap(items);

  return { accessibleFront, nodeFront, items, parents, relations };
};

module.exports = connect(mapStateToProps)(Accessible);