File size: 14,148 Bytes
57026c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Figma Element Extractor
Extracts all UI elements from Figma with their dev-mode specifications.
Traverses the node tree recursively and extracts properties for comparison.
"""

from typing import Dict, List, Optional, Any, Tuple
from .element_schema import (
    UIElement, ElementType, ElementBounds, ElementStyles,
    FIGMA_TYPE_MAP, rgb_to_hex
)


class FigmaElementExtractor:
    """
    Extracts UI elements from Figma file data.
    Mimics Figma Dev Mode by extracting all design specifications.
    """
    
    # Keywords to detect element types from names
    BUTTON_KEYWORDS = ["button", "btn", "cta", "submit", "pay", "checkout", "continue", "add", "remove"]
    INPUT_KEYWORDS = ["input", "field", "textfield", "textarea", "email", "password", "card", "cvv", "expiry"]
    CHECKBOX_KEYWORDS = ["checkbox", "check", "toggle"]
    PRICE_KEYWORDS = ["price", "total", "subtotal", "amount", "$", "cost"]
    HEADING_KEYWORDS = ["heading", "title", "header", "h1", "h2", "h3"]
    
    def __init__(self, frame_bounds: Optional[Dict] = None):
        """
        Initialize extractor.
        
        Args:
            frame_bounds: The bounds of the parent frame (for relative positioning)
        """
        self.frame_bounds = frame_bounds or {"x": 0, "y": 0}
        self.elements: List[UIElement] = []
        self.element_count = 0
    
    def extract_from_frame(self, frame_node: Dict, viewport: str = "desktop") -> List[UIElement]:
        """
        Extract all elements from a Figma frame.
        
        Args:
            frame_node: The frame node from Figma API
            viewport: "desktop" or "mobile"
            
        Returns:
            List of UIElement objects
        """
        self.elements = []
        self.element_count = 0
        
        # Get frame bounds for relative positioning
        self.frame_bounds = frame_node.get("absoluteBoundingBox", {"x": 0, "y": 0})
        
        # Start recursive extraction
        self._extract_node(frame_node, parent_id=None, depth=0)
        
        print(f"     📊 Extracted {len(self.elements)} elements from {viewport} frame")
        return self.elements
    
    def _extract_node(self, node: Dict, parent_id: Optional[str], depth: int) -> Optional[str]:
        """
        Recursively extract a node and its children.
        
        Returns:
            The ID of the created element, or None if skipped
        """
        node_type = node.get("type", "")
        node_name = node.get("name", "")
        node_id = node.get("id", "")
        
        # Skip invisible nodes
        if not node.get("visible", True):
            return None
        
        # Create element
        element = self._create_element(node, parent_id, depth)
        
        if element:
            self.elements.append(element)
            current_id = element.id
            
            # Process children
            children = node.get("children", [])
            child_ids = []
            
            for child in children:
                child_id = self._extract_node(child, current_id, depth + 1)
                if child_id:
                    child_ids.append(child_id)
            
            # Update children IDs
            element.children_ids = child_ids
            
            return current_id
        
        # If we skipped this node, still process children with same parent
        children = node.get("children", [])
        for child in children:
            self._extract_node(child, parent_id, depth)
        
        return None
    
    def _create_element(self, node: Dict, parent_id: Optional[str], depth: int) -> Optional[UIElement]:
        """
        Create a UIElement from a Figma node.
        """
        node_type = node.get("type", "")
        node_name = node.get("name", "")
        node_id = node.get("id", "")
        
        # Get bounds
        bounds_data = node.get("absoluteBoundingBox")
        if not bounds_data:
            return None
        
        # Calculate relative position (relative to frame)
        bounds = ElementBounds(
            x=bounds_data.get("x", 0) - self.frame_bounds.get("x", 0),
            y=bounds_data.get("y", 0) - self.frame_bounds.get("y", 0),
            width=bounds_data.get("width", 0),
            height=bounds_data.get("height", 0)
        )
        
        # Skip very small elements (likely decorative)
        if bounds.width < 5 or bounds.height < 5:
            return None
        
        # Determine element type
        element_type = self._determine_element_type(node, node_name)
        
        # Extract styles
        styles = self._extract_styles(node)
        
        # Extract text content
        text_content = None
        if node_type == "TEXT":
            text_content = node.get("characters", "")
        
        # Check if interactive
        is_interactive = element_type in [
            ElementType.BUTTON, ElementType.INPUT, ElementType.LINK,
            ElementType.CHECKBOX, ElementType.RADIO, ElementType.SELECT
        ]
        
        self.element_count += 1
        
        return UIElement(
            id=f"figma_{node_id}",
            element_type=element_type,
            name=node_name,
            bounds=bounds,
            styles=styles,
            text_content=text_content,
            parent_id=parent_id,
            depth=depth,
            source="figma",
            original_type=node_type,
            is_interactive=is_interactive
        )
    
    def _determine_element_type(self, node: Dict, name: str) -> ElementType:
        """
        Determine the semantic element type from Figma node.
        Uses node type + name heuristics.
        """
        node_type = node.get("type", "")
        name_lower = name.lower()
        
        # Check by Figma node type first
        if node_type == "TEXT":
            # Check if it's a heading or price
            font_size = node.get("style", {}).get("fontSize", 14)
            
            if any(kw in name_lower for kw in self.PRICE_KEYWORDS):
                return ElementType.PRICE
            if any(kw in name_lower for kw in self.HEADING_KEYWORDS) or font_size >= 24:
                return ElementType.HEADING
            if "label" in name_lower:
                return ElementType.LABEL
            return ElementType.TEXT
        
        # Check by name keywords
        if any(kw in name_lower for kw in self.BUTTON_KEYWORDS):
            return ElementType.BUTTON
        
        if any(kw in name_lower for kw in self.INPUT_KEYWORDS):
            return ElementType.INPUT
        
        if any(kw in name_lower for kw in self.CHECKBOX_KEYWORDS):
            return ElementType.CHECKBOX
        
        if any(kw in name_lower for kw in self.PRICE_KEYWORDS):
            return ElementType.PRICE
        
        # Check for image
        if node_type == "IMAGE" or "image" in name_lower or "img" in name_lower:
            return ElementType.IMAGE
        
        # Check for icon (small vectors or frames with icon in name)
        bounds = node.get("absoluteBoundingBox", {})
        is_small = bounds.get("width", 0) < 50 and bounds.get("height", 0) < 50
        if node_type == "VECTOR" or (is_small and ("icon" in name_lower or "ico" in name_lower)):
            return ElementType.ICON
        
        # Check for divider/line
        if node_type == "LINE" or "divider" in name_lower or "separator" in name_lower:
            return ElementType.DIVIDER
        
        # Check for card
        if "card" in name_lower:
            return ElementType.CARD
        
        # Check for link
        if "link" in name_lower:
            return ElementType.LINK
        
        # Default to container for frames/groups
        if node_type in ["FRAME", "GROUP", "COMPONENT", "INSTANCE"]:
            return ElementType.CONTAINER
        
        # Use mapping for other types
        return FIGMA_TYPE_MAP.get(node_type, ElementType.UNKNOWN)
    
    def _extract_styles(self, node: Dict) -> ElementStyles:
        """
        Extract visual styles from a Figma node.
        """
        styles = ElementStyles()
        
        # Background color (from fills)
        fills = node.get("fills", [])
        if fills and len(fills) > 0:
            fill = fills[0]
            if fill.get("type") == "SOLID" and fill.get("visible", True):
                color = fill.get("color", {})
                styles.background_color = rgb_to_hex(
                    color.get("r", 0),
                    color.get("g", 0),
                    color.get("b", 0)
                )
                styles.opacity = fill.get("opacity", 1.0)
        
        # Border/stroke
        strokes = node.get("strokes", [])
        if strokes and len(strokes) > 0:
            stroke = strokes[0]
            if stroke.get("type") == "SOLID" and stroke.get("visible", True):
                color = stroke.get("color", {})
                styles.border_color = rgb_to_hex(
                    color.get("r", 0),
                    color.get("g", 0),
                    color.get("b", 0)
                )
        
        # Border width
        stroke_weight = node.get("strokeWeight")
        if stroke_weight:
            styles.border_width = stroke_weight
        
        # Border radius
        corner_radius = node.get("cornerRadius")
        if corner_radius:
            styles.border_radius = corner_radius
        
        # Typography (for TEXT nodes)
        style_data = node.get("style", {})
        if style_data:
            styles.font_family = style_data.get("fontFamily")
            styles.font_size = style_data.get("fontSize")
            styles.font_weight = style_data.get("fontWeight")
            styles.line_height = style_data.get("lineHeightPx")
            styles.text_align = style_data.get("textAlignHorizontal", "").lower()
            styles.letter_spacing = style_data.get("letterSpacing")
        
        # Text color (from fills for TEXT nodes)
        if node.get("type") == "TEXT" and fills:
            fill = fills[0]
            if fill.get("type") == "SOLID":
                color = fill.get("color", {})
                styles.text_color = rgb_to_hex(
                    color.get("r", 0),
                    color.get("g", 0),
                    color.get("b", 0)
                )
        
        # Padding (from auto-layout)
        padding_left = node.get("paddingLeft")
        padding_right = node.get("paddingRight")
        padding_top = node.get("paddingTop")
        padding_bottom = node.get("paddingBottom")
        
        if padding_left is not None:
            styles.padding_left = padding_left
        if padding_right is not None:
            styles.padding_right = padding_right
        if padding_top is not None:
            styles.padding_top = padding_top
        if padding_bottom is not None:
            styles.padding_bottom = padding_bottom
        
        # Effects (shadows)
        effects = node.get("effects", [])
        for effect in effects:
            if effect.get("type") == "DROP_SHADOW" and effect.get("visible", True):
                shadow = effect
                color = shadow.get("color", {})
                offset = shadow.get("offset", {})
                radius = shadow.get("radius", 0)
                
                # Format as CSS-like box-shadow
                rgba = f"rgba({int(color.get('r', 0)*255)},{int(color.get('g', 0)*255)},{int(color.get('b', 0)*255)},{color.get('a', 1):.2f})"
                styles.box_shadow = f"{offset.get('x', 0)}px {offset.get('y', 0)}px {radius}px {rgba}"
                break
        
        return styles
    
    def get_interactive_elements(self) -> List[UIElement]:
        """Get only interactive elements (buttons, inputs, etc.)."""
        return [e for e in self.elements if e.is_interactive]
    
    def get_text_elements(self) -> List[UIElement]:
        """Get only text elements."""
        return [e for e in self.elements if e.element_type in [
            ElementType.TEXT, ElementType.HEADING, ElementType.LABEL, ElementType.PRICE
        ]]
    
    def get_elements_by_type(self, element_type: ElementType) -> List[UIElement]:
        """Get elements of a specific type."""
        return [e for e in self.elements if e.element_type == element_type]
    
    def summarize(self) -> Dict[str, Any]:
        """Get a summary of extracted elements."""
        type_counts = {}
        for element in self.elements:
            type_name = element.element_type.value
            type_counts[type_name] = type_counts.get(type_name, 0) + 1
        
        return {
            "total_elements": len(self.elements),
            "interactive_elements": len(self.get_interactive_elements()),
            "text_elements": len(self.get_text_elements()),
            "by_type": type_counts,
            "max_depth": max((e.depth for e in self.elements), default=0)
        }


def extract_figma_elements(file_data: Dict, frame_id: str, viewport: str = "desktop") -> Tuple[List[UIElement], Dict]:
    """
    Convenience function to extract elements from Figma file data.
    
    Args:
        file_data: Complete Figma file data from API
        frame_id: ID of the frame to extract from
        viewport: "desktop" or "mobile"
        
    Returns:
        Tuple of (list of UIElements, summary dict)
    """
    # Find the frame in the document
    frame_node = _find_node_by_id(file_data.get("document", {}), frame_id)
    
    if not frame_node:
        raise ValueError(f"Frame with ID {frame_id} not found in Figma file")
    
    extractor = FigmaElementExtractor()
    elements = extractor.extract_from_frame(frame_node, viewport)
    summary = extractor.summarize()
    
    return elements, summary


def _find_node_by_id(node: Dict, target_id: str) -> Optional[Dict]:
    """Recursively find a node by ID in the Figma document tree."""
    if node.get("id") == target_id:
        return node
    
    for child in node.get("children", []):
        result = _find_node_by_id(child, target_id)
        if result:
            return result
    
    return None