@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,1358 @@
1
+ // Copied by `vantage add ui chart-frame`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/charts/chart-frame.tsx by `npm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * ChartFrame — the frame every typed chart renders in: an optional title and a
7
+ * one-sentence summary above a plot area of fixed height. The plot is labelled
8
+ * by the title and described by the summary, so a screen reader hears what the
9
+ * chart says, not just that there is one.
10
+ *
11
+ * The plot area is the frame's one `role="img"` (`EChart` inside it drops its
12
+ * own); `dataTable` adds the numbers as a visually-hidden table beside it, so a
13
+ * screen reader can read the values the canvas only draws.
14
+ *
15
+ * The plot area keeps its height in every state: while loading it shows a
16
+ * skeleton shaped like the final chart, and with no data it says so (and offers
17
+ * one action) instead of drawing empty axes.
18
+ */
19
+ import { forwardRef, useId, type HTMLAttributes, type ReactNode } from "react"
20
+
21
+ import { cn } from "@squadbase/vantage/ui"
22
+ import type { ChartEmptyState } from "@squadbase/vantage/components"
23
+ import { createContext, useCallback, useEffect, useRef, useState, type ForwardedRef } from "react"
24
+ import type { ChartTone } from "@squadbase/vantage/components"
25
+ import { DEFAULT_LOCALE, EMPTY_VALUE, formatValue, toValueFormatter, type ValueFormat } from "@squadbase/vantage/components"
26
+ import type { ChartColor, ChartColors, ChartSeriesColor, ValueFormatter } from "@squadbase/vantage/components"
27
+
28
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
29
+
30
+ /**
31
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
32
+ * grey is defined — every chart takes it from here. It is the most subdued
33
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
34
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
35
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
36
+ * slice. Canvas charts resolve it through `resolveChartColors`.
37
+ */
38
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
39
+
40
+ /**
41
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
42
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
43
+ */
44
+ const ChartFrameContext = createContext(false)
45
+
46
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
47
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
48
+
49
+ interface ChartTokens {
50
+ /** Resolved `--chart-1..5`, in order. */
51
+ series: string[]
52
+ /** Body text: titles and the default `textStyle`. */
53
+ foreground: string | null
54
+ /** Secondary text: axis labels, legend, subtitles. */
55
+ mutedForeground: string | null
56
+ /** Axis lines, ticks, split lines, tooltip border. */
57
+ border: string | null
58
+ /** Tooltip surface. */
59
+ popover: string | null
60
+ /** Tooltip text. */
61
+ popoverForeground: string | null
62
+ }
63
+
64
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
65
+
66
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
67
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
68
+
69
+ /**
70
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
71
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
72
+ * input is written over two different known colours: agreeing results mean the
73
+ * value parsed, differing ones mean it was dropped.
74
+ */
75
+ function toCanvasColor(value: string): string | null {
76
+ const raw = value.trim()
77
+ if (!raw) return null
78
+ if (normalizeContext === undefined) {
79
+ const canvas = document.createElement("canvas")
80
+ canvas.width = 1
81
+ canvas.height = 1
82
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
83
+ }
84
+ const ctx = normalizeContext
85
+ if (!ctx) return raw
86
+ ctx.fillStyle = "#000000"
87
+ ctx.fillStyle = raw
88
+ const onBlack = ctx.fillStyle
89
+ ctx.fillStyle = "#ffffff"
90
+ ctx.fillStyle = raw
91
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
92
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
93
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
94
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
95
+ ctx.clearRect(0, 0, 1, 1)
96
+ ctx.fillRect(0, 0, 1, 1)
97
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
98
+ return a === 255
99
+ ? `rgb(${r}, ${g}, ${b})`
100
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
101
+ }
102
+
103
+ /**
104
+ * Read the chart tokens off `el` (the document root by default — tokens live on
105
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
106
+ * to plain ECharts defaults.
107
+ */
108
+ function readChartTokens(el?: Element | null): ChartTokens | null {
109
+ if (typeof document === "undefined") return null
110
+ const target = el ?? document.documentElement
111
+ if (!target) return null
112
+ const styles = getComputedStyle(target)
113
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
114
+ const series: string[] = []
115
+ for (const token of SERIES_TOKENS) {
116
+ const color = read(token)
117
+ if (color) series.push(color)
118
+ }
119
+ return {
120
+ series,
121
+ foreground: read("--foreground"),
122
+ mutedForeground: read("--muted-foreground"),
123
+ border: read("--border"),
124
+ popover: read("--popover"),
125
+ popoverForeground: read("--popover-foreground"),
126
+ }
127
+ }
128
+
129
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
130
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
131
+ if (a === b) return true
132
+ if (!a || !b) return false
133
+ return (
134
+ a.series.length === b.series.length &&
135
+ a.series.every((color, i) => color === b.series[i]) &&
136
+ a.foreground === b.foreground &&
137
+ a.mutedForeground === b.mutedForeground &&
138
+ a.border === b.border &&
139
+ a.popover === b.popover &&
140
+ a.popoverForeground === b.popoverForeground
141
+ )
142
+ }
143
+
144
+ /**
145
+ * Watch everything that can change the resolved tokens and call `onChange` when
146
+ * something might have. It only ever says "re-read" — the caller compares with
147
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
148
+ * disposer.
149
+ *
150
+ * Two sources, not one:
151
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
152
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
153
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
154
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
155
+ * attributes alone leaves the chart painted in the previous palette until a
156
+ * reload — the tokens in the DOM are new, the canvas is not.
157
+ */
158
+ function watchChartTokens(onChange: () => void): () => void {
159
+ if (typeof document === "undefined") return () => {}
160
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
161
+ // take it after the next frame so a swapped stylesheet has been applied.
162
+ let frame = 0
163
+ const schedule = () => {
164
+ if (frame) return
165
+ frame = requestAnimationFrame(() => {
166
+ frame = 0
167
+ onChange()
168
+ })
169
+ }
170
+
171
+ const themeObserver = new MutationObserver(schedule)
172
+ const attributeFilter = ["class", "style", "data-theme"]
173
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter })
174
+ if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter })
175
+
176
+ const styleObserver = new MutationObserver(schedule)
177
+ if (document.head) {
178
+ styleObserver.observe(document.head, {
179
+ childList: true,
180
+ subtree: true,
181
+ characterData: true,
182
+ attributes: true,
183
+ attributeFilter: ["href", "media", "disabled"],
184
+ })
185
+ }
186
+
187
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
188
+ const onLoad = (event: Event) => {
189
+ if (event.target instanceof HTMLLinkElement) schedule()
190
+ }
191
+ document.addEventListener("load", onLoad, true)
192
+
193
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
194
+ media.addEventListener("change", schedule)
195
+
196
+ return () => {
197
+ if (frame) cancelAnimationFrame(frame)
198
+ themeObserver.disconnect()
199
+ styleObserver.disconnect()
200
+ document.removeEventListener("load", onLoad, true)
201
+ media.removeEventListener("change", schedule)
202
+ }
203
+ }
204
+
205
+ /** Shared shape for the four axis types ECharts themes address separately. */
206
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
207
+ const line = tokens.border ?? undefined
208
+ return {
209
+ axisLine: { show: false },
210
+ axisTick: { show: false },
211
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
212
+ // Faint horizontal rules only: the border colour at low opacity.
213
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
214
+ splitArea: { show: false },
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
220
+ * app that sets its own palette keeps it.
221
+ */
222
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
223
+ const text = tokens.foreground ?? undefined
224
+ const muted = tokens.mutedForeground ?? undefined
225
+ const line = tokens.border ?? undefined
226
+ return {
227
+ // Let the page background show through: charts sit on cards, not on a canvas.
228
+ backgroundColor: "transparent",
229
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
230
+ textStyle: { color: text },
231
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
232
+ legend: { textStyle: { color: muted } },
233
+ categoryAxis: axisTheme(tokens, false),
234
+ valueAxis: axisTheme(tokens, true),
235
+ logAxis: axisTheme(tokens, true),
236
+ timeAxis: axisTheme(tokens, true),
237
+ tooltip: {
238
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
239
+ transitionDuration: 0,
240
+ backgroundColor: tokens.popover ?? undefined,
241
+ borderColor: line,
242
+ borderWidth: 1,
243
+ padding: [8, 12],
244
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
245
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
246
+ textStyle: { color: tokens.popoverForeground ?? undefined, fontSize: 12 },
247
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
248
+ },
249
+ }
250
+ }
251
+
252
+ /**
253
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
254
+ * they may have moved, and only replaced when a value actually changed. For
255
+ * components that build an ECharts option from token colours themselves (the
256
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
257
+ */
258
+ function useChartTokens(): ChartTokens | null {
259
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
260
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
261
+ // replayed by React on every rebase and returns a fresh object each time, so the state
262
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
263
+ const tokensRef = useRef(tokens)
264
+ useEffect(() => {
265
+ const sync = () => {
266
+ const next = readChartTokens()
267
+ if (sameChartTokens(tokensRef.current, next)) return
268
+ tokensRef.current = next
269
+ setTokens(next)
270
+ }
271
+ sync()
272
+ return watchChartTokens(sync)
273
+ }, [])
274
+ return tokens
275
+ }
276
+
277
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
278
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
279
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
280
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
281
+
282
+ /**
283
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
284
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
285
+ * variants `"positive-fill"`, …) are read off the document root (`--positive`, …); `var(--token)` is read off the document root; any
286
+ * other CSS colour is normalized like the tokens are. A colour that can't be
287
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
288
+ */
289
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
290
+ return colors.map((color) => {
291
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
292
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
293
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
294
+ if (TONE_NAME_RE.test(color.trim())) {
295
+ if (typeof document === "undefined") return ""
296
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue(`--${color.trim()}`)) ?? ""
297
+ }
298
+ if (typeof document === "undefined") return color
299
+ let value = color.trim()
300
+ const cssVar = CSS_VAR_RE.exec(value)
301
+ const styles = getComputedStyle(document.documentElement)
302
+ if (cssVar) {
303
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
304
+ } else if (value.includes("var(")) {
305
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
306
+ // substitute the tokens, then let the canvas resolve the rest.
307
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
308
+ }
309
+ return toCanvasColor(value) ?? ""
310
+ })
311
+ }
312
+
313
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
314
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
315
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
316
+ ["positive", "warning", "negative", "neutral"],
317
+ tokens,
318
+ )
319
+ return { positive, warning, negative, neutral }
320
+ }
321
+
322
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
323
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
324
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
325
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
326
+ tokens,
327
+ )
328
+ return { positive, warning, negative, neutral }
329
+ }
330
+
331
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
332
+
333
+ /**
334
+ * The colour the chart is painted on: the first opaque `background-color` up
335
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
336
+ * outside the browser.
337
+ */
338
+ function readChartSurface(el: Element | null): string | null {
339
+ if (typeof document === "undefined") return null
340
+ for (let node: Element | null = el; node; node = node.parentElement) {
341
+ const bg = getComputedStyle(node).backgroundColor.trim()
342
+ if (bg && !TRANSPARENT_RE.test(bg)) {
343
+ const color = toCanvasColor(bg)
344
+ if (color) return color
345
+ }
346
+ }
347
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue("--background"))
348
+ }
349
+
350
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
351
+ const WIDTH_BUCKET = 40
352
+
353
+ /**
354
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
355
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
356
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
357
+ * component's forwarded ref.
358
+ */
359
+ function useChartSurface<E extends Element>(
360
+ forwarded: ForwardedRef<E>,
361
+ tokens: ChartTokens | null,
362
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined } {
363
+ const [node, setNode] = useState<E | null>(null)
364
+ const [surface, setSurface] = useState<string | undefined>(undefined)
365
+ const [width, setWidth] = useState<number | undefined>(undefined)
366
+ const ref = useCallback(
367
+ (el: E | null) => {
368
+ setNode(el)
369
+ if (typeof forwarded === "function") forwarded(el)
370
+ else if (forwarded) forwarded.current = el
371
+ },
372
+ [forwarded],
373
+ )
374
+ useEffect(() => {
375
+ if (!node) return
376
+ setSurface(readChartSurface(node) ?? undefined)
377
+ }, [node, tokens])
378
+ useEffect(() => {
379
+ if (!node || typeof ResizeObserver === "undefined") return
380
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
381
+ update(node.getBoundingClientRect().width)
382
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
383
+ observer.observe(node)
384
+ return () => observer.disconnect()
385
+ }, [node])
386
+ return { ref, surface, width }
387
+ }
388
+
389
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
390
+
391
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
392
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
393
+
394
+ /**
395
+ * The attributes of a typed chart's leftover props that belong on its root
396
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
397
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
398
+ */
399
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
400
+ const out: Record<string, unknown> = {}
401
+ for (const [key, value] of Object.entries(rest)) {
402
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
403
+ }
404
+ return out
405
+ }
406
+
407
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
408
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
409
+ "chart-1",
410
+ "chart-2",
411
+ "chart-3",
412
+ "chart-4",
413
+ "chart-5",
414
+ ]
415
+
416
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
417
+
418
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
419
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
420
+
421
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
422
+ function isChartTone(color: string): color is ChartTone {
423
+ return (CHART_TONES as readonly string[]).includes(color.trim())
424
+ }
425
+
426
+ /**
427
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
428
+ * light/dark on its own), anything else passes through unchanged.
429
+ */
430
+ function chartColorToCss(color: ChartColor): string {
431
+ const value = color.trim()
432
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
433
+ }
434
+
435
+ /**
436
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
437
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
438
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
439
+ */
440
+ function chartFillToCss(color: ChartColor): string {
441
+ const value = color.trim()
442
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
443
+ }
444
+
445
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
446
+ function chartFillName(color: ChartColor): ChartColor {
447
+ const value = color.trim()
448
+ return isChartTone(value) ? `${value}-fill` : color
449
+ }
450
+
451
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
452
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
453
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
454
+ return palette[i % palette.length]!
455
+ }
456
+
457
+ /** `colors` extended (by cycling) to exactly `count` entries. */
458
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
459
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
460
+ }
461
+
462
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
463
+ function tintCss(cssColor: string, percent: number): string {
464
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
465
+ }
466
+
467
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
468
+
469
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
470
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
471
+
472
+ /**
473
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
474
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
475
+ */
476
+ function resolveValueFormatter(
477
+ valueFormatter: ValueFormatter | undefined,
478
+ format: ValueFormat | undefined,
479
+ locale?: string,
480
+ ): ValueFormatter {
481
+ return valueFormatter ?? toValueFormatter(format, locale)
482
+ }
483
+
484
+ /**
485
+ * The formatter of value-axis ticks and on-plot labels: an explicit
486
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
487
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
488
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
489
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
490
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
491
+ * currency sign and grouping.
492
+ */
493
+ function resolveAxisFormatter(
494
+ valueFormatter: ValueFormatter | undefined,
495
+ format: ValueFormat | undefined,
496
+ locale: string = DEFAULT_LOCALE,
497
+ ): ValueFormatter {
498
+ if (valueFormatter) return valueFormatter
499
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
500
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
501
+ const currency = "currency" in spec ? spec.currency : undefined
502
+ const short: ValueFormat =
503
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
504
+ return (value) => formatValue(value, short, locale)
505
+ }
506
+
507
+ /** The unit words of a ja number (`1.2万` / `3.4億` / `1兆`) and their sizes, largest first. */
508
+ const JA_UNITS = [
509
+ { char: "兆", size: 1e12 },
510
+ { char: "億", size: 1e8 },
511
+ { char: "万", size: 1e4 },
512
+ ] as const
513
+
514
+ const JA_NUMBER_TOKEN_RE = /\d[\d,]*(?:\.\d+)?(?:兆|億|万)?/
515
+
516
+ /**
517
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
518
+ * that largest tick, so 万 and 億 never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`).
519
+ * Only the ja short forms (`compact` / `number` / `currency`, no `valueFormatter`) have units to align;
520
+ * any other format — and an axis whose largest tick is under 1万 — keeps `resolveAxisFormatter`'s output as it is.
521
+ */
522
+ function resolveAxisTickFormatter(
523
+ valueFormatter: ValueFormatter | undefined,
524
+ format: ValueFormat | undefined,
525
+ locale: string = DEFAULT_LOCALE,
526
+ ): (top: number) => ValueFormatter {
527
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
528
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
529
+ const aligns =
530
+ !valueFormatter && locale.toLowerCase().startsWith("ja") && (spec.type === "compact" || spec.type === "number" || spec.type === "currency")
531
+ if (!aligns) return () => base
532
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
533
+ return (top) => {
534
+ const unit = JA_UNITS.find((u) => Math.abs(top) >= u.size)
535
+ if (!unit) return base
536
+ return (value) => {
537
+ const text = base(value)
538
+ if (value === 0 || !Number.isFinite(value)) return text
539
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.char}`
540
+ return text.replace(JA_NUMBER_TOKEN_RE, () => scaled)
541
+ }
542
+ }
543
+ }
544
+
545
+ /**
546
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
547
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
548
+ */
549
+ function toChartNumber(value: unknown): number | null {
550
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
551
+ if (typeof value === "bigint") return Number(value)
552
+ if (typeof value === "string" && value.trim() !== "") {
553
+ const n = Number(value)
554
+ return Number.isFinite(n) ? n : null
555
+ }
556
+ return null
557
+ }
558
+
559
+ /** Clamp `value` into `[min, max]`. */
560
+ function clamp(value: number, min: number, max: number): number {
561
+ return Math.min(max, Math.max(min, value))
562
+ }
563
+
564
+ /* ------------------------------------------------------------ aggregation */
565
+
566
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
567
+ const MAX_CHART_SERIES = 5
568
+
569
+ /** The series name the folded categories get. */
570
+ const OTHER_SERIES_LABEL = "その他"
571
+
572
+ interface AggregatedItems<Item extends { name: string; value: number }> {
573
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
574
+ top: Item[]
575
+ /** The items folded into `other`, in their given order. */
576
+ rest: Item[]
577
+ /** The folded remainder, or `null` when nothing was folded. */
578
+ other: { name: string; value: number } | null
579
+ }
580
+
581
+ /**
582
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
583
+ * given order and fold the rest into one `otherLabel` item. Shared by every
584
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
585
+ * BarList rows).
586
+ */
587
+ function aggregateTopN<Item extends { name: string; value: number }>(
588
+ items: readonly Item[],
589
+ n: number = MAX_CHART_SERIES,
590
+ otherLabel: string = OTHER_SERIES_LABEL,
591
+ ): AggregatedItems<Item> {
592
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
593
+ const ranked = items
594
+ .map((item, i) => ({ item, i }))
595
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
596
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
597
+ const top = items.filter((_, i) => keep.has(i))
598
+ const rest = items.filter((_, i) => !keep.has(i))
599
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
600
+ }
601
+
602
+ interface AggregatedSeries {
603
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
604
+ data: Record<string, unknown>[]
605
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
606
+ categories: string[]
607
+ /** The folded series' name, or `null`. */
608
+ otherCategory: string | null
609
+ }
610
+
611
+ /**
612
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
613
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
614
+ */
615
+ function aggregateSeries(
616
+ data: readonly Record<string, unknown>[],
617
+ categories: readonly string[],
618
+ n: number = MAX_CHART_SERIES,
619
+ otherLabel: string = OTHER_SERIES_LABEL,
620
+ ): AggregatedSeries {
621
+ const totals = categories.map((name) => ({
622
+ name,
623
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
624
+ }))
625
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
626
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
627
+ const folded = rest.map((item) => item.name)
628
+ return {
629
+ data: data.map((row) => {
630
+ let sum: number | null = null
631
+ for (const name of folded) {
632
+ const v = toChartNumber(row[name])
633
+ if (v !== null) sum = (sum ?? 0) + v
634
+ }
635
+ return { ...row, [other.name]: sum }
636
+ }),
637
+ categories: [...top.map((item) => item.name), other.name],
638
+ otherCategory: other.name,
639
+ }
640
+ }
641
+
642
+ /**
643
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
644
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
645
+ */
646
+ function aggregateSeriesKeeping(
647
+ data: readonly Record<string, unknown>[],
648
+ categories: readonly string[],
649
+ keep: string | undefined,
650
+ n: number = MAX_CHART_SERIES,
651
+ ): AggregatedSeries {
652
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n)
653
+ const aggregated = aggregateSeries(
654
+ data,
655
+ categories.filter((c) => c !== keep),
656
+ n,
657
+ )
658
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
659
+ }
660
+
661
+ /**
662
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
663
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
664
+ * so a main series keeps its colour whether or not a comparison is drawn.
665
+ */
666
+ function seriesColorsWithComparison(
667
+ categories: readonly string[],
668
+ colors: ChartColors | undefined,
669
+ otherColor: string,
670
+ otherCategory: string | null,
671
+ allCategories: readonly string[],
672
+ comparison: string | undefined,
673
+ ): string[] {
674
+ if (comparison === undefined || !categories.includes(comparison)) {
675
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
676
+ }
677
+ const main = categories.filter((c) => c !== comparison)
678
+ const mainColors = seriesColorsFor(
679
+ main,
680
+ colors,
681
+ otherColor,
682
+ otherCategory,
683
+ allCategories.filter((c) => c !== comparison),
684
+ )
685
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
686
+ }
687
+
688
+ /**
689
+ * Colour per drawn series: the record's token for that category, else the
690
+ * array's token at the category's position in `allCategories` (cycled), else
691
+ * the token palette by drawn position. `otherCategory` — and a category the
692
+ * data itself names「その他」(`OTHER_SERIES_LABEL`) — always gets `otherColor`.
693
+ */
694
+ function seriesColorsFor(
695
+ categories: readonly string[],
696
+ colors: ChartColors | undefined,
697
+ otherColor: string,
698
+ otherCategory: string | null = null,
699
+ allCategories: readonly string[] = categories,
700
+ ): string[] {
701
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
702
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
703
+ return categories.map((category, i) => {
704
+ if ((otherCategory !== null && category === otherCategory) || category === OTHER_SERIES_LABEL) return otherColor
705
+ const fromRecord = record?.[category]
706
+ if (fromRecord) return fromRecord
707
+ if (list && list.length > 0) {
708
+ const at = allCategories.indexOf(category)
709
+ return list[(at === -1 ? i : at) % list.length]!
710
+ }
711
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
712
+ })
713
+ }
714
+
715
+ /* ------------------------------------------------------------------ Donut */
716
+
717
+ /** One drawn donut slice, largest first. */
718
+ interface DonutSlice {
719
+ name: string
720
+ /** Negative and missing values count as 0. */
721
+ value: number
722
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
723
+ color: string
724
+ /** The folded「その他」slice. */
725
+ isOther: boolean
726
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
727
+ row: Record<string, unknown>
728
+ }
729
+
730
+ interface DonutSlicesConfig {
731
+ /** Label column. */
732
+ index: string
733
+ /** Value column. */
734
+ value: string
735
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
736
+ colors?: readonly ChartSeriesColor[]
737
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
738
+ maxSlices?: number
739
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
740
+ otherColor: string
741
+ otherLabel?: string
742
+ }
743
+
744
+ /**
745
+ * Donut slices: sorted by value (largest first, ties keep input order), the
746
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
747
+ * summed into one「その他」slice in `otherColor`.
748
+ */
749
+ function donutSlices(
750
+ data: readonly Record<string, unknown>[],
751
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = OTHER_SERIES_LABEL }: DonutSlicesConfig,
752
+ ): DonutSlice[] {
753
+ const items = data
754
+ .map((row, i) => {
755
+ const n = toChartNumber(row[value])
756
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
757
+ })
758
+ .sort((a, b) => b.value - a.value || a.i - b.i)
759
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
760
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
761
+ const slices: DonutSlice[] = top.map((item, rank) => ({
762
+ name: item.name,
763
+ value: item.value,
764
+ color: palette[rank % palette.length]!,
765
+ isOther: false,
766
+ row: item.row,
767
+ }))
768
+ if (other) {
769
+ slices.push({
770
+ name: other.name,
771
+ value: other.value,
772
+ color: otherColor,
773
+ isOther: true,
774
+ row: { [index]: other.name, [value]: other.value },
775
+ })
776
+ }
777
+ return slices
778
+ }
779
+
780
+ /* ---------------------------------------------------------------- BarList */
781
+
782
+ type BarListSortOrder = "ascending" | "descending" | "none"
783
+
784
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
785
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
786
+ const rows = [...data]
787
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
788
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
789
+ return rows
790
+ }
791
+
792
+ /** BarList-only settings. */
793
+ interface BarListOptions {
794
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
795
+ sortOrder?: BarListSortOrder
796
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
797
+ maxItems?: number
798
+ /** まとめた行のラベル。既定「その他」。 */
799
+ otherLabel?: string
800
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
801
+ exclude?: readonly string[]
802
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
803
+ showShare?: boolean
804
+ }
805
+
806
+ /** One drawn BarList row. */
807
+ interface BarListRow<Row = Record<string, unknown>> {
808
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
809
+ key: string
810
+ name: string
811
+ value: number
812
+ /** Only for real rows; the folded row never links. */
813
+ href?: string
814
+ /** Legacy per-row colour (`BarListItem.color`). */
815
+ color?: ChartColor
816
+ /** The folded「その他」row. */
817
+ isOther: boolean
818
+ /** The input row (`null` for the folded row). */
819
+ row: Row | null
820
+ }
821
+
822
+ interface BarListRowsConfig extends BarListOptions {
823
+ /** Name column. Default `"name"`. */
824
+ index?: string
825
+ /** Value column. Default `"value"`. */
826
+ category?: string
827
+ }
828
+
829
+ /**
830
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
831
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
832
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
833
+ * ranking and are always added to「その他」.
834
+ */
835
+ function barListRows<Row extends object>(
836
+ data: readonly Row[],
837
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = OTHER_SERIES_LABEL, exclude }: BarListRowsConfig = {},
838
+ ): BarListRow<Row>[] {
839
+ const items = data.map((row): BarListRow<Row> => {
840
+ const cells = row as Record<string, unknown>
841
+ const name = String(cells[index] ?? "")
842
+ return {
843
+ key: typeof cells.key === "string" ? cells.key : name,
844
+ name,
845
+ value: toChartNumber(cells[category]) ?? 0,
846
+ href: typeof cells.href === "string" ? cells.href : undefined,
847
+ color: typeof cells.color === "string" ? cells.color : undefined,
848
+ isOther: false,
849
+ row,
850
+ }
851
+ })
852
+ const excluded = new Set(exclude ?? [])
853
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
854
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
855
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
856
+ const rows = sortBarListData(top, sortOrder)
857
+ if (other || outside.length > 0) {
858
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
859
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
860
+ }
861
+ return rows
862
+ }
863
+
864
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
865
+ function barListWidths(values: readonly number[]): number[] {
866
+ const max = Math.max(0, ...values)
867
+ if (max === 0) return values.map(() => 0)
868
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
869
+ }
870
+
871
+ /**
872
+ * How strongly the BarList bars are painted: every row the same tint of the bar
873
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
874
+ * it sits on the card in light and dark; it must stay visible against the card
875
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
876
+ */
877
+ const BAR_LIST_TINT = 45
878
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
879
+ const BAR_LIST_OTHER_TINT = 30
880
+
881
+ /**
882
+ * The fill of each BarList row: all real rows in the same tint of `color`
883
+ * (`BAR_LIST_TINT`), the folded「その他」row in a tint of `otherColor`
884
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
885
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
886
+ * for that row. A tint, not the solid token, so the label printed over the bar
887
+ * keeps its contrast.
888
+ */
889
+ function barListFills(
890
+ rows: readonly Pick<BarListRow, "isOther" | "color">[],
891
+ color: ChartColor,
892
+ otherColor: string,
893
+ ): string[] {
894
+ return rows.map((row) =>
895
+ row.isOther ? tintCss(otherColor, BAR_LIST_OTHER_TINT) : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
896
+ )
897
+ }
898
+
899
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
900
+ function barListShareText(value: number, total: number): string {
901
+ const v = Number.isFinite(value) && value > 0 ? value : 0
902
+ if (total <= 0 || v === 0) return "0%"
903
+ const pct = (v / total) * 100
904
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
905
+ }
906
+
907
+ /**
908
+ * The text at the end of each BarList row: the formatted value and, with
909
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
910
+ * so the shares are of the whole list): `value` and `share` apart (the share is
911
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
912
+ */
913
+ function barListValueTexts(
914
+ values: readonly number[],
915
+ formatter: ValueFormatter,
916
+ showShare = false,
917
+ ): { value: string; share?: string; text: string }[] {
918
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
919
+ return values.map((v) => {
920
+ const value = formatter(v)
921
+ if (!showShare) return { value, text: value }
922
+ const share = barListShareText(v, total)
923
+ return { value, share, text: `${value} · ${share}` }
924
+ })
925
+ }
926
+
927
+ /* -------------------------------------------------------------- DataTable */
928
+
929
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
930
+ interface ChartDataTable {
931
+ /** 表の見出し(`<caption>`)。 */
932
+ caption?: string
933
+ /** 列見出し。先頭がラベル列。 */
934
+ columns: string[]
935
+ /** 行。セルは書式済みの文字列。 */
936
+ rows: string[][]
937
+ }
938
+
939
+ /**
940
+ * The chart's numbers as a table, for screen readers: one row per data row, the
941
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
942
+ * 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).
943
+ */
944
+ function chartDataTable(
945
+ data: readonly Record<string, unknown>[],
946
+ index: string,
947
+ categories: readonly string[],
948
+ formatter: ValueFormatter,
949
+ labels?: Readonly<Record<string, string>>,
950
+ indexName?: string,
951
+ ): ChartDataTable {
952
+ const label = (key: string) => labels?.[key] ?? key
953
+ return {
954
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
955
+ rows: data.map((row) => [
956
+ String(row[index] ?? ""),
957
+ ...categories.map((key) => {
958
+ const n = toChartNumber(row[key])
959
+ return n === null ? EMPTY_VALUE : formatter(n)
960
+ }),
961
+ ]),
962
+ }
963
+ }
964
+
965
+ /* ------------------------------------------------------------ CategoryBar */
966
+
967
+ interface CategoryBarSegment {
968
+ /** Width in percent of the whole bar. */
969
+ width: number
970
+ /** Where the segment starts, in percent. */
971
+ start: number
972
+ /** The running total at the segment's end — what its right-hand label shows. */
973
+ end: number
974
+ }
975
+
976
+ /** Lay the values side by side; negative values count as zero. */
977
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
978
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
979
+ const total = clean.reduce((sum, v) => sum + v, 0)
980
+ let running = 0
981
+ return clean.map((v) => {
982
+ const start = total === 0 ? 0 : (running / total) * 100
983
+ running += v
984
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
985
+ })
986
+ }
987
+
988
+ interface CategoryBarLabel {
989
+ /** Position in percent of the bar. */
990
+ position: number
991
+ /** The running total printed there. */
992
+ value: number
993
+ }
994
+
995
+ /**
996
+ * Tick labels under the bar: `0` at the start, then the running total at each
997
+ * segment's end. A label closer than `minGap` percent to the one before is
998
+ * dropped so narrow segments don't print on top of each other — except the
999
+ * last one (the total), which replaces its neighbour instead. With a
1000
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
1001
+ * too — the marker sits right under it and the two read as one crowded spot.
1002
+ */
1003
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
1004
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
1005
+ if (segments.length === 0) return []
1006
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
1007
+ segments.forEach((s, i) => {
1008
+ const label = { position: s.start + s.width, value: s.end }
1009
+ const prev = labels[labels.length - 1]!
1010
+ if (label.position - prev.position >= minGap) labels.push(label)
1011
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
1012
+ })
1013
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1014
+ return labels.filter(
1015
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1016
+ )
1017
+ }
1018
+
1019
+ /**
1020
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1021
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1022
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1023
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1024
+ * the rest 7 px at 12 px type).
1025
+ */
1026
+ function categoryBarFitLabels(
1027
+ labels: readonly CategoryBarLabel[],
1028
+ texts: readonly string[],
1029
+ width: number,
1030
+ gap = 8,
1031
+ ): CategoryBarLabel[] {
1032
+ const textWidth = (text: string) => {
1033
+ let w = 0
1034
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1035
+ return w
1036
+ }
1037
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1038
+ const w = textWidth(text)
1039
+ if (label.position <= 0) return [0, w]
1040
+ if (label.position >= 100) return [width - w, width]
1041
+ const center = (label.position / 100) * width
1042
+ return [center - w / 2, center + w / 2]
1043
+ }
1044
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1045
+ labels.forEach((label, i) => {
1046
+ const here = extent(label, texts[i] ?? "")
1047
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1048
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1049
+ else if (touches()) return
1050
+ kept.push({ label, extent: here })
1051
+ })
1052
+ return kept.map((k) => k.label)
1053
+ }
1054
+
1055
+ /** Marker position in percent of the bar, clamped to its ends. */
1056
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
1057
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1058
+ if (total === 0) return 0
1059
+ return clamp((value / total) * 100, 0, 100)
1060
+ }
1061
+
1062
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
1063
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
1064
+ const segments = categoryBarSegments(values)
1065
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
1066
+ if (index !== -1) return index
1067
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
1068
+ return 0
1069
+ }
1070
+
1071
+ /* --------------------------------------------------------- ProgressCircle */
1072
+
1073
+ interface ProgressCircleGeometry {
1074
+ /** SVG width/height. */
1075
+ size: number
1076
+ /** Radius of the stroke's centre line. */
1077
+ normalizedRadius: number
1078
+ circumference: number
1079
+ /** `stroke-dashoffset` for the value arc. */
1080
+ offset: number
1081
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
1082
+ ratio: number
1083
+ }
1084
+
1085
+ function progressCircleGeometry(
1086
+ value: number,
1087
+ max: number,
1088
+ radius: number,
1089
+ strokeWidth: number,
1090
+ ): ProgressCircleGeometry {
1091
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
1092
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
1093
+ const circumference = 2 * Math.PI * normalizedRadius
1094
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
1095
+ }
1096
+
1097
+ /* ---------------------------------------------------------------- summary */
1098
+
1099
+ interface ChartSummaryInput {
1100
+ data: readonly Record<string, unknown>[]
1101
+ /** The x-axis key. */
1102
+ index: string
1103
+ /** Series keys; the first one is described. */
1104
+ categories: readonly string[]
1105
+ /** Title of the chart, put in front when given. */
1106
+ title?: string
1107
+ /** Same as the chart's `format` (default `"compact"`). */
1108
+ format?: ValueFormat
1109
+ /** Wins over `format`. */
1110
+ valueFormatter?: ValueFormatter
1111
+ }
1112
+
1113
+ /**
1114
+ * One-sentence summary built from the rows, for `summary="auto"`:
1115
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」. The direction is
1116
+ * computed from the last two non-empty points of the first series — never
1117
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1118
+ * no usable point.
1119
+ */
1120
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1121
+ const key = input.categories[0]
1122
+ if (key === undefined) return undefined
1123
+ const points: { label: string; value: number }[] = []
1124
+ for (const row of input.data) {
1125
+ const raw = row[key]
1126
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1127
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1128
+ }
1129
+ const latest = points[points.length - 1]
1130
+ if (!latest) return undefined
1131
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact")
1132
+ const prev = points[points.length - 2]
1133
+ const direction = !prev ? "" : latest.value > prev.value ? "、前の点より増加" : latest.value < prev.value ? "、前の点より減少" : "、前の点と横ばい"
1134
+ const head = input.title ? `${input.title}: ` : ""
1135
+ return `${head}最新 ${latest.label} は ${text(latest.value)}${direction}`
1136
+ }
1137
+
1138
+ /**
1139
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」 from the slices
1140
+ * (largest first). `undefined` when there is nothing to describe.
1141
+ */
1142
+ function buildShareSummary(
1143
+ slices: readonly { name: string; value: number }[],
1144
+ title?: string,
1145
+ ): string | undefined {
1146
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1147
+ const top = slices[0]
1148
+ if (!top || total <= 0) return undefined
1149
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1150
+ return `${title ? `${title}: ` : ""}最大は ${top.name}(${share})`
1151
+ }
1152
+
1153
+ /* ---------- end of inlined code ---------- */
1154
+
1155
+ /** The shape the loading skeleton takes, matching the chart it stands in for. */
1156
+ export type ChartSkeletonVariant = "line" | "area" | "bar" | "donut" | "list"
1157
+
1158
+ /** The plot height of every typed chart unless `height` says otherwise (px). */
1159
+ export const DEFAULT_CHART_HEIGHT = 288
1160
+
1161
+ const DEFAULT_EMPTY_TITLE = "表示できるデータがありません"
1162
+
1163
+ export interface ChartFrameProps extends Omit<HTMLAttributes<HTMLElement>, "title" | "children"> {
1164
+ /** グラフの見出し。プロット領域の `aria-labelledby` になる。 */
1165
+ title?: string
1166
+ /** 1 文の要約。見出しの下に出し、プロット領域の `aria-describedby` になる。 */
1167
+ summary?: string
1168
+ /** 読み込み中。`variant` の形のスケルトンを同じ高さで出す。 */
1169
+ isLoading?: boolean
1170
+ /** データが無い。高さを保ったまま `emptyState` を出す。 */
1171
+ isEmpty?: boolean
1172
+ emptyState?: ChartEmptyState
1173
+ /** プロット領域の高さ。数値は px。既定 288。 */
1174
+ height?: number | string
1175
+ /** スケルトンの形。既定 `"line"`。 */
1176
+ variant?: ChartSkeletonVariant
1177
+ /** 見出しが無いときのプロット領域のラベル。 */
1178
+ ariaLabel?: string
1179
+ /**
1180
+ * プロット領域の役割。既定 `"img"`(canvas のグラフ)。行がボタンやリンクになる
1181
+ * HTML のグラフ(BarList・FunnelSteps)は `"group"` にして、中身を読ませる。
1182
+ */
1183
+ plotRole?: "img" | "group"
1184
+ /** 値の表。画面には出さず(`sr-only`)、スクリーンリーダー向けに図の中に置く。`chartDataTable` で作る。 */
1185
+ dataTable?: ChartDataTable
1186
+ /** プロット(チャート本体)。読み込み中・空のときは描かない。 */
1187
+ children?: ReactNode
1188
+ }
1189
+
1190
+ /**
1191
+ * The frame. `ref` points at the plot area (the element with the fixed height),
1192
+ * `className` / other attributes go to the outer `<figure>`.
1193
+ */
1194
+ export const ChartFrame = forwardRef<HTMLDivElement, ChartFrameProps>(function ChartFrame(
1195
+ {
1196
+ title,
1197
+ summary,
1198
+ isLoading = false,
1199
+ isEmpty = false,
1200
+ emptyState,
1201
+ height = DEFAULT_CHART_HEIGHT,
1202
+ variant = "line",
1203
+ ariaLabel,
1204
+ plotRole = "img",
1205
+ dataTable,
1206
+ className,
1207
+ children,
1208
+ ...props
1209
+ },
1210
+ ref,
1211
+ ) {
1212
+ const id = useId()
1213
+ const titleId = title ? `${id}-title` : undefined
1214
+ const summaryId = summary ? `${id}-summary` : undefined
1215
+ const state = isLoading ? "loading" : isEmpty ? "empty" : "ready"
1216
+
1217
+ return (
1218
+ <figure data-slot="chart-frame" className={cn("m-0 flex w-full min-w-0 flex-col gap-3", className)} {...props}>
1219
+ {(title || summary) && (
1220
+ <figcaption data-slot="chart-frame-header" className="flex flex-col gap-1">
1221
+ {title && (
1222
+ <h3 id={titleId} data-slot="chart-frame-title" className="text-sm leading-none font-medium">
1223
+ {title}
1224
+ </h3>
1225
+ )}
1226
+ {summary && (
1227
+ <p id={summaryId} data-slot="chart-frame-summary" className="text-sm text-muted-foreground">
1228
+ {summary}
1229
+ </p>
1230
+ )}
1231
+ </figcaption>
1232
+ )}
1233
+ <div
1234
+ ref={ref}
1235
+ data-slot="chart-frame-body"
1236
+ data-state={state}
1237
+ role={state === "ready" ? plotRole : "group"}
1238
+ aria-label={titleId ? undefined : ariaLabel}
1239
+ aria-labelledby={titleId}
1240
+ aria-describedby={summaryId}
1241
+ aria-busy={isLoading || undefined}
1242
+ className="relative w-full min-w-0"
1243
+ style={{ height: typeof height === "number" ? `${height}px` : height }}
1244
+ >
1245
+ {state === "loading" ? (
1246
+ <ChartSkeleton variant={variant} />
1247
+ ) : state === "empty" ? (
1248
+ <ChartEmpty {...emptyState} />
1249
+ ) : (
1250
+ <ChartFrameContext.Provider value>{children}</ChartFrameContext.Provider>
1251
+ )}
1252
+ </div>
1253
+ {state === "ready" && dataTable && dataTable.rows.length > 0 && (
1254
+ <ChartDataTableView table={dataTable} fallbackCaption={title ?? ariaLabel} />
1255
+ )}
1256
+ </figure>
1257
+ )
1258
+ })
1259
+ ChartFrame.displayName = "ChartFrame"
1260
+
1261
+ /* ---------------------------------------------------------------- skeleton */
1262
+
1263
+ const BAR_HEIGHTS = [58, 74, 46, 88, 64, 80, 52]
1264
+ const LIST_WIDTHS = [92, 76, 64, 48, 36]
1265
+ const LINE_POINTS = "0,70 16,58 33,62 50,40 66,46 83,28 100,34"
1266
+
1267
+ function ChartSkeleton({ variant }: { variant: ChartSkeletonVariant }) {
1268
+ const pulse = "animate-pulse motion-reduce:animate-none"
1269
+ return (
1270
+ <div data-slot="chart-skeleton" data-variant={variant} className="absolute inset-0 flex flex-col gap-3">
1271
+ <div aria-hidden="true" className="contents">
1272
+ {variant === "list" ? (
1273
+ <div className={cn("flex flex-1 flex-col justify-around", pulse)}>
1274
+ {LIST_WIDTHS.map((w) => (
1275
+ <div key={w} className="flex items-center gap-3">
1276
+ <div className="h-5 rounded-sm bg-muted" style={{ width: `${w}%` }} />
1277
+ </div>
1278
+ ))}
1279
+ </div>
1280
+ ) : variant === "donut" ? (
1281
+ <div className={cn("flex flex-1 items-center justify-center", pulse)}>
1282
+ <svg viewBox="0 0 100 100" className="h-full max-h-full w-auto text-muted">
1283
+ <circle cx="50" cy="50" r="40" fill="none" stroke="currentColor" strokeWidth="14" />
1284
+ </svg>
1285
+ </div>
1286
+ ) : variant === "bar" ? (
1287
+ <div className={cn("flex flex-1 items-end gap-3 px-1", pulse)}>
1288
+ {BAR_HEIGHTS.map((h, i) => (
1289
+ <div key={i} className="flex-1 rounded-t-sm bg-muted" style={{ height: `${h}%` }} />
1290
+ ))}
1291
+ </div>
1292
+ ) : (
1293
+ // A soft muted silhouette only — no stroke, no baseline, nothing that reads as a data line.
1294
+ <div className={cn("relative flex-1", pulse)}>
1295
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full text-muted">
1296
+ <polygon points={`${LINE_POINTS} 100,100 0,100`} fill="currentColor" opacity={variant === "area" ? 0.8 : 0.5} />
1297
+ </svg>
1298
+ </div>
1299
+ )}
1300
+ </div>
1301
+ <span className="sr-only">読み込み中</span>
1302
+ </div>
1303
+ )
1304
+ }
1305
+
1306
+ /* --------------------------------------------------------------- data table */
1307
+
1308
+ function ChartDataTableView({ table, fallbackCaption }: { table: ChartDataTable; fallbackCaption?: string }) {
1309
+ const caption = table.caption ?? fallbackCaption
1310
+ // The wrapper is the visually-hidden box: `sr-only` on the <table> itself still
1311
+ // lets table auto-layout give it a real width, which overflows narrow pages.
1312
+ return (
1313
+ <div data-slot="chart-frame-table-wrapper" className="sr-only">
1314
+ <table data-slot="chart-frame-table">
1315
+ {caption && <caption>{caption}</caption>}
1316
+ <thead>
1317
+ <tr>
1318
+ {table.columns.map((column, i) => (
1319
+ <th key={i} scope="col">
1320
+ {column}
1321
+ </th>
1322
+ ))}
1323
+ </tr>
1324
+ </thead>
1325
+ <tbody>
1326
+ {table.rows.map((row, r) => (
1327
+ <tr key={r}>
1328
+ {row.map((cell, c) =>
1329
+ c === 0 ? (
1330
+ <th key={c} scope="row">
1331
+ {cell}
1332
+ </th>
1333
+ ) : (
1334
+ <td key={c}>{cell}</td>
1335
+ ),
1336
+ )}
1337
+ </tr>
1338
+ ))}
1339
+ </tbody>
1340
+ </table>
1341
+ </div>
1342
+ )
1343
+ }
1344
+
1345
+ /* ------------------------------------------------------------------- empty */
1346
+
1347
+ function ChartEmpty({ title, description, action }: ChartEmptyState) {
1348
+ return (
1349
+ <div
1350
+ data-slot="chart-empty"
1351
+ className="absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-md border border-dashed border-border p-6 text-center"
1352
+ >
1353
+ <p className="text-sm font-medium text-balance">{title ?? DEFAULT_EMPTY_TITLE}</p>
1354
+ {description && <p className="max-w-prose text-sm text-balance text-muted-foreground">{description}</p>}
1355
+ {action && <div className="mt-3">{action}</div>}
1356
+ </div>
1357
+ )
1358
+ }