Bug 1890689 accumulate input in LargerReceiverBlockSizeThanDesiredBuffering GTest...
[gecko.git] / remote / shared / DOM.sys.mjs
blob73e89148944415dfb525f44c8cf09ec78ccf92fa
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 const lazy = {};
7 ChromeUtils.defineESModuleGetters(lazy, {
8   atom: "chrome://remote/content/marionette/atom.sys.mjs",
9   error: "chrome://remote/content/shared/webdriver/Errors.sys.mjs",
10   PollPromise: "chrome://remote/content/marionette/sync.sys.mjs",
11 });
13 const ORDERED_NODE_ITERATOR_TYPE = 5;
14 const FIRST_ORDERED_NODE_TYPE = 9;
16 const DOCUMENT_FRAGMENT_NODE = 11;
17 const ELEMENT_NODE = 1;
19 const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
21 /** XUL elements that support checked property. */
22 const XUL_CHECKED_ELS = new Set(["button", "checkbox", "toolbarbutton"]);
24 /** XUL elements that support selected property. */
25 const XUL_SELECTED_ELS = new Set([
26   "menu",
27   "menuitem",
28   "menuseparator",
29   "radio",
30   "richlistitem",
31   "tab",
32 ]);
34 /**
35  * This module provides shared functionality for dealing with DOM-
36  * and web elements in Marionette.
37  *
38  * A web element is an abstraction used to identify an element when it
39  * is transported across the protocol, between remote- and local ends.
40  *
41  * Each element has an associated web element reference (a UUID) that
42  * uniquely identifies the the element across all browsing contexts. The
43  * web element reference for every element representing the same element
44  * is the same.
45  *
46  * @namespace
47  */
48 export const dom = {};
50 dom.Strategy = {
51   ClassName: "class name",
52   Selector: "css selector",
53   ID: "id",
54   Name: "name",
55   LinkText: "link text",
56   PartialLinkText: "partial link text",
57   TagName: "tag name",
58   XPath: "xpath",
61 /**
62  * Find a single element or a collection of elements starting at the
63  * document root or a given node.
64  *
65  * If |timeout| is above 0, an implicit search technique is used.
66  * This will wait for the duration of <var>timeout</var> for the
67  * element to appear in the DOM.
68  *
69  * See the {@link dom.Strategy} enum for a full list of supported
70  * search strategies that can be passed to <var>strategy</var>.
71  *
72  * @param {Object<string, WindowProxy>} container
73  *     Window object.
74  * @param {string} strategy
75  *     Search strategy whereby to locate the element(s).
76  * @param {string} selector
77  *     Selector search pattern.  The selector must be compatible with
78  *     the chosen search <var>strategy</var>.
79  * @param {object=} options
80  * @param {boolean=} options.all
81  *     If true, a multi-element search selector is used and a sequence of
82  *     elements will be returned, otherwise a single element. Defaults to false.
83  * @param {Element=} options.startNode
84  *     Element to use as the root of the search.
85  * @param {number=} options.timeout
86  *     Duration to wait before timing out the search.  If <code>all</code>
87  *     is false, a {@link NoSuchElementError} is thrown if unable to
88  *     find the element within the timeout duration.
89  *
90  * @returns {Promise.<(Element|Array.<Element>)>}
91  *     Single element or a sequence of elements.
92  *
93  * @throws InvalidSelectorError
94  *     If <var>strategy</var> is unknown.
95  * @throws InvalidSelectorError
96  *     If <var>selector</var> is malformed.
97  * @throws NoSuchElementError
98  *     If a single element is requested, this error will throw if the
99  *     element is not found.
100  */
101 dom.find = function (container, strategy, selector, options = {}) {
102   const { all = false, startNode, timeout = 0 } = options;
104   let searchFn;
105   if (all) {
106     searchFn = findElements.bind(this);
107   } else {
108     searchFn = findElement.bind(this);
109   }
111   return new Promise((resolve, reject) => {
112     let findElements = new lazy.PollPromise(
113       async (resolve, reject) => {
114         try {
115           let res = await find_(container, strategy, selector, searchFn, {
116             all,
117             startNode,
118           });
119           if (res.length) {
120             resolve(Array.from(res));
121           } else {
122             reject([]);
123           }
124         } catch (e) {
125           reject(e);
126         }
127       },
128       { timeout }
129     );
131     findElements.then(foundEls => {
132       // the following code ought to be moved into findElement
133       // and findElements when bug 1254486 is addressed
134       if (!all && (!foundEls || !foundEls.length)) {
135         let msg = `Unable to locate element: ${selector}`;
136         reject(new lazy.error.NoSuchElementError(msg));
137       }
139       if (all) {
140         resolve(foundEls);
141       }
142       resolve(foundEls[0]);
143     }, reject);
144   });
147 async function find_(
148   container,
149   strategy,
150   selector,
151   searchFn,
152   { startNode = null, all = false } = {}
153 ) {
154   let rootNode;
156   if (dom.isShadowRoot(startNode)) {
157     rootNode = startNode.ownerDocument;
158   } else {
159     rootNode = container.frame.document;
160   }
162   if (!startNode) {
163     startNode = rootNode;
164   }
166   let res;
167   try {
168     res = await searchFn(strategy, selector, rootNode, startNode);
169   } catch (e) {
170     throw new lazy.error.InvalidSelectorError(
171       `Given ${strategy} expression "${selector}" is invalid: ${e}`
172     );
173   }
175   if (res) {
176     if (all) {
177       return res;
178     }
179     return [res];
180   }
181   return [];
185  * Find a single element by XPath expression.
187  * @param {Document} document
188  *     Document root.
189  * @param {Element} startNode
190  *     Where in the DOM hiearchy to begin searching.
191  * @param {string} expression
192  *     XPath search expression.
194  * @returns {Node}
195  *     First element matching <var>expression</var>.
196  */
197 dom.findByXPath = function (document, startNode, expression) {
198   let iter = document.evaluate(
199     expression,
200     startNode,
201     null,
202     FIRST_ORDERED_NODE_TYPE,
203     null
204   );
205   return iter.singleNodeValue;
209  * Find elements by XPath expression.
211  * @param {Document} document
212  *     Document root.
213  * @param {Element} startNode
214  *     Where in the DOM hierarchy to begin searching.
215  * @param {string} expression
216  *     XPath search expression.
218  * @returns {Iterable.<Node>}
219  *     Iterator over nodes matching <var>expression</var>.
220  */
221 dom.findByXPathAll = function* (document, startNode, expression) {
222   let iter = document.evaluate(
223     expression,
224     startNode,
225     null,
226     ORDERED_NODE_ITERATOR_TYPE,
227     null
228   );
229   let el = iter.iterateNext();
230   while (el) {
231     yield el;
232     el = iter.iterateNext();
233   }
237  * Find all hyperlinks descendant of <var>startNode</var> which
238  * link text is <var>linkText</var>.
240  * @param {Element} startNode
241  *     Where in the DOM hierarchy to begin searching.
242  * @param {string} linkText
243  *     Link text to search for.
245  * @returns {Iterable.<HTMLAnchorElement>}
246  *     Sequence of link elements which text is <var>s</var>.
247  */
248 dom.findByLinkText = function (startNode, linkText) {
249   return filterLinks(startNode, async link => {
250     const visibleText = await lazy.atom.getVisibleText(link, link.ownerGlobal);
251     return visibleText.trim() === linkText;
252   });
256  * Find all hyperlinks descendant of <var>startNode</var> which
257  * link text contains <var>linkText</var>.
259  * @param {Element} startNode
260  *     Where in the DOM hierachy to begin searching.
261  * @param {string} linkText
262  *     Link text to search for.
264  * @returns {Iterable.<HTMLAnchorElement>}
265  *     Iterator of link elements which text containins
266  *     <var>linkText</var>.
267  */
268 dom.findByPartialLinkText = function (startNode, linkText) {
269   return filterLinks(startNode, async link => {
270     const visibleText = await lazy.atom.getVisibleText(link, link.ownerGlobal);
272     return visibleText.includes(linkText);
273   });
277  * Filters all hyperlinks that are descendant of <var>startNode</var>
278  * by <var>predicate</var>.
280  * @param {Element} startNode
281  *     Where in the DOM hierarchy to begin searching.
282  * @param {function(HTMLAnchorElement): boolean} predicate
283  *     Function that determines if given link should be included in
284  *     return value or filtered away.
286  * @returns {Array.<HTMLAnchorElement>}
287  *     Array of link elements matching <var>predicate</var>.
288  */
289 async function filterLinks(startNode, predicate) {
290   const links = [];
292   for (const link of getLinks(startNode)) {
293     if (await predicate(link)) {
294       links.push(link);
295     }
296   }
298   return links;
302  * Finds a single element.
304  * @param {dom.Strategy} strategy
305  *     Selector strategy to use.
306  * @param {string} selector
307  *     Selector expression.
308  * @param {Document} document
309  *     Document root.
310  * @param {Element=} startNode
311  *     Optional Element from which to start searching.
313  * @returns {Element}
314  *     Found element.
316  * @throws {InvalidSelectorError}
317  *     If strategy <var>using</var> is not recognised.
318  * @throws {Error}
319  *     If selector expression <var>selector</var> is malformed.
320  */
321 async function findElement(
322   strategy,
323   selector,
324   document,
325   startNode = undefined
326 ) {
327   switch (strategy) {
328     case dom.Strategy.ID: {
329       if (startNode.getElementById) {
330         return startNode.getElementById(selector);
331       }
332       let expr = `.//*[@id="${selector}"]`;
333       return dom.findByXPath(document, startNode, expr);
334     }
336     case dom.Strategy.Name: {
337       if (startNode.getElementsByName) {
338         return startNode.getElementsByName(selector)[0];
339       }
340       let expr = `.//*[@name="${selector}"]`;
341       return dom.findByXPath(document, startNode, expr);
342     }
344     case dom.Strategy.ClassName:
345       return startNode.getElementsByClassName(selector)[0];
347     case dom.Strategy.TagName:
348       return startNode.getElementsByTagName(selector)[0];
350     case dom.Strategy.XPath:
351       return dom.findByXPath(document, startNode, selector);
353     case dom.Strategy.LinkText: {
354       const links = getLinks(startNode);
355       for (const link of links) {
356         const visibleText = await lazy.atom.getVisibleText(
357           link,
358           link.ownerGlobal
359         );
360         if (visibleText.trim() === selector) {
361           return link;
362         }
363       }
364       return undefined;
365     }
367     case dom.Strategy.PartialLinkText: {
368       const links = getLinks(startNode);
369       for (const link of links) {
370         const visibleText = await lazy.atom.getVisibleText(
371           link,
372           link.ownerGlobal
373         );
374         if (visibleText.includes(selector)) {
375           return link;
376         }
377       }
378       return undefined;
379     }
381     case dom.Strategy.Selector:
382       try {
383         return startNode.querySelector(selector);
384       } catch (e) {
385         throw new lazy.error.InvalidSelectorError(
386           `${e.message}: "${selector}"`
387         );
388       }
389   }
391   throw new lazy.error.InvalidSelectorError(`No such strategy: ${strategy}`);
395  * Find multiple elements.
397  * @param {dom.Strategy} strategy
398  *     Selector strategy to use.
399  * @param {string} selector
400  *     Selector expression.
401  * @param {Document} document
402  *     Document root.
403  * @param {Element=} startNode
404  *     Optional Element from which to start searching.
406  * @returns {Array.<Element>}
407  *     Found elements.
409  * @throws {InvalidSelectorError}
410  *     If strategy <var>strategy</var> is not recognised.
411  * @throws {Error}
412  *     If selector expression <var>selector</var> is malformed.
413  */
414 async function findElements(
415   strategy,
416   selector,
417   document,
418   startNode = undefined
419 ) {
420   switch (strategy) {
421     case dom.Strategy.ID:
422       selector = `.//*[@id="${selector}"]`;
424     // fall through
425     case dom.Strategy.XPath:
426       return [...dom.findByXPathAll(document, startNode, selector)];
428     case dom.Strategy.Name:
429       if (startNode.getElementsByName) {
430         return startNode.getElementsByName(selector);
431       }
432       return [
433         ...dom.findByXPathAll(document, startNode, `.//*[@name="${selector}"]`),
434       ];
436     case dom.Strategy.ClassName:
437       return startNode.getElementsByClassName(selector);
439     case dom.Strategy.TagName:
440       return startNode.getElementsByTagName(selector);
442     case dom.Strategy.LinkText:
443       return [...(await dom.findByLinkText(startNode, selector))];
445     case dom.Strategy.PartialLinkText:
446       return [...(await dom.findByPartialLinkText(startNode, selector))];
448     case dom.Strategy.Selector:
449       return startNode.querySelectorAll(selector);
451     default:
452       throw new lazy.error.InvalidSelectorError(
453         `No such strategy: ${strategy}`
454       );
455   }
458 function getLinks(startNode) {
459   // DocumentFragment doesn't have `getElementsByTagName` so using `querySelectorAll`.
460   if (dom.isShadowRoot(startNode)) {
461     return startNode.querySelectorAll("a");
462   }
463   return startNode.getElementsByTagName("a");
467  * Finds the closest parent node of <var>startNode</var> matching a CSS
468  * <var>selector</var> expression.
470  * @param {Node} startNode
471  *     Cycle through <var>startNode</var>'s parent nodes in tree-order
472  *     and return the first match to <var>selector</var>.
473  * @param {string} selector
474  *     CSS selector expression.
476  * @returns {Node=}
477  *     First match to <var>selector</var>, or null if no match was found.
478  */
479 dom.findClosest = function (startNode, selector) {
480   let node = startNode;
481   while (node.parentNode && node.parentNode.nodeType == ELEMENT_NODE) {
482     node = node.parentNode;
483     if (node.matches(selector)) {
484       return node;
485     }
486   }
487   return null;
491  * Determines if <var>obj<var> is an HTML or JS collection.
493  * @param {object} seq
494  *     Type to determine.
496  * @returns {boolean}
497  *     True if <var>seq</va> is a collection.
498  */
499 dom.isCollection = function (seq) {
500   switch (Object.prototype.toString.call(seq)) {
501     case "[object Arguments]":
502     case "[object Array]":
503     case "[object DOMTokenList]":
504     case "[object FileList]":
505     case "[object HTMLAllCollection]":
506     case "[object HTMLCollection]":
507     case "[object HTMLFormControlsCollection]":
508     case "[object HTMLOptionsCollection]":
509     case "[object NodeList]":
510       return true;
512     default:
513       return false;
514   }
518  * Determines if <var>shadowRoot</var> is detached.
520  * A ShadowRoot is detached if its node document is not the active document
521  * or if the element node referred to as its host is stale.
523  * @param {ShadowRoot} shadowRoot
524  *     ShadowRoot to check for detached state.
526  * @returns {boolean}
527  *     True if <var>shadowRoot</var> is detached, false otherwise.
528  */
529 dom.isDetached = function (shadowRoot) {
530   return !shadowRoot.ownerDocument.isActive() || dom.isStale(shadowRoot.host);
534  * Determines if <var>el</var> is stale.
536  * An element is stale if its node document is not the active document
537  * or if it is not connected.
539  * @param {Element} el
540  *     Element to check for staleness.
542  * @returns {boolean}
543  *     True if <var>el</var> is stale, false otherwise.
544  */
545 dom.isStale = function (el) {
546   if (!el.ownerGlobal) {
547     // Without a valid inner window the document is basically closed.
548     return true;
549   }
551   return !el.ownerDocument.isActive() || !el.isConnected;
555  * Determine if <var>el</var> is selected or not.
557  * This operation only makes sense on
558  * <tt>&lt;input type=checkbox&gt;</tt>,
559  * <tt>&lt;input type=radio&gt;</tt>,
560  * and <tt>&gt;option&gt;</tt> elements.
562  * @param {Element} el
563  *     Element to test if selected.
565  * @returns {boolean}
566  *     True if element is selected, false otherwise.
567  */
568 dom.isSelected = function (el) {
569   if (!el) {
570     return false;
571   }
573   if (dom.isXULElement(el)) {
574     if (XUL_CHECKED_ELS.has(el.tagName)) {
575       return el.checked;
576     } else if (XUL_SELECTED_ELS.has(el.tagName)) {
577       return el.selected;
578     }
579   } else if (dom.isDOMElement(el)) {
580     if (el.localName == "input" && ["checkbox", "radio"].includes(el.type)) {
581       return el.checked;
582     } else if (el.localName == "option") {
583       return el.selected;
584     }
585   }
587   return false;
591  * An element is considered read only if it is an
592  * <code>&lt;input&gt;</code> or <code>&lt;textarea&gt;</code>
593  * element whose <code>readOnly</code> content IDL attribute is set.
595  * @param {Element} el
596  *     Element to test is read only.
598  * @returns {boolean}
599  *     True if element is read only.
600  */
601 dom.isReadOnly = function (el) {
602   return (
603     dom.isDOMElement(el) &&
604     ["input", "textarea"].includes(el.localName) &&
605     el.readOnly
606   );
610  * An element is considered disabled if it is a an element
611  * that can be disabled, or it belongs to a container group which
612  * <code>disabled</code> content IDL attribute affects it.
614  * @param {Element} el
615  *     Element to test for disabledness.
617  * @returns {boolean}
618  *     True if element, or its container group, is disabled.
619  */
620 dom.isDisabled = function (el) {
621   if (!dom.isDOMElement(el)) {
622     return false;
623   }
625   // Selenium expects that even an enabled "option" element that is a child
626   // of a disabled "optgroup" or "select" element to be disabled.
627   if (["optgroup", "option"].includes(el.localName) && !el.disabled) {
628     const parent = dom.findClosest(el, "optgroup,select");
629     return dom.isDisabled(parent);
630   }
632   return el.matches(":disabled");
636  * Denotes elements that can be used for typing and clearing.
638  * Elements that are considered WebDriver-editable are non-readonly
639  * and non-disabled <code>&lt;input&gt;</code> elements in the Text,
640  * Search, URL, Telephone, Email, Password, Date, Month, Date and
641  * Time Local, Number, Range, Color, and File Upload states, and
642  * <code>&lt;textarea&gt;</code> elements.
644  * @param {Element} el
645  *     Element to test.
647  * @returns {boolean}
648  *     True if editable, false otherwise.
649  */
650 dom.isMutableFormControl = function (el) {
651   if (!dom.isDOMElement(el)) {
652     return false;
653   }
654   if (dom.isReadOnly(el) || dom.isDisabled(el)) {
655     return false;
656   }
658   if (el.localName == "textarea") {
659     return true;
660   }
662   if (el.localName != "input") {
663     return false;
664   }
666   switch (el.type) {
667     case "color":
668     case "date":
669     case "datetime-local":
670     case "email":
671     case "file":
672     case "month":
673     case "number":
674     case "password":
675     case "range":
676     case "search":
677     case "tel":
678     case "text":
679     case "time":
680     case "url":
681     case "week":
682       return true;
684     default:
685       return false;
686   }
690  * An editing host is a node that is either an HTML element with a
691  * <code>contenteditable</code> attribute, or the HTML element child
692  * of a document whose <code>designMode</code> is enabled.
694  * @param {Element} el
695  *     Element to determine if is an editing host.
697  * @returns {boolean}
698  *     True if editing host, false otherwise.
699  */
700 dom.isEditingHost = function (el) {
701   return (
702     dom.isDOMElement(el) &&
703     (el.isContentEditable || el.ownerDocument.designMode == "on")
704   );
708  * Determines if an element is editable according to WebDriver.
710  * An element is considered editable if it is not read-only or
711  * disabled, and one of the following conditions are met:
713  * <ul>
714  * <li>It is a <code>&lt;textarea&gt;</code> element.
716  * <li>It is an <code>&lt;input&gt;</code> element that is not of
717  * the <code>checkbox</code>, <code>radio</code>, <code>hidden</code>,
718  * <code>submit</code>, <code>button</code>, or <code>image</code> types.
720  * <li>It is content-editable.
722  * <li>It belongs to a document in design mode.
723  * </ul>
725  * @param {Element} el
726  *     Element to test if editable.
728  * @returns {boolean}
729  *     True if editable, false otherwise.
730  */
731 dom.isEditable = function (el) {
732   if (!dom.isDOMElement(el)) {
733     return false;
734   }
736   if (dom.isReadOnly(el) || dom.isDisabled(el)) {
737     return false;
738   }
740   return dom.isMutableFormControl(el) || dom.isEditingHost(el);
744  * This function generates a pair of coordinates relative to the viewport
745  * given a target element and coordinates relative to that element's
746  * top-left corner.
748  * @param {Node} node
749  *     Target node.
750  * @param {number=} xOffset
751  *     Horizontal offset relative to target's top-left corner.
752  *     Defaults to the centre of the target's bounding box.
753  * @param {number=} yOffset
754  *     Vertical offset relative to target's top-left corner.  Defaults to
755  *     the centre of the target's bounding box.
757  * @returns {Object<string, number>}
758  *     X- and Y coordinates.
760  * @throws TypeError
761  *     If <var>xOffset</var> or <var>yOffset</var> are not numbers.
762  */
763 dom.coordinates = function (node, xOffset = undefined, yOffset = undefined) {
764   let box = node.getBoundingClientRect();
766   if (typeof xOffset == "undefined" || xOffset === null) {
767     xOffset = box.width / 2.0;
768   }
769   if (typeof yOffset == "undefined" || yOffset === null) {
770     yOffset = box.height / 2.0;
771   }
773   if (typeof yOffset != "number" || typeof xOffset != "number") {
774     throw new TypeError("Offset must be a number");
775   }
777   return {
778     x: box.left + xOffset,
779     y: box.top + yOffset,
780   };
784  * This function returns true if the node is in the viewport.
786  * @param {Element} el
787  *     Target element.
788  * @param {number=} x
789  *     Horizontal offset relative to target.  Defaults to the centre of
790  *     the target's bounding box.
791  * @param {number=} y
792  *     Vertical offset relative to target.  Defaults to the centre of
793  *     the target's bounding box.
795  * @returns {boolean}
796  *     True if if <var>el</var> is in viewport, false otherwise.
797  */
798 dom.inViewport = function (el, x = undefined, y = undefined) {
799   let win = el.ownerGlobal;
800   let c = dom.coordinates(el, x, y);
801   let vp = {
802     top: win.pageYOffset,
803     left: win.pageXOffset,
804     bottom: win.pageYOffset + win.innerHeight,
805     right: win.pageXOffset + win.innerWidth,
806   };
808   return (
809     vp.left <= c.x + win.pageXOffset &&
810     c.x + win.pageXOffset <= vp.right &&
811     vp.top <= c.y + win.pageYOffset &&
812     c.y + win.pageYOffset <= vp.bottom
813   );
817  * Gets the element's container element.
819  * An element container is defined by the WebDriver
820  * specification to be an <tt>&lt;option&gt;</tt> element in a
821  * <a href="https://html.spec.whatwg.org/#concept-element-contexts">valid
822  * element context</a>, meaning that it has an ancestral element
823  * that is either <tt>&lt;datalist&gt;</tt> or <tt>&lt;select&gt;</tt>.
825  * If the element does not have a valid context, its container element
826  * is itself.
828  * @param {Element} el
829  *     Element to get the container of.
831  * @returns {Element}
832  *     Container element of <var>el</var>.
833  */
834 dom.getContainer = function (el) {
835   // Does <option> or <optgroup> have a valid context,
836   // meaning is it a child of <datalist> or <select>?
837   if (["option", "optgroup"].includes(el.localName)) {
838     return dom.findClosest(el, "datalist,select") || el;
839   }
841   return el;
845  * An element is in view if it is a member of its own pointer-interactable
846  * paint tree.
848  * This means an element is considered to be in view, but not necessarily
849  * pointer-interactable, if it is found somewhere in the
850  * <code>elementsFromPoint</code> list at <var>el</var>'s in-view
851  * centre coordinates.
853  * Before running the check, we change <var>el</var>'s pointerEvents
854  * style property to "auto", since elements without pointer events
855  * enabled do not turn up in the paint tree we get from
856  * document.elementsFromPoint.  This is a specialisation that is only
857  * relevant when checking if the element is in view.
859  * @param {Element} el
860  *     Element to check if is in view.
862  * @returns {boolean}
863  *     True if <var>el</var> is inside the viewport, or false otherwise.
864  */
865 dom.isInView = function (el) {
866   let originalPointerEvents = el.style.pointerEvents;
868   try {
869     el.style.pointerEvents = "auto";
870     const tree = dom.getPointerInteractablePaintTree(el);
872     // Bug 1413493 - <tr> is not part of the returned paint tree yet. As
873     // workaround check the visibility based on the first contained cell.
874     if (el.localName === "tr" && el.cells && el.cells.length) {
875       return tree.includes(el.cells[0]);
876     }
878     return tree.includes(el);
879   } finally {
880     el.style.pointerEvents = originalPointerEvents;
881   }
885  * This function throws the visibility of the element error if the element is
886  * not displayed or the given coordinates are not within the viewport.
888  * @param {Element} el
889  *     Element to check if visible.
890  * @param {number=} x
891  *     Horizontal offset relative to target.  Defaults to the centre of
892  *     the target's bounding box.
893  * @param {number=} y
894  *     Vertical offset relative to target.  Defaults to the centre of
895  *     the target's bounding box.
897  * @returns {boolean}
898  *     True if visible, false otherwise.
899  */
900 dom.isVisible = async function (el, x = undefined, y = undefined) {
901   let win = el.ownerGlobal;
903   if (!(await lazy.atom.isElementDisplayed(el, win))) {
904     return false;
905   }
907   if (el.tagName.toLowerCase() == "body") {
908     return true;
909   }
911   if (!dom.inViewport(el, x, y)) {
912     dom.scrollIntoView(el);
913     if (!dom.inViewport(el)) {
914       return false;
915     }
916   }
917   return true;
921  * A pointer-interactable element is defined to be the first
922  * non-transparent element, defined by the paint order found at the centre
923  * point of its rectangle that is inside the viewport, excluding the size
924  * of any rendered scrollbars.
926  * An element is obscured if the pointer-interactable paint tree at its
927  * centre point is empty, or the first element in this tree is not an
928  * inclusive descendant of itself.
930  * @param {DOMElement} el
931  *     Element determine if is pointer-interactable.
933  * @returns {boolean}
934  *     True if element is obscured, false otherwise.
935  */
936 dom.isObscured = function (el) {
937   let tree = dom.getPointerInteractablePaintTree(el);
938   return !el.contains(tree[0]);
941 // TODO(ato): Only used by deprecated action API
942 // https://bugzil.la/1354578
944  * Calculates the in-view centre point of an element's client rect.
946  * The portion of an element that is said to be _in view_, is the
947  * intersection of two squares: the first square being the initial
948  * viewport, and the second a DOM element.  From this square we
949  * calculate the in-view _centre point_ and convert it into CSS pixels.
951  * Although Gecko's system internals allow click points to be
952  * given in floating point precision, the DOM operates in CSS pixels.
953  * When the in-view centre point is later used to retrieve a coordinate's
954  * paint tree, we need to ensure to operate in the same language.
956  * As a word of warning, there appears to be inconsistencies between
957  * how `DOMElement.elementsFromPoint` and `DOMWindowUtils.sendMouseEvent`
958  * internally rounds (ceils/floors) coordinates.
960  * @param {DOMRect} rect
961  *     Element off a DOMRect sequence produced by calling
962  *     `getClientRects` on an {@link Element}.
963  * @param {WindowProxy} win
964  *     Current window global.
966  * @returns {Map.<string, number>}
967  *     X and Y coordinates that denotes the in-view centre point of
968  *     `rect`.
969  */
970 dom.getInViewCentrePoint = function (rect, win) {
971   const { floor, max, min } = Math;
973   // calculate the intersection of the rect that is inside the viewport
974   let visible = {
975     left: max(0, min(rect.x, rect.x + rect.width)),
976     right: min(win.innerWidth, max(rect.x, rect.x + rect.width)),
977     top: max(0, min(rect.y, rect.y + rect.height)),
978     bottom: min(win.innerHeight, max(rect.y, rect.y + rect.height)),
979   };
981   // arrive at the centre point of the visible rectangle
982   let x = (visible.left + visible.right) / 2.0;
983   let y = (visible.top + visible.bottom) / 2.0;
985   // convert to CSS pixels, as centre point can be float
986   x = floor(x);
987   y = floor(y);
989   return { x, y };
993  * Produces a pointer-interactable elements tree from a given element.
995  * The tree is defined by the paint order found at the centre point of
996  * the element's rectangle that is inside the viewport, excluding the size
997  * of any rendered scrollbars.
999  * @param {DOMElement} el
1000  *     Element to determine if is pointer-interactable.
1002  * @returns {Array.<DOMElement>}
1003  *     Sequence of elements in paint order.
1004  */
1005 dom.getPointerInteractablePaintTree = function (el) {
1006   const win = el.ownerGlobal;
1007   const rootNode = el.getRootNode();
1009   // pointer-interactable elements tree, step 1
1010   if (!el.isConnected) {
1011     return [];
1012   }
1014   // steps 2-3
1015   let rects = el.getClientRects();
1016   if (!rects.length) {
1017     return [];
1018   }
1020   // step 4
1021   let centre = dom.getInViewCentrePoint(rects[0], win);
1023   // step 5
1024   return rootNode.elementsFromPoint(centre.x, centre.y);
1027 // TODO(ato): Not implemented.
1028 // In fact, it's not defined in the spec.
1029 dom.isKeyboardInteractable = () => true;
1032  * Attempts to scroll into view |el|.
1034  * @param {DOMElement} el
1035  *     Element to scroll into view.
1036  */
1037 dom.scrollIntoView = function (el) {
1038   if (el.scrollIntoView) {
1039     el.scrollIntoView({ block: "end", inline: "nearest" });
1040   }
1044  * Ascertains whether <var>obj</var> is a DOM-, SVG-, or XUL element.
1046  * @param {object} obj
1047  *     Object thought to be an <code>Element</code> or
1048  *     <code>XULElement</code>.
1050  * @returns {boolean}
1051  *     True if <var>obj</var> is an element, false otherwise.
1052  */
1053 dom.isElement = function (obj) {
1054   return dom.isDOMElement(obj) || dom.isXULElement(obj);
1058  * Returns the shadow root of an element.
1060  * @param {Element} el
1061  *     Element thought to have a <code>shadowRoot</code>
1062  * @returns {ShadowRoot}
1063  *     Shadow root of the element.
1064  */
1065 dom.getShadowRoot = function (el) {
1066   const shadowRoot = el.openOrClosedShadowRoot;
1067   if (!shadowRoot) {
1068     throw new lazy.error.NoSuchShadowRootError();
1069   }
1070   return shadowRoot;
1074  * Ascertains whether <var>node</var> is a shadow root.
1076  * @param {ShadowRoot} node
1077  *   The node that will be checked to see if it has a shadow root
1079  * @returns {boolean}
1080  *     True if <var>node</var> is a shadow root, false otherwise.
1081  */
1082 dom.isShadowRoot = function (node) {
1083   return (
1084     node &&
1085     node.nodeType === DOCUMENT_FRAGMENT_NODE &&
1086     node.containingShadowRoot == node
1087   );
1091  * Ascertains whether <var>obj</var> is a DOM element.
1093  * @param {object} obj
1094  *     Object to check.
1096  * @returns {boolean}
1097  *     True if <var>obj</var> is a DOM element, false otherwise.
1098  */
1099 dom.isDOMElement = function (obj) {
1100   return obj && obj.nodeType == ELEMENT_NODE && !dom.isXULElement(obj);
1104  * Ascertains whether <var>obj</var> is a XUL element.
1106  * @param {object} obj
1107  *     Object to check.
1109  * @returns {boolean}
1110  *     True if <var>obj</var> is a XULElement, false otherwise.
1111  */
1112 dom.isXULElement = function (obj) {
1113   return obj && obj.nodeType === ELEMENT_NODE && obj.namespaceURI === XUL_NS;
1117  * Ascertains whether <var>node</var> is in a privileged document.
1119  * @param {Node} node
1120  *     Node to check.
1122  * @returns {boolean}
1123  *     True if <var>node</var> is in a privileged document,
1124  *     false otherwise.
1125  */
1126 dom.isInPrivilegedDocument = function (node) {
1127   return !!node?.nodePrincipal?.isSystemPrincipal;
1131  * Ascertains whether <var>obj</var> is a <code>WindowProxy</code>.
1133  * @param {object} obj
1134  *     Object to check.
1136  * @returns {boolean}
1137  *     True if <var>obj</var> is a DOM window.
1138  */
1139 dom.isDOMWindow = function (obj) {
1140   // TODO(ato): This should use Object.prototype.toString.call(node)
1141   // but it's not clear how to write a good xpcshell test for that,
1142   // seeing as we stub out a WindowProxy.
1143   return (
1144     typeof obj == "object" &&
1145     obj !== null &&
1146     typeof obj.toString == "function" &&
1147     obj.toString() == "[object Window]" &&
1148     obj.self === obj
1149   );
1152 const boolEls = {
1153   audio: ["autoplay", "controls", "loop", "muted"],
1154   button: ["autofocus", "disabled", "formnovalidate"],
1155   details: ["open"],
1156   dialog: ["open"],
1157   fieldset: ["disabled"],
1158   form: ["novalidate"],
1159   iframe: ["allowfullscreen"],
1160   img: ["ismap"],
1161   input: [
1162     "autofocus",
1163     "checked",
1164     "disabled",
1165     "formnovalidate",
1166     "multiple",
1167     "readonly",
1168     "required",
1169   ],
1170   keygen: ["autofocus", "disabled"],
1171   menuitem: ["checked", "default", "disabled"],
1172   ol: ["reversed"],
1173   optgroup: ["disabled"],
1174   option: ["disabled", "selected"],
1175   script: ["async", "defer"],
1176   select: ["autofocus", "disabled", "multiple", "required"],
1177   textarea: ["autofocus", "disabled", "readonly", "required"],
1178   track: ["default"],
1179   video: ["autoplay", "controls", "loop", "muted"],
1183  * Tests if the attribute is a boolean attribute on element.
1185  * @param {Element} el
1186  *     Element to test if <var>attr</var> is a boolean attribute on.
1187  * @param {string} attr
1188  *     Attribute to test is a boolean attribute.
1190  * @returns {boolean}
1191  *     True if the attribute is boolean, false otherwise.
1192  */
1193 dom.isBooleanAttribute = function (el, attr) {
1194   if (!dom.isDOMElement(el)) {
1195     return false;
1196   }
1198   // global boolean attributes that apply to all HTML elements,
1199   // except for custom elements
1200   const customElement = !el.localName.includes("-");
1201   if ((attr == "hidden" || attr == "itemscope") && customElement) {
1202     return true;
1203   }
1205   if (!boolEls.hasOwnProperty(el.localName)) {
1206     return false;
1207   }
1208   return boolEls[el.localName].includes(attr);