From 26a029d407be480d791972afb5975cf62c9360a6 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Fri, 19 Apr 2024 02:47:55 +0200 Subject: Adding upstream version 124.0.1. Signed-off-by: Daniel Baumann --- .../client/accessibility/accessibility-proxy.js | 595 +++ .../client/accessibility/accessibility-view.js | 260 ++ devtools/client/accessibility/accessibility.css | 850 ++++ .../client/accessibility/actions/accessibles.js | 70 + devtools/client/accessibility/actions/audit.js | 36 + devtools/client/accessibility/actions/details.js | 40 + devtools/client/accessibility/actions/moz.build | 5 + .../client/accessibility/actions/simulation.js | 16 + devtools/client/accessibility/actions/ui.js | 77 + .../accessibility/components/AccessibilityPrefs.js | 109 + .../accessibility/components/AccessibilityRow.js | 328 ++ .../components/AccessibilityRowValue.js | 58 + .../accessibility/components/AccessibilityTree.js | 298 ++ .../components/AccessibilityTreeFilter.js | 171 + .../client/accessibility/components/Accessible.js | 563 +++ .../accessibility/components/AuditController.js | 90 + .../client/accessibility/components/AuditFilter.js | 91 + .../components/AuditProgressOverlay.js | 92 + devtools/client/accessibility/components/Badge.js | 40 + devtools/client/accessibility/components/Badges.js | 88 + devtools/client/accessibility/components/Button.js | 112 + devtools/client/accessibility/components/Check.js | 157 + devtools/client/accessibility/components/Checks.js | 117 + .../components/ColorContrastAccessibility.js | 229 ++ .../accessibility/components/ContrastBadge.js | 55 + .../client/accessibility/components/Description.js | 56 + .../components/DisplayTabbingOrder.js | 79 + .../accessibility/components/KeyboardBadge.js | 56 + .../accessibility/components/KeyboardCheck.js | 94 + .../accessibility/components/LearnMoreLink.js | 76 + .../client/accessibility/components/MainFrame.js | 245 ++ .../accessibility/components/RightSidebar.js | 67 + .../components/SimulationMenuButton.js | 167 + .../accessibility/components/TextLabelBadge.js | 57 + .../accessibility/components/TextLabelCheck.js | 225 + .../client/accessibility/components/Toolbar.js | 74 + devtools/client/accessibility/components/moz.build | 33 + devtools/client/accessibility/constants.js | 197 + devtools/client/accessibility/index.html | 42 + devtools/client/accessibility/main.js | 17 + devtools/client/accessibility/moz.build | 20 + devtools/client/accessibility/panel.js | 350 ++ devtools/client/accessibility/picker.js | 189 + devtools/client/accessibility/provider.js | 112 + .../client/accessibility/reducers/accessibles.js | 158 + devtools/client/accessibility/reducers/audit.js | 109 + devtools/client/accessibility/reducers/details.js | 60 + devtools/client/accessibility/reducers/index.js | 28 + devtools/client/accessibility/reducers/moz.build | 7 + .../client/accessibility/reducers/simulation.js | 52 + devtools/client/accessibility/reducers/ui.js | 217 + .../client/accessibility/test/browser/browser.toml | 73 + .../browser_accessibility_context_menu_browser.js | 74 + ...browser_accessibility_context_menu_inspector.js | 104 + .../browser_accessibility_fission_switch_target.js | 58 + .../browser/browser_accessibility_mutations.js | 217 + ...wser_accessibility_panel_audit_hidden_iframe.js | 66 + .../browser_accessibility_panel_audit_oop.js | 109 + .../browser_accessibility_panel_toolbar_checks.js | 114 + ...wser_accessibility_panel_toolbar_pref_scroll.js | 73 + .../browser/browser_accessibility_print_to_json.js | 245 ++ .../browser_accessibility_relation_navigation.js | 169 + .../test/browser/browser_accessibility_reload.js | 107 + .../test/browser/browser_accessibility_sidebar.js | 81 + .../browser_accessibility_sidebar_checks.js | 83 + .../browser_accessibility_sidebar_dom_nodes.js | 111 + .../browser/browser_accessibility_simulation.js | 99 + ...wser_accessibility_tabbing_order_highlighter.js | 140 + ...lity_tabbing_order_highlighter_iframe_picker.js | 195 + .../test/browser/browser_accessibility_tree.js | 75 + .../browser/browser_accessibility_tree_audit.js | 137 + .../browser_accessibility_tree_audit_long.js | 104 + .../browser_accessibility_tree_audit_reset.js | 109 + .../browser_accessibility_tree_audit_toolbar.js | 112 + .../browser/browser_accessibility_tree_contrast.js | 62 + .../browser_accessibility_tree_iframe_picker.js | 121 + .../browser_accessibility_tree_navigation.js | 186 + .../browser_accessibility_tree_navigation_oop.js | 149 + devtools/client/accessibility/test/browser/head.js | 819 ++++ .../client/accessibility/test/chrome/chrome.toml | 16 + .../test/chrome/contrast.snapshots.js | 262 ++ devtools/client/accessibility/test/chrome/head.js | 32 + .../test/chrome/test_accessible_contrast.html | 84 + .../test/chrome/test_accessible_learnMoreLink.html | 97 + .../test/chrome/test_accessible_openLink.html | 111 + .../test/chrome/test_accessible_relations.html | 103 + .../chrome/test_accessible_row_context_menu.html | 148 + .../client/accessibility/test/node/.eslintrc.js | 11 + devtools/client/accessibility/test/node/README.md | 22 + .../client/accessibility/test/node/babel.config.js | 15 + .../__snapshots__/accessibility-prefs.test.js.snap | 7 + .../accessibility-row-value.test.js.snap | 3 + .../accessibility-tree-filter.test.js.snap | 39 + .../__snapshots__/audit-controller.test.js.snap | 7 + .../__snapshots__/audit-filter.test.js.snap | 13 + .../audit-progress-overlay.test.js.snap | 13 + .../components/__snapshots__/badge.test.js.snap | 3 + .../components/__snapshots__/badges.test.js.snap | 15 + .../components/__snapshots__/check.test.js.snap | 5 + .../__snapshots__/contrast-badge.test.js.snap | 11 + .../display-tabbing-order.test.js.snap | 9 + .../__snapshots__/keyboard-badge.test.js.snap | 7 + .../__snapshots__/keyboard-check.test.js.snap | 9 + .../__snapshots__/text-label-badge.test.js.snap | 9 + .../__snapshots__/text-label-check.test.js.snap | 13 + .../node/components/accessibility-prefs.test.js | 107 + .../components/accessibility-row-value.test.js | 56 + .../components/accessibility-tree-filter.test.js | 437 ++ .../test/node/components/audit-controller.test.js | 91 + .../test/node/components/audit-filter.test.js | 153 + .../node/components/audit-progress-overlay.test.js | 148 + .../test/node/components/badge.test.js | 42 + .../test/node/components/badges.test.js | 114 + .../test/node/components/check.test.js | 50 + .../test/node/components/contrast-badge.test.js | 96 + .../node/components/display-tabbing-order.test.js | 91 + .../test/node/components/keyboard-badge.test.js | 73 + .../test/node/components/keyboard-check.test.js | 47 + .../test/node/components/text-label-badge.test.js | 86 + .../test/node/components/text-label-check.test.js | 52 + devtools/client/accessibility/test/node/helpers.js | 134 + .../client/accessibility/test/node/jest.config.js | 19 + .../client/accessibility/test/node/package.json | 27 + devtools/client/accessibility/test/node/setup.js | 15 + devtools/client/accessibility/test/node/yarn.lock | 4316 ++++++++++++++++++++ devtools/client/accessibility/utils/audit.js | 45 + devtools/client/accessibility/utils/l10n.js | 11 + devtools/client/accessibility/utils/moz.build | 5 + 128 files changed, 18605 insertions(+) create mode 100644 devtools/client/accessibility/accessibility-proxy.js create mode 100644 devtools/client/accessibility/accessibility-view.js create mode 100644 devtools/client/accessibility/accessibility.css create mode 100644 devtools/client/accessibility/actions/accessibles.js create mode 100644 devtools/client/accessibility/actions/audit.js create mode 100644 devtools/client/accessibility/actions/details.js create mode 100644 devtools/client/accessibility/actions/moz.build create mode 100644 devtools/client/accessibility/actions/simulation.js create mode 100644 devtools/client/accessibility/actions/ui.js create mode 100644 devtools/client/accessibility/components/AccessibilityPrefs.js create mode 100644 devtools/client/accessibility/components/AccessibilityRow.js create mode 100644 devtools/client/accessibility/components/AccessibilityRowValue.js create mode 100644 devtools/client/accessibility/components/AccessibilityTree.js create mode 100644 devtools/client/accessibility/components/AccessibilityTreeFilter.js create mode 100644 devtools/client/accessibility/components/Accessible.js create mode 100644 devtools/client/accessibility/components/AuditController.js create mode 100644 devtools/client/accessibility/components/AuditFilter.js create mode 100644 devtools/client/accessibility/components/AuditProgressOverlay.js create mode 100644 devtools/client/accessibility/components/Badge.js create mode 100644 devtools/client/accessibility/components/Badges.js create mode 100644 devtools/client/accessibility/components/Button.js create mode 100644 devtools/client/accessibility/components/Check.js create mode 100644 devtools/client/accessibility/components/Checks.js create mode 100644 devtools/client/accessibility/components/ColorContrastAccessibility.js create mode 100644 devtools/client/accessibility/components/ContrastBadge.js create mode 100644 devtools/client/accessibility/components/Description.js create mode 100644 devtools/client/accessibility/components/DisplayTabbingOrder.js create mode 100644 devtools/client/accessibility/components/KeyboardBadge.js create mode 100644 devtools/client/accessibility/components/KeyboardCheck.js create mode 100644 devtools/client/accessibility/components/LearnMoreLink.js create mode 100644 devtools/client/accessibility/components/MainFrame.js create mode 100644 devtools/client/accessibility/components/RightSidebar.js create mode 100644 devtools/client/accessibility/components/SimulationMenuButton.js create mode 100644 devtools/client/accessibility/components/TextLabelBadge.js create mode 100644 devtools/client/accessibility/components/TextLabelCheck.js create mode 100644 devtools/client/accessibility/components/Toolbar.js create mode 100644 devtools/client/accessibility/components/moz.build create mode 100644 devtools/client/accessibility/constants.js create mode 100644 devtools/client/accessibility/index.html create mode 100644 devtools/client/accessibility/main.js create mode 100644 devtools/client/accessibility/moz.build create mode 100644 devtools/client/accessibility/panel.js create mode 100644 devtools/client/accessibility/picker.js create mode 100644 devtools/client/accessibility/provider.js create mode 100644 devtools/client/accessibility/reducers/accessibles.js create mode 100644 devtools/client/accessibility/reducers/audit.js create mode 100644 devtools/client/accessibility/reducers/details.js create mode 100644 devtools/client/accessibility/reducers/index.js create mode 100644 devtools/client/accessibility/reducers/moz.build create mode 100644 devtools/client/accessibility/reducers/simulation.js create mode 100644 devtools/client/accessibility/reducers/ui.js create mode 100644 devtools/client/accessibility/test/browser/browser.toml create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_context_menu_browser.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_context_menu_inspector.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_fission_switch_target.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_mutations.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_hidden_iframe.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_oop.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_checks.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_pref_scroll.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_print_to_json.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_relation_navigation.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_reload.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_sidebar.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_sidebar_checks.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_sidebar_dom_nodes.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_simulation.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter_iframe_picker.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_audit.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_long.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_reset.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_toolbar.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_contrast.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_iframe_picker.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation.js create mode 100644 devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation_oop.js create mode 100644 devtools/client/accessibility/test/browser/head.js create mode 100644 devtools/client/accessibility/test/chrome/chrome.toml create mode 100644 devtools/client/accessibility/test/chrome/contrast.snapshots.js create mode 100644 devtools/client/accessibility/test/chrome/head.js create mode 100644 devtools/client/accessibility/test/chrome/test_accessible_contrast.html create mode 100644 devtools/client/accessibility/test/chrome/test_accessible_learnMoreLink.html create mode 100644 devtools/client/accessibility/test/chrome/test_accessible_openLink.html create mode 100644 devtools/client/accessibility/test/chrome/test_accessible_relations.html create mode 100644 devtools/client/accessibility/test/chrome/test_accessible_row_context_menu.html create mode 100644 devtools/client/accessibility/test/node/.eslintrc.js create mode 100644 devtools/client/accessibility/test/node/README.md create mode 100644 devtools/client/accessibility/test/node/babel.config.js create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/accessibility-prefs.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/accessibility-row-value.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/accessibility-tree-filter.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/audit-controller.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/audit-filter.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/audit-progress-overlay.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/badge.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/badges.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/check.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/contrast-badge.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/display-tabbing-order.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/keyboard-badge.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/keyboard-check.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/text-label-badge.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/__snapshots__/text-label-check.test.js.snap create mode 100644 devtools/client/accessibility/test/node/components/accessibility-prefs.test.js create mode 100644 devtools/client/accessibility/test/node/components/accessibility-row-value.test.js create mode 100644 devtools/client/accessibility/test/node/components/accessibility-tree-filter.test.js create mode 100644 devtools/client/accessibility/test/node/components/audit-controller.test.js create mode 100644 devtools/client/accessibility/test/node/components/audit-filter.test.js create mode 100644 devtools/client/accessibility/test/node/components/audit-progress-overlay.test.js create mode 100644 devtools/client/accessibility/test/node/components/badge.test.js create mode 100644 devtools/client/accessibility/test/node/components/badges.test.js create mode 100644 devtools/client/accessibility/test/node/components/check.test.js create mode 100644 devtools/client/accessibility/test/node/components/contrast-badge.test.js create mode 100644 devtools/client/accessibility/test/node/components/display-tabbing-order.test.js create mode 100644 devtools/client/accessibility/test/node/components/keyboard-badge.test.js create mode 100644 devtools/client/accessibility/test/node/components/keyboard-check.test.js create mode 100644 devtools/client/accessibility/test/node/components/text-label-badge.test.js create mode 100644 devtools/client/accessibility/test/node/components/text-label-check.test.js create mode 100644 devtools/client/accessibility/test/node/helpers.js create mode 100644 devtools/client/accessibility/test/node/jest.config.js create mode 100644 devtools/client/accessibility/test/node/package.json create mode 100644 devtools/client/accessibility/test/node/setup.js create mode 100644 devtools/client/accessibility/test/node/yarn.lock create mode 100644 devtools/client/accessibility/utils/audit.js create mode 100644 devtools/client/accessibility/utils/l10n.js create mode 100644 devtools/client/accessibility/utils/moz.build (limited to 'devtools/client/accessibility') diff --git a/devtools/client/accessibility/accessibility-proxy.js b/devtools/client/accessibility/accessibility-proxy.js new file mode 100644 index 0000000000..287ea44b71 --- /dev/null +++ b/devtools/client/accessibility/accessibility-proxy.js @@ -0,0 +1,595 @@ +/* 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"; + +loader.lazyRequireGetter( + this, + "CombinedProgress", + "resource://devtools/client/accessibility/utils/audit.js", + true +); + +const { + accessibility: { AUDIT_TYPE }, +} = require("resource://devtools/shared/constants.js"); +const { + FILTERS, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Component responsible for tracking all Accessibility fronts in parent and + * content processes. + */ +class AccessibilityProxy { + #panel; + constructor(commands, panel) { + this.commands = commands; + this.#panel = panel; + + this._accessibilityWalkerFronts = new Set(); + this.lifecycleEvents = new Map(); + this.accessibilityEvents = new Map(); + this.supports = {}; + + this.audit = this.audit.bind(this); + this.enableAccessibility = this.enableAccessibility.bind(this); + this.getAccessibilityTreeRoot = this.getAccessibilityTreeRoot.bind(this); + this.resetAccessiblity = this.resetAccessiblity.bind(this); + this.startListeningForAccessibilityEvents = + this.startListeningForAccessibilityEvents.bind(this); + this.startListeningForLifecycleEvents = + this.startListeningForLifecycleEvents.bind(this); + this.startListeningForParentLifecycleEvents = + this.startListeningForParentLifecycleEvents.bind(this); + this.stopListeningForAccessibilityEvents = + this.stopListeningForAccessibilityEvents.bind(this); + this.stopListeningForLifecycleEvents = + this.stopListeningForLifecycleEvents.bind(this); + this.stopListeningForParentLifecycleEvents = + this.stopListeningForParentLifecycleEvents.bind(this); + this.highlightAccessible = this.highlightAccessible.bind(this); + this.unhighlightAccessible = this.unhighlightAccessible.bind(this); + this.onTargetAvailable = this.onTargetAvailable.bind(this); + this.onTargetDestroyed = this.onTargetDestroyed.bind(this); + this.onTargetSelected = this.onTargetSelected.bind(this); + this.onResourceAvailable = this.onResourceAvailable.bind(this); + this.onAccessibilityFrontAvailable = + this.onAccessibilityFrontAvailable.bind(this); + this.onAccessibilityFrontDestroyed = + this.onAccessibilityFrontDestroyed.bind(this); + this.onAccessibleWalkerFrontAvailable = + this.onAccessibleWalkerFrontAvailable.bind(this); + this.onAccessibleWalkerFrontDestroyed = + this.onAccessibleWalkerFrontDestroyed.bind(this); + this.unhighlightBeforeCalling = this.unhighlightBeforeCalling.bind(this); + this.toggleDisplayTabbingOrder = this.toggleDisplayTabbingOrder.bind(this); + } + + get enabled() { + return this.accessibilityFront && this.accessibilityFront.enabled; + } + + /** + * Indicates whether the accessibility service is enabled. + */ + get canBeEnabled() { + return this.parentAccessibilityFront.canBeEnabled; + } + + get currentTarget() { + return this.commands.targetCommand.selectedTargetFront; + } + + /** + * Perform an audit for a given filter. + * + * @param {String} filter + * Type of an audit to perform. + * @param {Function} onProgress + * Audit progress callback. + * + * @return {Promise} + * Resolves when the audit for every document, that each of the frame + * accessibility walkers traverse, completes. + */ + async audit(filter, onProgress) { + const types = filter === FILTERS.ALL ? Object.values(AUDIT_TYPE) : [filter]; + + const targetTypes = [this.commands.targetCommand.TYPES.FRAME]; + const targets = + await this.commands.targetCommand.getAllTargetsInSelectedTargetTree( + targetTypes + ); + + const progress = new CombinedProgress({ + onProgress, + totalFrames: targets.length, + }); + const audits = await this.withAllAccessibilityWalkerFronts( + async accessibleWalkerFront => + accessibleWalkerFront.audit({ + types, + onProgress: progress.onProgressForWalker.bind( + progress, + accessibleWalkerFront + ), + // If a frame was selected in the iframe picker, we don't want to retrieve the + // ancestries at it would mess with the tree structure and would make it misbehave. + retrieveAncestries: + this.commands.targetCommand.isTopLevelTargetSelected(), + }) + ); + + // Accumulate all audits into a single structure. + const combinedAudit = { ancestries: [] }; + for (const audit of audits) { + // If any of the audits resulted in an error, no need to continue. + if (audit.error) { + return audit; + } + + combinedAudit.ancestries.push(...audit.ancestries); + } + + return combinedAudit; + } + + async toggleDisplayTabbingOrder(displayTabbingOrder) { + if (displayTabbingOrder) { + const { walker: domWalkerFront } = await this.currentTarget.getFront( + "inspector" + ); + await this.accessibilityFront.accessibleWalkerFront.showTabbingOrder( + await domWalkerFront.getRootNode(), + 0 + ); + } else { + // we don't want to use withAllAccessibilityWalkerFronts as it only acts on selected + // target tree, and we want to hide _all_ highlighters. + const accessibilityFronts = + await this.commands.targetCommand.getAllFronts( + [this.commands.targetCommand.TYPES.FRAME], + "accessibility" + ); + await Promise.all( + accessibilityFronts.map(accessibilityFront => + accessibilityFront.accessibleWalkerFront.hideTabbingOrder() + ) + ); + } + } + + async enableAccessibility() { + // Accessibility service is initialized using the parent accessibility + // front. That, in turn, initializes accessibility service in all content + // processes. We need to wait until that happens to be sure platform + // accessibility is fully enabled. + const enabled = this.accessibilityFront.once("init"); + await this.parentAccessibilityFront.enable(); + await enabled; + } + + /** + * Return the topmost level accessibility walker to be used as the root of + * the accessibility tree view. + * + * @return {Object} + * Topmost accessibility walker. + */ + getAccessibilityTreeRoot() { + return this.accessibilityFront.accessibleWalkerFront; + } + + /** + * Look up accessibility fronts (get an existing one or create a new one) for + * all existing target fronts and run a task with each one of them. + * @param {Function} task + * Function to execute with each accessiblity front. + */ + async withAllAccessibilityFronts(taskFn) { + const accessibilityFronts = await this.commands.targetCommand.getAllFronts( + [this.commands.targetCommand.TYPES.FRAME], + "accessibility", + { + // only get the fronts for the selected frame tree, in case a specific document + // is selected in the iframe picker (if not, the top-level target is considered + // as the selected target) + onlyInSelectedTargetTree: true, + } + ); + const tasks = []; + for (const accessibilityFront of accessibilityFronts) { + tasks.push(taskFn(accessibilityFront)); + } + + return Promise.all(tasks); + } + + /** + * Look up accessibility walker fronts (get an existing one or create a new + * one using accessibility front) for all existing target fronts and run a + * task with each one of them. + * @param {Function} task + * Function to execute with each accessiblity walker front. + */ + withAllAccessibilityWalkerFronts(taskFn) { + return this.withAllAccessibilityFronts(async accessibilityFront => + taskFn(accessibilityFront.accessibleWalkerFront) + ); + } + + /** + * Unhighlight previous accessible object if we switched between processes and + * call the appropriate event handler. + */ + unhighlightBeforeCalling(listener) { + return async accessible => { + if (accessible) { + const accessibleWalkerFront = accessible.getParent(); + if (this._currentAccessibleWalkerFront !== accessibleWalkerFront) { + if (this._currentAccessibleWalkerFront) { + await this._currentAccessibleWalkerFront.unhighlight(); + } + + this._currentAccessibleWalkerFront = accessibleWalkerFront; + } + } + + await listener(accessible); + }; + } + + /** + * Start picking and add walker listeners. + * @param {Boolean} doFocus + * If true, move keyboard focus into content. + */ + pick(doFocus, onHovered, onPicked, onPreviewed, onCanceled) { + return this.withAllAccessibilityWalkerFronts( + async accessibleWalkerFront => { + this.startListening(accessibleWalkerFront, { + events: { + "picker-accessible-hovered": + this.unhighlightBeforeCalling(onHovered), + "picker-accessible-picked": this.unhighlightBeforeCalling(onPicked), + "picker-accessible-previewed": + this.unhighlightBeforeCalling(onPreviewed), + "picker-accessible-canceled": + this.unhighlightBeforeCalling(onCanceled), + }, + // Only register listeners once (for top level), no need to register + // them for all walkers again and again. + register: accessibleWalkerFront.targetFront.isTopLevel, + }); + await accessibleWalkerFront.pick( + // Only pass doFocus to the top level accessibility walker front. + doFocus && accessibleWalkerFront.targetFront.isTopLevel + ); + } + ); + } + + /** + * Stop picking and remove all walker listeners. + */ + async cancelPick() { + this._currentAccessibleWalkerFront = null; + return this.withAllAccessibilityWalkerFronts( + async accessibleWalkerFront => { + await accessibleWalkerFront.cancelPick(); + this.stopListening(accessibleWalkerFront, { + events: { + "picker-accessible-hovered": null, + "picker-accessible-picked": null, + "picker-accessible-previewed": null, + "picker-accessible-canceled": null, + }, + // Only unregister listeners once (for top level), no need to + // unregister them for all walkers again and again. + unregister: accessibleWalkerFront.targetFront.isTopLevel, + }); + } + ); + } + + async resetAccessiblity() { + const { enabled } = this.accessibilityFront; + const { canBeEnabled, canBeDisabled } = this.parentAccessibilityFront; + return { enabled, canBeDisabled, canBeEnabled }; + } + + startListening(front, { events, register = false } = {}) { + for (const [type, listener] of Object.entries(events)) { + front.on(type, listener); + if (register) { + this.registerEvent(front, type, listener); + } + } + } + + stopListening(front, { events, unregister = false } = {}) { + for (const [type, listener] of Object.entries(events)) { + front.off(type, listener); + if (unregister) { + this.unregisterEvent(front, type, listener); + } + } + } + + startListeningForAccessibilityEvents(events) { + for (const accessibleWalkerFront of this._accessibilityWalkerFronts.values()) { + this.startListening(accessibleWalkerFront, { + events, + // Only register listeners once (for top level), no need to register + // them for all walkers again and again. + register: accessibleWalkerFront.targetFront.isTopLevel, + }); + } + } + + stopListeningForAccessibilityEvents(events) { + for (const accessibleWalkerFront of this._accessibilityWalkerFronts.values()) { + this.stopListening(accessibleWalkerFront, { + events, + // Only unregister listeners once (for top level), no need to unregister + // them for all walkers again and again. + unregister: accessibleWalkerFront.targetFront.isTopLevel, + }); + } + } + + startListeningForLifecycleEvents(events) { + this.startListening(this.accessibilityFront, { events, register: true }); + } + + stopListeningForLifecycleEvents(events) { + this.stopListening(this.accessibilityFront, { events, unregister: true }); + } + + startListeningForParentLifecycleEvents(events) { + this.startListening(this.parentAccessibilityFront, { + events, + register: false, + }); + } + + stopListeningForParentLifecycleEvents(events) { + this.stopListening(this.parentAccessibilityFront, { + events, + unregister: false, + }); + } + + highlightAccessible(accessibleFront, options) { + if (!accessibleFront) { + return; + } + + const accessibleWalkerFront = accessibleFront.getParent(); + if (!accessibleWalkerFront) { + return; + } + + accessibleWalkerFront + .highlightAccessible(accessibleFront, options) + .catch(error => { + // Only report an error where there's still a commands instance. + // Ignore cases where toolbox is already destroyed. + if (this.commands) { + console.error(error); + } + }); + } + + unhighlightAccessible(accessibleFront) { + if (!accessibleFront) { + return; + } + + const accessibleWalkerFront = accessibleFront.getParent(); + if (!accessibleWalkerFront) { + return; + } + + accessibleWalkerFront.unhighlight().catch(error => { + // Only report an error where there's still a commands instance. + // Ignore cases where toolbox is already destroyed. + if (this.commands) { + console.error(error); + } + }); + } + + async initialize() { + await this.commands.targetCommand.watchTargets({ + types: [this.commands.targetCommand.TYPES.FRAME], + onAvailable: this.onTargetAvailable, + onSelected: this.onTargetSelected, + onDestroyed: this.onTargetDestroyed, + }); + await this.commands.resourceCommand.watchResources( + [this.commands.resourceCommand.TYPES.DOCUMENT_EVENT], + { + onAvailable: this.onResourceAvailable, + } + ); + this.parentAccessibilityFront = + await this.commands.targetCommand.rootFront.getFront( + "parentaccessibility" + ); + } + + destroy() { + this.commands.targetCommand.unwatchTargets({ + types: [this.commands.targetCommand.TYPES.FRAME], + onAvailable: this.onTargetAvailable, + onSelected: this.onTargetSelected, + onDestroyed: this.onTargetDestroyed, + }); + this.commands.resourceCommand.unwatchResources( + [this.commands.resourceCommand.TYPES.DOCUMENT_EVENT], + { onAvailable: this.onResourceAvailable } + ); + + this.lifecycleEvents.clear(); + this.accessibilityEvents.clear(); + + this.accessibilityFront = null; + this.accessibilityFrontGetPromise = null; + this.parentAccessibilityFront = null; + this.simulatorFront = null; + this.simulate = null; + this.commands = null; + } + + _getEvents(front) { + return front.typeName === "accessiblewalker" + ? this.accessibilityEvents + : this.lifecycleEvents; + } + + registerEvent(front, type, listener) { + const events = this._getEvents(front); + if (events.has(type)) { + events.get(type).add(listener); + } else { + events.set(type, new Set([listener])); + } + } + + unregisterEvent(front, type, listener) { + const events = this._getEvents(front); + if (!events.has(type)) { + return; + } + + if (!listener) { + events.delete(type); + return; + } + + const listeners = events.get(type); + if (listeners.has(listener)) { + listeners.delete(listener); + } + + if (!listeners.size) { + events.delete(type); + } + } + + onAccessibilityFrontAvailable(accessibilityFront) { + accessibilityFront.watchFronts( + "accessiblewalker", + this.onAccessibleWalkerFrontAvailable, + this.onAccessibleWalkerFrontDestroyed + ); + } + + onAccessibilityFrontDestroyed(accessibilityFront) { + accessibilityFront.unwatchFronts( + "accessiblewalker", + this.onAccessibleWalkerFrontAvailable, + this.onAccessibleWalkerFrontDestroyed + ); + } + + onAccessibleWalkerFrontAvailable(accessibleWalkerFront) { + this._accessibilityWalkerFronts.add(accessibleWalkerFront); + // Apply all existing accessible walker front event listeners to the new + // front. + for (const [type, listeners] of this.accessibilityEvents.entries()) { + for (const listener of listeners) { + accessibleWalkerFront.on(type, listener); + } + } + } + + onAccessibleWalkerFrontDestroyed(accessibleWalkerFront) { + this._accessibilityWalkerFronts.delete(accessibleWalkerFront); + // Remove all existing accessible walker front event listeners from the + // destroyed front. + for (const [type, listeners] of this.accessibilityEvents.entries()) { + for (const listener of listeners) { + accessibleWalkerFront.off(type, listener); + } + } + } + + async onTargetAvailable({ targetFront, isTargetSwitching }) { + targetFront.watchFronts( + "accessibility", + this.onAccessibilityFrontAvailable, + this.onAccessibilityFrontDestroyed + ); + + if (!targetFront.isTopLevel) { + return; + } + + this._accessibilityWalkerFronts.clear(); + + this.accessibilityFrontGetPromise = targetFront.getFront("accessibility"); + this.accessibilityFront = await this.accessibilityFrontGetPromise; + + // Check for backward compatibility. New API's must be described in the + // "getTraits" method of the AccessibilityActor. + this.supports = { ...this.accessibilityFront.traits }; + + this.simulatorFront = this.accessibilityFront.simulatorFront; + if (this.simulatorFront) { + this.simulate = types => this.simulatorFront.simulate({ types }); + } else { + this.simulate = null; + } + + // Move accessibility front lifecycle event listeners to a new top level + // front. + for (const [type, listeners] of this.lifecycleEvents.entries()) { + for (const listener of listeners.values()) { + this.accessibilityFront.on(type, listener); + } + } + } + + async onTargetDestroyed({ targetFront }) { + targetFront.unwatchFronts( + "accessibility", + this.onAccessibilityFrontAvailable, + this.onAccessibilityFrontDestroyed + ); + } + + async onTargetSelected({ targetFront }) { + await this.toggleDisplayTabbingOrder(false); + this.accessibilityFront = await targetFront.getFront("accessibility"); + + this.simulatorFront = this.accessibilityFront.simulatorFront; + if (this.simulatorFront) { + this.simulate = types => this.simulatorFront.simulate({ types }); + } else { + this.simulate = null; + } + + this.#panel.shouldRefresh = true; + this.#panel.refresh(); + } + + onResourceAvailable(resources) { + for (const resource of resources) { + // Only consider top level document, and ignore remote iframes top document + if ( + resource.resourceType === + this.commands.resourceCommand.TYPES.DOCUMENT_EVENT && + resource.name === "dom-complete" && + resource.targetFront.isTopLevel + ) { + this.#panel.forceRefresh(); + } + } + } +} + +exports.AccessibilityProxy = AccessibilityProxy; diff --git a/devtools/client/accessibility/accessibility-view.js b/devtools/client/accessibility/accessibility-view.js new file mode 100644 index 0000000000..36b5aa9e6e --- /dev/null +++ b/devtools/client/accessibility/accessibility-view.js @@ -0,0 +1,260 @@ +/* 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 */ + +const nodeConstants = require("resource://devtools/shared/dom-node-constants.js"); + +// React & Redux +const { + createFactory, + createElement, +} = require("resource://devtools/client/shared/vendor/react.js"); +const ReactDOM = require("resource://devtools/client/shared/vendor/react-dom.js"); +const { + Provider, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); + +// Accessibility Panel +const MainFrame = createFactory( + require("resource://devtools/client/accessibility/components/MainFrame.js") +); + +// Store +const createStore = require("resource://devtools/client/shared/redux/create-store.js"); + +// Reducers +const { + reducers, +} = require("resource://devtools/client/accessibility/reducers/index.js"); +const thunkOptions = { options: {} }; +const store = createStore(reducers, { + // Thunk options will be updated, when we [re]initialize the accessibility + // view. + thunkOptions, +}); + +// Actions +const { + reset, +} = require("resource://devtools/client/accessibility/actions/ui.js"); +const { + select, + highlight, +} = require("resource://devtools/client/accessibility/actions/accessibles.js"); + +/** + * This object represents view of the Accessibility panel and is responsible + * for rendering the content. It renders the top level ReactJS + * component: the MainFrame. + */ +function AccessibilityView(localStore) { + addEventListener("devtools/chrome/message", this.onMessage.bind(this), true); + this.store = localStore; +} + +AccessibilityView.prototype = { + /** + * Initialize accessibility view, create its top level component and set the + * data store. + * + * @param {Object} + * Object that contains the following properties: + * - supports {JSON} + * a collection of flags indicating + * which accessibility panel features + * are supported by the current + * serverside version. + * - fluentBundles {Array} + * array of FluentBundles elements + * for localization + * - toolbox {Object} + * devtools toolbox. + * - getAccessibilityTreeRoot {Function} + * Returns the topmost accessibiliity + * walker that is used as the root of + * the accessibility tree. + * - startListeningForAccessibilityEvents {Function} + * Add listeners for specific + * accessibility events. + * - stopListeningForAccessibilityEvents {Function} + * Remove listeners for specific + * accessibility events. + * - audit {Function} + * Audit function that will start + * accessibility audit for given types + * of accessibility issues. + * - simulate {null|Function} + * Apply simulation of a given type + * (by setting color matrices in + * docShell). + * - toggleDisplayTabbingOrder {Function} + * Toggle the highlight of focusable + * elements along with their tabbing + * index. + * - enableAccessibility {Function} + * Enable accessibility services. + * - resetAccessiblity {Function} + * Reset the state of the + * accessibility services. + * - startListeningForLifecycleEvents {Function} + * Add listeners for accessibility + * service lifecycle events. + * - stopListeningForLifecycleEvents {Function} + * Remove listeners for accessibility + * service lifecycle events. + * - startListeningForParentLifecycleEvents {Function} + * Add listeners for parent process + * accessibility service lifecycle + * events. + * - stopListeningForParentLifecycleEvents {Function} + * Remove listeners for parent + * process accessibility service + * lifecycle events. + * - highlightAccessible {Function} + * Highlight accessible object. + * - unhighlightAccessible {Function} + * Unhighlight accessible object. + */ + async initialize({ + supports, + fluentBundles, + toolbox, + getAccessibilityTreeRoot, + startListeningForAccessibilityEvents, + stopListeningForAccessibilityEvents, + audit, + simulate, + toggleDisplayTabbingOrder, + enableAccessibility, + resetAccessiblity, + startListeningForLifecycleEvents, + stopListeningForLifecycleEvents, + startListeningForParentLifecycleEvents, + stopListeningForParentLifecycleEvents, + highlightAccessible, + unhighlightAccessible, + }) { + // Make sure state is reset every time accessibility panel is initialized. + await this.store.dispatch(reset(resetAccessiblity, supports)); + const container = document.getElementById("content"); + const mainFrame = MainFrame({ + fluentBundles, + toolbox, + getAccessibilityTreeRoot, + startListeningForAccessibilityEvents, + stopListeningForAccessibilityEvents, + audit, + simulate, + enableAccessibility, + resetAccessiblity, + startListeningForLifecycleEvents, + stopListeningForLifecycleEvents, + startListeningForParentLifecycleEvents, + stopListeningForParentLifecycleEvents, + highlightAccessible, + unhighlightAccessible, + }); + thunkOptions.options.toggleDisplayTabbingOrder = toggleDisplayTabbingOrder; + // Render top level component + const provider = createElement(Provider, { store: this.store }, mainFrame); + window.once(EVENTS.PROPERTIES_UPDATED).then(() => { + window.emit(EVENTS.INITIALIZED); + }); + this.mainFrame = ReactDOM.render(provider, container); + }, + + destroy() { + const container = document.getElementById("content"); + ReactDOM.unmountComponentAtNode(container); + }, + + async selectAccessible(accessible) { + await this.store.dispatch(select(accessible)); + window.emit(EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED); + }, + + async highlightAccessible(accessible) { + await this.store.dispatch(highlight(accessible)); + window.emit(EVENTS.NEW_ACCESSIBLE_FRONT_HIGHLIGHTED); + }, + + async selectNodeAccessible(node) { + if (!node) { + return; + } + + const accessibilityFront = await node.targetFront.getFront("accessibility"); + const accessibleWalkerFront = await accessibilityFront.getWalker(); + let accessible = await accessibleWalkerFront.getAccessibleFor(node); + if (accessible) { + await accessible.hydrate(); + } + + // If node does not have an accessible object, try to find node's child text node and + // try to retrieve an accessible object for that child instead. This is the best + // effort approach until there's accessibility API to retrieve accessible object at + // point. + if (!accessible || accessible.indexInParent < 0) { + const { nodes: children } = await node.walkerFront.children(node); + for (const child of children) { + if (child.nodeType === nodeConstants.TEXT_NODE) { + accessible = await accessibleWalkerFront.getAccessibleFor(child); + // indexInParent property is only available with additional request + // for data (hydration) about the accessible object. + if (accessible) { + await accessible.hydrate(); + if (accessible.indexInParent >= 0) { + break; + } + } + } + } + } + + // Attempt to find closest accessible ancestor for a given node. + if (!accessible || accessible.indexInParent < 0) { + let parentNode = node.parentNode(); + while (parentNode) { + accessible = await accessibleWalkerFront.getAccessibleFor(parentNode); + if (accessible) { + await accessible.hydrate(); + if (accessible.indexInParent >= 0) { + break; + } + } + + parentNode = parentNode.parentNode(); + } + } + + // Do not set the selected state if there is no corresponding accessible. + if (!accessible) { + console.warn( + `No accessible object found for a node or a node in its ancestry: ${node.actorID}` + ); + return; + } + + await this.store.dispatch(select(accessible)); + window.emit(EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED); + }, + + /** + * Process message from accessibility panel. + * + * @param {Object} event message type and data. + */ + onMessage(event) { + const data = event.data; + const method = data.type; + + if (typeof this[method] === "function") { + this[method](...data.args); + } + }, +}; + +window.view = new AccessibilityView(store); diff --git a/devtools/client/accessibility/accessibility.css b/devtools/client/accessibility/accessibility.css new file mode 100644 index 0000000000..79ce838314 --- /dev/null +++ b/devtools/client/accessibility/accessibility.css @@ -0,0 +1,850 @@ +/* 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/. */ + +:root { + --accessibility-font-size: 12px; + --accessibility-toolbar-height-tall: 35px; + --accessibility-toolbar-focus: var(--blue-50); + --accessibility-toolbar-focus-alpha30: rgba(10, 132, 255, 0.3); + --accessibility-full-length-minus-splitter: calc(100% - 1px); + --accessibility-horizontal-padding: 5px; + --accessibility-horizontal-indent: 20px; + --accessibility-properties-item-width: calc(100% - var(--accessibility-horizontal-indent)); + /* The main content can use the full height minus the height of the toolbar + (including 1px border bottom) */ + --accessibility-main-height: calc(100vh - var(--theme-toolbar-height) - 1px); + /* The tree can use the main content height minus the height of the tree + header, which has the same height as the toolbar and a 1px border bottom */ + --accessibility-tree-height: calc(var(--accessibility-main-height) - var(--theme-toolbar-height) - 1px); + --accessibility-arrow-horizontal-padding: 4px; + --accessibility-tree-row-height: 21px; + --accessibility-unfocused-tree-focused-node-background: var(--grey-20); + --accessibility-unfocused-tree-focused-node-twisty-fill: var(--theme-icon-dimmed-color); + --accessibility-link-color: var(--theme-link-color); + --accessibility-link-color-active: var(--blue-70); + --accessibility-body-background-a90: rgba(255, 255, 255, 0.9); + --accessibility-code-background: var(--grey-20); +} + +:root.theme-dark { + --accessibility-unfocused-tree-focused-node-background: var(--grey-70); + --accessibility-unfocused-tree-focused-node-twisty-fill: var(--theme-selection-color); + --accessibility-link-color-active: var(--blue-40); + --accessibility-body-background-a90: rgba(42, 42, 46, 0.9); + --accessibility-code-background: var(--grey-70); +} + +/* General */ +html, +body { + height: 100%; + margin: 0; + padding: 0; + width: 100%; +} + +:root .flash-out { + animation: flash-out 0.5s ease-out; +} + +:root { + --theme-popup-border-radius: 0px; +} +:root[platform="mac"] { + --theme-popup-border-radius: 3.5px; +} + +@keyframes flash-out { + from { + background: var(--theme-contrast-background); + } +} + +.accessible .tree .node .theme-twisty { + width: var(--accessibility-horizontal-indent); +} + +.accessible .tree .node .theme-twisty:not(.open):dir(rtl) { + transform: rotate(-90deg); +} + +.accessible .tree .node.focused .theme-twisty, +.treeTable .treeRow.selected .theme-twisty { + fill: var(--theme-selection-color); +} + +.mainFrame { + height: 100%; + color: var(--theme-toolbar-color); +} + +.main-panel { + /* To compenstate for 1px splitter between the tree and sidebar. */ + width: var(--accessibility-full-length-minus-splitter); +} + +.devtools-button, +.toggle-button { + cursor: pointer; + border: 1px solid transparent; +} + +.mainFrame .devtools-button.devtools-throbber::before, +.mainFrame .toggle-button.devtools-throbber::before { + /* Default for .devtools-throbber is set to 1em which is too big for the + devtools toolbar. */ + height: 8px; + width: 8px; + margin-block-end: 1px; + margin-inline-end: 2px; +} + +.split-box.horz { + height: var(--accessibility-main-height); +} + +.mainFrame .devtools-button, +.description .devtools-button { + padding: unset; +} + +.mainFrame .devtools-button > .btn-content { + padding: 2px var(--accessibility-horizontal-padding); +} + +.description .devtools-button > .btn-content { + padding: 7px var(--accessibility-horizontal-padding); +} + +.devtools-button:focus, +.devtools-button > .btn-content:focus, +.devtools-button::-moz-focus-inner { + outline: none; +} + +.devtools-button:focus > .btn-content:not(.devtools-throbber) { + outline: 2px solid var(--accessibility-toolbar-focus); + outline-offset: -2px; + box-shadow: 0 0 0 2px var(--accessibility-toolbar-focus-alpha30); + border-radius: 2px; +} + +.devtools-toolbar { + display: flex; + align-items: center; + font: message-box; + font-size: var(--accessibility-font-size); +} + +/* Similarly to webconsole, add more padding before the toolbar group. */ +.devtools-toolbar .devtools-separator { + margin-inline: 5px; +} + +.devtools-toolbar .accessibility-tree-filters, +.devtools-toolbar .accessibility-simulation { + margin-inline-start: 4px; + display: flex; + flex-wrap: nowrap; + flex-direction: row; + align-items: center; + white-space: nowrap; +} + +.devtools-toolbar .toolbar-menu-button { + border-color: transparent; + padding: 0 3px; +} + +.devtools-toolbar .toolbar-menu-button.filters { + max-width: 100px; +} + +.devtools-toolbar .toolbar-menu-button.simulation { + max-width: 200px; +} + +.devtools-toolbar .toolbar-menu-button.filters, +.devtools-toolbar .toolbar-menu-button.simulation { + text-overflow: ellipsis; + overflow-x: hidden; + margin-inline-start: 3px; +} + +.devtools-toolbar .toolbar-menu-button::after, +.devtools-toolbar .toolbar-menu-button.simulation::before { + content: ""; + display: inline-block; + -moz-context-properties: fill; + fill: currentColor; + margin-inline-start: 3px; +} + +.devtools-toolbar .toolbar-menu-button.filters::after, +.devtools-toolbar .toolbar-menu-button.simulation::after { + background: url("chrome://devtools/skin/images/select-arrow.svg") no-repeat; + width: 8px; + height: 8px; +} + +.devtools-toolbar .toolbar-menu-button.prefs { + background-color: transparent; + height: 18px; + padding: 0; + margin-inline-start: auto; + margin-inline-end: 3px; +} + +.devtools-toolbar .toolbar-menu-button.prefs:active:hover { + background-color: var(--theme-selection-background-hover); +} + +.devtools-toolbar .toolbar-menu-button.prefs::after { + display: none; +} + +.devtools-toolbar .toolbar-menu-button.prefs::before { + background: url("chrome://devtools/skin/images/settings.svg") no-repeat; + width: 14px; + height: 14px; + background-size: contain; + margin: 0px 1px; + vertical-align: text-bottom; +} + +.devtools-toolbar .badge.toggle-button[disabled], +.tooltip-container .menuitem > .command[disabled] { + opacity: 0.5; +} + +:root .theme-body .tooltip-container.tooltip-visible[type="doorhanger"] > .tooltip-panel, +:root .theme-body .tooltip-container.tooltip-visible[type="doorhanger"] > .tooltip-arrow::before { + border: 1px solid var(--theme-popup-border-color); + border-radius: var(--theme-popup-border-radius); + box-shadow: 0 0 4px hsla(210,4%,10%,.2); +} + +.tooltip-container .menuitem > .command[role="link"] { + appearance: none; + border: none; + color: var(--theme-arrowpanel-color); + background-color: transparent; + text-align: start; + width: 100%; +} + +.devtools-toolbar .beta { + color: var(--theme-highlight-blue); + font-size: 80%; + font-weight: 500; + margin-inline-end: 3px; + margin-inline-start: 4px; +} + +#audit-progress-container { + position: fixed; + display: flex; + flex-direction: column; + align-items: center; + width: 100%; + height: 100%; + z-index: 9999; + background: var(--accessibility-body-background-a90); + padding-block-start: 30vh; + font: message-box; + font-size: 12px; + font-style: italic; +} + +.audit-progress-progressbar { + width: 30vw; +} + +/* Description */ +.description { + color: var(--theme-toolbar-color); + font: message-box; + font-size: calc(var(--accessibility-font-size) + 1px); + margin: auto; + padding-top: 15vh; + width: 50vw; +} + +/* To ensure that the message does not look squished in vertical mode, increase its width + when the toolbox is narrow */ +@media (max-width: 700px) { + .description { + width: 80vw; + } +} + +.description .general { + display: flex; + align-items: center; + margin-bottom: 1em; +} + +.description img { + margin-inline-end: 12px; + flex-basis: 42px; + height: 42px; + flex-shrink: 0; + -moz-context-properties: fill; + fill: var(--grey-40); +} + +.description .devtools-button { + display: flex; + align-items: center; + margin: auto; +} + +.description .link, +.accessibility-check-annotation .link { + color: var(--accessibility-link-color); + cursor: pointer; + outline: 0; +} + +.description .link:hover:not(:focus), +.accessibility-check-annotation .link:hover:not(:focus) { + text-decoration: underline; +} + +.description .link:focus:not(:active), +.accessibility-check-annotation .link:focus:not(:active) { + box-shadow: 0 0 0 2px var(--accessibility-toolbar-focus), 0 0 0 4px var(--accessibility-toolbar-focus-alpha30); + border-radius: 2px; +} + +.description .link:active, +.accessibility-check-annotation .link:active { + color: var(--accessibility-link-color-active); + text-decoration: underline; +} + +/* TreeView Customization */ +.treeTable thead, .treeTable tbody { + display: block; +} + +.treeTable tr { + width: 100%; + display: table; +} + +.treeTable tbody { + overflow-y: auto; +} + +.split-box:not(.horz) .treeTable tbody { + height: var(--accessibility-tree-height); +} + +.split-box.horz .treeTable tbody { + /* Accessibility tree height depends on the height of the controlled panel + (sidebar) when in horz mode and also has an additional separator. */ + height: calc(var(--accessibility-tree-height) - var(--split-box-controlled-panel-size) - 1px); +} + +.treeTable { + width: 100%; +} + +.treeTable .treeRow.highlighted:not(.selected) { + background-color: var(--theme-selection-background-hover); +} + +.treeTable.filtered .treeRow .treeLabelCell { + /* Unset row indentation when the tree is filtered. */ + padding-inline-start: var(--accessibility-arrow-horizontal-padding); +} + +/* When the accesibility tree is filtered, we flatten the tree and want to hide + the expander icon (▶) for expandable tree rows. */ +.treeTable.filtered .treeRow .treeLabelCell .treeIcon { + display: none; +} + +.treeTable .treeLabelCell { + min-width: 50%; +} + +.treeTable:focus, .treeTable tbody:focus { + outline: 0; +} + +.treeTable::-moz-focus-inner { + border: 0; +} + +.treeTable:not(:focus, :focus-within) .treeRow.selected { + background-color: var(--accessibility-unfocused-tree-focused-node-background); +} + +.treeTable:not(:focus, :focus-within) .treeRow.selected .theme-twisty { + fill: var(--accessibility-unfocused-tree-focused-node-twisty-fill); +} + +.treeTable:not(:focus, :focus-within) .treeRow.selected *, +.treeTable:not(:focus, :focus-within) .treeRow.selected .treeLabelCell:after { + color: inherit; +} + +.treeTable:not(:focus, :focus-within) .treeRow.selected .objectBox-string { + color: var(--string-color); +} + +.treeTable > thead { + pointer-events: none; +} + +.treeTable > tbody tr { + height: var(--accessibility-tree-row-height); +} + +.treeTable > tbody td { + user-select: none; +} + +.treeTable > tbody td > span { + user-select: text; +} + +.mainFrame .treeTable .treeRow.hasChildren > .treeLabelCell > .treeLabel:hover { + cursor: unset; + text-decoration: none; +} + +.mainFrame .treeTable .treeHeaderRow > .treeHeaderCell:first-child > .treeHeaderCellBox, +.mainFrame .treeTable .treeHeaderRow > .treeHeaderCell > .treeHeaderCellBox { + padding: 0; + padding-inline-start: var(--accessibility-arrow-horizontal-padding); +} + +.mainFrame .treeTable .treeHeaderCell { + width: 50%; + border-bottom: 1px solid var(--theme-splitter-color); + background: var(--theme-toolbar-background); + font: message-box; + font-size: var(--accessibility-font-size); + height: var(--theme-toolbar-height); + color: var(--theme-toolbar-color); +} + +.badge { + display: inline-block; + font: message-box; + font-size: var(--theme-body-font-size); + border-radius: 3px; + padding: 0px 3px; + margin-inline-start: 5px; + color: var(--badge-color); + background-color: var(--badge-background-color); + border: 1px solid var(--badge-border-color); + user-select: none; +} + +.badge.audit-badge::before { + content: ""; + display: inline-block; + vertical-align: 0px; + width: 9px; + height: 9px; + margin-inline-end: 2px; + -moz-context-properties: fill; + fill: currentColor; + opacity: 0.9; +} + +.badge.audit-badge[data-score="BEST_PRACTICES"]::before { + background-image: url(chrome://devtools/skin/images/info-tiny.svg); + vertical-align: -1px; +} + +.badge.audit-badge[data-score="WARNING"]::before { + background-image: url(chrome://devtools/skin/images/alert-tiny.svg); +} + +.badge.audit-badge[data-score="FAIL"]::before { + background-image: url(chrome://devtools/skin/images/error-tiny.svg); + vertical-align: -1px; +} + +/* improve alignment in high res (where we can use half pixels) */ +@media (min-resolution: 1.5x) { + .badge.audit-badge[data-score="WARNING"]::before { + vertical-align: -0.5px; + } +} + +.badge.toggle-button { + color: var(--theme-body-color); + background-color: var(--badge-interactive-background-color); + border-color: transparent; +} + +.devtools-toolbar .badge.toggle-button:focus, +.devtools-toolbar .toolbar-menu-button:focus { + outline: 2px solid var(--accessibility-toolbar-focus); + outline-offset: -2px; + box-shadow: 0 0 0 2px var(--accessibility-toolbar-focus-alpha30); +} + +.treeTable:focus-within .treeRow.selected .badges .badge { + background-color: var(--badge-active-background-color); + border-color: var(--accessible-active-border-color); + color: var(--theme-selection-color); +} + +.treeTable:not(:focus, :focus-within) .treeRow.selected .badges .badge { + color: var(--badge-color); +} + +.badge.toggle-button.checked { + background-color: var(--badge-active-background-color); + color: var(--theme-selection-color); +} + +/* Avoid having a default dotted border on keyboard focus since we provide focus + styling*/ +.badge.toggle-button::-moz-focus-inner { + border: none; +} + +/* Right Sidebar */ +.right-sidebar { + display: flex; + flex-direction: column; + flex: 1; + overflow-y: auto; + white-space: nowrap; + font: message-box; + font-size: var(--accessibility-font-size); + background-color: var(--theme-sidebar-background); +} + +.split-box:not(.horz) .right-sidebar { + position: fixed; + width: inherit; + height: var(--accessibility-main-height) +} + +/* Tree customization */ +.accessible .tree { + flex: 1; + height: 100%; + white-space: nowrap; + overflow: auto; + display: block; + /* Force the properties list to always be displayed in LTR (bug 1575002) */ + direction: ltr; +} + +.split-box.horz .accessible .tree { + width: 100vw; +} + +.accessible .tree button { + display: block; +} + +/* NOTE: total height of the node (height + padding + border + margin) must + be exactly the same as the value of TREE_ROW_HEIGHT constant in + devtools/client/accessibility/constants.js */ +.accessible .tree .node { + padding: 0 var(--accessibility-horizontal-indent); + position: relative; + display: flex; + height: var(--accessibility-tree-row-height); + width: var(--accessibility-properties-item-width); + cursor: default; + align-items: center; +} + +.accessible .tree:focus { + outline: 0; +} + +.accessible .tree::-moz-focus-inner { + border: 0; +} + +/* Unset tree styles leaking from reps.css */ +.accessible .tree .tree-node:not(.focused):hover { + background-color: transparent; +} + +.accessible .tree:not(:focus) .node.focused { + background-color: var(--accessibility-unfocused-tree-focused-node-background); +} + +.accessible .tree:not(:focus) .node.focused .theme-twisty { + fill: var(--accessibility-unfocused-tree-focused-node-twisty-fill); +} + +.accessible .tree .node:not(.focused):hover { + background-color: var(--theme-selection-background-hover); +} + +.accessible .tree:focus .node.focused, +.accessible .tree .tree-node-active .node.focused { + background-color: var(--theme-selection-background); +} + +.accessible .tree:focus .node.focused *, +.accessible .tree .tree-node-active .node.focused * { + color: var(--theme-selection-color); +} + +/* Invert text selection color in selected rows */ +.accessible .tree:focus .node.focused ::selection, +.accessible .tree .tree-node-active .node.focused ::selection { + color: var(--theme-selection-background); + background-color: var(--theme-selection-color); +} + +.accessible .tree:focus .node.focused .open-inspector, +.accessible .tree .tree-node-active .node.focused .open-inspector { + fill: var(--grey-30); +} + +.accessible .tree:focus .node.focused:hover .open-inspector, +.accessible .tree .tree-node-active .node.focused:hover .open-inspector { + fill: var(--theme-selection-color); +} + +.accessible .tree .tree-node-active .node.focused .open-inspector:focus, +.accessible .tree .tree-node-active .node.focused:hover .open-inspector:focus { + fill: var(--grey-40); +} + +.accessible .tree .arrow { + flex-shrink: 0; +} + +.accessible .tree .object-value { + overflow: hidden; + text-overflow: ellipsis; +} + +.accessible .tree .object-delimiter { + padding-inline-end: var(--accessibility-arrow-horizontal-padding); +} + +.accessible .tree .object-label { + color: var(--theme-highlight-blue); +} + +.accessible .tree .objectBox-accessible .accessible-role { + background-color: var(--badge-background-color); + color: var(--badge-color); + border: 1px solid var(--badge-border-color); + border-radius: 3px; + padding: 0px 2px; + margin-inline-start: 5px; + user-select: none; +} + +.accessible .tree:focus .node.focused .objectBox-accessible .accessible-role, +.accessible .tree .tree-node-active .node.focused .objectBox-accessible .accessible-role { + background-color: var(--badge-active-background-color); + border-color: var(--badge-active-border-color); + color: var(--theme-selection-color); +} + +.accessible .tree:focus .node.focused .open-accessibility-inspector, +.accessible .tree .tree-node-active .node.focused .open-accessibility-inspector { + fill: var(--grey-30); +} + +.accessible .tree:focus .node.focused:hover .open-accessibility-inspector, +.accessible .tree .tree-node-active .node.focused:hover .open-accessibility-inspector { + fill: var(--theme-selection-color); +} + +.accessible .tree .tree-node-active .node.focused .open-accessibility-inspector:focus, +.accessible .tree .tree-node-active .node.focused:hover .open-accessibility-inspector:focus { + fill: var(--grey-40); +} + +.accessible .tree .objectBox-accessible, +.accessible .tree .objectBox-node { + width: 100%; + display: flex; + align-items: center; +} + +.accessible .tree .objectBox-accessible .accessible-name, +.accessible .tree .objectBox-node .attrName { + overflow: hidden; + text-overflow: ellipsis; +} + +.accessible .tree .objectBox-accessible .open-accessibility-inspector, +.accessible .tree .objectBox-node .open-inspector { + width: 17px; + cursor: pointer; + flex-shrink: 0; +} + +.accessible .tree .objectBox-object, +.accessible .tree .objectBox-string, +.accessible .tree .objectBox-text, +.accessible .tree .objectBox-table, +.accessible .tree .objectLink-textNode, +.accessible .tree .objectLink-event, +.accessible .tree .objectLink-eventLog, +.accessible .tree .objectLink-regexp, +.accessible .tree .objectLink-object, +.accessible .tree .objectLink-Date, +.theme-dark .accessible .tree .objectBox-object, +.theme-light .accessible .tree .objectBox-object { + white-space: nowrap; +} + +/* Styling for accessible details panel when accessible is not available */ +.accessible .info { + color: var(--theme-body-color); + font-size: 110%; + padding-inline-start: var(--accessibility-arrow-horizontal-padding); + height: var(--accessibility-toolbar-height-tall); + line-height: var(--accessibility-toolbar-height-tall); +} + +.checks-empty { + font-style: italic; + padding: 0.5em 20px; + user-select: none; + font-size: 12px; + white-space: initial; +} + +/* Checks */ +.checks .list li:last-of-type { + padding-block-end: 4px; +} + +.accessibility-check code { + background-color: var(--accessibility-code-background); + border-radius: 2px; + box-decoration-break: clone; + padding: 0 4px; +} + +.accessibility-check .icon { + display: inline; + -moz-context-properties: fill; + vertical-align: top; + margin-block-start: 2px; + margin-inline-end: 4px; +} + +.accessibility-check .icon[data-score="FAIL"] { + fill: var(--theme-icon-error-color); +} + +.accessibility-check .icon[data-score="WARNING"] { + fill: var(--theme-icon-warning-color); +} + +.accessibility-check .icon[data-score="BEST_PRACTICES"] { + fill: currentColor; +} + +.accessibility-check, +.accessibility-color-contrast { + position: relative; + display: flex; + cursor: default; + height: inherit; +} + +.accessibility-check { + flex-direction: column; + padding: 4px var(--accessibility-horizontal-indent); + line-height: 20px; +} + +.accessibility-check-header { + margin: 0; + font-weight: bold; + font-size: var(--accessibility-font-size); + line-height: var(--theme-toolbar-height); +} + +.accessibility-check-annotation { + display: inline; + margin: 0; + white-space: normal; + color: var(--badge-color); +} + +.accessibility-check-annotation .link { + white-space: nowrap; + font-style: normal; +} + +.accessibility-color-contrast .accessibility-contrast-value:not(:empty) { + margin-block-end: 4px; +} + +.accessibility-color-contrast .accessibility-contrast-value:not(:empty):before { + content: ""; + height: 14px; + width: 14px; + display: inline-flex; + background-color: var(--accessibility-contrast-color); + box-shadow: 0 0 0 1px var(--grey-40), 6px 5px var(--accessibility-contrast-bg), 6px 5px 0 1px var(--grey-40); + margin-inline-end: 11px; +} + +.accessibility-color-contrast .accessibility-contrast-value:first-child:not(:empty):before { + margin-inline-start: 1px; +} + +.accessibility-color-contrast .accessibility-contrast-value:not(:first-child, :empty):before { + margin-inline-start: 4px; +} + +.accessibility-color-contrast .accessibility-color-contrast-label:after { + content: ":"; +} + +.accessibility-color-contrast .accessibility-color-contrast-label, +.accessibility-color-contrast .accessibility-color-contrast-separator:before { + margin-inline-end: 3px; +} + +.devtools-toolbar .toolbar-menu-button.simulation::before { + width: 12px; + height: 12px; + margin-inline-end: 3px; + margin-inline-start: 0px; + background: url("chrome://devtools/skin/images/eye.svg") no-repeat; + -moz-context-properties: fill, stroke; + fill: var(--theme-icon-color); + stroke: var(--theme-icon-color); + vertical-align: -2px; +} + +.devtools-toolbar .toolbar-menu-button.active, +.devtools-toolbar .toolbar-menu-button.active.devtools-button:not(:empty, .checked, :disabled):focus { + color: var(--theme-toolbar-selected-color); +} + +.devtools-toolbar .toolbar-menu-button.simulation.active::before { + fill: var(--theme-toolbar-selected-color); + stroke: var(--theme-toolbar-selected-color); +} + +#simulation-menu-button-menu .link { + background-color: transparent; + border: none; +} + +#simulation-menu-button-menu .link:focus, +#simulation-menu-button-menu .link:hover { + background-color: var(--theme-arrowpanel-dimmed); +} diff --git a/devtools/client/accessibility/actions/accessibles.js b/devtools/client/accessibility/actions/accessibles.js new file mode 100644 index 0000000000..085157c445 --- /dev/null +++ b/devtools/client/accessibility/actions/accessibles.js @@ -0,0 +1,70 @@ +/* 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 { + FETCH_CHILDREN, + SELECT, + HIGHLIGHT, + UNHIGHLIGHT, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Fetch child accessibles for a given accessible object. + * @param {Object} accessible front + */ +exports.fetchChildren = + accessible => + ({ dispatch }) => + accessible + .children() + .then(response => + dispatch({ accessible, type: FETCH_CHILDREN, response }) + ) + .catch(error => dispatch({ accessible, type: FETCH_CHILDREN, error })); + +exports.select = + accessible => + ({ dispatch }) => { + const accessibleWalkerFront = accessible.getParent(); + if (!accessibleWalkerFront) { + dispatch({ + accessible, + type: SELECT, + error: new Error("AccessibleWalker front is not available."), + }); + + return Promise.reject(); + } + + return accessibleWalkerFront + .getAncestry(accessible) + .then(response => dispatch({ accessible, type: SELECT, response })) + .catch(error => dispatch({ accessible, type: SELECT, error })); + }; + +exports.highlight = + accessible => + ({ dispatch }) => { + const accessibleWalkerFront = accessible.getParent(); + if (!accessibleWalkerFront) { + dispatch({ + accessible, + type: SELECT, + error: new Error("AccessibleWalker front is not available."), + }); + + return Promise.reject(); + } + + return accessibleWalkerFront + .getAncestry(accessible) + .then(response => dispatch({ accessible, type: HIGHLIGHT, response })) + .catch(error => dispatch({ accessible, type: HIGHLIGHT, error })); + }; + +exports.unhighlight = + () => + ({ dispatch }) => + dispatch({ type: UNHIGHLIGHT }); diff --git a/devtools/client/accessibility/actions/audit.js b/devtools/client/accessibility/actions/audit.js new file mode 100644 index 0000000000..7d91299eea --- /dev/null +++ b/devtools/client/accessibility/actions/audit.js @@ -0,0 +1,36 @@ +/* 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 { + AUDIT, + AUDIT_PROGRESS, + AUDITING, + FILTER_TOGGLE, + FILTERS, +} = require("resource://devtools/client/accessibility/constants.js"); + +exports.filterToggle = + filter => + ({ dispatch }) => + dispatch({ filter, type: FILTER_TOGGLE }); + +exports.auditing = + filter => + ({ dispatch }) => { + const auditing = filter === FILTERS.ALL ? Object.values(FILTERS) : [filter]; + return dispatch({ auditing, type: AUDITING }); + }; + +exports.audit = + (auditFunc, filter) => + ({ dispatch }) => + auditFunc(filter, progress => + dispatch({ type: AUDIT_PROGRESS, progress }) + ).then(({ error, ancestries }) => { + return error + ? dispatch({ type: AUDIT, error: true }) + : dispatch({ type: AUDIT, response: ancestries }); + }); diff --git a/devtools/client/accessibility/actions/details.js b/devtools/client/accessibility/actions/details.js new file mode 100644 index 0000000000..f25996589e --- /dev/null +++ b/devtools/client/accessibility/actions/details.js @@ -0,0 +1,40 @@ +/* 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 { + UPDATE_DETAILS, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Update details with the given accessible object. + * + * @param {Object} accessible front + */ +exports.updateDetails = + accessible => + async ({ dispatch }) => { + const { walker: domWalker } = await accessible.targetFront.getFront( + "inspector" + ); + // By the time getFront resolves, the accessibleFront may have been destroyed. + // This typically happens during navigations. + if (accessible.isDestroyed()) { + return; + } + try { + const response = await Promise.all([ + domWalker.getNodeFromActor(accessible.actorID, [ + "rawAccessible", + "DOMNode", + ]), + accessible.getRelations(), + accessible.audit(), + accessible.hydrate(), + ]); + dispatch({ accessible, type: UPDATE_DETAILS, response }); + } catch (error) { + dispatch({ accessible, type: UPDATE_DETAILS, error }); + } + }; diff --git a/devtools/client/accessibility/actions/moz.build b/devtools/client/accessibility/actions/moz.build new file mode 100644 index 0000000000..c4571d7998 --- /dev/null +++ b/devtools/client/accessibility/actions/moz.build @@ -0,0 +1,5 @@ +# 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/. + +DevToolsModules("accessibles.js", "audit.js", "details.js", "simulation.js", "ui.js") diff --git a/devtools/client/accessibility/actions/simulation.js b/devtools/client/accessibility/actions/simulation.js new file mode 100644 index 0000000000..98d69d62f3 --- /dev/null +++ b/devtools/client/accessibility/actions/simulation.js @@ -0,0 +1,16 @@ +/* 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 { + SIMULATE, +} = require("resource://devtools/client/accessibility/constants.js"); + +exports.simulate = + (simulateFunc, simTypes = []) => + ({ dispatch }) => + simulateFunc(simTypes) + .then(success => dispatch({ error: !success, simTypes, type: SIMULATE })) + .catch(error => dispatch({ error, type: SIMULATE })); diff --git a/devtools/client/accessibility/actions/ui.js b/devtools/client/accessibility/actions/ui.js new file mode 100644 index 0000000000..d4af5ba8fb --- /dev/null +++ b/devtools/client/accessibility/actions/ui.js @@ -0,0 +1,77 @@ +/* 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 { + ENABLE, + RESET, + UPDATE_CAN_BE_DISABLED, + UPDATE_CAN_BE_ENABLED, + UPDATE_PREF, + PREF_KEYS, + UPDATE_DISPLAY_TABBING_ORDER, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Reset accessibility panel UI. + */ +exports.reset = + (resetAccessiblity, supports) => + async ({ dispatch }) => { + try { + const { enabled, canBeDisabled, canBeEnabled } = + await resetAccessiblity(); + dispatch({ enabled, canBeDisabled, canBeEnabled, supports, type: RESET }); + } catch (error) { + dispatch({ type: RESET, error }); + } + }; + +/** + * Update a "canBeDisabled" flag for accessibility service. + */ +exports.updateCanBeDisabled = + canBeDisabled => + ({ dispatch }) => + dispatch({ canBeDisabled, type: UPDATE_CAN_BE_DISABLED }); + +/** + * Update a "canBeEnabled" flag for accessibility service. + */ +exports.updateCanBeEnabled = + canBeEnabled => + ({ dispatch }) => + dispatch({ canBeEnabled, type: UPDATE_CAN_BE_ENABLED }); + +exports.updatePref = + (name, value) => + ({ dispatch }) => { + dispatch({ type: UPDATE_PREF, name, value }); + Services.prefs.setBoolPref(PREF_KEYS[name], value); + }; + +/** + * Enable accessibility services in order to view accessible tree. + */ +exports.enable = + enableAccessibility => + async ({ dispatch }) => { + try { + await enableAccessibility(); + dispatch({ type: ENABLE }); + } catch (error) { + dispatch({ error, type: ENABLE }); + } + }; + +exports.updateDisplayTabbingOrder = + tabbingOrderDisplayed => + async ({ dispatch, options: { toggleDisplayTabbingOrder } }) => { + try { + await toggleDisplayTabbingOrder(tabbingOrderDisplayed); + dispatch({ tabbingOrderDisplayed, type: UPDATE_DISPLAY_TABBING_ORDER }); + } catch (error) { + dispatch({ error, type: UPDATE_DISPLAY_TABBING_ORDER }); + } + }; diff --git a/devtools/client/accessibility/components/AccessibilityPrefs.js b/devtools/client/accessibility/components/AccessibilityPrefs.js new file mode 100644 index 0000000000..8c5de5f15f --- /dev/null +++ b/devtools/client/accessibility/components/AccessibilityPrefs.js @@ -0,0 +1,109 @@ +/* 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"; + +// React +const { + createFactory, + Component, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + hr, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +loader.lazyGetter(this, "MenuButton", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuButton.js") + ); +}); +loader.lazyGetter(this, "MenuItem", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuItem.js") + ); +}); +loader.lazyGetter(this, "MenuList", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuList.js") + ); +}); + +const { + A11Y_LEARN_MORE_LINK, +} = require("resource://devtools/client/accessibility/constants.js"); +const { openDocLink } = require("resource://devtools/client/shared/link.js"); + +const { + updatePref, +} = require("resource://devtools/client/accessibility/actions/ui.js"); + +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); +const { + PREFS, +} = require("resource://devtools/client/accessibility/constants.js"); + +class AccessibilityPrefs extends Component { + static get propTypes() { + return { + dispatch: PropTypes.func.isRequired, + [PREFS.SCROLL_INTO_VIEW]: PropTypes.bool.isRequired, + toolboxDoc: PropTypes.object.isRequired, + }; + } + + togglePref(prefKey) { + this.props.dispatch(updatePref(prefKey, !this.props[prefKey])); + } + + onPrefClick(prefKey) { + this.togglePref(prefKey); + } + + onLearnMoreClick() { + openDocLink(A11Y_LEARN_MORE_LINK); + } + + render() { + return MenuButton( + { + menuId: "accessibility-tree-filters-prefs-menu", + toolboxDoc: this.props.toolboxDoc, + className: `devtools-button badge toolbar-menu-button prefs`, + title: L10N.getStr("accessibility.tree.filters.prefs"), + }, + MenuList({}, [ + MenuItem({ + key: "pref-scroll-into-view", + checked: this.props[PREFS.SCROLL_INTO_VIEW], + className: `pref ${PREFS.SCROLL_INTO_VIEW}`, + label: L10N.getStr("accessibility.pref.scroll.into.view.label"), + tooltip: L10N.getStr("accessibility.pref.scroll.into.view.title"), + onClick: this.onPrefClick.bind(this, PREFS.SCROLL_INTO_VIEW), + }), + hr({ key: "hr" }), + MenuItem({ + role: "link", + key: "accessibility-tree-filters-prefs-menu-help", + className: "help", + label: L10N.getStr("accessibility.documentation.label"), + tooltip: L10N.getStr("accessibility.learnMore"), + onClick: this.onLearnMoreClick, + }), + ]) + ); + } +} + +const mapStateToProps = ({ ui }) => ({ + [PREFS.SCROLL_INTO_VIEW]: ui[PREFS.SCROLL_INTO_VIEW], +}); + +// Exports from this module +module.exports = connect(mapStateToProps)(AccessibilityPrefs); diff --git a/devtools/client/accessibility/components/AccessibilityRow.js b/devtools/client/accessibility/components/AccessibilityRow.js new file mode 100644 index 0000000000..ffca5c74ef --- /dev/null +++ b/devtools/client/accessibility/components/AccessibilityRow.js @@ -0,0 +1,328 @@ +/* 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 gTelemetry, EVENTS */ + +// React & Redux +const { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.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 TreeRow = require("resource://devtools/client/shared/components/tree/TreeRow.js"); +const AuditFilter = createFactory( + require("resource://devtools/client/accessibility/components/AuditFilter.js") +); +const AuditController = createFactory( + require("resource://devtools/client/accessibility/components/AuditController.js") +); + +// Utils +const { + flashElementOn, + flashElementOff, +} = require("resource://devtools/client/inspector/markup/utils.js"); +const { openDocLink } = require("resource://devtools/client/shared/link.js"); +const { + PREFS, + VALUE_FLASHING_DURATION, + VALUE_HIGHLIGHT_DURATION, +} = require("resource://devtools/client/accessibility/constants.js"); + +const nodeConstants = require("resource://devtools/shared/dom-node-constants.js"); + +// Actions +const { + updateDetails, +} = require("resource://devtools/client/accessibility/actions/details.js"); +const { + unhighlight, +} = require("resource://devtools/client/accessibility/actions/accessibles.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +loader.lazyRequireGetter( + this, + "Menu", + "resource://devtools/client/framework/menu.js" +); +loader.lazyRequireGetter( + this, + "MenuItem", + "resource://devtools/client/framework/menu-item.js" +); + +const { + scrollIntoView, +} = require("resource://devtools/client/shared/scroll.js"); + +const JSON_URL_PREFIX = "data:application/json;charset=UTF-8,"; + +const TELEMETRY_ACCESSIBLE_CONTEXT_MENU_OPENED = + "devtools.accessibility.accessible_context_menu_opened"; +const TELEMETRY_ACCESSIBLE_CONTEXT_MENU_ITEM_ACTIVATED = + "devtools.accessibility.accessible_context_menu_item_activated"; + +class HighlightableTreeRowClass extends TreeRow { + shouldComponentUpdate(nextProps) { + const shouldTreeRowUpdate = super.shouldComponentUpdate(nextProps); + if (shouldTreeRowUpdate) { + return shouldTreeRowUpdate; + } + + if ( + nextProps.highlighted !== this.props.highlighted || + nextProps.filtered !== this.props.filtered + ) { + return true; + } + + return false; + } +} + +const HighlightableTreeRow = createFactory(HighlightableTreeRowClass); + +// Component that expands TreeView's own TreeRow and is responsible for +// rendering an accessible object. +class AccessibilityRow extends Component { + static get propTypes() { + return { + ...TreeRow.propTypes, + dispatch: PropTypes.func.isRequired, + toolboxDoc: PropTypes.object.isRequired, + scrollContentNodeIntoView: PropTypes.bool.isRequired, + highlightAccessible: PropTypes.func.isRequired, + unhighlightAccessible: PropTypes.func.isRequired, + }; + } + + componentDidMount() { + const { + member: { selected, object }, + scrollContentNodeIntoView, + } = this.props; + if (selected) { + this.unhighlight(object); + this.update(); + this.highlight( + object, + { duration: VALUE_HIGHLIGHT_DURATION }, + scrollContentNodeIntoView + ); + } + + if (this.props.highlighted) { + this.scrollIntoView(); + } + } + + /** + * Update accessible object details that are going to be rendered inside the + * accessible panel sidebar. + */ + componentDidUpdate(prevProps) { + const { + member: { selected, object }, + scrollContentNodeIntoView, + } = this.props; + // If row is selected, update corresponding accessible details. + if (!prevProps.member.selected && selected) { + this.unhighlight(object); + this.update(); + this.highlight( + object, + { duration: VALUE_HIGHLIGHT_DURATION }, + scrollContentNodeIntoView + ); + } + + if (this.props.highlighted) { + this.scrollIntoView(); + } + + if (!selected && prevProps.member.value !== this.props.member.value) { + this.flashValue(); + } + } + + scrollIntoView() { + const row = findDOMNode(this); + // Row might not be rendered in the DOM tree if it is filtered out during + // audit. + if (!row) { + return; + } + + scrollIntoView(row); + } + + update() { + const { + dispatch, + member: { object }, + } = this.props; + if (!object.actorID) { + return; + } + + dispatch(updateDetails(object)); + window.emit(EVENTS.NEW_ACCESSIBLE_FRONT_SELECTED, object); + } + + flashValue() { + const row = findDOMNode(this); + // Row might not be rendered in the DOM tree if it is filtered out during + // audit. + if (!row) { + return; + } + + const value = row.querySelector(".objectBox"); + + flashElementOn(value); + if (this._flashMutationTimer) { + clearTimeout(this._flashMutationTimer); + this._flashMutationTimer = null; + } + this._flashMutationTimer = setTimeout(() => { + flashElementOff(value); + }, VALUE_FLASHING_DURATION); + } + + /** + * Scroll the node that corresponds to a current accessible object into view. + * @param {Object} + * Accessible front that is rendered for this node. + * + * @returns {Promise} + * Promise that resolves when the node is scrolled into view if + * possible. + */ + async scrollNodeIntoViewIfNeeded(accessibleFront) { + if (accessibleFront.isDestroyed()) { + return; + } + + const domWalker = (await accessibleFront.targetFront.getFront("inspector")) + .walker; + if (accessibleFront.isDestroyed()) { + return; + } + + const node = await domWalker.getNodeFromActor(accessibleFront.actorID, [ + "rawAccessible", + "DOMNode", + ]); + if (!node) { + return; + } + + if (node.nodeType == nodeConstants.ELEMENT_NODE) { + await node.scrollIntoView(); + } else if (node.nodeType != nodeConstants.DOCUMENT_NODE) { + // scrollIntoView method is only part of the Element interface, in cases + // where node is a text node (and not a document node) scroll into view + // its parent. + await node.parentNode().scrollIntoView(); + } + } + + async highlight(accessibleFront, options, scrollContentNodeIntoView) { + this.props.dispatch(unhighlight()); + // If necessary scroll the node into view before showing the accessibility + // highlighter. + if (scrollContentNodeIntoView) { + await this.scrollNodeIntoViewIfNeeded(accessibleFront); + } + + this.props.highlightAccessible(accessibleFront, options); + } + + unhighlight(accessibleFront) { + this.props.dispatch(unhighlight()); + this.props.unhighlightAccessible(accessibleFront); + } + + async printToJSON() { + if (gTelemetry) { + gTelemetry.keyedScalarAdd( + TELEMETRY_ACCESSIBLE_CONTEXT_MENU_ITEM_ACTIVATED, + "print-to-json", + 1 + ); + } + + const snapshot = await this.props.member.object.snapshot(); + openDocLink( + `${JSON_URL_PREFIX}${encodeURIComponent(JSON.stringify(snapshot))}` + ); + } + + onContextMenu(e) { + e.stopPropagation(); + e.preventDefault(); + + if (!this.props.toolboxDoc) { + return; + } + + const menu = new Menu({ id: "accessibility-row-contextmenu" }); + menu.append( + new MenuItem({ + id: "menu-printtojson", + label: L10N.getStr("accessibility.tree.menu.printToJSON"), + click: () => this.printToJSON(), + }) + ); + + menu.popup(e.screenX, e.screenY, this.props.toolboxDoc); + + if (gTelemetry) { + gTelemetry.scalarAdd(TELEMETRY_ACCESSIBLE_CONTEXT_MENU_OPENED, 1); + } + } + + /** + * Render accessible row component. + * @returns acecssible-row React component. + */ + render() { + const { member } = this.props; + const props = { + ...this.props, + onContextMenu: e => this.onContextMenu(e), + onMouseOver: () => this.highlight(member.object), + onMouseOut: () => this.unhighlight(member.object), + key: `${member.path}-${member.active ? "active" : "inactive"}`, + }; + + return AuditController( + { + accessibleFront: member.object, + }, + AuditFilter({}, HighlightableTreeRow(props)) + ); + } +} + +const mapStateToProps = ({ + ui: { [PREFS.SCROLL_INTO_VIEW]: scrollContentNodeIntoView }, +}) => ({ + scrollContentNodeIntoView, +}); + +module.exports = connect(mapStateToProps, null, null, { withRef: true })( + AccessibilityRow +); diff --git a/devtools/client/accessibility/components/AccessibilityRowValue.js b/devtools/client/accessibility/components/AccessibilityRowValue.js new file mode 100644 index 0000000000..ab631fedb4 --- /dev/null +++ b/devtools/client/accessibility/components/AccessibilityRowValue.js @@ -0,0 +1,58 @@ +/* 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 { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + span, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const Badges = createFactory( + require("resource://devtools/client/accessibility/components/Badges.js") +); +const AuditController = createFactory( + require("resource://devtools/client/accessibility/components/AuditController.js") +); + +const { + REPS, +} = require("resource://devtools/client/shared/components/reps/index.js"); +const { Grip } = REPS; +const Rep = createFactory(REPS.Rep); + +class AccessibilityRowValue extends Component { + static get propTypes() { + return { + member: PropTypes.shape({ + object: PropTypes.object, + }).isRequired, + }; + } + + render() { + return span( + { + role: "presentation", + }, + Rep({ + ...this.props, + defaultRep: Grip, + cropLimit: 50, + }), + AuditController( + { + accessibleFront: this.props.member.object, + }, + Badges() + ) + ); + } +} + +module.exports = AccessibilityRowValue; diff --git a/devtools/client/accessibility/components/AccessibilityTree.js b/devtools/client/accessibility/components/AccessibilityTree.js new file mode 100644 index 0000000000..df67377283 --- /dev/null +++ b/devtools/client/accessibility/components/AccessibilityTree.js @@ -0,0 +1,298 @@ +/* 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 */ + +// React & Redux +const { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); + +const TreeView = createFactory( + require("resource://devtools/client/shared/components/tree/TreeView.js") +); +// Reps +const { + MODE, +} = require("resource://devtools/client/shared/components/reps/index.js"); + +const { + fetchChildren, +} = require("resource://devtools/client/accessibility/actions/accessibles.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); +const { + isFiltered, +} = require("resource://devtools/client/accessibility/utils/audit.js"); +const AccessibilityRow = createFactory( + require("resource://devtools/client/accessibility/components/AccessibilityRow.js") +); +const AccessibilityRowValue = createFactory( + require("resource://devtools/client/accessibility/components/AccessibilityRowValue.js") +); +const { + Provider, +} = require("resource://devtools/client/accessibility/provider.js"); + +const { + scrollIntoView, +} = require("resource://devtools/client/shared/scroll.js"); + +/** + * Renders Accessibility panel tree. + */ +class AccessibilityTree extends Component { + static get propTypes() { + return { + toolboxDoc: PropTypes.object.isRequired, + dispatch: PropTypes.func.isRequired, + accessibles: PropTypes.object, + expanded: PropTypes.object, + selected: PropTypes.string, + highlighted: PropTypes.object, + filtered: PropTypes.bool, + getAccessibilityTreeRoot: PropTypes.func.isRequired, + startListeningForAccessibilityEvents: PropTypes.func.isRequired, + stopListeningForAccessibilityEvents: PropTypes.func.isRequired, + highlightAccessible: PropTypes.func.isRequired, + unhighlightAccessible: PropTypes.func.isRequired, + }; + } + + constructor(props) { + super(props); + + this.onNameChange = this.onNameChange.bind(this); + this.onReorder = this.onReorder.bind(this); + this.onTextChange = this.onTextChange.bind(this); + this.renderValue = this.renderValue.bind(this); + this.scrollSelectedRowIntoView = this.scrollSelectedRowIntoView.bind(this); + } + + /** + * Add accessibility event listeners that affect tree rendering and updates. + */ + // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507 + UNSAFE_componentWillMount() { + this.props.startListeningForAccessibilityEvents({ + reorder: this.onReorder, + "name-change": this.onNameChange, + "text-change": this.onTextChange, + }); + window.on( + EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED, + this.scrollSelectedRowIntoView + ); + return null; + } + + componentDidUpdate(prevProps) { + // When filtering is toggled, make sure that the selected row remains in + // view. + if (this.props.filtered !== prevProps.filtered) { + this.scrollSelectedRowIntoView(); + } + + window.emit(EVENTS.ACCESSIBILITY_INSPECTOR_UPDATED); + } + + /** + * Remove accessible event listeners. + */ + componentWillUnmount() { + this.props.stopListeningForAccessibilityEvents({ + reorder: this.onReorder, + "name-change": this.onNameChange, + "text-change": this.onTextChange, + }); + + window.off( + EVENTS.NEW_ACCESSIBLE_FRONT_INSPECTED, + this.scrollSelectedRowIntoView + ); + } + + /** + * Handle accessible reorder event. If the accessible is cached and rendered + * within the accessibility tree, re-fetch its children and re-render the + * corresponding subtree. + * @param {Object} accessibleFront + * accessible front that had its subtree reordered. + */ + onReorder(accessibleFront) { + if (this.props.accessibles.has(accessibleFront.actorID)) { + this.props.dispatch(fetchChildren(accessibleFront)); + } + } + + scrollSelectedRowIntoView() { + const { treeview } = this.refs; + if (!treeview) { + return; + } + + const treeEl = treeview.treeRef.current; + if (!treeEl) { + return; + } + + const selected = treeEl.ownerDocument.querySelector( + ".treeTable .treeRow.selected" + ); + if (selected) { + scrollIntoView(selected, { center: true }); + } + } + + /** + * Handle accessible name change event. If the name of an accessible changes + * and that accessible is cached and rendered within the accessibility tree, + * re-fetch its parent's children and re-render the corresponding subtree. + * @param {Object} accessibleFront + * accessible front that had its name changed. + * @param {Object} parentFront + * optional parent accessible front. Note: if it parent is not + * present, we assume that the top level document's name has changed + * and use accessible walker as a parent. + */ + onNameChange(accessibleFront, parentFront) { + const { accessibles, dispatch } = this.props; + const accessibleWalkerFront = accessibleFront.getParent(); + parentFront = parentFront || accessibleWalkerFront; + + if ( + accessibles.has(accessibleFront.actorID) || + accessibles.has(parentFront.actorID) + ) { + dispatch(fetchChildren(parentFront)); + } + } + + /** + * Handle accessible text change (change/insert/remove) event. If the text of + * an accessible changes and that accessible is cached and rendered within the + * accessibility tree, re-fetch its children and re-render the corresponding + * subtree. + * @param {Object} accessibleFront + * accessible front that had its child text changed. + */ + onTextChange(accessibleFront) { + const { accessibles, dispatch } = this.props; + if (accessibles.has(accessibleFront.actorID)) { + dispatch(fetchChildren(accessibleFront)); + } + } + + renderValue(props) { + return AccessibilityRowValue(props); + } + + /** + * Render Accessibility panel content + */ + render() { + const columns = [ + { + id: "default", + title: L10N.getStr("accessibility.role"), + }, + { + id: "value", + title: L10N.getStr("accessibility.name"), + }, + ]; + + const { + accessibles, + dispatch, + expanded, + selected, + highlighted: highlightedItem, + toolboxDoc, + filtered, + getAccessibilityTreeRoot, + highlightAccessible, + unhighlightAccessible, + } = this.props; + + const renderRow = rowProps => { + const { object } = rowProps.member; + const highlighted = object === highlightedItem; + return AccessibilityRow( + Object.assign({}, rowProps, { + toolboxDoc, + highlighted, + decorator: { + getRowClass() { + return highlighted ? ["highlighted"] : []; + }, + }, + highlightAccessible, + unhighlightAccessible, + }) + ); + }; + const className = filtered ? "filtered" : undefined; + + return TreeView({ + ref: "treeview", + object: getAccessibilityTreeRoot(), + mode: MODE.SHORT, + provider: new Provider(accessibles, filtered, dispatch), + columns, + className, + renderValue: this.renderValue, + renderRow, + label: L10N.getStr("accessibility.treeName"), + header: true, + expandedNodes: expanded, + selected, + onClickRow(nodePath, event) { + if (event.target.classList.contains("theme-twisty")) { + this.toggle(nodePath); + } + + this.selectRow( + this.rows.find(row => row.props.member.path === nodePath), + { preventAutoScroll: true } + ); + + return true; + }, + onContextMenuTree(e) { + // If context menu event is triggered on (or bubbled to) the TreeView, it was + // done via keyboard. Open context menu for currently selected row. + let row = this.getSelectedRow(); + if (!row) { + return; + } + + row = row.getWrappedInstance(); + row.onContextMenu(e); + }, + }); + } +} + +const mapStateToProps = ({ + accessibles, + ui: { expanded, selected, highlighted }, + audit: { filters }, +}) => ({ + accessibles, + expanded, + selected, + highlighted, + filtered: isFiltered(filters), +}); +// Exports from this module +module.exports = connect(mapStateToProps)(AccessibilityTree); diff --git a/devtools/client/accessibility/components/AccessibilityTreeFilter.js b/devtools/client/accessibility/components/AccessibilityTreeFilter.js new file mode 100644 index 0000000000..90eabd350a --- /dev/null +++ b/devtools/client/accessibility/components/AccessibilityTreeFilter.js @@ -0,0 +1,171 @@ +/* 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 gTelemetry */ + +// React +const { + createFactory, + Component, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + div, + hr, + span, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +loader.lazyGetter(this, "MenuButton", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuButton.js") + ); +}); +loader.lazyGetter(this, "MenuItem", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuItem.js") + ); +}); +loader.lazyGetter(this, "MenuList", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuList.js") + ); +}); + +const actions = require("resource://devtools/client/accessibility/actions/audit.js"); + +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); +const { + FILTERS, +} = require("resource://devtools/client/accessibility/constants.js"); + +const TELEMETRY_AUDIT_ACTIVATED = "devtools.accessibility.audit_activated"; +const FILTER_LABELS = { + [FILTERS.NONE]: "accessibility.filter.none", + [FILTERS.ALL]: "accessibility.filter.all2", + [FILTERS.CONTRAST]: "accessibility.filter.contrast", + [FILTERS.KEYBOARD]: "accessibility.filter.keyboard", + [FILTERS.TEXT_LABEL]: "accessibility.filter.textLabel", +}; + +class AccessibilityTreeFilter extends Component { + static get propTypes() { + return { + auditing: PropTypes.array.isRequired, + filters: PropTypes.object.isRequired, + dispatch: PropTypes.func.isRequired, + describedby: PropTypes.string, + toolboxDoc: PropTypes.object.isRequired, + audit: PropTypes.func.isRequired, + }; + } + + async toggleFilter(filterKey) { + const { audit: auditFunc, dispatch, filters } = this.props; + + if (filterKey !== FILTERS.NONE && !filters[filterKey]) { + if (gTelemetry) { + gTelemetry.keyedScalarAdd(TELEMETRY_AUDIT_ACTIVATED, filterKey, 1); + } + + dispatch(actions.auditing(filterKey)); + await dispatch(actions.audit(auditFunc, filterKey)); + } + + // We wait to dispatch filter toggle until the tree is ready to be filtered + // right after the audit. This is to make sure that we render an empty tree + // (filtered) while the audit is running. + dispatch(actions.filterToggle(filterKey)); + } + + onClick(filterKey) { + this.toggleFilter(filterKey); + } + + render() { + const { auditing, filters, describedby, toolboxDoc } = this.props; + const toolbarLabelID = "accessibility-tree-filters-label"; + const filterNoneChecked = !Object.values(filters).includes(true); + const items = [ + MenuItem({ + key: FILTERS.NONE, + checked: filterNoneChecked, + className: `filter ${FILTERS.NONE}`, + label: L10N.getStr(FILTER_LABELS[FILTERS.NONE]), + onClick: this.onClick.bind(this, FILTERS.NONE), + disabled: !!auditing.length, + }), + hr({ key: "hr-1" }), + ]; + + const { [FILTERS.ALL]: filterAllChecked, ...filtersWithoutAll } = filters; + items.push( + MenuItem({ + key: FILTERS.ALL, + checked: filterAllChecked, + className: `filter ${FILTERS.ALL}`, + label: L10N.getStr(FILTER_LABELS[FILTERS.ALL]), + onClick: this.onClick.bind(this, FILTERS.ALL), + disabled: !!auditing.length, + }), + hr({ key: "hr-2" }), + Object.entries(filtersWithoutAll).map(([filterKey, active]) => + MenuItem({ + key: filterKey, + checked: active, + className: `filter ${filterKey}`, + label: L10N.getStr(FILTER_LABELS[filterKey]), + onClick: this.onClick.bind(this, filterKey), + disabled: !!auditing.length, + }) + ) + ); + + let label; + if (filterNoneChecked) { + label = L10N.getStr(FILTER_LABELS[FILTERS.NONE]); + } else if (filterAllChecked) { + label = L10N.getStr(FILTER_LABELS[FILTERS.ALL]); + } else { + label = Object.keys(filtersWithoutAll) + .filter(filterKey => filtersWithoutAll[filterKey]) + .map(filterKey => L10N.getStr(FILTER_LABELS[filterKey])) + .join(", "); + } + + return div( + { + role: "group", + className: "accessibility-tree-filters", + "aria-labelledby": toolbarLabelID, + "aria-describedby": describedby, + }, + span( + { id: toolbarLabelID, role: "presentation" }, + L10N.getStr("accessibility.tree.filters") + ), + MenuButton( + { + menuId: "accessibility-tree-filters-menu", + toolboxDoc, + className: `devtools-button badge toolbar-menu-button filters`, + label, + }, + MenuList({}, items) + ) + ); + } +} + +const mapStateToProps = ({ audit: { filters, auditing } }) => { + return { filters, auditing }; +}; + +// Exports from this module +module.exports = connect(mapStateToProps)(AccessibilityTreeFilter); diff --git a/devtools/client/accessibility/components/Accessible.js b/devtools/client/accessibility/components/Accessible.js new file mode 100644 index 0000000000..02467ccaab --- /dev/null +++ b/devtools/client/accessibility/components/Accessible.js @@ -0,0 +1,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); diff --git a/devtools/client/accessibility/components/AuditController.js b/devtools/client/accessibility/components/AuditController.js new file mode 100644 index 0000000000..e6ada9a0a9 --- /dev/null +++ b/devtools/client/accessibility/components/AuditController.js @@ -0,0 +1,90 @@ +/* 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 React = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); + +class AuditController extends React.Component { + static get propTypes() { + return { + accessibleFront: PropTypes.object.isRequired, + children: PropTypes.any, + }; + } + + constructor(props) { + super(props); + + const { + accessibleFront: { checks }, + } = props; + this.state = { + checks, + }; + + this.onAudited = this.onAudited.bind(this); + } + + // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507 + UNSAFE_componentWillMount() { + const { accessibleFront } = this.props; + accessibleFront.on("audited", this.onAudited); + } + + componentDidMount() { + this.maybeRequestAudit(); + } + + componentDidUpdate() { + this.maybeRequestAudit(); + } + + componentWillUnmount() { + const { accessibleFront } = this.props; + accessibleFront.off("audited", this.onAudited); + } + + onAudited() { + const { accessibleFront } = this.props; + if (accessibleFront.isDestroyed()) { + // Accessible front is being removed, stop listening for 'audited' events. + accessibleFront.off("audited", this.onAudited); + return; + } + + this.setState({ checks: accessibleFront.checks }); + } + + maybeRequestAudit() { + const { accessibleFront } = this.props; + if (accessibleFront.isDestroyed()) { + // Accessible front is being removed, stop listening for 'audited' events. + accessibleFront.off("audited", this.onAudited); + return; + } + + if (accessibleFront.checks) { + return; + } + + accessibleFront.audit().catch(error => { + // If the actor was destroyed (due to a connection closed for instance) do + // nothing, otherwise log a warning + if (!accessibleFront.isDestroyed()) { + console.warn(error); + } + }); + } + + render() { + const { children } = this.props; + const { checks } = this.state; + + return React.Children.only(React.cloneElement(children, { checks })); + } +} + +module.exports = AuditController; diff --git a/devtools/client/accessibility/components/AuditFilter.js b/devtools/client/accessibility/components/AuditFilter.js new file mode 100644 index 0000000000..361a1c30a7 --- /dev/null +++ b/devtools/client/accessibility/components/AuditFilter.js @@ -0,0 +1,91 @@ +/* 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 React = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); + +const { + isFiltered, +} = require("resource://devtools/client/accessibility/utils/audit.js"); +const { + FILTERS, +} = require("resource://devtools/client/accessibility/constants.js"); +const { + accessibility: { + AUDIT_TYPE, + SCORES: { BEST_PRACTICES, FAIL, WARNING }, + }, +} = require("resource://devtools/shared/constants.js"); + +function validateCheck({ error, score }) { + return !error && [BEST_PRACTICES, FAIL, WARNING].includes(score); +} + +const AUDIT_TYPE_TO_FILTER = { + [AUDIT_TYPE.CONTRAST]: { + filterKey: FILTERS.CONTRAST, + validator: validateCheck, + }, + [AUDIT_TYPE.KEYBOARD]: { + filterKey: FILTERS.KEYBOARD, + validator: validateCheck, + }, + [AUDIT_TYPE.TEXT_LABEL]: { + filterKey: FILTERS.TEXT_LABEL, + validator: validateCheck, + }, +}; + +class AuditFilter extends React.Component { + static get propTypes() { + return { + checks: PropTypes.object, + children: PropTypes.any, + filters: PropTypes.object.isRequired, + }; + } + + isVisible(filters) { + return !isFiltered(filters); + } + + shouldHide() { + const { filters, checks } = this.props; + if (this.isVisible(filters)) { + return false; + } + + if (!checks || Object.values(checks).every(check => check == null)) { + return true; + } + + for (const type in checks) { + if ( + AUDIT_TYPE_TO_FILTER[type] && + checks[type] && + filters[AUDIT_TYPE_TO_FILTER[type].filterKey] && + AUDIT_TYPE_TO_FILTER[type].validator(checks[type]) + ) { + return false; + } + } + + return true; + } + + render() { + return this.shouldHide() ? null : this.props.children; + } +} + +const mapStateToProps = ({ audit: { filters } }) => { + return { filters }; +}; + +module.exports = connect(mapStateToProps)(AuditFilter); diff --git a/devtools/client/accessibility/components/AuditProgressOverlay.js b/devtools/client/accessibility/components/AuditProgressOverlay.js new file mode 100644 index 0000000000..3c16998bcf --- /dev/null +++ b/devtools/client/accessibility/components/AuditProgressOverlay.js @@ -0,0 +1,92 @@ +/* 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 React = require("resource://devtools/client/shared/vendor/react.js"); +const ReactDOM = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); + +const FluentReact = require("resource://devtools/client/shared/vendor/fluent-react.js"); +const Localized = React.createFactory(FluentReact.Localized); + +/** + * Helper functional component to render an accessible text progressbar. + * @param {Object} props + * - id for the progressbar element + * - fluentId: localized string id + */ +function TextProgressBar({ id, fluentId }) { + return Localized( + { + id: fluentId, + attrs: { "aria-valuetext": true }, + }, + ReactDOM.span({ + id, + key: id, + role: "progressbar", + }) + ); +} + +class AuditProgressOverlay extends React.Component { + static get propTypes() { + return { + auditing: PropTypes.array.isRequired, + total: PropTypes.number, + percentage: PropTypes.number, + }; + } + + render() { + const { auditing, percentage, total } = this.props; + if (auditing.length === 0) { + return null; + } + + const id = "audit-progress-container"; + + if (total == null) { + return TextProgressBar({ + id, + fluentId: "accessibility-progress-initializing", + }); + } + + if (percentage === 100) { + return TextProgressBar({ + id, + fluentId: "accessibility-progress-finishing", + }); + } + + return ReactDOM.span( + { + id, + key: id, + }, + Localized({ + id: "accessibility-progress-progressbar", + $nodeCount: total, + }), + ReactDOM.progress({ + max: 100, + value: percentage, + className: "audit-progress-progressbar", + "aria-labelledby": id, + }) + ); + } +} + +const mapStateToProps = ({ audit: { auditing, progress } }) => { + const { total, percentage } = progress || {}; + return { auditing, total, percentage }; +}; + +module.exports = connect(mapStateToProps)(AuditProgressOverlay); diff --git a/devtools/client/accessibility/components/Badge.js b/devtools/client/accessibility/components/Badge.js new file mode 100644 index 0000000000..207bb96f55 --- /dev/null +++ b/devtools/client/accessibility/components/Badge.js @@ -0,0 +1,40 @@ +/* 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"; + +// React +const { + Component, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + span, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); + +class Badge extends Component { + static get propTypes() { + return { + score: PropTypes.string.isRequired, + label: PropTypes.string.isRequired, + ariaLabel: PropTypes.string, + tooltip: PropTypes.string, + }; + } + + render() { + const { score, label, ariaLabel, tooltip } = this.props; + + return span( + { + className: `audit-badge badge`, + "data-score": score, + title: tooltip, + "aria-label": ariaLabel || label, + }, + label + ); + } +} + +module.exports = Badge; diff --git a/devtools/client/accessibility/components/Badges.js b/devtools/client/accessibility/components/Badges.js new file mode 100644 index 0000000000..00079d21b6 --- /dev/null +++ b/devtools/client/accessibility/components/Badges.js @@ -0,0 +1,88 @@ +/* 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"; + +// React +const { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + span, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + accessibility: { AUDIT_TYPE }, +} = require("resource://devtools/shared/constants.js"); + +loader.lazyGetter(this, "ContrastBadge", () => + createFactory( + require("resource://devtools/client/accessibility/components/ContrastBadge.js") + ) +); + +loader.lazyGetter(this, "KeyboardBadge", () => + createFactory( + require("resource://devtools/client/accessibility/components/KeyboardBadge.js") + ) +); + +loader.lazyGetter(this, "TextLabelBadge", () => + createFactory( + require("resource://devtools/client/accessibility/components/TextLabelBadge.js") + ) +); + +function getComponentForAuditType(type) { + const auditTypeToComponentMap = { + [AUDIT_TYPE.CONTRAST]: ContrastBadge, + [AUDIT_TYPE.KEYBOARD]: KeyboardBadge, + [AUDIT_TYPE.TEXT_LABEL]: TextLabelBadge, + }; + + return auditTypeToComponentMap[type]; +} + +class Badges extends Component { + static get propTypes() { + return { + checks: PropTypes.object, + }; + } + + render() { + const { checks } = this.props; + if (!checks) { + return null; + } + + const items = []; + for (const type in checks) { + const component = getComponentForAuditType(type); + if (checks[type] && component) { + items.push(component({ key: type, ...checks[type] })); + } + } + + if (items.length === 0) { + return null; + } + + return span( + { + className: "badges", + role: "group", + "aria-label": L10N.getStr("accessibility.badges"), + }, + items + ); + } +} + +module.exports = Badges; diff --git a/devtools/client/accessibility/components/Button.js b/devtools/client/accessibility/components/Button.js new file mode 100644 index 0000000000..92cd90a56c --- /dev/null +++ b/devtools/client/accessibility/components/Button.js @@ -0,0 +1,112 @@ +/* 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 { + Component, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + button, + span, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const defaultProps = { + disabled: false, + busy: false, + title: null, + children: null, + className: "", +}; + +/** + * Button component that handles keyboard in an accessible way. When user + * uses the mouse to hover/click on the button, there is no focus + * highlighting. However if the user uses a keyboard to focus on the button, + * it will have focus highlighting in the form of an outline. + */ +class Button extends Component { + static get propTypes() { + return { + disabled: PropTypes.bool, + busy: PropTypes.bool, + title: PropTypes.string, + children: PropTypes.string, + className: PropTypes.string, + }; + } + + static get defaultProps() { + return defaultProps; + } + + render() { + const className = [ + ...this.props.className.split(" "), + "devtools-button", + ].join(" "); + const props = Object.assign({}, this.props, { + className, + "aria-busy": this.props.busy.toString(), + busy: this.props.busy.toString(), + }); + + const classList = ["btn-content"]; + if (this.props.busy) { + classList.push("devtools-throbber"); + } + + return button( + props, + span( + { + className: classList.join(" "), + tabIndex: -1, + }, + this.props.children + ) + ); + } +} + +function ToggleButton(props) { + const { + active, + busy, + disabled, + label, + className, + onClick, + onKeyDown, + tooltip, + } = props; + const classList = [...className.split(" "), "toggle-button"]; + + if (active) { + classList.push("checked"); + } + + if (busy) { + classList.push("devtools-throbber"); + } + + return button( + { + disabled, + "aria-pressed": active === true, + "aria-busy": busy, + className: classList.join(" "), + onClick, + onKeyDown, + title: tooltip, + }, + label + ); +} + +module.exports = { + Button, + ToggleButton, +}; diff --git a/devtools/client/accessibility/components/Check.js b/devtools/client/accessibility/components/Check.js new file mode 100644 index 0000000000..3ca6c9c39a --- /dev/null +++ b/devtools/client/accessibility/components/Check.js @@ -0,0 +1,157 @@ +/* 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"; + +// React +const { + Component, + createFactory, + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const ReactDOM = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const FluentReact = require("resource://devtools/client/shared/vendor/fluent-react.js"); +const Localized = createFactory(FluentReact.Localized); + +const { openDocLink } = require("resource://devtools/client/shared/link.js"); + +const { + accessibility: { + SCORES: { BEST_PRACTICES, FAIL, WARNING }, + }, +} = require("resource://devtools/shared/constants.js"); + +/** + * A map of accessibility scores to the text descriptions of check icons. + */ +const SCORE_TO_ICON_MAP = { + [BEST_PRACTICES]: { + l10nId: "accessibility-best-practices", + src: "chrome://devtools/skin/images/info.svg", + }, + [FAIL]: { + l10nId: "accessibility-fail", + src: "chrome://devtools/skin/images/error.svg", + }, + [WARNING]: { + l10nId: "accessibility-warning", + src: "chrome://devtools/skin/images/alert.svg", + }, +}; + +/** + * Localized "Learn more" link that opens a new tab with relevant documentation. + */ +class LearnMoreClass extends PureComponent { + static get propTypes() { + return { + href: PropTypes.string, + l10nId: PropTypes.string.isRequired, + onClick: PropTypes.func, + }; + } + + static get defaultProps() { + return { + href: "#", + l10nId: null, + onClick: LearnMoreClass.openDocOnClick, + }; + } + + static openDocOnClick(event) { + event.preventDefault(); + openDocLink(event.target.href); + } + + render() { + const { href, l10nId, onClick } = this.props; + const className = "link"; + + return Localized({ id: l10nId }, ReactDOM.a({ className, href, onClick })); + } +} + +const LearnMore = createFactory(LearnMoreClass); + +/** + * Renders icon with text description for the accessibility check. + * + * @param {Object} + * Options: + * - score: value from SCORES from "devtools/shared/constants" + */ +function Icon({ score }) { + const { l10nId, src } = SCORE_TO_ICON_MAP[score]; + + return Localized( + { id: l10nId, attrs: { alt: true } }, + ReactDOM.img({ src, "data-score": score, className: "icon" }) + ); +} + +/** + * Renders text description of the accessibility check. + * + * @param {Object} + * Options: + * - args: arguments for fluent localized string + * - href: url for the learn more link pointing to MDN + * - l10nId: fluent localization id + */ +function Annotation({ args, href, l10nId }) { + return Localized( + { + id: l10nId, + a: LearnMore({ l10nId: "accessibility-learn-more", href }), + ...args, + }, + ReactDOM.p({ className: "accessibility-check-annotation" }) + ); +} + +/** + * Component for rendering a check for accessibliity checks section, + * warnings and best practices suggestions association with a given + * accessibility object in the accessibility tree. + */ +class Check extends Component { + static get propTypes() { + return { + getAnnotation: PropTypes.func.isRequired, + id: PropTypes.string.isRequired, + issue: PropTypes.string.isRequired, + score: PropTypes.string.isRequired, + }; + } + + render() { + const { getAnnotation, id, issue, score } = this.props; + + return ReactDOM.div( + { + role: "presentation", + tabIndex: "-1", + className: "accessibility-check", + }, + Localized( + { + id, + }, + ReactDOM.h3({ className: "accessibility-check-header" }) + ), + ReactDOM.div( + { + role: "presentation", + tabIndex: "-1", + }, + Icon({ score }), + Annotation({ ...getAnnotation(issue) }) + ) + ); + } +} + +module.exports = Check; diff --git a/devtools/client/accessibility/components/Checks.js b/devtools/client/accessibility/components/Checks.js new file mode 100644 index 0000000000..f2b4e4835a --- /dev/null +++ b/devtools/client/accessibility/components/Checks.js @@ -0,0 +1,117 @@ +/* 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"; + +// React +const { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + div, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const List = createFactory( + require("resource://devtools/client/shared/components/List.js").List +); +const ColorContrastCheck = createFactory( + require("resource://devtools/client/accessibility/components/ColorContrastAccessibility.js") + .ColorContrastCheck +); +const TextLabelCheck = createFactory( + require("resource://devtools/client/accessibility/components/TextLabelCheck.js") +); +const KeyboardCheck = createFactory( + require("resource://devtools/client/accessibility/components/KeyboardCheck.js") +); +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + accessibility: { AUDIT_TYPE }, +} = require("resource://devtools/shared/constants.js"); + +function EmptyChecks() { + return div( + { + className: "checks-empty", + role: "presentation", + tabIndex: "-1", + }, + L10N.getStr("accessibility.checks.empty2") + ); +} + +// Component that is responsible for rendering accessible audit data in the a11y panel +// sidebar. +class Checks extends Component { + static get propTypes() { + return { + audit: PropTypes.object, + labelledby: PropTypes.string.isRequired, + }; + } + + [AUDIT_TYPE.CONTRAST](contrastRatio) { + return ColorContrastCheck(contrastRatio); + } + + [AUDIT_TYPE.KEYBOARD](keyboardCheck) { + return KeyboardCheck(keyboardCheck); + } + + [AUDIT_TYPE.TEXT_LABEL](textLabelCheck) { + return TextLabelCheck(textLabelCheck); + } + + render() { + const { audit, labelledby } = this.props; + if (!audit) { + return EmptyChecks(); + } + + const items = []; + for (const name in audit) { + // There are going to be various audit reports for this object, sent by the server. + // Iterate over them and delegate rendering to the method with the corresponding + // name. + if (audit[name] && this[name]) { + items.push({ + component: this[name](audit[name]), + className: name, + key: name, + }); + } + } + + if (items.length === 0) { + return EmptyChecks(); + } + + return div( + { + className: "checks", + role: "presentation", + tabIndex: "-1", + }, + List({ items, labelledby }) + ); + } +} + +const mapStateToProps = ({ details, ui }) => { + const { audit } = details; + if (!audit) { + return {}; + } + + return { audit }; +}; + +module.exports = connect(mapStateToProps)(Checks); diff --git a/devtools/client/accessibility/components/ColorContrastAccessibility.js b/devtools/client/accessibility/components/ColorContrastAccessibility.js new file mode 100644 index 0000000000..117ab67593 --- /dev/null +++ b/devtools/client/accessibility/components/ColorContrastAccessibility.js @@ -0,0 +1,229 @@ +/* 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 { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + div, + span, + h3, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const LearnMoreLink = createFactory( + require("resource://devtools/client/accessibility/components/LearnMoreLink.js") +); + +const { + A11Y_CONTRAST_LEARN_MORE_LINK, +} = require("resource://devtools/client/accessibility/constants.js"); +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +/** + * Component that renders a colour contrast value along with a swatch preview of what the + * text and background colours are. + */ +class ContrastValueClass extends Component { + static get propTypes() { + return { + backgroundColor: PropTypes.array.isRequired, + color: PropTypes.array.isRequired, + value: PropTypes.number.isRequired, + score: PropTypes.string, + }; + } + + render() { + const { backgroundColor, color, value, score } = this.props; + + const className = ["accessibility-contrast-value", score].join(" "); + + return span( + { + className, + role: "presentation", + style: { + "--accessibility-contrast-color": `rgba(${color})`, + "--accessibility-contrast-bg": `rgba(${backgroundColor})`, + }, + }, + value.toFixed(2) + ); + } +} + +const ContrastValue = createFactory(ContrastValueClass); + +/** + * Component that renders labeled colour contrast values together with the large text + * indiscator. + */ +class ColorContrastAccessibilityClass extends Component { + static get propTypes() { + return { + error: PropTypes.string, + isLargeText: PropTypes.bool.isRequired, + color: PropTypes.array.isRequired, + value: PropTypes.number, + min: PropTypes.number, + max: PropTypes.number, + backgroundColor: PropTypes.array, + backgroundColorMin: PropTypes.array, + backgroundColorMax: PropTypes.array, + score: PropTypes.string, + scoreMin: PropTypes.string, + scoreMax: PropTypes.string, + }; + } + + render() { + const { + error, + isLargeText, + color, + value, + backgroundColor, + score, + min, + backgroundColorMin, + scoreMin, + max, + backgroundColorMax, + scoreMax, + } = this.props; + + const children = []; + + if (error) { + children.push( + span( + { + className: "accessibility-color-contrast-error", + role: "presentation", + }, + L10N.getStr("accessibility.contrast.error") + ) + ); + + return div( + { + role: "presentation", + tabIndex: "-1", + className: "accessibility-color-contrast", + }, + ...children + ); + } + + if (value) { + children.push(ContrastValue({ score, color, backgroundColor, value })); + } else { + children.push( + ContrastValue({ + score: scoreMin, + color, + backgroundColor: backgroundColorMin, + value: min, + }), + div({ + role: "presentation", + tabIndex: "-1", + className: "accessibility-color-contrast-separator", + }), + ContrastValue({ + score: scoreMax, + color, + backgroundColor: backgroundColorMax, + value: max, + }) + ); + } + + if (isLargeText) { + children.push( + span( + { + className: "accessibility-color-contrast-large-text", + role: "presentation", + title: L10N.getStr("accessibility.contrast.large.title"), + }, + L10N.getStr("accessibility.contrast.large.text") + ) + ); + } + + return div( + { + role: "presentation", + tabIndex: "-1", + className: "accessibility-color-contrast", + }, + ...children + ); + } +} + +const ColorContrastAccessibility = createFactory( + ColorContrastAccessibilityClass +); + +class ContrastAnnotationClass extends Component { + static get propTypes() { + return { + score: PropTypes.string, + }; + } + + render() { + const { score } = this.props; + + return LearnMoreLink({ + className: "accessibility-check-annotation", + href: A11Y_CONTRAST_LEARN_MORE_LINK, + learnMoreStringKey: "accessibility.learnMore", + l10n: L10N, + messageStringKey: `accessibility.contrast.annotation.${score}`, + }); + } +} + +const ContrastAnnotation = createFactory(ContrastAnnotationClass); + +class ColorContrastCheck extends Component { + static get propTypes() { + return { + error: PropTypes.string.isRequired, + }; + } + + render() { + const { error } = this.props; + + return div( + { + role: "presentation", + tabIndex: "-1", + className: "accessibility-check", + }, + h3( + { + className: "accessibility-check-header", + }, + L10N.getStr("accessibility.contrast.header") + ), + ColorContrastAccessibility(this.props), + !error && ContrastAnnotation(this.props) + ); + } +} + +module.exports = { + ColorContrastAccessibility: ColorContrastAccessibilityClass, + ColorContrastCheck, +}; diff --git a/devtools/client/accessibility/components/ContrastBadge.js b/devtools/client/accessibility/components/ContrastBadge.js new file mode 100644 index 0000000000..ee37958f1e --- /dev/null +++ b/devtools/client/accessibility/components/ContrastBadge.js @@ -0,0 +1,55 @@ +/* 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"; + +// React +const { + createFactory, + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + accessibility: { SCORES }, +} = require("resource://devtools/shared/constants.js"); + +loader.lazyGetter(this, "Badge", () => + createFactory( + require("resource://devtools/client/accessibility/components/Badge.js") + ) +); + +/** + * Component for rendering a badge for contrast accessibliity check + * failures association with a given accessibility object in the accessibility + * tree. + */ +class ContrastBadge extends PureComponent { + static get propTypes() { + return { + error: PropTypes.string, + score: PropTypes.string, + }; + } + + render() { + const { error, score } = this.props; + if (error || score !== SCORES.FAIL) { + return null; + } + + return Badge({ + score, + label: L10N.getStr("accessibility.badge.contrast"), + ariaLabel: L10N.getStr("accessibility.badge.contrast.warning"), + tooltip: L10N.getStr("accessibility.badge.contrast.tooltip"), + }); + } +} + +module.exports = ContrastBadge; diff --git a/devtools/client/accessibility/components/Description.js b/devtools/client/accessibility/components/Description.js new file mode 100644 index 0000000000..a31dbcbfa6 --- /dev/null +++ b/devtools/client/accessibility/components/Description.js @@ -0,0 +1,56 @@ +/* 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"; + +// React & Redux +const { + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + div, + p, + img, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const LearnMoreLink = createFactory( + require("resource://devtools/client/accessibility/components/LearnMoreLink.js") +); + +// Localization +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + A11Y_LEARN_MORE_LINK, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Landing UI for the accessibility panel when Accessibility features are + * deactivated. + */ +function Description() { + return div( + { className: "description", role: "presentation", tabIndex: "-1" }, + div( + { className: "general", role: "presentation", tabIndex: "-1" }, + img({ + src: "chrome://devtools/skin/images/accessibility.svg", + alt: L10N.getStr("accessibility.logo"), + }), + div( + { role: "presentation", tabIndex: "-1" }, + LearnMoreLink({ + href: A11Y_LEARN_MORE_LINK, + learnMoreStringKey: "accessibility.learnMore", + l10n: L10N, + messageStringKey: "accessibility.description.general.p1", + }), + p({}, L10N.getStr("accessibility.enable.disabledTitle")) + ) + ) + ); +} + +// Exports from this module +exports.Description = Description; diff --git a/devtools/client/accessibility/components/DisplayTabbingOrder.js b/devtools/client/accessibility/components/DisplayTabbingOrder.js new file mode 100644 index 0000000000..f6e3fdf453 --- /dev/null +++ b/devtools/client/accessibility/components/DisplayTabbingOrder.js @@ -0,0 +1,79 @@ +/* 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"; + +// React +const { + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + label, + input, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); +const { + updateDisplayTabbingOrder, +} = require("resource://devtools/client/accessibility/actions/ui.js"); + +class DisplayTabbingOrder extends PureComponent { + static get propTypes() { + return { + dispatch: PropTypes.func.isRequired, + tabbingOrderDisplayed: PropTypes.bool.isRequired, + }; + } + + constructor(props) { + super(props); + + this.state = { + disabled: false, + }; + + this.onChange = this.onChange.bind(this); + } + + async onChange() { + const { dispatch, tabbingOrderDisplayed } = this.props; + + this.setState({ disabled: true }); + await dispatch(updateDisplayTabbingOrder(!tabbingOrderDisplayed)); + this.setState({ disabled: false }); + } + + render() { + const { tabbingOrderDisplayed } = this.props; + return label( + { + className: + "accessibility-tabbing-order devtools-checkbox-label devtools-ellipsis-text", + htmlFor: "devtools-display-tabbing-order-checkbox", + title: L10N.getStr("accessibility.toolbar.displayTabbingOrder.tooltip"), + }, + input({ + id: "devtools-display-tabbing-order-checkbox", + className: "devtools-checkbox", + type: "checkbox", + checked: tabbingOrderDisplayed, + disabled: this.state.disabled, + onChange: this.onChange, + }), + L10N.getStr("accessibility.toolbar.displayTabbingOrder.label") + ); + } +} + +const mapStateToProps = ({ ui: { tabbingOrderDisplayed } }) => ({ + tabbingOrderDisplayed, +}); + +module.exports = connect(mapStateToProps)(DisplayTabbingOrder); diff --git a/devtools/client/accessibility/components/KeyboardBadge.js b/devtools/client/accessibility/components/KeyboardBadge.js new file mode 100644 index 0000000000..ac6b6b8841 --- /dev/null +++ b/devtools/client/accessibility/components/KeyboardBadge.js @@ -0,0 +1,56 @@ +/* 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"; + +// React +const { + createFactory, + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + accessibility: { + SCORES: { BEST_PRACTICES, FAIL, WARNING }, + }, +} = require("resource://devtools/shared/constants.js"); + +loader.lazyGetter(this, "Badge", () => + createFactory( + require("resource://devtools/client/accessibility/components/Badge.js") + ) +); + +/** + * Component for rendering a badge for keyboard accessibliity check failures + * association with a given accessibility object in the accessibility tree. + */ +class KeyboardBadge extends PureComponent { + static get propTypes() { + return { + error: PropTypes.string, + score: PropTypes.string, + }; + } + + render() { + const { error, score } = this.props; + if (error || ![BEST_PRACTICES, FAIL, WARNING].includes(score)) { + return null; + } + + return Badge({ + score, + label: L10N.getStr("accessibility.badge.keyboard"), + tooltip: L10N.getStr("accessibility.badge.keyboard.tooltip"), + }); + } +} + +module.exports = KeyboardBadge; diff --git a/devtools/client/accessibility/components/KeyboardCheck.js b/devtools/client/accessibility/components/KeyboardCheck.js new file mode 100644 index 0000000000..0109dd22b0 --- /dev/null +++ b/devtools/client/accessibility/components/KeyboardCheck.js @@ -0,0 +1,94 @@ +/* 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"; + +// React +const { + createFactory, + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const ReactDOM = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const Check = createFactory( + require("resource://devtools/client/accessibility/components/Check.js") +); + +const { + A11Y_KEYBOARD_LINKS, +} = require("resource://devtools/client/accessibility/constants.js"); +const { + accessibility: { + AUDIT_TYPE: { KEYBOARD }, + ISSUE_TYPE: { + [KEYBOARD]: { + FOCUSABLE_NO_SEMANTICS, + FOCUSABLE_POSITIVE_TABINDEX, + INTERACTIVE_NO_ACTION, + INTERACTIVE_NOT_FOCUSABLE, + MOUSE_INTERACTIVE_ONLY, + NO_FOCUS_VISIBLE, + }, + }, + }, +} = require("resource://devtools/shared/constants.js"); + +/** + * A map from text label issues to annotation component properties. + */ +const ISSUE_TO_ANNOTATION_MAP = { + [FOCUSABLE_NO_SEMANTICS]: { + href: A11Y_KEYBOARD_LINKS.FOCUSABLE_NO_SEMANTICS, + l10nId: "accessibility-keyboard-issue-semantics", + }, + [FOCUSABLE_POSITIVE_TABINDEX]: { + href: A11Y_KEYBOARD_LINKS.FOCUSABLE_POSITIVE_TABINDEX, + l10nId: "accessibility-keyboard-issue-tabindex", + args: { + get code() { + return ReactDOM.code({}, "tabindex"); + }, + }, + }, + [INTERACTIVE_NO_ACTION]: { + href: A11Y_KEYBOARD_LINKS.INTERACTIVE_NO_ACTION, + l10nId: "accessibility-keyboard-issue-action", + }, + [INTERACTIVE_NOT_FOCUSABLE]: { + href: A11Y_KEYBOARD_LINKS.INTERACTIVE_NOT_FOCUSABLE, + l10nId: "accessibility-keyboard-issue-focusable", + }, + [MOUSE_INTERACTIVE_ONLY]: { + href: A11Y_KEYBOARD_LINKS.MOUSE_INTERACTIVE_ONLY, + l10nId: "accessibility-keyboard-issue-mouse-only", + }, + [NO_FOCUS_VISIBLE]: { + href: A11Y_KEYBOARD_LINKS.NO_FOCUS_VISIBLE, + l10nId: "accessibility-keyboard-issue-focus-visible", + }, +}; + +/** + * Component for rendering a check for text label accessibliity check failures, + * warnings and best practices suggestions association with a given + * accessibility object in the accessibility tree. + */ +class KeyboardCheck extends PureComponent { + static get propTypes() { + return { + issue: PropTypes.string.isRequired, + score: PropTypes.string.isRequired, + }; + } + + render() { + return Check({ + ...this.props, + getAnnotation: issue => ISSUE_TO_ANNOTATION_MAP[issue], + id: "accessibility-keyboard-header", + }); + } +} + +module.exports = KeyboardCheck; diff --git a/devtools/client/accessibility/components/LearnMoreLink.js b/devtools/client/accessibility/components/LearnMoreLink.js new file mode 100644 index 0000000000..2a21df4ea5 --- /dev/null +++ b/devtools/client/accessibility/components/LearnMoreLink.js @@ -0,0 +1,76 @@ +/* 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 { + Component, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + p, + a, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const { openDocLink } = require("resource://devtools/client/shared/link.js"); + +/** + * Localization friendly component for rendering a block of text with a "Learn more" link + * as a part of it. + */ +class LearnMoreLink extends Component { + static get propTypes() { + return { + className: PropTypes.string, + href: PropTypes.string, + learnMoreStringKey: PropTypes.string.isRequired, + l10n: PropTypes.object.isRequired, + messageStringKey: PropTypes.string.isRequired, + onClick: PropTypes.func, + }; + } + + static get defaultProps() { + return { + href: "#", + learnMoreStringKey: null, + l10n: null, + messageStringKey: null, + onClick: LearnMoreLink.openDocOnClick, + }; + } + + static openDocOnClick(event) { + event.preventDefault(); + openDocLink(event.target.href); + } + + render() { + const { + className, + href, + learnMoreStringKey, + l10n, + messageStringKey, + onClick, + } = this.props; + const learnMoreString = l10n.getStr(learnMoreStringKey); + const messageString = l10n.getFormatStr(messageStringKey, learnMoreString); + + // Split the paragraph string with the link as a separator, and include the link into + // results. + const re = new RegExp(`(\\b${learnMoreString}\\b)`); + const contents = messageString.split(re); + contents[1] = a({ className: "link", href, onClick }, contents[1]); + + return p( + { + className, + }, + ...contents + ); + } +} + +module.exports = LearnMoreLink; diff --git a/devtools/client/accessibility/components/MainFrame.js b/devtools/client/accessibility/components/MainFrame.js new file mode 100644 index 0000000000..d918dc7be0 --- /dev/null +++ b/devtools/client/accessibility/components/MainFrame.js @@ -0,0 +1,245 @@ +/* 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"; + +// React & Redux +const { + Component, + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + span, + div, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); +const { + enable, + reset, + updateCanBeEnabled, + updateCanBeDisabled, +} = require("resource://devtools/client/accessibility/actions/ui.js"); + +// Localization +const FluentReact = require("resource://devtools/client/shared/vendor/fluent-react.js"); +const LocalizationProvider = createFactory(FluentReact.LocalizationProvider); + +// Constants +const { + SIDEBAR_WIDTH, + PORTRAIT_MODE_WIDTH, +} = require("resource://devtools/client/accessibility/constants.js"); + +// Accessibility Panel +const AccessibilityTree = createFactory( + require("resource://devtools/client/accessibility/components/AccessibilityTree.js") +); +const AuditProgressOverlay = createFactory( + require("resource://devtools/client/accessibility/components/AuditProgressOverlay.js") +); +const Description = createFactory( + require("resource://devtools/client/accessibility/components/Description.js") + .Description +); +const RightSidebar = createFactory( + require("resource://devtools/client/accessibility/components/RightSidebar.js") +); +const Toolbar = createFactory( + require("resource://devtools/client/accessibility/components/Toolbar.js") + .Toolbar +); +const SplitBox = createFactory( + require("resource://devtools/client/shared/components/splitter/SplitBox.js") +); + +/** + * Renders basic layout of the Accessibility panel. The Accessibility panel + * content consists of two main parts: tree and sidebar. + */ +class MainFrame extends Component { + static get propTypes() { + return { + fluentBundles: PropTypes.array.isRequired, + enabled: PropTypes.bool.isRequired, + dispatch: PropTypes.func.isRequired, + auditing: PropTypes.array.isRequired, + supports: PropTypes.object, + toolbox: PropTypes.object.isRequired, + getAccessibilityTreeRoot: PropTypes.func.isRequired, + startListeningForAccessibilityEvents: PropTypes.func.isRequired, + stopListeningForAccessibilityEvents: PropTypes.func.isRequired, + audit: PropTypes.func.isRequired, + simulate: PropTypes.func, + enableAccessibility: PropTypes.func.isRequired, + resetAccessiblity: PropTypes.func.isRequired, + startListeningForLifecycleEvents: PropTypes.func.isRequired, + stopListeningForLifecycleEvents: PropTypes.func.isRequired, + startListeningForParentLifecycleEvents: PropTypes.func.isRequired, + stopListeningForParentLifecycleEvents: PropTypes.func.isRequired, + highlightAccessible: PropTypes.func.isRequired, + unhighlightAccessible: PropTypes.func.isRequired, + }; + } + + constructor(props) { + super(props); + + this.resetAccessibility = this.resetAccessibility.bind(this); + this.onPanelWindowResize = this.onPanelWindowResize.bind(this); + this.onCanBeEnabledChange = this.onCanBeEnabledChange.bind(this); + this.onCanBeDisabledChange = this.onCanBeDisabledChange.bind(this); + } + + // FIXME: https://bugzilla.mozilla.org/show_bug.cgi?id=1774507 + UNSAFE_componentWillMount() { + this.props.startListeningForLifecycleEvents({ + init: this.resetAccessibility, + shutdown: this.resetAccessibility, + }); + this.props.startListeningForParentLifecycleEvents({ + "can-be-enabled-change": this.onCanBeEnabledChange, + "can-be-disabled-change": this.onCanBeDisabledChange, + }); + this.props.startListeningForAccessibilityEvents({ + "top-level-document-ready": this.resetAccessibility, + }); + window.addEventListener("resize", this.onPanelWindowResize, true); + } + + componentWillUnmount() { + this.props.stopListeningForLifecycleEvents({ + init: this.resetAccessibility, + shutdown: this.resetAccessibility, + }); + this.props.stopListeningForParentLifecycleEvents({ + "can-be-enabled-change": this.onCanBeEnabledChange, + "can-be-disabled-change": this.onCanBeDisabledChange, + }); + this.props.stopListeningForAccessibilityEvents({ + "top-level-document-ready": this.resetAccessibility, + }); + window.removeEventListener("resize", this.onPanelWindowResize, true); + } + + resetAccessibility() { + const { dispatch, resetAccessiblity, supports } = this.props; + dispatch(reset(resetAccessiblity, supports)); + } + + onCanBeEnabledChange(canBeEnabled) { + const { enableAccessibility, dispatch } = this.props; + dispatch(updateCanBeEnabled(canBeEnabled)); + if (canBeEnabled) { + dispatch(enable(enableAccessibility)); + } + } + + onCanBeDisabledChange(canBeDisabled) { + this.props.dispatch(updateCanBeDisabled(canBeDisabled)); + } + + get useLandscapeMode() { + const { clientWidth } = document.getElementById("content"); + return clientWidth > PORTRAIT_MODE_WIDTH; + } + + /** + * If panel width is less than PORTRAIT_MODE_WIDTH px, the splitter changes + * its mode to `horizontal` to support portrait view. + */ + onPanelWindowResize() { + if (this.refs.splitBox) { + this.refs.splitBox.setState({ vert: this.useLandscapeMode }); + } + } + + /** + * Render Accessibility panel content + */ + render() { + const { + fluentBundles, + enabled, + auditing, + simulate, + toolbox, + getAccessibilityTreeRoot, + startListeningForAccessibilityEvents, + stopListeningForAccessibilityEvents, + audit, + highlightAccessible, + unhighlightAccessible, + } = this.props; + + if (!enabled) { + return Description(); + } + + // Audit is currently running. + const isAuditing = !!auditing.length; + + return LocalizationProvider( + { bundles: fluentBundles }, + div( + { className: "mainFrame", role: "presentation", tabIndex: "-1" }, + Toolbar({ + audit, + simulate, + toolboxDoc: toolbox.doc, + }), + isAuditing && AuditProgressOverlay(), + span( + { + "aria-hidden": isAuditing, + role: "presentation", + style: { display: "contents" }, + }, + SplitBox({ + ref: "splitBox", + initialSize: SIDEBAR_WIDTH, + minSize: "10%", + maxSize: "80%", + splitterSize: 1, + endPanelControl: true, + startPanel: div( + { + className: "main-panel", + role: "presentation", + tabIndex: "-1", + }, + AccessibilityTree({ + toolboxDoc: toolbox.doc, + getAccessibilityTreeRoot, + startListeningForAccessibilityEvents, + stopListeningForAccessibilityEvents, + highlightAccessible, + unhighlightAccessible, + }) + ), + endPanel: RightSidebar({ + highlightAccessible, + unhighlightAccessible, + toolbox, + }), + vert: this.useLandscapeMode, + }) + ) + ) + ); + } +} + +const mapStateToProps = ({ + ui: { enabled, supports }, + audit: { auditing }, +}) => ({ + enabled, + supports, + auditing, +}); + +// Exports from this module +module.exports = connect(mapStateToProps)(MainFrame); diff --git a/devtools/client/accessibility/components/RightSidebar.js b/devtools/client/accessibility/components/RightSidebar.js new file mode 100644 index 0000000000..f525b96294 --- /dev/null +++ b/devtools/client/accessibility/components/RightSidebar.js @@ -0,0 +1,67 @@ +/* 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"; + +// React +const { + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + div, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); +const Accessible = createFactory( + require("resource://devtools/client/accessibility/components/Accessible.js") +); +const Accordion = createFactory( + require("resource://devtools/client/shared/components/Accordion.js") +); +const Checks = createFactory( + require("resource://devtools/client/accessibility/components/Checks.js") +); + +// Component that is responsible for rendering accessible panel's sidebar. +function RightSidebar({ highlightAccessible, unhighlightAccessible, toolbox }) { + const propertiesID = "accessibility-properties"; + const checksID = "accessibility-checks"; + + return div( + { + className: "right-sidebar", + role: "presentation", + tabIndex: "-1", + }, + Accordion({ + items: [ + { + className: "checks", + component: Checks, + componentProps: { labelledby: `${checksID}-header` }, + header: L10N.getStr("accessibility.checks"), + id: checksID, + opened: true, + }, + { + className: "accessible", + component: Accessible, + componentProps: { + highlightAccessible, + unhighlightAccessible, + toolboxHighlighter: toolbox.getHighlighter(), + toolbox, + labelledby: `${propertiesID}-header`, + }, + header: L10N.getStr("accessibility.properties"), + id: propertiesID, + opened: true, + }, + ], + }) + ); +} + +module.exports = RightSidebar; diff --git a/devtools/client/accessibility/components/SimulationMenuButton.js b/devtools/client/accessibility/components/SimulationMenuButton.js new file mode 100644 index 0000000000..6fd21f4cc8 --- /dev/null +++ b/devtools/client/accessibility/components/SimulationMenuButton.js @@ -0,0 +1,167 @@ +/* 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 gTelemetry */ + +// React +const { + createFactory, + Component, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + hr, + span, + div, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); +const MenuButton = createFactory( + require("resource://devtools/client/shared/components/menu/MenuButton.js") +); +const { openDocLink } = require("resource://devtools/client/shared/link.js"); +const { + A11Y_SIMULATION_DOCUMENTATION_LINK, +} = require("resource://devtools/client/accessibility/constants.js"); +const { + accessibility: { SIMULATION_TYPE }, +} = require("resource://devtools/shared/constants.js"); +const actions = require("resource://devtools/client/accessibility/actions/simulation.js"); + +loader.lazyGetter(this, "MenuItem", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuItem.js") + ); +}); +loader.lazyGetter(this, "MenuList", function () { + return createFactory( + require("resource://devtools/client/shared/components/menu/MenuList.js") + ); +}); + +const TELEMETRY_SIMULATION_ACTIVATED = + "devtools.accessibility.simulation_activated"; +const SIMULATION_MENU_LABELS = { + NONE: "accessibility.filter.none", + [SIMULATION_TYPE.ACHROMATOPSIA]: "accessibility.simulation.achromatopsia", + [SIMULATION_TYPE.PROTANOPIA]: "accessibility.simulation.protanopia", + [SIMULATION_TYPE.DEUTERANOPIA]: "accessibility.simulation.deuteranopia", + [SIMULATION_TYPE.TRITANOPIA]: "accessibility.simulation.tritanopia", + [SIMULATION_TYPE.CONTRAST_LOSS]: "accessibility.simulation.contrastLoss", + DOCUMENTATION: "accessibility.documentation.label", +}; + +class SimulationMenuButton extends Component { + static get propTypes() { + return { + simulate: PropTypes.func, + simulation: PropTypes.object.isRequired, + dispatch: PropTypes.func.isRequired, + toolboxDoc: PropTypes.object.isRequired, + }; + } + + constructor(props) { + super(props); + + this.disableSimulation = this.disableSimulation.bind(this); + } + + disableSimulation() { + const { dispatch, simulate: simulateFunc } = this.props; + + dispatch(actions.simulate(simulateFunc)); + } + + toggleSimulation(simKey) { + const { dispatch, simulation, simulate: simulateFunc } = this.props; + + if (!simulation[simKey]) { + if (gTelemetry) { + gTelemetry.keyedScalarAdd(TELEMETRY_SIMULATION_ACTIVATED, simKey, 1); + } + + dispatch(actions.simulate(simulateFunc, [simKey])); + return; + } + + this.disableSimulation(); + } + + render() { + const { simulation, toolboxDoc } = this.props; + const simulationMenuButtonId = "simulation-menu-button"; + const toolbarLabelID = "accessibility-simulation-label"; + const currSimulation = Object.entries(simulation).find( + simEntry => simEntry[1] + ); + + const items = [ + // No simulation option + MenuItem({ + key: "simulation-none", + label: L10N.getStr(SIMULATION_MENU_LABELS.NONE), + checked: !currSimulation, + onClick: this.disableSimulation, + }), + hr({ key: "hr-1" }), + // Simulation options + ...Object.keys(SIMULATION_TYPE).map(simType => + MenuItem({ + key: `simulation-${simType}`, + label: L10N.getStr(SIMULATION_MENU_LABELS[simType]), + checked: simulation[simType], + onClick: this.toggleSimulation.bind(this, simType), + }) + ), + hr({ key: "hr-2" }), + // Documentation link + MenuItem({ + className: "link", + key: "simulation-documentation", + label: L10N.getStr(SIMULATION_MENU_LABELS.DOCUMENTATION), + role: "link", + onClick: () => openDocLink(A11Y_SIMULATION_DOCUMENTATION_LINK), + }), + ]; + + return div( + { + role: "group", + className: "accessibility-simulation", + "aria-labelledby": toolbarLabelID, + }, + span( + { id: toolbarLabelID, role: "presentation" }, + L10N.getStr("accessibility.simulation") + ), + MenuButton( + { + id: simulationMenuButtonId, + menuId: simulationMenuButtonId + "-menu", + className: `devtools-button toolbar-menu-button simulation${ + currSimulation ? " active" : "" + }`, + toolboxDoc, + label: L10N.getStr( + SIMULATION_MENU_LABELS[currSimulation ? currSimulation[0] : "NONE"] + ), + }, + MenuList({}, items) + ) + ); + } +} + +const mapStateToProps = ({ simulation }) => { + return { simulation }; +}; + +// Exports from this module +module.exports = connect(mapStateToProps)(SimulationMenuButton); diff --git a/devtools/client/accessibility/components/TextLabelBadge.js b/devtools/client/accessibility/components/TextLabelBadge.js new file mode 100644 index 0000000000..0ff54ef8e0 --- /dev/null +++ b/devtools/client/accessibility/components/TextLabelBadge.js @@ -0,0 +1,57 @@ +/* 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"; + +// React +const { + createFactory, + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const { + accessibility: { + SCORES: { BEST_PRACTICES, FAIL, WARNING }, + }, +} = require("resource://devtools/shared/constants.js"); + +loader.lazyGetter(this, "Badge", () => + createFactory( + require("resource://devtools/client/accessibility/components/Badge.js") + ) +); + +/** + * Component for rendering a badge for text alternative accessibliity check + * failures association with a given accessibility object in the accessibility + * tree. + */ +class TextLabelBadge extends PureComponent { + static get propTypes() { + return { + error: PropTypes.string, + score: PropTypes.string, + }; + } + + render() { + const { error, score } = this.props; + if (error || ![BEST_PRACTICES, FAIL, WARNING].includes(score)) { + return null; + } + + return Badge({ + score, + label: L10N.getStr("accessibility.badge.textLabel"), + tooltip: L10N.getStr("accessibility.badge.textLabel.tooltip"), + }); + } +} + +module.exports = TextLabelBadge; diff --git a/devtools/client/accessibility/components/TextLabelCheck.js b/devtools/client/accessibility/components/TextLabelCheck.js new file mode 100644 index 0000000000..adfbb4b412 --- /dev/null +++ b/devtools/client/accessibility/components/TextLabelCheck.js @@ -0,0 +1,225 @@ +/* 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"; + +// React +const { + createFactory, + PureComponent, +} = require("resource://devtools/client/shared/vendor/react.js"); +const PropTypes = require("resource://devtools/client/shared/vendor/react-prop-types.js"); +const ReactDOM = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); + +const Check = createFactory( + require("resource://devtools/client/accessibility/components/Check.js") +); + +const { + A11Y_TEXT_LABEL_LINKS, +} = require("resource://devtools/client/accessibility/constants.js"); +const { + accessibility: { + AUDIT_TYPE: { TEXT_LABEL }, + ISSUE_TYPE: { + [TEXT_LABEL]: { + AREA_NO_NAME_FROM_ALT, + DIALOG_NO_NAME, + DOCUMENT_NO_TITLE, + EMBED_NO_NAME, + FIGURE_NO_NAME, + FORM_FIELDSET_NO_NAME, + FORM_FIELDSET_NO_NAME_FROM_LEGEND, + FORM_NO_NAME, + FORM_NO_VISIBLE_NAME, + FORM_OPTGROUP_NO_NAME_FROM_LABEL, + FRAME_NO_NAME, + HEADING_NO_CONTENT, + HEADING_NO_NAME, + IFRAME_NO_NAME_FROM_TITLE, + IMAGE_NO_NAME, + INTERACTIVE_NO_NAME, + MATHML_GLYPH_NO_NAME, + TOOLBAR_NO_NAME, + }, + }, + }, +} = require("resource://devtools/shared/constants.js"); + +/** + * A map from text label issues to annotation component properties. + */ +const ISSUE_TO_ANNOTATION_MAP = { + [AREA_NO_NAME_FROM_ALT]: { + href: A11Y_TEXT_LABEL_LINKS.AREA_NO_NAME_FROM_ALT, + l10nId: "accessibility-text-label-issue-area", + args: { + get code() { + return ReactDOM.code({}, "alt"); + }, + // Note: there is no way right now to use custom elements in privileged + // content. We have to use something like
since we can't provide + // three args with the same name. + get div() { + return ReactDOM.code({}, "area"); + }, + // Note: there is no way right now to use custom elements in privileged + // content. We have to use something like since we can't provide + // three args with the same name. + get span() { + return ReactDOM.code({}, "href"); + }, + }, + }, + [DIALOG_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.DIALOG_NO_NAME, + l10nId: "accessibility-text-label-issue-dialog", + }, + [DOCUMENT_NO_TITLE]: { + href: A11Y_TEXT_LABEL_LINKS.DOCUMENT_NO_TITLE, + l10nId: "accessibility-text-label-issue-document-title", + args: { + get code() { + return ReactDOM.code({}, "title"); + }, + }, + }, + [EMBED_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.EMBED_NO_NAME, + l10nId: "accessibility-text-label-issue-embed", + }, + [FIGURE_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.FIGURE_NO_NAME, + l10nId: "accessibility-text-label-issue-figure", + }, + [FORM_FIELDSET_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.FORM_FIELDSET_NO_NAME, + l10nId: "accessibility-text-label-issue-fieldset", + args: { + get code() { + return ReactDOM.code({}, "fieldset"); + }, + }, + }, + [FORM_FIELDSET_NO_NAME_FROM_LEGEND]: { + href: A11Y_TEXT_LABEL_LINKS.FORM_FIELDSET_NO_NAME_FROM_LEGEND, + l10nId: "accessibility-text-label-issue-fieldset-legend2", + args: { + get code() { + return ReactDOM.code({}, "legend"); + }, + // Note: there is no way right now to use custom elements in privileged + // content. We have to use something like since we can't provide + // two args with the same name. + get span() { + return ReactDOM.code({}, "fieldset"); + }, + }, + }, + [FORM_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.FORM_NO_NAME, + l10nId: "accessibility-text-label-issue-form", + }, + [FORM_NO_VISIBLE_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.FORM_NO_VISIBLE_NAME, + l10nId: "accessibility-text-label-issue-form-visible", + }, + [FORM_OPTGROUP_NO_NAME_FROM_LABEL]: { + href: A11Y_TEXT_LABEL_LINKS.FORM_OPTGROUP_NO_NAME_FROM_LABEL, + l10nId: "accessibility-text-label-issue-optgroup-label2", + args: { + get code() { + return ReactDOM.code({}, "label"); + }, + // Note: there is no way right now to use custom elements in privileged + // content. We have to use something like since we can't provide + // two args with the same name. + get span() { + return ReactDOM.code({}, "optgroup"); + }, + }, + }, + [FRAME_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.FRAME_NO_NAME, + l10nId: "accessibility-text-label-issue-frame", + args: { + get code() { + return ReactDOM.code({}, "frame"); + }, + }, + }, + [HEADING_NO_CONTENT]: { + href: A11Y_TEXT_LABEL_LINKS.HEADING_NO_CONTENT, + l10nId: "accessibility-text-label-issue-heading-content", + }, + [HEADING_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.HEADING_NO_NAME, + l10nId: "accessibility-text-label-issue-heading", + }, + [IFRAME_NO_NAME_FROM_TITLE]: { + href: A11Y_TEXT_LABEL_LINKS.IFRAME_NO_NAME_FROM_TITLE, + l10nId: "accessibility-text-label-issue-iframe", + args: { + get code() { + return ReactDOM.code({}, "title"); + }, + // Note: there is no way right now to use custom elements in privileged + // content. We have to use something like since we can't provide + // two args with the same name. + get span() { + return ReactDOM.code({}, "iframe"); + }, + }, + }, + [IMAGE_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.IMAGE_NO_NAME, + l10nId: "accessibility-text-label-issue-image", + }, + [INTERACTIVE_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.INTERACTIVE_NO_NAME, + l10nId: "accessibility-text-label-issue-interactive", + }, + [MATHML_GLYPH_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.MATHML_GLYPH_NO_NAME, + l10nId: "accessibility-text-label-issue-glyph", + args: { + get code() { + return ReactDOM.code({}, "alt"); + }, + // Note: there is no way right now to use custom elements in privileged + // content. We have to use something like since we can't provide + // two args with the same name. + get span() { + return ReactDOM.code({}, "mglyph"); + }, + }, + }, + [TOOLBAR_NO_NAME]: { + href: A11Y_TEXT_LABEL_LINKS.TOOLBAR_NO_NAME, + l10nId: "accessibility-text-label-issue-toolbar", + }, +}; + +/** + * Component for rendering a check for text label accessibliity check failures, + * warnings and best practices suggestions association with a given + * accessibility object in the accessibility tree. + */ +class TextLabelCheck extends PureComponent { + static get propTypes() { + return { + issue: PropTypes.string.isRequired, + score: PropTypes.string.isRequired, + }; + } + + render() { + return Check({ + ...this.props, + getAnnotation: issue => ISSUE_TO_ANNOTATION_MAP[issue], + id: "accessibility-text-label-header", + }); + } +} + +module.exports = TextLabelCheck; diff --git a/devtools/client/accessibility/components/Toolbar.js b/devtools/client/accessibility/components/Toolbar.js new file mode 100644 index 0000000000..b5f27485ed --- /dev/null +++ b/devtools/client/accessibility/components/Toolbar.js @@ -0,0 +1,74 @@ +/* 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"; + +// React +const { + createFactory, +} = require("resource://devtools/client/shared/vendor/react.js"); +const { + div, +} = require("resource://devtools/client/shared/vendor/react-dom-factories.js"); +const AccessibilityTreeFilter = createFactory( + require("resource://devtools/client/accessibility/components/AccessibilityTreeFilter.js") +); +const AccessibilityPrefs = createFactory( + require("resource://devtools/client/accessibility/components/AccessibilityPrefs.js") +); +loader.lazyGetter(this, "SimulationMenuButton", function () { + return createFactory( + require("resource://devtools/client/accessibility/components/SimulationMenuButton.js") + ); +}); +const DisplayTabbingOrder = createFactory( + require("resource://devtools/client/accessibility/components/DisplayTabbingOrder.js") +); + +const { + connect, +} = require("resource://devtools/client/shared/vendor/react-redux.js"); + +function Toolbar({ audit, simulate, supportsTabbingOrder, toolboxDoc }) { + const optionalSimulationSection = simulate + ? [ + div({ + role: "separator", + className: "devtools-separator", + }), + SimulationMenuButton({ simulate, toolboxDoc }), + ] + : []; + const optionalDisplayTabbingOrderSection = supportsTabbingOrder + ? [ + div({ + role: "separator", + className: "devtools-separator", + }), + DisplayTabbingOrder(), + ] + : []; + + return div( + { + className: "devtools-toolbar", + role: "toolbar", + }, + AccessibilityTreeFilter({ audit, toolboxDoc }), + // Simulation section is shown if webrender is enabled + ...optionalSimulationSection, + ...optionalDisplayTabbingOrderSection, + AccessibilityPrefs({ toolboxDoc }) + ); +} + +const mapStateToProps = ({ + ui: { + supports: { tabbingOrder }, + }, +}) => ({ + supportsTabbingOrder: tabbingOrder, +}); + +// Exports from this module +exports.Toolbar = connect(mapStateToProps)(Toolbar); diff --git a/devtools/client/accessibility/components/moz.build b/devtools/client/accessibility/components/moz.build new file mode 100644 index 0000000000..23e01d42c6 --- /dev/null +++ b/devtools/client/accessibility/components/moz.build @@ -0,0 +1,33 @@ +# 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/. + +DevToolsModules( + "AccessibilityPrefs.js", + "AccessibilityRow.js", + "AccessibilityRowValue.js", + "AccessibilityTree.js", + "AccessibilityTreeFilter.js", + "Accessible.js", + "AuditController.js", + "AuditFilter.js", + "AuditProgressOverlay.js", + "Badge.js", + "Badges.js", + "Button.js", + "Check.js", + "Checks.js", + "ColorContrastAccessibility.js", + "ContrastBadge.js", + "Description.js", + "DisplayTabbingOrder.js", + "KeyboardBadge.js", + "KeyboardCheck.js", + "LearnMoreLink.js", + "MainFrame.js", + "RightSidebar.js", + "SimulationMenuButton.js", + "TextLabelBadge.js", + "TextLabelCheck.js", + "Toolbar.js", +) diff --git a/devtools/client/accessibility/constants.js b/devtools/client/accessibility/constants.js new file mode 100644 index 0000000000..192c5eaf8c --- /dev/null +++ b/devtools/client/accessibility/constants.js @@ -0,0 +1,197 @@ +/* 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 { + accessibility: { + AUDIT_TYPE, + ISSUE_TYPE: { + [AUDIT_TYPE.KEYBOARD]: { + FOCUSABLE_NO_SEMANTICS, + FOCUSABLE_POSITIVE_TABINDEX, + INTERACTIVE_NO_ACTION, + INTERACTIVE_NOT_FOCUSABLE, + MOUSE_INTERACTIVE_ONLY, + NO_FOCUS_VISIBLE, + }, + [AUDIT_TYPE.TEXT_LABEL]: { + AREA_NO_NAME_FROM_ALT, + DIALOG_NO_NAME, + DOCUMENT_NO_TITLE, + EMBED_NO_NAME, + FIGURE_NO_NAME, + FORM_FIELDSET_NO_NAME, + FORM_FIELDSET_NO_NAME_FROM_LEGEND, + FORM_NO_NAME, + FORM_NO_VISIBLE_NAME, + FORM_OPTGROUP_NO_NAME_FROM_LABEL, + FRAME_NO_NAME, + HEADING_NO_CONTENT, + HEADING_NO_NAME, + IFRAME_NO_NAME_FROM_TITLE, + IMAGE_NO_NAME, + INTERACTIVE_NO_NAME, + MATHML_GLYPH_NO_NAME, + TOOLBAR_NO_NAME, + }, + }, + }, +} = require("resource://devtools/shared/constants.js"); + +// Used in accessible component for properties tree rendering. +exports.TREE_ROW_HEIGHT = 21; + +// Initial sidebar width. +exports.SIDEBAR_WIDTH = "350px"; + +// When value is updated either in the tree or sidebar. +exports.VALUE_FLASHING_DURATION = 500; +// When new row is selected, flash highlighter. +exports.VALUE_HIGHLIGHT_DURATION = 1000; + +// If the panel width is smaller than given amount of pixels, +// the sidebar automatically switches from 'landscape' to 'portrait' mode. +exports.PORTRAIT_MODE_WIDTH = 700; + +// Names for Redux actions. +exports.FETCH_CHILDREN = "FETCH_CHILDREN"; +exports.UPDATE_DETAILS = "UPDATE_DETAILS"; +exports.RESET = "RESET"; +exports.SELECT = "SELECT"; +exports.HIGHLIGHT = "HIGHLIGHT"; +exports.UNHIGHLIGHT = "UNHIGHLIGHT"; +exports.ENABLE = "ENABLE"; +exports.UPDATE_CAN_BE_DISABLED = "UPDATE_CAN_BE_DISABLED"; +exports.UPDATE_CAN_BE_ENABLED = "UPDATE_CAN_BE_ENABLED"; +exports.UPDATE_PREF = "UPDATE_PREF"; +exports.FILTER_TOGGLE = "FILTER_TOGGLE"; +exports.AUDIT = "AUDIT"; +exports.AUDITING = "AUDITING"; +exports.AUDIT_PROGRESS = "AUDIT_PROGRESS"; +exports.SIMULATE = "SIMULATE"; +exports.UPDATE_DISPLAY_TABBING_ORDER = "UPDATE_DISPLAY_TABBING_ORDER"; + +// List of filters for accessibility checks. +exports.FILTERS = { + NONE: "NONE", + ALL: "ALL", + [AUDIT_TYPE.CONTRAST]: "CONTRAST", + [AUDIT_TYPE.KEYBOARD]: "KEYBOARD", + [AUDIT_TYPE.TEXT_LABEL]: "TEXT_LABEL", +}; + +// Ordered accessible properties to be displayed by the accessible component. +exports.ORDERED_PROPS = [ + "name", + "role", + "actions", + "value", + "DOMNode", + "description", + "keyboardShortcut", + "childCount", + "indexInParent", + "states", + "relations", + "attributes", +]; + +// Accessible events (emitted by accessible front) that the accessible component +// listens to for a current accessible. +exports.ACCESSIBLE_EVENTS = [ + "actions-change", + "attributes-change", + "description-change", + "name-change", + "reorder", + "shortcut-change", + "states-change", + "text-change", + "value-change", + "index-in-parent-change", +]; + +// Telemetry name constants. +exports.A11Y_SERVICE_DURATION = + "DEVTOOLS_ACCESSIBILITY_SERVICE_TIME_ACTIVE_SECONDS"; + +// URL constants +exports.A11Y_LEARN_MORE_LINK = + "https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/"; +exports.A11Y_CONTRAST_LEARN_MORE_LINK = + "https://developer.mozilla.org/docs/Web/Accessibility/Understanding_WCAG/Perceivable/" + + "Color_contrast?utm_source=devtools&utm_medium=a11y-panel-checks-color-contrast"; +exports.A11Y_SIMULATION_DOCUMENTATION_LINK = + "https://firefox-source-docs.mozilla.org/devtools-user/accessibility_inspector/simulation/"; + +const A11Y_TEXT_LABEL_LINK_BASE = + "https://developer.mozilla.org/docs/Web/Accessibility/Understanding_WCAG/Text_labels_and_names" + + "?utm_source=devtools&utm_medium=a11y-panel-checks-text-label"; + +const A11Y_TEXT_LABEL_LINK_IDS = { + [AREA_NO_NAME_FROM_ALT]: + "Use_alt_attribute_to_label_area_elements_that_have_the_href_attribute", + [DIALOG_NO_NAME]: "Dialogs_should_be_labeled", + [DOCUMENT_NO_TITLE]: "Documents_must_have_a_title", + [EMBED_NO_NAME]: "Embedded_content_must_be_labeled", + [FIGURE_NO_NAME]: "Figures_with_optional_captions_should_be_labeled", + [FORM_FIELDSET_NO_NAME]: "Fieldset_elements_must_be_labeled", + [FORM_FIELDSET_NO_NAME_FROM_LEGEND]: "Use_a_legend_to_label_a_fieldset", + [FORM_NO_NAME]: "Form_elements_must_be_labeled", + [FORM_NO_VISIBLE_NAME]: "Form_elements_should_have_a_visible_text_label", + [FORM_OPTGROUP_NO_NAME_FROM_LABEL]: + "Use_label_attribute_on_optgroup_elements", + [FRAME_NO_NAME]: "Frame_elements_must_be_labeled", + [HEADING_NO_NAME]: "Headings_must_be_labeled", + [HEADING_NO_CONTENT]: "Headings_should_have_visible_text_content", + [IFRAME_NO_NAME_FROM_TITLE]: "Use_title_attribute_to_describe_iframe_content", + [IMAGE_NO_NAME]: "Content_with_images_must_be_labeled", + [INTERACTIVE_NO_NAME]: "Interactive_elements_must_be_labeled", + [MATHML_GLYPH_NO_NAME]: "Use_alt_attribute_to_label_mglyph_elements", + [TOOLBAR_NO_NAME]: + "Toolbars_must_be_labeled_when_there_is_more_than_one_toolbar", +}; + +const A11Y_TEXT_LABEL_LINKS = {}; +for (const key in A11Y_TEXT_LABEL_LINK_IDS) { + A11Y_TEXT_LABEL_LINKS[ + key + ] = `${A11Y_TEXT_LABEL_LINK_BASE}#${A11Y_TEXT_LABEL_LINK_IDS[key]}`; +} +exports.A11Y_TEXT_LABEL_LINKS = A11Y_TEXT_LABEL_LINKS; + +const A11Y_KEYBOARD_LINK_BASE = + "https://developer.mozilla.org/docs/Web/Accessibility/Understanding_WCAG/Keyboard" + + "?utm_source=devtools&utm_medium=a11y-panel-checks-keyboard"; + +const A11Y_KEYBOARD_LINK_IDS = { + [FOCUSABLE_NO_SEMANTICS]: + "Focusable_elements_should_have_interactive_semantics", + [FOCUSABLE_POSITIVE_TABINDEX]: + "Avoid_using_tabindex_attribute_greater_than_zero", + [INTERACTIVE_NO_ACTION]: + "Interactive_elements_must_be_able_to_be_activated_using_a_keyboard", + [INTERACTIVE_NOT_FOCUSABLE]: "Interactive_elements_must_be_focusable", + [MOUSE_INTERACTIVE_ONLY]: + "Clickable_elements_must_be_focusable_and_should_have_interactive_semantics", + [NO_FOCUS_VISIBLE]: "Focusable_element_must_have_focus_styling", +}; + +const A11Y_KEYBOARD_LINKS = {}; +for (const key in A11Y_KEYBOARD_LINK_IDS) { + A11Y_KEYBOARD_LINKS[ + key + ] = `${A11Y_KEYBOARD_LINK_BASE}#${A11Y_KEYBOARD_LINK_IDS[key]}`; +} +exports.A11Y_KEYBOARD_LINKS = A11Y_KEYBOARD_LINKS; + +// Lists of preference names and keys. +const PREFS = { + SCROLL_INTO_VIEW: "SCROLL_INTO_VIEW", +}; + +exports.PREFS = PREFS; +exports.PREF_KEYS = { + [PREFS.SCROLL_INTO_VIEW]: "devtools.accessibility.scroll-into-view", +}; diff --git a/devtools/client/accessibility/index.html b/devtools/client/accessibility/index.html new file mode 100644 index 0000000000..74e5057769 --- /dev/null +++ b/devtools/client/accessibility/index.html @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/devtools/client/accessibility/main.js b/devtools/client/accessibility/main.js new file mode 100644 index 0000000000..c658d05825 --- /dev/null +++ b/devtools/client/accessibility/main.js @@ -0,0 +1,17 @@ +/* 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 { BrowserLoader } = ChromeUtils.import( + "resource://devtools/shared/loader/browser-loader.js" +); + +// Module Loader +const require = BrowserLoader({ + baseURI: "resource://devtools/client/accessibility/", + window, +}).require; + +// Load accessibility panel content +require("resource://devtools/client/accessibility/accessibility-view.js"); diff --git a/devtools/client/accessibility/moz.build b/devtools/client/accessibility/moz.build new file mode 100644 index 0000000000..26e265b58c --- /dev/null +++ b/devtools/client/accessibility/moz.build @@ -0,0 +1,20 @@ +# 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/. + +MOCHITEST_CHROME_MANIFESTS += ["test/chrome/chrome.toml"] +BROWSER_CHROME_MANIFESTS += ["test/browser/browser.toml"] + +DIRS += ["actions", "components", "reducers", "utils"] + +DevToolsModules( + "accessibility-proxy.js", + "accessibility-view.js", + "constants.js", + "panel.js", + "picker.js", + "provider.js", +) + +with Files("**"): + BUG_COMPONENT = ("DevTools", "Accessibility Tools") diff --git a/devtools/client/accessibility/panel.js b/devtools/client/accessibility/panel.js new file mode 100644 index 0000000000..02c6c8f415 --- /dev/null +++ b/devtools/client/accessibility/panel.js @@ -0,0 +1,350 @@ +/* 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 EventEmitter = require("resource://devtools/shared/event-emitter.js"); + +loader.lazyRequireGetter( + this, + "AccessibilityProxy", + "resource://devtools/client/accessibility/accessibility-proxy.js", + true +); +loader.lazyRequireGetter( + this, + "Picker", + "resource://devtools/client/accessibility/picker.js", + true +); +const { + A11Y_SERVICE_DURATION, +} = require("resource://devtools/client/accessibility/constants.js"); + +// The panel's window global is an EventEmitter firing the following events: +const EVENTS = { + // When the accessibility inspector has a new accessible front selected. + NEW_ACCESSIBLE_FRONT_SELECTED: "Accessibility:NewAccessibleFrontSelected", + // When the accessibility inspector has a new accessible front highlighted. + NEW_ACCESSIBLE_FRONT_HIGHLIGHTED: + "Accessibility:NewAccessibleFrontHighlighted", + // When the accessibility inspector has a new accessible front inspected. + NEW_ACCESSIBLE_FRONT_INSPECTED: "Accessibility:NewAccessibleFrontInspected", + // When the accessibility inspector is updated. + ACCESSIBILITY_INSPECTOR_UPDATED: + "Accessibility:AccessibilityInspectorUpdated", + // When accessibility panel UI is initialized (rendered). + INITIALIZED: "Accessibility:Initialized", + // When accessibile object properties are updated in the panel sidebar for a + // new accessible object. + PROPERTIES_UPDATED: "Accessibility:PropertiesUpdated", +}; + +/** + * This object represents Accessibility panel. It's responsibility is to + * render Accessibility Tree of the current debugger target and the sidebar that + * displays current relevant accessible details. + */ +function AccessibilityPanel(iframeWindow, toolbox, commands) { + this.panelWin = iframeWindow; + this._toolbox = toolbox; + this._commands = commands; + + this.onPanelVisibilityChange = this.onPanelVisibilityChange.bind(this); + this.onNewAccessibleFrontSelected = + this.onNewAccessibleFrontSelected.bind(this); + this.onAccessibilityInspectorUpdated = + this.onAccessibilityInspectorUpdated.bind(this); + this.updateA11YServiceDurationTimer = + this.updateA11YServiceDurationTimer.bind(this); + this.forceUpdatePickerButton = this.forceUpdatePickerButton.bind(this); + this.onLifecycleEvent = this.onLifecycleEvent.bind(this); + + EventEmitter.decorate(this); +} + +AccessibilityPanel.prototype = { + /** + * Open is effectively an asynchronous constructor. + */ + async open() { + if (this._opening) { + await this._opening; + return this._opening; + } + + let resolver; + this._opening = new Promise(resolve => { + resolver = resolve; + }); + + this._telemetry = this._toolbox.telemetry; + this.panelWin.gTelemetry = this._telemetry; + + this._toolbox.on("select", this.onPanelVisibilityChange); + + this.panelWin.EVENTS = EVENTS; + EventEmitter.decorate(this.panelWin); + this.panelWin.on( + EVENTS.NEW_ACCESSIBLE_FRONT_SELECTED, + this.onNewAccessibleFrontSelected + ); + this.panelWin.on( + EVENTS.ACCESSIBILITY_INSPECTOR_UPDATED, + this.onAccessibilityInspectorUpdated + ); + + this.accessibilityProxy = new AccessibilityProxy(this._commands, this); + await this.accessibilityProxy.initialize(); + + // Enable accessibility service if necessary. + if ( + this.accessibilityProxy.canBeEnabled && + !this.accessibilityProxy.enabled + ) { + await this.accessibilityProxy.enableAccessibility(); + } + + this.picker = new Picker(this); + this.fluentBundles = await this.createFluentBundles(); + + this.updateA11YServiceDurationTimer(); + this.accessibilityProxy.startListeningForLifecycleEvents({ + init: this.onLifecycleEvent, + shutdown: this.onLifecycleEvent, + }); + + // Force refresh to render the UI and wait for the INITIALIZED event. + const onInitialized = this.panelWin.once(EVENTS.INITIALIZED); + this.shouldRefresh = true; + this.refresh(); + await onInitialized; + + resolver(this); + return this._opening; + }, + + /** + * Retrieve message contexts for the current locales, and return them as an + * array of FluentBundles elements. + */ + async createFluentBundles() { + const locales = Services.locale.appLocalesAsBCP47; + const generator = L10nRegistry.getInstance().generateBundles(locales, [ + "devtools/client/accessibility.ftl", + ]); + + // Return value of generateBundles is a generator and should be converted to + // a sync iterable before using it with React. + const contexts = []; + for await (const message of generator) { + contexts.push(message); + } + + return contexts; + }, + + onLifecycleEvent() { + this.updateA11YServiceDurationTimer(); + this.forceUpdatePickerButton(); + }, + + onNewAccessibleFrontSelected(selected) { + this.emit("new-accessible-front-selected", selected); + }, + + onAccessibilityInspectorUpdated() { + this.emit("accessibility-inspector-updated"); + }, + + /** + * Make sure the panel is refreshed when the page is reloaded. The panel is + * refreshed immediatelly if it's currently selected or lazily when the user + * actually selects it. + */ + async forceRefresh() { + this.shouldRefresh = true; + await this._opening; + + await this.accessibilityProxy.accessibilityFrontGetPromise; + const onUpdated = this.panelWin.once(EVENTS.INITIALIZED); + this.refresh(); + await onUpdated; + + this.emit("reloaded"); + }, + + /** + * Make sure the panel is refreshed (if needed) when it's selected. + */ + onPanelVisibilityChange() { + this._opening.then(() => this.refresh()); + }, + + refresh() { + this.cancelPicker(); + + if (!this.isVisible) { + // Do not refresh if the panel isn't visible. + return; + } + + // Do not refresh if it isn't necessary. + if (!this.shouldRefresh) { + return; + } + // Alright reset the flag we are about to refresh the panel. + this.shouldRefresh = false; + const { + supports, + getAccessibilityTreeRoot, + startListeningForAccessibilityEvents, + stopListeningForAccessibilityEvents, + audit, + simulate, + toggleDisplayTabbingOrder, + enableAccessibility, + resetAccessiblity, + startListeningForLifecycleEvents, + stopListeningForLifecycleEvents, + startListeningForParentLifecycleEvents, + stopListeningForParentLifecycleEvents, + highlightAccessible, + unhighlightAccessible, + } = this.accessibilityProxy; + this.postContentMessage("initialize", { + fluentBundles: this.fluentBundles, + toolbox: this._toolbox, + supports, + getAccessibilityTreeRoot, + startListeningForAccessibilityEvents, + stopListeningForAccessibilityEvents, + audit, + simulate, + toggleDisplayTabbingOrder, + enableAccessibility, + resetAccessiblity, + startListeningForLifecycleEvents, + stopListeningForLifecycleEvents, + startListeningForParentLifecycleEvents, + stopListeningForParentLifecycleEvents, + highlightAccessible, + unhighlightAccessible, + }); + }, + + updateA11YServiceDurationTimer() { + if (this.accessibilityProxy.enabled) { + this._telemetry.start(A11Y_SERVICE_DURATION, this); + } else { + this._telemetry.finish(A11Y_SERVICE_DURATION, this, true); + } + }, + + selectAccessible(accessibleFront) { + this.postContentMessage("selectAccessible", accessibleFront); + }, + + selectAccessibleForNode(nodeFront, reason) { + if (reason) { + this._telemetry.keyedScalarAdd( + "devtools.accessibility.select_accessible_for_node", + reason, + 1 + ); + } + + this.postContentMessage("selectNodeAccessible", nodeFront); + }, + + highlightAccessible(accessibleFront) { + this.postContentMessage("highlightAccessible", accessibleFront); + }, + + postContentMessage(type, ...args) { + const event = new this.panelWin.MessageEvent("devtools/chrome/message", { + bubbles: true, + cancelable: true, + data: { type, args }, + }); + + this.panelWin.dispatchEvent(event); + }, + + updatePickerButton() { + this.picker && this.picker.updateButton(); + }, + + forceUpdatePickerButton() { + // Only update picker button when the panel is selected. + if (!this.isVisible) { + return; + } + + this.updatePickerButton(); + // Calling setToolboxButtons to make sure toolbar is forced to re-render. + this._toolbox.component.setToolboxButtons(this._toolbox.toolbarButtons); + }, + + togglePicker(focus) { + this.picker && this.picker.toggle(); + }, + + cancelPicker() { + this.picker && this.picker.cancel(); + }, + + stopPicker() { + this.picker && this.picker.stop(); + }, + + /** + * Return true if the Accessibility panel is currently selected. + */ + get isVisible() { + return this._toolbox.currentToolId === "accessibility"; + }, + + destroy() { + if (this._destroyed) { + return; + } + this._destroyed = true; + + this.postContentMessage("destroy"); + + if (this.accessibilityProxy) { + this.accessibilityProxy.stopListeningForLifecycleEvents({ + init: this.onLifecycleEvent, + shutdown: this.onLifecycleEvent, + }); + this.accessibilityProxy.destroy(); + this.accessibilityProxy = null; + } + + this._toolbox.off("select", this.onPanelVisibilityChange); + + this.panelWin.off( + EVENTS.NEW_ACCESSIBLE_FRONT_SELECTED, + this.onNewAccessibleFrontSelected + ); + this.panelWin.off( + EVENTS.ACCESSIBILITY_INSPECTOR_UPDATED, + this.onAccessibilityInspectorUpdated + ); + + // Older versions of devtools server do not support picker functionality. + if (this.picker) { + this.picker.release(); + this.picker = null; + } + + this._telemetry = null; + this.panelWin.gTelemetry = null; + + this.emit("destroyed"); + }, +}; + +// Exports from this module +exports.AccessibilityPanel = AccessibilityPanel; diff --git a/devtools/client/accessibility/picker.js b/devtools/client/accessibility/picker.js new file mode 100644 index 0000000000..49ba2b5bfc --- /dev/null +++ b/devtools/client/accessibility/picker.js @@ -0,0 +1,189 @@ +/* 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 { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +class Picker { + constructor(panel) { + this._panel = panel; + + this.isPicking = false; + + this.onPickerAccessibleHovered = this.onPickerAccessibleHovered.bind(this); + this.onPickerAccessiblePicked = this.onPickerAccessiblePicked.bind(this); + this.onPickerAccessiblePreviewed = + this.onPickerAccessiblePreviewed.bind(this); + this.onPickerAccessibleCanceled = + this.onPickerAccessibleCanceled.bind(this); + } + + get toolbox() { + return this._panel._toolbox; + } + + get accessibilityProxy() { + return this._panel.accessibilityProxy; + } + + get pickerButton() { + return this.toolbox.pickerButton; + } + + get _telemetry() { + return this._panel._telemetry; + } + + release() { + this._panel = null; + } + + emit(event, data) { + this.toolbox.emit(event, data); + } + + /** + * Select accessible object in the tree. + * @param {Object} accessible + * Accessiblle object to be selected in the inspector tree. + */ + select(accessible) { + this._panel.selectAccessible(accessible); + } + + /** + * Highlight accessible object in the tree. + * @param {Object} accessible + * Accessiblle object to be selected in the inspector tree. + */ + highlight(accessible) { + this._panel.highlightAccessible(accessible); + } + + getStr(key) { + return L10N.getStr(key); + } + + /** + * Override the default presentation of the picker button in toolbox's top + * level toolbar. + */ + updateButton() { + this.pickerButton.description = this.getStr("accessibility.pick"); + this.pickerButton.className = "accessibility"; + this.pickerButton.disabled = !this.accessibilityProxy.enabled; + if (!this.accessibilityProxy.enabled && this.isPicking) { + this.cancel(); + } + } + + /** + * Handle an event when a new accessible object is hovered over. + * @param {Object} accessible + * newly hovered accessible object + */ + onPickerAccessibleHovered(accessible) { + if (accessible) { + this.emit("picker-accessible-hovered", accessible); + this.highlight(accessible); + } + } + + /** + * Handle an event when a new accessible is picked by the user. + * @param {Object} accessible + * newly picked accessible object + */ + onPickerAccessiblePicked(accessible) { + if (accessible) { + this.select(accessible); + } + this.stop(); + } + + /** + * Handle an event when a new accessible is previewed by the user. + * @param {Object} accessible + * newly previewed accessible object + */ + onPickerAccessiblePreviewed(accessible) { + if (accessible) { + this.select(accessible); + } + } + + /** + * Handle an event when picking is cancelled by the user.s + */ + onPickerAccessibleCanceled() { + this.cancel(); + this.emit("picker-accessible-canceled"); + } + + /** + * Cancel picking. + */ + async cancel() { + await this.stop(); + } + + /** + * Stop picking. + */ + async stop() { + if (!this.isPicking) { + return; + } + + this.isPicking = false; + this.pickerButton.isChecked = false; + + await this.accessibilityProxy.cancelPick(); + this._telemetry.toolClosed("accessibility_picker", this); + this.emit("picker-stopped"); + } + + /** + * Start picking. + * @param {Boolean} doFocus + * If true, move keyboard focus into content. + */ + async start(doFocus = true) { + if (this.isPicking) { + return; + } + + this.isPicking = true; + this.pickerButton.isChecked = true; + + await this.accessibilityProxy.pick( + doFocus, + this.onPickerAccessibleHovered, + this.onPickerAccessiblePicked, + this.onPickerAccessiblePreviewed, + this.onPickerAccessibleCanceled + ); + + this._telemetry.toolOpened("accessibility_picker", this); + this.emit("picker-started"); + } + + /** + * Toggle between starting and canceling the picker. + * @param {Boolean} doFocus + * If true, move keyboard focus into content. + */ + toggle(doFocus) { + if (this.isPicking) { + return this.cancel(); + } + + return this.start(doFocus); + } +} + +exports.Picker = Picker; diff --git a/devtools/client/accessibility/provider.js b/devtools/client/accessibility/provider.js new file mode 100644 index 0000000000..f0fc05c628 --- /dev/null +++ b/devtools/client/accessibility/provider.js @@ -0,0 +1,112 @@ +/* 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 { + fetchChildren, +} = require("resource://devtools/client/accessibility/actions/accessibles.js"); + +/** + * Data provider that is responsible for mapping of an accessibles cache to the + * data format that is supported by the TreeView component. + * @param {Map} accessibles accessibles object cache + * @param {Function} dispatch react dispatch function that triggers a redux + * action. + */ + +class Provider { + constructor(accessibles, filtered, dispatch) { + this.accessibles = accessibles; + this.filtered = filtered; + this.dispatch = dispatch; + } + + /** + * Get accessible's cached children if available, if not fetch them from + * backend. + * @param {Object} accessible accessible object whose children to get. + * @returns {Array} arraof of accessible children. + */ + getChildren(accessible) { + if (!accessible || !accessible.actorID || accessible.childCount === 0) { + return []; + } + + const obj = this.accessibles.get(accessible.actorID); + if (!obj || !obj.children) { + return this.dispatch(fetchChildren(accessible)); + } + + return obj.children; + } + + /** + * Return a flag indicating if an accessible object has any children. + * @param {Object} accessible accessible object whose children to get. + * @returns {Boolean} idicator of whether accessible object has children. + */ + hasChildren(accessible) { + return accessible.childCount > 0; + } + + /** + * Get a value for an accessible object. Used to render the second (value) + * column of the accessible tree. Corresponds to an accesible object name, if + * available. + * @param {Object} accessible accessible object + * @returns {String} accessible object value. + */ + getValue(accessible) { + return accessible.name || ""; + } + + /** + * Get a label for an accessible object. Used to render the first column of + * the accessible tree. Corresponds to an accessible object role. + * @param {Object} accessible accessible object + * @returns {String} accessible object label. + */ + getLabel(accessible) { + return accessible.role; + } + + /** + * Get a unique key for an accessible object. Corresponds to an accessible + * front's actorID. + * @param {Object} accessible accessible object + * @returns {String} a key for an accessible object. + */ + getKey(accessible) { + return accessible.actorID; + } + + /** + * Get a type of an accesible object. Corresponds to the type of an accessible + * front. + * @param {Object} accessible accessible object + * @returns {String} accessible object type + */ + getType(accessible) { + return accessible.typeName; + } + + /** + * Get the depth of the accesible object in the accessibility tree. When the + * tree is filtered it is flattened and the level is set to 0. Otherwise use + * internal TreeView level. + * + * @param {Object} accessible + * accessible object + * @param {Number} defaultLevel + * default level provided by the TreeView component. + * + * @returns {null|Number} + * depth level of the accessible object. + */ + getLevel(accessible, defaultLevel) { + return this.filtered ? 0 : defaultLevel; + } +} + +exports.Provider = Provider; diff --git a/devtools/client/accessibility/reducers/accessibles.js b/devtools/client/accessibility/reducers/accessibles.js new file mode 100644 index 0000000000..908d1b734d --- /dev/null +++ b/devtools/client/accessibility/reducers/accessibles.js @@ -0,0 +1,158 @@ +/* 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 { + AUDIT, + FETCH_CHILDREN, + HIGHLIGHT, + RESET, + SELECT, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Initial state definition + */ +function getInitialState() { + return new Map(); +} + +/** + * Maintain a cache of received accessibles responses from the backend. + */ +function accessibles(state = getInitialState(), action) { + switch (action.type) { + case FETCH_CHILDREN: + return onReceiveChildren(state, action); + case HIGHLIGHT: + case SELECT: + return onReceiveAncestry(state, action); + case AUDIT: + return onAudit(state, action); + case RESET: + return getInitialState(); + default: + return state; + } +} + +function getActorID(accessible) { + return accessible.actorID || accessible._form?.actor; +} + +/** + * If accessible is cached recursively remove all its children and remove itself + * from cache. + * @param {Map} cache Previous state maintaining a cache of previously + * fetched accessibles. + * @param {Object} accessible Accessible object to remove from cache. + */ +function cleanupChild(cache, accessible) { + const actorID = getActorID(accessible); + const cached = cache.get(actorID); + if (!cached) { + return; + } + + for (const child of cached.children) { + cleanupChild(cache, child); + } + + cache.delete(actorID); +} + +/** + * Determine if accessible in cache is stale. Accessible object is stale if its + * cached children array has the size other than the value of its childCount + * property that updates on accessible actor event. + * @param {Map} cache Previous state maintaining a cache of previously + * fetched accessibles. + * @param {Object} accessible Accessible object to test for staleness. + */ +function staleChildren(cache, accessible) { + const cached = cache.get(getActorID(accessible)); + if (!cached) { + return false; + } + + return cached.children.length !== accessible.childCount; +} + +function updateChildrenCache(cache, accessible, children) { + const actorID = getActorID(accessible); + + if (cache.has(actorID)) { + const cached = cache.get(actorID); + for (const child of cached.children) { + // If exhisting children cache includes an accessible that is not present + // any more or if child accessible is stale remove it and all its children + // from cache. + if (!children.includes(child) || staleChildren(cache, child)) { + cleanupChild(cache, child); + } + } + cached.children = children; + cache.set(actorID, cached); + } else { + cache.set(actorID, { children }); + } + + return cache; +} + +function updateAncestry(cache, ancestry) { + ancestry.forEach(({ accessible, children }) => + updateChildrenCache(cache, accessible, children) + ); + + return cache; +} + +/** + * Handles fetching of accessible children. + * @param {Map} cache Previous state maintaining a cache of previously + * fetched accessibles. + * @param {Object} action Redux action object. + * @return {Object} updated state + */ +function onReceiveChildren(cache, action) { + const { error, accessible, response: children } = action; + if (!error) { + return updateChildrenCache(new Map(cache), accessible, children); + } + + if (!accessible.isDestroyed()) { + console.warn(`Error fetching children: `, error); + return cache; + } + + const newCache = new Map(cache); + cleanupChild(newCache, accessible); + return newCache; +} + +function onReceiveAncestry(cache, action) { + const { error, response: ancestry } = action; + if (error) { + console.warn(`Error fetching ancestry: `, error); + return cache; + } + + return updateAncestry(new Map(cache), ancestry); +} + +function onAudit(cache, action) { + const { error, response: ancestries } = action; + if (error) { + console.warn(`Error performing an audit: `, error); + return cache; + } + + const newCache = new Map(cache); + ancestries.forEach(ancestry => updateAncestry(newCache, ancestry)); + + return newCache; +} + +exports.accessibles = accessibles; diff --git a/devtools/client/accessibility/reducers/audit.js b/devtools/client/accessibility/reducers/audit.js new file mode 100644 index 0000000000..e65251ba64 --- /dev/null +++ b/devtools/client/accessibility/reducers/audit.js @@ -0,0 +1,109 @@ +/* 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 { + accessibility: { AUDIT_TYPE }, +} = require("resource://devtools/shared/constants.js"); +const { + AUDIT, + AUDITING, + AUDIT_PROGRESS, + FILTER_TOGGLE, + FILTERS, + RESET, + SELECT, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Initial state definition + */ +function getInitialState() { + return { + filters: { + [FILTERS.ALL]: false, + [FILTERS.CONTRAST]: false, + [FILTERS.KEYBOARD]: false, + [FILTERS.TEXT_LABEL]: false, + }, + auditing: [], + progress: null, + }; +} + +/** + * State with all filters active. + */ +function allActiveFilters() { + return { + [FILTERS.ALL]: true, + [FILTERS.CONTRAST]: true, + [FILTERS.KEYBOARD]: true, + [FILTERS.TEXT_LABEL]: true, + }; +} + +function audit(state = getInitialState(), action) { + switch (action.type) { + case FILTER_TOGGLE: + const { filter } = action; + let { filters } = state; + const isToggledToActive = !filters[filter]; + + if (filter === FILTERS.NONE) { + filters = getInitialState().filters; + } else if (filter === FILTERS.ALL) { + filters = isToggledToActive + ? allActiveFilters() + : getInitialState().filters; + } else { + filters = { + ...filters, + [filter]: isToggledToActive, + }; + + const allAuditTypesActive = Object.values(AUDIT_TYPE) + .filter(filterKey => filters.hasOwnProperty(filterKey)) + .every(filterKey => filters[filterKey]); + if (isToggledToActive && !filters[FILTERS.ALL] && allAuditTypesActive) { + filters[FILTERS.ALL] = true; + } else if (!isToggledToActive && filters[FILTERS.ALL]) { + filters[FILTERS.ALL] = false; + } + } + + return { + ...state, + filters, + }; + case AUDITING: + const { auditing } = action; + + return { + ...state, + auditing, + }; + case AUDIT: + return { + ...state, + auditing: getInitialState().auditing, + progress: null, + }; + case AUDIT_PROGRESS: + const { progress } = action; + + return { + ...state, + progress, + }; + case SELECT: + case RESET: + return getInitialState(); + default: + return state; + } +} + +exports.audit = audit; diff --git a/devtools/client/accessibility/reducers/details.js b/devtools/client/accessibility/reducers/details.js new file mode 100644 index 0000000000..25a1c42ed2 --- /dev/null +++ b/devtools/client/accessibility/reducers/details.js @@ -0,0 +1,60 @@ +/* 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 { + UPDATE_DETAILS, + RESET, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Initial state definition + */ +function getInitialState() { + return {}; +} + +/** + * Maintain details of a current relevant accessible. + */ +function details(state = getInitialState(), action) { + switch (action.type) { + case UPDATE_DETAILS: + return onUpdateDetails(state, action); + case RESET: + return getInitialState(); + default: + return state; + } +} + +/** + * Handle details update for an accessible object + * @param {Object} state Current accessible object details. + * @param {Object} action Redux action object + * @return {Object} updated state + */ +function onUpdateDetails(state, action) { + const { accessible, response, error } = action; + if (error) { + if (!accessible.isDestroyed()) { + console.warn( + `Error fetching accessible details: `, + accessible.actorID, + error + ); + } + + return getInitialState(); + } + + const [DOMNode, relationObjects, audit] = response; + const relations = {}; + relationObjects.forEach(({ type, targets }) => { + relations[type] = targets.length === 1 ? targets[0] : targets; + }); + return { accessible, DOMNode, relations, audit }; +} + +exports.details = details; diff --git a/devtools/client/accessibility/reducers/index.js b/devtools/client/accessibility/reducers/index.js new file mode 100644 index 0000000000..d9ca8467ff --- /dev/null +++ b/devtools/client/accessibility/reducers/index.js @@ -0,0 +1,28 @@ +/* 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 { + accessibles, +} = require("resource://devtools/client/accessibility/reducers/accessibles.js"); +const { + audit, +} = require("resource://devtools/client/accessibility/reducers/audit.js"); +const { + details, +} = require("resource://devtools/client/accessibility/reducers/details.js"); +const { + simulation, +} = require("resource://devtools/client/accessibility/reducers/simulation.js"); +const { + ui, +} = require("resource://devtools/client/accessibility/reducers/ui.js"); + +exports.reducers = { + accessibles, + audit, + details, + simulation, + ui, +}; diff --git a/devtools/client/accessibility/reducers/moz.build b/devtools/client/accessibility/reducers/moz.build new file mode 100644 index 0000000000..0c7398f397 --- /dev/null +++ b/devtools/client/accessibility/reducers/moz.build @@ -0,0 +1,7 @@ +# 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/. + +DevToolsModules( + "accessibles.js", "audit.js", "details.js", "index.js", "simulation.js", "ui.js" +) diff --git a/devtools/client/accessibility/reducers/simulation.js b/devtools/client/accessibility/reducers/simulation.js new file mode 100644 index 0000000000..1b68331d93 --- /dev/null +++ b/devtools/client/accessibility/reducers/simulation.js @@ -0,0 +1,52 @@ +/* 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 { + accessibility: { SIMULATION_TYPE }, +} = require("resource://devtools/shared/constants.js"); +const { + SIMULATE, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Initial state definition + */ +function getInitialState() { + return { + [SIMULATION_TYPE.ACHROMATOPSIA]: false, + [SIMULATION_TYPE.PROTANOPIA]: false, + [SIMULATION_TYPE.DEUTERANOPIA]: false, + [SIMULATION_TYPE.TRITANOPIA]: false, + [SIMULATION_TYPE.CONTRAST_LOSS]: false, + }; +} + +function simulation(state = getInitialState(), action) { + switch (action.type) { + case SIMULATE: + if (action.error) { + console.warn("Error running simulation", action.error); + return state; + } + + const simTypes = action.simTypes; + + if (simTypes.length === 0) { + return getInitialState(); + } + + const updatedState = getInitialState(); + simTypes.forEach(simType => { + updatedState[simType] = true; + }); + + return updatedState; + default: + return state; + } +} + +exports.simulation = simulation; diff --git a/devtools/client/accessibility/reducers/ui.js b/devtools/client/accessibility/reducers/ui.js new file mode 100644 index 0000000000..828889680c --- /dev/null +++ b/devtools/client/accessibility/reducers/ui.js @@ -0,0 +1,217 @@ +/* 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 { + AUDIT, + ENABLE, + RESET, + SELECT, + HIGHLIGHT, + UNHIGHLIGHT, + UPDATE_CAN_BE_DISABLED, + UPDATE_CAN_BE_ENABLED, + UPDATE_PREF, + UPDATE_DETAILS, + PREF_KEYS, + PREFS, + UPDATE_DISPLAY_TABBING_ORDER, +} = require("resource://devtools/client/accessibility/constants.js"); + +const TreeView = require("resource://devtools/client/shared/components/tree/TreeView.js"); + +/** + * Initial state definition + */ +function getInitialState() { + return { + enabled: false, + canBeDisabled: true, + canBeEnabled: true, + selected: null, + highlighted: null, + expanded: new Set(), + [PREFS.SCROLL_INTO_VIEW]: Services.prefs.getBoolPref( + PREF_KEYS[PREFS.SCROLL_INTO_VIEW], + false + ), + tabbingOrderDisplayed: false, + supports: {}, + }; +} + +/** + * Maintain ui components of the accessibility panel. + */ +function ui(state = getInitialState(), action) { + switch (action.type) { + case ENABLE: + return onToggle(state, action, true); + case UPDATE_CAN_BE_DISABLED: + return onCanBeDisabledChange(state, action); + case UPDATE_CAN_BE_ENABLED: + return onCanBeEnabledChange(state, action); + case UPDATE_PREF: + return onPrefChange(state, action); + case UPDATE_DETAILS: + return onUpdateDetails(state, action); + case HIGHLIGHT: + return onHighlight(state, action); + case AUDIT: + return onAudit(state, action); + case UNHIGHLIGHT: + return onUnhighlight(state, action); + case SELECT: + return onSelect(state, action); + case RESET: + return onReset(state, action); + case UPDATE_DISPLAY_TABBING_ORDER: + return onUpdateDisplayTabbingOrder(state, action); + default: + return state; + } +} + +function onUpdateDetails(state) { + if (!state.selected) { + return state; + } + + // Clear selected state that should only be set when select action is + // performed. + return Object.assign({}, state, { selected: null }); +} + +function onUnhighlight(state) { + return Object.assign({}, state, { highlighted: null }); +} + +function updateExpandedNodes(expanded, ancestry) { + expanded = new Set(expanded); + const path = ancestry.reduceRight((accPath, { accessible }) => { + accPath = TreeView.subPath(accPath, accessible.actorID); + expanded.add(accPath); + return accPath; + }, ""); + + return { path, expanded }; +} + +function onAudit(state, { response: ancestries, error }) { + if (error) { + console.warn("Error running audit", error); + return state; + } + + let expanded = new Set(state.expanded); + for (const ancestry of ancestries) { + ({ expanded } = updateExpandedNodes(expanded, ancestry)); + } + + return { + ...state, + expanded, + }; +} + +function onHighlight(state, { accessible, response: ancestry, error }) { + if (error) { + console.warn("Error fetching ancestry", error); + return state; + } + + const { expanded } = updateExpandedNodes(state.expanded, ancestry); + return Object.assign({}, state, { expanded, highlighted: accessible }); +} + +function onSelect(state, { accessible, response: ancestry, error }) { + if (error) { + console.warn("Error fetching ancestry", error); + return state; + } + + const { path, expanded } = updateExpandedNodes(state.expanded, ancestry); + const selected = TreeView.subPath(path, accessible.actorID); + + return Object.assign({}, state, { expanded, selected }); +} + +/** + * Handle "canBeDisabled" flag update for accessibility service + * @param {Object} state Current ui state + * @param {Object} action Redux action object + * @return {Object} updated state + */ +function onCanBeDisabledChange(state, { canBeDisabled }) { + return Object.assign({}, state, { canBeDisabled }); +} + +/** + * Handle "canBeEnabled" flag update for accessibility service + * @param {Object} state Current ui state. + * @param {Object} action Redux action object + * @return {Object} updated state + */ +function onCanBeEnabledChange(state, { canBeEnabled }) { + return Object.assign({}, state, { canBeEnabled }); +} + +/** + * Handle pref update for accessibility panel. + * @param {Object} state Current ui state. + * @param {Object} action Redux action object + * @return {Object} updated state + */ +function onPrefChange(state, { name, value }) { + return { + ...state, + [name]: value, + }; +} + +/** + * Handle reset action for the accessibility panel UI. + * @param {Object} state Current ui state. + * @param {Object} action Redux action object + * @return {Object} updated state + */ +function onReset(state, { enabled, canBeDisabled, canBeEnabled, supports }) { + const newState = { + ...getInitialState(), + enabled, + canBeDisabled, + canBeEnabled, + supports, + }; + + return newState; +} + +/** + * Handle accessibilty service enabling/disabling. + * @param {Object} state Current accessibility services enabled state. + * @param {Object} action Redux action object + * @param {Boolean} enabled New enabled state. + * @return {Object} updated state + */ +function onToggle(state, { error }, enabled) { + if (error) { + console.warn("Error enabling accessibility service: ", error); + return state; + } + + return Object.assign({}, state, { enabled }); +} + +function onUpdateDisplayTabbingOrder(state, { error, tabbingOrderDisplayed }) { + if (error) { + console.warn("Error updating displaying tabbing order: ", error); + return state; + } + + return Object.assign({}, state, { tabbingOrderDisplayed }); +} + +exports.ui = ui; diff --git a/devtools/client/accessibility/test/browser/browser.toml b/devtools/client/accessibility/test/browser/browser.toml new file mode 100644 index 0000000000..e545187857 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser.toml @@ -0,0 +1,73 @@ +[DEFAULT] +tags = "devtools" +subsuite = "devtools" +support-files = [ + "head.js", + "!/devtools/client/shared/test/shared-head.js", + "!/devtools/client/shared/test/highlighter-test-actor.js", + "!/devtools/client/inspector/test/shared-head.js", + "!/devtools/client/shared/test/telemetry-test-helpers.js", +] + +["browser_accessibility_context_menu_browser.js"] + +["browser_accessibility_context_menu_inspector.js"] +skip-if = [ + "apple_catalina", # Bug 1713392 +] + +["browser_accessibility_fission_switch_target.js"] +https_first_disabled = true +skip-if = ["os == 'linux' && asan"] # bug 1666940 + +["browser_accessibility_mutations.js"] +skip-if = [ + "os == 'linux' && bits == 64 && fission", # Bug 1675445 +] + +["browser_accessibility_panel_audit_hidden_iframe.js"] + +["browser_accessibility_panel_audit_oop.js"] + +["browser_accessibility_panel_toolbar_checks.js"] + +["browser_accessibility_panel_toolbar_pref_scroll.js"] +skip-if = ["true"] # bug 1674060 + +["browser_accessibility_print_to_json.js"] + +["browser_accessibility_relation_navigation.js"] + +["browser_accessibility_reload.js"] + +["browser_accessibility_sidebar.js"] + +["browser_accessibility_sidebar_checks.js"] +skip-if = ["os == 'linux' && !debug"] # Bug 1767748 + +["browser_accessibility_sidebar_dom_nodes.js"] + +["browser_accessibility_simulation.js"] +skip-if = ["true"] # bug 1674060 + +["browser_accessibility_tabbing_order_highlighter.js"] + +["browser_accessibility_tabbing_order_highlighter_iframe_picker.js"] + +["browser_accessibility_tree.js"] + +["browser_accessibility_tree_audit.js"] + +["browser_accessibility_tree_audit_long.js"] + +["browser_accessibility_tree_audit_reset.js"] + +["browser_accessibility_tree_audit_toolbar.js"] + +["browser_accessibility_tree_contrast.js"] + +["browser_accessibility_tree_iframe_picker.js"] + +["browser_accessibility_tree_navigation.js"] + +["browser_accessibility_tree_navigation_oop.js"] diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_context_menu_browser.js b/devtools/client/accessibility/test/browser/browser_accessibility_context_menu_browser.js new file mode 100644 index 0000000000..0491b29eb4 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_context_menu_browser.js @@ -0,0 +1,74 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = '

header

paragraph

'; + +addA11YPanelTask( + "Test show accessibility properties context menu in browser.", + TEST_URI, + async function ({ panel, toolbox, browser }) { + // Load the inspector to ensure it to use in this test. + await toolbox.loadTool("inspector"); + + const headerSelector = "#h1"; + + const contextMenu = document.getElementById("contentAreaContextMenu"); + const awaitPopupShown = BrowserTestUtils.waitForEvent( + contextMenu, + "popupshown" + ); + await BrowserTestUtils.synthesizeMouse( + headerSelector, + 0, + 0, + { + type: "contextmenu", + button: 2, + centered: true, + }, + browser + ); + await awaitPopupShown; + + const inspectA11YPropsItem = contextMenu.querySelector( + "#context-inspect-a11y" + ); + + info( + "Triggering 'Inspect Accessibility Properties' and waiting for " + + "accessibility panel to open" + ); + const popupHidden = BrowserTestUtils.waitForEvent( + contextMenu, + "popuphidden" + ); + contextMenu.activateItem(inspectA11YPropsItem); + await popupHidden; + + const selected = await panel.once("new-accessible-front-selected"); + const expectedSelectedNode = await getNodeFront( + headerSelector, + toolbox.getPanel("inspector") + ); + const expectedSelected = + await panel.accessibilityProxy.accessibilityFront.accessibleWalkerFront.getAccessibleFor( + expectedSelectedNode + ); + is( + toolbox.getCurrentPanel(), + panel, + "Accessibility panel is currently selected" + ); + is(selected, expectedSelected, "Accessible front selected correctly"); + + const doc = panel.panelWin.document; + const propertiesTree = doc.querySelector(".tree"); + is(doc.activeElement, propertiesTree, "Properties list must be focused."); + ok( + isVisible(doc.querySelector(".treeTable .treeRow.selected")), + "Selected row is visible." + ); + } +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_context_menu_inspector.js b/devtools/client/accessibility/test/browser/browser_accessibility_context_menu_inspector.js new file mode 100644 index 0000000000..03273a30c2 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_context_menu_inspector.js @@ -0,0 +1,104 @@ +/* Any copyright is dedicated to the Public Domain. +http://creativecommons.org/publicdomain/zero/1.0/ */ +"use strict"; + +const TEST_URI = ` +

header

+

paragraph

+ text + + IamaverylongtextwhichdoesntfitinInlineTextChildReallyIdontIamtoobig + `; + +async function openContextMenuForNode({ toolbox }, selector) { + info("Selecting Inspector tab and opening a context menu"); + const inspector = await toolbox.selectTool("inspector"); + + if (!selector) { + ok(inspector.selection.isBodyNode(), "Default selection is a body node."); + } else if (typeof selector === "string") { + await selectNode(selector, inspector, "test"); + } else { + const updated = inspector.once("inspector-updated"); + inspector.selection.setNodeFront(selector, { reason: "test" }); + await updated; + } + + return openContextMenuAndGetAllItems(inspector); +} + +function checkShowA11YPropertiesNode(allMenuItems) { + const showA11YPropertiesNode = allMenuItems.find( + item => item.id === "node-menu-showaccessibilityproperties" + ); + ok( + showA11YPropertiesNode, + "the popup menu now has a show accessibility properties item" + ); + return showA11YPropertiesNode; +} + +async function checkAccessibleObjectSelection( + { toolbox, panel }, + menuItem, + isText +) { + const inspector = await toolbox.getPanel("inspector"); + info( + "Triggering 'Show Accessibility Properties' and waiting for " + + "accessibility panel to open" + ); + const panelSelected = toolbox.once("accessibility-selected"); + const objectSelected = panel.once("new-accessible-front-selected"); + menuItem.click(); + await panelSelected; + const selected = await objectSelected; + + const expectedNode = isText + ? inspector.selection.nodeFront.inlineTextChild + : inspector.selection.nodeFront; + const expectedSelected = + await panel.accessibilityProxy.accessibilityFront.accessibleWalkerFront.getAccessibleFor( + expectedNode + ); + is(selected, expectedSelected, "Accessible front selected correctly"); + + const doc = panel.panelWin.document; + const propertiesTree = doc.querySelector(".tree"); + is(doc.activeElement, propertiesTree, "Properties list must be focused."); + ok( + isVisible(doc.querySelector(".treeTable .treeRow.selected")), + "Selected row is visible." + ); +} + +addA11YPanelTask( + "Test show accessibility properties context menu.", + TEST_URI, + async function testShowAccessibilityPropertiesContextMenu(env) { + // Load the inspector to ensure it to use in this test. + await env.toolbox.loadTool("inspector"); + + let allMenuItems = await openContextMenuForNode(env); + let showA11YPropertiesNode = checkShowA11YPropertiesNode(allMenuItems); + + allMenuItems = await openContextMenuForNode(env, "#h1"); + showA11YPropertiesNode = checkShowA11YPropertiesNode(allMenuItems); + await checkAccessibleObjectSelection(env, showA11YPropertiesNode); + + allMenuItems = await openContextMenuForNode(env, "#span-1"); + showA11YPropertiesNode = checkShowA11YPropertiesNode(allMenuItems); + await checkAccessibleObjectSelection(env, showA11YPropertiesNode, true); + + allMenuItems = await openContextMenuForNode(env, "#span-2"); + showA11YPropertiesNode = checkShowA11YPropertiesNode(allMenuItems); + + const inspector = env.toolbox.getPanel("inspector"); + const span2 = await getNodeFront("#span-2", inspector); + await inspector.markup.expandNode(span2); + const { nodes } = await inspector.walker.children(span2); + allMenuItems = await openContextMenuForNode(env, nodes[0]); + showA11YPropertiesNode = checkShowA11YPropertiesNode(allMenuItems); + await checkAccessibleObjectSelection(env, showA11YPropertiesNode, false); + } +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_fission_switch_target.js b/devtools/client/accessibility/test/browser/browser_accessibility_fission_switch_target.js new file mode 100644 index 0000000000..9da56a0b1b --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_fission_switch_target.js @@ -0,0 +1,58 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Test switching for the top-level target. + +const MAIN_PROCESS_URL = "about:robots"; +const MAIN_PROCESS_EXPECTED = [ + { + expected: { + sidebar: { + name: "Gort! Klaatu barada nikto!", + role: "document", + }, + }, + }, +]; + +const CONTENT_PROCESS_URL = buildURL(`Test page`); +const CONTENT_PROCESS_EXPECTED = [ + { + expected: { + sidebar: { + name: "Test page", + role: "document", + relations: { + "containing document": { + role: "document", + name: "Test page", + }, + embeds: { + role: "document", + name: "Test page", + }, + }, + }, + }, + }, +]; + +add_task(async () => { + info( + "Open a test page running on the content process and accessibility panel" + ); + const env = await addTestTab(CONTENT_PROCESS_URL); + await runA11yPanelTests(CONTENT_PROCESS_EXPECTED, env); + + info("Navigate to a page running on the main process"); + await navigateTo(MAIN_PROCESS_URL); + await runA11yPanelTests(MAIN_PROCESS_EXPECTED, env); + + info("Back to a page running on the content process"); + await navigateTo(CONTENT_PROCESS_URL); + await runA11yPanelTests(CONTENT_PROCESS_EXPECTED, env); + + await closeTabToolboxAccessibility(env.tab); +}); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_mutations.js b/devtools/client/accessibility/test/browser/browser_accessibility_mutations.js new file mode 100644 index 0000000000..4c564747f9 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_mutations.js @@ -0,0 +1,217 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = ` + + + Accessibility Panel Test + + +

Top level header

+

This is a paragraph.

+ +`; + +const documentRow = { + role: "document", + name: `"Accessibility Panel Test"`, +}; +const documentRowOOP = { + role: "document", + name: `""text label`, + badges: ["text label"], +}; +const subtree = [ + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "text leaf", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, +]; +const frameSubtree = [ + { role: "internal frame", name: `"Accessibility Panel Test (OOP)"` }, + { + role: "document", + name: `"Accessibility Panel Test (OOP)"`, + }, +]; +const subtreeOOP = [...frameSubtree, ...subtree]; +const renamed = [ + { + role: "heading", + name: `"New Header"`, + }, + { + role: "text leaf", + name: `"New Header"`, + }, +]; +const paragraphSidebar = { + name: null, + role: "paragraph", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 1, + indexInParent: 1, + states: ["selectable text", "opaque", "enabled", "sensitive"], +}; +const headerSidebar = { + name: "Top level header", + role: "text leaf", +}; +const newHeaderSidebar = { + name: "New Header", +}; + +function removeRow(rowNumber) { + return async ({ doc, browser }) => { + is( + doc.querySelectorAll(".treeRow").length, + rowNumber, + "Tree size is correct." + ); + await SpecialPowers.spawn(browser, [], async () => { + const iframe = content.document.getElementsByTagName("iframe")[0]; + if (iframe) { + await SpecialPowers.spawn(iframe, [], () => + content.document.getElementById("p").remove() + ); + return; + } + + content.document.getElementById("p").remove(); + }); + await BrowserTestUtils.waitForCondition( + () => doc.querySelectorAll(".treeRow").length === rowNumber - 1, + "Tree updated." + ); + }; +} + +async function rename({ browser }) { + await SpecialPowers.spawn(browser, [], async () => { + const iframe = content.document.getElementsByTagName("iframe")[0]; + if (iframe) { + await SpecialPowers.spawn( + iframe, + [], + () => (content.document.getElementById("h1").textContent = "New Header") + ); + return; + } + + content.document.getElementById("h1").textContent = "New Header"; + }); +} + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const testsTopLevel = [ + { + desc: "Expand first and second rows, select third row.", + setup: async ({ doc }) => { + await toggleRow(doc, 0); + await toggleRow(doc, 1); + selectRow(doc, 3); + }, + expected: { + tree: [documentRow, ...subtree], + sidebar: paragraphSidebar, + }, + }, + { + desc: "Remove a child from a document.", + setup: removeRow(4), + expected: { + tree: [documentRow, ...subtree.slice(0, -1)], + sidebar: headerSidebar, + }, + }, + { + desc: "Update child's text content.", + setup: rename, + expected: { + tree: [documentRow, ...renamed], + }, + }, + { + desc: "Select third row in the tree.", + setup: ({ doc }) => selectRow(doc, 1), + expected: { + sidebar: newHeaderSidebar, + }, + }, +]; + +const testsOOP = [ + { + desc: "Expand rows until we reach an internal OOP frame.", + setup: async ({ doc }) => { + await toggleRow(doc, 0); + await toggleRow(doc, 1); + await toggleRow(doc, 2); + await toggleRow(doc, 3); + selectRow(doc, 5); + }, + expected: { + tree: [documentRowOOP, ...subtreeOOP], + sidebar: paragraphSidebar, + }, + }, + { + desc: "Remove a child from a document.", + setup: removeRow(6), + expected: { + tree: [documentRowOOP, ...subtreeOOP.slice(0, -1)], + sidebar: headerSidebar, + }, + }, + { + desc: "Update child's text content.", + setup: rename, + expected: { + tree: [documentRowOOP, ...frameSubtree, ...renamed], + }, + }, + { + desc: "Select third row in the tree.", + setup: ({ doc }) => selectRow(doc, 1), + expected: { + sidebar: newHeaderSidebar, + }, + }, +]; + +/** + * Tests that checks the Accessibility panel after DOM tree mutations. + */ +addA11yPanelTestsTask( + testsTopLevel, + TEST_URI, + "Test Accessibility panel after DOM tree mutations." +); + +addA11yPanelTestsTask( + testsOOP, + TEST_URI, + "Test Accessibility panel after DOM tree mutations in the OOP frame.", + { remoteIframe: true } +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_hidden_iframe.js b/devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_hidden_iframe.js new file mode 100644 index 0000000000..1e7d0e26c2 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_hidden_iframe.js @@ -0,0 +1,66 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, TREE_FILTERS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +

+ Top level header +

+ + + + + `; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Initial state.", + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + }, + }, + { + desc: "Click on the Check for issues - all.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + level: 1, + }, + ], + }, + }, +]; + +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree audit on a page with hidden iframes." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_oop.js b/devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_oop.js new file mode 100644 index 0000000000..d1ccbe9d5c --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_panel_audit_oop.js @@ -0,0 +1,109 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, TREE_FILTERS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +

