soma-core 1.4.2 → 1.5.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.
Files changed (212) hide show
  1. package/bin/component.cjs +240 -0
  2. package/bin/eject.cjs +174 -0
  3. package/bin/migrate.cjs +362 -0
  4. package/core/build/blocks/block-compile.ts +143 -17
  5. package/core/build/blocks/migrate-flat.ts +118 -25
  6. package/core/build/compiler/page-declaration-compiler.ts +149 -5
  7. package/core/build/compiler/route-builder.ts +0 -4
  8. package/core/build/compiler/soma-precompile.js +431 -26
  9. package/core/build/component/component-graph.ts +28 -105
  10. package/core/build/component/package-loader.ts +18 -4
  11. package/core/build/eject/component-eject.ts +8 -2
  12. package/core/build/layout/constraint-solver.ts +131 -16
  13. package/core/build/layout/css-emitter.ts +15 -9
  14. package/core/build/ooui/artifact/artifact.types.ts +275 -0
  15. package/core/build/ooui/artifact/emit-artifact.ts +269 -0
  16. package/core/build/ooui/artifact/emit-html.ts +204 -0
  17. package/core/build/ooui/artifact/index.ts +53 -0
  18. package/core/build/ooui/artifact/spatial-tree.ts +268 -0
  19. package/core/build/ooui/artifact/utility-class.ts +83 -0
  20. package/core/build/ooui/composition/candidate.types.ts +323 -0
  21. package/core/build/ooui/composition/control-model.ts +114 -0
  22. package/core/build/ooui/composition/registry.ts +520 -0
  23. package/core/build/ooui/composition/select.ts +232 -0
  24. package/core/build/ooui/diagnostics/codes.ts +230 -0
  25. package/core/build/ooui/diagnostics/error.ts +235 -0
  26. package/core/build/ooui/diagnostics/format.ts +106 -0
  27. package/core/build/ooui/diagnostics/index.ts +62 -0
  28. package/core/build/ooui/diagnostics/issue.types.ts +112 -0
  29. package/core/build/ooui/engine-slot.ts +184 -0
  30. package/core/build/ooui/index.ts +1427 -0
  31. package/core/build/ooui/intent/derive-intent.ts +450 -0
  32. package/core/build/ooui/intent/field-rules.ts +330 -0
  33. package/core/build/ooui/intent/intent.types.ts +476 -0
  34. package/core/build/ooui/intent/verb-events.ts +285 -0
  35. package/core/build/ooui/page/budget.ts +503 -0
  36. package/core/build/ooui/page/compose-page.ts +736 -0
  37. package/core/build/ooui/page/index.ts +66 -0
  38. package/core/build/ooui/page/page.types.ts +402 -0
  39. package/core/build/ooui/page/region-row.ts +241 -0
  40. package/core/build/ooui/semantic/expand-page-surface.ts +180 -0
  41. package/core/build/ooui/semantic/kernel.types.ts +187 -0
  42. package/core/build/ooui/semantic/normalize.ts +784 -0
  43. package/core/build/ooui/semantic/origin.types.ts +211 -0
  44. package/core/build/ooui/semantic/role-alias.ts +154 -0
  45. package/core/build/ooui/semantic/shorthand.ts +233 -0
  46. package/core/build/ooui/semantic/surface.types.ts +78 -0
  47. package/core/build/ooui/semantic/validate-request.ts +267 -0
  48. package/core/build/ooui/spatial/emit-utility.ts +480 -0
  49. package/core/build/ooui/spatial/ir.types.ts +443 -0
  50. package/core/build/ooui/spatial/registry.ts +565 -0
  51. package/core/build/ooui/spatial/solve.ts +769 -0
  52. package/core/build/ooui/spatial/utility.types.ts +242 -0
  53. package/core/build/ooui/trace/index.ts +40 -0
  54. package/core/build/ooui/trace/render.ts +190 -0
  55. package/core/build/ooui/trace/source.types.ts +69 -0
  56. package/core/build/ooui/trace/trace.types.ts +326 -0
  57. package/core/client/component/example-blocks.ts +1 -7
  58. package/core/client/component/theme-component-tokens.ts +12 -15
  59. package/core/client/data/data-object-resolver.ts +27 -8
  60. package/core/client/diagnostics/telemetry-context.ts +0 -4
  61. package/core/client/engine/asset-resolver.ts +0 -1
  62. package/core/client/engine/event-engine.ts +7 -3
  63. package/core/client/engine/soma-bootstrap.ts +292 -34
  64. package/core/client/engine/style-binder.ts +0 -1
  65. package/core/client/infra/http/IHttpClient.ts +0 -6
  66. package/core/client/infra/http/SomaHttpService.ts +4 -1
  67. package/core/client/infra/notify/DomNotifyService.ts +1 -1
  68. package/core/client/infra/router/router-path.ts +0 -6
  69. package/core/client/parser/annotation-extractor.ts +1 -1
  70. package/core/client/parser/blocks/namespace.ts +30 -5
  71. package/core/client/parser/blocks/page-parser.ts +44 -1
  72. package/core/client/parser/blocks/use-parser.ts +266 -46
  73. package/core/client/parser/data-config-parser.ts +71 -3
  74. package/core/client/parser/layout-parser.ts +4 -3
  75. package/core/client/parser/reaction-parser.ts +0 -1
  76. package/core/client/parser/ui-config-parser.ts +212 -74
  77. package/core/client/theme/scene-tokens.ts +9 -3
  78. package/core/client/theme/theme-axes.ts +74 -16
  79. package/core/client/theme/theme-engine.ts +280 -69
  80. package/core/client/theme/tone-solver.ts +9 -8
  81. package/core/index.ts +18 -4
  82. package/core/server/api/load-host-service.ts +8 -2
  83. package/core/server/declaration-safety.ts +11 -0
  84. package/core/server/host/page-response-request.ts +0 -2
  85. package/core/server/host/published-page-artifact-cache.ts +244 -0
  86. package/core/server/host/published-page-assets.ts +44 -5
  87. package/core/server/mock/node/cli.mjs +0 -1
  88. package/core/server/mock/node/schema-generator.mjs +0 -1
  89. package/core/server/ooui.ts +34 -0
  90. package/core/server/page-assets.ts +8 -0
  91. package/core/server/page-declaration.ts +18 -0
  92. package/core/server/registry/asset-store.ts +327 -0
  93. package/core/server/registry/declaration-precompiler.ts +49 -6
  94. package/core/server/registry/index.ts +47 -1
  95. package/core/server/registry/page-registry-repository.ts +6 -2
  96. package/core/server/registry/page-registry-store.ts +133 -19
  97. package/core/server/registry/publish-asset-pin.ts +557 -0
  98. package/core/server/registry/services/pages/List.ts +15 -3
  99. package/core/server/registry/validation/compile-gate.ts +180 -8
  100. package/core/server/registry/validation/declaration-safety-scan.ts +113 -23
  101. package/core/shared/component/derive-sample.ts +201 -16
  102. package/core/shared/component/field-lines.ts +98 -8
  103. package/core/shared/container-breakpoints.ts +46 -0
  104. package/core/shared/object-semantics.ts +240 -0
  105. package/core/shared/ooui-declaration.ts +235 -0
  106. package/core/shared/types/component-contract.types.ts +7 -6
  107. package/core/shared/types/data-config.types.ts +95 -0
  108. package/core/shared/types/domain.types.ts +0 -24
  109. package/core/shared/types/engine.types.ts +0 -5
  110. package/core/shared/types/layout-constraint.types.ts +16 -0
  111. package/core/shared/types/ui-config.types.ts +163 -13
  112. package/dist/cli/soma.js +24 -11
  113. package/dist/core/index.cjs +1563 -800
  114. package/dist/types/build/blocks/block-compile.d.ts +16 -1
  115. package/dist/types/build/blocks/migrate-flat.d.ts +17 -0
  116. package/dist/types/build/compiler/page-declaration-compiler.d.ts +46 -0
  117. package/dist/types/build/compiler/route-builder.d.ts +0 -1
  118. package/dist/types/build/component/component-graph.d.ts +17 -53
  119. package/dist/types/build/component/package-loader.d.ts +8 -1
  120. package/dist/types/build/layout/constraint-solver.d.ts +46 -4
  121. package/dist/types/build/ooui/artifact/artifact.types.d.ts +180 -0
  122. package/dist/types/build/ooui/artifact/emit-artifact.d.ts +58 -0
  123. package/dist/types/build/ooui/artifact/emit-html.d.ts +53 -0
  124. package/dist/types/build/ooui/artifact/index.d.ts +5 -0
  125. package/dist/types/build/ooui/artifact/spatial-tree.d.ts +48 -0
  126. package/dist/types/build/ooui/artifact/utility-class.d.ts +46 -0
  127. package/dist/types/build/ooui/composition/candidate.types.d.ts +206 -0
  128. package/dist/types/build/ooui/composition/control-model.d.ts +37 -0
  129. package/dist/types/build/ooui/composition/registry.d.ts +66 -0
  130. package/dist/types/build/ooui/composition/select.d.ts +63 -0
  131. package/dist/types/build/ooui/diagnostics/codes.d.ts +28 -0
  132. package/dist/types/build/ooui/diagnostics/error.d.ts +135 -0
  133. package/dist/types/build/ooui/diagnostics/format.d.ts +51 -0
  134. package/dist/types/build/ooui/diagnostics/index.d.ts +25 -0
  135. package/dist/types/build/ooui/diagnostics/issue.types.d.ts +56 -0
  136. package/dist/types/build/ooui/engine-slot.d.ts +41 -0
  137. package/dist/types/build/ooui/index.d.ts +286 -0
  138. package/dist/types/build/ooui/intent/derive-intent.d.ts +32 -0
  139. package/dist/types/build/ooui/intent/field-rules.d.ts +99 -0
  140. package/dist/types/build/ooui/intent/intent.types.d.ts +318 -0
  141. package/dist/types/build/ooui/intent/verb-events.d.ts +70 -0
  142. package/dist/types/build/ooui/page/budget.d.ts +28 -0
  143. package/dist/types/build/ooui/page/compose-page.d.ts +41 -0
  144. package/dist/types/build/ooui/page/index.d.ts +4 -0
  145. package/dist/types/build/ooui/page/page.types.d.ts +264 -0
  146. package/dist/types/build/ooui/page/region-row.d.ts +16 -0
  147. package/dist/types/build/ooui/semantic/expand-page-surface.d.ts +33 -0
  148. package/dist/types/build/ooui/semantic/kernel.types.d.ts +125 -0
  149. package/dist/types/build/ooui/semantic/normalize.d.ts +45 -0
  150. package/dist/types/build/ooui/semantic/origin.types.d.ts +95 -0
  151. package/dist/types/build/ooui/semantic/role-alias.d.ts +35 -0
  152. package/dist/types/build/ooui/semantic/shorthand.d.ts +60 -0
  153. package/dist/types/build/ooui/semantic/surface.types.d.ts +16 -0
  154. package/dist/types/build/ooui/semantic/validate-request.d.ts +19 -0
  155. package/dist/types/build/ooui/spatial/emit-utility.d.ts +43 -0
  156. package/dist/types/build/ooui/spatial/ir.types.d.ts +280 -0
  157. package/dist/types/build/ooui/spatial/registry.d.ts +110 -0
  158. package/dist/types/build/ooui/spatial/solve.d.ts +42 -0
  159. package/dist/types/build/ooui/spatial/utility.types.d.ts +191 -0
  160. package/dist/types/build/ooui/trace/index.d.ts +3 -0
  161. package/dist/types/build/ooui/trace/render.d.ts +42 -0
  162. package/dist/types/build/ooui/trace/source.types.d.ts +25 -0
  163. package/dist/types/build/ooui/trace/trace.types.d.ts +143 -0
  164. package/dist/types/client/component/example-blocks.d.ts +0 -2
  165. package/dist/types/client/component/theme-component-tokens.d.ts +8 -5
  166. package/dist/types/client/data/data-object-resolver.d.ts +10 -2
  167. package/dist/types/client/diagnostics/telemetry-context.d.ts +0 -1
  168. package/dist/types/client/engine/soma-bootstrap.d.ts +123 -10
  169. package/dist/types/client/infra/http/IHttpClient.d.ts +0 -5
  170. package/dist/types/client/infra/http/SomaHttpService.d.ts +1 -1
  171. package/dist/types/client/infra/router/router-path.d.ts +0 -2
  172. package/dist/types/client/parser/blocks/namespace.d.ts +20 -0
  173. package/dist/types/client/parser/blocks/page-parser.d.ts +9 -0
  174. package/dist/types/client/parser/blocks/use-parser.d.ts +38 -4
  175. package/dist/types/client/parser/data-config-parser.d.ts +13 -0
  176. package/dist/types/client/parser/ui-config-parser.d.ts +1 -11
  177. package/dist/types/client/theme/scene-tokens.d.ts +9 -3
  178. package/dist/types/client/theme/theme-axes.d.ts +64 -1
  179. package/dist/types/client/theme/theme-engine.d.ts +13 -8
  180. package/dist/types/client/theme/tone-solver.d.ts +9 -5
  181. package/dist/types/index.d.ts +4 -5
  182. package/dist/types/server/declaration-safety.d.ts +7 -0
  183. package/dist/types/server/host/page-response-request.d.ts +0 -1
  184. package/dist/types/server/host/published-page-artifact-cache.d.ts +64 -0
  185. package/dist/types/server/ooui.d.ts +18 -0
  186. package/dist/types/server/page-assets.d.ts +7 -0
  187. package/dist/types/server/page-declaration.d.ts +14 -0
  188. package/dist/types/server/registry/asset-store.d.ts +112 -0
  189. package/dist/types/server/registry/declaration-precompiler.d.ts +23 -3
  190. package/dist/types/server/registry/index.d.ts +3 -1
  191. package/dist/types/server/registry/page-registry-store.d.ts +57 -4
  192. package/dist/types/server/registry/publish-asset-pin.d.ts +166 -0
  193. package/dist/types/server/registry/services/pages/List.d.ts +9 -3
  194. package/dist/types/server/registry/validation/compile-gate.d.ts +63 -0
  195. package/dist/types/shared/component/derive-sample.d.ts +14 -0
  196. package/dist/types/shared/container-breakpoints.d.ts +42 -0
  197. package/dist/types/shared/object-semantics.d.ts +42 -0
  198. package/dist/types/shared/ooui-declaration.d.ts +135 -0
  199. package/dist/types/shared/types/component-contract.types.d.ts +7 -6
  200. package/dist/types/shared/types/data-config.types.d.ts +86 -0
  201. package/dist/types/shared/types/domain.types.d.ts +0 -21
  202. package/dist/types/shared/types/engine.types.d.ts +0 -4
  203. package/dist/types/shared/types/layout-constraint.types.d.ts +1 -0
  204. package/dist/types/shared/types/ui-config.types.d.ts +157 -12
  205. package/next.config.js +106 -13
  206. package/package.json +28 -2
  207. package/core/client/host-bridge/index.ts +0 -27
  208. package/core/client/parser/yaml-loader.ts +0 -36
  209. package/core/shared/manifest/manifest-contract.ts +0 -12
  210. package/dist/types/client/host-bridge/index.d.ts +0 -9
  211. package/dist/types/client/parser/yaml-loader.d.ts +0 -21
  212. package/dist/types/shared/manifest/manifest-contract.d.ts +0 -4
