@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.5aae04e

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