soma-kit 0.1.13 → 0.1.15

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 (312) hide show
  1. package/package.json +3 -3
  2. package/packs/finance/reconcile-desk/compile.ts +1 -1
  3. package/packs/finance/reconcile-desk/shell.ts +1 -1
  4. package/spec/generated/kit-app.schema.json +18 -2
  5. package/spec/generated/kit-page.schema.json +95 -0
  6. package/spec/kit-grammar.json +332 -75
  7. package/spec/kit-grammar.schema.json +1 -27
  8. package/src/app/app-config.ts +11 -5
  9. package/src/app/component-gate.ts +2 -2
  10. package/src/app/compose-apps.ts +5 -2
  11. package/src/app/define-kit-actions.ts +82 -10
  12. package/src/app/define-kit-app.ts +6 -5
  13. package/src/app/define-kit-view.ts +1 -1
  14. package/src/app/index.ts +20 -8
  15. package/src/app/kit-view-context.ts +30 -4
  16. package/src/app/server-pages.ts +5 -1
  17. package/src/app/server.ts +15 -5
  18. package/src/app/theme-endpoint.ts +1 -1
  19. package/src/app/theme-runtime.ts +7 -2
  20. package/src/base/alert.ts +23 -20
  21. package/src/base/anchored-layer.ts +1 -1
  22. package/src/base/button.ts +34 -17
  23. package/src/base/cascader.ts +8 -4
  24. package/src/base/check-core.ts +9 -6
  25. package/src/base/color-picker.ts +10 -6
  26. package/src/base/command-palette.ts +10 -4
  27. package/src/base/context-menu.ts +5 -2
  28. package/src/base/date-range.ts +9 -6
  29. package/src/base/date.ts +10 -6
  30. package/src/base/delta.ts +4 -2
  31. package/src/base/divider.ts +15 -66
  32. package/src/base/end-edge.ts +14 -2
  33. package/src/base/fab.ts +11 -6
  34. package/src/base/gap-value.ts +25 -5
  35. package/src/base/hint-tips.ts +1 -1
  36. package/src/base/illustrations.ts +2 -1
  37. package/src/base/index.ts +20 -4
  38. package/src/base/inline-error.ts +84 -0
  39. package/src/base/input.ts +54 -18
  40. package/src/base/kbd.ts +4 -3
  41. package/src/base/link.ts +1 -1
  42. package/src/base/listbox-core.ts +70 -22
  43. package/src/base/mentions.ts +6 -3
  44. package/src/base/menu-button.ts +73 -50
  45. package/src/base/menu-core.ts +9 -2
  46. package/src/base/motion/hover-3d.ts +4 -1
  47. package/src/base/motion/hover-gallery.ts +4 -1
  48. package/src/base/otp.ts +7 -3
  49. package/src/base/overlay-runtime.ts +3 -2
  50. package/src/base/overlay-shell.ts +141 -0
  51. package/src/base/popover.ts +7 -6
  52. package/src/base/popup.ts +47 -41
  53. package/src/base/qty-stepper.ts +14 -9
  54. package/src/base/reason-tip.ts +2 -2
  55. package/src/{frames → base}/resize-handle.ts +1 -1
  56. package/src/base/segmented.ts +44 -35
  57. package/src/base/select.ts +1 -0
  58. package/src/base/shared.ts +52 -18
  59. package/src/base/state-panel.ts +34 -13
  60. package/src/base/status-tone.ts +1 -1
  61. package/src/base/tag-input.ts +13 -8
  62. package/src/base/tag.ts +56 -57
  63. package/src/base/text.ts +38 -14
  64. package/src/base/textarea.ts +1 -1
  65. package/src/base/time-picker.ts +9 -5
  66. package/src/base/tree-select.ts +12 -9
  67. package/src/base/upload.ts +26 -17
  68. package/src/biz/approval-desk/compile.ts +28 -1
  69. package/src/biz/approval-desk/shell.ts +10 -9
  70. package/src/biz/auth-panel/compile.ts +1 -1
  71. package/src/biz/auth-panel/shell.ts +7 -6
  72. package/src/biz/category-crud/compile.ts +20 -6
  73. package/src/biz/category-crud/shell.ts +10 -7
  74. package/src/biz/checkout-page/compile.ts +1 -1
  75. package/src/biz/checkout-page/shell.ts +15 -13
  76. package/src/biz/compose.ts +5 -5
  77. package/src/biz/data-components.ts +4 -0
  78. package/src/biz/define.ts +1 -1
  79. package/src/biz/import-wizard/compile.ts +1 -1
  80. package/src/biz/import-wizard/shell.ts +17 -13
  81. package/src/biz/index.ts +4 -3
  82. package/src/biz/landing-page/compile.ts +1 -1
  83. package/src/biz/landing-page/shell.ts +6 -5
  84. package/src/biz/link/shared.ts +8 -1
  85. package/src/biz/master-sub/compile.ts +269 -27
  86. package/src/biz/master-sub/detail-head.ts +62 -0
  87. package/src/biz/master-sub/index.ts +5 -4
  88. package/src/biz/master-sub/shell.ts +138 -69
  89. package/src/biz/multi-board/compile.ts +166 -11
  90. package/src/biz/multi-board/composition.ts +58 -0
  91. package/src/biz/multi-board/index.ts +25 -10
  92. package/src/biz/multi-board/prose-fold.ts +143 -0
  93. package/src/biz/multi-board/shell.ts +96 -24
  94. package/src/biz/names.ts +1 -0
  95. package/src/biz/notification-center/compile.ts +9 -2
  96. package/src/biz/notification-center/shell.ts +15 -7
  97. package/src/biz/page-templates/domain-templates.ts +7 -3
  98. package/src/biz/page-templates/result-page/compile.ts +1 -1
  99. package/src/biz/page-templates/result-page/shell.ts +5 -4
  100. package/src/biz/page-templates/shared.ts +1 -1
  101. package/src/biz/page-templates/sign-in-page/compile.ts +1 -1
  102. package/src/biz/page-templates/sign-in-page/shell.ts +18 -18
  103. package/src/biz/record-detail/compile.ts +5 -2
  104. package/src/biz/record-detail/shell.ts +12 -11
  105. package/src/biz/settings-center/compile.ts +1 -1
  106. package/src/biz/settings-center/shell.ts +14 -10
  107. package/src/biz/shared/action-host.ts +12 -5
  108. package/src/biz/shared/compile-helpers.ts +83 -4
  109. package/src/biz/shared/coordinator.ts +104 -21
  110. package/src/biz/shared/overlay-compile.ts +76 -4
  111. package/src/biz/shared/overlay-shell.ts +65 -112
  112. package/src/biz/single-form/compile.ts +2 -2
  113. package/src/biz/single-form/shell.ts +13 -7
  114. package/src/biz/standard-crud/compile.ts +24 -4
  115. package/src/biz/standard-crud/shell.ts +38 -30
  116. package/src/biz/standard-crud/summary.ts +42 -0
  117. package/src/biz/step-form/compile.ts +1 -1
  118. package/src/biz/step-form/hub.ts +4 -0
  119. package/src/biz/step-form/shell.ts +16 -12
  120. package/src/biz/types.ts +15 -3
  121. package/src/cli/app-layer-check.ts +375 -0
  122. package/src/cli/kit-cli.ts +35 -8
  123. package/src/cli/kit-init.ts +149 -0
  124. package/src/cli/layout-cli.ts +7 -7
  125. package/src/compile/access-gate-attach.ts +27 -0
  126. package/src/compile/action-host-attach.ts +1 -1
  127. package/src/compile/compile-page.ts +36 -230
  128. package/src/compile/component-candidates.ts +4 -1
  129. package/src/compile/hints.ts +5 -58
  130. package/src/compile/index.ts +2 -2
  131. package/src/compile/layout-lint/index.ts +4 -1
  132. package/src/compile/layout-lint/rules-composition.ts +97 -18
  133. package/src/compile/layout-lint/rules-form.ts +6 -7
  134. package/src/compile/layout-lint/rules-table.ts +98 -14
  135. package/src/compile/page-composition.ts +191 -0
  136. package/src/compile/parse.ts +4 -0
  137. package/src/compile/producer-fingerprint.ts +56 -0
  138. package/src/compile/redirect.ts +1 -1
  139. package/src/compile/stages.ts +169 -0
  140. package/src/compile/styles.ts +80 -32
  141. package/src/compile/types.ts +5 -3
  142. package/src/data/access-gate.ts +112 -0
  143. package/src/data/amount-breakdown.ts +6 -2
  144. package/src/data/anchor-nav.ts +4 -1
  145. package/src/data/approval-flow.ts +13 -5
  146. package/src/data/assignment-picker.ts +35 -20
  147. package/src/data/async-result-panel.ts +7 -3
  148. package/src/data/breadcrumbs.ts +13 -9
  149. package/src/data/calendar.ts +10 -4
  150. package/src/data/carousel.ts +13 -5
  151. package/src/data/chart.ts +745 -48
  152. package/src/data/checklist.ts +9 -5
  153. package/src/data/code-view.ts +220 -26
  154. package/src/data/comment-thread.ts +9 -3
  155. package/src/data/confirm-dialog.ts +57 -20
  156. package/src/data/diff.ts +4 -1
  157. package/src/data/dock.ts +5 -1
  158. package/src/data/embed.ts +1 -1
  159. package/src/data/engine-ports.ts +126 -0
  160. package/src/data/field-mapper.ts +16 -7
  161. package/src/data/flow-editor.ts +106 -29
  162. package/src/data/footer.ts +8 -2
  163. package/src/data/gantt.ts +192 -27
  164. package/src/data/hero.ts +8 -2
  165. package/src/data/image-viewer.ts +7 -3
  166. package/src/data/index.ts +22 -8
  167. package/src/data/item-list.ts +11 -3
  168. package/src/data/json-view.ts +844 -0
  169. package/src/data/kanban.ts +13 -8
  170. package/src/data/markdown-view.ts +487 -0
  171. package/src/data/matrix.ts +400 -0
  172. package/src/data/media-grid.ts +5 -2
  173. package/src/data/mega-menu.ts +4 -3
  174. package/src/data/menu-dom.ts +9 -8
  175. package/src/data/menu.ts +35 -17
  176. package/src/data/mockup.ts +12 -8
  177. package/src/data/modal-dialog.ts +108 -57
  178. package/src/data/navbar.ts +13 -7
  179. package/src/data/notice-list.ts +53 -20
  180. package/src/data/notify-renderer.ts +21 -10
  181. package/src/data/object-form.ts +248 -151
  182. package/src/data/pager.ts +15 -10
  183. package/src/data/panel-head.ts +406 -0
  184. package/src/data/permission-matrix.ts +19 -9
  185. package/src/data/permission-tree.ts +30 -13
  186. package/src/data/pricing-table.ts +10 -4
  187. package/src/data/reaction-bar.ts +6 -3
  188. package/src/data/record-card.ts +30 -14
  189. package/src/data/record-picker.ts +8 -4
  190. package/src/data/redirect.ts +1 -1
  191. package/src/data/request-console.ts +20 -7
  192. package/src/data/resident.ts +6 -10
  193. package/src/data/result-panel.ts +2 -2
  194. package/src/data/rich-text.ts +58 -96
  195. package/src/data/row-editor.ts +12 -7
  196. package/src/data/rule-builder.ts +22 -11
  197. package/src/data/shape-util.ts +26 -14
  198. package/src/data/stat-group.ts +369 -84
  199. package/src/data/static-lazy.ts +7 -0
  200. package/src/data/static-registry.ts +14 -2
  201. package/src/data/steps.ts +6 -2
  202. package/src/data/survey.ts +13 -4
  203. package/src/data/system-switcher.ts +17 -7
  204. package/src/data/text-diff.ts +663 -0
  205. package/src/data/timeline.ts +1 -1
  206. package/src/data/tour-guide.ts +8 -4
  207. package/src/data/transfer.ts +24 -11
  208. package/src/data/tree-table.ts +84 -17
  209. package/src/data/tree.ts +6 -3
  210. package/src/data/virtual-rows.ts +22 -11
  211. package/src/data/wrap.ts +2 -2
  212. package/src/data/wrapped-candidates.ts +22 -1
  213. package/src/frames/index.ts +4 -2
  214. package/src/frames/inherited-shell.ts +178 -0
  215. package/src/frames/list-summary.ts +123 -0
  216. package/src/frames/page-bar.ts +10 -16
  217. package/src/frames/resident-components.ts +20 -0
  218. package/src/frames/shared.ts +37 -17
  219. package/src/frames/split-frame/shell.ts +17 -11
  220. package/src/frames/split-frame/wiring.ts +2 -2
  221. package/src/frames/tabs-frame/shell.ts +17 -9
  222. package/src/frames/top-main-frame.ts +1 -1
  223. package/src/frames/types.ts +6 -3
  224. package/src/frames/workspace-frame/extras.ts +19 -5
  225. package/src/frames/workspace-frame/shell.ts +4 -3
  226. package/src/frames/workspace-frame/state.ts +8 -2
  227. package/src/frames/workspace-frame/tab-scroll.ts +28 -0
  228. package/src/frames/workspace-frame/view.ts +156 -91
  229. package/src/generated/kit-grammar-runtime.ts +227 -58
  230. package/src/i18n/kit-text.ts +141 -2
  231. package/src/i18n/resolve-text-refs.ts +1 -1
  232. package/src/object-renderer/action-group.ts +169 -0
  233. package/src/object-renderer/action-more.ts +160 -0
  234. package/src/object-renderer/arrange.ts +86 -26
  235. package/src/object-renderer/candidates.ts +4 -0
  236. package/src/object-renderer/collection-parts.ts +72 -20
  237. package/src/object-renderer/collection-table.ts +178 -65
  238. package/src/object-renderer/collection.ts +129 -83
  239. package/src/object-renderer/compile-data.ts +1 -1
  240. package/src/object-renderer/defaults.ts +10 -5
  241. package/src/object-renderer/emit-events.ts +1 -1
  242. package/src/object-renderer/emit-object.ts +7 -0
  243. package/src/object-renderer/emit-static.ts +243 -87
  244. package/src/object-renderer/field-value.ts +12 -239
  245. package/src/object-renderer/filter-plan.ts +84 -0
  246. package/src/object-renderer/filter-toolbar.ts +103 -0
  247. package/src/{compile → object-renderer}/fragment.ts +13 -2
  248. package/src/object-renderer/index.ts +6 -1
  249. package/src/object-renderer/layout-facts.ts +46 -6
  250. package/src/object-renderer/layout-plan.ts +136 -43
  251. package/src/object-renderer/layout-plan.types.ts +42 -5
  252. package/src/object-renderer/overlay-decide.ts +82 -0
  253. package/src/object-renderer/parts.ts +7 -259
  254. package/src/object-renderer/render-object.ts +60 -47
  255. package/src/object-renderer/table-actions.ts +135 -56
  256. package/src/object-renderer/table-gap.ts +37 -0
  257. package/src/object-renderer/table-tools.ts +63 -25
  258. package/src/object-renderer/types.ts +16 -22
  259. package/src/recipes/app-blocks.ts +66 -0
  260. package/src/recipes/code-view.ts +56 -0
  261. package/src/recipes/compact-group.ts +31 -0
  262. package/src/recipes/container.ts +54 -13
  263. package/src/recipes/control.ts +77 -157
  264. package/src/recipes/desc-list.ts +14 -0
  265. package/src/recipes/divider.ts +53 -0
  266. package/src/recipes/emphasis.ts +60 -0
  267. package/src/recipes/frame-bleed.ts +33 -0
  268. package/src/recipes/index.ts +34 -1
  269. package/src/recipes/inherited-shell.ts +37 -0
  270. package/src/recipes/json-view.ts +49 -0
  271. package/src/recipes/markdown.ts +86 -0
  272. package/src/recipes/overlay.ts +149 -18
  273. package/src/recipes/page-width.ts +20 -0
  274. package/src/recipes/placeholder.ts +21 -5
  275. package/src/recipes/rail-grid.ts +3 -0
  276. package/src/recipes/stat-state.ts +65 -0
  277. package/src/recipes/state.ts +20 -28
  278. package/src/recipes/status.ts +17 -8
  279. package/src/recipes/strip.ts +72 -0
  280. package/src/recipes/surface-edge.ts +16 -0
  281. package/src/recipes/surface.ts +10 -6
  282. package/src/recipes/table-gap.ts +80 -0
  283. package/src/recipes/table-native-edit.ts +242 -0
  284. package/src/recipes/table-row.ts +120 -11
  285. package/src/recipes/tabs.ts +126 -0
  286. package/src/recipes/text-diff.ts +90 -0
  287. package/src/recipes/title-row.ts +7 -5
  288. package/src/recipes/typography.ts +24 -43
  289. package/src/shared/diagnostics.ts +16 -0
  290. package/src/shared/envelope.ts +1 -1
  291. package/src/shared/field-value-format.ts +246 -0
  292. package/src/shared/focus-ring.ts +8 -0
  293. package/src/shared/hints.ts +56 -0
  294. package/src/{base → shared}/icons.ts +12 -0
  295. package/src/shared/kit-error.ts +1 -1
  296. package/src/{object-renderer → shared}/merge-class.ts +3 -2
  297. package/src/shared/path-guard.ts +1 -1
  298. package/src/shared/primitives-types.ts +8 -0
  299. package/src/shared/theme-runtime-shared.ts +19 -0
  300. package/src/theme/kit-theme-text.ts +1 -1
  301. package/src/theme/kit-theme.css +49 -14
  302. package/src/theme/kit-theme.tpl +49 -14
  303. package/src/theme/nine-dim-structure.ts +129 -37
  304. package/src/theme/surface-layers.ts +17 -4
  305. package/src/theme/theme-tokens.ts +16 -5
  306. package/src/theme/typography.ts +21 -17
  307. package/src/app/envelope.ts +0 -1
  308. package/src/app/notify-renderer.ts +0 -1
  309. package/src/app/paged-list-adapter.ts +0 -1
  310. package/src/app/theme-runtime-shared.ts +0 -1
  311. package/src/compile/kit-error.ts +0 -1
  312. /package/src/{base → shared}/class-candidates.ts +0 -0
