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

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