index.ts
11.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
import { tools } from 'evoltagent';
import * as path from 'path';
import type { AnnotateRenderResult, CombineOptions, MisalignedComponentData, IterationScreenshotResult } from './types';
import type { MisalignedComponent } from '../../types/validation-types';
import { annotateRenderWithPlaywright } from './utils/annotate-render';
import { annotateTargetWithPlaywright } from './utils/annotate-target';
import { browserManagement } from './utils/browser-management';
import { combineSideBySide } from './utils/combine';
import { captureAsWebP } from './utils/image-converter';
import { generatePixelDiffHeatmap } from './utils/pixel-diff-heatmap';
import { logger } from '../../utils/logger';
@tools({
annotateRender: {
description:
'Navigate to the dev server, capture a clean render screenshot, inject RED annotation boxes for misaligned components, and capture the annotated render screenshot.',
params: [
{ name: 'serverUrl', type: 'string', description: 'Dev server URL (e.g., http://localhost:5173)' },
{
name: 'misalignedData',
type: 'object',
description: 'MisalignedComponentData[] used to draw RED boxes on the render.',
},
{ name: 'viewport', type: 'object', description: 'Viewport {width,height} to use in Playwright.' },
],
returns: {
type: 'object',
description: 'AnnotateRenderResult containing renderSnap and renderMarked (WebP data URIs).',
},
},
annotateTarget: {
description:
'Fetch the Figma thumbnail, inject GREEN annotation boxes for misaligned components, and return an annotated target screenshot.',
params: [
{ name: 'figmaThumbnailUrl', type: 'string', description: 'Figma thumbnail CDN URL.' },
{
name: 'misalignedData',
type: 'object',
description: 'MisalignedComponentData[] used to draw GREEN boxes on the target.',
},
{ name: 'viewport', type: 'object', description: 'Viewport {width,height} to match the Figma thumbnail.' },
{
name: 'designOffset',
type: 'object',
description: 'Design offset {x,y} used when the thumbnail is not cropped (default behavior is cropped).',
optional: true,
},
],
returns: { type: 'string', description: 'Annotated target screenshot as WebP data URI.' },
},
annotateTargetFromBase64: {
description: 'Annotate target using pre-cached base64 thumbnail data. Use this to avoid redundant Figma thumbnail downloads.',
params: [
{ name: 'figmaThumbnailBase64', type: 'string', description: 'Base64-encoded Figma thumbnail data.' },
{
name: 'misalignedData',
type: 'object',
description: 'MisalignedComponentData[] used to draw GREEN boxes on the target.',
},
{ name: 'viewport', type: 'object', description: 'Viewport {width,height} to match the Figma thumbnail.' },
{
name: 'designOffset',
type: 'object',
description: 'Design offset {x,y} used when the thumbnail is not cropped (default behavior is cropped).',
optional: true,
},
],
returns: { type: 'string', description: 'Annotated target screenshot as WebP data URI.' },
},
combine: {
description: 'Combine two base64 screenshots side-by-side with headers and write to outputPath (WebP).',
params: [
{ name: 'renderMarked', type: 'string', description: 'Left image (render, typically annotated) as base64 data URI.' },
{ name: 'targetMarked', type: 'string', description: 'Right image (target, typically annotated) as base64 data URI.' },
{ name: 'outputPath', type: 'string', description: 'Filesystem output path for the combined WebP.' },
{ name: 'options', type: 'object', description: 'Optional CombineOptions', optional: true },
],
returns: { type: 'string', description: 'The outputPath written.' },
},
diffHeatmap: {
description: 'Generate pixel-diff heatmap between a render screenshot and the target thumbnail.',
params: [
{ name: 'renderSnap', type: 'string', description: 'Render screenshot (WebP data URI).' },
{ name: 'targetSnap', type: 'string', description: 'Target screenshot (WebP data URI) OR URL.' },
],
returns: { type: 'string', description: 'Heatmap image as WebP data URI.' },
},
generateIterationScreenshot: {
description: 'Generate annotated comparison screenshot for validation iteration. Orchestrates annotate + combine for convenience.',
params: [
{ name: 'misalignedComponents', type: 'object', description: 'MisalignedComponent[] from validation result' },
{ name: 'serverUrl', type: 'string', description: 'Dev server URL' },
{ name: 'figmaThumbnailUrl', type: 'string', description: 'Figma thumbnail URL' },
{ name: 'viewport', type: 'object', description: 'Viewport {width, height}' },
{ name: 'designOffset', type: 'object', description: 'Design offset {x, y}' },
{ name: 'outputPath', type: 'string', description: 'Output file path for combined screenshot' },
{
name: 'cachedFigmaThumbnailBase64',
type: 'string',
description: 'Optional cached thumbnail base64',
optional: true,
},
],
returns: { type: 'object', description: 'IterationScreenshotResult with renderMarked, targetMarked, and combinedPath' },
},
})
export class VisualizationTool {
async annotateRender(
serverUrl: string,
misalignedData: MisalignedComponentData[],
viewport: { width: number; height: number }
): Promise<AnnotateRenderResult> {
return await browserManagement(viewport, async (_browser, page) => {
await page.goto(serverUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
await new Promise(r => setTimeout(r, 1000));
const renderSnap = await captureAsWebP(page);
await annotateRenderWithPlaywright(page, misalignedData);
const renderMarked = await captureAsWebP(page);
return { renderSnap, renderMarked };
});
}
async annotateTarget(
figmaThumbnailUrl: string,
misalignedData: MisalignedComponentData[],
viewport: { width: number; height: number },
designOffset?: { x: number; y: number }
): Promise<string> {
const axios = (await import('axios')).default;
const response = await axios.get(figmaThumbnailUrl, { responseType: 'arraybuffer', timeout: 30000 });
const figmaThumbnailBase64 = Buffer.from(response.data).toString('base64');
return await browserManagement(viewport, async browser => {
return await annotateTargetWithPlaywright(browser, figmaThumbnailBase64, misalignedData, viewport, designOffset);
});
}
/**
* Annotate target using pre-cached base64 thumbnail data.
* Use this method when you have already downloaded the Figma thumbnail to avoid redundant downloads.
*/
async annotateTargetFromBase64(
figmaThumbnailBase64: string,
misalignedData: MisalignedComponentData[],
viewport: { width: number; height: number },
designOffset?: { x: number; y: number }
): Promise<string> {
return await browserManagement(viewport, async browser => {
return await annotateTargetWithPlaywright(browser, figmaThumbnailBase64, misalignedData, viewport, designOffset);
});
}
async combine(renderMarked: string, targetMarked: string, outputPath: string, options?: CombineOptions): Promise<string> {
await combineSideBySide(renderMarked, targetMarked, outputPath, options);
return outputPath;
}
async diffHeatmap(renderSnap: string, targetSnap: string): Promise<string> {
return await generatePixelDiffHeatmap(renderSnap, targetSnap);
}
/**
* Generate annotated comparison screenshot for a single iteration.
* This is a convenience method that orchestrates the full screenshot workflow.
*
* @returns IterationScreenshotResult with individual annotated screenshots and combined path
*/
async generateIterationScreenshot(
misalignedComponents: MisalignedComponent[],
serverUrl: string,
figmaThumbnailUrl: string,
viewport: { width: number; height: number },
designOffset: { x: number; y: number },
outputPath: string,
cachedFigmaThumbnailBase64?: string
): Promise<IterationScreenshotResult> {
if (misalignedComponents.length === 0) {
return { renderMarked: '', targetMarked: '', combinedPath: '' };
}
try {
// Transform validation data to visualization format
const misalignedData = this.formatForVisualization(misalignedComponents);
// Annotate render (browser screenshot)
const render = await this.annotateRender(serverUrl, misalignedData, viewport);
// Annotate target (Figma screenshot) - use cached thumbnail if available
const targetMarked = cachedFigmaThumbnailBase64
? await this.annotateTargetFromBase64(cachedFigmaThumbnailBase64, misalignedData, viewport, designOffset)
: await this.annotateTarget(figmaThumbnailUrl, misalignedData, viewport, designOffset);
// Combine into side-by-side comparison (needed for judger visual context in next iteration)
await this.combine(render.renderMarked, targetMarked, outputPath);
logger.printInfoLog(`已保存对比截图:${path.basename(outputPath)}`);
return {
renderMarked: render.renderMarked,
targetMarked,
combinedPath: outputPath,
};
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`生成迭代截图失败:${errorMsg}`);
return { renderMarked: '', targetMarked: '', combinedPath: '' };
}
}
/**
* Transform MisalignedComponent[] to MisalignedComponentData[] format.
* This is an internal helper for converting validation results to visualization format.
*/
private formatForVisualization(components: MisalignedComponent[]): MisalignedComponentData[] {
return components.map((comp, idx) => {
if (comp.elementIds.length === 0) {
logger.printWarnLog(`组件 ${comp.name} 无 elementIds,改用 componentId 作为回退。`);
}
return {
index: idx + 1,
elementId: comp.elementIds[0] || comp.componentId,
elementName: comp.name,
componentId: comp.componentId,
componentName: comp.name,
componentPath: comp.path,
currentX: comp.currentX,
currentY: comp.currentY,
currentWidth: comp.currentWidth,
currentHeight: comp.currentHeight,
targetX: comp.targetX,
targetY: comp.targetY,
targetWidth: comp.targetWidth,
targetHeight: comp.targetHeight,
distance: comp.distance,
xDelta: comp.validationReport.absoluteError[0],
yDelta: comp.validationReport.absoluteError[1],
};
});
}
}