@squadbase/vantage 0.6.2-dev1.b332e5a → 0.6.2-dev1.bcb51d1

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