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