-
-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathrectangles.ts
More file actions
755 lines (674 loc) · 29.6 KB
/
Copy pathrectangles.ts
File metadata and controls
755 lines (674 loc) · 29.6 KB
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
import { Jimp } from 'jimp'
import { ANDROID_OFFSETS, IOS_OFFSETS } from '../helpers/constants.js'
import { calculateDprData, getBase64ScreenshotSize, isObject } from '../helpers/utils.js'
import { getElementPositionAndroid, getElementPositionDesktop, getElementWebviewPosition } from './elementPosition.js'
import type {
DetermineDeviceBlockOutsOptions,
DetermineWebFullPageIgnoreRegionsOptions,
DetermineWebScreenIgnoreRegionsOptions,
DetermineWebElementIgnoreRegionsOptions,
DeviceRectangles,
ElementRectangles,
PrepareIgnoreRectanglesOptions,
PreparedIgnoreRectangles,
RectanglesOutput,
ScreenRectanglesOptions,
SplitIgnores,
StatusAddressToolBarRectangles,
StatusAddressToolBarRectanglesOptions,
} from './rectangles.interfaces.js'
import type { ElementIgnore } from 'src/commands/element.interfaces.js'
/**
* Determine the element rectangles on the page / screenshot
*/
export async function determineElementRectangles({
browserInstance,
base64Image,
options,
element,
}: ElementRectangles): Promise<RectanglesOutput> {
// Determine screenshot data
const {
devicePixelRatio,
deviceRectangles,
initialDevicePixelRatio,
innerHeight,
isAndroid,
isAndroidNativeWebScreenshot,
isEmulated,
isIOS,
} = options
const internalDpr = isEmulated ? initialDevicePixelRatio : devicePixelRatio
const { height } = getBase64ScreenshotSize(base64Image, internalDpr)
let elementPosition
// Determine the element position on the screenshot
if (isIOS) {
elementPosition = await getElementWebviewPosition(browserInstance, element, { deviceRectangles })
} else if (isAndroid) {
elementPosition = await getElementPositionAndroid(browserInstance, element, { deviceRectangles, isAndroidNativeWebScreenshot })
} else {
elementPosition = await getElementPositionDesktop(browserInstance, element, { innerHeight, screenshotHeight: height })
}
// Validate if the element is visible
if (elementPosition.height === 0 || elementPosition.width === 0) {
let selectorMessage = ' '
if (element.selector) {
selectorMessage = `, with selector "$(${element.selector})",`
}
const message = `The element${selectorMessage}is not visible. The dimensions are ${elementPosition.width}x${elementPosition.height}`
throw new Error(message)
}
// Determine the rectangles based on the device pixel ratio
return calculateDprData(
{
height: elementPosition.height,
width: elementPosition.width,
x: elementPosition.x,
y: elementPosition.y,
},
internalDpr,
)
}
/**
* Determine the rectangles of the screen for the screenshot
*/
export function determineScreenRectangles(base64Image: string, options: ScreenRectanglesOptions): RectanglesOutput {
// Determine screenshot data
const {
devicePixelRatio,
enableLegacyScreenshotMethod,
initialDevicePixelRatio,
innerHeight,
innerWidth,
isEmulated,
isIOS,
isAndroidChromeDriverScreenshot,
isAndroidNativeWebScreenshot,
isLandscape,
} = options
// For #967: When a screenshot of an emulated device is taken, but the browser was initially
// started as a "desktop" session, so not with emulated caps, we need to store the initial
// devicePixelRatio when we take a screenshot and enableLegacyScreenshotMethod is enabled
const internalDpr = isEmulated && enableLegacyScreenshotMethod ? initialDevicePixelRatio : devicePixelRatio
const { height, width } = getBase64ScreenshotSize(base64Image, internalDpr)
// Determine the width
const screenshotWidth = isIOS || isAndroidChromeDriverScreenshot ? width : innerWidth
const screenshotHeight = isIOS || isAndroidNativeWebScreenshot ? height : innerHeight
const isRotated = isLandscape && height > width
// Determine the rectangles
return calculateDprData(
{
height: isRotated ? screenshotWidth : screenshotHeight,
width: isRotated ? screenshotHeight : screenshotWidth,
x: 0,
y: 0,
},
internalDpr,
)
}
/**
* Determine the rectangles for the mobile devices
*/
export function determineStatusAddressToolBarRectangles({ deviceRectangles, options }:{
deviceRectangles: DeviceRectangles,
options: StatusAddressToolBarRectanglesOptions,
}): StatusAddressToolBarRectangles {
const {
blockOutSideBar,
blockOutStatusBar,
blockOutToolBar,
isAndroid,
isAndroidNativeWebScreenshot,
isMobile,
isViewPortScreenshot,
} = options
const rectangles = []
if (
isViewPortScreenshot &&
isMobile &&
( isAndroid && isAndroidNativeWebScreenshot || !isAndroid )
) {
const statusAddressBar = {
x: deviceRectangles.statusBarAndAddressBar.x, y: deviceRectangles.statusBarAndAddressBar.y,
width: deviceRectangles.statusBarAndAddressBar.width, height: deviceRectangles.statusBarAndAddressBar.height,
}
const toolBar = {
x: deviceRectangles.bottomBar.x, y: deviceRectangles.bottomBar.y,
width: deviceRectangles.bottomBar.width, height: deviceRectangles.bottomBar.height,
}
const leftSidePadding = {
x: deviceRectangles.leftSidePadding.x, y: deviceRectangles.leftSidePadding.y,
width: deviceRectangles.leftSidePadding.width, height: deviceRectangles.leftSidePadding.height,
}
const rightSidePadding = {
x: deviceRectangles.rightSidePadding.x, y: deviceRectangles.rightSidePadding.y,
width: deviceRectangles.rightSidePadding.width, height: deviceRectangles.rightSidePadding.height,
}
if (blockOutStatusBar) {
rectangles.push(statusAddressBar)
}
if (blockOutToolBar) {
rectangles.push(toolBar)
}
if (blockOutSideBar) {
rectangles.push(leftSidePadding, rightSidePadding)
}
}
return rectangles
}
/**
* Validate that the element is a WebdriverIO element
*/
export function isWdioElement(x: unknown) {
if (!isObject(x)) {
return false
}
const region = x as WebdriverIO.Element
const keys: (keyof WebdriverIO.Element)[] = ['selector', 'elementId']
return keys.every(key => typeof region[key] === 'string')
}
/**
* Validate that the object is a valid ignore region
*/
export function validateIgnoreRegion(x: unknown) {
if (!isObject(x)) {
return false
}
const region = x as RectanglesOutput
const keys: (keyof RectanglesOutput)[] = ['height', 'width', 'x', 'y']
return keys.every(key => typeof region[key] === 'number')
}
/**
* Format the error message
*/
export function formatErrorMessage(item:unknown, message:string) {
const formattedItem = isObject(item) ? JSON.stringify(item) : item
return `${formattedItem} ${message}`
}
/**
* Split the ignores into elements and regions and throw an error if
* an element is not a valid WebdriverIO element/region
*/
export function splitIgnores(items:unknown[]): SplitIgnores{
const elements = []
const regions = []
const errorMessages = []
for (const item of items) {
if (Array.isArray(item)) {
for (const nestedItem of item) {
if (!isWdioElement(nestedItem)) {
errorMessages.push(formatErrorMessage(nestedItem, 'is not a valid WebdriverIO element'))
} else {
elements.push(nestedItem as WebdriverIO.Element)
}
}
} else if (isWdioElement(item)) {
elements.push(item as WebdriverIO.Element)
} else if (validateIgnoreRegion(item)) {
regions.push(item as RectanglesOutput)
} else {
errorMessages.push(formatErrorMessage(item, 'is not a valid WebdriverIO element or region'))
}
}
if (errorMessages.length > 0) {
throw new Error('Invalid elements or regions: ' + errorMessages.join(', '))
}
return { elements, regions }
}
/**
* Get the regions from the elements
*/
export async function getRegionsFromElements(browserInstance: WebdriverIO.Browser, elements: WebdriverIO.Element[]): Promise<RectanglesOutput[]> {
const regions = []
for (const element of elements) {
const region = await browserInstance.getElementRect(element.elementId)
regions.push(region)
}
return regions
}
/**
* Translate ignores to regions
*/
export async function determineIgnoreRegions(
browserInstance: WebdriverIO.Browser,
ignores: (ElementIgnore | ElementIgnore[])[],
): Promise<RectanglesOutput[]>{
const awaitedIgnores = await Promise.all(ignores)
const { elements, regions } = splitIgnores(awaitedIgnores)
const regionsFromElements = await getRegionsFromElements(browserInstance, elements)
return [...regions, ...regionsFromElements]
.map((region:RectanglesOutput) => ({
x: Math.round(region.x),
y: Math.round(region.y),
width: Math.round(region.width),
height: Math.round(region.height),
}))
}
/**
* Translate ignores to regions for web screen (viewport) screenshots.
* Uses getBoundingClientRect (CSS pixels) and converts to device pixels,
* accounting for the viewport offset on native web screenshot devices.
*
* Coordinate systems per platform:
* - Desktop / Android ChromeDriver: screenshot is viewport-only, BCR × DPR
* - iOS: full-device screenshot, viewport offset is in CSS points → (BCR + offset) × DPR
* - Android native web: full-device screenshot, viewport offset is already in
* device pixels (injectWebviewOverlay pre-scales by DPR) → BCR × DPR + offset
*/
export async function determineWebScreenIgnoreRegions(
options: DetermineWebScreenIgnoreRegionsOptions,
ignores: (ElementIgnore | ElementIgnore[])[],
): Promise<RectanglesOutput[]> {
const awaitedIgnores = await Promise.all(ignores)
const { elements, regions } = splitIgnores(awaitedIgnores)
const { browserInstance, devicePixelRatio, deviceRectangles, isAndroid, isAndroidNativeWebScreenshot, isIOS, ignoreRegionPadding: padding } = options
// Get raw (unrounded) BCR values so we can multiply by DPR before
// rounding. The shared getBoundingClientRect script pre-rounds to CSS
// integers which loses sub-pixel precision that matters at higher DPRs.
const rawBcr = (el: HTMLElement) => {
const rect = el.getBoundingClientRect()
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }
}
// Browsers can invalidate element references when the DOM is mutated
// (e.g. by beforeScreenshot CSS/style injection). Re-query via $$ to
// get fresh refs. Use $$ per unique selector so multiple elements
// sharing the same selector (e.g. from a $$ call) each resolve to
// the correct match by index.
const regionsFromElements: RectanglesOutput[] = []
const selectorCache = new Map<string, WebdriverIO.Element[]>()
const selectorIndex = new Map<string, number>()
for (const element of elements) {
const selector = element.selector as string
if (!selectorCache.has(selector)) {
const fresh = await browserInstance.$$(selector)
selectorCache.set(selector, fresh as unknown as WebdriverIO.Element[])
selectorIndex.set(selector, 0)
}
const idx = selectorIndex.get(selector)!
const cached = selectorCache.get(selector)!
const el = idx < cached.length ? cached[idx] : element
selectorIndex.set(selector, idx + 1)
const bcr = await browserInstance.execute(rawBcr, el as any) as RectanglesOutput
regionsFromElements.push(bcr)
}
return [...regions, ...regionsFromElements]
.map((region: RectanglesOutput) => {
// Use floor for top-left and ceil for bottom-right so the
// device-pixel rectangle fully covers the CSS-pixel element.
// Rounding position and size independently can miss edge pixels.
let cssX = region.x
let cssY = region.y
if (isIOS) {
cssX += deviceRectangles.viewport.x
cssY += deviceRectangles.viewport.y
}
const left = Math.floor(cssX * devicePixelRatio)
const top = Math.floor(cssY * devicePixelRatio)
const right = Math.ceil((cssX + region.width) * devicePixelRatio)
const bottom = Math.ceil((cssY + region.height) * devicePixelRatio)
let x = left
let y = top
if (isAndroid && isAndroidNativeWebScreenshot) {
// Android native web viewport offset is already in device pixels
x += deviceRectangles.viewport.x
y += deviceRectangles.viewport.y
}
let width = right - left
let height = bottom - top
if (padding > 0) {
x = Math.max(0, x - padding)
y = Math.max(0, y - padding)
width += 2 * padding
height += 2 * padding
}
return { x, y, width, height }
})
}
/**
* Translate ignores to regions for web full-page screenshots (desktop and mobile).
* Full-page image (BiDi or scroll-and-stitch) is in document coordinates: (0,0) = top-left
* of document, device pixels. Uses getBoundingClientRect + (scrollX, scrollY) for elements,
* then converts to device pixels. Same logic for all platforms; no viewport offset needed
* because the stitched canvas is built in document space.
*/
export async function determineWebFullPageIgnoreRegions(
options: DetermineWebFullPageIgnoreRegionsOptions,
ignores: (ElementIgnore | ElementIgnore[])[],
): Promise<RectanglesOutput[]> {
const awaitedIgnores = await Promise.all(ignores)
const { elements, regions } = splitIgnores(awaitedIgnores)
const { browserInstance, devicePixelRatio, ignoreRegionPadding: padding, fullPageCropTopPaddingCSS: cropTop = 0 } = options
const rawDocumentBcr = (el: HTMLElement) => {
const rect = el.getBoundingClientRect()
return {
x: rect.x + window.scrollX,
y: rect.y + window.scrollY,
width: rect.width,
height: rect.height,
}
}
const regionsFromElements: RectanglesOutput[] = []
const selectorCache = new Map<string, WebdriverIO.Element[]>()
const selectorIndex = new Map<string, number>()
for (const element of elements) {
const selector = element.selector as string
if (!selectorCache.has(selector)) {
const fresh = await browserInstance.$$(selector)
selectorCache.set(selector, fresh as unknown as WebdriverIO.Element[])
selectorIndex.set(selector, 0)
}
const idx = selectorIndex.get(selector)!
const cached = selectorCache.get(selector)!
const el = idx < cached.length ? cached[idx] : element
selectorIndex.set(selector, idx + 1)
const bcr = await browserInstance.execute(rawDocumentBcr, el as any) as RectanglesOutput
regionsFromElements.push(bcr)
}
return [...regions, ...regionsFromElements]
.map((region: RectanglesOutput) => {
const left = Math.floor(region.x * devicePixelRatio)
const right = Math.ceil((region.x + region.width) * devicePixelRatio)
// On mobile full-page scroll-and-stitch, the canvas crops cropTop (e.g. 6px) from the top
// of each tile, so canvas y = (documentY - cropTop) × DPR
const topDevice = Math.floor((region.y - cropTop) * devicePixelRatio)
const bottomDevice = Math.ceil((region.y + region.height - cropTop) * devicePixelRatio)
const top = Math.max(0, topDevice)
const bottom = Math.max(top, bottomDevice)
let x = left
let y = top
let width = right - left
let height = bottom - top
if (padding > 0) {
x = Math.max(0, x - padding)
y = Math.max(0, y - padding)
width += 2 * padding
height += 2 * padding
}
return { x, y, width, height }
})
}
/**
* Translate ignores to regions for web element screenshots.
* By default regions are in *element-local* device pixels so they match the cropped element image
* (BiDi clip or fallback full-screenshot crop, both at device pixel size).
* Exception: when the element screenshot is from the native driver on Android native web
* (isWebDriverElementScreenshot && isAndroidNativeWebScreenshot), the driver returns an image at
* CSS pixel size (downscaled). We then output regions in CSS pixel coordinates (divide by DPR)
* so they align with that image. Fallback (full screenshot + crop) is at device size, so we do
* not downscale when fallback was used.
*/
export async function determineWebElementIgnoreRegions(
options: DetermineWebElementIgnoreRegionsOptions,
ignores: (ElementIgnore | ElementIgnore[])[],
): Promise<RectanglesOutput[]> {
const awaitedIgnores = await Promise.all(ignores)
const { elements, regions } = splitIgnores(awaitedIgnores)
const {
browserInstance,
devicePixelRatio,
rootElement,
ignoreRegionPadding: padding,
isAndroidNativeWebScreenshot,
isWebDriverElementScreenshot,
} = options
// Compute bounding boxes relative to the root element: (childBCR - rootBCR)
const rawRelativeBcr = (el: HTMLElement, root: HTMLElement) => {
const elRect = el.getBoundingClientRect()
const rootRect = root.getBoundingClientRect()
return {
x: elRect.x - rootRect.x,
y: elRect.y - rootRect.y,
width: elRect.width,
height: elRect.height,
}
}
const regionsFromElements: RectanglesOutput[] = []
const selectorCache = new Map<string, WebdriverIO.Element[]>()
const selectorIndex = new Map<string, number>()
for (const element of elements) {
const selector = element.selector as string
if (!selectorCache.has(selector)) {
const fresh = await browserInstance.$$(selector)
selectorCache.set(selector, fresh as unknown as WebdriverIO.Element[])
selectorIndex.set(selector, 0)
}
const idx = selectorIndex.get(selector)!
const cached = selectorCache.get(selector)!
const el = idx < cached.length ? cached[idx] : element
selectorIndex.set(selector, idx + 1)
const bcr = await browserInstance.execute(rawRelativeBcr, el as any, rootElement as any) as RectanglesOutput
regionsFromElements.push(bcr)
}
// Both literal regions and element-derived regions are currently expected
// to be in CSS pixels relative to the element. Scale everything by DPR and
// express as device-pixel rectangles using the same floor-based rounding
// strategy as the BiDi element clip (x/y/width/height all floored).
// Then expand each region by ignoreRegionPadding on each side (configurable, default 1)
// to reduce 1px boundary differences on high-DPR / BiDi.
let result = [...regions, ...regionsFromElements]
.map((region: RectanglesOutput) => {
// Floor position (x/y) to include the start pixel, ceil size (width/height)
// to include the end pixel. Flooring size can lose 1px when CSS * DPR has
// a fractional part, causing the last row or column of an element to fall
// outside the ignored region.
let x = Math.floor(region.x * devicePixelRatio)
let y = Math.floor(region.y * devicePixelRatio)
let width = Math.ceil(region.width * devicePixelRatio)
let height = Math.ceil(region.height * devicePixelRatio)
if (padding > 0) {
x = Math.max(0, x - padding)
y = Math.max(0, y - padding)
width += 2 * padding
height += 2 * padding
}
return { x, y, width, height }
})
// Only downscale when the element image is at CSS pixel size: native driver element screenshot
// on Android native web (fallback false). Fallback uses a device-pixel crop, so no downscale.
if (isAndroidNativeWebScreenshot === true && isWebDriverElementScreenshot === true && devicePixelRatio > 0) {
const dpr = devicePixelRatio
result = result.map((r) => ({
x: Math.round(r.x / dpr),
y: Math.round(r.y / dpr),
width: Math.round(r.width / dpr),
height: Math.round(r.height / dpr),
}))
}
return result
}
/**
* Determine the device block outs
*/
export async function determineDeviceBlockOuts({ isAndroid, screenCompareOptions, instanceData }: DetermineDeviceBlockOutsOptions){
const rectangles: RectanglesOutput[] = []
const { blockOutStatusBar, blockOutToolBar } = screenCompareOptions
const { deviceRectangles:{ homeBar, statusBar } } = instanceData
if (blockOutStatusBar){
rectangles.push(statusBar)
}
if (isAndroid){
//
} else if (blockOutToolBar){
rectangles.push(homeBar)
}
// @TODO: This is from the native-app-compare module, I can't really find the diffs between the two
// if (options.blockOutStatusBar) {
// rectangles.push(deviceInfo.rectangles.statusBar)
// }
// if (driver.isAndroid && options.blockOutNavigationBar) {
// rectangles.push(deviceInfo.rectangles.androidNavigationBar)
// }
return rectangles
}
/**
* Return a status bar rectangle for hybrid-app fallback when the overlay reports zero height.
* Uses IOS_OFFSETS / ANDROID_OFFSETS so the system status bar is blocked out in webview context.
* Android: uses device platformVersion (e.g. "14.0") as API level when present and in list; otherwise latest.
* iOS: keyed by screen size only (no OS version in data). When device not in list, uses latest entry.
*/
function getHybridAppStatusBarFallback(
deviceRectangles: DeviceRectangles,
isAndroid: boolean,
platformVersion?: string,
): RectanglesOutput | null {
const { width: screenWidth, height: screenHeight } = deviceRectangles.screenSize
if (screenWidth === 0 || screenHeight === 0) {
return null
}
if (isAndroid) {
const apiLevels = Object.keys(ANDROID_OFFSETS).map(Number)
const latestApiLevel = apiLevels.length > 0 ? Math.max(...apiLevels) : 14
const deviceApiLevel = platformVersion !== undefined ? parseInt(platformVersion, 10) : NaN
const useApiLevel =
Number.isInteger(deviceApiLevel) && apiLevels.includes(deviceApiLevel)
? deviceApiLevel
: latestApiLevel
const statusBarHeight = ANDROID_OFFSETS[useApiLevel as keyof typeof ANDROID_OFFSETS]?.STATUS_BAR ?? 24
return {
x: 0,
y: 0,
width: screenWidth,
height: statusBarHeight,
}
}
const isIphone = screenWidth < 1024 && screenHeight < 1024
const deviceType = isIphone ? 'IPHONE' : 'IPAD'
const portraitHeight = screenWidth > screenHeight ? screenWidth : screenHeight
const keys = Object.keys(IOS_OFFSETS[deviceType]).map(Number)
const exactMatch = keys.includes(portraitHeight)
const offsetPortraitHeight = exactMatch
? portraitHeight
: (keys.length > 0 ? Math.max(...keys) : (isIphone ? 667 : 1024))
const orientation = screenWidth > screenHeight ? 'LANDSCAPE' : 'PORTRAIT'
const currentOffsets = IOS_OFFSETS[deviceType][offsetPortraitHeight]?.[orientation]
const statusBarHeight = currentOffsets?.STATUS_BAR ?? (isIphone ? 44 : 20)
return {
x: 0,
y: 0,
width: screenWidth,
height: statusBarHeight,
}
}
/**
* Prepare all ignore rectangles for image comparison
*/
export async function prepareIgnoreRectangles(options: PrepareIgnoreRectanglesOptions): Promise<PreparedIgnoreRectangles> {
const {
blockOut,
ignoreRegions,
deviceRectangles,
devicePixelRatio,
isMobile,
isNativeContext,
isAndroid,
isAndroidNativeWebScreenshot,
isViewPortScreenshot,
imageCompareOptions,
isHybridApp,
platformVersion,
actualFilePath
} = options
// Get blockOut rectangles
let webStatusAddressToolBarOptions: RectanglesOutput[] = []
// Handle mobile web status/address/toolbar rectangles
if (isMobile && !isNativeContext) {
const statusAddressToolBarOptions = {
blockOutSideBar: imageCompareOptions.blockOutSideBar,
blockOutStatusBar: imageCompareOptions.blockOutStatusBar,
blockOutToolBar: imageCompareOptions.blockOutToolBar,
isAndroid,
isAndroidNativeWebScreenshot,
isMobile,
isViewPortScreenshot,
} as StatusAddressToolBarRectanglesOptions
webStatusAddressToolBarOptions.push(
...(determineStatusAddressToolBarRectangles({ deviceRectangles, options: statusAddressToolBarOptions })) || []
)
// Hybrid-app fallback: in webview the overlay often reports statusBarAndAddressBar height 0.
// Use native offsets (IOS_OFFSETS / ANDROID_OFFSETS) so the system status bar is still blocked out.
const needStatusBarFallback =
imageCompareOptions.blockOutStatusBar !== false &&
(isHybridApp === true || deviceRectangles.statusBarAndAddressBar.height === 0)
if (needStatusBarFallback) {
const fallback = getHybridAppStatusBarFallback(deviceRectangles, isAndroid, platformVersion)
if (fallback && fallback.height > 0) {
webStatusAddressToolBarOptions.push(fallback)
}
}
if (webStatusAddressToolBarOptions.length > 0) {
// There's an issue with the resemble lib when all the rectangles are 0,0,0,0, it will see this as a full
// blockout of the image and the comparison will succeed with 0 % difference.
// Additionally, rectangles with either width or height equal to 0 will result in an entire axis being ignored
// due to how resemble handles falsy values. Filter those out up front.
webStatusAddressToolBarOptions = webStatusAddressToolBarOptions
.filter((rectangle) => !(rectangle.x === 0 && rectangle.y === 0 && rectangle.width === 0 && rectangle.height === 0))
.filter((rectangle) => rectangle.width > 0 && rectangle.height > 0)
}
// Handle home bar (iOS) blockOut for full page screenshots
// The toolbar should be blocked out by default (when blockOutToolBar is true or undefined)
if (!isViewPortScreenshot && imageCompareOptions.blockOutToolBar !== false && actualFilePath) {
try {
// For iOS: block out home bar
if (!isAndroid && deviceRectangles.homeBar.height > 0) {
const image = await Jimp.read(actualFilePath)
const imageHeightDevicePixels = image.bitmap.height
const imageHeightCssPixels = imageHeightDevicePixels / devicePixelRatio
// Adjust home bar X position relative to the viewport (full page image only contains viewport)
const viewportXCssPixels = deviceRectangles.viewport.x
const homeBarXRelativeToViewport = deviceRectangles.homeBar.x - viewportXCssPixels
// Position the home bar at the bottom of the full page image
const homeBarYFullPageCssPixels = imageHeightCssPixels - deviceRectangles.homeBar.height
const homeBarRectangle: RectanglesOutput = {
x: homeBarXRelativeToViewport,
y: homeBarYFullPageCssPixels,
width: deviceRectangles.homeBar.width,
height: deviceRectangles.homeBar.height,
}
webStatusAddressToolBarOptions.push(homeBarRectangle)
}
} catch (_error) {
// If we can't read the image, skip adding the toolbar blockOut
// This shouldn't happen in normal operation, but we don't want to fail the comparison
}
}
}
// blockOut and device bar rectangles are in CSS pixels, scale by DPR
const dprScaledBoxes = [
...blockOut,
...webStatusAddressToolBarOptions
]
.map(
(rectangles) => {
return calculateDprData(
{
bottom: rectangles.y + rectangles.height,
right: rectangles.x + rectangles.width,
left: rectangles.x,
top: rectangles.y,
},
isAndroid ? 1 : devicePixelRatio,
)
},
)
// ignoreRegions: for web they are already in device pixels (pre-scaled by the caller).
// For native iOS app they are in logical pixels (getElementRect / statusBar/homeBar),
// so we scale by DPR here to match the device-pixel screenshot.
const isNativeIos = isNativeContext && isMobile && !isAndroid
const preScaledIgnoreBoxes = ignoreRegions.map((rectangles) => {
const box = {
left: rectangles.x,
top: rectangles.y,
right: rectangles.x + rectangles.width,
bottom: rectangles.y + rectangles.height,
}
if (isNativeIos) {
return calculateDprData({ ...box }, devicePixelRatio)
}
return box
})
const ignoredBoxes = [...dprScaledBoxes, ...preScaledIgnoreBoxes]
return {
ignoredBoxes,
hasIgnoreRectangles: ignoredBoxes.length > 0
}
}