+ Top level header +

+ + `; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Initial state.", + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + level: 1, + }, + ], + }, + }, + { + desc: "Click on the Check for issues - all.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + level: 1, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + level: 1, + }, + ], + }, + }, + { + desc: "Click on the Check for issues - all again.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + level: 1, + }, + { + role: "internal frame", + name: `"Accessibility Panel Test (OOP)"`, + level: 2, + }, + { + role: "document", + name: `"Accessibility Panel Test (OOP)"`, + level: 3, + }, + { + role: "heading", + name: `"Top level header"`, + level: 4, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + level: 5, + }, + ], + }, + }, +]; + +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree audit on a page with an OOP document.", + { remoteIframe: true } +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_checks.js b/devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_checks.js new file mode 100644 index 0000000000..b7d541853b --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_checks.js @@ -0,0 +1,114 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, TREE_FILTERS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Check initial state.", + expected: { + activeToolbarFilters: [true, false, false, false, false], + }, + }, + { + desc: "Toggle first filter (all) to activate.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + activeToolbarFilters: [false, true, true, true, true], + }, + }, + { + desc: "Click on the filter again.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + activeToolbarFilters: [true, false, false, false, false], + }, + }, + { + desc: "Toggle first custom filter to activate.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 2); + }, + expected: { + activeToolbarFilters: [false, false, true, false, false], + }, + }, + { + desc: "Click on the filter again.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 2); + }, + expected: { + activeToolbarFilters: [true, false, false, false, false], + }, + }, + { + desc: "Toggle first custom filter to activate.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 2); + }, + expected: { + activeToolbarFilters: [false, false, true, false, false], + }, + }, + { + desc: "Toggle second custom filter to activate.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 3); + }, + expected: { + activeToolbarFilters: [false, false, true, true, false], + }, + }, + { + desc: "Toggle third custom filter to activate.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 4); + }, + expected: { + activeToolbarFilters: [false, true, true, true, true], + }, + }, + { + desc: "Click on the none filter to de-activate all.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 0); + }, + expected: { + activeToolbarFilters: [true, false, false, false, false], + }, + }, +]; + +/** + * Simple test that checks toggle states for filters in the Accessibility panel + * toolbar. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel filter toggle states." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_pref_scroll.js b/devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_pref_scroll.js new file mode 100644 index 0000000000..9f8434f695 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_panel_toolbar_pref_scroll.js @@ -0,0 +1,73 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, PREFS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +`; + +const { + PREFS: { SCROLL_INTO_VIEW }, +} = require("resource://devtools/client/accessibility/constants.js"); + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Check initial state. All filters are disabled (except none). Scroll into view pref disabled.", + expected: { + activeToolbarFilters: [true, false, false, false], + toolbarPrefValues: { + [SCROLL_INTO_VIEW]: false, + }, + }, + }, + { + desc: "Toggle scroll into view checkbox to set the pref. Scroll into view pref should be enabled.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, PREFS_MENU_ID, 0); + }, + expected: { + activeToolbarFilters: [true, false, false, false], + toolbarPrefValues: { + [SCROLL_INTO_VIEW]: true, + }, + }, + }, + { + desc: "Toggle off scroll into view checkbox to unset the pref. Scroll into view pref disabled.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, PREFS_MENU_ID, 0); + }, + expected: { + activeToolbarFilters: [true, false, false, false], + toolbarPrefValues: { + [SCROLL_INTO_VIEW]: false, + }, + }, + }, +]; + +/** + * Simple test that checks toggle state and pref set for automatic scroll into + * view setting. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel scroll into view pref." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_print_to_json.js b/devtools/client/accessibility/test/browser/browser_accessibility_print_to_json.js new file mode 100644 index 0000000000..b7641430c0 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_print_to_json.js @@ -0,0 +1,245 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = "

Top level header

"; + +function getMenuItems(toolbox) { + const menuDoc = toolbox.doc.defaultView.windowRoot.ownerGlobal.document; + const menu = menuDoc.getElementById("accessibility-row-contextmenu"); + return { + menu, + items: [...menu.getElementsByTagName("menuitem")], + }; +} + +async function newTabSelected(tab) { + info("Waiting for the JSON viewer tab."); + await BrowserTestUtils.waitForCondition( + () => gBrowser.selectedTab !== tab, + "Current tab updated." + ); + return gBrowser.selectedTab; +} + +function parseSnapshotFromTabURI(tab) { + let snapshot = tab.label.split("data:application/json;charset=UTF-8,")[1]; + snapshot = decodeURIComponent(snapshot); + return JSON.parse(snapshot); +} + +async function checkJSONSnapshotForRow({ doc, tab, toolbox }, index, expected) { + info(`Triggering context menu for row #${index}.`); + EventUtils.synthesizeMouseAtCenter( + doc.querySelectorAll(".treeRow")[index], + { type: "contextmenu" }, + doc.defaultView + ); + + info(`Triggering "Print To JSON" menu item for row ${index}.`); + const { + menu, + items: [printToJSON], + } = getMenuItems(toolbox); + + await BrowserTestUtils.waitForPopupEvent(menu, "shown"); + + menu.activateItem(printToJSON); + + const jsonViewTab = await newTabSelected(tab); + Assert.deepEqual( + parseSnapshotFromTabURI(jsonViewTab), + expected, + "JSON snapshot for the whole document is correct" + ); + + await removeTab(jsonViewTab); +} + +const OOP_FRAME_DOCUMENT_SNAPSHOT = { + childCount: 1, + description: "", + indexInParent: 0, + keyboardShortcut: "", + name: "Accessibility Panel Test (OOP)", + nodeCssSelector: "", + nodeType: 9, + role: "document", + value: "", + actions: [], + attributes: { + display: "block", + "explicit-name": "true", + "margin-bottom": "8px", + "margin-left": "8px", + "margin-right": "8px", + "margin-top": "8px", + tag: "body", + "text-align": "start", + "text-indent": "0px", + }, + states: ["readonly", "focusable", "opaque", "enabled", "sensitive"], + children: [ + { + childCount: 1, + description: "", + indexInParent: 0, + keyboardShortcut: "", + name: "Top level header", + nodeCssSelector: "body > h1:nth-child(1)", + nodeType: 1, + role: "heading", + value: "", + actions: [], + attributes: { + display: "block", + formatting: "block", + level: "1", + "margin-bottom": "21.44px", + "margin-left": "0px", + "margin-right": "0px", + "margin-top": "0px", + tag: "h1", + "text-align": "start", + "text-indent": "0px", + }, + states: ["selectable text", "opaque", "enabled", "sensitive"], + children: [ + { + childCount: 0, + description: "", + indexInParent: 0, + keyboardShortcut: "", + name: "Top level header", + nodeCssSelector: "body > h1:nth-child(1)#text", + nodeType: 3, + role: "text leaf", + value: "", + actions: [], + attributes: { + "explicit-name": "true", + }, + states: ["opaque", "enabled", "sensitive"], + children: [], + }, + ], + }, + ], +}; + +const OOP_FRAME_SNAPSHOT = { + childCount: 1, + description: "", + indexInParent: 0, + keyboardShortcut: "", + name: "Accessibility Panel Test (OOP)", + nodeCssSelector: "body > iframe:nth-child(1)", + nodeType: 1, + role: "internal frame", + value: "", + actions: [], + attributes: { + display: "inline", + "explicit-name": "true", + "margin-bottom": "0px", + "margin-left": "0px", + "margin-right": "0px", + "margin-top": "0px", + tag: "iframe", + "text-align": "start", + "text-indent": "0px", + }, + states: ["focusable", "opaque", "enabled", "sensitive"], + children: [OOP_FRAME_DOCUMENT_SNAPSHOT], +}; + +const EXPECTED_SNAPSHOT = { + childCount: 1, + description: "", + indexInParent: 0, + keyboardShortcut: "", + name: "", + nodeCssSelector: "", + nodeType: 9, + role: "document", + value: "", + actions: [], + attributes: { + display: "block", + "explicit-name": "true", + "margin-bottom": "8px", + "margin-left": "8px", + "margin-right": "8px", + "margin-top": "8px", + tag: "body", + "text-align": "start", + "text-indent": "0px", + }, + states: ["readonly", "focusable", "opaque", "enabled", "sensitive"], + children: [OOP_FRAME_SNAPSHOT], +}; + +addA11YPanelTask( + "Test print to JSON functionality.", + TEST_URI, + async env => { + const { doc } = env; + await runA11yPanelTests( + [ + { + desc: "Test the initial accessibility tree.", + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + }, + ], + }, + }, + ], + env + ); + + await toggleRow(doc, 0); + await toggleRow(doc, 1); + + await runA11yPanelTests( + [ + { + desc: "Test expanded accessibility tree.", + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + }, + { + role: "internal frame", + name: `"Accessibility Panel Test (OOP)"`, + }, + { + role: "document", + name: `"Accessibility Panel Test (OOP)"`, + }, + ], + }, + }, + ], + env + ); + + // Complete snapshot that includes OOP frame document (crossing process boundry). + await checkJSONSnapshotForRow(env, 0, EXPECTED_SNAPSHOT); + // Snapshot of an OOP frame (crossing process boundry). + await checkJSONSnapshotForRow(env, 1, OOP_FRAME_SNAPSHOT); + // Snapshot of an OOP frame document (not crossing process boundry). + await checkJSONSnapshotForRow(env, 2, OOP_FRAME_DOCUMENT_SNAPSHOT); + }, + { + remoteIframe: true, + } +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_relation_navigation.js b/devtools/client/accessibility/test/browser/browser_accessibility_relation_navigation.js new file mode 100644 index 0000000000..5f9b5e6eb5 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_relation_navigation.js @@ -0,0 +1,169 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +const TEST_URI = ` + + + Accessibility Panel Test + + +

Top level header

+

This is a paragraph.

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility tree and sidebar states.", + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + sidebar: { + name: "Accessibility Panel Test", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 2, + indexInParent: 0, + states: [ + // The focused state is an outdated state, since the toolbox should now + // have the focus and not the content page. See Bug 1702709. + "focused", + "readonly", + "focusable", + "opaque", + "enabled", + "sensitive", + ], + }, + }, + }, + { + desc: "Expand first tree node.", + setup: ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + }, + }, + { + desc: "Select second tree node.", + setup: ({ doc }) => selectRow(doc, 1), + expected: { + sidebar: { + name: "Top level header", + role: "heading", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 1, + indexInParent: 0, + relations: { + "containing document": { + role: "document", + name: "Accessibility Panel Test", + }, + }, + states: ["selectable text", "opaque", "enabled", "sensitive"], + }, + }, + }, + { + desc: "Select containing document.", + setup: async ({ doc, win }) => { + const relations = await selectProperty(doc, "/relations"); + AccessibilityUtils.setEnv({ + // Keyboard navigation is handled on the container level using arrow + // keys. + mustHaveAccessibleRule: false, + }); + EventUtils.sendMouseEvent( + { type: "click" }, + relations.querySelector(".arrow"), + win + ); + AccessibilityUtils.resetEnv(); + const containingDocRelation = await selectProperty( + doc, + "/relations/containing document" + ); + AccessibilityUtils.setEnv({ + // Keyboard interaction is only enabled when the row is selected and + // activated. + nonNegativeTabIndexRule: false, + }); + + const selectElementInTreeButton = containingDocRelation.querySelector( + ".open-accessibility-inspector" + ); + ok(!!selectElementInTreeButton, "There's a button to select the element"); + is( + selectElementInTreeButton.getAttribute("title"), + L10N.getStr("accessibility.accessible.selectElement.title"), + "The button has the expected title" + ); + EventUtils.sendMouseEvent( + { type: "click" }, + selectElementInTreeButton, + win + ); + AccessibilityUtils.resetEnv(); + }, + expected: { + sidebar: { + name: "Accessibility Panel Test", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 2, + indexInParent: 0, + states: ["readonly", "focusable", "opaque", "enabled", "sensitive"], + }, + }, + }, +]; + +/** + * Check navigation within the tree. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel relation navigation." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_reload.js b/devtools/client/accessibility/test/browser/browser_accessibility_reload.js new file mode 100644 index 0000000000..c4ffdf30dd --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_reload.js @@ -0,0 +1,107 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI_1 = ` + + + Accessibility Panel Test + + +

Top level header

+

This is a paragraph.

+ +`; + +const TEST_URI_2 = ` + + + Navigation Accessibility Panel + + +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility tree state after first row is expanded.", + setup: async ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + sidebar: { + name: "Accessibility Panel Test", + role: "document", + }, + }, + }, + { + desc: "Reload the page.", + setup: async ({ panel }) => { + const onReloaded = panel.once("reloaded"); + panel.accessibilityProxy.commands.targetCommand.reloadTopLevelTarget(); + await onReloaded; + }, + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + sidebar: { + name: "Accessibility Panel Test", + role: "document", + }, + }, + }, + { + desc: "Navigate to a new page.", + setup: async () => { + // `navigate` waits for the "reloaded" event so we don't need to do it explicitly here + await navigateTo(buildURL(TEST_URI_2)); + }, + expected: { + tree: [ + { + role: "document", + name: `"Navigation Accessibility Panel"`, + }, + ], + sidebar: { + name: "Navigation Accessibility Panel", + role: "document", + }, + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree on reload. + */ +addA11yPanelTestsTask( + tests, + TEST_URI_1, + "Test Accessibility panel tree on reload." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_sidebar.js b/devtools/client/accessibility/test/browser/browser_accessibility_sidebar.js new file mode 100644 index 0000000000..e7c2795ced --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_sidebar.js @@ -0,0 +1,81 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = ` + + + Accessibility Panel Test + + +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility sidebar state.", + expected: { + sidebar: { + name: "Accessibility Panel Test", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 0, + indexInParent: 0, + states: [ + // The focused state is an outdated state, since the toolbox should now + // have the focus and not the content page. See Bug 1702709. + "focused", + "readonly", + "focusable", + "opaque", + "enabled", + "sensitive", + ], + }, + }, + }, + { + desc: "Mark document as disabled for accessibility.", + setup: async ({ browser }) => + SpecialPowers.spawn(browser, [], () => + content.document.body.setAttribute("aria-disabled", true) + ), + expected: { + sidebar: { + states: ["unavailable", "readonly", "focusable", "opaque"], + }, + }, + }, + { + desc: "Append a new child to the document.", + setup: async ({ browser }) => + SpecialPowers.spawn(browser, [], () => { + const doc = content.document; + const button = doc.createElement("button"); + button.textContent = "Press Me!"; + doc.body.appendChild(button); + }), + expected: { + sidebar: { + childCount: 1, + }, + }, + }, +]; + +/** + * Test that checks the Accessibility panel sidebar. + */ +addA11yPanelTestsTask(tests, TEST_URI, "Test Accessibility panel sidebar."); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_sidebar_checks.js b/devtools/client/accessibility/test/browser/browser_accessibility_sidebar_checks.js new file mode 100644 index 0000000000..f9c0abe8dc --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_sidebar_checks.js @@ -0,0 +1,83 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const { + accessibility: { SCORES }, +} = require("resource://devtools/shared/constants.js"); + +const TEST_URI = ` + + + Accessibility Panel Test + + +

Red

+

Blue

+

Gray

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility audit state.", + setup: async ({ doc }) => { + await selectRow(doc, 0); + }, + expected: { + audit: { CONTRAST: null }, + }, + }, + { + desc: "Check accessible representing text node in red.", + setup: async ({ doc }) => { + await toggleRow(doc, 0); + await toggleRow(doc, 1); + await selectRow(doc, 2); + }, + expected: { + audit: { + CONTRAST: { + value: 4.0, + color: [255, 0, 0, 1], + backgroundColor: [255, 255, 255, 1], + isLargeText: false, + score: SCORES.FAIL, + }, + }, + }, + }, + { + desc: "Check accessible representing text node in blue.", + setup: async ({ doc }) => { + await toggleRow(doc, 3); + await selectRow(doc, 4); + }, + expected: { + audit: { + CONTRAST: { + value: 8.59, + color: [0, 0, 255, 1], + backgroundColor: [255, 255, 255, 1], + isLargeText: false, + score: SCORES.AAA, + }, + }, + }, + }, +]; + +/** + * Test that checks the Accessibility panel sidebar. + */ +addA11yPanelTestsTask(tests, TEST_URI, "Test Accessibility panel sidebar."); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_sidebar_dom_nodes.js b/devtools/client/accessibility/test/browser/browser_accessibility_sidebar_dom_nodes.js new file mode 100644 index 0000000000..075354b0c3 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_sidebar_dom_nodes.js @@ -0,0 +1,111 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const { + L10N, +} = require("resource://devtools/client/accessibility/utils/l10n.js"); + +// Check that DOM nodes in the sidebar can be highlighted and that clicking on the icon +// next to them opens the inspector. + +const TEST_URI = ` + + + Accessibility Panel Sidebar DOM Nodes Test + + +

Hello

+ +`; + +/** + * Test that checks the Accessibility panel sidebar. + */ +addA11YPanelTask( + "Check behavior of DOM nodes in side panel", + TEST_URI, + async ({ toolbox, doc }) => { + info("Select an item having an actual associated DOM node"); + await toggleRow(doc, 0); + selectRow(doc, 1); + + await BrowserTestUtils.waitForCondition( + () => getPropertyValue(doc, "name") === `"Hello"`, + "Wait until the sidebar is updated" + ); + + info("Check DOMNode"); + const domNodeEl = getPropertyItem(doc, "DOMNode"); + ok(domNodeEl, "The DOMNode item was retrieved"); + + const openInspectorButton = domNodeEl.querySelector(".open-inspector"); + ok(openInspectorButton, "The open inspector button is displayed"); + is( + openInspectorButton.getAttribute("title"), + L10N.getStr("accessibility.accessible.selectNodeInInspector.title"), + "The open inspector button has expected title" + ); + + info("Check that hovering DOMNode triggers the highlight"); + // Loading the inspector panel at first, to make it possible to listen for + // new node selections + await toolbox.loadTool("inspector"); + const highlighter = toolbox.getHighlighter(); + const highlighterTestFront = await getHighlighterTestFront(toolbox); + + const onHighlighterShown = highlighter.waitForHighlighterShown(); + + EventUtils.synthesizeMouseAtCenter( + openInspectorButton, + { type: "mousemove" }, + doc.defaultView + ); + + const { nodeFront } = await onHighlighterShown; + is(nodeFront.displayName, "h1", "The correct node was highlighted"); + isVisible = await highlighterTestFront.isHighlighting(); + ok(isVisible, "Highlighter is displayed"); + + info("Unhighlight the node by moving away from the node"); + const onHighlighterHidden = highlighter.waitForHighlighterHidden(); + EventUtils.synthesizeMouseAtCenter( + getPropertyItem(doc, "name"), + { type: "mousemove" }, + doc.defaultView + ); + + await onHighlighterHidden; + ok(true, "The highlighter was closed when moving away from the node"); + + info( + "Clicking on the inspector icon and waiting for the inspector to be selected" + ); + const onNewNode = toolbox.selection.once("new-node-front"); + openInspectorButton.click(); + const inspectorSelectedNodeFront = await onNewNode; + + ok(true, "Inspector selected and new node got selected"); + is( + inspectorSelectedNodeFront.id, + "select-me", + "The expected node was selected" + ); + } +); + +function getPropertyItem(doc, label) { + const labelEl = Array.from( + doc.querySelectorAll("#accessibility-properties .object-label") + ).find(el => el.textContent === label); + if (!labelEl) { + return null; + } + return labelEl.closest(".node"); +} + +function getPropertyValue(doc, label) { + return getPropertyItem(doc, label)?.querySelector(".object-value") + ?.textContent; +} diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_simulation.js b/devtools/client/accessibility/test/browser/browser_accessibility_simulation.js new file mode 100644 index 0000000000..85a9be6b36 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_simulation.js @@ -0,0 +1,99 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global openSimulationMenu, toggleSimulationOption */ + +const TEST_URI = ` + + + Accessibility Simulations Test + + +

+ Top level header +

+

+ Second level header +

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the simulation components can be checked. + * expected {JSON} An expected states for the simulation components. + * } + */ +const tests = [ + { + desc: "Check that the menu button is inactivate and the menu is closed initially.", + expected: { + simulation: { + buttonActive: false, + }, + }, + }, + { + desc: "Clicking the menu button shows the menu with No Simulation selected.", + setup: async ({ doc }) => { + await openSimulationMenu(doc); + }, + expected: { + simulation: { + buttonActive: false, + checkedOptionIndices: [0], + }, + }, + }, + { + desc: "Selecting an option renders the menu button active and closes the menu.", + setup: async ({ doc }) => { + await toggleSimulationOption(doc, 2); + }, + expected: { + simulation: { + buttonActive: true, + checkedOptionIndices: [2], + }, + }, + }, + { + desc: "Reopening the menu preserves the previously selected option.", + setup: async ({ doc }) => { + await openSimulationMenu(doc); + }, + expected: { + simulation: { + buttonActive: true, + checkedOptionIndices: [2], + }, + }, + }, + { + desc: "Unselecting the option renders the button inactive and closes the menu.", + setup: async ({ doc }) => { + await toggleSimulationOption(doc, 2); + }, + expected: { + simulation: { + buttonActive: false, + checkedOptionIndices: [0], + }, + }, + }, +]; + +/** + * Test that checks state of simulation button and menu when + * options are selected/unselected with web render enabled. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test selecting and unselecting simulation options updates UI." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter.js b/devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter.js new file mode 100644 index 0000000000..ed872f46e0 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter.js @@ -0,0 +1,140 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Check "Show tabbing order" works as expected + +const TEST_URI = `https://example.com/document-builder.sjs?html= + + + + `; + +add_task(async () => { + const { doc, store, tab, toolbox } = await addTestTab(TEST_URI); + + const topLevelFrameHighlighterTestFront = await toolbox.target.getFront( + "highlighterTest" + ); + + const frameTargets = toolbox.commands.targetCommand.getAllTargets([ + toolbox.commands.targetCommand.TYPES.FRAME, + ]); + const orgIframeTarget = frameTargets.find(t => + t.url.startsWith("https://example.org") + ); + const netIframeTarget = frameTargets.find(t => + t.url.startsWith("https://example.net") + ); + + // The iframe only has a dedicated target when Fission or EFT is enabled + const orgIframeHighlighterTestFront = orgIframeTarget + ? await orgIframeTarget.getFront("highlighterTest") + : null; + const netIframeHighlighterTestFront = netIframeTarget + ? await netIframeTarget.getFront("highlighterTest") + : null; + + let tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData(); + is( + tabbingOrderHighlighterData.length, + 0, + "Tabbing order is not visible at first" + ); + + info(`Click on "Show Tabbing Order" checkbox`); + const tabbingOrderCheckbox = doc.getElementById( + "devtools-display-tabbing-order-checkbox" + ); + tabbingOrderCheckbox.click(); + + await waitUntilState(store, state => state.ui.tabbingOrderDisplayed === true); + + is(tabbingOrderCheckbox.checked, true, "Checkbox is checked"); + tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData(); + if (isFissionEnabled()) { + // ⚠️ We don't get the highlighter for the node of the iframe when Fission is enabled. + // This should be fix as part of Bug 1740509. + is( + JSON.stringify(tabbingOrderHighlighterData), + JSON.stringify([`button#top-btn-1 : 1`, `button#top-btn-2 : 4`]), + "Tabbing order is visible for the top level target after clicking the checkbox" + ); + + const orgIframeTabingOrderHighlighterData = + await orgIframeHighlighterTestFront.getTabbingOrderHighlighterData(); + is( + JSON.stringify(orgIframeTabingOrderHighlighterData), + JSON.stringify([ + `button#iframe-org-btn-1 : 2`, + `button#iframe-org-btn-2 : 3`, + ]), + "Tabbing order is visible for the org iframe after clicking the checkbox" + ); + + const netIframeTabingOrderHighlighterData = + await netIframeHighlighterTestFront.getTabbingOrderHighlighterData(); + is( + JSON.stringify(netIframeTabingOrderHighlighterData), + JSON.stringify([`button#iframe-net-btn-1 : 5`]), + "Tabbing order is visible for the net iframe after clicking the checkbox" + ); + } else { + is( + JSON.stringify(tabbingOrderHighlighterData), + JSON.stringify([ + `button#top-btn-1 : 1`, + `html : 2`, + `button#iframe-org-btn-1 : 3`, + `button#iframe-org-btn-2 : 4`, + `button#top-btn-2 : 5`, + `html : 6`, + `button#iframe-net-btn-1 : 7`, + ]), + "Tabbing order is visible for the top level target after clicking the checkbox" + ); + } + + info(`Clicking on the checkbox again hides the highlighter`); + tabbingOrderCheckbox.click(); + await waitUntilState( + store, + state => state.ui.tabbingOrderDisplayed === false + ); + + is(tabbingOrderCheckbox.checked, false, "Checkbox is unchecked"); + tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData(); + is( + tabbingOrderHighlighterData.length, + 0, + "Tabbing order is not visible anymore after unchecking the checkbox" + ); + + if (isFissionEnabled()) { + const orgIframeTabingOrderHighlighterData = + await orgIframeHighlighterTestFront.getTabbingOrderHighlighterData(); + is( + orgIframeTabingOrderHighlighterData.length, + 0, + "Tabbing order is also hidden on the org iframe target" + ); + const netIframeTabingOrderHighlighterData = + await netIframeHighlighterTestFront.getTabbingOrderHighlighterData(); + is( + netIframeTabingOrderHighlighterData.length, + 0, + "Tabbing order is also hidden on the net iframe target" + ); + } + + await closeTabToolboxAccessibility(tab); +}); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter_iframe_picker.js b/devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter_iframe_picker.js new file mode 100644 index 0000000000..788813d343 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tabbing_order_highlighter_iframe_picker.js @@ -0,0 +1,195 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Check "Show tabbing order" works as expected when used with the iframe picker + +const TEST_URI = `https://example.com/document-builder.sjs?html= + + + `; + +add_task(async () => { + const env = await addTestTab(TEST_URI); + const { doc, panel, store, toolbox, win } = env; + + const topLevelFrameHighlighterTestFront = await toolbox.target.getFront( + "highlighterTest" + ); + + const iframeTarget = toolbox.commands.targetCommand + .getAllTargets([toolbox.commands.targetCommand.TYPES.FRAME]) + .find(t => t.url.startsWith("https://example.org")); + + // The iframe only has a dedicated target when Fission or EFT is enabled + const iframeHighlighterTestFront = iframeTarget + ? await iframeTarget.getFront("highlighterTest") + : null; + + const topLevelAccessibilityFrontActorID = + panel.accessibilityProxy.accessibilityFront.actorID; + + const iframeAccessibilityFrontActorID = iframeTarget + ? (await iframeTarget.getFront("accessibility")).actorID + : null; + + info(`Click on "Show Tabbing Order" checkbox`); + const tabbingOrderCheckbox = doc.getElementById( + "devtools-display-tabbing-order-checkbox" + ); + tabbingOrderCheckbox.click(); + await waitUntilState(store, state => state.ui.tabbingOrderDisplayed === true); + + is(tabbingOrderCheckbox.checked, true, "Checkbox is checked"); + let tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData( + topLevelAccessibilityFrontActorID + ); + if (isFissionEnabled()) { + // ⚠️ We don't get the highlighter for the node of the iframe when Fission is enabled. + // This should be fix as part of Bug 1740509. + is( + JSON.stringify(tabbingOrderHighlighterData), + JSON.stringify([`button#top-btn-1 : 1`, `button#top-btn-2 : 4`]), + "Tabbing order is visible for the top level target after clicking the checkbox" + ); + + const iframeTabingOrderHighlighterData = + await iframeHighlighterTestFront.getTabbingOrderHighlighterData( + iframeAccessibilityFrontActorID + ); + + is( + JSON.stringify(iframeTabingOrderHighlighterData), + JSON.stringify([`button#iframe-btn-1 : 2`, `button#iframe-btn-2 : 3`]), + "Tabbing order is visible for the top level target after clicking the checkbox" + ); + } else { + is( + JSON.stringify(tabbingOrderHighlighterData), + JSON.stringify([ + `button#top-btn-1 : 1`, + `html : 2`, + `button#iframe-btn-1 : 3`, + `button#iframe-btn-2 : 4`, + `button#top-btn-2 : 5`, + ]), + "Tabbing order is visible for the top level target after clicking the checkbox" + ); + } + + info("Select the iframe in the iframe picker"); + // Get the iframe picker items + const menuList = toolbox.doc.getElementById("toolbox-frame-menu"); + + if (isFissionEnabled() && !isEveryFrameTargetEnabled()) { + is( + menuList, + null, + "iframe picker does not show remote frames when Fission is enabled and EFT is disabled" + ); + return; + } + + const frames = Array.from(menuList.querySelectorAll(".command")); + + let onInitialized = win.once(win.EVENTS.INITIALIZED); + frames[1].click(); + await onInitialized; + await waitUntilState( + store, + state => state.ui.tabbingOrderDisplayed === false + ); + + is( + tabbingOrderCheckbox.checked, + false, + "Checkbox is unchecked after selecting an iframe" + ); + + tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData( + topLevelAccessibilityFrontActorID + ); + is( + tabbingOrderHighlighterData.length, + 0, + "Tabbing order is not visible anymore" + ); + + info( + `Click on "Show Tabbing Order" checkbox and check that highlighter is only displayed for selected frame` + ); + tabbingOrderCheckbox.click(); + await waitUntilState(store, state => state.ui.tabbingOrderDisplayed === true); + + tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData( + topLevelAccessibilityFrontActorID + ); + if (isFissionEnabled() || isEveryFrameTargetEnabled()) { + is( + tabbingOrderHighlighterData.length, + 0, + "There's no highlighter displayed on the top level target when focused on specific iframe" + ); + + const iframeTabingOrderHighlighterData = + await iframeHighlighterTestFront.getTabbingOrderHighlighterData( + iframeAccessibilityFrontActorID + ); + + is( + JSON.stringify(iframeTabingOrderHighlighterData), + JSON.stringify([`button#iframe-btn-1 : 1`, `button#iframe-btn-2 : 2`]), + "Tabbing order has expected data when a specific iframe is selected" + ); + } else { + // When Fission/EFT are not enabled, the highlighter is displayed from the top-level + // target, but only for the iframe + is( + JSON.stringify(tabbingOrderHighlighterData), + JSON.stringify([`button#iframe-btn-1 : 1`, `button#iframe-btn-2 : 2`]), + "Tabbing order has expected data when a specific iframe is selected" + ); + } + + info("Select the top level document back"); + onInitialized = win.once(win.EVENTS.INITIALIZED); + toolbox.doc.querySelector("#toolbox-frame-menu .command").click(); + await onInitialized; + + is( + tabbingOrderCheckbox.checked, + false, + "Checkbox is unchecked after selecting the top level frame" + ); + await waitUntilState( + store, + state => state.ui.tabbingOrderDisplayed === false + ); + + tabbingOrderHighlighterData = + await topLevelFrameHighlighterTestFront.getTabbingOrderHighlighterData( + topLevelAccessibilityFrontActorID + ); + + if (isFissionEnabled() || isEveryFrameTargetEnabled()) { + const iframeTabingOrderHighlighterData = + await iframeHighlighterTestFront.getTabbingOrderHighlighterData( + iframeAccessibilityFrontActorID + ); + + is( + iframeTabingOrderHighlighterData.length, + 0, + "Highlighter is hidden on the frame after selecting back the top level target" + ); + } + + await closeTabToolboxAccessibility(env.tab); +}); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree.js new file mode 100644 index 0000000000..d1be57ee2d --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree.js @@ -0,0 +1,75 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = ` + + + Accessibility Panel Test + + +

Top level header

+

This is a paragraph.

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility tree state.", + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + }, + }, + { + desc: "Expand first tree node.", + setup: async ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + }, + }, + { + desc: "Collapse first tree node.", + setup: async ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree. + */ +addA11yPanelTestsTask(tests, TEST_URI, "Test Accessibility panel tree."); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit.js new file mode 100644 index 0000000000..b321fafba2 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit.js @@ -0,0 +1,137 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleRow, toggleMenuItem, TREE_FILTERS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +

+ Top level header +

+

+ Second level header +

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Expand first and second tree nodes.", + setup: async ({ doc }) => { + await toggleRow(doc, 0); + await toggleRow(doc, 1); + }, + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + level: 1, + }, + { + role: "heading", + name: `"Top level header"`, + level: 2, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + level: 3, + }, + { + role: "heading", + name: `"Second level header"`, + level: 2, + }, + ], + }, + }, + { + desc: "Click on the all filter.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + level: 1, + }, + { + role: "text leaf", + name: `"Second level header "contrast`, + badges: ["contrast"], + selected: true, + level: 1, + }, + ], + }, + }, + { + desc: "Click on the all filter again.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + level: 1, + }, + { + role: "heading", + name: `"Top level header"`, + level: 2, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + level: 3, + }, + { + role: "heading", + name: `"Second level header"`, + level: 2, + }, + { + role: "text leaf", + name: `"Second level header "contrast`, + badges: ["contrast"], + selected: true, + level: 3, + }, + ], + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree when one of + * the tree rows has a "contrast" badge and auditing is activated via toolbar + * filter. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree with contrast badge present." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_long.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_long.js new file mode 100644 index 0000000000..a8e295c504 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_long.js @@ -0,0 +1,104 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, TREE_FILTERS_MENU_ID */ + +const header = + '

header

'; + +const TEST_URI = ` + + + Accessibility Panel Test + + + ${header.repeat(20)} + +`; + +const docRow = { + role: "document", + name: `"Accessibility Panel Test"`, +}; +const headingRow = { + role: "heading", + name: `"header"`, +}; +const textLeafRow = { + role: "text leaf", + name: `"header"contrast`, + badges: ["contrast"], +}; +const audit = new Array(20).fill(textLeafRow); + +const auditInitial = audit.map(check => ({ ...check })); +auditInitial[0].selected = true; + +const auditSecondLastSelected = audit.map(check => ({ ...check })); +auditSecondLastSelected[19].selected = true; + +const resetAfterAudit = [docRow]; +for (let i = 0; i < 20; i++) { + resetAfterAudit.push(headingRow); + resetAfterAudit.push({ ...textLeafRow, selected: i === 19 }); +} + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Check initial state.", + expected: { + tree: [{ ...docRow, selected: true }], + }, + }, + { + desc: "Run an audit from a11y panel toolbar by activating a filter.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: auditInitial, + }, + }, + { + desc: "Select a row that is guaranteed to have to be scrolled into view.", + setup: async ({ doc }) => { + selectRow(doc, 0); + EventUtils.synthesizeKey("VK_END", {}, doc.defaultView); + }, + expected: { + tree: auditSecondLastSelected, + }, + }, + { + desc: "Click on the filter again.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: resetAfterAudit, + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree when the + * audit is activated via the panel's toolbar and the selection persists when + * the filter is toggled off. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree with persistent selected row." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_reset.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_reset.js new file mode 100644 index 0000000000..084a46dc89 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_reset.js @@ -0,0 +1,109 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, selectAccessibleForNode, TREE_FILTERS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +

+ Top level header +

+

+ Second level header +

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Check initial state.", + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + selected: true, + }, + ], + }, + }, + { + desc: "Run an audit from a11y panel toolbar by activating a filter.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + selected: true, + }, + { + role: "text leaf", + name: `"Second level header "contrast`, + badges: ["contrast"], + }, + ], + }, + }, + { + desc: "Select an accessible object.", + setup: async env => { + await selectAccessibleForNode(env, "h1"); + }, + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + selected: true, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + }, + { + role: "heading", + name: `"Second level header"`, + }, + { + role: "text leaf", + name: `"Second level header "contrast`, + badges: ["contrast"], + }, + ], + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree when the + * audit is activated via the panel's toolbar. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree with contrast filter audit activation." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_toolbar.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_toolbar.js new file mode 100644 index 0000000000..9a1b9ba4c7 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_audit_toolbar.js @@ -0,0 +1,112 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +/* global toggleMenuItem, TREE_FILTERS_MENU_ID */ + +const TEST_URI = ` + + + Accessibility Panel Test + + +

