@svadmin/core 0.72.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 +343 -0
- package/src/index.ts +11 -3
- package/src/schema-form.ts +301 -21
- package/src/schema.ts +3 -2
- package/src/theme-dtcg.ts +279 -0
- package/src/theme.svelte.ts +52 -4
- package/src/types.ts +12 -0
package/package.json
CHANGED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Color scale generation and theme-token exchange.
|
|
3
|
+
*
|
|
4
|
+
* Capability parity with the Arco ecosystem's `@arco-design/color` + theme
|
|
5
|
+
* editor: derive a tonal scale from one brand color, build light/dark CSS
|
|
6
|
+
* variable bundles, and exchange presets as portable JSON.
|
|
7
|
+
*
|
|
8
|
+
* Boundaries (intentional):
|
|
9
|
+
* - no Less/`modifyVars` layer; output is CSS custom properties only;
|
|
10
|
+
* - no arbitrary expression or code compilation in the payload;
|
|
11
|
+
* - gamut mapping happens in OKLCH so generated values stay valid sRGB.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export interface ColorScaleStep {
|
|
15
|
+
/** 1 = lightest, 10 = darkest. */
|
|
16
|
+
step: number;
|
|
17
|
+
/** `oklch(L C H)` string, directly assignable to a CSS variable. */
|
|
18
|
+
value: string;
|
|
19
|
+
/** Clamped sRGB hex, for swatches and contrast checks. */
|
|
20
|
+
hex: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Structural subset of `ColorPreset`; keeps this module rune-free. */
|
|
24
|
+
export interface DerivedColorPreset {
|
|
25
|
+
name: string;
|
|
26
|
+
label: string;
|
|
27
|
+
color: string;
|
|
28
|
+
light: Record<string, string>;
|
|
29
|
+
dark: Record<string, string>;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface ThemeTokenDocument {
|
|
33
|
+
version: 1;
|
|
34
|
+
presets: DerivedColorPreset[];
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const HEX_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
|
|
38
|
+
const MAX_PRESETS = 64;
|
|
39
|
+
const MAX_VARIABLES = 64;
|
|
40
|
+
|
|
41
|
+
function clamp01(value: number): number {
|
|
42
|
+
return value < 0 ? 0 : value > 1 ? 1 : value;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function srgbToLinear(channel: number): number {
|
|
46
|
+
return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function linearToSrgb(channel: number): number {
|
|
50
|
+
return channel <= 0.0031308 ? channel * 12.92 : 1.055 * channel ** (1 / 2.4) - 0.055;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function parseHex(hex: string): { r: number; g: number; b: number } {
|
|
54
|
+
if (typeof hex !== 'string' || !HEX_PATTERN.test(hex.trim())) {
|
|
55
|
+
throw new TypeError(`Expected a 3- or 6-digit hex color, received: ${String(hex)}`);
|
|
56
|
+
}
|
|
57
|
+
let body = hex.trim().slice(1);
|
|
58
|
+
if (body.length === 3) body = body.split('').map((digit) => digit + digit).join('');
|
|
59
|
+
return {
|
|
60
|
+
r: parseInt(body.slice(0, 2), 16) / 255,
|
|
61
|
+
g: parseInt(body.slice(2, 4), 16) / 255,
|
|
62
|
+
b: parseInt(body.slice(4, 6), 16) / 255,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function hexToOklch(hex: string): { l: number; c: number; h: number } {
|
|
67
|
+
const { r, g, b } = parseHex(hex);
|
|
68
|
+
const lr = srgbToLinear(r);
|
|
69
|
+
const lg = srgbToLinear(g);
|
|
70
|
+
const lb = srgbToLinear(b);
|
|
71
|
+
const l = 0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb;
|
|
72
|
+
const m = 0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb;
|
|
73
|
+
const s = 0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb;
|
|
74
|
+
const l3 = Math.cbrt(l);
|
|
75
|
+
const m3 = Math.cbrt(m);
|
|
76
|
+
const s3 = Math.cbrt(s);
|
|
77
|
+
const okL = 0.2104542553 * l3 + 0.793617785 * m3 - 0.0040720468 * s3;
|
|
78
|
+
const okA = 1.9779984951 * l3 - 2.428592205 * m3 + 0.4505937099 * s3;
|
|
79
|
+
const okB = 0.0259040371 * l3 + 0.7827717662 * m3 - 0.808675766 * s3;
|
|
80
|
+
const hue = (Math.atan2(okB, okA) * 180) / Math.PI;
|
|
81
|
+
return { l: okL, c: Math.hypot(okA, okB), h: hue < 0 ? hue + 360 : hue };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Convert OKLCH to sRGB channels, or `undefined` when the color is out of gamut. */
|
|
85
|
+
function oklchToRgbUnclamped(l: number, c: number, h: number): { r: number; g: number; b: number } | undefined {
|
|
86
|
+
const radians = (h * Math.PI) / 180;
|
|
87
|
+
const okA = c * Math.cos(radians);
|
|
88
|
+
const okB = c * Math.sin(radians);
|
|
89
|
+
const l3 = l + 0.3963377774 * okA + 0.2158037573 * okB;
|
|
90
|
+
const m3 = l - 0.1055613458 * okA - 0.0638541728 * okB;
|
|
91
|
+
const s3 = l - 0.0894841775 * okA - 1.291485548 * okB;
|
|
92
|
+
const lCube = l3 ** 3;
|
|
93
|
+
const mCube = m3 ** 3;
|
|
94
|
+
const sCube = s3 ** 3;
|
|
95
|
+
const linearR = 4.0767416621 * lCube - 3.3077115913 * mCube + 0.2309699292 * sCube;
|
|
96
|
+
const linearG = -1.2684380046 * lCube + 2.6097574011 * mCube - 0.3413193965 * sCube;
|
|
97
|
+
const linearB = -0.0041960863 * lCube - 0.7034186147 * mCube + 1.707614701 * sCube;
|
|
98
|
+
const epsilon = 1e-6;
|
|
99
|
+
if ([linearR, linearG, linearB].some((channel) => channel < -epsilon || channel > 1 + epsilon)) return undefined;
|
|
100
|
+
return {
|
|
101
|
+
r: clamp01(linearToSrgb(clamp01(linearR))),
|
|
102
|
+
g: clamp01(linearToSrgb(clamp01(linearG))),
|
|
103
|
+
b: clamp01(linearToSrgb(clamp01(linearB))),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Map an OKLCH color into sRGB by reducing chroma until it fits the gamut. */
|
|
108
|
+
function oklchToRgb(l: number, c: number, h: number): { r: number; g: number; b: number } {
|
|
109
|
+
const lightness = clamp01(l);
|
|
110
|
+
const direct = oklchToRgbUnclamped(lightness, c, h);
|
|
111
|
+
if (direct) return direct;
|
|
112
|
+
let low = 0;
|
|
113
|
+
let high = c;
|
|
114
|
+
let result = oklchToRgbUnclamped(lightness, 0, h) ?? { r: 0, g: 0, b: 0 };
|
|
115
|
+
for (let index = 0; index < 24; index += 1) {
|
|
116
|
+
const mid = (low + high) / 2;
|
|
117
|
+
const candidate = oklchToRgbUnclamped(lightness, mid, h);
|
|
118
|
+
if (candidate) {
|
|
119
|
+
result = candidate;
|
|
120
|
+
low = mid;
|
|
121
|
+
} else {
|
|
122
|
+
high = mid;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function toHex(channels: { r: number; g: number; b: number }): string {
|
|
129
|
+
const part = (value: number): string => Math.round(clamp01(value) * 255).toString(16).padStart(2, '0');
|
|
130
|
+
return `#${part(channels.r)}${part(channels.g)}${part(channels.b)}`.toUpperCase();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function formatOklch(l: number, c: number, h: number): string {
|
|
134
|
+
const roundedHue = Math.round((((h % 360) + 360) % 360) * 10) / 10;
|
|
135
|
+
return `oklch(${Math.round(l * 1000) / 1000} ${Math.round(c * 1000) / 1000} ${roundedHue})`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function relativeLuminance(hex: string): number {
|
|
139
|
+
const { r, g, b } = parseHex(hex);
|
|
140
|
+
return 0.2126 * srgbToLinear(r) + 0.7152 * srgbToLinear(g) + 0.0722 * srgbToLinear(b);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function contrastRatio(a: string, b: string): number {
|
|
144
|
+
const first = relativeLuminance(a);
|
|
145
|
+
const second = relativeLuminance(b);
|
|
146
|
+
const lighter = Math.max(first, second);
|
|
147
|
+
const darker = Math.min(first, second);
|
|
148
|
+
return (lighter + 0.05) / (darker + 0.05);
|
|
149
|
+
}
|
|
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
|
+
|
|
165
|
+
/** Pick the foreground with the higher contrast ratio (WCAG relative luminance). */
|
|
166
|
+
export function pickReadableForeground(backgroundHex: string): string {
|
|
167
|
+
return contrastRatio(backgroundHex, '#FFFFFF') >= contrastRatio(backgroundHex, '#111111')
|
|
168
|
+
? '#FFFFFF'
|
|
169
|
+
: '#111111';
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Derive a 10-step tonal scale from a brand color.
|
|
174
|
+
* Step 1 is the lightest tint, step 10 the darkest shade; hue is preserved.
|
|
175
|
+
*/
|
|
176
|
+
export function generateColorScale(color: string): ColorScaleStep[] {
|
|
177
|
+
const { c: baseChroma, h } = hexToOklch(color);
|
|
178
|
+
const lightest = 0.975;
|
|
179
|
+
const darkest = 0.26;
|
|
180
|
+
const steps: ColorScaleStep[] = [];
|
|
181
|
+
for (let step = 1; step <= 10; step += 1) {
|
|
182
|
+
const ratio = (step - 1) / 9;
|
|
183
|
+
const lightness = lightest - (lightest - darkest) * ratio;
|
|
184
|
+
// Chroma peaks in the mid tones so the endpoints stay near-neutral.
|
|
185
|
+
const chroma = baseChroma * (0.35 + 0.65 * Math.sin(Math.PI * (0.15 + 0.7 * ratio)));
|
|
186
|
+
const rgb = oklchToRgb(lightness, chroma, h);
|
|
187
|
+
steps.push({ step, value: formatOklch(lightness, chroma, h), hex: toHex(rgb) });
|
|
188
|
+
}
|
|
189
|
+
return steps;
|
|
190
|
+
}
|
|
191
|
+
|
|
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> {
|
|
226
|
+
const offsets = [0, 32, -32, 64, -64];
|
|
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
|
+
}));
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Build light/dark CSS variable bundles for one brand color.
|
|
235
|
+
* Keys mirror the built-in presets so `registerColorPreset` can consume it.
|
|
236
|
+
*/
|
|
237
|
+
export function deriveColorPreset(input: { name: string; label?: string; color: string }): DerivedColorPreset {
|
|
238
|
+
const name = input.name?.trim();
|
|
239
|
+
if (!name) throw new TypeError('deriveColorPreset requires a non-empty name');
|
|
240
|
+
const color = input.color?.trim();
|
|
241
|
+
const source = hexToOklch(color);
|
|
242
|
+
const scale = generateColorScale(color);
|
|
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);
|
|
249
|
+
|
|
250
|
+
return {
|
|
251
|
+
name,
|
|
252
|
+
label: input.label?.trim() || name,
|
|
253
|
+
color: color.toUpperCase(),
|
|
254
|
+
light: {
|
|
255
|
+
'--primary': lightPrimary.value,
|
|
256
|
+
'--primary-foreground': lightForeground,
|
|
257
|
+
'--ring': lightPrimary.value,
|
|
258
|
+
'--sidebar-primary': lightPrimary.value,
|
|
259
|
+
'--sidebar-primary-foreground': lightForeground,
|
|
260
|
+
'--sidebar-ring': lightPrimary.value,
|
|
261
|
+
...chartPalette(scale, source.h, source.c, source.l, '#FFFFFF'),
|
|
262
|
+
},
|
|
263
|
+
dark: {
|
|
264
|
+
'--primary': darkPrimary.value,
|
|
265
|
+
'--primary-foreground': darkForeground,
|
|
266
|
+
'--ring': scale[4]?.value as string,
|
|
267
|
+
'--sidebar-primary': darkPrimary.value,
|
|
268
|
+
'--sidebar-primary-foreground': darkForeground,
|
|
269
|
+
'--sidebar-ring': scale[4]?.value as string,
|
|
270
|
+
...chartPalette(scale, source.h, source.c * 1.05, Math.min(0.82, source.l + 0.12), '#111111'),
|
|
271
|
+
},
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function assertVariableMap(value: unknown, label: string): asserts value is Record<string, string> {
|
|
276
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
277
|
+
throw new TypeError(`${label} must be an object of CSS variable values`);
|
|
278
|
+
}
|
|
279
|
+
const entries = Object.entries(value);
|
|
280
|
+
if (entries.length === 0 || entries.length > MAX_VARIABLES) {
|
|
281
|
+
throw new TypeError(`${label} must declare between 1 and ${MAX_VARIABLES} variables`);
|
|
282
|
+
}
|
|
283
|
+
for (const [key, variable] of entries) {
|
|
284
|
+
if (!/^--[a-z0-9-]{1,64}$/i.test(key)) throw new TypeError(`${label} has an invalid CSS variable name: ${key}`);
|
|
285
|
+
if (typeof variable !== 'string' || variable.trim() === '' || variable.length > 200) {
|
|
286
|
+
throw new TypeError(`${label}.${key} must be a non-empty string`);
|
|
287
|
+
}
|
|
288
|
+
// Token exchange is a data contract: only color syntax, never arbitrary CSS.
|
|
289
|
+
if (!/^(?:oklch\(|#|rgb\(|hsl\(|var\(--)/i.test(variable.trim()) || /[;{}]/.test(variable)) {
|
|
290
|
+
throw new TypeError(`${label}.${key} is not a color token value: ${variable}`);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Serialize presets into a portable, versioned document. */
|
|
296
|
+
export function exportThemeTokens(presets: readonly DerivedColorPreset[]): ThemeTokenDocument {
|
|
297
|
+
return {
|
|
298
|
+
version: 1,
|
|
299
|
+
presets: presets.map((preset) => ({
|
|
300
|
+
name: preset.name,
|
|
301
|
+
label: preset.label,
|
|
302
|
+
color: preset.color,
|
|
303
|
+
light: { ...preset.light },
|
|
304
|
+
dark: { ...preset.dark },
|
|
305
|
+
})),
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
/** Validate and clone a token document without mutating shared state. */
|
|
310
|
+
export function parseThemeTokens(payload: unknown): DerivedColorPreset[] {
|
|
311
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
312
|
+
throw new TypeError('Theme token document must be an object');
|
|
313
|
+
}
|
|
314
|
+
const document = payload as Partial<ThemeTokenDocument>;
|
|
315
|
+
if (document.version !== 1) throw new TypeError('Unsupported theme token document version; expected 1');
|
|
316
|
+
if (!Array.isArray(document.presets) || document.presets.length === 0 || document.presets.length > MAX_PRESETS) {
|
|
317
|
+
throw new TypeError(`Theme token document must declare between 1 and ${MAX_PRESETS} presets`);
|
|
318
|
+
}
|
|
319
|
+
const seen = new Set<string>();
|
|
320
|
+
return document.presets.map((raw, index) => {
|
|
321
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
322
|
+
throw new TypeError(`Theme token preset at index ${index} must be an object`);
|
|
323
|
+
}
|
|
324
|
+
const { name, label, color } = raw as Partial<DerivedColorPreset>;
|
|
325
|
+
if (typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(name)) {
|
|
326
|
+
throw new TypeError(`Theme token preset at index ${index} has an invalid name`);
|
|
327
|
+
}
|
|
328
|
+
if (seen.has(name)) throw new TypeError(`Duplicate theme token preset: ${name}`);
|
|
329
|
+
seen.add(name);
|
|
330
|
+
if (typeof color !== 'string' || !HEX_PATTERN.test(color.trim())) {
|
|
331
|
+
throw new TypeError(`Theme token preset "${name}" must declare a hex color`);
|
|
332
|
+
}
|
|
333
|
+
assertVariableMap(raw.light, `${name}.light`);
|
|
334
|
+
assertVariableMap(raw.dark, `${name}.dark`);
|
|
335
|
+
return {
|
|
336
|
+
name,
|
|
337
|
+
label: typeof label === 'string' && label.trim() !== '' ? label.trim().slice(0, 64) : name,
|
|
338
|
+
color: color.trim().toUpperCase(),
|
|
339
|
+
light: { ...raw.light },
|
|
340
|
+
dark: { ...raw.dark },
|
|
341
|
+
};
|
|
342
|
+
});
|
|
343
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -215,8 +215,10 @@ export type {
|
|
|
215
215
|
MessageStatus, ToolState, AgentProvider, AgentEvent, AgentOptions, ApprovalResponseOptions,
|
|
216
216
|
AdminTool, ToolResult,
|
|
217
217
|
} from './chatProvider.svelte';
|
|
218
|
-
export { getTheme, setTheme, toggleTheme, getResolvedTheme, getColorTheme, setColorTheme, getColorThemes, configureTheme, getThemeConfig, clearCssOverrides, builtinPresets, registerColorPreset, getColorPresets, registerThemeOwner, updateThemeOwner, unregisterThemeOwner, resetTheme } from './theme.svelte';
|
|
219
|
-
export
|
|
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, hexContrastRatio, hexLuminance, hexToOklch, oklchToHex, parseThemeTokens, pickReadableForeground } from './color-scale';
|
|
220
|
+
export type { ColorScaleStep, DerivedColorPreset, ThemeTokenDocument } from './color-scale';
|
|
221
|
+
export type { ThemeMode, ColorTheme, BuiltinColorTheme, ThemeStrategy, ThemeConfig, ColorPreset, ThemeOwnerOptions, ThemeOwnerToken } from './theme.svelte';
|
|
220
222
|
export { setUnsavedChanges, getUnsavedChanges, initUnsavedChangesNotifier, resetUnsavedChanges } from './unsaved-changes.svelte';
|
|
221
223
|
export { setAdminOptions, getAdminOptions, getTextTransformers } from './options.svelte';
|
|
222
224
|
export type { AdminOptions, TextTransformers, OvertimeConfig } from './options.svelte';
|
|
@@ -275,10 +277,16 @@ export { FILTER_COLLECTION_LIMIT, isNumericFilterField, isCollectionFilterOperat
|
|
|
275
277
|
export {
|
|
276
278
|
assertSchemaFormSchema, prepareSchemaFormValue, readSchemaFormPath,
|
|
277
279
|
matchesSchemaFormCondition, isSchemaFormNodeVisible, validateSchemaFormValue,
|
|
280
|
+
resolveDeclaredFieldLayout, resolveSchemaFormLayout,
|
|
278
281
|
} from './schema-form';
|
|
279
282
|
export type {
|
|
280
|
-
SchemaFormScalar, SchemaFormCondition,
|
|
283
|
+
SchemaFormScalar, SchemaFormCondition, SchemaFormLayout, SchemaFormLayoutPlan, SchemaFormSchema,
|
|
284
|
+
SchemaFormValidationError,
|
|
281
285
|
} from './schema-form';
|
|
286
|
+
export {
|
|
287
|
+
auditThemeContrast, failingContrastChecks, parseDtcgTheme, presetFromDtcg,
|
|
288
|
+
} from './theme-dtcg';
|
|
289
|
+
export type { ContrastCheck, DtcgIssue, DtcgTheme } from './theme-dtcg';
|
|
282
290
|
export { useExport } from './export-hooks.svelte';
|
|
283
291
|
export { snapshotExportTaskResult, downloadExportArtifact, safeArtifactUrl } from './export-format';
|
|
284
292
|
export type { ExportTaskResult } from './export-format';
|
package/src/schema-form.ts
CHANGED
|
@@ -3,12 +3,46 @@ import { Value } from 'typebox/value';
|
|
|
3
3
|
|
|
4
4
|
export type SchemaFormScalar = string | number | boolean | null;
|
|
5
5
|
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* 条件路径从表单根开始,只能引用无条件的标量字段。
|
|
8
|
+
* 组合器(all/any/not)与跨字段比较(equalsField)让联动表达力接近
|
|
9
|
+
* schema 驱动的表单方案,但仍不引入表达式求值。
|
|
10
|
+
*/
|
|
7
11
|
export interface SchemaFormCondition {
|
|
8
|
-
path
|
|
12
|
+
path?: readonly string[];
|
|
9
13
|
equals?: SchemaFormScalar;
|
|
10
14
|
notEquals?: SchemaFormScalar;
|
|
11
15
|
exists?: boolean;
|
|
16
|
+
/** 与另一字段的当前值比较(路径从表单根开始)。 */
|
|
17
|
+
equalsField?: readonly string[];
|
|
18
|
+
all?: readonly SchemaFormCondition[];
|
|
19
|
+
any?: readonly SchemaFormCondition[];
|
|
20
|
+
not?: SchemaFormCondition;
|
|
21
|
+
}
|
|
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
|
+
|
|
38
|
+
/** 封闭集合的派生规则;不编译表达式,避免把 schema 变成代码执行入口。 */
|
|
39
|
+
export type SchemaFormComputedOp='sum'|'count'|'first'|'concat';
|
|
40
|
+
|
|
41
|
+
export interface SchemaFormComputed {
|
|
42
|
+
from: readonly string[];
|
|
43
|
+
op: SchemaFormComputedOp;
|
|
44
|
+
/** 仅 `concat` 使用,最多 8 个字符。 */
|
|
45
|
+
separator?: string;
|
|
12
46
|
}
|
|
13
47
|
|
|
14
48
|
export interface SchemaFormSchema {
|
|
@@ -21,6 +55,8 @@ export interface SchemaFormSchema {
|
|
|
21
55
|
default?: unknown;
|
|
22
56
|
required?: string[];
|
|
23
57
|
visibleWhen?: SchemaFormCondition;
|
|
58
|
+
computed?: SchemaFormComputed;
|
|
59
|
+
layout?: SchemaFormLayout;
|
|
24
60
|
minLength?: number;
|
|
25
61
|
maxLength?: number;
|
|
26
62
|
pattern?: string;
|
|
@@ -32,14 +68,71 @@ export interface SchemaFormSchema {
|
|
|
32
68
|
|
|
33
69
|
const keys = new Set([
|
|
34
70
|
'type', 'title', 'description', 'properties', 'items', 'enum', 'default', 'required',
|
|
35
|
-
'visibleWhen', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems',
|
|
71
|
+
'visibleWhen', 'computed', 'layout', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems',
|
|
36
72
|
]);
|
|
73
|
+
const COMPUTED_OPS=new Set<SchemaFormComputedOp>(['sum','count','first','concat']);
|
|
74
|
+
const LAYOUT_TYPES=new Set<SchemaFormLayoutType>(['grid','section','steps']);
|
|
37
75
|
const scalar = (value: unknown): value is SchemaFormScalar => value === null ||
|
|
38
76
|
typeof value === 'string' || typeof value === 'boolean' ||
|
|
39
77
|
(typeof value === 'number' && Number.isFinite(value));
|
|
40
|
-
const fail = ()
|
|
78
|
+
const fail: () => never = () => { throw new TypeError('Invalid schema form configuration.'); };
|
|
79
|
+
|
|
80
|
+
/** 解析条件路径并断言它指向一个无条件标量字段。 */
|
|
81
|
+
function assertFieldPath(schema: SchemaFormSchema, parts: readonly string[]): void {
|
|
82
|
+
if (parts.length === 0 || parts.length > 32 || parts.some(part => part === '')) fail();
|
|
83
|
+
let controller: SchemaFormSchema=schema;
|
|
84
|
+
for (const part of parts) {
|
|
85
|
+
const properties=controller.properties;
|
|
86
|
+
if (!properties || controller.visibleWhen || !Object.hasOwn(properties, part)) fail();
|
|
87
|
+
const next=properties[part];
|
|
88
|
+
if (!next) fail();
|
|
89
|
+
controller=next;
|
|
90
|
+
}
|
|
91
|
+
if (controller.visibleWhen || controller.properties || controller.type === 'object' || controller.type === 'array') fail();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** 条件结构自校验:组合器与路径二选一,并限制递归深度。 */
|
|
95
|
+
function assertCondition(condition: SchemaFormCondition, root: SchemaFormSchema, depth: number): void {
|
|
96
|
+
if (!condition || typeof condition !== 'object' || Array.isArray(condition) || depth > 8) fail();
|
|
97
|
+
const allowed=['path','equals','notEquals','exists','equalsField','all','any','not'];
|
|
98
|
+
if (Object.keys(condition).some(key => !allowed.includes(key))) fail();
|
|
99
|
+
const combinators=['all','any','not'].filter(key => Object.hasOwn(condition, key));
|
|
100
|
+
const comparators=['equals','notEquals','exists','equalsField'].filter(key => Object.hasOwn(condition, key));
|
|
101
|
+
const hasPath=condition.path !== undefined;
|
|
102
|
+
if (combinators.length === 0 && !hasPath) fail();
|
|
103
|
+
if (combinators.length > 0 && (hasPath || comparators.length > 0)) fail();
|
|
104
|
+
if (combinators.length > 1) fail();
|
|
105
|
+
if (condition.path !== undefined &&
|
|
106
|
+
(!Array.isArray(condition.path) || condition.path.length === 0 || condition.path.length > 32 ||
|
|
107
|
+
condition.path.some(part => typeof part !== 'string' || part === ''))) fail();
|
|
108
|
+
if (condition.equalsField !== undefined &&
|
|
109
|
+
(!Array.isArray(condition.equalsField) || condition.equalsField.length === 0 ||
|
|
110
|
+
condition.equalsField.length > 32 || condition.equalsField.some(part => typeof part !== 'string' || part === ''))) fail();
|
|
111
|
+
if ((Object.hasOwn(condition, 'equals') && !scalar(condition.equals)) ||
|
|
112
|
+
(Object.hasOwn(condition, 'notEquals') && !scalar(condition.notEquals)) ||
|
|
113
|
+
(Object.hasOwn(condition, 'exists') && typeof condition.exists !== 'boolean')) fail();
|
|
114
|
+
if (condition.all !== undefined &&
|
|
115
|
+
(!Array.isArray(condition.all) || condition.all.length === 0 || condition.all.length > 16)) fail();
|
|
116
|
+
if (condition.any !== undefined &&
|
|
117
|
+
(!Array.isArray(condition.any) || condition.any.length === 0 || condition.any.length > 16)) fail();
|
|
118
|
+
if (condition.not !== undefined && (typeof condition.not !== 'object' || Array.isArray(condition.not))) fail();
|
|
119
|
+
for (const child of condition.all ?? []) assertCondition(child, root, depth + 1);
|
|
120
|
+
for (const child of condition.any ?? []) assertCondition(child, root, depth + 1);
|
|
121
|
+
if (condition.not !== undefined) assertCondition(condition.not, root, depth + 1);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** 条件路径必须指向无条件的标量字段(与 visibleWhen 的既有约束一致)。 */
|
|
125
|
+
function assertConditionPaths(condition: SchemaFormCondition, root: SchemaFormSchema): void {
|
|
126
|
+
if (condition.path !== undefined) assertFieldPath(root, condition.path);
|
|
127
|
+
if (condition.equalsField !== undefined) assertFieldPath(root, condition.equalsField);
|
|
128
|
+
for (const child of condition.all ?? []) assertConditionPaths(child, root);
|
|
129
|
+
for (const child of condition.any ?? []) assertConditionPaths(child, root);
|
|
130
|
+
if (condition.not !== undefined) assertConditionPaths(condition.not, root);
|
|
131
|
+
}
|
|
41
132
|
|
|
42
|
-
/**
|
|
133
|
+
/**
|
|
134
|
+
* Schema 来自可信宿主,但仍拒绝未知关键字、循环、错误约束和超限结构。
|
|
135
|
+
*/
|
|
43
136
|
export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
44
137
|
let visited = 0;
|
|
45
138
|
const active = new Set<object>();
|
|
@@ -52,7 +145,13 @@ export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
|
52
145
|
if (kind !== undefined && !['object', 'array', 'string', 'number', 'integer', 'boolean', 'null'].includes(kind)) fail();
|
|
53
146
|
if (node.properties !== undefined) {
|
|
54
147
|
if (kind !== 'object' || !node.properties || typeof node.properties !== 'object' || Array.isArray(node.properties)) fail();
|
|
55
|
-
|
|
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();
|
|
56
155
|
}
|
|
57
156
|
if (node.items !== undefined) {
|
|
58
157
|
if (kind !== 'array') fail();
|
|
@@ -80,22 +179,39 @@ export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
|
80
179
|
}
|
|
81
180
|
const condition = node.visibleWhen;
|
|
82
181
|
if (condition !== undefined) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
182
|
+
assertCondition(condition, schema, 0);
|
|
183
|
+
assertConditionPaths(condition, schema);
|
|
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();
|
|
97
200
|
}
|
|
98
|
-
if (
|
|
201
|
+
if (layout.type === 'grid' && layout.step !== undefined) fail();
|
|
202
|
+
}
|
|
203
|
+
const computed = node.computed;
|
|
204
|
+
if (computed !== undefined) {
|
|
205
|
+
if (!computed || typeof computed !== 'object' || Array.isArray(computed) ||
|
|
206
|
+
Object.keys(computed).some(key => !['from', 'op', 'separator'].includes(key)) ||
|
|
207
|
+
!Array.isArray(computed.from) || computed.from.length === 0 || computed.from.length > 32 ||
|
|
208
|
+
computed.from.some(part => typeof part !== 'string') ||
|
|
209
|
+
!COMPUTED_OPS.has(computed.op)) fail();
|
|
210
|
+
if (computed.separator !== undefined &&
|
|
211
|
+
(computed.op !== 'concat' || typeof computed.separator !== 'string' || computed.separator.length > 8)) fail();
|
|
212
|
+
// 派生字段是只读标量,写回对象/数组会让投影与校验产生二义性。
|
|
213
|
+
if (kind === 'object' || kind === 'array') fail();
|
|
214
|
+
for (const path of computed.from) assertFieldPath(schema, path.split('.'));
|
|
99
215
|
}
|
|
100
216
|
active.delete(node);
|
|
101
217
|
}
|
|
@@ -113,10 +229,16 @@ export function readSchemaFormPath(value: unknown, path: readonly string[]): unk
|
|
|
113
229
|
|
|
114
230
|
export function matchesSchemaFormCondition(condition: SchemaFormCondition | undefined, value: unknown): boolean {
|
|
115
231
|
if (!condition) return true;
|
|
232
|
+
if (condition.all !== undefined) return condition.all.every((child) => matchesSchemaFormCondition(child, value));
|
|
233
|
+
if (condition.any !== undefined) return condition.any.some((child) => matchesSchemaFormCondition(child, value));
|
|
234
|
+
if (condition.not !== undefined) return !matchesSchemaFormCondition(condition.not, value);
|
|
235
|
+
if (condition.path === undefined) return false;
|
|
116
236
|
const current = readSchemaFormPath(value, condition.path);
|
|
117
237
|
if (condition.exists !== undefined && (current !== undefined) !== condition.exists) return false;
|
|
118
238
|
if (Object.hasOwn(condition, 'equals') && !Object.is(current, condition.equals)) return false;
|
|
119
239
|
if (Object.hasOwn(condition, 'notEquals') && Object.is(current, condition.notEquals)) return false;
|
|
240
|
+
if (condition.equalsField !== undefined &&
|
|
241
|
+
!Object.is(current, readSchemaFormPath(value, condition.equalsField))) return false;
|
|
120
242
|
return true;
|
|
121
243
|
}
|
|
122
244
|
|
|
@@ -124,6 +246,106 @@ export function isSchemaFormNodeVisible(schema: SchemaFormSchema, rootValue: unk
|
|
|
124
246
|
return matchesSchemaFormCondition(schema.visibleWhen, rootValue);
|
|
125
247
|
}
|
|
126
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
|
+
|
|
127
349
|
export interface SchemaFormValidationError {
|
|
128
350
|
/** JSON 数组路径,不混淆字段名中的点、斜杠和数组索引。 */
|
|
129
351
|
path: string;
|
|
@@ -199,6 +421,64 @@ export function prepareSchemaFormValue(schema: SchemaFormSchema, value: unknown)
|
|
|
199
421
|
};
|
|
200
422
|
}
|
|
201
423
|
|
|
424
|
+
function readComputedSource(value: unknown, path: string): unknown {
|
|
425
|
+
return readSchemaFormPath(value, path.split('.'));
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
function computeSchemaFormNode(node: SchemaFormComputed, value: unknown): SchemaFormScalar {
|
|
429
|
+
const sources=node.from.map((path) => readComputedSource(value, path));
|
|
430
|
+
switch (node.op) {
|
|
431
|
+
case 'count': return sources.filter((entry) => entry !== undefined && entry !== null && entry !== '').length;
|
|
432
|
+
case 'sum': return sources.reduce<number>((total, entry) => {
|
|
433
|
+
const numeric=typeof entry === 'number' ? entry : typeof entry === 'string' ? Number(entry) : Number.NaN;
|
|
434
|
+
return Number.isFinite(numeric) ? total + numeric : total;
|
|
435
|
+
}, 0);
|
|
436
|
+
case 'first': {
|
|
437
|
+
const first=sources.find((entry) => scalar(entry));
|
|
438
|
+
return scalar(first) ? first : null;
|
|
439
|
+
}
|
|
440
|
+
case 'concat': {
|
|
441
|
+
const parts=sources.filter((entry): entry is string|number|boolean =>
|
|
442
|
+
typeof entry === 'string' || typeof entry === 'number' || typeof entry === 'boolean');
|
|
443
|
+
return parts.join(node.separator ?? '');
|
|
444
|
+
}
|
|
445
|
+
default: return null;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* 计算 `computed` 字段并返回新的表单值;不修改入参,也不参与写回校验。
|
|
451
|
+
* 派生值只用于展示与只读提交,宿主仍可覆盖。
|
|
452
|
+
*/
|
|
453
|
+
export function applySchemaFormComputed(schema: SchemaFormSchema, value: unknown): unknown {
|
|
454
|
+
assertSchemaFormSchema(schema);
|
|
455
|
+
let visited=0;
|
|
456
|
+
function visit(node: SchemaFormSchema, current: unknown): unknown {
|
|
457
|
+
if (++visited > 1000) throw new TypeError('Schema form data limit exceeded.');
|
|
458
|
+
if (node.properties && current !== null && typeof current === 'object' && !Array.isArray(current)) {
|
|
459
|
+
const source=current as Record<string, unknown>;
|
|
460
|
+
const result: Record<string, unknown>={ ...source };
|
|
461
|
+
for (const [key, child] of Object.entries(node.properties)) {
|
|
462
|
+
if (child.computed !== undefined) {
|
|
463
|
+
Object.defineProperty(result, key, {
|
|
464
|
+
value: computeSchemaFormNode(child.computed, value),
|
|
465
|
+
enumerable: true,
|
|
466
|
+
writable: true,
|
|
467
|
+
configurable: true,
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
if (Object.hasOwn(source, key)) {
|
|
471
|
+
Object.defineProperty(result, key, { value: visit(child, source[key]), enumerable: true, writable: true, configurable: true });
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
return result;
|
|
475
|
+
}
|
|
476
|
+
if (Array.isArray(current) && node.items) return current.map((item) => visit(node.items as SchemaFormSchema, item));
|
|
477
|
+
return current;
|
|
478
|
+
}
|
|
479
|
+
return visit(schema, value);
|
|
480
|
+
}
|
|
481
|
+
|
|
202
482
|
export function validateSchemaFormValue(schema: SchemaFormSchema, value: unknown): SchemaFormValidationError[] {
|
|
203
483
|
return prepareSchemaFormValue(schema, value).errors;
|
|
204
484
|
}
|
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/theme.svelte.ts
CHANGED
|
@@ -1,4 +1,11 @@
|
|
|
1
1
|
import { definedOptions } from './defined-options';
|
|
2
|
+
import {
|
|
3
|
+
deriveColorPreset,
|
|
4
|
+
exportThemeTokens,
|
|
5
|
+
parseThemeTokens,
|
|
6
|
+
type DerivedColorPreset,
|
|
7
|
+
type ThemeTokenDocument,
|
|
8
|
+
} from './color-scale';
|
|
2
9
|
// Theme — dark/light/system mode + color theme management (Svelte 5 runes)
|
|
3
10
|
//
|
|
4
11
|
// Supports two class strategies:
|
|
@@ -6,7 +13,9 @@ import { definedOptions } from './defined-options';
|
|
|
6
13
|
// - 'dark-first': adds 'light' class for light mode (dark-first)
|
|
7
14
|
|
|
8
15
|
export type ThemeMode='light'|'dark'|'system';
|
|
9
|
-
|
|
16
|
+
/** Built-in preset names keep editor autocomplete; registered presets are any string. */
|
|
17
|
+
export type BuiltinColorTheme='default'|'blue'|'green'|'rose'|'orange'|'violet'|'neutral'|'indigo'|'stripe';
|
|
18
|
+
export type ColorTheme=BuiltinColorTheme|(string&{});
|
|
10
19
|
|
|
11
20
|
/** Controls how the theme class is applied to <html> */
|
|
12
21
|
export type ThemeStrategy='standard'|'dark-first';
|
|
@@ -347,9 +356,10 @@ function readStoredTheme(): ThemeMode|undefined {
|
|
|
347
356
|
}
|
|
348
357
|
|
|
349
358
|
function readStoredColorTheme(): ColorTheme {
|
|
350
|
-
const stored=getStorage()?.getItem(COLOR_STORAGE_KEY);
|
|
351
|
-
//
|
|
352
|
-
|
|
359
|
+
const stored=getStorage()?.getItem(COLOR_STORAGE_KEY)?.trim();
|
|
360
|
+
// A registered preset may be re-created after this module loads, so any
|
|
361
|
+
// non-empty stored id stays authoritative; unknown ids fall back at apply time.
|
|
362
|
+
return stored? stored:'default';
|
|
353
363
|
}
|
|
354
364
|
|
|
355
365
|
function persistSelection(key: string,value: string): void {
|
|
@@ -582,6 +592,44 @@ export function unregisterThemeOwner(token: ThemeOwnerToken|undefined): void {
|
|
|
582
592
|
if(removed&&(isExplicitOwner(removed.options)||removed.options.fallbackThemeConfig)) applyEffectiveTheme();
|
|
583
593
|
}
|
|
584
594
|
|
|
595
|
+
/**
|
|
596
|
+
* Derive a full tonal palette from one brand color and register it.
|
|
597
|
+
* Mirrors the Arco `@arco-design/color` capability without a Less variable layer.
|
|
598
|
+
*/
|
|
599
|
+
export function registerColorTheme(input: { name: string; label?: string; color: string }): ColorPreset {
|
|
600
|
+
const derived=deriveColorPreset(input);
|
|
601
|
+
const preset: ColorPreset={
|
|
602
|
+
name: derived.name,
|
|
603
|
+
label: derived.label,
|
|
604
|
+
color: derived.color,
|
|
605
|
+
light: { ...derived.light },
|
|
606
|
+
dark: { ...derived.dark },
|
|
607
|
+
};
|
|
608
|
+
registerColorPreset(preset);
|
|
609
|
+
return preset;
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/** Serialize every registered preset (built-in + custom) as a portable document. */
|
|
613
|
+
export function exportColorThemes(): ThemeTokenDocument {
|
|
614
|
+
return exportThemeTokens(getColorPresets() as readonly DerivedColorPreset[]);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* Validate and register a token document. Invalid payloads throw before any
|
|
619
|
+
* preset is written, so importing never leaves the registry half-updated.
|
|
620
|
+
*/
|
|
621
|
+
export function importColorThemes(payload: unknown): ColorPreset[] {
|
|
622
|
+
const presets=parseThemeTokens(payload);
|
|
623
|
+
for(const preset of presets) registerColorPreset(preset);
|
|
624
|
+
return presets.map((preset) => ({
|
|
625
|
+
name: preset.name,
|
|
626
|
+
label: preset.label,
|
|
627
|
+
color: preset.color,
|
|
628
|
+
light: { ...preset.light },
|
|
629
|
+
dark: { ...preset.dark },
|
|
630
|
+
}));
|
|
631
|
+
}
|
|
632
|
+
|
|
585
633
|
export function resetTheme(): void {
|
|
586
634
|
selectedMode=readStoredTheme();
|
|
587
635
|
selectedColorTheme=readStoredColorTheme();
|
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 ───────────────────────────────────
|