Skip to content
Source
Sign inSign up

snapShotSource.ts

39 lines1.5 KB

1import type { SnapShotAccessibilityNode, SnapShotSource } from "@t3tools/contracts";
2​
3export function resizeSnapShotSource(
4 source: SnapShotSource,
5 imageSize?: { readonly width: number; readonly height: number },
6): SnapShotSource {
7 const accessibility = source.accessibility;
8 if (
9 !imageSize ||
10 accessibility?.format !== "element-tree" ||
11 (imageSize.width === accessibility.imageSize.width &&
12 imageSize.height === accessibility.imageSize.height)
13 )
14 return source;
15​
16 const scaleX = imageSize.width / accessibility.imageSize.width;
17 const scaleY = imageSize.height / accessibility.imageSize.height;
18 const resizeNode = (node: SnapShotAccessibilityNode): SnapShotAccessibilityNode => {
19 let bounds = null;
20 if (node.bounds) {
21 const x = Math.min(imageSize.width, Math.round(node.bounds.x * scaleX));
22 const y = Math.min(imageSize.height, Math.round(node.bounds.y * scaleY));
23 const right = Math.min(
24 imageSize.width,
25 Math.round((node.bounds.x + node.bounds.width) * scaleX),
26 );
27 const bottom = Math.min(
28 imageSize.height,
29 Math.round((node.bounds.y + node.bounds.height) * scaleY),
30 );
31 if (right > x && bottom > y) bounds = { x, y, width: right - x, height: bottom - y };
32 }
33 return { ...node, bounds, children: node.children.map(resizeNode) };
34 };
35 return {
36 ...source,
37 accessibility: { ...accessibility, imageSize, root: resizeNode(accessibility.root) },
38 };