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

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