+ Top level header +

+

+ Second level header +

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Check initial state.", + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + selected: true, + }, + ], + activeToolbarFilters: [true, false, false, false, false], + }, + }, + { + desc: "Run an audit (all) from a11y panel toolbar by activating a filter.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + selected: true, + }, + { + role: "text leaf", + name: `"Second level header "contrast`, + badges: ["contrast"], + }, + ], + activeToolbarFilters: [false, true, true, true, true], + }, + }, + { + desc: "Click on the filter again.", + setup: async ({ doc, toolbox }) => { + await toggleMenuItem(doc, toolbox.doc, TREE_FILTERS_MENU_ID, 1); + }, + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + selected: true, + }, + { + role: "heading", + name: `"Second level header"`, + }, + { + role: "text leaf", + name: `"Second level header "contrast`, + badges: ["contrast"], + }, + ], + activeToolbarFilters: [true, false, false, false, false], + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree when the + * audit is activated via the panel's toolbar. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree with 'all' filter audit activation." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_contrast.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_contrast.js new file mode 100644 index 0000000000..2abfabd324 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_contrast.js @@ -0,0 +1,62 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = ` + + + Accessibility Panel Test + + +

+ Top level header +

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Expand first and second tree nodes.", + setup: async ({ doc }) => { + await toggleRow(doc, 0); + await toggleRow(doc, 1); + }, + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "text leaf", + name: `"Top level header "contrast`, + badges: ["contrast"], + }, + ], + }, + }, +]; + +/** + * Simple test that checks content of the Accessibility panel tree when one of + * the tree rows has a "contrast" badge. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree with contrast badge." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_iframe_picker.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_iframe_picker.js new file mode 100644 index 0000000000..dc146a32d5 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_iframe_picker.js @@ -0,0 +1,121 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +// Check that the accessibility panel works as expected when using the iframe picker + +const TEST_URI = `data:text/html, + + TopLevel + + + +