package/src/data/chart.ts CHANGED
@@ -12,19 +12,36 @@
12
12
 
13
13
  import type { SomaComponentDefinition } from 'soma-core';
14
14
  import { createKitController, joinClass, num, str } from '../base/shared';
15
+ import { createLoadingGate, type KitLoadingGate } from '../base/loading-gate';
15
16
  import { kitText, type KitTextKey } from '../i18n/kit-text';
16
17
  import {
17
18
  KIT_READ_STATE_EMIT_DEFS, KIT_READ_STATE_PROP_DEFS, KIT_STATE_PANEL_CLASS_CANDIDATES, paintKitStatePanel,
18
19
  type KitStateKind, type KitStatePanelOptions,
19
20
  } from '../base/state-panel';
20
21
  import { KIT_DATA_LIMITS } from 'soma-foundation/kit-limits';
22
+ import {
23
+ chartMarkDashPattern, defaultReadoutColumn, formatReadoutValue, parseChartMarks, parseReadout, resolveChartMarks, stepChartColumn,
24
+ type ChartMark, type ChartMarkSpec, type ReadoutConfig, type ResolvedChartMark, type VizTone,
25
+ } from 'soma-foundation/kit-viz';
26
+ import { classCandidates } from '../shared/class-candidates';
27
+ import { mergeClass } from '../shared/merge-class';
28
+ import { kitShellRecipe } from '../recipes/container';
29
+ import { kitFocusRingRecipe } from '../recipes/state';
30
+ import { KIT_NOTICE_HEADLINE, KIT_STAT_VALUES_NUM, KIT_STAT_VALUES_ROW } from '../recipes/status';
21
31
  import { KIT_GRAMMAR_RUNTIME as grammarJson } from '../generated/kit-grammar-runtime';
22
32
 
23
33
  // 参考线 / 图例 / 数值格式的闭集与限值只读 kit-grammar.json#dataLimits.chart,代码里不手抄
24
34
  const CHART_LIMITS = (grammarJson as unknown as { dataLimits: { chart: {
25
35
  refLines: { stats: string[]; tones: string[] };
26
36
  legends: string[];
37
+ seriesRoles: string[];
38
+ seriesToneRoles: Record<string, string>;
39
+ seriesKinds: string[];
40
+ seriesAxes: string[];
41
+ marks: ChartMarkSpec;
27
42
  } } }).dataLimits.chart;
43
+ /** 标记的角色闭集(取色 / 线型 / 符号):读 kit-grammar.json#dataLimits.chart.marks */
44
+ const MARK_SPEC: ChartMarkSpec = CHART_LIMITS.marks;
28
45
  // 数字(条数 / 字数上限)读 design 的 kit-limits,闭集仍读语法
29
46
  const CHART_NUM = KIT_DATA_LIMITS.chart;
30
47
  /** 线宽 / 透明度 / 点径:design 真源 kit-limits#dataLimits.chart.style */
@@ -32,20 +49,69 @@ const CHART_STYLE = CHART_NUM.style;
32
49
  export const KIT_CHART_REF_STATS: readonly string[] = CHART_LIMITS.refLines.stats;
33
50
  export const KIT_CHART_REF_TONES: readonly string[] = CHART_LIMITS.refLines.tones;
34
51
  export const KIT_CHART_LEGENDS: readonly string[] = CHART_LIMITS.legends;
