@squadbase/vantage 0.6.2-dev1.b332e5a → 0.6.2-dev1.d7c0911

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (212) hide show
  1. package/dist/add-4GHF2TX2.js +6 -0
  2. package/dist/add-4GHF2TX2.js.map +1 -0
  3. package/dist/{build-TVKFIVFQ.js → build-X5NVCQKT.js} +7 -7
  4. package/dist/{build-TVKFIVFQ.js.map → build-X5NVCQKT.js.map} +1 -1
  5. package/dist/{check-3KHZXZMQ.js → check-ZBIH422T.js} +5 -5
  6. package/dist/{check-3KHZXZMQ.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-P7W4LR3Z.js → chunk-7DZGJQ3P.js} +3 -3
  12. package/dist/{chunk-P7W4LR3Z.js.map → chunk-7DZGJQ3P.js.map} +1 -1
  13. package/dist/{chunk-U2M6HGKQ.js → chunk-AABMKHEU.js} +4 -4
  14. package/dist/{chunk-U2M6HGKQ.js.map → chunk-AABMKHEU.js.map} +1 -1
  15. package/dist/{chunk-QI3XQKHS.js → chunk-GNXCX4WE.js} +10 -3
  16. package/dist/chunk-GNXCX4WE.js.map +1 -0
  17. package/dist/{chunk-PXRX5PEC.js → chunk-PDOBHMUQ.js} +3 -3
  18. package/dist/chunk-PDOBHMUQ.js.map +1 -0
  19. package/dist/{chunk-ZVANIULZ.js → chunk-RNTDBX6S.js} +4 -4
  20. package/dist/{chunk-ZVANIULZ.js.map → chunk-RNTDBX6S.js.map} +1 -1
  21. package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
  22. package/dist/chunk-U736PVHY.js.map +1 -0
  23. package/dist/{chunk-PVTHHV7X.js → chunk-V3LF7BE7.js} +27 -5
  24. package/dist/chunk-V3LF7BE7.js.map +1 -0
  25. package/dist/{chunk-LMUACBMA.js → chunk-WAMZWZJB.js} +53 -8
  26. package/dist/chunk-WAMZWZJB.js.map +1 -0
  27. package/dist/chunk-WRSX2MDK.js +7866 -0
  28. package/dist/chunk-WRSX2MDK.js.map +1 -0
  29. package/dist/{chunk-RPZAALCX.js → chunk-XPQSTZUU.js} +254 -164
  30. package/dist/chunk-XPQSTZUU.js.map +1 -0
  31. package/dist/{chunk-DTDVSFRY.js → chunk-XQUSGIDG.js} +17 -3
  32. package/dist/chunk-XQUSGIDG.js.map +1 -0
  33. package/dist/cli.js +12 -11
  34. package/dist/cli.js.map +1 -1
  35. package/dist/client/index.d.ts +32 -3
  36. package/dist/client/index.js +205 -12
  37. package/dist/client/index.js.map +1 -1
  38. package/dist/components/index.d.ts +1975 -28
  39. package/dist/components/index.js +4 -4
  40. package/dist/{dev-GDKATCC7.js → dev-4XEDTELV.js} +8 -8
  41. package/dist/dev-4XEDTELV.js.map +1 -0
  42. package/dist/doc/index.js +2 -2
  43. package/dist/doc/index.js.map +1 -1
  44. package/dist/{docs-EJJ3BECT.js → docs-JVP4RPKT.js} +3 -3
  45. package/dist/{docs-EJJ3BECT.js.map → docs-JVP4RPKT.js.map} +1 -1
  46. package/dist/{doctor-WQXPXP6K.js → doctor-5E2VEZPK.js} +5 -5
  47. package/dist/{doctor-WQXPXP6K.js.map → doctor-5E2VEZPK.js.map} +1 -1
  48. package/dist/markdown/index.js +1 -1
  49. package/dist/markdown/index.js.map +1 -1
  50. package/dist/{preview-OGMCNQUO.js → preview-T6CLSQVX.js} +3 -3
  51. package/dist/{preview-OGMCNQUO.js.map → preview-T6CLSQVX.js.map} +1 -1
  52. package/dist/query/index.d.ts +0 -11
  53. package/dist/query/index.js +2 -2
  54. package/dist/{routes-MWBWWOJ2.js → routes-3SGAFDMC.js} +4 -4
  55. package/dist/{routes-MWBWWOJ2.js.map → routes-3SGAFDMC.js.map} +1 -1
  56. package/dist/{search-6Y422SV6.js → search-5LC4XPB5.js} +3 -3
  57. package/dist/{search-6Y422SV6.js.map → search-5LC4XPB5.js.map} +1 -1
  58. package/dist/table/index.js +10 -9
  59. package/dist/table/index.js.map +1 -1
  60. package/dist/ui/index.d.ts +144 -11
  61. package/dist/ui/index.js +1339 -87
  62. package/dist/ui/index.js.map +1 -1
  63. package/dist/{upgrade-HCANX4GQ.js → upgrade-JHXZBGQS.js} +6 -6
  64. package/dist/{upgrade-HCANX4GQ.js.map → upgrade-JHXZBGQS.js.map} +1 -1
  65. package/dist/vite/index.d.ts +10 -0
  66. package/dist/vite/index.js +3 -3
  67. package/docs/en/components.md +29 -15
  68. package/docs/en/parts/data-table.md +22 -0
  69. package/docs/en/parts/delta.md +50 -0
  70. package/docs/en/parts/format.md +43 -0
  71. package/docs/en/parts/kpi-card.md +57 -0
  72. package/docs/en/parts/metric-value.md +3 -2
  73. package/docs/en/parts/sparkline.md +1 -1
  74. package/docs/en/parts/trend-indicator.md +17 -1
  75. package/docs/en/ui-and-theming.md +1 -1
  76. package/docs/index.json +366 -76
  77. package/docs/ja/changelog.md +31 -0
  78. package/docs/ja/components.md +57 -101
  79. package/docs/ja/page-types/csv.md +83 -0
  80. package/docs/ja/page-types/doc.md +83 -0
  81. package/docs/ja/page-types/excel.md +82 -0
  82. package/docs/ja/page-types/slide.md +132 -0
  83. package/docs/ja/page-types.md +47 -0
  84. package/docs/ja/parts/area-chart.md +61 -0
  85. package/docs/ja/parts/bar-chart.md +69 -0
  86. package/docs/ja/parts/bar-list.md +35 -0
  87. package/docs/ja/parts/category-bar.md +36 -0
  88. package/docs/ja/parts/data-table.md +22 -0
  89. package/docs/ja/parts/delta.md +50 -0
  90. package/docs/ja/parts/donut-chart.md +47 -0
  91. package/docs/ja/parts/echart.md +3 -0
  92. package/docs/ja/parts/format.md +44 -0
  93. package/docs/ja/parts/kpi-card.md +55 -0
  94. package/docs/ja/parts/line-chart.md +58 -0
  95. package/docs/ja/parts/metric-value.md +3 -2
  96. package/docs/ja/parts/progress-circle.md +34 -0
  97. package/docs/ja/parts/sparkline.md +2 -2
  98. package/docs/ja/parts/tracker.md +32 -0
  99. package/docs/ja/parts/trend-indicator.md +17 -1
  100. package/docs/ja/routing.md +8 -86
  101. package/docs/ja/ui/alert-dialog.md +41 -0
  102. package/docs/ja/ui/avatar.md +31 -0
  103. package/docs/ja/ui/combobox.md +74 -0
  104. package/docs/ja/ui/drawer.md +41 -0
  105. package/docs/ja/ui/field.md +42 -0
  106. package/docs/ja/ui/hover-card.md +21 -0
  107. package/docs/ja/ui/kbd.md +16 -0
  108. package/docs/ja/ui/pagination.md +36 -0
  109. package/docs/ja/ui/radio-group.md +21 -0
  110. package/docs/ja/ui/toast.md +46 -0
  111. package/docs/ja/ui-and-theming.md +14 -7
  112. package/package.json +13 -4
  113. package/registry/ui/accordion.tsx +76 -0
  114. package/registry/ui/alert-dialog.tsx +189 -0
  115. package/registry/ui/alert.tsx +80 -0
  116. package/registry/ui/app-shell.tsx +287 -0
  117. package/registry/ui/area-chart.tsx +3639 -0
  118. package/registry/ui/avatar.tsx +110 -0
  119. package/registry/ui/badge.tsx +56 -0
  120. package/registry/ui/bar-chart.tsx +3636 -0
  121. package/registry/ui/bar-list.tsx +3680 -0
  122. package/registry/ui/breadcrumb.tsx +128 -0
  123. package/registry/ui/button.tsx +62 -0
  124. package/registry/ui/calendar.tsx +223 -0
  125. package/registry/ui/card.tsx +107 -0
  126. package/registry/ui/category-bar.tsx +1255 -0
  127. package/registry/ui/chart-frame.tsx +1358 -0
  128. package/registry/ui/checkbox.tsx +30 -0
  129. package/registry/ui/collapsible.tsx +23 -0
  130. package/registry/ui/combobox.tsx +310 -0
  131. package/registry/ui/command.tsx +198 -0
  132. package/registry/ui/dashboard-card.tsx +217 -0
  133. package/registry/ui/data-table.tsx +693 -146
  134. package/registry/ui/date-range-picker.tsx +390 -0
  135. package/registry/ui/delta.tsx +188 -0
  136. package/registry/ui/dialog.tsx +161 -0
  137. package/registry/ui/donut-chart.tsx +3688 -0
  138. package/registry/ui/drawer.tsx +229 -0
  139. package/registry/ui/dropdown-menu.tsx +274 -0
  140. package/registry/ui/echart.tsx +890 -0
  141. package/registry/ui/field.tsx +240 -0
  142. package/registry/ui/filter-bar.tsx +392 -0
  143. package/registry/ui/funnel-steps.tsx +3541 -0
  144. package/registry/ui/heatmap.tsx +1752 -0
  145. package/registry/ui/hover-card.tsx +52 -0
  146. package/registry/ui/input-group.tsx +160 -0
  147. package/registry/ui/input.tsx +24 -0
  148. package/registry/ui/kbd.tsx +30 -0
  149. package/registry/ui/kpi-card.tsx +677 -0
  150. package/registry/ui/label.tsx +22 -0
  151. package/registry/ui/legend.tsx +3500 -0
  152. package/registry/ui/line-chart.tsx +3637 -0
  153. package/registry/ui/metric-value.tsx +62 -0
  154. package/registry/ui/multi-select.tsx +232 -0
  155. package/registry/ui/page-shell.tsx +282 -0
  156. package/registry/ui/pagination.tsx +140 -0
  157. package/registry/ui/placeholder.tsx +36 -0
  158. package/registry/ui/popover.tsx +92 -0
  159. package/registry/ui/progress-circle.tsx +867 -0
  160. package/registry/ui/progress.tsx +85 -0
  161. package/registry/ui/radio-group.tsx +39 -0
  162. package/registry/ui/sample-data.tsx +86 -0
  163. package/registry/ui/scatter-chart.tsx +4150 -0
  164. package/registry/ui/scroll-area.tsx +56 -0
  165. package/registry/ui/searchable-select.tsx +214 -0
  166. package/registry/ui/section-header.tsx +43 -0
  167. package/registry/ui/segmented-control.tsx +76 -0
  168. package/registry/ui/select.tsx +255 -0
  169. package/registry/ui/separator.tsx +27 -0
  170. package/registry/ui/sheet.tsx +139 -0
  171. package/registry/ui/sidebar.tsx +725 -0
  172. package/registry/ui/skeleton.tsx +17 -0
  173. package/registry/ui/slider.tsx +56 -0
  174. package/registry/ui/sparkline.tsx +230 -0
  175. package/registry/ui/spinner.tsx +14 -0
  176. package/registry/ui/states.tsx +90 -0
  177. package/registry/ui/status-badge.tsx +121 -0
  178. package/registry/ui/switch.tsx +34 -0
  179. package/registry/ui/table.tsx +118 -0
  180. package/registry/ui/tabs.tsx +84 -0
  181. package/registry/ui/textarea.tsx +22 -0
  182. package/registry/ui/toast.tsx +250 -0
  183. package/registry/ui/toggle-group.tsx +91 -0
  184. package/registry/ui/toggle.tsx +47 -0
  185. package/registry/ui/tooltip.tsx +68 -0
  186. package/registry/ui/tracker.tsx +843 -0
  187. package/registry/ui/trend-indicator.tsx +74 -0
  188. package/registry/ui/updated-at.tsx +122 -0
  189. package/registry/ui/waterfall-chart.tsx +4186 -0
  190. package/skills/vantage-add-feature/SKILL.md +9 -7
  191. package/skills/vantage-pitfalls/SKILL.md +5 -1
  192. package/templates/AGENTS.md +22 -1
  193. package/templates/agents/csv.md +2 -1
  194. package/templates/agents/doc.md +4 -3
  195. package/templates/agents/page.md +20 -6
  196. package/templates/agents/xlsx.md +2 -1
  197. package/theme.css +237 -136
  198. package/dist/add-DY4AXANK.js +0 -6
  199. package/dist/add-DY4AXANK.js.map +0 -1
  200. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  201. package/dist/chunk-A2UUGASH.js.map +0 -1
  202. package/dist/chunk-DTDVSFRY.js.map +0 -1
  203. package/dist/chunk-LMUACBMA.js.map +0 -1
  204. package/dist/chunk-NKFBFDRZ.js +0 -2241
  205. package/dist/chunk-NKFBFDRZ.js.map +0 -1
  206. package/dist/chunk-PVTHHV7X.js.map +0 -1
  207. package/dist/chunk-PXRX5PEC.js.map +0 -1
  208. package/dist/chunk-QI3XQKHS.js.map +0 -1
  209. package/dist/chunk-RPZAALCX.js.map +0 -1
  210. package/dist/chunk-VA776YE5.js +0 -316
  211. package/dist/chunk-VA776YE5.js.map +0 -1
  212. package/dist/dev-GDKATCC7.js.map +0 -1