@@ -0,0 +1,769 @@
1
+ // 空间层 · 二级(需要分配的布局):IR 树 → 逐档解 → CSS。
2
+ //
3
+ // ── 为什么这一层的失败模式是静默的 ─────────────────────────────────
4
+ // 见 `ir.types.ts` 的头注释:二级产出的是**数字**,数字错了没有任何外在标记。
5
+ // 本文件补一条只在实现里才成立的:
6
+ //
7
+ // **"复用"与"重写"的差别,在测试全绿的那一刻是看不出来的。**
8
+ // 一维分配这件事仓库里已经有了一份实现(`core/build/layout/constraint-solver.ts`,
9
+ // REQ-010 S3):三档 sizing、四档优先级、min-max 夹逼、不可满足时报出打架的两条声明。
10
+ // 在这里照着"再写一遍"是最省事的做法——它甚至会更简单,因为可以只实现用得到的分支。
11
+ // 坏就坏在**两份实现在写下的那天结果完全一致**,单测各自全绿;
12
+ // 漂开发生在半年后有人给其中一份修了一个边界(比如 `required` 不参与压缩),
13
+ // 而另一份没跟上。那时的表现是**页面 `layout:` 段解出来的宽度与演绎出来的宽度
14
+ // 在某一档上差了 0.5rem**——两块本该对齐的区域错开半个字符,
15
+ // 没有异常、没有日志,也没有任何一条断言把两者放在一起比过。
16
+ // 断点表抄成三份(期 0)、`SomaSource` 抄成三份(架构 §36.3②)、
17
+ // 字段类型表抄成四份,本仓库为同一件事已经付过三次学费。
18
+ //
19
+ // 所以本文件**一个求解分支都不自己写**:
20
+ // · 逐档分配 → `solveStep`(含冲突对报告);
21
+ // · 声明校验 → `validateConstraint`;
22
+ // · 长度折算 → `toRem`;
23
+ // · 容器查询 CSS → `emitLayoutCss`(它的 `EmitOptions` 本来就收任意 `root`
24
+ // 与 `selectorOf` 回调,不是页面专用的);
25
+ // · 断点八档 → `shared/container-breakpoints` 唯一真源。
26
+ // 本文件只做上游没做的三件事:**把树摊成组**、**把组件塞不下这条闸门接上**、
27
+ // **把不可满足翻译成带错误码与 remedy 的空间层错误**。
28
+ //
29
+ // ── 为什么不引 Cassowary / kiwi(架构 D3) ──────────────────────────
30
+ // 理由与 `constraint-solver.ts` 头注释同一条,且更硬:**错误可解释性**。
31
+ // Auto Layout 那句 "Unable to simultaneously satisfy constraints" 后面跟着一串
32
+ // 内部约束编号,是公认的开发者体验灾难——它告诉你"有矛盾",却不告诉你
33
+ // **哪两句是你写的**。单纯形法给出的不可满足集要翻译回作者写的那行 YAML,
34
+ // 得另做一层映射,而那层映射本身就是这里想避免的复杂度。
35
+ // 逐档按优先级分配是确定性的,冲突时能直接指着两条声明说"这两条打架"。
36
+ //
37
+ // ── 求解协议(架构 §3.4;单遍,自顶向下,每档独立,O(节点数 × 8)) ────
38
+ // leaf → 作为被分配者进入父组的约束
39
+ // component → **不下探**(类型上就没有 children);校验每档可用宽 ≥ minInline
40
+ // intrinsic → **不分配**尺寸(CSS 自解),但继续遍历:它底下的每个 group
41
+ // 都是自己的容器,各自要发自己的 CSS
42
+ // group → block 轴:只发排列 CSS(架构 D5:Web 的高度应内容驱动)
43
+ // inline 轴:逐档优先级分配 → widths → 递归子项
44
+ //
45
+ // ── 为什么每个组都独立解八档,而不是把父组解出的宽度传下去 ──────────
46
+ // `emitLayoutCss` 发的是**容器查询**,而容器查询在运行时是相对**最近的容器祖先**
47
+ // 求值的;每个组自己就声明了 `container-type: inline-size`,所以子组的八档解
48
+ // 与父组解出多宽无关——传下去反而会把"编译期猜的那一档"焊死进产物(架构 D4:
49
+ // 档间宽度命中下一档,是**非精确解**,这正是它可以逐组独立的原因)。
50
+ // 自顶向下传的那个 availRem 只有一个用途:**组件塞得下**闸门,而那道闸门是
51
+ // **局部**的——每个 inline 组核对自己直接子项的 minInline 就够了,
52
+ // 孙子由孙子所在的那个组核对。
53
+ //
54
+ // ── 幂等(架构 §19.3) ──────────────────────────────────────────────
55
+ // DFS 前序、按稳定键排序、不读时间/随机数、不依赖 Map 遍历序;
56
+ // 产物是纯数据(无函数、无 Map/Set、无循环引用,可 `yaml.dump`)。
57
+
58
+ import {
59
+ CONTAINER_STEPS,
60
+ SomaLayoutConstraintError,
61
+ solveStep,
62
+ toRem,
63
+ validateConstraint,
64
+ } from '../../layout/constraint-solver';
65
+ import { emitLayoutCss } from '../../layout/css-emitter';
66
+ import type {
67
+ SomaLayoutConstraint,
68
+ SomaLayoutNodeConstraint,
69
+ SomaLayoutSolution,
70
+ } from '../../../shared/types/layout-constraint.types';
71
+ // 节点 id 的文法与 `ooui:` 锚点名、页面区域名是**同一条**(三处是同一个名字,
72
+ // 见该常量的注释)。此前本文件自持一份「字母或数字开头」,产物层是「字母开头」、
73
+ // 解析器是「字母或下划线开头」——`1list` 在这里放行、到产物层才红,
74
+ // 而那条错误指着的是派生出来的 `1list-shell`,不是作者写错的那一行。
75
+ import {
76
+ SOMA_OOUI_ANCHOR_GRAMMAR,
77
+ SOMA_OOUI_ANCHOR_PATTERN,
78
+ SOMA_OOUI_SIZINGS,
79
+ SOMA_TEXT_NODE,
80
+ isOouiSizing,
81
+ } from '../../../shared/ooui-declaration';
82
+ import { describeOouiValue } from '../diagnostics';
83
+
84
+ import {
85
+ SOMA_INTRINSIC_PRIMITIVES,
86
+ SOMA_SPATIAL_AXES,
87
+ SOMA_SPATIAL_NODE_KINDS,
88
+ SomaSpatialError,
89
+ SomaSpatialSolveError,
90
+ type SomaSizing,
91
+ type SomaSpatialBoundary,
92
+ type SomaSpatialDecision,
93
+ type SomaSpatialGroupNode,
94
+ type SomaSpatialGroupSolution,
95
+ type SomaSpatialNode,
96
+ type SomaSpatialPlan,
97
+ type SomaSpatialUncheckedFit,
98
+ type SomaSource,
99
+ } from './ir.types';
100
+
101
+ /** 浮点比较的容差。四位小数是 `constraint-solver` 的 `round()` 精度 */
102
+ const EPSILON = 1e-9;
103
+
104
+ const WIDEST_REM = CONTAINER_STEPS[CONTAINER_STEPS.length - 1][1];
105
+
106
+ export interface SolveSpatialOptions {
107
+ /**
108
+ * 节点 → CSS 选择器。缺省:有 `anchor` 用 `[data-soma-id="…"]`,否则
109
+ * `[data-soma-node="<id>"]`。
110
+ *
111
+ * 与 `build/layout/page-layout.ts` 同一形态——那里也是把宿主类名前缀
112
+ * 交给调用方拼,求解器不认识宿主。
113
+ */
114
+ selectorOf?(node: SomaSpatialNode): string;
115
+ /**
116
+ * 声明这棵树的容器**最窄只会到哪一档**(rem)。缺省:八档全部可达。
117
+ *
118
+ * 这是"组件塞不下"与"约束不可满足"的**唯一逃生门**(铁律一:显式声明永远赢)。
119
+ * 没有它的话,一个 `minInline: 24rem` 的组件在 20rem 那档必红——
120
+ * 而那一档可能根本不会出现(比如这棵树只挂在主区,主区最窄 36rem)。
121
+ * 不可达的档不参与求解,其 CSS 沿用最窄可达档的解(`emitLayoutCss` 会把
122
+ * 逐字节相同的相邻档合并掉,所以产物上就是"基线 = 最窄可达档")。
123
+ */
124
+ minContainerRem?: number;
125
+ /**
126
+ * 根节点自身的可用宽(rem)。只用于**根就是组件**时核对它的 `minInline`;
127
+ * 不给则该条核对记进 `plan.unchecked`,不静默放行。
128
+ */
129
+ availRem?: number;
130
+ }
131
+
132
+ interface WalkContext {
133
+ readonly selectorOf: (node: SomaSpatialNode) => string;
134
+ readonly floorIndex: number;
135
+ readonly groups: SomaSpatialGroupSolution[];
136
+ readonly boundaries: SomaSpatialBoundary[];
137
+ readonly unchecked: SomaSpatialUncheckedFit[];
138
+ readonly decisions: SomaSpatialDecision[];
139
+ readonly classes: Set<string>;
140
+ stats: SomaSpatialPlan['stats'];
141
+ }
142
+
143
+ // ─────────────────────────────────────────────────────────────
144
+ // 公开 API
145
+ // ─────────────────────────────────────────────────────────────
146
+
147
+ /**
148
+ * 校验 IR 树的形状。**求解前必跑**,`solveSpatial` 内部会调用。
149
+ *
150
+ * 单独导出是给闸门与上游(产物层组树的那一步)用的:形状错了要在**组树的地方**
151
+ * 报,而不是等到求解时报——两者相隔几层调用栈,后者的错误指不回真正写错的那行。
152
+ */
153
+ export function validateSpatialTree(root: SomaSpatialNode, path?: string): void {
154
+ const ids = new Map<string, string>();
155
+ validateNode(root, path ?? rootPath(root), ids);
156
+ }
157
+
158
+ /**
159
+ * 根路径取根节点自己的 id。
160
+ *
161
+ * 用字面量 `'root'` 的话,一棵树里所有错误消息的第一段都叫 root——
162
+ * 而一次编译会解很多棵树(每个锚点一棵),报出来的 `root.nav.min` 指不回是哪个区域。
163
+ * id 不合法时才退回 `'root'`:那一刻错误本来就是"id 不合法",指不指得准都轮不到它。
164
+ */
165
+ function rootPath(root: SomaSpatialNode): string {
166
+ const id = root && typeof root === 'object' ? (root as { id?: unknown }).id : undefined;
167
+ return typeof id === 'string' && SOMA_OOUI_ANCHOR_PATTERN.test(id) ? id : 'root';
168
+ }
169
+
170
+ /**
171
+ * 解一棵 IR 树。
172
+ *
173
+ * 失败一律**编译期抛**(铁律二),错误带码 + 三段式正文 + 可直接抄的修法;
174
+ * 不可满足时额外带结构化的 `conflict` 两条声明(`SomaSpatialSolveError`)。
175
+ * **没有任何一条路径会返回"降级后的解"**——降级出来的 CSS 一样能渲染,
176
+ * 而那正是本层要拦的坏法。
177
+ */
178
+ export function solveSpatial(
179
+ root: SomaSpatialNode,
180
+ options: SolveSpatialOptions = {},
181
+ ): SomaSpatialPlan {
182
+ validateSpatialTree(root);
183
+
184
+ const floorIndex = resolveFloorIndex(options.minContainerRem);
185
+ const context: WalkContext = {
186
+ selectorOf: options.selectorOf ?? defaultSelectorOf,
187
+ floorIndex,
188
+ groups: [],
189
+ boundaries: [],
190
+ unchecked: [],
191
+ decisions: [],
192
+ classes: new Set<string>(),
193
+ stats: {
194
+ nodes: 0, groups: 0, solvedGroups: 0, components: 0, intrinsics: 0, leaves: 0, steps: 0,
195
+ },
196
+ };
197
+
198
+ const basePath = rootPath(root);
199
+
200
+ if (floorIndex > 0) {
201
+ context.decisions.push({
202
+ path: basePath,
203
+ conclusion: `窄于 ${CONTAINER_STEPS[floorIndex][1]}rem 的 ${floorIndex} 档不参与求解,其 CSS 沿用 ${CONTAINER_STEPS[floorIndex][0]} 档的解`,
204
+ rule: 'options.minContainerRem',
205
+ origin: 'declared',
206
+ });
207
+ }
208
+
209
+ // 根就是组件时的 minInline 核对:只有调用方给了 availRem 才量得出来。
210
+ // 量不出来时**不在这里记 unchecked**——`walk` 会按同一条判据记一次,
211
+ // 两处各记一条的表现是同一件事在产物里出现两遍,而去重逻辑又是第三份判据。
212
+ if (root.kind === 'component' && root.minInline !== undefined && options.availRem !== undefined) {
213
+ const required = toRemGuarded(root.minInline, options.availRem, `${basePath}.minInline`);
214
+ if (options.availRem + EPSILON < required) {
215
+ throw tooWide({
216
+ path: basePath,
217
+ component: root.component,
218
+ breakpoint: '<root>',
219
+ available: options.availRem,
220
+ required,
221
+ minInline: root.minInline,
222
+ ...(root.src !== undefined ? { src: root.src } : {}),
223
+ });
224
+ }
225
+ }
226
+
227
+ walk(root, basePath, context, {
228
+ allocated: options.availRem !== undefined,
229
+ under: '<root>',
230
+ });
231
+
232
+ const css = context.groups.map((group) => group.css).filter((text) => text !== '').join('\n\n');
233
+
234
+ return {
235
+ root: root.id,
236
+ groups: context.groups,
237
+ css,
238
+ utilityCandidates: [...context.classes].sort(),
239
+ boundaries: context.boundaries,
240
+ unchecked: context.unchecked,
241
+ decisions: context.decisions,
242
+ stats: context.stats,
243
+ };
244
+ }
245
+
246
+ // ─────────────────────────────────────────────────────────────
247
+ // 形状校验
248
+ // ─────────────────────────────────────────────────────────────
249
+
250
+ function validateNode(node: SomaSpatialNode, path: string, ids: Map<string, string>): void {
251
+ if (node === null || typeof node !== 'object' || Array.isArray(node)) {
252
+ throw shapeError({
253
+ path,
254
+ situation: `${path} 不是一个 IR 节点(收到 ${describeOouiValue(node)})。`,
255
+ problem: '不是节点的东西在遍历里会被当成"没有子项"而静默跳过,那一整棵子树的 CSS 一条都发不出来——浏览器照样渲染,只是排版塌成正常流。',
256
+ remedy: `节点形如:{ kind: 'group', id: '${path.split('.').pop()}', axis: 'inline', children: [...] }。四类:${SOMA_SPATIAL_NODE_KINDS.join(' / ')}。`,
257
+ });
258
+ }
259
+
260
+ if (!(SOMA_SPATIAL_NODE_KINDS as readonly string[]).includes(node.kind)) {
261
+ throw shapeError({
262
+ path,
263
+ situation: `${path}.kind 是 “${String(node.kind)}”,不在节点四类里。`,
264
+ problem: '未知 kind 会走到遍历的兜底分支被跳过。跳过一棵子树不会报错,页面上只是"这一块的排版是竖的",而这与"作者本来就想竖排"长得一模一样。',
265
+ remedy: `kind 只能是 ${SOMA_SPATIAL_NODE_KINDS.join(' / ')}。要做的事在哪一类:一维排列组用 group;被分配的叶子用 leaf;组件实例用 component(求解到此为止);CSS 能自解的排布用 intrinsic。`,
266
+ ...(node.src !== undefined ? { src: node.src } : {}),
267
+ });
268
+ }
269
+
270
+ if (typeof node.id !== 'string' || !SOMA_OOUI_ANCHOR_PATTERN.test(node.id)) {
271
+ throw shapeError({
272
+ path,
273
+ situation: `${path}.id 是 ${describeOouiValue(node.id)},不是合法的节点标识。`,
274
+ problem: 'id 会原样进 CSS 属性选择器。缺了它这条规则无处可指(整组样式发不出来);带引号或括号则会让选择器提前闭合,而被吃掉的那部分规则**不报错**,只是不生效。',
275
+ remedy: `id 文法:${SOMA_OOUI_ANCHOR_GRAMMAR}(正则 ${SOMA_OOUI_ANCHOR_PATTERN.source})。`,
276
+ ...(node.src !== undefined ? { src: node.src } : {}),
277
+ });
278
+ }
279
+
280
+ const seen = ids.get(node.id);
281
+ if (seen !== undefined) {
282
+ throw shapeError({
283
+ code: 'OOUI-SPA-NODE-ID-DUPLICATE',
284
+ path,
285
+ situation: `节点 id “${node.id}” 出现了两次(${seen} 与 ${path})。`,
286
+ problem: '默认选择器按 id 生成,重名的两个节点会共用同一条规则:后解出的那一份**覆盖**先解出的那一份,而谁在后面取决于遍历顺序。表现是"其中一处的宽度莫名其妙跟另一处一样",且改一句无关的模板就会翻转。',
287
+ remedy: `给其中一个换个 id(如 “${node.id}-2”),或者给它们各自的 anchor —— 两个节点必须能被分别指到。`,
288
+ ...(node.src !== undefined ? { src: node.src } : {}),
289
+ });
290
+ }
291
+ ids.set(node.id, path);
292
+
293
+ // sizing 的三档闭集:缺席合法(本层按节点类型推导并记 decisions),写了就必须是三档之一。
294
+ // 此前这里不核,`validateConstraint` 也不核——闭集之外的值两边都不认识,
295
+ // 求解器既不按 fixed 取 width、也不按 fill 分余量,于是该项**静默缩到 min**(没写 min 就是 0rem)。
296
+ // 页面组合层与编译器已在声明期按同一份常量拦过;这一道守的是直接喂 IR 树的调用方。
297
+ if (node.sizing !== undefined && !isOouiSizing(node.sizing)) {
298
+ throw shapeError({
299
+ code: 'OOUI-SPA-SIZING-UNKNOWN',
300
+ path,
301
+ situation: `${path}.sizing 是 ${describeOouiValue(node.sizing)},不在尺寸意图三档里。`,
302
+ problem: '闭集之外的 sizing 既不是 fixed(按 width 定宽)也不是 fill(分余量),求解器只剩"从 min 起步"这一条:该项静默缩到下界,没写 min 就是 0rem。CSS 照样合法、页面照样渲染,只是这一格挤成一条缝。',
303
+ remedy: `sizing 只能是 ${SOMA_OOUI_SIZINGS.join(' / ')}:fixed 就这么宽(须同时给 width);hug 内容多宽我多宽(不能再给 min / max);fill 剩下的给我。省略则由本层按节点类型推导,并记进 decisions。`,
304
+ ...(node.src !== undefined ? { src: node.src } : {}),
305
+ });
306
+ }
307
+
308
+ if (node.kind === 'component') {
309
+ if (typeof node.component !== 'string' || node.component === '') {
310
+ throw shapeError({
311
+ path,
312
+ situation: `${path}.component 是 ${describeOouiValue(node.component)},不是契约名。`,
313
+ problem: 'component 节点是求解边界,它的名字是"边界那头是谁"的唯一答案。空名字让边界记录退化成一条查不到出处的占位。',
314
+ remedy: `写组件契约名(PascalCase),纯文本节点写 '${SOMA_TEXT_NODE}'。`,
315
+ ...(node.src !== undefined ? { src: node.src } : {}),
316
+ });
317
+ }
318
+ return; // 组件不下探:类型上就没有 children
319
+ }
320
+
321
+ if (node.kind === 'leaf') return;
322
+
323
+ if (node.kind === 'intrinsic') {
324
+ if (!(SOMA_INTRINSIC_PRIMITIVES as readonly string[]).includes(node.primitive)) {
325
+ throw new SomaSpatialError({
326
+ layer: 'spatial',
327
+ code: 'OOUI-SPA-INTRINSIC-UNKNOWN',
328
+ situation: `${path}.primitive 是 “${String(node.primitive)}”,不在原语闭集里。`,
329
+ problem: '未知原语没有对应的排布语义,本层既不分配也不知道该发什么——结果是这个容器什么 CSS 都没有,子项按正常流各占一行。浏览器不报错,页面"能看",只是排版不对。',
330
+ remedy: `原语闭集:${SOMA_INTRINSIC_PRIMITIVES.join(' / ')}。判据是"这个排布的结果不依赖有几个子项"。真要一种表外排布,先问它是不是其实需要分配——需要分配的用 kind: 'group'(axis: 'inline'),不需要的才扩这个闭集。`,
331
+ ...(node.src !== undefined ? { src: node.src } : {}),
332
+ });
333
+ }
334
+ }
335
+
336
+ if (node.kind === 'group') {
337
+ if (!(SOMA_SPATIAL_AXES as readonly string[]).includes(node.axis)) {
338
+ throw shapeError({
339
+ path,
340
+ situation: `${path}.axis 是 ${describeOouiValue(node.axis)},不是 ${SOMA_SPATIAL_AXES.join(' / ')}。`,
341
+ problem: '一个组是横排还是竖排没有合理的缺省。靠猜的那一刻,"猜错了"的表现就是排版方向反了,而这在没有设计稿对照时没人说得清是不是 bug。',
342
+ remedy: "axis: 'inline'(行内排列,进求解器分配宽度)或 axis: 'block'(块轴堆叠,只发排列 CSS——Web 的高度应内容驱动,架构 D5)。",
343
+ ...(node.src !== undefined ? { src: node.src } : {}),
344
+ });
345
+ }
346
+
347
+ if (node.axis === 'block' && (node.align !== undefined || (node.wrap !== undefined && node.wrap !== 'none'))) {
348
+ throw shapeError({
349
+ path,
350
+ situation: `${path} 是 block 轴,却声明了 ${node.align !== undefined ? 'align' : 'wrap'}。`,
351
+ problem: 'block 轴不分配尺寸,align / wrap 这两个词在这里没有求解含义。放行它们等于让作者以为自己声明了一件事,而产物里一个字都没有——声明写了没生效,是本体系最不该有的形态。',
352
+ remedy: "块轴的交叉轴对齐走一级原子类:classes: ['soma-align-center'](词表见 soma-ui/src/ooui/utilities.ts 的 align 词条)。真要横排换行,改成 axis: 'inline' 并声明 wrap: 'below'。",
353
+ ...(node.src !== undefined ? { src: node.src } : {}),
354
+ });
355
+ }
356
+
357
+ // 铁律四:子项数运行时可变的组,分配出来的每个 rem 值都是拿初始值打的赌。
358
+ if (node.cardinality === 'unknown' && node.axis === 'inline' && (node.wrap ?? 'none') === 'none') {
359
+ throw new SomaSpatialError({
360
+ layer: 'spatial',
361
+ code: 'OOUI-SPA-VARIABLE-CARDINALITY',
362
+ situation: `${path} 声明了 cardinality: 'unknown'(子项数运行时可变),却是一个不换行的 inline 组。`,
363
+ problem: '逐档分配是按**声明时的子项数**算的:三项分 36rem,各得 12rem。运行时被 reactions 的 options 补丁换成八项时,产物里那三条 flex 值还在,多出来的五项各自被挤成内容宽。页面渲染正常、控制台干净,只是"这一排看着有点挤"(架构 §33.2 实测)。铁律四:编译期决策必须对运行时可变量取保守边界,不得取初始值。',
364
+ remedy: "三条修法,按代价从小到大:"
365
+ + "\n ① 改用 CSS 自解的原语(不依赖子项数):{ kind: 'intrinsic', primitive: 'wrap' } 或 'autofit';"
366
+ + "\n ② 保留 inline 组但声明 wrap: 'below' —— 放不下时整组竖排,多出来的项各占一行;"
367
+ + "\n ③ 子项数确实有上界时,由上游把上界展开成固定子项,并把 cardinality 改回 'known'。",
368
+ ...(node.src !== undefined ? { src: node.src } : {}),
369
+ });
370
+ }
371
+ }
372
+
373
+ const children = node.children;
374
+ if (!Array.isArray(children) || children.length === 0) {
375
+ throw shapeError({
376
+ path,
377
+ situation: `${path}(kind: ${node.kind})的 children 是 ${describeOouiValue(children)}。`,
378
+ problem: '空容器会发出一条谁也套不到的规则:CSS 有了、元素有了、里面没东西。它不报错,只是页面上多一个高度为零的盒子,而排查的人会先怀疑数据没来。',
379
+ remedy: '容器至少要有一个子项。确实可能为空的区域,应由上游决定"不产出这个节点",而不是产出一个空组。',
380
+ ...(node.src !== undefined ? { src: node.src } : {}),
381
+ });
382
+ }
383
+
384
+ children.forEach((child, index) => {
385
+ validateNode(child, `${path}.${childKey(child, index)}`, ids);
386
+ });
387
+ }
388
+
389
+ // ─────────────────────────────────────────────────────────────
390
+ // 遍历与求解
391
+ // ─────────────────────────────────────────────────────────────
392
+
393
+ interface WalkFrame {
394
+ /** 父节点是否为本节点分配了宽度(只有 inline 组会) */
395
+ allocated: boolean;
396
+ /** 分配不了时,是谁挡住了(用于 unchecked 的可读性) */
397
+ under: string;
398
+ }
399
+
400
+ function walk(node: SomaSpatialNode, path: string, context: WalkContext, frame: WalkFrame): void {
401
+ context.stats.nodes += 1;
402
+ for (const className of node.classes ?? []) context.classes.add(className);
403
+
404
+ if (node.kind === 'leaf') {
405
+ context.stats.leaves += 1;
406
+ return;
407
+ }
408
+
409
+ if (node.kind === 'component') {
410
+ context.stats.components += 1;
411
+ context.boundaries.push({
412
+ path,
413
+ id: node.id,
414
+ kind: 'component',
415
+ component: node.component,
416
+ reason: '组件边界即编译边界(架构 D4):内部排布由组件自己的 CSS 预编译,页面这一侧不下探',
417
+ });
418
+ if (node.minInline !== undefined && !frame.allocated) {
419
+ context.unchecked.push({
420
+ path,
421
+ id: node.id,
422
+ component: node.component,
423
+ minInline: node.minInline,
424
+ under: frame.under,
425
+ reason: '父节点不分配宽度(块轴 / CSS 自解原语 / 根),可用宽在编译期量不出来',
426
+ });
427
+ }
428
+ return;
429
+ }
430
+
431
+ if (node.kind === 'intrinsic') {
432
+ context.stats.intrinsics += 1;
433
+ context.boundaries.push({
434
+ path,
435
+ id: node.id,
436
+ kind: 'intrinsic',
437
+ primitive: node.primitive,
438
+ reason: `原语 “${node.primitive}” 的分配由 CSS 自己完成(架构 D6),本层不分配尺寸;子树仍然遍历,因为里面的每个 group 都是自己的容器`,
439
+ });
440
+ node.children.forEach((child, index) => {
441
+ walk(child, `${path}.${childKey(child, index)}`, context, { allocated: false, under: path });
442
+ });
443
+ return;
444
+ }
445
+
446
+ context.stats.groups += 1;
447
+ const selector = context.selectorOf(node);
448
+ if (node.axis === 'block') {
449
+ // 只发排列 CSS,不分配(架构 D5)。gap 的文法仍要校——写错单位的 gap
450
+ // 在 CSS 里是一条被丢弃的声明,表现是"这一列贴在一起了"。
451
+ if (node.gap !== undefined) toRemGuarded(node.gap, WIDEST_REM, `${path}.gap`);
452
+ context.groups.push({
453
+ path,
454
+ id: node.id,
455
+ axis: 'block',
456
+ selector,
457
+ solutions: [],
458
+ css: emitBlockCss(node, selector),
459
+ });
460
+ } else {
461
+ context.groups.push(solveInlineGroup(node, path, selector, context));
462
+ context.stats.solvedGroups += 1;
463
+ context.stats.steps += CONTAINER_STEPS.length - context.floorIndex;
464
+ }
465
+
466
+ const allocated = node.axis === 'inline';
467
+ node.children.forEach((child, index) => {
468
+ walk(child, `${path}.${childKey(child, index)}`, context, { allocated, under: path });
469
+ });
470
+ }
471
+
472
+ function solveInlineGroup(
473
+ node: SomaSpatialGroupNode,
474
+ path: string,
475
+ selector: string,
476
+ context: WalkContext,
477
+ ): SomaSpatialGroupSolution {
478
+ const byId = new Map<string, SomaSpatialNode>();
479
+ const nodes: Record<string, SomaLayoutNodeConstraint> = {};
480
+
481
+ node.children.forEach((child, index) => {
482
+ const childPath = `${path}.${childKey(child, index)}`;
483
+ byId.set(child.id, child);
484
+ nodes[child.id] = childConstraint(child, childPath, context);
485
+ });
486
+
487
+ const constraint: SomaLayoutConstraint = {
488
+ nodes,
489
+ ...(node.gap !== undefined ? { gap: node.gap } : {}),
490
+ ...(node.wrap !== undefined ? { wrap: node.wrap } : {}),
491
+ ...(node.align !== undefined ? { align: node.align } : {}),
492
+ ...(node.containerName !== undefined ? { container_name: node.containerName } : {}),
493
+ };
494
+
495
+ guardLayout(() => validateConstraint(constraint, path), path, undefined, node.src);
496
+
497
+ // 八档各解一次。窄于 minContainerRem 的档不可达,沿用最窄可达档的解——
498
+ // 长度必须仍是八档:`emitLayoutCss` 按下标取档位 rem,少一档会让所有
499
+ // `@container` 阈值整体错位,而错位后的 CSS 依然合法。
500
+ const solutions: SomaLayoutSolution[] = [];
501
+ for (let index = context.floorIndex; index < CONTAINER_STEPS.length; index += 1) {
502
+ const [name, rem] = CONTAINER_STEPS[index];
503
+ solutions.push(guardLayout(
504
+ () => solveStep(constraint, rem, name, path),
505
+ path,
506
+ name,
507
+ node.src,
508
+ ));
509
+ }
510
+ const floorSolution = solutions[0];
511
+ for (let index = context.floorIndex - 1; index >= 0; index -= 1) {
512
+ const [name, rem] = CONTAINER_STEPS[index];
513
+ solutions.unshift({ ...floorSolution, breakpoint: name, containerRem: rem });
514
+ }
515
+
516
+ // ── 闸门:组件塞得下(架构 §8 第四行) ──────────────────────────
517
+ const wrap = node.wrap ?? 'none';
518
+ for (let index = context.floorIndex; index < CONTAINER_STEPS.length; index += 1) {
519
+ const solution = solutions[index];
520
+ for (const [childId, child] of byId) {
521
+ if (child.kind !== 'component' || child.minInline === undefined) continue;
522
+ const sizing = nodes[childId].sizing;
523
+ if (sizing === 'hug') continue; // hug 的宽度由内容决定,编译期量不出来(已记 unchecked)
524
+ const required = toRemGuarded(child.minInline, solution.containerRem, `${path}.${childId}.minInline`);
525
+ // 换行档上每项独占一行,可用宽是整个容器宽,不是解出来的那个 rem 值
526
+ const available = solution.wrapped && wrap === 'below'
527
+ ? solution.containerRem
528
+ : solution.widths[childId];
529
+ if (available + EPSILON < required) {
530
+ throw tooWide({
531
+ path: `${path}.${childId}`,
532
+ component: child.component,
533
+ breakpoint: solution.breakpoint,
534
+ available,
535
+ required,
536
+ minInline: child.minInline,
537
+ ...(child.src !== undefined ? { src: child.src } : {}),
538
+ });
539
+ }
540
+ }
541
+ }
542
+
543
+ // hug 的组件:塞得下这条闸门核对不了,如实记下来
544
+ for (const [childId, child] of byId) {
545
+ if (child.kind !== 'component' || child.minInline === undefined) continue;
546
+ if (nodes[childId].sizing !== 'hug') continue;
547
+ context.unchecked.push({
548
+ path: `${path}.${childId}`,
549
+ id: child.id,
550
+ component: child.component,
551
+ minInline: child.minInline,
552
+ under: path,
553
+ reason: "显式声明了 sizing: 'hug' —— 宽度由内容决定,编译期量不出可用宽",
554
+ });
555
+ }
556
+
557
+ const css = emitLayoutCss({ constraint, solutions }, {
558
+ root: selector,
559
+ selectorOf: (name) => {
560
+ const child = byId.get(name);
561
+ return child === undefined ? `${selector} > [data-soma-node="${name}"]` : `${selector} > ${context.selectorOf(child)}`;
562
+ },
563
+ });
564
+
565
+ return { path, id: node.id, axis: 'inline', selector, constraint, solutions, css };
566
+ }
567
+
568
+ /**
569
+ * 一个子项的约束。**缺省值在这里产生,并逐条记进 `decisions`**(铁律三:
570
+ * 作者写的与系统补的必须可区分)。
571
+ */
572
+ function childConstraint(
573
+ child: SomaSpatialNode,
574
+ path: string,
575
+ context: WalkContext,
576
+ ): SomaLayoutNodeConstraint {
577
+ const derived = deriveSizing(child);
578
+ const sizing = child.sizing ?? derived.sizing;
579
+ if (child.sizing === undefined) {
580
+ context.decisions.push({
581
+ path,
582
+ conclusion: `sizing 取 ${derived.sizing}`,
583
+ rule: derived.rule,
584
+ origin: 'inferred',
585
+ ...(child.src !== undefined ? { src: child.src } : {}),
586
+ });
587
+ }
588
+
589
+ const constraint: SomaLayoutNodeConstraint = { sizing };
590
+ if (child.width !== undefined) constraint.width = child.width;
591
+ if (child.max !== undefined) constraint.max = child.max;
592
+ if (child.priority !== undefined) constraint.priority = child.priority;
593
+
594
+ // **不把 `minInline` 抬成 `min`。** 看着很顺手,实测是把两道闸门合并成一道:
595
+ // 一旦 minInline 进了约束,求解器要么满足它、要么报"不可满足",
596
+ // "组件塞不下"这条分支就**永远不可达**了——而它报出来的
597
+ // "组件 X 在 cqSm 档上塞不下:可用宽 4rem,要求 24rem" 正是作者最需要的那句话,
598
+ // 换成"这两条 min 打架"反而指不到组件契约上。
599
+ // 两者本来就是两件事:`min` 是作者写的布局下界,`minInline` 是构件层带下来的
600
+ // 组件契约要求;合并之后,产物里再也分不出这个下界是谁提的。
601
+ if (child.min !== undefined) constraint.min = child.min;
602
+ return constraint;
603
+ }
604
+
605
+ /** 缺省 sizing 的推导。**每一条都要说得出理由**——说不出理由的缺省就是猜 */
606
+ function deriveSizing(child: SomaSpatialNode): { sizing: SomaSizing; rule: string } {
607
+ if (child.cardinality === 'unknown') {
608
+ return {
609
+ sizing: 'fill',
610
+ rule: "铁律四:基数运行时可变 → fill(能承载任意数量),不按声明时的内容定宽",
611
+ };
612
+ }
613
+ if (child.kind === 'component' && child.minInline !== undefined) {
614
+ return {
615
+ sizing: 'fill',
616
+ rule: '组件声明了 minInline → fill + min;hug 与 min/max 不能共存(两个来源争同一个数)',
617
+ };
618
+ }
619
+ if (child.kind === 'group' || child.kind === 'intrinsic') {
620
+ return { sizing: 'fill', rule: '容器型子项默认占满可用宽' };
621
+ }
622
+ return { sizing: 'hug', rule: '叶子与无 minInline 的组件默认由内容定宽' };
623
+ }
624
+
625
+ // ─────────────────────────────────────────────────────────────
626
+ // CSS(block 轴)
627
+ // ─────────────────────────────────────────────────────────────
628
+
629
+ /**
630
+ * block 轴只发排列 CSS(架构 D5)。
631
+ *
632
+ * 为什么仍然声明 `container-type`:子孙的 `@container` 是相对**最近的容器祖先**
633
+ * 求值的。块轴组不声明容器的话,里面的 inline 组的断点会跳过这一层去量更外面的盒子,
634
+ * 表现是"某一档上里层的布局提前/推迟切换了"——而那种错只在特定宽度下可见。
635
+ */
636
+ function emitBlockCss(node: SomaSpatialGroupNode, selector: string): string {
637
+ const lines = [
638
+ `${selector} {`,
639
+ ' display: flex;',
640
+ ' flex-direction: column;',
641
+ node.containerName === undefined
642
+ ? ' container-type: inline-size;'
643
+ : ` container: ${node.containerName} / inline-size;`,
644
+ ];
645
+ if (node.gap !== undefined) lines.push(` gap: ${node.gap};`);
646
+ lines.push('}');
647
+ return lines.join('\n');
648
+ }
649
+
650
+ // ─────────────────────────────────────────────────────────────
651
+ // 内部
652
+ // ─────────────────────────────────────────────────────────────
653
+
654
+ function defaultSelectorOf(node: SomaSpatialNode): string {
655
+ return node.anchor === undefined
656
+ ? `[data-soma-node="${node.id}"]`
657
+ : `[data-soma-id="${node.anchor}"]`;
658
+ }
659
+
660
+ /** 子项路径用 id,不用下标:下标会让"插了一个子项"把后面所有错误消息的位置全挪一格 */
661
+ function childKey(child: SomaSpatialNode, index: number): string {
662
+ const id = child && typeof child === 'object' ? (child as { id?: unknown }).id : undefined;
663
+ return typeof id === 'string' && id !== '' ? id : `[${index}]`;
664
+ }
665
+
666
+ function resolveFloorIndex(minContainerRem: number | undefined): number {
667
+ if (minContainerRem === undefined) return 0;
668
+ const index = CONTAINER_STEPS.findIndex(([, rem]) => rem >= minContainerRem);
669
+ if (index < 0) {
670
+ throw shapeError({
671
+ path: 'options.minContainerRem',
672
+ situation: `options.minContainerRem = ${minContainerRem}rem 比最宽的一档(${WIDEST_REM}rem)还宽。`,
673
+ problem: '没有任何一档可达,等于宣称这棵树永远不会被渲染——求解会解出一个空的档位集合,而空集合发出来的 CSS 是空串,页面上一条样式都没有,且不报错。',
674
+ remedy: `minContainerRem 必须落在八档之内:${CONTAINER_STEPS.map(([name, rem]) => `${name}=${rem}`).join(' / ')}。`,
675
+ });
676
+ }
677
+ return index;
678
+ }
679
+
680
+ /**
681
+ * 把 `build/layout` 的错误翻译成带错误码与 remedy 的空间层错误。
682
+ *
683
+ * **只翻译,不重判**:`SomaLayoutConstraintError` 已经把打架的两条声明算出来了
684
+ * (`conflict`),这里再判一次等于第二份判据,而两份判据漂开时没有任何断言会红。
685
+ */
686
+ function guardLayout<T>(
687
+ run: () => T,
688
+ path: string,
689
+ breakpoint: string | undefined,
690
+ src: SomaSource | undefined,
691
+ ): T {
692
+ try {
693
+ return run();
694
+ } catch (error) {
695
+ if (!(error instanceof SomaLayoutConstraintError)) throw error;
696
+ const detail = error.message.replace(/^\[SOMA Layout\]\s*/, '');
697
+ throw new SomaSpatialSolveError({
698
+ code: 'OOUI-SPA-UNSATISFIABLE',
699
+ situation: `${path} 的布局约束求不出解:${detail}`,
700
+ problem: '不可满足时"尽力而为"地压下去,产出的 CSS 一样能渲染——只是每一项都比它声明的下限窄,而"下限"这个词的全部意义就是"再窄就不能用了"。页面不报错,表现只是"这一排挤了点"。所以本层不降级,只报打架的那两条声明。',
701
+ remedy: `打架的两条声明:${error.conflict[0]} 与 ${error.conflict[1]}。四条修法:`
702
+ + `\n ① 把其中一条的 min 调小(或去掉),让两者的下限之和落进可用宽;`
703
+ + `\n ② 给这一组声明 wrap: 'below' —— 放不下时整组竖排,每项独占一行;`
704
+ + `\n ③ 用 priority 表明谁该先让:250 = 我愿意被拉大 / 750 = 我不愿意被压小;`
705
+ + `\n ④ 这棵树的容器其实不会那么窄时,给 solveSpatial 传 minContainerRem,`
706
+ + `\n 声明最窄可达档(八档:${CONTAINER_STEPS.map(([name, rem]) => `${name}=${rem}rem`).join(' / ')})。`,
707
+ conflict: error.conflict,
708
+ ...(breakpoint !== undefined ? { breakpoint } : {}),
709
+ ...(src !== undefined ? { src } : {}),
710
+ });
711
+ }
712
+ }
713
+
714
+ function toRemGuarded(literal: string, containerRem: number, where: string): number {
715
+ return guardLayout(() => toRem(literal, containerRem, where), where, undefined, undefined);
716
+ }
717
+
718
+ function tooWide(input: {
719
+ path: string;
720
+ component: string;
721
+ breakpoint: string;
722
+ available: number;
723
+ required: number;
724
+ minInline: string;
725
+ src?: SomaSource;
726
+ }): SomaSpatialError {
727
+ return new SomaSpatialError({
728
+ layer: 'spatial',
729
+ code: 'OOUI-SPA-COMPONENT-TOO-WIDE',
730
+ situation: `${input.path} 的组件 ${input.component} 在 ${input.breakpoint} 档上塞不下:`
731
+ + `可用宽 ${round(input.available)}rem,要求 ${round(input.required)}rem(minInline: ${input.minInline})。`,
732
+ problem: '塞不下的组件不会报错,它会按 CSS 的规则被压扁:表格挤成两列、按钮文字换行、下拉框的箭头压到文字上。这些都是"看着有点丑",没人会当成 bug 报上来,而它只在这一档宽度下复现。',
733
+ remedy: `四条修法:`
734
+ + `\n ① 给这一组声明 wrap: 'below' —— 到这一档就竖排,每项拿到整个容器宽;`
735
+ + `\n ② 调大这个子项的 priority(750 = 不愿意被压小),让别的子项先让;`
736
+ + `\n ③ 换一个 minInline 更小的候选组件(构件层按形态还有别的候选);`
737
+ + `\n ④ 这棵树的容器其实到不了这么窄时,给 solveSpatial 传 minContainerRem,`
738
+ + `\n 声明最窄可达档(八档:${CONTAINER_STEPS.map(([name, rem]) => `${name}=${rem}rem`).join(' / ')})。`,
739
+ ...(input.src !== undefined ? { src: input.src } : {}),
740
+ });
741
+ }
742
+
743
+ function shapeError(input: {
744
+ path: string;
745
+ situation: string;
746
+ problem: string;
747
+ remedy: string;
748
+ code?: string;
749
+ src?: SomaSource;
750
+ }): SomaSpatialError {
751
+ return new SomaSpatialError({
752
+ layer: 'spatial',
753
+ code: input.code ?? 'OOUI-SPA-IR-SHAPE',
754
+ situation: input.situation,
755
+ problem: input.problem,
756
+ remedy: input.remedy,
757
+ ...(input.src !== undefined ? { src: input.src } : {}),
758
+ });
759
+ }
760
+
761
+ /**
762
+ * 四位小数:与 `constraint-solver.round()` 同精度,免得错误消息里出现浮点尾巴。
763
+ *
764
+ * **OOUI 里只此一份。** 真源那份在 `build/layout/constraint-solver.ts` 里是模块私有的
765
+ * (没有导出),本层没法 import;两份的精度必须一致,改一处要同步改另一处。
766
+ */
767
+ function round(value: number): number {
768
+ return Math.round(value * 10_000) / 10_000;
769
+ }