@squadbase/vantage 0.6.1 → 0.6.2-dev1.0010f67

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