soma-kit 0.1.12 → 0.1.14

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 (300) hide show
  1. package/README.md +5 -4
  2. package/bin/soma-kit.mjs +31 -1
  3. package/bin/soma.mjs +0 -0
  4. package/package.json +5 -4
  5. package/spec/generated/kit-app.schema.json +172 -4
  6. package/spec/generated/kit-page.schema.json +164 -5
  7. package/spec/kit-grammar.json +598 -96
  8. package/spec/kit-grammar.schema.json +12 -6
  9. package/src/app/app-config.ts +92 -8
  10. package/src/app/component-gate.ts +271 -13
  11. package/src/app/define-kit-app.ts +2 -2
  12. package/src/app/define-kit-view.ts +9 -5
  13. package/src/app/dev-diagnostic.ts +5 -0
  14. package/src/app/index.ts +29 -5
  15. package/src/app/kit-view-context.ts +181 -15
  16. package/src/app/render-ports.ts +18 -0
  17. package/src/app/server-pages.ts +8 -2
  18. package/src/app/server.ts +55 -8
  19. package/src/app/theme-runtime.ts +4 -0
  20. package/src/base/action-busy.ts +101 -4
  21. package/src/base/action-slots.ts +13 -2
  22. package/src/base/anchored-layer.ts +50 -0
  23. package/src/base/button.ts +62 -15
  24. package/src/base/check-core.ts +8 -0
  25. package/src/base/checkbox.ts +2 -1
  26. package/src/base/choice.ts +21 -2
  27. package/src/base/color-picker.ts +10 -5
  28. package/src/base/command-palette.ts +1 -1
  29. package/src/base/context-menu.ts +10 -7
  30. package/src/base/date-range.ts +7 -7
  31. package/src/base/date.ts +55 -16
  32. package/src/base/delta.ts +72 -0
  33. package/src/base/end-edge.ts +61 -0
  34. package/src/base/fab.ts +1 -1
  35. package/src/base/gap-value.ts +168 -0
  36. package/src/base/hint-tips.ts +170 -0
  37. package/src/base/icons.ts +8 -0
  38. package/src/base/illustrations.ts +95 -0
  39. package/src/base/index.ts +32 -9
  40. package/src/base/listbox-core.ts +6 -5
  41. package/src/base/loading-gate.ts +140 -87
  42. package/src/base/mentions.ts +2 -1
  43. package/src/base/menu-button.ts +16 -18
  44. package/src/base/menu-core.ts +37 -8
  45. package/src/base/motion/hover-3d.ts +1 -1
  46. package/src/base/motion/marquee.ts +1 -1
  47. package/src/base/otp.ts +5 -4
  48. package/src/base/overlay-runtime.ts +235 -0
  49. package/src/base/popover.ts +10 -9
  50. package/src/base/popup.ts +67 -8
  51. package/src/base/portal-core.ts +4 -0
  52. package/src/base/qty-stepper.ts +5 -5
  53. package/src/base/radio.ts +2 -1
  54. package/src/base/range.ts +19 -2
  55. package/src/base/rating.ts +11 -6
  56. package/src/base/reason-tip.ts +150 -0
  57. package/src/base/segmented.ts +36 -24
  58. package/src/base/shared.ts +180 -36
  59. package/src/base/state-panel.ts +367 -0
  60. package/src/base/status-tone.ts +27 -0
  61. package/src/base/sticky-edge.ts +116 -0
  62. package/src/base/swap.ts +6 -6
  63. package/src/base/switch.ts +10 -5
  64. package/src/base/tag-input.ts +6 -6
  65. package/src/base/tag.ts +76 -41
  66. package/src/base/text.ts +43 -14
  67. package/src/base/time-picker.ts +7 -5
  68. package/src/base/tree-select.ts +6 -4
  69. package/src/base/trend-tone.ts +9 -0
  70. package/src/base/upload.ts +15 -9
  71. package/src/base/view-transition.ts +77 -0
  72. package/src/biz/approval-desk/shell.ts +15 -11
  73. package/src/biz/auth-panel/shell.ts +9 -7
  74. package/src/biz/category-crud/compile.ts +5 -4
  75. package/src/biz/category-crud/shell.ts +5 -3
  76. package/src/biz/checkout-page/compile.ts +2 -1
  77. package/src/biz/checkout-page/shell.ts +10 -8
  78. package/src/biz/compose.ts +2 -2
  79. package/src/biz/data-components.ts +4 -0
  80. package/src/biz/import-wizard/shell.ts +13 -10
  81. package/src/biz/landing-page/shell.ts +2 -2
  82. package/src/biz/link/hub.ts +23 -5
  83. package/src/biz/link/shared.ts +23 -12
  84. package/src/biz/master-sub/compile.ts +207 -16
  85. package/src/biz/master-sub/detail-head.ts +61 -0
  86. package/src/biz/master-sub/index.ts +7 -3
  87. package/src/biz/master-sub/shell.ts +133 -24
  88. package/src/biz/multi-board/compile.ts +167 -9
  89. package/src/biz/multi-board/composition.ts +58 -0
  90. package/src/biz/multi-board/index.ts +1 -1
  91. package/src/biz/multi-board/prose-fold.ts +143 -0
  92. package/src/biz/multi-board/shell.ts +94 -23
  93. package/src/biz/notification-center/shell.ts +10 -7
  94. package/src/biz/page-templates/domain-templates.ts +2 -2
  95. package/src/biz/page-templates/result-page/shell.ts +4 -3
  96. package/src/biz/page-templates/sign-in-page/shell.ts +16 -16
  97. package/src/biz/record-detail/compile.ts +2 -2
  98. package/src/biz/record-detail/shell.ts +13 -10
  99. package/src/biz/settings-center/compile.ts +2 -1
  100. package/src/biz/settings-center/shell.ts +12 -9
  101. package/src/biz/shared/action-host.ts +6 -0
  102. package/src/biz/shared/compile-helpers.ts +97 -0
  103. package/src/biz/shared/coordinator.ts +7 -30
  104. package/src/biz/shared/index.ts +5 -0
  105. package/src/biz/shared/object-aliases.ts +154 -0
  106. package/src/biz/shared/overlay-compile.ts +281 -0
  107. package/src/biz/shared/overlay-shell.ts +142 -11
  108. package/src/biz/shared/pipes.ts +11 -5
  109. package/src/biz/shared/remove-wire.ts +4 -19
  110. package/src/biz/shared/runtime-hub.ts +10 -0
  111. package/src/biz/single-form/compile.ts +3 -2
  112. package/src/biz/single-form/shell.ts +9 -6
  113. package/src/biz/standard-crud/compile.ts +36 -161
  114. package/src/biz/standard-crud/shell.ts +23 -60
  115. package/src/biz/standard-crud/summary.ts +40 -0
  116. package/src/biz/step-form/shell.ts +15 -13
  117. package/src/biz/types.ts +6 -1
  118. package/src/cli/kit-cli.ts +138 -13
  119. package/src/cli/kit-init.ts +6 -1
  120. package/src/cli/layout-cli.ts +167 -0
  121. package/src/cli/migrate/index.ts +10 -0
  122. package/src/cli/migrate/migrate.ts +248 -0
  123. package/src/cli/migrate/text-utils.ts +306 -0
  124. package/src/cli/migrate/theme-map.ts +104 -0
  125. package/src/cli/migrate/ts-rules.ts +235 -0
  126. package/src/cli/migrate/types.ts +95 -0
  127. package/src/cli/migrate/view-skeleton.ts +159 -0
  128. package/src/cli/migrate/yaml-report.ts +376 -0
  129. package/src/cli/migrate/yaml-rules.ts +465 -0
  130. package/src/cli/view-writes.ts +69 -60
  131. package/src/compile/access-gate-attach.ts +27 -0
  132. package/src/compile/closed-set.ts +65 -4
  133. package/src/compile/compile-page.ts +66 -11
  134. package/src/compile/component-candidates.ts +14 -1
  135. package/src/compile/fragment.ts +11 -0
  136. package/src/compile/layout-lint/engine.ts +82 -0
  137. package/src/compile/layout-lint/index.ts +55 -0
  138. package/src/compile/layout-lint/rules-composition.ts +267 -0
  139. package/src/compile/layout-lint/rules-form.ts +191 -0
  140. package/src/compile/layout-lint/rules-table.ts +278 -0
  141. package/src/compile/layout-lint/score.ts +52 -0
  142. package/src/compile/layout-lint/types.ts +51 -0
  143. package/src/compile/page-composition.ts +189 -0
  144. package/src/compile/parse.ts +4 -0
  145. package/src/compile/producer-fingerprint.ts +56 -0
  146. package/src/compile/remove-guard.ts +10 -7
  147. package/src/compile/styles.ts +46 -8
  148. package/src/compile/types.ts +16 -2
  149. package/src/compile/view-check.ts +149 -16
  150. package/src/data/access-gate.ts +112 -0
  151. package/src/data/amount-breakdown.ts +9 -2
  152. package/src/data/approval-flow.ts +5 -2
  153. package/src/data/assignment-picker.ts +59 -28
  154. package/src/data/async-result-panel.ts +49 -3
  155. package/src/data/breadcrumbs.ts +3 -2
  156. package/src/data/calendar.ts +8 -3
  157. package/src/data/carousel.ts +10 -6
  158. package/src/data/chart.ts +744 -46
  159. package/src/data/checklist.ts +22 -6
  160. package/src/data/code-view.ts +8 -4
  161. package/src/data/comment-thread.ts +3 -2
  162. package/src/data/confirm-dialog.ts +72 -25
  163. package/src/data/context-menu.ts +3 -3
  164. package/src/data/dock.ts +1 -1
  165. package/src/data/embed.ts +231 -29
  166. package/src/data/field-mapper.ts +7 -4
  167. package/src/data/flow-editor-contract.ts +7 -0
  168. package/src/data/flow-editor.ts +26 -9
  169. package/src/data/flow-node-options.ts +33 -3
  170. package/src/data/footer.ts +2 -0
  171. package/src/data/gantt.ts +192 -27
  172. package/src/data/hero.ts +4 -1
  173. package/src/data/image-viewer.ts +7 -4
  174. package/src/data/index.ts +16 -4
  175. package/src/data/item-list.ts +27 -12
  176. package/src/data/kanban.ts +41 -10
  177. package/src/data/matrix.ts +391 -0
  178. package/src/data/media-grid.ts +6 -1
  179. package/src/data/mega-menu.ts +6 -4
  180. package/src/data/menu-dom.ts +4 -2
  181. package/src/data/menu.ts +60 -16
  182. package/src/data/mockup.ts +5 -1
  183. package/src/data/modal-dialog.ts +146 -26
  184. package/src/data/navbar.ts +8 -6
  185. package/src/data/notice-list.ts +301 -0
  186. package/src/data/notify-renderer.ts +21 -6
  187. package/src/data/object-form.ts +409 -87
  188. package/src/data/outcome-watch.ts +61 -2
  189. package/src/data/pager.ts +19 -8
  190. package/src/data/panel-head.ts +406 -0
  191. package/src/data/permission-matrix.ts +36 -11
  192. package/src/data/permission-tree.ts +52 -23
  193. package/src/data/pricing-table.ts +22 -11
  194. package/src/data/prompt-dialog.ts +165 -0
  195. package/src/data/reaction-bar.ts +6 -4
  196. package/src/data/record-card.ts +40 -7
  197. package/src/data/record-picker.ts +13 -7
  198. package/src/data/resident.ts +8 -0
  199. package/src/data/result-panel.ts +4 -2
  200. package/src/data/rich-text.ts +17 -1
  201. package/src/data/row-editor.ts +77 -24
  202. package/src/data/rule-builder.ts +14 -9
  203. package/src/data/shape-util.ts +27 -12
  204. package/src/data/stat-group.ts +459 -74
  205. package/src/data/static-lazy.ts +5 -0
  206. package/src/data/static-registry.ts +8 -0
  207. package/src/data/steps.ts +8 -3
  208. package/src/data/survey.ts +7 -4
  209. package/src/data/system-switcher.ts +3 -2
  210. package/src/data/text-action-button.ts +17 -0
  211. package/src/data/timeline.ts +17 -6
  212. package/src/data/tour-guide.ts +3 -2
  213. package/src/data/transfer.ts +40 -16
  214. package/src/data/tree-table.ts +65 -37
  215. package/src/data/tree.ts +22 -2
  216. package/src/data/virtual-rows.ts +21 -11
  217. package/src/data/wrapped-candidates.ts +32 -1
  218. package/src/frames/index.ts +1 -0
  219. package/src/frames/list-summary.ts +100 -0
  220. package/src/frames/page-bar.ts +7 -14
  221. package/src/frames/page-status.ts +7 -5
  222. package/src/frames/shared.ts +34 -13
  223. package/src/frames/split-frame/shell.ts +1 -1
  224. package/src/frames/tabs-frame/shell.ts +9 -6
  225. package/src/frames/tabs-frame/wiring.ts +1 -0
  226. package/src/frames/top-main-frame.ts +3 -3
  227. package/src/frames/types.ts +3 -1
  228. package/src/frames/workspace-frame/extras.ts +1 -1
  229. package/src/frames/workspace-frame/shell.ts +4 -4
  230. package/src/frames/workspace-frame/tab-scroll.ts +28 -0
  231. package/src/frames/workspace-frame/view.ts +168 -44
  232. package/src/generated/kit-grammar-runtime.ts +390 -59
  233. package/src/i18n/kit-text.ts +90 -4
  234. package/src/i18n/resolve-text-refs.ts +22 -6
  235. package/src/object-renderer/action-group.ts +139 -0
  236. package/src/object-renderer/action-more.ts +144 -0
  237. package/src/object-renderer/arrange.ts +71 -7
  238. package/src/object-renderer/candidates.ts +4 -0
  239. package/src/object-renderer/collection-parts.ts +264 -62
  240. package/src/object-renderer/collection-table.ts +177 -5
  241. package/src/object-renderer/collection.ts +188 -37
  242. package/src/object-renderer/compile-data.ts +28 -3
  243. package/src/object-renderer/defaults.ts +27 -2
  244. package/src/object-renderer/display-checks.ts +1 -1
  245. package/src/object-renderer/emit-events.ts +43 -9
  246. package/src/object-renderer/emit-object.ts +4 -0
  247. package/src/object-renderer/emit-static.ts +434 -41
  248. package/src/object-renderer/filter-plan.ts +84 -0
  249. package/src/object-renderer/form-detail.ts +1 -2
  250. package/src/object-renderer/form-notify.ts +45 -0
  251. package/src/object-renderer/index.ts +5 -0
  252. package/src/object-renderer/layout-facts.ts +394 -0
  253. package/src/object-renderer/layout-plan.ts +225 -0
  254. package/src/object-renderer/layout-plan.types.ts +59 -0
  255. package/src/object-renderer/parts.ts +6 -7
  256. package/src/object-renderer/render-object.ts +107 -46
  257. package/src/object-renderer/request-actions.ts +4 -2
  258. package/src/object-renderer/skeleton.ts +58 -19
  259. package/src/object-renderer/table-actions.ts +172 -32
  260. package/src/object-renderer/table-gap.ts +37 -0
  261. package/src/object-renderer/table-tools.ts +62 -30
  262. package/src/object-renderer/types.ts +84 -13
  263. package/src/object-renderer/view-binding.ts +205 -8
  264. package/src/page-target/intent-schema.ts +11 -0
  265. package/src/page-target/target.ts +5 -1
  266. package/src/recipes/container.ts +77 -1
  267. package/src/recipes/control.ts +76 -116
  268. package/src/recipes/emphasis.ts +56 -0
  269. package/src/recipes/frame-bleed.ts +33 -0
  270. package/src/recipes/index.ts +72 -0
  271. package/src/recipes/nowrap.ts +16 -0
  272. package/src/recipes/overlay.ts +120 -17
  273. package/src/recipes/placeholder.ts +95 -0
  274. package/src/recipes/rail-grid.ts +48 -0
  275. package/src/recipes/slot-align.ts +56 -0
  276. package/src/recipes/stat-state.ts +65 -0
  277. package/src/recipes/state.ts +40 -21
  278. package/src/recipes/status.ts +147 -0
  279. package/src/recipes/surface-edge.ts +16 -0
  280. package/src/recipes/surface.ts +40 -0
  281. package/src/recipes/table-gap.ts +80 -0
  282. package/src/recipes/table-native-edit.ts +242 -0
  283. package/src/recipes/table-row.ts +146 -3
  284. package/src/recipes/tabs.ts +49 -0
  285. package/src/recipes/title-row.ts +37 -0
  286. package/src/recipes/typography.ts +30 -37
  287. package/src/shared/confirm-decl.ts +118 -0
  288. package/src/shared/envelope.ts +2 -2
  289. package/src/shared/paged-list-adapter.ts +15 -240
  290. package/src/shared/theme-runtime-shared.ts +6 -1
  291. package/src/theme/index.ts +1 -0
  292. package/src/theme/kit-theme-text.ts +1 -1
  293. package/src/theme/kit-theme.css +384 -13
  294. package/src/theme/kit-theme.tpl +384 -13
  295. package/src/theme/nine-dim-structure.ts +244 -7
  296. package/src/theme/surface-layers.ts +10 -1
  297. package/src/theme/theme-tokens.ts +63 -16
  298. package/src/theme/theme-types.ts +32 -0
  299. package/src/theme/typography.ts +21 -17
  300. package/src/biz/shared/remove-key.ts +0 -6
