@squadbase/vantage 0.6.2-dev1.a7c4a3e → 0.6.2-dev1.a881d95

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