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