@squadbase/vantage 0.6.2-stg.3a2ba98 → 0.7.0-dev1.275b4ed

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