@squadbase/vantage 0.6.2-dev1.ac99e02 → 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 (141) 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-PXRX5PEC.js → chunk-PDOBHMUQ.js} +3 -3
  8. package/dist/chunk-PDOBHMUQ.js.map +1 -0
  9. package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
  10. package/dist/chunk-U736PVHY.js.map +1 -0
  11. package/dist/{chunk-QEWCYW3I.js → chunk-WAMZWZJB.js} +13 -3
  12. package/dist/chunk-WAMZWZJB.js.map +1 -0
  13. package/dist/chunk-WRSX2MDK.js +7866 -0
  14. package/dist/chunk-WRSX2MDK.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 +1831 -99
  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/table/index.js +5 -5
  27. package/dist/table/index.js.map +1 -1
  28. package/dist/ui/index.d.ts +4 -1
  29. package/dist/ui/index.js +21 -111
  30. package/dist/ui/index.js.map +1 -1
  31. package/dist/{upgrade-DBBE6GIR.js → upgrade-JHXZBGQS.js} +3 -3
  32. package/dist/{upgrade-DBBE6GIR.js.map → upgrade-JHXZBGQS.js.map} +1 -1
  33. package/dist/vite/index.js +2 -2
  34. package/docs/en/components.md +29 -15
  35. package/docs/en/parts/data-table.md +22 -0
  36. package/docs/en/parts/delta.md +50 -0
  37. package/docs/en/parts/format.md +43 -0
  38. package/docs/en/parts/kpi-card.md +57 -0
  39. package/docs/en/parts/metric-value.md +3 -2
  40. package/docs/en/parts/sparkline.md +1 -1
  41. package/docs/en/parts/trend-indicator.md +17 -1
  42. package/docs/en/ui-and-theming.md +1 -1
  43. package/docs/index.json +92 -32
  44. package/docs/ja/changelog.md +5 -0
  45. package/docs/ja/components.md +27 -15
  46. package/docs/ja/parts/data-table.md +22 -0
  47. package/docs/ja/parts/delta.md +50 -0
  48. package/docs/ja/parts/format.md +44 -0
  49. package/docs/ja/parts/kpi-card.md +55 -0
  50. package/docs/ja/parts/metric-value.md +3 -2
  51. package/docs/ja/parts/sparkline.md +1 -1
  52. package/docs/ja/parts/trend-indicator.md +17 -1
  53. package/docs/ja/ui-and-theming.md +2 -2
  54. package/package.json +2 -1
  55. package/registry/ui/accordion.tsx +4 -2
  56. package/registry/ui/alert-dialog.tsx +3 -3
  57. package/registry/ui/alert.tsx +3 -1
  58. package/registry/ui/app-shell.tsx +7 -1
  59. package/registry/ui/area-chart.tsx +2781 -157
  60. package/registry/ui/avatar.tsx +1 -1
  61. package/registry/ui/badge.tsx +3 -1
  62. package/registry/ui/bar-chart.tsx +2780 -157
  63. package/registry/ui/bar-list.tsx +3471 -93
  64. package/registry/ui/breadcrumb.tsx +3 -1
  65. package/registry/ui/button.tsx +3 -1
  66. package/registry/ui/calendar.tsx +3 -1
  67. package/registry/ui/card.tsx +4 -2
  68. package/registry/ui/category-bar.tsx +990 -16
  69. package/registry/ui/chart-frame.tsx +1358 -0
  70. package/registry/ui/checkbox.tsx +3 -1
  71. package/registry/ui/collapsible.tsx +3 -1
  72. package/registry/ui/combobox.tsx +2 -2
  73. package/registry/ui/command.tsx +3 -1
  74. package/registry/ui/dashboard-card.tsx +69 -26
  75. package/registry/ui/data-table.tsx +678 -56
  76. package/registry/ui/date-range-picker.tsx +245 -64
  77. package/registry/ui/delta.tsx +188 -0
  78. package/registry/ui/dialog.tsx +5 -3
  79. package/registry/ui/donut-chart.tsx +2857 -173
  80. package/registry/ui/drawer.tsx +1 -1
  81. package/registry/ui/dropdown-menu.tsx +5 -3
  82. package/registry/ui/echart.tsx +448 -44
  83. package/registry/ui/field.tsx +1 -1
  84. package/registry/ui/filter-bar.tsx +33 -6
  85. package/registry/ui/funnel-steps.tsx +3316 -49
  86. package/registry/ui/heatmap.tsx +1752 -0
  87. package/registry/ui/hover-card.tsx +2 -2
  88. package/registry/ui/input-group.tsx +3 -1
  89. package/registry/ui/input.tsx +3 -1
  90. package/registry/ui/kbd.tsx +3 -1
  91. package/registry/ui/kpi-card.tsx +677 -0
  92. package/registry/ui/label.tsx +3 -1
  93. package/registry/ui/legend.tsx +3500 -0
  94. package/registry/ui/line-chart.tsx +2781 -151
  95. package/registry/ui/metric-value.tsx +9 -1
  96. package/registry/ui/multi-select.tsx +11 -5
  97. package/registry/ui/page-shell.tsx +104 -49
  98. package/registry/ui/pagination.tsx +3 -1
  99. package/registry/ui/placeholder.tsx +8 -2
  100. package/registry/ui/popover.tsx +4 -2
  101. package/registry/ui/progress-circle.tsx +607 -12
  102. package/registry/ui/progress.tsx +3 -1
  103. package/registry/ui/radio-group.tsx +1 -1
  104. package/registry/ui/sample-data.tsx +86 -0
  105. package/registry/ui/scatter-chart.tsx +4150 -0
  106. package/registry/ui/scroll-area.tsx +3 -2
  107. package/registry/ui/searchable-select.tsx +8 -3
  108. package/registry/ui/section-header.tsx +4 -2
  109. package/registry/ui/segmented-control.tsx +7 -2
  110. package/registry/ui/select.tsx +4 -2
  111. package/registry/ui/separator.tsx +3 -1
  112. package/registry/ui/sheet.tsx +4 -2
  113. package/registry/ui/sidebar.tsx +4 -2
  114. package/registry/ui/skeleton.tsx +4 -2
  115. package/registry/ui/slider.tsx +3 -1
  116. package/registry/ui/sparkline.tsx +84 -9
  117. package/registry/ui/spinner.tsx +3 -1
  118. package/registry/ui/states.tsx +34 -5
  119. package/registry/ui/status-badge.tsx +81 -39
  120. package/registry/ui/switch.tsx +3 -1
  121. package/registry/ui/table.tsx +4 -2
  122. package/registry/ui/tabs.tsx +5 -3
  123. package/registry/ui/textarea.tsx +3 -1
  124. package/registry/ui/toast.tsx +2 -2
  125. package/registry/ui/toggle-group.tsx +3 -1
  126. package/registry/ui/toggle.tsx +3 -1
  127. package/registry/ui/tooltip.tsx +4 -2
  128. package/registry/ui/tracker.tsx +624 -17
  129. package/registry/ui/trend-indicator.tsx +13 -1
  130. package/registry/ui/updated-at.tsx +122 -0
  131. package/registry/ui/waterfall-chart.tsx +4186 -0
  132. package/templates/AGENTS.md +13 -1
  133. package/theme.css +237 -136
  134. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  135. package/dist/chunk-A2UUGASH.js.map +0 -1
  136. package/dist/chunk-AG6RZ2RR.js +0 -3208
  137. package/dist/chunk-AG6RZ2RR.js.map +0 -1
  138. package/dist/chunk-IBGOCWJB.js.map +0 -1
  139. package/dist/chunk-OB6UBJXF.js.map +0 -1
  140. package/dist/chunk-PXRX5PEC.js.map +0 -1
  141. package/dist/chunk-QEWCYW3I.js.map +0 -1
