soma-core 1.4.0 → 1.4.2

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.
Files changed (132) hide show
  1. package/README.md +1 -1
  2. package/core/build/blocks/block-compile.ts +31 -2
  3. package/core/build/blocks/block-container.ts +2 -11
  4. package/core/build/compiler/page-declaration-compiler.ts +30 -2
  5. package/core/build/compiler/soma-precompile.js +2053 -23
  6. package/core/build/component/component-graph.ts +208 -0
  7. package/core/build/component/package-loader.ts +32 -0
  8. package/core/build/eject/component-eject.ts +473 -0
  9. package/core/build/eject/component-upgrade.ts +359 -0
  10. package/core/build/layout/constraint-solver.ts +235 -0
  11. package/core/build/layout/css-emitter.ts +116 -0
  12. package/core/build/layout/page-layout.ts +85 -0
  13. package/core/build/pack/pack-init.ts +270 -0
  14. package/core/client/base/SomaHttpClient.ts +34 -1
  15. package/core/client/base/SomaPageRootBase.ts +61 -0
  16. package/core/client/component/ai-catalog.ts +121 -4
  17. package/core/client/component/component-defaults.ts +100 -0
  18. package/core/client/component/component-definition.types.ts +39 -0
  19. package/core/client/component/component-manager.ts +79 -4
  20. package/core/client/component/component-pack.ts +126 -2
  21. package/core/client/component/keyboard-matrix.ts +144 -0
  22. package/core/client/component/pack-styles.ts +59 -1
  23. package/core/client/component/style-features.ts +131 -0
  24. package/core/client/component/theme-component-tokens.ts +83 -0
  25. package/core/client/component/verify-pack.ts +120 -1
  26. package/core/client/container/SomaContainerAdapter.ts +6 -2
  27. package/core/client/data/data-object-resolver.ts +407 -4
  28. package/core/client/data/reaction-engine.ts +176 -0
  29. package/core/client/data/window-engine.ts +477 -0
  30. package/core/client/engine/event-engine.ts +98 -0
  31. package/core/client/engine/soma-bootstrap.ts +265 -5
  32. package/core/client/engine/step-runner.ts +134 -0
  33. package/core/client/infra/http/SomaHttpService.ts +2 -2
  34. package/core/client/parser/blocks/page-parser.ts +15 -1
  35. package/core/client/parser/blocks/use-parser.ts +5 -12
  36. package/core/client/parser/data-config-parser.ts +316 -8
  37. package/core/client/parser/duration.ts +16 -0
  38. package/core/client/parser/layout-parser.ts +157 -0
  39. package/core/client/parser/page-state-parser.ts +166 -0
  40. package/core/client/parser/pipeline-parser.ts +76 -1
  41. package/core/client/parser/reaction-parser.ts +459 -0
  42. package/core/client/parser/reaction-sugar.ts +47 -0
  43. package/core/client/parser/step-parser.ts +359 -0
  44. package/core/client/parser/ui-config-parser.ts +59 -0
  45. package/core/client/parser/window-parser.ts +294 -0
  46. package/core/client/theme/theme-engine.ts +102 -2
  47. package/core/index.ts +184 -0
  48. package/core/shared/block-errors.ts +11 -0
  49. package/core/shared/calc/coerce.ts +29 -0
  50. package/core/shared/calc/errors.ts +43 -0
  51. package/core/shared/calc/evaluator.ts +101 -0
  52. package/core/shared/calc/index.ts +12 -0
  53. package/core/shared/calc/lexer.ts +194 -0
  54. package/core/shared/calc/parser.ts +204 -0
  55. package/core/shared/calc/typer.ts +184 -0
  56. package/core/shared/component/derive-sample.ts +105 -0
  57. package/core/shared/component/field-lines.ts +473 -0
  58. package/core/shared/path-algebra.ts +169 -0
  59. package/core/shared/predicates/index.ts +527 -0
  60. package/core/shared/types/component-contract.types.ts +151 -9
  61. package/core/shared/types/data-config.types.ts +120 -1
  62. package/core/shared/types/domain.types.ts +13 -0
  63. package/core/shared/types/event.types.ts +22 -2
  64. package/core/shared/types/layout-constraint.types.ts +73 -0
  65. package/core/shared/types/page-state.types.ts +60 -0
  66. package/core/shared/types/reaction.types.ts +144 -0
  67. package/core/shared/types/step.types.ts +91 -0
  68. package/core/shared/types/ui-config.types.ts +18 -0
  69. package/core/shared/types/window.types.ts +177 -0
  70. package/dist/cli/soma.js +13 -1
  71. package/dist/core/index.cjs +5529 -631
  72. package/dist/types/build/blocks/block-container.d.ts +1 -6
  73. package/dist/types/build/compiler/page-declaration-compiler.d.ts +2 -0
  74. package/dist/types/build/component/component-graph.d.ts +85 -0
  75. package/dist/types/build/eject/component-eject.d.ts +121 -0
  76. package/dist/types/build/eject/component-upgrade.d.ts +43 -0
  77. package/dist/types/build/layout/constraint-solver.d.ts +36 -0
  78. package/dist/types/build/layout/css-emitter.d.ts +18 -0
  79. package/dist/types/build/layout/page-layout.d.ts +24 -0
  80. package/dist/types/build/pack/pack-init.d.ts +8 -0
  81. package/dist/types/client/base/SomaHttpClient.d.ts +8 -0
  82. package/dist/types/client/base/SomaPageRootBase.d.ts +28 -0
  83. package/dist/types/client/component/ai-catalog.d.ts +33 -1
  84. package/dist/types/client/component/component-defaults.d.ts +15 -0
  85. package/dist/types/client/component/component-definition.types.d.ts +38 -0
  86. package/dist/types/client/component/component-manager.d.ts +36 -0
  87. package/dist/types/client/component/component-pack.d.ts +32 -2
  88. package/dist/types/client/component/keyboard-matrix.d.ts +24 -0
  89. package/dist/types/client/component/pack-styles.d.ts +21 -0
  90. package/dist/types/client/component/style-features.d.ts +26 -0
  91. package/dist/types/client/component/theme-component-tokens.d.ts +14 -0
  92. package/dist/types/client/component/verify-pack.d.ts +10 -0
  93. package/dist/types/client/data/data-object-resolver.d.ts +106 -1
  94. package/dist/types/client/data/reaction-engine.d.ts +21 -0
  95. package/dist/types/client/data/window-engine.d.ts +27 -0
  96. package/dist/types/client/engine/event-engine.d.ts +15 -0
  97. package/dist/types/client/engine/soma-bootstrap.d.ts +70 -0
  98. package/dist/types/client/engine/step-runner.d.ts +24 -0
  99. package/dist/types/client/parser/blocks/use-parser.d.ts +2 -2
  100. package/dist/types/client/parser/duration.d.ts +1 -0
  101. package/dist/types/client/parser/layout-parser.d.ts +9 -0
  102. package/dist/types/client/parser/page-state-parser.d.ts +32 -0
  103. package/dist/types/client/parser/reaction-parser.d.ts +16 -0
  104. package/dist/types/client/parser/reaction-sugar.d.ts +13 -0
  105. package/dist/types/client/parser/step-parser.d.ts +23 -0
  106. package/dist/types/client/parser/ui-config-parser.d.ts +5 -0
  107. package/dist/types/client/parser/window-parser.d.ts +25 -0
  108. package/dist/types/client/theme/theme-engine.d.ts +26 -0
  109. package/dist/types/index.d.ts +35 -2
  110. package/dist/types/shared/block-errors.d.ts +5 -0
  111. package/dist/types/shared/calc/coerce.d.ts +4 -0
  112. package/dist/types/shared/calc/errors.d.ts +14 -0
  113. package/dist/types/shared/calc/evaluator.d.ts +2 -0
  114. package/dist/types/shared/calc/index.d.ts +6 -0
  115. package/dist/types/shared/calc/lexer.d.ts +20 -0
  116. package/dist/types/shared/calc/parser.d.ts +49 -0
  117. package/dist/types/shared/calc/typer.d.ts +16 -0
  118. package/dist/types/shared/component/derive-sample.d.ts +23 -0
  119. package/dist/types/shared/component/field-lines.d.ts +19 -0
  120. package/dist/types/shared/path-algebra.d.ts +56 -0
  121. package/dist/types/shared/predicates/index.d.ts +79 -0
  122. package/dist/types/shared/types/component-contract.types.d.ts +134 -6
  123. package/dist/types/shared/types/data-config.types.d.ts +115 -1
  124. package/dist/types/shared/types/domain.types.d.ts +12 -0
  125. package/dist/types/shared/types/event.types.d.ts +8 -2
  126. package/dist/types/shared/types/layout-constraint.types.d.ts +52 -0
  127. package/dist/types/shared/types/page-state.types.d.ts +49 -0
  128. package/dist/types/shared/types/reaction.types.d.ts +115 -0
  129. package/dist/types/shared/types/step.types.d.ts +76 -0
  130. package/dist/types/shared/types/ui-config.types.d.ts +18 -0
  131. package/dist/types/shared/types/window.types.d.ts +171 -0
  132. package/package.json +3 -2