@@ -0,0 +1,1752 @@
1
+ // Copied by `vantage add ui heatmap`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/charts/heatmap.tsx by `npm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * Heatmap — a typed heatmap over `EChart`: pass rows, the column keys for the
7
+ * x axis / y axis (`x` / `y`) and the number to shade by (`value`) instead of an
8
+ * ECharts option. Cohort retention (週 × コホート), weekday × hour counts, …
9
+ *
10
+ * Shading is a single-colour ramp (light → dark) of one theme colour
11
+ * (`--chart-1` by default; `tone` moves it to another series token or a meaning
12
+ * colour) and follows light/dark. A cell with no value (null / missing row) is left
13
+ * unpainted (transparent, no text), never shaded like 0; the tooltip and the table say「—」.
14
+ * The shading range is the data's min–max unless `scale` fixes it. The ramp's lowest end is the tone mixed 20% into
15
+ * the surface (`color-mix(in oklch, var(--chart-1) 20%, var(--card))`), so the lowest cell never melts into the
16
+ * background in dark mode; the legend's gradient starts at the same colour.
17
+ * Renders inside `ChartFrame` (title, summary, loading skeleton, empty state)
18
+ * with the numbers as a screen-reader table.
19
+ */
20
+ import { forwardRef, useMemo, type ForwardedRef, type ReactElement, type Ref } from "react"
21
+ import { use } from "echarts/core"
22
+ import { HeatmapChart } from "echarts/charts"
23
+ import { VisualMapComponent } from "echarts/components"
24
+ import type { EChartsOption } from "echarts"
25
+
26
+ import { ChartFrame } from "@squadbase/vantage/components"
27
+ import { EChart } from "@squadbase/vantage/components"
28
+ import { EMPTY_VALUE, type ValueFormat } from "@squadbase/vantage/components"
29
+ import type { ChartActionsOptions, ChartEmptyState, ChartRootAttributes, ChartSeriesColor, ValueFormatter } from "@squadbase/vantage/components"
30
+ import { createContext, useCallback, useEffect, useRef, useState } from "react"
31
+ import type { ChartTone } from "@squadbase/vantage/components"
32
+ import { DEFAULT_LOCALE, formatValue, toValueFormatter } from "@squadbase/vantage/components"
33
+ import type { ChartColor, ChartColors } from "@squadbase/vantage/components"
34
+
35
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
36
+
37
+ /**
38
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
39
+ * grey is defined — every chart takes it from here. It is the most subdued
40
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
41
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
42
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
43
+ * slice. Canvas charts resolve it through `resolveChartColors`.
44
+ */
45
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
46
+
47
+ /**
48
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
49
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
50
+ */
51
+ const ChartFrameContext = createContext(false)
52
+
53
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
54
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
55
+
56
+ interface ChartTokens {
57
+ /** Resolved `--chart-1..5`, in order. */
58
+ series: string[]
59
+ /** Body text: titles and the default `textStyle`. */
60
+ foreground: string | null
61
+ /** Secondary text: axis labels, legend, subtitles. */
62
+ mutedForeground: string | null
63
+ /** Axis lines, ticks, split lines, tooltip border. */
64
+ border: string | null
65
+ /** Tooltip surface. */
66
+ popover: string | null
67
+ /** Tooltip text. */
68
+ popoverForeground: string | null
69
+ }
70
+
71
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
72
+
73
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
74
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
75
+
76
+ /**
77
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
78
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
79
+ * input is written over two different known colours: agreeing results mean the
80
+ * value parsed, differing ones mean it was dropped.
81
+ */
82
+ function toCanvasColor(value: string): string | null {
83
+ const raw = value.trim()
84
+ if (!raw) return null
85
+ if (normalizeContext === undefined) {
86
+ const canvas = document.createElement("canvas")
87
+ canvas.width = 1
88
+ canvas.height = 1
89
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
90
+ }
91
+ const ctx = normalizeContext
92
+ if (!ctx) return raw
93
+ ctx.fillStyle = "#000000"
94
+ ctx.fillStyle = raw
95
+ const onBlack = ctx.fillStyle
96
+ ctx.fillStyle = "#ffffff"
97
+ ctx.fillStyle = raw
98
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
99
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
100
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
101
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
102
+ ctx.clearRect(0, 0, 1, 1)
103
+ ctx.fillRect(0, 0, 1, 1)
104
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
105
+ return a === 255
106
+ ? `rgb(${r}, ${g}, ${b})`
107
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
108
+ }
109
+
110
+ /**
111
+ * Read the chart tokens off `el` (the document root by default — tokens live on
112
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
113
+ * to plain ECharts defaults.
114
+ */
115
+ function readChartTokens(el?: Element | null): ChartTokens | null {
116
+ if (typeof document === "undefined") return null
117
+ const target = el ?? document.documentElement
118
+ if (!target) return null
119
+ const styles = getComputedStyle(target)
120
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
121
+ const series: string[] = []
122
+ for (const token of SERIES_TOKENS) {
123
+ const color = read(token)
124
+ if (color) series.push(color)
125
+ }
126
+ return {
127
+ series,
128
+ foreground: read("--foreground"),
129
+ mutedForeground: read("--muted-foreground"),
130
+ border: read("--border"),
131
+ popover: read("--popover"),
132
+ popoverForeground: read("--popover-foreground"),
133
+ }
134
+ }
135
+
136
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
137
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
138
+ if (a === b) return true
139
+ if (!a || !b) return false
140
+ return (
141
+ a.series.length === b.series.length &&
142
+ a.series.every((color, i) => color === b.series[i]) &&
143
+ a.foreground === b.foreground &&
144
+ a.mutedForeground === b.mutedForeground &&
145
+ a.border === b.border &&
146
+ a.popover === b.popover &&
147
+ a.popoverForeground === b.popoverForeground
148
+ )
149
+ }
150
+
151
+ /**
152
+ * Watch everything that can change the resolved tokens and call `onChange` when
153
+ * something might have. It only ever says "re-read" — the caller compares with
154
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
155
+ * disposer.
156
+ *
157
+ * Two sources, not one:
158
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
159
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
160
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
161
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
162
+ * attributes alone leaves the chart painted in the previous palette until a
163
+ * reload — the tokens in the DOM are new, the canvas is not.
164
+ */
165
+ function watchChartTokens(onChange: () => void): () => void {
166
+ if (typeof document === "undefined") return () => {}
167
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
168
+ // take it after the next frame so a swapped stylesheet has been applied.
169
+ let frame = 0
170
+ const schedule = () => {
171
+ if (frame) return
172
+ frame = requestAnimationFrame(() => {
173
+ frame = 0
174
+ onChange()
175
+ })
176
+ }
177
+
178
+ const themeObserver = new MutationObserver(schedule)
179
+ const attributeFilter = ["class", "style", "data-theme"]
180
+ themeObserver.observe(document.documentElement, { attributes: true, attributeFilter })
181
+ if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter })
182
+
183
+ const styleObserver = new MutationObserver(schedule)
184
+ if (document.head) {
185
+ styleObserver.observe(document.head, {
186
+ childList: true,
187
+ subtree: true,
188
+ characterData: true,
189
+ attributes: true,
190
+ attributeFilter: ["href", "media", "disabled"],
191
+ })
192
+ }
193
+
194
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
195
+ const onLoad = (event: Event) => {
196
+ if (event.target instanceof HTMLLinkElement) schedule()
197
+ }
198
+ document.addEventListener("load", onLoad, true)
199
+
200
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
201
+ media.addEventListener("change", schedule)
202
+
203
+ return () => {
204
+ if (frame) cancelAnimationFrame(frame)
205
+ themeObserver.disconnect()
206
+ styleObserver.disconnect()
207
+ document.removeEventListener("load", onLoad, true)
208
+ media.removeEventListener("change", schedule)
209
+ }
210
+ }
211
+
212
+ /** Shared shape for the four axis types ECharts themes address separately. */
213
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
214
+ const line = tokens.border ?? undefined
215
+ return {
216
+ axisLine: { show: false },
217
+ axisTick: { show: false },
218
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
219
+ // Faint horizontal rules only: the border colour at low opacity.
220
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
221
+ splitArea: { show: false },
222
+ }
223
+ }
224
+
225
+ /**
226
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
227
+ * app that sets its own palette keeps it.
228
+ */
229
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
230
+ const text = tokens.foreground ?? undefined
231
+ const muted = tokens.mutedForeground ?? undefined
232
+ const line = tokens.border ?? undefined
233
+ return {
234
+ // Let the page background show through: charts sit on cards, not on a canvas.
235
+ backgroundColor: "transparent",
236
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
237
+ textStyle: { color: text },
238
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
239
+ legend: { textStyle: { color: muted } },
240
+ categoryAxis: axisTheme(tokens, false),
241
+ valueAxis: axisTheme(tokens, true),
242
+ logAxis: axisTheme(tokens, true),
243
+ timeAxis: axisTheme(tokens, true),
244
+ tooltip: {
245
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
246
+ transitionDuration: 0,
247
+ backgroundColor: tokens.popover ?? undefined,
248
+ borderColor: line,
249
+ borderWidth: 1,
250
+ padding: [8, 12],
251
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
252
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
253
+ textStyle: { color: tokens.popoverForeground ?? undefined, fontSize: 12 },
254
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
255
+ },
256
+ }
257
+ }
258
+
259
+ /**
260
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
261
+ * they may have moved, and only replaced when a value actually changed. For
262
+ * components that build an ECharts option from token colours themselves (the
263
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
264
+ */
265
+ function useChartTokens(): ChartTokens | null {
266
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
267
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
268
+ // replayed by React on every rebase and returns a fresh object each time, so the state
269
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
270
+ const tokensRef = useRef(tokens)
271
+ useEffect(() => {
272
+ const sync = () => {
273
+ const next = readChartTokens()
274
+ if (sameChartTokens(tokensRef.current, next)) return
275
+ tokensRef.current = next
276
+ setTokens(next)
277
+ }
278
+ sync()
279
+ return watchChartTokens(sync)
280
+ }, [])
281
+ return tokens
282
+ }
283
+
284
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
285
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
286
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
287
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
288
+
289
+ /**
290
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
291
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
292
+ * variants `"positive-fill"`, …) are read off the document root (`--positive`, …); `var(--token)` is read off the document root; any
293
+ * other CSS colour is normalized like the tokens are. A colour that can't be
294
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
295
+ */
296
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
297
+ return colors.map((color) => {
298
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
299
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
300
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
301
+ if (TONE_NAME_RE.test(color.trim())) {
302
+ if (typeof document === "undefined") return ""
303
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue(`--${color.trim()}`)) ?? ""
304
+ }
305
+ if (typeof document === "undefined") return color
306
+ let value = color.trim()
307
+ const cssVar = CSS_VAR_RE.exec(value)
308
+ const styles = getComputedStyle(document.documentElement)
309
+ if (cssVar) {
310
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
311
+ } else if (value.includes("var(")) {
312
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
313
+ // substitute the tokens, then let the canvas resolve the rest.
314
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
315
+ }
316
+ return toCanvasColor(value) ?? ""
317
+ })
318
+ }
319
+
320
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
321
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
322
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
323
+ ["positive", "warning", "negative", "neutral"],
324
+ tokens,
325
+ )
326
+ return { positive, warning, negative, neutral }
327
+ }
328
+
329
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
330
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
331
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
332
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
333
+ tokens,
334
+ )
335
+ return { positive, warning, negative, neutral }
336
+ }
337
+
338
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
339
+
340
+ /**
341
+ * The colour the chart is painted on: the first opaque `background-color` up
342
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
343
+ * outside the browser.
344
+ */
345
+ function readChartSurface(el: Element | null): string | null {
346
+ if (typeof document === "undefined") return null
347
+ for (let node: Element | null = el; node; node = node.parentElement) {
348
+ const bg = getComputedStyle(node).backgroundColor.trim()
349
+ if (bg && !TRANSPARENT_RE.test(bg)) {
350
+ const color = toCanvasColor(bg)
351
+ if (color) return color
352
+ }
353
+ }
354
+ return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue("--background"))
355
+ }
356
+
357
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
358
+ const WIDTH_BUCKET = 40
359
+
360
+ /**
361
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
362
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
363
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
364
+ * component's forwarded ref.
365
+ */
366
+ function useChartSurface<E extends Element>(
367
+ forwarded: ForwardedRef<E>,
368
+ tokens: ChartTokens | null,
369
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined } {
370
+ const [node, setNode] = useState<E | null>(null)
371
+ const [surface, setSurface] = useState<string | undefined>(undefined)
372
+ const [width, setWidth] = useState<number | undefined>(undefined)
373
+ const ref = useCallback(
374
+ (el: E | null) => {
375
+ setNode(el)
376
+ if (typeof forwarded === "function") forwarded(el)
377
+ else if (forwarded) forwarded.current = el
378
+ },
379
+ [forwarded],
380
+ )
381
+ useEffect(() => {
382
+ if (!node) return
383
+ setSurface(readChartSurface(node) ?? undefined)
384
+ }, [node, tokens])
385
+ useEffect(() => {
386
+ if (!node || typeof ResizeObserver === "undefined") return
387
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
388
+ update(node.getBoundingClientRect().width)
389
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
390
+ observer.observe(node)
391
+ return () => observer.disconnect()
392
+ }, [node])
393
+ return { ref, surface, width }
394
+ }
395
+
396
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
397
+
398
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
399
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
400
+
401
+ /**
402
+ * The attributes of a typed chart's leftover props that belong on its root
403
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
404
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
405
+ */
406
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
407
+ const out: Record<string, unknown> = {}
408
+ for (const [key, value] of Object.entries(rest)) {
409
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
410
+ }
411
+ return out
412
+ }
413
+
414
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
415
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
416
+ "chart-1",
417
+ "chart-2",
418
+ "chart-3",
419
+ "chart-4",
420
+ "chart-5",
421
+ ]
422
+
423
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
424
+
425
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
426
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
427
+
428
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
429
+ function isChartTone(color: string): color is ChartTone {
430
+ return (CHART_TONES as readonly string[]).includes(color.trim())
431
+ }
432
+
433
+ /**
434
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
435
+ * light/dark on its own), anything else passes through unchanged.
436
+ */
437
+ function chartColorToCss(color: ChartColor): string {
438
+ const value = color.trim()
439
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
440
+ }
441
+
442
+ /**
443
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
444
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
445
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
446
+ */
447
+ function chartFillToCss(color: ChartColor): string {
448
+ const value = color.trim()
449
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
450
+ }
451
+
452
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
453
+ function chartFillName(color: ChartColor): ChartColor {
454
+ const value = color.trim()
455
+ return isChartTone(value) ? `${value}-fill` : color
456
+ }
457
+
458
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
459
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
460
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
461
+ return palette[i % palette.length]!
462
+ }
463
+
464
+ /** `colors` extended (by cycling) to exactly `count` entries. */
465
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
466
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
467
+ }
468
+
469
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
470
+ function tintCss(cssColor: string, percent: number): string {
471
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
472
+ }
473
+
474
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
475
+
476
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
477
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
478
+
479
+ /**
480
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
481
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
482
+ */
483
+ function resolveValueFormatter(
484
+ valueFormatter: ValueFormatter | undefined,
485
+ format: ValueFormat | undefined,
486
+ locale?: string,
487
+ ): ValueFormatter {
488
+ return valueFormatter ?? toValueFormatter(format, locale)
489
+ }
490
+
491
+ /**
492
+ * The formatter of value-axis ticks and on-plot labels: an explicit
493
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
494
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
495
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
496
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
497
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
498
+ * currency sign and grouping.
499
+ */
500
+ function resolveAxisFormatter(
501
+ valueFormatter: ValueFormatter | undefined,
502
+ format: ValueFormat | undefined,
503
+ locale: string = DEFAULT_LOCALE,
504
+ ): ValueFormatter {
505
+ if (valueFormatter) return valueFormatter
506
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
507
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
508
+ const currency = "currency" in spec ? spec.currency : undefined
509
+ const short: ValueFormat =
510
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
511
+ return (value) => formatValue(value, short, locale)
512
+ }
513
+
514
+ /** The unit words of a ja number (`1.2万` / `3.4億` / `1兆`) and their sizes, largest first. */
515
+ const JA_UNITS = [
516
+ { char: "兆", size: 1e12 },
517
+ { char: "億", size: 1e8 },
518
+ { char: "万", size: 1e4 },
519
+ ] as const
520
+
521
+ const JA_NUMBER_TOKEN_RE = /\d[\d,]*(?:\.\d+)?(?:兆|億|万)?/
522
+
523
+ /**
524
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
525
+ * that largest tick, so 万 and 億 never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`).
526
+ * Only the ja short forms (`compact` / `number` / `currency`, no `valueFormatter`) have units to align;
527
+ * any other format — and an axis whose largest tick is under 1万 — keeps `resolveAxisFormatter`'s output as it is.
528
+ */
529
+ function resolveAxisTickFormatter(
530
+ valueFormatter: ValueFormatter | undefined,
531
+ format: ValueFormat | undefined,
532
+ locale: string = DEFAULT_LOCALE,
533
+ ): (top: number) => ValueFormatter {
534
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
535
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
536
+ const aligns =
537
+ !valueFormatter && locale.toLowerCase().startsWith("ja") && (spec.type === "compact" || spec.type === "number" || spec.type === "currency")
538
+ if (!aligns) return () => base
539
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
540
+ return (top) => {
541
+ const unit = JA_UNITS.find((u) => Math.abs(top) >= u.size)
542
+ if (!unit) return base
543
+ return (value) => {
544
+ const text = base(value)
545
+ if (value === 0 || !Number.isFinite(value)) return text
546
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.char}`
547
+ return text.replace(JA_NUMBER_TOKEN_RE, () => scaled)
548
+ }
549
+ }
550
+ }
551
+
552
+ /**
553
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
554
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
555
+ */
556
+ function toChartNumber(value: unknown): number | null {
557
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
558
+ if (typeof value === "bigint") return Number(value)
559
+ if (typeof value === "string" && value.trim() !== "") {
560
+ const n = Number(value)
561
+ return Number.isFinite(n) ? n : null
562
+ }
563
+ return null
564
+ }
565
+
566
+ /** Clamp `value` into `[min, max]`. */
567
+ function clamp(value: number, min: number, max: number): number {
568
+ return Math.min(max, Math.max(min, value))
569
+ }
570
+
571
+ /* ------------------------------------------------------------ aggregation */
572
+
573
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
574
+ const MAX_CHART_SERIES = 5
575
+
576
+ /** The series name the folded categories get. */
577
+ const OTHER_SERIES_LABEL = "その他"
578
+
579
+ interface AggregatedItems<Item extends { name: string; value: number }> {
580
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
581
+ top: Item[]
582
+ /** The items folded into `other`, in their given order. */
583
+ rest: Item[]
584
+ /** The folded remainder, or `null` when nothing was folded. */
585
+ other: { name: string; value: number } | null
586
+ }
587
+
588
+ /**
589
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
590
+ * given order and fold the rest into one `otherLabel` item. Shared by every
591
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
592
+ * BarList rows).
593
+ */
594
+ function aggregateTopN<Item extends { name: string; value: number }>(
595
+ items: readonly Item[],
596
+ n: number = MAX_CHART_SERIES,
597
+ otherLabel: string = OTHER_SERIES_LABEL,
598
+ ): AggregatedItems<Item> {
599
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
600
+ const ranked = items
601
+ .map((item, i) => ({ item, i }))
602
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
603
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
604
+ const top = items.filter((_, i) => keep.has(i))
605
+ const rest = items.filter((_, i) => !keep.has(i))
606
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
607
+ }
608
+
609
+ interface AggregatedSeries {
610
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
611
+ data: Record<string, unknown>[]
612
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
613
+ categories: string[]
614
+ /** The folded series' name, or `null`. */
615
+ otherCategory: string | null
616
+ }
617
+
618
+ /**
619
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
620
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
621
+ */
622
+ function aggregateSeries(
623
+ data: readonly Record<string, unknown>[],
624
+ categories: readonly string[],
625
+ n: number = MAX_CHART_SERIES,
626
+ otherLabel: string = OTHER_SERIES_LABEL,
627
+ ): AggregatedSeries {
628
+ const totals = categories.map((name) => ({
629
+ name,
630
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
631
+ }))
632
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
633
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
634
+ const folded = rest.map((item) => item.name)
635
+ return {
636
+ data: data.map((row) => {
637
+ let sum: number | null = null
638
+ for (const name of folded) {
639
+ const v = toChartNumber(row[name])
640
+ if (v !== null) sum = (sum ?? 0) + v
641
+ }
642
+ return { ...row, [other.name]: sum }
643
+ }),
644
+ categories: [...top.map((item) => item.name), other.name],
645
+ otherCategory: other.name,
646
+ }
647
+ }
648
+
649
+ /**
650
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
651
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
652
+ */
653
+ function aggregateSeriesKeeping(
654
+ data: readonly Record<string, unknown>[],
655
+ categories: readonly string[],
656
+ keep: string | undefined,
657
+ n: number = MAX_CHART_SERIES,
658
+ ): AggregatedSeries {
659
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n)
660
+ const aggregated = aggregateSeries(
661
+ data,
662
+ categories.filter((c) => c !== keep),
663
+ n,
664
+ )
665
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
666
+ }
667
+
668
+ /**
669
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
670
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
671
+ * so a main series keeps its colour whether or not a comparison is drawn.
672
+ */
673
+ function seriesColorsWithComparison(
674
+ categories: readonly string[],
675
+ colors: ChartColors | undefined,
676
+ otherColor: string,
677
+ otherCategory: string | null,
678
+ allCategories: readonly string[],
679
+ comparison: string | undefined,
680
+ ): string[] {
681
+ if (comparison === undefined || !categories.includes(comparison)) {
682
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
683
+ }
684
+ const main = categories.filter((c) => c !== comparison)
685
+ const mainColors = seriesColorsFor(
686
+ main,
687
+ colors,
688
+ otherColor,
689
+ otherCategory,
690
+ allCategories.filter((c) => c !== comparison),
691
+ )
692
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
693
+ }
694
+
695
+ /**
696
+ * Colour per drawn series: the record's token for that category, else the
697
+ * array's token at the category's position in `allCategories` (cycled), else
698
+ * the token palette by drawn position. `otherCategory` — and a category the
699
+ * data itself names「その他」(`OTHER_SERIES_LABEL`) — always gets `otherColor`.
700
+ */
701
+ function seriesColorsFor(
702
+ categories: readonly string[],
703
+ colors: ChartColors | undefined,
704
+ otherColor: string,
705
+ otherCategory: string | null = null,
706
+ allCategories: readonly string[] = categories,
707
+ ): string[] {
708
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
709
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
710
+ return categories.map((category, i) => {
711
+ if ((otherCategory !== null && category === otherCategory) || category === OTHER_SERIES_LABEL) return otherColor
712
+ const fromRecord = record?.[category]
713
+ if (fromRecord) return fromRecord
714
+ if (list && list.length > 0) {
715
+ const at = allCategories.indexOf(category)
716
+ return list[(at === -1 ? i : at) % list.length]!
717
+ }
718
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
719
+ })
720
+ }
721
+
722
+ /* ------------------------------------------------------------------ Donut */
723
+
724
+ /** One drawn donut slice, largest first. */
725
+ interface DonutSlice {
726
+ name: string
727
+ /** Negative and missing values count as 0. */
728
+ value: number
729
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
730
+ color: string
731
+ /** The folded「その他」slice. */
732
+ isOther: boolean
733
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
734
+ row: Record<string, unknown>
735
+ }
736
+
737
+ interface DonutSlicesConfig {
738
+ /** Label column. */
739
+ index: string
740
+ /** Value column. */
741
+ value: string
742
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
743
+ colors?: readonly ChartSeriesColor[]
744
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
745
+ maxSlices?: number
746
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
747
+ otherColor: string
748
+ otherLabel?: string
749
+ }
750
+
751
+ /**
752
+ * Donut slices: sorted by value (largest first, ties keep input order), the
753
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
754
+ * summed into one「その他」slice in `otherColor`.
755
+ */
756
+ function donutSlices(
757
+ data: readonly Record<string, unknown>[],
758
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = OTHER_SERIES_LABEL }: DonutSlicesConfig,
759
+ ): DonutSlice[] {
760
+ const items = data
761
+ .map((row, i) => {
762
+ const n = toChartNumber(row[value])
763
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
764
+ })
765
+ .sort((a, b) => b.value - a.value || a.i - b.i)
766
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
767
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
768
+ const slices: DonutSlice[] = top.map((item, rank) => ({
769
+ name: item.name,
770
+ value: item.value,
771
+ color: palette[rank % palette.length]!,
772
+ isOther: false,
773
+ row: item.row,
774
+ }))
775
+ if (other) {
776
+ slices.push({
777
+ name: other.name,
778
+ value: other.value,
779
+ color: otherColor,
780
+ isOther: true,
781
+ row: { [index]: other.name, [value]: other.value },
782
+ })
783
+ }
784
+ return slices
785
+ }
786
+
787
+ /* ---------------------------------------------------------------- BarList */
788
+
789
+ type BarListSortOrder = "ascending" | "descending" | "none"
790
+
791
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
792
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
793
+ const rows = [...data]
794
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
795
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
796
+ return rows
797
+ }
798
+
799
+ /** BarList-only settings. */
800
+ interface BarListOptions {
801
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
802
+ sortOrder?: BarListSortOrder
803
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
804
+ maxItems?: number
805
+ /** まとめた行のラベル。既定「その他」。 */
806
+ otherLabel?: string
807
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
808
+ exclude?: readonly string[]
809
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
810
+ showShare?: boolean
811
+ }
812
+
813
+ /** One drawn BarList row. */
814
+ interface BarListRow<Row = Record<string, unknown>> {
815
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
816
+ key: string
817
+ name: string
818
+ value: number
819
+ /** Only for real rows; the folded row never links. */
820
+ href?: string
821
+ /** Legacy per-row colour (`BarListItem.color`). */
822
+ color?: ChartColor
823
+ /** The folded「その他」row. */
824
+ isOther: boolean
825
+ /** The input row (`null` for the folded row). */
826
+ row: Row | null
827
+ }
828
+
829
+ interface BarListRowsConfig extends BarListOptions {
830
+ /** Name column. Default `"name"`. */
831
+ index?: string
832
+ /** Value column. Default `"value"`. */
833
+ category?: string
834
+ }
835
+
836
+ /**
837
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
838
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
839
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
840
+ * ranking and are always added to「その他」.
841
+ */
842
+ function barListRows<Row extends object>(
843
+ data: readonly Row[],
844
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = OTHER_SERIES_LABEL, exclude }: BarListRowsConfig = {},
845
+ ): BarListRow<Row>[] {
846
+ const items = data.map((row): BarListRow<Row> => {
847
+ const cells = row as Record<string, unknown>
848
+ const name = String(cells[index] ?? "")
849
+ return {
850
+ key: typeof cells.key === "string" ? cells.key : name,
851
+ name,
852
+ value: toChartNumber(cells[category]) ?? 0,
853
+ href: typeof cells.href === "string" ? cells.href : undefined,
854
+ color: typeof cells.color === "string" ? cells.color : undefined,
855
+ isOther: false,
856
+ row,
857
+ }
858
+ })
859
+ const excluded = new Set(exclude ?? [])
860
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
861
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
862
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
863
+ const rows = sortBarListData(top, sortOrder)
864
+ if (other || outside.length > 0) {
865
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
866
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
867
+ }
868
+ return rows
869
+ }
870
+
871
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
872
+ function barListWidths(values: readonly number[]): number[] {
873
+ const max = Math.max(0, ...values)
874
+ if (max === 0) return values.map(() => 0)
875
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
876
+ }
877
+
878
+ /**
879
+ * How strongly the BarList bars are painted: every row the same tint of the bar
880
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
881
+ * it sits on the card in light and dark; it must stay visible against the card
882
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
883
+ */
884
+ const BAR_LIST_TINT = 45
885
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
886
+ const BAR_LIST_OTHER_TINT = 30
887
+
888
+ /**
889
+ * The fill of each BarList row: all real rows in the same tint of `color`
890
+ * (`BAR_LIST_TINT`), the folded「その他」row in a tint of `otherColor`
891
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
892
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
893
+ * for that row. A tint, not the solid token, so the label printed over the bar
894
+ * keeps its contrast.
895
+ */
896
+ function barListFills(
897
+ rows: readonly Pick<BarListRow, "isOther" | "color">[],
898
+ color: ChartColor,
899
+ otherColor: string,
900
+ ): string[] {
901
+ return rows.map((row) =>
902
+ row.isOther ? tintCss(otherColor, BAR_LIST_OTHER_TINT) : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
903
+ )
904
+ }
905
+
906
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
907
+ function barListShareText(value: number, total: number): string {
908
+ const v = Number.isFinite(value) && value > 0 ? value : 0
909
+ if (total <= 0 || v === 0) return "0%"
910
+ const pct = (v / total) * 100
911
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
912
+ }
913
+
914
+ /**
915
+ * The text at the end of each BarList row: the formatted value and, with
916
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
917
+ * so the shares are of the whole list): `value` and `share` apart (the share is
918
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
919
+ */
920
+ function barListValueTexts(
921
+ values: readonly number[],
922
+ formatter: ValueFormatter,
923
+ showShare = false,
924
+ ): { value: string; share?: string; text: string }[] {
925
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
926
+ return values.map((v) => {
927
+ const value = formatter(v)
928
+ if (!showShare) return { value, text: value }
929
+ const share = barListShareText(v, total)
930
+ return { value, share, text: `${value} · ${share}` }
931
+ })
932
+ }
933
+
934
+ /* -------------------------------------------------------------- DataTable */
935
+
936
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
937
+ interface ChartDataTable {
938
+ /** 表の見出し(`<caption>`)。 */
939
+ caption?: string
940
+ /** 列見出し。先頭がラベル列。 */
941
+ columns: string[]
942
+ /** 行。セルは書式済みの文字列。 */
943
+ rows: string[][]
944
+ }
945
+
946
+ /**
947
+ * The chart's numbers as a table, for screen readers: one row per data row, the
948
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
949
+ * 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).
950
+ */
951
+ function chartDataTable(
952
+ data: readonly Record<string, unknown>[],
953
+ index: string,
954
+ categories: readonly string[],
955
+ formatter: ValueFormatter,
956
+ labels?: Readonly<Record<string, string>>,
957
+ indexName?: string,
958
+ ): ChartDataTable {
959
+ const label = (key: string) => labels?.[key] ?? key
960
+ return {
961
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
962
+ rows: data.map((row) => [
963
+ String(row[index] ?? ""),
964
+ ...categories.map((key) => {
965
+ const n = toChartNumber(row[key])
966
+ return n === null ? EMPTY_VALUE : formatter(n)
967
+ }),
968
+ ]),
969
+ }
970
+ }
971
+
972
+ /* ------------------------------------------------------------ CategoryBar */
973
+
974
+ interface CategoryBarSegment {
975
+ /** Width in percent of the whole bar. */
976
+ width: number
977
+ /** Where the segment starts, in percent. */
978
+ start: number
979
+ /** The running total at the segment's end — what its right-hand label shows. */
980
+ end: number
981
+ }
982
+
983
+ /** Lay the values side by side; negative values count as zero. */
984
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
985
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
986
+ const total = clean.reduce((sum, v) => sum + v, 0)
987
+ let running = 0
988
+ return clean.map((v) => {
989
+ const start = total === 0 ? 0 : (running / total) * 100
990
+ running += v
991
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
992
+ })
993
+ }
994
+
995
+ interface CategoryBarLabel {
996
+ /** Position in percent of the bar. */
997
+ position: number
998
+ /** The running total printed there. */
999
+ value: number
1000
+ }
1001
+
1002
+ /**
1003
+ * Tick labels under the bar: `0` at the start, then the running total at each
1004
+ * segment's end. A label closer than `minGap` percent to the one before is
1005
+ * dropped so narrow segments don't print on top of each other — except the
1006
+ * last one (the total), which replaces its neighbour instead. With a
1007
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
1008
+ * too — the marker sits right under it and the two read as one crowded spot.
1009
+ */
1010
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
1011
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
1012
+ if (segments.length === 0) return []
1013
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
1014
+ segments.forEach((s, i) => {
1015
+ const label = { position: s.start + s.width, value: s.end }
1016
+ const prev = labels[labels.length - 1]!
1017
+ if (label.position - prev.position >= minGap) labels.push(label)
1018
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
1019
+ })
1020
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1021
+ return labels.filter(
1022
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1023
+ )
1024
+ }
1025
+
1026
+ /**
1027
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1028
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1029
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1030
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1031
+ * the rest 7 px at 12 px type).
1032
+ */
1033
+ function categoryBarFitLabels(
1034
+ labels: readonly CategoryBarLabel[],
1035
+ texts: readonly string[],
1036
+ width: number,
1037
+ gap = 8,
1038
+ ): CategoryBarLabel[] {
1039
+ const textWidth = (text: string) => {
1040
+ let w = 0
1041
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1042
+ return w
1043
+ }
1044
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1045
+ const w = textWidth(text)
1046
+ if (label.position <= 0) return [0, w]
1047
+ if (label.position >= 100) return [width - w, width]
1048
+ const center = (label.position / 100) * width
1049
+ return [center - w / 2, center + w / 2]
1050
+ }
1051
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1052
+ labels.forEach((label, i) => {
1053
+ const here = extent(label, texts[i] ?? "")
1054
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1055
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1056
+ else if (touches()) return
1057
+ kept.push({ label, extent: here })
1058
+ })
1059
+ return kept.map((k) => k.label)
1060
+ }
1061
+
1062
+ /** Marker position in percent of the bar, clamped to its ends. */
1063
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
1064
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1065
+ if (total === 0) return 0
1066
+ return clamp((value / total) * 100, 0, 100)
1067
+ }
1068
+
1069
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
1070
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
1071
+ const segments = categoryBarSegments(values)
1072
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
1073
+ if (index !== -1) return index
1074
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
1075
+ return 0
1076
+ }
1077
+
1078
+ /* --------------------------------------------------------- ProgressCircle */
1079
+
1080
+ interface ProgressCircleGeometry {
1081
+ /** SVG width/height. */
1082
+ size: number
1083
+ /** Radius of the stroke's centre line. */
1084
+ normalizedRadius: number
1085
+ circumference: number
1086
+ /** `stroke-dashoffset` for the value arc. */
1087
+ offset: number
1088
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
1089
+ ratio: number
1090
+ }
1091
+
1092
+ function progressCircleGeometry(
1093
+ value: number,
1094
+ max: number,
1095
+ radius: number,
1096
+ strokeWidth: number,
1097
+ ): ProgressCircleGeometry {
1098
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
1099
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
1100
+ const circumference = 2 * Math.PI * normalizedRadius
1101
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
1102
+ }
1103
+
1104
+ /* ---------------------------------------------------------------- summary */
1105
+
1106
+ interface ChartSummaryInput {
1107
+ data: readonly Record<string, unknown>[]
1108
+ /** The x-axis key. */
1109
+ index: string
1110
+ /** Series keys; the first one is described. */
1111
+ categories: readonly string[]
1112
+ /** Title of the chart, put in front when given. */
1113
+ title?: string
1114
+ /** Same as the chart's `format` (default `"compact"`). */
1115
+ format?: ValueFormat
1116
+ /** Wins over `format`. */
1117
+ valueFormatter?: ValueFormatter
1118
+ }
1119
+
1120
+ /**
1121
+ * One-sentence summary built from the rows, for `summary="auto"`:
1122
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」. The direction is
1123
+ * computed from the last two non-empty points of the first series — never
1124
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1125
+ * no usable point.
1126
+ */
1127
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1128
+ const key = input.categories[0]
1129
+ if (key === undefined) return undefined
1130
+ const points: { label: string; value: number }[] = []
1131
+ for (const row of input.data) {
1132
+ const raw = row[key]
1133
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1134
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1135
+ }
1136
+ const latest = points[points.length - 1]
1137
+ if (!latest) return undefined
1138
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact")
1139
+ const prev = points[points.length - 2]
1140
+ const direction = !prev ? "" : latest.value > prev.value ? "、前の点より増加" : latest.value < prev.value ? "、前の点より減少" : "、前の点と横ばい"
1141
+ const head = input.title ? `${input.title}: ` : ""
1142
+ return `${head}最新 ${latest.label} は ${text(latest.value)}${direction}`
1143
+ }
1144
+
1145
+ /**
1146
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」 from the slices
1147
+ * (largest first). `undefined` when there is nothing to describe.
1148
+ */
1149
+ function buildShareSummary(
1150
+ slices: readonly { name: string; value: number }[],
1151
+ title?: string,
1152
+ ): string | undefined {
1153
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1154
+ const top = slices[0]
1155
+ if (!top || total <= 0) return undefined
1156
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1157
+ return `${title ? `${title}: ` : ""}最大は ${top.name}(${share})`
1158
+ }
1159
+
1160
+ /* ---------- end of inlined code ---------- */
1161
+
1162
+ // HeatmapChart and the (hidden) visual map that shades the cells are this part's own.
1163
+ use([HeatmapChart, VisualMapComponent])
1164
+
1165
+ /** The lightest end of the ramp is this share of the tone colour mixed into the surface; the darkest end is the colour itself. */
1166
+ export const HEATMAP_FLOOR_SHARE = 0.2
1167
+ /** Cells at or above this share of the ramp get the surface colour as text (dark cell), below it the foreground. */
1168
+ export const HEATMAP_LIGHT_TEXT_FROM = 0.55
1169
+
1170
+ /** Columns of `T` that hold numbers (null / undefined allowed for gaps); untyped rows keep every key. */
1171
+ type NumericColumn<T> = {
1172
+ [K in keyof T]-?: unknown extends T[K] ? K : T[K] extends number | bigint | null | undefined ? K : never
1173
+ }[keyof T] &
1174
+ string
1175
+
1176
+ export interface HeatmapProps<T extends Record<string, unknown> = Record<string, unknown>> extends ChartRootAttributes {
1177
+ /** 行の配列。1 行 = 1 マス(x と y の組)。同じ組が複数あれば後の行が勝つ。値は number か数値文字列。 */
1178
+ data: T[]
1179
+ /** 横軸(列)に使う列名。例 `"hour"`・`"week"`。 */
1180
+ x: keyof T & string
1181
+ /** 縦軸(行)に使う列名。例 `"weekday"`・`"cohort"`。先頭の行が一番上。 */
1182
+ y: keyof T & string
1183
+ /** マスの濃さを決める数値の列名。null・欠損・数値でない値のマスは塗らない(0 とは別。ツールチップとデータ表は「—」)。 */
1184
+ value: NumericColumn<T>
1185
+ /** 横軸の並び順(と表示するマス)。省略時は `data` の出現順。ここに無い x の行は描かない。 */
1186
+ xLabels?: string[]
1187
+ /** 縦軸の並び順(と表示するマス)。省略時は `data` の出現順。ここに無い y の行は描かない。 */
1188
+ yLabels?: string[]
1189
+ /**
1190
+ * 列名・軸の値 → 表示名(軸・ツールチップ・データ表に反映)。
1191
+ * 例 `{ mon: "月曜", value: "件数", breached: "SLA 未達" }`。無いキーはそのまま。データ表の先頭列名は `y` のキーを渡すと直る(既定は「項目」)。
1192
+ */
1193
+ labels?: Record<string, string>
1194
+ /** 数値の書式(`"number"` / `"percent"` / `{ type: "number", unit: "件" }` など)。マス内・ツールチップ・データ表で同じ書式。既定 `"number"`。 */
1195
+ format?: ValueFormat
1196
+ /** 書式を関数で直接渡す逃げ道。`format` より優先する。 */
1197
+ valueFormatter?: ValueFormatter
1198
+ /**
1199
+ * 濃淡の色。`"chart-1"`〜`"chart-5"` か意味色(`"positive"` / `"warning"` / `"negative"` / `"neutral"`)。
1200
+ * 薄い → 濃いの単色グラデーション(レインボーにしない)。既定 `"chart-1"`。
1201
+ */
1202
+ tone?: ChartSeriesColor
1203
+ /**
1204
+ * 濃さの固定スケール。省略時はデータの最小〜最大(自動)。比べたい上限・下限が決まっているときだけ渡す。`min` 以下が最も薄く、`max` 以上が最も濃い(範囲外の値は端に丸める)。凡例の両端もこの値になる。
1205
+ * 継続率(0〜100)なら `{ min: 0, max: 100 }`。片方だけでもよく、省略した側はデータの最小・最大。
1206
+ * `minValue` / `maxValue` より優先する。
1207
+ */
1208
+ scale?: { min?: number; max?: number }
1209
+ /** @deprecated `scale={{ min }}` を使う。濃さの下限(この値以下が最も薄い)。 */
1210
+ minValue?: number
1211
+ /** @deprecated `scale={{ max }}` を使う。濃さの上限(この値以上が最も濃い)。 */
1212
+ maxValue?: number
1213
+ /** マスの中に値を書く(`format` どおり)。既定 `false`。 */
1214
+ showValues?: boolean
1215
+ /** 凡例(薄い → 濃いの帯と両端の値)を出す。既定 `true`。 */
1216
+ showLegend?: boolean
1217
+ /** ホバーでツールチップを出す。既定 `true`。 */
1218
+ showTooltip?: boolean
1219
+ /**
1220
+ * ツールチップとデータ表に添える列(同じ行の別の数値)。例 `["breached"]` →「月曜 9時台 電話 12件・SLA 未達 2件」の「SLA 未達 2件」。
1221
+ * 列名の表示は `labels`、値は `format`(単位つきの書式なら同じ単位)で出る。
1222
+ */
1223
+ details?: NumericColumn<T>[]
1224
+ /**
1225
+ * この列が真(`true` / 0 でない数)の行のマスに、注意色(`--negative`)の枠を付ける。
1226
+ * 例 SLA 未達が集中したマス。色だけでなく枠の太さでも区別でき、ツールチップに「要注意」と出る。
1227
+ */
1228
+ flag?: keyof T & string
1229
+ /** グラフの見出し。 */
1230
+ title?: string
1231
+ /** グラフが言っていることの 1 文要約。`"auto"` で最大のマスから自動生成。 */
1232
+ summary?: string | "auto"
1233
+ /** 読み込み中。最終形と同じ高さのスケルトンを出す。 */
1234
+ isLoading?: boolean
1235
+ /** `data` が空のときの表示。 */
1236
+ emptyState?: ChartEmptyState
1237
+ /** プロット領域の高さ(px)。既定 288。 */
1238
+ height?: number
1239
+ /** 生成した EChartsOption に最後に深くマージする逃げ道。 */
1240
+ chartOptions?: EChartsOption
1241
+ /** グラフ右上に PNG 保存/コピーのボタンを出す。見出しがあれば PNG の上に含める(`{ includeTitle: false }` で含めない)。 */
1242
+ actions?: boolean | ChartActionsOptions
1243
+ /** PNG 保存時のファイル名(拡張子つき)。 */
1244
+ fileName?: string
1245
+ className?: string
1246
+ /** スクリーンリーダー向けのラベル。省略時は `<yの列>×<xの列>のヒートマップ`。 */
1247
+ ariaLabel?: string
1248
+ }
1249
+
1250
+ /* ------------------------------------------------------------------ model */
1251
+
1252
+ export interface HeatmapCell {
1253
+ /** Index into `xs`. */
1254
+ xi: number
1255
+ /** Index into `ys`. */
1256
+ yi: number
1257
+ /** `null` for a gap. */
1258
+ value: number | null
1259
+ flagged: boolean
1260
+ row: Record<string, unknown> | null
1261
+ }
1262
+
1263
+ export interface HeatmapModel {
1264
+ xs: string[]
1265
+ ys: string[]
1266
+ /** One per grid position (`xs.length * ys.length`), row-major by y. */
1267
+ cells: HeatmapCell[]
1268
+ min: number
1269
+ max: number
1270
+ hasGap: boolean
1271
+ }
1272
+
1273
+ function truthy(raw: unknown): boolean {
1274
+ if (typeof raw === "number") return raw !== 0 && !Number.isNaN(raw)
1275
+ return raw === true || raw === "true"
1276
+ }
1277
+
1278
+ /** Rows → the grid: axes in order, one cell per (x, y) with `null` for gaps, and the shading range. */
1279
+ export function buildHeatmapModel(config: {
1280
+ data: readonly Record<string, unknown>[]
1281
+ x: string
1282
+ y: string
1283
+ value: string
1284
+ xLabels?: readonly string[]
1285
+ yLabels?: readonly string[]
1286
+ flag?: string
1287
+ scale?: { min?: number; max?: number }
1288
+ /** @deprecated Use `scale`. */
1289
+ minValue?: number
1290
+ /** @deprecated Use `scale`. */
1291
+ maxValue?: number
1292
+ }): HeatmapModel {
1293
+ const { data, x, y, value, flag } = config
1294
+ const order = (key: string, given: readonly string[] | undefined) => {
1295
+ if (given) return [...given]
1296
+ const seen: string[] = []
1297
+ for (const row of data) {
1298
+ const k = String(row[key] ?? "")
1299
+ if (!seen.includes(k)) seen.push(k)
1300
+ }
1301
+ return seen
1302
+ }
1303
+ const xs = order(x, config.xLabels)
1304
+ const ys = order(y, config.yLabels)
1305
+ const byCell = new Map<string, Record<string, unknown>>()
1306
+ for (const row of data) byCell.set(`${String(row[x] ?? "")}\u0000${String(row[y] ?? "")}`, row)
1307
+ const cells: HeatmapCell[] = []
1308
+ let lo = Infinity
1309
+ let hi = -Infinity
1310
+ let hasGap = false
1311
+ ys.forEach((yk, yi) =>
1312
+ xs.forEach((xk, xi) => {
1313
+ const row = byCell.get(`${xk}\u0000${yk}`) ?? null
1314
+ const n = row ? toChartNumber(row[value]) : null
1315
+ if (n === null) hasGap = true
1316
+ else {
1317
+ lo = Math.min(lo, n)
1318
+ hi = Math.max(hi, n)
1319
+ }
1320
+ cells.push({ xi, yi, value: n, flagged: !!(row && flag && truthy(row[flag])), row })
1321
+ }),
1322
+ )
1323
+ const min = config.scale?.min ?? config.minValue ?? (Number.isFinite(lo) ? lo : 0)
1324
+ let max = config.scale?.max ?? config.maxValue ?? (Number.isFinite(hi) ? hi : 1)
1325
+ if (max <= min) max = min + 1
1326
+ return { xs, ys, cells, min, max, hasGap }
1327
+ }
1328
+
1329
+ /** The share (0–1) of the ramp a value sits at. */
1330
+ export function heatmapRatio(value: number, min: number, max: number): number {
1331
+ return max > min ? Math.min(1, Math.max(0, (value - min) / (max - min))) : 1
1332
+ }
1333
+
1334
+ /** A canvas-safe colour (`#rrggbb` / `rgb()` / `rgba()`) at `alpha`; anything else comes back unchanged. */
1335
+ export function withAlpha(color: string, alpha: number): string {
1336
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1337
+ if (hex) {
1338
+ const n = parseInt(hex[1]!, 16)
1339
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
1340
+ }
1341
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1342
+ return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color
1343
+ }
1344
+
1345
+ /** `#rrggbb` / `rgb()` / `rgba()` → [r, g, b] (0–255), or null. */
1346
+ function parseRgb(color: string): [number, number, number] | null {
1347
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1348
+ if (hex) {
1349
+ const n = parseInt(hex[1]!, 16)
1350
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
1351
+ }
1352
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1353
+ return rgb ? [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])] : null
1354
+ }
1355
+
1356
+ const toLinear = (c: number) => ((c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
1357
+ const fromLinear = (c: number) => Math.round(255 * Math.min(1, Math.max(0, c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055)))
1358
+
1359
+ function toOklab([r, g, b]: [number, number, number]): [number, number, number] {
1360
+ const [lr, lg, lb] = [toLinear(r), toLinear(g), toLinear(b)]
1361
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb)
1362
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb)
1363
+ const t = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb)
1364
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * t, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * t, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * t]
1365
+ }
1366
+
1367
+ function fromOklab([L, a, b]: [number, number, number]): string {
1368
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
1369
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
1370
+ const t = (L - 0.0894841775 * a - 1.291485548 * b) ** 3
1371
+ const rgb = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * t, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * t, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * t]
1372
+ return `rgb(${rgb.map(fromLinear).join(", ")})`
1373
+ }
1374
+
1375
+ /**
1376
+ * `share` of `color` mixed into `surface` — the canvas form of `color-mix(in oklch, <color> 20%, <surface>)`. The
1377
+ * surface is a neutral, so its hue is powerless and the oklch mix is the straight line in Oklab. An unreadable
1378
+ * colour falls back to `color` at `share` opacity.
1379
+ */
1380
+ export function mixIntoSurface(color: string, surface: string | undefined, share: number): string {
1381
+ const c = parseRgb(color)
1382
+ const s = surface ? parseRgb(surface) : null
1383
+ if (!c || !s) return withAlpha(color, share)
1384
+ const [c1, c2] = [toOklab(c), toOklab(s)]
1385
+ return fromOklab([0, 1, 2].map((i) => c2[i]! + (c1[i]! - c2[i]!) * share) as [number, number, number])
1386
+ }
1387
+
1388
+ function escapeHtml(text: string): string {
1389
+ return text.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!)
1390
+ }
1391
+
1392
+ /** Rough width (px) of 12px text: full-width characters 12, the rest 7 (as `chart-options` estimates it; kept local, like `escapeHtml`, so this part inlines on its own). */
1393
+ function estimateTextWidth(text: string): number {
1394
+ let w = 0
1395
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1396
+ return w
1397
+ }
1398
+
1399
+ /** The grid's left and right margins (px), and the room a cell's text needs beside its edges. */
1400
+ const HEATMAP_GRID_X = 16
1401
+ const HEATMAP_CELL_PADDING = 4
1402
+ /** `plotWidth` is floored to a 40 px bucket (`useChartSurface`): the true width is half a bucket more on average. */
1403
+ const HEATMAP_BUCKET_MID = 20
1404
+
1405
+ /**
1406
+ * The font size (px) of the numbers inside the cells at a plot width: 12 when the widest text fits a cell,
1407
+ * 10 when only the smaller size does, `null` (no numbers: the shade and the tooltip carry them) when neither.
1408
+ * Cells are the plot — its width less the margins and the row-name column — shared by the columns.
1409
+ */
1410
+ export function heatmapCellFontSize(
1411
+ plotWidth: number,
1412
+ columns: number,
1413
+ rowNames: readonly string[],
1414
+ texts: readonly string[],
1415
+ ): 12 | 10 | null {
1416
+ const widest = (items: readonly string[]) => items.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
1417
+ const cell = (plotWidth + HEATMAP_BUCKET_MID - HEATMAP_GRID_X - (widest(rowNames) + 8)) / Math.max(1, columns)
1418
+ const text = widest(texts)
1419
+ if (text + HEATMAP_CELL_PADDING <= cell) return 12
1420
+ return (text * 10) / 12 + HEATMAP_CELL_PADDING <= cell ? 10 : null
1421
+ }
1422
+
1423
+ export interface HeatmapOptionConfig {
1424
+ model: HeatmapModel
1425
+ x: string
1426
+ y: string
1427
+ value: string
1428
+ /** Resolved (canvas-safe) tone colour; `""` leaves it to the theme palette. */
1429
+ color: string
1430
+ /** Resolved colour of the flag outline. */
1431
+ flagColor: string
1432
+ /** Resolved muted colour, for the missing-value cells and the axis. */
1433
+ mutedColor: string
1434
+ /** The colour the chart sits on (a card): the ramp's lowest end mixes the tone into it. */
1435
+ surfaceColor?: string
1436
+ /** Text on a dark cell / on a light cell. */
1437
+ darkCellText: string
1438
+ lightCellText: string
1439
+ labels?: Record<string, string>
1440
+ valueFormatter: ValueFormatter
1441
+ details?: readonly string[]
1442
+ showValues: boolean
1443
+ showTooltip: boolean
1444
+ /** The plot's width (px), when known: the numbers shrink (or go) when the cells are too narrow for them. */
1445
+ plotWidth?: number | null
1446
+ chartOptions?: EChartsOption
1447
+ }
1448
+
1449
+ /**
1450
+ * The ECharts option: a shaded series (visual map, hidden), a grey series for gaps, category axes.
1451
+ * ECharts requires every heatmap series to be bound to a visual map (it throws「Heatmap must use with
1452
+ * visualMap」otherwise) and skips cells whose value is not a number, so the gap series gets its own
1453
+ * hidden visual map with a single grey and carries a placeholder `0` as its value (the label and the
1454
+ * tooltip read「—」from the cell, never the placeholder).
1455
+ */
1456
+ export function buildHeatmapOption(config: HeatmapOptionConfig): EChartsOption {
1457
+ const { model, labels, valueFormatter } = config
1458
+ const label = (key: string) => labels?.[key] ?? key
1459
+ const present = model.cells.filter((c) => c.value !== null)
1460
+ const missing = model.cells.filter((c) => c.value === null)
1461
+ const base = config.color || "#6366f1"
1462
+ const range = [mixIntoSurface(base, config.surfaceColor, HEATMAP_FLOOR_SHARE), base]
1463
+ const gapColor = "rgba(0, 0, 0, 0)"
1464
+ const flagged = (cell: HeatmapCell) =>
1465
+ cell.flagged ? { borderColor: config.flagColor, borderWidth: 3, borderType: "solid" as const } : { borderColor: "transparent", borderWidth: 1 }
1466
+
1467
+ const tooltip = (cell: HeatmapCell): string => {
1468
+ const head = `${escapeHtml(label(model.ys[cell.yi]!))} ${escapeHtml(label(model.xs[cell.xi]!))}`
1469
+ const main = cell.value === null ? EMPTY_VALUE : escapeHtml(valueFormatter(cell.value))
1470
+ const extras = (config.details ?? [])
1471
+ .map((key) => {
1472
+ const n = cell.row ? toChartNumber(cell.row[key]) : null
1473
+ return `${escapeHtml(label(key))} ${n === null ? EMPTY_VALUE : escapeHtml(valueFormatter(n))}`
1474
+ })
1475
+ .join("・")
1476
+ const flag = cell.flagged ? "・要注意" : ""
1477
+ return `${head} ${main}${extras ? `・${extras}` : ""}${flag}`
1478
+ }
1479
+
1480
+ const cellFont = config.plotWidth
1481
+ ? heatmapCellFontSize(
1482
+ config.plotWidth,
1483
+ model.xs.length,
1484
+ model.ys.map(label),
1485
+ model.cells.flatMap((cell) => (cell.value === null ? [] : [valueFormatter(cell.value)])),
1486
+ )
1487
+ : 12
1488
+ const point = (cell: HeatmapCell) => ({ value: [cell.xi, cell.yi, cell.value], cell })
1489
+ const option: EChartsOption = {
1490
+ animation: false,
1491
+ tooltip: config.showTooltip
1492
+ ? { trigger: "item", formatter: (p: unknown) => tooltip((p as { data: { cell: HeatmapCell } }).data.cell) }
1493
+ : { show: false },
1494
+ grid: { left: 8, right: 8, top: 8, bottom: 8, containLabel: true },
1495
+ xAxis: {
1496
+ type: "category",
1497
+ data: model.xs,
1498
+ splitArea: { show: false },
1499
+ axisTick: { show: false },
1500
+ axisLine: { show: false },
1501
+ axisLabel: { formatter: (v: string) => label(v), hideOverlap: true },
1502
+ },
1503
+ yAxis: {
1504
+ type: "category",
1505
+ data: model.ys,
1506
+ inverse: true,
1507
+ splitArea: { show: false },
1508
+ axisTick: { show: false },
1509
+ axisLine: { show: false },
1510
+ axisLabel: { formatter: (v: string) => label(v) },
1511
+ },
1512
+ visualMap: [
1513
+ {
1514
+ type: "continuous",
1515
+ show: false,
1516
+ min: model.min,
1517
+ max: model.max,
1518
+ dimension: 2,
1519
+ seriesIndex: 0,
1520
+ inRange: { color: range },
1521
+ outOfRange: { color: range },
1522
+ },
1523
+ {
1524
+ type: "continuous",
1525
+ show: false,
1526
+ min: 0,
1527
+ max: 1,
1528
+ dimension: 2,
1529
+ seriesIndex: 1,
1530
+ inRange: { color: [gapColor, gapColor] },
1531
+ outOfRange: { color: [gapColor, gapColor] },
1532
+ },
1533
+ ],
1534
+ series: [
1535
+ {
1536
+ id: "values",
1537
+ type: "heatmap",
1538
+ data: present.map((cell) => ({
1539
+ ...point(cell),
1540
+ itemStyle: flagged(cell),
1541
+ label: {
1542
+ color:
1543
+ heatmapRatio(cell.value as number, model.min, model.max) >= HEATMAP_LIGHT_TEXT_FROM
1544
+ ? config.darkCellText
1545
+ : config.lightCellText,
1546
+ },
1547
+ })),
1548
+ label: {
1549
+ show: config.showValues && cellFont !== null,
1550
+ fontSize: cellFont ?? 12,
1551
+ formatter: (p: unknown) => valueFormatter((p as { value: [number, number, number] }).value[2]),
1552
+ },
1553
+ itemStyle: { borderColor: "transparent", borderWidth: 1, borderRadius: 2 },
1554
+ emphasis: { itemStyle: { borderColor: config.lightCellText, borderWidth: 2 } },
1555
+ z: 2,
1556
+ },
1557
+ {
1558
+ id: "gaps",
1559
+ type: "heatmap",
1560
+ data: missing.map((cell) => ({ value: [cell.xi, cell.yi, 0], cell, itemStyle: flagged(cell) })),
1561
+ label: { show: false },
1562
+ itemStyle: {
1563
+ color: gapColor,
1564
+ borderColor: "transparent",
1565
+ borderWidth: 1,
1566
+ borderRadius: 2,
1567
+ },
1568
+ emphasis: { disabled: true },
1569
+ z: 1,
1570
+ },
1571
+ ],
1572
+ }
1573
+ return config.chartOptions ? mergeDeep(option as Record<string, unknown>, config.chartOptions as Record<string, unknown>) as EChartsOption : option
1574
+ }
1575
+
1576
+ function mergeDeep(a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown> {
1577
+ const out: Record<string, unknown> = { ...a }
1578
+ for (const [k, v] of Object.entries(b)) {
1579
+ const cur = out[k]
1580
+ out[k] =
1581
+ v && cur && typeof v === "object" && typeof cur === "object" && !Array.isArray(v) && !Array.isArray(cur)
1582
+ ? mergeDeep(cur as Record<string, unknown>, v as Record<string, unknown>)
1583
+ : v
1584
+ }
1585
+ return out
1586
+ }
1587
+
1588
+ /** The screen-reader table: one row per y, one column per x; gaps read「—」. */
1589
+ export function heatmapDataTable(
1590
+ model: HeatmapModel,
1591
+ names: { x: string; y: string },
1592
+ formatter: ValueFormatter,
1593
+ labels?: Record<string, string>,
1594
+ ): ChartDataTable {
1595
+ const label = (key: string) => labels?.[key] ?? key
1596
+ const rows = model.ys.map((yk, yi) => [
1597
+ label(yk),
1598
+ ...model.xs.map((_, xi) => {
1599
+ const v = model.cells[yi * model.xs.length + xi]?.value
1600
+ return v === null || v === undefined ? EMPTY_VALUE : formatter(v)
1601
+ }),
1602
+ ])
1603
+ return { caption: `${label(names.y)}×${label(names.x)}`, columns: [labels?.[names.y] ?? "項目", ...model.xs.map(label)], rows }
1604
+ }
1605
+
1606
+ /** `summary="auto"`: the strongest cell, e.g. 「最大は 月曜 9時台 の 12件」. `undefined` with no usable cell. */
1607
+ export function buildHeatmapSummary(model: HeatmapModel, formatter: ValueFormatter, title?: string, labels?: Record<string, string>): string | undefined {
1608
+ let best: HeatmapCell | undefined
1609
+ for (const cell of model.cells) if (cell.value !== null && (!best || cell.value > (best.value as number))) best = cell
1610
+ if (!best) return undefined
1611
+ const label = (key: string) => labels?.[key] ?? key
1612
+ const head = title ? `${title}: ` : ""
1613
+ return `${head}最大は ${label(model.ys[best.yi]!)} ${label(model.xs[best.xi]!)} の ${formatter(best.value as number)}`
1614
+ }
1615
+
1616
+ /* -------------------------------------------------------------- component */
1617
+
1618
+ function colorsFor(tokens: ChartTokens | null, tone: string) {
1619
+ const [color = "", flag = "", muted = ""] = resolveChartColors([tone, "negative", "var(--muted-foreground)"], tokens)
1620
+ return { color, flag, muted }
1621
+ }
1622
+
1623
+ /** Rows not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
1624
+ const NO_ROWS: never[] = []
1625
+
1626
+ function HeatmapImpl<T extends Record<string, unknown>>(
1627
+ {
1628
+ data = NO_ROWS,
1629
+ x,
1630
+ y,
1631
+ value,
1632
+ xLabels,
1633
+ yLabels,
1634
+ labels,
1635
+ format,
1636
+ valueFormatter,
1637
+ tone = "chart-1",
1638
+ scale,
1639
+ minValue,
1640
+ maxValue,
1641
+ showValues = false,
1642
+ showLegend = true,
1643
+ showTooltip = true,
1644
+ details,
1645
+ flag,
1646
+ title,
1647
+ summary,
1648
+ isLoading,
1649
+ emptyState,
1650
+ height,
1651
+ chartOptions,
1652
+ actions,
1653
+ fileName,
1654
+ className,
1655
+ ariaLabel,
1656
+ ...rest
1657
+ }: HeatmapProps<T>,
1658
+ ref: ForwardedRef<HTMLDivElement>,
1659
+ ) {
1660
+ const tokens = useChartTokens()
1661
+ const { ref: frameRef, surface, width: plotWidth } = useChartSurface(ref, tokens)
1662
+ const formatter = useMemo(() => resolveValueFormatter(valueFormatter, format ?? "number"), [valueFormatter, format])
1663
+ const model = useMemo(
1664
+ () => buildHeatmapModel({ data, x, y, value, xLabels, yLabels, flag, scale, minValue, maxValue }),
1665
+ [data, x, y, value, xLabels, yLabels, flag, scale?.min, scale?.max, minValue, maxValue],
1666
+ )
1667
+ const colors = useMemo(() => colorsFor(tokens, tone), [tokens, tone])
1668
+ const option = useMemo(
1669
+ () =>
1670
+ buildHeatmapOption({
1671
+ model,
1672
+ x,
1673
+ y,
1674
+ value,
1675
+ color: colors.color,
1676
+ flagColor: colors.flag,
1677
+ mutedColor: colors.muted,
1678
+ surfaceColor: surface ?? undefined,
1679
+ darkCellText: surface ?? "#ffffff",
1680
+ lightCellText: tokens?.foreground ?? "",
1681
+ labels,
1682
+ valueFormatter: formatter,
1683
+ details: details as string[] | undefined,
1684
+ showValues,
1685
+ showTooltip,
1686
+ plotWidth,
1687
+ chartOptions,
1688
+ }),
1689
+ [model, x, y, value, colors, surface, tokens, labels, formatter, details, showValues, showTooltip, plotWidth, chartOptions],
1690
+ )
1691
+ const dataTable = useMemo(() => heatmapDataTable(model, { x, y }, formatter, labels), [model, x, y, formatter, labels])
1692
+ const resolvedSummary = useMemo(
1693
+ () => (summary === "auto" ? buildHeatmapSummary(model, formatter, title, labels) : summary),
1694
+ [summary, model, formatter, title, labels],
1695
+ )
1696
+ const label = ariaLabel ?? `${labels?.[y] ?? y}×${labels?.[x] ?? x}のヒートマップ`
1697
+ const legend = showLegend ? (
1698
+ <HeatmapLegend model={model} formatter={formatter} tone={tone} />
1699
+ ) : null
1700
+ return (
1701
+ <ChartFrame
1702
+ {...chartRootProps(rest)}
1703
+ ref={frameRef}
1704
+ title={title}
1705
+ summary={resolvedSummary}
1706
+ isLoading={isLoading ?? false}
1707
+ isEmpty={data.length === 0}
1708
+ emptyState={emptyState}
1709
+ height={height}
1710
+ variant="bar"
1711
+ ariaLabel={label}
1712
+ className={className}
1713
+ dataTable={dataTable}
1714
+ >
1715
+ <div className="flex h-full w-full flex-col gap-2">
1716
+ <div className="min-h-0 flex-1">
1717
+ <EChart option={option} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
1718
+ </div>
1719
+ {legend}
1720
+ </div>
1721
+ </ChartFrame>
1722
+ )
1723
+ }
1724
+
1725
+ function HeatmapLegend({
1726
+ model,
1727
+ formatter,
1728
+ tone,
1729
+ }: {
1730
+ model: HeatmapModel
1731
+ formatter: ValueFormatter
1732
+ tone: string
1733
+ }) {
1734
+ const ramp = `linear-gradient(to right, color-mix(in oklch, var(--${tone}) ${HEATMAP_FLOOR_SHARE * 100}%, var(--card)), var(--${tone}))`
1735
+ return (
1736
+ <div data-slot="heatmap-legend" className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground tabular-nums">
1737
+ <span className="flex items-center gap-2">
1738
+ <span>{formatter(model.min)}</span>
1739
+ <span aria-hidden className="h-2 w-24 rounded-sm" style={{ backgroundImage: ramp }} />
1740
+ <span>{formatter(model.max)}</span>
1741
+ </span>
1742
+ </div>
1743
+ )
1744
+ }
1745
+
1746
+ /** Generic over the row type, so `x` / `y` / `value` keys are checked against `data`. */
1747
+ export const Heatmap = forwardRef(HeatmapImpl as (props: HeatmapProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
1748
+ T extends Record<string, unknown>,
1749
+ >(
1750
+ props: HeatmapProps<T> & { ref?: Ref<HTMLDivElement> },
1751
+ ) => ReactElement) & { displayName?: string }
1752
+ Heatmap.displayName = "Heatmap"