ai-direct-theme.mjs 11.6 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 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 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
#!/usr/bin/env node
/**
 * AI Direct - Token to Theme Mapping 模块
 *
 * 将 design spec 中的 token candidates 映射到项目的语义主题变量。
 *
 * 核心原则:
 * 1. 优先复用已有语义角色 (--vui-color-primary, --vui-spacing-4 等)
 * 2. 只动 theme 层 (CSS variables, Tailwind config)
 * 3. 保留项目已有格式 (HSL/hex/rgb)
 * 4. 不发明局部变量 (--header-bg, --nav-text 等)
 *
 * 输出:theme-mapping.json,指导 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);

/**
 * 扫描项目的语义主题变量
 * @param {string} projectRoot - 项目根目录
 * @returns {object} 语义变量集合
 */
export function scanProjectTheme(projectRoot) {
	const theme = {
		colors: {},
		spacing: {},
		typography: {},
		radius: {},
		format: "rgb", // hsl | hex | rgb
	};

	// 1. 扫描 VUI tokens (packages/vui/tokens/src/ 和 packages/vui/*/tokens/)
	const vuiTokensDirs = [
		path.join(projectRoot, "packages/vui/tokens/src"),
		path.join(projectRoot, "packages/vui/mobile/tokens"),
		path.join(projectRoot, "packages/vui/pc/tokens"),
		path.join(projectRoot, "packages/vui/shared/tokens"),
	];

	for (const dir of vuiTokensDirs) {
		if (fs.existsSync(dir)) {
			const tokenFiles = fs.readdirSync(dir).filter((f) => f.endsWith(".json") || f.endsWith(".css") || f.endsWith(".ts") || f.endsWith(".js"));
			for (const file of tokenFiles) {
				const content = fs.readFileSync(path.join(dir, file), "utf8");
				parseThemeVariables(content, theme);
			}
		}
	}

	// 2. 扫描项目级 CSS variables (apps/*/src/**/*.css)
	const appsDir = path.join(projectRoot, "apps");
	if (fs.existsSync(appsDir)) {
		const apps = fs.readdirSync(appsDir);
		for (const app of apps) {
			const cssDir = path.join(appsDir, app, "src");
			if (fs.existsSync(cssDir)) {
				scanCssVariables(cssDir, theme);
			}
		}
	}

	// 3. 扫描 Tailwind config (tailwind.config.js)
	const tailwindConfig = path.join(projectRoot, "tailwind.config.js");
	if (fs.existsSync(tailwindConfig)) {
		const content = fs.readFileSync(tailwindConfig, "utf8");
		parseTailwindTheme(content, theme);
	}

	return theme;
}

/**
 * 解析 CSS variables (--var-name: value) 和 TypeScript token exports
 */
function parseThemeVariables(content, theme) {
	// 1. CSS variables
	const varPattern = /--([a-z0-9-]+)\s*:\s*([^;]+);/gi;
	let match;
	while ((match = varPattern.exec(content)) !== null) {
		const name = match[1];
		const value = match[2].trim();

		if (/color|primary|secondary|accent|error|warning|success|background|foreground|border/i.test(name)) {
			theme.colors[name] = value;
			if (/hsl/i.test(value)) theme.format = "hsl";
			else if (value.startsWith("#")) theme.format = "hex";
		} else if (/spacing|gap|margin|padding/i.test(name)) {
			theme.spacing[name] = value;
		} else if (/font|text|heading|body/i.test(name)) {
			theme.typography[name] = value;
		} else if (/radius|rounded/i.test(name)) {
			theme.radius[name] = value;
		}
	}

	// 2. TypeScript token exports (vuiColorTokens, vuiSpacingTokens 等)
	// 匹配: export const vuiXxxTokens = { key: "value", ... } as const;
	const tsExportPattern = /export\s+const\s+vui(\w+)Tokens\s*=\s*\{([\s\S]*?)\}\s*as\s+const/g;
	while ((match = tsExportPattern.exec(content)) !== null) {
		const tokenType = match[1].toLowerCase(); // color, spacing, etc.
		const body = match[2];

		// 解析 key: value 对
		const entryPattern = /(\w+)\s*:\s*(?:"([^"]+)"|'([^']+)'|(\d+))/g;
		let entry;
		while ((entry = entryPattern.exec(body)) !== null) {
			const key = entry[1];
			const value = entry[2] || entry[3] || entry[4];

			switch (tokenType) {
				case "color": {
					theme.colors[`vui-color-${key}`] = value;
					if (value.startsWith("#")) theme.format = "hex";

					break;
				}
				case "font":
				case "typography": {
					theme.typography[`vui-${key}`] = value;

					break;
				}
				case "radius": {
					theme.radius[`vui-radius-${key}`] = `${value}px`;

					break;
				}
				case "spacing": {
					theme.spacing[`vui-spacing-${key}`] = `${value}px`;

					break;
				}
				default: {
				// 通用 token
					theme.colors[`vui-${tokenType}-${key}`] = value;
				}
			}
		}
	}
}

