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