@@ -1,17 +1,401 @@
1
1
  // Copied by `vantage add ui category-bar`. This file is yours to edit.
2
- // Generated from @squadbase/vantage src/components/category-bar.tsx by `npm run registry` (in Vantage, edit src/, not registry/).
2
+ // Generated from @squadbase/squadkit registry/charts/category-bar.tsx by `npm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
3
5
  /**
4
6
  * CategoryBar — one bar split into coloured segments by `values`, with the
5
7
  * running totals underneath and an optional marker: a score against bands
6
8
  * (要改善 / 標準 / 良好), budget consumption, a share breakdown. Plain HTML/CSS.
7
9
  */
8
- import { forwardRef, type ComponentProps } from "react"
10
+ import { forwardRef, useMemo, type ComponentProps } from "react"
9
11
 
10
12
  import { cn } from "@squadbase/vantage/ui"
11
13
  import { Tooltip, TooltipContent, TooltipTrigger } from "@squadbase/vantage/ui"
14
+ import type { ValueFormat } from "@squadbase/vantage/components"
12
15
  import type { ChartColor, ValueFormatter } from "@squadbase/vantage/components"
16
+ import { createContext, useCallback, useEffect, useRef, useState, type ForwardedRef } from "react"
17
+ import type { ChartTone } from "@squadbase/vantage/components"
18
+ import { DEFAULT_LOCALE, EMPTY_VALUE, formatValue, toValueFormatter } from "@squadbase/vantage/components"
19
+ import type { ChartColors, ChartSeriesColor } from "@squadbase/vantage/components"
20
+
21
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
22
+
23
+ /**
24
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
25
+ * grey is defined — every chart takes it from here. It is the most subdued
26
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
27
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
28
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
29
+ * slice. Canvas charts resolve it through `resolveChartColors`.
30
+ */
31
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
32
+
33
+ /**
34
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
35
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
36
+ */
37
+ const ChartFrameContext = createContext(false)
38
+
39
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
40
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
41
+
42
+ interface ChartTokens {
43
+ /** Resolved `--chart-1..5`, in order. */
44
+ series: string[]
45
+ /** Body text: titles and the default `textStyle`. */
46
+ foreground: string | null
47
+ /** Secondary text: axis labels, legend, subtitles. */
48
+ mutedForeground: string | null
49
+ /** Axis lines, ticks, split lines, tooltip border. */
50
+ border: string | null
51
+ /** Tooltip surface. */
52
+ popover: string | null
53
+ /** Tooltip text. */
54
+ popoverForeground: string | null
55
+ }
56
+
57
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
58
+
59
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
60
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
61
+
62
+ /**
63
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
64
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
65
+ * input is written over two different known colours: agreeing results mean the
66
+ * value parsed, differing ones mean it was dropped.
67
+ */
68
+ function toCanvasColor(value: string): string | null {
69
+ const raw = value.trim()
70
+ if (!raw) return null
71
+ if (normalizeContext === undefined) {
72
+ const canvas = document.createElement("canvas")
73
+ canvas.width = 1
74
+ canvas.height = 1
75
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
76
+ }
77
+ const ctx = normalizeContext
78
+ if (!ctx) return raw
79
+ ctx.fillStyle = "#000000"
80
+ ctx.fillStyle = raw
81
+ const onBlack = ctx.fillStyle
82
+ ctx.fillStyle = "#ffffff"
83
+ ctx.fillStyle = raw
84
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
85
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
86
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
87
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
88
+ ctx.clearRect(0, 0, 1, 1)
89
+ ctx.fillRect(0, 0, 1, 1)
90
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
91
+ return a === 255
92
+ ? `rgb(${r}, ${g}, ${b})`
93
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
94
+ }
95
+
96
+ /**
97
+ * Read the chart tokens off `el` (the document root by default — tokens live on
98
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
99
+ * to plain ECharts defaults.
100
+ */
101
+ function readChartTokens(el?: Element | null): ChartTokens | null {
102
+ if (typeof document === "undefined") return null
103
+ const target = el ?? document.documentElement
104
+ if (!target) return null
105
+ const styles = getComputedStyle(target)
106
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
107
+ const series: string[] = []
108
+ for (const token of SERIES_TOKENS) {
109
+ const color = read(token)
110
+ if (color) series.push(color)
111
+ }
112
+ return {
113
+ series,
114
+ foreground: read("--foreground"),
115
+ mutedForeground: read("--muted-foreground"),
116
+ border: read("--border"),
117
+ popover: read("--popover"),
118
+ popoverForeground: read("--popover-foreground"),
119
+ }
120
+ }
121
+
122
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
123
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
124
+ if (a === b) return true
125
+ if (!a || !b) return false
126
+ return (
127
+ a.series.length === b.series.length &&
128
+ a.series.every((color, i) => color === b.series[i]) &&
129
+ a.foreground === b.foreground &&
130
+ a.mutedForeground === b.mutedForeground &&
131
+ a.border === b.border &&
132
+ a.popover === b.popover &&
133
+ a.popoverForeground === b.popoverForeground
134
+ )
135
+ }
136
+
137
+ /**
138
+ * Watch everything that can change the resolved tokens and call `onChange` when
139
+ * something might have. It only ever says "re-read" — the caller compares with
140
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
141
+ * disposer.
142
+ *
143
+ * Two sources, not one:
144
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
145
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
146
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
147
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
148
+ * attributes alone leaves the chart painted in the previous palette until a
149
+ * reload — the tokens in the DOM are new, the canvas is not.
150
+ */
151
+ function watchChartTokens(onChange: () => void): () => void {
152
+ if (typeof document === "undefined") return () => {}
153
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
154
+ // take it after the next frame so a swapped stylesheet has been applied.
155
+ let frame = 0
156
+ const schedule = () => {
157
+ if (frame) return
158
+ frame = requestAnimationFrame(() => {
159
+ frame = 0
160
+ onChange()
161
+ })
162
+ }
163
+
164
+ const themeObserver = new MutationObserver(schedule)
165
+ const attributeFilter = ["class", "style", "data-theme"]
166
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter })
167
+ if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter })
168
+
169
+ const styleObserver = new MutationObserver(schedule)
170
+ if (document.head) {
171
+ styleObserver.observe(document.head, {
172
+ childList: true,
173
+ subtree: true,
174
+ characterData: true,
175
+ attributes: true,
176
+ attributeFilter: ["href", "media", "disabled"],
177
+ })
178
+ }
179
+
180
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
181
+ const onLoad = (event: Event) => {
182
+ if (event.target instanceof HTMLLinkElement) schedule()
183
+ }
184
+ document.addEventListener("load", onLoad, true)
13
185
 
