@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.5aae04e

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