@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.9365dcd

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