ai-direct-spec.mjs 9.5 KB
#!/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);
}