package/src/data/chart.ts CHANGED
@@ -12,15 +12,35 @@
12
12
 
13
13
  import type { SomaComponentDefinition } from 'soma-core';
14
14
  import { createKitController, joinClass, num, str } from '../base/shared';
15
- import { kitText } from '../i18n/kit-text';
15
+ import { createLoadingGate, type KitLoadingGate } from '../base/loading-gate';
16
+ import { kitText, type KitTextKey } from '../i18n/kit-text';
17
+ import {
18
+ KIT_READ_STATE_EMIT_DEFS, KIT_READ_STATE_PROP_DEFS, KIT_STATE_PANEL_CLASS_CANDIDATES, paintKitStatePanel,
19
+ type KitStateKind, type KitStatePanelOptions,
20
+ } from '../base/state-panel';
16
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 '../base/class-candidates';
27
+ import { mergeClass } from '../object-renderer/merge-class';
28
+ import { kitFocusRingRecipe } from '../recipes/state';
29
+ import { KIT_NOTICE_HEADLINE, KIT_STAT_VALUES_NUM, KIT_STAT_VALUES_ROW } from '../recipes/status';
17
30
  import { KIT_GRAMMAR_RUNTIME as grammarJson } from '../generated/kit-grammar-runtime';
18
31
 
19
32
  // 参考线 / 图例 / 数值格式的闭集与限值只读 kit-grammar.json#dataLimits.chart,代码里不手抄
20
33
  const CHART_LIMITS = (grammarJson as unknown as { dataLimits: { chart: {
21
34
  refLines: { stats: string[]; tones: string[] };
22
35
  legends: string[];
36
+ seriesRoles: string[];
37
+ seriesToneRoles: Record<string, string>;
38
+ seriesKinds: string[];
39
+ seriesAxes: string[];
40
+ marks: ChartMarkSpec;
23
41
  } } }).dataLimits.chart;
42
+ /** 标记的角色闭集(取色 / 线型 / 符号):读 kit-grammar.json#dataLimits.chart.marks */
43
+ const MARK_SPEC: ChartMarkSpec = CHART_LIMITS.marks;
24
44
  // 数字(条数 / 字数上限)读 design 的 kit-limits,闭集仍读语法
25
45
  const CHART_NUM = KIT_DATA_LIMITS.chart;
26
46
  /** 线宽 / 透明度 / 点径:design 真源 kit-limits#dataLimits.chart.style */
@@ -28,19 +48,68 @@ const CHART_STYLE = CHART_NUM.style;
28
48
  export const KIT_CHART_REF_STATS: readonly string[] = CHART_LIMITS.refLines.stats;
29
49
  export const KIT_CHART_REF_TONES: readonly string[] = CHART_LIMITS.refLines.tones;
30
50
  export const KIT_CHART_LEGENDS: readonly string[] = CHART_LIMITS.legends;
