@squadbase/vantage 0.6.1 → 0.6.2-dev1.0017a4d

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