Top level header

+

This is a paragraph.

+ `; + +add_task(async () => { + const env = await addTestTab(TEST_URI); + const { doc, toolbox, win } = env; + + await checkTree(env, [ + { + role: "document", + name: `"TopLevel"`, + }, + ]); + + info("Select the iframe in the iframe picker"); + // Get the iframe picker items + const menuList = toolbox.doc.getElementById("toolbox-frame-menu"); + const frames = Array.from(menuList.querySelectorAll(".command")); + + let onInitialized = win.once(win.EVENTS.INITIALIZED); + frames[1].click(); + await onInitialized; + + await checkTree(env, [ + { + role: "document", + name: `"iframe"`, + }, + ]); + + info( + "Run a constrast audit to check only issues from selected iframe tree are displayed" + ); + const CONTRAST_MENU_ITEM_INDEX = 2; + const onUpdated = win.once(win.EVENTS.ACCESSIBILITY_INSPECTOR_UPDATED); + await toggleMenuItem( + doc, + toolbox.doc, + TREE_FILTERS_MENU_ID, + CONTRAST_MENU_ITEM_INDEX + ); + await onUpdated; + // wait until the tree is filtered (i.e. the audit is done and only nodes with issues + // should be displayed) + await waitFor(() => doc.querySelector(".treeTable.filtered")); + + await checkTree(env, [ + { + role: "text leaf", + name: `"Iframe header"contrast`, + badges: ["contrast"], + level: 1, + }, + { + role: "text leaf", + name: `"Nested Iframe header"contrast`, + badges: ["contrast"], + level: 1, + }, + ]); + + info("Select the top level document back"); + onInitialized = win.once(win.EVENTS.INITIALIZED); + frames[0].click(); + await onInitialized; + + await checkTree(env, [ + { + role: "document", + name: `"TopLevel"`, + }, + ]); + + await closeTabToolboxAccessibility(env.tab); +}); + +function checkTree(env, tree) { + return runA11yPanelTests( + [ + { + expected: { + tree, + }, + }, + ], + env + ); +} diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation.js new file mode 100644 index 0000000000..d98c3d8e35 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation.js @@ -0,0 +1,186 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = ` + + + Accessibility Panel Test + + +

