aggregate-elements.ts
2.57 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
/**
* Aggregate element-level rectangles into component-level bounds and misalignment metrics.
*/
/**
* Rectangle with position and dimensions.
*/
export interface Rectangle {
x: number;
y: number;
width: number;
height: number;
}
/**
* Converts a rect-like object to a proper Rectangle type.
*/
export function toRect(rectLike: { x: number; y: number; width: number; height: number }): Rectangle {
return { x: rectLike.x, y: rectLike.y, width: rectLike.width, height: rectLike.height };
}
/**
* Aggregate bounding box result.
*/
export interface BoundingBox {
minX: number;
minY: number;
maxRight: number;
maxBottom: number;
width: number;
height: number;
}
/**
* Position error calculation result.
*/
export interface PositionError {
errorX: number;
errorY: number;
distance: number;
}
/**
* Minimum shape required for component-level aggregation.
*/
export interface ComponentAggregationData {
positions: Rectangle[];
targets: Rectangle[];
}
export function calculateAggregateBoundingBox(rectangles: Rectangle[]): BoundingBox {
if (rectangles.length === 0) {
throw new Error('Cannot calculate bounding box from empty array');
}
const minX = Math.min(...rectangles.map(r => r.x));
const minY = Math.min(...rectangles.map(r => r.y));
const maxRight = Math.max(...rectangles.map(r => r.x + r.width));
const maxBottom = Math.max(...rectangles.map(r => r.y + r.height));
return {
minX,
minY,
maxRight,
maxBottom,
width: maxRight - minX,
height: maxBottom - minY,
};
}
export function calculatePositionError(current: BoundingBox, target: BoundingBox): PositionError {
const errorX = Math.abs(target.minX - current.minX);
const errorY = Math.abs(target.minY - current.minY);
const distance = Math.sqrt(errorX ** 2 + errorY ** 2);
return { errorX, errorY, distance };
}
export function calculateComponentMetrics(
compData: ComponentAggregationData,
positionThreshold: number
): {
currentBounds: BoundingBox;
targetBounds: BoundingBox;
error: PositionError;
} | null {
if (compData.positions.length === 0 || compData.targets.length === 0) {
return null;
}
const currentBounds = calculateAggregateBoundingBox(compData.positions);
const targetBounds = calculateAggregateBoundingBox(compData.targets);
const error = calculatePositionError(currentBounds, targetBounds);
if (error.distance <= positionThreshold) {
return null;
}
return { currentBounds, targetBounds, error };
}