-
-
Notifications
You must be signed in to change notification settings - Fork 8.2k
/
dom.js
1386 lines (1222 loc) · 47.6 KB
/
dom.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
// Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
/**
* @fileoverview DOM manipulation and querying routines.
*/
goog.provide('bot.dom');
goog.require('bot');
goog.require('bot.color');
goog.require('bot.dom.core');
goog.require('bot.locators.xpath');
goog.require('bot.userAgent');
goog.require('goog.array');
goog.require('goog.dom');
goog.require('goog.dom.DomHelper');
goog.require('goog.dom.NodeType');
goog.require('goog.dom.TagName');
goog.require('goog.math');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Rect');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.userAgent');
/**
* Whether Shadow DOM operations are supported by the browser.
* @const {boolean}
*/
bot.dom.IS_SHADOW_DOM_ENABLED = (typeof ShadowRoot === 'function');
/**
* Retrieves the active element for a node's owner document.
* @param {!(Node|Window)} nodeOrWindow The node whose owner document to get
* the active element for.
* @return {Element} The active element, if any.
*/
bot.dom.getActiveElement = function(nodeOrWindow) {
var active = goog.dom.getActiveElement(
goog.dom.getOwnerDocument(nodeOrWindow));
// IE has the habit of returning an empty object from
// goog.dom.getActiveElement instead of null.
if (goog.userAgent.IE &&
active &&
typeof active.nodeType === 'undefined') {
return null;
}
return active;
};
/**
* @const
*/
bot.dom.isElement = bot.dom.core.isElement;
/**
* Returns whether an element is in an interactable state: whether it is shown
* to the user, ignoring its opacity, and whether it is enabled.
*
* @param {!Element} element The element to check.
* @return {boolean} Whether the element is interactable.
* @see bot.dom.isShown.
* @see bot.dom.isEnabled
*/
bot.dom.isInteractable = function(element) {
return bot.dom.isShown(element, /*ignoreOpacity=*/true) &&
bot.dom.isEnabled(element) &&
!bot.dom.hasPointerEventsDisabled_(element);
};
/**
* @param {!Element} element Element.
* @return {boolean} Whether element is set by the CSS pointer-events property
* not to be interactable.
* @private
*/
bot.dom.hasPointerEventsDisabled_ = function(element) {
if (goog.userAgent.IE ||
(goog.userAgent.GECKO && !bot.userAgent.isEngineVersion('1.9.2'))) {
// Don't support pointer events
return false;
}
return bot.dom.getEffectiveStyle(element, 'pointer-events') == 'none';
};
/**
* @const
*/
bot.dom.isSelectable = bot.dom.core.isSelectable;
/**
* @const
*/
bot.dom.isSelected = bot.dom.core.isSelected;
/**
* List of the focusable fields, according to
* http://www.w3.org/TR/html401/interact/scripts.html#adef-onfocus
* @private {!Array.<!goog.dom.TagName>}
* @const
*/
bot.dom.FOCUSABLE_FORM_FIELDS_ = [
goog.dom.TagName.A,
goog.dom.TagName.AREA,
goog.dom.TagName.BUTTON,
goog.dom.TagName.INPUT,
goog.dom.TagName.LABEL,
goog.dom.TagName.SELECT,
goog.dom.TagName.TEXTAREA
];
/**
* Returns whether a node is a focusable element. An element may receive focus
* if it is a form field, has a non-negative tabindex, or is editable.
* @param {!Element} element The node to test.
* @return {boolean} Whether the node is focusable.
*/
bot.dom.isFocusable = function(element) {
return goog.array.some(bot.dom.FOCUSABLE_FORM_FIELDS_, tagNameMatches) ||
(bot.dom.getAttribute(element, 'tabindex') != null &&
Number(bot.dom.getProperty(element, 'tabIndex')) >= 0) ||
bot.dom.isEditable(element);
function tagNameMatches(tagName) {
return bot.dom.isElement(element, tagName);
}
};
/**
* @const
*/
bot.dom.getProperty = bot.dom.core.getProperty;
/**
* @const
*/
bot.dom.getAttribute = bot.dom.core.getAttribute;
/**
* List of elements that support the "disabled" attribute, as defined by the
* HTML 4.01 specification.
* @private {!Array.<goog.dom.TagName>}
* @const
* @see http://www.w3.org/TR/html401/interact/forms.html#h-17.12.1
*/
bot.dom.DISABLED_ATTRIBUTE_SUPPORTED_ = [
goog.dom.TagName.BUTTON,
goog.dom.TagName.INPUT,
goog.dom.TagName.OPTGROUP,
goog.dom.TagName.OPTION,
goog.dom.TagName.SELECT,
goog.dom.TagName.TEXTAREA
];
/**
* Determines if an element is enabled. An element is considered enabled if it
* does not support the "disabled" attribute, or if it is not disabled.
* @param {!Element} el The element to test.
* @return {boolean} Whether the element is enabled.
*/
bot.dom.isEnabled = function(el) {
var isSupported = goog.array.some(
bot.dom.DISABLED_ATTRIBUTE_SUPPORTED_,
function(tagName) { return bot.dom.isElement(el, tagName); });
if (!isSupported) {
return true;
}
if (bot.dom.getProperty(el, 'disabled')) {
return false;
}
// The element is not explicitly disabled, but if it is an OPTION or OPTGROUP,
// we must test if it inherits its state from a parent.
if (el.parentNode &&
el.parentNode.nodeType == goog.dom.NodeType.ELEMENT &&
bot.dom.isElement(el, goog.dom.TagName.OPTGROUP) ||
bot.dom.isElement(el, goog.dom.TagName.OPTION)) {
return bot.dom.isEnabled(/**@type{!Element}*/ (el.parentNode));
}
// Is there an ancestor of the current element that is a disabled fieldset
// and whose child is also an ancestor-or-self of the current element but is
// not the first legend child of the fieldset. If so then the element is
// disabled.
return !goog.dom.getAncestor(el, function(e) {
var parent = e.parentNode;
if (parent &&
bot.dom.isElement(parent, goog.dom.TagName.FIELDSET) &&
bot.dom.getProperty(/** @type {!Element} */ (parent), 'disabled')) {
if (!bot.dom.isElement(e, goog.dom.TagName.LEGEND)) {
return true;
}
var sibling = e;
// Are there any previous legend siblings? If so then we are not the
// first and the element is disabled
while (sibling = goog.dom.getPreviousElementSibling(sibling)) {
if (bot.dom.isElement(sibling, goog.dom.TagName.LEGEND)) {
return true;
}
}
}
return false;
}, true);
};
/**
* List of input types that create text fields.
* @private {!Array.<string>}
* @const
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#attr-input-type
*/
bot.dom.TEXTUAL_INPUT_TYPES_ = [
'text',
'search',
'tel',
'url',
'email',
'password',
'number'
];
/**
* TODO: Add support for designMode elements.
*
* @param {!Element} element The element to check.
* @return {boolean} Whether the element accepts user-typed text.
*/
bot.dom.isTextual = function(element) {
if (bot.dom.isElement(element, goog.dom.TagName.TEXTAREA)) {
return true;
}
if (bot.dom.isElement(element, goog.dom.TagName.INPUT)) {
var type = element.type.toLowerCase();
return goog.array.contains(bot.dom.TEXTUAL_INPUT_TYPES_, type);
}
if (bot.dom.isContentEditable(element)) {
return true;
}
return false;
};
/**
* @param {!Element} element The element to check.
* @return {boolean} Whether the element is a file input.
*/
bot.dom.isFileInput = function(element) {
if (bot.dom.isElement(element, goog.dom.TagName.INPUT)) {
var type = element.type.toLowerCase();
return type == 'file';
}
return false;
};
/**
* @param {!Element} element The element to check.
* @param {string} inputType The type of input to check.
* @return {boolean} Whether the element is an input with specified type.
*/
bot.dom.isInputType = function(element, inputType) {
if (bot.dom.isElement(element, goog.dom.TagName.INPUT)) {
var type = element.type.toLowerCase();
return type == inputType;
}
return false;
};
/**
* @param {!Element} element The element to check.
* @return {boolean} Whether the element is contentEditable.
*/
bot.dom.isContentEditable = function(element) {
// Check if browser supports contentEditable.
if (!goog.isDef(element['contentEditable'])) {
return false;
}
// Checking the element's isContentEditable property is preferred except for
// IE where that property is not reliable on IE versions 7, 8, and 9.
if (!goog.userAgent.IE && goog.isDef(element['isContentEditable'])) {
return element.isContentEditable;
}
// For IE and for browsers where contentEditable is supported but
// isContentEditable is not, traverse up the ancestors:
function legacyIsContentEditable(e) {
if (e.contentEditable == 'inherit') {
var parent = bot.dom.getParentElement(e);
return parent ? legacyIsContentEditable(parent) : false;
} else {
return e.contentEditable == 'true';
}
}
return legacyIsContentEditable(element);
};
/**
* TODO: Merge isTextual into this function and move to bot.dom.
* For Puppet, requires adding support to getVisibleText for grabbing
* text from all textual elements.
*
* Whether the element may contain text the user can edit.
*
* @param {!Element} element The element to check.
* @return {boolean} Whether the element accepts user-typed text.
*/
bot.dom.isEditable = function(element) {
return (bot.dom.isTextual(element) ||
bot.dom.isFileInput(element) ||
bot.dom.isInputType(element, 'range')) &&
!bot.dom.getProperty(element, 'readOnly');
};
/**
* Returns the parent element of the given node, or null. This is required
* because the parent node may not be another element.
*
* @param {!Node} node The node who's parent is desired.
* @return {Element} The parent element, if available, null otherwise.
*/
bot.dom.getParentElement = function(node) {
var elem = node.parentNode;
while (elem &&
elem.nodeType != goog.dom.NodeType.ELEMENT &&
elem.nodeType != goog.dom.NodeType.DOCUMENT &&
elem.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {
elem = elem.parentNode;
}
return /** @type {Element} */ (bot.dom.isElement(elem) ? elem : null);
};
/**
* Retrieves an explicitly-set, inline style value of an element. This returns
* '' if there isn't a style attribute on the element or if this style property
* has not been explicitly set in script.
*
* @param {!Element} elem Element to get the style value from.
* @param {string} styleName Name of the style property in selector-case.
* @return {string} The value of the style property.
*/
bot.dom.getInlineStyle = function(elem, styleName) {
return goog.style.getStyle(elem, styleName);
};
/**
* Retrieves the implicitly-set, effective style of an element, or null if it is
* unknown. It returns the computed style where available; otherwise it looks
* up the DOM tree for the first style value not equal to 'inherit,' using the
* IE currentStyle of each node if available, and otherwise the inline style.
* Since the computed, current, and inline styles can be different, the return
* value of this function is not always consistent across browsers. See:
* http://code.google.com/p/doctype/wiki/ArticleComputedStyleVsCascadedStyle
*
* @param {!Element} elem Element to get the style value from.
* @param {string} propertyName Name of the CSS property.
* @return {?string} The value of the style property, or null.
*/
bot.dom.getEffectiveStyle = function(elem, propertyName) {
var styleName = goog.string.toCamelCase(propertyName);
if (styleName == 'float' ||
styleName == 'cssFloat' ||
styleName == 'styleFloat') {
styleName = bot.userAgent.IE_DOC_PRE9 ? 'styleFloat' : 'cssFloat';
}
var style = goog.style.getComputedStyle(elem, styleName) ||
bot.dom.getCascadedStyle_(elem, styleName);
if (style === null) {
return null;
}
return bot.color.standardizeColor(styleName, style);
};
/**
* Looks up the DOM tree for the first style value not equal to 'inherit,' using
* the currentStyle of each node if available, and otherwise the inline style.
*
* @param {!Element} elem Element to get the style value from.
* @param {string} styleName CSS style property in camelCase.
* @return {?string} The value of the style property, or null.
* @private
*/
bot.dom.getCascadedStyle_ = function(elem, styleName) {
var style = elem.currentStyle || elem.style;
var value = style[styleName];
if (!goog.isDef(value) && goog.isFunction(style.getPropertyValue)) {
value = style.getPropertyValue(styleName);
}
if (value != 'inherit') {
return goog.isDef(value) ? value : null;
}
var parent = bot.dom.getParentElement(elem);
return parent ? bot.dom.getCascadedStyle_(parent, styleName) : null;
};
/**
* Extracted code from bot.dom.isShown.
*
* @param {!Element} elem The element to consider.
* @param {boolean} ignoreOpacity Whether to ignore the element's opacity
* when determining whether it is shown.
* @param {function(!Element):boolean} parentsDisplayedFn a function that's used
* to tell if the chain of ancestors are all shown.
* @return {boolean} Whether or not the element is visible.
* @private
*/
bot.dom.isShown_ = function(elem, ignoreOpacity, parentsDisplayedFn) {
if (!bot.dom.isElement(elem)) {
throw new Error('Argument to isShown must be of type Element');
}
// By convention, BODY element is always shown: BODY represents the document
// and even if there's nothing rendered in there, user can always see there's
// the document.
if (bot.dom.isElement(elem, goog.dom.TagName.BODY)) {
return true;
}
// Option or optgroup is shown iff enclosing select is shown (ignoring the
// select's opacity).
if (bot.dom.isElement(elem, goog.dom.TagName.OPTION) ||
bot.dom.isElement(elem, goog.dom.TagName.OPTGROUP)) {
var select = /**@type {Element}*/ (goog.dom.getAncestor(elem, function(e) {
return bot.dom.isElement(e, goog.dom.TagName.SELECT);
}));
return !!select && bot.dom.isShown_(select, true, parentsDisplayedFn);
}
// Image map elements are shown if image that uses it is shown, and
// the area of the element is positive.
var imageMap = bot.dom.maybeFindImageMap_(elem);
if (imageMap) {
return !!imageMap.image &&
imageMap.rect.width > 0 && imageMap.rect.height > 0 &&
bot.dom.isShown_(
imageMap.image, ignoreOpacity, parentsDisplayedFn);
}
// Any hidden input is not shown.
if (bot.dom.isElement(elem, goog.dom.TagName.INPUT) &&
elem.type.toLowerCase() == 'hidden') {
return false;
}
// Any NOSCRIPT element is not shown.
if (bot.dom.isElement(elem, goog.dom.TagName.NOSCRIPT)) {
return false;
}
// Any element with hidden/collapsed visibility is not shown.
var visibility = bot.dom.getEffectiveStyle(elem, 'visibility');
if (visibility == 'collapse' || visibility == 'hidden') {
return false;
}
if (!parentsDisplayedFn(elem)) {
return false;
}
// Any transparent element is not shown.
if (!ignoreOpacity && bot.dom.getOpacity(elem) == 0) {
return false;
}
// Any element without positive size dimensions is not shown.
function positiveSize(e) {
var rect = bot.dom.getClientRect(e);
if (rect.height > 0 && rect.width > 0) {
return true;
}
// A vertical or horizontal SVG Path element will report zero width or
// height but is "shown" if it has a positive stroke-width.
if (bot.dom.isElement(e, 'PATH') && (rect.height > 0 || rect.width > 0)) {
var strokeWidth = bot.dom.getEffectiveStyle(e, 'stroke-width');
return !!strokeWidth && (parseInt(strokeWidth, 10) > 0);
}
// Zero-sized elements should still be considered to have positive size
// if they have a child element or text node with positive size, unless
// the element has an 'overflow' style of 'hidden'.
return bot.dom.getEffectiveStyle(e, 'overflow') != 'hidden' &&
goog.array.some(e.childNodes, function(n) {
return n.nodeType == goog.dom.NodeType.TEXT ||
(bot.dom.isElement(n) && positiveSize(n));
});
}
if (!positiveSize(elem)) {
return false;
}
// Elements that are hidden by overflow are not shown.
function hiddenByOverflow(e) {
return bot.dom.getOverflowState(e) == bot.dom.OverflowState.HIDDEN &&
goog.array.every(e.childNodes, function(n) {
return !bot.dom.isElement(n) || hiddenByOverflow(n) ||
!positiveSize(n);
});
}
return !hiddenByOverflow(elem);
};
/**
* Determines whether an element is what a user would call "shown". This means
* that the element is shown in the viewport of the browser, and only has
* height and width greater than 0px, and that its visibility is not "hidden"
* and its display property is not "none".
* Options and Optgroup elements are treated as special cases: they are
* considered shown iff they have a enclosing select element that is shown.
*
* Elements in Shadow DOMs with younger shadow roots are not visible, and
* elements distributed into shadow DOMs check the visibility of the
* ancestors in the Composed DOM, rather than their ancestors in the logical
* DOM.
*
* @param {!Element} elem The element to consider.
* @param {boolean=} opt_ignoreOpacity Whether to ignore the element's opacity
* when determining whether it is shown; defaults to false.
* @return {boolean} Whether or not the element is visible.
*/
bot.dom.isShown = function(elem, opt_ignoreOpacity) {
var displayed;
if (bot.dom.IS_SHADOW_DOM_ENABLED) {
// Any element with a display style equal to 'none' or that has an ancestor
// with display style equal to 'none' is not shown.
displayed = function(e) {
if (bot.dom.getEffectiveStyle(e, 'display') == 'none') {
return false;
}
var parent;
do {
parent = bot.dom.getParentNodeInComposedDom(e);
if (parent instanceof ShadowRoot) {
if (parent.host.shadowRoot != parent) {
// There is a younger shadow root, which will take precedence over
// the shadow this element is in, thus this element won't be
// displayed.
return false;
} else {
parent = parent.host;
}
} else if (parent && (parent.nodeType == goog.dom.NodeType.DOCUMENT ||
parent.nodeType == goog.dom.NodeType.DOCUMENT_FRAGMENT)) {
parent = null;
}
} while (elem && elem.nodeType != goog.dom.NodeType.ELEMENT);
return !parent || displayed(parent);
};
} else {
// Any element with a display style equal to 'none' or that has an ancestor
// with display style equal to 'none' is not shown.
displayed = function(e) {
if (bot.dom.getEffectiveStyle(e, 'display') == 'none') {
return false;
}
var parent = bot.dom.getParentElement(e);
return !parent || displayed(parent);
};
}
return bot.dom.isShown_(elem, !!opt_ignoreOpacity, displayed);
};
/**
* The kind of overflow area in which an element may be located. NONE if it does
* not overflow any ancestor element; HIDDEN if it overflows and cannot be
* scrolled into view; SCROLL if it overflows but can be scrolled into view.
*
* @enum {string}
*/
bot.dom.OverflowState = {
NONE: 'none',
HIDDEN: 'hidden',
SCROLL: 'scroll'
};
/**
* Returns the overflow state of the given element.
*
* If an optional coordinate or rectangle region is provided, returns the
* overflow state of that region relative to the element. A coordinate is
* treated as a 1x1 rectangle whose top-left corner is the coordinate.
*
* @param {!Element} elem Element.
* @param {!(goog.math.Coordinate|goog.math.Rect)=} opt_region
* Coordinate or rectangle relative to the top-left corner of the element.
* @return {bot.dom.OverflowState} Overflow state of the element.
*/
bot.dom.getOverflowState = function(elem, opt_region) {
var region = bot.dom.getClientRegion(elem, opt_region);
var ownerDoc = goog.dom.getOwnerDocument(elem);
var htmlElem = ownerDoc.documentElement;
var bodyElem = ownerDoc.body;
var htmlOverflowStyle = bot.dom.getEffectiveStyle(htmlElem, 'overflow');
var treatAsFixedPosition;
// Return the closest ancestor that the given element may overflow.
function getOverflowParent(e) {
var position = bot.dom.getEffectiveStyle(e, 'position');
if (position == 'fixed') {
treatAsFixedPosition = true;
// Fixed-position element may only overflow the viewport.
return e == htmlElem ? null : htmlElem;
} else {
var parent = bot.dom.getParentElement(e);
while (parent && !canBeOverflowed(parent)) {
parent = bot.dom.getParentElement(parent);
}
return parent;
}
function canBeOverflowed(container) {
// The HTML element can always be overflowed.
if (container == htmlElem) {
return true;
}
// An element cannot overflow an element with an inline display style.
var containerDisplay = /** @type {string} */ (
bot.dom.getEffectiveStyle(container, 'display'));
if (goog.string.startsWith(containerDisplay, 'inline')) {
return false;
}
// An absolute-positioned element cannot overflow a static-positioned one.
if (position == 'absolute' &&
bot.dom.getEffectiveStyle(container, 'position') == 'static') {
return false;
}
return true;
}
}
// Return the x and y overflow styles for the given element.
function getOverflowStyles(e) {
// When the <html> element has an overflow style of 'visible', it assumes
// the overflow style of the body, and the body is really overflow:visible.
var overflowElem = e;
if (htmlOverflowStyle == 'visible') {
// Note: bodyElem will be null/undefined in SVG documents.
if (e == htmlElem && bodyElem) {
overflowElem = bodyElem;
} else if (e == bodyElem) {
return {x: 'visible', y: 'visible'};
}
}
var overflow = {
x: bot.dom.getEffectiveStyle(overflowElem, 'overflow-x'),
y: bot.dom.getEffectiveStyle(overflowElem, 'overflow-y')
};
// The <html> element cannot have a genuine 'visible' overflow style,
// because the viewport can't expand; 'visible' is really 'auto'.
if (e == htmlElem) {
overflow.x = overflow.x == 'visible' ? 'auto' : overflow.x;
overflow.y = overflow.y == 'visible' ? 'auto' : overflow.y;
}
return overflow;
}
// Returns the scroll offset of the given element.
function getScroll(e) {
if (e == htmlElem) {
return new goog.dom.DomHelper(ownerDoc).getDocumentScroll();
} else {
return new goog.math.Coordinate(e.scrollLeft, e.scrollTop);
}
}
// Check if the element overflows any ancestor element.
for (var container = getOverflowParent(elem);
!!container;
container = getOverflowParent(container)) {
var containerOverflow = getOverflowStyles(container);
// If the container has overflow:visible, the element cannot overflow it.
if (containerOverflow.x == 'visible' && containerOverflow.y == 'visible') {
continue;
}
var containerRect = bot.dom.getClientRect(container);
// Zero-sized containers without overflow:visible hide all descendants.
if (containerRect.width == 0 || containerRect.height == 0) {
return bot.dom.OverflowState.HIDDEN;
}
// Check "underflow": if an element is to the left or above the container
var underflowsX = region.right < containerRect.left;
var underflowsY = region.bottom < containerRect.top;
if ((underflowsX && containerOverflow.x == 'hidden') ||
(underflowsY && containerOverflow.y == 'hidden')) {
return bot.dom.OverflowState.HIDDEN;
} else if ((underflowsX && containerOverflow.x != 'visible') ||
(underflowsY && containerOverflow.y != 'visible')) {
// When the element is positioned to the left or above a container, we
// have to distinguish between the element being completely outside the
// container and merely scrolled out of view within the container.
var containerScroll = getScroll(container);
var unscrollableX = region.right < containerRect.left - containerScroll.x;
var unscrollableY = region.bottom < containerRect.top - containerScroll.y;
if ((unscrollableX && containerOverflow.x != 'visible') ||
(unscrollableY && containerOverflow.x != 'visible')) {
return bot.dom.OverflowState.HIDDEN;
}
var containerState = bot.dom.getOverflowState(container);
return containerState == bot.dom.OverflowState.HIDDEN ?
bot.dom.OverflowState.HIDDEN : bot.dom.OverflowState.SCROLL;
}
// Check "overflow": if an element is to the right or below a container
var overflowsX = region.left >= containerRect.left + containerRect.width;
var overflowsY = region.top >= containerRect.top + containerRect.height;
if ((overflowsX && containerOverflow.x == 'hidden') ||
(overflowsY && containerOverflow.y == 'hidden')) {
return bot.dom.OverflowState.HIDDEN;
} else if ((overflowsX && containerOverflow.x != 'visible') ||
(overflowsY && containerOverflow.y != 'visible')) {
// If the element has fixed position and falls outside the scrollable area
// of the document, then it is hidden.
if (treatAsFixedPosition) {
var docScroll = getScroll(container);
if ((region.left >= htmlElem.scrollWidth - docScroll.x) ||
(region.right >= htmlElem.scrollHeight - docScroll.y)) {
return bot.dom.OverflowState.HIDDEN;
}
}
// If the element can be scrolled into view of the parent, it has a scroll
// state; unless the parent itself is entirely hidden by overflow, in
// which it is also hidden by overflow.
var containerState = bot.dom.getOverflowState(container);
return containerState == bot.dom.OverflowState.HIDDEN ?
bot.dom.OverflowState.HIDDEN : bot.dom.OverflowState.SCROLL;
}
}
// Does not overflow any ancestor.
return bot.dom.OverflowState.NONE;
};
/**
* A regular expression to match the CSS transform matrix syntax.
* @private {!RegExp}
* @const
*/
bot.dom.CSS_TRANSFORM_MATRIX_REGEX_ =
new RegExp('matrix\\(([\\d\\.\\-]+), ([\\d\\.\\-]+), ' +
'([\\d\\.\\-]+), ([\\d\\.\\-]+), ' +
'([\\d\\.\\-]+)(?:px)?, ([\\d\\.\\-]+)(?:px)?\\)');
/**
* Gets the client rectangle of the DOM element. It often returns the same value
* as Element.getBoundingClientRect, but is "fixed" for various scenarios:
* 1. Like goog.style.getClientPosition, it adjusts for the inset border in IE.
* 2. Gets a rect for <map>'s and <area>'s relative to the image using them.
* 3. Gets a rect for SVG elements representing their true bounding box.
* 4. Defines the client rect of the <html> element to be the window viewport.
*
* @param {!Element} elem The element to use.
* @return {!goog.math.Rect} The interaction box of the element.
*/
bot.dom.getClientRect = function(elem) {
var imageMap = bot.dom.maybeFindImageMap_(elem);
if (imageMap) {
return imageMap.rect;
} else if (bot.dom.isElement(elem, goog.dom.TagName.HTML)) {
// Define the client rect of the <html> element to be the viewport.
var doc = goog.dom.getOwnerDocument(elem);
var viewportSize = goog.dom.getViewportSize(goog.dom.getWindow(doc));
return new goog.math.Rect(0, 0, viewportSize.width, viewportSize.height);
} else {
var nativeRect;
try {
// TODO: in IE and Firefox, getBoundingClientRect includes stroke width,
// but getBBox does not.
nativeRect = elem.getBoundingClientRect();
} catch (e) {
// On IE < 9, calling getBoundingClientRect on an orphan element raises
// an "Unspecified Error". All other browsers return zeros.
return new goog.math.Rect(0, 0, 0, 0);
}
var rect = new goog.math.Rect(nativeRect.left, nativeRect.top,
nativeRect.right - nativeRect.left, nativeRect.bottom - nativeRect.top);
// In IE, the element can additionally be offset by a border around the
// documentElement or body element that we have to subtract.
if (goog.userAgent.IE && elem.ownerDocument.body) {
var doc = goog.dom.getOwnerDocument(elem);
rect.left -= doc.documentElement.clientLeft + doc.body.clientLeft;
rect.top -= doc.documentElement.clientTop + doc.body.clientTop;
}
return rect;
}
};
/**
* If given a <map> or <area> element, finds the corresponding image and client
* rectangle of the element; otherwise returns null. The return value is an
* object with 'image' and 'rect' properties. When no image uses the given
* element, the returned rectangle is present but has zero size.
*
* @param {!Element} elem Element to test.
* @return {?{image: Element, rect: !goog.math.Rect}} Image and rectangle.
* @private
*/
bot.dom.maybeFindImageMap_ = function(elem) {
// If not a <map> or <area>, return null indicating so.
var isMap = bot.dom.isElement(elem, goog.dom.TagName.MAP);
if (!isMap && !bot.dom.isElement(elem, goog.dom.TagName.AREA)) {
return null;
}
// Get the <map> associated with this element, or null if none.
var map = isMap ? elem :
(bot.dom.isElement(elem.parentNode, goog.dom.TagName.MAP) ?
elem.parentNode : null);
var image = null, rect = null;
if (map && map.name) {
var mapDoc = goog.dom.getOwnerDocument(map);
// The "//*" XPath syntax can confuse the closure compiler, so we use
// the "/descendant::*" syntax instead.
// TODO: Try to find a reproducible case for the compiler bug.
// TODO: Restrict to applet, img, input:image, and object nodes.
var imageXpath = '/descendant::*[@usemap = "#' + map.name + '"]';
// TODO: Break dependency of bot.locators on bot.dom,
// so bot.locators.findElement can be called here instead.
image = bot.locators.xpath.single(imageXpath, mapDoc);
if (image) {
rect = bot.dom.getClientRect(image);
if (!isMap && elem.shape.toLowerCase() != 'default') {
// Shift and crop the relative area rectangle to the map.
var relRect = bot.dom.getAreaRelativeRect_(elem);
var relX = Math.min(Math.max(relRect.left, 0), rect.width);
var relY = Math.min(Math.max(relRect.top, 0), rect.height);
var w = Math.min(relRect.width, rect.width - relX);
var h = Math.min(relRect.height, rect.height - relY);
rect = new goog.math.Rect(relX + rect.left, relY + rect.top, w, h);
}
}
}
return {image: image, rect: rect || new goog.math.Rect(0, 0, 0, 0)};
};
/**
* Returns the bounding box around an <area> element relative to its enclosing
* <map>. Does not apply to <area> elements with shape=='default'.
*
* @param {!Element} area Area element.
* @return {!goog.math.Rect} Bounding box of the area element.
* @private
*/
bot.dom.getAreaRelativeRect_ = function(area) {
var shape = area.shape.toLowerCase();
var coords = area.coords.split(',');
if (shape == 'rect' && coords.length == 4) {
var x = coords[0], y = coords[1];
return new goog.math.Rect(x, y, coords[2] - x, coords[3] - y);
} else if (shape == 'circle' && coords.length == 3) {
var centerX = coords[0], centerY = coords[1], radius = coords[2];
return new goog.math.Rect(centerX - radius, centerY - radius,
2 * radius, 2 * radius);
} else if (shape == 'poly' && coords.length > 2) {
var minX = coords[0], minY = coords[1], maxX = minX, maxY = minY;
for (var i = 2; i + 1 < coords.length; i += 2) {
minX = Math.min(minX, coords[i]);
maxX = Math.max(maxX, coords[i]);
minY = Math.min(minY, coords[i + 1]);
maxY = Math.max(maxY, coords[i + 1]);
}
return new goog.math.Rect(minX, minY, maxX - minX, maxY - minY);
}
return new goog.math.Rect(0, 0, 0, 0);
};
/**
* Gets the element's client rectangle as a box, optionally clipped to the
* given coordinate or rectangle relative to the client's position. A coordinate
* is treated as a 1x1 rectangle whose top-left corner is the coordinate.
*
* @param {!Element} elem The element.
* @param {!(goog.math.Coordinate|goog.math.Rect)=} opt_region
* Coordinate or rectangle relative to the top-left corner of the element.
* @return {!goog.math.Box} The client region box.
*/
bot.dom.getClientRegion = function(elem, opt_region) {
var region = bot.dom.getClientRect(elem).toBox();
if (opt_region) {
var rect = opt_region instanceof goog.math.Rect ? opt_region :
new goog.math.Rect(opt_region.x, opt_region.y, 1, 1);
region.left = goog.math.clamp(
region.left + rect.left, region.left, region.right);
region.top = goog.math.clamp(
region.top + rect.top, region.top, region.bottom);
region.right = goog.math.clamp(
region.left + rect.width, region.left, region.right);
region.bottom = goog.math.clamp(
region.top + rect.height, region.top, region.bottom);
}
return region;
};
/**
* Trims leading and trailing whitespace from strings, leaving non-breaking
* space characters in place.
*
* @param {string} str The string to trim.
* @return {string} str without any leading or trailing whitespace characters
* except non-breaking spaces.
* @private
*/
bot.dom.trimExcludingNonBreakingSpaceCharacters_ = function(str) {
return str.replace(/^[^\S\xa0]+|[^\S\xa0]+$/g, '');
};
/**
* Helper function for getVisibleText[InDisplayedDom].
* @param {!Array.<string>} lines Accumulated visible lines of text.
* @return {string} cleaned up concatenated lines
* @private
*/
bot.dom.concatenateCleanedLines_ = function(lines) {
lines = goog.array.map(
lines,
bot.dom.trimExcludingNonBreakingSpaceCharacters_);
var joined = lines.join('\n');
var trimmed = bot.dom.trimExcludingNonBreakingSpaceCharacters_(joined);
// Replace non-breakable spaces with regular ones.
return trimmed.replace(/\xa0/g, ' ');
};
/**
* @param {!Element} elem The element to consider.
* @return {string} visible text.
*/
bot.dom.getVisibleText = function(elem) {
var lines = [];