@hia/theme-core 0.5.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,70 @@
1
+ /**
2
+ * @lang zh-CN DTCG 令牌互操作(`W-tb-P38`,ADR-013):W3C Design Tokens Format **2025.10 稳定版**
3
+ * 的导出与白名单导入。依据(一手资料):design-tokens/community-group `schemas/src/2025.10/`
4
+ * 的 color/gradient/shadow/dimension/token/group schema——值形状逐条对照,不凭记忆。
5
+ *
6
+ * **导出映射**:`color.primary/secondary/third/aux<N>/semantic.<status>` 各组含 base/10 阶/on;
7
+ * `radius.*` 用 dimension(px);`shadow.*` 用 shadow 数组(双层阴影逐层展开);
8
+ * `typography.fontFamily` 用 fontFamily(字符串数组);`spacing.<i>` 用 dimension;
9
+ * 渐变用 `$type:"gradient"`(stops 数组,position 0–1),方向不在 DTCG 类型内 → 写入
10
+ * `$extensions["com.hia-theme-builder"].direction`。根级 `$extensions` 携带生成器信息。
11
+ *
12
+ * **导入(白名单子集)**:识别 `color.primary/secondary/semantic.<status>` 与 `radius`;
13
+ * 色值接受三形态(2025.10 对象 / 纯 hex 字符串(Tokens Studio 事实标准)/ 组内 `$ref`);
14
+ * 其余组跳过并出 `W_DTCG_SKIPPED` 警告(不静默丢弃)。
15
+ *
16
+ * @lang en DTCG token interop (`W-tb-P38`, ADR-013): W3C Design Tokens Format **2025.10 stable** export and
17
+ * whitelist import. Source of truth: the community-group `schemas/src/2025.10/` schemas — every value shape
18
+ * is checked against them, not recalled from memory.
19
+ *
20
+ * **Export mapping**: `color.primary/secondary/third/aux<N>/semantic.<status>` groups carry base/10 steps/on;
21
+ * `radius.*` as dimension(px); `shadow.*` as shadow arrays (both layers of our two-layer shadows);
22
+ * `typography.fontFamily` as fontFamily (string arrays); `spacing.<i>` as dimension; gradients as
23
+ * `$type:"gradient"` (stop array, position 0–1) with direction in `$extensions` since the DTCG gradient type
24
+ * has no axis concept. Root `$extensions` carries generator info.
25
+ *
26
+ * **Import (whitelist)**: recognises `color.primary/secondary/semantic.<status>` and `radius`; colour values
27
+ * accept three shapes (2025.10 objects / plain hex strings (Tokens Studio's de-facto form) / in-file `$ref`);
28
+ * other groups are skipped with `W_DTCG_SKIPPED` warnings — never silently dropped.
29
+ */
30
+ import type { Theme, ThemeDraft } from '../types.js';
31
+ import type { ExportTarget } from './types.js';
32
+ /**
33
+ * @lang zh-CN 导出 DTCG 2025.10 文本(`.tokens.json`)。根级组:color(含语义)、radius、shadow、
34
+ * typography、spacing、gradient;`$extensions["com.hia-theme-builder"]` 记录生成器与主题名。
35
+ * 可选组按 ADR-012/006 语义缺省不输出。
36
+ * @lang en Emits the DTCG 2025.10 text (`.tokens.json`). Root groups: colour (incl. semantics), radius, shadow,
37
+ * typography, spacing, gradient; `$extensions["com.hia-theme-builder"]` records generator and theme name.
38
+ * Optional groups are omitted when absent.
39
+ */
40
+ export declare function exportDtcgTokens(theme: Theme): string;
41
+ /** @lang zh-CN 导入错误/警告码(ADR-013)。 @lang en Import error/warning codes (ADR-013). */
42
+ export type DtcgIssueCode = 'E_DTCG_ROOT' | 'E_DTCG_TOKEN' | 'E_DTCG_COLOR' | 'E_JSON' | 'W_DTCG_SKIPPED';
43
+ export interface DtcgIssue {
44
+ code: DtcgIssueCode;
45
+ path: string;
46
+ message: string;
47
+ messageEn: string;
48
+ }
49
+ export interface DtcgParseResult {
50
+ ok: boolean;
51
+ /** @lang zh-CN 成功时的可编辑草稿(semanticDerived 全 false=用户值,不随主色刷新)。 @lang en An editable draft on success (semanticDerived all false — user-managed, not following the primary). */
52
+ draft?: ThemeDraft;
53
+ errors: DtcgIssue[];
54
+ warnings: DtcgIssue[];
55
+ }
56
+ /**
57
+ * @lang zh-CN 导入 DTCG 文件(白名单子集,ADR-013):识别 `color.primary/secondary/semantic.<status>` 与
58
+ * `radius`(md/base 为圆角基准)。成功返回可编辑草稿(**semanticDerived 全 false**——导入值视为用户值,
59
+ * 不随主色刷新,ADR-012 决策 3 的导入侧对称);跳过的组逐条 `W_DTCG_SKIPPED`。
60
+ * 语义组以导入基色重建完整色阶与 on 色(与角色色同一管线,保证导出物完整)。
61
+ * @lang en Imports a DTCG file (whitelist subset, ADR-013): recognises `color.primary/secondary/semantic.<status>`
62
+ * and `radius` (md/base becomes the base radius). Returns an editable draft with **semanticDerived all
63
+ * false** — imported values are user-managed (the import-side mirror of ADR-012 decision 3); skipped groups
64
+ * warn one by one. Semantic groups rebuild full scales and `on` from the imported base colours (same pipeline
65
+ * as role colours, so exports stay complete).
66
+ */
67
+ export declare function parseDtcgTokens(raw: unknown): DtcgParseResult;
68
+ /** @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). */
69
+ export declare const dtcgExportTarget: ExportTarget;
70
+ //# sourceMappingURL=dtcg.d.ts.map
@@ -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