@squadbase/vantage 0.6.2 → 0.7.0-dev1.3b0e616

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