51
+ /** 系列角色闭集(目前只有 ideal = 理想线),读 kit-grammar.json#dataLimits.chart.seriesRoles */
52
+ export const KIT_CHART_SERIES_ROLES: readonly string[] = CHART_LIMITS.seriesRoles ?? [];
53
+ export type KitChartSeriesRole = 'ideal' | 'baseline' | 'projection' | 'ok' | 'caution' | 'overload';
54
+
55
+ /**
56
+ * 参考线图例样例的字形(引擎 path 图标,不画「线 + 圆点」):baseline = 一段细实线,其余(理想)= 两段虚线;
57
+ * 路径里两个零长度线段把包围盒撑成 25 x 14,引擎按包围盒缩放时细线不会被拉粗。
58
+ */
59
+ const LEGEND_BOX = 'M0,0L0,0M25,14L25,14';
60
+ export function referenceLegendIcon(role: string | undefined): string {
61
+ return role === 'baseline'
62
+ ? `path://${LEGEND_BOX}M0,6L25,6L25,8L0,8Z`
63
+ : `path://${LEGEND_BOX}M0,6L8,6L8,8L0,8ZM13,6L21,6L21,8L13,8Z`;
64
+ }
65
+
66
+ /**
67
+ * 参考线类系列(理想 / baseline)的线型:图里的系列与图例样例共用这一份(两处各写一份会让图例与图不一致)。
68
+ * baseline = 细实线,其余(理想)= 虚线;线宽 / 虚线样式读真源 kit-limits#dataLimits.chart.style。
69
+ */
70
+ export function referenceLineStyle(role: string | undefined, color: string): { width: number; type: 'solid' | number[]; color: string } {
71
+ return role === 'baseline'
72
+ ? { width: CHART_STYLE.baselineLineWidth, type: 'solid', color }
73
+ : { width: CHART_STYLE.idealLineWidth, type: [...CHART_STYLE.idealDash], color };
74
+ }
75
+ /** 语义取色的系列角色 -> 语气(读 kit-grammar.json#dataLimits.chart.seriesToneRoles) */
76
+ const SERIES_TONE_ROLES: Readonly<Record<string, string>> = CHART_LIMITS.seriesToneRoles;
77
+ /** combo 逐系列的柱 / 线与纵轴闭集,读 kit-grammar.json#dataLimits.chart.seriesKinds / seriesAxes */
78
+ export const KIT_CHART_SERIES_KINDS: readonly string[] = CHART_LIMITS.seriesKinds;
79
+ export const KIT_CHART_SERIES_AXES: readonly string[] = CHART_LIMITS.seriesAxes;
80
+ /** 只有这些图型的 y 系列可以带 role(理想线画成折线,叠在直角坐标系上) */
81
+ const ROLE_TYPES: ReadonlySet<string> = new Set(['line', 'area', 'bar', 'combo']);
31
82
 
32
83
  // ───────── 样式常量:Tailwind 类串与候选类清单 ─────────
33
84
  // hidden 与布局类分写在两层:外层只管显隐,内层管布局。
34
85
 
35
- const ROOT_CLASS = 'w-full';
86
+ const ROOT_CLASS = 'relative w-full';
87
+ /** 图已就绪的根标记:引擎加载完并出过图后才有(截图 / 渲染测量据此判断,不靠固定等待) */
88
+ export const KIT_CHART_READY_ATTR = 'data-kit-chart-ready';
36
89
  const STAGE_CLASS = 'h-72 w-full';
37
90
  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
91
 
92
+ /**
93
+ * 逐列读数区的类:排版与表面取 kit 配方(说明条标题 / StatGroup 多值行的字阶与等宽数字),不手写字阶;
94
+ * 容器是下沉面(bg-surface-sunken + rounded-md,与空态同一表面),键盘焦点环取条目焦点环配方。
95
+ */
96
+ const READOUT_CLASS = `rounded-md bg-surface-sunken px-3 py-2 ${KIT_STAT_VALUES_ROW}`;
97
+ const READOUT_TITLE_CLASS = KIT_NOTICE_HEADLINE;
98
+ const READOUT_ITEM_CLASS = 'inline-flex items-baseline gap-1.5';
99
+ const READOUT_VALUE_CLASS = KIT_STAT_VALUES_NUM;
100
+ const READOUT_NOTE_CLASS = 'text-fg-subtle';
101
+ const ROOT_FOCUS_CLASS = mergeClass('rounded-md', kitFocusRingRecipe('item'));
102
+ const READOUT_TOP_CLASS = 'mb-2';
103
+ const READOUT_BOTTOM_CLASS = 'mt-2';
104
+
39
105
  /** 本组件自带的全部类(供编译器并入候选类) */
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
- ]);
106
+ export const KIT_CHART_CLASS_CANDIDATES: readonly string[] = classCandidates(
107
+ ['relative', 'absolute', 'inset-0', 'invisible', 'w-full', 'h-72', 'hidden', 'sr-only',
108
+ 'flex', 'items-center', 'justify-center', 'rounded-md', 'border', 'border-border-subtle', 'bg-surface-sunken', 'text-sm', 'text-fg-muted'],
109
+ KIT_STATE_PANEL_CLASS_CANDIDATES,
110
+ READOUT_CLASS, READOUT_TITLE_CLASS, READOUT_ITEM_CLASS, READOUT_VALUE_CLASS, READOUT_NOTE_CLASS, ROOT_FOCUS_CLASS,
111
+ READOUT_TOP_CLASS, READOUT_BOTTOM_CLASS,
112
+ );
44
113
 
45
114
  // ───────── 数据规整:图形配置解析、层级树、仪表盘分段、引擎 option 生成(均为纯函数) ─────────
46
115
 
