soma-kit 0.0.0-stage → 0.1.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 (353) hide show
  1. package/README.md +539 -2
  2. package/bin/soma-kit.mjs +27 -0
  3. package/package.json +66 -4
  4. package/packs/ai/agent-run-card.ts +64 -0
  5. package/packs/ai/evaluation-card.ts +51 -0
  6. package/packs/ai/guardrail-policy-card.ts +48 -0
  7. package/packs/ai/index.ts +31 -0
  8. package/packs/ai/model-card.ts +55 -0
  9. package/packs/ai/model-routing-card.ts +49 -0
  10. package/packs/ai/prompt-template-card.ts +49 -0
  11. package/packs/ai/texts.ts +19 -0
  12. package/packs/commerce/address-card.ts +58 -0
  13. package/packs/commerce/coupon-card.ts +64 -0
  14. package/packs/commerce/index.ts +25 -0
  15. package/packs/commerce/order-card.ts +60 -0
  16. package/packs/commerce/purchase-order-card.ts +74 -0
  17. package/packs/commerce/texts.ts +14 -0
  18. package/packs/finance/index.ts +30 -0
  19. package/packs/finance/invoice-summary-card.ts +48 -0
  20. package/packs/finance/reconcile-board.ts +450 -0
  21. package/packs/finance/reconcile-case-card.ts +70 -0
  22. package/packs/finance/reconcile-desk/compile.ts +208 -0
  23. package/packs/finance/reconcile-desk/index.ts +20 -0
  24. package/packs/finance/reconcile-desk/shell.ts +27 -0
  25. package/packs/finance/texts.ts +21 -0
  26. package/packs/ops/change-window-card.ts +54 -0
  27. package/packs/ops/dependency-status-card.ts +50 -0
  28. package/packs/ops/error-budget-card.ts +60 -0
  29. package/packs/ops/execution-task-runner.ts +61 -0
  30. package/packs/ops/index.ts +36 -0
  31. package/packs/ops/integration-status-card.ts +45 -0
  32. package/packs/ops/release-readiness-card.ts +63 -0
  33. package/packs/ops/runbook-execution-card.ts +81 -0
  34. package/packs/ops/texts.ts +21 -0
  35. package/packs/security/control-evidence-card.ts +54 -0
  36. package/packs/security/finding-card.ts +96 -0
  37. package/packs/security/index.ts +29 -0
  38. package/packs/security/texts.ts +31 -0
  39. package/packs/shared/card-util.ts +60 -0
  40. package/packs/shared/wrap.ts +13 -0
  41. package/spec/generated/kit-app.schema.json +84 -0
  42. package/spec/generated/kit-page.schema.json +2766 -0
  43. package/spec/kit-grammar.json +1358 -0
  44. package/spec/kit-grammar.schema.json +716 -0
  45. package/src/app/app-config.ts +108 -0
  46. package/src/app/compose-apps.ts +139 -0
  47. package/src/app/define-kit-actions.ts +89 -0
  48. package/src/app/define-kit-app.ts +362 -0
  49. package/src/app/define-kit-pack.ts +114 -0
  50. package/src/app/envelope.ts +117 -0
  51. package/src/app/index.ts +50 -0
  52. package/src/app/notify-renderer.ts +114 -0
  53. package/src/app/paged-list-adapter.ts +246 -0
  54. package/src/app/server-pages.ts +303 -0
  55. package/src/app/server.ts +244 -0
  56. package/src/app/submit.types.ts +87 -0
  57. package/src/base/action-busy.ts +159 -0
  58. package/src/base/action-gate.ts +267 -0
  59. package/src/base/action-status.ts +31 -0
  60. package/src/base/alert.ts +136 -0
  61. package/src/base/avatar.ts +271 -0
  62. package/src/base/button.ts +139 -0
  63. package/src/base/cascader.ts +523 -0
  64. package/src/base/check-core.ts +214 -0
  65. package/src/base/checkbox.ts +35 -0
  66. package/src/base/choice.ts +183 -0
  67. package/src/base/color-picker.ts +316 -0
  68. package/src/base/combobox.ts +61 -0
  69. package/src/base/command-palette.ts +371 -0
  70. package/src/base/context-menu.ts +103 -0
  71. package/src/base/countdown.ts +168 -0
  72. package/src/base/date-range.ts +444 -0
  73. package/src/base/date.ts +899 -0
  74. package/src/base/divider.ts +156 -0
  75. package/src/base/fab.ts +192 -0
  76. package/src/base/icons.ts +106 -0
  77. package/src/base/image.ts +177 -0
  78. package/src/base/index.ts +214 -0
  79. package/src/base/input.ts +316 -0
  80. package/src/base/kbd.ts +99 -0
  81. package/src/base/link.ts +167 -0
  82. package/src/base/listbox-core.ts +965 -0
  83. package/src/base/mentions.ts +323 -0
  84. package/src/base/menu-button.ts +240 -0
  85. package/src/base/menu-core.ts +341 -0
  86. package/src/base/month-grid.ts +171 -0
  87. package/src/base/motion/aura.ts +94 -0
  88. package/src/base/motion/hover-3d.ts +154 -0
  89. package/src/base/motion/hover-gallery.ts +185 -0
  90. package/src/base/motion/index.ts +27 -0
  91. package/src/base/motion/limits.ts +75 -0
  92. package/src/base/motion/marquee.ts +157 -0
  93. package/src/base/motion/text-rotate.ts +195 -0
  94. package/src/base/number.ts +121 -0
  95. package/src/base/otp.ts +259 -0
  96. package/src/base/permission-gate.ts +99 -0
  97. package/src/base/popover.ts +352 -0
  98. package/src/base/popup.ts +542 -0
  99. package/src/base/portal-core.ts +297 -0
  100. package/src/base/price-text.ts +126 -0
  101. package/src/base/progress.ts +216 -0
  102. package/src/base/qr-code.ts +446 -0
  103. package/src/base/qty-stepper.ts +241 -0
  104. package/src/base/radio.ts +33 -0
  105. package/src/base/range.ts +444 -0
  106. package/src/base/rating.ts +249 -0
  107. package/src/base/segmented.ts +286 -0
  108. package/src/base/select.ts +57 -0
  109. package/src/base/shared.ts +708 -0
  110. package/src/base/swap.ts +86 -0
  111. package/src/base/switch.ts +111 -0
  112. package/src/base/tag-input.ts +464 -0
  113. package/src/base/tag.ts +250 -0
  114. package/src/base/text.ts +126 -0
  115. package/src/base/textarea.ts +129 -0
  116. package/src/base/time-picker.ts +606 -0
  117. package/src/base/tree-select.ts +629 -0
  118. package/src/base/upload.ts +548 -0
  119. package/src/base/virtual-list.ts +286 -0
  120. package/src/biz/approval-desk/compile.ts +179 -0
  121. package/src/biz/approval-desk/index.ts +21 -0
  122. package/src/biz/approval-desk/shell.ts +50 -0
  123. package/src/biz/auth-panel/compile.ts +196 -0
  124. package/src/biz/auth-panel/index.ts +24 -0
  125. package/src/biz/auth-panel/shell.ts +46 -0
  126. package/src/biz/category-crud/compile.ts +173 -0
  127. package/src/biz/category-crud/index.ts +19 -0
  128. package/src/biz/category-crud/shell.ts +29 -0
  129. package/src/biz/checkout-page/compile.ts +111 -0
  130. package/src/biz/checkout-page/index.ts +20 -0
  131. package/src/biz/checkout-page/shell.ts +50 -0
  132. package/src/biz/compose.ts +313 -0
  133. package/src/biz/data-components.ts +26 -0
  134. package/src/biz/define.ts +23 -0
  135. package/src/biz/import-wizard/compile.ts +204 -0
  136. package/src/biz/import-wizard/hub.ts +540 -0
  137. package/src/biz/import-wizard/index.ts +24 -0
  138. package/src/biz/import-wizard/shell.ts +161 -0
  139. package/src/biz/index.ts +80 -0
  140. package/src/biz/landing-page/compile.ts +67 -0
  141. package/src/biz/landing-page/index.ts +20 -0
  142. package/src/biz/landing-page/shell.ts +48 -0
  143. package/src/biz/link/hub.ts +255 -0
  144. package/src/biz/link/shared.ts +493 -0
  145. package/src/biz/master-sub/compile.ts +232 -0
  146. package/src/biz/master-sub/index.ts +20 -0
  147. package/src/biz/master-sub/shell.ts +56 -0
  148. package/src/biz/multi-board/compile.ts +234 -0
  149. package/src/biz/multi-board/index.ts +19 -0
  150. package/src/biz/multi-board/shell.ts +70 -0
  151. package/src/biz/names.ts +30 -0
  152. package/src/biz/notification-center/compile.ts +138 -0
  153. package/src/biz/notification-center/index.ts +29 -0
  154. package/src/biz/notification-center/shell.ts +42 -0
  155. package/src/biz/page-templates/result-page/compile.ts +46 -0
  156. package/src/biz/page-templates/result-page/index.ts +19 -0
  157. package/src/biz/page-templates/result-page/shell.ts +31 -0
  158. package/src/biz/page-templates/shared.ts +121 -0
  159. package/src/biz/page-templates/sign-in-page/compile.ts +176 -0
  160. package/src/biz/page-templates/sign-in-page/index.ts +18 -0
  161. package/src/biz/page-templates/sign-in-page/shell.ts +116 -0
  162. package/src/biz/record-detail/compile.ts +290 -0
  163. package/src/biz/record-detail/index.ts +22 -0
  164. package/src/biz/record-detail/shell.ts +64 -0
  165. package/src/biz/settings-center/compile.ts +100 -0
  166. package/src/biz/settings-center/index.ts +18 -0
  167. package/src/biz/settings-center/shell.ts +51 -0
  168. package/src/biz/shared/action-host.ts +469 -0
  169. package/src/biz/shared/coordinator.ts +516 -0
  170. package/src/biz/shared/index.ts +9 -0
  171. package/src/biz/shared/pipes.ts +58 -0
  172. package/src/biz/shared/runtime-hub.ts +112 -0
  173. package/src/biz/shared/step-values.ts +25 -0
  174. package/src/biz/single-form/compile.ts +146 -0
  175. package/src/biz/single-form/index.ts +18 -0
  176. package/src/biz/single-form/shell.ts +38 -0
  177. package/src/biz/standard-crud/bridge.ts +11 -0
  178. package/src/biz/standard-crud/compile.ts +546 -0
  179. package/src/biz/standard-crud/index.ts +18 -0
  180. package/src/biz/standard-crud/shell.ts +157 -0
  181. package/src/biz/step-form/compile.ts +400 -0
  182. package/src/biz/step-form/hub.ts +412 -0
  183. package/src/biz/step-form/index.ts +23 -0
  184. package/src/biz/step-form/shell.ts +96 -0
  185. package/src/biz/step-form/steps-ref.ts +112 -0
  186. package/src/biz/types.ts +96 -0
  187. package/src/cli/kit-cli.ts +102 -0
  188. package/src/compile/action-host-attach.ts +76 -0
  189. package/src/compile/compile-page.ts +472 -0
  190. package/src/compile/component-candidates.ts +147 -0
  191. package/src/compile/fragment.ts +104 -0
  192. package/src/compile/hints.ts +255 -0
  193. package/src/compile/index.ts +16 -0
  194. package/src/compile/locate.ts +166 -0
  195. package/src/compile/page-params.ts +80 -0
  196. package/src/compile/parse.ts +355 -0
  197. package/src/compile/redirect.ts +90 -0
  198. package/src/compile/registry.ts +30 -0
  199. package/src/compile/remove-guard.ts +99 -0
  200. package/src/compile/styles.ts +244 -0
  201. package/src/compile/types.ts +106 -0
  202. package/src/data/amount-breakdown.ts +132 -0
  203. package/src/data/anchor-nav.ts +225 -0
  204. package/src/data/approval-flow.ts +269 -0
  205. package/src/data/assignment-picker.ts +652 -0
  206. package/src/data/async-result-panel.ts +308 -0
  207. package/src/data/breadcrumbs.ts +197 -0
  208. package/src/data/calendar.ts +363 -0
  209. package/src/data/carousel.ts +408 -0
  210. package/src/data/chart.ts +726 -0
  211. package/src/data/checklist.ts +215 -0
  212. package/src/data/code-view.ts +415 -0
  213. package/src/data/comment-thread.ts +342 -0
  214. package/src/data/confirm-dialog.ts +144 -0
  215. package/src/data/context-menu.ts +216 -0
  216. package/src/data/d9-limits.ts +42 -0
  217. package/src/data/d9-util.ts +81 -0
  218. package/src/data/diff.ts +239 -0
  219. package/src/data/display-util.ts +135 -0
  220. package/src/data/dock.ts +152 -0
  221. package/src/data/embed.ts +200 -0
  222. package/src/data/field-mapper.ts +544 -0
  223. package/src/data/flow-editor-contract.ts +41 -0
  224. package/src/data/flow-editor.ts +2622 -0
  225. package/src/data/flow-remote-options.ts +257 -0
  226. package/src/data/footer.ts +157 -0
  227. package/src/data/form-draft-registry.ts +76 -0
  228. package/src/data/gantt.ts +430 -0
  229. package/src/data/hero.ts +149 -0
  230. package/src/data/image-viewer.ts +333 -0
  231. package/src/data/index.ts +268 -0
  232. package/src/data/item-list.ts +335 -0
  233. package/src/data/kanban.ts +667 -0
  234. package/src/data/media-grid.ts +246 -0
  235. package/src/data/mega-menu.ts +257 -0
  236. package/src/data/menu-dom.ts +169 -0
  237. package/src/data/menu.ts +464 -0
  238. package/src/data/mockup.ts +176 -0
  239. package/src/data/modal-dialog.ts +182 -0
  240. package/src/data/navbar.ts +292 -0
  241. package/src/data/object-form.ts +1981 -0
  242. package/src/data/options-bus.ts +24 -0
  243. package/src/data/outcome-watch.ts +40 -0
  244. package/src/data/overlay-portal.ts +6 -0
  245. package/src/data/pager.ts +473 -0
  246. package/src/data/permission-matrix.ts +432 -0
  247. package/src/data/permission-tree.ts +916 -0
  248. package/src/data/pricing-table.ts +269 -0
  249. package/src/data/prompt-dialog.ts +235 -0
  250. package/src/data/reaction-bar.ts +236 -0
  251. package/src/data/record-card.ts +413 -0
  252. package/src/data/record-picker.ts +489 -0
  253. package/src/data/redirect.ts +109 -0
  254. package/src/data/remote-options.ts +54 -0
  255. package/src/data/request-console.ts +399 -0
  256. package/src/data/resident.ts +58 -0
  257. package/src/data/result-panel.ts +160 -0
  258. package/src/data/rich-text.ts +626 -0
  259. package/src/data/row-editor.ts +1066 -0
  260. package/src/data/rule-builder.ts +1137 -0
  261. package/src/data/shape-util.ts +221 -0
  262. package/src/data/staged-rows.ts +69 -0
  263. package/src/data/stat-group.ts +231 -0
  264. package/src/data/static-lazy.ts +63 -0
  265. package/src/data/static-registry.ts +227 -0
  266. package/src/data/steps.ts +195 -0
  267. package/src/data/survey.ts +455 -0
  268. package/src/data/system-switcher.ts +243 -0
  269. package/src/data/timeline.ts +204 -0
  270. package/src/data/tour-guide.ts +392 -0
  271. package/src/data/transfer.ts +597 -0
  272. package/src/data/tree-check.ts +30 -0
  273. package/src/data/tree-table.ts +674 -0
  274. package/src/data/tree.ts +656 -0
  275. package/src/data/trend-line.ts +147 -0
  276. package/src/data/virtual-rows.ts +556 -0
  277. package/src/data/watermark.ts +140 -0
  278. package/src/data/wrap.ts +267 -0
  279. package/src/data/wrapped-candidates.ts +96 -0
  280. package/src/frames/blank-frame.ts +19 -0
  281. package/src/frames/index.ts +44 -0
  282. package/src/frames/page-bar.ts +185 -0
  283. package/src/frames/page-header.ts +185 -0
  284. package/src/frames/page-status.ts +54 -0
  285. package/src/frames/resize-handle.ts +147 -0
  286. package/src/frames/shared.ts +242 -0
  287. package/src/frames/single-frame.ts +16 -0
  288. package/src/frames/split-frame/index.ts +4 -0
  289. package/src/frames/split-frame/shell.ts +219 -0
  290. package/src/frames/split-frame/span.ts +64 -0
  291. package/src/frames/split-frame/wiring.ts +164 -0
  292. package/src/frames/tabs-frame/index.ts +3 -0
  293. package/src/frames/tabs-frame/shell.ts +112 -0
  294. package/src/frames/tabs-frame/wiring.ts +69 -0
  295. package/src/frames/top-main-frame.ts +20 -0
  296. package/src/frames/types.ts +72 -0
  297. package/src/frames/workspace-frame/extras.ts +197 -0
  298. package/src/frames/workspace-frame/index.ts +13 -0
  299. package/src/frames/workspace-frame/shell.ts +282 -0
  300. package/src/frames/workspace-frame/state.ts +152 -0
  301. package/src/frames/workspace-frame/view.ts +1013 -0
  302. package/src/generated/kit-grammar-runtime.ts +2822 -0
  303. package/src/generated/page-origin.ts +57 -0
  304. package/src/i18n/index.ts +22 -0
  305. package/src/i18n/kit-text.ts +692 -0
  306. package/src/i18n/resolve-text-refs.ts +128 -0
  307. package/src/index.ts +6 -0
  308. package/src/object-renderer/action-gate.ts +216 -0
  309. package/src/object-renderer/adopt-gate.ts +333 -0
  310. package/src/object-renderer/arrange.ts +411 -0
  311. package/src/object-renderer/candidates.ts +68 -0
  312. package/src/object-renderer/collapse-wiring.ts +99 -0
  313. package/src/object-renderer/collection-expand.ts +185 -0
  314. package/src/object-renderer/collection-parts.ts +653 -0
  315. package/src/object-renderer/collection-table.ts +503 -0
  316. package/src/object-renderer/collection.ts +628 -0
  317. package/src/object-renderer/compile-data.ts +549 -0
  318. package/src/object-renderer/defaults.ts +252 -0
  319. package/src/object-renderer/display-checks.ts +153 -0
  320. package/src/object-renderer/emit-events.ts +498 -0
  321. package/src/object-renderer/emit-object.ts +98 -0
  322. package/src/object-renderer/emit-static.ts +1036 -0
  323. package/src/object-renderer/field-policy.ts +89 -0
  324. package/src/object-renderer/field-value.ts +581 -0
  325. package/src/object-renderer/form-detail.ts +116 -0
  326. package/src/object-renderer/index.ts +13 -0
  327. package/src/object-renderer/linkage.ts +371 -0
  328. package/src/object-renderer/merge-class.ts +126 -0
  329. package/src/object-renderer/mode.ts +25 -0
  330. package/src/object-renderer/outcome-draft.ts +61 -0
  331. package/src/object-renderer/parts.ts +136 -0
  332. package/src/object-renderer/pick-component.ts +36 -0
  333. package/src/object-renderer/render-object.ts +724 -0
  334. package/src/object-renderer/request-actions.ts +581 -0
  335. package/src/object-renderer/skeleton.ts +101 -0
  336. package/src/object-renderer/table-actions.ts +438 -0
  337. package/src/object-renderer/table-summary.ts +105 -0
  338. package/src/object-renderer/table-tools.ts +1072 -0
  339. package/src/object-renderer/types.ts +936 -0
  340. package/src/page-target/ai-surface.ts +154 -0
  341. package/src/page-target/compile.ts +354 -0
  342. package/src/page-target/drift.ts +186 -0
  343. package/src/page-target/index.ts +25 -0
  344. package/src/page-target/intent-map.ts +137 -0
  345. package/src/page-target/intent-schema.ts +711 -0
  346. package/src/page-target/origin.ts +17 -0
  347. package/src/page-target/target.ts +450 -0
  348. package/src/page-target/writer-policy.ts +315 -0
  349. package/src/theme/block-theme.ts +202 -0
  350. package/src/theme/kit-theme-text.ts +2 -0
  351. package/src/theme/kit-theme.css +275 -0
  352. package/src/theme/kit-theme.tpl +275 -0
  353. package/src/theme/theme-tokens.ts +135 -0