52
+ /** 系列角色闭集(目前只有 ideal = 理想线),读 kit-grammar.json#dataLimits.chart.seriesRoles */
53
+ export const KIT_CHART_SERIES_ROLES: readonly string[] = CHART_LIMITS.seriesRoles ?? [];
54
+ export type KitChartSeriesRole = 'ideal' | 'baseline' | 'projection' | 'ok' | 'caution' | 'overload';
55
+
56
+ /**
57
+ * 参考线图例样例的字形(引擎 path 图标,不画「线 + 圆点」):baseline = 一段细实线,其余(理想)= 两段虚线;
58
+ * 路径里两个零长度线段把包围盒撑成 25 x 14,引擎按包围盒缩放时细线不会被拉粗。
59
+ */
60
+ const LEGEND_BOX = 'M0,0L0,0M25,14L25,14';
61
+ export function referenceLegendIcon(role: string | undefined): string {
62
+ return role === 'baseline'
63
+ ? `path://${LEGEND_BOX}M0,6L25,6L25,8L0,8Z`
64
+ : `path://${LEGEND_BOX}M0,6L8,6L8,8L0,8ZM13,6L21,6L21,8L13,8Z`;
65
+ }
66
+
67
+ /**
68
+ * 参考线类系列(理想 / baseline)的线型:图里的系列与图例样例共用这一份(两处各写一份会让图例与图不一致)。
69
+ * baseline = 细实线,其余(理想)= 虚线;线宽 / 虚线样式读真源 kit-limits#dataLimits.chart.style。
70
+ */
71
+ export function referenceLineStyle(role: string | undefined, color: string): { width: number; type: 'solid' | number[]; color: string } {
72
+ return role === 'baseline'
73
+ ? { width: CHART_STYLE.baselineLineWidth, type: 'solid', color }
74
+ : { width: CHART_STYLE.idealLineWidth, type: [...CHART_STYLE.idealDash], color };
75
+ }
76
+ /** 语义取色的系列角色 -> 语气(读 kit-grammar.json#dataLimits.chart.seriesToneRoles) */
77
+ const SERIES_TONE_ROLES: Readonly<Record<string, string>> = CHART_LIMITS.seriesToneRoles;
78
+ /** combo 逐系列的柱 / 线与纵轴闭集,读 kit-grammar.json#dataLimits.chart.seriesKinds / seriesAxes */
79
+ export const KIT_CHART_SERIES_KINDS: readonly string[] = CHART_LIMITS.seriesKinds;
80
+ export const KIT_CHART_SERIES_AXES: readonly string[] = CHART_LIMITS.seriesAxes;
81
+ /** 只有这些图型的 y 系列可以带 role(理想线画成折线,叠在直角坐标系上) */
82
+ const ROLE_TYPES: ReadonlySet<string> = new Set(['line', 'area', 'bar', 'combo']);
35
83
 
36
84
  // ───────── 样式常量:Tailwind 类串与候选类清单 ─────────
37
85
  // hidden 与布局类分写在两层:外层只管显隐,内层管布局。
38
86
 
39
- const ROOT_CLASS = 'w-full';
87
+ const ROOT_CLASS = 'relative w-full';
88
+ /** 图已就绪的根标记:引擎加载完并出过图后才有(截图 / 渲染测量据此判断,不靠固定等待) */
89
+ export const KIT_CHART_READY_ATTR = 'data-kit-chart-ready';
40
90
  const STAGE_CLASS = 'h-72 w-full';
41
- 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';
91
+ // 空态框 = 凹槽面的壳配方(容器边,KT-B2)
92
+ const EMPTY_INNER_CLASS = mergeClass('flex h-72 w-full items-center justify-center text-sm text-fg-muted', kitShellRecipe({ tone: 'sunken', shadow: false }));
93
+
94
+ /**
95
+ * 逐列读数区的类:排版与表面取 kit 配方(说明条标题 / StatGroup 多值行的字阶与等宽数字),不手写字阶;
96
+ * 容器是下沉面(bg-surface-sunken + rounded-md,与空态同一表面),键盘焦点环取条目焦点环配方。
97
+ */
98
+ const READOUT_CLASS = `rounded-md bg-surface-sunken px-3 py-2 ${KIT_STAT_VALUES_ROW}`;
99
+ const READOUT_TITLE_CLASS = KIT_NOTICE_HEADLINE;
100
+ const READOUT_ITEM_CLASS = 'inline-flex items-baseline gap-1.5';
101
+ const READOUT_VALUE_CLASS = KIT_STAT_VALUES_NUM;
102
+ const READOUT_NOTE_CLASS = 'text-fg-subtle';
103
+ const ROOT_FOCUS_CLASS = mergeClass('rounded-md', kitFocusRingRecipe('item'));
104
+ const READOUT_TOP_CLASS = 'mb-2';
105
+ const READOUT_BOTTOM_CLASS = 'mt-2';
42
106
 
43
107
  /** 本组件自带的全部类(供编译器并入候选类) */
44
- export const KIT_CHART_CLASS_CANDIDATES: readonly string[] = Object.freeze([
45
- 'w-full', 'h-72', 'hidden', 'sr-only',
46
- 'flex', 'items-center', 'justify-center', 'rounded-md', 'border', 'border-border-subtle', 'bg-surface-sunken', 'text-sm', 'text-fg-muted',
47
- ...KIT_STATE_PANEL_CLASS_CANDIDATES,
48
- ]);
108
+ export const KIT_CHART_CLASS_CANDIDATES: readonly string[] = classCandidates(
109
+ ['relative', 'absolute', 'inset-0', 'invisible', 'w-full', 'h-72', 'hidden', 'sr-only',
110
+ EMPTY_INNER_CLASS],
111
+ KIT_STATE_PANEL_CLASS_CANDIDATES,
112
+ READOUT_CLASS, READOUT_TITLE_CLASS, READOUT_ITEM_CLASS, READOUT_VALUE_CLASS, READOUT_NOTE_CLASS, ROOT_FOCUS_CLASS,
113
+ READOUT_TOP_CLASS, READOUT_BOTTOM_CLASS,
114
+ );
49
115
 
50
116
  // ───────── 数据规整:图形配置解析、层级树、仪表盘分段、引擎 option 生成(均为纯函数) ─────────
51
117
 
