extract-protocol-context.ts
7.97 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
/**
* Unified Protocol Context Extraction
*
* Extracts all validation-relevant data from protocol in a single traversal.
* Replaces the legacy multi-step extraction pipeline:
* - extractFigmaTreeFromProtocol
* - normalizeFigmaCoordinates
* - FigmaNodeService
* - extractElementMetadata
*
* Core principle: Protocol is the single source of truth. Extract once, use everywhere.
*/
import type { Protocol } from '../../../../types/protocol-types';
import type {
ComponentInfo,
ElementInfo,
ElementMetadataRegistry,
FigmaPosition,
ValidationContext,
ValidationFrameInfo,
} from '../../../../types/validation-types';
import { workspaceManager } from '../../../../utils/workspace';
import type { WorkspaceStructure } from '../../../../types/workspace-types';
/**
* Extract unified validation context from protocol.
*
* Single traversal builds all needed maps:
* - Component info (id, name, path)
* - Element metadata with normalized positions
* - Figma positions with offset applied
*
* @param protocol - Protocol structure tree (Protocol)
* @returns ValidationContext containing all data needed for validation
*/
export function extractValidationContext(protocol: Protocol): ValidationContext {
// Extract offset from root bounding box
const offset = extractOffset(protocol);
const elements = new Map<string, ElementInfo>();
const components = new Map<string, ComponentInfo>();
const elementToComponent = new Map<string, ComponentInfo>();
const figmaPositions: Record<string, FigmaPosition | undefined> = {};
// Single traversal of protocol tree
traverseProtocol(protocol, node => {
const componentInfo: ComponentInfo = {
id: node.id,
name: node.data.name,
path: node.data.componentPath ?? node.data.path ?? node.data.kebabName ?? node.id,
};
components.set(node.id, componentInfo);
// Determine item type based on children
const hasChildren = Array.isArray(node.children) && node.children.length > 0;
const itemType: 'frame' | 'component' = hasChildren ? 'frame' : 'component';
// Extract elements from this component
if (node.data.elements && Array.isArray(node.data.elements)) {
extractElementsRecursive(
node.data.elements as ValidationFrameInfo[],
componentInfo,
itemType,
elements,
elementToComponent,
figmaPositions,
offset
);
}
});
return { offset, elements, components, elementToComponent, figmaPositions };
}
/**
* Extract coordinate offset from protocol root.
*/
function extractOffset(protocol: Protocol): { x: number; y: number } {
// First try: protocol.data.layout.boundingBox (pre-computed CSS coordinates)
if (protocol.data.layout?.boundingBox) {
return {
x: protocol.data.layout.boundingBox.left,
y: protocol.data.layout.boundingBox.top,
};
}
// Second try: first element's absoluteBoundingBox (Figma coordinates)
const firstElement = protocol.data.elements?.[0] as ValidationFrameInfo | undefined;
if (firstElement?.absoluteBoundingBox) {
return {
x: firstElement.absoluteBoundingBox.x,
y: firstElement.absoluteBoundingBox.y,
};
}
// Default: no offset
return { x: 0, y: 0 };
}
/**
* Traverse protocol structure tree and invoke callback for each node.
*/
function traverseProtocol(node: Protocol, callback: (node: Protocol) => void): void {
callback(node);
if (node.children && Array.isArray(node.children)) {
for (const child of node.children) {
traverseProtocol(child, callback);
}
}
}
/**
* Recursively extract elements from Figma node tree.
* Applies offset to positions and builds element metadata.
*/
function extractElementsRecursive(
elements: ValidationFrameInfo[],
componentInfo: ComponentInfo,
itemType: 'frame' | 'component',
elementsMap: Map<string, ElementInfo>,
elementToComponent: Map<string, ComponentInfo>,
figmaPositions: Record<string, FigmaPosition | undefined>,
offset: { x: number; y: number }
): void {
for (const element of elements) {
if (!element || !element.id) continue;
const bbox = element.absoluteBoundingBox;
const position: FigmaPosition = bbox
? {
x: bbox.x - offset.x,
y: bbox.y - offset.y,
w: bbox.width,
h: bbox.height,
}
: { x: 0, y: 0, w: 0, h: 0 };
// Store normalized Figma position
figmaPositions[element.id] = position;
// Store element metadata
elementsMap.set(element.id, {
id: element.id,
name: element.name,
type: element.type,
position,
layoutMode: element.layoutMode,
primaryAxisAlignItems: element.primaryAxisAlignItems,
counterAxisAlignItems: element.counterAxisAlignItems,
itemSpacing: element.itemSpacing,
paddingTop: element.paddingTop,
paddingRight: element.paddingRight,
paddingBottom: element.paddingBottom,
paddingLeft: element.paddingLeft,
constraints: element.constraints as Record<string, unknown> | undefined,
parentComponentId: componentInfo.id,
parentComponentName: componentInfo.name,
parentComponentPath: componentInfo.path,
parentItemType: itemType,
});
// Store element-to-component mapping
elementToComponent.set(element.id, componentInfo);
// Recurse into children and frames
if (element.children && Array.isArray(element.children)) {
extractElementsRecursive(element.children, componentInfo, itemType, elementsMap, elementToComponent, figmaPositions, offset);
}
if (element.frames && Array.isArray(element.frames)) {
extractElementsRecursive(element.frames, componentInfo, itemType, elementsMap, elementToComponent, figmaPositions, offset);
}
}
}
// ============================================================================
// Compatibility Helpers
// ============================================================================
/**
* Extract component paths from context and resolve to absolute filesystem paths.
*
* Transforms protocol alias paths (@/components/Button) to absolute paths
* (/Users/.../my-app/src/components/Button/index.tsx)
*
* @param context - Validation context with component info
* @param workspace - Workspace structure for path resolution
* @returns Map of component IDs to absolute filesystem paths
*/
export function extractComponentPaths(context: ValidationContext, workspace: WorkspaceStructure): Record<string, string> {
const paths: Record<string, string> = {};
for (const [id, info] of context.components) {
if (info.path) {
paths[id] = workspaceManager.resolveAppSrc(workspace, workspaceManager.resolveComponentPath(info.path));
}
}
return paths;
}
/**
* Convert ValidationContext to ElementMetadataRegistry for compatibility.
*/
export function toElementMetadataRegistry(context: ValidationContext): ElementMetadataRegistry {
const elements = new Map<
string,
{
id: string;
name: string;
parentComponentId: string;
parentComponentName: string;
parentComponentPath: string;
parentItemType: 'frame' | 'component';
}
>();
for (const [id, element] of context.elements) {
elements.set(id, {
id: element.id,
name: element.name,
parentComponentId: element.parentComponentId,
parentComponentName: element.parentComponentName,
parentComponentPath: element.parentComponentPath,
parentItemType: element.parentItemType,
});
}
return { elements, components: context.components };
}