Bug 1625482 [wpt PR 22496] - [ScrollTimeline] Do not show scrollbar to bypass flakine...
[gecko.git] / testing / marionette / accessibility.js
blobeb1354fbec48ef5c4ed26a84bced7dda0f1d9b94
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
3  * You can obtain one at http://mozilla.org/MPL/2.0/. */
5 "use strict";
7 const { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
8 const { XPCOMUtils } = ChromeUtils.import(
9   "resource://gre/modules/XPCOMUtils.jsm"
12 const { ElementNotAccessibleError } = ChromeUtils.import(
13   "chrome://marionette/content/error.js"
15 const { Log } = ChromeUtils.import("chrome://marionette/content/log.js");
17 XPCOMUtils.defineLazyGetter(this, "logger", Log.get);
19 XPCOMUtils.defineLazyGetter(this, "service", () => {
20   try {
21     return Cc["@mozilla.org/accessibilityService;1"].getService(
22       Ci.nsIAccessibilityService
23     );
24   } catch (e) {
25     logger.warn("Accessibility module is not present");
26     return undefined;
27   }
28 });
30 this.EXPORTED_SYMBOLS = ["accessibility"];
32 /** @namespace */
33 this.accessibility = {
34   get service() {
35     return service;
36   },
39 /**
40  * Accessible states used to check element"s state from the accessiblity API
41  * perspective.
42  *
43  * Note: if gecko is built with --disable-accessibility, the interfaces
44  * are not defined. This is why we use getters instead to be able to use
45  * these statically.
46  */
47 accessibility.State = {
48   get Unavailable() {
49     return Ci.nsIAccessibleStates.STATE_UNAVAILABLE;
50   },
51   get Focusable() {
52     return Ci.nsIAccessibleStates.STATE_FOCUSABLE;
53   },
54   get Selectable() {
55     return Ci.nsIAccessibleStates.STATE_SELECTABLE;
56   },
57   get Selected() {
58     return Ci.nsIAccessibleStates.STATE_SELECTED;
59   },
62 /**
63  * Accessible object roles that support some action.
64  */
65 accessibility.ActionableRoles = new Set([
66   "checkbutton",
67   "check menu item",
68   "check rich option",
69   "combobox",
70   "combobox option",
71   "entry",
72   "key",
73   "link",
74   "listbox option",
75   "listbox rich option",
76   "menuitem",
77   "option",
78   "outlineitem",
79   "pagetab",
80   "pushbutton",
81   "radiobutton",
82   "radio menu item",
83   "rowheader",
84   "slider",
85   "spinbutton",
86   "switch",
87 ]);
89 /**
90  * Factory function that constructs a new {@code accessibility.Checks}
91  * object with enforced strictness or not.
92  */
93 accessibility.get = function(strict = false) {
94   return new accessibility.Checks(!!strict);
97 /**
98  * Component responsible for interacting with platform accessibility
99  * API.
101  * Its methods serve as wrappers for testing content and chrome
102  * accessibility as well as accessibility of user interactions.
103  */
104 accessibility.Checks = class {
105   /**
106    * @param {boolean} strict
107    *     Flag indicating whether the accessibility issue should be logged
108    *     or cause an error to be thrown.  Default is to log to stdout.
109    */
110   constructor(strict) {
111     this.strict = strict;
112   }
114   /**
115    * Get an accessible object for an element.
116    *
117    * @param {DOMElement|XULElement} element
118    *     Element to get the accessible object for.
119    * @param {boolean=} mustHaveAccessible
120    *     Flag indicating that the element must have an accessible object.
121    *     Defaults to not require this.
122    *
123    * @return {Promise.<nsIAccessible>}
124    *     Promise with an accessibility object for the given element.
125    */
126   getAccessible(element, mustHaveAccessible = false) {
127     if (!this.strict) {
128       return Promise.resolve();
129     }
131     return new Promise((resolve, reject) => {
132       if (!accessibility.service) {
133         reject();
134         return;
135       }
137       // First, check if accessibility is ready.
138       let docAcc = accessibility.service.getAccessibleFor(
139         element.ownerDocument
140       );
141       let state = {};
142       docAcc.getState(state, {});
143       if ((state.value & Ci.nsIAccessibleStates.STATE_BUSY) == 0) {
144         // Accessibility is ready, resolve immediately.
145         let acc = accessibility.service.getAccessibleFor(element);
146         if (mustHaveAccessible && !acc) {
147           reject();
148         } else {
149           resolve(acc);
150         }
151         return;
152       }
153       // Accessibility for the doc is busy, so wait for the state to change.
154       let eventObserver = {
155         observe(subject, topic) {
156           if (topic !== "accessible-event") {
157             return;
158           }
160           // If event type does not match expected type, skip the event.
161           let event = subject.QueryInterface(Ci.nsIAccessibleEvent);
162           if (event.eventType !== Ci.nsIAccessibleEvent.EVENT_STATE_CHANGE) {
163             return;
164           }
166           // If event's accessible does not match expected accessible,
167           // skip the event.
168           if (event.accessible !== docAcc) {
169             return;
170           }
172           Services.obs.removeObserver(this, "accessible-event");
173           let acc = accessibility.service.getAccessibleFor(element);
174           if (mustHaveAccessible && !acc) {
175             reject();
176           } else {
177             resolve(acc);
178           }
179         },
180       };
181       Services.obs.addObserver(eventObserver, "accessible-event");
182     }).catch(() =>
183       this.error("Element does not have an accessible object", element)
184     );
185   }
187   /**
188    * Test if the accessible has a role that supports some arbitrary
189    * action.
190    *
191    * @param {nsIAccessible} accessible
192    *     Accessible object.
193    *
194    * @return {boolean}
195    *     True if an actionable role is found on the accessible, false
196    *     otherwise.
197    */
198   isActionableRole(accessible) {
199     return accessibility.ActionableRoles.has(
200       accessibility.service.getStringRole(accessible.role)
201     );
202   }
204   /**
205    * Test if an accessible has at least one action that it supports.
206    *
207    * @param {nsIAccessible} accessible
208    *     Accessible object.
209    *
210    * @return {boolean}
211    *     True if the accessible has at least one supported action,
212    *     false otherwise.
213    */
214   hasActionCount(accessible) {
215     return accessible.actionCount > 0;
216   }
218   /**
219    * Test if an accessible has a valid name.
220    *
221    * @param {nsIAccessible} accessible
222    *     Accessible object.
223    *
224    * @return {boolean}
225    *     True if the accessible has a non-empty valid name, or false if
226    *     this is not the case.
227    */
228   hasValidName(accessible) {
229     return accessible.name && accessible.name.trim();
230   }
232   /**
233    * Test if an accessible has a {@code hidden} attribute.
234    *
235    * @param {nsIAccessible} accessible
236    *     Accessible object.
237    *
238    * @return {boolean}
239    *     True if the accessible object has a {@code hidden} attribute,
240    *     false otherwise.
241    */
242   hasHiddenAttribute(accessible) {
243     let hidden = false;
244     try {
245       hidden = accessible.attributes.getStringProperty("hidden");
246     } catch (e) {}
247     // if the property is missing, error will be thrown
248     return hidden && hidden === "true";
249   }
251   /**
252    * Verify if an accessible has a given state.
253    * Test if an accessible has a given state.
254    *
255    * @param {nsIAccessible} accessible
256    *     Accessible object to test.
257    * @param {number} stateToMatch
258    *     State to match.
259    *
260    * @return {boolean}
261    *     True if |accessible| has |stateToMatch|, false otherwise.
262    */
263   matchState(accessible, stateToMatch) {
264     let state = {};
265     accessible.getState(state, {});
266     return !!(state.value & stateToMatch);
267   }
269   /**
270    * Test if an accessible is hidden from the user.
271    *
272    * @param {nsIAccessible} accessible
273    *     Accessible object.
274    *
275    * @return {boolean}
276    *     True if element is hidden from user, false otherwise.
277    */
278   isHidden(accessible) {
279     if (!accessible) {
280       return true;
281     }
283     while (accessible) {
284       if (this.hasHiddenAttribute(accessible)) {
285         return true;
286       }
287       accessible = accessible.parent;
288     }
289     return false;
290   }
292   /**
293    * Test if the element's visible state corresponds to its accessibility
294    * API visibility.
295    *
296    * @param {nsIAccessible} accessible
297    *     Accessible object.
298    * @param {DOMElement|XULElement} element
299    *     Element associated with |accessible|.
300    * @param {boolean} visible
301    *     Visibility state of |element|.
302    *
303    * @throws ElementNotAccessibleError
304    *     If |element|'s visibility state does not correspond to
305    *     |accessible|'s.
306    */
307   assertVisible(accessible, element, visible) {
308     let hiddenAccessibility = this.isHidden(accessible);
310     let message;
311     if (visible && hiddenAccessibility) {
312       message =
313         "Element is not currently visible via the accessibility API " +
314         "and may not be manipulated by it";
315     } else if (!visible && !hiddenAccessibility) {
316       message =
317         "Element is currently only visible via the accessibility API " +
318         "and can be manipulated by it";
319     }
320     this.error(message, element);
321   }
323   /**
324    * Test if the element's unavailable accessibility state matches the
325    * enabled state.
326    *
327    * @param {nsIAccessible} accessible
328    *     Accessible object.
329    * @param {DOMElement|XULElement} element
330    *     Element associated with |accessible|.
331    * @param {boolean} enabled
332    *     Enabled state of |element|.
333    *
334    * @throws ElementNotAccessibleError
335    *     If |element|'s enabled state does not match |accessible|'s.
336    */
337   assertEnabled(accessible, element, enabled) {
338     if (!accessible) {
339       return;
340     }
342     let win = element.ownerGlobal;
343     let disabledAccessibility = this.matchState(
344       accessible,
345       accessibility.State.Unavailable
346     );
347     let explorable =
348       win.getComputedStyle(element).getPropertyValue("pointer-events") !==
349       "none";
351     let message;
352     if (!explorable && !disabledAccessibility) {
353       message =
354         "Element is enabled but is not explorable via the " +
355         "accessibility API";
356     } else if (enabled && disabledAccessibility) {
357       message = "Element is enabled but disabled via the accessibility API";
358     } else if (!enabled && !disabledAccessibility) {
359       message = "Element is disabled but enabled via the accessibility API";
360     }
361     this.error(message, element);
362   }
364   /**
365    * Test if it is possible to activate an element with the accessibility
366    * API.
367    *
368    * @param {nsIAccessible} accessible
369    *     Accessible object.
370    * @param {DOMElement|XULElement} element
371    *     Element associated with |accessible|.
372    *
373    * @throws ElementNotAccessibleError
374    *     If it is impossible to activate |element| with |accessible|.
375    */
376   assertActionable(accessible, element) {
377     if (!accessible) {
378       return;
379     }
381     let message;
382     if (!this.hasActionCount(accessible)) {
383       message = "Element does not support any accessible actions";
384     } else if (!this.isActionableRole(accessible)) {
385       message =
386         "Element does not have a correct accessibility role " +
387         "and may not be manipulated via the accessibility API";
388     } else if (!this.hasValidName(accessible)) {
389       message = "Element is missing an accessible name";
390     } else if (!this.matchState(accessible, accessibility.State.Focusable)) {
391       message = "Element is not focusable via the accessibility API";
392     }
394     this.error(message, element);
395   }
397   /**
398    * Test that an element's selected state corresponds to its
399    * accessibility API selected state.
400    *
401    * @param {nsIAccessible} accessible
402    *     Accessible object.
403    * @param {DOMElement|XULElement}
404    *     Element associated with |accessible|.
405    * @param {boolean} selected
406    *     The |element|s selected state.
407    *
408    * @throws ElementNotAccessibleError
409    *     If |element|'s selected state does not correspond to
410    *     |accessible|'s.
411    */
412   assertSelected(accessible, element, selected) {
413     if (!accessible) {
414       return;
415     }
417     // element is not selectable via the accessibility API
418     if (!this.matchState(accessible, accessibility.State.Selectable)) {
419       return;
420     }
422     let selectedAccessibility = this.matchState(
423       accessible,
424       accessibility.State.Selected
425     );
427     let message;
428     if (selected && !selectedAccessibility) {
429       message =
430         "Element is selected but not selected via the accessibility API";
431     } else if (!selected && selectedAccessibility) {
432       message =
433         "Element is not selected but selected via the accessibility API";
434     }
435     this.error(message, element);
436   }
438   /**
439    * Throw an error if strict accessibility checks are enforced and log
440    * the error to the log.
441    *
442    * @param {string} message
443    * @param {DOMElement|XULElement} element
444    *     Element that caused an error.
445    *
446    * @throws ElementNotAccessibleError
447    *     If |strict| is true.
448    */
449   error(message, element) {
450     if (!message || !this.strict) {
451       return;
452     }
453     if (element) {
454       let { id, tagName, className } = element;
455       message += `: id: ${id}, tagName: ${tagName}, className: ${className}`;
456     }
458     throw new ElementNotAccessibleError(message);
459   }