@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.54bde93

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