@@ -26,6 +26,7 @@ import type { SomaComponentDefinition } from './component-definition.types';
26
26
  import { generateAiCatalog, type SomaAiCatalog } from './ai-catalog';
27
27
  import { attachPackStyles } from './pack-styles';
28
28
  import { checkOverrideCompat } from './contract-compat';
29
+ import { componentTokenPrefix } from '../../shared/types/component-contract.types';
29
30
 
30
31
  /** 包标识:小写字母/数字/连字符——冲突报错与来源登记都用它 */
31
32
  export const PACK_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
@@ -39,6 +40,20 @@ export interface SomaComponentPackStyles {
39
40
  deps?: Record<string, string[]>;
40
41
  /** 包级基座 CSS(恒定注入;克制使用——它是每个页面首屏都要付的钱) */
41
42
  base?: string;
43
+ /**
44
+ * 样式补丁(REQ-009 M-4):给**别的包**的组件追加 CSS。
45
+ *
46
+ * 解决的是「官方组件 90% 合适、改 10%」——此前这类诉求只有整组件覆盖一条路,
47
+ * 为了挪一处间距就要接手整个组件的维护。补丁在目标组件分片与其特性分片**之后**注入。
48
+ *
49
+ * 四条硬规矩(compose 期判定,见 collectPatches):
50
+ * ① 目标必须属于别的包(本包组件直接改分片,不需要补丁);
51
+ * ② 每条规则的首选择器必须以 `.soma-<组件名 kebab>` 开头——
52
+ * 补丁只能改目标组件内部,不能顺手改页面;
53
+ * ③ ≤ 1,200 字节(超了说明该 eject 或该覆盖,不该是补丁);
54
+ * ④ 能用组件令牌调的(圆角/高度/颜色)走令牌,不给补丁。
55
+ */
56
+ patches?: Record<string, string>;
42
57
  }
43
58
 
