/
dom.js
443 lines (368 loc) · 11.5 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
import _ from 'lodash'
import { $ } from '@packages/driver'
import Promise from 'bluebird'
import selectorPlaygroundHighlight from '../selector-playground/highlight'
const styles = (styleString) => {
return styleString.replace(/\s*\n\s*/g, '')
}
const resetStyles = `
border: none !important;
margin: 0 !important;
padding: 0 !important;
`
function addHitBoxLayer (coords, body) {
if (body == null) {
body = $('body')
}
const height = 10
const width = 10
const dotHeight = 4
const dotWidth = 4
const top = coords.y - height / 2
const left = coords.x - width / 2
const dotTop = height / 2 - dotHeight / 2
const dotLeft = width / 2 - dotWidth / 2
const boxStyles = styles(`
${resetStyles}
position: absolute;
top: ${top}px;
left: ${left}px;
width: ${width}px;
height: ${height}px;
background-color: red;
border-radius: 5px;
box-shadow: 0 0 5px #333;
z-index: 2147483647;
`)
const box = $(`<div class="__cypress-highlight" style="${boxStyles}" />`)
const wrapper = $(`<div style="${styles(resetStyles)} position: relative" />`).appendTo(box)
const dotStyles = styles(`
${resetStyles}
position: absolute;
top: ${dotTop}px;
left: ${dotLeft}px;
height: ${dotHeight}px;
width: ${dotWidth}px;
height: ${dotHeight}px;
background-color: pink;
border-radius: 5px;
`)
$(`<div style="${dotStyles}">`).appendTo(wrapper)
return box.appendTo(body)
}
function addElementBoxModelLayers ($el, body) {
if (body == null) {
body = $('body')
}
const dimensions = getElementDimensions($el)
const container = $('<div class="__cypress-highlight">')
const layers = {
Content: '#9FC4E7',
Padding: '#C1CD89',
Border: '#FCDB9A',
Margin: '#F9CC9D',
}
// create the margin / bottom / padding layers
_.each(layers, (color, attr) => {
let obj
switch (attr) {
case 'Content':
// rearrange the contents offset so
// its inside of our border + padding
obj = {
width: dimensions.width,
height: dimensions.height,
top: dimensions.offset.top + dimensions.borderTop + dimensions.paddingTop,
left: dimensions.offset.left + dimensions.borderLeft + dimensions.paddingLeft,
}
break
default:
obj = {
width: getDimensionsFor(dimensions, attr, 'width'),
height: getDimensionsFor(dimensions, attr, 'height'),
top: dimensions.offset.top,
left: dimensions.offset.left,
}
}
// if attr is margin then we need to additional
// subtract what the actual marginTop + marginLeft
// values are, since offset disregards margin completely
if (attr === 'Margin') {
obj.top -= dimensions.marginTop
obj.left -= dimensions.marginLeft
}
// bail if the dimensions of this layer match the previous one
// so we dont create unnecessary layers
if (dimensionsMatchPreviousLayer(obj, container)) return
return createLayer($el, attr, color, container, obj)
})
container.appendTo(body)
container.children().each((index, el) => {
const $el = $(el)
const top = $el.data('top')
const left = $el.data('left')
// dont ask... for some reason we
// have to run offset twice!
_.times(2, () => $el.offset({ top, left }))
})
return container
}
function getOrCreateSelectorHelperDom ($body) {
let $container = $body.find('.__cypress-selector-playground')
if ($container.length) {
const shadowRoot = $container.find('.__cypress-selector-playground-shadow-root-container')[0].shadowRoot
return Promise.resolve({
$container,
shadowRoot,
$reactContainer: $(shadowRoot).find('.react-container'),
$cover: $container.find('.__cypress-selector-playground-cover'),
})
}
$container = $('<div />')
.addClass('__cypress-selector-playground')
.css({ position: 'static' })
.appendTo($body)
const $shadowRootContainer = $('<div />')
.addClass('__cypress-selector-playground-shadow-root-container')
.css({ position: 'static' })
.appendTo($container)
const shadowRoot = $shadowRootContainer[0].attachShadow({ mode: 'open' })
const $reactContainer = $('<div />')
.addClass('react-container')
.appendTo(shadowRoot)
const $cover = $('<div />')
.addClass('__cypress-selector-playground-cover')
.appendTo($container)
return Promise.try(() => fetch('/__cypress/runner/cypress_selector_playground.css'))
.then((result) => {
return result.text()
})
.then((content) => {
$('<style />', { html: content }).prependTo(shadowRoot)
return { $container, shadowRoot, $reactContainer, $cover }
})
.catch((error) => {
console.error('Selector playground failed to load styles:', error) // eslint-disable-line no-console
return { $container, shadowRoot, $reactContainer, $cover }
})
}
function addOrUpdateSelectorPlaygroundHighlight ({ $el, $body, selector, showTooltip, onClick }) {
getOrCreateSelectorHelperDom($body)
.then(({ $container, shadowRoot, $reactContainer, $cover }) => {
if (!$el) {
selectorPlaygroundHighlight.unmount($reactContainer[0])
$cover.off('click')
$container.remove()
return
}
const borderSize = 2
const styles = $el.map((__, el) => {
const $el = $(el)
const offset = $el.offset()
return {
position: 'absolute',
margin: 0,
padding: 0,
width: $el.outerWidth(),
height: $el.outerHeight(),
top: offset.top - borderSize,
left: offset.left - borderSize,
transform: $el.css('transform'),
zIndex: getZIndex($el),
}
}).get()
if (styles.length === 1) {
$cover
.css(styles[0])
.off('click')
.on('click', onClick)
}
selectorPlaygroundHighlight.render($reactContainer[0], {
selector,
appendTo: shadowRoot,
boundary: $body[0],
showTooltip,
styles,
})
})
}
function createLayer ($el, attr, color, container, dimensions) {
const transform = $el.css('transform')
const css = {
transform,
width: dimensions.width,
height: dimensions.height,
position: 'absolute',
zIndex: getZIndex($el),
backgroundColor: color,
opacity: 0.6,
}
return $('<div>')
.css(css)
.attr('data-top', dimensions.top)
.attr('data-left', dimensions.left)
.attr('data-layer', attr)
.prependTo(container)
}
function dimensionsMatchPreviousLayer (obj, container) {
// since we're prepending to the container that
// means the previous layer is actually the first child element
const previousLayer = container.children().first()
// bail if there is no previous layer
if (!previousLayer.length) { return }
return obj.width === previousLayer.width() &&
obj.height === previousLayer.height()
}
function getDimensionsFor (dimensions, attr, dimension) {
return dimensions[`${dimension}With${attr}`]
}
function getZIndex (el) {
if (/^(auto|0)$/.test(el.css('zIndex'))) {
return 2147483647
} else {
return _.toNumber(el.css('zIndex'))
}
}
function getElementDimensions (el) {
const dimensions = {
offset: el.offset(), // offset disregards margin but takes into account border + padding
height: el.height(), // we want to use height here (because that always returns just the content hight) instead of .css() because .css('height') is altered based on whether box-sizing: border-box is set
width: el.width(),
paddingTop: getPadding(el, 'top'),
paddingRight: getPadding(el, 'right'),
paddingBottom: getPadding(el, 'bottom'),
paddingLeft: getPadding(el, 'left'),
borderTop: getBorder(el, 'top'),
borderRight: getBorder(el, 'right'),
borderBottom: getBorder(el, 'bottom'),
borderLeft: getBorder(el, 'left'),
marginTop: getMargin(el, 'top'),
marginRight: getMargin(el, 'right'),
marginBottom: getMargin(el, 'bottom'),
marginLeft: getMargin(el, 'left'),
}
// innerHeight: Get the current computed height for the first
// element in the set of matched elements, including padding but not border.
// outerHeight: Get the current computed height for the first
// element in the set of matched elements, including padding, border,
// and optionally margin. Returns a number (without 'px') representation
// of the value or null if called on an empty set of elements.
dimensions.heightWithPadding = el.innerHeight()
dimensions.heightWithBorder = el.innerHeight() + getTotalFor(['borderTop', 'borderBottom'], dimensions)
dimensions.heightWithMargin = el.outerHeight(true)
dimensions.widthWithPadding = el.innerWidth()
dimensions.widthWithBorder = el.innerWidth() + getTotalFor(['borderRight', 'borderLeft'], dimensions)
dimensions.widthWithMargin = el.outerWidth(true)
return dimensions
}
function getAttr (el, attr) {
// nuke anything thats not a number or a negative symbol
const num = _.toNumber(el.css(attr).replace(/[^0-9\.-]+/, ''))
if (!_.isFinite(num)) {
throw new Error('Element attr did not return a valid number')
}
return num
}
function getPadding (el, dir) {
return getAttr(el, `padding-${dir}`)
}
function getBorder (el, dir) {
return getAttr(el, `border-${dir}-width`)
}
function getMargin (el, dir) {
return getAttr(el, `margin-${dir}`)
}
function getTotalFor (directions, dimensions) {
return _.reduce(directions, (memo, direction) => memo + dimensions[direction], 0)
}
function getOuterSize (el) {
return {
width: el.outerWidth(true),
height: el.outerHeight(true),
}
}
function isInViewport (win, el) {
let rect = el.getBoundingClientRect()
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= $(win).height() &&
rect.right <= $(win).width()
)
}
function scrollIntoView (win, el) {
if (!el || isInViewport(win, el)) return
el.scrollIntoView()
}
const sizzleRe = /sizzle/i
function getElementsForSelector ({ root, selector, method, cypressDom }) {
let $el = null
try {
if (method === 'contains') {
$el = root.find(cypressDom.getContainsSelector(selector))
if ($el.length) {
$el = cypressDom.getFirstDeepestElement($el)
}
} else {
$el = root.find(selector)
}
} catch (err) {
// if not a sizzle error, ignore it and let $el be null
if (!sizzleRe.test(err.stack)) throw err
}
return $el
}
function addCssAnimationDisabler ($body) {
$(`
<style id="__cypress-animation-disabler">
*, *:before, *:after {
transition-property: none !important;
animation: none !important;
}
</style>
`).appendTo($body)
}
function removeCssAnimationDisabler ($body) {
$body.find('#__cypress-animation-disabler').remove()
}
function addBlackout ($body, selector) {
let $el
try {
$el = $body.find(selector)
if (!$el.length) return
} catch (err) {
// if it's an invalid selector, just ignore it
return
}
const dimensions = getElementDimensions($el)
const width = dimensions.widthWithBorder
const height = dimensions.heightWithBorder
const top = dimensions.offset.top
const left = dimensions.offset.left
const style = styles(`
${resetStyles}
position: absolute;
top: ${top}px;
left: ${left}px;
width: ${width}px;
height: ${height}px;
background-color: black;
z-index: 2147483647;
`)
$(`<div class="__cypress-blackout" style="${style}">`).appendTo($body)
}
function removeBlackouts ($body) {
$body.find('.__cypress-blackout').remove()
}
export default {
addBlackout,
removeBlackouts,
addElementBoxModelLayers,
addHitBoxLayer,
addOrUpdateSelectorPlaygroundHighlight,
addCssAnimationDisabler,
removeCssAnimationDisabler,
getElementsForSelector,
getOuterSize,
scrollIntoView,
}