@squadbase/vantage 0.6.2-dev1.9612525 → 0.6.2-dev1.9d7130b

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