-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
elements.ts
1376 lines (1090 loc) · 32.8 KB
/
elements.ts
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
// NOT patched jquery
import $ from 'jquery'
import _ from '../config/lodash'
import $utils from '../cypress/utils'
import * as $document from './document'
import * as $jquery from './jquery'
import * as $selection from './selection'
import { parentHasDisplayNone } from './visibility'
import * as $window from './window'
import Debug from 'debug'
const debug = Debug('cypress:driver:elements')
const { wrap } = $jquery
const fixedOrStickyRe = /(fixed|sticky)/
const focusableSelectors = [
'a[href]',
'area[href]',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'button:not([disabled])',
'iframe',
'[tabindex]',
'[contenteditable]',
]
const focusableWhenNotDisabledSelectors = [
'a[href]',
'area[href]',
'input',
'select',
'textarea',
'button',
'iframe',
'[tabindex]',
'[contenteditable]',
]
const inputTypeNeedSingleValueChangeRe = /^(date|time|week|month|datetime-local)$/
const canSetSelectionRangeElementRe = /^(text|search|URL|tel|password)$/
const valueIsNumberTypeRe = /progress|meter|li/
declare global {
interface Window {
Element: typeof Element
HTMLElement: typeof HTMLElement
HTMLInputElement: typeof HTMLInputElement
HTMLSelectElement: typeof HTMLSelectElement
HTMLButtonElement: typeof HTMLButtonElement
HTMLOptionElement: typeof HTMLOptionElement
HTMLTextAreaElement: typeof HTMLTextAreaElement
Selection: typeof Selection
SVGElement: typeof SVGElement
EventTarget: typeof EventTarget
Document: typeof Document
}
interface Selection {
modify: Function
}
}
// rules for native methods and props
// if a setter or getter or function then add a native method
// if a traversal, don't
const descriptor = <T extends keyof Window, K extends keyof Window[T]['prototype']>(klass: T, prop: K) => {
const descriptor = Object.getOwnPropertyDescriptor(window[klass].prototype, prop)
if (descriptor === undefined) {
throw new Error(`Error, could not get property descriptor for ${klass} ${prop}. This should never happen`)
}
return descriptor
}
const _getValue = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'value').get
}
if (isTextarea(this)) {
return descriptor('HTMLTextAreaElement', 'value').get
}
if (isSelect(this)) {
return descriptor('HTMLSelectElement', 'value').get
}
if (isButton(this)) {
return descriptor('HTMLButtonElement', 'value').get
}
// is an option element
return descriptor('HTMLOptionElement', 'value').get
}
const _setValue = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'value').set
}
if (isTextarea(this)) {
return descriptor('HTMLTextAreaElement', 'value').set
}
if (isSelect(this)) {
return descriptor('HTMLSelectElement', 'value').set
}
if (isButton(this)) {
return descriptor('HTMLButtonElement', 'value').set
}
// is an options element
return descriptor('HTMLOptionElement', 'value').set
}
const _getSelectionStart = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'selectionStart').get
}
if (isTextarea(this)) {
return descriptor('HTMLTextAreaElement', 'selectionStart').get
}
throw new Error('this should never happen, cannot get selectionStart')
}
const _getSelectionEnd = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'selectionEnd').get
}
if (isTextarea(this)) {
return descriptor('HTMLTextAreaElement', 'selectionEnd').get
}
throw new Error('this should never happen, cannot get selectionEnd')
}
const _nativeFocus = function () {
if ($window.isWindow(this)) {
return window.focus
}
if (isSvg(this)) {
return window.SVGElement.prototype.focus
}
return window.HTMLElement.prototype.focus
}
const _nativeBlur = function () {
if ($window.isWindow(this)) {
return window.blur
}
if (isSvg(this)) {
return window.SVGElement.prototype.blur
}
return window.HTMLElement.prototype.blur
}
const _nativeSetSelectionRange = function () {
if (isInput(this)) {
return window.HTMLInputElement.prototype.setSelectionRange
}
// is textarea
return window.HTMLTextAreaElement.prototype.setSelectionRange
}
const _nativeSelect = function () {
if (isInput(this)) {
return window.HTMLInputElement.prototype.select
}
// is textarea
return window.HTMLTextAreaElement.prototype.select
}
const _isContentEditable = function () {
if (isSvg(this)) {
return false
}
return descriptor('HTMLElement', 'isContentEditable').get
}
const _setType = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'type').set
}
if (isButton(this)) {
return descriptor('HTMLButtonElement', 'type').set
}
throw new Error('this should never happen, cannot set type')
}
const _getType = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'type').get
}
if (isButton(this)) {
return descriptor('HTMLButtonElement', 'type').get
}
throw new Error('this should never happen, cannot get type')
}
const _getMaxLength = function () {
if (isInput(this)) {
return descriptor('HTMLInputElement', 'maxLength').get
}
if (isTextarea(this)) {
return descriptor('HTMLTextAreaElement', 'maxLength').get
}
throw new Error('this should never happen, cannot get maxLength')
}
const nativeGetters = {
value: _getValue,
isContentEditable: _isContentEditable,
isCollapsed: descriptor('Selection', 'isCollapsed').get,
selectionStart: _getSelectionStart,
selectionEnd: _getSelectionEnd,
type: _getType,
activeElement: descriptor('Document', 'activeElement').get,
body: descriptor('Document', 'body').get,
frameElement: Object.getOwnPropertyDescriptor(window, 'frameElement')!.get,
maxLength: _getMaxLength,
}
const nativeSetters = {
value: _setValue,
type: _setType,
}
const nativeMethods = {
addEventListener: window.EventTarget.prototype.addEventListener,
removeEventListener: window.EventTarget.prototype.removeEventListener,
createRange: window.document.createRange,
getSelection: window.document.getSelection,
removeAllRanges: window.Selection.prototype.removeAllRanges,
addRange: window.Selection.prototype.addRange,
execCommand: window.document.execCommand,
getAttribute: window.Element.prototype.getAttribute,
setSelectionRange: _nativeSetSelectionRange,
modify: window.Selection.prototype.modify,
focus: _nativeFocus,
hasFocus: window.document.hasFocus,
blur: _nativeBlur,
select: _nativeSelect,
}
const tryCallNativeMethod = (obj, fn, ...args) => {
try {
return callNativeMethod(obj, fn, ...args)
} catch (err) {
return
}
}
const callNativeMethod = function (obj, fn, ...args) {
const nativeFn = nativeMethods[fn]
if (!nativeFn) {
const fns = _.keys(nativeMethods).join(', ')
throw new Error(`attempted to use a native fn called: ${fn}. Available fns are: ${fns}`)
}
let retFn = nativeFn.apply(obj, args)
if (_.isFunction(retFn)) {
retFn = retFn.apply(obj, args)
}
return retFn
}
const getNativeProp = function<T, K extends keyof T> (obj: T, prop: K): T[K] {
const nativeProp = nativeGetters[prop as string]
if (!nativeProp) {
const props = _.keys(nativeGetters).join(', ')
throw new Error(`attempted to use a native getter prop called: ${prop}. Available props are: ${props}`)
}
let retProp = nativeProp.call(obj, prop)
if (_.isFunction(retProp)) {
// if we got back another function
// then invoke it again
retProp = retProp.call(obj, prop)
}
return retProp
}
const setNativeProp = function<T, K extends keyof T> (obj: T, prop: K, val) {
const nativeProp = nativeSetters[prop as string]
if (!nativeProp) {
const fns = _.keys(nativeSetters).join(', ')
throw new Error(`attempted to use a native setter prop called: ${prop}. Available props are: ${fns}`)
}
let retProp = nativeProp.call(obj, val)
if (_.isFunction(retProp)) {
retProp = retProp.call(obj, val)
}
return retProp
}
interface HTMLValueIsNumberTypeElement extends HTMLElement {
value: number
}
const isValueNumberTypeElement = (el: HTMLElement): el is HTMLValueIsNumberTypeElement => {
return valueIsNumberTypeRe.test(getTagName(el))
}
export interface HTMLSingleValueChangeInputElement extends HTMLInputElement {
type: 'date' | 'time' | 'week' | 'month'
}
const isNeedSingleValueChangeInputElement = (el: HTMLElement): el is HTMLSingleValueChangeInputElement => {
if (!isInput(el)) {
return false
}
return inputTypeNeedSingleValueChangeRe.test((el.getAttribute('type') || '').toLocaleLowerCase())
}
const canSetSelectionRangeElement = (el): el is HTMLElementCanSetSelectionRange => {
//TODO: If IE, all inputs can set selection range
return isTextarea(el) || (isInput(el) && canSetSelectionRangeElementRe.test(getNativeProp(el, 'type')))
}
const getTagName = (el) => {
const tagName = el.tagName || ''
return tagName.toLowerCase()
}
// this property is the tell-all for contenteditable
// should be true for elements:
// - with [contenteditable]
// - with document.designMode = 'on'
const isContentEditable = (el: HTMLElement): el is HTMLContentEditableElement => {
return getNativeProp(el, 'isContentEditable') || $document.getDocumentFromElement(el).designMode === 'on'
}
const isTextarea = (el): el is HTMLTextAreaElement => {
return getTagName(el) === 'textarea'
}
const isInput = (el): el is HTMLInputElement => {
return getTagName(el) === 'input'
}
const isButton = (el): el is HTMLButtonElement => {
return getTagName(el) === 'button'
}
const isSelect = (el): el is HTMLSelectElement => {
return getTagName(el) === 'select'
}
const isOption = (el) => {
return getTagName(el) === 'option'
}
const isOptgroup = (el) => {
return getTagName(el) === 'optgroup'
}
const isBody = (el): el is HTMLBodyElement => {
return getTagName(el) === 'body'
}
const isIframe = (el) => {
return getTagName(el) === 'iframe'
}
const isHTML = (el) => {
return getTagName(el) === 'html'
}
const isSvg = function (el): el is SVGElement {
try {
return 'ownerSVGElement' in el
} catch (error) {
return false
}
}
// active element is the default if its null
// or it's equal to document.body that is not contenteditable
const activeElementIsDefault = (activeElement, body: HTMLElement) => {
return !activeElement || (activeElement === body && !isContentEditable(body))
}
const isFocused = (el) => {
try {
let doc
if (Cypress.config('experimentalShadowDomSupport') && isWithinShadowRoot(el)) {
doc = el.getRootNode()
} else {
doc = $document.getDocumentFromElement(el)
}
const { activeElement, body } = doc
if (activeElementIsDefault(activeElement, body)) {
return false
}
return doc.activeElement === el
} catch (err) {
return false
}
}
const isFocusedOrInFocused = (el: HTMLElement) => {
debug('isFocusedOrInFocus', el)
const doc = $document.getDocumentFromElement(el)
if (!doc.hasFocus()) {
return false
}
const { activeElement } = doc
let elToCheckCurrentlyFocused
let isContentEditableEl = false
if (isFocusable($(el))) {
elToCheckCurrentlyFocused = el
} else if (isContentEditable(el)) {
isContentEditableEl = true
elToCheckCurrentlyFocused = $selection.getHostContenteditable(el)
}
debug('elToCheckCurrentlyFocused', elToCheckCurrentlyFocused)
if (elToCheckCurrentlyFocused && elToCheckCurrentlyFocused === activeElement) {
if (isContentEditableEl) {
// we make sure the the current document selection (blinking cursor) is inside the element
const sel = doc.getSelection()
if (sel?.rangeCount) {
const range = sel.getRangeAt(0)
const curSelectionContainer = range.commonAncestorContainer
const selectionInsideElement = el.contains(curSelectionContainer)
debug('isInFocused by document selection?', selectionInsideElement, ':', curSelectionContainer, 'is inside', el)
return selectionInsideElement
}
// no selection, not in focused
return false
}
return true
}
return false
}
// mostly useful when traversing up parent nodes and wanting to
// stop traversal if el is undefined or is html, body, or document
const isUndefinedOrHTMLBodyDoc = ($el: JQuery<HTMLElement>) => {
return !$el || !$el[0] || $el.is('body,html') || $document.isDocument($el[0])
}
const isElement = function (obj): obj is HTMLElement | JQuery<HTMLElement> {
try {
if ($jquery.isJquery(obj)) {
obj = obj[0]
}
return Boolean(obj && _.isElement(obj))
} catch (error) {
return false
}
}
const isDesignModeDocumentElement = (el: HTMLElement) => {
return isElement(el) && getTagName(el) === 'html' && isContentEditable(el)
}
/**
* The element can be activeElement, receive focus events, and also receive keyboard events
*/
const isFocusable = ($el: JQuery<HTMLElement>) => {
return (
_.some(focusableSelectors, (sel) => $el.is(sel)) ||
isDesignModeDocumentElement($el.get(0))
)
}
/**
* The element can be activeElement, receive focus events, and also receive keyboard events
* OR, it is a disabled element that would have been focusable
*/
const isFocusableWhenNotDisabled = ($el: JQuery<HTMLElement>) => {
return (
_.some(focusableWhenNotDisabledSelectors, (sel) => $el.is(sel)) ||
isDesignModeDocumentElement($el.get(0))
)
}
const isW3CRendered = (el) => {
// @see https://html.spec.whatwg.org/multipage/rendering.html#being-rendered
return !(parentHasDisplayNone(wrap(el)) || wrap(el).css('visibility') === 'hidden')
}
const isW3CFocusable = (el) => {
// @see https://html.spec.whatwg.org/multipage/interaction.html#focusable-area
return isFocusable(wrap(el)) && isW3CRendered(el)
}
type JQueryOrEl<T extends HTMLElement> = JQuery<T> | T
const isInputType = function (el: JQueryOrEl<HTMLElement>, type) {
el = ([] as HTMLElement[]).concat($jquery.unwrap(el))[0]
if (!isInput(el) && !isButton(el)) {
return false
}
// NOTE: use DOMElement.type instead of getAttribute('type') since
// <input type="asdf"> will have type="text", and behaves like text type
const elType = (getNativeProp(el, 'type') || '').toLowerCase()
if (_.isArray(type)) {
return _.includes(type, elType)
}
return elType === type
}
const isAttrType = function (el: HTMLInputElement, type: string) {
const elType = (el.getAttribute('type') || '').toLowerCase()
return elType === type
}
const isScrollOrAuto = (prop) => {
return prop === 'scroll' || prop === 'auto'
}
const isAncestor = ($el, $maybeAncestor) => {
return $el.parents().index($maybeAncestor) >= 0
}
const getFirstCommonAncestor = (el1, el2) => {
// get all parents of each element
const el1Ancestors = [el1].concat(getAllParents(el1))
const el2Ancestors = [el2].concat(getAllParents(el2))
let a
let b
// choose the largest tree of parents to
// traverse up
if (el1Ancestors.length > el2Ancestors.length) {
a = el1Ancestors
b = el2Ancestors
} else {
a = el2Ancestors
b = el1Ancestors
}
// for each ancestor of the largest of the two
// parent arrays, check if the other parent array
// contains it.
for (const ancestor of a) {
if (b.includes(ancestor)) {
return ancestor
}
}
return el2
}
const isShadowRoot = (maybeRoot) => {
return maybeRoot?.toString() === '[object ShadowRoot]'
}
const isWithinShadowRoot = (node: HTMLElement) => {
return isShadowRoot(node.getRootNode())
}
const getParentNode = (el) => {
// if the element has a direct parent element,
// simply return it.
if (el.parentElement) {
return el.parentElement
}
const root = el.getRootNode()
// if the element is inside a shadow root,
// return the host of the root.
if (root && isWithinShadowRoot(el)) {
return root.host
}
return null
}
const getParent = ($el: JQuery): JQuery => {
return $(getParentNode($el[0]))
}
const getAllParents = (el: HTMLElement, untilSelector?: string) => {
const collectParents = (parents, node) => {
const parent = getParentNode(node)
if (!parent || untilSelector && $(parent).is(untilSelector)) {
return parents
}
return collectParents(parents.concat(parent), parent)
}
return collectParents([], el)
}
const isChild = ($el, $maybeChild) => {
return $el.children().index($maybeChild) >= 0
}
const isSelector = ($el: JQuery<HTMLElement>, selector) => {
return $el.is(selector)
}
const isDisabled = ($el: JQuery) => {
return $el.prop('disabled')
}
const isReadOnlyInputOrTextarea = (
el: HTMLInputElement | HTMLTextAreaElement,
) => {
return el.readOnly
}
const isReadOnlyInput = ($el: JQuery) => {
return $el.prop('readonly')
}
const isDetached = ($el) => {
return !isAttached($el)
}
const isAttached = function ($el) {
// if we're being given window
// then these are automaticallyed attached
if ($window.isWindow($el)) {
// there is a code path when forcing focus and
// blur on the window where this check is necessary.
return true
}
const nodes: Node[] = []
// push the set of elements to the nodes array
// whether they are wrapped or not
if ($jquery.isJquery($el)) {
nodes.push(...$el.toArray())
} else if ($el) {
nodes.push($el)
}
// if there are no nodes, nothing is attached
if (nodes.length === 0) {
return false
}
// check that every node has an active window
// and is connected to the dom
return nodes.every((node) => {
const doc = $document.getDocumentFromElement(node)
if (!$document.hasActiveWindow(doc)) {
return false
}
return node.isConnected
})
}
/**
* @param {HTMLElement} el
*/
const isDetachedEl = (el) => {
return !isAttachedEl(el)
}
/**
* @param {HTMLElement} el
*/
const isAttachedEl = function (el) {
return isAttached($(el))
}
const isSame = function ($el1, $el2) {
const el1 = $jquery.unwrap($el1)
const el2 = $jquery.unwrap($el2)
return el1 && el2 && _.isEqual(el1, el2)
}
export interface HTMLContentEditableElement extends HTMLElement {
isContenteditable: true
}
export interface HTMLTextLikeInputElement extends HTMLInputElement {
type:
| 'text'
| 'password'
| 'email'
| 'number'
| 'date'
| 'week'
| 'month'
| 'time'
| 'datetime'
| 'datetime-local'
| 'search'
| 'url'
| 'tel'
setSelectionRange: HTMLInputElement['setSelectionRange']
}
export interface HTMLElementCanSetSelectionRange extends HTMLElement {
setSelectionRange: HTMLInputElement['setSelectionRange']
value: HTMLInputElement['value']
selectionStart: number
selectionEnd: number
}
export type HTMLTextLikeElement = HTMLTextAreaElement | HTMLTextLikeInputElement | HTMLContentEditableElement
const isTextLike = function (el: HTMLElement): el is HTMLTextLikeElement {
const $el = $jquery.wrap(el)
const sel = (selector) => {
return isSelector($el, selector)
}
const type = (type) => {
if (isInput(el)) {
return isInputType(el, type)
}
return false
}
const isContentEditableElement = isContentEditable(el)
if (isContentEditableElement) return true
return _.some([
isContentEditableElement,
sel('textarea'),
sel(':text'),
type('text'),
type('password'),
type('email'),
type('number'),
type('date'),
type('week'),
type('month'),
type('time'),
type('datetime'),
type('datetime-local'),
type('search'),
type('url'),
type('tel'),
])
}
const isInputAllowingImplicitFormSubmission = function ($el) {
const type = (type) => {
return isInputType($el, type)
}
// https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#implicit-submission
return _.some([
type('text'),
type('search'),
type('url'),
type('tel'),
type('email'),
type('password'),
type('date'),
type('month'),
type('week'),
type('time'),
type('datetime-local'),
type('number'),
])
}
const isScrollable = ($el) => {
const checkDocumentElement = (win, documentElement) => {
// Check if body height is higher than window height
if (win.innerHeight < documentElement.scrollHeight) {
debug('isScrollable: window scrollable on Y')
return true
}
// Check if body width is higher than window width
if (win.innerWidth < documentElement.scrollWidth) {
debug('isScrollable: window scrollable on X')
return true
}
// else return false since the window is not scrollable
return false
}
// if we're the window, we want to get the document's
// element and check its size against the actual window
if ($window.isWindow($el)) {
const win = $el
return checkDocumentElement(win, win.document.documentElement)
}
const el = $el[0]
// window.getComputedStyle(el) will error if el is undefined
if (!el) {
return false
}
// if we're any other element, we do some css calculations
// to see that the overflow is correct and the scroll
// area is larger than the actual height or width
const { overflow, overflowY, overflowX } = window.getComputedStyle(el)
// y axis
// if our content height is less than the total scroll height
if (el.clientHeight < el.scrollHeight) {
// and our element has scroll or auto overflow or overflowX
if (isScrollOrAuto(overflow) || isScrollOrAuto(overflowY)) {
debug('isScrollable: clientHeight < scrollHeight and scroll/auto overflow')
return true
}
}
// x axis
if (el.clientWidth < el.scrollWidth) {
if (isScrollOrAuto(overflow) || isScrollOrAuto(overflowX)) {
debug('isScrollable: clientWidth < scrollWidth and scroll/auto overflow')
return true
}
}
return false
}
const isDescendent = ($el1, $el2) => {
if (!$el2) {
return false
}
// if they are equal, consider them a descendent
if ($el1.get(0) === $el2.get(0)) {
return true
}
// walk up the tree until we find a parent which
// equals the descendent, if ever
return findParent($el2.get(0), (node) => {
if (node === $el1.get(0)) {
return node
}
}) === $el1.get(0)
}
const findParent = (el, condition) => {
const collectParent = (node) => {
const parent = getParentNode(node)
if (!parent) return null
const parentMatchingCondition = condition(parent, node)
if (parentMatchingCondition) return parentMatchingCondition
return collectParent(parent)
}
return collectParent(el)
}
// in order to simulate actual user behavior we need to do the following:
// 1. take our element and figure out its center coordinate
// 2. check to figure out the element listed at those coordinates
// 3. if this element is ourself or our descendants, click whatever was returned
// 4. else throw an error because something is covering us up
const getFirstFocusableEl = ($el: JQuery<HTMLElement>) => {
if (isFocusable($el)) {
return $el
}
const $parent = getParent($el)
// if we have no parent then just return
// the window since that can receive focus
if (!$parent.length) {
const win = $window.getWindowByElement($el.get(0))
return $(win)
}
return getFirstFocusableEl(getParent($el))
}
const getActiveElByDocument = ($el: JQuery<HTMLElement>): HTMLElement | null => {
let activeElement
if (Cypress.config('experimentalShadowDomSupport') && isWithinShadowRoot($el[0])) {
activeElement = ($el[0].getRootNode() as ShadowRoot).activeElement
} else {
activeElement = getNativeProp($el[0].ownerDocument as Document, 'activeElement')
}
if (isFocused(activeElement)) {
return activeElement as HTMLElement
}
return null
}
const getFirstParentWithTagName = ($el, tagName) => {
if (isUndefinedOrHTMLBodyDoc($el) || !tagName) {
return null
}
// if this element is already the tag we want,
// return it
if (getTagName($el.get(0)) === tagName) {
return $el
}
// walk up the tree until we find a parent with
// the tag we want
return findParent($el.get(0), (node) => {
if (getTagName(node) === tagName) {
return $jquery.wrap(node)
}
return null
})
}
const getFirstFixedOrStickyPositionParent = ($el) => {
if (isUndefinedOrHTMLBodyDoc($el)) {
return null
}
if (fixedOrStickyRe.test($el.css('position'))) {
return $el
}
// walk up the tree until we find an element
// with a fixed/sticky position
return findParent($el.get(0), (node) => {
let wrapped = $jquery.wrap(node)
if (fixedOrStickyRe.test(wrapped.css('position'))) {
return wrapped
}