@svadmin/core 0.72.0 → 0.73.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 +294 -0
- package/src/index.ts +4 -2
- package/src/schema-form.ts +160 -21
- package/src/theme.svelte.ts +52 -4
package/package.json
CHANGED
|
@@ -0,0 +1,294 @@
|
|
|
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
|
+
/** Pick the foreground with the higher contrast ratio (WCAG relative luminance). */
|
|
152
|
+
export function pickReadableForeground(backgroundHex: string): string {
|
|
153
|
+
return contrastRatio(backgroundHex, '#FFFFFF') >= contrastRatio(backgroundHex, '#111111')
|
|
154
|
+
? '#FFFFFF'
|
|
155
|
+
: '#111111';
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Derive a 10-step tonal scale from a brand color.
|
|
160
|
+
* Step 1 is the lightest tint, step 10 the darkest shade; hue is preserved.
|
|
161
|
+
*/
|
|
162
|
+
export function generateColorScale(color: string): ColorScaleStep[] {
|
|
163
|
+
const { c: baseChroma, h } = hexToOklch(color);
|
|
164
|
+
const lightest = 0.975;
|
|
165
|
+
const darkest = 0.26;
|
|
166
|
+
const steps: ColorScaleStep[] = [];
|
|
167
|
+
for (let step = 1; step <= 10; step += 1) {
|
|
168
|
+
const ratio = (step - 1) / 9;
|
|
169
|
+
const lightness = lightest - (lightest - darkest) * ratio;
|
|
170
|
+
// Chroma peaks in the mid tones so the endpoints stay near-neutral.
|
|
171
|
+
const chroma = baseChroma * (0.35 + 0.65 * Math.sin(Math.PI * (0.15 + 0.7 * ratio)));
|
|
172
|
+
const rgb = oklchToRgb(lightness, chroma, h);
|
|
173
|
+
steps.push({ step, value: formatOklch(lightness, chroma, h), hex: toHex(rgb) });
|
|
174
|
+
}
|
|
175
|
+
return steps;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function chartPalette(scale: ColorScaleStep[], hue: number, chroma: number, lightness: number): Record<string, string> {
|
|
179
|
+
const offsets = [0, 32, -32, 64, -64];
|
|
180
|
+
return Object.fromEntries(offsets.map((offset, index) => [
|
|
181
|
+
`--chart-${index + 1}`,
|
|
182
|
+
index === 0 ? scale[5]?.value as string : formatOklch(lightness, chroma, hue + offset),
|
|
183
|
+
]));
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Build light/dark CSS variable bundles for one brand color.
|
|
188
|
+
* Keys mirror the built-in presets so `registerColorPreset` can consume it.
|
|
189
|
+
*/
|
|
190
|
+
export function deriveColorPreset(input: { name: string; label?: string; color: string }): DerivedColorPreset {
|
|
191
|
+
const name = input.name?.trim();
|
|
192
|
+
if (!name) throw new TypeError('deriveColorPreset requires a non-empty name');
|
|
193
|
+
const color = input.color?.trim();
|
|
194
|
+
const source = hexToOklch(color);
|
|
195
|
+
const scale = generateColorScale(color);
|
|
196
|
+
const lightPrimary = scale[5] as ColorScaleStep;
|
|
197
|
+
const darkPrimary = scale[3] as ColorScaleStep;
|
|
198
|
+
const lightForeground = pickReadableForeground(lightPrimary.hex);
|
|
199
|
+
const darkForeground = pickReadableForeground(darkPrimary.hex);
|
|
200
|
+
|
|
201
|
+
return {
|
|
202
|
+
name,
|
|
203
|
+
label: input.label?.trim() || name,
|
|
204
|
+
color: color.toUpperCase(),
|
|
205
|
+
light: {
|
|
206
|
+
'--primary': lightPrimary.value,
|
|
207
|
+
'--primary-foreground': lightForeground,
|
|
208
|
+
'--ring': lightPrimary.value,
|
|
209
|
+
'--sidebar-primary': lightPrimary.value,
|
|
210
|
+
'--sidebar-primary-foreground': lightForeground,
|
|
211
|
+
'--sidebar-ring': lightPrimary.value,
|
|
212
|
+
...chartPalette(scale, source.h, source.c, source.l),
|
|
213
|
+
},
|
|
214
|
+
dark: {
|
|
215
|
+
'--primary': darkPrimary.value,
|
|
216
|
+
'--primary-foreground': darkForeground,
|
|
217
|
+
'--ring': scale[4]?.value as string,
|
|
218
|
+
'--sidebar-primary': darkPrimary.value,
|
|
219
|
+
'--sidebar-primary-foreground': darkForeground,
|
|
220
|
+
'--sidebar-ring': scale[4]?.value as string,
|
|
221
|
+
...chartPalette(scale, source.h, source.c * 1.05, Math.min(0.82, source.l + 0.12)),
|
|
222
|
+
},
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
function assertVariableMap(value: unknown, label: string): asserts value is Record<string, string> {
|
|
227
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
228
|
+
throw new TypeError(`${label} must be an object of CSS variable values`);
|
|
229
|
+
}
|
|
230
|
+
const entries = Object.entries(value);
|
|
231
|
+
if (entries.length === 0 || entries.length > MAX_VARIABLES) {
|
|
232
|
+
throw new TypeError(`${label} must declare between 1 and ${MAX_VARIABLES} variables`);
|
|
233
|
+
}
|
|
234
|
+
for (const [key, variable] of entries) {
|
|
235
|
+
if (!/^--[a-z0-9-]{1,64}$/i.test(key)) throw new TypeError(`${label} has an invalid CSS variable name: ${key}`);
|
|
236
|
+
if (typeof variable !== 'string' || variable.trim() === '' || variable.length > 200) {
|
|
237
|
+
throw new TypeError(`${label}.${key} must be a non-empty string`);
|
|
238
|
+
}
|
|
239
|
+
// Token exchange is a data contract: only color syntax, never arbitrary CSS.
|
|
240
|
+
if (!/^(?:oklch\(|#|rgb\(|hsl\(|var\(--)/i.test(variable.trim()) || /[;{}]/.test(variable)) {
|
|
241
|
+
throw new TypeError(`${label}.${key} is not a color token value: ${variable}`);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Serialize presets into a portable, versioned document. */
|
|
247
|
+
export function exportThemeTokens(presets: readonly DerivedColorPreset[]): ThemeTokenDocument {
|
|
248
|
+
return {
|
|
249
|
+
version: 1,
|
|
250
|
+
presets: presets.map((preset) => ({
|
|
251
|
+
name: preset.name,
|
|
252
|
+
label: preset.label,
|
|
253
|
+
color: preset.color,
|
|
254
|
+
light: { ...preset.light },
|
|
255
|
+
dark: { ...preset.dark },
|
|
256
|
+
})),
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Validate and clone a token document without mutating shared state. */
|
|
261
|
+
export function parseThemeTokens(payload: unknown): DerivedColorPreset[] {
|
|
262
|
+
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
|
|
263
|
+
throw new TypeError('Theme token document must be an object');
|
|
264
|
+
}
|
|
265
|
+
const document = payload as Partial<ThemeTokenDocument>;
|
|
266
|
+
if (document.version !== 1) throw new TypeError('Unsupported theme token document version; expected 1');
|
|
267
|
+
if (!Array.isArray(document.presets) || document.presets.length === 0 || document.presets.length > MAX_PRESETS) {
|
|
268
|
+
throw new TypeError(`Theme token document must declare between 1 and ${MAX_PRESETS} presets`);
|
|
269
|
+
}
|
|
270
|
+
const seen = new Set<string>();
|
|
271
|
+
return document.presets.map((raw, index) => {
|
|
272
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
273
|
+
throw new TypeError(`Theme token preset at index ${index} must be an object`);
|
|
274
|
+
}
|
|
275
|
+
const { name, label, color } = raw as Partial<DerivedColorPreset>;
|
|
276
|
+
if (typeof name !== 'string' || !/^[a-z][a-z0-9-]{0,31}$/.test(name)) {
|
|
277
|
+
throw new TypeError(`Theme token preset at index ${index} has an invalid name`);
|
|
278
|
+
}
|
|
279
|
+
if (seen.has(name)) throw new TypeError(`Duplicate theme token preset: ${name}`);
|
|
280
|
+
seen.add(name);
|
|
281
|
+
if (typeof color !== 'string' || !HEX_PATTERN.test(color.trim())) {
|
|
282
|
+
throw new TypeError(`Theme token preset "${name}" must declare a hex color`);
|
|
283
|
+
}
|
|
284
|
+
assertVariableMap(raw.light, `${name}.light`);
|
|
285
|
+
assertVariableMap(raw.dark, `${name}.dark`);
|
|
286
|
+
return {
|
|
287
|
+
name,
|
|
288
|
+
label: typeof label === 'string' && label.trim() !== '' ? label.trim().slice(0, 64) : name,
|
|
289
|
+
color: color.trim().toUpperCase(),
|
|
290
|
+
light: { ...raw.light },
|
|
291
|
+
dark: { ...raw.dark },
|
|
292
|
+
};
|
|
293
|
+
});
|
|
294
|
+
}
|
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, hexToOklch, 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';
|
package/src/schema-form.ts
CHANGED
|
@@ -3,12 +3,31 @@ 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
|
+
/** 封闭集合的派生规则;不编译表达式,避免把 schema 变成代码执行入口。 */
|
|
24
|
+
export type SchemaFormComputedOp='sum'|'count'|'first'|'concat';
|
|
25
|
+
|
|
26
|
+
export interface SchemaFormComputed {
|
|
27
|
+
from: readonly string[];
|
|
28
|
+
op: SchemaFormComputedOp;
|
|
29
|
+
/** 仅 `concat` 使用,最多 8 个字符。 */
|
|
30
|
+
separator?: string;
|
|
12
31
|
}
|
|
13
32
|
|
|
14
33
|
export interface SchemaFormSchema {
|
|
@@ -21,6 +40,7 @@ export interface SchemaFormSchema {
|
|
|
21
40
|
default?: unknown;
|
|
22
41
|
required?: string[];
|
|
23
42
|
visibleWhen?: SchemaFormCondition;
|
|
43
|
+
computed?: SchemaFormComputed;
|
|
24
44
|
minLength?: number;
|
|
25
45
|
maxLength?: number;
|
|
26
46
|
pattern?: string;
|
|
@@ -32,14 +52,70 @@ export interface SchemaFormSchema {
|
|
|
32
52
|
|
|
33
53
|
const keys = new Set([
|
|
34
54
|
'type', 'title', 'description', 'properties', 'items', 'enum', 'default', 'required',
|
|
35
|
-
'visibleWhen', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems',
|
|
55
|
+
'visibleWhen', 'computed', 'minLength', 'maxLength', 'pattern', 'minimum', 'maximum', 'minItems', 'maxItems',
|
|
36
56
|
]);
|
|
57
|
+
const COMPUTED_OPS=new Set<SchemaFormComputedOp>(['sum','count','first','concat']);
|
|
37
58
|
const scalar = (value: unknown): value is SchemaFormScalar => value === null ||
|
|
38
59
|
typeof value === 'string' || typeof value === 'boolean' ||
|
|
39
60
|
(typeof value === 'number' && Number.isFinite(value));
|
|
40
|
-
const fail = ()
|
|
61
|
+
const fail: () => never = () => { throw new TypeError('Invalid schema form configuration.'); };
|
|
62
|
+
|
|
63
|
+
/** 解析条件路径并断言它指向一个无条件标量字段。 */
|
|
64
|
+
function assertFieldPath(schema: SchemaFormSchema, parts: readonly string[]): void {
|
|
65
|
+
if (parts.length === 0 || parts.length > 32 || parts.some(part => part === '')) fail();
|
|
66
|
+
let controller: SchemaFormSchema=schema;
|
|
67
|
+
for (const part of parts) {
|
|
68
|
+
const properties=controller.properties;
|
|
69
|
+
if (!properties || controller.visibleWhen || !Object.hasOwn(properties, part)) fail();
|
|
70
|
+
const next=properties[part];
|
|
71
|
+
if (!next) fail();
|
|
72
|
+
controller=next;
|
|
73
|
+
}
|
|
74
|
+
if (controller.visibleWhen || controller.properties || controller.type === 'object' || controller.type === 'array') fail();
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 条件结构自校验:组合器与路径二选一,并限制递归深度。 */
|
|
78
|
+
function assertCondition(condition: SchemaFormCondition, root: SchemaFormSchema, depth: number): void {
|
|
79
|
+
if (!condition || typeof condition !== 'object' || Array.isArray(condition) || depth > 8) fail();
|
|
80
|
+
const allowed=['path','equals','notEquals','exists','equalsField','all','any','not'];
|
|
81
|
+
if (Object.keys(condition).some(key => !allowed.includes(key))) fail();
|
|
82
|
+
const combinators=['all','any','not'].filter(key => Object.hasOwn(condition, key));
|
|
83
|
+
const comparators=['equals','notEquals','exists','equalsField'].filter(key => Object.hasOwn(condition, key));
|
|
84
|
+
const hasPath=condition.path !== undefined;
|
|
85
|
+
if (combinators.length === 0 && !hasPath) fail();
|
|
86
|
+
if (combinators.length > 0 && (hasPath || comparators.length > 0)) fail();
|
|
87
|
+
if (combinators.length > 1) fail();
|
|
88
|
+
if (condition.path !== undefined &&
|
|
89
|
+
(!Array.isArray(condition.path) || condition.path.length === 0 || condition.path.length > 32 ||
|
|
90
|
+
condition.path.some(part => typeof part !== 'string' || part === ''))) fail();
|
|
91
|
+
if (condition.equalsField !== undefined &&
|
|
92
|
+
(!Array.isArray(condition.equalsField) || condition.equalsField.length === 0 ||
|
|
93
|
+
condition.equalsField.length > 32 || condition.equalsField.some(part => typeof part !== 'string' || part === ''))) fail();
|
|
94
|
+
if ((Object.hasOwn(condition, 'equals') && !scalar(condition.equals)) ||
|
|
95
|
+
(Object.hasOwn(condition, 'notEquals') && !scalar(condition.notEquals)) ||
|
|
96
|
+
(Object.hasOwn(condition, 'exists') && typeof condition.exists !== 'boolean')) fail();
|
|
97
|
+
if (condition.all !== undefined &&
|
|
98
|
+
(!Array.isArray(condition.all) || condition.all.length === 0 || condition.all.length > 16)) fail();
|
|
99
|
+
if (condition.any !== undefined &&
|
|
100
|
+
(!Array.isArray(condition.any) || condition.any.length === 0 || condition.any.length > 16)) fail();
|
|
101
|
+
if (condition.not !== undefined && (typeof condition.not !== 'object' || Array.isArray(condition.not))) fail();
|
|
102
|
+
for (const child of condition.all ?? []) assertCondition(child, root, depth + 1);
|
|
103
|
+
for (const child of condition.any ?? []) assertCondition(child, root, depth + 1);
|
|
104
|
+
if (condition.not !== undefined) assertCondition(condition.not, root, depth + 1);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 条件路径必须指向无条件的标量字段(与 visibleWhen 的既有约束一致)。 */
|
|
108
|
+
function assertConditionPaths(condition: SchemaFormCondition, root: SchemaFormSchema): void {
|
|
109
|
+
if (condition.path !== undefined) assertFieldPath(root, condition.path);
|
|
110
|
+
if (condition.equalsField !== undefined) assertFieldPath(root, condition.equalsField);
|
|
111
|
+
for (const child of condition.all ?? []) assertConditionPaths(child, root);
|
|
112
|
+
for (const child of condition.any ?? []) assertConditionPaths(child, root);
|
|
113
|
+
if (condition.not !== undefined) assertConditionPaths(condition.not, root);
|
|
114
|
+
}
|
|
41
115
|
|
|
42
|
-
/**
|
|
116
|
+
/**
|
|
117
|
+
* Schema 来自可信宿主,但仍拒绝未知关键字、循环、错误约束和超限结构。
|
|
118
|
+
*/
|
|
43
119
|
export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
44
120
|
let visited = 0;
|
|
45
121
|
const active = new Set<object>();
|
|
@@ -80,22 +156,21 @@ export function assertSchemaFormSchema(schema: SchemaFormSchema): void {
|
|
|
80
156
|
}
|
|
81
157
|
const condition = node.visibleWhen;
|
|
82
158
|
if (condition !== undefined) {
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
if (
|
|
89
|
-
|
|
90
|
-
(
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
if (controller.visibleWhen || controller.properties || controller.type === 'object' || controller.type === 'array') fail();
|
|
159
|
+
assertCondition(condition, schema, 0);
|
|
160
|
+
assertConditionPaths(condition, schema);
|
|
161
|
+
}
|
|
162
|
+
const computed = node.computed;
|
|
163
|
+
if (computed !== undefined) {
|
|
164
|
+
if (!computed || typeof computed !== 'object' || Array.isArray(computed) ||
|
|
165
|
+
Object.keys(computed).some(key => !['from', 'op', 'separator'].includes(key)) ||
|
|
166
|
+
!Array.isArray(computed.from) || computed.from.length === 0 || computed.from.length > 32 ||
|
|
167
|
+
computed.from.some(part => typeof part !== 'string') ||
|
|
168
|
+
!COMPUTED_OPS.has(computed.op)) fail();
|
|
169
|
+
if (computed.separator !== undefined &&
|
|
170
|
+
(computed.op !== 'concat' || typeof computed.separator !== 'string' || computed.separator.length > 8)) fail();
|
|
171
|
+
// 派生字段是只读标量,写回对象/数组会让投影与校验产生二义性。
|
|
172
|
+
if (kind === 'object' || kind === 'array') fail();
|
|
173
|
+
for (const path of computed.from) assertFieldPath(schema, path.split('.'));
|
|
99
174
|
}
|
|
100
175
|
active.delete(node);
|
|
101
176
|
}
|
|
@@ -113,10 +188,16 @@ export function readSchemaFormPath(value: unknown, path: readonly string[]): unk
|
|
|
113
188
|
|
|
114
189
|
export function matchesSchemaFormCondition(condition: SchemaFormCondition | undefined, value: unknown): boolean {
|
|
115
190
|
if (!condition) return true;
|
|
191
|
+
if (condition.all !== undefined) return condition.all.every((child) => matchesSchemaFormCondition(child, value));
|
|
192
|
+
if (condition.any !== undefined) return condition.any.some((child) => matchesSchemaFormCondition(child, value));
|
|
193
|
+
if (condition.not !== undefined) return !matchesSchemaFormCondition(condition.not, value);
|
|
194
|
+
if (condition.path === undefined) return false;
|
|
116
195
|
const current = readSchemaFormPath(value, condition.path);
|
|
117
196
|
if (condition.exists !== undefined && (current !== undefined) !== condition.exists) return false;
|
|
118
197
|
if (Object.hasOwn(condition, 'equals') && !Object.is(current, condition.equals)) return false;
|
|
119
198
|
if (Object.hasOwn(condition, 'notEquals') && Object.is(current, condition.notEquals)) return false;
|
|
199
|
+
if (condition.equalsField !== undefined &&
|
|
200
|
+
!Object.is(current, readSchemaFormPath(value, condition.equalsField))) return false;
|
|
120
201
|
return true;
|
|
121
202
|
}
|
|
122
203
|
|
|
@@ -199,6 +280,64 @@ export function prepareSchemaFormValue(schema: SchemaFormSchema, value: unknown)
|
|
|
199
280
|
};
|
|
200
281
|
}
|
|
201
282
|
|
|
283
|
+
function readComputedSource(value: unknown, path: string): unknown {
|
|
284
|
+
return readSchemaFormPath(value, path.split('.'));
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
function computeSchemaFormNode(node: SchemaFormComputed, value: unknown): SchemaFormScalar {
|
|
288
|
+
const sources=node.from.map((path) => readComputedSource(value, path));
|
|
289
|
+
switch (node.op) {
|
|
290
|
+
case 'count': return sources.filter((entry) => entry !== undefined && entry !== null && entry !== '').length;
|
|
291
|
+
case 'sum': return sources.reduce<number>((total, entry) => {
|
|
292
|
+
const numeric=typeof entry === 'number' ? entry : typeof entry === 'string' ? Number(entry) : Number.NaN;
|
|
293
|
+
return Number.isFinite(numeric) ? total + numeric : total;
|
|
294
|
+
}, 0);
|
|
295
|
+
case 'first': {
|
|
296
|
+
const first=sources.find((entry) => scalar(entry));
|
|
297
|
+
return scalar(first) ? first : null;
|
|
298
|
+
}
|
|
299
|
+
case 'concat': {
|
|
300
|
+
const parts=sources.filter((entry): entry is string|number|boolean =>
|
|
301
|
+
typeof entry === 'string' || typeof entry === 'number' || typeof entry === 'boolean');
|
|
302
|
+
return parts.join(node.separator ?? '');
|
|
303
|
+
}
|
|
304
|
+
default: return null;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* 计算 `computed` 字段并返回新的表单值;不修改入参,也不参与写回校验。
|
|
310
|
+
* 派生值只用于展示与只读提交,宿主仍可覆盖。
|
|
311
|
+
*/
|
|
312
|
+
export function applySchemaFormComputed(schema: SchemaFormSchema, value: unknown): unknown {
|
|
313
|
+
assertSchemaFormSchema(schema);
|
|
314
|
+
let visited=0;
|
|
315
|
+
function visit(node: SchemaFormSchema, current: unknown): unknown {
|
|
316
|
+
if (++visited > 1000) throw new TypeError('Schema form data limit exceeded.');
|
|
317
|
+
if (node.properties && current !== null && typeof current === 'object' && !Array.isArray(current)) {
|
|
318
|
+
const source=current as Record<string, unknown>;
|
|
319
|
+
const result: Record<string, unknown>={ ...source };
|
|
320
|
+
for (const [key, child] of Object.entries(node.properties)) {
|
|
321
|
+
if (child.computed !== undefined) {
|
|
322
|
+
Object.defineProperty(result, key, {
|
|
323
|
+
value: computeSchemaFormNode(child.computed, value),
|
|
324
|
+
enumerable: true,
|
|
325
|
+
writable: true,
|
|
326
|
+
configurable: true,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
if (Object.hasOwn(source, key)) {
|
|
330
|
+
Object.defineProperty(result, key, { value: visit(child, source[key]), enumerable: true, writable: true, configurable: true });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return result;
|
|
334
|
+
}
|
|
335
|
+
if (Array.isArray(current) && node.items) return current.map((item) => visit(node.items as SchemaFormSchema, item));
|
|
336
|
+
return current;
|
|
337
|
+
}
|
|
338
|
+
return visit(schema, value);
|
|
339
|
+
}
|
|
340
|
+
|
|
202
341
|
export function validateSchemaFormValue(schema: SchemaFormSchema, value: unknown): SchemaFormValidationError[] {
|
|
203
342
|
return prepareSchemaFormValue(schema, value).errors;
|
|
204
343
|
}
|
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();
|