@squadbase/vantage 0.6.2-dev1.9d91dda → 0.6.2-dev1.abc3f77

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