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