figma-handoff-kit 0.0.0-stage → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1227 @@
1
+ let activeRunId = null;
2
+ function sendUI(message) {
3
+ figma.ui.postMessage({ ...message, runId: activeRunId });
4
+ }
5
+
6
+ // Prefer the Figma file key; persist an explicit local identity when unavailable.
7
+ let localDocumentId = figma.root.getPluginData("figmaExportDocumentId");
8
+ if (!localDocumentId) {
9
+ localDocumentId = "local-" + Date.now() + "-" + Math.random().toString(36).slice(2);
10
+ figma.root.setPluginData("figmaExportDocumentId", localDocumentId);
11
+ }
12
+ function exportIdentity(node) {
13
+ const path = [];
14
+ for (let item = node; item && item.type !== "DOCUMENT"; item = item.parent) {
15
+ path.unshift({ id: item.id, name: item.name });
16
+ }
17
+ return {
18
+ document: { id: figma.fileKey || localDocumentId, name: figma.root.name },
19
+ node_path: path
20
+ };
21
+ }
22
+
23
+ // Figma to AI Agent Exporter - Pixel-Perfect High-Fidelity & Design System Edition
24
+ figma.showUI(__html__, { width: 500, height: 720 });
25
+ let language = "vi";
26
+ figma.clientStorage.getAsync("exportLanguage").then(value => {
27
+ language = value === "en" ? "en" : "vi";
28
+ sendUI({ type: "LANGUAGE", language });
29
+ });
30
+ const localized = (vi, en) => language === "en" ? en : vi;
31
+
32
+ let currentAckResolver = null;
33
+
34
+ function waitForUploadAck(timeoutMs = 60000) {
35
+ return new Promise((resolve) => {
36
+ const timer = setTimeout(() => {
37
+ resolve(false);
38
+ }, timeoutMs);
39
+ currentAckResolver = (success) => {
40
+ clearTimeout(timer);
41
+ resolve(success);
42
+ };
43
+ });
44
+ }
45
+
46
+ function getStatusInfo() {
47
+ const selection = figma.currentPage.selection;
48
+ const currentPage = figma.currentPage;
49
+ const pages = figma.root.children.map(p => ({ id: p.id, name: p.name }));
50
+
51
+ let pageScreens = 0;
52
+ let pageSections = 0;
53
+ for (const node of currentPage.children) {
54
+ if (node.type === "SECTION") {
55
+ pageSections++;
56
+ for (const ch of node.children) {
57
+ if (ch.type === "FRAME" || ch.type === "COMPONENT" || ch.type === "INSTANCE" || ch.type === "COMPONENT_SET") {
58
+ pageScreens++;
59
+ }
60
+ }
61
+ } else if (node.type === "FRAME" || node.type === "COMPONENT" || node.type === "INSTANCE" || node.type === "COMPONENT_SET") {
62
+ pageScreens++;
63
+ }
64
+ }
65
+
66
+ let selSections = 0;
67
+ let selScreens = 0;
68
+ for (const node of selection) {
69
+ if (node.type === "SECTION") {
70
+ selSections++;
71
+ for (const ch of node.children) {
72
+ if (ch.type === "FRAME" || ch.type === "COMPONENT" || ch.type === "INSTANCE" || ch.type === "COMPONENT_SET") {
73
+ selScreens++;
74
+ }
75
+ }
76
+ } else if (node.type === "FRAME" || node.type === "COMPONENT" || node.type === "INSTANCE" || node.type === "COMPONENT_SET") {
77
+ selScreens++;
78
+ }
79
+ }
80
+
81
+ return {
82
+ currentPageName: currentPage.name,
83
+ pageScreens: pageScreens,
84
+ pageSections: pageSections,
85
+ totalPages: pages.length,
86
+ pagesList: pages,
87
+ hasSelection: selection.length > 0,
88
+ selectionName: selection.length > 0 ? selection[0].name : "Chưa chọn mục nào",
89
+ selectionScreens: selScreens,
90
+ selectionSections: selSections
91
+ };
92
+ }
93
+
94
+ function sendStatus() {
95
+ sendUI({
96
+ type: "STATUS_UPDATE",
97
+ data: getStatusInfo()
98
+ });
99
+ }
100
+
101
+ sendStatus();
102
+ figma.on("selectionchange", () => sendStatus());
103
+ figma.on("currentpagechange", () => sendStatus());
104
+
105
+ function sanitizeFilename(name) {
106
+ const value = String(name || "unnamed").replace(/[\\/*?:"<>| ]/g, "_").replace(/_+/g, "_").trim() || "unnamed";
107
+ let prefix = "", bytes = 0, hash = 2166136261;
108
+ for (let i = 0; i < value.length; i++) hash = Math.imul(hash ^ value.charCodeAt(i), 16777619) >>> 0;
109
+ for (const char of value) {
110
+ const point = char.codePointAt(0);
111
+ const size = point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
112
+ if (bytes + size > 80) return prefix + "--" + hash.toString(16).padStart(8, "0");
113
+ prefix += char;
114
+ bytes += size;
115
+ }
116
+ return value;
117
+ }
118
+
119
+ function bufferToBase64(bytes) {
120
+ let binary = "";
121
+ const len = bytes.byteLength;
122
+ for (let i = 0; i < len; i++) {
123
+ binary += String.fromCharCode(bytes[i]);
124
+ }
125
+ return btoa(binary);
126
+ }
127
+
128
+ function decodeUtf8(bytes) {
129
+ if (typeof TextDecoder !== "undefined") {
130
+ return new TextDecoder("utf-8").decode(bytes);
131
+ }
132
+ let binary = "";
133
+ for (let i = 0; i < bytes.length; i++) {
134
+ binary += String.fromCharCode(bytes[i]);
135
+ }
136
+ return binary;
137
+ }
138
+
139
+ // Convert Figma color (0-1 RGB) to HEX or RGBA
140
+ function colorToRgba(color, opacity = 1) {
141
+ const r = Math.round(color.r * 255);
142
+ const g = Math.round(color.g * 255);
143
+ const b = Math.round(color.b * 255);
144
+ const a = Math.round(opacity * 100) / 100;
145
+ if (a >= 1) {
146
+ const toHex = (c) => c.toString(16).padStart(2, "0");
147
+ return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
148
+ }
149
+ return `rgba(${r}, ${g}, ${b}, ${a})`;
150
+ }
151
+
152
+ // Convert gradient paint to CSS gradient string
153
+ function gradientToCss(fill) {
154
+ if (!fill.gradientStops || fill.gradientStops.length === 0) return null;
155
+ const stops = fill.gradientStops.map(s => {
156
+ const col = colorToRgba(s.color, s.color.a !== undefined ? s.color.a : 1);
157
+ const pos = Math.round(s.position * 100);
158
+ return `${col} ${pos}%`;
159
+ }).join(", ");
160
+
161
+ if (fill.type === "GRADIENT_LINEAR") {
162
+ return `linear-gradient(180deg, ${stops})`;
163
+ } else if (fill.type === "GRADIENT_RADIAL") {
164
+ return `radial-gradient(circle, ${stops})`;
165
+ }
166
+ return null;
167
+ }
168
+
169
+ // Semantic HTML tag detector
170
+ function detectSemanticTag(node) {
171
+ const name = (node.name || "").toLowerCase();
172
+
173
+ if (node.type === "TEXT") {
174
+ const size = typeof node.fontSize === "number" ? node.fontSize : 14;
175
+ const style = (node.fontName && typeof node.fontName === "object" && node.fontName.style) ? node.fontName.style.toLowerCase() : "";
176
+ if (size >= 30) return "h1";
177
+ if (size >= 24) return "h2";
178
+ if (size >= 20) return "h3";
179
+ if (size >= 16 && (style.includes("bold") || style.includes("semi"))) return "h4";
180
+ if (name.includes("label") || name.includes("caption")) return "label";
181
+ if (name.includes("link") || name.includes("url")) return "a";
182
+ return "p";
183
+ }
184
+
185
+ if (name.includes("button") || name.includes("btn") || name.includes("cta")) return "button";
186
+ if (name.includes("input") || name.includes("search") || name.includes("field") || name.includes("textbox")) return "input";
187
+ if (name.includes("header") || name.includes("navbar") || name.includes("topbar")) return "header";
188
+ if (name.includes("sidebar") || name.includes("drawer") || name.includes("aside")) return "aside";
189
+ if (name.includes("nav") || name.includes("menu") || name.includes("breadcrumb")) return "nav";
190
+ if (name.includes("footer")) return "footer";
191
+ if (name.includes("card") || name.includes("panel") || name.includes("item")) return "article";
192
+ if (name.includes("badge") || name.includes("tag") || name.includes("chip") || name.includes("pill")) return "span";
193
+ if (name.includes("modal") || name.includes("dialog") || name.includes("popup")) return "dialog";
194
+ if (name.includes("table") || name.includes("grid")) return "table";
195
+ if (name.includes("icon") || node.type === "VECTOR" || node.type === "BOOLEAN_OPERATION") return "svg";
196
+
197
+ return "div";
198
+ }
199
+
200
+ // Comprehensive CSS Builder (Merges native getCSSAsync with programmatic extraction for 100% fidelity)
201
+ async function computeFullCSS(node, figmaCss = {}, parentNode = null) {
202
+ const css = Object.assign({}, figmaCss);
203
+
204
+ // 1. Box Model / Dimensions
205
+ if (node.width !== undefined && node.height !== undefined) {
206
+ if (!css.width) css.width = `${Math.round(node.width * 100) / 100}px`;
207
+ if (!css.height) css.height = `${Math.round(node.height * 100) / 100}px`;
208
+ css["box-sizing"] = "border-box";
209
+ }
210
+
211
+ // 2. Sizing Constraints (Auto Layout Child)
212
+ if ("layoutSizingHorizontal" in node) {
213
+ if (node.layoutSizingHorizontal === "FILL") {
214
+ css["width"] = "100%";
215
+ css["flex-grow"] = "1";
216
+ } else if (node.layoutSizingHorizontal === "HUG") {
217
+ css["width"] = "fit-content";
218
+ }
219
+ }
220
+ if ("layoutSizingVertical" in node) {
221
+ if (node.layoutSizingVertical === "FILL") {
222
+ css["height"] = "100%";
223
+ css["align-self"] = "stretch";
224
+ } else if (node.layoutSizingVertical === "HUG") {
225
+ css["height"] = "fit-content";
226
+ }
227
+ }
228
+
229
+ // 3. Positioning (Absolute vs In-Flow)
230
+ if ("layoutPositioning" in node && node.layoutPositioning === "ABSOLUTE") {
231
+ css["position"] = "absolute";
232
+ css["left"] = `${Math.round(node.x * 100) / 100}px`;
233
+ css["top"] = `${Math.round(node.y * 100) / 100}px`;
234
+ }
235
+
236
+ // 4. Flexbox / Auto Layout
237
+ if ("layoutMode" in node && node.layoutMode !== "NONE") {
238
+ css["display"] = "flex";
239
+ css["flex-direction"] = node.layoutMode === "HORIZONTAL" ? "row" : "column";
240
+
241
+ if (node.layoutWrap === "WRAP") {
242
+ css["flex-wrap"] = "wrap";
243
+ if (node.counterAxisSpacing) {
244
+ css["row-gap"] = `${node.counterAxisSpacing}px`;
245
+ }
246
+ } else {
247
+ css["flex-wrap"] = "nowrap";
248
+ }
249
+
250
+ if (node.itemSpacing !== undefined && node.itemSpacing > 0) {
251
+ css["gap"] = `${node.itemSpacing}px`;
252
+ }
253
+
254
+ // Align items & Justify Content
255
+ const alignMap = {
256
+ MIN: "flex-start",
257
+ CENTER: "center",
258
+ MAX: "flex-end",
259
+ SPACE_BETWEEN: "space-between",
260
+ BASELINE: "baseline"
261
+ };
262
+ if (node.primaryAxisAlignItems && alignMap[node.primaryAxisAlignItems]) {
263
+ css["justify-content"] = alignMap[node.primaryAxisAlignItems];
264
+ }
265
+ if (node.counterAxisAlignItems && alignMap[node.counterAxisAlignItems]) {
266
+ css["align-items"] = alignMap[node.counterAxisAlignItems];
267
+ }
268
+
269
+ // Padding (4 sides)
270
+ const pt = node.paddingTop || 0;
271
+ const pr = node.paddingRight || 0;
272
+ const pb = node.paddingBottom || 0;
273
+ const pl = node.paddingLeft || 0;
274
+ if (pt !== 0 || pr !== 0 || pb !== 0 || pl !== 0) {
275
+ if (pt === pb && pr === pl) {
276
+ css["padding"] = pt === pr ? `${pt}px` : `${pt}px ${pr}px`;
277
+ } else {
278
+ css["padding"] = `${pt}px ${pr}px ${pb}px ${pl}px`;
279
+ }
280
+ }
281
+ }
282
+
283
+ // 5. Fills & Backgrounds
284
+ if ("fills" in node && Array.isArray(node.fills) && node.fills.length > 0) {
285
+ const visibleFills = node.fills.filter(f => f.visible !== false);
286
+ for (const fill of visibleFills) {
287
+ if (fill.type === "SOLID") {
288
+ css["background-color"] = colorToRgba(fill.color, fill.opacity !== undefined ? fill.opacity : 1);
289
+ } else if (fill.type.startsWith("GRADIENT")) {
290
+ const grad = gradientToCss(fill);
291
+ if (grad) css["background"] = grad;
292
+ }
293
+ }
294
+ }
295
+
296
+ // 6. Strokes & Borders
297
+ if ("strokes" in node && Array.isArray(node.strokes) && node.strokes.length > 0) {
298
+ const visibleStrokes = node.strokes.filter(s => s.visible !== false);
299
+ if (visibleStrokes.length > 0) {
300
+ const stroke = visibleStrokes[0];
301
+ const strokeColor = stroke.type === "SOLID" ? colorToRgba(stroke.color, stroke.opacity !== undefined ? stroke.opacity : 1) : "#000000";
302
+ const weight = node.strokeWeight || 1;
303
+ const style = (node.dashPattern && node.dashPattern.length > 0) ? "dashed" : "solid";
304
+
305
+ // Individual borders
306
+ const st = node.strokeTopWeight !== undefined ? node.strokeTopWeight : weight;
307
+ const sr = node.strokeRightWeight !== undefined ? node.strokeRightWeight : weight;
308
+ const sb = node.strokeBottomWeight !== undefined ? node.strokeBottomWeight : weight;
309
+ const sl = node.strokeLeftWeight !== undefined ? node.strokeLeftWeight : weight;
310
+
311
+ if (st === sr && sr === sb && sb === sl) {
312
+ if (weight > 0) css["border"] = `${weight}px ${style} ${strokeColor}`;
313
+ } else {
314
+ if (st > 0) css["border-top"] = `${st}px ${style} ${strokeColor}`;
315
+ if (sr > 0) css["border-right"] = `${sr}px ${style} ${strokeColor}`;
316
+ if (sb > 0) css["border-bottom"] = `${sb}px ${style} ${strokeColor}`;
317
+ if (sl > 0) css["border-left"] = `${sl}px ${style} ${strokeColor}`;
318
+ }
319
+ }
320
+ }
321
+
322
+ // 7. Border Radius
323
+ if ("cornerRadius" in node) {
324
+ if (node.cornerRadius !== figma.mixed && typeof node.cornerRadius === "number" && node.cornerRadius > 0) {
325
+ css["border-radius"] = `${node.cornerRadius}px`;
326
+ } else if ("topLeftRadius" in node) {
327
+ const tl = node.topLeftRadius || 0;
328
+ const tr = node.topRightRadius || 0;
329
+ const br = node.bottomRightRadius || 0;
330
+ const bl = node.bottomLeftRadius || 0;
331
+ if (tl > 0 || tr > 0 || br > 0 || bl > 0) {
332
+ css["border-radius"] = `${tl}px ${tr}px ${br}px ${bl}px`;
333
+ }
334
+ }
335
+ }
336
+
337
+ // 8. Effects (Drop Shadows, Inner Shadows, Background Blur)
338
+ if ("effects" in node && Array.isArray(node.effects)) {
339
+ const shadows = [];
340
+ for (const eff of node.effects) {
341
+ if (eff.visible === false) continue;
342
+ if (eff.type === "DROP_SHADOW" || eff.type === "INNER_SHADOW") {
343
+ const inset = eff.type === "INNER_SHADOW" ? "inset " : "";
344
+ const col = colorToRgba(eff.color, eff.color.a !== undefined ? eff.color.a : 1);
345
+ const x = eff.offset.x;
346
+ const y = eff.offset.y;
347
+ const r = eff.radius;
348
+ const s = eff.spread || 0;
349
+ shadows.push(`${inset}${x}px ${y}px ${r}px ${s}px ${col}`);
350
+ } else if (eff.type === "BACKGROUND_BLUR") {
351
+ css["backdrop-filter"] = `blur(${eff.radius}px)`;
352
+ css["-webkit-backdrop-filter"] = `blur(${eff.radius}px)`;
353
+ } else if (eff.type === "LAYER_BLUR") {
354
+ css["filter"] = `blur(${eff.radius}px)`;
355
+ }
356
+ }
357
+ if (shadows.length > 0) {
358
+ css["box-shadow"] = shadows.join(", ");
359
+ }
360
+ }
361
+
362
+ // 9. Typography
363
+ if (node.type === "TEXT") {
364
+ if (node.fontName && typeof node.fontName === "object" && node.fontName !== figma.mixed) {
365
+ css["font-family"] = `"${node.fontName.family}", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`;
366
+ const style = (node.fontName.style || "").toLowerCase();
367
+ if (style.includes("black")) css["font-weight"] = "900";
368
+ else if (style.includes("extra bold")) css["font-weight"] = "800";
369
+ else if (style.includes("bold")) css["font-weight"] = "700";
370
+ else if (style.includes("semi")) css["font-weight"] = "600";
371
+ else if (style.includes("medium")) css["font-weight"] = "500";
372
+ else if (style.includes("light")) css["font-weight"] = "300";
373
+ else css["font-weight"] = "400";
374
+ }
375
+
376
+ if (node.fontSize && typeof node.fontSize === "number") {
377
+ css["font-size"] = `${node.fontSize}px`;
378
+ }
379
+
380
+ if (node.lineHeight && typeof node.lineHeight === "object") {
381
+ if (node.lineHeight.unit === "PIXELS") {
382
+ css["line-height"] = `${Math.round(node.lineHeight.value * 100) / 100}px`;
383
+ } else if (node.lineHeight.unit === "PERCENT") {
384
+ css["line-height"] = `${Math.round(node.lineHeight.value) / 100}`;
385
+ }
386
+ }
387
+
388
+ if (node.letterSpacing && typeof node.letterSpacing === "object") {
389
+ if (node.letterSpacing.unit === "PIXELS" && node.letterSpacing.value !== 0) {
390
+ css["letter-spacing"] = `${Math.round(node.letterSpacing.value * 100) / 100}px`;
391
+ } else if (node.letterSpacing.unit === "PERCENT" && node.letterSpacing.value !== 0) {
392
+ css["letter-spacing"] = `${Math.round(node.letterSpacing.value) / 100}em`;
393
+ }
394
+ }
395
+
396
+ if (node.textAlignHorizontal) {
397
+ css["text-align"] = node.textAlignHorizontal.toLowerCase();
398
+ }
399
+
400
+ // Text color
401
+ if ("fills" in node && Array.isArray(node.fills) && node.fills.length > 0) {
402
+ const textFill = node.fills.find(f => f.visible !== false && f.type === "SOLID");
403
+ if (textFill) {
404
+ css["color"] = colorToRgba(textFill.color, textFill.opacity !== undefined ? textFill.opacity : 1);
405
+ }
406
+ }
407
+ }
408
+
409
+ // 10. Opacity & Overflow
410
+ if ("opacity" in node && typeof node.opacity === "number" && node.opacity < 1) {
411
+ css["opacity"] = `${Math.round(node.opacity * 100) / 100}`;
412
+ }
413
+ if ("clipsContent" in node && node.clipsContent === true) {
414
+ css["overflow"] = "hidden";
415
+ }
416
+
417
+ return css;
418
+ }
419
+
420
+ function formatCssBlock(cssObj) {
421
+ return Object.entries(cssObj)
422
+ .map(([k, v]) => ` ${k}: ${v};`)
423
+ .join("\n");
424
+ }
425
+
426
+ // Invalid component sets can throw from Figma's native variant getter.
427
+ function readVariantProperties(node, variantNode = node) {
428
+ try {
429
+ return { value: node.variantProperties || null };
430
+ } catch (error) {
431
+ const warning = `Variant metadata unavailable for ${node.name} (${node.id}): ${error.message}`;
432
+ // Only recover actual variants, not arbitrary instance or component-set labels.
433
+ const rawName = variantNode.name;
434
+ const normalized = typeof rawName === "string" ? rawName.trim().replace(/^=+\s*/, "") : "";
435
+ function parseName(name) {
436
+ const properties = {}, unassigned = [];
437
+ for (const part of name.split(",")) {
438
+ const pair = part.trim();
439
+ if (!pair) return null;
440
+ if (!pair.includes("=")) { unassigned.push(pair); continue; }
441
+ const match = pair.match(/^([^=]+)=([^=]+)$/);
442
+ if (!match) return null;
443
+ const key = match[1].trim(), value = match[2].trim();
444
+ if (!key || !value || ["__proto__", "constructor", "prototype"].includes(key) || Object.prototype.hasOwnProperty.call(properties, key)) return null;
445
+ properties[key] = value;
446
+ }
447
+ return { properties, unassigned };
448
+ }
449
+ const parsed = parseName(normalized);
450
+ const value = parsed?.properties || {};
451
+ let valid = variantNode.parent?.type === "COMPONENT_SET" && normalized.length > 0 && !!parsed;
452
+ let source = "normalized-name";
453
+ if (valid && parsed.unassigned.length) {
454
+ // Infer one missing key only from a consistent schema of well-formed siblings.
455
+ const siblings = (variantNode.parent.children || []).filter(child => child.type === "COMPONENT" && child.id !== variantNode.id);
456
+ const schemas = siblings.map(child => parseName(String(child.name || "").trim()));
457
+ const complete = schemas.filter(schema => schema && !schema.unassigned.length);
458
+ const keys = complete.length ? Object.keys(complete[0].properties).sort() : [];
459
+ const consistent = complete.length === siblings.length && complete.length > 0 && complete.every(schema => JSON.stringify(Object.keys(schema.properties).sort()) === JSON.stringify(keys));
460
+ const missing = keys.filter(key => !Object.prototype.hasOwnProperty.call(value, key));
461
+ valid = consistent && parsed.unassigned.length === 1 && missing.length === 1 && Object.keys(value).every(key => keys.includes(key));
462
+ if (valid) {
463
+ value[missing[0]] = parsed.unassigned[0];
464
+ valid = !complete.some(schema => keys.every(key => schema.properties[key] === value[key]));
465
+ if (!valid) delete value[missing[0]];
466
+ source = "sibling-schema";
467
+ }
468
+ }
469
+ if (valid) {
470
+ sendUI({ type: "PROGRESS_UPDATE", message: `⚠ Variant metadata inferred from name for ${node.name} (${node.id}); verify the original component.` });
471
+ return { value, warning, source, rawName, normalizedName: Object.entries(value).map(([key, entry]) => `${key}=${entry}`).join(", ") };
472
+ }
473
+ if (variantNode.parent?.type === "COMPONENT_SET" && parsed && parsed.unassigned.length) {
474
+ const partialWarning = `Variant metadata incomplete for ${node.name} (${node.id}); unassigned labels: ${parsed.unassigned.join(", ")}. Figma: ${error.message}`;
475
+ sendUI({ type: "PROGRESS_UPDATE", message: `⚠ ${partialWarning}` });
476
+ return { value, warning: partialWarning, source: "partial-name", rawName, normalizedName: normalized, unassigned: parsed.unassigned };
477
+ }
478
+ sendUI({ type: "PROGRESS_UPDATE", message: `⚠ ${warning}` });
479
+ return { value: null, warning };
480
+ }
481
+ }
482
+
483
+ // Inspect Component Instance & Generate Reusable Directives
484
+ function inspectComponentInstance(node) {
485
+ const mainComp = node.mainComponent;
486
+ if (!mainComp) return null;
487
+
488
+ const compSet = (mainComp.parent && mainComp.parent.type === "COMPONENT_SET") ? mainComp.parent : null;
489
+ const componentSetName = compSet ? compSet.name : mainComp.name;
490
+ const variants = readVariantProperties(node, mainComp);
491
+ const variantProps = variants.value || {};
492
+ const masterName = mainComp.name;
493
+
494
+ // Extract props by scanning instance children
495
+ const extractedProps = {};
496
+ function findOverrides(n) {
497
+ if (n.type === "TEXT" && n.characters) {
498
+ const lower = (n.name || "").toLowerCase();
499
+ const propKey = lower.includes("label") ? "label"
500
+ : lower.includes("title") ? "title"
501
+ : lower.includes("placeholder") ? "placeholder"
502
+ : lower.includes("value") ? "value"
503
+ : "text";
504
+ if (!extractedProps[propKey]) {
505
+ extractedProps[propKey] = n.characters;
506
+ }
507
+ }
508
+ if (n.children) {
509
+ for (const ch of n.children) findOverrides(ch);
510
+ }
511
+ }
512
+ findOverrides(node);
513
+
514
+ // Generate clean JSX / HTML snippet
515
+ const propPairs = Object.entries(variantProps)
516
+ .map(([k, v]) => `${k.toLowerCase()}="${v}"`)
517
+ .join(" ");
518
+ const attrStr = propPairs ? ` ${propPairs}` : "";
519
+ const innerText = extractedProps.label || extractedProps.text || "";
520
+ const codeSnippet = innerText
521
+ ? `<${componentSetName}${attrStr}>${innerText}</${componentSetName}>`
522
+ : `<${componentSetName}${attrStr} />`;
523
+
524
+ return {
525
+ isSharedComponent: true,
526
+ componentSetName: componentSetName,
527
+ masterComponentName: masterName,
528
+ masterComponentId: mainComp.id,
529
+ variantProperties: variants.value,
530
+ ...(variants.warning ? { variantWarning: variants.warning } : {}),
531
+ ...(variants.unassigned ? { unassignedVariantLabels: variants.unassigned } : {}),
532
+ ...(variants.source ? { variantMetadataSource: variants.source, variantRawName: variants.rawName, variantNormalizedName: variants.normalizedName } : {}),
533
+ description: compSet?.description || mainComp.description || "",
534
+ extractedProps: extractedProps,
535
+ recommendedUsage: codeSnippet,
536
+ reuseDirective: `REUSE DIRECTIVE: Use shared component <${componentSetName}> with variant ${JSON.stringify(variantProps)}. Do NOT create a custom ad-hoc component.`
537
+ };
538
+ }
539
+
540
+ // Generate Google Fonts links from font families and weights
541
+ function generateFontGuides(fontsMap) {
542
+ const families = [];
543
+ const details = [];
544
+
545
+ for (const [family, weightsObj] of Object.entries(fontsMap)) {
546
+ const weights = Object.keys(weightsObj).sort();
547
+ details.push({
548
+ family: family,
549
+ weights: weights
550
+ });
551
+ const formattedFamily = family.replace(/ /g, "+");
552
+ const weightStr = weights.length > 0 ? `:wght@${weights.join(";")}` : "";
553
+ families.push(`family=${formattedFamily}${weightStr}`);
554
+ }
555
+
556
+ if (families.length === 0) {
557
+ families.push("family=IBM+Plex+Sans:wght@400;500;600;700");
558
+ }
559
+
560
+ const googleFontUrl = `https://fonts.googleapis.com/css2?${families.join("&")}&display=swap`;
561
+ return {
562
+ fonts: details,
563
+ googleFontUrl: googleFontUrl,
564
+ htmlLinkTag: `<link rel="preconnect" href="https://fonts.googleapis.com">\n<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>\n<link href="${googleFontUrl}" rel="stylesheet">`,
565
+ cssImportRule: `@import url('${googleFontUrl}');`,
566
+ cssFontFamilyStack: `"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`
567
+ };
568
+ }
569
+
570
+ // Deep recursive DOM Tree Extractor
571
+ async function extractDetailedNodeTree(node, context, parentNode = null) {
572
+ let nativeCss = {};
573
+ if ("getCSSAsync" in node) {
574
+ try {
575
+ nativeCss = await node.getCSSAsync();
576
+ } catch (e) {}
577
+ }
578
+
579
+ const computedCss = await computeFullCSS(node, nativeCss, parentNode);
580
+ const semanticTag = detectSemanticTag(node);
581
+
582
+ const nodeItem = {
583
+ id: node.id,
584
+ name: node.name,
585
+ type: node.type,
586
+ semanticTag: semanticTag,
587
+ visible: node.visible !== false,
588
+ bounds: {
589
+ width: Math.round(node.width * 100) / 100,
590
+ height: Math.round(node.height * 100) / 100,
591
+ x: Math.round(node.x * 100) / 100,
592
+ y: Math.round(node.y * 100) / 100
593
+ },
594
+ layoutFlow: ("layoutPositioning" in node && node.layoutPositioning === "ABSOLUTE") ? "absolute" : "in-flow",
595
+ css: computedCss,
596
+ cssString: formatCssBlock(computedCss)
597
+ };
598
+
599
+ // 1. REUSABLE COMPONENT IDENTIFICATION
600
+ if (node.type === "INSTANCE") {
601
+ const compInfo = inspectComponentInstance(node);
602
+ if (compInfo) {
603
+ nodeItem.component = compInfo;
604
+
605
+ const setName = compInfo.componentSetName;
606
+ if (!context.componentsUsed[setName]) {
607
+ context.componentsUsed[setName] = {
608
+ componentSet: setName,
609
+ description: compInfo.description,
610
+ totalUsageCount: 0,
611
+ variantsEncountered: [],
612
+ sampleUsages: [],
613
+ reuseRules: `Always reuse <${setName}>. Do not write duplicate CSS or markup.`
614
+ };
615
+ }
616
+ context.componentsUsed[setName].totalUsageCount++;
617
+
618
+ // Track variants
619
+ const varStr = JSON.stringify(compInfo.variantProperties);
620
+ const existingVar = context.componentsUsed[setName].variantsEncountered.find(v => JSON.stringify(v.properties) === varStr && JSON.stringify(v.unassignedVariantLabels) === JSON.stringify(compInfo.unassignedVariantLabels));
621
+ if (existingVar) {
622
+ existingVar.count++;
623
+ } else {
624
+ context.componentsUsed[setName].variantsEncountered.push({
625
+ properties: compInfo.variantProperties,
626
+ ...(compInfo.unassignedVariantLabels ? { unassignedVariantLabels: compInfo.unassignedVariantLabels, variantMetadataSource: compInfo.variantMetadataSource } : {}),
627
+ count: 1
628
+ });
629
+ }
630
+
631
+ if (context.componentsUsed[setName].sampleUsages.length < 5) {
632
+ context.componentsUsed[setName].sampleUsages.push({
633
+ nodeId: node.id,
634
+ nodeName: node.name,
635
+ variant: compInfo.variantProperties,
636
+ ...(compInfo.unassignedVariantLabels ? { unassignedVariantLabels: compInfo.unassignedVariantLabels, variantMetadataSource: compInfo.variantMetadataSource } : {}),
637
+ props: compInfo.extractedProps,
638
+ recommendedSnippet: compInfo.recommendedUsage
639
+ });
640
+ }
641
+ }
642
+ } else if (node.type === "COMPONENT" || node.type === "COMPONENT_SET") {
643
+ const compSet = node.type === "COMPONENT_SET" ? node : (node.parent && node.parent.type === "COMPONENT_SET" ? node.parent : null);
644
+ const variants = readVariantProperties(node);
645
+ nodeItem.component = {
646
+ isMasterDefinition: true,
647
+ componentSetName: compSet ? compSet.name : node.name,
648
+ variantProperties: variants.value,
649
+ ...(variants.warning ? { variantWarning: variants.warning } : {}),
650
+ ...(variants.unassigned ? { unassignedVariantLabels: variants.unassigned } : {}),
651
+ ...(variants.source ? { variantMetadataSource: variants.source, variantRawName: variants.rawName, variantNormalizedName: variants.normalizedName } : {}),
652
+ description: node.description || ""
653
+ };
654
+ }
655
+
656
+ // 2. AUTO-LAYOUT DETAILS
657
+ if ("layoutMode" in node && node.layoutMode !== "NONE") {
658
+ nodeItem.autoLayout = {
659
+ mode: node.layoutMode,
660
+ itemSpacing: node.itemSpacing,
661
+ padding: {
662
+ top: node.paddingTop || 0,
663
+ right: node.paddingRight || 0,
664
+ bottom: node.paddingBottom || 0,
665
+ left: node.paddingLeft || 0
666
+ },
667
+ primaryAxisAlign: node.primaryAxisAlignItems,
668
+ counterAxisAlign: node.counterAxisAlignItems,
669
+ layoutSizingHorizontal: node.layoutSizingHorizontal,
670
+ layoutSizingVertical: node.layoutSizingVertical
671
+ };
672
+ }
673
+
674
+ // 3. TEXT & TYPOGRAPHY & FONT TRACKING
675
+ if (node.type === "TEXT" && node.characters) {
676
+ nodeItem.text = node.characters;
677
+ const font = node.fontName;
678
+ const fontFamily = (font && typeof font === "object") ? font.family : "mixed";
679
+ const fontStyle = (font && typeof font === "object") ? font.style : "mixed";
680
+
681
+ // Numeric weight mapping
682
+ let weightNum = "400";
683
+ const s = fontStyle.toLowerCase();
684
+ if (s.includes("black")) weightNum = "900";
685
+ else if (s.includes("extra bold")) weightNum = "800";
686
+ else if (s.includes("bold")) weightNum = "700";
687
+ else if (s.includes("semi")) weightNum = "600";
688
+ else if (s.includes("medium")) weightNum = "500";
689
+ else if (s.includes("light")) weightNum = "300";
690
+
691
+ if (fontFamily !== "mixed" && !context.fontsUsed[fontFamily]) {
692
+ context.fontsUsed[fontFamily] = {};
693
+ }
694
+ if (fontFamily !== "mixed") context.fontsUsed[fontFamily][weightNum] = true;
695
+
696
+ const typo = {
697
+ fontFamily: fontFamily,
698
+ fontWeight: fontStyle,
699
+ fontWeightNum: weightNum,
700
+ fontSize: typeof node.fontSize === "number" ? node.fontSize : "mixed",
701
+ lineHeight: node.lineHeight === figma.mixed ? "mixed" : node.lineHeight ? (node.lineHeight.value ?? "AUTO") : "AUTO",
702
+ letterSpacing: node.letterSpacing === figma.mixed ? "mixed" : node.letterSpacing ? (node.letterSpacing.value ?? 0) : 0,
703
+ textAlign: node.textAlignHorizontal || "LEFT",
704
+ color: computedCss.color || "#101828"
705
+ };
706
+ nodeItem.typography = typo;
707
+ // Figma uses a Symbol for mixed text properties; retain the actual per-range styles.
708
+ if ([node.fontName, node.fontSize, node.lineHeight, node.letterSpacing].includes(figma.mixed)) {
709
+ nodeItem.textRuns = node.getStyledTextSegments(["fontName", "fontSize", "lineHeight", "letterSpacing"]);
710
+ for (const run of nodeItem.textRuns) {
711
+ const style = run.fontName.style.toLowerCase();
712
+ const weights = [["black", "900"], ["extra bold", "800"], ["semi", "600"], ["bold", "700"], ["medium", "500"], ["light", "300"]];
713
+ const weight = (weights.find(([name]) => style.includes(name)) || [null, "400"])[1];
714
+ if (!context.fontsUsed[run.fontName.family]) context.fontsUsed[run.fontName.family] = {};
715
+ context.fontsUsed[run.fontName.family][weight] = true;
716
+ }
717
+ }
718
+ const typoKey = `${typo.fontFamily} ${typo.fontWeight} ${typo.fontSize}px`;
719
+ context.designTokens.typography[typoKey] = typo;
720
+ }
721
+
722
+ // 4. COLOR & EFFECT TOKENS
723
+ if (computedCss["background-color"]) context.designTokens.colors[computedCss["background-color"]] = true;
724
+ if (computedCss.color) context.designTokens.colors[computedCss.color] = true;
725
+ if (computedCss["border-color"]) context.designTokens.colors[computedCss["border-color"]] = true;
726
+ if (computedCss["border-radius"]) context.designTokens.radii[computedCss["border-radius"]] = true;
727
+ if (computedCss["box-shadow"]) context.designTokens.shadows[computedCss["box-shadow"]] = true;
728
+
729
+ // 5. VECTOR / ICON SVG EXPORT (Small frames, Vectors, Boolean ops)
730
+ const isExplicitIconName = /icon|logo|arrow|chevron|check|close|search|status|dot|avatar|badge|spinner|caret|menu|bell|filter|lock|key|alert|eye|copy|logout|login/i.test(node.name || "");
731
+ const isVectorType = (
732
+ node.type === "VECTOR" ||
733
+ node.type === "BOOLEAN_OPERATION" ||
734
+ node.type === "STAR" ||
735
+ node.type === "LINE" ||
736
+ node.type === "ELLIPSE" ||
737
+ node.type === "POLYGON"
738
+ );
739
+ const isSmallIconContainer = (
740
+ (node.type === "FRAME" || node.type === "INSTANCE" || node.type === "COMPONENT") &&
741
+ node.width > 0 && node.width <= 72 &&
742
+ node.height > 0 && node.height <= 72 &&
743
+ (isExplicitIconName || ("children" in node && node.children.every(ch => ch.type === "VECTOR" || ch.type === "BOOLEAN_OPERATION" || ch.type === "LINE" || ch.type === "ELLIPSE")))
744
+ );
745
+
746
+ const shouldExportAsSvg = (isVectorType || isSmallIconContainer || (isExplicitIconName && node.width <= 120 && node.height <= 120)) && node.type !== "TEXT";
747
+
748
+ if (shouldExportAsSvg && node.width > 0 && node.height > 0) {
749
+ try {
750
+ const svgBytes = await node.exportAsync({ format: "SVG" });
751
+ const svgCode = decodeUtf8(svgBytes);
752
+
753
+ if (svgCode && svgCode.includes("<svg")) {
754
+ const assetFileName = `assets/${sanitizeFilename(node.name)}_${sanitizeFilename(node.id.replace(":", "_"))}.svg`;
755
+ context.assets.push({
756
+ name: assetFileName,
757
+ type: "text",
758
+ content: svgCode
759
+ });
760
+ context.assetsManifest.push({
761
+ filename: assetFileName,
762
+ format: "SVG",
763
+ nodeId: node.id,
764
+ nodeName: node.name,
765
+ dimensions: `${node.width}×${node.height}px`,
766
+ purpose: "Icon / Vector graphic"
767
+ });
768
+ nodeItem.assetSvg = assetFileName;
769
+ }
770
+ } catch (e) {
771
+ try {
772
+ const svgCode = await node.exportAsync({ format: "SVG_STRING" });
773
+ if (typeof svgCode === "string" && svgCode.includes("<svg")) {
774
+ const assetFileName = `assets/${sanitizeFilename(node.name)}_${sanitizeFilename(node.id.replace(":", "_"))}.svg`;
775
+ context.assets.push({
776
+ name: assetFileName,
777
+ type: "text",
778
+ content: svgCode
779
+ });
780
+ context.assetsManifest.push({
781
+ filename: assetFileName,
782
+ format: "SVG",
783
+ nodeId: node.id,
784
+ nodeName: node.name,
785
+ dimensions: `${node.width}×${node.height}px`,
786
+ purpose: "Icon / Vector graphic"
787
+ });
788
+ nodeItem.assetSvg = assetFileName;
789
+ }
790
+ } catch (e2) {}
791
+ }
792
+ }
793
+
794
+ // 6. IMAGE EXPORT (PNG)
795
+ // 6a. Fill type == IMAGE (Figma native image hashes)
796
+ if ("fills" in node && Array.isArray(node.fills)) {
797
+ for (const fill of node.fills) {
798
+ if (fill.type === "IMAGE" && fill.imageHash) {
799
+ try {
800
+ const img = figma.getImageByHash(fill.imageHash);
801
+ if (img) {
802
+ const bytes = await img.getBytesAsync();
803
+ const b64 = bufferToBase64(bytes);
804
+ const assetFileName = `assets/img_${sanitizeFilename(node.name)}_${fill.imageHash.substring(0, 10)}.png`;
805
+ context.assets.push({
806
+ name: assetFileName,
807
+ type: "base64",
808
+ content: b64
809
+ });
810
+ context.assetsManifest.push({
811
+ filename: assetFileName,
812
+ format: "PNG",
813
+ nodeId: node.id,
814
+ nodeName: node.name,
815
+ dimensions: `${node.width}×${node.height}px`,
816
+ purpose: "Image fill (Photo / Illustration)"
817
+ });
818
+ nodeItem.assetImage = assetFileName;
819
+ }
820
+ } catch (e) {}
821
+ }
822
+ }
823
+ }
824
+
825
+ // 6b. Named raster / illustration / photo / hero / campus image frames (rendered as 2x PNG)
826
+ const isImageNode = /image|photo|campus|hero|banner|illustration|mockup|preview|picture/i.test(node.name || "") &&
827
+ node.width >= 100 && node.height >= 80 &&
828
+ !shouldExportAsSvg && node.type !== "TEXT";
829
+
830
+ if (isImageNode && !nodeItem.assetImage) {
831
+ try {
832
+ const pngBytes = await node.exportAsync({
833
+ format: "PNG",
834
+ constraint: { type: "SCALE", value: 2 }
835
+ });
836
+ const b64 = bufferToBase64(pngBytes);
837
+ const assetFileName = `assets/${sanitizeFilename(node.name)}_${sanitizeFilename(node.id.replace(":", "_"))}.png`;
838
+ context.assets.push({
839
+ name: assetFileName,
840
+ type: "base64",
841
+ content: b64
842
+ });
843
+ context.assetsManifest.push({
844
+ filename: assetFileName,
845
+ format: "PNG (2x Retina)",
846
+ nodeId: node.id,
847
+ nodeName: node.name,
848
+ dimensions: `${node.width * 2}×${node.height * 2}px`,
849
+ purpose: "Raster Hero / Photo / Illustration"
850
+ });
851
+ nodeItem.assetImage = assetFileName;
852
+ } catch (e) {}
853
+ }
854
+
855
+ // 7. RECURSIVE CHILDREN
856
+ // If this container is already exported as a coherent atomic SVG icon, avoid bloating the tree with internal vector paths!
857
+ const shouldSkipChildren = !!nodeItem.assetSvg;
858
+ if ("children" in node && !shouldSkipChildren) {
859
+ nodeItem.children = [];
860
+ for (const child of node.children) {
861
+ if (child.visible !== false) {
862
+ nodeItem.children.push(await extractDetailedNodeTree(child, context, node));
863
+ }
864
+ }
865
+ }
866
+
867
+ return nodeItem;
868
+ }
869
+
870
+ // Generate Screen Spec Markdown
871
+ function generateMarkdownDoc(tree, componentsUsed, designTokens, fontGuide, assetsManifest) {
872
+ let md = `# Screen Spec: ${tree.name} (\`${tree.id}\`)\n\n`;
873
+ md += `![Screenshot](./screenshot.png)\n\n`;
874
+
875
+ // 1. REUSABLE COMPONENTS CATALOG (CRITICAL FOR AGENT REUSE)
876
+ md += `## 🧩 1. Reusable Components (Design System Catalog)\n`;
877
+ md += `> **QUAN TRỌNG:** Các component dùng chung dưới đây đã được định nghĩa trong Design System.\n`;
878
+ md += `> Khi AI Agent tạo giao diện, **PHẢI TÁI SỬ DỤNG** các component này thay vì tạo div/button mới!\n\n`;
879
+
880
+ const compList = Object.values(componentsUsed);
881
+ if (compList.length > 0) {
882
+ md += `| Component Name | Lần dùng | Variants sử dụng | Code Snippet Gợi Ý |\n`;
883
+ md += `| :--- | :--- | :--- | :--- |\n`;
884
+ for (const comp of compList) {
885
+ const varSample = comp.variantsEncountered.map(v => JSON.stringify(v.properties)).join("<br>");
886
+ const snippetSample = comp.sampleUsages.length > 0 ? `\`${comp.sampleUsages[0].recommendedSnippet.replace(/`/g, "")}\`` : "-";
887
+ md += `| **\`<${comp.componentSet}>\`** | \`${comp.totalUsageCount}\` | ${varSample} | ${snippetSample} |\n`;
888
+ }
889
+ md += `\n### Chi tiết mẫu sử dụng Component:\n`;
890
+ for (const comp of compList) {
891
+ md += `#### Component \`<${comp.componentSet}>\`:\n`;
892
+ for (const s of comp.sampleUsages) {
893
+ md += `- **Element:** \`${s.nodeName}\` | **Props:** \`${JSON.stringify(s.props)}\`\n`;
894
+ md += ` \`\`\`jsx\n ${s.recommendedSnippet}\n \`\`\`\n`;
895
+ }
896
+ }
897
+ } else {
898
+ md += `*Không phát hiện Component thư viện ngoài, các thành phần là Custom Frames.*\n`;
899
+ }
900
+ md += `\n`;
901
+
902
+ // 2. FONT & TYPOGRAPHY SETUP
903
+ md += `## 🔤 2. Font & Typography Setup (Google Fonts Auto-Resolver)\n`;
904
+ md += `Màn hình này sử dụng các font sau đây. Agent chỉ cần nhúng mã dưới đây vào HTML/CSS để load đúng 100% font:\n\n`;
905
+ md += `### HTML \`<head>\` Embed Code:\n\`\`\`html\n${fontGuide.htmlLinkTag}\n\`\`\`\n\n`;
906
+ md += `### CSS \`@import\` Rule:\n\`\`\`css\n${fontGuide.cssImportRule}\n\nbody {\n font-family: ${fontGuide.cssFontFamilyStack};\n}\n\`\`\`\n\n`;
907
+
908
+ // 3. ASSETS INVENTORY (ICONS & IMAGES)
909
+ md += `## 🖼️ 3. Assets Đã Trích Xuất (Icons SVG & Images PNG)\n`;
910
+ if (assetsManifest && assetsManifest.length > 0) {
911
+ md += `| File Name | Format | Dimensions | Purpose | Code Usage Gợi Ý |\n`;
912
+ md += `| :--- | :--- | :--- | :--- | :--- |\n`;
913
+ for (const a of assetsManifest) {
914
+ const usage = a.format === "SVG" ? `\`<img src="./${a.filename}" alt="${a.nodeName}" />\`` : `\`<img src="./${a.filename}" class="w-full object-cover" />\``;
915
+ md += `| **\`${a.filename}\`** | \`${a.format}\` | \`${a.dimensions}\` | ${a.purpose} | ${usage} |\n`;
916
+ }
917
+ } else {
918
+ md += `*Không có icon hoặc ảnh bitmap độc lập trên màn hình này.*\n`;
919
+ }
920
+ md += `\n`;
921
+
922
+ // 4. ROOT CONTAINER CSS
923
+ md += `## 📐 4. Bố cục tổng thể & CSS Container Gốc\n`;
924
+ md += `- **Dimensions:** \`${tree.bounds.width}px\` × \`${tree.bounds.height}px\`\n`;
925
+ if (tree.autoLayout) {
926
+ md += `- **Auto Layout Mode:** \`${tree.autoLayout.mode}\`\n`;
927
+ md += `- **Padding:** \`[T: ${tree.autoLayout.padding.top}, R: ${tree.autoLayout.padding.right}, B: ${tree.autoLayout.padding.bottom}, L: ${tree.autoLayout.padding.left}]\`\n`;
928
+ md += `- **Item Spacing (Gap):** \`${tree.autoLayout.itemSpacing}px\`\n`;
929
+ }
930
+ md += `\n\`\`\`css\n/* Exact Computed CSS for Screen Root */\n${tree.cssString}\n\`\`\`\n\n`;
931
+
932
+ // 5. DESIGN TOKENS
933
+ md += `## 🎨 5. Design Tokens (Colors & Typography)\n`;
934
+ md += `### Colors:\n`;
935
+ for (const c of Object.keys(designTokens.colors)) {
936
+ md += `- \`${c}\`\n`;
937
+ }
938
+ md += `\n### Typography:\n`;
939
+ md += `| Font Family | Style / Weight | Size | Line Height | Color |\n`;
940
+ md += `| :--- | :--- | :--- | :--- | :--- |\n`;
941
+ for (const [k, t] of Object.entries(designTokens.typography)) {
942
+ md += `| ${t.fontFamily} | ${t.fontWeight} | ${t.fontSize}px | ${t.lineHeight} | \`${t.color}\` |\n`;
943
+ }
944
+ md += `\n`;
945
+
946
+ // 6. NESTED DOM TREE WITH CSS & TAGS
947
+ md += `## 🌲 6. Cây cấu trúc lồng nhau (DOM Hierarchy Tree)\n`;
948
+ function printBranch(n, depth = 0) {
949
+ const indent = " ".repeat(depth);
950
+ const tag = n.semanticTag ? `<${n.semanticTag}>` : "<div>";
951
+ const compTag = n.component?.isSharedComponent ? ` 🧩 **[REUSE: ${n.component.componentSetName}]**` : "";
952
+ const sizeTag = ` (${n.bounds.width}×${n.bounds.height}px)`;
953
+ const assetTag = n.assetSvg ? ` 🎨 [SVG: \`${n.assetSvg}\`]` : (n.assetImage ? ` 🖼️ [IMG: \`${n.assetImage}\`]` : "");
954
+ let out = `${indent}- **${n.name}** \`${tag}\`${compTag}${assetTag}${sizeTag}\n`;
955
+ if (n.text) {
956
+ out += `${indent} > *Text:* "${n.text.replace(/\n/g, " ").slice(0, 60)}"\n`;
957
+ }
958
+ if (n.children && n.children.length > 0) {
959
+ for (const ch of n.children) {
960
+ out += printBranch(ch, depth + 1);
961
+ }
962
+ }
963
+ return out;
964
+ }
965
+ md += printBranch(tree, 0);
966
+
967
+ return md;
968
+ }
969
+
970
+ // Generate HTML preview & code snippet cheatsheet for reused components
971
+ function generateComponentSnippetsHtml(screenName, componentsUsed, fontGuide) {
972
+ let html = `<!DOCTYPE html>
973
+ <html lang="en">
974
+ <head>
975
+ <meta charset="utf-8">
976
+ <title>Component Reuse CheatSheet - ${screenName}</title>
977
+ ${fontGuide.htmlLinkTag}
978
+ <style>
979
+ body { font-family: ${fontGuide.cssFontFamilyStack}; padding: 24px; background: #f8fafc; color: #0f172a; line-height: 1.5; }
980
+ h1 { font-size: 20px; font-weight: 700; margin-bottom: 8px; }
981
+ .badge { background: #dbeafe; color: #1e40af; font-size: 12px; padding: 3px 8px; border-radius: 9999px; font-weight: 600; }
982
+ .card { background: #ffffff; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; margin-bottom: 16px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
983
+ .code-box { background: #0f172a; color: #f8fafc; padding: 12px; border-radius: 6px; font-family: ui-monospace, Menlo, Monaco, Consolas, monospace; font-size: 13px; overflow-x: auto; margin-top: 8px; }
984
+ table { width: 100%; border-collapse: collapse; margin-top: 12px; font-size: 13px; }
985
+ th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid #e2e8f0; }
986
+ th { background: #f1f5f9; font-weight: 600; }
987
+ </style>
988
+ </head>
989
+ <body>
990
+ <h1>🧩 Component Reuse Guide: ${screenName}</h1>
991
+ <p>The following shared components must be reused when implementing this screen:</p>
992
+ `;
993
+
994
+ for (const comp of Object.values(componentsUsed)) {
995
+ html += `
996
+ <div class="card">
997
+ <h2>&lt;${comp.componentSet}&gt; <span class="badge">${comp.totalUsageCount} usages</span></h2>
998
+ <p><em>${comp.description || "Shared Design System Component"}</em></p>
999
+ <table>
1000
+ <thead>
1001
+ <tr><th>Node Name</th><th>Variant Props</th><th>Suggested Code</th></tr>
1002
+ </thead>
1003
+ <tbody>
1004
+ `;
1005
+ for (const sample of comp.sampleUsages) {
1006
+ html += `
1007
+ <tr>
1008
+ <td><strong>${sample.nodeName}</strong></td>
1009
+ <td><code>${JSON.stringify(sample.variant)}</code></td>
1010
+ <td><code>${sample.recommendedSnippet}</code></td>
1011
+ </tr>
1012
+ `;
1013
+ }
1014
+ html += `
1015
+ </tbody>
1016
+ </table>
1017
+ <div class="code-box">${comp.sampleUsages[0]?.recommendedSnippet || ""}</div>
1018
+ </div>
1019
+ `;
1020
+ }
1021
+
1022
+ html += `
1023
+ </body>
1024
+ </html>
1025
+ `;
1026
+ return html;
1027
+ }
1028
+
1029
+ let checkResolver = null;
1030
+ let forceExport = false;
1031
+ function checkScreen(identity, snapshot) {
1032
+ return new Promise((resolve, reject) => {
1033
+ const timer = setTimeout(() => { checkResolver = null; reject(new Error("Change check timed out")); }, 60000);
1034
+ checkResolver = result => { clearTimeout(timer); checkResolver = null; result.error ? reject(new Error(result.error)) : resolve(result); };
1035
+ sendUI({ type: "CHECK_SCREEN", ...identity, snapshot });
1036
+ });
1037
+ }
1038
+
1039
+ // Process individual screen/frame
1040
+ async function exportScreenNode(node, currentPath, scale) {
1041
+ const screenPath = [...currentPath, node.name];
1042
+ const identity = exportIdentity(node);
1043
+ // JSON_REST captures the resolved subtree before expensive image rendering.
1044
+ const snapshot = await node.exportAsync({ format: "JSON_REST_V1" });
1045
+ const check = await checkScreen(identity, JSON.stringify({ version: 1, scale, snapshot }));
1046
+ if (!forceExport && check.unchanged) {
1047
+ sendUI({ type: "PROGRESS_UPDATE", message: `⏭ Không đổi: ${node.name}` });
1048
+ return;
1049
+ }
1050
+
1051
+ sendUI({
1052
+ type: "PROGRESS_UPDATE",
1053
+ message: `📸 Render ảnh 2x Retina & trích xuất SVGs, Images, CSS 100%: ${node.name}...`
1054
+ });
1055
+
1056
+ const context = {
1057
+ componentsUsed: {},
1058
+ fontsUsed: {},
1059
+ designTokens: {
1060
+ colors: {},
1061
+ typography: {},
1062
+ radii: {},
1063
+ shadows: {}
1064
+ },
1065
+ assets: [],
1066
+ assetsManifest: []
1067
+ };
1068
+
1069
+ // 1. Export High-Res Screenshot (PNG)
1070
+ const screenshotBytes = await node.exportAsync({
1071
+ format: "PNG",
1072
+ constraint: { type: "SCALE", value: scale }
1073
+ });
1074
+ const screenshotB64 = bufferToBase64(screenshotBytes);
1075
+
1076
+ // 2. Extract Deep Recursive DOM Tree with Native + Computed CSS, SVGs & Images
1077
+ const detailedTree = await extractDetailedNodeTree(node, context);
1078
+
1079
+ // 3. Generate Font Guides & Assets Manifest
1080
+ const fontGuide = generateFontGuides(context.fontsUsed);
1081
+ const markdownSpec = generateMarkdownDoc(detailedTree, context.componentsUsed, context.designTokens, fontGuide, context.assetsManifest);
1082
+ const specJson = JSON.stringify(detailedTree, null, 2);
1083
+ const componentsJson = JSON.stringify(context.componentsUsed, null, 2);
1084
+ const tokensJson = JSON.stringify(context.designTokens, null, 2);
1085
+ const fontGuideJson = JSON.stringify(fontGuide, null, 2);
1086
+ const assetsManifestJson = JSON.stringify(context.assetsManifest, null, 2);
1087
+ const snippetsHtml = generateComponentSnippetsHtml(node.name, context.componentsUsed, fontGuide);
1088
+
1089
+ // 4. Bundle files to send to Bridge Server
1090
+ const filesToUpload = [
1091
+ { name: "screenshot.png", type: "base64", content: screenshotB64 },
1092
+ { name: "spec.json", type: "text", content: specJson },
1093
+ { name: "spec.md", type: "text", content: markdownSpec },
1094
+ { name: "components_used.json", type: "text", content: componentsJson },
1095
+ { name: "fonts_guide.json", type: "text", content: fontGuideJson },
1096
+ { name: "assets_manifest.json", type: "text", content: assetsManifestJson },
1097
+ { name: "component_snippets.html", type: "text", content: snippetsHtml },
1098
+ { name: "design_tokens.json", type: "text", content: tokensJson },
1099
+ ...context.assets
1100
+ ];
1101
+
1102
+ sendUI({
1103
+ type: "UPLOAD_SCREEN_BATCH",
1104
+ folder_path: screenPath,
1105
+ ...exportIdentity(node),
1106
+ screen_name: node.name,
1107
+ content_hash: check.hash,
1108
+ files: filesToUpload
1109
+ });
1110
+
1111
+ // Await sequential ACK from UI before proceeding to next screen!
1112
+ if (!await waitForUploadAck(60000)) throw new Error("Upload failed or timed out; export stopped.");
1113
+ }
1114
+
1115
+ // Recursive section walker
1116
+ async function processNode(node, currentPath, scale) {
1117
+ if (node.type === "SECTION") {
1118
+ const sectionPath = [...currentPath, node.name];
1119
+
1120
+ // Gather UX Notes in Section
1121
+ const notes = [];
1122
+ for (const child of node.children) {
1123
+ if (child.type === "TEXT" && child.characters) {
1124
+ notes.push(child.characters);
1125
+ }
1126
+ }
1127
+ if (notes.length > 0) {
1128
+ const notesMd = `# Flow & UX Notes: ${node.name}\n\n` + notes.map(n => `- ${n}`).join("\n\n");
1129
+ sendUI({
1130
+ type: "UPLOAD_NOTES",
1131
+ folder_path: sectionPath,
1132
+ ...exportIdentity(node),
1133
+ content: notesMd
1134
+ });
1135
+ if (!await waitForUploadAck(30000)) throw new Error("Notes upload failed or timed out; export stopped.");
1136
+ }
1137
+
1138
+ for (const child of node.children) {
1139
+ if (child.type === "SECTION" || child.type === "FRAME" || child.type === "COMPONENT" || child.type === "INSTANCE" || child.type === "COMPONENT_SET") {
1140
+ await processNode(child, sectionPath, scale);
1141
+ }
1142
+ }
1143
+ } else if (node.type === "FRAME" || node.type === "COMPONENT" || node.type === "INSTANCE" || node.type === "COMPONENT_SET") {
1144
+ // Export artboard-level frames or component sets
1145
+ if (node.width >= 160 && node.height >= 100) {
1146
+ await exportScreenNode(node, currentPath, scale);
1147
+ }
1148
+ }
1149
+ }
1150
+
1151
+ figma.ui.onmessage = async (msg) => {
1152
+ if (msg.type === "SET_LANGUAGE") {
1153
+ language = msg.language === "en" ? "en" : "vi";
1154
+ await figma.clientStorage.setAsync("exportLanguage", language);
1155
+ } else if (msg.type === "CHECK_RESULT") {
1156
+ if (checkResolver) checkResolver(msg);
1157
+ } else if (msg.type === "SCREEN_UPLOAD_ACK") {
1158
+ if (currentAckResolver) {
1159
+ currentAckResolver(msg.success);
1160
+ currentAckResolver = null;
1161
+ }
1162
+ } else if (msg.type === "GET_DOCUMENT") {
1163
+ sendUI({type:"DOCUMENT_ID", documentId:figma.fileKey || localDocumentId});
1164
+ } else if (msg.type === "START_EXPORT") {
1165
+ if (activeRunId || typeof msg.runId !== "string" || !msg.runId) return;
1166
+ activeRunId = msg.runId;
1167
+ try {
1168
+ forceExport = !!msg.force;
1169
+ const scope = msg.scope || "current_page";
1170
+ const scale = msg.scale || 2;
1171
+
1172
+ figma.notify(localized("Bắt đầu xuất dữ liệu Pixel-Perfect (SVGs, Images, Fonts, CSS 100%)...","Starting export (assets, fonts and CSS)\u2026"));
1173
+
1174
+ if (scope === "selection") {
1175
+ const selection = figma.currentPage.selection;
1176
+ if (!selection || selection.length === 0) {
1177
+ throw new Error(localized("Vui lòng chọn ít nhất 1 mục trên canvas!","Select at least one item on the canvas."));
1178
+ }
1179
+ for (const item of selection) {
1180
+ await processNode(item, [], scale);
1181
+ }
1182
+ } else if (scope === "current_page") {
1183
+ const page = figma.currentPage;
1184
+ sendUI({
1185
+ type: "PROGRESS_UPDATE",
1186
+ message: `🚀 Đang quét toàn bộ Page '${page.name}'...`
1187
+ });
1188
+ for (const item of page.children) {
1189
+ if (item.type === "SECTION" || item.type === "FRAME" || item.type === "COMPONENT" || item.type === "INSTANCE" || item.type === "COMPONENT_SET") {
1190
+ await processNode(item, [page.name], scale);
1191
+ }
1192
+ }
1193
+ } else if (scope === "all_pages") {
1194
+ sendUI({
1195
+ type: "PROGRESS_UPDATE",
1196
+ message: `📥 Đang tải tất cả các pages trong document...`
1197
+ });
1198
+ await figma.loadAllPagesAsync();
1199
+
1200
+ for (const page of figma.root.children) {
1201
+ if (page.name.toUpperCase().includes("TRASH") || page.name === "---" || page.children.length === 0) {
1202
+ continue;
1203
+ }
1204
+ sendUI({
1205
+ type: "PROGRESS_UPDATE",
1206
+ message: `📁 Đang xử lý Page: ${page.name}...`
1207
+ });
1208
+ for (const item of page.children) {
1209
+ if (item.type === "SECTION" || item.type === "FRAME" || item.type === "COMPONENT" || item.type === "INSTANCE" || item.type === "COMPONENT_SET") {
1210
+ await processNode(item, [page.name], scale);
1211
+ }
1212
+ }
1213
+ }
1214
+ }
1215
+
1216
+ sendUI({
1217
+ type: "EXPORT_FINISHED"
1218
+ });
1219
+ figma.notify(localized("🎉 Đã hoàn tất xuất toàn bộ screens, assets (SVG/PNG) và specs chuẩn xác 100%!","\ud83c\udf89 Export completed."));
1220
+ } catch (error) {
1221
+ sendUI({ type: "EXPORT_ERROR", message: error.message });
1222
+ figma.notify(error.message, { error: true });
1223
+ } finally {
1224
+ activeRunId = null;
1225
+ }
1226
+ }
1227
+ };