forked from Floorp-Projects/Floorp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathelement.js
1649 lines (1494 loc) · 45.8 KB
/
element.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* 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 XPCNativeWrapper */
ChromeUtils.import("chrome://marionette/content/assert.js");
ChromeUtils.import("chrome://marionette/content/atom.js");
const {
InvalidArgumentError,
InvalidSelectorError,
NoSuchElementError,
StaleElementReferenceError,
} = ChromeUtils.import("chrome://marionette/content/error.js", {});
const {pprint} = ChromeUtils.import("chrome://marionette/content/format.js", {});
const {PollPromise} = ChromeUtils.import("chrome://marionette/content/sync.js", {});
this.EXPORTED_SYMBOLS = [
"ChromeWebElement",
"ContentWebElement",
"ContentWebFrame",
"ContentWebWindow",
"element",
"WebElement",
];
const ORDERED_NODE_ITERATOR_TYPE = 5;
const FIRST_ORDERED_NODE_TYPE = 9;
const ELEMENT_NODE = 1;
const DOCUMENT_NODE = 9;
const XBLNS = "http://www.mozilla.org/xbl";
const XULNS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
/** XUL elements that support checked property. */
const XUL_CHECKED_ELS = new Set([
"button",
"checkbox",
"listitem",
"toolbarbutton",
]);
/** XUL elements that support selected property. */
const XUL_SELECTED_ELS = new Set([
"listitem",
"menu",
"menuitem",
"menuseparator",
"radio",
"richlistitem",
"tab",
]);
const uuidGen = Cc["@mozilla.org/uuid-generator;1"]
.getService(Ci.nsIUUIDGenerator);
/**
* This module provides shared functionality for dealing with DOM-
* and web elements in Marionette.
*
* A web element is an abstraction used to identify an element when it
* is transported across the protocol, between remote- and local ends.
*
* Each element has an associated web element reference (a UUID) that
* uniquely identifies the the element across all browsing contexts. The
* web element reference for every element representing the same element
* is the same.
*
* The {@link element.Store} provides a mapping between web element
* references and DOM elements for each browsing context. It also provides
* functionality for looking up and retrieving elements.
*
* @namespace
*/
this.element = {};
element.Strategy = {
ClassName: "class name",
Selector: "css selector",
ID: "id",
Name: "name",
LinkText: "link text",
PartialLinkText: "partial link text",
TagName: "tag name",
XPath: "xpath",
Anon: "anon",
AnonAttribute: "anon attribute",
};
/**
* Stores known/seen elements and their associated web element
* references.
*
* Elements are added by calling {@link #add()} or {@link addAll()},
* and may be queried by their web element reference using {@link get()}.
*
* @class
* @memberof element
*/
element.Store = class {
constructor() {
this.els = {};
}
clear() {
this.els = {};
}
/**
* Make a collection of elements seen.
*
* The oder of the returned web element references is guaranteed to
* match that of the collection passed in.
*
* @param {NodeList} els
* Sequence of elements to add to set of seen elements.
*
* @return {Array.<WebElement>}
* List of the web element references associated with each element
* from <var>els</var>.
*/
addAll(els) {
let add = this.add.bind(this);
return [...els].map(add);
}
/**
* Make an element seen.
*
* @param {(Element|WindowProxy|XULElement)} el
* Element to add to set of seen elements.
*
* @return {WebElement}
* Web element reference associated with element.
*
* @throws {TypeError}
* If <var>el</var> is not an {@link Element} or a {@link XULElement}.
*/
add(el) {
const isDOMElement = element.isDOMElement(el);
const isDOMWindow = element.isDOMWindow(el);
const isXULElement = element.isXULElement(el);
const context = isXULElement ? "chrome" : "content";
if (!(isDOMElement || isDOMWindow || isXULElement)) {
throw new TypeError(
"Expected an element or WindowProxy, " +
pprint`got: ${el}`);
}
for (let i in this.els) {
let foundEl;
try {
foundEl = this.els[i].get();
} catch (e) {}
if (foundEl) {
if (new XPCNativeWrapper(foundEl) == new XPCNativeWrapper(el)) {
return WebElement.fromUUID(i, context);
}
// cleanup reference to gc'd element
} else {
delete this.els[i];
}
}
let webEl = WebElement.from(el);
this.els[webEl.uuid] = Cu.getWeakReference(el);
return webEl;
}
/**
* Determine if the provided web element reference has been seen
* before/is in the element store.
*
* Unlike when getting the element, a staleness check is not
* performed.
*
* @param {WebElement} webEl
* Element's associated web element reference.
*
* @return {boolean}
* True if element is in the store, false otherwise.
*
* @throws {TypeError}
* If <var>webEl</var> is not a {@link WebElement}.
*/
has(webEl) {
if (!(webEl instanceof WebElement)) {
throw new TypeError(
pprint`Expected web element, got: ${webEl}`);
}
return Object.keys(this.els).includes(webEl.uuid);
}
/**
* Retrieve a DOM {@link Element} or a {@link XULElement} by its
* unique {@link WebElement} reference.
*
* @param {WebElement} webEl
* Web element reference to find the associated {@link Element}
* of.
* @param {WindowProxy} window
* Current browsing context, which may differ from the associate
* browsing context of <var>el</var>.
*
* @returns {(Element|XULElement)}
* Element associated with reference.
*
* @throws {TypeError}
* If <var>webEl</var> is not a {@link WebElement}.
* @throws {NoSuchElementError}
* If the web element reference <var>uuid</var> has not been
* seen before.
* @throws {StaleElementReferenceError}
* If the element has gone stale, indicating it is no longer
* attached to the DOM, or its node document is no longer the
* active document.
*/
get(webEl, window) {
if (!(webEl instanceof WebElement)) {
throw new TypeError(
pprint`Expected web element, got: ${webEl}`);
}
if (!this.has(webEl)) {
throw new NoSuchElementError(
"Web element reference not seen before: " + webEl.uuid);
}
let el;
let ref = this.els[webEl.uuid];
try {
el = ref.get();
} catch (e) {
delete this.els[webEl.uuid];
}
if (element.isStale(el, window)) {
throw new StaleElementReferenceError(
pprint`The element reference of ${el || webEl.uuid} is stale; ` +
"either the element is no longer attached to the DOM, " +
"it is not in the current frame context, " +
"or the document has been refreshed");
}
return el;
}
};
/**
* Find a single element or a collection of elements starting at the
* document root or a given node.
*
* If |timeout| is above 0, an implicit search technique is used.
* This will wait for the duration of <var>timeout</var> for the
* element to appear in the DOM.
*
* See the {@link element.Strategy} enum for a full list of supported
* search strategies that can be passed to <var>strategy</var>.
*
* Available flags for <var>opts</var>:
*
* <dl>
* <dt><code>all</code>
* <dd>
* If true, a multi-element search selector is used and a sequence
* of elements will be returned. Otherwise a single element.
*
* <dt><code>timeout</code>
* <dd>
* Duration to wait before timing out the search. If <code>all</code>
* is false, a {@link NoSuchElementError} is thrown if unable to
* find the element within the timeout duration.
*
* <dt><code>startNode</code>
* <dd>Element to use as the root of the search.
*
* @param {Object.<string, WindowProxy>} container
* Window object and an optional shadow root that contains the
* root shadow DOM element.
* @param {string} strategy
* Search strategy whereby to locate the element(s).
* @param {string} selector
* Selector search pattern. The selector must be compatible with
* the chosen search <var>strategy</var>.
* @param {Object.<string, ?>} opts
* Options.
*
* @return {Promise.<(Element|Array.<Element>)>}
* Single element or a sequence of elements.
*
* @throws InvalidSelectorError
* If <var>strategy</var> is unknown.
* @throws InvalidSelectorError
* If <var>selector</var> is malformed.
* @throws NoSuchElementError
* If a single element is requested, this error will throw if the
* element is not found.
*/
element.find = function(container, strategy, selector, opts = {}) {
let all = !!opts.all;
let timeout = opts.timeout || 0;
let startNode = opts.startNode;
let searchFn;
if (opts.all) {
searchFn = findElements.bind(this);
} else {
searchFn = findElement.bind(this);
}
return new Promise((resolve, reject) => {
let findElements = new PollPromise((resolve, reject) => {
let res = find_(container, strategy, selector, searchFn,
{all, startNode});
if (res.length > 0) {
resolve(Array.from(res));
} else {
reject([]);
}
}, {timeout});
findElements.then(foundEls => {
// the following code ought to be moved into findElement
// and findElements when bug 1254486 is addressed
if (!opts.all && (!foundEls || foundEls.length == 0)) {
let msg;
switch (strategy) {
case element.Strategy.AnonAttribute:
msg = "Unable to locate anonymous element: " +
JSON.stringify(selector);
break;
default:
msg = "Unable to locate element: " + selector;
}
reject(new NoSuchElementError(msg));
}
if (opts.all) {
resolve(foundEls);
}
resolve(foundEls[0]);
}, reject);
});
};
function find_(container, strategy, selector, searchFn,
{startNode = null, all = false} = {}) {
let rootNode = container.shadowRoot || container.frame.document;
if (!startNode) {
switch (strategy) {
// For anonymous nodes the start node needs to be of type
// DOMElement, which will refer to :root in case of a DOMDocument.
case element.Strategy.Anon:
case element.Strategy.AnonAttribute:
if (rootNode instanceof Ci.nsIDOMDocument) {
startNode = rootNode.documentElement;
}
break;
default:
startNode = rootNode;
}
}
let res;
try {
res = searchFn(strategy, selector, rootNode, startNode);
} catch (e) {
throw new InvalidSelectorError(
`Given ${strategy} expression "${selector}" is invalid: ${e}`);
}
if (res) {
if (all) {
return res;
}
return [res];
}
return [];
}
/**
* Find a single element by XPath expression.
*
* @param {HTMLDocument} document
* Document root.
* @param {Element} startNode
* Where in the DOM hiearchy to begin searching.
* @param {string} expression
* XPath search expression.
*
* @return {Node}
* First element matching <var>expression</var>.
*/
element.findByXPath = function(document, startNode, expression) {
let iter = document.evaluate(
expression, startNode, null, FIRST_ORDERED_NODE_TYPE, null);
return iter.singleNodeValue;
};
/**
* Find elements by XPath expression.
*
* @param {HTMLDocument} document
* Document root.
* @param {Element} startNode
* Where in the DOM hierarchy to begin searching.
* @param {string} expression
* XPath search expression.
*
* @return {Iterable.<Node>}
* Iterator over elements matching <var>expression</var>.
*/
element.findByXPathAll = function* (document, startNode, expression) {
let iter = document.evaluate(
expression, startNode, null, ORDERED_NODE_ITERATOR_TYPE, null);
let el = iter.iterateNext();
while (el) {
yield el;
el = iter.iterateNext();
}
};
/**
* Find all hyperlinks descendant of <var>startNode</var> which
* link text is <var>linkText</var>.
*
* @param {Element} startNode
* Where in the DOM hierarchy to begin searching.
* @param {string} linkText
* Link text to search for.
*
* @return {Iterable.<HTMLAnchorElement>}
* Sequence of link elements which text is <var>s</var>.
*/
element.findByLinkText = function(startNode, linkText) {
return filterLinks(startNode, link => link.text.trim() === linkText);
};
/**
* Find all hyperlinks descendant of <var>startNode</var> which
* link text contains <var>linkText</var>.
*
* @param {Element} startNode
* Where in the DOM hierachy to begin searching.
* @param {string} linkText
* Link text to search for.
*
* @return {Iterable.<HTMLAnchorElement>}
* Iterator of link elements which text containins
* <var>linkText</var>.
*/
element.findByPartialLinkText = function(startNode, linkText) {
return filterLinks(startNode, link => link.text.includes(linkText));
};
/**
* Find anonymous nodes of <var>node</var>.
*
* @param {XULDocument} document
* Root node of the document.
* @param {XULElement} node
* Where in the DOM hierarchy to begin searching.
*
* @return {Iterable.<XULElement>}
* Iterator over anonymous elements.
*/
element.findAnonymousNodes = function* (document, node) {
let anons = document.getAnonymousNodes(node) || [];
for (let node of anons) {
yield node;
}
};
/**
* Filters all hyperlinks that are descendant of <var>startNode</var>
* by <var>predicate</var>.
*
* @param {Element} startNode
* Where in the DOM hierarchy to begin searching.
* @param {function(HTMLAnchorElement): boolean} predicate
* Function that determines if given link should be included in
* return value or filtered away.
*
* @return {Iterable.<HTMLAnchorElement>}
* Iterator of link elements matching <var>predicate</var>.
*/
function* filterLinks(startNode, predicate) {
for (let link of startNode.getElementsByTagName("a")) {
if (predicate(link)) {
yield link;
}
}
}
/**
* Finds a single element.
*
* @param {element.Strategy} strategy
* Selector strategy to use.
* @param {string} selector
* Selector expression.
* @param {HTMLDocument} document
* Document root.
* @param {Element=} startNode
* Optional node from which to start searching.
*
* @return {Element}
* Found elements.
*
* @throws {InvalidSelectorError}
* If strategy <var>using</var> is not recognised.
* @throws {Error}
* If selector expression <var>selector</var> is malformed.
*/
function findElement(strategy, selector, document, startNode = undefined) {
switch (strategy) {
case element.Strategy.ID:
{
if (startNode.getElementById) {
return startNode.getElementById(selector);
}
let expr = `.//*[@id="${selector}"]`;
return element.findByXPath(document, startNode, expr);
}
case element.Strategy.Name:
{
if (startNode.getElementsByName) {
return startNode.getElementsByName(selector)[0];
}
let expr = `.//*[@name="${selector}"]`;
return element.findByXPath(document, startNode, expr);
}
case element.Strategy.ClassName:
return startNode.getElementsByClassName(selector)[0];
case element.Strategy.TagName:
return startNode.getElementsByTagName(selector)[0];
case element.Strategy.XPath:
return element.findByXPath(document, startNode, selector);
case element.Strategy.LinkText:
for (let link of startNode.getElementsByTagName("a")) {
if (link.text.trim() === selector) {
return link;
}
}
return undefined;
case element.Strategy.PartialLinkText:
for (let link of startNode.getElementsByTagName("a")) {
if (link.text.includes(selector)) {
return link;
}
}
return undefined;
case element.Strategy.Selector:
try {
return startNode.querySelector(selector);
} catch (e) {
throw new InvalidSelectorError(`${e.message}: "${selector}"`);
}
case element.Strategy.Anon:
return element.findAnonymousNodes(document, startNode).next().value;
case element.Strategy.AnonAttribute:
let attr = Object.keys(selector)[0];
return document.getAnonymousElementByAttribute(
startNode, attr, selector[attr]);
}
throw new InvalidSelectorError(`No such strategy: ${strategy}`);
}
/**
* Find multiple elements.
*
* @param {element.Strategy} strategy
* Selector strategy to use.
* @param {string} selector
* Selector expression.
* @param {HTMLDocument} document
* Document root.
* @param {Element=} startNode
* Optional node from which to start searching.
*
* @return {Array.<Element>}
* Found elements.
*
* @throws {InvalidSelectorError}
* If strategy <var>strategy</var> is not recognised.
* @throws {Error}
* If selector expression <var>selector</var> is malformed.
*/
function findElements(strategy, selector, document, startNode = undefined) {
switch (strategy) {
case element.Strategy.ID:
selector = `.//*[@id="${selector}"]`;
// fall through
case element.Strategy.XPath:
return [...element.findByXPathAll(document, startNode, selector)];
case element.Strategy.Name:
if (startNode.getElementsByName) {
return startNode.getElementsByName(selector);
}
return [...element.findByXPathAll(
document, startNode, `.//*[@name="${selector}"]`)];
case element.Strategy.ClassName:
return startNode.getElementsByClassName(selector);
case element.Strategy.TagName:
return startNode.getElementsByTagName(selector);
case element.Strategy.LinkText:
return [...element.findByLinkText(startNode, selector)];
case element.Strategy.PartialLinkText:
return [...element.findByPartialLinkText(startNode, selector)];
case element.Strategy.Selector:
return startNode.querySelectorAll(selector);
case element.Strategy.Anon:
return [...element.findAnonymousNodes(document, startNode)];
case element.Strategy.AnonAttribute:
let attr = Object.keys(selector)[0];
let el = document.getAnonymousElementByAttribute(
startNode, attr, selector[attr]);
if (el) {
return [el];
}
return [];
default:
throw new InvalidSelectorError(`No such strategy: ${strategy}`);
}
}
/**
* Finds the closest parent node of <var>startNode</var> by CSS a
* <var>selector</var> expression.
*
* @param {Node} startNode
* Cyce through <var>startNode</var>'s parent nodes in tree-order
* and return the first match to <var>selector</var>.
* @param {string} selector
* CSS selector expression.
*
* @return {Node=}
* First match to <var>selector</var>, or null if no match was found.
*/
element.findClosest = function(startNode, selector) {
let node = startNode;
while (node.parentNode && node.parentNode.nodeType == ELEMENT_NODE) {
node = node.parentNode;
if (node.matches(selector)) {
return node;
}
}
return null;
};
/**
* Determines if <var>obj<var> is an HTML or JS collection.
*
* @param {*} seq
* Type to determine.
*
* @return {boolean}
* True if <var>seq</va> is collection.
*/
element.isCollection = function(seq) {
switch (Object.prototype.toString.call(seq)) {
case "[object Arguments]":
case "[object Array]":
case "[object FileList]":
case "[object HTMLAllCollection]":
case "[object HTMLCollection]":
case "[object HTMLFormControlsCollection]":
case "[object HTMLOptionsCollection]":
case "[object NodeList]":
return true;
default:
return false;
}
};
/**
* Determines if <var>el</var> is stale.
*
* A stale element is an element no longer attached to the DOM or which
* node document is not the active document of the current browsing
* context.
*
* The currently selected browsing context, specified through
* <var>window<var>, is a WebDriver concept defining the target
* against which commands will run. As the current browsing context
* may differ from <var>el</var>'s associated context, an element is
* considered stale even if it is connected to a living (not discarded)
* browsing context such as an <tt><iframe></tt>.
*
* @param {Element=} el
* DOM element to check for staleness. If null, which may be
* the case if the element has been unwrapped from a weak
* reference, it is always considered stale.
* @param {WindowProxy=} window
* Current browsing context, which may differ from the associate
* browsing context of <var>el</var>. When retrieving XUL
* elements, this is optional.
*
* @return {boolean}
* True if <var>el</var> is stale, false otherwise.
*/
element.isStale = function(el, window = undefined) {
if (typeof window == "undefined") {
window = el.ownerGlobal;
}
if (el === null ||
!el.ownerGlobal ||
el.ownerDocument !== window.document) {
return true;
}
return !el.isConnected;
};
/**
* Determine if <var>el</var> is selected or not.
*
* This operation only makes sense on
* <tt><input type=checkbox></tt>,
* <tt><input type=radio></tt>,
* and <tt>>option></tt> elements.
*
* @param {(DOMElement|XULElement)} el
* Element to test if selected.
*
* @return {boolean}
* True if element is selected, false otherwise.
*/
element.isSelected = function(el) {
if (!el) {
return false;
}
if (element.isXULElement(el)) {
if (XUL_CHECKED_ELS.has(el.tagName)) {
return el.checked;
} else if (XUL_SELECTED_ELS.has(el.tagName)) {
return el.selected;
}
} else if (element.isDOMElement(el)) {
if (el.localName == "input" && ["checkbox", "radio"].includes(el.type)) {
return el.checked;
} else if (el.localName == "option") {
return el.selected;
}
}
return false;
};
/**
* An element is considered read only if it is an
* <code><input></code> or <code><textarea></code>
* element whose <code>readOnly</code> content IDL attribute is set.
*
* @param {Element} el
* Element to test is read only.
*
* @return {boolean}
* True if element is read only.
*/
element.isReadOnly = function(el) {
return element.isDOMElement(el) &&
["input", "textarea"].includes(el.localName) && el.readOnly;
};
/**
* An element is considered disabled if it is a an element
* that can be disabled, or it belongs to a container group which
* <code>disabled</code> content IDL attribute affects it.
*
* @param {Element} el
* Element to test for disabledness.
*
* @return {boolean}
* True if element, or its container group, is disabled.
*/
element.isDisabled = function(el) {
if (!element.isDOMElement(el)) {
return false;
}
switch (el.localName) {
case "option":
case "optgroup":
if (el.disabled) {
return true;
}
let parent = element.findClosest(el, "optgroup,select");
return element.isDisabled(parent);
case "button":
case "input":
case "select":
case "textarea":
return el.disabled;
default:
return false;
}
};
/**
* Denotes elements that can be used for typing and clearing.
*
* Elements that are considered WebDriver-editable are non-readonly
* and non-disabled <code><input></code> elements in the Text,
* Search, URL, Telephone, Email, Password, Date, Month, Date and
* Time Local, Number, Range, Color, and File Upload states, and
* <code><textarea></code> elements.
*
* @param {Element} el
* Element to test.
*
* @return {boolean}
* True if editable, false otherwise.
*/
element.isMutableFormControl = function(el) {
if (!element.isDOMElement(el)) {
return false;
}
if (element.isReadOnly(el) || element.isDisabled(el)) {
return false;
}
if (el.localName == "textarea") {
return true;
}
if (el.localName != "input") {
return false;
}
switch (el.type) {
case "color":
case "date":
case "datetime-local":
case "email":
case "file":
case "month":
case "number":
case "password":
case "range":
case "search":
case "tel":
case "text":
case "time":
case "url":
case "week":
return true;
default:
return false;
}
};
/**
* An editing host is a node that is either an HTML element with a
* <code>contenteditable</code> attribute, or the HTML element child
* of a document whose <code>designMode</code> is enabled.
*
* @param {Element} el
* Element to determine if is an editing host.
*
* @return {boolean}
* True if editing host, false otherwise.
*/
element.isEditingHost = function(el) {
return element.isDOMElement(el) &&
(el.isContentEditable || el.ownerDocument.designMode == "on");
};
/**
* Determines if an element is editable according to WebDriver.
*
* An element is considered editable if it is not read-only or
* disabled, and one of the following conditions are met:
*
* <ul>
* <li>It is a <code><textarea></code> element.
*
* <li>It is an <code><input></code> element that is not of
* the <code>checkbox</code>, <code>radio</code>, <code>hidden</code>,
* <code>submit</code>, <code>button</code>, or <code>image</code> types.
*
* <li>It is content-editable.
*
* <li>It belongs to a document in design mode.
* </ul>
*
* @param {Element}
* Element to test if editable.
*
* @return {boolean}
* True if editable, false otherwise.
*/
element.isEditable = function(el) {
if (!element.isDOMElement(el)) {
return false;
}
if (element.isReadOnly(el) || element.isDisabled(el)) {
return false;
}
return element.isMutableFormControl(el) || element.isEditingHost(el);
};
/**
* This function generates a pair of coordinates relative to the viewport
* given a target element and coordinates relative to that element's
* top-left corner.
*
* @param {Node} node
* Target node.
* @param {number=} xOffset
* Horizontal offset relative to target's top-left corner.
* Defaults to the centre of the target's bounding box.
* @param {number=} yOffset
* Vertical offset relative to target's top-left corner. Defaults to
* the centre of the target's bounding box.
*
* @return {Object.<string, number>}
* X- and Y coordinates.
*
* @throws TypeError
* If <var>xOffset</var> or <var>yOffset</var> are not numbers.
*/
element.coordinates = function(
node, xOffset = undefined, yOffset = undefined) {
let box = node.getBoundingClientRect();
if (typeof xOffset == "undefined" || xOffset === null) {
xOffset = box.width / 2.0;
}
if (typeof yOffset == "undefined" || yOffset === null) {
yOffset = box.height / 2.0;
}
if (typeof yOffset != "number" || typeof xOffset != "number") {
throw new TypeError("Offset must be a number");
}
return {
x: box.left + xOffset,
y: box.top + yOffset,
};
};
/**
* This function returns true if the node is in the viewport.
*
* @param {Element} el
* Target element.
* @param {number=} x
* Horizontal offset relative to target. Defaults to the centre of
* the target's bounding box.
* @param {number=} y
* Vertical offset relative to target. Defaults to the centre of
* the target's bounding box.
*
* @return {boolean}
* True if if <var>el</var> is in viewport, false otherwise.
*/
element.inViewport = function(el, x = undefined, y = undefined) {
let win = el.ownerGlobal;
let c = element.coordinates(el, x, y);
let vp = {