14
- /* ---------- inlined from src/components/chart-utils.ts (internal to @squadbase/vantage) ---------- */
186
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
187
+ media.addEventListener("change", schedule)
188
+
189
+ return () => {
190
+ if (frame) cancelAnimationFrame(frame)
191
+ themeObserver.disconnect()
192
+ styleObserver.disconnect()
193
+ document.removeEventListener("load", onLoad, true)
194
+ media.removeEventListener("change", schedule)
195
+ }
196
+ }
197
+
198
+ /** Shared shape for the four axis types ECharts themes address separately. */
199
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
200
+ const line = tokens.border ?? undefined
201
+ return {
202
+ axisLine: { show: false },
203
+ axisTick: { show: false },
204
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
205
+ // Faint horizontal rules only: the border colour at low opacity.
206
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
207
+ splitArea: { show: false },
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
213
+ * app that sets its own palette keeps it.
214
+ */
215
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
216
+ const text = tokens.foreground ?? undefined
217
+ const muted = tokens.mutedForeground ?? undefined
218
+ const line = tokens.border ?? undefined
219
+ return {
220
+ // Let the page background show through: charts sit on cards, not on a canvas.
221
+ backgroundColor: "transparent",
222
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
223
+ textStyle: { color: text },
224
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
225
+ legend: { textStyle: { color: muted } },
226
+ categoryAxis: axisTheme(tokens, false),
227
+ valueAxis: axisTheme(tokens, true),
228
+ logAxis: axisTheme(tokens, true),
229
+ timeAxis: axisTheme(tokens, true),
230
+ tooltip: {
231
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
232
+ transitionDuration: 0,
233
+ backgroundColor: tokens.popover ?? undefined,
234
+ borderColor: line,
235
+ borderWidth: 1,
236
+ padding: [8, 12],
237
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
238
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
239
+ textStyle: { color: tokens.popoverForeground ?? undefined, fontSize: 12 },
240
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
241
+ },
242
+ }
243
+ }
244
+
245
+ /**
246
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
247
+ * they may have moved, and only replaced when a value actually changed. For
248
+ * components that build an ECharts option from token colours themselves (the
249
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
250
+ */
251
+ function useChartTokens(): ChartTokens | null {
252
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
253
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
254
+ // replayed by React on every rebase and returns a fresh object each time, so the state
255
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
256
+ const tokensRef = useRef(tokens)
257
+ useEffect(() => {
258
+ const sync = () => {
259
+ const next = readChartTokens()
260
+ if (sameChartTokens(tokensRef.current, next)) return
261
+ tokensRef.current = next
262
+ setTokens(next)
263
+ }
264
+ sync()
265
+ return watchChartTokens(sync)
266
+ }, [])
267
+ return tokens
268
+ }
269
+
270
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
271
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
272
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
273
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
274
+
275
+ /**
276
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
277
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
278
+ * variants `"positive-fill"`, …) are read off the document root (`--positive`, …); `var(--token)` is read off the document root; any
279
+ * other CSS colour is normalized like the tokens are. A colour that can't be
280
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
281
+ */
282
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
283
+ return colors.map((color) => {
284
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
285
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
286
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
287
+ if (TONE_NAME_RE.test(color.trim())) {
288
+ if (typeof document === "undefined") return ""
289
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue(`--${color.trim()}`)) ?? ""
290
+ }
291
+ if (typeof document === "undefined") return color
292
+ let value = color.trim()
293
+ const cssVar = CSS_VAR_RE.exec(value)
294
+ const styles = getComputedStyle(document.documentElement)
295
+ if (cssVar) {
296
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
297
+ } else if (value.includes("var(")) {
298
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
299
+ // substitute the tokens, then let the canvas resolve the rest.
300
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
301
+ }
302
+ return toCanvasColor(value) ?? ""
303
+ })
304
+ }
305
+
306
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
307
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
308
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
309
+ ["positive", "warning", "negative", "neutral"],
310
+ tokens,
311
+ )
312
+ return { positive, warning, negative, neutral }
313
+ }
314
+
315
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
316
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
317
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
318
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
319
+ tokens,
320
+ )
321
+ return { positive, warning, negative, neutral }
322
+ }
323
+
324
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
325
+
326
+ /**
327
+ * The colour the chart is painted on: the first opaque `background-color` up
328
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
329
+ * outside the browser.
330
+ */
331
+ function readChartSurface(el: Element | null): string | null {
332
+ if (typeof document === "undefined") return null
333
+ for (let node: Element | null = el; node; node = node.parentElement) {
334
+ const bg = getComputedStyle(node).backgroundColor.trim()
335
+ if (bg && !TRANSPARENT_RE.test(bg)) {
336
+ const color = toCanvasColor(bg)
337
+ if (color) return color
338
+ }
339
+ }
340
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue("--background"))
341
+ }
342
+
343
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
344
+ const WIDTH_BUCKET = 40
345
+
346
+ /**
347
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
348
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
349
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
350
+ * component's forwarded ref.
351
+ */
352
+ function useChartSurface<E extends Element>(
353
+ forwarded: ForwardedRef<E>,
354
+ tokens: ChartTokens | null,
355
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined } {
356
+ const [node, setNode] = useState<E | null>(null)
357
+ const [surface, setSurface] = useState<string | undefined>(undefined)
358
+ const [width, setWidth] = useState<number | undefined>(undefined)
359
+ const ref = useCallback(
360
+ (el: E | null) => {
361
+ setNode(el)
362
+ if (typeof forwarded === "function") forwarded(el)
363
+ else if (forwarded) forwarded.current = el
364
+ },
365
+ [forwarded],
366
+ )
367
+ useEffect(() => {
368
+ if (!node) return
369
+ setSurface(readChartSurface(node) ?? undefined)
370
+ }, [node, tokens])
371
+ useEffect(() => {
372
+ if (!node || typeof ResizeObserver === "undefined") return
373
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
374
+ update(node.getBoundingClientRect().width)
375
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
376
+ observer.observe(node)
377
+ return () => observer.disconnect()
378
+ }, [node])
379
+ return { ref, surface, width }
380
+ }
381
+
382
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
383
+
384
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
385
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
386
+
387
+ /**
388
+ * The attributes of a typed chart's leftover props that belong on its root
389
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
390
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
391
+ */
392
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
393
+ const out: Record<string, unknown> = {}
394
+ for (const [key, value] of Object.entries(rest)) {
395
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
396
+ }
397
+ return out
398
+ }
15
399
 
