@svadmin/core 0.73.0 → 0.74.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.
- package/package.json +1 -1
- package/src/color-scale.ts +60 -11
- package/src/index.ts +8 -2
- package/src/schema-form.ts +143 -2
- package/src/schema.ts +3 -2
- package/src/theme-dtcg.ts +279 -0
- package/src/types.ts +12 -0
package/package.json
CHANGED
package/src/color-scale.ts
CHANGED
|
@@ -148,6 +148,20 @@ function contrastRatio(a: string, b: string): number {
|
|
|
148
148
|
return (lighter + 0.05) / (darker + 0.05);
|
|
149
149
|
}
|
|
150
150
|
|
|
151
|
+
/** Convert an OKLCH triple to a clamped sRGB hex string. */
|
|
152
|
+
export function oklchToHex(l: number, c: number, h: number): string {
|
|
153
|
+
return toHex(oklchToRgb(l, c, h));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** Contrast helpers shared by the token audit. */
|
|
157
|
+
export function hexLuminance(hex: string): number {
|
|
158
|
+
return relativeLuminance(hex);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function hexContrastRatio(a: string, b: string): number {
|
|
162
|
+
return contrastRatio(a, b);
|
|
163
|
+
}
|
|
164
|
+
|
|
151
165
|
/** Pick the foreground with the higher contrast ratio (WCAG relative luminance). */
|
|
152
166
|
export function pickReadableForeground(backgroundHex: string): string {
|
|
153
167
|
return contrastRatio(backgroundHex, '#FFFFFF') >= contrastRatio(backgroundHex, '#111111')
|
|
@@ -175,12 +189,45 @@ export function generateColorScale(color: string): ColorScaleStep[] {
|
|
|
175
189
|
return steps;
|
|
176
190
|
}
|
|
177
191
|
|
|
178
|
-
|
|
192
|
+
/**
|
|
193
|
+
* Nudge lightness until the color reaches `minimum` contrast against a surface.
|
|
194
|
+
* Direction is chosen so the adjustment moves away from the surface, keeping the
|
|
195
|
+
* hue and chroma intact (only the lightness dimension changes).
|
|
196
|
+
*/
|
|
197
|
+
function contrastAdjusted(
|
|
198
|
+
lightness: number,
|
|
199
|
+
chroma: number,
|
|
200
|
+
hue: number,
|
|
201
|
+
surfaceHex: string,
|
|
202
|
+
minimum: number,
|
|
203
|
+
): { value: string; hex: string } {
|
|
204
|
+
const step = hexLuminance(surfaceHex) > 0.5 ? -0.008 : 0.008;
|
|
205
|
+
let current = clamp01(lightness);
|
|
206
|
+
let hex = toHex(oklchToRgb(current, chroma, hue));
|
|
207
|
+
// Rounding to `oklch(L C H)` loses precision, so aim above the threshold
|
|
208
|
+
// instead of landing on 2.99.
|
|
209
|
+
const target = minimum + 0.1;
|
|
210
|
+
for (let index = 0; index < 80 && contrastRatio(hex, surfaceHex) < target; index += 1) {
|
|
211
|
+
const next = clamp01(current + step);
|
|
212
|
+
if (next === current) break;
|
|
213
|
+
current = next;
|
|
214
|
+
hex = toHex(oklchToRgb(current, chroma, hue));
|
|
215
|
+
}
|
|
216
|
+
return { value: formatOklch(current, chroma, hue), hex };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function chartPalette(
|
|
220
|
+
scale: ColorScaleStep[],
|
|
221
|
+
hue: number,
|
|
222
|
+
chroma: number,
|
|
223
|
+
lightness: number,
|
|
224
|
+
surfaceHex: string,
|
|
225
|
+
): Record<string, string> {
|
|
179
226
|
const offsets = [0, 32, -32, 64, -64];
|
|
180
|
-
return Object.fromEntries(offsets.map((offset, index) =>
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
227
|
+
return Object.fromEntries(offsets.map((offset, index) => {
|
|
228
|
+
if (index === 0) return ['--chart-1', contrastAdjusted(lightness, chroma, hue, surfaceHex, 3).value];
|
|
229
|
+
return [`--chart-${index + 1}`, contrastAdjusted(lightness, chroma, hue + offset, surfaceHex, 3).value];
|
|
230
|
+
}));
|
|
184
231
|
}
|
|
185
232
|
|
|
186
233
|
/**
|
|
@@ -193,10 +240,12 @@ export function deriveColorPreset(input: { name: string; label?: string; color:
|
|
|
193
240
|
const color = input.color?.trim();
|
|
194
241
|
const source = hexToOklch(color);
|
|
195
242
|
const scale = generateColorScale(color);
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const lightForeground =
|
|
199
|
-
const darkForeground =
|
|
243
|
+
// One foreground per mode keeps `primary` usable both as a fill and as text on
|
|
244
|
+
// the mode surface: white on a light-mode primary, near-black on a dark one.
|
|
245
|
+
const lightForeground = '#FFFFFF';
|
|
246
|
+
const darkForeground = '#111111';
|
|
247
|
+
const lightPrimary = contrastAdjusted(source.l, source.c, source.h, '#FFFFFF', 4.5);
|
|
248
|
+
const darkPrimary = contrastAdjusted(Math.min(0.82, source.l + 0.12), source.c, source.h, '#111111', 4.5);
|
|
200
249
|
|
|
201
250
|
return {
|
|
202
251
|
name,
|
|
@@ -209,7 +258,7 @@ export function deriveColorPreset(input: { name: string; label?: string; color:
|
|
|
209
258
|
'--sidebar-primary': lightPrimary.value,
|
|
210
259
|
'--sidebar-primary-foreground': lightForeground,
|
|
211
260
|
'--sidebar-ring': lightPrimary.value,
|
|
212
|
-
...chartPalette(scale, source.h, source.c, source.l),
|
|
261
|
+
...chartPalette(scale, source.h, source.c, source.l, '#FFFFFF'),
|
|
213
262
|
},
|
|
214
263
|
dark: {
|
|
215
264
|
'--primary': darkPrimary.value,
|
|
@@ -218,7 +267,7 @@ export function deriveColorPreset(input: { name: string; label?: string; color:
|
|
|
218
267
|
'--sidebar-primary': darkPrimary.value,
|
|
219
268
|
'--sidebar-primary-foreground': darkForeground,
|
|
220
269
|
'--sidebar-ring': scale[4]?.value as string,
|
|
221
|
-
...chartPalette(scale, source.h, source.c * 1.05, Math.min(0.82, source.l + 0.12)),
|
|
270
|
+
...chartPalette(scale, source.h, source.c * 1.05, Math.min(0.82, source.l + 0.12), '#111111'),
|
|
222
271
|
},
|
|
223
272
|
};
|
|
224
273
|
}
|
package/src/index.ts
CHANGED
|
@@ -216,7 +216,7 @@ export type {
|
|
|
216
216
|
AdminTool, ToolResult,
|
|
217
217
|
} from './chatProvider.svelte';
|
|
218
218
|
export { getTheme, setTheme, toggleTheme, getResolvedTheme, getColorTheme, setColorTheme, getColorThemes, configureTheme, getThemeConfig, clearCssOverrides, builtinPresets, registerColorPreset, getColorPresets, registerColorTheme, exportColorThemes, importColorThemes, registerThemeOwner, updateThemeOwner, unregisterThemeOwner, resetTheme } from './theme.svelte';
|
|
219
|
-
export { deriveColorPreset, exportThemeTokens, generateColorScale, hexToOklch, parseThemeTokens, pickReadableForeground } from './color-scale';
|
|
219
|
+
export { deriveColorPreset, exportThemeTokens, generateColorScale, hexContrastRatio, hexLuminance, hexToOklch, oklchToHex, parseThemeTokens, pickReadableForeground } from './color-scale';
|
|
220
220
|
export type { ColorScaleStep, DerivedColorPreset, ThemeTokenDocument } from './color-scale';
|
|
221
221
|
export type { ThemeMode, ColorTheme, BuiltinColorTheme, ThemeStrategy, ThemeConfig, ColorPreset, ThemeOwnerOptions, ThemeOwnerToken } from './theme.svelte';
|
|
222
222
|
export { setUnsavedChanges, getUnsavedChanges, initUnsavedChangesNotifier, resetUnsavedChanges } from './unsaved-changes.svelte';
|
|
@@ -277,10 +277,16 @@ export { FILTER_COLLECTION_LIMIT, isNumericFilterField, isCollectionFilterOperat
|
|
|
277
277
|
export {
|
|
278
278
|
assertSchemaFormSchema, prepareSchemaFormValue, readSchemaFormPath,
|
|
279
279
|
matchesSchemaFormCondition, isSchemaFormNodeVisible, validateSchemaFormValue,
|
|
280
|
+
resolveDeclaredFieldLayout, resolveSchemaFormLayout,
|
|
280
281
|
} from './schema-form';
|
|
281
282
|
export type {
|
|
282
|
-
SchemaFormScalar, SchemaFormCondition,
|
|
283
|
+
SchemaFormScalar, SchemaFormCondition, SchemaFormLayout, SchemaFormLayoutPlan, SchemaFormSchema,
|
|
284
|
+
SchemaFormValidationError,
|
|
283
285
|
} from './schema-form';
|
|
286
|
+
export {
|
|
287
|
+
auditThemeContrast, failingContrastChecks, parseDtcgTheme, presetFromDtcg,
|
|
288
|
+
} from './theme-dtcg';
|
|
289
|
+
export type { ContrastCheck, DtcgIssue, DtcgTheme } from './theme-dtcg';
|
|
284
290
|
export { useExport } from './export-hooks.svelte';
|
|
285
291
|
export { snapshotExportTaskResult, downloadExportArtifact, safeArtifactUrl } from './export-format';
|
|
286
292
|
export type { ExportTaskResult } from './export-format';
|
package/src/schema-form.ts
CHANGED
|
@@ -20,6 +20,21 @@ export interface SchemaFormCondition {
|
|
|
20
20
|
not?: SchemaFormCondition;
|
|
21
21
|
}
|
|
22
22
|
|
|
23
|
+
/** 声明式排版:只描述呈现分组,不参与校验与提交投影。 */
|
|
24
|
+
export type SchemaFormLayoutType='grid'|'section'|'steps';
|
|
25
|
+
|
|
26
|
+
export interface SchemaFormLayout {
|
|
27
|
+
type: SchemaFormLayoutType;
|
|
28
|
+
title?: string;
|
|
29
|
+
description?: string;
|
|
30
|
+
/** 仅 grid:1-4 列。 */
|
|
31
|
+
columns?: 1|2|3|4;
|
|
32
|
+
/** 仅 grid:字段跨列数。 */
|
|
33
|
+
span?: 1|2|3|4;
|
|
34
|
+
/** 仅 steps:有序分组序号。 */
|
|
35
|
+
step?: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
23
38
|
/** 封闭集合的派生规则;不编译表达式,避免把 schema 变成代码执行入口。 */
|
|
24
39
|
export type SchemaFormComputedOp='sum'|'count'|'first'|'concat';
|
|
25
40
|
|
|
@@ -41,6 +56,7 @@ export interface SchemaFormSchema {
|
|
|
41
56
|
required?: string[];
|
|
42
57
|
visibleWhen?: SchemaFormCondition;
|
|
43
58
|
computed?: SchemaFormComputed;
|
|
59
|
+
layout?: SchemaFormLayout;
|
|
44
60
|
minLength?: number;
|
|
45
61
|
maxLength?: number;
|
|
46
62
|
pattern?: string;
|
|
@@ -52,9 +68,10 @@ export interface SchemaFormSchema {
|
|
|
52
68
|
|
|
53
69
|
const keys = new Set([
|
|
54
70
|
'type', 'title', 'description', 'properties', 'items', 'enum', 'default', 'required',
|
|
55
|
-
'visibleWhen', 'computed', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems',
|
|
71
|
+
'visibleWhen', 'computed', 'layout', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems',
|
|
56
72
|
]);
|
|
57
73
|
const COMPUTED_OPS=new Set<SchemaFormComputedOp>(['sum','count','first','concat']);
|
|
74
|
+
const LAYOUT_TYPES=new Set<SchemaFormLayoutType>(['grid','section','steps']);
|
|
58
75
|
const scalar = (value: unknown): value is SchemaFormScalar => value === null ||
|
|
59
76
|
typeof value === 'string' || typeof value === 'boolean' ||
|
|
60
77
|
(typeof value === 'number' && Number.isFinite(value));
|
|
@@ -128,7 +145,13 @@ export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
|
128
145
|
if (kind !== undefined && !['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'].includes(kind)) fail();
|
|
129
146
|
if (node.properties !== undefined) {
|
|
130
147
|
if (kind !== 'object' || !node.properties || typeof node.properties !== 'object' || Array.isArray(node.properties)) fail();
|
|
131
|
-
|
|
148
|
+
const structural = new Set<string>();
|
|
149
|
+
for (const child of Object.values(node.properties)) {
|
|
150
|
+
visit(child, depth + 1);
|
|
151
|
+
const layoutType = child.layout?.type;
|
|
152
|
+
if (layoutType === 'section' || layoutType === 'steps') structural.add(layoutType);
|
|
153
|
+
}
|
|
154
|
+
if (structural.size > 1) fail();
|
|
132
155
|
}
|
|
133
156
|
if (node.items !== undefined) {
|
|
134
157
|
if (kind !== 'array') fail();
|
|
@@ -159,6 +182,24 @@ export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
|
159
182
|
assertCondition(condition, schema, 0);
|
|
160
183
|
assertConditionPaths(condition, schema);
|
|
161
184
|
}
|
|
185
|
+
const layout = node.layout;
|
|
186
|
+
if (layout !== undefined) {
|
|
187
|
+
if (!layout || typeof layout !== 'object' || Array.isArray(layout) ||
|
|
188
|
+
Object.keys(layout).some(key => !['type', 'title', 'description', 'columns', 'span', 'step'].includes(key)) ||
|
|
189
|
+
!LAYOUT_TYPES.has(layout.type)) fail();
|
|
190
|
+
if (layout.title !== undefined && (typeof layout.title !== 'string' || layout.title.trim() === '' || layout.title.length > 120)) fail();
|
|
191
|
+
if (layout.description !== undefined && (typeof layout.description !== 'string' || layout.description.length > 400)) fail();
|
|
192
|
+
if (layout.columns !== undefined &&
|
|
193
|
+
(layout.type !== 'grid' || ![1, 2, 3, 4].includes(layout.columns))) fail();
|
|
194
|
+
if (layout.span !== undefined &&
|
|
195
|
+
(layout.type !== 'grid' || ![1, 2, 3, 4].includes(layout.span))) fail();
|
|
196
|
+
if (layout.step !== undefined &&
|
|
197
|
+
(layout.type !== 'steps' || !Number.isSafeInteger(layout.step) || layout.step < 1 || layout.step > 12)) fail();
|
|
198
|
+
if (layout.type === 'section' || layout.type === 'steps') {
|
|
199
|
+
if (layout.title === undefined) fail();
|
|
200
|
+
}
|
|
201
|
+
if (layout.type === 'grid' && layout.step !== undefined) fail();
|
|
202
|
+
}
|
|
162
203
|
const computed = node.computed;
|
|
163
204
|
if (computed !== undefined) {
|
|
164
205
|
if (!computed || typeof computed !== 'object' || Array.isArray(computed) ||
|
|
@@ -205,6 +246,106 @@ export function isSchemaFormNodeVisible(schema: SchemaFormSchema, rootValue: unk
|
|
|
205
246
|
return matchesSchemaFormCondition(schema.visibleWhen, rootValue);
|
|
206
247
|
}
|
|
207
248
|
|
|
249
|
+
export interface SchemaFormLayoutField {
|
|
250
|
+
key: string;
|
|
251
|
+
/** 1-4;仅 grid 分组会大于 1。 */
|
|
252
|
+
span: number;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
export interface SchemaFormLayoutGroup {
|
|
256
|
+
/** 稳定的渲染 key;默认分组为空字符串。 */
|
|
257
|
+
key: string;
|
|
258
|
+
title?: string;
|
|
259
|
+
description?: string;
|
|
260
|
+
step?: number;
|
|
261
|
+
columns: 1|2|3|4;
|
|
262
|
+
fields: readonly SchemaFormLayoutField[];
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
export interface SchemaFormLayoutPlan {
|
|
266
|
+
kind: 'flat'|'sections'|'steps';
|
|
267
|
+
columns: 1|2|3|4;
|
|
268
|
+
groups: readonly SchemaFormLayoutGroup[];
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* 把 `layout` 关键字折叠成渲染器可直接消费的分组计划。
|
|
273
|
+
* 纯函数:不读取表单值,因此隐藏字段仍由 `visibleWhen` 在渲染时过滤。
|
|
274
|
+
*/
|
|
275
|
+
export function resolveSchemaFormLayout(schema: SchemaFormSchema): SchemaFormLayoutPlan {
|
|
276
|
+
assertSchemaFormSchema(schema);
|
|
277
|
+
const entries=Object.entries(schema.properties ?? {});
|
|
278
|
+
let columns: 1|2|3|4=1;
|
|
279
|
+
let sawSection=false;
|
|
280
|
+
let sawSteps=false;
|
|
281
|
+
for (const [, child] of entries) {
|
|
282
|
+
const layout=child.layout;
|
|
283
|
+
if (!layout) continue;
|
|
284
|
+
if (layout.type === 'grid') columns=Math.max(columns, layout.columns ?? 1) as 1|2|3|4;
|
|
285
|
+
if (layout.type === 'section') sawSection=true;
|
|
286
|
+
if (layout.type === 'steps') sawSteps=true;
|
|
287
|
+
}
|
|
288
|
+
const kind: SchemaFormLayoutPlan['kind']=sawSteps ? 'steps' : sawSection ? 'sections' : 'flat';
|
|
289
|
+
|
|
290
|
+
const groups: Array<{ key: string; title?: string; description?: string; step?: number; columns: 1|2|3|4; fields: Array<SchemaFormLayoutField> }>=[];
|
|
291
|
+
let currentKey: string|undefined;
|
|
292
|
+
for (const [key, child] of entries) {
|
|
293
|
+
const layout=child.layout;
|
|
294
|
+
const grouped=layout !== undefined && (layout.type === 'section' || layout.type === 'steps');
|
|
295
|
+
const groupKey=grouped ? `${layout.type}:${layout.step ?? ''}:${layout.title ?? ''}` : '';
|
|
296
|
+
if (currentKey !== groupKey) {
|
|
297
|
+
currentKey=groupKey;
|
|
298
|
+
groups.push({
|
|
299
|
+
key: groupKey,
|
|
300
|
+
columns: grouped ? 1 : columns,
|
|
301
|
+
fields: [],
|
|
302
|
+
...(grouped && layout.title !== undefined ? { title: layout.title } : {}),
|
|
303
|
+
...(grouped && layout.description !== undefined ? { description: layout.description } : {}),
|
|
304
|
+
...(grouped && layout.type === 'steps' && layout.step !== undefined ? { step: layout.step } : {}),
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
groups.at(-1)?.fields.push({
|
|
308
|
+
key,
|
|
309
|
+
span: layout?.type === 'grid' ? Math.min(layout.span ?? 1, columns) : 1,
|
|
310
|
+
});
|
|
311
|
+
if (layout?.type === 'grid' && layout.columns !== undefined) {
|
|
312
|
+
const group=groups.at(-1);
|
|
313
|
+
if (group) group.columns=Math.max(group.columns, layout.columns) as 1|2|3|4;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
return {
|
|
318
|
+
kind,
|
|
319
|
+
columns,
|
|
320
|
+
groups: groups.map((group) => ({
|
|
321
|
+
key: group.key,
|
|
322
|
+
columns: group.columns,
|
|
323
|
+
fields: group.fields,
|
|
324
|
+
...(group.title === undefined ? {} : { title: group.title }),
|
|
325
|
+
...(group.description === undefined ? {} : { description: group.description }),
|
|
326
|
+
...(group.step === undefined ? {} : { step: group.step }),
|
|
327
|
+
})),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* AutoForm 字段上的 `layout` 与 schema 关键字走同一投影。
|
|
334
|
+
* 没有声明时返回 undefined,调用方保持原有 `group` / `columns` 行为。
|
|
335
|
+
*/
|
|
336
|
+
export function resolveDeclaredFieldLayout(
|
|
337
|
+
fields: readonly { key: string; layout?: SchemaFormLayout }[],
|
|
338
|
+
): SchemaFormLayoutPlan | undefined {
|
|
339
|
+
if (!fields.some((field) => field.layout !== undefined)) return undefined;
|
|
340
|
+
const properties: Record<string, SchemaFormSchema> = {};
|
|
341
|
+
for (const field of fields) {
|
|
342
|
+
properties[field.key] = field.layout === undefined
|
|
343
|
+
? { type: 'string' }
|
|
344
|
+
: { type: 'string', layout: field.layout };
|
|
345
|
+
}
|
|
346
|
+
return resolveSchemaFormLayout({ type: 'object', properties });
|
|
347
|
+
}
|
|
348
|
+
|
|
208
349
|
export interface SchemaFormValidationError {
|
|
209
350
|
/** JSON 数组路径,不混淆字段名中的点、斜杠和数组索引。 */
|
|
210
351
|
path: string;
|
package/src/schema.ts
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
export { createExactSchemaValidator, checkExact } from './schema-validation';
|
|
2
2
|
export {
|
|
3
3
|
readSchemaFormPath, matchesSchemaFormCondition, isSchemaFormNodeVisible, validateSchemaFormValue,
|
|
4
|
-
assertSchemaFormSchema, prepareSchemaFormValue,
|
|
4
|
+
assertSchemaFormSchema, prepareSchemaFormValue, resolveDeclaredFieldLayout, resolveSchemaFormLayout,
|
|
5
5
|
} from './schema-form';
|
|
6
6
|
export type {
|
|
7
|
-
SchemaFormScalar, SchemaFormCondition,
|
|
7
|
+
SchemaFormScalar, SchemaFormCondition, SchemaFormLayout, SchemaFormLayoutPlan, SchemaFormSchema,
|
|
8
|
+
SchemaFormValidationError,
|
|
8
9
|
} from './schema-form';
|
|
9
10
|
export { snapshotPlainData } from './plain-data';
|
|
10
11
|
export type { JsonValue } from './plain-data';
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Theme token ingestion (DTCG / Figma Variables) and contrast auditing.
|
|
3
|
+
*
|
|
4
|
+
* The token document in `color-scale.ts` is svadmin's own exchange format. This
|
|
5
|
+
* module covers the inbound direction used by design tooling — DTCG design
|
|
6
|
+
* tokens (`$value` / `$type`, nested groups, `{alias}` references) — plus a
|
|
7
|
+
* WCAG contrast audit so a palette change can fail CI instead of shipping
|
|
8
|
+
* unreadable text.
|
|
9
|
+
*/
|
|
10
|
+
import {
|
|
11
|
+
deriveColorPreset,
|
|
12
|
+
hexContrastRatio,
|
|
13
|
+
oklchToHex,
|
|
14
|
+
parseHex,
|
|
15
|
+
type DerivedColorPreset,
|
|
16
|
+
} from './color-scale';
|
|
17
|
+
|
|
18
|
+
export interface DtcgIssue {
|
|
19
|
+
path: string;
|
|
20
|
+
reason: 'unsupported-type' | 'invalid-value' | 'unresolved-alias' | 'duplicate-variable';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DtcgTheme {
|
|
24
|
+
/** CSS variable → color value, ready for the theme applier. */
|
|
25
|
+
light: Record<string, string>;
|
|
26
|
+
dark: Record<string, string>;
|
|
27
|
+
issues: DtcgIssue[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const MAX_DEPTH = 32;
|
|
31
|
+
const MAX_TOKENS = 2000;
|
|
32
|
+
const CSS_VAR_PATTERN = /^--[a-z0-9-]{1,64}$/i;
|
|
33
|
+
const COLOR_VALUE_PATTERN = /^(?:#(?:[0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})|oklch\(|rgb\(|hsl\(|color\()/i;
|
|
34
|
+
|
|
35
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
36
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** `color.primary.foreground` → `--primary-foreground` (leading segment dropped when it is `color`). */
|
|
40
|
+
export function dtcgPathToCssVar(path: string): string | undefined {
|
|
41
|
+
const segments = path
|
|
42
|
+
.split('.')
|
|
43
|
+
.flatMap((segment) => segment.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase().split(/[^a-z0-9]+/))
|
|
44
|
+
.filter(Boolean);
|
|
45
|
+
if (segments[0] === 'color' || segments[0] === 'colors') segments.shift();
|
|
46
|
+
if (segments.length === 0) return undefined;
|
|
47
|
+
const variable = `--${segments.join('-')}`;
|
|
48
|
+
return CSS_VAR_PATTERN.test(variable) ? variable : undefined;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
interface FlatToken {
|
|
52
|
+
path: string;
|
|
53
|
+
value: string;
|
|
54
|
+
type?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function flatten(document: Record<string, unknown>): { tokens: FlatToken[]; issues: DtcgIssue[] } {
|
|
58
|
+
const tokens: FlatToken[] = [];
|
|
59
|
+
const issues: DtcgIssue[] = [];
|
|
60
|
+
let visited = 0;
|
|
61
|
+
|
|
62
|
+
function visit(node: Record<string, unknown>, path: string[], depth: number): void {
|
|
63
|
+
if (depth > MAX_DEPTH || ++visited > MAX_TOKENS * 8) return;
|
|
64
|
+
if (typeof node['$value'] !== 'undefined') {
|
|
65
|
+
const value = node['$value'];
|
|
66
|
+
const type = typeof node['$type'] === 'string' ? node['$type'] : undefined;
|
|
67
|
+
if (typeof value !== 'string') {
|
|
68
|
+
issues.push({ path: path.join('.'), reason: 'invalid-value' });
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
tokens.push({ path: path.join('.'), value, ...(type ? { type } : {}) });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
for (const [key, child] of Object.entries(node)) {
|
|
75
|
+
if (key.startsWith('$')) continue;
|
|
76
|
+
if (!isRecord(child)) {
|
|
77
|
+
issues.push({ path: [...path, key].join('.'), reason: 'invalid-value' });
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
visit(child, [...path, key], depth + 1);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
for (const [key, child] of Object.entries(document)) {
|
|
85
|
+
if (key.startsWith('$')) continue;
|
|
86
|
+
if (!isRecord(child)) continue;
|
|
87
|
+
visit(child, [key], 1);
|
|
88
|
+
}
|
|
89
|
+
return { tokens, issues };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Parse a DTCG document into light/dark CSS variable maps.
|
|
95
|
+
*
|
|
96
|
+
* Modes are detected from a `light` / `dark` path segment anywhere below the
|
|
97
|
+
* root, so both `{ light: {...}, dark: {...} }` and
|
|
98
|
+
* `{ color: { light: {...}, dark: {...} } }` work. Tokens without a mode segment
|
|
99
|
+
* apply to both modes. Aliases resolve against full paths.
|
|
100
|
+
*/
|
|
101
|
+
export function parseDtcgTheme(document: unknown): DtcgTheme {
|
|
102
|
+
if (!isRecord(document)) throw new TypeError('DTCG document must be an object');
|
|
103
|
+
const result: DtcgTheme = { light: {}, dark: {}, issues: [] };
|
|
104
|
+
const { tokens, issues } = flatten(document);
|
|
105
|
+
result.issues.push(...issues);
|
|
106
|
+
const byPath = new Map(tokens.map((token) => [token.path.toLowerCase(), token]));
|
|
107
|
+
const resolvedCache = new Map<string, string | undefined>();
|
|
108
|
+
|
|
109
|
+
function resolve(token: FlatToken, depth = 0): string | undefined {
|
|
110
|
+
if (depth > 16) return undefined;
|
|
111
|
+
const alias = /^\{(.+)\}$/.exec(token.value.trim());
|
|
112
|
+
if (!alias) return token.value;
|
|
113
|
+
const key = token.path.toLowerCase();
|
|
114
|
+
if (resolvedCache.has(key)) return resolvedCache.get(key);
|
|
115
|
+
const target = byPath.get((alias[1] ?? '').toLowerCase());
|
|
116
|
+
const value = target ? resolve(target, depth + 1) : undefined;
|
|
117
|
+
if (value === undefined) result.issues.push({ path: token.path, reason: 'unresolved-alias' });
|
|
118
|
+
resolvedCache.set(key, value);
|
|
119
|
+
return value;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const seen = { light: new Set<string>(), dark: new Set<string>() };
|
|
123
|
+
const unmodeed: Array<[string, string]> = [];
|
|
124
|
+
for (const token of tokens) {
|
|
125
|
+
const segments = token.path.split('.');
|
|
126
|
+
const type = token.type?.toLowerCase();
|
|
127
|
+
if (type !== undefined && type !== 'color' && type !== 'all') {
|
|
128
|
+
result.issues.push({ path: token.path, reason: 'unsupported-type' });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const value = resolve(token);
|
|
132
|
+
if (value === undefined || !COLOR_VALUE_PATTERN.test(value.trim())) continue;
|
|
133
|
+
const modeIndex = segments.findIndex((segment) => segment === 'light' || segment === 'dark');
|
|
134
|
+
const variablePath = modeIndex === -1 ? segments : [...segments.slice(0, modeIndex), ...segments.slice(modeIndex + 1)];
|
|
135
|
+
const variable = dtcgPathToCssVar(variablePath.join('.'));
|
|
136
|
+
if (variable === undefined) continue;
|
|
137
|
+
if (modeIndex === -1) {
|
|
138
|
+
unmodeed.push([variable, value.trim()]);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const mode = segments[modeIndex] as 'light' | 'dark';
|
|
142
|
+
if (seen[mode].has(variable)) {
|
|
143
|
+
result.issues.push({ path: token.path, reason: 'duplicate-variable' });
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
seen[mode].add(variable);
|
|
147
|
+
result[mode][variable] = value.trim();
|
|
148
|
+
}
|
|
149
|
+
// Un-moded tokens feed both modes unless the mode already declared the key.
|
|
150
|
+
for (const [variable, value] of unmodeed) {
|
|
151
|
+
for (const mode of ['light', 'dark'] as const) {
|
|
152
|
+
if (seen[mode].has(variable)) continue;
|
|
153
|
+
seen[mode].add(variable);
|
|
154
|
+
result[mode][variable] = value;
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (Object.keys(result.light).length === 0 && Object.keys(result.dark).length === 0) {
|
|
159
|
+
throw new TypeError('DTCG document contains no color tokens');
|
|
160
|
+
}
|
|
161
|
+
if (Object.keys(result.dark).length === 0) result.dark = { ...result.light };
|
|
162
|
+
if (Object.keys(result.light).length === 0) result.light = { ...result.dark };
|
|
163
|
+
return result;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Build a complete preset from a DTCG document. Tokens present in the document
|
|
168
|
+
* win; missing keys fall back to the generated palette for the same brand color.
|
|
169
|
+
*/
|
|
170
|
+
export function presetFromDtcg(input: {
|
|
171
|
+
name: string;
|
|
172
|
+
label?: string;
|
|
173
|
+
color: string;
|
|
174
|
+
document: unknown;
|
|
175
|
+
}): DerivedColorPreset {
|
|
176
|
+
const generated = deriveColorPreset(input);
|
|
177
|
+
const dtcg = parseDtcgTheme(input.document);
|
|
178
|
+
return {
|
|
179
|
+
name: generated.name,
|
|
180
|
+
label: generated.label,
|
|
181
|
+
color: generated.color,
|
|
182
|
+
// Overlay wins key-by-key. Do not re-read `--primary`: indexed access is
|
|
183
|
+
// `string | undefined` under noUncheckedIndexedAccess.
|
|
184
|
+
light: { ...generated.light, ...dtcg.light },
|
|
185
|
+
dark: { ...generated.dark, ...dtcg.dark },
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export interface ContrastCheck {
|
|
190
|
+
pair: string;
|
|
191
|
+
mode: 'light' | 'dark';
|
|
192
|
+
foreground: string;
|
|
193
|
+
background: string;
|
|
194
|
+
ratio: number;
|
|
195
|
+
aa: boolean;
|
|
196
|
+
aaa: boolean;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const MODE_SURFACE = { light: '#FFFFFF', dark: '#111111' } as const;
|
|
200
|
+
|
|
201
|
+
function cssColorToHex(value: string): string | undefined {
|
|
202
|
+
const trimmed = value.trim();
|
|
203
|
+
if (trimmed.startsWith('#')) {
|
|
204
|
+
try {
|
|
205
|
+
parseHex(trimmed);
|
|
206
|
+
return trimmed.length === 4
|
|
207
|
+
? `#${trimmed[1]}${trimmed[1]}${trimmed[2]}${trimmed[2]}${trimmed[3]}${trimmed[3]}`.toUpperCase()
|
|
208
|
+
: trimmed.slice(0, 7).toUpperCase();
|
|
209
|
+
} catch {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
const match = /^oklch\(\s*([\d.]+)\s+([\d.]+)\s+([\d.]+)/i.exec(trimmed);
|
|
214
|
+
if (match) {
|
|
215
|
+
return oklchToHex(Number(match[1]), Number(match[2]), Number(match[3]));
|
|
216
|
+
}
|
|
217
|
+
return undefined;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Audit the token pairs that decide readability. AA is 4.5:1 for body text and
|
|
222
|
+
* 3:1 for large text/graphics, matching WCAG 2.1.
|
|
223
|
+
*/
|
|
224
|
+
export function auditThemeContrast(preset: DerivedColorPreset): ContrastCheck[] {
|
|
225
|
+
const checks: ContrastCheck[] = [];
|
|
226
|
+
const pairs: Array<[string, string, string, number]> = [
|
|
227
|
+
['primary text', '--primary-foreground', '--primary', 4.5],
|
|
228
|
+
['primary on surface', '--primary', '#surface', 3],
|
|
229
|
+
['sidebar primary text', '--sidebar-primary-foreground', '--sidebar-primary', 4.5],
|
|
230
|
+
['chart-1 on surface', '--chart-1', '#surface', 3],
|
|
231
|
+
['chart-2 on surface', '--chart-2', '#surface', 3],
|
|
232
|
+
['chart-3 on surface', '--chart-3', '#surface', 3],
|
|
233
|
+
['chart-4 on surface', '--chart-4', '#surface', 3],
|
|
234
|
+
['chart-5 on surface', '--chart-5', '#surface', 3],
|
|
235
|
+
];
|
|
236
|
+
|
|
237
|
+
for (const mode of ['light', 'dark'] as const) {
|
|
238
|
+
const tokens = preset[mode];
|
|
239
|
+
const surface = MODE_SURFACE[mode];
|
|
240
|
+
for (const [pair, foregroundKey, backgroundKey, minimum] of pairs) {
|
|
241
|
+
const foreground = foregroundKey.startsWith('#') ? foregroundKey : tokens[foregroundKey];
|
|
242
|
+
const background = backgroundKey === '#surface'
|
|
243
|
+
? surface
|
|
244
|
+
: backgroundKey.startsWith('#') ? backgroundKey : tokens[backgroundKey];
|
|
245
|
+
if (!foreground || !background) continue;
|
|
246
|
+
const foregroundHex = cssColorToHex(foreground);
|
|
247
|
+
const backgroundHex = cssColorToHex(background);
|
|
248
|
+
if (!foregroundHex || !backgroundHex) continue;
|
|
249
|
+
const ratio = Math.round(hexContrastRatio(foregroundHex, backgroundHex) * 100) / 100;
|
|
250
|
+
checks.push({
|
|
251
|
+
pair,
|
|
252
|
+
mode,
|
|
253
|
+
foreground: foregroundHex,
|
|
254
|
+
background: backgroundHex,
|
|
255
|
+
ratio,
|
|
256
|
+
aa: ratio >= minimum,
|
|
257
|
+
aaa: ratio >= (minimum === 4.5 ? 7 : 4.5),
|
|
258
|
+
});
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return checks;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export function failingContrastChecks(checks: readonly ContrastCheck[]): ContrastCheck[] {
|
|
265
|
+
return checks.filter((check) => !check.aa);
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
export function formatContrastReport(presetName: string, checks: readonly ContrastCheck[]): string {
|
|
269
|
+
const rows = checks.map((check) => (
|
|
270
|
+
`| ${check.mode} | ${check.pair} | ${check.foreground} on ${check.background} | ${check.ratio} | ${check.aa ? 'pass' : 'FAIL'} |`
|
|
271
|
+
));
|
|
272
|
+
return [
|
|
273
|
+
`# Theme contrast: ${presetName}`,
|
|
274
|
+
'',
|
|
275
|
+
'| Mode | Pair | Colors | Ratio | AA |',
|
|
276
|
+
'| --- | --- | --- | --- | --- |',
|
|
277
|
+
...rows,
|
|
278
|
+
].join('\n');
|
|
279
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -485,6 +485,18 @@ export interface FieldDefinition {
|
|
|
485
485
|
validate?: (value: unknown) => string | null;
|
|
486
486
|
// Grouping
|
|
487
487
|
group?: string;
|
|
488
|
+
/**
|
|
489
|
+
* 声明式排版,与 schema `layout` 使用同一投影规则。
|
|
490
|
+
* 只影响 AutoForm 呈现,不参与校验和提交。
|
|
491
|
+
*/
|
|
492
|
+
layout?: {
|
|
493
|
+
type: 'grid' | 'section' | 'steps';
|
|
494
|
+
title?: string;
|
|
495
|
+
description?: string;
|
|
496
|
+
columns?: 1 | 2 | 3 | 4;
|
|
497
|
+
span?: 1 | 2 | 3 | 4;
|
|
498
|
+
step?: number;
|
|
499
|
+
};
|
|
488
500
|
}
|
|
489
501
|
|
|
490
502
|
// ─── Resource Type Registry ───────────────────────────────────
|