@@ -0,0 +1,726 @@
1
+ // Chart:图表(layer: data,写死形状,accept: list)。
2
+ //
3
+ // 数据:`data` 是行数组。图形配置由外部显式传入 `chart: { type: line | bar | area | pie, x: 字段, y: [字段…], stack?: bool }`:
4
+ // - line / bar / area:x 字段作类目轴,每个 y 字段一条系列(stack 为真时叠加);
5
+ // - pie / donut(环形):x 字段作扇区名,取 y 的第一个字段作数值;
6
+ // - funnel:x 作阶段名,y[0] 作数值,行序即流程顺序;
7
+ // - gauge:单值,取列表第一行(x 作名称、y[0] 作数值),min / max 量程,warnAt / dangerAt 阈值分段着色。
8
+ // `map` 是键名对照(组件期望的键 -> 数据里的键),浅映射不改源数据。
9
+ // 渲染走 soma-core 公开的图表引擎端口(`services.engines.chart`,契约声明 `services: ['engines']`);
10
+ // 没装配图表引擎、没数据、配置非法、引擎加载失败,都显示降级空态,不抛。
11
+ // 颜色只取 `--soma-*` 令牌(读运行期计算值交给引擎主题,源码里不写裸色值);样式类只用语义色名与 utilityScales 内的尺度。
12
+
13
+ import type { SomaComponentControllerContext, SomaComponentDefinition } from 'soma-core';
14
+ import { findRoot, joinClass, num, str } from '../base/shared';
15
+ import { kitText } from '../i18n/kit-text';
16
+ import { KIT_DATA_LIMITS } from 'soma-foundation/kit-limits';
17
+ import { KIT_GRAMMAR_RUNTIME as grammarJson } from '../generated/kit-grammar-runtime';
18
+
19
+ // 参考线 / 图例 / 数值格式的闭集与限值只读 kit-grammar.json#dataLimits.chart,代码里不手抄
20
+ const CHART_LIMITS = (grammarJson as unknown as { dataLimits: { chart: {
21
+ refLines: { stats: string[]; tones: string[] };
22
+ legends: string[];
23
+ } } }).dataLimits.chart;
24
+ // 数字(条数 / 字数上限)读 design 的 kit-limits,闭集仍读语法
25
+ const CHART_NUM = KIT_DATA_LIMITS.chart;
26
+ /** 线宽 / 透明度 / 点径:design 真源 kit-limits#dataLimits.chart.style */
27
+ const CHART_STYLE = CHART_NUM.style;
28
+ export const KIT_CHART_REF_STATS: readonly string[] = CHART_LIMITS.refLines.stats;
29
+ export const KIT_CHART_REF_TONES: readonly string[] = CHART_LIMITS.refLines.tones;
30
+ export const KIT_CHART_LEGENDS: readonly string[] = CHART_LIMITS.legends;
31
+
32
+ // ───────── 样式常量:Tailwind 类串与候选类清单 ─────────
33
+ // hidden 与布局类分写在两层:外层只管显隐,内层管布局。
34
+
35
+ const ROOT_CLASS = 'w-full';
36
+ const STAGE_CLASS = 'h-72 w-full';
37
+ const EMPTY_INNER_CLASS = 'flex h-72 w-full items-center justify-center rounded-md border border-border-subtle bg-surface-sunken text-sm text-fg-muted';
38
+
39
+ /** 本组件自带的全部类(供编译器并入候选类) */
40
+ export const KIT_CHART_CLASS_CANDIDATES: readonly string[] = Object.freeze([
41
+ 'w-full', 'h-72', 'hidden',
42
+ 'flex', 'items-center', 'justify-center', 'rounded-md', 'border', 'border-border-subtle', 'bg-surface-sunken', 'text-sm', 'text-fg-muted',
43
+ ]);
44
+
45
+ // ───────── 数据规整:图形配置解析、层级树、仪表盘分段、引擎 option 生成(均为纯函数) ─────────
46
+
47
+ export type KitChartType =
48
+ | 'line' | 'bar' | 'area' | 'pie' | 'donut' | 'funnel' | 'gauge'
49
+ | 'scatter' | 'combo' | 'radar' | 'heatmap' | 'boxplot' | 'candlestick' | 'sankey' | 'treemap' | 'sunburst' | 'chord';
50
+ export const KIT_CHART_TYPES: readonly KitChartType[] = Object.freeze([
51
+ 'line', 'bar', 'area', 'pie', 'donut', 'funnel', 'gauge',
52
+ 'scatter', 'combo', 'radar', 'heatmap', 'boxplot', 'candlestick', 'sankey', 'treemap', 'sunburst', 'chord',
53
+ ]);
54
+
55
+ export interface KitChartConfig {
56
+ type: KitChartType;
57
+ x: string;
58
+ y: string[];
59
+ stack: boolean;
60
+ /** gauge:量程(缺省 0 到 100)与告警阈值(值 >= warnAt 变警告色,>= dangerAt 变危险色) */
61
+ min?: number;
62
+ max?: number;
63
+ warnAt?: number | null;
64
+ dangerAt?: number | null;
65
+ /** 数值字段:heatmap 的格值、sankey / chord 的流量 */
66
+ value?: string;
67
+ /** 父级字段:treemap / sunburst 的层级(行的 parent 等于另一行的 x 名即其子项;空 = 全是根) */
68
+ parent?: string;
69
+ /** radar:各指标的量程上限,缺省取数据最大值的 1.2 倍;只在配置里显式写了 max 才有 */
70
+ scaleMax?: number | null;
71
+ /** combo:画成折线的 y 字段(其余画柱);y2:挂右侧第二纵轴的 y 字段 */
72
+ line?: string[];
73
+ y2?: string[];
74
+ /** 参考线(直角坐标系图型):固定值或引擎统计值,虚线 */
75
+ refLines?: KitChartRefLine[];
76
+ /** 图例位置:auto = 多系列时在底部(饼 / 漏斗始终在底部),none 关闭 */
77
+ legend?: 'auto' | 'top' | 'bottom' | 'none';
78
+ /** 纵轴 / 标签的数值前后缀(引擎字符串模板,不含函数) */
79
+ valueFormat?: { prefix: string; suffix: string };
80
+ }
81
+
82
+ export interface KitChartRefLine {
83
+ value?: number;
84
+ stat?: 'average' | 'max' | 'min' | 'median';
85
+ label: string;
86
+ tone: 'neutral' | 'success' | 'warning' | 'danger';
87
+ }
88
+
89
+ /** 引擎端口里的系列类型:area 走 line,donut 走 pie;combo 同时要柱和线两种 */
90
+ export function engineSeriesOf(type: KitChartType): string {
91
+ return type === 'area' ? 'line' : type === 'donut' ? 'pie' : type === 'combo' ? 'bar' : type;
92
+ }
93
+
94
+ /** 一张图要装的全部引擎系列类型(combo = bar + line) */
95
+ export function engineSeriesListOf(type: KitChartType): string[] {
96
+ return type === 'combo' ? ['bar', 'line'] : [engineSeriesOf(type)];
97
+ }
98
+
99
+ /** 数据要求:除 x / y 外还必须给的字段,以及 y 最少几个字段(纯函数,chartConfigOf 用) */
100
+ const MIN_Y: Readonly<Partial<Record<KitChartType, number>>> = Object.freeze({ boxplot: 5, candlestick: 4 });
101
+ const NEEDS_VALUE: ReadonlySet<KitChartType> = new Set<KitChartType>(['heatmap', 'sankey', 'chord']);
102
+
103
+ /** 各类型需要的引擎组件:直角坐标系要 grid + legend;pie / donut / funnel 只要 legend;gauge 都不要 */
104
+ export function engineComponentsOf(type: KitChartType, withMarkLine = false): string[] {
105
+ if (type === 'gauge' || type === 'sankey' || type === 'treemap' || type === 'sunburst' || type === 'chord') return [];
106
+ if (type === 'pie' || type === 'donut' || type === 'funnel') return ['legend'];
107
+ if (type === 'radar') return ['radar', 'legend'];
108
+ if (type === 'heatmap') return ['grid', 'visualMap'];
109
+ if (type === 'boxplot' || type === 'candlestick') return ['grid'];
110
+ return withMarkLine ? ['grid', 'legend', 'markLine'] : ['grid', 'legend'];
111
+ }
112
+
113
+ /** 系列用色顺序:图表系列令牌 --soma-chart-1 到 --soma-chart-8(token-catalog 内),不写裸色 */
114
+ export const KIT_CHART_SERIES_TOKENS: readonly string[] = Object.freeze(
115
+ [1, 2, 3, 4, 5, 6, 7, 8].map((n) => `--soma-chart-${n}`),
116
+ );
117
+
118
+ function recOf(raw: unknown): Record<string, unknown> {
119
+ return raw !== null && typeof raw === 'object' && !Array.isArray(raw) ? raw as Record<string, unknown> : {};
120
+ }
121
+
122
+ /** 前后缀:去掉引擎模板的花括号,限长(纯函数) */
123
+ export function affixOf(raw: unknown): string {
124
+ return str(raw).replace(/[{}]/g, '').slice(0, CHART_NUM.valueFormat.affixMax);
125
+ }
126
+
127
+ /** 参考线列表(纯函数):每项 value(数)或 stat(闭集)二选一,value 优先;条数与标签长度有上限;非法项丢弃 */
128
+ export function refLinesOf(raw: unknown): KitChartRefLine[] {
129
+ if (!Array.isArray(raw)) return [];
130
+ const out: KitChartRefLine[] = [];
131
+ for (const item of raw) {
132
+ if (out.length >= CHART_NUM.refLines.maxItems) break;
133
+ const r = recOf(item);
134
+ const value = num(r.value);
135
+ const stat = str(r.stat);
136
+ if (value === null && !KIT_CHART_REF_STATS.includes(stat)) continue;
137
+ const tone = KIT_CHART_REF_TONES.includes(str(r.tone)) ? str(r.tone) as KitChartRefLine['tone'] : 'neutral';
138
+ out.push({
139
+ ...(value !== null ? { value } : { stat: stat as NonNullable<KitChartRefLine['stat']> }),
140
+ label: str(r.label).slice(0, CHART_NUM.refLines.labelMax),
141
+ tone,
142
+ });
143
+ }
144
+ return out;
145
+ }
146
+
147
+ /** 解析图形配置(纯函数,便于单测);非法返回 null */
148
+ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
149
+ const src = recOf(chartRaw);
150
+ const type = str(src.type) as KitChartType;
151
+ if (!KIT_CHART_TYPES.includes(type)) return null;
152
+ const x = str(src.x);
153
+ if (x === '') return null;
154
+ const yRaw = src.y;
155
+ const y = Array.isArray(yRaw)
156
+ ? yRaw.filter((v): v is string => typeof v === 'string' && v !== '')
157
+ : typeof yRaw === 'string' ? yRaw.split(',').map((s) => s.trim()).filter((s) => s !== '') : [];
158
+ if (y.length === 0) return null;
159
+ if (y.length < (MIN_Y[type] ?? 1)) return null;
160
+ const value = str(src.value);
161
+ if (NEEDS_VALUE.has(type) && value === '') return null;
162
+ const stackRaw = src.stack;
163
+ const stack = stackRaw === true || stackRaw === 'true';
164
+ const min = num(src.min) ?? 0;
165
+ const max = num(src.max) ?? 100;
166
+ const nameList = (raw: unknown): string[] => (Array.isArray(raw)
167
+ ? raw.filter((v): v is string => typeof v === 'string' && v !== '')
168
+ : typeof raw === 'string' ? raw.split(',').map((s) => s.trim()).filter((s) => s !== '') : []);
169
+ const lineFields = type === 'combo' ? nameList(src.line).filter((f) => y.includes(f)) : [];
170
+ const y2Fields = type === 'combo' ? nameList(src.y2).filter((f) => y.includes(f)) : [];
171
+ const refLines = refLinesOf(src.ref_lines);
172
+ const legend = KIT_CHART_LEGENDS.includes(str(src.legend)) ? str(src.legend) as KitChartConfig['legend'] : 'auto';
173
+ const vf = recOf(src.value_format);
174
+ const prefix = affixOf(vf.prefix);
175
+ const suffix = affixOf(vf.suffix);
176
+ return {
177
+ ...(lineFields.length > 0 ? { line: lineFields } : {}),
178
+ ...(y2Fields.length > 0 ? { y2: y2Fields } : {}),
179
+ ...(refLines.length > 0 ? { refLines } : {}),
180
+ ...(legend !== 'auto' ? { legend } : {}),
181
+ ...(prefix !== '' || suffix !== '' ? { valueFormat: { prefix, suffix } } : {}),
182
+ type, x, y, stack, min, max, warnAt: num(src.warnAt), dangerAt: num(src.dangerAt),
183
+ ...(value !== '' ? { value } : {}),
184
+ ...(str(src.parent) !== '' ? { parent: str(src.parent) } : {}),
185
+ ...(type === 'radar' ? { scaleMax: num(src.max) } : {}),
186
+ };
187
+ }
188
+
189
+ export interface KitChartNode {
190
+ name: string;
191
+ value?: number;
192
+ children?: KitChartNode[];
193
+ }
194
+
195
+ /**
196
+ * 行 -> 层级树(treemap / sunburst,纯函数):每行 { 名称, 数值, 父名称? };父名称等于另一行的名称即其子项;
197
+ * 找不到父或父名为空即根;环状引用(A 的父是 B、B 的父是 A)里的行当根处理,不会死循环。
198
+ */
199
+ export function chartHierarchy(
200
+ rows: ReadonlyArray<Record<string, unknown>>,
201
+ nameKey: string,
202
+ valueKey: string,
203
+ parentKey: string,
204
+ ): KitChartNode[] {
205
+ const nodes = new Map<string, KitChartNode>();
206
+ const parentOf = new Map<string, string>();
207
+ for (const r of rows) {
208
+ const name = r[nameKey] === undefined || r[nameKey] === null ? '' : String(r[nameKey]);
209
+ if (name === '' || nodes.has(name)) continue;
210
+ nodes.set(name, { name, value: num(r[valueKey]) ?? 0 });
211
+ const parent = parentKey === '' || r[parentKey] === undefined || r[parentKey] === null ? '' : String(r[parentKey]);
212
+ if (parent !== '') parentOf.set(name, parent);
213
+ }
214
+ const rootsOf = (name: string): boolean => {
215
+ // 沿父链向上走,走回自己 / 走太久即环
216
+ const seen = new Set<string>([name]);
217
+ let cur = parentOf.get(name);
218
+ while (cur !== undefined && nodes.has(cur)) {
219
+ if (seen.has(cur)) return true;
220
+ seen.add(cur);
221
+ cur = parentOf.get(cur);
222
+ }
223
+ return false;
224
+ };
225
+ const roots: KitChartNode[] = [];
226
+ for (const [name, node] of nodes) {
227
+ const parent = parentOf.get(name);
228
+ if (parent === undefined || !nodes.has(parent) || rootsOf(name)) { roots.push(node); continue; }
229
+ const p = nodes.get(parent)!;
230
+ (p.children ??= []).push(node);
231
+ // 有子项的父节点数值由引擎汇总,不重复计
232
+ delete p.value;
233
+ }
234
+ return roots;
235
+ }
236
+
237
+ export interface KitChartTheme {
238
+ /** 系列色(解析后的运行期颜色值,取自 --soma-c-*) */
239
+ palette: string[];
240
+ text: string;
241
+ line: string;
242
+ /** gauge 阈值着色:正常 / 警告 / 危险(取自 --soma-c-success / warning / danger);缺省退回系列色 */
243
+ ok?: string;
244
+ warn?: string;
245
+ danger?: string;
246
+ }
247
+
248
+ /** gauge 轴线分段 [[占量程的比例, 颜色], …]:阈值之下 ok,warnAt 起 warn,dangerAt 起 danger;纯函数 */
249
+ export function gaugeBands(config: KitChartConfig, theme: KitChartTheme): Array<[number, string]> {
250
+ const min = config.min ?? 0;
251
+ const span = (config.max ?? 100) - min;
252
+ const warnAt = config.warnAt ?? null;
253
+ const dangerAt = config.dangerAt ?? null;
254
+ const ratio = (v: number): number => (span <= 0 ? 1 : Math.min(1, Math.max(0, (v - min) / span)));
255
+ const ok = theme.ok ?? theme.palette[0] ?? '';
256
+ const warn = theme.warn ?? theme.palette[1] ?? ok;
257
+ const danger = theme.danger ?? theme.palette[2] ?? warn;
258
+ const bands: Array<[number, string]> = [];
259
+ if (warnAt !== null) bands.push([ratio(warnAt), ok]);
260
+ if (dangerAt !== null) bands.push([ratio(dangerAt), warnAt !== null ? warn : ok]);
261
+ const last = dangerAt !== null ? danger : warnAt !== null ? warn : ok;
262
+ bands.push([1, last]);
263
+ return bands.sort((a, b) => a[0] - b[0]);
264
+ }
265
+
266
+ /**
267
+ * 生成引擎 option(纯函数)。键名对照 map 只对数据键生效:配置里的 x / y 先经 map 取源键。
268
+ * option 不含 tooltip(端口禁止)。
269
+ */
270
+ export function buildChartOption(
271
+ config: KitChartConfig,
272
+ rows: ReadonlyArray<Record<string, unknown>>,
273
+ theme: KitChartTheme,
274
+ mapRaw?: unknown,
275
+ ): Record<string, unknown> {
276
+ const map = recOf(mapRaw);
277
+ const src = (k: string): string => (typeof map[k] === 'string' && map[k] !== '' ? String(map[k]) : k);
278
+ const xKey = src(config.x);
279
+ const label = (v: unknown): string => (v === undefined || v === null ? '' : String(v));
280
+ const numeric = (v: unknown): number => num(v) ?? 0;
281
+
282
+ // 图例位置与数值前后缀:legend 缺省按各图型原习惯(auto),value_format 只拼引擎字符串模板
283
+ const fmt = config.valueFormat;
284
+ const valueTemplate = fmt ? `${fmt.prefix}{value}${fmt.suffix}` : undefined;
285
+ const labelTemplate = fmt ? `{b}: ${fmt.prefix}{c}${fmt.suffix}` : undefined;
286
+ const legendShown = (auto: boolean): boolean => (config.legend === 'none' ? false : config.legend === 'top' || config.legend === 'bottom' ? true : auto);
287
+ const legendOf = (auto: boolean): Record<string, unknown> | undefined =>
288
+ (legendShown(auto) ? { ...(config.legend === 'top' ? { top: 0 } : { bottom: 0 }), textStyle: { color: theme.text } } : undefined);
289
+ const toneColor = (tone: KitChartRefLine['tone']): string =>
290
+ (tone === 'success' ? (theme.ok ?? theme.palette[0] ?? theme.text)
291
+ : tone === 'warning' ? (theme.warn ?? theme.palette[1] ?? theme.text)
292
+ : tone === 'danger' ? (theme.danger ?? theme.palette[2] ?? theme.text)
293
+ : theme.text);
294
+ /** 参考线只挂在第一条系列上(引擎 markLine,虚线,不带 tooltip) */
295
+ const markLineOf = (): Record<string, unknown> => {
296
+ const refs = config.refLines ?? [];
297
+ if (refs.length === 0) return {};
298
+ return {
299
+ markLine: {
300
+ silent: true,
301
+ symbol: 'none',
302
+ data: refs.map((r) => ({
303
+ ...(r.value !== undefined ? { yAxis: r.value } : { type: r.stat }),
304
+ name: r.label,
305
+ lineStyle: { type: 'dashed', color: toneColor(r.tone) },
306
+ label: { show: r.label !== '', formatter: r.label, color: toneColor(r.tone) },
307
+ })),
308
+ },
309
+ };
310
+ };
311
+ /** 直角坐标系的 grid:底部图例留 32,顶部图例把上沿让到 40 */
312
+ const gridFor = (multi: boolean): Record<string, unknown> => ({
313
+ left: 8, right: 8, containLabel: true,
314
+ top: legendShown(multi) && config.legend === 'top' ? 40 : 24,
315
+ bottom: legendShown(multi) && config.legend !== 'top' ? 32 : 8,
316
+ });
317
+
318
+ if (config.type === 'gauge') {
319
+ // 仪表盘是单值:取列表第一行,x 作名称,y 的第一个字段作数值
320
+ const first = rows[0] ?? {};
321
+ const value = numeric(first[src(config.y[0]!)]);
322
+ return {
323
+ textStyle: { color: theme.text },
324
+ series: [{
325
+ type: 'gauge',
326
+ min: config.min ?? 0,
327
+ max: config.max ?? 100,
328
+ axisLine: { lineStyle: { width: CHART_STYLE.gaugeWidth, color: gaugeBands(config, theme) } },
329
+ axisLabel: { color: theme.text },
330
+ axisTick: { lineStyle: { color: theme.line } },
331
+ splitLine: { lineStyle: { color: theme.line } },
332
+ pointer: { width: CHART_STYLE.pointerWidth },
333
+ title: { color: theme.text },
334
+ detail: { color: theme.text, valueAnimation: false, ...(valueTemplate !== undefined ? { formatter: valueTemplate } : {}) },
335
+ data: [{ name: label(first[xKey]), value }],
336
+ }],
337
+ };
338
+ }
339
+
340
+ if (config.type === 'funnel') {
341
+ const yKey = src(config.y[0]!);
342
+ return {
343
+ color: theme.palette,
344
+ textStyle: { color: theme.text },
345
+ legend: legendOf(true),
346
+ series: [{
347
+ type: 'funnel',
348
+ // 行序即流程顺序,不让引擎重排
349
+ sort: 'none',
350
+ left: '10%',
351
+ width: '80%',
352
+ data: rows.map((r) => ({ name: label(r[xKey]), value: numeric(r[yKey]) })),
353
+ label: { color: theme.text, ...(labelTemplate !== undefined ? { formatter: labelTemplate } : {}) },
354
+ }],
355
+ };
356
+ }
357
+
358
+ if (config.type === 'pie' || config.type === 'donut') {
359
+ const yKey = src(config.y[0]!);
360
+ return {
361
+ color: theme.palette,
362
+ textStyle: { color: theme.text },
363
+ legend: legendOf(true),
364
+ series: [{
365
+ type: 'pie',
366
+ radius: config.type === 'donut' ? ['40%', '65%'] : '60%',
367
+ data: rows.map((r) => ({ name: label(r[xKey]), value: numeric(r[yKey]) })),
368
+ label: { color: theme.text, ...(labelTemplate !== undefined ? { formatter: labelTemplate } : {}) },
369
+ }],
370
+ };
371
+ }
372
+
373
+ const yKeys = config.y.map(src);
374
+ const valueKey = src(config.value ?? '');
375
+ const axisStyle = {
376
+ axisLine: { lineStyle: { color: theme.line } },
377
+ axisLabel: { color: theme.text },
378
+ splitLine: { lineStyle: { color: theme.line } },
379
+ };
380
+ const gridBox = { left: 8, right: 8, top: 24, bottom: 8, containLabel: true };
381
+
382
+ if (config.type === 'scatter') {
383
+ return {
384
+ color: theme.palette,
385
+ textStyle: { color: theme.text },
386
+ grid: gridFor(config.y.length > 1),
387
+ legend: legendOf(config.y.length > 1),
388
+ xAxis: { type: 'value', ...axisStyle },
389
+ yAxis: { type: 'value', ...axisStyle, axisLabel: { ...axisStyle.axisLabel, ...(valueTemplate !== undefined ? { formatter: valueTemplate } : {}) } },
390
+ series: config.y.map((y, i) => ({
391
+ type: 'scatter',
392
+ name: y,
393
+ data: rows.map((r) => [numeric(r[xKey]), numeric(r[yKeys[i]!])]),
394
+ ...(i === 0 ? markLineOf() : {}),
395
+ })),
396
+ };
397
+ }
398
+
399
+ if (config.type === 'radar') {
400
+ // 每个指标(行)的量程:配置显式给了 max 就用,否则取该行各系列最大值的 1.2 倍(至少 1)
401
+ const indicator = rows.map((r) => {
402
+ const top = Math.max(...yKeys.map((k) => numeric(r[k])), 0);
403
+ return { name: label(r[xKey]), max: config.scaleMax ?? (top > 0 ? Math.ceil(top * 1.2) : 1) };
404
+ });
405
+ return {
406
+ color: theme.palette,
407
+ textStyle: { color: theme.text },
408
+ legend: config.y.length > 1 ? { bottom: 0, textStyle: { color: theme.text } } : undefined,
409
+ radar: {
410
+ indicator,
411
+ axisName: { color: theme.text },
412
+ axisLine: { lineStyle: { color: theme.line } },
413
+ splitLine: { lineStyle: { color: theme.line } },
414
+ },
415
+ series: [{
416
+ type: 'radar',
417
+ data: config.y.map((y, i) => ({ name: y, value: rows.map((r) => numeric(r[yKeys[i]!])) })),
418
+ }],
419
+ };
420
+ }
421
+
422
+ if (config.type === 'heatmap') {
423
+ // x 为横轴类目,y[0] 为纵轴类目,value 字段为格值;类目按首次出现的顺序
424
+ const xs: string[] = [];
425
+ const ys: string[] = [];
426
+ for (const r of rows) {
427
+ const xv = label(r[xKey]);
428
+ const yv = label(r[yKeys[0]!]);
429
+ if (!xs.includes(xv)) xs.push(xv);
430
+ if (!ys.includes(yv)) ys.push(yv);
431
+ }
432
+ const cells = rows.map((r) => [xs.indexOf(label(r[xKey])), ys.indexOf(label(r[yKeys[0]!])), numeric(r[valueKey])]);
433
+ const values = cells.map((c) => c[2]!);
434
+ return {
435
+ textStyle: { color: theme.text },
436
+ grid: { left: 8, right: 8, top: 16, bottom: 48, containLabel: true },
437
+ xAxis: { type: 'category', data: xs, splitArea: { show: false }, ...axisStyle },
438
+ yAxis: { type: 'category', data: ys, ...axisStyle },
439
+ visualMap: {
440
+ min: Math.min(...values, 0),
441
+ max: Math.max(...values, 1),
442
+ calculable: false,
443
+ orient: 'horizontal',
444
+ left: 'center',
445
+ bottom: 0,
446
+ textStyle: { color: theme.text },
447
+ inRange: { color: [theme.line, theme.palette[0] ?? theme.text] },
448
+ },
449
+ series: [{ type: 'heatmap', data: cells }],
450
+ };
451
+ }
452
+
453
+ if (config.type === 'boxplot' || config.type === 'candlestick') {
454
+ // boxplot:y 依次为 最小 / 下四分位 / 中位 / 上四分位 / 最大;candlestick:y 依次为 开盘 / 收盘 / 最低 / 最高
455
+ const width = config.type === 'boxplot' ? 5 : 4;
456
+ return {
457
+ color: theme.palette,
458
+ textStyle: { color: theme.text },
459
+ grid: gridBox,
460
+ xAxis: { type: 'category', data: rows.map((r) => label(r[xKey])), ...axisStyle },
461
+ yAxis: { type: 'value', scale: true, ...axisStyle },
462
+ series: [{ type: config.type, data: rows.map((r) => yKeys.slice(0, width).map((k) => numeric(r[k]))) }],
463
+ };
464
+ }
465
+
466
+ if (config.type === 'sankey' || config.type === 'chord') {
467
+ // 每行是一条连线:x = 来源,y[0] = 去向,value 字段 = 流量;节点由连线两端去重得到
468
+ const links = rows
469
+ .map((r) => ({ source: label(r[xKey]), target: label(r[yKeys[0]!]), value: numeric(r[valueKey]) }))
470
+ .filter((l) => l.source !== '' && l.target !== '' && l.source !== l.target);
471
+ const names: string[] = [];
472
+ for (const l of links) for (const n of [l.source, l.target]) if (!names.includes(n)) names.push(n);
473
+ return {
474
+ color: theme.palette,
475
+ textStyle: { color: theme.text },
476
+ series: [{
477
+ type: config.type,
478
+ data: names.map((name) => ({ name })),
479
+ links,
480
+ label: { color: theme.text },
481
+ }],
482
+ };
483
+ }
484
+
485
+ if (config.type === 'treemap' || config.type === 'sunburst') {
486
+ const tree = chartHierarchy(rows, xKey, yKeys[0]!, src(config.parent ?? ''));
487
+ return {
488
+ color: theme.palette,
489
+ textStyle: { color: theme.text },
490
+ series: [{ type: config.type, data: tree, label: { color: theme.text }, ...(config.type === 'treemap' ? { roam: false, breadcrumb: { show: false } } : {}) }],
491
+ };
492
+ }
493
+
494
+ const cats = rows.map((r) => label(r[xKey]));
495
+ const combo = config.type === 'combo';
496
+ const lineSet = new Set(config.line ?? []);
497
+ const y2Set = new Set(config.y2 ?? []);
498
+ const series = config.y.map((y, i) => {
499
+ const key = src(y);
500
+ // combo:line 里列出的 y 画折线、其余画柱;y2 里列出的挂右轴。柱才叠加(折线叠加没有意义)
501
+ const seriesType = combo ? (lineSet.has(y) ? 'line' : 'bar') : config.type === 'bar' ? 'bar' : 'line';
502
+ return {
503
+ type: seriesType,
504
+ name: y,
505
+ data: rows.map((r) => numeric(r[key])),
506
+ ...(seriesType === 'line' ? { lineStyle: { width: CHART_STYLE.lineWidth }, symbolSize: CHART_STYLE.symbolSize } : {}),
507
+ ...(config.type === 'area' ? { areaStyle: { opacity: CHART_STYLE.areaOpacity } } : {}),
508
+ ...(config.stack && (!combo || seriesType === 'bar') ? { stack: 'total' } : {}),
509
+ ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
510
+ ...(i === 0 ? markLineOf() : {}),
511
+ };
512
+ });
513
+ const valueAxis = (extra: Record<string, unknown> = {}): Record<string, unknown> => ({
514
+ type: 'value',
515
+ splitLine: { lineStyle: { color: theme.line, width: CHART_STYLE.gridLineWidth } },
516
+ axisLabel: { color: theme.text, ...(valueTemplate !== undefined ? { formatter: valueTemplate } : {}) },
517
+ ...extra,
518
+ });
519
+ return {
520
+ color: theme.palette,
521
+ textStyle: { color: theme.text },
522
+ grid: gridFor(config.y.length > 1),
523
+ legend: legendOf(config.y.length > 1),
524
+ xAxis: { type: 'category', data: cats, axisLine: { lineStyle: { color: theme.line, width: CHART_STYLE.gridLineWidth } }, axisLabel: { color: theme.text } },
525
+ yAxis: combo && y2Set.size > 0
526
+ ? [valueAxis(), valueAxis({ position: 'right', splitLine: { show: false } })]
527
+ : valueAxis(),
528
+ series,
529
+ };
530
+ }
531
+
532
+ // ───────── 组件 ─────────
533
+
534
+ interface ChartEnginePort {
535
+ ensure(seriesTypes: readonly string[], components?: readonly string[]): Promise<void>;
536
+ create(host: HTMLElement, init: { theme: Record<string, unknown>; locale?: string }): Promise<{
537
+ setOption(option: Record<string, unknown>, mode?: 'merge' | 'replace'): void;
538
+ resize(): void;
539
+ dispose(): void;
540
+ }>;
541
+ }
542
+
543
+ /** 把 --soma-* 令牌解析成运行期颜色值:直接读宿主的计算样式,源码不出现裸色值,也不写内联样式 */
544
+ function resolveToken(host: HTMLElement, token: string): string {
545
+ const value = typeof getComputedStyle === 'function' ? getComputedStyle(host).getPropertyValue(token).trim() : '';
546
+ return value === '' ? `var(${token})` : value;
547
+ }
548
+
549
+ function themeOf(host: HTMLElement): KitChartTheme {
550
+ return {
551
+ palette: KIT_CHART_SERIES_TOKENS.map((n) => resolveToken(host, n)),
552
+ text: resolveToken(host, '--soma-text-secondary'),
553
+ line: resolveToken(host, '--soma-border-hairline'),
554
+ ok: resolveToken(host, '--soma-c-success'),
555
+ warn: resolveToken(host, '--soma-c-warning'),
556
+ danger: resolveToken(host, '--soma-c-danger'),
557
+ };
558
+ }
559
+
560
+ export function createChart(): SomaComponentDefinition {
561
+ return {
562
+ contract: {
563
+ name: 'Chart',
564
+ layer: 'data',
565
+ props: {
566
+ data: { type: 'array', default: [], desc: '行数组' },
567
+ chart: { type: 'object', default: {}, desc: '图形配置 { type: line | bar | area | pie | donut | funnel | gauge | scatter | combo | radar | heatmap | boxplot | candlestick | sankey | treemap | sunburst | chord, x: 字段, y: [字段…], stack?: bool, min? / max? / warnAt? / dangerAt?(gauge;radar 的 max 为各指标量程上限), value?: 字段, parent?: 字段 };funnel 行序即流程顺序;gauge 取列表第一行;scatter:x 与每个 y 字段都是数值;combo:柱线组合,line: [字段…] 里的 y 画折线、其余画柱,y2: [字段…] 挂右侧第二纵轴;ref_lines: [{ value 或 stat(average|max|min|median), label?, tone?(neutral|success|warning|danger) }] 虚线参考线(直角坐标系图型);legend: auto|top|bottom|none;value_format: { prefix?, suffix? } 纵轴与标签的数值前后缀;radar:每行一个指标(x 作名)、每个 y 字段一条系列;heatmap:x / y[0] 为横纵类目、value 为格值;boxplot:y 依次为 最小 / 下四分位 / 中位 / 上四分位 / 最大;candlestick:y 依次为 开盘 / 收盘 / 最低 / 最高;sankey / chord:每行一条连线,x 来源、y[0] 去向、value 流量;treemap / sunburst:x 名称、y[0] 数值、parent 父名称(空 = 根)' },
568
+ map: { type: 'object', default: {}, desc: '键名对照:chart 里的字段名 -> 数据里的键' },
569
+ empty: { type: 'string', default: '', desc: '无数据时的空态文案;缺省取内置文案(按页面语言)' },
570
+ locale: { type: 'string', default: '', desc: '图表语言;空则不传' },
571
+ class: { type: 'string', default: '', desc: '外部传入的类,追加在根节点类串末尾' },
572
+ },
573
+ emits: {},
574
+ },
575
+ services: ['engines'],
576
+ templateHtml:
577
+ `<div data-soma-id="root" class="${ROOT_CLASS}">`
578
+ + `<div data-soma-id="stageWrap" class="hidden"><div data-soma-id="stage" class="${STAGE_CLASS}"></div></div>`
579
+ + `<div data-soma-id="emptyWrap"><div data-soma-id="emptyText" class="${EMPTY_INNER_CLASS}"></div></div>`
580
+ + '</div>',
581
+ controllerFactory: (ctx: SomaComponentControllerContext) => {
582
+ const P = (): Record<string, unknown> => (ctx.readProps ? ctx.readProps() : ctx.props);
583
+ let root: HTMLElement | null = null;
584
+ let stageWrap: HTMLElement | null = null;
585
+ let stage: HTMLElement | null = null;
586
+ let emptyWrap: HTMLElement | null = null;
587
+ let emptyText: HTMLElement | null = null;
588
+ let instance: { setOption(o: Record<string, unknown>, m?: 'merge' | 'replace'): void; resize(): void; dispose(): void } | null = null;
589
+ let creating: Promise<void> | null = null;
590
+ let resizeObs: ResizeObserver | null = null;
591
+ let seq = 0;
592
+ let alive = false;
593
+
594
+ // 深浅色切换:系列色取自运行期计算值,主题变了要重算并 setOption。
595
+ // 两个来源——系统偏好 prefers-color-scheme,以及 <html> 上 soma-scheme-dark / soma-scheme-light 类的变化
596
+ let schemeOff: (() => void) | null = null;
597
+ const schemeKey = (): string => {
598
+ const cl = typeof document !== 'undefined' ? document.documentElement.classList : null;
599
+ return `${cl?.contains('soma-scheme-dark') === true}/${cl?.contains('soma-scheme-light') === true}`;
600
+ };
601
+ const watchScheme = (): void => {
602
+ unwatchScheme();
603
+ let last = schemeKey();
604
+ const repaint = (): void => { if (alive) void paint(); };
605
+ const offs: Array<() => void> = [];
606
+ if (typeof matchMedia === 'function') {
607
+ const mq = matchMedia('(prefers-color-scheme: dark)');
608
+ if (typeof mq.addEventListener === 'function') {
609
+ mq.addEventListener('change', repaint);
610
+ offs.push(() => mq.removeEventListener('change', repaint));
611
+ } else if (typeof mq.addListener === 'function') {
612
+ mq.addListener(repaint);
613
+ offs.push(() => mq.removeListener(repaint));
614
+ }
615
+ }
616
+ if (typeof MutationObserver === 'function' && typeof document !== 'undefined') {
617
+ const mo = new MutationObserver(() => {
618
+ const now = schemeKey();
619
+ if (now === last) return;
620
+ last = now;
621
+ repaint();
622
+ });
623
+ mo.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
624
+ offs.push(() => mo.disconnect());
625
+ }
626
+ schemeOff = () => { for (const off of offs) off(); };
627
+ };
628
+ const unwatchScheme = (): void => {
629
+ schemeOff?.();
630
+ schemeOff = null;
631
+ };
632
+
633
+ const find = (id: string): HTMLElement | null =>
634
+ root?.querySelector<HTMLElement>(`[data-soma-scoped-id="${id}"]`) ?? root?.querySelector<HTMLElement>(`[data-soma-id="${id}"]`) ?? null;
635
+
636
+ const showEmpty = (text: string): void => {
637
+ if (!stageWrap || !emptyWrap || !emptyText) return;
638
+ stageWrap.classList.add('hidden');
639
+ emptyWrap.classList.remove('hidden');
640
+ emptyText.textContent = text;
641
+ };
642
+ const showStage = (): void => {
643
+ if (!stageWrap || !emptyWrap) return;
644
+ emptyWrap.classList.add('hidden');
645
+ stageWrap.classList.remove('hidden');
646
+ };
647
+
648
+ const portOf = (): ChartEnginePort | null => {
649
+ const engines = (ctx.services as { engines?: { chart?: ChartEnginePort } } | undefined)?.engines;
650
+ return engines?.chart ?? null;
651
+ };
652
+
653
+ const paint = async (): Promise<void> => {
654
+ if (!root || !stage) return;
655
+ const mine = ++seq;
656
+ const p = P();
657
+ root.className = joinClass(ROOT_CLASS, p.class);
658
+ const rows = (Array.isArray(p.data) ? p.data : []).filter((r): r is Record<string, unknown> => r !== null && typeof r === 'object');
659
+ const config = chartConfigOf(p.chart);
660
+ if (config === null) { showEmpty(kitText('soma.kit.chart_incomplete', undefined, root)); return; }
661
+ if (rows.length === 0) { showEmpty(str(p.empty, kitText('soma.kit.empty', undefined, root))); return; }
662
+ const port = portOf();
663
+ if (port === null) { showEmpty(kitText('soma.kit.chart_no_engine', undefined, root)); return; }
664
+ try {
665
+ showStage();
666
+ const theme = themeOf(root);
667
+ const option = buildChartOption(config, rows, theme, p.map);
668
+ if (instance === null) {
669
+ if (creating === null) {
670
+ creating = (async () => {
671
+ await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, (config.refLines?.length ?? 0) > 0));
672
+ const locale = str(p.locale);
673
+ const created = await port.create(stage!, { theme: { color: theme.palette }, ...(locale !== '' ? { locale } : {}) });
674
+ if (!alive) { created.dispose(); return; }
675
+ instance = created;
676
+ if (typeof ResizeObserver === 'function') {
677
+ resizeObs = new ResizeObserver(() => instance?.resize());
678
+ resizeObs.observe(stage!);
679
+ }
680
+ })();
681
+ }
682
+ await creating;
683
+ creating = null;
684
+ }
685
+ // 异步期间又有新一轮 paint 或已卸载:交给最新一轮
686
+ if (!alive || mine !== seq || instance === null) return;
687
+ await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, (config.refLines?.length ?? 0) > 0));
688
+ if (!alive || mine !== seq) return;
689
+ instance.setOption(option, 'replace');
690
+ } catch {
691
+ creating = null;
692
+ if (alive && mine === seq) showEmpty(kitText('soma.kit.chart_unavailable', undefined, root));
693
+ }
694
+ };
695
+
696
+ return {
697
+ onMount(): void {
698
+ alive = true;
699
+ root = findRoot(ctx.host);
700
+ stageWrap = find('stageWrap');
701
+ stage = find('stage');
702
+ emptyWrap = find('emptyWrap');
703
+ emptyText = find('emptyText');
704
+ watchScheme();
705
+ void paint();
706
+ },
707
+ onPropsChange(): void {
708
+ void paint();
709
+ },
710
+ onUnmount(): void {
711
+ alive = false;
712
+ unwatchScheme();
713
+ resizeObs?.disconnect();
714
+ resizeObs = null;
715
+ instance?.dispose();
716
+ instance = null;
717
+ root = null;
718
+ stageWrap = null;
719
+ stage = null;
720
+ emptyWrap = null;
721
+ emptyText = null;
722
+ },
723
+ };
724
+ },
725
+ };
726
+ }