/**
 * 递归扫描 CSS 文件中的 variables
 */
function scanCssVariables(dir, theme) {
	const files = fs.readdirSync(dir);
	for (const file of files) {
		const fullPath = path.join(dir, file);
		const stat = fs.statSync(fullPath);
		if (stat.isDirectory()) {
			scanCssVariables(fullPath, theme);
		} else if (file.endsWith(".css")) {
			const content = fs.readFileSync(fullPath, "utf8");
			parseThemeVariables(content, theme);
		}
	}
}

/**
 * 解析 Tailwind config 中的 theme 扩展
 */
function parseTailwindTheme(content, theme) {
	// 简单匹配 colors/spacing/extend 等
	if (/colors\s*:\s*\{/.test(content)) {
		const colorMatch = content.match(/colors\s*:\s*\{([^}]+)\}/);
		if (colorMatch) {
			const colorContent = colorMatch[1];
			const entryPattern = /(\w+)\s*:\s*['"]([^'"]+)['"]/g;
			let match;
			while ((match = entryPattern.exec(colorContent)) !== null) {
				theme.colors[`tw-${match[1]}`] = match[2];
			}
		}
	}
}

/**
 * 将 token candidates 映射到语义主题变量
 * @param {object} spec - design spec
 * @param {object} projectTheme - 项目语义主题
 * @returns {object} theme mapping
 */
export function mapTokensToTheme(spec, projectTheme) {
	const mapping = {
		version: "1.0",
		generatedAt: new Date().toISOString(),
		colors: [],
		spacing: [],
		typography: [],
		radius: [],
	};

	// 1. 映射颜色
	for (const token of spec.tokens.colors) {
		const mapped = findMatchingThemeColor(token.value, token.role, projectTheme.colors);
		mapping.colors.push({
			designValue: token.value,
			inferredRole: token.role,
			semanticVariable: mapped.variable,
			status: mapped.status, // "reused" | "missing" | "approximate"
			recommendation: mapped.recommendation,
		});
	}

	// 2. 映射间距
	for (const token of spec.tokens.spacing) {
		const mapped = findMatchingThemeSpacing(token.raw, projectTheme.spacing);
		mapping.spacing.push({
			designValue: token.value,
			semanticVariable: mapped.variable,
			status: mapped.status,
		});
	}

	// 3. 映射字体
	for (const token of spec.tokens.typography) {
		const mapped = findMatchingThemeTypography(token.raw, projectTheme.typography);
		mapping.typography.push({
			designValue: token.fontSize || token.lineHeight,
			semanticVariable: mapped.variable,
			status: mapped.status,
		});
	}

	// 4. 映射圆角
	for (const token of spec.tokens.radius) {
		const mapped = findMatchingThemeRadius(token.raw, projectTheme.radius);
		mapping.radius.push({
			designValue: token.value,
			semanticVariable: mapped.variable,
			status: mapped.status,
		});
	}

	return mapping;
}

/**
 * 查找匹配的主题颜色变量
 */
function findMatchingThemeColor(designValue, inferredRole, themeColors) {
	// 1. 先按 role 匹配
	const roleKeys = Object.keys(themeColors).filter((k) => k.toLowerCase().includes(inferredRole));
	if (roleKeys.length > 0) {
		return {
			variable: `--${roleKeys[0]}`,
			status: "reused",
			recommendation: `使用已有语义变量 --${roleKeys[0]}`,
		};
	}

	// 2. 按颜色值近似匹配
	for (const [name, value] of Object.entries(themeColors)) {
		if (colorDistance(designValue, value) < 30) {
			return {
				variable: `--${name}`,
				status: "approximate",
				recommendation: `颜色接近 --${name},建议复用`,
			};
		}
	}

	// 3. 未找到
	return {
		variable: null,
		status: "missing",
		recommendation: `项目中未找到匹配的颜色变量,建议新增 --${inferredRole}`,
	};
}

/**
 * 计算两个颜色的距离 (简单 RGB 欧氏距离)
 */
function colorDistance(c1, c2) {
	const rgb1 = parseColor(c1);
	const rgb2 = parseColor(c2);
	if (!rgb1 || !rgb2) return Infinity;
	return Math.hypot((rgb1.r - rgb2.r), (rgb1.g - rgb2.g), (rgb1.b - rgb2.b));
}