16
400
  /** The series tokens, in palette order — the default `colors` of every typed chart. */
17
401
  const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
@@ -24,13 +408,37 @@ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
24
408
 
25
409
  const TOKEN_NAME_RE = /^chart-[1-5]$/
26
410
 
411
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
412
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
413
+
414
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
415
+ function isChartTone(color: string): color is ChartTone {
416
+ return (CHART_TONES as readonly string[]).includes(color.trim())
417
+ }
418
+
27
419
  /**
28
420
  * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
29
421
  * light/dark on its own), anything else passes through unchanged.
30
422
  */
31
423
  function chartColorToCss(color: ChartColor): string {
32
424
  const value = color.trim()
33
- return TOKEN_NAME_RE.test(value) ? `var(--${value})` : value
425
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
426
+ }
427
+
428
+ /**
429
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
430
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
431
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
432
+ */
433
+ function chartFillToCss(color: ChartColor): string {
434
+ const value = color.trim()
435
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
436
+ }
437
+
438
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
439
+ function chartFillName(color: ChartColor): ChartColor {
440
+ const value = color.trim()
441
+ return isChartTone(value) ? `${value}-fill` : color
34
442
  }
35
443
 
36
444
  /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
@@ -54,6 +462,79 @@ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 }
54
462
  /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
55
463
  const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
56
464
 
