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

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