@squadbase/vantage 0.6.1 → 0.6.2-dev1.1c9e8bc

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