ai-direct-spec.mjs
9.5 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
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
#!/usr/bin/env node
/**
* AI Direct - Figma to Design Spec 模块
*
* 从 Figma design context 中提取结构化 spec,包括:
* - section purpose (区域作用)
* - patterns (可复用 UI 模式)
* - token candidates (颜色、间距、字体等设计信号)
* - uncertainty (未明确的决策点)
*
* 这个 spec 作为 AI 代码生成的中间层输入,避免 AI 直接猜测设计意图。
*/
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const _filename = fileURLToPath(import.meta.url);
const _dirname = path.dirname(_filename);
/**
* 从 Figma design context 中提取设计 spec
* @param {string} designContext - Figma YAML 或 HTML 格式的设计上下文
* @param {object} options - 选项
* @returns {object} design spec
*/
export function buildDesignSpec(designContext, options = {}) {
if (!designContext || typeof designContext !== "string") {
return null;
}
const spec = {
version: "1.0",
generatedAt: new Date().toISOString(),
sections: [],
uncertainty: [],
};
// 1. 提取 token candidates (颜色、间距、字体)
const tokens = extractTokenCandidates(designContext);
spec.tokens = tokens;
// 2. 识别 UI patterns (可复用模式)
const patterns = extractPatterns(designContext);
spec.patterns = patterns;
// 3. 标记 uncertainty (未明确的决策点)
const uncertainty = detectUncertainty(designContext);
spec.uncertainty = uncertainty;
// 4. 提取 section purpose (如果有多个 frame/section)
const sections = extractSections(designContext);
spec.sections = sections;
return spec;
}
/**
* 提取 token candidates:从 Figma 数据中识别设计信号
*/
function extractTokenCandidates(designContext) {
const tokens = {
colors: [],
spacing: [],
typography: [],
radius: [],
};
// 1. 提取颜色
const colorPattern = /rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)(?:\s*,\s*([\d.]+))?\s*\)/g;
const colorSet = new Set();
let match;
while ((match = colorPattern.exec(designContext)) !== null) {
const [r, g, b, a] = [
parseInt(match[1], 10),
parseInt(match[2], 10),
parseInt(match[3], 10),
match[4] ? parseFloat(match[4]) : 1,
];
const color = a < 1 ? `rgba(${r}, ${g}, ${b}, ${a})` : `rgb(${r}, ${g}, ${b})`;
if (!colorSet.has(color)) {
colorSet.add(color);
tokens.colors.push({
value: color,
role: inferColorRole(r, g, b, a, designContext, match.index),
});
}
}
// 2. 提取间距 (padding, margin, gap)
const spacingPattern = /(?:padding|margin|gap|w|h|width|height)[:\s]+(\d+)px/gi;
const spacingSet = new Set();
while ((match = spacingPattern.exec(designContext)) !== null) {
const value = parseInt(match[1], 10);
if (value > 0 && value <= 200 && !spacingSet.has(value)) {
spacingSet.add(value);
tokens.spacing.push({ value: `${value}px`, raw: value });
}
}
tokens.spacing.sort((a, b) => a.raw - b.raw);
// 3. 提取字体大小和行高
const fontSizePattern = /font-?size[:\s]+(\d+)px/gi;
const lineHeightPattern = /line-?height[:\s]+([\d.]+)/gi;
const typographySet = new Set();
while ((match = fontSizePattern.exec(designContext)) !== null) {
const size = parseInt(match[1], 10);
if (!typographySet.has(size)) {
typographySet.add(size);
tokens.typography.push({ fontSize: `${size}px`, raw: size });
}
}
while ((match = lineHeightPattern.exec(designContext)) !== null) {
const lh = parseFloat(match[1]);
const existing = tokens.typography.find((t) => t.lineHeight === lh);
if (!existing) {
tokens.typography.push({ lineHeight: lh, raw: lh });
}
}
tokens.typography.sort((a, b) => (a.raw || 0) - (b.raw || 0));
// 4. 提取圆角
const radiusPattern = /radius[:\s]+\[(\d+(?:,\s*\d+)*)\]/gi;
while ((match = radiusPattern.exec(designContext)) !== null) {
const values = match[1].split(",").map((v) => parseInt(v.trim(), 10));
tokens.radius.push({ value: values.map((v) => `${v}px`).join(" "), raw: values });
}
return tokens;
}
/**
* 推断颜色的语义角色
*/
function inferColorRole(r, g, b, a, context, index) {
// 高饱和度 = 主色/强调色
const saturation = Math.max(r, g, b) - Math.min(r, g, b);
// 主色 (蓝色系)
if (b > 180 && r < 100 && saturation > 150) {
return "primary";
}
// 错误/警告 (红色系)
if (r > 180 && g < 100 && saturation > 150) {
return "error";
}
// 成功 (绿色系)
if (g > 150 && r < 100 && b < 100) {
return "success";
}
// 文字色 (深灰/黑)
if (r === g && g === b && r < 100) {
return "text-primary";
}
// 次级文字 (中灰)
if (r === g && g === b && r >= 100 && r < 180) {
return "text-secondary";
}
// 背景色 (浅灰/白)
if (r === g && g === b && r >= 230) {
return "background";
}
// 边框 (中等灰度)
if (r === g && g === b && r >= 180 && r < 230) {
return "border";
}
return "unknown";
}
/**
* 识别 UI patterns (可复用模式)
*/
function extractPatterns(designContext) {
const patterns = [];
// 1. Key-Value 列表
if (/label|key|title[\s\S]{0,50}value|content|text/i.test(designContext)) {
patterns.push({
type: "key-value-list",
description: "标签-值对列表,常用于信息展示",
selector: ".label + .value 或 .key + .value",
});
}
// 2. 图片网格
if (/grid[\s\S]{0,100}image|photo|picture/i.test(designContext)) {
patterns.push({
type: "image-grid",
description: "图片网格布局",
selector: "display: grid + img",
});
}
// 3. 悬浮按钮/角标
if (/absolute[\s\S]{0,100}(top|right|bottom|left)/i.test(designContext)) {
patterns.push({
type: "floating-overlay",
description: "悬浮元素 (按钮、角标、计数器等)",
selector: "position: absolute",
});
}
// 4. 固定底栏
if (/fixed[\s\S]{0,50}bottom[:\s]+0/i.test(designContext)) {
patterns.push({
type: "fixed-bottom-bar",
description: "固定底栏 (操作按钮、导航等)",
selector: "position: fixed; bottom: 0",
});
}
// 5. 价格/倒计时区域
if (/price|countdown|timer/i.test(designContext)) {
patterns.push({
type: "price-countdown",
description: "价格或倒计时展示区域",
selector: ".price-section 或 .countdown",
});
}
return patterns;
}
/**
* 检测 uncertainty (未明确的决策点)
*/
function detectUncertainty(designContext) {
const uncertainty = [];
// 1. hover/focus 态
if (!/hover|:hover|focus|:focus/i.test(designContext)) {
uncertainty.push({
type: "interaction-state",
description: "hover/focus 态未在设计稿中明确",
impact: "需要设计师确认或参考同类组件",
});
}
// 2. 响应式/移动端
if (!/mobile|tablet|responsive|@media/i.test(designContext)) {
uncertainty.push({
type: "responsive",
description: "响应式/移动端布局未在设计稿中明确",
impact: "需要设计师确认或参考设计系统",
});
}
// 3. 暗色模式
if (!/dark|theme|mode/i.test(designContext)) {
uncertainty.push({
type: "dark-mode",
description: "暗色模式配色未在设计稿中明确",
impact: "如果项目支持暗色模式,需要设计师补充",
});
}
// 4. 空状态/加载态/错误态
if (!/empty|loading|error|skeleton/i.test(designContext)) {
uncertainty.push({
type: "edge-states",
description: "空状态/加载态/错误态未在设计稿中明确",
impact: "需要设计师补充或参考设计系统",
});
}
return uncertainty;
}
/**
* 提取多个 sections (如果 design context 包含多个 frame)
*/
function extractSections(designContext) {
const sections = [];
// 尝试识别 frame/section 边界
const framePattern = /name:\s*["']?([^"'\n]+)["']?[\s\S]{0,200}?type:\s*(?:FRAME|GROUP)/gi;
let match;
while ((match = framePattern.exec(designContext)) !== null) {
const name = match[1].trim();
sections.push({
name,
purpose: inferSectionPurpose(name),
});
}
return sections;
}
/**
* 推断 section 的作用
*/
function inferSectionPurpose(name) {
const lower = name.toLowerCase();
if (/hero|banner|header/i.test(lower)) return "页面顶部展示区";
if (/nav|menu|sidebar/i.test(lower)) return "导航/菜单";
if (/content|main|body/i.test(lower)) return "主要内容区";
if (/footer|bottom/i.test(lower)) return "页面底部";
if (/card|list|grid/i.test(lower)) return "卡片/列表展示";
if (/form|input|search/i.test(lower)) return "表单/输入";
if (/modal|dialog|popup/i.test(lower)) return "弹窗/浮层";
return "通用区域";
}
/**
* 将 spec 写入文件
*/
export function writeDesignSpec(spec, outputPath) {
const content = JSON.stringify(spec, null, 2);
fs.writeFileSync(outputPath, content, "utf-8");
console.log(`[ai-direct-spec] ✓ Design spec written to ${outputPath}`);
return outputPath;
}
/**
* 读取 spec 文件
*/
export function readDesignSpec(specPath) {
if (!fs.existsSync(specPath)) {
return null;
}
try {
const content = fs.readFileSync(specPath, "utf-8");
return JSON.parse(content);
} catch (err) {
console.warn(`[ai-direct-spec] Failed to read spec: ${err.message}`);
return null;
}
}
// CLI 入口
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const designContextPath = process.argv[2];
const outputPath = process.argv[3] || designContextPath.replace(/\.html$/, ".spec.json");
if (!designContextPath) {
console.error("Usage: node ai-direct-spec.mjs <design-context.html> [output.spec.json]");
process.exit(1);
}
if (!fs.existsSync(designContextPath)) {
console.error(`Error: File not found: ${designContextPath}`);
process.exit(1);
}
const designContext = fs.readFileSync(designContextPath, "utf-8");
const spec = buildDesignSpec(designContext);
writeDesignSpec(spec, outputPath);
}