Top level header

+

This is a paragraph.

+ +`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility tree and sidebar states.", + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + sidebar: { + name: "Accessibility Panel Test", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 2, + indexInParent: 0, + states: [ + // The focused state is an outdated state, since the toolbox should now + // have the focus and not the content page. See Bug 1702709. + "focused", + "readonly", + "focusable", + "opaque", + "enabled", + "sensitive", + ], + }, + }, + }, + { + desc: "Expand first tree node.", + setup: async ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + }, + }, + { + desc: "Expand second tree node.", + setup: async ({ doc }) => toggleRow(doc, 1), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "text leaf", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + sidebar: { + name: "Top level header", + role: "heading", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 1, + indexInParent: 0, + states: ["selectable text", "opaque", "enabled", "sensitive"], + }, + }, + }, + { + desc: "Select third tree node.", + setup: ({ doc }) => selectRow(doc, 2), + expected: { + sidebar: { + name: "Top level header", + role: "text leaf", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 0, + indexInParent: 0, + states: ["opaque", "enabled", "sensitive"], + }, + }, + }, + { + desc: "Collapse first tree node.", + setup: async ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + ], + sidebar: { + name: "Accessibility Panel Test", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 2, + indexInParent: 0, + states: ["readonly", "focusable", "opaque", "enabled", "sensitive"], + }, + }, + }, + { + desc: "Expand first tree node again.", + setup: async ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `"Accessibility Panel Test"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "text leaf", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + }, + }, +]; + +/** + * Check navigation within the tree. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree navigation." +); diff --git a/devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation_oop.js b/devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation_oop.js new file mode 100644 index 0000000000..dc710c82e4 --- /dev/null +++ b/devtools/client/accessibility/test/browser/browser_accessibility_tree_navigation_oop.js @@ -0,0 +1,149 @@ +/* Any copyright is dedicated to the Public Domain. + * http://creativecommons.org/publicdomain/zero/1.0/ */ + +"use strict"; + +const TEST_URI = `

Top level header

This is a paragraph.

`; + +/** + * Test data has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be performed before + * the state of the tree and the sidebar can be checked. + * expected {JSON} An expected states for the tree and the sidebar. + * } + */ +const tests = [ + { + desc: "Test the initial accessibility tree and sidebar states.", + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + }, + ], + sidebar: { + name: "", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 1, + indexInParent: 0, + states: [ + // The focused state is an outdated state, since the toolbox should now + // have the focus and not the content page. See Bug 1702709. + "focused", + "readonly", + "focusable", + "opaque", + "enabled", + "sensitive", + ], + }, + }, + }, + { + desc: "Expand first tree node.", + setup: ({ doc }) => toggleRow(doc, 0), + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + }, + { + role: "internal frame", + name: `"Accessibility Panel Test (OOP)"`, + }, + ], + }, + }, + { + desc: "Expand second tree node. Display OOP document.", + setup: ({ doc }) => toggleRow(doc, 1), + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + }, + { + role: "internal frame", + name: `"Accessibility Panel Test (OOP)"`, + }, + { + role: "document", + name: `"Accessibility Panel Test (OOP)"`, + }, + ], + sidebar: { + name: "Accessibility Panel Test (OOP)", + role: "internal frame", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 1, + indexInParent: 0, + states: ["focusable", "opaque", "enabled", "sensitive"], + }, + }, + }, + { + desc: "Expand third tree node. Display OOP frame content.", + setup: ({ doc }) => toggleRow(doc, 2), + expected: { + tree: [ + { + role: "document", + name: `""text label`, + badges: ["text label"], + }, + { + role: "internal frame", + name: `"Accessibility Panel Test (OOP)"`, + }, + { + role: "document", + name: `"Accessibility Panel Test (OOP)"`, + }, + { + role: "heading", + name: `"Top level header"`, + }, + { + role: "paragraph", + name: `""`, + }, + ], + sidebar: { + name: "Accessibility Panel Test (OOP)", + role: "document", + actions: [], + value: "", + description: "", + keyboardShortcut: "", + childCount: 2, + indexInParent: 0, + states: ["readonly", "focusable", "opaque", "enabled", "sensitive"], + }, + }, + }, +]; + +/** + * Check navigation within the tree. + */ +addA11yPanelTestsTask( + tests, + TEST_URI, + "Test Accessibility panel tree navigation with OOP frame.", + { remoteIframe: true } +); diff --git a/devtools/client/accessibility/test/browser/head.js b/devtools/client/accessibility/test/browser/head.js new file mode 100644 index 0000000000..3a734f6c70 --- /dev/null +++ b/devtools/client/accessibility/test/browser/head.js @@ -0,0 +1,819 @@ +/* Any copyright is dedicated to the Public Domain. + http://creativecommons.org/publicdomain/zero/1.0/ */ + +/* global waitUntilState, gBrowser */ +/* exported addTestTab, checkTreeState, checkSidebarState, checkAuditState, selectRow, + toggleRow, toggleMenuItem, addA11yPanelTestsTask, navigate, + openSimulationMenu, toggleSimulationOption, TREE_FILTERS_MENU_ID, + PREFS_MENU_ID */ + +"use strict"; + +// Import framework's shared head. +Services.scriptloader.loadSubScript( + "chrome://mochitests/content/browser/devtools/client/shared/test/shared-head.js", + this +); + +// Import inspector's shared head. +Services.scriptloader.loadSubScript( + "chrome://mochitests/content/browser/devtools/client/inspector/test/shared-head.js", + this +); + +const { + ORDERED_PROPS, + PREF_KEYS, +} = require("resource://devtools/client/accessibility/constants.js"); + +// Enable the Accessibility panel +Services.prefs.setBoolPref("devtools.accessibility.enabled", true); + +const SIMULATION_MENU_BUTTON_ID = "#simulation-menu-button"; +const TREE_FILTERS_MENU_ID = "accessibility-tree-filters-menu"; +const PREFS_MENU_ID = "accessibility-tree-filters-prefs-menu"; + +const MENU_INDEXES = { + [TREE_FILTERS_MENU_ID]: 0, + [PREFS_MENU_ID]: 1, +}; + +/** + * Wait for accessibility service to shut down. We consider it shut down when + * an "a11y-init-or-shutdown" event is received with a value of "0". + */ +function waitForAccessibilityShutdown() { + return new Promise(resolve => { + if (!Services.appinfo.accessibilityEnabled) { + resolve(); + return; + } + + const observe = (subject, topic, data) => { + if (data === "0") { + Services.obs.removeObserver(observe, "a11y-init-or-shutdown"); + // Sanity check + ok( + !Services.appinfo.accessibilityEnabled, + "Accessibility disabled in this process" + ); + resolve(); + } + }; + // This event is coming from Gecko accessibility module when the + // accessibility service is shutdown or initialzied. We attempt to shutdown + // accessibility service naturally if there are no more XPCOM references to + // a11y related objects (after GC/CC). + Services.obs.addObserver(observe, "a11y-init-or-shutdown"); + + // Force garbage collection. + SpecialPowers.gc(); + SpecialPowers.forceShrinkingGC(); + SpecialPowers.forceCC(); + }); +} + +/** + * Ensure that accessibility is completely shutdown. + */ +async function shutdownAccessibility(browser) { + await waitForAccessibilityShutdown(); + await SpecialPowers.spawn(browser, [], waitForAccessibilityShutdown); +} + +registerCleanupFunction(async () => { + info("Cleaning up..."); + Services.prefs.clearUserPref("devtools.accessibility.enabled"); +}); + +const EXPANDABLE_PROPS = ["actions", "states", "attributes"]; + +/** + * Add a new test tab in the browser and load the given url. + * @param {String} url + * The url to be loaded in the new tab + * @return a promise that resolves to the tab object when + * the url is loaded + */ +async function addTestTab(url) { + info("Adding a new test tab with URL: '" + url + "'"); + + const tab = await addTab(url); + const panel = await initAccessibilityPanel(tab); + const win = panel.panelWin; + const doc = win.document; + const store = win.view.store; + + win.focus(); + + await waitUntilState( + store, + state => + state.accessibles.size === 1 && + state.details.accessible && + state.details.accessible.role === "document" + ); + + return { + tab, + browser: tab.linkedBrowser, + panel, + win, + toolbox: panel._toolbox, + doc, + store, + }; +} + +/** + * Open the Accessibility panel for the given tab. + * + * @param {Element} tab + * Optional tab element for which you want open the Accessibility panel. + * The default tab is taken from the global variable |tab|. + * @return a promise that is resolved once the panel is open. + */ +async function initAccessibilityPanel(tab = gBrowser.selectedTab) { + const toolbox = await gDevTools.showToolboxForTab(tab, { + toolId: "accessibility", + }); + return toolbox.getCurrentPanel(); +} + +/** + * Compare text within the list of potential badges rendered for accessibility + * tree row when its accessible object has accessibility failures. + * @param {DOMNode} badges + * Container element that contains badge elements. + * @param {Array|null} expected + * List of expected badge labels for failing accessibility checks. + */ +function compareBadges(badges, expected = []) { + const badgeEls = badges ? [...badges.querySelectorAll(".badge")] : []; + return ( + badgeEls.length === expected.length && + badgeEls.every((badge, i) => badge.textContent === expected[i]) + ); +} + +/** + * Find an ancestor that is scrolled for a given DOMNode. + * + * @param {DOMNode} node + * DOMNode that to find an ancestor for that is scrolled. + */ +function closestScrolledParent(node) { + if (node == null) { + return null; + } + + if (node.scrollHeight > node.clientHeight) { + return node; + } + + return closestScrolledParent(node.parentNode); +} + +/** + * Check if a given element is visible to the user and is not scrolled off + * because of the overflow. + * + * @param {Element} element + * Element to be checked whether it is visible and is not scrolled off. + * + * @returns {Boolean} + * True if the element is visible. + */ +function isVisible(element) { + const { top, bottom } = element.getBoundingClientRect(); + const scrolledParent = closestScrolledParent(element.parentNode); + const scrolledParentRect = scrolledParent + ? scrolledParent.getBoundingClientRect() + : null; + return ( + !scrolledParent || + (top >= scrolledParentRect.top && bottom <= scrolledParentRect.bottom) + ); +} + +/** + * Check selected styling and visibility for a given row in the accessibility + * tree. + * @param {DOMNode} row + * DOMNode for a given accessibility row. + * @param {Boolean} expected + * Expected selected state. + * + * @returns {Boolean} + * True if visibility and styling matches expected selected state. + */ +function checkSelected(row, expected) { + if (!expected) { + return true; + } + + if (row.classList.contains("selected") !== expected) { + return false; + } + + return isVisible(row); +} + +/** + * Check level for a given row in the accessibility tree. + * @param {DOMNode} row + * DOMNode for a given accessibility row. + * @param {Boolean} expected + * Expected row level (aria-level). + * + * @returns {Boolean} + * True if the aria-level for the row is as expected. + */ +function checkLevel(row, expected) { + if (!expected) { + return true; + } + + return parseInt(row.getAttribute("aria-level"), 10) === expected; +} + +/** + * Check the state of the accessibility tree. + * @param {document} doc panel documnent. + * @param {Array} expected an array that represents an expected row list. + */ +async function checkTreeState(doc, expected) { + info("Checking tree state."); + const hasExpectedStructure = await BrowserTestUtils.waitForCondition(() => { + const rows = [...doc.querySelectorAll(".treeRow")]; + if (rows.length !== expected.length) { + return false; + } + + return rows.every((row, i) => { + const { role, name, badges, selected, level } = expected[i]; + return ( + row.querySelector(".treeLabelCell").textContent === role && + row.querySelector(".treeValueCell").textContent === name && + compareBadges(row.querySelector(".badges"), badges) && + checkSelected(row, selected) && + checkLevel(row, level) + ); + }); + }, "Wait for the right tree update."); + + ok(hasExpectedStructure, "Tree structure is correct."); +} + +/** + * Check if relations object matches what is expected. Note: targets are matched by their + * name and role. + * @param {Object} relations Relations to test. + * @param {Object} expected Expected relations. + * @return {Boolean} True if relation types and their targers match what is + * expected. + */ +function relationsMatch(relations, expected) { + for (const relationType in expected) { + let expTargets = expected[relationType]; + expTargets = Array.isArray(expTargets) ? expTargets : [expTargets]; + + let targets = relations ? relations[relationType] : []; + targets = Array.isArray(targets) ? targets : [targets]; + + for (const index in expTargets) { + if (!targets[index]) { + return false; + } + if ( + expTargets[index].name !== targets[index].name || + expTargets[index].role !== targets[index].role + ) { + return false; + } + } + } + + return true; +} + +/** + * When comparing numerical values (for example contrast), we only care about the 2 + * decimal points. + * @param {String} _ + * Key of the property that is parsed. + * @param {Any} value + * Value of the property that is parsed. + * @return {Any} + * Newly formatted value in case of the numeric value. + */ +function parseNumReplacer(_, value) { + if (typeof value === "number") { + return value.toFixed(2); + } + + return value; +} + +/** + * Check the state of the accessibility sidebar audit(checks). + * @param {Object} store React store for the panel (includes store for + * the audit). + * @param {Object} expectedState Expected state of the sidebar audit(checks). + */ +async function checkAuditState(store, expectedState) { + info("Checking audit state."); + await waitUntilState(store, ({ details }) => { + const { audit } = details; + + for (const key in expectedState) { + const expected = expectedState[key]; + if (expected && typeof expected === "object") { + if ( + JSON.stringify(audit[key], parseNumReplacer) !== + JSON.stringify(expected, parseNumReplacer) + ) { + return false; + } + } else if (audit && audit[key] !== expected) { + return false; + } + } + + ok(true, "Audit state is correct."); + return true; + }); +} + +/** + * Check the state of the accessibility sidebar. + * @param {Object} store React store for the panel (includes store for + * the sidebar). + * @param {Object} expectedState Expected state of the sidebar. + */ +async function checkSidebarState(store, expectedState) { + info("Checking sidebar state."); + await waitUntilState(store, ({ details }) => { + for (const key of ORDERED_PROPS) { + const expected = expectedState[key]; + if (expected === undefined) { + continue; + } + + if (key === "relations") { + if (!relationsMatch(details.relations, expected)) { + return false; + } + } else if (EXPANDABLE_PROPS.includes(key)) { + if ( + JSON.stringify(details.accessible[key]) !== JSON.stringify(expected) + ) { + return false; + } + } else if (details.accessible && details.accessible[key] !== expected) { + return false; + } + } + + ok(true, "Sidebar state is correct."); + return true; + }); +} + +/** + * Check the state of the accessibility related prefs. + * @param {Document} doc + * accessibility inspector panel document. + * @param {Object} toolbarPrefValues + * Expected state of the panel prefs as well as the redux state that + * keeps track of it. Includes: + * - SCROLL_INTO_VIEW (devtools.accessibility.scroll-into-view) + * @param {Object} store + * React store for the panel (includes store for the sidebar). + */ +async function checkToolbarPrefsState(doc, toolbarPrefValues, store) { + info("Checking toolbar prefs state."); + const [hasExpectedStructure] = await Promise.all([ + // Check that appropriate preferences are set as expected. + BrowserTestUtils.waitForCondition(() => { + return Object.keys(toolbarPrefValues).every( + name => + Services.prefs.getBoolPref(PREF_KEYS[name], false) === + toolbarPrefValues[name] + ); + }, "Wait for the right prefs state."), + // Check that ui state is set as expected. + waitUntilState(store, ({ ui }) => { + for (const name in toolbarPrefValues) { + if (ui[name] !== toolbarPrefValues[name]) { + return false; + } + } + + ok(true, "UI pref state is correct."); + return true; + }), + ]); + ok(hasExpectedStructure, "Prefs state is correct."); +} + +/** + * Check the state of the accessibility checks toolbar. + * @param {Object} store + * React store for the panel (includes store for the sidebar). + * @param {Object} activeToolbarFilters + * Expected active state of the filters in the toolbar. + */ +async function checkToolbarState(doc, activeToolbarFilters) { + info("Checking toolbar state."); + const hasExpectedStructure = await BrowserTestUtils.waitForCondition( + () => + [ + ...doc.querySelectorAll("#accessibility-tree-filters-menu .command"), + ].every( + (filter, i) => + (activeToolbarFilters[i] ? "true" : null) === + filter.getAttribute("aria-checked") + ), + "Wait for the right toolbar state." + ); + + ok(hasExpectedStructure, "Toolbar state is correct."); +} + +/** + * Check the state of the simulation button and menu components. + * @param {Object} doc Panel document. + * @param {Object} expected Expected states of the simulation components: + * menuVisible, buttonActive, checkedOptionIndices (Optional) + */ +async function checkSimulationState(doc, expected) { + const { buttonActive, checkedOptionIndices } = expected; + const simulationMenuOptions = doc + .querySelector(SIMULATION_MENU_BUTTON_ID + "-menu") + .querySelectorAll(".menuitem"); + + // Check simulation menu button state + is( + doc.querySelector(SIMULATION_MENU_BUTTON_ID).className, + `devtools-button toolbar-menu-button simulation${ + buttonActive ? " active" : "" + }`, + `Simulation menu button contains ${buttonActive ? "active" : "base"} class.` + ); + + // Check simulation menu options states, if specified + if (checkedOptionIndices) { + simulationMenuOptions.forEach((menuListItem, index) => { + const isChecked = checkedOptionIndices.includes(index); + const button = menuListItem.firstChild; + + is( + button.getAttribute("aria-checked"), + isChecked ? "true" : null, + `Simulation option ${index} is ${isChecked ? "" : "not "}selected.` + ); + }); + } +} + +/** + * Focus accessibility properties tree in the a11y inspector sidebar. If focused for the + * first time, the tree will select first rendered node as defult selection for keyboard + * purposes. + * + * @param {Document} doc accessibility inspector panel document. + */ +async function focusAccessibleProperties(doc) { + const tree = doc.querySelector(".tree"); + if (doc.activeElement !== tree) { + tree.focus(); + await BrowserTestUtils.waitForCondition( + () => tree.querySelector(".node.focused"), + "Tree selected." + ); + } +} + +/** + * Select accessibility property in the sidebar. + * @param {Document} doc accessibility inspector panel document. + * @param {String} id id of the property to be selected. + * @return {DOMNode} Node that corresponds to the selected accessibility property. + */ +async function selectProperty(doc, id) { + const win = doc.defaultView; + let selected = false; + let node; + + await focusAccessibleProperties(doc); + await BrowserTestUtils.waitForCondition(() => { + node = doc.getElementById(`${id}`); + if (node) { + if (selected) { + return node.firstChild.classList.contains("focused"); + } + + AccessibilityUtils.setEnv({ + // Keyboard navigation is handled on the container level using arrow + // keys. + nonNegativeTabIndexRule: false, + }); + EventUtils.sendMouseEvent({ type: "click" }, node, win); + AccessibilityUtils.resetEnv(); + selected = true; + } else { + const tree = doc.querySelector(".tree"); + tree.scrollTop = parseFloat(win.getComputedStyle(tree).height); + } + + return false; + }); + + return node; +} + +/** + * Select tree row. + * @param {document} doc panel documnent. + * @param {Number} rowNumber number of the row/tree node to be selected. + */ +function selectRow(doc, rowNumber) { + info(`Selecting row ${rowNumber}.`); + AccessibilityUtils.setEnv({ + // Keyboard navigation is handled on the container level using arrow keys. + nonNegativeTabIndexRule: false, + }); + EventUtils.sendMouseEvent( + { type: "click" }, + doc.querySelectorAll(".treeRow")[rowNumber], + doc.defaultView + ); + AccessibilityUtils.resetEnv(); +} + +/** + * Toggle an expandable tree row. + * @param {document} doc panel documnent. + * @param {Number} rowNumber number of the row/tree node to be toggled. + */ +async function toggleRow(doc, rowNumber) { + const win = doc.defaultView; + const row = doc.querySelectorAll(".treeRow")[rowNumber]; + const twisty = row.querySelector(".theme-twisty"); + const expected = !twisty.classList.contains("open"); + + info(`${expected ? "Expanding" : "Collapsing"} row ${rowNumber}.`); + + AccessibilityUtils.setEnv({ + // We intentionally remove the twisty from the accessibility tree in the + // TreeView component and handle keyboard navigation using the arrow keys. + mustHaveAccessibleRule: false, + }); + EventUtils.sendMouseEvent({ type: "click" }, twisty, win); + AccessibilityUtils.resetEnv(); + await BrowserTestUtils.waitForCondition( + () => + !twisty.classList.contains("devtools-throbber") && + expected === twisty.classList.contains("open"), + "Twisty updated." + ); +} + +/** + * Toggle a specific menu item based on its index in the menu. + * @param {document} toolboxDoc + * toolbox document. + * @param {document} doc + * panel document. + * @param {String} menuId + * The id of the menu (menuId passed to the MenuButton component) + * @param {Number} menuItemIndex + * index of the menu item to be toggled. + */ +async function toggleMenuItem(doc, toolboxDoc, menuId, menuItemIndex) { + const toolboxWin = toolboxDoc.defaultView; + const panelWin = doc.defaultView; + + const menuButton = doc.querySelectorAll(".toolbar-menu-button")[ + MENU_INDEXES[menuId] + ]; + ok(menuButton, "Expected menu button"); + + const menuEl = toolboxDoc.getElementById(menuId); + const menuItem = menuEl.querySelectorAll(".command")[menuItemIndex]; + ok(menuItem, "Expected menu item"); + + const expected = + menuItem.getAttribute("aria-checked") === "true" ? null : "true"; + + // Make the menu visible first. + const onPopupShown = new Promise(r => + toolboxDoc.addEventListener("popupshown", r, { once: true }) + ); + EventUtils.synthesizeMouseAtCenter(menuButton, {}, panelWin); + await onPopupShown; + const boundingRect = menuItem.getBoundingClientRect(); + ok( + boundingRect.width > 0 && boundingRect.height > 0, + "Menu item is visible." + ); + + EventUtils.synthesizeMouseAtCenter(menuItem, {}, toolboxWin); + await BrowserTestUtils.waitForCondition( + () => expected === menuItem.getAttribute("aria-checked"), + "Menu item updated." + ); +} + +async function openSimulationMenu(doc) { + doc.querySelector(SIMULATION_MENU_BUTTON_ID).click(); + + await BrowserTestUtils.waitForCondition(() => + doc + .querySelector(SIMULATION_MENU_BUTTON_ID + "-menu") + .classList.contains("tooltip-visible") + ); +} + +async function toggleSimulationOption(doc, optionIndex) { + const simulationMenu = doc.querySelector(SIMULATION_MENU_BUTTON_ID + "-menu"); + simulationMenu.querySelectorAll(".menuitem")[optionIndex].firstChild.click(); + + await BrowserTestUtils.waitForCondition( + () => !simulationMenu.classList.contains("tooltip-visible") + ); +} + +async function findAccessibleFor( + { + toolbox: { target }, + panel: { + accessibilityProxy: { + accessibilityFront: { accessibleWalkerFront }, + }, + }, + }, + selector +) { + const domWalker = (await target.getFront("inspector")).walker; + const node = await domWalker.querySelector(domWalker.rootNode, selector); + return accessibleWalkerFront.getAccessibleFor(node); +} + +async function selectAccessibleForNode(env, selector) { + const { panel, win } = env; + const front = await findAccessibleFor(env, selector); + const { EVENTS } = win; + const onSelected = win.once(EVENTS.NEW_ACCESSIBLE_FRONT_SELECTED); + panel.selectAccessible(front); + await onSelected; +} + +/** + * Iterate over setups/tests structure and test the state of the + * accessibility panel. + * @param {JSON} tests + * test data that has the format of: + * { + * desc {String} description for better logging + * setup {Function} An optional setup that needs to be + * performed before the state of the + * tree and the sidebar can be checked + * expected {JSON} An expected states for parts of + * accessibility panel: + * - tree: state of the accessibility tree widget + * - sidebar: state of the accessibility panel sidebar + * - audit: state of the audit redux state of the + * panel + * - toolbarPrefValues: state of the accessibility panel + * toolbar prefs and corresponding user + * preferences. + * - activeToolbarFilters: state of the accessibility panel + * toolbar filters. + * } + * @param {Object} env + * contains all relevant environment objects (same structure as the + * return value of 'addTestTab' funciton) + */ +async function runA11yPanelTests(tests, env) { + for (const { desc, setup, expected } of tests) { + info(desc); + + if (setup) { + await setup(env); + } + + const { + tree, + sidebar, + audit, + toolbarPrefValues, + activeToolbarFilters, + simulation, + } = expected; + if (tree) { + await checkTreeState(env.doc, tree); + } + + if (sidebar) { + await checkSidebarState(env.store, sidebar); + } + + if (activeToolbarFilters) { + await checkToolbarState(env.doc, activeToolbarFilters); + } + + if (toolbarPrefValues) { + await checkToolbarPrefsState(env.doc, toolbarPrefValues, env.store); + } + + if (typeof audit !== "undefined") { + await checkAuditState(env.store, audit); + } + + if (simulation) { + await checkSimulationState(env.doc, simulation); + } + } +} + +/** + * Build a valid URL from an HTML snippet. + * @param {String} uri HTML snippet + * @param {Object} options options for the test + * @return {String} built URL + */ +function buildURL(uri, options = {}) { + if (options.remoteIframe) { + const srcURL = new URL(`http://example.net/document-builder.sjs`); + srcURL.searchParams.append( + "html", + ` + + + Accessibility Panel Test (OOP) + + ${uri} + ` + ); + uri = `