@hia/theme-core 0.6.0 → 0.7.0

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,433 @@
1
+ import { hexToRgb, rgbToHex, normalizeHex, validHex, clamp } from '../color/convert.js';
2
+ import { nameColor } from '../color/color-name.js';
3
+ import { bestOnColor } from '../color/contrast.js';
4
+ import { tonalScale } from '../color/scale.js';
5
+ import { radiusSequence, shadowCss } from '../token/radius.js';
6
+ import { spacingSequence } from '../token/typography.js';
7
+ import { resolveScaleColor, collectCustomShades } from '../gradient/render.js';
8
+ import { cloneGradientSettings } from '../data/gradients.js';
9
+ import { GRADIENT_DEFS } from '../data/gradients.js';
10
+ import { slugifyThemeName } from './shared.js';
11
+ // ===== 导出 =====
12
+ /** @lang zh-CN sRGB HEX → DTCG color 值(components 归一化 0–1 三位小数 + hex 兜底,均为 schema 允许形态)。 @lang en sRGB HEX → DTCG color value (components normalised 0–1 at 3dp plus the optional hex fallback — both schema-sanctioned). */
13
+ function colorValue(hex) {
14
+ const [r, g, b] = hexToRgb(hex);
15
+ return { colorSpace: 'srgb', components: [Number(r.toFixed(3)), Number(g.toFixed(3)), Number(b.toFixed(3))], hex: normalizeHex(hex) };
16
+ }
17
+ /** @lang zh-CN 颜色 token。 @lang en A colour token. */
18
+ function colorToken(hex, description) {
19
+ const t = { '$type': 'color', '$value': colorValue(hex) };
20
+ if (description)
21
+ t['$description'] = description;
22
+ return t;
23
+ }
24
+ /** @lang zh-CN dimension token(px)。 @lang en A dimension token (px). */
25
+ function dimensionToken(px) {
26
+ return { '$type': 'dimension', '$value': { value: px, unit: 'px' } };
27
+ }
28
+ /** @lang zh-CN 角色色 → DTCG 组:base + on + 10 阶 + 渐变引用的自定义档。 @lang en Role colour → DTCG group: base + on + ten steps + gradient-referenced custom shades. */
29
+ function roleGroup(role, custom) {
30
+ const group = {};
31
+ group['base'] = colorToken(role.value, 'Base colour / 基色');
32
+ group['on'] = colorToken(role.on, 'Readable foreground on base / 基色上的可读前景');
33
+ for (const [k, v] of Object.entries(role.scale))
34
+ group[k] = colorToken(v, `Step ${k} / ${k} 阶`);
35
+ for (const [k, v] of Object.entries(custom))
36
+ group[k] = colorToken(v, `Custom shade ${k} / 自定义 ${k} 阶`);
37
+ return group;
38
+ }
39
+ /**
40
+ * @lang zh-CN 渐变 bias → DTCG stops(position 0–1)。
41
+ * front80 → [(start,0),(start,0.8),(end,1)];end20 → [(start,0),(end,0.8),(end,1)];
42
+ * 无 bias → [(start,0),(end,1)]。色值取 literal(真实色阶值)。
43
+ * @lang en Gradient bias → DTCG stops (position 0–1): front80 → [(start,0),(start,0.8),(end,1)];
44
+ * end20 → [(start,0),(end,0.8),(end,1)]; no bias → [(start,0),(end,1)]. Colours are literal resolved scale
45
+ * values.
46
+ */
47
+ function gradientStopsValue(config, theme) {
48
+ const start = resolveScaleColor(theme, config.family, config.start), end = resolveScaleColor(theme, config.family, config.end);
49
+ const m = /^(front|end)(\d+)$/.exec(config.bias);
50
+ const n = m ? clamp(Number(m[2]), 0, 100) : null;
51
+ const raw = m && m[1] === 'front'
52
+ ? [[start, 0], [start, n / 100], [end, 1]]
53
+ : m && m[1] === 'end'
54
+ ? [[start, 0], [end, (100 - n) / 100], [end, 1]]
55
+ : [[start, 0], [end, 1]];
56
+ return raw.map(([hex, position]) => ({ color: colorValue(hex), position }));
57
+ }
58
+ /**
59
+ * @lang zh-CN CSS 双层 box-shadow 字符串 → DTCG shadow 数组(逐层解析 offset/blur/spread 与颜色)。
60
+ * 我们生成的两层格式固定;覆写值可能任意——用宽松正则逐层抽取,解析失败的层跳过(尽量保真)。
61
+ * @lang en Parses our two-layer CSS box-shadow string into a DTCG shadow array (offset/blur/spread/colour per
62
+ * layer). Our generated format is fixed, but overrides may be arbitrary — a lenient regex extracts layers and
63
+ * skips unparseable ones to stay lossless where possible.
64
+ */
65
+ function parseBoxShadow(css) {
66
+ if (!css || css === 'none')
67
+ return null;
68
+ // 顶层逗号分层(括号深度感知)——legacy rgba(...) 内的逗号不会被误切。
69
+ // <lang en>Split on top-level commas (paren-depth aware) so commas inside legacy rgba(...) never split.</lang>
70
+ const layers = [];
71
+ let depth = 0, buf = '';
72
+ for (const ch of css) {
73
+ if (ch === '(')
74
+ depth++;
75
+ else if (ch === ')')
76
+ depth--;
77
+ if (ch === ',' && depth === 0) {
78
+ layers.push(buf.trim());
79
+ buf = '';
80
+ }
81
+ else
82
+ buf += ch;
83
+ }
84
+ if (buf.trim())
85
+ layers.push(buf.trim());
86
+ const out = [];
87
+ for (const layer of layers) {
88
+ // 首 token 可无 px(CSS box-shadow 合法形态:`0 1px 3px 0px …`)。
89
+ // <lang en>The first token may omit px (a legal box-shadow form: `0 1px 3px 0px …`).</lang>
90
+ const m = /^([-.\d]+)(?:px)?\s+([-\d.]+)px\s+([-\d.]+)px(?:\s+([-\d.]+)px)?\s+(.+)$/.exec(layer);
91
+ if (!m)
92
+ continue;
93
+ const shadowColor = parseShadowColor(m[5] ?? '');
94
+ if (!shadowColor)
95
+ continue;
96
+ out.push({
97
+ color: shadowColor,
98
+ offsetX: { value: Number(m[1] ?? 0), unit: 'px' },
99
+ offsetY: { value: Number(m[2]), unit: 'px' },
100
+ blur: { value: Number(m[3]), unit: 'px' },
101
+ spread: { value: Number(m[4] ?? 0), unit: 'px' },
102
+ inset: false
103
+ });
104
+ }
105
+ return out.length ? out : null;
106
+ }
107
+ /** @lang zh-CN 解析阴影色:rgb(R G B / A) 现代记法或 #hex。 @lang en Parses a shadow colour: modern rgb(R G B / A) notation or #hex. */
108
+ function parseShadowColor(text) {
109
+ const hex = /#[0-9a-fA-F]{6}/.exec(text);
110
+ if (hex)
111
+ return colorValue(hex[0]);
112
+ const rgb = /rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:\s*[/,]\s*([\d.]+))?\s*\)/.exec(text);
113
+ if (rgb) {
114
+ const r = Number(rgb[1]) / 255, g = Number(rgb[2]) / 255, b = Number(rgb[3]) / 255, a = rgb[4] !== undefined ? Number(rgb[4]) : 1;
115
+ return { colorSpace: 'srgb', components: [Number(r.toFixed(3)), Number(g.toFixed(3)), Number(b.toFixed(3))], alpha: a, hex: rgbToHex([r, g, b]) };
116
+ }
117
+ return null;
118
+ }
119
+ /** @lang zh-CN CSS 字体栈 → fontFamily 数组(去引号、去空白)。 @lang en CSS font stack → fontFamily array (quotes/whitespace stripped). */
120
+ function fontFamilyValue(stack) { return stack.split(',').map(s => s.trim().replace(/^["']|["']$/g, '')).filter(Boolean); }
121
+ /**
122
+ * @lang zh-CN 导出 DTCG 2025.10 文本(`.tokens.json`)。根级组:color(含语义)、radius、shadow、
123
+ * typography、spacing、gradient;`$extensions["com.hia-theme-builder"]` 记录生成器与主题名。
124
+ * 可选组按 ADR-012/006 语义缺省不输出。
125
+ * @lang en Emits the DTCG 2025.10 text (`.tokens.json`). Root groups: colour (incl. semantics), radius, shadow,
126
+ * typography, spacing, gradient; `$extensions["com.hia-theme-builder"]` records generator and theme name.
127
+ * Optional groups are omitted when absent.
128
+ */
129
+ export function exportDtcgTokens(theme) {
130
+ const custom = collectCustomShades(theme);
131
+ const color = {
132
+ primary: roleGroup(theme.primary, custom.primary),
133
+ secondary: roleGroup(theme.secondary, custom.secondary)
134
+ };
135
+ if (theme.thirdColor)
136
+ color['third'] = roleGroup(theme.thirdColor, {});
137
+ theme.auxiliary.forEach((aux, i) => { color[`aux${i}`] = roleGroup(aux, {}); });
138
+ if (theme.semantic)
139
+ color['semantic'] = Object.fromEntries(Object.entries(theme.semantic).map(([k, role]) => [k, roleGroup(role, {})]));
140
+ const radius = Object.fromEntries(Object.entries(radiusSequence(theme.radius)).map(([k, v]) => [k, dimensionToken(v)]));
141
+ const shadows = shadowCss(theme.shadow, theme.primary.value);
142
+ const shadow = {};
143
+ for (const k of ['sm', 'md', 'lg']) {
144
+ const parsed = parseBoxShadow(shadows[k]);
145
+ if (parsed)
146
+ shadow[k] = { '$type': 'shadow', '$value': parsed };
147
+ }
148
+ const spacing = Object.fromEntries(spacingSequence(theme.spacing).map((v, i) => [String(i), dimensionToken(v)]));
149
+ const gradients = {};
150
+ for (const def of GRADIENT_DEFS) {
151
+ const config = theme.gradients[def.key];
152
+ if (!config || config.enabled === false)
153
+ continue;
154
+ gradients[def.key] = {
155
+ '$type': 'gradient',
156
+ '$value': gradientStopsValue(config, theme),
157
+ '$extensions': { 'com.hia-theme-builder': { direction: config.direction, bias: config.bias } },
158
+ '$description': def.label
159
+ };
160
+ }
161
+ const root = {
162
+ '$description': `HIA Theme Builder tokens — ${theme.name}`,
163
+ '$extensions': { 'com.hia-theme-builder': { generator: 'HIA Theme Builder', format: 'dtcg-2025.10', themeName: theme.name } },
164
+ color,
165
+ radius,
166
+ shadow,
167
+ typography: { fontFamily: Object.fromEntries(['body', 'heading', 'mono'].map(k => [k, { '$type': 'fontFamily', '$value': fontFamilyValue(theme.typography.fontFamily[k]) }])) },
168
+ spacing,
169
+ gradients
170
+ };
171
+ return JSON.stringify(root, null, 2) + '\n';
172
+ }
173
+ /** @lang zh-CN JSON Pointer(`#/a/b/0`)解析:仅本文件内引用,失败返回 null。 @lang en JSON Pointer (`#/a/b/0`) resolution: in-file references only; null on failure. */
174
+ function resolveRef(root, ref) {
175
+ if (typeof ref !== 'string' || !ref.startsWith('#/'))
176
+ return null;
177
+ let node = root;
178
+ for (const seg of ref.slice(2).split('/')) {
179
+ if (node === null || typeof node !== 'object')
180
+ return null;
181
+ node = node[seg.replace(/~1/g, '/').replace(/~0/g, '~')];
182
+ }
183
+ return node;
184
+ }
185
+ /** @lang zh-CN 色值解析(三形态):返回 HEX 或 null(不可解析,由调用方记警告/错误)。 @lang en Colour resolution (three shapes): returns HEX or null (the caller warns/errors). */
186
+ function resolveColorValue(value, ctx, path, depth = 0) {
187
+ // 统一解包:token 包装($value)与组内引用($ref,限两层防循环)都在入口处理——
188
+ // 调用方(含 $ref 目标是完整 token 的情况)无需各自关心包装层。
189
+ // <lang en>Uniform unwrapping at the top: token wrappers ($value) and in-file references ($ref, depth-capped
190
+ // against cycles) are handled here, so callers — including cases where a $ref targets a full token — never
191
+ // worry about wrapper layers.</lang>
192
+ if (value && typeof value === 'object') {
193
+ const w = value;
194
+ if ('$value' in w && depth < 4)
195
+ return resolveColorValue(w['$value'], ctx, path, depth + 1);
196
+ if ('$ref' in w && depth < 2) {
197
+ const target = resolveRef(ctx.root, w['$ref']);
198
+ if (target === null || target === value)
199
+ return null;
200
+ return resolveColorValue(target, ctx, path, depth + 1);
201
+ }
202
+ }
203
+ if (value && typeof value === 'object') {
204
+ const v = value;
205
+ // 形态一:2025.10 对象——hex 兜底优先(无损),否则 srgb components(alpha 相乘)。
206
+ // <lang en>Shape 1: the 2025.10 object — prefer the hex fallback (lossless), else srgb components
207
+ // (alpha multiplied in).</lang>
208
+ if (typeof v.hex === 'string' && validHex(v.hex))
209
+ return normalizeHex(v.hex);
210
+ if (v.colorSpace === 'srgb' && Array.isArray(v.components) && v.components.length >= 3) {
211
+ const comps = v.components.map(c => typeof c === 'number' ? clamp(c, 0, 1) : 0);
212
+ const alpha = typeof v.alpha === 'number' ? clamp(v.alpha, 0, 1) : 1;
213
+ return rgbToHex([comps[0] * alpha, comps[1] * alpha, comps[2] * alpha]);
214
+ }
215
+ ctx.warnings.push({ code: 'W_DTCG_SKIPPED', path, message: `色彩空间 ${String(v.colorSpace)} 无 hex 兜底,跳过。`, messageEn: `Colour space ${String(v.colorSpace)} without a hex fallback — skipped.` });
216
+ return null;
217
+ }
218
+ // 形态二:颜色字符串——hex(Tokens Studio 事实标准)或 rgb()/rgba() CSS 记法。
219
+ // <lang en>Shape 2: colour strings — hex (Tokens Studio's de-facto standard) or rgb()/rgba() CSS notation.</lang>
220
+ if (typeof value === 'string') {
221
+ if (validHex(value))
222
+ return normalizeHex(value);
223
+ const css = parseShadowColor(value);
224
+ if (css)
225
+ return css['hex'];
226
+ }
227
+ return null;
228
+ }
229
+ /**
230
+ * @lang zh-CN 递归收集一个组内全部颜色 token。判定顺序(DTCG 生态形态差异大):
231
+ * ①带 `$value` 的标准 token;②`$ref`-only token;③值对象(含 hex/colorSpace 键——2025.10 形态);
232
+ * ④字符串叶子(Tokens Studio 的 hex 简写);⑤其余下探为子组。
233
+ * 非 color 类型逐条警告(不静默丢弃)。
234
+ * @lang en Recursively collects colour tokens in a group. Decision order (ecosystem shapes vary): (1) standard
235
+ * `$value` tokens; (2) `$ref`-only tokens; (3) value objects (hex/colorSpace keys — the 2025.10 shape);
236
+ * (4) string leaves (Tokens Studio hex shorthand); (5) otherwise descend as a sub-group. Non-colour types
237
+ * warn individually — never silently dropped.
238
+ */
239
+ function collectColors(group, ctx, base, out) {
240
+ if (group === null || typeof group !== 'object')
241
+ return;
242
+ for (const [key, value] of Object.entries(group)) {
243
+ if (key.startsWith('$'))
244
+ continue;
245
+ const path = `${base}.${key}`;
246
+ const record = value;
247
+ const type = record && typeof record === 'object' ? record['$type'] : undefined;
248
+ const hasValue = !!(record && typeof record === 'object' && '$value' in record);
249
+ const isRef = !!(record && typeof record === 'object' && '$ref' in record);
250
+ const isValueLike = !!(record && typeof record === 'object' && ('hex' in record || 'colorSpace' in record));
251
+ if (hasValue || isRef || isValueLike) {
252
+ // token 形态(标准/$ref/值对象)——统一走色值解析;类型白名单先校验。
253
+ // <lang en>Token shapes (standard/$ref/value-object) all go through colour resolution; the type
254
+ // whitelist is checked first.</lang>
255
+ if (typeof type === 'string' && type !== 'color') {
256
+ ctx.warnings.push({ code: 'W_DTCG_SKIPPED', path, message: `类型 ${type} 超出导入白名单,跳过。`, messageEn: `Type ${type} is outside the import whitelist — skipped.` });
257
+ continue;
258
+ }
259
+ const hex = resolveColorValue(record, ctx, path);
260
+ if (hex)
261
+ out[key] = hex;
262
+ else
263
+ ctx.errors.push({ code: 'E_DTCG_COLOR', path, message: '颜色值不可解析。', messageEn: 'Colour value is unresolvable.' });
264
+ continue;
265
+ }
266
+ if (typeof value === 'string') {
267
+ // 字符串叶子:Tokens Studio 的 hex 简写;非色字符串记 E_DTCG_TOKEN。
268
+ // <lang en>String leaves: Tokens Studio hex shorthand; non-colour strings report E_DTCG_TOKEN.</lang>
269
+ const hex = resolveColorValue(value, ctx, path);
270
+ if (hex)
271
+ out[key] = hex;
272
+ else
273
+ ctx.errors.push({ code: 'E_DTCG_TOKEN', path, message: '叶子值不是可识别的颜色。', messageEn: 'Leaf value is not a recognisable colour.' });
274
+ continue;
275
+ }
276
+ if (record && typeof record === 'object' && Object.keys(record).some(k => !k.startsWith('$'))) {
277
+ if (typeof type === 'string') {
278
+ ctx.warnings.push({ code: 'W_DTCG_SKIPPED', path, message: `类型 ${type} 超出导入白名单,跳过。`, messageEn: `Type ${type} is outside the import whitelist — skipped.` });
279
+ continue;
280
+ }
281
+ collectColors(value, ctx, path, out);
282
+ continue;
283
+ }
284
+ ctx.errors.push({ code: 'E_DTCG_TOKEN', path, message: 'token 缺少 $value。', messageEn: 'Token lacks $value.' });
285
+ }
286
+ }
287
+ /** @lang zh-CN 组内取"base 优先、500 兜底"的基色。 @lang en Picks the group base colour: "base" first, "500" fallback. */
288
+ function pickBase(colors) { return colors['base'] ?? colors['500']; }
289
+ /** @lang zh-CN 组内按顺序找第一个可解析的 dimension(px)。 @lang en Finds the first parseable dimension (px) in a group by key order. */
290
+ function walkDimension(group, keys) {
291
+ if (!group)
292
+ return undefined;
293
+ for (const key of keys) {
294
+ const token = group[key];
295
+ if (token && typeof token === 'object') {
296
+ const value = token['$value'];
297
+ if (value && typeof value === 'object') {
298
+ const v = value;
299
+ if (v.unit === 'px' && typeof v.value === 'number')
300
+ return v.value;
301
+ }
302
+ if (typeof value === 'number')
303
+ return value;
304
+ }
305
+ }
306
+ return undefined;
307
+ }
308
+ /** @lang zh-CN 读取根级 $extensions["com.hia-theme-builder"] 的字段。 @lang en Reads a field from the root $extensions["com.hia-theme-builder"]. */
309
+ function ext(obj, key) {
310
+ const e = obj['$extensions'];
311
+ const h = e?.['com.hia-theme-builder'];
312
+ const v = h?.[key];
313
+ return typeof v === 'string' ? v : undefined;
314
+ }
315
+ /**
316
+ * @lang zh-CN 导入 DTCG 文件(白名单子集,ADR-013):识别 `color.primary/secondary/semantic.<status>` 与
317
+ * `radius`(md/base 为圆角基准)。成功返回可编辑草稿(**semanticDerived 全 false**——导入值视为用户值,
318
+ * 不随主色刷新,ADR-012 决策 3 的导入侧对称);跳过的组逐条 `W_DTCG_SKIPPED`。
319
+ * 语义组以导入基色重建完整色阶与 on 色(与角色色同一管线,保证导出物完整)。
320
+ * @lang en Imports a DTCG file (whitelist subset, ADR-013): recognises `color.primary/secondary/semantic.<status>`
321
+ * and `radius` (md/base becomes the base radius). Returns an editable draft with **semanticDerived all
322
+ * false** — imported values are user-managed (the import-side mirror of ADR-012 decision 3); skipped groups
323
+ * warn one by one. Semantic groups rebuild full scales and `on` from the imported base colours (same pipeline
324
+ * as role colours, so exports stay complete).
325
+ */
326
+ export function parseDtcgTokens(raw) {
327
+ const ctx = { errors: [], warnings: [], root: raw };
328
+ let root = raw;
329
+ if (typeof raw === 'string') {
330
+ try {
331
+ root = JSON.parse(raw);
332
+ }
333
+ catch (e) {
334
+ return { ok: false, errors: [{ code: 'E_JSON', path: '$', message: `JSON 解析失败:${e instanceof Error ? e.message : String(e)}`, messageEn: `JSON parse failed: ${e instanceof Error ? e.message : String(e)}` }], warnings: [] };
335
+ }
336
+ }
337
+ if (root === null || typeof root !== 'object' || Array.isArray(root)) {
338
+ return { ok: false, errors: [{ code: 'E_DTCG_ROOT', path: '$', message: 'DTCG 顶层必须是 JSON 对象。', messageEn: 'The DTCG top level must be a JSON object.' }], warnings: [] };
339
+ }
340
+ const obj = root;
341
+ // 定位颜色组:root.color 或 root 下任一层包装的 color 组(Tokens Studio 主题包装常见)。
342
+ // <lang en>Locate the colour group: root.color, or a wrapped "color" group (common Tokens Studio shape).</lang>
343
+ let colorGroup = obj['color'];
344
+ if (!colorGroup || typeof colorGroup !== 'object') {
345
+ for (const value of Object.values(obj)) {
346
+ if (value && typeof value === 'object' && value['color']) {
347
+ colorGroup = value['color'];
348
+ break;
349
+ }
350
+ }
351
+ }
352
+ let primaryHex, secondaryHex;
353
+ const sem = {};
354
+ if (colorGroup && typeof colorGroup === 'object') {
355
+ const cg = colorGroup;
356
+ for (const role of ['primary', 'secondary']) {
357
+ const g = cg[role];
358
+ if (!g || typeof g !== 'object')
359
+ continue;
360
+ const colors = {};
361
+ collectColors(g, ctx, `color.${role}`, colors);
362
+ const hex = pickBase(colors);
363
+ if (role === 'primary')
364
+ primaryHex = hex;
365
+ else
366
+ secondaryHex = hex;
367
+ }
368
+ const semGroup = cg['semantic'];
369
+ if (semGroup && typeof semGroup === 'object') {
370
+ for (const key of ['success', 'info', 'warning', 'danger']) {
371
+ const g = semGroup[key];
372
+ if (!g || typeof g !== 'object')
373
+ continue;
374
+ const colors = {};
375
+ collectColors(g, ctx, `color.semantic.${key}`, colors);
376
+ const hex = pickBase(colors);
377
+ if (!hex)
378
+ continue;
379
+ // 以导入基色重建完整色阶与 on 色(导入组可能只有 base/500——重建保证导出物完整)。
380
+ // <lang en>Rebuild the full scale and on from the imported base (groups may only carry base/500) so
381
+ // exports stay complete.</lang>
382
+ sem[key] = { name: nameColor(hex).zh, value: hex, scale: tonalScale(hex), on: bestOnColor(hex).hex };
383
+ }
384
+ }
385
+ }
386
+ else {
387
+ ctx.warnings.push({ code: 'W_DTCG_SKIPPED', path: 'color', message: '未找到 color 组。', messageEn: 'No colour group found.' });
388
+ }
389
+ // 圆角:radius.md(base 兜底)为圆角基准(dimension px)。
390
+ // <lang en>Radius: radius.md (base fallback) becomes the base radius (dimension px).</lang>
391
+ const radiusBase = walkDimension(obj['radius'], ['md', 'base']);
392
+ // 其余根级组逐条警告(不静默丢弃)。
393
+ // <lang en>Warn per remaining root group — never silently dropped.</lang>
394
+ for (const [key, value] of Object.entries(obj)) {
395
+ if (key.startsWith('$') || key === 'color' || key === 'radius')
396
+ continue;
397
+ const type = value && typeof value === 'object' ? value['$type'] : undefined;
398
+ ctx.warnings.push({ code: 'W_DTCG_SKIPPED', path: key, message: `组 "${key}"(${typeof type === 'string' ? type : 'group'})超出导入白名单,跳过。`, messageEn: `Group "${key}" (${typeof type === 'string' ? type : 'group'}) is outside the import whitelist — skipped.` });
399
+ }
400
+ if (!primaryHex || !secondaryHex) {
401
+ ctx.errors.push({ code: 'E_DTCG_COLOR', path: 'color.primary/secondary', message: '缺少可识别的主色或副色。', messageEn: 'No recognisable primary or secondary colour.' });
402
+ }
403
+ if (ctx.errors.length || !primaryHex || !secondaryHex)
404
+ return { ok: false, errors: ctx.errors, warnings: ctx.warnings };
405
+ const semantic = Object.keys(sem).length ? sem : undefined;
406
+ const radius = radiusBase !== undefined ? { base: radiusBase } : undefined;
407
+ const draft = {
408
+ name: ext(obj, 'themeName') || 'DTCG 导入',
409
+ category: 'custom',
410
+ industry: '',
411
+ primary: primaryHex,
412
+ secondary: secondaryHex,
413
+ primaryName: nameColor(primaryHex).zh,
414
+ secondaryName: nameColor(secondaryHex).zh,
415
+ note: '由 DTCG .tokens.json 导入。',
416
+ semantic,
417
+ ...(radius ? { radius } : {}),
418
+ gradients: cloneGradientSettings(undefined),
419
+ semanticDerived: semantic ? Object.fromEntries(Object.keys(semantic).map(k => [k, false])) : undefined
420
+ };
421
+ return { ok: true, draft, errors: ctx.errors, warnings: ctx.warnings };
422
+ }
423
+ /** @lang zh-CN DTCG 导出目标(注册在导出注册表;ZIP 内单一 `.tokens.json`,W3C 2025.10 形状)。 @lang en The DTCG export target (registered in the export registry; a single .tokens.json in W3C 2025.10 shape inside the ZIP). */
424
+ export const dtcgExportTarget = {
425
+ id: 'dtcg',
426
+ name: 'DTCG .tokens.json(ZIP)',
427
+ nameEn: 'DTCG .tokens.json (ZIP)',
428
+ notes: '导出 W3C Design Tokens 2025.10 格式(color/radius/shadow/typography/spacing/gradient),可直接导入 Tokens Studio、Style Dictionary、Penpot 等生态工具。',
429
+ notesEn: 'Emits W3C Design Tokens 2025.10 (colour/radius/shadow/typography/spacing/gradient) consumable by Tokens Studio, Style Dictionary, Penpot and friends.',
430
+ archiveName: theme => `hia-dtcg-${slugifyThemeName(theme.name)}.zip`,
431
+ files: theme => [{ path: `${slugifyThemeName(theme.name)}.tokens.json`, content: exportDtcgTokens(theme) }]
432
+ };
433
+ //# sourceMappingURL=dtcg.js.map
@@ -36,7 +36,9 @@ import './hia-tokens.css';
36
36
  \`\`\`vue
37
37
  <style scoped>
38
38
  .hero {
39
- background: var(--hia-gradient-carousel); /* 渐变令牌 / gradient token */
39
+ /* 降级链(W-tb-P37):color 先行垫底,image 失败时仍有纯色 / Degradation chain: colour first, image second */
40
+ background-color: var(--hia-primary-500);
41
+ background-image: var(--hia-gradient-carousel);
40
42
  color: var(--hia-primary-700);
41
43
  padding: var(--hia-space-3);
42
44
  }
@@ -66,7 +68,8 @@ export function Card() {
66
68
  \`\`\`html
67
69
  <link rel="stylesheet" href="./hia-tokens.css">
68
70
  <style>
69
- .banner { background: var(--hia-gradient-banner); color: var(--hia-secondary-900); }
71
+ /* 降级链:先 color 后 image / Degradation chain: colour first, image second */
72
+ .banner { background-color: var(--hia-secondary-400); background-image: var(--hia-gradient-banner); color: var(--hia-secondary-900); }
70
73
  </style>
71
74
  \`\`\`
72
75
 
@@ -75,6 +78,7 @@ export function Card() {
75
78
  - 变量名规则 / Naming: \`--hia-primary-<shade>\`(shade 为 50–900 标准档或渐变引用的自定义档);
76
79
  - 明暗适配:在 \`html.dark\` 等作用域内覆写同批变量即可,无需改组件 / override the same vars under a scope like \`html.dark\`;
77
80
  - 主题再生成时请整体替换本文件,避免手工修改丢失 / regenerate the whole file from HIA Theme Builder rather than hand-editing.
81
+ - **降级链**(W-tb-P37):渐变/图片背景一律"先 \`background-color\` 纯色垫底、后 \`background-image\`",渐变变量自身也携带起始色垫底层;任何一层失效都不露底色 / **Degradation chain**: gradient/image backgrounds pair a solid \`background-color\` with \`background-image\`; gradient vars also carry a start-colour underlay, so no layer failure exposes the bare container.
78
82
  `;
79
83
  // 固定两文件顺序:tokens.css 在前(主产物)。
80
84
  // <lang zh-CN>路径为 ZIP 内相对根路径。</lang>
@@ -1,13 +1,17 @@
1
1
  import { wordpressChildTarget } from './wordpress.js';
2
2
  import { tailwindConfigTarget } from './tailwind.js';
3
3
  import { injectTemplateTarget } from './inject-template.js';
4
+ import { tailwindV4Target } from './tailwind4.js';
5
+ import { dtcgExportTarget } from './dtcg.js';
4
6
  // 内置导出目标清单(顺序即 UI 展示顺序:WP → Tailwind → 通用注入)。
5
7
  // <lang zh-CN>与 `W-tb-P9` 计划 §3.2-3.4 的首批栈对应;深冻结保证清单与条目均不可变。</lang>
6
8
  // <lang en>Matches the first batch stacks in the `W-tb-P9` plan §3.2-3.4; deep-frozen so neither list nor entries mutate.</lang>
7
9
  export const EXPORT_TARGETS = [
8
10
  wordpressChildTarget,
9
11
  tailwindConfigTarget,
10
- injectTemplateTarget
12
+ tailwindV4Target,
13
+ injectTemplateTarget,
14
+ dtcgExportTarget
11
15
  ].map(t => Object.freeze({ ...t }));
12
16
  // 按 id 检索导出目标。
13
17
  // <lang zh-CN>未命中返回 undefined,由 UI 层决定报错方式;id 精确匹配(大小写敏感)。</lang>
@@ -1,5 +1,6 @@
1
1
  import { collectCustomShades } from '../gradient/render.js';
2
2
  import { slugifyThemeName, fullTokenCss, commentSafe } from './shared.js';
3
+ import { radiusSequence, shadowCss } from '../token/radius.js';
3
4
  // 生成单色族的 Tailwind colors 子对象:DEFAULT=基色,标准 10 档 + 自定义色阶附加键。
4
5
  // <lang zh-CN>档位键加引号('50'…'900'/'650'),保证 JS 对象字面量合法且键序与 SHADE_KEYS 一致;
5
6
  // 自定义档与 CSS/JSON/WP 导出同源(collectCustomShades),四处产物一致。</lang>
@@ -43,8 +44,19 @@ ${[
43
44
  ` primary: ${familyColors(theme.primary.scale, custom.primary, theme.primary.value)}`,
44
45
  ` secondary: ${familyColors(theme.secondary.scale, custom.secondary, theme.secondary.value)}`,
45
46
  ...(theme.thirdColor ? [` third: ${familyColors(theme.thirdColor.scale, {}, theme.thirdColor.value)}`] : []),
46
- ...theme.auxiliary.map((aux, i) => ` aux${i}: ${familyColors(aux.scale, {}, aux.value)}`)
47
+ ...theme.auxiliary.map((aux, i) => ` aux${i}: ${familyColors(aux.scale, {}, aux.value)}`),
48
+ // 语义状态色(W-tb-P37/ADR-012):success/info/warning/danger 四组全档。
49
+ // <lang en>Semantic status colours (W-tb-P37/ADR-012): full scales for the four statuses.</lang>
50
+ ...(theme.semantic ? Object.entries(theme.semantic).map(([k, role]) => ` ${k}: ${familyColors(role.scale, {}, role.value)}`) : [])
47
51
  ].join(',\n')}
52
+ },
53
+ // 圆角/阴影(W-tb-P37):五档半径 px + 三档阴影字符串(可随主色染色)。
54
+ // <lang en>Radius/shadow (W-tb-P37): five radius steps (px) + three shadow strings (primary-tintable).</lang>
55
+ borderRadius: {
56
+ ${Object.entries(radiusSequence(theme.radius)).map(([k, v]) => ` '${k}': '${v}px'`).join(',\n')}
57
+ },
58
+ boxShadow: {
59
+ ${Object.entries(shadowCss(theme.shadow, theme.primary.value)).map(([k, v]) => ` '${k}': ${JSON.stringify(v)}`).join(',\n')}
48
60
  },
49
61
  fontFamily: {
50
62
  body: ${JSON.stringify(theme.typography.fontFamily.body)},
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @lang zh-CN Tailwind v4 适配器(`W-tb-P37`):生成 **CSS-first** 的 `@theme` 块(app.css),
3
+ * 把主题令牌直接定义为 Tailwind v4 主题变量——`--color-*` 生成 utilities(`bg-primary-500` 等),
4
+ * `--radius-*`/`--shadow-*` 接入 `rounded-*`/`shadow-*`。这是 v4 的一等形态;v3 `config.js`
5
+ * 适配器保留为兼容形态(ADR-005 清单追加条目)。
6
+ * @lang en Tailwind v4 adapter (`W-tb-P37`): emits a **CSS-first** `@theme` block (app.css) defining theme
7
+ * tokens as Tailwind v4 theme variables — `--color-*` generate utilities (`bg-primary-500`…), while
8
+ * `--radius-*`/`--shadow-*` power `rounded-*`/`shadow-*`. This is the v4 first-class form; the v3
9
+ * `config.js` adapter stays as the compatibility form (added to the ADR-005 registry).
10
+ */
11
+ import type { ExportTarget } from './types.js';
12
+ /** @lang zh-CN Tailwind v4 导出目标(注册表条目)。 @lang en Tailwind v4 export target (registry entry). */
13
+ export declare const tailwindV4Target: ExportTarget;
14
+ //# sourceMappingURL=tailwind4.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { collectCustomShades } from '../gradient/render.js';
2
+ import { radiusSequence, shadowCss } from '../token/radius.js';
3
+ import { slugifyThemeName, commentSafe } from './shared.js';
4
+ // 单色族 @theme 行:DEFAULT 之外的 10 档 + 自定义档(与 v3/CSS/JSON 同源)。
5
+ // <lang en>One family's @theme lines: the 10 steps plus custom shades (same source as v3/CSS/JSON).</lang>
6
+ function themeColorLines(prefix, scale, custom, base) {
7
+ return [
8
+ ` --color-${prefix}: ${base};`,
9
+ ...Object.entries(scale).map(([k, v]) => ` --color-${prefix}-${k}: ${v};`),
10
+ ...Object.entries(custom).map(([k, v]) => ` --color-${prefix}-${k}: ${v};`)
11
+ ];
12
+ }
13
+ /**
14
+ * @lang zh-CN v4 适配器主体:产出单个 app.css(@theme 块 + 消费说明注释)。
15
+ * 语义状态色、圆角、阴影随主题携带时输出;渐变以 CSS 变量 `--gradient-*` 形态放在 :root
16
+ * (@theme 只收静态值,渐变引用色阶时保持 var() 动态性)。
17
+ * @lang en v4 adapter body: a single app.css (@theme block + usage comments). Semantic colours, radius and
18
+ * shadow emit when carried; gradients stay in :root as `--gradient-*` vars because @theme takes static
19
+ * values and gradients must keep referencing live scale vars.
20
+ */
21
+ function tailwindV4Files(theme) {
22
+ const custom = collectCustomShades(theme);
23
+ const radius = radiusSequence(theme.radius);
24
+ const shadows = shadowCss(theme.shadow, theme.primary.value);
25
+ const colorLines = [
26
+ ...themeColorLines('primary', theme.primary.scale, custom.primary, theme.primary.value),
27
+ ...themeColorLines('secondary', theme.secondary.scale, custom.secondary, theme.secondary.value),
28
+ ...(theme.thirdColor ? themeColorLines('third', theme.thirdColor.scale, {}, theme.thirdColor.value) : []),
29
+ ...theme.auxiliary.flatMap((aux, i) => themeColorLines(`aux${i}`, aux.scale, {}, aux.value)),
30
+ // 语义状态色(ADR-012):仅主题携带时输出。
31
+ // <lang en>Semantic statuses (ADR-012): emitted only when the theme carries them.</lang>
32
+ ...(theme.semantic ? Object.keys(theme.semantic).flatMap(k => themeColorLines(k, theme.semantic[k].scale, {}, theme.semantic[k].value)) : [])
33
+ ];
34
+ const radiusLines = Object.entries(radius).map(([k, v]) => ` --radius-${k}: ${v}px;`);
35
+ const shadowLines = Object.entries(shadows).map(([k, v]) => ` --shadow-${k}: ${JSON.stringify(v).replace(/"/g, '')};`);
36
+ const gradientLines = Object.entries(theme.gradients)
37
+ .filter(([, c]) => c)
38
+ .map(([k]) => ` --gradient-${k}: var(--hia-gradient-${k});`);
39
+ const css = `/* HIA Theme Builder — Tailwind v4 @theme tokens — ${commentSafe(theme.name)}
40
+ * Generated by HIA Theme Builder (W-tb-P37 / ADR-005). Import in your main CSS:
41
+ * @import "app.css";
42
+ * Utilities: bg-primary-500 · text-success-700 · rounded-md · shadow-lg · (gradients via var(--gradient-*))
43
+ */
44
+ @theme {
45
+ ${colorLines.join('\n')}
46
+ ${radiusLines.join('\n')}
47
+ ${shadowLines.join('\n')}
48
+ }
49
+
50
+ :root {
51
+ ${gradientLines.join('\n')}
52
+ }
53
+ `;
54
+ return [{ path: 'app.css', content: css }];
55
+ }
56
+ /** @lang zh-CN Tailwind v4 导出目标(注册表条目)。 @lang en Tailwind v4 export target (registry entry). */
57
+ export const tailwindV4Target = {
58
+ id: 'tailwind-v4',
59
+ name: 'Tailwind v4 @theme(ZIP)',
60
+ nameEn: 'Tailwind v4 @theme (ZIP)',
61
+ notes: '生成 CSS-first 的 app.css:@theme 定义 --color-*/--radius-*/--shadow-*(v4 一等形态);渐变经 var() 动态引用。',
62
+ notesEn: 'Emits a CSS-first app.css: @theme defines --color-*/--radius-*/--shadow-* (v4 first-class); gradients referenced dynamically via var().',
63
+ archiveName: theme => `hia-tailwind-v4-${slugifyThemeName(theme.name)}.zip`,
64
+ files: tailwindV4Files
65
+ };
66
+ //# sourceMappingURL=tailwind4.js.map
@@ -96,7 +96,7 @@ function wordpressChildFiles(theme, options) {
96
96
  if (!config || config.enabled === false)
97
97
  return [];
98
98
  const roleSlug = def.key.replace(/([A-Z])/g, '-$1').toLowerCase();
99
- return [{ name: def.label, slug: `hia-gradient-${roleSlug}`, gradient: gradientCss(config, 'literal', theme) }];
99
+ return [{ name: def.label, slug: `hia-gradient-${roleSlug}`, gradient: gradientCss(config, 'literal', theme, false) }];
100
100
  });
101
101
  // theme.json:WP 块主题全站编辑契约($schema 便于编辑器补全,version 2 为兼容口径)。
102
102
  // <lang zh-CN>defaultPalette/defaultGradients 关闭核心默认,突出 HIA 面板;custom 透传排版/间距令牌。</lang>
@@ -1,8 +1,10 @@
1
- import type { CssVariableMap, GradientBias, GradientConfig, GradientSettings, Theme } from '../types.js';
1
+ import type { CssVariableMap, GradientBias, GradientConfig, GradientFamily, GradientSettings, ShadeValue, Theme } from '../types.js';
2
2
  export type GradientRenderMode = 'runtime' | 'export' | 'literal';
3
3
  export declare function gradientStops(a: string, b: string, bias: GradientBias): string;
4
4
  export declare function swapGradientBias(bias: GradientBias): GradientBias;
5
- export declare function gradientCss(config: GradientConfig, mode?: GradientRenderMode, theme?: Theme): string;
5
+ /** @lang zh-CN 解析任意色阶引用为实际色值(`W-tb-P38` 导出为 DTCG 渐变 stops 所需,改公开)。 @lang en Resolves an arbitrary shade reference to its colour (exported for `W-tb-P38` DTCG gradient stops). */
6
+ export declare function resolveScaleColor(theme: Theme, family: GradientFamily, shade: ShadeValue): string;
7
+ export declare function gradientCss(config: GradientConfig, mode?: GradientRenderMode, theme?: Theme, underlay?: boolean): string;
6
8
  export declare function gradientDominantColor(config: GradientConfig, theme: Theme): string;
7
9
  export declare function collectCustomShades(theme: Theme): {
8
10
  primary: Record<string, string>;