44
59
  export interface SomaComponentPack {
@@ -103,8 +118,8 @@ export interface ComposedComponentPacks {
103
118
  components: Record<string, SomaComponentDefinition>;
104
119
  /** 组件名 → 来源包名。排障、目录展示、闸门报错都用它 */
105
120
  provenance: Record<string, string>;
106
- /** 合成后的按需装配样式(键已按包做过冲突检查) */
107
- styles: Required<Omit<SomaComponentPackStyles, 'base'>> & { base: string[] };
121
+ /** 合成后的按需装配样式(键已按包做过冲突检查)。补丁不在这里,它有自己的顶层字段 */
122
+ styles: Required<Omit<SomaComponentPackStyles, 'base' | 'patches'>> & { base: string[] };
108
123
  /** 参与合成的包(顺序保留;目录生成用) */
109
124
  packs: SomaComponentPack[];
110
125
  /** 被显式覆盖的组件名 → { 胜出包, 被盖掉的包, 覆盖来源 } */
@@ -113,8 +128,13 @@ export interface ComposedComponentPacks {
113
128
  shadowed: string[];
114
129
  source: 'contract' | 'allowOverride';
115
130
  }>;
131
+ /** 生效的样式补丁(M-4):谁给谁打了什么。目录条目据此标注「被 X 包打了补丁」 */
132
+ patches: Array<{ target: string; patchedBy: string; css: string }>;
116
133
  }
117
134
 
135
+ /** 单条补丁的字节上限:超了说明该 eject 或该整包覆盖,不该是补丁 */
136
+ export const PACK_PATCH_BYTE_LIMIT = 1200;
137
+
118
138
  function assertPack(pack: SomaComponentPack): void {
119
139
  if (!pack || typeof pack !== 'object') {
120
140
  throw new ComponentPackError('组件包必须是对象');
@@ -228,6 +248,7 @@ export function composeComponentPacks(
228
248
  styles: composeStyles(packs, provenance),
229
249
  packs: [...packs],
230
250
  overrides,
251
+ patches: collectPatches(packs, provenance),
231
252
  };
232
253
  if (options.lazyStyles === false) return composed;
233
254
  return {
@@ -406,6 +427,109 @@ function composeStyles(
406
427
  return { components, shared, deps, base };
407
428
  }
408
429
 
430
+ /**
431
+ * 收集样式补丁(M-4)并逐条过闸门。
432
+ *
433
+ * 为什么全部在合成期判定而不是注入期:注入发生在浏览器里、在某个页面第一次用到
434
+ * 那个组件的时候——那时报错既晚又难归因。合成期是包与包相遇的唯一时刻,
435
+ * 也是「谁能给谁打补丁」唯一说得清的时刻。
436
+ */
437
+ function collectPatches(
438
+ packs: readonly SomaComponentPack[],
439
+ provenance: Record<string, string>,
440
+ ): ComposedComponentPacks['patches'] {
441
+ const patches: ComposedComponentPacks['patches'] = [];
442
+
443
+ for (const pack of packs) {
444
+ for (const [target, css] of Object.entries(pack.styles?.patches ?? {})) {
445
+ const owner = provenance[target];
446
+ if (owner === undefined) {
447
+ throw new ComponentPackError(
448
+ `包 "${pack.name}" 的样式补丁指向组件 "${target}",但本次合成里没有这个组件。`
449
+ + '\n 补丁指向不存在的组件时永远不会生效,而页面只是"看起来没改动"——所以这里拒绝',
450
+ );
451
+ }
452
+ if (owner === pack.name) {
453
+ throw new ComponentPackError(
454
+ `包 "${pack.name}" 给自己的组件 "${target}" 打补丁——`
455
+ + '本包组件请直接改它的样式分片,补丁通道是给跨包微调用的',
456
+ );
457
+ }
458
+ const bytes = byteLengthOf(css);
459
+ if (bytes > PACK_PATCH_BYTE_LIMIT) {
460
+ throw new ComponentPackError(
461
+ `包 "${pack.name}" 给 "${target}" 的补丁有 ${bytes} 字节,超过上限 ${PACK_PATCH_BYTE_LIMIT}。`
462
+ + '\n 补丁是"改 10%"的通道;要改的比这更多,正确的路是 soma component eject 或整包覆盖',
463
+ );
464
+ }
465
+ const stray = findStraySelector(css, target);
466
+ if (stray) {
467
+ throw new ComponentPackError(
468
+ `包 "${pack.name}" 给 "${target}" 的补丁里有越界选择器:${stray}。`
469
+ + `\n 每条规则的首选择器必须以 ".soma-${componentTokenPrefix(target)}" 开头——`
470
+ + '补丁只能改目标组件内部,不能顺手改页面上别的东西',
471
+ );
472
+ }
473
+ patches.push({ target, patchedBy: pack.name, css });
474
+ }
475
+ }
476
+ return patches;
477
+ }
478
+
479
+ function byteLengthOf(text: string): number {
480
+ return typeof TextEncoder === 'undefined'
481
+ ? Buffer.byteLength(text, 'utf8')
482
+ : new TextEncoder().encode(text).length;
483
+ }
484
+
485
+ /**
486
+ * 找出补丁里第一条不以目标组件根类开头的规则。
487
+ *
488
+ * 只做静态扫描(去注释 → 按顶层 `}` 切规则 → 取选择器列表),不解析完整 CSS:
489
+ * 目的是拦住"顺手改页面"这类越界,不是实现一个 CSS parser。
490
+ * `@media` / `@supports` 这类块级 at 规则递归进去看里面的规则。
491
+ */
492
+ export function findStraySelector(css: string, target: string): string | null {
493
+ const prefix = `.soma-${componentTokenPrefix(target)}`;
494
+ const cleaned = css.replace(/\/\*[\s\S]*?\*\//g, '');
495
+ let depth = 0;
496
+ let buffer = '';
497
+ for (const char of cleaned) {
498
+ if (char === '{') {
499
+ depth += 1;
500
+ if (depth === 1) {
501
+ const selectorText = buffer.trim();
502
+ buffer = '';
503
+ if (!selectorText) continue;
504
+ if (selectorText.startsWith('@')) {
505
+ // 块级 at 规则:里面的规则继续受同一条约束,交给下一轮 depth 计数处理
506
+ if (/^@(media|supports|container|layer)\b/.test(selectorText)) {
507
+ depth -= 1;
508
+ continue;
509
+ }
510
+ // @keyframes 之类:整块跳过(内部是百分比选择器,不是组件锚点)
511
+ continue;
512
+ }
513
+ for (const selector of selectorText.split(',')) {
514
+ const trimmed = selector.trim();
515
+ if (!trimmed) continue;
516
+ if (!trimmed.startsWith(prefix)) return trimmed;
517
+ }
518
+ continue;
519
+ }
520
+ buffer = '';
521
+ continue;
522
+ }
523
+ if (char === '}') {
524
+ depth = Math.max(0, depth - 1);
525
+ buffer = '';
526
+ continue;
527
+ }
528
+ if (depth === 0) buffer += char;
529
+ }
530
+ return null;
531
+ }
532
+
409
533
  /**
410
534
  * 生成带来源标注的组件目录。
411
535
  *
@@ -0,0 +1,144 @@
1
+ // 键盘矩阵(REQ-011 / IK-2)——契约 `keyboard:` 段 → 「按哪个键做什么」的唯一答案。
2
+ //
3
+ // ── 为什么它必须是一个函数而不是一张手写表 ──────────────────────────────
4
+ // 「声明 → 接线 → 文档 → 测试」四者同源,靠的是三个消费者读**同一个函数**:
5
+ // · soma-ui 的 keyboard-wiring 按它派发按键(接线);
6
+ // · ai-catalog 按它渲染目录里的键盘表(文档);
7
+ // · 闸门按它逐键真按并断言落点(测试)。
8
+ // 任何一处改成手抄,就会出现"目录说 Home 到首项、实际按了没反应"——而且没人会发现,
9
+ // 因为目录与实现各自看起来都对。React Aria 新站删掉了全部键盘表、键位真相只在源码里,
10
+ // 正是同一种漂移的终点。
11
+
12
+ import type { SomaContractKeyboard } from '../../shared/types/component-contract.types';
13
+
14
+ /** 引擎能兑现的意图闭集;矩阵里的每个键都落在这里面 */
15
+ export const SOMA_KEYBOARD_INTENTS = [
16
+ 'next', 'previous', 'left', 'right',
17
+ 'first', 'last', 'page_next', 'page_previous',
18
+ 'expand', 'collapse',
19
+ 'activate', 'toggle_select', 'search',
20
+ ] as const;
21
+ export type SomaKeyboardIntent = (typeof SOMA_KEYBOARD_INTENTS)[number];
22
+
23
+ export interface SomaKeyboardMatrixRow {
24
+ /** 触发这个意图的按键(`KeyboardEvent.key` 值);多个键同义时并列 */
25
+ keys: string[];
26
+ intent: SomaKeyboardIntent;
27
+ /** 给目录看的一句话 */
28
+ desc: string;
29
+ }
30
+
31
+ const INTENT_DESC: Record<SomaKeyboardIntent, string> = {
32
+ next: '下一项',
33
+ previous: '上一项',
34
+ left: '左一格',
35
+ right: '右一格',
36
+ first: '首项',
37
+ last: '末项',
38
+ page_next: '下翻一页',
39
+ page_previous: '上翻一页',
40
+ expand: '展开(已展开则进入第一个子级)',
41
+ collapse: '收起(已收起则回到父级)',
42
+ activate: '激活当前项',
43
+ toggle_select: '勾选 / 取消当前项',
44
+ search: '首字母跳转',
45
+ };
46
+
47
+ /**
48
+ * 由契约推出矩阵。纯函数、无 DOM:目录构建(Node)与浏览器接线读同一份。
49
+ *
50
+ * `layout: none` 出空表——这是"我不接管键盘"的显式声明,不是缺省。
51
+ */
52
+ export function deriveKeyboardMatrix(keyboard: SomaContractKeyboard): SomaKeyboardMatrixRow[] {
53
+ if (keyboard.layout === 'none') return [];
54
+ const rows: SomaKeyboardMatrixRow[] = [];
55
+ const horizontal = keyboard.layout !== 'grid' && keyboard.orientation === 'horizontal';
56
+
57
+ if (keyboard.layout === 'grid') {
58
+ rows.push({ keys: ['ArrowDown'], intent: 'next', desc: '下一行同列' });
59
+ rows.push({ keys: ['ArrowUp'], intent: 'previous', desc: '上一行同列' });
60
+ rows.push({ keys: ['ArrowRight'], intent: 'right', desc: INTENT_DESC.right });
61
+ rows.push({ keys: ['ArrowLeft'], intent: 'left', desc: INTENT_DESC.left });
62
+ } else if (horizontal) {
63
+ rows.push({ keys: ['ArrowRight'], intent: 'next', desc: `${INTENT_DESC.next}(RTL 下换向)` });
64
+ rows.push({ keys: ['ArrowLeft'], intent: 'previous', desc: `${INTENT_DESC.previous}(RTL 下换向)` });
65
+ } else if (keyboard.layout !== 'tree' && keyboard.orientation === 'both') {
66
+ rows.push({ keys: ['ArrowDown', 'ArrowRight'], intent: 'next', desc: `${INTENT_DESC.next}(→ 在 RTL 下换向)` });
67
+ rows.push({ keys: ['ArrowUp', 'ArrowLeft'], intent: 'previous', desc: `${INTENT_DESC.previous}(← 在 RTL 下换向)` });
68
+ } else {
69
+ rows.push({ keys: ['ArrowDown'], intent: 'next', desc: INTENT_DESC.next });
70
+ rows.push({ keys: ['ArrowUp'], intent: 'previous', desc: INTENT_DESC.previous });
71
+ if (keyboard.layout === 'tree') {
72
+ rows.push({ keys: ['ArrowRight'], intent: 'expand', desc: `${INTENT_DESC.expand}(RTL 下换向)` });
73
+ rows.push({ keys: ['ArrowLeft'], intent: 'collapse', desc: `${INTENT_DESC.collapse}(RTL 下换向)` });
74
+ }
75
+ }
76
+
77
+ rows.push({ keys: ['Home'], intent: 'first', desc: INTENT_DESC.first });
78
+ rows.push({ keys: ['End'], intent: 'last', desc: INTENT_DESC.last });
79
+ // 横向列表不翻页:一行选项卡没有"页"可翻,把 PageDown 吞掉只会挡住页面滚动
80
+ if (!horizontal) {
81
+ rows.push({ keys: ['PageDown'], intent: 'page_next', desc: INTENT_DESC.page_next });
82
+ rows.push({ keys: ['PageUp'], intent: 'page_previous', desc: INTENT_DESC.page_previous });
83
+ }
84
+
85
+ if (keyboard.space === 'toggle_select') {
86
+ rows.push({ keys: ['Enter'], intent: 'activate', desc: INTENT_DESC.activate });
87
+ rows.push({ keys: [' '], intent: 'toggle_select', desc: INTENT_DESC.toggle_select });
88
+ } else if (keyboard.space === 'none') {
89
+ // 空格不进表:它归触发器(原生 button 的"按下")。印上去等于替组件承诺一件它不做的事
90
+ rows.push({ keys: ['Enter'], intent: 'activate', desc: INTENT_DESC.activate });
91
+ } else {
92
+ rows.push({ keys: ['Enter', ' '], intent: 'activate', desc: INTENT_DESC.activate });
93
+ }
94
+
95
+ if (keyboard.typeahead === true) {
96
+ rows.push({ keys: ['<字符>'], intent: 'search', desc: `${INTENT_DESC.search}(1 秒内连打为前缀)` });
97
+ }
98
+ return rows;
99
+ }
100
+
101
+ const LAYOUT_LABEL: Record<SomaContractKeyboard['layout'], string> = {
102
+ list: '列表', grid: '网格', tree: '树', none: '不接管',
103
+ };
104
+
105
+ function keyLabel(key: string): string {
106
+ switch (key) {
107
+ case 'ArrowDown': return '↓';
108
+ case 'ArrowUp': return '↑';
109
+ case 'ArrowLeft': return '←';
110
+ case 'ArrowRight': return '→';
111
+ case ' ': return 'Space';
112
+ default: return key;
113
+ }
114
+ }
115
+
116
+ /**
117
+ * 目录用的一行紧凑键盘表。
118
+ *
119
+ * 一行而不是一张表:目录会被压成裸文本喂给模型,且每个分片有字节预算;
120
+ * 键盘表是"查得到"的信息,不是"读一遍"的信息。
121
+ */
122
+ export function renderKeyboardMatrixLine(keyboard: SomaContractKeyboard): string {
123
+ const rows = deriveKeyboardMatrix(keyboard);
124
+ const traits: string[] = [LAYOUT_LABEL[keyboard.layout]];
125
+ if (keyboard.layout !== 'none') {
126
+ if (keyboard.layout !== 'grid') {
127
+ traits.push(keyboard.orientation === 'horizontal' ? '横向' : keyboard.orientation === 'both' ? '双向' : '纵向');
128
+ }
129
+ traits.push(keyboard.wrap === true ? '到边回绕' : '到边停住');
130
+ if (keyboard.selection_follows_focus === true) traits.push('选中随焦点');
131
+ if (keyboard.focus_model === 'activedescendant') traits.push('aria-activedescendant');
132
+ }
133
+ // 组件特有键:与矩阵某一键同名时**替换**那一行的说明(Enter 在穿梭框里是"搬运"),
134
+ // 否则追加。同一个键印两行说明,读的人不知道该信哪一行。
135
+ const extra = new Map(Object.entries(keyboard.extra ?? {}));
136
+ const parts = rows.map((row) => {
137
+ const label = row.keys.map(keyLabel).join('/');
138
+ const override = extra.get(label);
139
+ if (override !== undefined) extra.delete(label);
140
+ return `${label} ${override ?? row.desc}`;
141
+ });
142
+ for (const [key, desc] of extra) parts.push(`${key} ${desc}`);
143
+ return `键盘(${traits.join('·')}):${parts.join(';')}`;
144
+ }
@@ -15,10 +15,28 @@
15
15
  // 这样热更新重复执行也不会堆出十几张同样的 <style>)。
16
16
 
17
17
  import type { SomaComponentDefinition } from './component-definition.types';
18
+ import type { SomaComponentContract } from '../../shared/types/component-contract.types';
19
+ import { componentTokenPrefix, componentTokenVar } from '../../shared/types/component-contract.types';
18
20
  import type { ComposedComponentPacks } from './component-pack';
19
21
 
20
22
  const injected = new Set<string>();
21
23
 
24
+ /**
25
+ * 组件令牌规则(M-1):把契约声明的可调旋钮写成一条挂在组件根类上的规则。
26
+ *
27
+ * 为什么是规则不是内联样式:一个组件一条,与实例数无关;
28
+ * 且 `ThemeScope` 或主题 `components` 段写出的 `--soma-<comp>-*` 层级更高,
29
+ * 靠 CSS 级联天然覆盖,不需要引擎逐实例改写。
30
+ */
31
+ export function renderComponentTokenRule(contract: SomaComponentContract): string {
32
+ const tokens = contract.tokens;
33
+ if (!tokens || Object.keys(tokens).length === 0) return '';
34
+ const decls = Object.entries(tokens)
35
+ .map(([key, token]) => `${componentTokenVar(contract.name, key)}:${token.default};`)
36
+ .join('');
37
+ return `.soma-${componentTokenPrefix(contract.name)}{${decls}}`;
38
+ }
39
+
22
40
  export interface PackStyleOptions {
23
41
  /** CSP nonce;宿主启用严格 CSP 时必须给 */
24
42
  nonce?: string | null;
@@ -29,6 +47,14 @@ export function resetPackStyleInjection(): void {
29
47
  injected.clear();
30
48
  }
31
49
 
50
+ /**
51
+ * 幂等注入一段 CSS(组件分片、特性分片与页面级布局产物共用同一个入口)。
52
+ * 同一个 key 只落一张 <style>;热更新重复执行不会堆出十几张同样的样式表。
53
+ */
54
+ export function injectStyleOnce(key: string, css: string, options: PackStyleOptions): void {
55
+ injectOnce(key, css, options);
56
+ }
57
+
32
58
  function injectOnce(key: string, css: string, options: PackStyleOptions): void {
33
59
  if (!css.trim() || injected.has(key)) return;
34
60
  if (typeof document === 'undefined') return;
@@ -56,10 +82,19 @@ export function attachPackStyles(
56
82
  const { components, styles } = composed;
57
83
  const result: Record<string, SomaComponentDefinition> = {};
58
84
 
85
+ const patchesByTarget = new Map<string, Array<{ patchedBy: string; css: string }>>();
86
+ for (const patch of composed.patches ?? []) {
87
+ const list = patchesByTarget.get(patch.target) ?? [];
88
+ list.push({ patchedBy: patch.patchedBy, css: patch.css });
89
+ patchesByTarget.set(patch.target, list);
90
+ }
91
+
59
92
  for (const [name, definition] of Object.entries(components) as Array<[string, SomaComponentDefinition]>) {
60
93
  const own = styles.components[name];
61
94
  const deps = styles.deps[name] ?? [];
62
- if (!own && deps.length === 0) {
95
+ const tokenRule = renderComponentTokenRule(definition.contract);
96
+ const patches = patchesByTarget.get(name) ?? [];
97
+ if (!own && deps.length === 0 && !tokenRule && patches.length === 0) {
63
98
  result[name] = definition;
64
99
  continue;
65
100
  }
@@ -71,7 +106,15 @@ export function attachPackStyles(
71
106
  const shared = styles.shared[dep];
72
107
  if (shared) injectOnce(`shared:${dep}`, shared, options);
73
108
  }
109
+ // 令牌规则必须排在组件分片**之前**:分片里的声明要能覆盖旋钮的缺省值,
110
+ // 反过来注入会让组件自己的特化失效。
111
+ if (tokenRule) injectOnce(`tokens:${name}`, tokenRule, options);
74
112
  if (own) injectOnce(`component:${name}`, own, options);
113
+ // 补丁最后:它的全部意义就是覆盖官方分片(M-4)。
114
+ // 特性分片在这两者之间,由 component-manager 按 prop 注入。
115
+ for (const patch of patches) {
116
+ injectOnce(`patch:${patch.patchedBy}→${name}`, patch.css, options);
117
+ }
75
118
  return inner ? inner(ctx) : {};
76
119
  },
77
120
  };
@@ -92,3 +135,18 @@ export function ensurePackBaseStyles(
92
135
  injectOnce(`base:${index}`, css, options);
93
136
  });
94
137
  }
138
+
139
+ /**
140
+ * 注入一片特性分片(M-3)。由 component-manager 在 prop 首次为真值时调用。
141
+ *
142
+ * key 用 `feature:<组件>#<特性>`,与 `component:<组件>` 同一个 injected 集合,
143
+ * 所以「注入一次」的保证是同一套,不需要组件自己记账。
144
+ */
145
+ export function injectStyleFeature(
146
+ componentName: string,
147
+ featureName: string,
148
+ css: string,
149
+ options: PackStyleOptions = {},
150
+ ): void {
151
+ injectOnce(`feature:${componentName}#${featureName}`, css, options);
152
+ }
@@ -0,0 +1,131 @@
1
+ // 特性分片的装配(REQ-009 M-3)。
2
+ //
3
+ // 「按需装配」此前只细到组件一档:组件一实例化就付它全部 CSS。
4
+ // 这一档在 DataTable 上不够用——核心分片贴着 7,600 上限,而排队的表格特性有五个。
5
+ // 抬上限只装得下一个;正确的杠杆是再细一档:**用到这个特性的页面才为它付钱**。
6
+ //
7
+ // 判定刻意做得很窄:`when` 只能指向契约里的 **prop**,不能指向控制器的派生态。
8
+ // 派生态要等实例跑起来才知道,而"要不要注入 CSS"必须在渲染第一帧之前定下来——
9
+ // 否则用户会看到一帧无样式的内容。
10
+ //
11
+ // 两种开关形态:boolean/array 的真值门控,以及 enum 的按值门控
12
+ // (`{ prop, equals }`)。后者是施工中补的:首批两个消费者都卡在同一处——
13
+ // 真正决定"要不要这段样式"的是一个枚举值而不是布尔开关,只有布尔一种写法时
14
+ // 它们只能退而按一个恒为真的数组 prop 开门,于是所有页面都付这笔钱,机制等于白建。
15
+
16
+ import type {
17
+ SomaComponentDefinition,
18
+ SomaStyleFeatureWhen,
19
+ } from './component-definition.types';
20
+ import { injectStyleFeature, type PackStyleOptions } from './pack-styles';
21
+
22
+ /**
23
+ * 真值门控:`true`、非空数组,或**非空字符串**。`0` / `''` / `[]` 一律不算启用。
24
+ *
25
+ * 字符串这一路是后补的:`detail_api` / `submit_api` 这类"声明了接口就要这段样式"的
26
+ * prop 是自治组件里最常见的开关形态——给了路径就意味着这段界面会出现。
27
+ * 不认它的话,这类特性只能退回"所有页面都付这笔钱",机制等于白建
28
+ * (与枚举门控当初的处境完全一样)。
29
+ */
30
+ export function isFeatureActive(value: unknown): boolean {
31
+ if (Array.isArray(value)) return value.length > 0;
32
+ if (typeof value === 'string') return value.trim() !== '';
33
+ return value === true;
34
+ }
35
+
36
+ /** 开关名(两种形态共用的取 prop 名) */
37
+ export function featurePropOf(when: SomaStyleFeatureWhen): string {
38
+ return typeof when === 'string' ? when : when.prop;
39
+ }
40
+
41
+ /** 按当前 props 判定某个特性是否启用 */
42
+ export function isFeatureEnabled(when: SomaStyleFeatureWhen, props: Record<string, unknown>): boolean {
43
+ if (typeof when === 'string') return isFeatureActive(props[when]);
44
+ const value = props[when.prop];
45
+ // 逐值比较用 Object.is 而不是 ==:枚举值可能是数字,'2' 与 2 不该互相命中
46
+ return when.equals.some((candidate) => Object.is(candidate, value));
47
+ }
48
+
49
+ /**
50
+ * 装配期校验:`when` 必须指向契约里真实存在的 prop,且形态要对得上——
51
+ * 真值门控只认 boolean / array,按值门控只认 enum 且取值必须在枚举内。
52
+ * 返回问题清单(空数组 = 通过),由 bootstrap 汇总后抛。
53
+ */
54
+ export function validateStyleFeatures(definition: SomaComponentDefinition): string[] {
55
+ const features = definition.styleFeatures;
56
+ if (!features) return [];
57
+ const issues: string[] = [];
58
+ const props = definition.contract.props ?? {};
59
+ const componentName = definition.contract.name;
60
+
61
+ for (const [featureName, feature] of Object.entries(features)) {
62
+ if (!feature || typeof feature.css !== 'string' || !feature.css.trim()) {
63
+ issues.push(`"${componentName}" 的特性分片 "${featureName}" 缺少 css`);
64
+ continue;
65
+ }
66
+ const propName = featurePropOf(feature.when);
67
+ const prop = props[propName];
68
+ if (!prop) {
69
+ issues.push(
70
+ `"${componentName}" 的特性分片 "${featureName}" 的 when 指向 "${propName}",`
71
+ + '但契约里没有这个 prop(when 只能指向契约 prop,不能指向控制器派生态——'
72
+ + '派生态要等实例跑起来才知道,而"要不要注入 CSS"必须在第一帧之前定下来)',
73
+ );
74
+ continue;
75
+ }
76
+
77
+ if (typeof feature.when === 'string') {
78
+ if (prop.type !== 'boolean' && prop.type !== 'array' && prop.type !== 'string') {
79
+ issues.push(
80
+ `"${componentName}" 的特性分片 "${featureName}" 的 when 指向 "${propName}",`
81
+ + `但它是 ${prop.type} 类型——真值开关只能是 boolean / array / string`
82
+ + '(string 按"非空即启用"判,用于 detail_api 这类"声明了就要这段样式"的口子)。'
83
+ + `若想按取值开门,写成 { prop: '${propName}', equals: [...] }`,
84
+ );
85
+ }
86
+ continue;
87
+ }
88
+
89
+ if (prop.type !== 'enum') {
90
+ issues.push(
91
+ `"${componentName}" 的特性分片 "${featureName}" 用了按值门控,`
92
+ + `但 "${propName}" 是 ${prop.type} 类型——{ prop, equals } 只对 enum 有意义`,
93
+ );
94
+ continue;
95
+ }
96
+ if (!Array.isArray(feature.when.equals) || feature.when.equals.length === 0) {
97
+ issues.push(`"${componentName}" 的特性分片 "${featureName}" 的 equals 必须是非空数组`);
98
+ continue;
99
+ }
100
+ // 取值不在枚举内 = 这个特性永远不会被注入。它不报错、只是"设了没用",
101
+ // 所以必须在装配期拦下——运行期没有任何迹象能让人发现它。
102
+ const allowed = new Set<unknown>(prop.values ?? []);
103
+ const stray = feature.when.equals.filter((value) => !allowed.has(value));
104
+ if (allowed.size > 0 && stray.length > 0) {
105
+ issues.push(
106
+ `"${componentName}" 的特性分片 "${featureName}" 的 equals 含枚举外取值 `
107
+ + `${stray.map((v) => JSON.stringify(v)).join(' / ')}——`
108
+ + `"${propName}" 的合法取值是 [${(prop.values ?? []).join(' | ')}]。`
109
+ + '取不到的值等于这段样式永远不注入,而运行期没有任何迹象能发现它',
110
+ );
111
+ }
112
+ }
113
+ return issues;
114
+ }
115
+
116
+ /**
117
+ * 按当前 props 注入该启用的特性分片。实例创建与每次 setProps 后调用。
118
+ * 注入是幂等的(pack-styles 的 injected 集合负责),所以这里不用自己记账。
119
+ */
120
+ export function ensureStyleFeatures(
121
+ definition: SomaComponentDefinition,
122
+ props: Record<string, unknown>,
123
+ options: PackStyleOptions = {},
124
+ ): void {
125
+ const features = definition.styleFeatures;
126
+ if (!features) return;
127
+ for (const [featureName, feature] of Object.entries(features)) {
128
+ if (!isFeatureEnabled(feature.when, props)) continue;
129
+ injectStyleFeature(definition.contract.name, featureName, feature.css, options);
130
+ }
131
+ }
@@ -0,0 +1,83 @@
1
+ // 主题输入里的组件令牌 × 契约声明的对账(REQ-009 M-1)。
2
+ //
3
+ // 分工的理由:主题引擎不认识组件(它只认令牌名,且刻意不可插拔),
4
+ // 而契约住在组件包里。两者相遇的唯一地点是装配层——也就是这里。
5
+ //
6
+ // 为什么必须对账而不是随便写:`components: { Buton: { radius: … } }` 这样一个拼写错误,
7
+ // 在没有对账时的表现是「改了没反应」——变量确实写进了 :root,只是没有任何组件读它。
8
+ // 这类错误的排查成本远高于报错。
9
+
10
+ import type { SomaComponentDefinition } from './component-definition.types';
11
+ import { COMPONENT_TOKEN_KEY_PATTERN } from '../../shared/types/component-contract.types';
12
+
13
+ export class SomaThemeComponentTokenError extends Error {
14
+ constructor(message: string) {
15
+ super(`[SomaThemeComponentTokens] ${message}`);
16
+ this.name = 'SomaThemeComponentTokenError';
17
+ }
18
+ }
19
+
20
+ /**
21
+ * 校验主题输入的 `components` / `darkComponents` 段是否与契约对得上。
22
+ * Host 在调 `applyTheme` 之前调用;不给组件表时(纯预览场景)跳过。
23
+ */
24
+ export function validateThemeComponentTokens(
25
+ input: {
26
+ components?: Record<string, Record<string, string>>;
27
+ darkComponents?: Record<string, Record<string, string>>;
28
+ },
29
+ components: Record<string, SomaComponentDefinition>,
30
+ ): void {
31
+ const issues: string[] = [];
32
+ for (const segment of [input.components, input.darkComponents]) {
33
+ if (!segment) continue;
34
+ for (const [componentName, tokens] of Object.entries(segment)) {
35
+ const definition = components[componentName];
36
+ if (!definition) {
37
+ issues.push(`未知组件 "${componentName}"`);
38
+ continue;
39
+ }
40
+ const declared = definition.contract.tokens ?? {};
41
+ for (const key of Object.keys(tokens ?? {})) {
42
+ if (!(key in declared)) {
43
+ const available = Object.keys(declared);
44
+ issues.push(
45
+ `"${componentName}" 没有声明可调令牌 "${key}"`
46
+ + (available.length > 0
47
+ ? `(它声明的是:${available.join(' / ')})`
48
+ : '(它一个可调令牌都没声明——组件令牌是组件自己的承诺,'
49
+ + '不能由外面凭空指定)'),
50
+ );
51
+ }
52
+ }
53
+ }
54
+ }
55
+ if (issues.length > 0) {
56
+ throw new SomaThemeComponentTokenError(
57
+ `主题的组件令牌段有 ${issues.length} 处问题:\n${issues.map((i) => ` · ${i}`).join('\n')}`,
58
+ );
59
+ }
60
+ }
61
+
62
+ /** 契约自检:令牌键名格式 + default 必须引用语义令牌。返回问题清单 */
63
+ export function validateContractTokens(definition: SomaComponentDefinition): string[] {
64
+ const tokens = definition.contract.tokens;
65
+ if (!tokens) return [];
66
+ const issues: string[] = [];
67
+ const name = definition.contract.name;
68
+ for (const [key, token] of Object.entries(tokens)) {
69
+ if (!COMPONENT_TOKEN_KEY_PATTERN.test(key)) {
70
+ issues.push(`"${name}" 的令牌键 "${key}" 必须是 kebab-case`);
71
+ }
72
+ if (!token || typeof token.default !== 'string' || !token.default.includes('var(--soma-')) {
73
+ issues.push(
74
+ `"${name}.${key}" 的 default 必须引用语义令牌(形如 var(--soma-…))——`
75
+ + '组件令牌是语义令牌的别名与收窄,不是新的真源',
76
+ );
77
+ }
78
+ if (!token?.desc?.trim()) {
79
+ issues.push(`"${name}.${key}" 缺少 desc(可调令牌要告诉使用者它调的是什么)`);
80
+ }
81
+ }
82
+ return issues;
83
+ }