@@ -78,6 +144,14 @@ export interface KitChartConfig {
78
144
  y2?: string[];
79
145
  /** 参考线(直角坐标系图型):固定值或引擎统计值,虚线 */
80
146
  refLines?: KitChartRefLine[];
147
+ /** 系列角色:字段名 -> role(折线 / 面积 / 柱 / 组合;ideal = 理想线);没有带 role 的系列时不出现 */
148
+ roles?: Record<string, KitChartSeriesRole>;
149
+ /** 标记(竖线 / 区间带 / 标记点,K1):声明解析后的结果,几何由 resolveChartMarks 套数据行得到;没有则不出现 */
150
+ marks?: ChartMark[];
151
+ /** 逐列读数区(K2);没有则不出现 */
152
+ readout?: ReadoutConfig;
153
+ /** 点击 / Enter 选中列抛 point_pick(K3) */
154
+ interact?: { pick: boolean };
81
155
  /** 图例位置:auto = 多系列时在底部(饼 / 漏斗始终在底部),none 关闭 */
82
156
  legend?: 'auto' | 'top' | 'bottom' | 'none';
83
157
  /** 纵轴 / 标签的数值前后缀(引擎字符串模板,不含函数) */
@@ -96,9 +170,36 @@ export function engineSeriesOf(type: KitChartType): string {
96
170
  return type === 'area' ? 'line' : type === 'donut' ? 'pie' : type === 'combo' ? 'bar' : type;
97
171
  }
98
172
 
99
- /** 一张图要装的全部引擎系列类型(combo = bar + line) */
100
- export function engineSeriesListOf(type: KitChartType): string[] {
101
- return type === 'combo' ? ['bar', 'line'] : [engineSeriesOf(type)];
173
+ /** 一张图要装的全部引擎系列类型(combo = bar + line;bar 等直角图含 baseline / ideal / projection / line 系列时补齐 line) */
174
+ export function engineSeriesListOf(type: KitChartType, config?: Pick<KitChartConfig, 'roles' | 'line'>): string[] {
175
+ const out = type === 'combo' ? ['bar', 'line'] : [engineSeriesOf(type)];
176
+ const needsLine = (config?.line?.length ?? 0) > 0
177
+ || Object.values(config?.roles ?? {}).some((r) => r === 'ideal' || r === 'baseline' || r === 'projection');
178
+ if (needsLine && !out.includes('line')) out.push('line');
179
+ return out;
180
+ }
181
+
182
+ /** 扫描实际产出的 option.series,补齐全部引擎系列类型(防止 bar + baseline/line 等运行时报未导入系列) */
183
+ function renderedSeriesTypesOf(config: KitChartConfig, option: Record<string, unknown>): string[] {
184
+ const types = new Set(engineSeriesListOf(config.type, config));
185
+ if (Array.isArray(option.series)) {
186
+ for (const s of option.series) {
187
+ if (s !== null && typeof s === 'object' && typeof (s as { type?: unknown }).type === 'string') {
188
+ types.add((s as { type: string }).type);
189
+ }
190
+ }
191
+ }
192
+ return [...types];
193
+ }
194
+
195
+ /** 角色后缀去重:字段名已含同义角色词(如「预测」「理想」)时不拼成「预测(预测)」「理想(理想)」 */
196
+ function appendRoleSuffix(name: string, suffix: string): string {
197
+ if (suffix === '') return name;
198
+ const trimmed = name.trim();
199
+ if (trimmed === '') return name;
200
+ const core = suffix.replace(/^[\s((]+|[\s))]+$/g, '').trim().toLowerCase();
201
+ if (core !== '' && trimmed.toLowerCase().includes(core)) return name;
202
+ return `${name}${suffix}`;
102
203
  }
103
204
 
104
205
  /** 数据要求:除 x / y 外还必须给的字段,以及 y 最少几个字段(纯函数,chartConfigOf 用) */
@@ -106,15 +207,28 @@ const MIN_Y: Readonly<Partial<Record<KitChartType, number>>> = Object.freeze({ b
106
207
  const NEEDS_VALUE: ReadonlySet<KitChartType> = new Set<KitChartType>(['heatmap', 'sankey', 'chord']);
107
208
 
108
209
  /** 各类型需要的引擎组件:直角坐标系要 grid + legend;pie / donut / funnel 只要 legend;gauge 都不要 */
109
- export function engineComponentsOf(type: KitChartType, withMarkLine = false): string[] {
210
+ export function engineComponentsOf(type: KitChartType, withMarkLine = false, extra: readonly string[] = []): string[] {
110
211
  if (type === 'gauge' || type === 'sankey' || type === 'treemap' || type === 'sunburst' || type === 'chord') return [];
111
212
  if (type === 'pie' || type === 'donut' || type === 'funnel') return ['legend'];
112
213
  if (type === 'radar') return ['radar', 'legend'];
113
214
  if (type === 'heatmap') return ['grid', 'visualMap'];
114
215
  if (type === 'boxplot' || type === 'candlestick') return ['grid'];
115
- return withMarkLine ? ['grid', 'legend', 'markLine'] : ['grid', 'legend'];
216
+ const base = withMarkLine ? ['grid', 'legend', 'markLine'] : ['grid', 'legend'];
217
+ return [...base, ...extra.filter((c) => !base.includes(c))];
116
218
  }
117
219
 
220
+ /** 配置里用到的引擎标记组件(markLine / markArea / markPoint);键盘焦点带也要 markArea(有读数 / 选中时预装) */
221
+ export function chartMarkComponentsOf(config: KitChartConfig): { markLine: boolean; extra: string[] } {
222
+ const marks = config.marks ?? [];
223
+ const extra: string[] = [];
224
+ if (marks.some((m) => m.kind === 'band')) extra.push('markArea');
225
+ if (marks.some((m) => m.kind === 'point')) extra.push('markPoint');
226
+ return { markLine: (config.refLines?.length ?? 0) > 0 || marks.some((m) => m.kind === 'line'), extra };
227
+ }
228
+
229
+ /** 只有这些图型有「类目轴列」:标记与读数 / 键盘漫游只对它们生效 */
230
+ export const KIT_CHART_COLUMN_TYPES: ReadonlySet<string> = new Set(['line', 'bar', 'area', 'combo']);
231
+
118
232
  /** 系列用色顺序:图表系列令牌 --soma-chart-1 到 --soma-chart-8(token-catalog 内),不写裸色 */
119
233
  export const KIT_CHART_SERIES_TOKENS: readonly string[] = Object.freeze(
120
234
  [1, 2, 3, 4, 5, 6, 7, 8].map((n) => `--soma-chart-${n}`),
@@ -157,9 +271,35 @@ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
157
271
  const x = str(src.x);
158
272
  if (x === '') return null;
159
273
  const yRaw = src.y;
160
- const y = Array.isArray(yRaw)
161
- ? yRaw.filter((v): v is string => typeof v === 'string' && v !== '')
162
- : typeof yRaw === 'string' ? yRaw.split(',').map((s) => s.trim()).filter((s) => s !== '') : [];
274
+ // y 项可以是字段名,也可以是 { field, role? };role 不在闭集(或图型不支持 role)即整份配置非法
275
+ const roles: Record<string, KitChartSeriesRole> = {};
276
+ const kindOf = new Map<string, string>();
277
+ const axisOf = new Map<string, string>();
278
+ let badRole = false;
279
+ const y: string[] = [];
280
+ if (Array.isArray(yRaw)) {
281
+ for (const v of yRaw) {
282
+ if (typeof v === 'string') { if (v !== '') y.push(v); continue; }
283
+ const item = recOf(v);
284
+ const field = str(item.field);
285
+ if (field === '') continue;
286
+ y.push(field);
287
+ // combo 的逐系列声明:kind(bar / line)与 axis(primary / secondary);非闭集的值、非 combo 图型写它们都算非法
288
+ for (const [key, set, bucket] of [['kind', KIT_CHART_SERIES_KINDS, kindOf], ['axis', KIT_CHART_SERIES_AXES, axisOf]] as const) {
289
+ const raw = item[key];
290
+ if (raw === undefined || raw === null || raw === '') continue;
291
+ if (type !== 'combo' || !set.includes(str(raw))) { badRole = true; continue; }
292
+ bucket.set(field, str(raw));
293
+ }
294
+ if (item.role === undefined || item.role === null || item.role === '') continue;
295
+ const role = str(item.role);
296
+ if (!KIT_CHART_SERIES_ROLES.includes(role) || !ROLE_TYPES.has(type)) { badRole = true; continue; }
297
+ roles[field] = role as KitChartSeriesRole;
298
+ }
299
+ } else if (typeof yRaw === 'string') {
300
+ for (const s of yRaw.split(',')) if (s.trim() !== '') y.push(s.trim());
301
+ }
302
+ if (badRole) return null;
163
303
  if (y.length === 0) return null;
164
304
  if (y.length < (MIN_Y[type] ?? 1)) return null;
165
305
  const value = str(src.value);
@@ -171,9 +311,21 @@ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
171
311
  const nameList = (raw: unknown): string[] => (Array.isArray(raw)
172
312
  ? raw.filter((v): v is string => typeof v === 'string' && v !== '')
173
313
  : typeof raw === 'string' ? raw.split(',').map((s) => s.trim()).filter((s) => s !== '') : []);
174
- const lineFields = type === 'combo' ? nameList(src.line).filter((f) => y.includes(f)) : [];
175
- const y2Fields = type === 'combo' ? nameList(src.y2).filter((f) => y.includes(f)) : [];
314
+ // 逐系列声明与顶层 line / y2 名单取并集(同一系列两处都写时以逐系列为准)
315
+ const merged = (names: string[], declared: ReadonlyMap<string, string>, on: string): string[] =>
316
+ y.filter((f) => (declared.has(f) ? declared.get(f) === on : names.includes(f)));
317
+ const lineFields = type === 'combo' ? merged(nameList(src.line), kindOf, 'line') : [];
318
+ const y2Fields = type === 'combo' ? merged(nameList(src.y2), axisOf, 'secondary') : [];
176
319
  const refLines = refLinesOf(src.ref_lines);
320
+ // 标记 / 读数 / 选中只对有类目轴列的图型(折线 / 面积 / 柱 / 组合);写在别的图型或值非法 = 配置不完整
321
+ const marks = parseChartMarks(src.marks, MARK_SPEC);
322
+ const readout = parseReadout(src.readout);
323
+ const interactRaw = src.interact;
324
+ const wantsColumns = (marks !== null && marks.length > 0) || (readout !== undefined && readout !== null) || (interactRaw !== undefined && interactRaw !== null);
325
+ if (marks === null || readout === null) return null;
326
+ if (wantsColumns && !KIT_CHART_COLUMN_TYPES.has(type)) return null;
327
+ const interactRec = recOf(interactRaw);
328
+ if (interactRaw !== undefined && interactRaw !== null && (typeof interactRaw !== 'object' || Array.isArray(interactRaw) || Object.keys(interactRec).some((k) => k !== 'pick'))) return null;
177
329
  const legend = KIT_CHART_LEGENDS.includes(str(src.legend)) ? str(src.legend) as KitChartConfig['legend'] : 'auto';
178
330
  const vf = recOf(src.value_format);
179
331
  const prefix = affixOf(vf.prefix);
@@ -182,6 +334,10 @@ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
182
334
  ...(lineFields.length > 0 ? { line: lineFields } : {}),
183
335
  ...(y2Fields.length > 0 ? { y2: y2Fields } : {}),
184
336
  ...(refLines.length > 0 ? { refLines } : {}),
337
+ ...(Object.keys(roles).length > 0 ? { roles } : {}),
338
+ ...(marks.length > 0 ? { marks } : {}),
339
+ ...(readout !== undefined ? { readout } : {}),
340
+ ...(interactRaw !== undefined && interactRaw !== null ? { interact: { pick: interactRec.pick === true || interactRec.pick === 'true' } } : {}),
185
341
  ...(legend !== 'auto' ? { legend } : {}),
186
342
  ...(prefix !== '' || suffix !== '' ? { valueFormat: { prefix, suffix } } : {}),
187
343
  type, x, y, stack, min, max, warnAt: num(src.warnAt), dangerAt: num(src.dangerAt),
@@ -244,10 +400,34 @@ export interface KitChartTheme {
244
400
  palette: string[];
245
401
  text: string;
246
402
  line: string;
403
+ /** 理想线色(中性令牌 --soma-text-muted 的运行期值);缺省退回 text */
404
+ ideal?: string;
405
+ /** 主色(标记 primary 语气、焦点带;--soma-c-primary 的运行期值);缺省退回 palette[0] */
406
+ primary?: string;
407
+ /** 预测线系列名后缀(如「(预测)」,来自 kit 文案);缺省不加 */
408
+ projectionSuffix?: string;
247
409
  /** gauge 阈值着色:正常 / 警告 / 危险(取自 --soma-c-success / warning / danger);缺省退回系列色 */
248
410
  ok?: string;
249
411
  warn?: string;
250
412
  danger?: string;
413
+ /** 柱宽 / 类间距的比例(百分数,取 --soma-chart-bar-ratio;强调级越低越细);缺省用引擎默认 */
414
+ barRatioPct?: number;
415
+ }
416
+
417
+ /** 把 #rrggbb 色按 pct% 混入面板面色(pct = 系列色占比);无法解析(非 #rrggbb)时原样返回。强调级低的图表填充更浅,主图表 100 = 实心。 */
418
+ export function mixTowardSurface(color: string, surface: string, pct: number): string {
419
+ const hex = (s: string): [number, number, number] | null => {
420
+ const m = /^#([0-9a-f]{6})$/i.exec(s.trim());
421
+ if (m === null) return null;
422
+ const v = parseInt(m[1]!, 16);
423
+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
424
+ };
425
+ const a = hex(color);
426
+ const b = hex(surface);
427
+ if (pct >= 100 || a === null || b === null) return color;
428
+ const k = Math.max(0, pct) / 100;
429
+ const ch = (i: number): string => Math.round(a[i]! * k + b[i]! * (1 - k)).toString(16).padStart(2, '0');
430
+ return `#${ch(0)}${ch(1)}${ch(2)}`;
251
431
  }
252
432
 
253
433
  /** gauge 轴线分段 [[占量程的比例, 颜色], …]:阈值之下 ok,warnAt 起 warn,dangerAt 起 danger;纯函数 */
@@ -277,6 +457,8 @@ export function buildChartOption(
277
457
  rows: ReadonlyArray<Record<string, unknown>>,
278
458
  theme: KitChartTheme,
279
459
  mapRaw?: unknown,
460
+ /** 保留入参(焦点带已取消,见 markAreaOf);不再影响输出 */
461
+ _view: { focus?: number } = {},
280
462
  ): Record<string, unknown> {
281
463
  const map = recOf(mapRaw);
282
464
  const src = (k: string): string => (typeof map[k] === 'string' && map[k] !== '' ? String(map[k]) : k);
@@ -291,31 +473,195 @@ export function buildChartOption(
291
473
  const legendShown = (auto: boolean): boolean => (config.legend === 'none' ? false : config.legend === 'top' || config.legend === 'bottom' ? true : auto);
292
474
  const legendOf = (auto: boolean): Record<string, unknown> | undefined =>
293
475
  (legendShown(auto) ? { ...(config.legend === 'top' ? { top: 0 } : { bottom: 0 }), textStyle: { color: theme.text } } : undefined);
294
- const toneColor = (tone: KitChartRefLine['tone']): string =>
476
+ const toneColor = (tone: KitChartRefLine['tone'] | VizTone): string =>
295
477
  (tone === 'success' ? (theme.ok ?? theme.palette[0] ?? theme.text)
296
478
  : tone === 'warning' ? (theme.warn ?? theme.palette[1] ?? theme.text)
297
479
  : tone === 'danger' ? (theme.danger ?? theme.palette[2] ?? theme.text)
298
- : theme.text);
299
- /** 参考线只挂在第一条系列上(引擎 markLine,虚线,不带 tooltip) */
480
+ : tone === 'primary' ? (theme.primary ?? theme.palette[0] ?? theme.text)
481
+ : tone === 'muted' ? (theme.ideal ?? theme.text)
482
+ : theme.text);
483
+ // 标记几何:声明套到数据行(x 轴 = 列序号);只对有类目轴列的图型
484
+ const resolvedMarks: ResolvedChartMark[] = config.marks !== undefined && KIT_CHART_COLUMN_TYPES.has(config.type)
485
+ ? resolveChartMarks(config.marks, rows, { xKey, seriesKey: src })
486
+ : [];
487
+ const roleOf = (role: string): { color: string; dash: readonly number[] | null; symbol: string } => {
488
+ const style = MARK_SPEC.roles[role]!;
489
+ return { color: toneColor(style.tone), dash: chartMarkDashPattern(style.dash), symbol: style.symbol };
490
+ };
491
+ const hasY2 = config.type === 'combo' && (config.y2?.length ?? 0) > 0;
492
+ /** 估算参考线标签像素宽(中文约 12px、ASCII 约 7px),避免在无布局环境下被 SVG 右边界裁切 */
493
+ const estimateLabelPx = (text: string): number => {
494
+ let px = 0;
495
+ for (const ch of text) px += ch.charCodeAt(0) > 127 ? 12 : 7;
496
+ return px;
497
+ };
498
+ /** 估算参考线的数值坐标(用于判定右侧相邻标签是否过近并错开 y 偏移) */
499
+ const primaryValues = (): number[] => {
500
+ const firstY = config.y[0];
501
+ if (firstY === undefined) return [];
502
+ const k = src(firstY);
503
+ return rows.map((r) => num(r[k])).filter((v): v is number => v !== null);
504
+ };
505
+ const statValueOf = (stat: KitChartRefLine['stat'], vals: readonly number[]): number | null => {
506
+ if (vals.length === 0 || stat === undefined) return null;
507
+ if (stat === 'max') return Math.max(...vals);
508
+ if (stat === 'min') return Math.min(...vals);
509
+ if (stat === 'average') return vals.reduce((a, b) => a + b, 0) / vals.length;
510
+ const sorted = [...vals].sort((a, b) => a - b);
511
+ const mid = Math.floor(sorted.length / 2);
512
+ return sorted.length % 2 === 1 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
513
+ };
514
+ /** 参考线与标记竖线 / 横线合并成引擎 markLine,只挂在第一条系列上(虚线 / 实线由角色定,不带 tooltip) */
300
515
  const markLineOf = (): Record<string, unknown> => {
301
516
  const refs = config.refLines ?? [];
302
- if (refs.length === 0) return {};
517
+ const lines = resolvedMarks.filter((m) => m.kind === 'line');
518
+ if (refs.length === 0 && lines.length === 0) return {};
519
+ const vals = primaryValues();
520
+ const yLines: Array<{ key: string; yVal: number | null; label: string }> = [];
521
+ refs.forEach((r, idx) => {
522
+ if (r.label !== '') yLines.push({ key: `r:${idx}`, yVal: r.value !== undefined ? r.value : statValueOf(r.stat, vals), label: r.label });
523
+ });
524
+ lines.forEach((m, idx) => {
525
+ if (m.axis === 'y' && m.label !== '') yLines.push({ key: `m:${idx}`, yVal: typeof m.at === 'number' ? m.at : null, label: m.label });
526
+ });
527
+ const numericVals = [...vals, ...yLines.map((x) => x.yVal).filter((v): v is number => v !== null)];
528
+ // 直角坐标值轴默认含 0,估算可见纵轴跨度时把 0 纳入上下界,避免相邻参考线被误判为相距甚远
529
+ const ySpan = numericVals.length > 0 ? Math.max(0, ...numericVals) - Math.min(0, ...numericVals) : 0;
530
+ const closeGap = ySpan > 0 ? ySpan * 0.14 : 0;
531
+ const dyByKey = new Map<string, number>();
532
+ const posByKey = new Map<string, 'end' | 'insideEndTop' | 'insideEndBottom'>();
533
+ if (yLines.length > 0) {
534
+ const sorted = [...yLines].sort((a, b) => (b.yVal ?? 0) - (a.yVal ?? 0));
535
+ const clusters: Array<typeof sorted> = [];
536
+ for (const item of sorted) {
537
+ const lastCluster = clusters[clusters.length - 1];
538
+ const prev = lastCluster?.[lastCluster.length - 1];
539
+ const isClose = prev !== undefined && (
540
+ item.yVal === null || prev.yVal === null || Math.abs(prev.yVal - item.yVal) <= closeGap
541
+ );
542
+ if (lastCluster && isClose) lastCluster.push(item);
543
+ else clusters.push([item]);
544
+ }
545
+ for (const cluster of clusters) {
546
+ if (cluster.length === 1) {
547
+ posByKey.set(cluster[0]!.key, hasY2 ? 'insideEndTop' : 'end');
548
+ dyByKey.set(cluster[0]!.key, 0);
549
+ } else {
550
+ const mid = (cluster.length - 1) / 2;
551
+ cluster.forEach((item, i) => {
552
+ if (hasY2) {
553
+ posByKey.set(item.key, i <= mid ? 'insideEndTop' : 'insideEndBottom');
554
+ dyByKey.set(item.key, Math.round((i - mid) * 14));
555
+ } else {
556
+ posByKey.set(item.key, 'end');
557
+ dyByKey.set(item.key, Math.round((i - mid) * 16));
558
+ }
559
+ });
560
+ }
561
+ }
562
+ }
303
563
  return {
304
564
  markLine: {
305
565
  silent: true,
306
566
  symbol: 'none',
307
- data: refs.map((r) => ({
308
- ...(r.value !== undefined ? { yAxis: r.value } : { type: r.stat }),
309
- name: r.label,
310
- lineStyle: { type: 'dashed', color: toneColor(r.tone) },
311
- label: { show: r.label !== '', formatter: r.label, color: toneColor(r.tone) },
312
- })),
567
+ data: [
568
+ ...refs.map((r, idx) => {
569
+ const key = `r:${idx}`;
570
+ const dy = dyByKey.get(key) ?? 0;
571
+ const position = posByKey.get(key) ?? (hasY2 ? 'insideEndTop' : 'end');
572
+ return {
573
+ ...(r.value !== undefined ? { yAxis: r.value } : { type: r.stat }),
574
+ name: r.label,
575
+ lineStyle: { type: 'dashed', color: toneColor(r.tone) },
576
+ label: {
577
+ show: r.label !== '',
578
+ formatter: r.label,
579
+ color: toneColor(r.tone),
580
+ position,
581
+ ...(dy !== 0 ? { offset: [0, dy] } : {}),
582
+ },
583
+ };
584
+ }),
585
+ ...lines.map((m, idx) => {
586
+ const s = roleOf(m.role);
587
+ const key = `m:${idx}`;
588
+ const isY = m.axis === 'y';
589
+ const dy = isY ? (dyByKey.get(key) ?? 0) : 0;
590
+ const position = isY ? (posByKey.get(key) ?? (hasY2 ? 'insideEndTop' : 'end')) : 'end';
591
+ return {
592
+ ...(m.axis === 'x' ? { xAxis: m.at } : { yAxis: m.at }),
593
+ name: m.label,
594
+ lineStyle: { type: s.dash === null ? 'solid' : [...s.dash], color: s.color, width: CHART_NUM.marks.lineWidth },
595
+ label: {
596
+ show: m.label !== '',
597
+ formatter: m.label,
598
+ color: s.color,
599
+ position,
600
+ rotate: 0,
601
+ ...(dy !== 0 ? { offset: [0, dy] } : {}),
602
+ },
603
+ };
604
+ }),
605
+ ],
313
606
  },
314
607
  };
315
608
  };
316
- /** 直角坐标系的 grid:底部图例留 32,顶部图例把上沿让到 40 */
609
+ /** 区间带(标记 band + 焦点带):x 轴两端各外扩半列,使单列区间也有宽度;挂在第一条系列上 */
610
+ const markAreaOf = (): Record<string, unknown> => {
611
+ const bands = resolvedMarks.filter((m) => m.kind === 'band');
612
+ if (bands.length === 0) return {};
613
+ const data: unknown[] = bands.map((m) => {
614
+ const s = roleOf(m.role);
615
+ // 类目轴坐标被引擎取整(Math.round),±0.5 外扩无效(实测整体右移半列);改为外扩一整列到相邻快照点:
616
+ // 折线在「缺快照」处断开,带 = 断开的区间(上一个有值点 → 下一个有值点),单列区间也有宽度
617
+ const edge = (v: number, side: -1 | 1): number => (m.axis === 'x' ? Math.min(Math.max(v + side, 0), Math.max(rows.length - 1, 0)) : v);
618
+ return [
619
+ {
620
+ ...(m.axis === 'x' ? { xAxis: edge(m.from!, -1) } : { yAxis: m.from }),
621
+ name: m.label,
622
+ itemStyle: { color: s.color, opacity: CHART_NUM.marks.bandOpacity },
623
+ label: { show: m.label !== '', formatter: m.label, color: s.color, position: 'insideBottom' },
624
+ },
625
+ m.axis === 'x' ? { xAxis: edge(m.to!, 1) } : { yAxis: m.to },
626
+ ];
627
+ });
628
+ // 焦点列不再画带:类目轴坐标取整后,带只能落在「焦点 → 下一列」、与悬停的列错开半列;焦点由高亮点 + 读数区表达
629
+ return { markArea: { silent: true, data } };
630
+ };
631
+ /** 标记点:落在对应系列的该列(该系列值为空的列 resolveChartMarks 已跳过) */
632
+ const markPointOf = (seriesName: string): Record<string, unknown> => {
633
+ const points = resolvedMarks.filter((m) => m.kind === 'point' && m.series === seriesName);
634
+ if (points.length === 0) return {};
635
+ return {
636
+ markPoint: {
637
+ silent: true,
638
+ data: points.map((m) => {
639
+ const s = roleOf(m.role);
640
+ const hollow = s.symbol === 'hollow';
641
+ return {
642
+ coord: [m.at, num(rows[m.at!]?.[src(seriesName)])],
643
+ name: m.label,
644
+ symbol: s.symbol === 'diamond' ? 'diamond' : 'circle',
645
+ symbolSize: CHART_NUM.marks.pointSize,
646
+ itemStyle: hollow ? { color: 'transparent', borderColor: s.color, borderWidth: CHART_NUM.marks.lineWidth } : { color: s.color },
647
+ label: { show: m.label !== '', formatter: m.label, color: s.color, position: 'top' },
648
+ };
649
+ }),
650
+ },
651
+ };
652
+ };
653
+ /** 直角坐标系的 grid:底部图例留 32,顶部图例把上沿让到 40;有右侧参考线外置标签时按标签宽留出右边距避免裁切 */
654
+ const rightMarkLabels = hasY2
655
+ ? []
656
+ : [
657
+ ...(config.refLines ?? []).map((r) => r.label).filter((s) => s !== ''),
658
+ ...resolvedMarks.filter((m) => m.kind === 'line' && m.axis === 'y' && m.label !== '').map((m) => m.label),
659
+ ];
660
+ const rightLabelPad = rightMarkLabels.length > 0
661
+ ? Math.min(136, Math.max(48, Math.max(...rightMarkLabels.map(estimateLabelPx)) + 20))
662
+ : 8;
317
663
  const gridFor = (multi: boolean): Record<string, unknown> => ({
318
- left: 8, right: 8, containLabel: true,
664
+ left: 8, right: rightLabelPad, containLabel: true,
319
665
  top: legendShown(multi) && config.legend === 'top' ? 40 : 24,
320
666
  bottom: legendShown(multi) && config.legend !== 'top' ? 32 : 8,
321
667
  });
@@ -500,21 +846,94 @@ export function buildChartOption(
500
846
  const combo = config.type === 'combo';
501
847
  const lineSet = new Set(config.line ?? []);
502
848
  const y2Set = new Set(config.y2 ?? []);
503
- const series = config.y.map((y, i) => {
849
+ // 理想线排在最后:不占序列配色序号(其它系列的颜色不后移),图例也排最后
850
+ // baseline(范围线 / 容量线等参考性序列)与理想线同属「参考线类」:不占配色序号、中性色、无点;区别只在线型(baseline = 细实线,不与理想线虚线混用)
851
+ const isIdeal = (y: string): boolean => config.roles?.[y] === 'ideal' || config.roles?.[y] === 'baseline';
852
+ const isProjection = (y: string): boolean => config.roles?.[y] === 'projection';
853
+ /** 语义取色角色(ok / caution / overload):画成普通系列但取语气色、排在其它普通系列之后(不占配色序号) */
854
+ const toneOfRole = (y: string): string | null => SERIES_TONE_ROLES[config.roles?.[y] ?? ''] ?? null;
855
+ const basicYs = config.y.filter((y) => !isIdeal(y) && !isProjection(y));
856
+ const plainYs = [...basicYs.filter((y) => toneOfRole(y) === null), ...basicYs.filter((y) => toneOfRole(y) !== null)];
857
+ const idealYs = config.y.filter(isIdeal);
858
+ const projectionYs = config.y.filter(isProjection);
859
+ const projectionName = (y: string): string => appendRoleSuffix(y, theme.projectionSuffix ?? '');
860
+ /** 空值(null / undefined / 非数)保持 null:引擎据此断线留白,不补零不插值 */
861
+ const cell = (r: Record<string, unknown>, key: string): number | null => num(r[key]);
862
+ const idealSeries = idealYs.map((y) => {
863
+ const key = src(y);
864
+ const color = theme.ideal ?? theme.text;
865
+ return {
866
+ type: 'line',
867
+ name: y,
868
+ data: rows.map((r) => cell(r, key)),
869
+ connectNulls: false,
870
+ symbol: 'none',
871
+ showSymbol: false,
872
+ color,
873
+ itemStyle: { color },
874
+ lineStyle: referenceLineStyle(config.roles?.[y], color),
875
+ ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
876
+ };
877
+ });
878
+ // 预测线:与第一条普通序列同色相的虚线延伸,不占配色序号(颜色显式指定)、无点、不叠加、断线留白
879
+ const projectionColor = theme.palette[0] ?? theme.text;
880
+ const projectionSeries = projectionYs.map((y) => {
881
+ const key = src(y);
882
+ return {
883
+ type: 'line',
884
+ name: projectionName(y),
885
+ data: rows.map((r) => cell(r, key)),
886
+ connectNulls: false,
887
+ symbol: 'none',
888
+ showSymbol: false,
889
+ color: projectionColor,
890
+ itemStyle: { color: projectionColor },
891
+ lineStyle: { width: CHART_STYLE.idealLineWidth, type: [...CHART_STYLE.projectionDash], color: projectionColor, opacity: CHART_STYLE.projectionOpacity },
892
+ ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
893
+ };
894
+ });
895
+ const series = [...plainYs.map((y, i) => {
504
896
  const key = src(y);
505
897
  // combo:line 里列出的 y 画折线、其余画柱;y2 里列出的挂右轴。柱才叠加(折线叠加没有意义)
506
898
  const seriesType = combo ? (lineSet.has(y) ? 'line' : 'bar') : config.type === 'bar' ? 'bar' : 'line';
507
899
  return {
508
900
  type: seriesType,
509
901
  name: y,
510
- data: rows.map((r) => numeric(r[key])),
902
+ data: rows.map((r) => cell(r, key)),
903
+ ...(seriesType === 'line' ? { connectNulls: false } : {}),
904
+ ...(seriesType === 'bar' && theme.barRatioPct !== undefined ? { barCategoryGap: `${Math.max(0, 100 - theme.barRatioPct)}%` } : {}),
511
905
  ...(seriesType === 'line' ? { lineStyle: { width: CHART_STYLE.lineWidth }, symbolSize: CHART_STYLE.symbolSize } : {}),
512
906
  ...(config.type === 'area' ? { areaStyle: { opacity: CHART_STYLE.areaOpacity } } : {}),
513
907
  ...(config.stack && (!combo || seriesType === 'bar') ? { stack: 'total' } : {}),
514
908
  ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
515
- ...(i === 0 ? markLineOf() : {}),
909
+ ...(toneOfRole(y) !== null ? (() => { const c = toneColor(toneOfRole(y) as VizTone); return { color: c, itemStyle: { color: c } }; })() : {}),
910
+ ...(i === 0 ? { ...markLineOf(), ...markAreaOf() } : {}),
911
+ ...markPointOf(y),
516
912
  };
517
- });
913
+ }), ...idealSeries, ...projectionSeries];
914
+ // 有理想 / 预测线时图例逐项给出:虚线项用虚线样例,其余项沿用序列色
915
+ const legend = legendOf(config.y.length > 1);
916
+ const legendWithIdeal = legend !== undefined && (idealYs.length > 0 || projectionYs.length > 0)
917
+ ? {
918
+ ...legend,
919
+ data: [
920
+ ...plainYs.map((name) => ({ name })),
921
+ ...projectionYs.map((name) => ({
922
+ name: projectionName(name),
923
+ itemStyle: { color: projectionColor },
924
+ lineStyle: { type: [...CHART_STYLE.projectionDash], width: CHART_STYLE.idealLineWidth, color: projectionColor },
925
+ })),
926
+ ...idealYs.map((name) => ({
927
+ name,
928
+ // 引擎默认的线型图例样例是「线段 + 圆点」,虚线 / 实线的线型差异画不出来:参考线用 path 图标(referenceLegendIcon)
929
+ // 画各自的线型,lineStyle 仍与图里该序列同一份(referenceLineStyle):理想线 = 虚线,范围 / 容量(baseline)= 细实线
930
+ icon: referenceLegendIcon(config.roles?.[name]),
931
+ itemStyle: { color: theme.ideal ?? theme.text },
932
+ lineStyle: referenceLineStyle(config.roles?.[name], theme.ideal ?? theme.text),
933
+ })),
934
+ ],
935
+ }
936
+ : legend;
518
937
  const valueAxis = (extra: Record<string, unknown> = {}): Record<string, unknown> => ({
519
938
  type: 'value',
520
939
  splitLine: { lineStyle: { color: theme.line, width: CHART_STYLE.gridLineWidth } },
@@ -525,7 +944,7 @@ export function buildChartOption(
525
944
  color: theme.palette,
526
945
  textStyle: { color: theme.text },
527
946
  grid: gridFor(config.y.length > 1),
528
- legend: legendOf(config.y.length > 1),
947
+ legend: legendWithIdeal,
529
948
  xAxis: { type: 'category', data: cats, axisLine: { lineStyle: { color: theme.line, width: CHART_STYLE.gridLineWidth } }, axisLabel: { color: theme.text } },
530
949
  yAxis: combo && y2Set.size > 0
531
950
  ? [valueAxis(), valueAxis({ position: 'right', splitLine: { show: false } })]
@@ -581,23 +1000,48 @@ export function chartAltOf(
581
1000
  const label = title !== ''
582
1001
  ? kitText('soma.kit.chart_alt', { ...params, title }, at)
583
1002
  : kitText('soma.kit.chart_alt_untitled', params, at);
1003
+ // 标注列:命中该行的标记文本(颜色之外必有文字,读屏据此知道今日 / 缺口 / 里程碑)
1004
+ const noteByRow = new Map<number, string[]>();
1005
+ if (config.marks !== undefined && KIT_CHART_COLUMN_TYPES.has(config.type)) {
1006
+ for (const m of resolveChartMarks(config.marks, shown, { xKey: src(config.x), seriesKey: src })) {
1007
+ if (m.label === '') continue;
1008
+ const lo = m.kind === 'band' ? m.from! : m.at;
1009
+ const hi = m.kind === 'band' ? m.to! : m.at;
1010
+ if (m.axis !== 'x' || lo === undefined || hi === undefined) continue;
1011
+ for (let i = lo; i <= hi; i += 1) noteByRow.set(i, [...(noteByRow.get(i) ?? []), m.label]);
1012
+ }
1013
+ }
1014
+ const withNotes = noteByRow.size > 0;
1015
+ const idealSuffix = kitText('soma.kit.chart_ideal', { name: '' }, at);
1016
+ const projSuffix = kitText('soma.kit.chart_projection', { name: '' }, at);
584
1017
  return {
585
1018
  label,
586
- columns: fields,
587
- rows: shown.slice(0, cap).map((r) => fields.map((f) => cell(r[src(f)]))),
1019
+ // 理想线 / 预测线的表头标注;空值(null / 缺值)单元格为空串(字段名已含角色词时不拼成「预测(预测)」)
1020
+ columns: [
1021
+ ...fields.map((f) => (config.roles?.[f] === 'ideal' ? appendRoleSuffix(f, idealSuffix)
1022
+ : config.roles?.[f] === 'projection' ? appendRoleSuffix(f, projSuffix) : f)),
1023
+ ...(withNotes ? [kitText('soma.kit.chart_marks_col', undefined, at)] : []),
1024
+ ],
1025
+ rows: shown.slice(0, cap).map((r, i) => [...fields.map((f) => cell(r[src(f)])), ...(withNotes ? [(noteByRow.get(i) ?? []).join('、')] : [])]),
588
1026
  total: shown.length,
589
1027
  };
590
1028
  }
591
1029
 
592
1030
  // ───────── 组件 ─────────
593
1031
 
1032
+ /** 引擎实例里本组件用到的成员;onColumn / highlight / onPointer 是可选能力(旧适配器缺它们时读数只对有图元的列生效) */
1033
+ interface ChartInstanceLike {
1034
+ setOption(option: Record<string, unknown>, mode?: 'merge' | 'replace'): void;
1035
+ resize(): void;
1036
+ dispose(): void;
1037
+ highlight?(p: { seriesIndex: number; dataIndex: number } | null): void;
1038
+ onColumn?(handler: (kind: 'hover' | 'click' | 'leave', col: { dataIndex: number } | null) => void): () => void;
1039
+ onPointer?(handler: (kind: 'hover' | 'click' | 'leave', p: { dataIndex: number } | null) => void): () => void;
1040
+ }
1041
+
594
1042
  interface ChartEnginePort {
595
1043
  ensure(seriesTypes: readonly string[], components?: readonly string[]): Promise<void>;
596
- create(host: HTMLElement, init: { theme: Record<string, unknown>; locale?: string }): Promise<{
597
- setOption(option: Record<string, unknown>, mode?: 'merge' | 'replace'): void;
598
- resize(): void;
599
- dispose(): void;
600
- }>;
1044
+ create(host: HTMLElement, init: { theme: Record<string, unknown>; locale?: string }): Promise<ChartInstanceLike>;
601
1045
  }
602
1046
 
603
1047
  /** 把 --soma-* 令牌解析成运行期颜色值:直接读宿主的计算样式,源码不出现裸色值,也不写内联样式 */
@@ -606,11 +1050,29 @@ function resolveToken(host: HTMLElement, token: string): string {
606
1050
  return value === '' ? `var(${token})` : value;
607
1051
  }
608
1052
 
1053
+ /** 令牌里的百分数(`55%` / `55`)→ 数;读不到 null */
1054
+ function pctToken(host: HTMLElement, token: string): number | null {
1055
+ const raw = typeof getComputedStyle === 'function' ? getComputedStyle(host).getPropertyValue(token).trim() : '';
1056
+ const n = Number.parseFloat(raw);
1057
+ return Number.isFinite(n) ? n : null;
1058
+ }
1059
+
609
1060
  function themeOf(host: HTMLElement): KitChartTheme {
1061
+ // 图表填充重量(强调级作用域重写 --soma-chart-fill-mix / --soma-chart-bar-ratio):首绘读一次(data-kit-emphasis 是编译期常量,运行期不变)
1062
+ const fillMix = pctToken(host, '--soma-chart-fill-mix');
1063
+ const barRatio = pctToken(host, '--soma-chart-bar-ratio');
1064
+ const surface = resolveToken(host, '--soma-surface-panel');
610
1065
  return {
611
- palette: KIT_CHART_SERIES_TOKENS.map((n) => resolveToken(host, n)),
1066
+ palette: KIT_CHART_SERIES_TOKENS.map((n) => {
1067
+ const c = resolveToken(host, n);
1068
+ return fillMix === null ? c : mixTowardSurface(c, surface, fillMix);
1069
+ }),
1070
+ ...(barRatio !== null ? { barRatioPct: barRatio } : {}),
612
1071
  text: resolveToken(host, '--soma-text-secondary'),
613
1072
  line: resolveToken(host, '--soma-border-hairline'),
1073
+ ideal: resolveToken(host, '--soma-text-muted'),
1074
+ primary: resolveToken(host, '--soma-c-primary'),
1075
+ projectionSuffix: kitText('soma.kit.chart_projection', { name: '' }, host),
614
1076
  ok: resolveToken(host, '--soma-c-success'),
615
1077
  warn: resolveToken(host, '--soma-c-warning'),
616
1078
  danger: resolveToken(host, '--soma-c-danger'),
@@ -624,7 +1086,7 @@ export function createChart(): SomaComponentDefinition {
624
1086
  layer: 'data',
625
1087
  props: {
626
1088
  data: { type: 'array', default: [], desc: '行数组' },
627
- 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 父名称(空 = 根)' },
1089
+ 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(line / area / bar / combo 的 y 项也可写 { field, role?: ideal }:ideal = 理想线,虚线中性色、不占序列配色、图例排最后;数据点 null = 断线留白,不补零不连线), 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 父名称(空 = 根);折线 / 面积 / 柱 / 组合另可写 marks: [{ kind: line|band|point, axis?: x|y, at? / from? / to?: 字面量或 { field }, series?, label?, role? }](竖线 / 区间带 / 标记点,取色线型由 role 决定)、readout: { place?, title?, note?, items: [{ field, label?, format?, unit? }], default? }(逐列读数区)、interact: { pick?: bool }(点击 / Enter 选中列抛 point_pick);y 项 role 另有 projection(预测线)与 ok / caution / overload(语义取色)' },
628
1090
  map: { type: 'object', default: {}, desc: '键名对照:chart 里的字段名 -> 数据里的键' },
629
1091
  empty: { type: 'string', default: '', desc: '无数据时的空态文案;缺省取内置文案(按页面语言)' },
630
1092
  title: { type: 'string', default: '', desc: '图表标题:进可访问名(role=img)与读屏数据表标题;缺省只用「图型 + 系列数 + 数据点数」' },
@@ -633,7 +1095,13 @@ export function createChart(): SomaComponentDefinition {
633
1095
  locale: { type: 'string', default: '', desc: '图表语言;空则不传' },
634
1096
  class: { type: 'string', default: '', desc: '外部传入的类,追加在根节点类串末尾' },
635
1097
  },
636
- emits: { ...KIT_READ_STATE_EMIT_DEFS },
1098
+ emits: {
1099
+ ...KIT_READ_STATE_EMIT_DEFS,
1100
+ point_pick: {
1101
+ payload: { index: { type: 'number' }, x: { type: 'string' }, row: { type: 'object' } },
1102
+ desc: 'chart.interact.pick 为真时,点击 / Enter 选中某一列:index 列序号、x 类目值、row 该列的源数据行;去向由展示对象按 row 的业务字段决定,kit 不判断',
1103
+ },
1104
+ },
637
1105
  },
638
1106
  services: ['engines'],
639
1107
  templateHtml:
@@ -650,11 +1118,59 @@ export function createChart(): SomaComponentDefinition {
650
1118
  let emptyWrap: HTMLElement | null = null;
651
1119
  let emptyText: HTMLElement | null = null;
652
1120
  let altWrap: HTMLElement | null = null;
653
- let instance: { setOption(o: Record<string, unknown>, m?: 'merge' | 'replace'): void; resize(): void; dispose(): void } | null = null;
1121
+ let instance: ChartInstanceLike | null = null;
1122
+ // 交互状态(K2 / K3):读数区 DOM、当前列、键盘漫游标记、最近一次出图的上下文(焦点带重建 option 用)
1123
+ let readoutEl: HTMLElement | null = null;
1124
+ let liveEl: HTMLElement | null = null;
1125
+ let activeCol = -1;
1126
+ let defaultCol = -1;
1127
+ let kbdActive = false;
1128
+ let offColumn: (() => void) | null = null;
1129
+ let drawn: { config: KitChartConfig; rows: Array<Record<string, unknown>>; theme: KitChartTheme; map: unknown; reduceMotion: boolean } | null = null;
654
1130
  let creating: Promise<void> | null = null;
655
1131
  let resizeObs: ResizeObserver | null = null;
656
1132
  let seq = 0;
657
1133
  let alive = false;
1134
+ // 引擎就绪前的占位:引擎动态加载,首次出图晚于页面其余部分。就绪前舞台保留尺寸但不可见(invisible,不跳动),
1135
+ // 沿用 kit 的加载反馈时序(loading-gate:延迟 200ms 才出加载面板、出现后至少显示 400ms),面板与舞台同尺寸叠在同一位置;
1136
+ // 出图后在根上标 data-kit-chart-ready(截图 / 渲染测量据此判断图已就绪,不靠固定等待)。
1137
+ let engineGate: KitLoadingGate | null = null;
1138
+ let settled = false;
1139
+ let revealed = false;
1140
+ const reveal = (): void => {
1141
+ revealed = true;
1142
+ engineGate = null;
1143
+ // 只收起加载占位;数据旁的错误提示条(keepStage 的 error 面板)保留
1144
+ if (emptyText?.getAttribute('data-kit-state') === 'loading' || emptyText?.getAttribute('data-kit-state') === null) {
1145
+ emptyWrap?.classList.remove('absolute', 'inset-0');
1146
+ emptyWrap?.classList.add('hidden');
1147
+ }
1148
+ stageWrap?.classList.remove('invisible');
1149
+ root?.setAttribute(KIT_CHART_READY_ATTR, '');
1150
+ };
1151
+ const beginEngineWait = (): void => {
1152
+ if (revealed || engineGate !== null) return;
1153
+ settled = false;
1154
+ stageWrap?.classList.add('invisible');
1155
+ engineGate = createLoadingGate((phase) => {
1156
+ if (!alive) return;
1157
+ if (phase === 'visible' && !revealed) {
1158
+ showPanel('loading', str(P().loading_text, kitText('soma.kit.loading', undefined, root ?? undefined)), {}, true);
1159
+ emptyWrap?.classList.add('absolute', 'inset-0');
1160
+ } else if (phase === 'idle' && settled) reveal();
1161
+ });
1162
+ engineGate.start();
1163
+ };
1164
+ const endEngineWait = (): void => {
1165
+ if (engineGate === null) return;
1166
+ settled = true;
1167
+ engineGate.finish();
1168
+ };
1169
+ const abortEngineWait = (): void => {
1170
+ settled = false;
1171
+ engineGate?.cancel();
1172
+ engineGate = null;
1173
+ };
658
1174
 
659
1175
  // 深浅色切换:系列色取自运行期计算值,主题变了要重算并 setOption。
660
1176
  // 两个来源——系统偏好 prefers-color-scheme,以及 <html> 上 soma-scheme-dark / soma-scheme-light 类的变化
@@ -701,6 +1217,7 @@ export function createChart(): SomaComponentDefinition {
701
1217
  // 空 / 加载 / 错误都画进同一个面板位(与集合三态同一画法:base/state-panel.ts);keepStage = 图保留、面板作提示条
702
1218
  const showPanel = (kind: KitStateKind, text: string, o: Partial<KitStatePanelOptions> = {}, keepStage = false): void => {
703
1219
  if (!stageWrap || !emptyWrap || !emptyText) return;
1220
+ emptyWrap.classList.remove('absolute', 'inset-0');
704
1221
  if (keepStage) stageWrap.classList.remove('hidden'); else { stageWrap.classList.add('hidden'); clearAlt(); }
705
1222
  emptyWrap.classList.remove('hidden');
706
1223
  paintKitStatePanel(emptyText, kind, { ...o, text });
@@ -711,6 +1228,8 @@ export function createChart(): SomaComponentDefinition {
711
1228
  stageWrap?.removeAttribute('role');
712
1229
  stageWrap?.removeAttribute('aria-label');
713
1230
  if (altWrap) altWrap.textContent = '';
1231
+ drawn = null;
1232
+ resetInteractive();
714
1233
  };
715
1234
  const setAlt = (alt: KitChartAlt, title: string, override: string): void => {
716
1235
  if (!stageWrap) return;
@@ -761,6 +1280,153 @@ export function createChart(): SomaComponentDefinition {
761
1280
  stageWrap.classList.remove('hidden');
762
1281
  };
763
1282
 
1283
+ // ── 逐列读数与列选中(K2 / K3):读数区由 kit 自己渲染,不用引擎 tooltip;指针经端口 onColumn(缺则回落 onPointer)、键盘经根上的 keydown ──
1284
+ const interactiveOf = (c: KitChartConfig | undefined): boolean => c !== undefined && (c.readout !== undefined || c.interact !== undefined);
1285
+ const cellText = (row: Record<string, unknown> | undefined, field: string, map: unknown): string => {
1286
+ const m = recOf(map);
1287
+ const key = typeof m[field] === 'string' && m[field] !== '' ? String(m[field]) : field;
1288
+ const v = row?.[key];
1289
+ return v === undefined || v === null ? '' : String(v);
1290
+ };
1291
+ /** 读数内容(标题 + 各项「名 值」+ 附注):值取行字段不重算,空值「—」 */
1292
+ const readoutParts = (col: number): { title: string; items: Array<{ label: string; value: string }>; note: string } | null => {
1293
+ const d = drawn;
1294
+ const ro = d?.config.readout;
1295
+ if (!d || !ro || col < 0 || col >= d.rows.length) return null;
1296
+ const row = d.rows[col];
1297
+ const m = recOf(d.map);
1298
+ const empty = kitText('soma.kit.chart_readout_empty', undefined, root ?? undefined);
1299
+ return {
1300
+ title: ro.title !== '' ? cellText(row, ro.title, m).slice(0, CHART_NUM.readout.titleMax) : cellText(row, d.config.x, m),
1301
+ items: ro.items.map((it) => {
1302
+ const key = typeof m[it.field] === 'string' && m[it.field] !== '' ? String(m[it.field]) : it.field;
1303
+ return { label: it.label, value: formatReadoutValue(row?.[key], it.format, it.unit, empty) };
1304
+ }),
1305
+ note: ro.note !== '' ? cellText(row, ro.note, m).slice(0, CHART_NUM.readout.noteMax) : '',
1306
+ };
1307
+ };
1308
+ const paintReadout = (col: number): void => {
1309
+ if (!readoutEl) return;
1310
+ const parts = readoutParts(col);
1311
+ readoutEl.textContent = '';
1312
+ if (parts === null) { readoutEl.classList.add('hidden'); return; }
1313
+ readoutEl.classList.remove('hidden');
1314
+ const doc = readoutEl.ownerDocument;
1315
+ const add = (cls: string, text: string, parent: HTMLElement = readoutEl!): HTMLElement => {
1316
+ const span = doc.createElement('span');
1317
+ span.className = cls;
1318
+ span.textContent = text;
1319
+ parent.appendChild(span);
1320
+ return span;
1321
+ };
1322
+ if (parts.title !== '') add(READOUT_TITLE_CLASS, parts.title);
1323
+ for (const it of parts.items) {
1324
+ const wrap = add(READOUT_ITEM_CLASS, '');
1325
+ add('', it.label, wrap);
1326
+ add(READOUT_VALUE_CLASS, it.value, wrap);
1327
+ }
1328
+ if (parts.note !== '') add(READOUT_NOTE_CLASS, parts.note);
1329
+ };
1330
+ /** 焦点带:整份 option 带上焦点列重建(动画关;默认列不画带) */
1331
+ const announce = (col: number, picked: boolean): void => {
1332
+ if (!liveEl) return;
1333
+ const parts = readoutParts(col);
1334
+ const title = parts?.title ?? String(col + 1);
1335
+ liveEl.textContent = picked
1336
+ ? kitText('soma.kit.chart_picked', { title }, root ?? undefined)
1337
+ : parts === null ? title : kitText('soma.kit.chart_column_summary', { title, items: parts.items.map((i) => `${i.label} ${i.value}`).join(',') }, root ?? undefined);
1338
+ };
1339
+ const setColumn = (col: number, source: 'pointer' | 'key' | 'default'): void => {
1340
+ if (col === activeCol && source !== 'key') return;
1341
+ activeCol = col;
1342
+ paintReadout(col);
1343
+ // 焦点列的视觉由 highlight(高亮点)+ 读数区承担,不画焦点带(见 markAreaOf 注释)
1344
+ if (source === 'default') { instance?.highlight?.(null); return; }
1345
+ if (col >= 0) instance?.highlight?.({ seriesIndex: 0, dataIndex: col });
1346
+ // 读屏只在键盘移动时播报,悬停不播报
1347
+ if (source === 'key' && col >= 0) announce(col, false);
1348
+ };
1349
+ const pick = (col: number): void => {
1350
+ const d = drawn;
1351
+ if (!d || d.config.interact?.pick !== true || col < 0 || col >= d.rows.length) return;
1352
+ const row = d.rows[col]!;
1353
+ const m = recOf(d.map);
1354
+ const xKey = typeof m[d.config.x] === 'string' && m[d.config.x] !== '' ? String(m[d.config.x]) : d.config.x;
1355
+ api.emit('point_pick', { index: col, x: row[xKey] === undefined || row[xKey] === null ? '' : String(row[xKey]), row });
1356
+ announce(col, true);
1357
+ };
1358
+ const onColumnEvent = (kind: 'hover' | 'click' | 'leave', col: { dataIndex: number } | null): void => {
1359
+ if (!interactiveOf(drawn?.config)) return;
1360
+ if (kind === 'click') { if (col) pick(col.dataIndex); return; }
1361
+ if (kbdActive) return;
1362
+ if (kind === 'hover' && col) setColumn(col.dataIndex, 'pointer');
1363
+ else if (kind === 'leave') setColumn(defaultCol, 'default');
1364
+ };
1365
+ const bindColumns = (inst: ChartInstanceLike): void => {
1366
+ offColumn?.();
1367
+ offColumn = inst.onColumn !== undefined
1368
+ ? inst.onColumn(onColumnEvent)
1369
+ : inst.onPointer !== undefined ? inst.onPointer(onColumnEvent) : null;
1370
+ };
1371
+ const onKeyDown = (event: KeyboardEvent): void => {
1372
+ const d = drawn;
1373
+ if (!d || !interactiveOf(d.config)) return;
1374
+ if (event.key === 'Enter' || event.key === ' ') {
1375
+ if (d.config.interact?.pick === true && activeCol >= 0) { event.preventDefault(); pick(activeCol); }
1376
+ return;
1377
+ }
1378
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
1379
+ event.preventDefault();
1380
+ kbdActive = true;
1381
+ const next = stepChartColumn(activeCol, d.rows.length, event.key);
1382
+ if (next >= 0) setColumn(next, 'key');
1383
+ };
1384
+ const onFocusIn = (): void => {
1385
+ // 只有键盘获得焦点才进入键盘漫游(鼠标点击聚焦不抢走悬停驱动)
1386
+ let visible = true;
1387
+ try { visible = root?.matches(':focus-visible') ?? true; } catch { visible = true; }
1388
+ kbdActive = visible;
1389
+ };
1390
+ const onFocusOut = (): void => {
1391
+ if (!kbdActive) return;
1392
+ kbdActive = false;
1393
+ setColumn(defaultCol, 'default');
1394
+ };
1395
+ /** 按本次出图的配置同步交互壳:根的焦点属性、读数区位置与默认列 */
1396
+ const syncInteractive = (config: KitChartConfig, rows: Array<Record<string, unknown>>, label: string): void => {
1397
+ if (!root || !stageWrap) return;
1398
+ if (!interactiveOf(config)) { resetInteractive(); return; }
1399
+ root.setAttribute('tabindex', '0');
1400
+ root.setAttribute('role', 'group');
1401
+ root.setAttribute('aria-roledescription', kitText('soma.kit.chart_roledesc', undefined, root));
1402
+ root.setAttribute('aria-label', label);
1403
+ root.className = joinClass(root.className, ROOT_FOCUS_CLASS);
1404
+ if (readoutEl) {
1405
+ const top = config.readout?.place === 'top';
1406
+ readoutEl.className = `${READOUT_CLASS} ${top ? READOUT_TOP_CLASS : READOUT_BOTTOM_CLASS}`;
1407
+ readoutEl.setAttribute('aria-hidden', 'true');
1408
+ // data-kit-chart-readout:渲染判定 chart.readout.hover 的稳定选择器
1409
+ readoutEl.setAttribute('data-kit-chart-readout', '');
1410
+ if (top) root.insertBefore(readoutEl, stageWrap); else stageWrap.after(readoutEl);
1411
+ }
1412
+ if (liveEl && !liveEl.isConnected) root.appendChild(liveEl);
1413
+ const fields = (config.readout?.items.map((i) => i.field) ?? config.y).map((f) => {
1414
+ const m = recOf(drawn?.map);
1415
+ return typeof m[f] === 'string' && m[f] !== '' ? String(m[f]) : f;
1416
+ });
1417
+ defaultCol = defaultReadoutColumn(rows, fields, config.readout?.defaultMode ?? 'none');
1418
+ if (kbdActive && activeCol >= 0 && activeCol < rows.length) paintReadout(activeCol);
1419
+ else { activeCol = -2; setColumn(defaultCol, 'default'); }
1420
+ };
1421
+ const resetInteractive = (): void => {
1422
+ for (const a of ['tabindex', 'role', 'aria-roledescription', 'aria-label']) root?.removeAttribute(a);
1423
+ readoutEl?.classList.add('hidden');
1424
+ if (readoutEl) readoutEl.textContent = '';
1425
+ if (liveEl) liveEl.textContent = '';
1426
+ activeCol = -1;
1427
+ defaultCol = -1;
1428
+ };
1429
+
764
1430
  const portOf = (): ChartEnginePort | null => {
765
1431
  const engines = (api.services as { engines?: { chart?: ChartEnginePort } } | undefined)?.engines;
766
1432
  return engines?.chart ?? null;
@@ -788,21 +1454,28 @@ export function createChart(): SomaComponentDefinition {
788
1454
  if (port === null) { showPanel('error', kitText('soma.kit.chart_no_engine', undefined, root)); return; }
789
1455
  try {
790
1456
  showStage();
1457
+ if (instance === null) beginEngineWait();
791
1458
  if (errorText !== '') showPanel('error', errorText, { retry, retryLabel }, true);
792
1459
  const theme = themeOf(root);
793
1460
  // 减少动效偏好:关掉引擎的入场 / 更新动画(端口不透出 aria / decal 初始化项,系列区分靠图例 + 数据表)
794
1461
  const reduceMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
795
1462
  const option = { ...buildChartOption(config, rows, theme, p.map), ...(reduceMotion ? { animation: false } : {}) };
796
- setAlt(chartAltOf(config, rows, p.map, str(p.title), root), str(p.title), str(p.aria_label));
1463
+ const alt = chartAltOf(config, rows, p.map, str(p.title), root);
1464
+ setAlt(alt, str(p.title), str(p.aria_label));
1465
+ drawn = { config, rows, theme, map: p.map, reduceMotion };
1466
+ syncInteractive(config, rows, str(p.aria_label) !== '' ? str(p.aria_label) : alt.label);
1467
+ const marked = chartMarkComponentsOf(config);
1468
+ const requiredSeries = renderedSeriesTypesOf(config, option);
797
1469
  if (instance === null) {
798
1470
  if (creating === null) {
799
1471
  creating = (async () => {
800
1472
  try {
801
- await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, (config.refLines?.length ?? 0) > 0));
1473
+ await port.ensure(requiredSeries, engineComponentsOf(config.type, marked.markLine, marked.extra));
802
1474
  const locale = str(p.locale);
803
1475
  const created = await port.create(stage!, { theme: { color: theme.palette }, ...(locale !== '' ? { locale } : {}) });
804
1476
  if (!alive) { created.dispose(); return; }
805
1477
  instance = created;
1478
+ bindColumns(created);
806
1479
  if (typeof ResizeObserver === 'function') {
807
1480
  resizeObs = new ResizeObserver(() => instance?.resize());
808
1481
  resizeObs.observe(stage!);
@@ -821,11 +1494,13 @@ export function createChart(): SomaComponentDefinition {
821
1494
  }
822
1495
  // 异步期间又有新一轮 paint 或已卸载:交给最新一轮
823
1496
  if (!alive || mine !== seq || instance === null) return;
824
- await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, (config.refLines?.length ?? 0) > 0));
1497
+ await port.ensure(requiredSeries, engineComponentsOf(config.type, marked.markLine, marked.extra));
825
1498
  if (!alive || mine !== seq) return;
826
1499
  instance.setOption(option, 'replace');
1500
+ endEngineWait();
827
1501
  } catch {
828
1502
  creating = null;
1503
+ abortEngineWait();
829
1504
  if (alive && mine === seq) showPanel('error', kitText('soma.kit.chart_unavailable', undefined, root));
830
1505
  }
831
1506
  };
@@ -840,8 +1515,30 @@ export function createChart(): SomaComponentDefinition {
840
1515
  emptyText = find('emptyText');
841
1516
  altWrap = find('altWrap');
842
1517
  watchScheme();
1518
+ // 读数区(视觉)与读屏播报区(仅键盘驱动更新):由 kit 自己渲染,位置在 paint 里按 readout.place 摆
1519
+ readoutEl = rootEl.ownerDocument.createElement('div');
1520
+ readoutEl.className = 'hidden';
1521
+ liveEl = rootEl.ownerDocument.createElement('div');
1522
+ liveEl.className = 'sr-only';
1523
+ liveEl.setAttribute('role', 'status');
1524
+ liveEl.setAttribute('aria-live', 'polite');
1525
+ liveEl.setAttribute('aria-atomic', 'true');
1526
+ rootEl.addEventListener('keydown', onKeyDown);
1527
+ rootEl.addEventListener('focusin', onFocusIn);
1528
+ rootEl.addEventListener('focusout', onFocusOut);
843
1529
  return () => {
844
1530
  alive = false;
1531
+ rootEl.removeEventListener('keydown', onKeyDown);
1532
+ rootEl.removeEventListener('focusin', onFocusIn);
1533
+ rootEl.removeEventListener('focusout', onFocusOut);
1534
+ offColumn?.();
1535
+ offColumn = null;
1536
+ readoutEl?.remove();
1537
+ liveEl?.remove();
1538
+ readoutEl = null;
1539
+ liveEl = null;
1540
+ drawn = null;
1541
+ abortEngineWait();
845
1542
  unwatchScheme();
846
1543
  resizeObs?.disconnect();
847
1544
  resizeObs = null;