@squadbase/vantage 0.6.2-dev1.ac99e02 → 0.6.2-dev1.b1f45c0

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