/**
 * 解析颜色值为 RGB
 */
function parseColor(value) {
	if (!value) return null;

	// rgb(r, g, b) 或 rgba(r, g, b, a)
	const rgbMatch = value.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
	if (rgbMatch) {
		return { r: +rgbMatch[1], g: +rgbMatch[2], b: +rgbMatch[3] };
	}

	// hex
	const hexMatch = value.match(/^#([0-9a-f]{3,8})$/i);
	if (hexMatch) {
		const hex = hexMatch[1];
		if (hex.length === 3) {
			return {
				r: Number.parseInt(hex[0] + hex[0], 16),
				g: Number.parseInt(hex[1] + hex[1], 16),
				b: Number.parseInt(hex[2] + hex[2], 16),
			};
		}
		if (hex.length === 6) {
			return {
				r: Number.parseInt(hex.slice(0, 2), 16),
				g: Number.parseInt(hex.slice(2, 4), 16),
				b: Number.parseInt(hex.slice(4, 6), 16),
			};
		}
	}

	return null;
}

/**
 * 查找匹配的主题间距变量
 */
function findMatchingThemeSpacing(rawValue, themeSpacing) {
	// 优先精确匹配
	for (const [name, value] of Object.entries(themeSpacing)) {
		const match = value.match(/^(\d+)px$/);
		if (match && Number.parseInt(match[1], 10) === rawValue) {
			return { variable: `--${name}`, status: "reused" };
		}
	}

	// 近似匹配 (±2px)
	for (const [name, value] of Object.entries(themeSpacing)) {
		const match = value.match(/^(\d+)px$/);
		if (match && Math.abs(Number.parseInt(match[1], 10) - rawValue) <= 2) {
			return { variable: `--${name}`, status: "approximate" };
		}
	}

	return { variable: null, status: "missing" };
}

/**
 * 查找匹配的主题字体变量
 */
function findMatchingThemeTypography(rawValue, themeTypography) {
	// 简单匹配
	for (const [name, value] of Object.entries(themeTypography)) {
		if (Number.parseInt(value, 10) === rawValue) {
			return { variable: `--${name}`, status: "reused" };
		}
	}
	return { variable: null, status: "missing" };
}

/**
 * 查找匹配的主题圆角变量
 */
function findMatchingThemeRadius(rawValues, themeRadius) {
	const primaryRadius = rawValues[0];
	for (const [name, value] of Object.entries(themeRadius)) {
		const match = value.match(/^(\d+)px/);
		if (match && Number.parseInt(match[1], 10) === primaryRadius) {
			return { variable: `--${name}`, status: "reused" };
		}
	}
	return { variable: null, status: "missing" };
}

/**
 * 将 mapping 写入文件
 */
export function writeThemeMapping(mapping, outputPath) {
	const content = JSON.stringify(mapping, null, 2);
	fs.writeFileSync(outputPath, content, "utf-8");
	console.log(`[ai-direct-theme] ✓ Theme mapping written to ${outputPath}`);
	return outputPath;
}

/**
 * 读取 mapping 文件
 */
export function readThemeMapping(mappingPath) {
	if (!fs.existsSync(mappingPath)) {
		return null;
	}
	try {
		const content = fs.readFileSync(mappingPath, "utf8");
		return JSON.parse(content);
	} catch (error) {
		console.warn(`[ai-direct-theme] Failed to read mapping: ${error.message}`);
		return null;
	}
}

// CLI 入口
if (process.argv[1] === fileURLToPath(import.meta.url)) {
	const specPath = process.argv[2];
	const projectRoot = process.argv[3] || path.resolve(_dirname, "..");
	const outputPath = process.argv[4] || specPath.replace(/\.spec\.json$/, ".theme-mapping.json");

	if (!specPath) {
		console.error("Usage: node ai-direct-theme.mjs <design.spec.json> [project-root] [output.theme-mapping.json]");
		process.exit(1);
	}

	if (!fs.existsSync(specPath)) {
		console.error(`Error: File not found: ${specPath}`);
		process.exit(1);
	}

	const specContent = fs.readFileSync(specPath, "utf8");
	const spec = JSON.parse(specContent);

	console.log(`[ai-direct-theme] Scanning project theme from ${projectRoot}...`);
	const projectTheme = scanProjectTheme(projectRoot);

	console.log(`[ai-direct-theme] Mapping tokens to theme...`);
	const mapping = mapTokensToTheme(spec, projectTheme);

	writeThemeMapping(mapping, outputPath);
}