@squadbase/vantage 0.6.2-dev2.5e7a250 → 0.6.2-dev2.b5837f0

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