465
+ /**
466
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
467
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
468
+ */
469
+ function resolveValueFormatter(
470
+ valueFormatter: ValueFormatter | undefined,
471
+ format: ValueFormat | undefined,
472
+ locale?: string,
473
+ ): ValueFormatter {
474
+ return valueFormatter ?? toValueFormatter(format, locale)
475
+ }
476
+
477
+ /**
478
+ * The formatter of value-axis ticks and on-plot labels: an explicit
479
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
480
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
481
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
482
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
483
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
484
+ * currency sign and grouping.
485
+ */
486
+ function resolveAxisFormatter(
487
+ valueFormatter: ValueFormatter | undefined,
488
+ format: ValueFormat | undefined,
489
+ locale: string = DEFAULT_LOCALE,
490
+ ): ValueFormatter {
491
+ if (valueFormatter) return valueFormatter
492
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
493
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
494
+ const currency = "currency" in spec ? spec.currency : undefined
495
+ const short: ValueFormat =
496
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
497
+ return (value) => formatValue(value, short, locale)
498
+ }
499
+
500
+ /** The unit words of a ja number (`1.2万` / `3.4億` / `1兆`) and their sizes, largest first. */
501
+ const JA_UNITS = [
502
+ { char: "兆", size: 1e12 },
503
+ { char: "億", size: 1e8 },
504
+ { char: "万", size: 1e4 },
505
+ ] as const
506
+
507
+ const JA_NUMBER_TOKEN_RE = /\d[\d,]*(?:\.\d+)?(?:兆|億|万)?/
508
+
509
+ /**
510
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
511
+ * that largest tick, so 万 and 億 never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`).
512
+ * Only the ja short forms (`compact` / `number` / `currency`, no `valueFormatter`) have units to align;
513
+ * any other format — and an axis whose largest tick is under 1万 — keeps `resolveAxisFormatter`'s output as it is.
514
+ */
515
+ function resolveAxisTickFormatter(
516
+ valueFormatter: ValueFormatter | undefined,
517
+ format: ValueFormat | undefined,
518
+ locale: string = DEFAULT_LOCALE,
519
+ ): (top: number) => ValueFormatter {
520
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
521
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
522
+ const aligns =
523
+ !valueFormatter && locale.toLowerCase().startsWith("ja") && (spec.type === "compact" || spec.type === "number" || spec.type === "currency")
524
+ if (!aligns) return () => base
525
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
526
+ return (top) => {
527
+ const unit = JA_UNITS.find((u) => Math.abs(top) >= u.size)
528
+ if (!unit) return base
529
+ return (value) => {
530
+ const text = base(value)
531
+ if (value === 0 || !Number.isFinite(value)) return text
532
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.char}`
533
+ return text.replace(JA_NUMBER_TOKEN_RE, () => scaled)
534
+ }
535
+ }
536
+ }
537
+
57
538
  /**
58
539
  * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
59
540
  * `DECIMAL` / `BIGINT` columns usually arrive as strings.
@@ -73,6 +554,222 @@ function clamp(value: number, min: number, max: number): number {
73
554
  return Math.min(max, Math.max(min, value))
74
555
  }
75
556
 
557
+ /* ------------------------------------------------------------ aggregation */
558
+
559
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
560
+ const MAX_CHART_SERIES = 5
561
+
562
+ /** The series name the folded categories get. */
563
+ const OTHER_SERIES_LABEL = "その他"
564
+
565
+ interface AggregatedItems<Item extends { name: string; value: number }> {
566
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
567
+ top: Item[]
568
+ /** The items folded into `other`, in their given order. */
569
+ rest: Item[]
570
+ /** The folded remainder, or `null` when nothing was folded. */
571
+ other: { name: string; value: number } | null
572
+ }
573
+
574
+ /**
575
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
576
+ * given order and fold the rest into one `otherLabel` item. Shared by every
577
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
578
+ * BarList rows).
579
+ */
580
+ function aggregateTopN<Item extends { name: string; value: number }>(
581
+ items: readonly Item[],
582
+ n: number = MAX_CHART_SERIES,
583
+ otherLabel: string = OTHER_SERIES_LABEL,
584
+ ): AggregatedItems<Item> {
585
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
586
+ const ranked = items
587
+ .map((item, i) => ({ item, i }))
588
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
589
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
590
+ const top = items.filter((_, i) => keep.has(i))
591
+ const rest = items.filter((_, i) => !keep.has(i))
592
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
593
+ }
594
+
595
+ interface AggregatedSeries {
596
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
597
+ data: Record<string, unknown>[]
598
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
599
+ categories: string[]
600
+ /** The folded series' name, or `null`. */
601
+ otherCategory: string | null
602
+ }
603
+
604
+ /**
605
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
606
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
607
+ */
608
+ function aggregateSeries(
609
+ data: readonly Record<string, unknown>[],
610
+ categories: readonly string[],
611
+ n: number = MAX_CHART_SERIES,
612
+ otherLabel: string = OTHER_SERIES_LABEL,
613
+ ): AggregatedSeries {
614
+ const totals = categories.map((name) => ({
615
+ name,
616
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
617
+ }))
618
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
619
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
620
+ const folded = rest.map((item) => item.name)
621
+ return {
622
+ data: data.map((row) => {
623
+ let sum: number | null = null
624
+ for (const name of folded) {
625
+ const v = toChartNumber(row[name])
626
+ if (v !== null) sum = (sum ?? 0) + v
627
+ }
628
+ return { ...row, [other.name]: sum }
629
+ }),
630
+ categories: [...top.map((item) => item.name), other.name],
631
+ otherCategory: other.name,
632
+ }
633
+ }
634
+
635
+ /**
636
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
637
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
638
+ */
639
+ function aggregateSeriesKeeping(
640
+ data: readonly Record<string, unknown>[],
641
+ categories: readonly string[],
642
+ keep: string | undefined,
643
+ n: number = MAX_CHART_SERIES,
644
+ ): AggregatedSeries {
645
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n)
646
+ const aggregated = aggregateSeries(
647
+ data,
648
+ categories.filter((c) => c !== keep),
649
+ n,
650
+ )
651
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
652
+ }
653
+
654
+ /**
655
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
656
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
657
+ * so a main series keeps its colour whether or not a comparison is drawn.
658
+ */
659
+ function seriesColorsWithComparison(
660
+ categories: readonly string[],
661
+ colors: ChartColors | undefined,
662
+ otherColor: string,
663
+ otherCategory: string | null,
664
+ allCategories: readonly string[],
665
+ comparison: string | undefined,
666
+ ): string[] {
667
+ if (comparison === undefined || !categories.includes(comparison)) {
668
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
669
+ }
670
+ const main = categories.filter((c) => c !== comparison)
671
+ const mainColors = seriesColorsFor(
672
+ main,
673
+ colors,
674
+ otherColor,
675
+ otherCategory,
676
+ allCategories.filter((c) => c !== comparison),
677
+ )
678
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
679
+ }
680
+
681
+ /**
682
+ * Colour per drawn series: the record's token for that category, else the
683
+ * array's token at the category's position in `allCategories` (cycled), else
684
+ * the token palette by drawn position. `otherCategory` — and a category the
685
+ * data itself names「その他」(`OTHER_SERIES_LABEL`) — always gets `otherColor`.
686
+ */
687
+ function seriesColorsFor(
688
+ categories: readonly string[],
689
+ colors: ChartColors | undefined,
690
+ otherColor: string,
691
+ otherCategory: string | null = null,
692
+ allCategories: readonly string[] = categories,
693
+ ): string[] {
694
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
695
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
696
+ return categories.map((category, i) => {
697
+ if ((otherCategory !== null && category === otherCategory) || category === OTHER_SERIES_LABEL) return otherColor
698
+ const fromRecord = record?.[category]
699
+ if (fromRecord) return fromRecord
700
+ if (list && list.length > 0) {
701
+ const at = allCategories.indexOf(category)
702
+ return list[(at === -1 ? i : at) % list.length]!
703
+ }
704
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
705
+ })
706
+ }
707
+
708
+ /* ------------------------------------------------------------------ Donut */
709
+
710
+ /** One drawn donut slice, largest first. */
711
+ interface DonutSlice {
712
+ name: string
713
+ /** Negative and missing values count as 0. */
714
+ value: number
715
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
716
+ color: string
717
+ /** The folded「その他」slice. */
718
+ isOther: boolean
719
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
720
+ row: Record<string, unknown>
721
+ }
722
+
723
+ interface DonutSlicesConfig {
724
+ /** Label column. */
725
+ index: string
726
+ /** Value column. */
727
+ value: string
728
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
729
+ colors?: readonly ChartSeriesColor[]
730
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
731
+ maxSlices?: number
732
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
733
+ otherColor: string
734
+ otherLabel?: string
735
+ }
736
+
737
+ /**
738
+ * Donut slices: sorted by value (largest first, ties keep input order), the
739
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
740
+ * summed into one「その他」slice in `otherColor`.
741
+ */
742
+ function donutSlices(
743
+ data: readonly Record<string, unknown>[],
744
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = OTHER_SERIES_LABEL }: DonutSlicesConfig,
745
+ ): DonutSlice[] {
746
+ const items = data
747
+ .map((row, i) => {
748
+ const n = toChartNumber(row[value])
749
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
750
+ })
751
+ .sort((a, b) => b.value - a.value || a.i - b.i)
752
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
753
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
754
+ const slices: DonutSlice[] = top.map((item, rank) => ({
755
+ name: item.name,
756
+ value: item.value,
757
+ color: palette[rank % palette.length]!,
758
+ isOther: false,
759
+ row: item.row,
760
+ }))
761
+ if (other) {
762
+ slices.push({
763
+ name: other.name,
764
+ value: other.value,
765
+ color: otherColor,
766
+ isOther: true,
767
+ row: { [index]: other.name, [value]: other.value },
768
+ })
769
+ }
770
+ return slices
771
+ }
772
+
76
773
  /* ---------------------------------------------------------------- BarList */
77
774
 
78
775
  type BarListSortOrder = "ascending" | "descending" | "none"
@@ -85,6 +782,78 @@ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOr
85
782
  return rows
86
783
  }
87
784
 
785
+ /** BarList-only settings. */
786
+ interface BarListOptions {
787
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
788
+ sortOrder?: BarListSortOrder
789
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
790
+ maxItems?: number
791
+ /** まとめた行のラベル。既定「その他」。 */
792
+ otherLabel?: string
793
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
794
+ exclude?: readonly string[]
795
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
796
+ showShare?: boolean
797
+ }
798
+
799
+ /** One drawn BarList row. */
800
+ interface BarListRow<Row = Record<string, unknown>> {
801
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
802
+ key: string
803
+ name: string
804
+ value: number
805
+ /** Only for real rows; the folded row never links. */
806
+ href?: string
807
+ /** Legacy per-row colour (`BarListItem.color`). */
808
+ color?: ChartColor
809
+ /** The folded「その他」row. */
810
+ isOther: boolean
811
+ /** The input row (`null` for the folded row). */
812
+ row: Row | null
813
+ }
814
+
815
+ interface BarListRowsConfig extends BarListOptions {
816
+ /** Name column. Default `"name"`. */
817
+ index?: string
818
+ /** Value column. Default `"value"`. */
819
+ category?: string
820
+ }
821
+
822
+ /**
823
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
824
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
825
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
826
+ * ranking and are always added to「その他」.
827
+ */
828
+ function barListRows<Row extends object>(
829
+ data: readonly Row[],
830
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = OTHER_SERIES_LABEL, exclude }: BarListRowsConfig = {},
831
+ ): BarListRow<Row>[] {
832
+ const items = data.map((row): BarListRow<Row> => {
833
+ const cells = row as Record<string, unknown>
834
+ const name = String(cells[index] ?? "")
835
+ return {
836
+ key: typeof cells.key === "string" ? cells.key : name,
837
+ name,
838
+ value: toChartNumber(cells[category]) ?? 0,
839
+ href: typeof cells.href === "string" ? cells.href : undefined,
840
+ color: typeof cells.color === "string" ? cells.color : undefined,
841
+ isOther: false,
842
+ row,
843
+ }
844
+ })
845
+ const excluded = new Set(exclude ?? [])
846
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
847
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
848
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
849
+ const rows = sortBarListData(top, sortOrder)
850
+ if (other || outside.length > 0) {
851
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
852
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
853
+ }
854
+ return rows
855
+ }
856
+
88
857
  /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
89
858
  function barListWidths(values: readonly number[]): number[] {
90
859
  const max = Math.max(0, ...values)
@@ -92,6 +861,100 @@ function barListWidths(values: readonly number[]): number[] {
92
861
  return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
93
862
  }
94
863
 
864
+ /**
865
+ * How strongly the BarList bars are painted: every row the same tint of the bar
866
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
867
+ * it sits on the card in light and dark; it must stay visible against the card
868
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
869
+ */
870
+ const BAR_LIST_TINT = 45
871
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
872
+ const BAR_LIST_OTHER_TINT = 30
873
+
874
+ /**
875
+ * The fill of each BarList row: all real rows in the same tint of `color`
876
+ * (`BAR_LIST_TINT`), the folded「その他」row in a tint of `otherColor`
877
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
878
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
879
+ * for that row. A tint, not the solid token, so the label printed over the bar
880
+ * keeps its contrast.
881
+ */
882
+ function barListFills(
883
+ rows: readonly Pick<BarListRow, "isOther" | "color">[],
884
+ color: ChartColor,
885
+ otherColor: string,
886
+ ): string[] {
887
+ return rows.map((row) =>
888
+ row.isOther ? tintCss(otherColor, BAR_LIST_OTHER_TINT) : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
889
+ )
890
+ }
891
+
892
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
893
+ function barListShareText(value: number, total: number): string {
894
+ const v = Number.isFinite(value) && value > 0 ? value : 0
895
+ if (total <= 0 || v === 0) return "0%"
896
+ const pct = (v / total) * 100
897
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
898
+ }
899
+
900
+ /**
901
+ * The text at the end of each BarList row: the formatted value and, with
902
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
903
+ * so the shares are of the whole list): `value` and `share` apart (the share is
904
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
905
+ */
906
+ function barListValueTexts(
907
+ values: readonly number[],
908
+ formatter: ValueFormatter,
909
+ showShare = false,
910
+ ): { value: string; share?: string; text: string }[] {
911
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
912
+ return values.map((v) => {
913
+ const value = formatter(v)
914
+ if (!showShare) return { value, text: value }
915
+ const share = barListShareText(v, total)
916
+ return { value, share, text: `${value} · ${share}` }
917
+ })
918
+ }
919
+
920
+ /* -------------------------------------------------------------- DataTable */
921
+
922
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
923
+ interface ChartDataTable {
924
+ /** 表の見出し(`<caption>`)。 */
925
+ caption?: string
926
+ /** 列見出し。先頭がラベル列。 */
927
+ columns: string[]
928
+ /** 行。セルは書式済みの文字列。 */
929
+ rows: string[][]
930
+ }
931
+
932
+ /**
933
+ * The chart's numbers as a table, for screen readers: one row per data row, the
934
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
935
+ * 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).
936
+ */
937
+ function chartDataTable(
938
+ data: readonly Record<string, unknown>[],
939
+ index: string,
940
+ categories: readonly string[],
941
+ formatter: ValueFormatter,
942
+ labels?: Readonly<Record<string, string>>,
943
+ indexName?: string,
944
+ ): ChartDataTable {
945
+ const label = (key: string) => labels?.[key] ?? key
946
+ return {
947
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
948
+ rows: data.map((row) => [
949
+ String(row[index] ?? ""),
950
+ ...categories.map((key) => {
951
+ const n = toChartNumber(row[key])
952
+ return n === null ? EMPTY_VALUE : formatter(n)
953
+ }),
954
+ ]),
955
+ }
956
+ }
957
+
95
958
  /* ------------------------------------------------------------ CategoryBar */
96
959
 
97
960
  interface CategoryBarSegment {
@@ -126,9 +989,11 @@ interface CategoryBarLabel {
126
989
  * Tick labels under the bar: `0` at the start, then the running total at each
127
990
  * segment's end. A label closer than `minGap` percent to the one before is
128
991
  * dropped so narrow segments don't print on top of each other — except the
129
- * last one (the total), which replaces its neighbour instead.
992
+ * last one (the total), which replaces its neighbour instead. With a
993
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
994
+ * too — the marker sits right under it and the two read as one crowded spot.
130
995
  */
131
- function categoryBarLabels(values: readonly number[], minGap = 8): CategoryBarLabel[] {
996
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
132
997
  const segments = categoryBarSegments(values).filter((s) => s.width > 0)
133
998
  if (segments.length === 0) return []
134
999
  const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
@@ -138,7 +1003,46 @@ function categoryBarLabels(values: readonly number[], minGap = 8): CategoryBarLa
138
1003
  if (label.position - prev.position >= minGap) labels.push(label)
139
1004
  else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
140
1005
  })
141
- return labels
1006
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1007
+ return labels.filter(
1008
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1009
+ )
1010
+ }
1011
+
1012
+ /**
1013
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1014
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1015
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1016
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1017
+ * the rest 7 px at 12 px type).
1018
+ */
1019
+ function categoryBarFitLabels(
1020
+ labels: readonly CategoryBarLabel[],
1021
+ texts: readonly string[],
1022
+ width: number,
1023
+ gap = 8,
1024
+ ): CategoryBarLabel[] {
1025
+ const textWidth = (text: string) => {
1026
+ let w = 0
1027
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1028
+ return w
1029
+ }
1030
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1031
+ const w = textWidth(text)
1032
+ if (label.position <= 0) return [0, w]
1033
+ if (label.position >= 100) return [width - w, width]
1034
+ const center = (label.position / 100) * width
1035
+ return [center - w / 2, center + w / 2]
1036
+ }
1037
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1038
+ labels.forEach((label, i) => {
1039
+ const here = extent(label, texts[i] ?? "")
1040
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1041
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1042
+ else if (touches()) return
1043
+ kept.push({ label, extent: here })
1044
+ })
1045
+ return kept.map((k) => k.label)
142
1046
  }
143
1047
 
144
1048
  /** Marker position in percent of the bar, clamped to its ends. */
@@ -183,6 +1087,62 @@ function progressCircleGeometry(
183
1087
  return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
184
1088
  }
185
1089
 
1090
+ /* ---------------------------------------------------------------- summary */
1091
+
1092
+ interface ChartSummaryInput {
1093
+ data: readonly Record<string, unknown>[]
1094
+ /** The x-axis key. */
1095
+ index: string
1096
+ /** Series keys; the first one is described. */
1097
+ categories: readonly string[]
1098
+ /** Title of the chart, put in front when given. */
1099
+ title?: string
1100
+ /** Same as the chart's `format` (default `"compact"`). */
1101
+ format?: ValueFormat
1102
+ /** Wins over `format`. */
1103
+ valueFormatter?: ValueFormatter
1104
+ }
1105
+
1106
+ /**
1107
+ * One-sentence summary built from the rows, for `summary="auto"`:
1108
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」. The direction is
1109
+ * computed from the last two non-empty points of the first series — never
1110
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1111
+ * no usable point.
1112
+ */
1113
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1114
+ const key = input.categories[0]
1115
+ if (key === undefined) return undefined
1116
+ const points: { label: string; value: number }[] = []
1117
+ for (const row of input.data) {
1118
+ const raw = row[key]
1119
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1120
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1121
+ }
1122
+ const latest = points[points.length - 1]
1123
+ if (!latest) return undefined
1124
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact")
1125
+ const prev = points[points.length - 2]
1126
+ const direction = !prev ? "" : latest.value > prev.value ? "、前の点より増加" : latest.value < prev.value ? "、前の点より減少" : "、前の点と横ばい"
1127
+ const head = input.title ? `${input.title}: ` : ""
1128
+ return `${head}最新 ${latest.label} は ${text(latest.value)}${direction}`
1129
+ }
1130
+
1131
+ /**
1132
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」 from the slices
1133
+ * (largest first). `undefined` when there is nothing to describe.
1134
+ */
1135
+ function buildShareSummary(
1136
+ slices: readonly { name: string; value: number }[],
1137
+ title?: string,
1138
+ ): string | undefined {
1139
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1140
+ const top = slices[0]
1141
+ if (!top || total <= 0) return undefined
1142
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1143
+ return `${title ? `${title}: ` : ""}最大は ${top.name}(${share})`
1144
+ }
1145
+
186
1146
  /* ---------- end of inlined code ---------- */
187
1147
 
188
1148
  export interface CategoryBarMarker {
@@ -190,30 +1150,44 @@ export interface CategoryBarMarker {
190
1150
  value: number
191
1151
  /** ホバーで出す説明。 */
192
1152
  tooltip?: string
193
- /** 位置の変化をアニメーションする。 */
1153
+ /** 位置の変化をアニメーションする。既定 `false`(`prefers-reduced-motion` では常に無効)。 */
194
1154
  showAnimation?: boolean
195
1155
  }
196
1156
 
197
1157
  export interface CategoryBarProps extends Omit<ComponentProps<"div">, "children"> {
198
1158
  /** 各区間の幅(相対値)。合計が 100 である必要はない。負の値は 0 扱い。 */
199
1159
  values: number[]
200
- /** 区間の色(順に対応)。`"chart-1"`〜`"chart-5"` か CSS カラー。省略時はトークン順。 */
1160
+ /** 区間の色(順に対応)。`"chart-1"`〜`"chart-5"`・意味色(`"positive"` など。面用の `--<tone>-fill` で塗る)・CSS カラー。省略時はトークン順。 */
201
1161
  colors?: ChartColor[]
202
1162
  marker?: CategoryBarMarker
203
1163
  /** バーの上に区切りの累計値を出す。既定 `true`。 */
204
1164
  showLabels?: boolean
205
- /** 区切りの数値の書式。 */
1165
+ /**
1166
+ * 区切りの数値の書式(`"compact"` / `"currency"` / `{ type, currency }`)。他のグラフの
1167
+ * 軸と同じ短縮形で出す(`"currency"` → `¥780万`)。既定 `"compact"`。
1168
+ */
1169
+ format?: ValueFormat
1170
+ /** 書式を関数で直接渡す逃げ道。`format` より優先する。 */
206
1171
  valueFormatter?: ValueFormatter
207
1172
  }
208
1173
 
1174
+ /** Values not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
1175
+ const NO_ROWS: never[] = []
1176
+
209
1177
  export const CategoryBar = forwardRef<HTMLDivElement, CategoryBarProps>(function CategoryBar(
210
- { values, colors, marker, showLabels = true, valueFormatter = defaultValueFormatter, className, ...props },
211
- ref,
1178
+ { values = NO_ROWS, colors, marker, showLabels = true, format, valueFormatter: valueFormatterProp, className, ...props },
1179
+ forwardedRef,
212
1180
  ) {
1181
+ // The bar's width thins the running totals that would print over each other.
1182
+ const { ref, width } = useChartSurface(forwardedRef, null)
1183
+ const valueFormatter = useMemo(() => resolveAxisFormatter(valueFormatterProp, format), [valueFormatterProp, format])
213
1184
  const segments = categoryBarSegments(values)
214
- const labels = showLabels ? categoryBarLabels(values) : []
215
1185
  const markerPosition = marker ? categoryBarMarkerPosition(marker.value, values) : 0
216
- const markerColor = marker ? chartColorToCss(chartColorAt(colors, categoryBarMarkerSegment(marker.value, values))) : ""
1186
+ const allLabels = showLabels ? categoryBarLabels(values, undefined, marker ? markerPosition : undefined) : []
1187
+ const labels = width
1188
+ ? categoryBarFitLabels(allLabels, allLabels.map((label) => valueFormatter(label.value)), width)
1189
+ : allLabels
1190
+ const markerColor = marker ? chartFillToCss(chartColorAt(colors, categoryBarMarkerSegment(marker.value, values))) : ""
217
1191
 
218
1192
  const markerDot = (
219
1193
  <span
@@ -248,7 +1222,7 @@ export const CategoryBar = forwardRef<HTMLDivElement, CategoryBarProps>(function
248
1222
  key={i}
249
1223
  data-slot="category-bar-segment"
250
1224
  className="h-full"
251
- style={{ flex: `${segment.width} 1 0%`, background: chartColorToCss(chartColorAt(colors, i)) }}
1225
+ style={{ flex: `${segment.width} 1 0%`, background: chartFillToCss(chartColorAt(colors, i)) }}
252
1226
  />
253
1227
  ) : null,
254
1228
  )}
@@ -258,7 +1232,7 @@ export const CategoryBar = forwardRef<HTMLDivElement, CategoryBarProps>(function
258
1232
  data-slot="category-bar-marker"
259
1233
  className={cn(
260
1234
  "absolute -translate-x-1/2",
261
- marker.showAnimation && "transition-[left] duration-700 ease-out",
1235
+ marker.showAnimation && "transition-[left] duration-700 ease-out motion-reduce:transition-none",
262
1236
  )}
263
1237
  style={{ left: `${markerPosition}%` }}
264
1238
  >