@hia/theme-core 0.6.0 → 1.0.0-rc.1
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.
- package/dist/color/apca.d.ts +48 -0
- package/dist/color/apca.js +94 -0
- package/dist/color/contrast.d.ts +46 -0
- package/dist/color/contrast.js +113 -1
- package/dist/color/image-extract.d.ts +56 -0
- package/dist/color/image-extract.js +217 -0
- package/dist/color/semantic.d.ts +52 -0
- package/dist/color/semantic.js +68 -0
- package/dist/color/vision.d.ts +22 -0
- package/dist/color/vision.js +63 -0
- package/dist/export/dtcg.d.ts +70 -0
- package/dist/export/dtcg.js +433 -0
- package/dist/export/editor-themes.d.ts +62 -0
- package/dist/export/editor-themes.js +201 -0
- package/dist/export/inject-template.js +6 -2
- package/dist/export/registry.js +5 -1
- package/dist/export/tailwind.js +13 -1
- package/dist/export/tailwind4.d.ts +14 -0
- package/dist/export/tailwind4.js +66 -0
- package/dist/export/wordpress.js +1 -1
- package/dist/gradient/render.d.ts +4 -2
- package/dist/gradient/render.js +44 -5
- package/dist/index.d.ts +16 -1
- package/dist/index.js +29 -4
- package/dist/studio.js +3 -3
- package/dist/theme.js +12 -1
- package/dist/token/css.js +23 -3
- package/dist/token/json.js +6 -0
- package/dist/token/radius.d.ts +38 -0
- package/dist/token/radius.js +94 -0
- package/dist/types.d.ts +31 -0
- package/package.json +1 -1
|
@@ -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
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lang zh-CN 编辑器配色主题生成器(`W-tb-P42`,ADR-015):把 HIA 主题映射为
|
|
3
|
+
* TextMate(`.tmTheme` XML plist)/ VSCode(`.color-theme.json`)/ Vim(`.vim`)/ Emacs(`.el`)
|
|
4
|
+
* 四种格式。**scope→角色档位映射**是 HIA 的设计判断(登记于 ADR-015),逐 scope 独立取色——
|
|
5
|
+
* 导出产物是精确的(与预览的"着色示意"分离)。明暗两套由 appearance 参数派生。
|
|
6
|
+
*
|
|
7
|
+
* @lang en Editor colour theme generators (`W-tb-P42`, ADR-015): map an HIA theme to
|
|
8
|
+
* TextMate (`.tmTheme` XML plist) / VSCode (`.color-theme.json`) / Vim (`.vim`) / Emacs (`.el`).
|
|
9
|
+
* The scope→role mapping is an HIA design judgement (registered in ADR-015); each scope resolves
|
|
10
|
+
* independently, so exports are exact (the preview remains an approximation, by design).
|
|
11
|
+
*/
|
|
12
|
+
import type { Theme } from '../types.js';
|
|
13
|
+
/** @lang zh-CN 外观档位:light/dark 各派生一套编辑器主题。 @lang en Appearance: light/dark each derive one editor theme. */
|
|
14
|
+
export type EditorAppearance = 'light' | 'dark';
|
|
15
|
+
/**
|
|
16
|
+
* @lang zh-CN 生成 TextMate 主题(`.tmTheme`,XML plist 格式)。
|
|
17
|
+
* scope 按"父 scope"粒度输出(TextMate 匹配前缀,子 scope 继承)。
|
|
18
|
+
* @lang en TextMate theme (`.tmTheme`, XML plist). Scopes emit at parent granularity (TextMate matches by
|
|
19
|
+
* prefix, children inherit).
|
|
20
|
+
*/
|
|
21
|
+
export declare function textmateTheme(t: Theme, appearance?: EditorAppearance): string;
|
|
22
|
+
/**
|
|
23
|
+
* @lang zh-CN 生成 VSCode 主题(`.color-theme.json`):tokenColors(scope 数组)+ colors
|
|
24
|
+
* (workbench chrome:editorBackground/lineNumber/selection 等)。
|
|
25
|
+
* @lang en VSCode theme (`.color-theme.json`): tokenColors (scope array) + workbench colors
|
|
26
|
+
* (editorBackground, lineNumber, selection…).
|
|
27
|
+
*/
|
|
28
|
+
export declare function vscodeTheme(t: Theme, appearance?: EditorAppearance): string;
|
|
29
|
+
/**
|
|
30
|
+
* @lang zh-CN 生成 Vim 主题(`.vim` 脚本):highlight 组映射——
|
|
31
|
+
* Comment/String/Number/Keyword/Function/Type/Normal/Visual/LineNr。
|
|
32
|
+
* @lang en Vim theme (`.vim` script): highlight groups Comment/String/Number/Keyword/Function/Type/Normal/
|
|
33
|
+
* Visual/LineNr.
|
|
34
|
+
*/
|
|
35
|
+
export declare function vimTheme(t: Theme, appearance?: EditorAppearance): string;
|
|
36
|
+
/**
|
|
37
|
+
* @lang zh-CN 生成 Emacs 主题(`.el` face 定义):defface + deftheme,组与 Vim 对齐。
|
|
38
|
+
* @lang en Emacs theme (`.el` face definitions): deftheme + defface, groups aligned with Vim.
|
|
39
|
+
*/
|
|
40
|
+
export declare function emacsTheme(t: Theme, appearance?: EditorAppearance): string;
|
|
41
|
+
/**
|
|
42
|
+
* @lang zh-CN 生成器注册表:`builtin:` templateRef 名 → 生成函数与产物扩展名。
|
|
43
|
+
* TDON 文档经 `exportManifest.files[]` 以 `templateRef` 引用(与 `builtin:hia-tokens-css` 同构)。
|
|
44
|
+
* appearance 由调用方(导出链路)传入——TDON 文档可用同一路径声明两份(light/dark)。
|
|
45
|
+
* @lang en Generator registry: `builtin:` templateRef name → generator + file extension. TDON documents
|
|
46
|
+
* reference them from `exportManifest.files[]` (isomorphic with `builtin:hia-tokens-css`); appearance is
|
|
47
|
+
* passed by the export pipeline, so a document can declare both light/dark files.
|
|
48
|
+
*/
|
|
49
|
+
export declare const EDITOR_THEME_GENERATORS: {
|
|
50
|
+
ref: string;
|
|
51
|
+
ext: string;
|
|
52
|
+
label: string;
|
|
53
|
+
generate: (t: Theme, appearance: EditorAppearance) => string;
|
|
54
|
+
}[];
|
|
55
|
+
/** @lang zh-CN 按 ref 取生成器定义;未命中返回 undefined。 @lang en Looks up a generator by ref; undefined when missing. */
|
|
56
|
+
export declare function findEditorThemeGenerator(ref: string): {
|
|
57
|
+
ref: string;
|
|
58
|
+
ext: string;
|
|
59
|
+
label: string;
|
|
60
|
+
generate: (t: Theme, appearance: EditorAppearance) => string;
|
|
61
|
+
} | undefined;
|
|
62
|
+
//# sourceMappingURL=editor-themes.d.ts.map
|