@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.81c1bbe

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