@squadbase/vantage 0.6.2-stg.3a2ba98 → 0.7.0-dev1.1197de7

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 (357) hide show
  1. package/dist/add-4GHF2TX2.js +6 -0
  2. package/dist/add-4GHF2TX2.js.map +1 -0
  3. package/dist/{build-O5TVNH4E.js → build-U7GO26HR.js} +9 -9
  4. package/dist/{build-O5TVNH4E.js.map → build-U7GO26HR.js.map} +1 -1
  5. package/dist/{check-WFBEDHDR.js → check-MRVAIHG5.js} +7 -7
  6. package/dist/{check-WFBEDHDR.js.map → check-MRVAIHG5.js.map} +1 -1
  7. package/dist/{chunk-QDZA5JSL.js → chunk-AABMKHEU.js} +4 -4
  8. package/dist/{chunk-QDZA5JSL.js.map → chunk-AABMKHEU.js.map} +1 -1
  9. package/dist/{chunk-PVTHHV7X.js → chunk-ANZLVSEP.js} +28 -7
  10. package/dist/chunk-ANZLVSEP.js.map +1 -0
  11. package/dist/chunk-CKWPK4RO.js +50 -0
  12. package/dist/chunk-CKWPK4RO.js.map +1 -0
  13. package/dist/chunk-EG4PX726.js +678 -0
  14. package/dist/chunk-EG4PX726.js.map +1 -0
  15. package/dist/{chunk-3G43C6OL.js → chunk-GNXCX4WE.js} +46 -3
  16. package/dist/chunk-GNXCX4WE.js.map +1 -0
  17. package/dist/chunk-LYUGDHSF.js +61 -0
  18. package/dist/chunk-LYUGDHSF.js.map +1 -0
  19. package/dist/{chunk-RPZAALCX.js → chunk-MQUIAP66.js} +321 -165
  20. package/dist/chunk-MQUIAP66.js.map +1 -0
  21. package/dist/chunk-P2KIHF65.js +152 -0
  22. package/dist/chunk-P2KIHF65.js.map +1 -0
  23. package/dist/{chunk-BCE22JSM.js → chunk-PJ4SPXHS.js} +52 -16
  24. package/dist/chunk-PJ4SPXHS.js.map +1 -0
  25. package/dist/{chunk-ZVANIULZ.js → chunk-RNTDBX6S.js} +4 -4
  26. package/dist/{chunk-ZVANIULZ.js.map → chunk-RNTDBX6S.js.map} +1 -1
  27. package/dist/{chunk-PXRX5PEC.js → chunk-ROHNXP7J.js} +73 -4
  28. package/dist/chunk-ROHNXP7J.js.map +1 -0
  29. package/dist/chunk-S5MDTHH7.js +466 -0
  30. package/dist/chunk-S5MDTHH7.js.map +1 -0
  31. package/dist/chunk-SDJTTMLK.js +1877 -0
  32. package/dist/chunk-SDJTTMLK.js.map +1 -0
  33. package/dist/{chunk-EP6JHXSR.js → chunk-SHZM3EXB.js} +68 -12
  34. package/dist/chunk-SHZM3EXB.js.map +1 -0
  35. package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
  36. package/dist/chunk-U736PVHY.js.map +1 -0
  37. package/dist/{chunk-JGRMRXXZ.js → chunk-UWSQUHX6.js} +4 -99
  38. package/dist/chunk-UWSQUHX6.js.map +1 -0
  39. package/dist/chunk-XRKSIC5Z.js +176 -0
  40. package/dist/chunk-XRKSIC5Z.js.map +1 -0
  41. package/dist/chunk-YJQCB3UP.js +10764 -0
  42. package/dist/chunk-YJQCB3UP.js.map +1 -0
  43. package/dist/cli.js +15 -11
  44. package/dist/cli.js.map +1 -1
  45. package/dist/client/index.d.ts +34 -3
  46. package/dist/client/index.js +211 -12
  47. package/dist/client/index.js.map +1 -1
  48. package/dist/components/index.d.ts +2389 -31
  49. package/dist/components/index.js +7 -4
  50. package/dist/delta-text-tav2Lh5d.d.ts +17 -0
  51. package/dist/{dev-NZRLOQCL.js → dev-O42JFQ64.js} +24 -13
  52. package/dist/dev-O42JFQ64.js.map +1 -0
  53. package/dist/doc/index.d.ts +215 -2
  54. package/dist/doc/index.js +423 -5
  55. package/dist/doc/index.js.map +1 -1
  56. package/dist/{docs-ZGDJUHJI.js → docs-JVP4RPKT.js} +3 -3
  57. package/dist/{docs-ZGDJUHJI.js.map → docs-JVP4RPKT.js.map} +1 -1
  58. package/dist/{doctor-VFKEMR54.js → doctor-YD3XAAOT.js} +8 -8
  59. package/dist/doctor-YD3XAAOT.js.map +1 -0
  60. package/dist/format-D34piCei.d.ts +250 -0
  61. package/dist/geo-japan-7BMSOJRX.js +8 -0
  62. package/dist/geo-japan-7BMSOJRX.js.map +1 -0
  63. package/dist/geo-us-GVOG7VXH.js +8 -0
  64. package/dist/geo-us-GVOG7VXH.js.map +1 -0
  65. package/dist/geo-world-35HL56UU.js +8 -0
  66. package/dist/geo-world-35HL56UU.js.map +1 -0
  67. package/dist/markdown/index.js +1 -1
  68. package/dist/markdown/index.js.map +1 -1
  69. package/dist/{preview-QDCIVVSR.js → preview-T6CLSQVX.js} +12 -4
  70. package/dist/preview-T6CLSQVX.js.map +1 -0
  71. package/dist/query/index.d.ts +0 -11
  72. package/dist/query/index.js +2 -2
  73. package/dist/{routes-RHP5FVGD.js → routes-PVKNT777.js} +6 -6
  74. package/dist/{routes-RHP5FVGD.js.map → routes-PVKNT777.js.map} +1 -1
  75. package/dist/{search-RFBELGY7.js → search-5LC4XPB5.js} +3 -3
  76. package/dist/{search-RFBELGY7.js.map → search-5LC4XPB5.js.map} +1 -1
  77. package/dist/slide/index.d.ts +272 -1
  78. package/dist/slide/index.js +1086 -19
  79. package/dist/slide/index.js.map +1 -1
  80. package/dist/table/index.js +13 -10
  81. package/dist/table/index.js.map +1 -1
  82. package/dist/ui/index.d.ts +148 -12
  83. package/dist/ui/index.js +1339 -88
  84. package/dist/ui/index.js.map +1 -1
  85. package/dist/{upgrade-GF2P67M6.js → upgrade-6DT7ADRP.js} +7 -7
  86. package/dist/{upgrade-GF2P67M6.js.map → upgrade-6DT7ADRP.js.map} +1 -1
  87. package/dist/vite/index.d.ts +10 -0
  88. package/dist/vite/index.js +4 -4
  89. package/docs/en/agent-skills.md +1 -1
  90. package/docs/en/changelog.md +82 -0
  91. package/docs/en/cli-reference.md +30 -0
  92. package/docs/en/components.md +42 -17
  93. package/docs/en/doc/delta-text.md +40 -0
  94. package/docs/en/doc/doc-action-items.md +49 -0
  95. package/docs/en/doc/doc-callout.md +38 -0
  96. package/docs/en/doc/doc-data-table.md +60 -0
  97. package/docs/en/doc/doc-executive-summary.md +64 -0
  98. package/docs/en/doc/doc-figure.md +56 -0
  99. package/docs/en/doc/doc-key-findings.md +61 -0
  100. package/docs/en/doc/doc-kpi-scorecard.md +80 -0
  101. package/docs/en/doc/doc-notes-and-sources.md +43 -0
  102. package/docs/en/doc/doc-report-header.md +46 -0
  103. package/docs/en/pages-and-metadata.md +15 -0
  104. package/docs/en/parts/area-chart.md +99 -0
  105. package/docs/en/parts/bar-chart.md +91 -0
  106. package/docs/en/parts/bar-list.md +50 -0
  107. package/docs/en/parts/category-bar.md +37 -0
  108. package/docs/en/parts/chart-frame.md +39 -0
  109. package/docs/en/parts/data-table.md +22 -0
  110. package/docs/en/parts/delta.md +51 -0
  111. package/docs/en/parts/donut-chart.md +72 -0
  112. package/docs/en/parts/draft-chart.md +42 -0
  113. package/docs/en/parts/format.md +43 -0
  114. package/docs/en/parts/funnel-steps.md +2 -1
  115. package/docs/en/parts/heatmap.md +53 -0
  116. package/docs/en/parts/kpi-card.md +58 -0
  117. package/docs/en/parts/legend.md +35 -0
  118. package/docs/en/parts/line-chart.md +94 -0
  119. package/docs/en/parts/metric-value.md +3 -2
  120. package/docs/en/parts/page-shell.md +2 -2
  121. package/docs/en/parts/progress-circle.md +33 -0
  122. package/docs/en/parts/sample-data.md +39 -0
  123. package/docs/en/parts/scatter-chart.md +56 -0
  124. package/docs/en/parts/sparkline.md +1 -1
  125. package/docs/en/parts/tracker.md +36 -0
  126. package/docs/en/parts/trend-indicator.md +17 -1
  127. package/docs/en/parts/updated-at.md +30 -0
  128. package/docs/en/parts/waterfall-chart.md +56 -0
  129. package/docs/en/slide/slide-chart-full.md +48 -0
  130. package/docs/en/slide/slide-chart-insight.md +52 -0
  131. package/docs/en/slide/slide-columns.md +46 -0
  132. package/docs/en/slide/slide-comparison.md +68 -0
  133. package/docs/en/slide/slide-cover.md +39 -0
  134. package/docs/en/slide/slide-exec-summary.md +47 -0
  135. package/docs/en/slide/slide-heading.md +38 -0
  136. package/docs/en/slide/slide-kpi-grid.md +55 -0
  137. package/docs/en/slide/slide-kpi-hero.md +58 -0
  138. package/docs/en/slide/slide-next-actions.md +49 -0
  139. package/docs/en/slide/slide-scorecard-table.md +54 -0
  140. package/docs/en/slide/slide-section.md +44 -0
  141. package/docs/en/slide/slide-source-line.md +34 -0
  142. package/docs/en/ui/alert-dialog.md +42 -0
  143. package/docs/en/ui/avatar.md +31 -0
  144. package/docs/en/ui/combobox.md +74 -0
  145. package/docs/en/ui/drawer.md +41 -0
  146. package/docs/en/ui/empty.md +1 -1
  147. package/docs/en/ui/error-state.md +4 -3
  148. package/docs/en/ui/field.md +42 -0
  149. package/docs/en/ui/hover-card.md +21 -0
  150. package/docs/en/ui/kbd.md +17 -0
  151. package/docs/en/ui/loading.md +1 -1
  152. package/docs/en/ui/pagination.md +36 -0
  153. package/docs/en/ui/radio-group.md +21 -0
  154. package/docs/en/ui/toast.md +44 -0
  155. package/docs/en/ui/toggle-group.md +4 -3
  156. package/docs/en/ui-and-theming.md +1 -1
  157. package/docs/index.json +1222 -132
  158. package/docs/ja/agent-skills.md +1 -1
  159. package/docs/ja/changelog.md +84 -0
  160. package/docs/ja/cli-reference.md +29 -0
  161. package/docs/ja/components.md +68 -101
  162. package/docs/ja/doc/delta-text.md +40 -0
  163. package/docs/ja/doc/doc-action-items.md +49 -0
  164. package/docs/ja/doc/doc-callout.md +38 -0
  165. package/docs/ja/doc/doc-data-table.md +60 -0
  166. package/docs/ja/doc/doc-executive-summary.md +64 -0
  167. package/docs/ja/doc/doc-figure.md +56 -0
  168. package/docs/ja/doc/doc-key-findings.md +61 -0
  169. package/docs/ja/doc/doc-kpi-scorecard.md +80 -0
  170. package/docs/ja/doc/doc-notes-and-sources.md +43 -0
  171. package/docs/ja/doc/doc-report-header.md +46 -0
  172. package/docs/ja/page-types/csv.md +83 -0
  173. package/docs/ja/page-types/doc.md +83 -0
  174. package/docs/ja/page-types/excel.md +82 -0
  175. package/docs/ja/page-types/slide.md +133 -0
  176. package/docs/ja/page-types.md +47 -0
  177. package/docs/ja/pages-and-metadata.md +15 -0
  178. package/docs/ja/parts/area-chart.md +85 -0
  179. package/docs/ja/parts/bar-chart.md +95 -0
  180. package/docs/ja/parts/bar-list.md +58 -0
  181. package/docs/ja/parts/category-bar.md +36 -0
  182. package/docs/ja/parts/chart-frame.md +36 -0
  183. package/docs/ja/parts/data-table.md +22 -0
  184. package/docs/ja/parts/delta.md +51 -0
  185. package/docs/ja/parts/donut-chart.md +66 -0
  186. package/docs/ja/parts/draft-chart.md +40 -0
  187. package/docs/ja/parts/echart.md +3 -0
  188. package/docs/ja/parts/format.md +44 -0
  189. package/docs/ja/parts/funnel-steps.md +27 -8
  190. package/docs/ja/parts/heatmap.md +45 -0
  191. package/docs/ja/parts/kpi-card.md +56 -0
  192. package/docs/ja/parts/legend.md +36 -0
  193. package/docs/ja/parts/line-chart.md +84 -0
  194. package/docs/ja/parts/metric-value.md +3 -2
  195. package/docs/ja/parts/page-shell.md +2 -2
  196. package/docs/ja/parts/progress-circle.md +34 -0
  197. package/docs/ja/parts/sample-data.md +61 -0
  198. package/docs/ja/parts/scatter-chart.md +69 -0
  199. package/docs/ja/parts/sparkline.md +2 -2
  200. package/docs/ja/parts/tracker.md +32 -0
  201. package/docs/ja/parts/trend-indicator.md +17 -1
  202. package/docs/ja/parts/updated-at.md +27 -0
  203. package/docs/ja/parts/waterfall-chart.md +61 -0
  204. package/docs/ja/routing.md +8 -86
  205. package/docs/ja/slide/slide-chart-full.md +48 -0
  206. package/docs/ja/slide/slide-chart-insight.md +52 -0
  207. package/docs/ja/slide/slide-columns.md +46 -0
  208. package/docs/ja/slide/slide-comparison.md +68 -0
  209. package/docs/ja/slide/slide-cover.md +39 -0
  210. package/docs/ja/slide/slide-exec-summary.md +47 -0
  211. package/docs/ja/slide/slide-heading.md +38 -0
  212. package/docs/ja/slide/slide-kpi-grid.md +55 -0
  213. package/docs/ja/slide/slide-kpi-hero.md +58 -0
  214. package/docs/ja/slide/slide-next-actions.md +49 -0
  215. package/docs/ja/slide/slide-scorecard-table.md +54 -0
  216. package/docs/ja/slide/slide-section.md +44 -0
  217. package/docs/ja/slide/slide-source-line.md +34 -0
  218. package/docs/ja/ui/alert-dialog.md +41 -0
  219. package/docs/ja/ui/avatar.md +31 -0
  220. package/docs/ja/ui/combobox.md +74 -0
  221. package/docs/ja/ui/drawer.md +41 -0
  222. package/docs/ja/ui/empty.md +1 -1
  223. package/docs/ja/ui/error-state.md +4 -3
  224. package/docs/ja/ui/field.md +42 -0
  225. package/docs/ja/ui/hover-card.md +21 -0
  226. package/docs/ja/ui/kbd.md +16 -0
  227. package/docs/ja/ui/loading.md +1 -1
  228. package/docs/ja/ui/pagination.md +36 -0
  229. package/docs/ja/ui/radio-group.md +21 -0
  230. package/docs/ja/ui/toast.md +46 -0
  231. package/docs/ja/ui/toggle-group.md +4 -3
  232. package/docs/ja/ui-and-theming.md +14 -7
  233. package/package.json +43 -29
  234. package/registry/parts.json +5221 -0
  235. package/registry/ui/accordion.tsx +76 -0
  236. package/registry/ui/alert-dialog.tsx +189 -0
  237. package/registry/ui/alert.tsx +80 -0
  238. package/registry/ui/app-shell.tsx +424 -0
  239. package/registry/ui/area-chart.tsx +3960 -0
  240. package/registry/ui/attention-list.tsx +465 -0
  241. package/registry/ui/avatar.tsx +110 -0
  242. package/registry/ui/badge.tsx +56 -0
  243. package/registry/ui/bar-chart.tsx +3954 -0
  244. package/registry/ui/bar-list.tsx +3998 -0
  245. package/registry/ui/box-plot-chart.tsx +4214 -0
  246. package/registry/ui/breadcrumb.tsx +128 -0
  247. package/registry/ui/button.tsx +62 -0
  248. package/registry/ui/calendar.tsx +223 -0
  249. package/registry/ui/card.tsx +107 -0
  250. package/registry/ui/category-bar.tsx +1498 -0
  251. package/registry/ui/chart-frame.tsx +1612 -0
  252. package/registry/ui/checkbox.tsx +30 -0
  253. package/registry/ui/collapsible.tsx +23 -0
  254. package/registry/ui/combo-chart.tsx +1852 -0
  255. package/registry/ui/combobox.tsx +310 -0
  256. package/registry/ui/command.tsx +198 -0
  257. package/registry/ui/dashboard-card.tsx +219 -0
  258. package/registry/ui/data-table.tsx +899 -158
  259. package/registry/ui/date-range-picker.tsx +544 -0
  260. package/registry/ui/delta.tsx +352 -0
  261. package/registry/ui/dialog.tsx +161 -0
  262. package/registry/ui/donut-chart.tsx +4006 -0
  263. package/registry/ui/drawer.tsx +229 -0
  264. package/registry/ui/dropdown-menu.tsx +274 -0
  265. package/registry/ui/echart.tsx +1178 -0
  266. package/registry/ui/field.tsx +240 -0
  267. package/registry/ui/filter-bar.tsx +553 -0
  268. package/registry/ui/forecast-chart.tsx +4734 -0
  269. package/registry/ui/funnel-steps.tsx +3843 -0
  270. package/registry/ui/heatmap.tsx +2027 -0
  271. package/registry/ui/histogram-chart.tsx +4284 -0
  272. package/registry/ui/hover-card.tsx +52 -0
  273. package/registry/ui/input-group.tsx +160 -0
  274. package/registry/ui/input.tsx +24 -0
  275. package/registry/ui/kbd.tsx +30 -0
  276. package/registry/ui/kpi-card.tsx +907 -0
  277. package/registry/ui/label.tsx +22 -0
  278. package/registry/ui/legend.tsx +3817 -0
  279. package/registry/ui/line-chart.tsx +3958 -0
  280. package/registry/ui/metric-value.tsx +62 -0
  281. package/registry/ui/multi-select.tsx +382 -0
  282. package/registry/ui/page-shell.tsx +441 -0
  283. package/registry/ui/pagination.tsx +140 -0
  284. package/registry/ui/paired-chart.tsx +4086 -0
  285. package/registry/ui/pivot-table.tsx +1260 -0
  286. package/registry/ui/placeholder.tsx +36 -0
  287. package/registry/ui/popover.tsx +92 -0
  288. package/registry/ui/progress-circle.tsx +1033 -0
  289. package/registry/ui/progress.tsx +85 -0
  290. package/registry/ui/radio-group.tsx +39 -0
  291. package/registry/ui/sample-data.tsx +230 -0
  292. package/registry/ui/scatter-chart.tsx +4503 -0
  293. package/registry/ui/scroll-area.tsx +56 -0
  294. package/registry/ui/searchable-select.tsx +352 -0
  295. package/registry/ui/section-header.tsx +43 -0
  296. package/registry/ui/segmented-control.tsx +76 -0
  297. package/registry/ui/select.tsx +255 -0
  298. package/registry/ui/separator.tsx +27 -0
  299. package/registry/ui/sheet.tsx +139 -0
  300. package/registry/ui/sidebar.tsx +725 -0
  301. package/registry/ui/skeleton.tsx +17 -0
  302. package/registry/ui/slider.tsx +56 -0
  303. package/registry/ui/sparkline.tsx +230 -0
  304. package/registry/ui/spinner.tsx +14 -0
  305. package/registry/ui/states.tsx +247 -0
  306. package/registry/ui/status-badge.tsx +286 -0
  307. package/registry/ui/switch.tsx +34 -0
  308. package/registry/ui/table.tsx +118 -0
  309. package/registry/ui/tabs.tsx +84 -0
  310. package/registry/ui/textarea.tsx +22 -0
  311. package/registry/ui/toast.tsx +250 -0
  312. package/registry/ui/toggle-group.tsx +91 -0
  313. package/registry/ui/toggle.tsx +47 -0
  314. package/registry/ui/tooltip.tsx +72 -0
  315. package/registry/ui/tracker.tsx +1015 -0
  316. package/registry/ui/treemap.tsx +1917 -0
  317. package/registry/ui/trend-indicator.tsx +217 -0
  318. package/registry/ui/updated-at.tsx +276 -0
  319. package/registry/ui/waterfall-chart.tsx +4561 -0
  320. package/skills/vantage-add-feature/SKILL.md +14 -7
  321. package/skills/vantage-design/SKILL.md +62 -52
  322. package/skills/vantage-design/references/extract.md +26 -27
  323. package/skills/vantage-design/references/format.md +12 -172
  324. package/skills/vantage-design/references/presets.md +50 -110
  325. package/skills/vantage-pitfalls/SKILL.md +10 -1
  326. package/skills/vantage-slide/SKILL.md +71 -36
  327. package/templates/AGENTS.md +54 -16
  328. package/templates/agents/api.md +36 -0
  329. package/templates/agents/csv.md +2 -1
  330. package/templates/agents/doc.md +52 -3
  331. package/templates/agents/page.md +91 -10
  332. package/templates/agents/slide.md +90 -4
  333. package/templates/agents/xlsx.md +2 -1
  334. package/theme.css +247 -132
  335. package/dist/add-EISGSZAH.js +0 -6
  336. package/dist/add-EISGSZAH.js.map +0 -1
  337. package/dist/chunk-3G43C6OL.js.map +0 -1
  338. package/dist/chunk-5ZOP4SQR.js +0 -47
  339. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  340. package/dist/chunk-A2UUGASH.js.map +0 -1
  341. package/dist/chunk-BCE22JSM.js.map +0 -1
  342. package/dist/chunk-DTDVSFRY.js +0 -29
  343. package/dist/chunk-DTDVSFRY.js.map +0 -1
  344. package/dist/chunk-EP6JHXSR.js.map +0 -1
  345. package/dist/chunk-JGRMRXXZ.js.map +0 -1
  346. package/dist/chunk-KLEIVDUV.js +0 -165
  347. package/dist/chunk-KLEIVDUV.js.map +0 -1
  348. package/dist/chunk-LSRMRIXA.js +0 -2227
  349. package/dist/chunk-LSRMRIXA.js.map +0 -1
  350. package/dist/chunk-PVTHHV7X.js.map +0 -1
  351. package/dist/chunk-PXRX5PEC.js.map +0 -1
  352. package/dist/chunk-RPZAALCX.js.map +0 -1
  353. package/dist/chunk-T3FLAGI6.js +0 -316
  354. package/dist/chunk-T3FLAGI6.js.map +0 -1
  355. package/dist/dev-NZRLOQCL.js.map +0 -1
  356. package/dist/doctor-VFKEMR54.js.map +0 -1
  357. package/dist/preview-QDCIVVSR.js.map +0 -1