@@ -73,6 +142,14 @@ export interface KitChartConfig {
73
142
  y2?: string[];
74
143
  /** 参考线(直角坐标系图型):固定值或引擎统计值,虚线 */
75
144
  refLines?: KitChartRefLine[];
145
+ /** 系列角色:字段名 -> role(折线 / 面积 / 柱 / 组合;ideal = 理想线);没有带 role 的系列时不出现 */
146
+ roles?: Record<string, KitChartSeriesRole>;
147
+ /** 标记(竖线 / 区间带 / 标记点,K1):声明解析后的结果,几何由 resolveChartMarks 套数据行得到;没有则不出现 */
148
+ marks?: ChartMark[];
149
+ /** 逐列读数区(K2);没有则不出现 */
150
+ readout?: ReadoutConfig;
151
+ /** 点击 / Enter 选中列抛 point_pick(K3) */
152
+ interact?: { pick: boolean };
76
153
  /** 图例位置:auto = 多系列时在底部(饼 / 漏斗始终在底部),none 关闭 */
77
154
  legend?: 'auto' | 'top' | 'bottom' | 'none';
78
155
  /** 纵轴 / 标签的数值前后缀(引擎字符串模板,不含函数) */
@@ -101,15 +178,28 @@ const MIN_Y: Readonly<Partial<Record<KitChartType, number>>> = Object.freeze({ b
101
178
  const NEEDS_VALUE: ReadonlySet<KitChartType> = new Set<KitChartType>(['heatmap', 'sankey', 'chord']);
102
179
 
103
180
  /** 各类型需要的引擎组件:直角坐标系要 grid + legend;pie / donut / funnel 只要 legend;gauge 都不要 */
104
- export function engineComponentsOf(type: KitChartType, withMarkLine = false): string[] {
181
+ export function engineComponentsOf(type: KitChartType, withMarkLine = false, extra: readonly string[] = []): string[] {
105
182
  if (type === 'gauge' || type === 'sankey' || type === 'treemap' || type === 'sunburst' || type === 'chord') return [];
106
183
  if (type === 'pie' || type === 'donut' || type === 'funnel') return ['legend'];
107
184
  if (type === 'radar') return ['radar', 'legend'];
108
185
  if (type === 'heatmap') return ['grid', 'visualMap'];
109
186
  if (type === 'boxplot' || type === 'candlestick') return ['grid'];
110
- return withMarkLine ? ['grid', 'legend', 'markLine'] : ['grid', 'legend'];
187
+ const base = withMarkLine ? ['grid', 'legend', 'markLine'] : ['grid', 'legend'];
188
+ return [...base, ...extra.filter((c) => !base.includes(c))];
111
189
  }
112
190
 
191
+ /** 配置里用到的引擎标记组件(markLine / markArea / markPoint);键盘焦点带也要 markArea(有读数 / 选中时预装) */
192
+ export function chartMarkComponentsOf(config: KitChartConfig): { markLine: boolean; extra: string[] } {
193
+ const marks = config.marks ?? [];
194
+ const extra: string[] = [];
195
+ if (marks.some((m) => m.kind === 'band')) extra.push('markArea');
196
+ if (marks.some((m) => m.kind === 'point')) extra.push('markPoint');
197
+ return { markLine: (config.refLines?.length ?? 0) > 0 || marks.some((m) => m.kind === 'line'), extra };
198
+ }
199
+
200
+ /** 只有这些图型有「类目轴列」:标记与读数 / 键盘漫游只对它们生效 */
201
+ export const KIT_CHART_COLUMN_TYPES: ReadonlySet<string> = new Set(['line', 'bar', 'area', 'combo']);
202
+
113
203
  /** 系列用色顺序:图表系列令牌 --soma-chart-1 到 --soma-chart-8(token-catalog 内),不写裸色 */
114
204
  export const KIT_CHART_SERIES_TOKENS: readonly string[] = Object.freeze(
115
205
  [1, 2, 3, 4, 5, 6, 7, 8].map((n) => `--soma-chart-${n}`),
@@ -152,9 +242,35 @@ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
152
242
  const x = str(src.x);
153
243
  if (x === '') return null;
154
244
  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 !== '') : [];
245
+ // y 项可以是字段名,也可以是 { field, role? };role 不在闭集(或图型不支持 role)即整份配置非法
246
+ const roles: Record<string, KitChartSeriesRole> = {};
247
+ const kindOf = new Map<string, string>();
248
+ const axisOf = new Map<string, string>();
249
+ let badRole = false;
250
+ const y: string[] = [];
251
+ if (Array.isArray(yRaw)) {
252
+ for (const v of yRaw) {
253
+ if (typeof v === 'string') { if (v !== '') y.push(v); continue; }
254
+ const item = recOf(v);
255
+ const field = str(item.field);
256
+ if (field === '') continue;
257
+ y.push(field);
258
+ // combo 的逐系列声明:kind(bar / line)与 axis(primary / secondary);非闭集的值、非 combo 图型写它们都算非法
259
+ for (const [key, set, bucket] of [['kind', KIT_CHART_SERIES_KINDS, kindOf], ['axis', KIT_CHART_SERIES_AXES, axisOf]] as const) {
260
+ const raw = item[key];
261
+ if (raw === undefined || raw === null || raw === '') continue;
262
+ if (type !== 'combo' || !set.includes(str(raw))) { badRole = true; continue; }
263
+ bucket.set(field, str(raw));
264
+ }
265
+ if (item.role === undefined || item.role === null || item.role === '') continue;
266
+ const role = str(item.role);
267
+ if (!KIT_CHART_SERIES_ROLES.includes(role) || !ROLE_TYPES.has(type)) { badRole = true; continue; }
268
+ roles[field] = role as KitChartSeriesRole;
269
+ }
270
+ } else if (typeof yRaw === 'string') {
271
+ for (const s of yRaw.split(',')) if (s.trim() !== '') y.push(s.trim());
272
+ }
273
+ if (badRole) return null;
158
274
  if (y.length === 0) return null;
159
275
  if (y.length < (MIN_Y[type] ?? 1)) return null;
160
276
  const value = str(src.value);
@@ -166,9 +282,21 @@ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
166
282
  const nameList = (raw: unknown): string[] => (Array.isArray(raw)
167
283
  ? raw.filter((v): v is string => typeof v === 'string' && v !== '')
168
284
  : 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)) : [];
285
+ // 逐系列声明与顶层 line / y2 名单取并集(同一系列两处都写时以逐系列为准)
286
+ const merged = (names: string[], declared: ReadonlyMap<string, string>, on: string): string[] =>
287
+ y.filter((f) => (declared.has(f) ? declared.get(f) === on : names.includes(f)));
288
+ const lineFields = type === 'combo' ? merged(nameList(src.line), kindOf, 'line') : [];
289
+ const y2Fields = type === 'combo' ? merged(nameList(src.y2), axisOf, 'secondary') : [];
171
290
  const refLines = refLinesOf(src.ref_lines);
291
+ // 标记 / 读数 / 选中只对有类目轴列的图型(折线 / 面积 / 柱 / 组合);写在别的图型或值非法 = 配置不完整
292
+ const marks = parseChartMarks(src.marks, MARK_SPEC);
293
+ const readout = parseReadout(src.readout);
294
+ const interactRaw = src.interact;
295
+ const wantsColumns = (marks !== null && marks.length > 0) || (readout !== undefined && readout !== null) || (interactRaw !== undefined && interactRaw !== null);
296
+ if (marks === null || readout === null) return null;
297
+ if (wantsColumns && !KIT_CHART_COLUMN_TYPES.has(type)) return null;
298
+ const interactRec = recOf(interactRaw);
299
+ if (interactRaw !== undefined && interactRaw !== null && (typeof interactRaw !== 'object' || Array.isArray(interactRaw) || Object.keys(interactRec).some((k) => k !== 'pick'))) return null;
172
300
  const legend = KIT_CHART_LEGENDS.includes(str(src.legend)) ? str(src.legend) as KitChartConfig['legend'] : 'auto';
173
301
  const vf = recOf(src.value_format);
174
302
  const prefix = affixOf(vf.prefix);
@@ -177,6 +305,10 @@ export function chartConfigOf(chartRaw: unknown): KitChartConfig | null {
177
305
  ...(lineFields.length > 0 ? { line: lineFields } : {}),
178
306
  ...(y2Fields.length > 0 ? { y2: y2Fields } : {}),
179
307
  ...(refLines.length > 0 ? { refLines } : {}),
308
+ ...(Object.keys(roles).length > 0 ? { roles } : {}),
309
+ ...(marks.length > 0 ? { marks } : {}),
310
+ ...(readout !== undefined ? { readout } : {}),
311
+ ...(interactRaw !== undefined && interactRaw !== null ? { interact: { pick: interactRec.pick === true || interactRec.pick === 'true' } } : {}),
180
312
  ...(legend !== 'auto' ? { legend } : {}),
181
313
  ...(prefix !== '' || suffix !== '' ? { valueFormat: { prefix, suffix } } : {}),
182
314
  type, x, y, stack, min, max, warnAt: num(src.warnAt), dangerAt: num(src.dangerAt),
@@ -239,10 +371,34 @@ export interface KitChartTheme {
239
371
  palette: string[];
240
372
  text: string;
241
373
  line: string;
374
+ /** 理想线色(中性令牌 --soma-text-muted 的运行期值);缺省退回 text */
375
+ ideal?: string;
376
+ /** 主色(标记 primary 语气、焦点带;--soma-c-primary 的运行期值);缺省退回 palette[0] */
377
+ primary?: string;
378
+ /** 预测线系列名后缀(如「(预测)」,来自 kit 文案);缺省不加 */
379
+ projectionSuffix?: string;
242
380
  /** gauge 阈值着色:正常 / 警告 / 危险(取自 --soma-c-success / warning / danger);缺省退回系列色 */
243
381
  ok?: string;
244
382
  warn?: string;
245
383
  danger?: string;
384
+ /** 柱宽 / 类间距的比例(百分数,取 --soma-chart-bar-ratio;强调级越低越细);缺省用引擎默认 */
385
+ barRatioPct?: number;
386
+ }
387
+
388
+ /** 把 #rrggbb 色按 pct% 混入面板面色(pct = 系列色占比);无法解析(非 #rrggbb)时原样返回。强调级低的图表填充更浅,主图表 100 = 实心。 */
389
+ export function mixTowardSurface(color: string, surface: string, pct: number): string {
390
+ const hex = (s: string): [number, number, number] | null => {
391
+ const m = /^#([0-9a-f]{6})$/i.exec(s.trim());
392
+ if (m === null) return null;
393
+ const v = parseInt(m[1]!, 16);
394
+ return [(v >> 16) & 255, (v >> 8) & 255, v & 255];
395
+ };
396
+ const a = hex(color);
397
+ const b = hex(surface);
398
+ if (pct >= 100 || a === null || b === null) return color;
399
+ const k = Math.max(0, pct) / 100;
400
+ const ch = (i: number): string => Math.round(a[i]! * k + b[i]! * (1 - k)).toString(16).padStart(2, '0');
401
+ return `#${ch(0)}${ch(1)}${ch(2)}`;
246
402
  }
247
403
 
248
404
  /** gauge 轴线分段 [[占量程的比例, 颜色], …]:阈值之下 ok,warnAt 起 warn,dangerAt 起 danger;纯函数 */
@@ -272,6 +428,8 @@ export function buildChartOption(
272
428
  rows: ReadonlyArray<Record<string, unknown>>,
273
429
  theme: KitChartTheme,
274
430
  mapRaw?: unknown,
431
+ /** 保留入参(焦点带已取消,见 markAreaOf);不再影响输出 */
432
+ _view: { focus?: number } = {},
275
433
  ): Record<string, unknown> {
276
434
  const map = recOf(mapRaw);
277
435
  const src = (k: string): string => (typeof map[k] === 'string' && map[k] !== '' ? String(map[k]) : k);
@@ -286,25 +444,91 @@ export function buildChartOption(
286
444
  const legendShown = (auto: boolean): boolean => (config.legend === 'none' ? false : config.legend === 'top' || config.legend === 'bottom' ? true : auto);
287
445
  const legendOf = (auto: boolean): Record<string, unknown> | undefined =>
288
446
  (legendShown(auto) ? { ...(config.legend === 'top' ? { top: 0 } : { bottom: 0 }), textStyle: { color: theme.text } } : undefined);
289
- const toneColor = (tone: KitChartRefLine['tone']): string =>
447
+ const toneColor = (tone: KitChartRefLine['tone'] | VizTone): string =>
290
448
  (tone === 'success' ? (theme.ok ?? theme.palette[0] ?? theme.text)
291
449
  : tone === 'warning' ? (theme.warn ?? theme.palette[1] ?? theme.text)
292
450
  : tone === 'danger' ? (theme.danger ?? theme.palette[2] ?? theme.text)
293
- : theme.text);
294
- /** 参考线只挂在第一条系列上(引擎 markLine,虚线,不带 tooltip) */
451
+ : tone === 'primary' ? (theme.primary ?? theme.palette[0] ?? theme.text)
452
+ : tone === 'muted' ? (theme.ideal ?? theme.text)
453
+ : theme.text);
454
+ // 标记几何:声明套到数据行(x 轴 = 列序号);只对有类目轴列的图型
455
+ const resolvedMarks: ResolvedChartMark[] = config.marks !== undefined && KIT_CHART_COLUMN_TYPES.has(config.type)
456
+ ? resolveChartMarks(config.marks, rows, { xKey, seriesKey: src })
457
+ : [];
458
+ const roleOf = (role: string): { color: string; dash: readonly number[] | null; symbol: string } => {
459
+ const style = MARK_SPEC.roles[role]!;
460
+ return { color: toneColor(style.tone), dash: chartMarkDashPattern(style.dash), symbol: style.symbol };
461
+ };
462
+ /** 参考线与标记竖线 / 横线合并成引擎 markLine,只挂在第一条系列上(虚线 / 实线由角色定,不带 tooltip) */
295
463
  const markLineOf = (): Record<string, unknown> => {
296
464
  const refs = config.refLines ?? [];
297
- if (refs.length === 0) return {};
465
+ const lines = resolvedMarks.filter((m) => m.kind === 'line');
466
+ if (refs.length === 0 && lines.length === 0) return {};
298
467
  return {
299
468
  markLine: {
300
469
  silent: true,
301
470
  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
- })),
471
+ data: [
472
+ ...refs.map((r) => ({
473
+ ...(r.value !== undefined ? { yAxis: r.value } : { type: r.stat }),
474
+ name: r.label,
475
+ lineStyle: { type: 'dashed', color: toneColor(r.tone) },
476
+ label: { show: r.label !== '', formatter: r.label, color: toneColor(r.tone) },
477
+ })),
478
+ ...lines.map((m) => {
479
+ const s = roleOf(m.role);
480
+ return {
481
+ ...(m.axis === 'x' ? { xAxis: m.at } : { yAxis: m.at }),
482
+ name: m.label,
483
+ lineStyle: { type: s.dash === null ? 'solid' : [...s.dash], color: s.color, width: CHART_NUM.marks.lineWidth },
484
+ label: { show: m.label !== '', formatter: m.label, color: s.color, position: 'end', rotate: 0 },
485
+ };
486
+ }),
487
+ ],
488
+ },
489
+ };
490
+ };
491
+ /** 区间带(标记 band + 焦点带):x 轴两端各外扩半列,使单列区间也有宽度;挂在第一条系列上 */
492
+ const markAreaOf = (): Record<string, unknown> => {
493
+ const bands = resolvedMarks.filter((m) => m.kind === 'band');
494
+ if (bands.length === 0) return {};
495
+ const data: unknown[] = bands.map((m) => {
496
+ const s = roleOf(m.role);
497
+ // 类目轴坐标被引擎取整(Math.round),±0.5 外扩无效(实测整体右移半列);改为外扩一整列到相邻快照点:
498
+ // 折线在「缺快照」处断开,带 = 断开的区间(上一个有值点 → 下一个有值点),单列区间也有宽度
499
+ 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);
500
+ return [
501
+ {
502
+ ...(m.axis === 'x' ? { xAxis: edge(m.from!, -1) } : { yAxis: m.from }),
503
+ name: m.label,
504
+ itemStyle: { color: s.color, opacity: CHART_NUM.marks.bandOpacity },
505
+ label: { show: m.label !== '', formatter: m.label, color: s.color, position: 'insideBottom' },
506
+ },
507
+ m.axis === 'x' ? { xAxis: edge(m.to!, 1) } : { yAxis: m.to },
508
+ ];
509
+ });
510
+ // 焦点列不再画带:类目轴坐标取整后,带只能落在「焦点 → 下一列」、与悬停的列错开半列;焦点由高亮点 + 读数区表达
511
+ return { markArea: { silent: true, data } };
512
+ };
513
+ /** 标记点:落在对应系列的该列(该系列值为空的列 resolveChartMarks 已跳过) */
514
+ const markPointOf = (seriesName: string): Record<string, unknown> => {
515
+ const points = resolvedMarks.filter((m) => m.kind === 'point' && m.series === seriesName);
516
+ if (points.length === 0) return {};
517
+ return {
518
+ markPoint: {
519
+ silent: true,
520
+ data: points.map((m) => {
521
+ const s = roleOf(m.role);
522
+ const hollow = s.symbol === 'hollow';
523
+ return {
524
+ coord: [m.at, num(rows[m.at!]?.[src(seriesName)])],
525
+ name: m.label,
526
+ symbol: s.symbol === 'diamond' ? 'diamond' : 'circle',
527
+ symbolSize: CHART_NUM.marks.pointSize,
528
+ itemStyle: hollow ? { color: 'transparent', borderColor: s.color, borderWidth: CHART_NUM.marks.lineWidth } : { color: s.color },
529
+ label: { show: m.label !== '', formatter: m.label, color: s.color, position: 'top' },
530
+ };
531
+ }),
308
532
  },
309
533
  };
310
534
  };
@@ -495,21 +719,94 @@ export function buildChartOption(
495
719
  const combo = config.type === 'combo';
496
720
  const lineSet = new Set(config.line ?? []);
497
721
  const y2Set = new Set(config.y2 ?? []);
498
- const series = config.y.map((y, i) => {
722
+ // 理想线排在最后:不占序列配色序号(其它系列的颜色不后移),图例也排最后
723
+ // baseline(范围线 / 容量线等参考性序列)与理想线同属「参考线类」:不占配色序号、中性色、无点;区别只在线型(baseline = 细实线,不与理想线虚线混用)
724
+ const isIdeal = (y: string): boolean => config.roles?.[y] === 'ideal' || config.roles?.[y] === 'baseline';
725
+ const isProjection = (y: string): boolean => config.roles?.[y] === 'projection';
726
+ /** 语义取色角色(ok / caution / overload):画成普通系列但取语气色、排在其它普通系列之后(不占配色序号) */
727
+ const toneOfRole = (y: string): string | null => SERIES_TONE_ROLES[config.roles?.[y] ?? ''] ?? null;
728
+ const basicYs = config.y.filter((y) => !isIdeal(y) && !isProjection(y));
729
+ const plainYs = [...basicYs.filter((y) => toneOfRole(y) === null), ...basicYs.filter((y) => toneOfRole(y) !== null)];
730
+ const idealYs = config.y.filter(isIdeal);
731
+ const projectionYs = config.y.filter(isProjection);
732
+ const projectionName = (y: string): string => `${y}${theme.projectionSuffix ?? ''}`;
733
+ /** 空值(null / undefined / 非数)保持 null:引擎据此断线留白,不补零不插值 */
734
+ const cell = (r: Record<string, unknown>, key: string): number | null => num(r[key]);
735
+ const idealSeries = idealYs.map((y) => {
736
+ const key = src(y);
737
+ const color = theme.ideal ?? theme.text;
738
+ return {
739
+ type: 'line',
740
+ name: y,
741
+ data: rows.map((r) => cell(r, key)),
742
+ connectNulls: false,
743
+ symbol: 'none',
744
+ showSymbol: false,
745
+ color,
746
+ itemStyle: { color },
747
+ lineStyle: referenceLineStyle(config.roles?.[y], color),
748
+ ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
749
+ };
750
+ });
751
+ // 预测线:与第一条普通序列同色相的虚线延伸,不占配色序号(颜色显式指定)、无点、不叠加、断线留白
752
+ const projectionColor = theme.palette[0] ?? theme.text;
753
+ const projectionSeries = projectionYs.map((y) => {
754
+ const key = src(y);
755
+ return {
756
+ type: 'line',
757
+ name: projectionName(y),
758
+ data: rows.map((r) => cell(r, key)),
759
+ connectNulls: false,
760
+ symbol: 'none',
761
+ showSymbol: false,
762
+ color: projectionColor,
763
+ itemStyle: { color: projectionColor },
764
+ lineStyle: { width: CHART_STYLE.idealLineWidth, type: [...CHART_STYLE.projectionDash], color: projectionColor, opacity: CHART_STYLE.projectionOpacity },
765
+ ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
766
+ };
767
+ });
768
+ const series = [...plainYs.map((y, i) => {
499
769
  const key = src(y);
500
770
  // combo:line 里列出的 y 画折线、其余画柱;y2 里列出的挂右轴。柱才叠加(折线叠加没有意义)
501
771
  const seriesType = combo ? (lineSet.has(y) ? 'line' : 'bar') : config.type === 'bar' ? 'bar' : 'line';
502
772
  return {
503
773
  type: seriesType,
504
774
  name: y,
505
- data: rows.map((r) => numeric(r[key])),
775
+ data: rows.map((r) => cell(r, key)),
776
+ ...(seriesType === 'line' ? { connectNulls: false } : {}),
777
+ ...(seriesType === 'bar' && theme.barRatioPct !== undefined ? { barCategoryGap: `${Math.max(0, 100 - theme.barRatioPct)}%` } : {}),
506
778
  ...(seriesType === 'line' ? { lineStyle: { width: CHART_STYLE.lineWidth }, symbolSize: CHART_STYLE.symbolSize } : {}),
507
779
  ...(config.type === 'area' ? { areaStyle: { opacity: CHART_STYLE.areaOpacity } } : {}),
508
780
  ...(config.stack && (!combo || seriesType === 'bar') ? { stack: 'total' } : {}),
509
781
  ...(combo && y2Set.has(y) ? { yAxisIndex: 1 } : {}),
510
- ...(i === 0 ? markLineOf() : {}),
782
+ ...(toneOfRole(y) !== null ? (() => { const c = toneColor(toneOfRole(y) as VizTone); return { color: c, itemStyle: { color: c } }; })() : {}),
783
+ ...(i === 0 ? { ...markLineOf(), ...markAreaOf() } : {}),
784
+ ...markPointOf(y),
511
785
  };
512
- });
786
+ }), ...idealSeries, ...projectionSeries];
787
+ // 有理想 / 预测线时图例逐项给出:虚线项用虚线样例,其余项沿用序列色
788
+ const legend = legendOf(config.y.length > 1);
789
+ const legendWithIdeal = legend !== undefined && (idealYs.length > 0 || projectionYs.length > 0)
790
+ ? {
791
+ ...legend,
792
+ data: [
793
+ ...plainYs.map((name) => ({ name })),
794
+ ...projectionYs.map((name) => ({
795
+ name: projectionName(name),
796
+ itemStyle: { color: projectionColor },
797
+ lineStyle: { type: [...CHART_STYLE.projectionDash], width: CHART_STYLE.idealLineWidth, color: projectionColor },
798
+ })),
799
+ ...idealYs.map((name) => ({
800
+ name,
801
+ // 引擎默认的线型图例样例是「线段 + 圆点」,虚线 / 实线的线型差异画不出来:参考线用 path 图标(referenceLegendIcon)
802
+ // 画各自的线型,lineStyle 仍与图里该序列同一份(referenceLineStyle):理想线 = 虚线,范围 / 容量(baseline)= 细实线
803
+ icon: referenceLegendIcon(config.roles?.[name]),
804
+ itemStyle: { color: theme.ideal ?? theme.text },
805
+ lineStyle: referenceLineStyle(config.roles?.[name], theme.ideal ?? theme.text),
806
+ })),
807
+ ],
808
+ }
809
+ : legend;
513
810
  const valueAxis = (extra: Record<string, unknown> = {}): Record<string, unknown> => ({
514
811
  type: 'value',
515
812
  splitLine: { lineStyle: { color: theme.line, width: CHART_STYLE.gridLineWidth } },
@@ -520,7 +817,7 @@ export function buildChartOption(
520
817
  color: theme.palette,
521
818
  textStyle: { color: theme.text },
522
819
  grid: gridFor(config.y.length > 1),
523
- legend: legendOf(config.y.length > 1),
820
+ legend: legendWithIdeal,
524
821
  xAxis: { type: 'category', data: cats, axisLine: { lineStyle: { color: theme.line, width: CHART_STYLE.gridLineWidth } }, axisLabel: { color: theme.text } },
525
822
  yAxis: combo && y2Set.size > 0
526
823
  ? [valueAxis(), valueAxis({ position: 'right', splitLine: { show: false } })]
@@ -529,15 +826,93 @@ export function buildChartOption(
529
826
  };
530
827
  }
531
828
 
829
+ // ───────── 文字替代:可访问名与读屏数据表(纯函数,WCAG 1.1.1 / 1.4.1) ─────────
830
+
831
+ const CHART_TYPE_TEXT: Readonly<Record<KitChartType, KitTextKey>> = Object.freeze({
832
+ line: 'soma.kit.chart_type_line', bar: 'soma.kit.chart_type_bar', area: 'soma.kit.chart_type_area',
833
+ pie: 'soma.kit.chart_type_pie', donut: 'soma.kit.chart_type_donut', funnel: 'soma.kit.chart_type_funnel',
834
+ gauge: 'soma.kit.chart_type_gauge', scatter: 'soma.kit.chart_type_scatter', combo: 'soma.kit.chart_type_combo',
835
+ radar: 'soma.kit.chart_type_radar', heatmap: 'soma.kit.chart_type_heatmap', boxplot: 'soma.kit.chart_type_boxplot',
836
+ candlestick: 'soma.kit.chart_type_candlestick', sankey: 'soma.kit.chart_type_sankey', treemap: 'soma.kit.chart_type_treemap',
837
+ sunburst: 'soma.kit.chart_type_sunburst', chord: 'soma.kit.chart_type_chord',
838
+ });
839
+
840
+ /** 系列数:直角坐标 / 雷达按 y 字段数,其余图型(扇区、阶段、单值、层级、连线)都是一个系列;箱线 / K 线的 y 是同一系列的五 / 四个统计量 */
841
+ export function chartSeriesCount(config: KitChartConfig): number {
842
+ const multi: ReadonlySet<KitChartType> = new Set<KitChartType>(['line', 'bar', 'area', 'scatter', 'combo', 'radar']);
843
+ return multi.has(config.type) ? Math.max(1, config.y.length) : 1;
844
+ }
845
+
846
+ export interface KitChartAlt {
847
+ /** role=img 的可访问名:标题 + 图型 + 系列数 + 数据点数 */
848
+ label: string;
849
+ /** 数据表:表头(配置里的字段名)+ 至多 altTable.maxRows 行(文字化) */
850
+ columns: string[];
851
+ rows: string[][];
852
+ /** 数据行总数(超出上限时表后附「仅列出前 n 行」) */
853
+ total: number;
854
+ }
855
+
856
+ /** 由图形配置与数据行生成文字替代(纯函数);键名对照 map 与 buildChartOption 一致(配置字段 -> 数据键) */
857
+ export function chartAltOf(
858
+ config: KitChartConfig,
859
+ rows: ReadonlyArray<Record<string, unknown>>,
860
+ mapRaw: unknown,
861
+ title: string,
862
+ at?: Element | string | null,
863
+ ): KitChartAlt {
864
+ const map = recOf(mapRaw);
865
+ const src = (k: string): string => (typeof map[k] === 'string' && map[k] !== '' ? String(map[k]) : k);
866
+ const fields: string[] = [];
867
+ for (const f of [config.x, ...config.y, config.value ?? '', config.parent ?? '']) if (f !== '' && !fields.includes(f)) fields.push(f);
868
+ const shown = config.type === 'gauge' ? rows.slice(0, 1) : rows;
869
+ const cap = CHART_NUM.altTable.maxRows;
870
+ const cell = (v: unknown): string => (v === undefined || v === null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v));
871
+ const type = kitText(CHART_TYPE_TEXT[config.type], undefined, at);
872
+ const params = { type, series: chartSeriesCount(config), points: shown.length };
873
+ const label = title !== ''
874
+ ? kitText('soma.kit.chart_alt', { ...params, title }, at)
875
+ : kitText('soma.kit.chart_alt_untitled', params, at);
876
+ // 标注列:命中该行的标记文本(颜色之外必有文字,读屏据此知道今日 / 缺口 / 里程碑)
877
+ const noteByRow = new Map<number, string[]>();
878
+ if (config.marks !== undefined && KIT_CHART_COLUMN_TYPES.has(config.type)) {
879
+ for (const m of resolveChartMarks(config.marks, shown, { xKey: src(config.x), seriesKey: src })) {
880
+ if (m.label === '') continue;
881
+ const lo = m.kind === 'band' ? m.from! : m.at;
882
+ const hi = m.kind === 'band' ? m.to! : m.at;
883
+ if (m.axis !== 'x' || lo === undefined || hi === undefined) continue;
884
+ for (let i = lo; i <= hi; i += 1) noteByRow.set(i, [...(noteByRow.get(i) ?? []), m.label]);
885
+ }
886
+ }
887
+ const withNotes = noteByRow.size > 0;
888
+ return {
889
+ label,
890
+ // 理想线 / 预测线的表头标注;空值(null / 缺值)单元格为空串
891
+ columns: [
892
+ ...fields.map((f) => (config.roles?.[f] === 'ideal' ? kitText('soma.kit.chart_ideal', { name: f }, at)
893
+ : config.roles?.[f] === 'projection' ? kitText('soma.kit.chart_projection', { name: f }, at) : f)),
894
+ ...(withNotes ? [kitText('soma.kit.chart_marks_col', undefined, at)] : []),
895
+ ],
896
+ rows: shown.slice(0, cap).map((r, i) => [...fields.map((f) => cell(r[src(f)])), ...(withNotes ? [(noteByRow.get(i) ?? []).join('、')] : [])]),
897
+ total: shown.length,
898
+ };
899
+ }
900
+
532
901
  // ───────── 组件 ─────────
533
902
 
903
+ /** 引擎实例里本组件用到的成员;onColumn / highlight / onPointer 是可选能力(旧适配器缺它们时读数只对有图元的列生效) */
904
+ interface ChartInstanceLike {
905
+ setOption(option: Record<string, unknown>, mode?: 'merge' | 'replace'): void;
906
+ resize(): void;
907
+ dispose(): void;
908
+ highlight?(p: { seriesIndex: number; dataIndex: number } | null): void;
909
+ onColumn?(handler: (kind: 'hover' | 'click' | 'leave', col: { dataIndex: number } | null) => void): () => void;
910
+ onPointer?(handler: (kind: 'hover' | 'click' | 'leave', p: { dataIndex: number } | null) => void): () => void;
911
+ }
912
+
534
913
  interface ChartEnginePort {
535
914
  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
- }>;
915
+ create(host: HTMLElement, init: { theme: Record<string, unknown>; locale?: string }): Promise<ChartInstanceLike>;
541
916
  }
542
917
 
543
918
  /** 把 --soma-* 令牌解析成运行期颜色值:直接读宿主的计算样式,源码不出现裸色值,也不写内联样式 */
@@ -546,11 +921,29 @@ function resolveToken(host: HTMLElement, token: string): string {
546
921
  return value === '' ? `var(${token})` : value;
547
922
  }
548
923
 
924
+ /** 令牌里的百分数(`55%` / `55`)→ 数;读不到 null */
925
+ function pctToken(host: HTMLElement, token: string): number | null {
926
+ const raw = typeof getComputedStyle === 'function' ? getComputedStyle(host).getPropertyValue(token).trim() : '';
927
+ const n = Number.parseFloat(raw);
928
+ return Number.isFinite(n) ? n : null;
929
+ }
930
+
549
931
  function themeOf(host: HTMLElement): KitChartTheme {
932
+ // 图表填充重量(强调级作用域重写 --soma-chart-fill-mix / --soma-chart-bar-ratio):首绘读一次(data-kit-emphasis 是编译期常量,运行期不变)
933
+ const fillMix = pctToken(host, '--soma-chart-fill-mix');
934
+ const barRatio = pctToken(host, '--soma-chart-bar-ratio');
935
+ const surface = resolveToken(host, '--soma-surface-panel');
550
936
  return {
551
- palette: KIT_CHART_SERIES_TOKENS.map((n) => resolveToken(host, n)),
937
+ palette: KIT_CHART_SERIES_TOKENS.map((n) => {
938
+ const c = resolveToken(host, n);
939
+ return fillMix === null ? c : mixTowardSurface(c, surface, fillMix);
940
+ }),
941
+ ...(barRatio !== null ? { barRatioPct: barRatio } : {}),
552
942
  text: resolveToken(host, '--soma-text-secondary'),
553
943
  line: resolveToken(host, '--soma-border-hairline'),
944
+ ideal: resolveToken(host, '--soma-text-muted'),
945
+ primary: resolveToken(host, '--soma-c-primary'),
946
+ projectionSuffix: kitText('soma.kit.chart_projection', { name: '' }, host),
554
947
  ok: resolveToken(host, '--soma-c-success'),
555
948
  warn: resolveToken(host, '--soma-c-warning'),
556
949
  danger: resolveToken(host, '--soma-c-danger'),
@@ -564,18 +957,28 @@ export function createChart(): SomaComponentDefinition {
564
957
  layer: 'data',
565
958
  props: {
566
959
  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 父名称(空 = 根)' },
960
+ 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(语义取色)' },
568
961
  map: { type: 'object', default: {}, desc: '键名对照:chart 里的字段名 -> 数据里的键' },
569
962
  empty: { type: 'string', default: '', desc: '无数据时的空态文案;缺省取内置文案(按页面语言)' },
963
+ title: { type: 'string', default: '', desc: '图表标题:进可访问名(role=img)与读屏数据表标题;缺省只用「图型 + 系列数 + 数据点数」' },
964
+ aria_label: { type: 'string', default: '', desc: '直接指定图的可访问名(覆盖自动生成的)' },
965
+ ...KIT_READ_STATE_PROP_DEFS,
570
966
  locale: { type: 'string', default: '', desc: '图表语言;空则不传' },
571
967
  class: { type: 'string', default: '', desc: '外部传入的类,追加在根节点类串末尾' },
572
968
  },
573
- emits: {},
969
+ emits: {
970
+ ...KIT_READ_STATE_EMIT_DEFS,
971
+ point_pick: {
972
+ payload: { index: { type: 'number' }, x: { type: 'string' }, row: { type: 'object' } },
973
+ desc: 'chart.interact.pick 为真时,点击 / Enter 选中某一列:index 列序号、x 类目值、row 该列的源数据行;去向由展示对象按 row 的业务字段决定,kit 不判断',
974
+ },
975
+ },
574
976
  },
575
977
  services: ['engines'],
576
978
  templateHtml:
577
979
  `<div data-soma-id="root" class="${ROOT_CLASS}">`
578
980
  + `<div data-soma-id="stageWrap" class="hidden"><div data-soma-id="stage" class="${STAGE_CLASS}"></div></div>`
981
+ + '<div data-soma-id="altWrap" class="sr-only"></div>'
579
982
  + `<div data-soma-id="emptyWrap"><div data-soma-id="emptyText" class="${EMPTY_INNER_CLASS}"></div></div>`
580
983
  + '</div>',
581
984
  controllerFactory: createKitController((api) => {
@@ -585,11 +988,60 @@ export function createChart(): SomaComponentDefinition {
585
988
  let stage: HTMLElement | null = null;
586
989
  let emptyWrap: HTMLElement | null = null;
587
990
  let emptyText: HTMLElement | null = null;
588
- let instance: { setOption(o: Record<string, unknown>, m?: 'merge' | 'replace'): void; resize(): void; dispose(): void } | null = null;
991
+ let altWrap: HTMLElement | null = null;
992
+ let instance: ChartInstanceLike | null = null;
993
+ // 交互状态(K2 / K3):读数区 DOM、当前列、键盘漫游标记、最近一次出图的上下文(焦点带重建 option 用)
994
+ let readoutEl: HTMLElement | null = null;
995
+ let liveEl: HTMLElement | null = null;
996
+ let activeCol = -1;
997
+ let defaultCol = -1;
998
+ let kbdActive = false;
999
+ let offColumn: (() => void) | null = null;
1000
+ let drawn: { config: KitChartConfig; rows: Array<Record<string, unknown>>; theme: KitChartTheme; map: unknown; reduceMotion: boolean } | null = null;
589
1001
  let creating: Promise<void> | null = null;
590
1002
  let resizeObs: ResizeObserver | null = null;
591
1003
  let seq = 0;
592
1004
  let alive = false;
1005
+ // 引擎就绪前的占位:引擎动态加载,首次出图晚于页面其余部分。就绪前舞台保留尺寸但不可见(invisible,不跳动),
1006
+ // 沿用 kit 的加载反馈时序(loading-gate:延迟 200ms 才出加载面板、出现后至少显示 400ms),面板与舞台同尺寸叠在同一位置;
1007
+ // 出图后在根上标 data-kit-chart-ready(截图 / 渲染测量据此判断图已就绪,不靠固定等待)。
1008
+ let engineGate: KitLoadingGate | null = null;
1009
+ let settled = false;
1010
+ let revealed = false;
1011
+ const reveal = (): void => {
1012
+ revealed = true;
1013
+ engineGate = null;
1014
+ // 只收起加载占位;数据旁的错误提示条(keepStage 的 error 面板)保留
1015
+ if (emptyText?.getAttribute('data-kit-state') === 'loading' || emptyText?.getAttribute('data-kit-state') === null) {
1016
+ emptyWrap?.classList.remove('absolute', 'inset-0');
1017
+ emptyWrap?.classList.add('hidden');
1018
+ }
1019
+ stageWrap?.classList.remove('invisible');
1020
+ root?.setAttribute(KIT_CHART_READY_ATTR, '');
1021
+ };
1022
+ const beginEngineWait = (): void => {
1023
+ if (revealed || engineGate !== null) return;
1024
+ settled = false;
1025
+ stageWrap?.classList.add('invisible');
1026
+ engineGate = createLoadingGate((phase) => {
1027
+ if (!alive) return;
1028
+ if (phase === 'visible' && !revealed) {
1029
+ showPanel('loading', str(P().loading_text, kitText('soma.kit.loading', undefined, root ?? undefined)), {}, true);
1030
+ emptyWrap?.classList.add('absolute', 'inset-0');
1031
+ } else if (phase === 'idle' && settled) reveal();
1032
+ });
1033
+ engineGate.start();
1034
+ };
1035
+ const endEngineWait = (): void => {
1036
+ if (engineGate === null) return;
1037
+ settled = true;
1038
+ engineGate.finish();
1039
+ };
1040
+ const abortEngineWait = (): void => {
1041
+ settled = false;
1042
+ engineGate?.cancel();
1043
+ engineGate = null;
1044
+ };
593
1045
 
594
1046
  // 深浅色切换:系列色取自运行期计算值,主题变了要重算并 setOption。
595
1047
  // 两个来源——系统偏好 prefers-color-scheme,以及 <html> 上 soma-scheme-dark / soma-scheme-light 类的变化
@@ -633,11 +1085,65 @@ export function createChart(): SomaComponentDefinition {
633
1085
  const find = (id: string): HTMLElement | null =>
634
1086
  root?.querySelector<HTMLElement>(`[data-soma-scoped-id="${id}"]`) ?? root?.querySelector<HTMLElement>(`[data-soma-id="${id}"]`) ?? null;
635
1087
 
636
- const showEmpty = (text: string): void => {
1088
+ // 空 / 加载 / 错误都画进同一个面板位(与集合三态同一画法:base/state-panel.ts);keepStage = 图保留、面板作提示条
1089
+ const showPanel = (kind: KitStateKind, text: string, o: Partial<KitStatePanelOptions> = {}, keepStage = false): void => {
637
1090
  if (!stageWrap || !emptyWrap || !emptyText) return;
638
- stageWrap.classList.add('hidden');
1091
+ emptyWrap.classList.remove('absolute', 'inset-0');
1092
+ if (keepStage) stageWrap.classList.remove('hidden'); else { stageWrap.classList.add('hidden'); clearAlt(); }
639
1093
  emptyWrap.classList.remove('hidden');
640
- emptyText.textContent = text;
1094
+ paintKitStatePanel(emptyText, kind, { ...o, text });
1095
+ };
1096
+ // 文字替代:只在真有图(舞台可见)时给舞台 role=img + 可访问名,并在旁边放读屏数据表;
1097
+ // 空 / 加载 / 错误 / 降级面板没有图,不带 role=img。role=img 会把子孙当装饰,所以数据表是舞台的兄弟而不是子孙。
1098
+ const clearAlt = (): void => {
1099
+ stageWrap?.removeAttribute('role');
1100
+ stageWrap?.removeAttribute('aria-label');
1101
+ if (altWrap) altWrap.textContent = '';
1102
+ drawn = null;
1103
+ resetInteractive();
1104
+ };
1105
+ const setAlt = (alt: KitChartAlt, title: string, override: string): void => {
1106
+ if (!stageWrap) return;
1107
+ stageWrap.setAttribute('role', 'img');
1108
+ stageWrap.setAttribute('aria-label', override !== '' ? override : alt.label);
1109
+ if (!altWrap) return;
1110
+ const doc = altWrap.ownerDocument;
1111
+ altWrap.textContent = '';
1112
+ const table = doc.createElement('table');
1113
+ const caption = doc.createElement('caption');
1114
+ caption.textContent = override !== '' ? override : title !== '' ? title : alt.label;
1115
+ table.appendChild(caption);
1116
+ const head = doc.createElement('tr');
1117
+ for (const col of alt.columns) {
1118
+ const th = doc.createElement('th');
1119
+ th.setAttribute('scope', 'col');
1120
+ th.textContent = col;
1121
+ head.appendChild(th);
1122
+ }
1123
+ const thead = doc.createElement('thead');
1124
+ thead.appendChild(head);
1125
+ table.appendChild(thead);
1126
+ const tbody = doc.createElement('tbody');
1127
+ for (const r of alt.rows) {
1128
+ const tr = doc.createElement('tr');
1129
+ r.forEach((value, i) => {
1130
+ const td = doc.createElement(i === 0 ? 'th' : 'td');
1131
+ if (i === 0) td.setAttribute('scope', 'row');
1132
+ td.textContent = value;
1133
+ tr.appendChild(td);
1134
+ });
1135
+ tbody.appendChild(tr);
1136
+ }
1137
+ table.appendChild(tbody);
1138
+ altWrap.appendChild(table);
1139
+ if (alt.total > alt.rows.length) {
1140
+ const more = doc.createElement('p');
1141
+ more.textContent = kitText('soma.kit.chart_table_more', { n: alt.rows.length, total: alt.total }, altWrap);
1142
+ altWrap.appendChild(more);
1143
+ }
1144
+ };
1145
+ const showEmpty = (text: string): void => {
1146
+ showPanel('empty', text);
641
1147
  };
642
1148
  const showStage = (): void => {
643
1149
  if (!stageWrap || !emptyWrap) return;
@@ -645,6 +1151,153 @@ export function createChart(): SomaComponentDefinition {
645
1151
  stageWrap.classList.remove('hidden');
646
1152
  };
647
1153
 
1154
+ // ── 逐列读数与列选中(K2 / K3):读数区由 kit 自己渲染,不用引擎 tooltip;指针经端口 onColumn(缺则回落 onPointer)、键盘经根上的 keydown ──
1155
+ const interactiveOf = (c: KitChartConfig | undefined): boolean => c !== undefined && (c.readout !== undefined || c.interact !== undefined);
1156
+ const cellText = (row: Record<string, unknown> | undefined, field: string, map: unknown): string => {
1157
+ const m = recOf(map);
1158
+ const key = typeof m[field] === 'string' && m[field] !== '' ? String(m[field]) : field;
1159
+ const v = row?.[key];
1160
+ return v === undefined || v === null ? '' : String(v);
1161
+ };
1162
+ /** 读数内容(标题 + 各项「名 值」+ 附注):值取行字段不重算,空值「—」 */
1163
+ const readoutParts = (col: number): { title: string; items: Array<{ label: string; value: string }>; note: string } | null => {
1164
+ const d = drawn;
1165
+ const ro = d?.config.readout;
1166
+ if (!d || !ro || col < 0 || col >= d.rows.length) return null;
1167
+ const row = d.rows[col];
1168
+ const m = recOf(d.map);
1169
+ const empty = kitText('soma.kit.chart_readout_empty', undefined, root ?? undefined);
1170
+ return {
1171
+ title: ro.title !== '' ? cellText(row, ro.title, m).slice(0, CHART_NUM.readout.titleMax) : cellText(row, d.config.x, m),
1172
+ items: ro.items.map((it) => {
1173
+ const key = typeof m[it.field] === 'string' && m[it.field] !== '' ? String(m[it.field]) : it.field;
1174
+ return { label: it.label, value: formatReadoutValue(row?.[key], it.format, it.unit, empty) };
1175
+ }),
1176
+ note: ro.note !== '' ? cellText(row, ro.note, m).slice(0, CHART_NUM.readout.noteMax) : '',
1177
+ };
1178
+ };
1179
+ const paintReadout = (col: number): void => {
1180
+ if (!readoutEl) return;
1181
+ const parts = readoutParts(col);
1182
+ readoutEl.textContent = '';
1183
+ if (parts === null) { readoutEl.classList.add('hidden'); return; }
1184
+ readoutEl.classList.remove('hidden');
1185
+ const doc = readoutEl.ownerDocument;
1186
+ const add = (cls: string, text: string, parent: HTMLElement = readoutEl!): HTMLElement => {
1187
+ const span = doc.createElement('span');
1188
+ span.className = cls;
1189
+ span.textContent = text;
1190
+ parent.appendChild(span);
1191
+ return span;
1192
+ };
1193
+ if (parts.title !== '') add(READOUT_TITLE_CLASS, parts.title);
1194
+ for (const it of parts.items) {
1195
+ const wrap = add(READOUT_ITEM_CLASS, '');
1196
+ add('', it.label, wrap);
1197
+ add(READOUT_VALUE_CLASS, it.value, wrap);
1198
+ }
1199
+ if (parts.note !== '') add(READOUT_NOTE_CLASS, parts.note);
1200
+ };
1201
+ /** 焦点带:整份 option 带上焦点列重建(动画关;默认列不画带) */
1202
+ const announce = (col: number, picked: boolean): void => {
1203
+ if (!liveEl) return;
1204
+ const parts = readoutParts(col);
1205
+ const title = parts?.title ?? String(col + 1);
1206
+ liveEl.textContent = picked
1207
+ ? kitText('soma.kit.chart_picked', { title }, root ?? undefined)
1208
+ : parts === null ? title : kitText('soma.kit.chart_column_summary', { title, items: parts.items.map((i) => `${i.label} ${i.value}`).join(',') }, root ?? undefined);
1209
+ };
1210
+ const setColumn = (col: number, source: 'pointer' | 'key' | 'default'): void => {
1211
+ if (col === activeCol && source !== 'key') return;
1212
+ activeCol = col;
1213
+ paintReadout(col);
1214
+ // 焦点列的视觉由 highlight(高亮点)+ 读数区承担,不画焦点带(见 markAreaOf 注释)
1215
+ if (source === 'default') { instance?.highlight?.(null); return; }
1216
+ if (col >= 0) instance?.highlight?.({ seriesIndex: 0, dataIndex: col });
1217
+ // 读屏只在键盘移动时播报,悬停不播报
1218
+ if (source === 'key' && col >= 0) announce(col, false);
1219
+ };
1220
+ const pick = (col: number): void => {
1221
+ const d = drawn;
1222
+ if (!d || d.config.interact?.pick !== true || col < 0 || col >= d.rows.length) return;
1223
+ const row = d.rows[col]!;
1224
+ const m = recOf(d.map);
1225
+ const xKey = typeof m[d.config.x] === 'string' && m[d.config.x] !== '' ? String(m[d.config.x]) : d.config.x;
1226
+ api.emit('point_pick', { index: col, x: row[xKey] === undefined || row[xKey] === null ? '' : String(row[xKey]), row });
1227
+ announce(col, true);
1228
+ };
1229
+ const onColumnEvent = (kind: 'hover' | 'click' | 'leave', col: { dataIndex: number } | null): void => {
1230
+ if (!interactiveOf(drawn?.config)) return;
1231
+ if (kind === 'click') { if (col) pick(col.dataIndex); return; }
1232
+ if (kbdActive) return;
1233
+ if (kind === 'hover' && col) setColumn(col.dataIndex, 'pointer');
1234
+ else if (kind === 'leave') setColumn(defaultCol, 'default');
1235
+ };
1236
+ const bindColumns = (inst: ChartInstanceLike): void => {
1237
+ offColumn?.();
1238
+ offColumn = inst.onColumn !== undefined
1239
+ ? inst.onColumn(onColumnEvent)
1240
+ : inst.onPointer !== undefined ? inst.onPointer(onColumnEvent) : null;
1241
+ };
1242
+ const onKeyDown = (event: KeyboardEvent): void => {
1243
+ const d = drawn;
1244
+ if (!d || !interactiveOf(d.config)) return;
1245
+ if (event.key === 'Enter' || event.key === ' ') {
1246
+ if (d.config.interact?.pick === true && activeCol >= 0) { event.preventDefault(); pick(activeCol); }
1247
+ return;
1248
+ }
1249
+ if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
1250
+ event.preventDefault();
1251
+ kbdActive = true;
1252
+ const next = stepChartColumn(activeCol, d.rows.length, event.key);
1253
+ if (next >= 0) setColumn(next, 'key');
1254
+ };
1255
+ const onFocusIn = (): void => {
1256
+ // 只有键盘获得焦点才进入键盘漫游(鼠标点击聚焦不抢走悬停驱动)
1257
+ let visible = true;
1258
+ try { visible = root?.matches(':focus-visible') ?? true; } catch { visible = true; }
1259
+ kbdActive = visible;
1260
+ };
1261
+ const onFocusOut = (): void => {
1262
+ if (!kbdActive) return;
1263
+ kbdActive = false;
1264
+ setColumn(defaultCol, 'default');
1265
+ };
1266
+ /** 按本次出图的配置同步交互壳:根的焦点属性、读数区位置与默认列 */
1267
+ const syncInteractive = (config: KitChartConfig, rows: Array<Record<string, unknown>>, label: string): void => {
1268
+ if (!root || !stageWrap) return;
1269
+ if (!interactiveOf(config)) { resetInteractive(); return; }
1270
+ root.setAttribute('tabindex', '0');
1271
+ root.setAttribute('role', 'group');
1272
+ root.setAttribute('aria-roledescription', kitText('soma.kit.chart_roledesc', undefined, root));
1273
+ root.setAttribute('aria-label', label);
1274
+ root.className = joinClass(root.className, ROOT_FOCUS_CLASS);
1275
+ if (readoutEl) {
1276
+ const top = config.readout?.place === 'top';
1277
+ readoutEl.className = `${READOUT_CLASS} ${top ? READOUT_TOP_CLASS : READOUT_BOTTOM_CLASS}`;
1278
+ readoutEl.setAttribute('aria-hidden', 'true');
1279
+ // data-kit-chart-readout:渲染判定 chart.readout.hover 的稳定选择器
1280
+ readoutEl.setAttribute('data-kit-chart-readout', '');
1281
+ if (top) root.insertBefore(readoutEl, stageWrap); else stageWrap.after(readoutEl);
1282
+ }
1283
+ if (liveEl && !liveEl.isConnected) root.appendChild(liveEl);
1284
+ const fields = (config.readout?.items.map((i) => i.field) ?? config.y).map((f) => {
1285
+ const m = recOf(drawn?.map);
1286
+ return typeof m[f] === 'string' && m[f] !== '' ? String(m[f]) : f;
1287
+ });
1288
+ defaultCol = defaultReadoutColumn(rows, fields, config.readout?.defaultMode ?? 'none');
1289
+ if (kbdActive && activeCol >= 0 && activeCol < rows.length) paintReadout(activeCol);
1290
+ else { activeCol = -2; setColumn(defaultCol, 'default'); }
1291
+ };
1292
+ const resetInteractive = (): void => {
1293
+ for (const a of ['tabindex', 'role', 'aria-roledescription', 'aria-label']) root?.removeAttribute(a);
1294
+ readoutEl?.classList.add('hidden');
1295
+ if (readoutEl) readoutEl.textContent = '';
1296
+ if (liveEl) liveEl.textContent = '';
1297
+ activeCol = -1;
1298
+ defaultCol = -1;
1299
+ };
1300
+
648
1301
  const portOf = (): ChartEnginePort | null => {
649
1302
  const engines = (api.services as { engines?: { chart?: ChartEnginePort } } | undefined)?.engines;
650
1303
  return engines?.chart ?? null;
@@ -655,25 +1308,44 @@ export function createChart(): SomaComponentDefinition {
655
1308
  const mine = ++seq;
656
1309
  const p = P();
657
1310
  root.className = joinClass(ROOT_CLASS, p.class);
1311
+ altWrap ??= find('altWrap');
658
1312
  const rows = (Array.isArray(p.data) ? p.data : []).filter((r): r is Record<string, unknown> => r !== null && typeof r === 'object');
659
1313
  const config = chartConfigOf(p.chart);
660
- if (config === null) { showEmpty(kitText('soma.kit.chart_incomplete', undefined, root)); return; }
1314
+ // 读状态(有读接口时编译器自动绑 loading / error_text):没有数据时读取失败 / 读取中不再冒充「暂无数据」;有数据时错误作提示条、读取中保留图
1315
+ const errorText = str(p.error_text);
1316
+ const retryLabel = str(p.retry_text);
1317
+ const retry = retryLabel !== '' ? (): void => { api.emit('retry', {}); } : null;
1318
+ const loading = p.loading === true || p.loading === 'true';
1319
+ if (rows.length === 0 && errorText !== '') { showPanel('error', errorText, { retry, retryLabel }); return; }
1320
+ if (rows.length === 0 && loading) { showPanel('loading', str(p.loading_text, kitText('soma.kit.loading', undefined, root))); return; }
1321
+ // 配置 / 引擎问题是页面或环境的错,不是「没数据」:按错误态画(无重试)
1322
+ if (config === null) { showPanel('error', kitText('soma.kit.chart_incomplete', undefined, root)); return; }
661
1323
  if (rows.length === 0) { showEmpty(str(p.empty, kitText('soma.kit.empty', undefined, root))); return; }
662
1324
  const port = portOf();
663
- if (port === null) { showEmpty(kitText('soma.kit.chart_no_engine', undefined, root)); return; }
1325
+ if (port === null) { showPanel('error', kitText('soma.kit.chart_no_engine', undefined, root)); return; }
664
1326
  try {
665
1327
  showStage();
1328
+ if (instance === null) beginEngineWait();
1329
+ if (errorText !== '') showPanel('error', errorText, { retry, retryLabel }, true);
666
1330
  const theme = themeOf(root);
667
- const option = buildChartOption(config, rows, theme, p.map);
1331
+ // 减少动效偏好:关掉引擎的入场 / 更新动画(端口不透出 aria / decal 初始化项,系列区分靠图例 + 数据表)
1332
+ const reduceMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
1333
+ const option = { ...buildChartOption(config, rows, theme, p.map), ...(reduceMotion ? { animation: false } : {}) };
1334
+ const alt = chartAltOf(config, rows, p.map, str(p.title), root);
1335
+ setAlt(alt, str(p.title), str(p.aria_label));
1336
+ drawn = { config, rows, theme, map: p.map, reduceMotion };
1337
+ syncInteractive(config, rows, str(p.aria_label) !== '' ? str(p.aria_label) : alt.label);
1338
+ const marked = chartMarkComponentsOf(config);
668
1339
  if (instance === null) {
669
1340
  if (creating === null) {
670
1341
  creating = (async () => {
671
1342
  try {
672
- await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, (config.refLines?.length ?? 0) > 0));
1343
+ await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, marked.markLine, marked.extra));
673
1344
  const locale = str(p.locale);
674
1345
  const created = await port.create(stage!, { theme: { color: theme.palette }, ...(locale !== '' ? { locale } : {}) });
675
1346
  if (!alive) { created.dispose(); return; }
676
1347
  instance = created;
1348
+ bindColumns(created);
677
1349
  if (typeof ResizeObserver === 'function') {
678
1350
  resizeObs = new ResizeObserver(() => instance?.resize());
679
1351
  resizeObs.observe(stage!);
@@ -692,12 +1364,14 @@ export function createChart(): SomaComponentDefinition {
692
1364
  }
693
1365
  // 异步期间又有新一轮 paint 或已卸载:交给最新一轮
694
1366
  if (!alive || mine !== seq || instance === null) return;
695
- await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, (config.refLines?.length ?? 0) > 0));
1367
+ await port.ensure(engineSeriesListOf(config.type), engineComponentsOf(config.type, marked.markLine, marked.extra));
696
1368
  if (!alive || mine !== seq) return;
697
1369
  instance.setOption(option, 'replace');
1370
+ endEngineWait();
698
1371
  } catch {
699
1372
  creating = null;
700
- if (alive && mine === seq) showEmpty(kitText('soma.kit.chart_unavailable', undefined, root));
1373
+ abortEngineWait();
1374
+ if (alive && mine === seq) showPanel('error', kitText('soma.kit.chart_unavailable', undefined, root));
701
1375
  }
702
1376
  };
703
1377
 
@@ -709,9 +1383,32 @@ export function createChart(): SomaComponentDefinition {
709
1383
  stage = find('stage');
710
1384
  emptyWrap = find('emptyWrap');
711
1385
  emptyText = find('emptyText');
1386
+ altWrap = find('altWrap');
712
1387
  watchScheme();
1388
+ // 读数区(视觉)与读屏播报区(仅键盘驱动更新):由 kit 自己渲染,位置在 paint 里按 readout.place 摆
1389
+ readoutEl = rootEl.ownerDocument.createElement('div');
1390
+ readoutEl.className = 'hidden';
1391
+ liveEl = rootEl.ownerDocument.createElement('div');
1392
+ liveEl.className = 'sr-only';
1393
+ liveEl.setAttribute('role', 'status');
1394
+ liveEl.setAttribute('aria-live', 'polite');
1395
+ liveEl.setAttribute('aria-atomic', 'true');
1396
+ rootEl.addEventListener('keydown', onKeyDown);
1397
+ rootEl.addEventListener('focusin', onFocusIn);
1398
+ rootEl.addEventListener('focusout', onFocusOut);
713
1399
  return () => {
714
1400
  alive = false;
1401
+ rootEl.removeEventListener('keydown', onKeyDown);
1402
+ rootEl.removeEventListener('focusin', onFocusIn);
1403
+ rootEl.removeEventListener('focusout', onFocusOut);
1404
+ offColumn?.();
1405
+ offColumn = null;
1406
+ readoutEl?.remove();
1407
+ liveEl?.remove();
1408
+ readoutEl = null;
1409
+ liveEl = null;
1410
+ drawn = null;
1411
+ abortEngineWait();
715
1412
  unwatchScheme();
716
1413
  resizeObs?.disconnect();
717
1414
  resizeObs = null;
@@ -722,6 +1419,7 @@ export function createChart(): SomaComponentDefinition {
722
1419
  stage = null;
723
1420
  emptyWrap = null;
724
1421
  emptyText = null;
1422
+ altWrap = null;
725
1423
  };
726
1424
  },
727
1425
  async render(rootEl) {