@@ -0,0 +1,4561 @@
1
+ // Copied by `vantage add ui waterfall-chart`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/charts/waterfall-chart.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * WaterfallChart — a typed waterfall chart over `EChart`: pass the steps as rows,
7
+ * the name key (`index`) and the amount key (`categories: [valueKey]`) instead of
8
+ * an ECharts option. 売上 → 原価 → 粗利 の内訳、前期からの増減要因。
9
+ *
10
+ * Each row is a step that moves the running total by its value; rows named in
11
+ * `totals` are totals — a bar from 0 to the running total (or to their own value
12
+ * when they carry one). The bars are a stacked bar chart over a transparent base,
13
+ * so the value axis always starts at 0. Increase / decrease bars use the
14
+ * area tokens (`--positive-fill` / `--negative-fill`, swapped by `polarity`), totals are
15
+ * `--chart-1`; every step also prints its signed amount (+ / -), so the colour is
16
+ * never the only carrier of the direction. Missing values (null) draw no bar and read「—」.
17
+ * `mode="delta"` draws only the moves: the axis is the cumulative change from 0 (the start),
18
+ * totals are not bars (their numbers go in a note above the plot), so a small change against
19
+ * a large total is not a hairline on a tall axis; the axis still starts at 0 and can go negative.
20
+ * A closing「純増」bar (the net change, `--chart-1`, signed) is appended in `delta`. Value-axis ticks carry no "+" in
21
+ * both modes; the sign is on the bar labels only.
22
+ * Renders inside `ChartFrame` (title, summary, loading skeleton, empty state, and
23
+ * a visually-hidden table of the steps).
24
+ */
25
+ import { forwardRef, useMemo, type ForwardedRef, type ReactElement, type Ref } from "react"
26
+ import { use } from "echarts/core"
27
+ import { GraphicComponent } from "echarts/components"
28
+ import type { EChartsOption } from "echarts"
29
+
30
+ import { ChartFrame } from "@squadbase/vantage/components"
31
+ import { EChart } from "@squadbase/vantage/components"
32
+ import type { Polarity } from "@squadbase/vantage/components"
33
+ import { EMPTY_VALUE, MINUS_SIGN } from "@squadbase/vantage/components"
34
+ import type { ChartCommonProps, NumericKeys, ValueFormatter } from "@squadbase/vantage/components"
35
+ import { useSyncExternalStore } from "react"
36
+ import { createContext, useCallback, useEffect, useRef, useState, type RefObject } from "react"
37
+ import type { ChartTone } from "@squadbase/vantage/components"
38
+ import { type ReactNode } from "react"
39
+ import { computeComparison, defaultChangeDisplay, formatChange, toneForValue, type ComparisonKind, type PeriodGrain } from "@squadbase/vantage/components"
40
+ import { DEFAULT_LOCALE, type ValueFormat } from "@squadbase/vantage/components"
41
+ import type { ChartThreshold, ChartAnnotation, ChartEventPayload, ChartForecast, ChartForecastRow, ChartHighlight } from "@squadbase/vantage/components"
42
+ import { formatValue, toValueFormatter } from "@squadbase/vantage/components"
43
+ import type { ChartColor, ChartColors, ChartSeriesColor } from "@squadbase/vantage/components"
44
+
45
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
46
+
47
+ /**
48
+ * The display language of the parts and the defaults that follow it.
49
+ *
50
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
51
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
52
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
53
+ *
54
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
55
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
56
+ */
57
+
58
+ /** The language of the built-in wording: Japanese or English. */
59
+ type UiLanguage = "ja" | "en"
60
+
61
+ /** The locale used when `<html lang>` gives none (and on the server). */
62
+ const FALLBACK_LOCALE = "en-US"
63
+
64
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
65
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
66
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
67
+ }
68
+
69
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
70
+ function normalizeLocale(tag: string | null | undefined): string {
71
+ const value = tag?.trim()
72
+ if (!value) return FALLBACK_LOCALE
73
+ try {
74
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
75
+ } catch {
76
+ return FALLBACK_LOCALE
77
+ }
78
+ }
79
+
80
+ /**
81
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
82
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
83
+ */
84
+ function documentLocale(): string {
85
+ if (typeof document === "undefined") return FALLBACK_LOCALE
86
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
87
+ }
88
+
89
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
90
+ function resolveLocale(locale?: string | null): string {
91
+ return locale || documentLocale()
92
+ }
93
+
94
+ /** Picks the wording table of the locale's language. */
95
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
96
+ return table[uiLanguage(resolveLocale(locale))]
97
+ }
98
+
99
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
100
+ function defaultCurrency(locale?: string | null): string {
101
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
102
+ }
103
+
104
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
105
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
106
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
107
+ }
108
+
109
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
110
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
111
+
112
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
113
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
114
+
115
+ /**
116
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
117
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
118
+ * Monday for the rest.
119
+ */
120
+ function weekStartsOn(locale?: string | null): WeekDay {
121
+ const tag = normalizeLocale(resolveLocale(locale))
122
+ if (uiLanguage(tag) === "ja") return 1
123
+ try {
124
+ const info = new Intl.Locale(tag) as Intl.Locale & {
125
+ getWeekInfo?: () => { firstDay: number }
126
+ weekInfo?: { firstDay: number }
127
+ }
128
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
129
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
130
+ } catch {
131
+ // Fall through to the table below.
132
+ }
133
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
134
+ }
135
+
136
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
137
+
138
+ const listeners = new Set<() => void>()
139
+ let observer: MutationObserver | null = null
140
+
141
+ /** One observer on `<html lang>` for every subscribed part. */
142
+ function subscribe(onChange: () => void): () => void {
143
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
144
+ listeners.add(onChange)
145
+ if (!observer) {
146
+ observer = new MutationObserver(() => {
147
+ for (const listener of [...listeners]) listener()
148
+ })
149
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
150
+ }
151
+ return () => {
152
+ listeners.delete(onChange)
153
+ if (listeners.size === 0 && observer) {
154
+ observer.disconnect()
155
+ observer = null
156
+ }
157
+ }
158
+ }
159
+
160
+ const serverLocale = () => FALLBACK_LOCALE
161
+
162
+ /**
163
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
164
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
165
+ */
166
+ function useDocumentLocale(): string {
167
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
168
+ }
169
+
170
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
171
+ function useLocale(locale?: string | null): string {
172
+ const page = useDocumentLocale()
173
+ return locale || page
174
+ }
175
+
176
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
177
+
178
+ /**
179
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
180
+ * grey is defined — every chart takes it from here. It is the most subdued
181
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
182
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
183
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
184
+ * slice. Canvas charts resolve it through `resolveChartColors`.
185
+ */
186
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
187
+
188
+ /**
189
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
190
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
191
+ */
192
+ const ChartFrameContext = createContext(false)
193
+
194
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
195
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
196
+
197
+ interface ChartTokens {
198
+ /** Resolved `--chart-1..5`, in order. */
199
+ series: string[]
200
+ /** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
201
+ fontFamily?: string
202
+ /** Body text: titles and the default `textStyle`. */
203
+ foreground: string | null
204
+ /** Secondary text: axis labels, legend, subtitles. */
205
+ mutedForeground: string | null
206
+ /** Axis lines, ticks, split lines, tooltip border. */
207
+ border: string | null
208
+ /** Tooltip surface. */
209
+ popover: string | null
210
+ /** Semantic and surface dependencies used by typed chart options. Optional for hand-built tokens. */
211
+ colors?: Record<string, string>
212
+ /** Actual inherited painting surface (may change without a token changing). */
213
+ surface?: string | null
214
+ /** Tooltip text. */
215
+ popoverForeground: string | null
216
+ }
217
+
218
+ // Keep scope out of the public token shape. A resolved snapshot remembers where arbitrary
219
+ // var(--token) expressions must be read, without retaining unmounted charts globally.
220
+ const tokenScopes = new WeakMap<ChartTokens, Element>()
221
+ const OPTION_COLOR_TOKENS = [
222
+ "--background", "--card", "--muted", "--primary", "--destructive",
223
+ ...["positive", "negative", "warning", "neutral", "info"].flatMap((tone) =>
224
+ ["", "-fill", "-subtle"].map((suffix) => `--${tone}${suffix}`)),
225
+ ]
226
+
227
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
228
+
229
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
230
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
231
+
232
+ /**
233
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
234
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
235
+ * input is written over two different known colours: agreeing results mean the
236
+ * value parsed, differing ones mean it was dropped.
237
+ */
238
+ function toCanvasColor(value: string): string | null {
239
+ const raw = value.trim()
240
+ if (!raw) return null
241
+ if (normalizeContext === undefined) {
242
+ const canvas = document.createElement("canvas")
243
+ canvas.width = 1
244
+ canvas.height = 1
245
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
246
+ }
247
+ const ctx = normalizeContext
248
+ if (!ctx) return raw
249
+ ctx.fillStyle = "#000000"
250
+ ctx.fillStyle = raw
251
+ const onBlack = ctx.fillStyle
252
+ ctx.fillStyle = "#ffffff"
253
+ ctx.fillStyle = raw
254
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
255
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
256
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
257
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
258
+ ctx.clearRect(0, 0, 1, 1)
259
+ ctx.fillRect(0, 0, 1, 1)
260
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
261
+ return a === 255
262
+ ? `rgb(${r}, ${g}, ${b})`
263
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
264
+ }
265
+
266
+ /**
267
+ * Read the chart tokens off `el` (the document root by default — tokens live on
268
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
269
+ * to plain ECharts defaults.
270
+ */
271
+ function readChartTokens(el?: Element | null): ChartTokens | null {
272
+ if (typeof document === "undefined") return null
273
+ const target = el ?? document.documentElement
274
+ if (!target) return null
275
+ const styles = getComputedStyle(target)
276
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
277
+ const series: string[] = []
278
+ for (const token of SERIES_TOKENS) {
279
+ const color = read(token)
280
+ if (color) series.push(color)
281
+ }
282
+ const tokens: ChartTokens = {
283
+ series,
284
+ colors: Object.fromEntries(OPTION_COLOR_TOKENS.map((name) => [name, styles.getPropertyValue(name).trim()])),
285
+ surface: readChartSurface(target),
286
+ ...(styles.fontFamily ? { fontFamily: styles.fontFamily } : {}),
287
+ foreground: read("--foreground"),
288
+ mutedForeground: read("--muted-foreground"),
289
+ border: read("--border"),
290
+ popover: read("--popover"),
291
+ popoverForeground: read("--popover-foreground"),
292
+ }
293
+ tokenScopes.set(tokens, target)
294
+ return tokens
295
+ }
296
+
297
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
298
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
299
+ if (a === b) return true
300
+ if (!a || !b) return false
301
+ return (
302
+ tokenScopes.get(a) === tokenScopes.get(b) &&
303
+ a.surface === b.surface &&
304
+ Object.keys(a.colors ?? {}).length === Object.keys(b.colors ?? {}).length &&
305
+ Object.entries(a.colors ?? {}).every(([name, value]) => b.colors?.[name] === value) &&
306
+ a.series.length === b.series.length &&
307
+ a.series.every((color, i) => color === b.series[i]) &&
308
+ a.fontFamily === b.fontFamily &&
309
+ a.foreground === b.foreground &&
310
+ a.mutedForeground === b.mutedForeground &&
311
+ a.border === b.border &&
312
+ a.popover === b.popover &&
313
+ a.popoverForeground === b.popoverForeground
314
+ )
315
+ }
316
+
317
+ /**
318
+ * Watch everything that can change the resolved tokens and call `onChange` when
319
+ * something might have. It only ever says "re-read" — the caller compares with
320
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
321
+ * disposer.
322
+ *
323
+ * Two sources, not one:
324
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
325
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
326
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
327
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
328
+ * attributes alone leaves the chart painted in the previous palette until a
329
+ * reload — the tokens in the DOM are new, the canvas is not.
330
+ */
331
+ function watchChartTokens(onChange: () => void, scope?: Element | null): () => void {
332
+ if (typeof document === "undefined") return () => {}
333
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
334
+ // take it after the next frame so a swapped stylesheet has been applied.
335
+ let frame = 0
336
+ const schedule = () => {
337
+ if (frame) return
338
+ frame = requestAnimationFrame(() => {
339
+ frame = 0
340
+ onChange()
341
+ })
342
+ }
343
+
344
+ const themeObserver = new MutationObserver(schedule)
345
+ const attributeFilter = ["class", "style", "data-theme"]
346
+ // Only the chart and its ancestors can change its inherited theme. Never observe
347
+ // the document subtree: canvas/tooltip/rendering mutations would trigger every chart.
348
+ for (let node: Element | null = scope ?? document.body ?? document.documentElement; node; node = node.parentElement) {
349
+ themeObserver.observe(node, { attributes: true, attributeFilter })
350
+ }
351
+
352
+ const styleObserver = new MutationObserver(schedule)
353
+ if (document.head) {
354
+ styleObserver.observe(document.head, {
355
+ childList: true,
356
+ subtree: true,
357
+ characterData: true,
358
+ attributes: true,
359
+ attributeFilter: ["href", "media", "disabled"],
360
+ })
361
+ }
362
+
363
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
364
+ const onLoad = (event: Event) => {
365
+ if (event.target instanceof HTMLLinkElement) schedule()
366
+ }
367
+ document.addEventListener("load", onLoad, true)
368
+
369
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
370
+ media.addEventListener("change", schedule)
371
+
372
+ return () => {
373
+ if (frame) cancelAnimationFrame(frame)
374
+ themeObserver.disconnect()
375
+ styleObserver.disconnect()
376
+ document.removeEventListener("load", onLoad, true)
377
+ media.removeEventListener("change", schedule)
378
+ }
379
+ }
380
+
381
+ /** Shared shape for the four axis types ECharts themes address separately. */
382
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
383
+ const line = tokens.border ?? undefined
384
+ return {
385
+ axisLine: { show: false },
386
+ axisTick: { show: false },
387
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
388
+ // Faint horizontal rules only: the border colour at low opacity.
389
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
390
+ splitArea: { show: false },
391
+ }
392
+ }
393
+
394
+ /**
395
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
396
+ * app that sets its own palette keeps it.
397
+ */
398
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
399
+ const text = tokens.foreground ?? undefined
400
+ const muted = tokens.mutedForeground ?? undefined
401
+ const line = tokens.border ?? undefined
402
+ return {
403
+ // Let the page background show through: charts sit on cards, not on a canvas.
404
+ backgroundColor: "transparent",
405
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
406
+ textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
407
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
408
+ legend: { textStyle: { color: muted } },
409
+ categoryAxis: axisTheme(tokens, false),
410
+ valueAxis: axisTheme(tokens, true),
411
+ logAxis: axisTheme(tokens, true),
412
+ timeAxis: axisTheme(tokens, true),
413
+ tooltip: {
414
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
415
+ transitionDuration: 0,
416
+ backgroundColor: tokens.popover ?? undefined,
417
+ borderColor: line,
418
+ borderWidth: 1,
419
+ padding: [8, 12],
420
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
421
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
422
+ textStyle: {
423
+ color: tokens.popoverForeground ?? undefined,
424
+ fontSize: 12,
425
+ ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}),
426
+ },
427
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
428
+ },
429
+ }
430
+ }
431
+
432
+ /**
433
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
434
+ * they may have moved, and only replaced when a value actually changed. For
435
+ * components that build an ECharts option from token colours themselves (the
436
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
437
+ */
438
+ function useChartTokens(scope?: Element | null | RefObject<Element | null>): ChartTokens | null {
439
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
440
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
441
+ // replayed by React on every rebase and returns a fresh object each time, so the state
442
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
443
+ const tokensRef = useRef(tokens)
444
+ useEffect(() => {
445
+ const target = scope && "current" in scope ? scope.current : scope
446
+ const sync = () => {
447
+ const next = readChartTokens(target)
448
+ if (sameChartTokens(tokensRef.current, next)) return
449
+ tokensRef.current = next
450
+ setTokens(next)
451
+ }
452
+ sync()
453
+ return watchChartTokens(sync, target)
454
+ }, [scope])
455
+ return tokens
456
+ }
457
+
458
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
459
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
460
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
461
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
462
+
463
+ /**
464
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
465
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
466
+ * variants `"positive-fill"`, …) are read in the snapshot's inherited scope (`--positive`, …); `var(--token)` uses the same scope; any
467
+ * other CSS colour is normalized like the tokens are. A colour that can't be
468
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
469
+ */
470
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
471
+ return colors.map((color) => {
472
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
473
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
474
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
475
+ if (TONE_NAME_RE.test(color.trim())) {
476
+ if (typeof document === "undefined") return ""
477
+ const target = (tokens && tokenScopes.get(tokens)) ?? document.documentElement
478
+ return toCanvasColor(getComputedStyle(target).getPropertyValue(`--${color.trim()}`)) ?? ""
479
+ }
480
+ if (typeof document === "undefined") return color
481
+ let value = color.trim()
482
+ const cssVar = CSS_VAR_RE.exec(value)
483
+ const styles = getComputedStyle((tokens && tokenScopes.get(tokens)) ?? document.documentElement)
484
+ if (cssVar) {
485
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
486
+ } else if (value.includes("var(")) {
487
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
488
+ // substitute the tokens, then let the canvas resolve the rest.
489
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
490
+ }
491
+ return toCanvasColor(value) ?? ""
492
+ })
493
+ }
494
+
495
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
496
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
497
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
498
+ ["positive", "warning", "negative", "neutral"],
499
+ tokens,
500
+ )
501
+ return { positive, warning, negative, neutral }
502
+ }
503
+
504
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
505
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
506
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
507
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
508
+ tokens,
509
+ )
510
+ return { positive, warning, negative, neutral }
511
+ }
512
+
513
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
514
+
515
+ /**
516
+ * The colour the chart is painted on: the first opaque `background-color` up
517
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
518
+ * outside the browser.
519
+ */
520
+ function readChartSurface(el: Element | null): string | null {
521
+ if (typeof document === "undefined") return null
522
+ for (let node: Element | null = el; node; node = node.parentElement) {
523
+ const bg = getComputedStyle(node).backgroundColor.trim()
524
+ if (bg && !TRANSPARENT_RE.test(bg)) {
525
+ const color = toCanvasColor(bg)
526
+ if (color) return color
527
+ }
528
+ }
529
+ return toCanvasColor(getComputedStyle(el ?? document.documentElement).getPropertyValue("--background"))
530
+ }
531
+
532
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
533
+ const WIDTH_BUCKET = 40
534
+
535
+ /**
536
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
537
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
538
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
539
+ * component's forwarded ref.
540
+ */
541
+ function useChartSurface<E extends Element>(
542
+ forwarded: ForwardedRef<E>,
543
+ tokens?: ChartTokens | null,
544
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined; tokens: ChartTokens | null } {
545
+ const [node, setNode] = useState<E | null>(null)
546
+ const scopedTokens = useChartTokens(node)
547
+ const [surface, setSurface] = useState<string | undefined>(undefined)
548
+ const [width, setWidth] = useState<number | undefined>(undefined)
549
+ const ref = useCallback(
550
+ (el: E | null) => {
551
+ setNode(el)
552
+ if (typeof forwarded === "function") forwarded(el)
553
+ else if (forwarded) forwarded.current = el
554
+ },
555
+ [forwarded],
556
+ )
557
+ useEffect(() => {
558
+ if (!node) return
559
+ setSurface(readChartSurface(node) ?? undefined)
560
+ }, [node, tokens, scopedTokens])
561
+ useEffect(() => {
562
+ if (!node || typeof ResizeObserver === "undefined") return
563
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
564
+ update(node.getBoundingClientRect().width)
565
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
566
+ observer.observe(node)
567
+ return () => observer.disconnect()
568
+ }, [node])
569
+ return { ref, surface, width, tokens: scopedTokens }
570
+ }
571
+
572
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-options.ts (internal to @squadbase/vantage) ---------- */
573
+
574
+ /** The built-in words of the option builders, by language. */
575
+ const CHART_TEXT = {
576
+ ja: {
577
+ target: "目標",
578
+ forecast: "予測",
579
+ total: "合計",
580
+ provisional: "速報",
581
+ noComparison: "比較なし",
582
+ share: (share: string) => `(${share})`,
583
+ targetRate: (rate: string) => `(達成率 ${rate})`,
584
+ provisionalTitle: (title: string, label: string) => `${title}(${label})`,
585
+ },
586
+ en: {
587
+ target: "Target",
588
+ forecast: "Forecast",
589
+ total: "Total",
590
+ provisional: "Preliminary",
591
+ noComparison: "No comparison",
592
+ share: (share: string) => ` (${share})`,
593
+ targetRate: (rate: string) => ` (${rate} achieved)`,
594
+ provisionalTitle: (title: string, label: string) => `${title} (${label})`,
595
+ },
596
+ } satisfies Record<UiLanguage, unknown>
597
+
598
+ const chartText = (locale?: string) => CHART_TEXT[uiLanguage(resolveLocale(locale))]
599
+
600
+ type CartesianChartKind = "area" | "bar" | "line"
601
+ type CartesianStackType = "default" | "stacked" | "percent"
602
+ type CartesianCurveType = "linear" | "smooth" | "step"
603
+ type AreaFill = "gradient" | "solid" | "none"
604
+ type BarLayout = "horizontal" | "vertical"
605
+
606
+ /** AreaChart-only settings. */
607
+ interface AreaChartOptions {
608
+ /** `"stacked"` は積み上げ、`"percent"` は各点の合計を 100% にした積み上げ。既定 `"default"`。 */
609
+ type?: CartesianStackType
610
+ /** 線の形。既定 `"linear"`。 */
611
+ curveType?: CartesianCurveType
612
+ /** 面の塗り。既定 `"gradient"`。 */
613
+ fill?: AreaFill
614
+ /** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
615
+ connectNulls?: boolean
616
+ }
617
+
618
+ /** LineChart-only settings. */
619
+ interface LineChartOptions {
620
+ /** 線の形。既定 `"linear"`。 */
621
+ curveType?: CartesianCurveType
622
+ /** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
623
+ connectNulls?: boolean
624
+ /** 値軸を 0 からではなくデータの範囲に合わせる。既定 `false`(0 起点)。最小の目盛ラベルは先頭の x ラベルと重なるので出さない(グリッド線は残る)。 */
625
+ fitToData?: boolean
626
+ /**
627
+ * 目標線(`target`)のラベルの置き場所。`"start"`(既定)は線の左端の上(最大・最新の強調と近いときは下)。
628
+ * `"end"` は線の右端の上。`"legend"` は凡例だけに出し、線の上には出さない(線の周りが混み合うとき)。
629
+ * 目標の呼び名は、どれを選んでも凡例に出る。
630
+ */
631
+ targetLabelPosition?: LineTargetLabelPosition
632
+ }
633
+
634
+ /** Where a line chart prints its target label: at the line's left end, its right end, or in the legend only. */
635
+ type LineTargetLabelPosition = "start" | "end" | "legend"
636
+
637
+ /** BarChart-only settings. */
638
+ interface BarChartOptions<T extends Record<string, unknown> = Record<string, unknown>> {
639
+ /** `"stacked"` は積み上げ、`"percent"` は各カテゴリの合計を 100% にした積み上げ。既定 `"default"`(横並び)。 */
640
+ type?: CartesianStackType
641
+ /**
642
+ * 棒の向き。既定 `"horizontal"`(カテゴリが横に並ぶ縦棒)。`"vertical"` はカテゴリを
643
+ * 縦に並べた横棒で、ラベルの長いランキングに向く(先頭の行が一番上)。
644
+ */
645
+ layout?: BarLayout
646
+ /** カテゴリ間の隙間(`"20%"` や px)。省略時は ECharts の既定。 */
647
+ barCategoryGap?: string | number
648
+ /**
649
+ * 値が 0 の棒に「0」の値ラベルを付ける。棒が描かれない 0 が「データなし」に見えるのを防ぐ
650
+ * (在庫 0・件数 0 など)。積み上げでは付けない。0 以外の棒の見た目は変わらない。既定 `true`。
651
+ */
652
+ showZeroValues?: boolean
653
+ /**
654
+ * 棒ごとの目標値が入った `data` の列名(行ごとの目標。店舗別の月次目標など)。各棒に短い目標マーカーを
655
+ * 引き、ツールチップに「目標 … (達成率 …%)」を足す。凡例に目標の呼び名(`targetLabel`、既定「目標」)が出る。
656
+ * 1 系列の棒と積み上げ(達成率は合計に対して)で使える。横並びの複数系列と 100% 積み上げでは描かない。
657
+ * 値が欠けた(null・0 以下の)行はマーカーを引かない。
658
+ *
659
+ * 優先順位: `targetKey` を渡すと 1 本の目標線 `target` は描かない(`targetLabel` はマーカーの呼び名として使う)。
660
+ * 値による色分け `thresholds` とは併用できる(色は棒、マーカーは目標)。値軸は最大の目標を含む。
661
+ * 例: `barOptions={{ targetKey: "月次目標" }}`
662
+ */
663
+ targetKey?: NumericKeys<T>
664
+ /**
665
+ * 横棒(`layout: "vertical"`)の 1 系列で伝えたい 1 本。`index` の値で渡す(例 `"東京店"`)。
666
+ * 横棒は淡い色(`--chart-1` の薄い塗り)が既定で、この 1 本だけ濃い色(系列色そのまま)になる。省略すると全部が淡い色。
667
+ * 縦棒・複数系列・積み上げでは効かない(色は変わらない)。意味色の `thresholds` に当たった棒はそちらの色が優先。
668
+ * 例: `barOptions={{ layout: "vertical", highlight: "東京店" }}`
669
+ */
670
+ highlight?: string | number
671
+ }
672
+
673
+ /** Props every cartesian typed chart (Area / Bar / Line) shares. */
674
+ interface CartesianChartBaseProps<T extends Record<string, unknown> = Record<string, unknown>>
675
+ extends ChartCommonProps<T> {
676
+ /**
677
+ * 最大値と最新値に値ラベルを付ける(最初の系列だけ・系列が 2 つ以下のときだけ・最大 2 つ)。
678
+ * 100% 積み上げの面グラフでは、最初の系列(一番下の帯)の最初と最新の比率(「24%」「31%」)を帯の中に付ける。
679
+ * 既定は Line / Area が `"auto"`、Bar は `index` が日付・年月・年のときだけ `"auto"`。
680
+ */
681
+ highlight?: ChartHighlight
682
+ /**
683
+ * ここから先は確定前(速報)の点。index の値で渡す(例 `"2026-09"`)。薄い色・点線(棒は薄い塗りと破線の縁)で
684
+ * 描き、凡例・ツールチップに `provisionalLabel` を出す。線・面は確定の最終点とつなぐ。`forecast`(予測)とは別物。
685
+ * 例: `provisionalFrom="2026-09"`
686
+ */
687
+ provisionalFrom?: string | number
688
+ /** 速報の呼び名(凡例・ツールチップ)。既定「速報」。例: `provisionalLabel="暫定"` */
689
+ provisionalLabel?: string
690
+ /**
691
+ * グラフが言っていることの 1 文要約(自由文)。`"auto"` なら data から機械的に組む
692
+ * (「<見出し>: 最新 <index値> は <値>、前の点より増加/減少」。向きは最新 2 点の値で決まる)。
693
+ * 増減の向きを文に書くなら `"auto"` を使うか data から作る — 手書きの向きは data とずれて誤る。
694
+ * 省略時は要約なし(既存どおり)。例: `summary="auto"`
695
+ */
696
+ summary?: string | "auto"
697
+ /** 目標値。点線の水平線で示し、値軸は必ずこの値を含む。棒ごとの目標(`barOptions.targetKey`)を渡したときは描かない。 */
698
+ target?: number
699
+ /** 目標線のラベル。既定「目標 <書式化した値>」。`barOptions.targetKey` のときはマーカーの呼び名(既定「目標」)。 */
700
+ targetLabel?: string
701
+ /**
702
+ * 任意の位置への注記(縦の線、または `to` で区間の帯)。折れ線・面・縦の棒(`barOptions.layout` が既定のとき)で使え、
703
+ * 横棒では描かない。`at` / `to` は `index` の値。色は中立で、ツールチップにも文言が出る。例:
704
+ * `annotations={[{ at: "2026-04", label: "料金改定" }, { at: "2026-08", to: "2026-09", label: "キャンペーン" }]}`
705
+ */
706
+ annotations?: ChartAnnotation[]
707
+ /** 凡例を出す。既定 `true`。 */
708
+ showLegend?: boolean
709
+ /** ホバー時のツールチップを出す。既定 `true`。 */
710
+ showTooltip?: boolean
711
+ /** 値軸の目盛り線を出す。既定 `true`。 */
712
+ showGridLines?: boolean
713
+ showXAxis?: boolean
714
+ showYAxis?: boolean
715
+ /** x 軸のラベルを最初と最後だけにする。 */
716
+ startEndOnly?: boolean
717
+ /** y 軸ラベルの幅(px)。並べた複数グラフのプロット領域を揃えたいときに固定する。 */
718
+ yAxisWidth?: number
719
+ /**
720
+ * 値軸の下限。Bar / Area は常に 0 起点なので、0 以下の値だけ有効(負の値の下に余白を取る。正の値は無視)。
721
+ * Line は指定した値から始める。データが下限を下回るときは軸を広げる(切り詰めない)。
722
+ * 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
723
+ */
724
+ minValue?: number
725
+ /**
726
+ * 値軸の上限(横棒は横軸)。データが上限を超えるときは軸を広げる(切り詰めない)。
727
+ * 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
728
+ */
729
+ maxValue?: number
730
+ /** @deprecated `lineOptions.fitToData` を使う。Bar / Area では無視される(常に 0 起点)。 */
731
+ autoMinValue?: boolean
732
+ /** `false` で値軸の目盛りを整数に限る。 */
733
+ allowDecimals?: boolean
734
+ xAxisLabel?: string
735
+ yAxisLabel?: string
736
+ /**
737
+ * 点(棒)のクリックで呼ばれる。クリックした行に `eventType` / `categoryClicked` を
738
+ * 足して渡し、同じ点をもう一度クリックすると `null`。渡すと選択以外が薄くなる。
739
+ */
740
+ onValueChange?: (value: ChartEventPayload) => void
741
+ /** @deprecated `isLoading` を使う。 */
742
+ loading?: boolean
743
+ }
744
+
745
+ /** The point a user clicked, used to dim everything else. */
746
+ interface ChartActivePoint {
747
+ category: string
748
+ index: number
749
+ }
750
+
751
+ /** The forecast as the builder takes it: untyped keys, already validated by the component's props. */
752
+ type CartesianForecastConfig = Omit<ChartForecast, "category"> & { category?: string }
753
+
754
+ /** The comparison series as the builder takes it (see `ChartComparison`); `label` names the baseline for `vs: "custom"`. */
755
+ interface CartesianComparisonConfig {
756
+ /** One of `categories`; drawn as a thin muted line, outside the `--chart-*` order. */
757
+ category: string
758
+ vs: ComparisonKind
759
+ label?: string
760
+ }
761
+
762
+ interface CartesianChartConfig {
763
+ kind: CartesianChartKind
764
+ data: readonly Record<string, unknown>[]
765
+ index: string
766
+ categories: readonly string[]
767
+ /** Resolved series colours, by category position. `""`/missing → theme palette. */
768
+ palette: readonly string[]
769
+ /** Display names for `index` values and category names (axis, legend, tooltip). Missing keys show as they are. */
770
+ labels?: Readonly<Record<string, string>>
771
+ /** Bar only, not stacked: colour each bar by its value (first matching rule wins). With several series (side by side) a bar that matches takes the tone as its fill and keeps its series colour as the edge. */
772
+ thresholds?: readonly ChartThreshold[]
773
+ /** Resolved colour of each tone (`resolveChartColors`); a tone missing here keeps the series colour. */
774
+ toneColors?: Partial<Record<ChartTone, string>>
775
+ /** Tooltip values. */
776
+ valueFormatter: (value: number) => string
777
+ /** Value-axis ticks, highlight and target labels (short form, e.g. ¥1億). Default `valueFormatter`. */
778
+ axisFormatter?: (value: number) => string
779
+ /**
780
+ * The value-axis tick formatter for an axis whose largest tick is the given number (`resolveAxisTickFormatter`):
781
+ * all ticks read in one unit (¥0.5億 / ¥1億). Default: `axisFormatter` for every tick.
782
+ */
783
+ axisTicks?: (top: number) => (value: number) => string
784
+ /** Locale of the time-axis labels and the built-in words (total, target, forecast). Default the page's (`<html lang>`). */
785
+ locale?: string
786
+ type?: CartesianStackType
787
+ /** Bar only. `"vertical"` lays the categories down the y axis (horizontal bars). */
788
+ layout?: BarLayout
789
+ curveType?: CartesianCurveType
790
+ fill?: AreaFill
791
+ connectNulls?: boolean
792
+ showLegend?: boolean
793
+ showTooltip?: boolean
794
+ showGridLines?: boolean
795
+ showXAxis?: boolean
796
+ showYAxis?: boolean
797
+ startEndOnly?: boolean
798
+ yAxisWidth?: number
799
+ /** Bar / Area: only a value ≤ 0 takes effect (they start at 0). Line: the axis' start. The axis widens to the data. */
800
+ minValue?: number
801
+ /** The axis' top; the axis widens to the data. */
802
+ maxValue?: number
803
+ /** Line only: legacy alias of `fitToData`. */
804
+ autoMinValue?: boolean
805
+ /** Line only: let the value axis follow the data instead of starting at 0. */
806
+ fitToData?: boolean
807
+ allowDecimals?: boolean
808
+ xAxisLabel?: string
809
+ yAxisLabel?: string
810
+ barCategoryGap?: string | number
811
+ /** Always draw the line/area points (needed to click them). */
812
+ showDots?: boolean
813
+ active?: ChartActivePoint | null
814
+ /** Default: `"auto"` for line/area, for bar only when `index` holds dates. */
815
+ highlight?: ChartHighlight
816
+ /** Bar only: the index value of the one horizontal bar drawn in the full colour (`BarChartOptions.highlight`). */
817
+ barHighlight?: string | number
818
+ target?: number
819
+ targetLabel?: string
820
+ /** Line only: where the target label sits (see `LineChartOptions.targetLabelPosition`). Default `"start"`. */
821
+ targetLabelPosition?: LineTargetLabelPosition
822
+ /** Bar only: a data column holding each bar's target (see `BarChartOptions.targetKey`). */
823
+ targetKey?: string
824
+ /** Notes at an index value or over a range (vertical bars, line, area). */
825
+ annotations?: readonly ChartAnnotation[]
826
+ /** Bar only, not stacked: label bars whose value is 0 with「0」(default true). */
827
+ showZeroValues?: boolean
828
+ /** Line / Area only; ignored for bar and for percent stacking. */
829
+ forecast?: CartesianForecastConfig
830
+ /**
831
+ * Line / Area only; ignored for bar and for percent stacking. The series `category` is drawn as a muted 1.5px solid line
832
+ * (no markers, no fill, outside a stack) and the first other series' tooltip row gets its difference from it.
833
+ */
834
+ comparison?: CartesianComparisonConfig
835
+ /** The `format` of the values, for the comparison's difference in the tooltip (percent → points). Default: relative change. */
836
+ comparisonFormat?: ValueFormat
837
+ /** Index value of the first provisional point (see `CartesianChartBaseProps.provisionalFrom`). */
838
+ provisionalFrom?: string | number
839
+ provisionalLabel?: string
840
+ /** The PNG action buttons are shown (top right): the legend keeps clear of them. */
841
+ reserveActions?: boolean
842
+ /** Colour of the target / forecast guide lines (resolved muted text). */
843
+ guideColor?: string
844
+ /**
845
+ * The surface the chart sits on (resolved). Highlight labels get it as a
846
+ * backdrop, so a guide line passing behind them never runs through the text.
847
+ */
848
+ labelBackground?: string
849
+ /** Colour of the highlight labels (resolved foreground). */
850
+ labelColor?: string
851
+ /**
852
+ * The plot's width in px, when known. Sets how many time labels fit, how many value ticks a
853
+ * horizontal bar chart carries, and drops the max highlight when it would print over the latest one.
854
+ */
855
+ plotWidth?: number
856
+ /** The plot's height in px (the `height` prop), when known: under 200 the value axis carries 3 intervals, else 4–5. */
857
+ plotHeight?: number
858
+ reducedMotion?: boolean
859
+ /** Deep-merged onto the generated option last. */
860
+ chartOptions?: EChartsOption
861
+ }
862
+
863
+ /* ----------------------------------------------------------------- motion */
864
+
865
+ /**
866
+ * The typed charts' motion: no entrance animation, a short ease on updates so a
867
+ * filter change reads as a change. Reduced motion turns animation off.
868
+ */
869
+ function chartMotion(reducedMotion: boolean): EChartsOption {
870
+ if (reducedMotion) return { animation: false }
871
+ return { animation: true, animationDuration: 0, animationDurationUpdate: 300, animationEasingUpdate: "cubicOut" }
872
+ }
873
+
874
+ /* ----------------------------------------------------------------- merge */
875
+
876
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
877
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false
878
+ const proto = Object.getPrototypeOf(value)
879
+ return proto === Object.prototype || proto === null
880
+ }
881
+
882
+ /**
883
+ * Deep-merge `override` onto `base` without mutating either: plain objects merge
884
+ * key by key, arrays merge by position (so `series: [{ … }]` tweaks the first
885
+ * series), anything else in `override` replaces. `undefined` keeps the base.
886
+ */
887
+ function mergeChartOptions<T>(base: T, override: unknown): T {
888
+ if (override === undefined) return base
889
+ if (Array.isArray(override)) {
890
+ if (!Array.isArray(base)) return override as T
891
+ const length = Math.max(base.length, override.length)
892
+ return Array.from({ length }, (_, i) => (i < override.length ? mergeChartOptions(base[i], override[i]) : base[i])) as T
893
+ }
894
+ if (isPlainRecord(override) && isPlainRecord(base)) {
895
+ const out: Record<string, unknown> = { ...base }
896
+ for (const key of Object.keys(override)) out[key] = mergeChartOptions(base[key], override[key])
897
+ return out as T
898
+ }
899
+ return override as T
900
+ }
901
+
902
+ /* -------------------------------------------------------------- highlight */
903
+
904
+ const TIME_INDEX_RE =
905
+ /^\d{4}(?:[-/]\d{1,2}(?:[-/]\d{1,2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)?)?$/
906
+
907
+ /**
908
+ * Whether the x values look like time: ISO dates / date-times, `YYYY-MM`,
909
+ * `YYYY`, or `Date` objects. Blank cells are ignored; nothing at all → `false`.
910
+ */
911
+ function isTimeIndex(values: readonly unknown[]): boolean {
912
+ const present = values.filter((v) => v !== null && v !== undefined && v !== "")
913
+ if (present.length === 0) return false
914
+ return present.every((v) =>
915
+ v instanceof Date ? !Number.isNaN(v.getTime()) : typeof v === "string" && TIME_INDEX_RE.test(v.trim()),
916
+ )
917
+ }
918
+
919
+ /* -------------------------------------------------------------- time axis */
920
+
921
+ type TimeGranularity = "year" | "month" | "day"
922
+
923
+ interface ParsedTime {
924
+ year: number
925
+ /** 1–12. */
926
+ month: number
927
+ day: number
928
+ }
929
+
930
+ const TIME_PARTS_RE = /^(\d{4})(?:[-/](\d{1,2})(?:[-/](\d{1,2}))?)?$/
931
+
932
+ /**
933
+ * The x values as calendar dates, with the finest granularity they carry — or
934
+ * `null` when any value is not a plain year / month / date (date-times with a
935
+ * clock part stay as they are: one label per hour would need its own format).
936
+ */
937
+ function parseTimeIndex(values: readonly unknown[]): { granularity: TimeGranularity; times: (ParsedTime | null)[] } | null {
938
+ if (!isTimeIndex(values)) return null
939
+ const ranks: readonly TimeGranularity[] = ["year", "month", "day"]
940
+ let rank = 0
941
+ const finer = (g: TimeGranularity) => {
942
+ rank = Math.max(rank, ranks.indexOf(g))
943
+ }
944
+ const times: (ParsedTime | null)[] = []
945
+ for (const v of values) {
946
+ if (v === null || v === undefined || v === "") {
947
+ times.push(null)
948
+ continue
949
+ }
950
+ if (v instanceof Date) {
951
+ if (v.getHours() !== 0 || v.getMinutes() !== 0 || v.getSeconds() !== 0) return null
952
+ finer(v.getDate() === 1 ? "month" : "day")
953
+ times.push({ year: v.getFullYear(), month: v.getMonth() + 1, day: v.getDate() })
954
+ continue
955
+ }
956
+ const text = String(v).trim()
957
+ // A trailing midnight (`2025-09-01T00:00:00Z`) is still a date; any other time of day is not.
958
+ const date = text.replace(/[T ]00:00(?::00(?:\.0+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/, "")
959
+ const m = TIME_PARTS_RE.exec(date)
960
+ if (!m) return null
961
+ finer(m[3] !== undefined ? "day" : m[2] !== undefined ? "month" : "year")
962
+ times.push({ year: Number(m[1]), month: Number(m[2] ?? 1), day: Number(m[3] ?? 1) })
963
+ }
964
+ // Date objects on the 1st read as months only when every value falls on a 1st.
965
+ if (rank === 1 && values.some((v) => v instanceof Date) && times.some((t) => t !== null && t.day !== 1)) rank = 2
966
+ return { granularity: ranks[rank]!, times }
967
+ }
968
+
969
+ const timeFormatCache = new Map<string, Intl.DateTimeFormat>()
970
+
971
+ function timeFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
972
+ const key = `${locale}|${JSON.stringify(options)}`
973
+ let format = timeFormatCache.get(key)
974
+ if (!format) {
975
+ format = new Intl.DateTimeFormat(locale, options)
976
+ timeFormatCache.set(key, format)
977
+ }
978
+ return format
979
+ }
980
+
981
+ const toDate = (t: ParsedTime) => new Date(t.year, t.month - 1, t.day)
982
+
983
+ /** How many x labels a time axis shows at most (the step is picked so the labels never crowd). */
984
+ const TIME_AXIS_MAX_LABELS = 6
985
+ /** Under this plot width (px) the axis, legend and labels switch to their compact form. */
986
+ const NARROW_PLOT_WIDTH = 400
987
+ /** The most x labels a narrow plot shows (a 262px plot reads 4 at most). */
988
+ const NARROW_TIME_AXIS_MAX_LABELS = 4
989
+
990
+ /** Calendar-friendly label steps per granularity (every 3 months, every week …). */
991
+ const TIME_AXIS_STEPS: Record<TimeGranularity, readonly number[]> = {
992
+ year: [1, 2, 5, 10, 20, 50, 100],
993
+ month: [1, 2, 3, 4, 6, 12, 24, 36, 60, 120],
994
+ day: [1, 2, 7, 14, 28, 56, 91, 182, 364],
995
+ }
996
+
997
+ /**
998
+ * Every how many points a time axis prints a label: the smallest calendar step
999
+ * (1, 2, 3, 4, 6, 12 months; 1, 2, 7, 14 days; …) that keeps the labels at or
1000
+ * under `maxLabels`. Deterministic, so the year-change label is never skipped by
1001
+ * ECharts' own overlap thinning. `null` when the values are not dates.
1002
+ */
1003
+ function timeAxisLabelStep(values: readonly unknown[], maxLabels: number = TIME_AXIS_MAX_LABELS): number | null {
1004
+ const parsed = parseTimeIndex(values)
1005
+ if (!parsed) return null
1006
+ const count = values.length
1007
+ const max = Math.max(1, maxLabels)
1008
+ const steps = TIME_AXIS_STEPS[parsed.granularity]
1009
+ return steps.find((step) => Math.ceil(count / step) <= max) ?? Math.ceil(count / max)
1010
+ }
1011
+
1012
+ /**
1013
+ * Category-axis labels for time-like x values, in `locale`: monthly data reads
1014
+ * `4月`, with the year (`2025年1月`) on the first shown label and on any shown
1015
+ * label whose year differs from the previous *shown* one; daily data reads
1016
+ * `4/1` (`2025/4/1` likewise); yearly data `2025年`. `shown(i)` says which
1017
+ * labels the axis prints (default: all) — hidden ones never carry the year.
1018
+ * `null` when the values are not dates — the axis then shows them as they are.
1019
+ */
1020
+ function timeAxisLabels(
1021
+ values: readonly unknown[],
1022
+ localeArg?: string,
1023
+ shown: (i: number) => boolean = () => true,
1024
+ ): string[] | null {
1025
+ const parsed = parseTimeIndex(values)
1026
+ if (!parsed) return null
1027
+ const locale = resolveLocale(localeArg)
1028
+ const { granularity, times } = parsed
1029
+ let prevYear: number | null = null
1030
+ return times.map((t, i) => {
1031
+ if (t === null) return String(values[i] ?? "")
1032
+ const visible = shown(i)
1033
+ const withYear = visible && (prevYear === null || t.year !== prevYear)
1034
+ if (visible) prevYear = t.year
1035
+ const options: Intl.DateTimeFormatOptions =
1036
+ granularity === "year"
1037
+ ? { year: "numeric" }
1038
+ : granularity === "month"
1039
+ ? withYear
1040
+ ? { year: "numeric", month: "short" }
1041
+ : { month: "short" }
1042
+ : withYear
1043
+ ? { year: "numeric", month: "numeric", day: "numeric" }
1044
+ : { month: "numeric", day: "numeric" }
1045
+ return timeFormat(locale, options).format(toDate(t))
1046
+ })
1047
+ }
1048
+
1049
+ /** The tooltip titles for time-like x values (`2025年9月`, `2025年9月1日`), or `null` when they are not dates. */
1050
+ function timeTooltipLabels(values: readonly unknown[], localeArg?: string): string[] | null {
1051
+ const parsed = parseTimeIndex(values)
1052
+ if (!parsed) return null
1053
+ const locale = resolveLocale(localeArg)
1054
+ const options: Intl.DateTimeFormatOptions =
1055
+ parsed.granularity === "year"
1056
+ ? { year: "numeric" }
1057
+ : parsed.granularity === "month"
1058
+ ? { year: "numeric", month: "long" }
1059
+ : { year: "numeric", month: "long", day: "numeric" }
1060
+ return parsed.times.map((t, i) => (t === null ? String(values[i] ?? "") : timeFormat(locale, options).format(toDate(t))))
1061
+ }
1062
+
1063
+ interface HighlightPoint {
1064
+ kind: "max" | "latest" | "start"
1065
+ index: number
1066
+ value: number
1067
+ }
1068
+
1069
+ /**
1070
+ * The points `highlight="auto"` labels on one series: the latest (last
1071
+ * non-null) point, and the maximum unless it *is* the latest or sits next to it
1072
+ * (`|i - latest| ≤ 1`, the labels would collide) — at most 2, max first.
1073
+ */
1074
+ function pickHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
1075
+ let latest = -1
1076
+ for (let i = values.length - 1; i >= 0; i--) {
1077
+ if (values[i] !== null && values[i] !== undefined) {
1078
+ latest = i
1079
+ break
1080
+ }
1081
+ }
1082
+ if (latest === -1) return []
1083
+ const latestValue = values[latest]!
1084
+ let max = -1
1085
+ values.forEach((v, i) => {
1086
+ if (v !== null && v !== undefined && (max === -1 || v > values[max]!)) max = i
1087
+ })
1088
+ const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: latestValue }
1089
+ if (max === -1 || max === latest || latestValue >= values[max]! || Math.abs(max - latest) <= 1) return [latestPoint]
1090
+ return [{ kind: "max", index: max, value: values[max]! }, latestPoint]
1091
+ }
1092
+
1093
+ /**
1094
+ * The points a 100% stacked area labels: the first and the latest (last
1095
+ * non-null) share of one band — "24% → 31%" is the claim such a chart makes.
1096
+ */
1097
+ function pickShareHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
1098
+ const first = values.findIndex((v) => v !== null && v !== undefined)
1099
+ if (first === -1) return []
1100
+ let latest = first
1101
+ for (let i = values.length - 1; i > first; i--) {
1102
+ if (values[i] !== null && values[i] !== undefined) {
1103
+ latest = i
1104
+ break
1105
+ }
1106
+ }
1107
+ const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: values[latest]! }
1108
+ return latest === first ? [latestPoint] : [{ kind: "start", index: first, value: values[first]! }, latestPoint]
1109
+ }
1110
+
1111
+ /** Whether a chart of `kind` labels its highlights by default. */
1112
+ function defaultChartHighlight(
1113
+ kind: CartesianChartKind,
1114
+ data: readonly Record<string, unknown>[],
1115
+ index: string,
1116
+ ): ChartHighlight {
1117
+ if (kind !== "bar") return "auto"
1118
+ return isTimeIndex(data.map((row) => row[index])) ? "auto" : "none"
1119
+ }
1120
+
1121
+ /* ---------------------------------------------------------------- helpers */
1122
+
1123
+ /** Same coercion as `toChartNumber` in chart-utils (kept local: inlined modules can't import each other). */
1124
+ function cellNumber(value: unknown): number | null {
1125
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
1126
+ if (typeof value === "bigint") return Number(value)
1127
+ if (typeof value === "string" && value.trim() !== "") {
1128
+ const n = Number(value)
1129
+ return Number.isFinite(n) ? n : null
1130
+ }
1131
+ return null
1132
+ }
1133
+
1134
+ /**
1135
+ * Series values per category. `"percent"` turns each row into shares of that
1136
+ * row's total (0–100); a row whose total is 0 stays at 0.
1137
+ */
1138
+ function cartesianSeriesValues(
1139
+ data: readonly Record<string, unknown>[],
1140
+ categories: readonly string[],
1141
+ type: CartesianStackType = "default",
1142
+ ): (number | null)[][] {
1143
+ const raw = categories.map((category) => data.map((row) => cellNumber(row[category])))
1144
+ if (type !== "percent") return raw
1145
+ return raw.map((values) =>
1146
+ values.map((value, i) => {
1147
+ if (value === null) return null
1148
+ const total = categories.reduce((sum, _, k) => sum + Math.abs(raw[k]![i] ?? 0), 0)
1149
+ return total === 0 ? 0 : (Math.abs(value) / total) * 100
1150
+ }),
1151
+ )
1152
+ }
1153
+
1154
+ /** A colour with alpha, for gradient stops. Understands `#rgb`, `#rrggbb`, `rgb()`/`rgba()`. */
1155
+ function withAlpha(color: string, alpha: number): string {
1156
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())
1157
+ if (hex) {
1158
+ const h = hex[1]!
1159
+ const full = h.length === 3 ? h.replace(/./g, (c) => c + c) : h
1160
+ const n = Number.parseInt(full, 16)
1161
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
1162
+ }
1163
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1164
+ if (rgb) return `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})`
1165
+ return color
1166
+ }
1167
+
1168
+ const HTML_ESCAPES: Record<string, string> = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }
1169
+
1170
+ function escapeHtml(value: string): string {
1171
+ return value.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]!)
1172
+ }
1173
+
1174
+ interface TooltipRow {
1175
+ name: string
1176
+ color: string
1177
+ value: number | null
1178
+ /** Percent stacking: the row's share of its point's total (0–100). */
1179
+ share?: number
1180
+ /** A muted line right under the row (a comparison's difference). */
1181
+ note?: string
1182
+ }
1183
+
1184
+ const shareFormat = new Intl.NumberFormat(DEFAULT_LOCALE, { maximumFractionDigits: 1 })
1185
+ const formatShare = (share: number) => `${shareFormat.format(share)}%`
1186
+
1187
+ /** The tooltip body: a title, then one `● name value` row per series, then muted one-line `notes` (target, annotation). */
1188
+ function tooltipHtml(
1189
+ title: string,
1190
+ rows: readonly TooltipRow[],
1191
+ valueFormatter: (value: number) => string,
1192
+ notes: readonly string[] = [],
1193
+ locale?: string,
1194
+ ): string {
1195
+ const t = chartText(locale)
1196
+ const lines = rows.map(
1197
+ (row) =>
1198
+ `<div style="display:flex;align-items:center;gap:8px;line-height:20px">` +
1199
+ `<span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${escapeHtml(row.color)}"></span>` +
1200
+ `<span style="flex:1;opacity:.8">${escapeHtml(row.name)}</span>` +
1201
+ `<span style="font-weight:600;font-variant-numeric:tabular-nums;margin-left:12px">${
1202
+ row.value === null ? EMPTY_VALUE : escapeHtml(valueFormatter(row.value))
1203
+ }${
1204
+ row.share === undefined ? "" : `<span style="opacity:.6;margin-left:4px">${escapeHtml(t.share(formatShare(row.share)))}</span>`
1205
+ }</span></div>` +
1206
+ (row.note === undefined
1207
+ ? ""
1208
+ : `<div style="padding-left:16px;line-height:18px;font-size:12px;opacity:.7;font-variant-numeric:tabular-nums">${escapeHtml(row.note)}</div>`),
1209
+ )
1210
+ const noteLines = notes.map(
1211
+ (note) => `<div style="margin-top:4px;line-height:18px;font-size:12px;opacity:.7">${escapeHtml(note)}</div>`,
1212
+ )
1213
+ return `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(title)}</div>${lines.join("")}${noteLines.join("")}`
1214
+ }
1215
+
1216
+ /* ------------------------------------------------- per-bar targets / notes */
1217
+
1218
+ /** Default name of the per-bar target marker (legend, tooltip) in `locale`: "Target" / 「目標」. Default the page's locale. */
1219
+ function barTargetLabel(locale?: string): string {
1220
+ return chartText(locale).target
1221
+ }
1222
+
1223
+ /** How far (px) the target marker reaches past each side of its bar. */
1224
+ const TARGET_MARKER_OVERHANG = 4
1225
+
1226
+ /**
1227
+ * The `renderItem` of the per-bar target marker: a 2px tick across the bar. Its length
1228
+ * is the bar's own width as ECharts lays it out (`api.barLayout`, one column — a single
1229
+ * series or a stack) plus a little overhang; without that it falls back to the
1230
+ * category band times `barHalfWidth`.
1231
+ */
1232
+ function targetMarkerRenderer(horizontalBars: boolean, barCategoryGap: string | number | undefined, color: string | undefined) {
1233
+ type Api = {
1234
+ value(dim: number): number
1235
+ coord(value: number[]): number[]
1236
+ size(value: number[]): number[]
1237
+ barLayout?(opt: { count: number; barCategoryGap?: string | number }): { width: number }[]
1238
+ }
1239
+ return (_params: unknown, api: Api) => {
1240
+ const [x = 0, y = 0] = api.coord([api.value(0), api.value(1)])
1241
+ const band = Math.abs(horizontalBars ? (api.size([0, 1])[1] ?? 0) : (api.size([1, 0])[0] ?? 0))
1242
+ const barWidth = api.barLayout?.({ count: 1, barCategoryGap })?.[0]?.width
1243
+ const length = (barWidth && barWidth > 0 ? barWidth : band * 2 * barHalfWidth(barCategoryGap)) + TARGET_MARKER_OVERHANG * 2
1244
+ return {
1245
+ type: "line",
1246
+ silent: true,
1247
+ shape: horizontalBars
1248
+ ? { x1: x, y1: y - length / 2, x2: x, y2: y + length / 2 }
1249
+ : { x1: x - length / 2, y1: y, x2: x + length / 2, y2: y },
1250
+ style: { stroke: color, lineWidth: 2, lineCap: "butt" },
1251
+ }
1252
+ }
1253
+ }
1254
+
1255
+ /**
1256
+ * Each row's target from the `targetKey` column. A missing, non-numeric or
1257
+ * non-positive cell is `null` (no marker for that bar).
1258
+ */
1259
+ function barTargetValues(data: readonly Record<string, unknown>[], targetKey: string): (number | null)[] {
1260
+ return data.map((row) => {
1261
+ const value = cellNumber(row[targetKey])
1262
+ return value !== null && value > 0 ? value : null
1263
+ })
1264
+ }
1265
+
1266
+ /** `value` as a share of `target` in percent; `null` without a value or a positive target. */
1267
+ function achievementRate(value: number | null | undefined, target: number | null | undefined): number | null {
1268
+ if (value === null || value === undefined || target === null || target === undefined || !(target > 0)) return null
1269
+ return (value / target) * 100
1270
+ }
1271
+
1272
+ /** The tooltip line of a bar with a target: 「目標 ¥1,200万(達成率 85.3%)」 / "Target $12M (85.3% achieved)". `null` without a target. */
1273
+ function barTargetNote(
1274
+ label: string,
1275
+ value: number | null,
1276
+ target: number | null,
1277
+ valueFormatter: (value: number) => string,
1278
+ locale?: string,
1279
+ ): string | null {
1280
+ if (target === null) return null
1281
+ const rate = achievementRate(value, target)
1282
+ return `${label} ${valueFormatter(target)}${rate === null ? "" : chartText(locale).targetRate(formatShare(rate))}`
1283
+ }
1284
+
1285
+ /** Half the width of a bar in category-axis units, from `barCategoryGap` (`"20%"`; a px gap or none → ECharts' 20%). */
1286
+ function barHalfWidth(barCategoryGap?: string | number): number {
1287
+ const gap = typeof barCategoryGap === "string" && /^\d+(\.\d+)?%$/.test(barCategoryGap.trim()) ? parseFloat(barCategoryGap) / 100 : 0.2
1288
+ return 0.5 / (1 + gap)
1289
+ }
1290
+
1291
+ /** An annotation placed on the category axis: positions are indexes into the x labels. */
1292
+ interface ResolvedAnnotation {
1293
+ from: number
1294
+ /** Set for a range (`to` after `from`); a single position leaves it out. */
1295
+ to?: number
1296
+ label: string
1297
+ }
1298
+
1299
+ /**
1300
+ * Place annotations on the x labels by `String(value)` equality. An annotation
1301
+ * whose `at` is not an `index` value is dropped; `to` before `at` swaps them; a
1302
+ * `to` that is unknown or equal to `at` makes it a single position.
1303
+ */
1304
+ function resolveAnnotations(
1305
+ annotations: readonly ChartAnnotation[] | undefined,
1306
+ indexValues: readonly unknown[],
1307
+ ): ResolvedAnnotation[] {
1308
+ if (!annotations?.length) return []
1309
+ const position = new Map<string, number>()
1310
+ indexValues.forEach((value, i) => {
1311
+ const key = String(value ?? "")
1312
+ if (!position.has(key)) position.set(key, i)
1313
+ })
1314
+ const out: ResolvedAnnotation[] = []
1315
+ for (const note of annotations) {
1316
+ const from = position.get(String(note.at))
1317
+ if (from === undefined || !note.label) continue
1318
+ const end = note.to === undefined ? undefined : position.get(String(note.to))
1319
+ if (end === undefined || end === from) out.push({ from, label: note.label })
1320
+ else out.push({ from: Math.min(from, end), to: Math.max(from, end), label: note.label })
1321
+ }
1322
+ return out
1323
+ }
1324
+
1325
+ /** Gap (px) under which two neighbouring vertical labels (12px text) would print over each other. */
1326
+ const ANNOTATION_LABEL_GAP = 16
1327
+ /** Assumed spacing (px) between two index positions when the plot's width is unknown. */
1328
+ const ANNOTATION_ASSUMED_GAP = 40
1329
+
1330
+ /**
1331
+ * Which end of its line each single-position annotation's label sits on. Labels
1332
+ * run along the line; neighbours closer than a label's height alternate between
1333
+ * the top and the bottom end, so they never print over one another. `lines` are
1334
+ * the annotation positions (index units) in any order; the result follows that order.
1335
+ */
1336
+ function annotationLabelEnds(lines: readonly number[], pointGap: number | null): ("top" | "bottom")[] {
1337
+ const gap = pointGap ?? ANNOTATION_ASSUMED_GAP
1338
+ const order = lines.map((at, i) => ({ at, i })).sort((a, b) => a.at - b.at || a.i - b.i)
1339
+ const ends: ("top" | "bottom")[] = Array(lines.length).fill("top")
1340
+ for (let k = 1; k < order.length; k++) {
1341
+ const prev = order[k - 1]!
1342
+ const cur = order[k]!
1343
+ if ((cur.at - prev.at) * gap < ANNOTATION_LABEL_GAP) ends[cur.i] = ends[prev.i] === "top" ? "bottom" : "top"
1344
+ }
1345
+ return ends
1346
+ }
1347
+
1348
+ interface AxisTooltipParam {
1349
+ seriesId?: string
1350
+ seriesName?: string
1351
+ dataIndex?: number
1352
+ color?: unknown
1353
+ }
1354
+
1355
+ const DIMMED = 0.3
1356
+
1357
+
1358
+ /** Series ids. Ours are stable across updates so ECharts can transition them; `__` marks the helpers. */
1359
+ const SERIES_ID_PREFIX = "series:"
1360
+ const FORECAST_SERIES_ID = "__forecast"
1361
+ const PROVISIONAL_SERIES_PREFIX = "__provisional:"
1362
+ /** Provisional points are drawn at this opacity (lines, areas, bars). */
1363
+ const PROVISIONAL_OPACITY = 0.55
1364
+ /** Horizontal bars (one series, not stacked) are painted at this share of the series colour; the highlighted bar is solid. Same tint as BarList. */
1365
+ const LIGHT_BAR_ALPHA = 0.7
1366
+ const FORECAST_BAND_BASE_ID = "__forecast-band-base"
1367
+ const FORECAST_BAND_RANGE_ID = "__forecast-band-range"
1368
+ const OVERLAY_SERIES_ID = "__overlay"
1369
+ const TARGET_MARKER_SERIES_ID = "__target-marker"
1370
+ const TARGET_LEGEND_SERIES_ID = "__target-legend"
1371
+ /** A flat tick (8×8 legend box, aspect kept): the per-bar target's legend icon. */
1372
+ const TARGET_LEGEND_ICON = "path://M0,0 L100,0 L100,24 L0,24 Z"
1373
+
1374
+ /**
1375
+ * The label at the top of a forecast's boundary line: the forecast's name (as in the legend) and an arrow toward the forecast side.
1376
+ * Without a `label`, "Forecast" / 「予測」 in `locale` (default the page's).
1377
+ */
1378
+ function forecastBoundaryText(label?: string, locale?: string): string {
1379
+ return `${label ?? chartText(locale).forecast} →`
1380
+ }
1381
+
1382
+ /** A comparison series: a thin, muted, solid line with no markers (60% of `--muted-foreground`). */
1383
+ const COMPARISON_LINE_WIDTH = 1.5
1384
+ const COMPARISON_OPACITY = 0.6
1385
+ /** Target line: 1px dotted. Forecast: 2px dashed. Different widths *and* patterns, so the two never read as one. */
1386
+ const TARGET_LINE_DASH = [2, 3]
1387
+ const FORECAST_LINE_DASH = [6, 4]
1388
+ /** Legend icons for the two (8×8 box, aspect kept): a row of dots / of dashes in the line's own proportions. */
1389
+ const TARGET_DOTTED_ICON = "path://M0,0 L12,0 L12,10 L0,10 Z M30,0 L42,0 L42,10 L30,10 Z M60,0 L72,0 L72,10 L60,10 Z M88,0 L100,0 L100,10 L88,10 Z"
1390
+ const FORECAST_DASHED_ICON = "path://M0,0 L42,0 L42,24 L0,24 Z M58,0 L100,0 L100,24 L58,24 Z"
1391
+
1392
+ /** The forecast band's fill opacity: on a dark surface it needs more to show against the background. */
1393
+ const FORECAST_BAND_ALPHA_LIGHT = 0.15
1394
+ const FORECAST_BAND_ALPHA_DARK = 0.22
1395
+
1396
+ /** Whether a resolved surface colour (`#rrggbb` / `rgb()`) is dark (relative luminance under 0.4). `false` when it can't be read. */
1397
+ function isDarkSurface(color: string | undefined): boolean {
1398
+ if (!color) return false
1399
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1400
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1401
+ let channels: number[]
1402
+ if (hex) {
1403
+ const n = Number.parseInt(hex[1]!, 16)
1404
+ channels = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
1405
+ } else if (rgb) channels = [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])]
1406
+ else return false
1407
+ const [r, g, b] = channels.map((c) => {
1408
+ const v = c / 255
1409
+ return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
1410
+ }) as [number, number, number]
1411
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.4
1412
+ }
1413
+
1414
+ interface AxisExtent {
1415
+ min: number
1416
+ max: number
1417
+ }
1418
+
1419
+ /** The label of a stack's total (highlight and tooltip) in `locale`: "Total" / 「合計」. Default the page's locale. */
1420
+ function stackTotalLabel(locale?: string): string {
1421
+ return chartText(locale).total
1422
+ }
1423
+
1424
+ /** Per point, the sum of the stacked series; `null` where every series is missing. */
1425
+ function stackTotalsOf(values: readonly (readonly (number | null)[])[]): (number | null)[] {
1426
+ const length = Math.max(0, ...values.map((v) => v.length))
1427
+ return Array.from({ length }, (_, i) => {
1428
+ let total: number | null = null
1429
+ for (const series of values) {
1430
+ const v = series[i]
1431
+ if (v !== null && v !== undefined) total = (total ?? 0) + v
1432
+ }
1433
+ return total
1434
+ })
1435
+ }
1436
+
1437
+ const LEGEND_LINE_HEIGHT = 24
1438
+ /** A rough width budget per legend line (px): a narrow card fits about this much. */
1439
+ const LEGEND_LINE_BUDGET = 320
1440
+
1441
+ /** How many lines the plain legend takes, estimated from its labels (12px text + 8px dot + gaps). */
1442
+ function legendLines(items: readonly string[], plotWidth?: number, reserve = 0): number {
1443
+ const width = items.reduce((sum, name) => sum + [...name].length * 12 + 8 + 5 + 16, 0)
1444
+ // A narrow plot has no room for the PNG buttons beside the legend: they move off its line, so no reserve.
1445
+ const narrow = plotWidth !== undefined && plotWidth < NARROW_PLOT_WIDTH
1446
+ const budget = Math.max(80, (plotWidth ? (narrow ? plotWidth : Math.min(LEGEND_LINE_BUDGET, plotWidth)) : LEGEND_LINE_BUDGET) - (narrow ? 0 : reserve))
1447
+ return Math.min(3, Math.max(1, Math.ceil(width / budget)))
1448
+ }
1449
+
1450
+ /** Width (px) kept free at the legend's right for the PNG action buttons (two 32px buttons + gaps). */
1451
+ const ACTIONS_RESERVE = 80
1452
+
1453
+ /** Room (px) one time label (`2026年1月`) needs, gap included. */
1454
+ const TIME_LABEL_WIDTH = 80
1455
+ /** Room (px) one highlight label (`¥6,240万`) needs, gap included. */
1456
+ const HIGHLIGHT_LABEL_WIDTH = 96
1457
+
1458
+ /** A highlight this close under the target (share of the larger of the two) can reach its label. */
1459
+ const TARGET_NEAR_SHARE = 0.12
1460
+ /** Under this plot width (px) a target label that would run into the latest value's label is dropped from the line. */
1461
+ const TARGET_LABEL_NARROW_WIDTH = 480
1462
+ /** A typical value-axis label column (`¥8,000万`), px. */
1463
+ const Y_AXIS_ESTIMATE = 72
1464
+ /** Breathing room between two labels, px — the estimate is rough. */
1465
+ const LABEL_SLACK = 24
1466
+
1467
+ /** Rough width (px) of 12px text: full-width characters 12, the rest 7. */
1468
+ function estimateTextWidth(text: string): number {
1469
+ let w = 0
1470
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1471
+ return w
1472
+ }
1473
+
1474
+ /**
1475
+ * How many intervals a horizontal value axis (a horizontal bar chart's x) can carry in `plot` px
1476
+ * without its tick labels touching: each tick takes the widest of `samples` (the axis' end labels
1477
+ * printed) plus a gap. At least 1, at most 5 (ECharts' default, which it rounds to a tidy step).
1478
+ */
1479
+ function valueAxisSplitNumber(plot: number, samples: readonly string[]): number {
1480
+ const widest = samples.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
1481
+ return Math.max(1, Math.min(5, Math.floor(plot / (widest + LABEL_SLACK))))
1482
+ }
1483
+
1484
+ /** Room (px) above a vertical bar chart's plot for the label of an annotation band. */
1485
+ const BAND_LABEL_ROOM = 18
1486
+
1487
+ /** The grid's right margin on a line / area chart (px): the last x label hangs past the plot. */
1488
+ const LINE_RIGHT_MARGIN = 32
1489
+
1490
+ /** Room (px) above the plot for a forecast's boundary label (「予測 →」). */
1491
+ const FORECAST_LABEL_ROOM = 18
1492
+
1493
+ /**
1494
+ * Which side of the forecast boundary line the flat boundary label reads from: `"left"` starts at the line and runs
1495
+ * over the forecast side; `"right"` ends at the line and runs over the actuals, when the forecast side (the room right
1496
+ * of the line, grid margin included) is narrower than the text, so it never runs off the chart.
1497
+ * `forecastSpan` is `null` when the width is unknown.
1498
+ */
1499
+ function forecastLabelAlign(forecastSpan: number | null, text: string = forecastBoundaryText()): "left" | "right" {
1500
+ return forecastSpan !== null && forecastSpan >= estimateTextWidth(text) + 8 ? "left" : "right"
1501
+ }
1502
+
1503
+ /** ECharts' "nice" tick step for a raw step (1 / 2 / 3 / 5 × 10ⁿ, rounded): the same rule its value axis uses. */
1504
+ function niceStep(raw: number): number {
1505
+ if (!(raw > 0) || !Number.isFinite(raw)) return 1
1506
+ const exp10 = 10 ** Math.floor(Math.log10(raw))
1507
+ const f = raw / exp10
1508
+ return (f < 1.5 ? 1 : f < 2.5 ? 2 : f < 4 ? 3 : f < 7 ? 5 : 10) * exp10
1509
+ }
1510
+
1511
+ /**
1512
+ * The largest tick (by size) a value axis over `[lo, hi]` will carry once ECharts has niced its ends — the number
1513
+ * that decides the unit the ticks read in (`resolveAxisTickFormatter`). `max`, when fixed, is the axis' top as is.
1514
+ */
1515
+ function estimateAxisTop(lo: number, hi: number, splitNumber: number, max?: number): number {
1516
+ const top = Math.max(Math.abs(lo), Math.abs(hi))
1517
+ if (!(top > 0)) return 0
1518
+ const step = niceStep((hi - lo) / splitNumber)
1519
+ const niceHi = max !== undefined && max >= hi ? max : Math.ceil(hi / step) * step
1520
+ const niceLo = Math.floor(lo / step) * step
1521
+ return Math.max(Math.abs(niceHi), Math.abs(niceLo))
1522
+ }
1523
+
1524
+ /** Plot heights (px) under this carry 3 value intervals, not 4–5. */
1525
+ const SHORT_PLOT_HEIGHT = 200
1526
+ /** Plot heights under this carry 4 value intervals; taller ones 5. */
1527
+ const TALL_PLOT_HEIGHT = 300
1528
+ /** The plot height assumed when it isn't known (the charts' default `height`). */
1529
+ const ASSUMED_PLOT_HEIGHT = 288
1530
+
1531
+ /** How many intervals a vertical value axis carries: 3 under 200px of plot height, 4 under 300px, else 5. */
1532
+ function valueAxisSplitCount(plotHeight: number = ASSUMED_PLOT_HEIGHT): number {
1533
+ return plotHeight < SHORT_PLOT_HEIGHT ? 3 : plotHeight < TALL_PLOT_HEIGHT ? 4 : 5
1534
+ }
1535
+
1536
+ /** The grain of time-like x values (`"month"` for `2026-04`), or `null` when they aren't plain years / months / days. */
1537
+ function indexGrain(values: readonly unknown[]): PeriodGrain | null {
1538
+ const parsed = parseTimeIndex(values)
1539
+ return parsed ? parsed.granularity : null
1540
+ }
1541
+
1542
+ /**
1543
+ * The tooltip line under the main series' row when a comparison series is drawn: the arrow, the signed change and the
1544
+ * comparison's name, as `Delta` writes it ("↑ +12.4% vs. same month last year" / "↑ +12.4% 前年同月比"; a minus is U+2212).
1545
+ * "No comparison vs. same month last year" / "比較なし 前年同月比" when either value is missing or the baseline is 0.
1546
+ */
1547
+ function comparisonNote(
1548
+ current: number | null,
1549
+ previous: number | null,
1550
+ comparison: Pick<CartesianComparisonConfig, "vs" | "label">,
1551
+ grain?: PeriodGrain,
1552
+ format?: ValueFormat,
1553
+ localeArg?: string,
1554
+ ): string {
1555
+ const locale = resolveLocale(localeArg)
1556
+ const result = computeComparison(
1557
+ current,
1558
+ comparison.vs === "custom"
1559
+ ? { previous, vs: "custom", label: comparison.label ?? "", grain }
1560
+ : { previous, vs: comparison.vs, label: comparison.label, grain },
1561
+ { locale },
1562
+ )
1563
+ const text = formatChange(result, defaultChangeDisplay(format), locale, format)
1564
+ if (text === null) return `${chartText(locale).noComparison} ${result.label}`
1565
+ const arrow = result.direction === "up" ? "↑" : result.direction === "down" ? "↓" : "→"
1566
+ return `${arrow} ${text.replace(/^-/, "−")} ${result.label}`
1567
+ }
1568
+
1569
+ /** Bars and areas start at 0: the length / area *is* the value. */
1570
+ const zeroBasedMin = (extent: AxisExtent) => Math.min(0, extent.min)
1571
+
1572
+ /**
1573
+ * A value axis' `min` / `max` from the limits a caller asked for, so that charts shown side by side can share one scale.
1574
+ * A limit never cuts the data: when the data runs past it, the axis widens to the data (`max(maxValue, data max)`).
1575
+ * `zeroBased` (bars, areas, waterfall): the axis always reaches 0, so a `minValue` above 0 is ignored and only a
1576
+ * negative one (room below 0) takes effect. Without a limit asked for, that edge is `undefined` (ECharts' own choice)
1577
+ * — except a zero-based `min`, which is always given.
1578
+ */
1579
+ function valueAxisLimits(
1580
+ limits: { minValue?: number; maxValue?: number },
1581
+ zeroBased: boolean,
1582
+ ): { min: ((extent: AxisExtent) => number) | undefined; max: ((extent: AxisExtent) => number) | undefined } {
1583
+ const lo = Number.isFinite(limits.minValue) ? limits.minValue : undefined
1584
+ const hi = Number.isFinite(limits.maxValue) ? limits.maxValue : undefined
1585
+ return {
1586
+ min: zeroBased
1587
+ ? (extent) => Math.min(0, lo ?? 0, extent.min)
1588
+ : lo === undefined
1589
+ ? undefined
1590
+ : (extent) => Math.min(lo, extent.min),
1591
+ max: hi === undefined ? undefined : (extent) => Math.max(hi, extent.max),
1592
+ }
1593
+ }
1594
+
1595
+ function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
1596
+ const {
1597
+ kind,
1598
+ data,
1599
+ index,
1600
+ categories,
1601
+ palette,
1602
+ labels: nameLabels,
1603
+ thresholds,
1604
+ toneColors,
1605
+ valueFormatter,
1606
+ axisFormatter = valueFormatter,
1607
+ type = "default",
1608
+ layout = "horizontal",
1609
+ curveType = "linear",
1610
+ fill = "gradient",
1611
+ connectNulls = false,
1612
+ showLegend = true,
1613
+ showTooltip = true,
1614
+ showGridLines = true,
1615
+ showXAxis = true,
1616
+ showYAxis = true,
1617
+ startEndOnly = false,
1618
+ yAxisWidth,
1619
+ minValue,
1620
+ maxValue,
1621
+ autoMinValue = false,
1622
+ fitToData,
1623
+ allowDecimals = true,
1624
+ xAxisLabel,
1625
+ yAxisLabel,
1626
+ barCategoryGap,
1627
+ showDots = false,
1628
+ active = null,
1629
+ target,
1630
+ targetLabel,
1631
+ targetLabelPosition = "start",
1632
+ targetKey,
1633
+ showZeroValues = true,
1634
+ guideColor,
1635
+ labelBackground,
1636
+ labelColor,
1637
+ plotWidth,
1638
+ plotHeight,
1639
+ reducedMotion = false,
1640
+ chartOptions,
1641
+ reserveActions = false,
1642
+ } = cfg
1643
+ const locale = resolveLocale(cfg.locale)
1644
+ const text = chartText(locale)
1645
+ const provisionalLabel = cfg.provisionalLabel ?? text.provisional
1646
+
1647
+ const stacked = kind !== "line" && type !== "default"
1648
+ const percent = kind !== "line" && type === "percent"
1649
+ const horizontalBars = kind === "bar" && layout === "vertical"
1650
+ /*
1651
+ * -- comparison: a plain line, outside the stack and the palette. Never with bars or a 100% stack
1652
+ * (shares of a total have no "last year" line).
1653
+ */
1654
+ const comparison = kind !== "bar" && !percent ? cfg.comparison : undefined
1655
+ const compIdx = comparison ? categories.indexOf(comparison.category) : -1
1656
+ /** Positions of the series that are not the comparison: the stack, the highlight and the forecast read these. */
1657
+ const mainIdx = categories.map((_, i) => i).filter((i) => i !== compIdx)
1658
+ const seriesType = kind === "line" ? "default" : type
1659
+ const values = (() => {
1660
+ if (compIdx === -1) return cartesianSeriesValues(data, categories, seriesType)
1661
+ const main = cartesianSeriesValues(data, mainIdx.map((i) => categories[i]!), seriesType)
1662
+ const compared = cartesianSeriesValues(data, [categories[compIdx]!], "default")[0]!
1663
+ return categories.map((_, i) => (i === compIdx ? compared : main[mainIdx.indexOf(i)]!))
1664
+ })()
1665
+ const comparisonColor = guideColor ? withAlpha(guideColor, COMPARISON_OPACITY) : undefined
1666
+
1667
+ /* -- x labels: the actual rows, then the forecast rows that extend them */
1668
+ const labels = data.map((row) => String(row[index] ?? ""))
1669
+ const rawIndex: unknown[] = data.map((row) => row[index])
1670
+ const lastActual = labels.length - 1
1671
+ // First provisional point (-1: none). Looked up among the actual rows only; unrelated to `forecast`.
1672
+ const provStart = categories.length > 0 ? provisionalStart(rawIndex, cfg.provisionalFrom) : -1
1673
+ const forecast =
1674
+ kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 && data.length > 0 && categories.length > 0
1675
+ ? cfg.forecast
1676
+ : undefined
1677
+ const forecastAt: number[] = []
1678
+ if (forecast) {
1679
+ const position = new Map(labels.map((label, i) => [label, i]))
1680
+ for (const row of forecast.data) {
1681
+ const label = String(row[index] ?? "")
1682
+ let at = position.get(label)
1683
+ if (at === undefined || at <= lastActual) {
1684
+ // A forecast row never overwrites an actual point; repeated labels append.
1685
+ at = labels.length
1686
+ labels.push(label)
1687
+ rawIndex.push(row[index])
1688
+ position.set(label, at)
1689
+ }
1690
+ forecastAt.push(at)
1691
+ }
1692
+ }
1693
+ const pad = (series: (number | null)[]) =>
1694
+ series.length < labels.length ? [...series, ...Array<null>(labels.length - series.length).fill(null)] : series
1695
+ const last = labels.length - 1
1696
+ /*
1697
+ * -- time-like x values read as dates in the locale (`4月`, `2026年1月`), at a
1698
+ * fixed calendar step so the year-change label is never thinned away.
1699
+ */
1700
+ const timeStep = startEndOnly
1701
+ ? null
1702
+ : timeAxisLabelStep(
1703
+ rawIndex,
1704
+ plotWidth
1705
+ ? Math.max(
1706
+ 2,
1707
+ Math.min(
1708
+ plotWidth < NARROW_PLOT_WIDTH ? NARROW_TIME_AXIS_MAX_LABELS : TIME_AXIS_MAX_LABELS,
1709
+ Math.floor(plotWidth / TIME_LABEL_WIDTH),
1710
+ ),
1711
+ )
1712
+ : undefined,
1713
+ )
1714
+ // Plain (non-date) x labels of a line chart: thinned to every n-th so they never touch, never rotated.
1715
+ const plainStep = (() => {
1716
+ if (kind !== "line" || startEndOnly || timeStep !== null || !plotWidth || labels.length < 3) return 1
1717
+ const widest = Math.max(...labels.map((l) => estimateTextWidth(nameLabels && hasLabel(nameLabels, l) ? labelOf(l, nameLabels) : l)))
1718
+ const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN)
1719
+ return Math.max(1, Math.ceil(((widest + 12) * (labels.length - 1)) / plot))
1720
+ })()
1721
+ const shownLabel = startEndOnly
1722
+ ? (i: number) => i === 0 || i === last
1723
+ : timeStep !== null
1724
+ ? (i: number) => i % timeStep === 0
1725
+ : plainStep > 1
1726
+ ? (i: number) => i % plainStep === 0
1727
+ : null
1728
+ const timeLabels = timeAxisLabels(rawIndex, locale, shownLabel ?? undefined)
1729
+ const compGrain = comparison ? (indexGrain(rawIndex.slice(0, lastActual + 1)) ?? undefined) : undefined
1730
+ const tooltipTitles = (timeTooltipLabels(rawIndex, locale) ?? labels).map((title, i) =>
1731
+ nameLabels ? (hasLabel(nameLabels, labels[i] ?? "") ? labelOf(labels[i] ?? "", nameLabels) : title) : title,
1732
+ )
1733
+
1734
+ /*
1735
+ * -- highlight: max + latest. Normal stacking labels the stack's total (on the
1736
+ * top layer); otherwise the first series, ≤ 2 series. A 100% stacked area
1737
+ * labels the first series' (the bottom band's) first and latest share inside
1738
+ * the band; a 100% stacked bar labels nothing.
1739
+ */
1740
+ const highlight = cfg.highlight ?? defaultChartHighlight(kind, data, index)
1741
+ const stackTotals = stacked && !percent ? stackTotalsOf(mainIdx.map((i) => values[i]!)) : null
1742
+ const highlightSeries = (stackTotals ? mainIdx[mainIdx.length - 1] : mainIdx[0]) ?? 0
1743
+ const shareHighlight = percent && kind === "area"
1744
+ const picked =
1745
+ highlight !== "auto" || mainIdx.length === 0 || (percent && !shareHighlight)
1746
+ ? []
1747
+ : shareHighlight
1748
+ ? categories.length <= 2
1749
+ ? pickShareHighlightPoints(values[0] ?? [])
1750
+ : []
1751
+ : stackTotals
1752
+ ? pickHighlightPoints(stackTotals)
1753
+ : mainIdx.length <= 2
1754
+ ? pickHighlightPoints(values[highlightSeries] ?? [])
1755
+ : []
1756
+ // On a narrow plot the max and the latest label would print over each other: keep the latest.
1757
+ const pointGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
1758
+ // By default only the latest value is labelled; an explicit `highlight` keeps its max + latest.
1759
+ const latestOnly = cfg.highlight === undefined && !shareHighlight && picked.length === 2
1760
+ const highlightPoints =
1761
+ latestOnly
1762
+ ? [picked[1]!]
1763
+ : picked.length === 2 && pointGap !== null && Math.abs(picked[1]!.index - picked[0]!.index) * pointGap < HIGHLIGHT_LABEL_WIDTH
1764
+ ? [picked[1]!]
1765
+ : picked
1766
+
1767
+ /*
1768
+ * Points (and the outer bars) sit at the plot's edges: pull the first / last
1769
+ * label inward so it isn't clipped. A label on the forecast boundary sits left
1770
+ * of the boundary line instead of across it.
1771
+ */
1772
+ const boundaryIndex = kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 ? lastActual : -1
1773
+ const edgeAlign = (i: number) =>
1774
+ horizontalBars || labels.length < 2
1775
+ ? undefined
1776
+ : i === boundaryIndex && i !== last
1777
+ ? { align: "right" as const, offset: [-6, 0] }
1778
+ : i === last
1779
+ ? { align: "right" as const, ...(kind === "bar" ? { offset: [8, 0] } : {}) }
1780
+ : i === 0
1781
+ ? { align: "left" as const, ...(kind === "bar" ? { offset: [-8, 0] } : {}) }
1782
+ : undefined
1783
+
1784
+ /*
1785
+ * The target label sits at the plot's start (left), above its line, so it stays clear of the latest value's label at
1786
+ * the right end. Near the label (horizontally, estimated from `plotWidth`) a line / area highlight just under the
1787
+ * target prints below its point, and one just over it moves the target label under the line instead. On a plot
1788
+ * narrower than 480px, when the *latest* point's label would still run into the target label, the target label leaves
1789
+ * the line altogether — the legend names the target.
1790
+ */
1791
+ // `barOptions.targetKey` (a target per bar) takes over from the single `target` line.
1792
+ const perBarTarget = kind === "bar" && Boolean(targetKey)
1793
+ const hasTarget = !perBarTarget && target !== undefined && Number.isFinite(target)
1794
+ const targetText = hasTarget ? (targetLabel ?? `${text.target} ${axisFormatter(target)}`) : ""
1795
+ const highlightText = (value: number) =>
1796
+ shareHighlight ? `${Math.round(value)}%` : `${stackTotals ? `${text.total} ` : ""}${axisFormatter(value)}`
1797
+ /** Whether `p`'s label sits within the target's value band and under the target label (at the right end). */
1798
+ const nearTargetLabel = (p: HighlightPoint, side: "under" | "over") => {
1799
+ if (!hasTarget || !plotWidth || kind === "bar" || labels.length < 2) return false
1800
+ if (side === "under" ? p.value > target : p.value <= target) return false
1801
+ const scale = Math.max(Math.abs(target), ...highlightPoints.map((h) => Math.abs(h.value)))
1802
+ if (scale === 0 || Math.abs(target - p.value) / scale > TARGET_NEAR_SHARE) return false
1803
+ const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - 32)
1804
+ const x = (p.index / (labels.length - 1)) * plot
1805
+ const w = estimateTextWidth(highlightText(p.value)) + 8
1806
+ const align = edgeAlign(p.index)?.align
1807
+ const left = align === "right" ? x - w - 6 : align === "left" ? x : x - w / 2
1808
+ return left < estimateTextWidth(targetText) + 8 + LABEL_SLACK
1809
+ }
1810
+ const hideTargetLabel =
1811
+ (kind === "line" && targetLabelPosition === "legend") ||
1812
+ !shareHighlight &&
1813
+ plotWidth !== undefined &&
1814
+ plotWidth < TARGET_LABEL_NARROW_WIDTH &&
1815
+ highlightPoints.some((p) => p.index === labels.length - 1 && (nearTargetLabel(p, "under") || nearTargetLabel(p, "over")))
1816
+ const below = (p: HighlightPoint) => !shareHighlight && !hideTargetLabel && nearTargetLabel(p, "under")
1817
+ const targetLabelBelow = !shareHighlight && !hideTargetLabel && highlightPoints.some((p) => nearTargetLabel(p, "over"))
1818
+
1819
+ // One series (or a stack, against its total) can be compared to a target; grouped series and 100% stacks cannot.
1820
+ const barTargets: (number | null)[] | null =
1821
+ perBarTarget && targetKey && !percent && (stacked || categories.length === 1) ? barTargetValues(data, targetKey) : null
1822
+ const barTargetName = targetLabel ?? text.target
1823
+ const barTargetColor = labelColor ?? guideColor
1824
+
1825
+ const markPointFor = (c: number, color: string | undefined) =>
1826
+ c === highlightSeries && highlightPoints.length > 0
1827
+ ? {
1828
+ silent: true,
1829
+ symbol: "circle",
1830
+ symbolSize: kind === "bar" ? 0 : 7,
1831
+ itemStyle: { color, borderColor: "transparent" },
1832
+ label: {
1833
+ show: true,
1834
+ position: horizontalBars ? ("right" as const) : ("top" as const),
1835
+ distance: 6,
1836
+ fontSize: 12,
1837
+ fontWeight: 500,
1838
+ color: labelColor,
1839
+ ...(labelBackground ? { backgroundColor: labelBackground, padding: [2, 4], borderRadius: 2 } : {}),
1840
+ formatter: (p: { value?: unknown }) => highlightText(Number(p.value)),
1841
+ },
1842
+ data: highlightPoints.map((p) => {
1843
+ // Below the point; on the forecast boundary, on the forecast side (the actual line comes in from the left).
1844
+ const label = shareHighlight
1845
+ ? // Inside the bottom band, under its upper edge: the label reads as that band's share.
1846
+ { ...edgeAlign(p.index), position: "bottom" as const }
1847
+ : below(p)
1848
+ ? p.index === boundaryIndex && p.index !== last
1849
+ ? { position: "bottom" as const, align: "left" as const, offset: [6, 0] }
1850
+ : { ...edgeAlign(p.index), position: "bottom" as const }
1851
+ : edgeAlign(p.index)
1852
+ return {
1853
+ name: p.kind,
1854
+ value: p.value,
1855
+ coord: horizontalBars ? [p.value, p.index] : [p.index, p.value],
1856
+ ...(label ? { label } : {}),
1857
+ }
1858
+ }),
1859
+ }
1860
+ : undefined
1861
+
1862
+ // Threshold colours: bars side by side (one series or several). A stacked segment is a part, not a level to judge, so stacks keep their series colours.
1863
+ const byValue = kind === "bar" && !stacked && Boolean(thresholds?.length)
1864
+ const multiSeries = categories.length > 1
1865
+ // Horizontal bars of one series read light; only the highlighted bar is solid (the one the page is about).
1866
+ const lightBars = kind === "bar" && horizontalBars && !stacked && !multiSeries
1867
+ const series: Record<string, unknown>[] = categories.map((category, c) => {
1868
+ const solid = palette[c] || undefined
1869
+ const color = lightBars && solid ? withAlpha(solid, LIGHT_BAR_ALPHA) : solid
1870
+ const dimSeries = active !== null && active.category !== category
1871
+ const seriesData = pad(values[c]!)
1872
+ if (kind === "bar") {
1873
+ const rounded = horizontalBars ? [0, 4, 4, 0] : [4, 4, 0, 0]
1874
+ // Stacked: only the topmost segment is rounded.
1875
+ const radius = stacked && c !== categories.length - 1 ? 0 : rounded
1876
+ return {
1877
+ id: SERIES_ID_PREFIX + category,
1878
+ type: "bar" as const,
1879
+ name: category,
1880
+ stack: stacked ? "total" : undefined,
1881
+ barCategoryGap,
1882
+ itemStyle: { color, borderRadius: radius },
1883
+ markPoint: markPointFor(c, solid),
1884
+ markLine: undefined,
1885
+ data: seriesData.map((value, i) => {
1886
+ const tone = byValue ? toneForValue(value, thresholds) : undefined
1887
+ const toneColor = tone ? toneColors?.[tone] || undefined : undefined
1888
+ const isHighlight = lightBars && cfg.barHighlight !== undefined && String(rawIndex[i]) === String(cfg.barHighlight)
1889
+ const dimmed = active !== null && !(active.category === category && active.index === i)
1890
+ // Provisional bars: lighter fill and a dashed edge, never the solid look of a confirmed bar.
1891
+ const provisional = provStart !== -1 && i >= provStart && i <= lastActual
1892
+ const zeroLabel =
1893
+ showZeroValues && !stacked && value === 0
1894
+ ? {
1895
+ show: true,
1896
+ position: horizontalBars ? ("right" as const) : ("top" as const),
1897
+ distance: 4,
1898
+ fontSize: 12,
1899
+ color: labelColor,
1900
+ formatter: () => axisFormatter(0),
1901
+ }
1902
+ : undefined
1903
+ if (!dimmed && !toneColor && !isHighlight && !provisional && !zeroLabel) return value
1904
+ return {
1905
+ value,
1906
+ ...(zeroLabel ? { label: zeroLabel } : {}),
1907
+ itemStyle: {
1908
+ ...(isHighlight && solid ? { color: solid } : {}),
1909
+ ...(toneColor ? { color: toneColor } : {}),
1910
+ // Several series: the series colour stays on the edge so the legend still points at the bar.
1911
+ ...(toneColor && multiSeries && color && !provisional ? { borderColor: color, borderWidth: 2 } : {}),
1912
+ ...(provisional ? { opacity: PROVISIONAL_OPACITY, borderColor: toneColor ?? color, borderWidth: 1, borderType: "dashed" as const } : {}),
1913
+ ...(dimmed ? { opacity: DIMMED } : {}),
1914
+ },
1915
+ }
1916
+ }),
1917
+ }
1918
+ }
1919
+ if (c === compIdx) {
1920
+ // The comparison: thin, muted, solid, no markers, no fill, never stacked — behind the main series.
1921
+ return {
1922
+ id: SERIES_ID_PREFIX + category,
1923
+ type: "line" as const,
1924
+ name: category,
1925
+ z: 1,
1926
+ smooth: curveType === "smooth",
1927
+ step: curveType === "step" ? ("middle" as const) : undefined,
1928
+ connectNulls,
1929
+ symbol: "none",
1930
+ showSymbol: false,
1931
+ lineStyle: { width: COMPARISON_LINE_WIDTH, type: "solid" as const, color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
1932
+ itemStyle: { color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
1933
+ areaStyle: undefined,
1934
+ markPoint: undefined,
1935
+ markLine: undefined,
1936
+ data: seriesData,
1937
+ }
1938
+ }
1939
+ const areaStyle =
1940
+ kind !== "area" || fill === "none"
1941
+ ? undefined
1942
+ : fill === "solid" || !color
1943
+ ? { opacity: fill === "solid" ? 0.3 : 0.2 }
1944
+ : {
1945
+ color: {
1946
+ type: "linear" as const,
1947
+ x: 0,
1948
+ y: 0,
1949
+ x2: 0,
1950
+ y2: 1,
1951
+ colorStops: [
1952
+ { offset: 0, color: withAlpha(color, 0.28) },
1953
+ { offset: 1, color: withAlpha(color, 0) },
1954
+ ],
1955
+ },
1956
+ }
1957
+ return {
1958
+ id: SERIES_ID_PREFIX + category,
1959
+ type: "line" as const,
1960
+ name: category,
1961
+ stack: stacked ? "total" : undefined,
1962
+ smooth: curveType === "smooth",
1963
+ step: curveType === "step" ? ("middle" as const) : undefined,
1964
+ connectNulls,
1965
+ symbol: "circle",
1966
+ symbolSize: 6,
1967
+ showSymbol: showDots || data.length === 1,
1968
+ // 100% stacked: the top band's upper edge is the 100% line, not a value — drawn, it reads as「this band = 100%」.
1969
+ lineStyle:
1970
+ percent && c === categories.length - 1
1971
+ ? { width: 0, color, opacity: 0 }
1972
+ : { width: 2, color, opacity: dimSeries ? DIMMED : 1 },
1973
+ itemStyle: { color, opacity: dimSeries ? DIMMED : 1 },
1974
+ // Hovering a series fades the others (not for a stack, where the bands read together).
1975
+ emphasis: stacked ? undefined : { focus: "series" as const },
1976
+ areaStyle: areaStyle && dimSeries ? { ...areaStyle, opacity: DIMMED * 0.3 } : areaStyle,
1977
+ markPoint: markPointFor(c, color),
1978
+ markLine: undefined,
1979
+ data: provStart === -1 ? seriesData : splitProvisional(seriesData, provStart).confirmed,
1980
+ }
1981
+ })
1982
+
1983
+ /* -- provisional: a dashed, lighter continuation of every series from `provStart`, joined to the last confirmed point */
1984
+ if (kind !== "bar" && provStart !== -1) {
1985
+ categories.forEach((category, c) => {
1986
+ // The comparison is not provisional: it keeps its own line to the end.
1987
+ if (c === compIdx) return
1988
+ const color = palette[c] || undefined
1989
+ const dimSeries = active !== null && active.category !== category
1990
+ const solid = series[c] as { areaStyle?: { opacity?: number } }
1991
+ const opacity = (dimSeries ? DIMMED : 1) * PROVISIONAL_OPACITY
1992
+ series.push({
1993
+ id: PROVISIONAL_SERIES_PREFIX + category,
1994
+ type: "line" as const,
1995
+ name: provisionalLabel,
1996
+ // Its own stack: the joint point repeats the confirmed value and must not pile onto it.
1997
+ stack: stacked ? "provisional" : undefined,
1998
+ smooth: curveType === "smooth",
1999
+ step: curveType === "step" ? ("middle" as const) : undefined,
2000
+ connectNulls: false,
2001
+ symbol: "circle",
2002
+ symbolSize: 6,
2003
+ showSymbol: showDots || data.length === 1,
2004
+ lineStyle:
2005
+ percent && c === categories.length - 1
2006
+ ? { width: 0, color, opacity: 0 }
2007
+ : { width: 2, type: "dashed" as const, color, opacity },
2008
+ itemStyle: { color, opacity },
2009
+ areaStyle: solid.areaStyle ? { ...solid.areaStyle, opacity: (solid.areaStyle.opacity ?? 1) * PROVISIONAL_OPACITY } : undefined,
2010
+ markPoint: undefined,
2011
+ markLine: undefined,
2012
+ data: splitProvisional(pad(values[c]!), provStart).provisional,
2013
+ })
2014
+ })
2015
+ }
2016
+ // A bar legend entry for the provisional style (an empty line series: it takes no bar slot).
2017
+ if (kind === "bar" && provStart !== -1) {
2018
+ series.push({
2019
+ id: PROVISIONAL_SERIES_PREFIX + "legend",
2020
+ type: "line" as const,
2021
+ name: provisionalLabel,
2022
+ silent: true,
2023
+ symbol: "none",
2024
+ showSymbol: false,
2025
+ tooltip: { show: false },
2026
+ legendHoverLink: false,
2027
+ lineStyle: { opacity: 0 },
2028
+ itemStyle: { color: palette[0] || undefined, opacity: PROVISIONAL_OPACITY },
2029
+ markPoint: undefined,
2030
+ markLine: undefined,
2031
+ data: [],
2032
+ })
2033
+ }
2034
+
2035
+ /* -- forecast: dashed continuation (+ optional band) of one series */
2036
+ const forecastLabel = forecast?.label ?? text.forecast
2037
+ const forecastBandAlpha = isDarkSurface(labelBackground) ? FORECAST_BAND_ALPHA_DARK : FORECAST_BAND_ALPHA_LIGHT
2038
+ const forecastValues: (number | null)[] = []
2039
+ if (forecast) {
2040
+ const category =
2041
+ forecast.category !== undefined && categories.includes(forecast.category) && forecast.category !== comparison?.category
2042
+ ? forecast.category
2043
+ : categories[mainIdx[0] ?? 0]!
2044
+ const c = categories.indexOf(category)
2045
+ const color = palette[c] || undefined
2046
+ const actual = values[c]!
2047
+ let start = -1
2048
+ for (let i = actual.length - 1; i >= 0; i--) {
2049
+ if (actual[i] !== null) {
2050
+ start = i
2051
+ break
2052
+ }
2053
+ }
2054
+ const line: (number | null)[] = Array<null>(labels.length).fill(null)
2055
+ const lower: (number | null)[] = Array<null>(labels.length).fill(null)
2056
+ const range: (number | null)[] = Array<null>(labels.length).fill(null)
2057
+ if (start !== -1) {
2058
+ line[start] = actual[start]!
2059
+ lower[start] = actual[start]!
2060
+ range[start] = 0
2061
+ }
2062
+ let hasBand = false
2063
+ forecast.data.forEach((row: ChartForecastRow, k) => {
2064
+ const at = forecastAt[k]!
2065
+ line[at] = cellNumber(row.value)
2066
+ const lo = cellNumber(row.lower)
2067
+ const hi = cellNumber(row.upper)
2068
+ if (lo !== null && hi !== null) {
2069
+ hasBand = true
2070
+ lower[at] = Math.min(lo, hi)
2071
+ range[at] = Math.abs(hi - lo)
2072
+ }
2073
+ })
2074
+ forecastValues.push(...line)
2075
+ const helper = {
2076
+ type: "line" as const,
2077
+ silent: true,
2078
+ symbol: "none",
2079
+ showSymbol: false,
2080
+ connectNulls: true,
2081
+ tooltip: { show: false },
2082
+ legendHoverLink: false,
2083
+ emphasis: { disabled: true },
2084
+ markPoint: undefined,
2085
+ markLine: undefined,
2086
+ }
2087
+ if (hasBand) {
2088
+ series.push(
2089
+ {
2090
+ ...helper,
2091
+ id: FORECAST_BAND_BASE_ID,
2092
+ name: FORECAST_BAND_BASE_ID,
2093
+ stack: FORECAST_BAND_BASE_ID,
2094
+ lineStyle: { opacity: 0 },
2095
+ areaStyle: undefined,
2096
+ data: lower,
2097
+ },
2098
+ {
2099
+ ...helper,
2100
+ id: FORECAST_BAND_RANGE_ID,
2101
+ name: FORECAST_BAND_RANGE_ID,
2102
+ stack: FORECAST_BAND_BASE_ID,
2103
+ lineStyle: { opacity: 0 },
2104
+ areaStyle: color ? { color: withAlpha(color, forecastBandAlpha), opacity: 1 } : { opacity: forecastBandAlpha },
2105
+ data: range,
2106
+ },
2107
+ )
2108
+ }
2109
+ series.push({
2110
+ ...helper,
2111
+ id: FORECAST_SERIES_ID,
2112
+ name: forecastLabel,
2113
+ silent: false,
2114
+ tooltip: undefined,
2115
+ emphasis: undefined,
2116
+ smooth: curveType === "smooth",
2117
+ // Always dashed (2px, 6-4) and lighter — a forecast must never read as a measurement, nor as the 1px dotted target.
2118
+ lineStyle: { width: 2, type: FORECAST_LINE_DASH, color, opacity: 0.7 },
2119
+ itemStyle: { color, opacity: 0.7 },
2120
+ areaStyle: undefined,
2121
+ data: line,
2122
+ })
2123
+ }
2124
+
2125
+ /* -- overlay: target line, forecast boundary, and the extent that keeps the target on the axis */
2126
+ /**
2127
+ * Horizontal bars: the target line is vertical and its label lies flat above the plot, centred
2128
+ * on the line — unless that would run past the plot's right (or left) edge, e.g. a target near
2129
+ * the axis max on a narrow chart; then it hangs to the line's left (right) instead. The axis max
2130
+ * is estimated from the data (ECharts rounds it up, which only moves the line left of the guess).
2131
+ */
2132
+ const horizontalTargetAlign = ((): "left" | "center" | "right" => {
2133
+ if (!horizontalBars || !hasTarget) return "center"
2134
+ const totals = labels.map((_, i) =>
2135
+ stacked
2136
+ ? values.reduce((sum, v) => sum + Math.max(0, v[i] ?? 0), 0)
2137
+ : Math.max(0, ...values.map((v) => v[i] ?? 0)),
2138
+ )
2139
+ const top = percent ? 100 : (maxValue ?? Math.max(target, ...totals))
2140
+ if (!(top > 0)) return "center"
2141
+ const ratio = Math.min(1, Math.max(0, target / top))
2142
+ const half = (estimateTextWidth(targetText) + 8) / 2
2143
+ if (!plotWidth) return ratio > 0.85 ? "right" : ratio < 0.15 ? "left" : "center"
2144
+ const right = highlightPoints.length > 0 ? 64 : 16
2145
+ const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
2146
+ const plot = Math.max(1, plotWidth - categoryColumn - right - 4)
2147
+ const at = ratio * plot
2148
+ if (plot - at + right < half) return "right"
2149
+ if (at + categoryColumn < half) return "left"
2150
+ return "center"
2151
+ })()
2152
+ const markLines: unknown[] = []
2153
+ const markAreas: unknown[] = []
2154
+ if (hasTarget && target !== undefined) {
2155
+ markLines.push({
2156
+ name: "target",
2157
+ [horizontalBars ? "xAxis" : "yAxis"]: target,
2158
+ // 1px dotted — the forecast is 2px dashed, so the two never read as one line.
2159
+ lineStyle: { type: TARGET_LINE_DASH, width: 1, color: guideColor },
2160
+ label: {
2161
+ show: !hideTargetLabel,
2162
+ // The start (left) of the line, above it — under it when a highlight sits just above the target there.
2163
+ // Horizontal bars: the line is vertical, so the label goes flat above its top end, outside the plot (no rotation, clear of the bars).
2164
+ // The category axis is inverted there (first row on top), so the line runs top → bottom and its top end is the *start*.
2165
+ position: horizontalBars
2166
+ ? "start"
2167
+ : kind === "line" && targetLabelPosition === "end"
2168
+ ? "insideEndTop"
2169
+ : targetLabelBelow
2170
+ ? "insideStartBottom"
2171
+ : "insideStartTop",
2172
+ ...(horizontalBars ? { rotate: 0, align: horizontalTargetAlign, verticalAlign: "bottom" as const, distance: 4 } : {}),
2173
+ color: guideColor,
2174
+ formatter: targetText,
2175
+ },
2176
+ })
2177
+ }
2178
+ if (forecast) {
2179
+ const forecastSpan =
2180
+ plotWidth && labels.length > 1
2181
+ ? (Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN) / (labels.length - 1)) *
2182
+ (labels.length - 1 - lastActual) +
2183
+ LINE_RIGHT_MARGIN
2184
+ : null
2185
+ markLines.push({
2186
+ name: "forecast-boundary",
2187
+ xAxis: lastActual,
2188
+ lineStyle: { type: "dashed", width: 1, color: guideColor },
2189
+ // Flat (text-xs, muted), just above the plot's top edge at the top of the line (`grid.top` makes the room; the legend
2190
+ // sits above that): along the line at its foot it ran into the x axis labels on a narrow chart.
2191
+ label: {
2192
+ show: true,
2193
+ position: "end",
2194
+ rotate: 0,
2195
+ align: forecastLabelAlign(forecastSpan, forecastBoundaryText(forecastLabel)),
2196
+ verticalAlign: "bottom" as const,
2197
+ distance: 4,
2198
+ fontSize: 12,
2199
+ color: guideColor,
2200
+ formatter: forecastBoundaryText(forecastLabel),
2201
+ },
2202
+ })
2203
+ }
2204
+ /* -- annotations: a thin neutral line, or a faint band for a range, on the category axis (vertical layouts only) */
2205
+ const notes = horizontalBars ? [] : resolveAnnotations(cfg.annotations, rawIndex)
2206
+ const noteGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
2207
+ if (notes.length > 0) {
2208
+ const singles = notes.filter((n) => n.to === undefined)
2209
+ const ends = annotationLabelEnds(singles.map((n) => n.from), noteGap)
2210
+ const background = labelBackground ? { backgroundColor: labelBackground, padding: [1, 3], borderRadius: 2 } : {}
2211
+ singles.forEach((note, k) => {
2212
+ markLines.push({
2213
+ name: `annotation:${note.label}`,
2214
+ xAxis: note.from,
2215
+ lineStyle: { type: "solid", width: 1, color: guideColor },
2216
+ // Along the line, at the top (the legend sits above the plot) or at its foot when a neighbour is close.
2217
+ label: {
2218
+ show: true,
2219
+ position: ends[k] === "top" ? "insideEndTop" : "insideStartBottom",
2220
+ color: guideColor,
2221
+ ...background,
2222
+ formatter: note.label,
2223
+ },
2224
+ })
2225
+ })
2226
+ const over = kind === "bar" ? 0.5 : 0
2227
+ for (const note of notes) {
2228
+ if (note.to === undefined) continue
2229
+ const widthPx = noteGap === null ? null : (note.to - note.from + (kind === "bar" ? 1 : 0)) * noteGap
2230
+ const fits = widthPx === null ? [...note.label].length <= 6 : estimateTextWidth(note.label) + 8 <= widthPx
2231
+ markAreas.push([
2232
+ {
2233
+ name: note.label,
2234
+ xAxis: note.from - over,
2235
+ itemStyle: { color: guideColor ? withAlpha(guideColor, 0.12) : undefined },
2236
+ // The band's foot (bars: just above the plot — inside, the text would run into the value label of a tall bar,
2237
+ // and `grid.top` makes the room); a band narrower than its text reads the text upright along the band instead.
2238
+ label: {
2239
+ show: true,
2240
+ position: kind === "bar" ? "top" : fits ? "insideBottom" : "inside",
2241
+ rotate: fits ? 0 : 90,
2242
+ color: guideColor,
2243
+ fontSize: 12,
2244
+ formatter: note.label,
2245
+ },
2246
+ },
2247
+ { xAxis: note.to + over },
2248
+ ])
2249
+ }
2250
+ }
2251
+ // The target is a legend entry too (an empty line series carries the name): the line may lose its label on a narrow plot.
2252
+ if (hasTarget) {
2253
+ series.push({
2254
+ id: TARGET_LEGEND_SERIES_ID,
2255
+ type: "line" as const,
2256
+ name: targetText,
2257
+ silent: true,
2258
+ symbol: "none",
2259
+ showSymbol: false,
2260
+ tooltip: { show: false },
2261
+ legendHoverLink: false,
2262
+ emphasis: { disabled: true },
2263
+ lineStyle: { opacity: 0 },
2264
+ itemStyle: { color: guideColor },
2265
+ markPoint: undefined,
2266
+ markLine: undefined,
2267
+ data: [],
2268
+ })
2269
+ }
2270
+ if (markLines.length > 0 || markAreas.length > 0) {
2271
+ series.push({
2272
+ id: OVERLAY_SERIES_ID,
2273
+ name: OVERLAY_SERIES_ID,
2274
+ type: "line" as const,
2275
+ silent: true,
2276
+ symbol: "none",
2277
+ showSymbol: false,
2278
+ tooltip: { show: false },
2279
+ legendHoverLink: false,
2280
+ emphasis: { disabled: true },
2281
+ lineStyle: { opacity: 0 },
2282
+ itemStyle: { color: guideColor },
2283
+ // A single invisible point at the target, so the value axis always reaches it.
2284
+ data: labels.map((_, i) => (i === 0 && hasTarget && target !== undefined ? target : null)),
2285
+ markPoint: undefined,
2286
+ // `precision`: ECharts rounds a mark line's value to 2 decimals by default (a 0.035 target would land on 0.04 — off a fitted axis,
2287
+ // where the line is then dropped). `z` keeps the guide lines above the series' own lines.
2288
+ markLine: markLines.length > 0 ? { silent: true, symbol: "none", animation: false, precision: 20, z: 6, data: markLines } : undefined,
2289
+ markArea: markAreas.length > 0 ? { silent: true, animation: false, data: markAreas } : undefined,
2290
+ })
2291
+ }
2292
+ /*
2293
+ * -- per-bar targets: a short marker across each bar at its target. A custom
2294
+ * series (the marker's length follows the bar's width, in px, whatever the chart's
2295
+ * size) whose data also keeps the value axis reaching the largest target. It is
2296
+ * the legend's entry too: the marker is named, with a tick as its icon.
2297
+ */
2298
+ if (barTargets) {
2299
+ series.push({
2300
+ id: TARGET_MARKER_SERIES_ID,
2301
+ type: "custom" as const,
2302
+ name: barTargetName,
2303
+ silent: true,
2304
+ animation: false,
2305
+ z: 5,
2306
+ tooltip: { show: false },
2307
+ legendHoverLink: false,
2308
+ emphasis: { disabled: true },
2309
+ itemStyle: { color: barTargetColor },
2310
+ encode: { x: 0, y: 1 },
2311
+ data: barTargets.flatMap((value, i) => (value === null ? [] : [horizontalBars ? [value, i] : [i, value]])),
2312
+ renderItem: targetMarkerRenderer(horizontalBars, barCategoryGap, barTargetColor),
2313
+ })
2314
+ }
2315
+
2316
+ const categoryAxis = {
2317
+ id: horizontalBars ? "y" : "x",
2318
+ type: "category" as const,
2319
+ data: labels,
2320
+ show: horizontalBars ? showYAxis : showXAxis,
2321
+ boundaryGap: kind === "bar",
2322
+ inverse: horizontalBars,
2323
+ axisTick: { show: false },
2324
+ axisLabel: {
2325
+ hideOverlap: true,
2326
+ rotate: kind === "line" ? 0 : undefined,
2327
+ interval: shownLabel ?? ("auto" as const),
2328
+ formatter:
2329
+ timeLabels || nameLabels
2330
+ ? (value: string, i: number) => {
2331
+ const time = timeLabels?.[i]
2332
+ if (time === "") return ""
2333
+ return hasLabel(nameLabels, value) ? labelOf(value, nameLabels) : (time ?? value)
2334
+ }
2335
+ : undefined,
2336
+ width: horizontalBars ? yAxisWidth : undefined,
2337
+ overflow: horizontalBars && yAxisWidth != null ? ("truncate" as const) : undefined,
2338
+ },
2339
+ name: horizontalBars ? yAxisLabel : xAxisLabel,
2340
+ nameLocation: "middle" as const,
2341
+ nameGap: horizontalBars ? (yAxisWidth ?? 48) + 8 : 28,
2342
+ }
2343
+ const fit = kind === "line" && (fitToData ?? autoMinValue)
2344
+ // A horizontal bar chart's value ticks run along the (narrow) width: as many as fit side by side.
2345
+ const valueSplitNumber = (() => {
2346
+ if (!horizontalBars || !plotWidth) return undefined
2347
+ const top = percent
2348
+ ? 100
2349
+ : (maxValue ?? Math.max(0, ...(stacked ? stackTotalsOf(values) : values.flat()).map((v) => v ?? 0)))
2350
+ const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
2351
+ const plot = plotWidth - categoryColumn - (highlightPoints.length > 0 ? 64 : 16) - 4
2352
+ const text = percent ? (v: number) => `${v}%` : (v: number) => axisFormatter(v)
2353
+ return valueAxisSplitNumber(plot, [text(0), text(top)])
2354
+ })()
2355
+ const limits = valueAxisLimits({ minValue, maxValue }, kind !== "line")
2356
+ // Vertical value axes carry 3 intervals on a short plot, else 4–5 (a horizontal bar chart's follows its width, above).
2357
+ const splitNumber = horizontalBars ? valueSplitNumber : valueAxisSplitCount(plotHeight)
2358
+ /*
2359
+ * Ticks read in one unit — the unit of the axis' largest tick (¥0.5億 / ¥1億, never ¥5,000万 beside ¥1億). The largest
2360
+ * tick is estimated from the data the way ECharts nices its ends.
2361
+ */
2362
+ const tickFormatter = (() => {
2363
+ if (!cfg.axisTicks || percent) return axisFormatter
2364
+ const extentValues: number[] = []
2365
+ const addAll = (list: readonly (number | null)[]) => {
2366
+ for (const v of list) if (v !== null && Number.isFinite(v)) extentValues.push(v)
2367
+ }
2368
+ if (stackTotals) addAll(stackTotals)
2369
+ else values.forEach(addAll)
2370
+ addAll(forecastValues)
2371
+ if (forecast) addAll(forecast.data.flatMap((row) => [cellNumber(row.lower), cellNumber(row.upper)]))
2372
+ if (barTargets) addAll(barTargets)
2373
+ if (hasTarget && target !== undefined) extentValues.push(target)
2374
+ if (maxValue !== undefined && Number.isFinite(maxValue)) extentValues.push(maxValue)
2375
+ if (minValue !== undefined && Number.isFinite(minValue)) extentValues.push(minValue)
2376
+ if (extentValues.length === 0) return axisFormatter
2377
+ const zeroBased = kind !== "line" || !fit
2378
+ const hi = Math.max(...extentValues, zeroBased ? 0 : -Infinity)
2379
+ const lo = Math.min(...extentValues, zeroBased ? 0 : Infinity)
2380
+ return cfg.axisTicks(estimateAxisTop(lo, hi, splitNumber ?? 5, maxValue !== undefined && Number.isFinite(maxValue) ? maxValue : undefined))
2381
+ })()
2382
+ const valueAxis = {
2383
+ id: horizontalBars ? "x" : "y",
2384
+ type: "value" as const,
2385
+ show: horizontalBars ? showXAxis : showYAxis,
2386
+ // Bars and areas always start at 0 (a positive `minValue` can't lift them, a negative one makes room below);
2387
+ // lines do too unless asked to fit the data. A limit never cuts the data: the axis widens to it.
2388
+ min: percent ? 0 : kind === "line" ? (minValue === undefined ? (fit ? undefined : zeroBasedMin) : limits.min) : limits.min,
2389
+ max: percent ? 100 : limits.max,
2390
+ scale: fit && minValue == null,
2391
+ splitNumber,
2392
+ minInterval: allowDecimals ? undefined : 1,
2393
+ axisLine: { show: false },
2394
+ axisTick: { show: false },
2395
+ splitLine: { show: showGridLines },
2396
+ axisLabel: {
2397
+ formatter: percent ? (v: number) => `${v}%` : (v: number) => tickFormatter(v),
2398
+ // Fitted to the data: the lowest tick would print over the first x label at the bottom left. The gridline stays.
2399
+ showMinLabel: fit && minValue == null && !horizontalBars ? false : undefined,
2400
+ // Horizontal: ticks that would still touch on a narrow plot are dropped.
2401
+ hideOverlap: horizontalBars ? true : undefined,
2402
+ // A fixed width lines up side-by-side plots, but a value tick is never cut: the grid contains it.
2403
+ width: horizontalBars ? undefined : yAxisWidth,
2404
+ },
2405
+ name: horizontalBars ? xAxisLabel : yAxisLabel,
2406
+ nameLocation: "middle" as const,
2407
+ nameGap: horizontalBars ? 28 : (yAxisWidth ?? 48) + 8,
2408
+ }
2409
+
2410
+ const legendItems = [
2411
+ ...categories,
2412
+ ...(forecast ? [forecastLabel] : []),
2413
+ ...(provStart !== -1 ? [provisionalLabel] : []),
2414
+ ...(barTargets ? [barTargetName] : []),
2415
+ ...(hasTarget ? [targetText] : []),
2416
+ ]
2417
+ const option = {
2418
+ ...chartMotion(reducedMotion),
2419
+ legend: {
2420
+ show: showLegend,
2421
+ top: 0,
2422
+ // Narrow: left-aligned and wrapping above the plot, so nothing is cut off at the right edge.
2423
+ ...(plotWidth !== undefined && plotWidth < NARROW_PLOT_WIDTH
2424
+ ? { left: 0, right: 0 }
2425
+ : { right: reserveActions ? ACTIONS_RESERVE : 0 }),
2426
+ // Plain wraps onto a second line at narrow widths instead of hiding items behind arrows.
2427
+ type: "plain",
2428
+ icon: "circle",
2429
+ itemWidth: 8,
2430
+ itemHeight: 8,
2431
+ itemGap: 16,
2432
+ // The target marker is a tick, not a dot.
2433
+ // The target is a row of dots and the forecast a row of dashes — their lines' patterns — and a per-bar target a tick.
2434
+ data: legendItems.map((name) =>
2435
+ barTargets && name === barTargetName
2436
+ ? { name, icon: TARGET_LEGEND_ICON }
2437
+ : forecast && name === forecastLabel
2438
+ ? { name, icon: FORECAST_DASHED_ICON }
2439
+ : hasTarget && name === targetText
2440
+ ? { name, icon: TARGET_DOTTED_ICON }
2441
+ : name,
2442
+ ),
2443
+ formatter: nameLabels ? (name: string) => labelOf(name, nameLabels) : undefined,
2444
+ },
2445
+ grid: {
2446
+ top:
2447
+ (showLegend ? 12 + LEGEND_LINE_HEIGHT * legendLines(legendItems, plotWidth, reserveActions ? ACTIONS_RESERVE : 0) : 12) +
2448
+ // The flat target label of a horizontal bar chart sits above the plot.
2449
+ (horizontalBars && hasTarget ? 18 : 0) +
2450
+ // The label of a band over bars sits above the plot's top edge.
2451
+ (kind === "bar" && notes.some((n) => n.to !== undefined) ? BAND_LABEL_ROOM : 0) +
2452
+ // The boundary label of a forecast sits above the plot's top edge too.
2453
+ (forecast ? FORECAST_LABEL_ROOM : 0),
2454
+ // Lines start and end on the outermost ticks, so the last x label (and an edge
2455
+ // highlight) hangs past the plot; a horizontal bar's highlight sits past its end.
2456
+ right: horizontalBars ? (highlightPoints.length > 0 ? 64 : 16) : kind === "bar" ? 16 : LINE_RIGHT_MARGIN,
2457
+ bottom: xAxisLabel ? 24 : 4,
2458
+ left: yAxisLabel ? 24 : 4,
2459
+ containLabel: true,
2460
+ },
2461
+ tooltip: {
2462
+ show: showTooltip,
2463
+ trigger: "axis",
2464
+ axisPointer: { type: kind === "bar" ? "shadow" : "line" },
2465
+ formatter: (params: unknown) => {
2466
+ const list = (Array.isArray(params) ? params : [params]) as AxisTooltipParam[]
2467
+ const i = list[0]?.dataIndex ?? 0
2468
+ const row = i <= lastActual ? (data[i] ?? {}) : {}
2469
+ const rows: TooltipRow[] = []
2470
+ // The main series' difference from the comparison: one muted line under its row.
2471
+ const primary = mainIdx[0]
2472
+ const noteFor = (at: number): { note?: string } => {
2473
+ if (!comparison || compIdx === -1 || at !== primary || i > lastActual) return {}
2474
+ return {
2475
+ note: comparisonNote(
2476
+ cellNumber(row[categories[at]!]),
2477
+ cellNumber(row[comparison.category]),
2478
+ comparison,
2479
+ compGrain,
2480
+ cfg.comparisonFormat,
2481
+ locale,
2482
+ ),
2483
+ }
2484
+ }
2485
+ const shares = percent ? cartesianSeriesValues(i <= lastActual ? [row] : [], categories, "percent") : null
2486
+ // Rows follow the legend order (categories first), not ECharts' own series order.
2487
+ const legendRank = (p: AxisTooltipParam) => {
2488
+ const at = categories.indexOf(p.seriesName ?? "")
2489
+ return at === -1 ? categories.length : at
2490
+ }
2491
+ for (const p of [...list].sort((a, b) => legendRank(a) - legendRank(b))) {
2492
+ const color = typeof p.color === "string" ? p.color : "currentColor"
2493
+ if (p.seriesId === FORECAST_SERIES_ID) {
2494
+ // At and before the boundary the forecast repeats the actual value.
2495
+ if (i > lastActual) rows.push({ name: p.seriesName ?? forecastLabel, color, value: forecastValues[i] ?? null })
2496
+ continue
2497
+ }
2498
+ if (p.seriesId?.startsWith("__")) continue
2499
+ if (i > lastActual) continue
2500
+ const name = p.seriesName ?? ""
2501
+ const at = categories.indexOf(name)
2502
+ const share = shares && at !== -1 ? (shares[at]![0] ?? undefined) : undefined
2503
+ rows.push({
2504
+ name: labelOf(name, nameLabels),
2505
+ color: at === compIdx ? (comparisonColor ?? color) : color,
2506
+ value: cellNumber(row[name]),
2507
+ ...(share !== undefined ? { share } : {}),
2508
+ ...(at !== -1 ? noteFor(at) : {}),
2509
+ })
2510
+ }
2511
+ if (stackTotals && i <= lastActual && rows.length > 1) {
2512
+ rows.push({ name: text.total, color: "transparent", value: stackTotals[i] ?? null })
2513
+ }
2514
+ const provisional = provStart !== -1 && i >= provStart && i <= lastActual
2515
+ if (provisional) {
2516
+ // The confirmed series are empty here: rows come from the data, under a 「速報」 title.
2517
+ rows.length = 0
2518
+ categories.forEach((name, at) => {
2519
+ const share = shares ? (shares[at]![0] ?? undefined) : undefined
2520
+ rows.push({
2521
+ name,
2522
+ color: at === compIdx ? (comparisonColor ?? "currentColor") : palette[at] || "currentColor",
2523
+ value: cellNumber(row[name]),
2524
+ ...(share !== undefined ? { share } : {}),
2525
+ ...noteFor(at),
2526
+ })
2527
+ })
2528
+ if (stackTotals && rows.length > 1) rows.push({ name: text.total, color: "transparent", value: stackTotals[i] ?? null })
2529
+ }
2530
+ const title = tooltipTitles[i] ?? labels[i] ?? ""
2531
+ const lines: string[] = []
2532
+ if (barTargets && i <= lastActual) {
2533
+ const total = stackTotals ? (stackTotals[i] ?? null) : (values[0]?.[i] ?? null)
2534
+ const note = barTargetNote(barTargetName, total, barTargets[i] ?? null, valueFormatter, locale)
2535
+ if (note) lines.push(note)
2536
+ }
2537
+ for (const note of notes) {
2538
+ if (note.to === undefined ? note.from === i : note.from <= i && i <= note.to) lines.push(note.label)
2539
+ }
2540
+ return tooltipHtml(provisional ? text.provisionalTitle(title, provisionalLabel) : title, rows, valueFormatter, lines, locale)
2541
+ },
2542
+ },
2543
+ xAxis: horizontalBars ? valueAxis : categoryAxis,
2544
+ yAxis: horizontalBars ? categoryAxis : valueAxis,
2545
+ series,
2546
+ }
2547
+ return mergeChartOptions(option as EChartsOption, chartOptions)
2548
+ }
2549
+
2550
+ /* ------------------------------------------------------------------ donut */
2551
+
2552
+ type DonutVariant = "donut" | "pie"
2553
+
2554
+ /** What the donut prints in its hole (`donutOptions.centerLabel`). */
2555
+ type DonutCenterLabel = "none" | "total" | "top"
2556
+
2557
+ /**
2558
+ * The center of the donut as one of the three built-ins or a custom node.
2559
+ * Default `"none"`; the legacy `showLabel` (`false` → none, an explicit `true` →
2560
+ * total, the old default) and `label` (a custom node) still win over the default.
2561
+ */
2562
+ function resolveDonutCenter(
2563
+ centerLabel: DonutChartOptions["centerLabel"],
2564
+ { showLabel, label }: { showLabel?: boolean; label?: ReactNode } = {},
2565
+ ): { kind: DonutCenterLabel } | { kind: "custom"; node: ReactNode } {
2566
+ if (showLabel === false) return { kind: "none" }
2567
+ if (centerLabel === "none") return { kind: "none" }
2568
+ if (centerLabel === "total") return { kind: "total" }
2569
+ if (centerLabel === "top") return { kind: "top" }
2570
+ if (centerLabel !== undefined && centerLabel !== null && centerLabel !== false) return { kind: "custom", node: centerLabel }
2571
+ if (label !== undefined && label !== null && label !== false) return { kind: "custom", node: label }
2572
+ return { kind: showLabel === true ? "total" : "none" }
2573
+ }
2574
+
2575
+ /** Below this plot width (px) the outside labels can't fit beside the ring. */
2576
+ const DONUT_OUTSIDE_LABEL_MIN_WIDTH = 440
2577
+
2578
+ /**
2579
+ * How many slices get an outside label. A share is printed once: the legend
2580
+ * carries every slice's share, so with a legend there are no outside labels;
2581
+ * without one the 2 largest are labelled when the plot is wide enough
2582
+ * (`plotWidth` `null` = not measured yet → labelled).
2583
+ */
2584
+ function donutOutsideLabelCount(plotWidth: number | null, showLegend: boolean): number {
2585
+ if (showLegend) return 0
2586
+ return plotWidth !== null && plotWidth < DONUT_OUTSIDE_LABEL_MIN_WIDTH ? 0 : DONUT_OUTSIDE_LABELS
2587
+ }
2588
+
2589
+ /** The `"top"` center: the largest real slice's name (`label`) and share (`amount`); `null` when there is none. */
2590
+ function donutTopText(
2591
+ slices: readonly DonutOptionSlice[],
2592
+ labels?: Readonly<Record<string, string>>,
2593
+ ): { label: string; amount: string } | null {
2594
+ const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
2595
+ const top = [...slices].filter((s) => !s.isOther && sliceValue(s.value) > 0).sort((a, b) => sliceValue(b.value) - sliceValue(a.value))[0]
2596
+ return top ? { label: labelOf(top.name, labels), amount: donutShareText(top.value, total) } : null
2597
+ }
2598
+
2599
+ /** DonutChart-only settings. */
2600
+ interface DonutChartOptions {
2601
+ /** `"donut"`(中央に穴とラベル)か `"pie"`。既定 `"donut"`。 */
2602
+ variant?: DonutVariant
2603
+ /** @deprecated `centerLabel` を使う。`false` は `centerLabel: "none"` と同じ。`true` を明示すると `"total"` 扱い(以前の既定)。 */
2604
+ showLabel?: boolean
2605
+ /**
2606
+ * 穴の中央に出すもの。`"none"`(既定。何も出さない。合計は KPI と重複しがち)/ `"total"`(「合計」と
2607
+ * 合計を書式化した値。`totalLabel` / `unit` を添える)/ `"top"`(最大の切片の名前と構成比)。
2608
+ * それ以外のノードを渡すとそのまま中央に置く。donut のみ。
2609
+ */
2610
+ centerLabel?: DonutCenterLabel | ReactNode
2611
+ /** 中央ラベルの見出し(何の合計か)。既定「合計」。 */
2612
+ totalLabel?: string
2613
+ /** 中央ラベルの合計に添える単位(`"セッション"` → 「9.2万 セッション」)。 */
2614
+ unit?: string
2615
+ /** 凡例(名前と構成比、大きい順)を出す。広いときは右、狭いときは下。既定 `true`。構成比は凡例だけが持つ(凡例を消すと、広いときだけ大きい 2 切片に外ラベルで名前と構成比が出る)。 */
2616
+ showLegend?: boolean
2617
+ /** 個別に描く切片の数。超えた分は大きさ順の残りを「その他」1 切片にまとめる。既定 5。 */
2618
+ maxSlices?: number
2619
+ }
2620
+
2621
+ /** A slice as the builder takes it: already sorted, folded and coloured (see `donutSlices`). */
2622
+ interface DonutOptionSlice {
2623
+ name: string
2624
+ value: number
2625
+ /** The folded「その他」slice: never labelled outside. */
2626
+ isOther?: boolean
2627
+ }
2628
+
2629
+ /** How many of the largest slices get an outside label (「自然検索 41%」) by default. */
2630
+ const DONUT_OUTSIDE_LABELS = 2
2631
+
2632
+ const sliceValue = (value: number) => (Number.isFinite(value) && value > 0 ? value : 0)
2633
+
2634
+ /** A slice's share of `total` as text: whole percent, `<1%` for a sliver, `0%` for nothing. */
2635
+ function donutShareText(value: number, total: number): string {
2636
+ const v = sliceValue(value)
2637
+ if (total <= 0 || v === 0) return "0%"
2638
+ const pct = (v / total) * 100
2639
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
2640
+ }
2641
+
2642
+ /** One legend row: name, share text and the slice's position (for its colour). */
2643
+ interface DonutLegendItem {
2644
+ name: string
2645
+ value: number
2646
+ share: string
2647
+ isOther: boolean
2648
+ /** Index into the slices / palette. */
2649
+ slice: number
2650
+ }
2651
+
2652
+ /**
2653
+ * The donut legend: every slice with its share, largest first, the folded
2654
+ * 「その他」 last (it is a remainder, not a rank).
2655
+ */
2656
+ function donutLegendItems(slices: readonly DonutOptionSlice[]): DonutLegendItem[] {
2657
+ const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
2658
+ return slices
2659
+ .map((s, slice) => ({ name: s.name, value: sliceValue(s.value), share: donutShareText(s.value, total), isOther: Boolean(s.isOther), slice }))
2660
+ .sort((a, b) => Number(a.isOther) - Number(b.isOther) || b.value - a.value || a.slice - b.slice)
2661
+ }
2662
+
2663
+ /**
2664
+ * The default center label: what is totalled (「合計」 / "Total" in `locale`, default the page's), the formatted total
2665
+ * (`amount`, the big line), the unit (a small line under it) and both as one
2666
+ * string (`value`, 「9.2万 セッション」).
2667
+ */
2668
+ function donutCenterText(
2669
+ total: number,
2670
+ valueFormatter: (value: number) => string,
2671
+ { totalLabel, unit, locale }: { totalLabel?: string; unit?: string; locale?: string } = {},
2672
+ ): { label: string; value: string; amount: string; unit?: string } {
2673
+ totalLabel ??= chartText(locale).total
2674
+ const amount = valueFormatter(total)
2675
+ return { label: totalLabel, value: unit ? `${amount} ${unit}` : amount, amount, ...(unit ? { unit } : {}) }
2676
+ }
2677
+
2678
+ /** The ring's inner radius, in percent of the plot's shorter side / 2 — with and without outside labels. */
2679
+ const DONUT_INNER_WITH_LABELS = 50
2680
+ const DONUT_INNER_PLAIN = 72
2681
+
2682
+ /**
2683
+ * The hole's diameter as a fraction of the plot's shorter side (ECharts reads a
2684
+ * `%` radius against half of it), so an HTML center label can be sized to fit.
2685
+ */
2686
+ function donutHoleRatio(withOutsideLabels: boolean): number {
2687
+ return (withOutsideLabels ? DONUT_INNER_WITH_LABELS : DONUT_INNER_PLAIN) / 100
2688
+ }
2689
+
2690
+ interface DonutChartConfig {
2691
+ /** Slices in draw order (largest first, 「その他」 last). */
2692
+ slices: readonly DonutOptionSlice[]
2693
+ /** Resolved slice colours, by slice position. `""`/missing → theme palette. */
2694
+ palette: readonly string[]
2695
+ /** Display names for slice names (tooltip, outside labels). Missing keys show as they are. */
2696
+ labels?: Readonly<Record<string, string>>
2697
+ valueFormatter: (value: number) => string
2698
+ /** The value column's name, shown in the tooltip row. */
2699
+ valueName?: string
2700
+ variant?: DonutVariant
2701
+ showTooltip?: boolean
2702
+ /** How many of the largest (non-「その他」) slices get an outside label. Default `DONUT_OUTSIDE_LABELS` (2); 0 = none. */
2703
+ outsideLabels?: number
2704
+ /** Name of the selected slice; the others are dimmed. */
2705
+ active?: string | null
2706
+ /** Colour of the outside labels (resolved foreground). Default: the theme's text colour. */
2707
+ labelColor?: string
2708
+ reducedMotion?: boolean
2709
+ /** Deep-merged onto the generated option last. */
2710
+ chartOptions?: EChartsOption
2711
+ }
2712
+
2713
+ /** Sum of the `value` column, ignoring gaps and negative cells. */
2714
+ function donutTotal(data: readonly Record<string, unknown>[], value: string): number {
2715
+ return data.reduce((sum, row) => {
2716
+ const n = cellNumber(row[value])
2717
+ return n !== null && n > 0 ? sum + n : sum
2718
+ }, 0)
2719
+ }
2720
+
2721
+ interface ItemTooltipParam {
2722
+ name?: string
2723
+ value?: unknown
2724
+ percent?: number
2725
+ color?: unknown
2726
+ }
2727
+
2728
+ /**
2729
+ * The donut / pie option. Only the `outsideLabels` largest slices carry an
2730
+ * outside label (name + share); the legend, center label and tooltip carry the
2731
+ * rest. No entrance animation, a short ease on updates.
2732
+ */
2733
+ function buildDonutOption(cfg: DonutChartConfig): EChartsOption {
2734
+ const {
2735
+ slices,
2736
+ palette,
2737
+ labels: nameLabels,
2738
+ valueFormatter,
2739
+ valueName = "",
2740
+ variant = "donut",
2741
+ showTooltip = true,
2742
+ outsideLabels = DONUT_OUTSIDE_LABELS,
2743
+ active = null,
2744
+ labelColor,
2745
+ reducedMotion = false,
2746
+ chartOptions,
2747
+ } = cfg
2748
+ const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
2749
+ // The largest real slices, by value (the slices arrive sorted, but don't rely on it).
2750
+ const labelled = new Set(
2751
+ slices
2752
+ .map((s, i) => ({ i, v: sliceValue(s.value), other: Boolean(s.isOther) }))
2753
+ .filter((s) => !s.other && s.v > 0)
2754
+ .sort((a, b) => b.v - a.v || a.i - b.i)
2755
+ .slice(0, Math.max(0, outsideLabels))
2756
+ .map((s) => s.i),
2757
+ )
2758
+ const withLabels = labelled.size > 0
2759
+ // Room for the outside labels: the ring shrinks inside the plot.
2760
+ const outer = withLabels ? "70%" : "100%"
2761
+ const option = {
2762
+ ...chartMotion(reducedMotion),
2763
+ tooltip: {
2764
+ show: showTooltip,
2765
+ trigger: "item",
2766
+ formatter: (params: unknown) => {
2767
+ const p = params as ItemTooltipParam
2768
+ const n = cellNumber(p.value)
2769
+ const share = typeof p.percent === "number" ? ` (${p.percent.toFixed(1)}%)` : ""
2770
+ return tooltipHtml(
2771
+ `${labelOf(p.name ?? "", nameLabels)}${share}`,
2772
+ [{ name: valueName, color: typeof p.color === "string" ? p.color : "currentColor", value: n }],
2773
+ valueFormatter,
2774
+ )
2775
+ },
2776
+ },
2777
+ series: [
2778
+ {
2779
+ id: "slices",
2780
+ type: "pie",
2781
+ radius: variant === "donut" ? [`${donutHoleRatio(withLabels) * 100}%`, outer] : [0, outer],
2782
+ center: ["50%", "50%"],
2783
+ avoidLabelOverlap: true,
2784
+ // Plain text: no outline / shadow, which reads as a halo on a dark surface.
2785
+ label: {
2786
+ show: false,
2787
+ position: "outside",
2788
+ color: labelColor,
2789
+ textBorderWidth: 0,
2790
+ textBorderColor: "transparent",
2791
+ textShadowBlur: 0,
2792
+ textShadowColor: "transparent",
2793
+ },
2794
+ labelLine: { show: false, length: 8, length2: 8 },
2795
+ // A hairline gap between slices instead of a border — no background colour to match.
2796
+ padAngle: slices.length > 1 ? 1 : 0,
2797
+ itemStyle: { borderRadius: variant === "donut" ? 2 : 0 },
2798
+ emphasis: { scale: true, scaleSize: 4 },
2799
+ data: slices.map((slice, i) => ({
2800
+ name: slice.name,
2801
+ value: sliceValue(slice.value),
2802
+ itemStyle: { color: palette[i] || undefined, opacity: active !== null && active !== slice.name ? DIMMED : 1 },
2803
+ ...(labelled.has(i)
2804
+ ? {
2805
+ label: { show: true, formatter: () => `${labelOf(slice.name, nameLabels)} ${donutShareText(slice.value, total)}` },
2806
+ labelLine: { show: true },
2807
+ }
2808
+ : {}),
2809
+ })),
2810
+ },
2811
+ ],
2812
+ }
2813
+ return mergeChartOptions(option as EChartsOption, chartOptions)
2814
+ }
2815
+
2816
+ /* -------------------------------------------------------------- selection */
2817
+
2818
+ /** Toggle: clicking the active point again clears the selection. */
2819
+ function nextChartSelection(
2820
+ current: ChartActivePoint | null,
2821
+ category: string,
2822
+ index: number,
2823
+ ): ChartActivePoint | null {
2824
+ return current && current.category === category && current.index === index ? null : { category, index }
2825
+ }
2826
+
2827
+ /** What `onValueChange` receives: the clicked row plus what was clicked (ours win over row keys). */
2828
+ function chartSelectionPayload(
2829
+ selection: ChartActivePoint | null,
2830
+ data: readonly Record<string, unknown>[],
2831
+ eventType: NonNullable<ChartEventPayload>["eventType"],
2832
+ ): ChartEventPayload {
2833
+ if (!selection) return null
2834
+ return { ...data[selection.index], eventType, categoryClicked: selection.category }
2835
+ }
2836
+
2837
+ interface ChartClickParams {
2838
+ componentType?: string
2839
+ seriesName?: string
2840
+ name?: string
2841
+ dataIndex?: number
2842
+ }
2843
+
2844
+ /**
2845
+ * Click-to-select for the typed charts: the `onEvents` to hand `EChart`, and
2846
+ * the active point to dim the rest with. Inert (no handler, nothing active)
2847
+ * without `onValueChange`.
2848
+ */
2849
+ function useChartSelection(
2850
+ data: readonly Record<string, unknown>[],
2851
+ onValueChange: ((value: ChartEventPayload) => void) | undefined,
2852
+ eventType: NonNullable<ChartEventPayload>["eventType"],
2853
+ ): { active: ChartActivePoint | null; onEvents: Record<string, (params: unknown) => void> | undefined } {
2854
+ const [active, setActive] = useState<ChartActivePoint | null>(null)
2855
+ // Handlers read the latest props without re-subscribing on every render.
2856
+ const latest = useRef({ data, onValueChange, active })
2857
+ latest.current = { data, onValueChange, active }
2858
+ const interactive = onValueChange !== undefined
2859
+ const onEvents = useMemo(() => {
2860
+ if (!interactive) return undefined
2861
+ return {
2862
+ click: (raw: unknown) => {
2863
+ const p = raw as ChartClickParams
2864
+ if (p.componentType !== "series" || typeof p.dataIndex !== "number") return
2865
+ const category = eventType === "slice" ? (p.name ?? "") : (p.seriesName ?? "")
2866
+ const next = nextChartSelection(latest.current.active, category, p.dataIndex)
2867
+ latest.current.active = next
2868
+ setActive(next)
2869
+ latest.current.onValueChange?.(chartSelectionPayload(next, latest.current.data, eventType))
2870
+ },
2871
+ }
2872
+ }, [interactive, eventType])
2873
+ return { active: interactive ? active : null, onEvents }
2874
+ }
2875
+
2876
+ /**
2877
+ * Display name for `key`: `labels[key]` when present, else `key` itself.
2878
+ * (Own keys only, so `"constructor"` is not looked up on the prototype.)
2879
+ */
2880
+ function labelOf(key: string, labels?: Readonly<Record<string, string>>): string {
2881
+ return hasLabel(labels, key) ? labels![key]! : key
2882
+ }
2883
+
2884
+ /** `data` with each row's `index` cell replaced by its display name (rows are copied, not mutated). */
2885
+ function labelRows<Row extends Record<string, unknown>>(
2886
+ data: readonly Row[],
2887
+ index: string,
2888
+ labels?: Readonly<Record<string, string>>,
2889
+ ): Row[] {
2890
+ if (!labels) return data as Row[]
2891
+ return data.map((row) => ({ ...row, [index]: labelOf(String(row[index] ?? ""), labels) }))
2892
+ }
2893
+
2894
+ /** Whether `labels` renames `key` (own keys only). */
2895
+ function hasLabel(labels: Readonly<Record<string, string>> | undefined, key: string): boolean {
2896
+ return Boolean(labels) && Object.prototype.hasOwnProperty.call(labels, key)
2897
+ }
2898
+
2899
+ /* ------------------------------------------------------------ provisional */
2900
+
2901
+ /** The default label for points that are not final yet, in `locale`: "Preliminary" / 「速報」. Default the page's locale. */
2902
+ function defaultProvisionalLabel(locale?: string): string {
2903
+ return chartText(locale).provisional
2904
+ }
2905
+
2906
+ /**
2907
+ * Position of the first provisional point: the first entry of `indexValues`
2908
+ * that equals `from` (compared as text, so `"2026-09"` and a Date-less string
2909
+ * key both work). `-1` when `from` is unset or not among the values — the chart
2910
+ * then draws everything as confirmed.
2911
+ */
2912
+ function provisionalStart(indexValues: readonly unknown[], from: string | number | undefined | null): number {
2913
+ if (from === undefined || from === null) return -1
2914
+ const key = String(from)
2915
+ return indexValues.findIndex((value) => String(value ?? "") === key)
2916
+ }
2917
+
2918
+ /**
2919
+ * Split one series at `start` (see `provisionalStart`). `confirmed` keeps the
2920
+ * points before `start`; `provisional` keeps `start` onward plus the last
2921
+ * confirmed point, so the dashed line joins the solid one. `start <= 0` or
2922
+ * `-1` leaves nothing to join (all provisional / none provisional).
2923
+ */
2924
+ function splitProvisional(
2925
+ values: readonly (number | null)[],
2926
+ start: number,
2927
+ ): { confirmed: (number | null)[]; provisional: (number | null)[] } {
2928
+ if (start < 0) return { confirmed: [...values], provisional: values.map(() => null) }
2929
+ return {
2930
+ confirmed: values.map((v, i) => (i < start ? v : null)),
2931
+ provisional: values.map((v, i) => (i >= Math.max(0, start - 1) ? v : null)),
2932
+ }
2933
+ }
2934
+
2935
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
2936
+
2937
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
2938
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
2939
+
2940
+ /**
2941
+ * The attributes of a typed chart's leftover props that belong on its root
2942
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
2943
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
2944
+ */
2945
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
2946
+ const out: Record<string, unknown> = {}
2947
+ for (const [key, value] of Object.entries(rest)) {
2948
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
2949
+ }
2950
+ return out
2951
+ }
2952
+
2953
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
2954
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
2955
+ "chart-1",
2956
+ "chart-2",
2957
+ "chart-3",
2958
+ "chart-4",
2959
+ "chart-5",
2960
+ ]
2961
+
2962
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
2963
+
2964
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
2965
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
2966
+
2967
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
2968
+ function isChartTone(color: string): color is ChartTone {
2969
+ return (CHART_TONES as readonly string[]).includes(color.trim())
2970
+ }
2971
+
2972
+ /**
2973
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
2974
+ * light/dark on its own), anything else passes through unchanged.
2975
+ */
2976
+ function chartColorToCss(color: ChartColor): string {
2977
+ const value = color.trim()
2978
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
2979
+ }
2980
+
2981
+ /**
2982
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
2983
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
2984
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
2985
+ */
2986
+ function chartFillToCss(color: ChartColor): string {
2987
+ const value = color.trim()
2988
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
2989
+ }
2990
+
2991
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
2992
+ function chartFillName(color: ChartColor): ChartColor {
2993
+ const value = color.trim()
2994
+ return isChartTone(value) ? `${value}-fill` : color
2995
+ }
2996
+
2997
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
2998
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
2999
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
3000
+ return palette[i % palette.length]!
3001
+ }
3002
+
3003
+ /** `colors` extended (by cycling) to exactly `count` entries. */
3004
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
3005
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
3006
+ }
3007
+
3008
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
3009
+ function tintCss(cssColor: string, percent: number): string {
3010
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
3011
+ }
3012
+
3013
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
3014
+
3015
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
3016
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
3017
+
3018
+ /**
3019
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
3020
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
3021
+ */
3022
+ function resolveValueFormatter(
3023
+ valueFormatter: ValueFormatter | undefined,
3024
+ format: ValueFormat | undefined,
3025
+ locale?: string,
3026
+ ): ValueFormatter {
3027
+ return valueFormatter ?? toValueFormatter(format, locale)
3028
+ }
3029
+
3030
+ /**
3031
+ * The formatter of value-axis ticks and on-plot labels: an explicit
3032
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
3033
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
3034
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
3035
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
3036
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
3037
+ * currency sign and grouping.
3038
+ */
3039
+ function resolveAxisFormatter(
3040
+ valueFormatter: ValueFormatter | undefined,
3041
+ format: ValueFormat | undefined,
3042
+ localeArg?: string,
3043
+ ): ValueFormatter {
3044
+ if (valueFormatter) return valueFormatter
3045
+ const locale = resolveLocale(localeArg)
3046
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
3047
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
3048
+ const currency = "currency" in spec ? spec.currency : undefined
3049
+ const short: ValueFormat =
3050
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
3051
+ return (value) => formatValue(value, short, locale)
3052
+ }
3053
+
3054
+ interface CompactUnit {
3055
+ token: string
3056
+ size: number
3057
+ }
3058
+
3059
+ const compactUnitCache = new Map<string, CompactUnit[] | null>()
3060
+
3061
+ /**
3062
+ * The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
3063
+ * `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
3064
+ * word (`1,5 Mio.`), where a token cannot be swapped in place.
3065
+ */
3066
+ function compactUnits(locale: string): CompactUnit[] | null {
3067
+ const cached = compactUnitCache.get(locale)
3068
+ if (cached !== undefined) return cached
3069
+ let units: CompactUnit[] | null = []
3070
+ try {
3071
+ const compact = new Intl.NumberFormat(locale, { notation: "compact" })
3072
+ const seen = new Set<string>()
3073
+ for (let exp = 3; exp <= 15; exp++) {
3074
+ const parts = compact.formatToParts(10 ** exp)
3075
+ const at = parts.findIndex((p) => p.type === "compact")
3076
+ if (at === -1) continue
3077
+ if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
3078
+ units = null
3079
+ break
3080
+ }
3081
+ const token = parts[at]!.value
3082
+ if (seen.has(token)) continue
3083
+ seen.add(token)
3084
+ units.push({ token, size: 10 ** exp })
3085
+ }
3086
+ } catch {
3087
+ units = null
3088
+ }
3089
+ const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
3090
+ compactUnitCache.set(locale, sorted)
3091
+ return sorted
3092
+ }
3093
+
3094
+ const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
3095
+
3096
+ /**
3097
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
3098
+ * that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
3099
+ * `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
3100
+ * no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
3101
+ * unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
3102
+ */
3103
+ function resolveAxisTickFormatter(
3104
+ valueFormatter: ValueFormatter | undefined,
3105
+ format: ValueFormat | undefined,
3106
+ localeArg?: string,
3107
+ ): (top: number) => ValueFormatter {
3108
+ const locale = resolveLocale(localeArg)
3109
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
3110
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
3111
+ const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
3112
+ if (!units) return () => base
3113
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
3114
+ const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
3115
+ return (top) => {
3116
+ const unit = units.find((u) => Math.abs(top) >= u.size)
3117
+ if (!unit) return base
3118
+ return (value) => {
3119
+ const text = base(value)
3120
+ if (value === 0 || !Number.isFinite(value)) return text
3121
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
3122
+ return text.replace(numberToken, () => scaled)
3123
+ }
3124
+ }
3125
+ }
3126
+
3127
+ /**
3128
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
3129
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
3130
+ */
3131
+ function toChartNumber(value: unknown): number | null {
3132
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
3133
+ if (typeof value === "bigint") return Number(value)
3134
+ if (typeof value === "string" && value.trim() !== "") {
3135
+ const n = Number(value)
3136
+ return Number.isFinite(n) ? n : null
3137
+ }
3138
+ return null
3139
+ }
3140
+
3141
+ /** Clamp `value` into `[min, max]`. */
3142
+ function clamp(value: number, min: number, max: number): number {
3143
+ return Math.min(max, Math.max(min, value))
3144
+ }
3145
+
3146
+ /* ------------------------------------------------------------ aggregation */
3147
+
3148
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
3149
+ const MAX_CHART_SERIES = 5
3150
+
3151
+ /** The series name the folded categories get, by language. */
3152
+ const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
3153
+
3154
+ /** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
3155
+ function otherSeriesLabel(locale?: string): string {
3156
+ return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
3157
+ }
3158
+
3159
+ const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
3160
+
3161
+ /** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
3162
+ function isOtherName(name: string | null | undefined): boolean {
3163
+ return typeof name === "string" && OTHER_NAMES.has(name)
3164
+ }
3165
+
3166
+ interface AggregatedItems<Item extends { name: string; value: number }> {
3167
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
3168
+ top: Item[]
3169
+ /** The items folded into `other`, in their given order. */
3170
+ rest: Item[]
3171
+ /** The folded remainder, or `null` when nothing was folded. */
3172
+ other: { name: string; value: number } | null
3173
+ }
3174
+
3175
+ /**
3176
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
3177
+ * given order and fold the rest into one `otherLabel` item. Shared by every
3178
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
3179
+ * BarList rows).
3180
+ */
3181
+ function aggregateTopN<Item extends { name: string; value: number }>(
3182
+ items: readonly Item[],
3183
+ n: number = MAX_CHART_SERIES,
3184
+ otherLabel: string = otherSeriesLabel(),
3185
+ ): AggregatedItems<Item> {
3186
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
3187
+ const ranked = items
3188
+ .map((item, i) => ({ item, i }))
3189
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
3190
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
3191
+ const top = items.filter((_, i) => keep.has(i))
3192
+ const rest = items.filter((_, i) => !keep.has(i))
3193
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
3194
+ }
3195
+
3196
+ interface AggregatedSeries {
3197
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
3198
+ data: Record<string, unknown>[]
3199
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
3200
+ categories: string[]
3201
+ /** The folded series' name, or `null`. */
3202
+ otherCategory: string | null
3203
+ }
3204
+
3205
+ /**
3206
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
3207
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
3208
+ */
3209
+ function aggregateSeries(
3210
+ data: readonly Record<string, unknown>[],
3211
+ categories: readonly string[],
3212
+ n: number = MAX_CHART_SERIES,
3213
+ otherLabel: string = otherSeriesLabel(),
3214
+ ): AggregatedSeries {
3215
+ const totals = categories.map((name) => ({
3216
+ name,
3217
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
3218
+ }))
3219
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
3220
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
3221
+ const folded = rest.map((item) => item.name)
3222
+ return {
3223
+ data: data.map((row) => {
3224
+ let sum: number | null = null
3225
+ for (const name of folded) {
3226
+ const v = toChartNumber(row[name])
3227
+ if (v !== null) sum = (sum ?? 0) + v
3228
+ }
3229
+ return { ...row, [other.name]: sum }
3230
+ }),
3231
+ categories: [...top.map((item) => item.name), other.name],
3232
+ otherCategory: other.name,
3233
+ }
3234
+ }
3235
+
3236
+ /**
3237
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
3238
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
3239
+ */
3240
+ function aggregateSeriesKeeping(
3241
+ data: readonly Record<string, unknown>[],
3242
+ categories: readonly string[],
3243
+ keep: string | undefined,
3244
+ n: number = MAX_CHART_SERIES,
3245
+ otherLabel: string = otherSeriesLabel(),
3246
+ ): AggregatedSeries {
3247
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
3248
+ const aggregated = aggregateSeries(
3249
+ data,
3250
+ categories.filter((c) => c !== keep),
3251
+ n,
3252
+ otherLabel,
3253
+ )
3254
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
3255
+ }
3256
+
3257
+ /**
3258
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
3259
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
3260
+ * so a main series keeps its colour whether or not a comparison is drawn.
3261
+ */
3262
+ function seriesColorsWithComparison(
3263
+ categories: readonly string[],
3264
+ colors: ChartColors | undefined,
3265
+ otherColor: string,
3266
+ otherCategory: string | null,
3267
+ allCategories: readonly string[],
3268
+ comparison: string | undefined,
3269
+ ): string[] {
3270
+ if (comparison === undefined || !categories.includes(comparison)) {
3271
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
3272
+ }
3273
+ const main = categories.filter((c) => c !== comparison)
3274
+ const mainColors = seriesColorsFor(
3275
+ main,
3276
+ colors,
3277
+ otherColor,
3278
+ otherCategory,
3279
+ allCategories.filter((c) => c !== comparison),
3280
+ )
3281
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
3282
+ }
3283
+
3284
+ /**
3285
+ * Colour per drawn series: the record's token for that category, else the
3286
+ * array's token at the category's position in `allCategories` (cycled), else
3287
+ * the token palette by drawn position. `otherCategory` — and a category the
3288
+ * data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
3289
+ */
3290
+ function seriesColorsFor(
3291
+ categories: readonly string[],
3292
+ colors: ChartColors | undefined,
3293
+ otherColor: string,
3294
+ otherCategory: string | null = null,
3295
+ allCategories: readonly string[] = categories,
3296
+ ): string[] {
3297
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
3298
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
3299
+ return categories.map((category, i) => {
3300
+ if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
3301
+ const fromRecord = record?.[category]
3302
+ if (fromRecord) return fromRecord
3303
+ if (list && list.length > 0) {
3304
+ const at = allCategories.indexOf(category)
3305
+ return list[(at === -1 ? i : at) % list.length]!
3306
+ }
3307
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
3308
+ })
3309
+ }
3310
+
3311
+ /* ------------------------------------------------------------------ Donut */
3312
+
3313
+ /** One drawn donut slice, largest first. */
3314
+ interface DonutSlice {
3315
+ name: string
3316
+ /** Negative and missing values count as 0. */
3317
+ value: number
3318
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
3319
+ color: string
3320
+ /** The folded「その他」slice. */
3321
+ isOther: boolean
3322
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
3323
+ row: Record<string, unknown>
3324
+ }
3325
+
3326
+ interface DonutSlicesConfig {
3327
+ /** Label column. */
3328
+ index: string
3329
+ /** Value column. */
3330
+ value: string
3331
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
3332
+ colors?: readonly ChartSeriesColor[]
3333
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
3334
+ maxSlices?: number
3335
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
3336
+ otherColor: string
3337
+ otherLabel?: string
3338
+ }
3339
+
3340
+ /**
3341
+ * Donut slices: sorted by value (largest first, ties keep input order), the
3342
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
3343
+ * summed into one「その他」slice in `otherColor`.
3344
+ */
3345
+ function donutSlices(
3346
+ data: readonly Record<string, unknown>[],
3347
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
3348
+ ): DonutSlice[] {
3349
+ const items = data
3350
+ .map((row, i) => {
3351
+ const n = toChartNumber(row[value])
3352
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
3353
+ })
3354
+ .sort((a, b) => b.value - a.value || a.i - b.i)
3355
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
3356
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
3357
+ const slices: DonutSlice[] = top.map((item, rank) => ({
3358
+ name: item.name,
3359
+ value: item.value,
3360
+ // A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
3361
+ color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
3362
+ isOther: false,
3363
+ row: item.row,
3364
+ }))
3365
+ if (other) {
3366
+ slices.push({
3367
+ name: other.name,
3368
+ value: other.value,
3369
+ color: otherColor,
3370
+ isOther: true,
3371
+ row: { [index]: other.name, [value]: other.value },
3372
+ })
3373
+ }
3374
+ return slices
3375
+ }
3376
+
3377
+ /* ---------------------------------------------------------------- BarList */
3378
+
3379
+ type BarListSortOrder = "ascending" | "descending" | "none"
3380
+
3381
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
3382
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
3383
+ const rows = [...data]
3384
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
3385
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
3386
+ return rows
3387
+ }
3388
+
3389
+ /** BarList-only settings. */
3390
+ interface BarListOptions {
3391
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
3392
+ sortOrder?: BarListSortOrder
3393
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
3394
+ maxItems?: number
3395
+ /** まとめた行のラベル。既定「その他」。 */
3396
+ otherLabel?: string
3397
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
3398
+ exclude?: readonly string[]
3399
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
3400
+ showShare?: boolean
3401
+ }
3402
+
3403
+ /** One drawn BarList row. */
3404
+ interface BarListRow<Row = Record<string, unknown>> {
3405
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
3406
+ key: string
3407
+ name: string
3408
+ value: number
3409
+ /** Only for real rows; the folded row never links. */
3410
+ href?: string
3411
+ /** Legacy per-row colour (`BarListItem.color`). */
3412
+ color?: ChartColor
3413
+ /** The folded「その他」row. */
3414
+ isOther: boolean
3415
+ /** The input row (`null` for the folded row). */
3416
+ row: Row | null
3417
+ }
3418
+
3419
+ interface BarListRowsConfig extends BarListOptions {
3420
+ /** Name column. Default `"name"`. */
3421
+ index?: string
3422
+ /** Value column. Default `"value"`. */
3423
+ category?: string
3424
+ }
3425
+
3426
+ /**
3427
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
3428
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
3429
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
3430
+ * ranking and are always added to「その他」.
3431
+ */
3432
+ function barListRows<Row extends object>(
3433
+ data: readonly Row[],
3434
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
3435
+ ): BarListRow<Row>[] {
3436
+ const items = data.map((row): BarListRow<Row> => {
3437
+ const cells = row as Record<string, unknown>
3438
+ const name = String(cells[index] ?? "")
3439
+ return {
3440
+ key: typeof cells.key === "string" ? cells.key : name,
3441
+ name,
3442
+ value: toChartNumber(cells[category]) ?? 0,
3443
+ href: typeof cells.href === "string" ? cells.href : undefined,
3444
+ color: typeof cells.color === "string" ? cells.color : undefined,
3445
+ isOther: false,
3446
+ row,
3447
+ }
3448
+ })
3449
+ const excluded = new Set(exclude ?? [])
3450
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
3451
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
3452
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
3453
+ const rows = sortBarListData(top, sortOrder)
3454
+ if (other || outside.length > 0) {
3455
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
3456
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
3457
+ }
3458
+ return rows
3459
+ }
3460
+
3461
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
3462
+ function barListWidths(values: readonly number[]): number[] {
3463
+ const max = Math.max(0, ...values)
3464
+ if (max === 0) return values.map(() => 0)
3465
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
3466
+ }
3467
+
3468
+ /**
3469
+ * How strongly the BarList bars are painted: every row the same tint of the bar
3470
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
3471
+ * it sits on the card in light and dark; it must stay visible against the card
3472
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
3473
+ */
3474
+ const BAR_LIST_TINT = 45
3475
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
3476
+ const BAR_LIST_OTHER_TINT = 30
3477
+
3478
+ /**
3479
+ * The fill of each BarList row: all real rows in the same tint of `color`
3480
+ * (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
3481
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
3482
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
3483
+ * for that row. A tint, not the solid token, so the label printed over the bar
3484
+ * keeps its contrast.
3485
+ */
3486
+ function barListFills(
3487
+ rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
3488
+ color: ChartColor,
3489
+ otherColor: string,
3490
+ ): string[] {
3491
+ return rows.map((row) =>
3492
+ row.isOther || isOtherName(row.name)
3493
+ ? tintCss(otherColor, BAR_LIST_OTHER_TINT)
3494
+ : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
3495
+ )
3496
+ }
3497
+
3498
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
3499
+ function barListShareText(value: number, total: number): string {
3500
+ const v = Number.isFinite(value) && value > 0 ? value : 0
3501
+ if (total <= 0 || v === 0) return "0%"
3502
+ const pct = (v / total) * 100
3503
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
3504
+ }
3505
+
3506
+ /**
3507
+ * The text at the end of each BarList row: the formatted value and, with
3508
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
3509
+ * so the shares are of the whole list): `value` and `share` apart (the share is
3510
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
3511
+ */
3512
+ function barListValueTexts(
3513
+ values: readonly number[],
3514
+ formatter: ValueFormatter,
3515
+ showShare = false,
3516
+ ): { value: string; share?: string; text: string }[] {
3517
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
3518
+ return values.map((v) => {
3519
+ const value = formatter(v)
3520
+ if (!showShare) return { value, text: value }
3521
+ const share = barListShareText(v, total)
3522
+ return { value, share, text: `${value} · ${share}` }
3523
+ })
3524
+ }
3525
+
3526
+ /* -------------------------------------------------------------- DataTable */
3527
+
3528
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
3529
+ interface ChartDataTable {
3530
+ /** 表の見出し(`<caption>`)。 */
3531
+ caption?: string
3532
+ /** 列見出し。先頭がラベル列。 */
3533
+ columns: string[]
3534
+ /** 行。セルは書式済みの文字列。 */
3535
+ rows: string[][]
3536
+ }
3537
+
3538
+ /**
3539
+ * The chart's numbers as a table, for screen readers: one row per data row, the
3540
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
3541
+ * renames column keys for the header (`{ sessions: "セッション" }`); `indexName` is the first column's header when `labels` has none for `index` (e.g. 「項目」, instead of the raw key).
3542
+ */
3543
+ function chartDataTable(
3544
+ data: readonly Record<string, unknown>[],
3545
+ index: string,
3546
+ categories: readonly string[],
3547
+ formatter: ValueFormatter,
3548
+ labels?: Readonly<Record<string, string>>,
3549
+ indexName?: string,
3550
+ ): ChartDataTable {
3551
+ const label = (key: string) => labels?.[key] ?? key
3552
+ return {
3553
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
3554
+ rows: data.map((row) => [
3555
+ String(row[index] ?? ""),
3556
+ ...categories.map((key) => {
3557
+ const n = toChartNumber(row[key])
3558
+ return n === null ? EMPTY_VALUE : formatter(n)
3559
+ }),
3560
+ ]),
3561
+ }
3562
+ }
3563
+
3564
+ /* ------------------------------------------------------------ CategoryBar */
3565
+
3566
+ interface CategoryBarSegment {
3567
+ /** Width in percent of the whole bar. */
3568
+ width: number
3569
+ /** Where the segment starts, in percent. */
3570
+ start: number
3571
+ /** The running total at the segment's end — what its right-hand label shows. */
3572
+ end: number
3573
+ }
3574
+
3575
+ /** Lay the values side by side; negative values count as zero. */
3576
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
3577
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
3578
+ const total = clean.reduce((sum, v) => sum + v, 0)
3579
+ let running = 0
3580
+ return clean.map((v) => {
3581
+ const start = total === 0 ? 0 : (running / total) * 100
3582
+ running += v
3583
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
3584
+ })
3585
+ }
3586
+
3587
+ interface CategoryBarLabel {
3588
+ /** Position in percent of the bar. */
3589
+ position: number
3590
+ /** The running total printed there. */
3591
+ value: number
3592
+ }
3593
+
3594
+ /**
3595
+ * Tick labels under the bar: `0` at the start, then the running total at each
3596
+ * segment's end. A label closer than `minGap` percent to the one before is
3597
+ * dropped so narrow segments don't print on top of each other — except the
3598
+ * last one (the total), which replaces its neighbour instead. With a
3599
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
3600
+ * too — the marker sits right under it and the two read as one crowded spot.
3601
+ */
3602
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
3603
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
3604
+ if (segments.length === 0) return []
3605
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
3606
+ segments.forEach((s, i) => {
3607
+ const label = { position: s.start + s.width, value: s.end }
3608
+ const prev = labels[labels.length - 1]!
3609
+ if (label.position - prev.position >= minGap) labels.push(label)
3610
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
3611
+ })
3612
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
3613
+ return labels.filter(
3614
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
3615
+ )
3616
+ }
3617
+
3618
+ /**
3619
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
3620
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
3621
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
3622
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
3623
+ * the rest 7 px at 12 px type).
3624
+ */
3625
+ function categoryBarFitLabels(
3626
+ labels: readonly CategoryBarLabel[],
3627
+ texts: readonly string[],
3628
+ width: number,
3629
+ gap = 8,
3630
+ ): CategoryBarLabel[] {
3631
+ const textWidth = (text: string) => {
3632
+ let w = 0
3633
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
3634
+ return w
3635
+ }
3636
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
3637
+ const w = textWidth(text)
3638
+ if (label.position <= 0) return [0, w]
3639
+ if (label.position >= 100) return [width - w, width]
3640
+ const center = (label.position / 100) * width
3641
+ return [center - w / 2, center + w / 2]
3642
+ }
3643
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
3644
+ labels.forEach((label, i) => {
3645
+ const here = extent(label, texts[i] ?? "")
3646
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
3647
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
3648
+ else if (touches()) return
3649
+ kept.push({ label, extent: here })
3650
+ })
3651
+ return kept.map((k) => k.label)
3652
+ }
3653
+
3654
+ /** Marker position in percent of the bar, clamped to its ends. */
3655
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
3656
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
3657
+ if (total === 0) return 0
3658
+ return clamp((value / total) * 100, 0, 100)
3659
+ }
3660
+
3661
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
3662
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
3663
+ const segments = categoryBarSegments(values)
3664
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
3665
+ if (index !== -1) return index
3666
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
3667
+ return 0
3668
+ }
3669
+
3670
+ /* --------------------------------------------------------- ProgressCircle */
3671
+
3672
+ interface ProgressCircleGeometry {
3673
+ /** SVG width/height. */
3674
+ size: number
3675
+ /** Radius of the stroke's centre line. */
3676
+ normalizedRadius: number
3677
+ circumference: number
3678
+ /** `stroke-dashoffset` for the value arc. */
3679
+ offset: number
3680
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
3681
+ ratio: number
3682
+ }
3683
+
3684
+ function progressCircleGeometry(
3685
+ value: number,
3686
+ max: number,
3687
+ radius: number,
3688
+ strokeWidth: number,
3689
+ ): ProgressCircleGeometry {
3690
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
3691
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
3692
+ const circumference = 2 * Math.PI * normalizedRadius
3693
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
3694
+ }
3695
+
3696
+ /* ---------------------------------------------------------------- summary */
3697
+
3698
+ interface ChartSummaryInput {
3699
+ data: readonly Record<string, unknown>[]
3700
+ /** The x-axis key. */
3701
+ index: string
3702
+ /** Series keys; the first one is described. */
3703
+ categories: readonly string[]
3704
+ /** Title of the chart, put in front when given. */
3705
+ title?: string
3706
+ /** Same as the chart's `format` (default `"compact"`). */
3707
+ format?: ValueFormat
3708
+ /** Wins over `format`. */
3709
+ valueFormatter?: ValueFormatter
3710
+ /** Language of the sentence. Default the page's locale (`<html lang>`). */
3711
+ locale?: string
3712
+ }
3713
+
3714
+ const SUMMARY_TEXT = {
3715
+ ja: {
3716
+ up: "、前の点より増加",
3717
+ down: "、前の点より減少",
3718
+ flat: "、前の点と横ばい",
3719
+ latest: (label: string, value: string) => `最新 ${label} は ${value}`,
3720
+ top: (name: string, share: string) => `最大は ${name}(${share})`,
3721
+ },
3722
+ en: {
3723
+ up: ", up from the previous point",
3724
+ down: ", down from the previous point",
3725
+ flat: ", flat from the previous point",
3726
+ latest: (label: string, value: string) => `Latest ${label}: ${value}`,
3727
+ top: (name: string, share: string) => `Largest: ${name} (${share})`,
3728
+ },
3729
+ }
3730
+
3731
+ /**
3732
+ * One-sentence summary built from the rows, for `summary="auto"`:
3733
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
3734
+ * computed from the last two non-empty points of the first series — never
3735
+ * written by hand, so it cannot contradict the data. `undefined` when there is
3736
+ * no usable point.
3737
+ */
3738
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
3739
+ const key = input.categories[0]
3740
+ if (key === undefined) return undefined
3741
+ const points: { label: string; value: number }[] = []
3742
+ for (const row of input.data) {
3743
+ const raw = row[key]
3744
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
3745
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
3746
+ }
3747
+ const latest = points[points.length - 1]
3748
+ if (!latest) return undefined
3749
+ const locale = resolveLocale(input.locale)
3750
+ const t = SUMMARY_TEXT[uiLanguage(locale)]
3751
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
3752
+ const prev = points[points.length - 2]
3753
+ const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
3754
+ const head = input.title ? `${input.title}: ` : ""
3755
+ return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
3756
+ }
3757
+
3758
+ /**
3759
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
3760
+ * (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
3761
+ */
3762
+ function buildShareSummary(
3763
+ slices: readonly { name: string; value: number }[],
3764
+ title?: string,
3765
+ locale?: string,
3766
+ ): string | undefined {
3767
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
3768
+ const top = slices[0]
3769
+ if (!top || total <= 0) return undefined
3770
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
3771
+ return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
3772
+ }
3773
+
3774
+ /* ---------- end of inlined code ---------- */
3775
+
3776
+ // The delta note is a `graphic` text, which `EChart` does not register for the other charts.
3777
+ use([GraphicComponent])
3778
+
3779
+ /**
3780
+ * `"total"`: 合計の段を 0 からの棒として描く(既定)。`"delta"`: 増減の段だけを描く(開始を 0 とした累計増減の軸)。
3781
+ */
3782
+ export type WaterfallMode = "total" | "delta"
3783
+
3784
+ export interface WaterfallChartProps<T extends Record<string, unknown> = Record<string, unknown>>
3785
+ extends Omit<ChartCommonProps<T>, "index" | "categories" | "colors" | "summary"> {
3786
+ /** 段の名前に使う列名。行の並びがそのままグラフの左から右の順。 */
3787
+ index: keyof T & string
3788
+ /** 増減額(合計の行は合計値)の列名を 1 つだけ入れた配列(`["金額"]`)。2 つ以上渡しても最初の 1 つだけを使う。値は number か数値文字列。 */
3789
+ categories: NumericKeys<T>[]
3790
+ /**
3791
+ * 合計の段にする行の `index` の値(例 `["売上", "粗利"]`)。合計の段は 0 から累計まで届く棒で、色は `--chart-1`。
3792
+ * 合計の行の値が null なら直前までの累計になる(計算に任せるのが確実)。値があればその値が合計になり、以降の累計はそこから続く。
3793
+ * 最初の段が増減の行なら 0 から始まる。`mode="delta"` では棒にならず、先頭の行が「開始」、末尾の行が「終了」の注記になる。
3794
+ */
3795
+ totals?: string[]
3796
+ /**
3797
+ * 増えるのが良いか。`"higher-is-better"`(既定)は増加が `--positive-fill`・減少が `--negative-fill`(棒用の面のトークン)。
3798
+ * 解約数のように増えて悪い指標は `"lower-is-better"` で色が入れ替わる。`"neutral"` は増減とも `--neutral-fill`(符号は付く)。
3799
+ */
3800
+ polarity?: Polarity
3801
+ /**
3802
+ * 描き方。`"total"`(既定)は合計の段を 0 からの棒で描く。
3803
+ * `"delta"` は開始を 0 とした累計増減の軸で増減の段だけを描き、`totals` の行は棒にせず、
3804
+ * 開始・終了の値は図の上の注記(と要約・データ表)に出し、末尾に「純増」棒(増減の合計。`--chart-1`、符号つき)を足す。値軸の目盛に `+` は付かない。合計に対して増減が小さい(目安: 総額の 5% 未満)ときに使う。
3805
+ * 軸は 0 起点のまま(累計が負になる段も 0 の下に描く)。例 `mode="delta"`
3806
+ */
3807
+ mode?: WaterfallMode
3808
+ /** 段の名前(`index` の値)→ 表示名。軸・ツールチップ・データ表に反映。例 `{ cogs: "売上原価" }`。無いキーはそのまま。データ表の先頭列名を直すには `index` のキーも渡す(既定は「項目」)。 */
3809
+ labels?: Record<string, string>
3810
+ /**
3811
+ * 縦軸の下限。軸は常に 0 を含むので、0 以下の値だけ有効(累計が負になる段の下に余白を取る。正の値は無視)。
3812
+ * データが下限を下回るときは軸を広げる(切り詰めない)。`mode="total"` / `"delta"` の両方で効く。
3813
+ * 部署別などを並べて比べるときは、全部のグラフに同じ `minValue` / `maxValue` を渡して縦軸をそろえる。
3814
+ */
3815
+ minValue?: number
3816
+ /**
3817
+ * 縦軸の上限。データが上限を超えるときは軸を広げる(切り詰めない)。`mode="total"` / `"delta"` の両方で効く。
3818
+ * 並べて比べるときは、全部のグラフに同じ `minValue` / `maxValue` を渡して縦軸をそろえる。
3819
+ */
3820
+ maxValue?: number
3821
+ /** y 軸ラベルの幅(px)。並べた複数グラフのプロット領域を揃えたいときに固定する。 */
3822
+ yAxisWidth?: number
3823
+ /** 各棒に符号つきの増減額(合計は累計)を書く。既定 `true`。 */
3824
+ showValues?: boolean
3825
+ /** ホバー時のツールチップ(増減と累計)を出す。既定 `true`。 */
3826
+ showTooltip?: boolean
3827
+ /**
3828
+ * グラフが言っていることの 1 文要約(自由文)。`"auto"` なら steps から「<見出し>: <最初> <値> → <最後> <値>。最大の増加は …、最大の減少は …」を組む(`mode="delta"` は「<開始> <値> → <終了> <値>(<増減>)」)。
3829
+ * 省略時は要約なし。例: `summary="auto"`
3830
+ */
3831
+ summary?: string | "auto"
3832
+ /** 見出しが無いときのプロット領域の読み上げ名。省略時は「<金額の列>のウォーターフォールチャート」。 */
3833
+ ariaLabel?: string
3834
+ }
3835
+
3836
+ /* ------------------------------------------------------------------ model */
3837
+
3838
+ const TEXT = {
3839
+ ja: {
3840
+ net: "純増",
3841
+ total: "合計",
3842
+ change: "増減",
3843
+ cumulative: "累計",
3844
+ cumulativeChange: "累計増減",
3845
+ item: "項目",
3846
+ start: "開始",
3847
+ end: "終了",
3848
+ fromTo: (from: string, to: string, net: string) => `${from} → ${to}(${net})`,
3849
+ from: (from: string, net: string) => `${from} から ${net}`,
3850
+ to: (to: string, net: string) => `${to}(${net})`,
3851
+ netOnly: (net: string) => `増減の合計 ${net}`,
3852
+ increase: (name: string, value: string) => `最大の増加は ${name}(${value})`,
3853
+ decrease: (name: string, value: string) => `最大の減少は ${name}(${value})`,
3854
+ sentenceJoin: "。",
3855
+ chart: (label: string) => `${label}のウォーターフォールチャート`,
3856
+ },
3857
+ en: {
3858
+ net: "Net change",
3859
+ total: "Total",
3860
+ change: "Change",
3861
+ cumulative: "Cumulative",
3862
+ cumulativeChange: "Cumulative change",
3863
+ item: "Item",
3864
+ start: "Start",
3865
+ end: "End",
3866
+ fromTo: (from: string, to: string, net: string) => `${from} → ${to} (${net})`,
3867
+ from: (from: string, net: string) => `${net} from ${from}`,
3868
+ to: (to: string, net: string) => `${to} (${net})`,
3869
+ netOnly: (net: string) => `Net change ${net}`,
3870
+ increase: (name: string, value: string) => `Largest increase: ${name} (${value})`,
3871
+ decrease: (name: string, value: string) => `Largest decrease: ${name} (${value})`,
3872
+ sentenceJoin: ". ",
3873
+ chart: (label: string) => `Waterfall chart of ${label}`,
3874
+ },
3875
+ }
3876
+
3877
+ const textOf = (locale?: string) => TEXT[uiLanguage(resolveLocale(locale))]
3878
+
3879
+ export type WaterfallKind = "total" | "increase" | "decrease" | "flat" | "gap"
3880
+
3881
+ export interface WaterfallStep {
3882
+ name: string
3883
+ kind: WaterfallKind
3884
+ /** A step's signed change, a total's value. `null` for a gap. */
3885
+ value: number | null
3886
+ /** The running total before this step (a total starts at 0). */
3887
+ start: number
3888
+ /** The running total after this step. */
3889
+ end: number
3890
+ row: Record<string, unknown>
3891
+ }
3892
+
3893
+ /**
3894
+ * Rows → steps. A row named in `totals` is a total: it spans 0 → its own value,
3895
+ * or 0 → the running total when the value is missing. Every other row moves the
3896
+ * running total by its value; a missing value moves nothing (a gap).
3897
+ */
3898
+ export function waterfallSteps(
3899
+ data: readonly Record<string, unknown>[],
3900
+ config: { index: string; value: string; totals?: readonly string[]; mode?: WaterfallMode; locale?: string },
3901
+ ): WaterfallStep[] {
3902
+ const totals = new Set(config.totals ?? [])
3903
+ const delta = config.mode === "delta"
3904
+ let running = 0
3905
+ // `delta`: totals are not steps (they neither draw nor move the running change), so only the moves remain.
3906
+ const steps = (delta ? data.filter((row) => !totals.has(String(row[config.index] ?? ""))) : data).map((row) => {
3907
+ const name = String(row[config.index] ?? "")
3908
+ const n = config.value ? toChartNumber(row[config.value]) : null
3909
+ if (totals.has(name)) {
3910
+ const end = n ?? running
3911
+ running = end
3912
+ return { name, kind: "total" as const, value: end, start: 0, end, row }
3913
+ }
3914
+ if (n === null) return { name, kind: "gap" as const, value: null, start: running, end: running, row }
3915
+ const start = running
3916
+ running = start + n
3917
+ return { name, kind: n > 0 ? ("increase" as const) : n < 0 ? ("decrease" as const) : ("flat" as const), value: n, start, end: running, row }
3918
+ })
3919
+ // `delta`: the net change closes the plot as a total bar from 0 (series colour 1), so the moves add up to something.
3920
+ if (delta && steps.some((s) => s.kind !== "gap")) {
3921
+ steps.push({ name: deltaTotalName(config.locale), kind: "total", value: running, start: 0, end: running, row: {} })
3922
+ }
3923
+ return steps
3924
+ }
3925
+
3926
+ /** The name of the net-change bar that `mode="delta"` appends, in `locale` ("Net change" / 「純増」). Default the page's locale. */
3927
+ export function deltaTotalName(locale?: string): string {
3928
+ return textOf(locale).net
3929
+ }
3930
+
3931
+ /** What `mode="delta"` leaves out of the bars: the opening / closing totals and the net change of the moves. */
3932
+ export interface WaterfallDeltaEnds {
3933
+ /** The first total row when it comes before every move (its value, `null` when the row carries none). */
3934
+ opening: { name: string; value: number | null } | null
3935
+ /** The last total row when it comes after every move; a missing value is the opening plus the net change. */
3936
+ closing: { name: string; value: number | null } | null
3937
+ /** The sum of every move (the cumulative change at the last step). */
3938
+ net: number
3939
+ }
3940
+
3941
+ /** `mode="delta"`: the opening / closing totals and the net change, read from the rows (`totals` rows are not bars there). */
3942
+ export function waterfallDeltaEnds(
3943
+ data: readonly Record<string, unknown>[],
3944
+ config: { index: string; value: string; totals?: readonly string[] },
3945
+ ): WaterfallDeltaEnds {
3946
+ const totals = new Set(config.totals ?? [])
3947
+ const kinds = data.map((row) => totals.has(String(row[config.index] ?? "")))
3948
+ const firstMove = kinds.indexOf(false)
3949
+ const lastMove = kinds.lastIndexOf(false)
3950
+ const valueAt = (i: number) => (config.value ? toChartNumber(data[i]![config.value]) : null)
3951
+ const nameAt = (i: number) => String(data[i]![config.index] ?? "")
3952
+ const net = data.reduce((sum, row, i) => (kinds[i] ? sum : sum + (toChartNumber(row[config.value]) ?? 0)), 0)
3953
+ const openingAt = kinds.indexOf(true)
3954
+ const closingAt = kinds.lastIndexOf(true)
3955
+ const opening =
3956
+ openingAt !== -1 && (firstMove === -1 || openingAt < firstMove) ? { name: nameAt(openingAt), value: valueAt(openingAt) } : null
3957
+ const closingRow =
3958
+ closingAt !== -1 && closingAt !== openingAt && (lastMove === -1 || closingAt > lastMove)
3959
+ ? { name: nameAt(closingAt), value: valueAt(closingAt) }
3960
+ : null
3961
+ const closing =
3962
+ closingRow && closingRow.value === null && opening?.value != null ? { ...closingRow, value: opening.value + net } : closingRow
3963
+ return { opening, closing, net }
3964
+ }
3965
+
3966
+ /** The note above a delta plot: `前期 ¥2.2億 → 当期 ¥2.2億(+¥130万)`; without the totals' values, the net change alone. */
3967
+ export function waterfallDeltaNote(
3968
+ ends: WaterfallDeltaEnds,
3969
+ formatter: ValueFormatter,
3970
+ labels?: Record<string, string>,
3971
+ locale?: string,
3972
+ ): string {
3973
+ const t = textOf(locale)
3974
+ const net = signedText(ends.net, formatter)
3975
+ const { opening, closing } = ends
3976
+ const side = (e: { name: string; value: number | null } | null) => (e && e.value !== null ? `${labelOf(e.name, labels)} ${formatter(e.value)}` : null)
3977
+ const from = side(opening)
3978
+ const to = side(closing)
3979
+ if (from && to) return t.fromTo(from, to, net)
3980
+ if (from) return t.from(from, net)
3981
+ if (to) return t.to(to, net)
3982
+ return t.netOnly(net)
3983
+ }
3984
+
3985
+ export interface WaterfallStack {
3986
+ /** The transparent base under each bar (0 when the bar starts at the axis or crosses it). */
3987
+ base: number[]
3988
+ /** The part of each bar above 0. */
3989
+ pos: number[]
3990
+ /** The part of each bar below 0 (≤ 0). */
3991
+ neg: number[]
3992
+ /** Which series carries the step's value label. */
3993
+ labelOn: ("pos" | "neg")[]
3994
+ }
3995
+
3996
+ /**
3997
+ * Steps → the three stacked series (base, above 0, below 0). Positive and negative
3998
+ * values stack separately in ECharts, so a bar entirely in the negative needs its
3999
+ * base there too, and a bar crossing 0 has no base and a part on each side.
4000
+ */
4001
+ export function waterfallStack(steps: readonly WaterfallStep[]): WaterfallStack {
4002
+ const base: number[] = []
4003
+ const pos: number[] = []
4004
+ const neg: number[] = []
4005
+ const labelOn: ("pos" | "neg")[] = []
4006
+ for (const step of steps) {
4007
+ if (step.kind === "gap") {
4008
+ base.push(0)
4009
+ pos.push(0)
4010
+ neg.push(0)
4011
+ labelOn.push("pos")
4012
+ continue
4013
+ }
4014
+ const from = step.kind === "total" ? 0 : step.start
4015
+ const lo = Math.min(from, step.end)
4016
+ const hi = Math.max(from, step.end)
4017
+ if (lo >= 0) {
4018
+ base.push(lo)
4019
+ pos.push(hi - lo)
4020
+ neg.push(0)
4021
+ labelOn.push("pos")
4022
+ } else if (hi <= 0) {
4023
+ base.push(hi)
4024
+ pos.push(0)
4025
+ neg.push(lo - hi)
4026
+ labelOn.push("neg")
4027
+ } else {
4028
+ base.push(0)
4029
+ pos.push(hi)
4030
+ neg.push(lo)
4031
+ labelOn.push("pos")
4032
+ }
4033
+ }
4034
+ return { base, pos, neg, labelOn }
4035
+ }
4036
+
4037
+ /** The colour role of a step: totals are series colour 1, steps follow `polarity` (neutral: both directions grey). */
4038
+ export function waterfallTone(kind: WaterfallKind, polarity: Polarity = "higher-is-better"): "total" | "positive" | "negative" | "neutral" {
4039
+ if (kind === "total") return "total"
4040
+ if (kind === "gap" || kind === "flat" || polarity === "neutral") return "neutral"
4041
+ const up = kind === "increase"
4042
+ return up === (polarity === "higher-is-better") ? "positive" : "negative"
4043
+ }
4044
+
4045
+ /** `+600` / `−600` (U+2212) through `formatter`; zero has no sign. */
4046
+ export function signedText(value: number, formatter: ValueFormatter): string {
4047
+ if (value > 0) return `+${formatter(value)}`
4048
+ if (value < 0) return `${MINUS_SIGN}${formatter(-value)}`
4049
+ return formatter(0)
4050
+ }
4051
+
4052
+ /** The text on a step's bar: a signed change, a total as is, 「—」 for a gap. */
4053
+ export function waterfallStepText(step: WaterfallStep, formatter: ValueFormatter, delta = false): string {
4054
+ if (step.value === null) return EMPTY_VALUE
4055
+ // `delta`: the closing total is the net change, so it carries a sign like the moves it sums.
4056
+ return step.kind === "total" && !delta ? formatter(step.value) : signedText(step.value, formatter)
4057
+ }
4058
+
4059
+ /** `summary="auto"`: first → last level and the largest increase / decrease. `undefined` with no usable step. */
4060
+ export function buildWaterfallSummary(
4061
+ steps: readonly WaterfallStep[],
4062
+ formatter: ValueFormatter,
4063
+ title?: string,
4064
+ labels?: Record<string, string>,
4065
+ delta?: WaterfallDeltaEnds,
4066
+ locale?: string,
4067
+ ): string | undefined {
4068
+ const t = textOf(locale)
4069
+ const real = steps.filter((s) => s.kind !== "gap")
4070
+ const first = real[0]
4071
+ const last = real[real.length - 1]
4072
+ if (!first || !last) return undefined
4073
+ const name = (s: WaterfallStep) => labelOf(s.name, labels)
4074
+ const head = title ? `${title}: ` : ""
4075
+ // A first step starts at 0, so its end is its value; a total's end is the total. `delta`: the note (totals and net change) instead.
4076
+ const parts = [
4077
+ delta
4078
+ ? waterfallDeltaNote(delta, formatter, labels, locale)
4079
+ : real.length === 1
4080
+ ? `${name(first)} ${formatter(first.end)}`
4081
+ : `${name(first)} ${formatter(first.end)} → ${name(last)} ${formatter(last.end)}`,
4082
+ ]
4083
+ let up: WaterfallStep | undefined
4084
+ let down: WaterfallStep | undefined
4085
+ for (const s of real) {
4086
+ if (s.kind === "increase" && (!up || s.value! > up.value!)) up = s
4087
+ if (s.kind === "decrease" && (!down || s.value! < down.value!)) down = s
4088
+ }
4089
+ if (up) parts.push(t.increase(name(up), signedText(up.value!, formatter)))
4090
+ if (down) parts.push(t.decrease(name(down), signedText(down.value!, formatter)))
4091
+ return `${head}${parts.join(t.sentenceJoin)}`
4092
+ }
4093
+
4094
+ /** The screen-reader table: one row per step with its change and the running total. */
4095
+ export function waterfallDataTable(
4096
+ steps: readonly WaterfallStep[],
4097
+ names: { index: string; value: string },
4098
+ formatter: ValueFormatter,
4099
+ labels?: Record<string, string>,
4100
+ delta?: WaterfallDeltaEnds,
4101
+ locale?: string,
4102
+ ): ChartDataTable {
4103
+ const t = textOf(locale)
4104
+ const label = (key: string) => labelOf(key, labels)
4105
+ const rows = steps.map((s) => [
4106
+ label(s.name),
4107
+ s.kind === "total" ? (delta ? t.net : t.total) : s.value === null ? EMPTY_VALUE : signedText(s.value, formatter),
4108
+ s.kind === "gap" ? EMPTY_VALUE : delta ? signedText(s.end, formatter) : formatter(s.end),
4109
+ ])
4110
+ // `delta`: the totals are not bars, so the opening / closing values are rows of their own (they are not in `steps`).
4111
+ const end = (e: WaterfallDeltaEnds["opening"], role: string) =>
4112
+ e && e.value !== null ? [[label(e.name), role, formatter(e.value)]] : []
4113
+ return {
4114
+ columns: [labels?.[names.index] ?? t.item, t.change, delta ? t.cumulativeChange : t.cumulative],
4115
+ rows: delta ? [...end(delta.opening, t.start), ...rows, ...end(delta.closing, t.end)] : rows,
4116
+ }
4117
+ }
4118
+
4119
+ /* ----------------------------------------------------------------- option */
4120
+
4121
+ export interface WaterfallOptionConfig {
4122
+ steps: readonly WaterfallStep[]
4123
+ /** Resolved (canvas-safe) colours; `""` leaves the theme palette. */
4124
+ colors: { total: string; positive: string; negative: string; neutral: string }
4125
+ polarity?: Polarity
4126
+ labels?: Record<string, string>
4127
+ /** Tooltip and value labels. */
4128
+ valueFormatter: ValueFormatter
4129
+ /** Value-axis ticks (short form). */
4130
+ axisFormatter?: ValueFormatter
4131
+ showValues?: boolean
4132
+ showTooltip?: boolean
4133
+ labelColor?: string
4134
+ /** The plot's width (px), when known: every step name is shown (wrapped into its share, or tilted when narrow) and value labels that would collide are thinned. */
4135
+ plotWidth?: number | null
4136
+ chartOptions?: EChartsOption
4137
+ /** Value-axis limits (see `WaterfallChartProps`): the axis always reaches 0 and widens to the data. */
4138
+ minValue?: number
4139
+ maxValue?: number
4140
+ /** The value axis' label width (px); fixes the plot's left edge so stacked charts line up. */
4141
+ yAxisWidth?: number
4142
+ /** `"delta"`: only the moves are bars, the axis is the signed cumulative change, and `deltaNote` prints above the plot. */
4143
+ mode?: WaterfallMode
4144
+ /** `mode="delta"`: the note printed above the plot (opening → closing and the net change), and the signed value axis. */
4145
+ deltaNote?: string
4146
+ /** Text colour for the note (the muted token). */
4147
+ noteColor?: string
4148
+ /** Colour of the 1px line joining the bars' tops (the border token). `undefined` draws no connector. */
4149
+ connectorColor?: string
4150
+ /** Language of the tooltip. Default the page's locale (`<html lang>`). */
4151
+ locale?: string
4152
+ }
4153
+
4154
+ /** The bar fills 45% of its category band. ECharts reads `barCategoryGap` as a share of the band (not of the bar), so the gap is the other 55%; a gap over 100% leaves the bar at its 1px minimum. */
4155
+ const WATERFALL_BAR_SHARE = 0.45
4156
+ const WATERFALL_BAR_GAP = `${Math.round((1 - WATERFALL_BAR_SHARE) * 100)}%`
4157
+
4158
+ /** The area tokens one step lighter: the same colour at 75% over the surface (light and dark alike). */
4159
+ export function waterfallSoftFill(color: string): string {
4160
+ return color ? withAlpha(color, 0.75) : color
4161
+ }
4162
+
4163
+ /**
4164
+ * The 1px lines that join the tops of consecutive bars: [step index, level] per link. A link needs two real bars
4165
+ * that meet at the same level (a gap, or a total whose own value breaks the running level, is not joined).
4166
+ */
4167
+ export function waterfallConnectors(steps: readonly WaterfallStep[]): [number, number][] {
4168
+ const links: [number, number][] = []
4169
+ for (let i = 0; i < steps.length - 1; i++) {
4170
+ const a = steps[i]!
4171
+ const b = steps[i + 1]!
4172
+ if (a.kind === "gap" || b.kind === "gap") continue
4173
+ const meets = b.kind === "total" ? b.end === a.end : b.start === a.end
4174
+ if (meets) links.push([i, a.end])
4175
+ }
4176
+ return links
4177
+ }
4178
+
4179
+ /** The value-tick column and the grid's left / right margins, px: what the steps do not get of the plot's width. */
4180
+ const WATERFALL_GUTTER = 60 + 20
4181
+
4182
+ /** The width (px) each step gets: the plot less the tick column and margins, shared by the steps. */
4183
+ export function stepSlotWidth(plotWidth: number, steps: number): number {
4184
+ return Math.max(1, Math.floor((plotWidth - WATERFALL_GUTTER) / Math.max(1, steps)))
4185
+ }
4186
+
4187
+ /** Below this slot (px) a step name no longer wraps into a readable column (under 3 full-width characters): it is tilted instead. */
4188
+ const STEP_LABEL_MIN_SLOT = 44
4189
+
4190
+ /** Width (px) for a step's axis label: its slot less a gap. */
4191
+ export function stepLabelWidth(plotWidth: number, steps: number): number {
4192
+ return Math.max(24, stepSlotWidth(plotWidth, steps) - 8)
4193
+ }
4194
+
4195
+ /**
4196
+ * How the step names sit on the axis at a plot width: wrapped into the step's slot when it fits a few
4197
+ * characters, otherwise tilted (and not wrapped) so every name stays readable and none is dropped.
4198
+ */
4199
+ export function stepLabelLayout(plotWidth: number, steps: number): { width: number; rotate: 0 } | { rotate: 45 } {
4200
+ return stepSlotWidth(plotWidth, steps) >= STEP_LABEL_MIN_SLOT
4201
+ ? { width: stepLabelWidth(plotWidth, steps), rotate: 0 }
4202
+ : { rotate: 45 }
4203
+ }
4204
+
4205
+ /**
4206
+ * Which steps print their value on the bar at a plot width. Every label stays when they fit side by side;
4207
+ * on a narrow plot the neighbours that would print over each other are dropped (the tooltip and the table still
4208
+ * carry them): totals first, then the largest moves, each kept only if it clears the labels already kept.
4209
+ * A decrease is never dropped: its label sits under its bar (away from the increases' labels above), and a decrease
4210
+ * that would touch the previous decrease's label steps down a line (see `buildWaterfallOption`).
4211
+ * `plotWidth` unknown → all shown.
4212
+ */
4213
+ export function waterfallValueLabelPlan(
4214
+ steps: readonly WaterfallStep[],
4215
+ texts: readonly string[],
4216
+ plotWidth?: number | null,
4217
+ ): boolean[] {
4218
+ const show = steps.map((s) => s.kind !== "gap")
4219
+ if (!plotWidth) return show
4220
+ const slot = stepSlotWidth(plotWidth, steps.length)
4221
+ const kept: { center: number; half: number }[] = []
4222
+ const order = steps
4223
+ .map((_, i) => i)
4224
+ .filter((i) => show[i])
4225
+ .sort((a, b) => {
4226
+ const rank = (i: number) => (steps[i]!.kind === "total" ? 0 : 1)
4227
+ return rank(a) - rank(b) || Math.abs(steps[b]!.value ?? 0) - Math.abs(steps[a]!.value ?? 0) || a - b
4228
+ })
4229
+ for (const i of order) {
4230
+ // Labels above a bar and labels under a bar never meet, so only the same side competes; decreases stay.
4231
+ if (steps[i]!.kind === "decrease") continue
4232
+ const center = (i + 0.5) * slot
4233
+ const half = (estimateTextWidth(texts[i] ?? "") + 6) / 2
4234
+ if (kept.some((k) => Math.abs(k.center - center) < k.half + half)) show[i] = false
4235
+ else kept.push({ center, half })
4236
+ }
4237
+ return show
4238
+ }
4239
+
4240
+ /** Gap (px) between a decrease label and the bar it hangs under; a stepped-down label adds one line. */
4241
+ const DECREASE_LABEL_DISTANCE = 4
4242
+ const DECREASE_LABEL_LINE = 14
4243
+
4244
+ /**
4245
+ * Where each decrease prints its value: under its bar (`"bottom"`), or — when the bar ends on the axis, where the step
4246
+ * names are — above it (`"top"`). `lineDown` steps a label that would touch the previous decrease's label down one line.
4247
+ */
4248
+ export function waterfallDecreaseLabels(
4249
+ steps: readonly WaterfallStep[],
4250
+ texts: readonly string[],
4251
+ plotWidth?: number | null,
4252
+ ): { position: "top" | "bottom"; lineDown: boolean }[] {
4253
+ const top = Math.max(1, ...steps.map((s) => Math.abs(s.end)), ...steps.map((s) => Math.abs(s.start)))
4254
+ const slot = plotWidth ? stepSlotWidth(plotWidth, steps.length) : null
4255
+ let prev: { index: number; half: number; down: boolean } | null = null
4256
+ return steps.map((step, i) => {
4257
+ if (step.kind !== "decrease") return { position: "top", lineDown: false }
4258
+ const lo = Math.min(step.start, step.end)
4259
+ // A bar whose foot is within 8% of the axis' span of the 0 line has no room under it.
4260
+ const position = lo >= 0 && lo / top < 0.08 ? ("top" as const) : ("bottom" as const)
4261
+ const half = (estimateTextWidth(texts[i] ?? "") + 6) / 2
4262
+ let lineDown = false
4263
+ if (slot && position === "bottom" && prev && (i - prev.index) * slot < prev.half + half) lineDown = !prev.down
4264
+ prev = position === "bottom" ? { index: i, half, down: lineDown } : prev
4265
+ return { position, lineDown }
4266
+ })
4267
+ }
4268
+
4269
+ /** The `renderItem` of the connectors: a 1px line from the right edge of one bar to the left edge of the next, at the level they share. */
4270
+ export function waterfallConnectorRenderer(color: string | undefined) {
4271
+ type Api = { value(dim: number): number; coord(value: number[]): number[]; size(value: number[]): number[] }
4272
+ return (_params: unknown, api: Api) => {
4273
+ const [x = 0, y = 0] = api.coord([api.value(0), api.value(1)])
4274
+ const band = Math.abs(api.size([1, 0])[0] ?? 0)
4275
+ const half = (band * WATERFALL_BAR_SHARE) / 2
4276
+ // Snap to the pixel grid so the 1px line stays crisp.
4277
+ const at = Math.round(y) + 0.5
4278
+ return {
4279
+ type: "line" as const,
4280
+ silent: true,
4281
+ shape: { x1: x + half, y1: at, x2: x + band - half, y2: at },
4282
+ style: { stroke: color, lineWidth: 1, fill: "none" },
4283
+ }
4284
+ }
4285
+ }
4286
+
4287
+ const ROW_STYLE = "display:flex;align-items:center;gap:8px;line-height:20px"
4288
+
4289
+ /** The ECharts option: a transparent base plus the part above and below 0, coloured per step. */
4290
+ export function buildWaterfallOption(config: WaterfallOptionConfig): EChartsOption {
4291
+ const { steps, colors, polarity, labels, valueFormatter, showValues = true, showTooltip = true } = config
4292
+ const t = textOf(config.locale)
4293
+ const delta = config.mode === "delta"
4294
+ const axisFormatter = config.axisFormatter ?? valueFormatter
4295
+ const noteWidth = config.plotWidth ? Math.max(120, config.plotWidth - 16) : undefined
4296
+ const noteLines = delta && config.deltaNote ? Math.min(3, noteWidth ? Math.ceil(estimateTextWidth(config.deltaNote) / noteWidth) : 1) : 0
4297
+ const gridTop = 28 + (noteLines > 0 ? 6 + noteLines * 16 : 0)
4298
+ const hasNegative = delta && steps.some((s) => s.kind !== "gap" && Math.min(s.start, s.end) < 0)
4299
+ const stack = waterfallStack(steps)
4300
+ const stepTexts = steps.map((step) => waterfallStepText(step, valueFormatter, delta))
4301
+ const valueShown = waterfallValueLabelPlan(steps, stepTexts, config.plotWidth)
4302
+ const decreaseLabels = waterfallDecreaseLabels(steps, stepTexts, config.plotWidth)
4303
+ // A decrease prints under its bar (on the below-0 part when the bar reaches below 0); every other step above its bar.
4304
+ const labelSeries = (step: WaterfallStep, i: number): "pos" | "neg" =>
4305
+ step.kind === "decrease" && Math.min(step.start, step.end) < 0 ? "neg" : stack.labelOn[i]!
4306
+ const colorOf = (step: WaterfallStep) => colors[waterfallTone(step.kind, polarity)] || undefined
4307
+ const series = (id: "pos" | "neg") => ({
4308
+ id,
4309
+ type: "bar" as const,
4310
+ stack: "waterfall",
4311
+ barCategoryGap: WATERFALL_BAR_GAP,
4312
+ data: steps.map((step, i) => {
4313
+ const decrease = decreaseLabels[i]!
4314
+ const isDecrease = step.kind === "decrease"
4315
+ return {
4316
+ value: stack[id][i],
4317
+ itemStyle: { color: colorOf(step), borderRadius: 2 },
4318
+ label: {
4319
+ show: showValues && valueShown[i] === true && labelSeries(step, i) === id,
4320
+ position: isDecrease ? decrease.position : id === "pos" ? ("top" as const) : ("bottom" as const),
4321
+ distance: isDecrease && decrease.position === "bottom" ? DECREASE_LABEL_DISTANCE + (decrease.lineDown ? DECREASE_LABEL_LINE : 0) : undefined,
4322
+ formatter: () => waterfallStepText(step, valueFormatter, delta),
4323
+ },
4324
+ }
4325
+ }),
4326
+ label: { show: false, color: config.labelColor, fontVariantNumeric: "tabular-nums" },
4327
+ // The 0 line is the start: with moves below it, draw it once on the first series so the two sides read as gain / loss.
4328
+ ...(hasNegative && id === "pos"
4329
+ ? {
4330
+ markLine: {
4331
+ silent: true,
4332
+ symbol: "none",
4333
+ animation: false,
4334
+ label: { show: false },
4335
+ lineStyle: { type: "solid" as const, width: 1, color: config.noteColor, opacity: 0.6 },
4336
+ data: [{ yAxis: 0 }],
4337
+ },
4338
+ }
4339
+ : {}),
4340
+ })
4341
+ const limits = valueAxisLimits({ minValue: config.minValue, maxValue: config.maxValue }, true)
4342
+ const option = {
4343
+ ...chartMotion(false),
4344
+ legend: { show: false },
4345
+ grid: { top: gridTop, right: 16, bottom: 4, left: 4, containLabel: true },
4346
+ ...(noteLines > 0
4347
+ ? {
4348
+ graphic: [
4349
+ {
4350
+ type: "text" as const,
4351
+ left: 4,
4352
+ top: 0,
4353
+ silent: true,
4354
+ style: { text: config.deltaNote, fill: config.noteColor, fontSize: 12, lineHeight: 16, ...(noteWidth ? { width: noteWidth, overflow: "break" as const } : {}) },
4355
+ },
4356
+ ],
4357
+ }
4358
+ : {}),
4359
+ tooltip: {
4360
+ show: showTooltip,
4361
+ trigger: "axis",
4362
+ axisPointer: { type: "shadow" },
4363
+ formatter: (params: unknown) => {
4364
+ const list = (Array.isArray(params) ? params : [params]) as { dataIndex?: number }[]
4365
+ const step = steps[list[0]?.dataIndex ?? 0]
4366
+ if (!step) return ""
4367
+ const color = escapeHtml(colorOf(step) ?? "currentColor")
4368
+ const line = (name: string, text: string) =>
4369
+ `<div style="${ROW_STYLE}"><span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${color}"></span>` +
4370
+ `<span style="flex:1;opacity:.8">${escapeHtml(name)}</span>` +
4371
+ `<span style="font-weight:500;font-variant-numeric:tabular-nums;margin-left:12px">${escapeHtml(text)}</span></div>`
4372
+ const rows =
4373
+ step.kind === "total"
4374
+ ? line(delta ? t.net : t.total, delta ? signedText(step.end, valueFormatter) : valueFormatter(step.end))
4375
+ : line(t.change, waterfallStepText(step, valueFormatter)) +
4376
+ (step.kind === "gap"
4377
+ ? ""
4378
+ : delta
4379
+ ? line(t.cumulativeChange, signedText(step.end, valueFormatter))
4380
+ : line(t.cumulative, valueFormatter(step.end)))
4381
+ return `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(labelOf(step.name, labels))}</div>${rows}`
4382
+ },
4383
+ },
4384
+ xAxis: {
4385
+ type: "category" as const,
4386
+ data: steps.map((s) => s.name),
4387
+ axisTick: { show: false },
4388
+ // A negative cumulative change draws below 0: the names stay at the bottom edge, not on the 0 line.
4389
+ ...(hasNegative ? { axisLine: { onZero: false } } : {}),
4390
+ // Every step name stays (a dropped name makes a bar unreadable): wrapped into the step's share of the
4391
+ // plot, or tilted when the share is too narrow to wrap into.
4392
+ axisLabel: {
4393
+ interval: 0,
4394
+ hideOverlap: false,
4395
+ formatter: (value: string) => labelOf(value, labels),
4396
+ ...(config.plotWidth ? { ...stepLabelLayout(config.plotWidth, steps.length), overflow: "break" as const } : {}),
4397
+ },
4398
+ },
4399
+ yAxis: {
4400
+ type: "value" as const,
4401
+ ...(config.minValue !== undefined || config.maxValue !== undefined ? limits : {}),
4402
+ axisLine: { show: false },
4403
+ axisTick: { show: false },
4404
+ splitLine: { show: true },
4405
+ axisLabel: {
4406
+ // Ticks are unsigned: the sign belongs to the bar labels, not the axis.
4407
+ formatter: (v: number) => axisFormatter(v),
4408
+ // A fixed width lines up side-by-side plots, but a value tick is never cut: the grid contains it.
4409
+ width: config.yAxisWidth,
4410
+ },
4411
+ },
4412
+ series: [
4413
+ {
4414
+ id: "base",
4415
+ type: "bar" as const,
4416
+ stack: "waterfall",
4417
+ silent: true,
4418
+ barCategoryGap: WATERFALL_BAR_GAP,
4419
+ itemStyle: { color: "transparent", borderColor: "transparent" },
4420
+ emphasis: { disabled: true },
4421
+ data: stack.base,
4422
+ },
4423
+ series("pos"),
4424
+ series("neg"),
4425
+ {
4426
+ id: "connectors",
4427
+ type: "custom" as const,
4428
+ silent: true,
4429
+ z: 1,
4430
+ tooltip: { show: false },
4431
+ emphasis: { disabled: true },
4432
+ // Every link is [step index, level]; the value axis already reaches each level (they are the bars' own ends).
4433
+ encode: { x: 0, y: 1 },
4434
+ data: waterfallConnectors(steps),
4435
+ renderItem: waterfallConnectorRenderer(config.connectorColor),
4436
+ },
4437
+ ],
4438
+ }
4439
+ return mergeChartOptions(option as EChartsOption, config.chartOptions)
4440
+ }
4441
+
4442
+ /* -------------------------------------------------------------- component */
4443
+
4444
+ /** Rows not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
4445
+ const NO_ROWS: never[] = []
4446
+
4447
+ function WaterfallChartImpl<T extends Record<string, unknown>>(
4448
+ {
4449
+ data = NO_ROWS,
4450
+ index,
4451
+ categories = NO_ROWS,
4452
+ totals,
4453
+ mode = "total",
4454
+ polarity = "higher-is-better",
4455
+ labels,
4456
+ format,
4457
+ valueFormatter: valueFormatterProp,
4458
+ showValues = true,
4459
+ showTooltip = true,
4460
+ title,
4461
+ summary,
4462
+ actions,
4463
+ fileName,
4464
+ isLoading,
4465
+ emptyState,
4466
+ height,
4467
+ chartOptions,
4468
+ minValue,
4469
+ maxValue,
4470
+ yAxisWidth,
4471
+ ariaLabel,
4472
+ className,
4473
+ ...rest
4474
+ }: WaterfallChartProps<T>,
4475
+ ref: ForwardedRef<HTMLDivElement>,
4476
+ ) {
4477
+ const valueKey: string = categories[0] ?? ""
4478
+ const { ref: frameRef, width: plotWidth, tokens } = useChartSurface(ref)
4479
+ // Value labels and the tooltip read in full (as `format` says); ticks read short.
4480
+ const locale = useLocale()
4481
+ const valueFormatter = useMemo(() => resolveValueFormatter(valueFormatterProp, format, locale), [valueFormatterProp, format, locale])
4482
+ const axisFormatter = useMemo(() => resolveAxisFormatter(valueFormatterProp, format, locale), [valueFormatterProp, format, locale])
4483
+ const steps = useMemo(
4484
+ () => waterfallSteps(data, { index, value: valueKey, totals, mode, locale }),
4485
+ [data, index, valueKey, totals, mode, locale],
4486
+ )
4487
+ const ends = useMemo(() => (mode === "delta" ? waterfallDeltaEnds(data, { index, value: valueKey, totals }) : undefined), [data, index, valueKey, totals, mode])
4488
+ const deltaNote = useMemo(() => (ends ? waterfallDeltaNote(ends, valueFormatter, labels, locale) : undefined), [ends, valueFormatter, labels, locale])
4489
+ const colors = useMemo(() => {
4490
+ const fills = resolveFillColors(tokens)
4491
+ const [total = ""] = resolveChartColors(["chart-1"], tokens)
4492
+ // The area tokens one step lighter, so the bars stay quieter than the numbers on them.
4493
+ return {
4494
+ total,
4495
+ positive: waterfallSoftFill(fills.positive),
4496
+ negative: waterfallSoftFill(fills.negative),
4497
+ neutral: waterfallSoftFill(fills.neutral),
4498
+ }
4499
+ }, [tokens])
4500
+ const option = useMemo(
4501
+ () =>
4502
+ buildWaterfallOption({
4503
+ steps,
4504
+ colors,
4505
+ polarity,
4506
+ labels,
4507
+ valueFormatter,
4508
+ axisFormatter,
4509
+ showValues,
4510
+ showTooltip,
4511
+ labelColor: tokens?.foreground ?? undefined,
4512
+ noteColor: tokens?.mutedForeground ?? undefined,
4513
+ connectorColor: tokens?.border ?? undefined,
4514
+ mode,
4515
+ deltaNote,
4516
+ plotWidth,
4517
+ chartOptions,
4518
+ minValue,
4519
+ maxValue,
4520
+ yAxisWidth,
4521
+ locale,
4522
+ }),
4523
+ [steps, colors, polarity, labels, valueFormatter, axisFormatter, showValues, showTooltip, tokens, mode, deltaNote, plotWidth, chartOptions, minValue, maxValue, yAxisWidth, locale],
4524
+ )
4525
+ const dataTable = useMemo(
4526
+ () => waterfallDataTable(steps, { index, value: valueKey }, valueFormatter, labels, ends, locale),
4527
+ [steps, index, valueKey, valueFormatter, labels, ends, locale],
4528
+ )
4529
+ const resolvedSummary = useMemo(
4530
+ () => (summary === "auto" ? buildWaterfallSummary(steps, valueFormatter, title, labels, ends, locale) : summary),
4531
+ [summary, steps, valueFormatter, title, labels, ends, locale],
4532
+ )
4533
+ const t = textOf(locale)
4534
+ const label = ariaLabel ?? t.chart(labelOf(valueKey, labels) || t.change.toLowerCase())
4535
+ return (
4536
+ <ChartFrame
4537
+ {...chartRootProps(rest)}
4538
+ ref={frameRef}
4539
+ title={title}
4540
+ summary={resolvedSummary}
4541
+ isLoading={isLoading ?? false}
4542
+ isEmpty={data.length === 0}
4543
+ emptyState={emptyState}
4544
+ height={height}
4545
+ variant="bar"
4546
+ ariaLabel={label}
4547
+ className={className}
4548
+ dataTable={dataTable}
4549
+ >
4550
+ <EChart option={option} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
4551
+ </ChartFrame>
4552
+ )
4553
+ }
4554
+
4555
+ /** Generic over the row type, so `index` / `categories` keys are checked against `data`. */
4556
+ export const WaterfallChart = forwardRef(WaterfallChartImpl as (props: WaterfallChartProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
4557
+ T extends Record<string, unknown>,
4558
+ >(
4559
+ props: WaterfallChartProps<T> & { ref?: Ref<HTMLDivElement> },
4560
+ ) => ReactElement) & { displayName?: string }
4561
+ WaterfallChart.displayName = "WaterfallChart"