@squadbase/vantage 0.7.0 → 0.7.1-dev1.0d13f9a

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 (101) hide show
  1. package/README.md +1 -1
  2. package/dist/add-AU3EDPNW.js +6 -0
  3. package/dist/add-AU3EDPNW.js.map +1 -0
  4. package/dist/{chunk-AABMKHEU.js → chunk-35B3YIBF.js} +16 -7
  5. package/dist/chunk-35B3YIBF.js.map +1 -0
  6. package/dist/{chunk-QNOX7WLZ.js → chunk-5HBUBVQ3.js} +94 -8
  7. package/dist/chunk-5HBUBVQ3.js.map +1 -0
  8. package/dist/{chunk-EG4PX726.js → chunk-GWXKENNH.js} +122 -5
  9. package/dist/chunk-GWXKENNH.js.map +1 -0
  10. package/dist/{chunk-77CISBMG.js → chunk-I2GWIPTD.js} +3685 -350
  11. package/dist/chunk-I2GWIPTD.js.map +1 -0
  12. package/dist/{chunk-TRMHNMMZ.js → chunk-LYUGDHSF.js} +3 -3
  13. package/dist/{chunk-TRMHNMMZ.js.map → chunk-LYUGDHSF.js.map} +1 -1
  14. package/dist/{chunk-2IAPIOPS.js → chunk-U6MWBCM6.js} +28 -7
  15. package/dist/chunk-U6MWBCM6.js.map +1 -0
  16. package/dist/{chunk-3RJEOP3J.js → chunk-XRKSIC5Z.js} +5 -3
  17. package/dist/chunk-XRKSIC5Z.js.map +1 -0
  18. package/dist/cli.js +2 -2
  19. package/dist/components/index.d.ts +849 -12
  20. package/dist/components/index.js +5 -5
  21. package/dist/{delta-text-CbrOaW83.d.ts → delta-text-tav2Lh5d.d.ts} +1 -1
  22. package/dist/doc/index.d.ts +2 -2
  23. package/dist/doc/index.js +4 -4
  24. package/dist/{format-DihQkL1N.d.ts → format-D34piCei.d.ts} +2 -1
  25. package/dist/geo-japan-7BMSOJRX.js +8 -0
  26. package/dist/geo-japan-7BMSOJRX.js.map +1 -0
  27. package/dist/geo-us-GVOG7VXH.js +8 -0
  28. package/dist/geo-us-GVOG7VXH.js.map +1 -0
  29. package/dist/geo-world-35HL56UU.js +8 -0
  30. package/dist/geo-world-35HL56UU.js.map +1 -0
  31. package/dist/slide/index.d.ts +2 -2
  32. package/dist/slide/index.js +4 -4
  33. package/dist/table/index.js +5 -6
  34. package/dist/table/index.js.map +1 -1
  35. package/dist/ui/index.d.ts +35 -4
  36. package/dist/ui/index.js +174 -11
  37. package/dist/ui/index.js.map +1 -1
  38. package/dist/{upgrade-6DT7ADRP.js → upgrade-MCHMELWC.js} +3 -3
  39. package/dist/{upgrade-6DT7ADRP.js.map → upgrade-MCHMELWC.js.map} +1 -1
  40. package/docs/en/agent-skills.md +13 -14
  41. package/docs/en/changelog.md +8 -0
  42. package/docs/en/parts/draft-chart.md +42 -0
  43. package/docs/en/parts/page-shell.md +1 -1
  44. package/docs/index.json +70 -50
  45. package/docs/ja/agent-skills.md +14 -14
  46. package/docs/ja/changelog.md +8 -0
  47. package/docs/ja/parts/draft-chart.md +40 -0
  48. package/docs/ja/parts/page-shell.md +1 -1
  49. package/package.json +2 -2
  50. package/registry/parts.json +5319 -0
  51. package/registry/ui/area-chart.tsx +43 -8
  52. package/registry/ui/bar-chart.tsx +43 -8
  53. package/registry/ui/bar-list.tsx +43 -8
  54. package/registry/ui/box-plot-chart.tsx +42 -7
  55. package/registry/ui/category-bar.tsx +25 -5
  56. package/registry/ui/chart-frame.tsx +55 -14
  57. package/registry/ui/checkbox.tsx +4 -3
  58. package/registry/ui/code-block.tsx +44 -0
  59. package/registry/ui/combo-chart.tsx +1869 -0
  60. package/registry/ui/combobox.tsx +7 -0
  61. package/registry/ui/context-menu.tsx +71 -0
  62. package/registry/ui/dashboard-card.tsx +23 -10
  63. package/registry/ui/data-table.tsx +10 -2
  64. package/registry/ui/date-range-picker.tsx +51 -4
  65. package/registry/ui/delta.tsx +39 -12
  66. package/registry/ui/donut-chart.tsx +43 -8
  67. package/registry/ui/echart.tsx +167 -7
  68. package/registry/ui/file-dropzone.tsx +143 -0
  69. package/registry/ui/filter-bar.tsx +77 -2
  70. package/registry/ui/forecast-chart.tsx +4769 -0
  71. package/registry/ui/funnel-steps.tsx +23 -5
  72. package/registry/ui/heatmap.tsx +20 -3
  73. package/registry/ui/histogram-chart.tsx +42 -7
  74. package/registry/ui/kpi-card.tsx +15 -9
  75. package/registry/ui/legend.tsx +73 -15
  76. package/registry/ui/line-chart.tsx +43 -8
  77. package/registry/ui/metric-value.tsx +2 -2
  78. package/registry/ui/page-shell.tsx +27 -4
  79. package/registry/ui/paired-chart.tsx +44 -9
  80. package/registry/ui/pivot-table.tsx +1260 -0
  81. package/registry/ui/progress-circle.tsx +2 -2
  82. package/registry/ui/progress.tsx +1 -1
  83. package/registry/ui/scatter-chart.tsx +50 -12
  84. package/registry/ui/sparkline.tsx +44 -9
  85. package/registry/ui/states.tsx +34 -1
  86. package/registry/ui/status-badge.tsx +7 -7
  87. package/registry/ui/tabs.tsx +1 -0
  88. package/registry/ui/treemap.tsx +1934 -0
  89. package/registry/ui/waterfall-chart.tsx +64 -11
  90. package/templates/AGENTS.md +3 -3
  91. package/templates/agents/page.md +5 -4
  92. package/dist/add-4GHF2TX2.js +0 -6
  93. package/dist/add-4GHF2TX2.js.map +0 -1
  94. package/dist/chunk-2IAPIOPS.js.map +0 -1
  95. package/dist/chunk-3RJEOP3J.js.map +0 -1
  96. package/dist/chunk-77CISBMG.js.map +0 -1
  97. package/dist/chunk-AABMKHEU.js.map +0 -1
  98. package/dist/chunk-EG4PX726.js.map +0 -1
  99. package/dist/chunk-NZ5QIIG4.js +0 -74
  100. package/dist/chunk-NZ5QIIG4.js.map +0 -1
  101. package/dist/chunk-QNOX7WLZ.js.map +0 -1
@@ -0,0 +1,1934 @@
1
+ // Copied by `vantage add ui treemap`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/charts/treemap.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * Treemap — parts of a whole as nested rectangles whose areas are the values.
7
+ * Pass rows, the leaf column (`index`),
8
+ * optionally a parent column (`group`, for two levels) and the number (`value`) instead of an ECharts option.
9
+ *
10
+ * Colour is categorical by `group` (or by `index` without one): `--chart-1..5` for the largest five, the rest the
11
+ * 「その他」grey. A numeric `color` column shades each tile on a single-hue ramp of `tone` instead (like Heatmap).
12
+ * Each tile carries its name and value when it fits. Values that are zero, negative or missing take no area; they
13
+ * stay in the screen-reader table. Clicking a tile calls `onSelect` with its row.
14
+ */
15
+ import { forwardRef, useMemo, type ForwardedRef, type ReactElement, type Ref } from "react"
16
+ import { use } from "echarts/core"
17
+ import { TreemapChart } from "echarts/charts"
18
+ import type { EChartsOption } from "echarts"
19
+
20
+ import { ChartFrame } from "@squadbase/vantage/components"
21
+ import { EChart } from "@squadbase/vantage/components"
22
+ import { Legend } from "@squadbase/vantage/components"
23
+ import { EMPTY_VALUE, formatValue, type ValueFormat } from "@squadbase/vantage/components"
24
+ import type { ChartActionsOptions, ChartEmptyState, ChartRootAttributes, ChartSeriesColor, ValueFormatter } from "@squadbase/vantage/components"
25
+ import { useSyncExternalStore } from "react"
26
+ import { createContext, useCallback, useEffect, useRef, useState, type RefObject } from "react"
27
+ import type { ChartTone } from "@squadbase/vantage/components"
28
+ import { toValueFormatter } from "@squadbase/vantage/components"
29
+ import type { ChartColor, ChartColors } from "@squadbase/vantage/components"
30
+
31
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
32
+
33
+ /**
34
+ * The display language of the parts and the defaults that follow it.
35
+ *
36
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
37
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
38
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
39
+ *
40
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
41
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
42
+ */
43
+
44
+ /** The language of the built-in wording: Japanese or English. */
45
+ type UiLanguage = "ja" | "en"
46
+
47
+ /** The locale used when `<html lang>` gives none (and on the server). */
48
+ const FALLBACK_LOCALE = "en-US"
49
+
50
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
51
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
52
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
53
+ }
54
+
55
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
56
+ function normalizeLocale(tag: string | null | undefined): string {
57
+ const value = tag?.trim()
58
+ if (!value) return FALLBACK_LOCALE
59
+ try {
60
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
61
+ } catch {
62
+ return FALLBACK_LOCALE
63
+ }
64
+ }
65
+
66
+ /**
67
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
68
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
69
+ */
70
+ function documentLocale(): string {
71
+ if (typeof document === "undefined") return FALLBACK_LOCALE
72
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
73
+ }
74
+
75
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
76
+ function resolveLocale(locale?: string | null): string {
77
+ return locale || documentLocale()
78
+ }
79
+
80
+ /** Picks the wording table of the locale's language. */
81
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
82
+ return table[uiLanguage(resolveLocale(locale))]
83
+ }
84
+
85
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
86
+ function defaultCurrency(locale?: string | null): string {
87
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
88
+ }
89
+
90
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
91
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
92
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
93
+ }
94
+
95
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
96
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
97
+
98
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
99
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
100
+
101
+ /**
102
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
103
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
104
+ * Monday for the rest.
105
+ */
106
+ function weekStartsOn(locale?: string | null): WeekDay {
107
+ const tag = normalizeLocale(resolveLocale(locale))
108
+ if (uiLanguage(tag) === "ja") return 1
109
+ try {
110
+ const info = new Intl.Locale(tag) as Intl.Locale & {
111
+ getWeekInfo?: () => { firstDay: number }
112
+ weekInfo?: { firstDay: number }
113
+ }
114
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
115
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
116
+ } catch {
117
+ // Fall through to the table below.
118
+ }
119
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
120
+ }
121
+
122
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
123
+
124
+ const listeners = new Set<() => void>()
125
+ let observer: MutationObserver | null = null
126
+
127
+ /** One observer on `<html lang>` for every subscribed part. */
128
+ function subscribe(onChange: () => void): () => void {
129
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
130
+ listeners.add(onChange)
131
+ if (!observer) {
132
+ observer = new MutationObserver(() => {
133
+ for (const listener of [...listeners]) listener()
134
+ })
135
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
136
+ }
137
+ return () => {
138
+ listeners.delete(onChange)
139
+ if (listeners.size === 0 && observer) {
140
+ observer.disconnect()
141
+ observer = null
142
+ }
143
+ }
144
+ }
145
+
146
+ const serverLocale = () => FALLBACK_LOCALE
147
+
148
+ /**
149
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
150
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
151
+ */
152
+ function useDocumentLocale(): string {
153
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
154
+ }
155
+
156
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
157
+ function useLocale(locale?: string | null): string {
158
+ const page = useDocumentLocale()
159
+ return locale || page
160
+ }
161
+
162
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
163
+
164
+ /**
165
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
166
+ * grey is defined — every chart takes it from here. It is the most subdued
167
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
168
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
169
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
170
+ * slice. Canvas charts resolve it through `resolveChartColors`.
171
+ */
172
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
173
+
174
+ /**
175
+ * What a `ChartFrame` tells the plot inside it. A frame whose plot is an image
176
+ * (`image`) puts `role="img"` on its plot area, unless an `EChart` inside it
177
+ * `claim`s the image: then the canvas alone carries `role="img"` with this name
178
+ * and description (`claimed`), so the action buttons beside the canvas are not
179
+ * inside the image (an interactive control inside `role="img"` is a
180
+ * nested-interactive violation and is not exposed). A `group` frame never
181
+ * hands the role to the canvas. `false` outside a frame.
182
+ */
183
+ interface ChartFramePlot {
184
+ image: boolean
185
+ /** An `EChart` inside has taken over the `role="img"`. */
186
+ claimed: boolean
187
+ /** Take over the image role; returns the release. */
188
+ claim: () => () => void
189
+ ariaLabel?: string
190
+ ariaLabelledBy?: string
191
+ ariaDescribedBy?: string
192
+ }
193
+ const ChartFrameContext = createContext<ChartFramePlot | false>(false)
194
+
195
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
196
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
197
+
198
+ interface ChartTokens {
199
+ /** Resolved `--chart-1..5`, in order. */
200
+ series: string[]
201
+ /** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
202
+ fontFamily?: string
203
+ /** Body text: titles and the default `textStyle`. */
204
+ foreground: string | null
205
+ /** Secondary text: axis labels, legend, subtitles. */
206
+ mutedForeground: string | null
207
+ /** Axis lines, ticks, split lines, tooltip border. */
208
+ border: string | null
209
+ /** Tooltip surface. */
210
+ popover: string | null
211
+ /** Semantic and surface dependencies used by typed chart options. Optional for hand-built tokens. */
212
+ colors?: Record<string, string>
213
+ /** Actual inherited painting surface (may change without a token changing). */
214
+ surface?: string | null
215
+ /** Tooltip text. */
216
+ popoverForeground: string | null
217
+ }
218
+
219
+ // Keep scope out of the public token shape. A resolved snapshot remembers where arbitrary
220
+ // var(--token) expressions must be read, without retaining unmounted charts globally.
221
+ const tokenScopes = new WeakMap<ChartTokens, Element>()
222
+ const OPTION_COLOR_TOKENS = [
223
+ "--background", "--card", "--muted", "--primary", "--destructive",
224
+ ...["positive", "negative", "warning", "neutral", "info"].flatMap((tone) =>
225
+ ["", "-fill", "-subtle"].map((suffix) => `--${tone}${suffix}`)),
226
+ ]
227
+
228
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
229
+
230
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
231
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
232
+
233
+ /**
234
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
235
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
236
+ * input is written over two different known colours: agreeing results mean the
237
+ * value parsed, differing ones mean it was dropped.
238
+ */
239
+ function toCanvasColor(value: string): string | null {
240
+ const raw = value.trim()
241
+ if (!raw) return null
242
+ if (normalizeContext === undefined) {
243
+ const canvas = document.createElement("canvas")
244
+ canvas.width = 1
245
+ canvas.height = 1
246
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
247
+ }
248
+ const ctx = normalizeContext
249
+ if (!ctx) return raw
250
+ ctx.fillStyle = "#000000"
251
+ ctx.fillStyle = raw
252
+ const onBlack = ctx.fillStyle
253
+ ctx.fillStyle = "#ffffff"
254
+ ctx.fillStyle = raw
255
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
256
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
257
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
258
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
259
+ ctx.clearRect(0, 0, 1, 1)
260
+ ctx.fillRect(0, 0, 1, 1)
261
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
262
+ return a === 255
263
+ ? `rgb(${r}, ${g}, ${b})`
264
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
265
+ }
266
+
267
+ /**
268
+ * Read the chart tokens off `el` (the document root by default — tokens live on
269
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
270
+ * to plain ECharts defaults.
271
+ */
272
+ function readChartTokens(el?: Element | null): ChartTokens | null {
273
+ if (typeof document === "undefined") return null
274
+ const target = el ?? document.documentElement
275
+ if (!target) return null
276
+ const styles = getComputedStyle(target)
277
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
278
+ const series: string[] = []
279
+ for (const token of SERIES_TOKENS) {
280
+ const color = read(token)
281
+ if (color) series.push(color)
282
+ }
283
+ const tokens: ChartTokens = {
284
+ series,
285
+ colors: Object.fromEntries(OPTION_COLOR_TOKENS.map((name) => [name, styles.getPropertyValue(name).trim()])),
286
+ surface: readChartSurface(target),
287
+ ...(styles.fontFamily ? { fontFamily: styles.fontFamily } : {}),
288
+ foreground: read("--foreground"),
289
+ mutedForeground: read("--muted-foreground"),
290
+ border: read("--border"),
291
+ popover: read("--popover"),
292
+ popoverForeground: read("--popover-foreground"),
293
+ }
294
+ tokenScopes.set(tokens, target)
295
+ return tokens
296
+ }
297
+
298
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
299
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
300
+ if (a === b) return true
301
+ if (!a || !b) return false
302
+ return (
303
+ tokenScopes.get(a) === tokenScopes.get(b) &&
304
+ a.surface === b.surface &&
305
+ Object.keys(a.colors ?? {}).length === Object.keys(b.colors ?? {}).length &&
306
+ Object.entries(a.colors ?? {}).every(([name, value]) => b.colors?.[name] === value) &&
307
+ a.series.length === b.series.length &&
308
+ a.series.every((color, i) => color === b.series[i]) &&
309
+ a.fontFamily === b.fontFamily &&
310
+ a.foreground === b.foreground &&
311
+ a.mutedForeground === b.mutedForeground &&
312
+ a.border === b.border &&
313
+ a.popover === b.popover &&
314
+ a.popoverForeground === b.popoverForeground
315
+ )
316
+ }
317
+
318
+ /**
319
+ * Watch everything that can change the resolved tokens and call `onChange` when
320
+ * something might have. It only ever says "re-read" — the caller compares with
321
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
322
+ * disposer.
323
+ *
324
+ * Two sources, not one:
325
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
326
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
327
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
328
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
329
+ * attributes alone leaves the chart painted in the previous palette until a
330
+ * reload — the tokens in the DOM are new, the canvas is not.
331
+ */
332
+ function watchChartTokens(onChange: () => void, scope?: Element | null): () => void {
333
+ if (typeof document === "undefined") return () => {}
334
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
335
+ // take it after the next frame so a swapped stylesheet has been applied.
336
+ let frame = 0
337
+ const schedule = () => {
338
+ if (frame) return
339
+ frame = requestAnimationFrame(() => {
340
+ frame = 0
341
+ onChange()
342
+ })
343
+ }
344
+
345
+ const themeObserver = new MutationObserver(schedule)
346
+ const attributeFilter = ["class", "style", "data-theme"]
347
+ // Only the chart and its ancestors can change its inherited theme. Never observe
348
+ // the document subtree: canvas/tooltip/rendering mutations would trigger every chart.
349
+ for (let node: Element | null = scope ?? document.body ?? document.documentElement; node; node = node.parentElement) {
350
+ themeObserver.observe(node, { attributes: true, attributeFilter })
351
+ }
352
+
353
+ const styleObserver = new MutationObserver(schedule)
354
+ if (document.head) {
355
+ styleObserver.observe(document.head, {
356
+ childList: true,
357
+ subtree: true,
358
+ characterData: true,
359
+ attributes: true,
360
+ attributeFilter: ["href", "media", "disabled"],
361
+ })
362
+ }
363
+
364
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
365
+ const onLoad = (event: Event) => {
366
+ if (event.target instanceof HTMLLinkElement) schedule()
367
+ }
368
+ document.addEventListener("load", onLoad, true)
369
+
370
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
371
+ media.addEventListener("change", schedule)
372
+
373
+ return () => {
374
+ if (frame) cancelAnimationFrame(frame)
375
+ themeObserver.disconnect()
376
+ styleObserver.disconnect()
377
+ document.removeEventListener("load", onLoad, true)
378
+ media.removeEventListener("change", schedule)
379
+ }
380
+ }
381
+
382
+ /** Shared shape for the four axis types ECharts themes address separately. */
383
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
384
+ const line = tokens.border ?? undefined
385
+ return {
386
+ axisLine: { show: false },
387
+ axisTick: { show: false },
388
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
389
+ // Faint horizontal rules only: the border colour at low opacity.
390
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
391
+ splitArea: { show: false },
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
397
+ * app that sets its own palette keeps it.
398
+ */
399
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
400
+ const text = tokens.foreground ?? undefined
401
+ const muted = tokens.mutedForeground ?? undefined
402
+ const line = tokens.border ?? undefined
403
+ return {
404
+ // Let the page background show through: charts sit on cards, not on a canvas.
405
+ backgroundColor: "transparent",
406
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
407
+ textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
408
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
409
+ legend: { textStyle: { color: muted } },
410
+ categoryAxis: axisTheme(tokens, false),
411
+ valueAxis: axisTheme(tokens, true),
412
+ logAxis: axisTheme(tokens, true),
413
+ timeAxis: axisTheme(tokens, true),
414
+ tooltip: {
415
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
416
+ transitionDuration: 0,
417
+ // Stay inside the chart: cards are often narrow and overflow-hidden.
418
+ confine: true,
419
+ backgroundColor: tokens.popover ?? undefined,
420
+ borderColor: line,
421
+ borderWidth: 1,
422
+ padding: [8, 12],
423
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
424
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
425
+ textStyle: {
426
+ color: tokens.popoverForeground ?? undefined,
427
+ fontSize: 12,
428
+ ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}),
429
+ },
430
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
431
+ },
432
+ }
433
+ }
434
+
435
+ /**
436
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
437
+ * they may have moved, and only replaced when a value actually changed. For
438
+ * components that build an ECharts option from token colours themselves (the
439
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
440
+ */
441
+ function useChartTokens(scope?: Element | null | RefObject<Element | null>): ChartTokens | null {
442
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
443
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
444
+ // replayed by React on every rebase and returns a fresh object each time, so the state
445
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
446
+ const tokensRef = useRef(tokens)
447
+ useEffect(() => {
448
+ const target = scope && "current" in scope ? scope.current : scope
449
+ const sync = () => {
450
+ const next = readChartTokens(target)
451
+ if (sameChartTokens(tokensRef.current, next)) return
452
+ tokensRef.current = next
453
+ setTokens(next)
454
+ }
455
+ sync()
456
+ return watchChartTokens(sync, target)
457
+ }, [scope])
458
+ return tokens
459
+ }
460
+
461
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
462
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
463
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
464
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
465
+
466
+ /**
467
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
468
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
469
+ * variants `"positive-fill"`, …) are read in the snapshot's inherited scope (`--positive`, …); `var(--token)` uses the same scope; any
470
+ * other CSS colour is normalized like the tokens are. A colour that can't be
471
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
472
+ */
473
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
474
+ return colors.map((color) => {
475
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
476
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
477
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
478
+ if (TONE_NAME_RE.test(color.trim())) {
479
+ if (typeof document === "undefined") return ""
480
+ const target = (tokens && tokenScopes.get(tokens)) ?? document.documentElement
481
+ return toCanvasColor(getComputedStyle(target).getPropertyValue(`--${color.trim()}`)) ?? ""
482
+ }
483
+ if (typeof document === "undefined") return color
484
+ let value = color.trim()
485
+ const cssVar = CSS_VAR_RE.exec(value)
486
+ const styles = getComputedStyle((tokens && tokenScopes.get(tokens)) ?? document.documentElement)
487
+ if (cssVar) {
488
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
489
+ } else if (value.includes("var(")) {
490
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
491
+ // substitute the tokens, then let the canvas resolve the rest.
492
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
493
+ }
494
+ return toCanvasColor(value) ?? ""
495
+ })
496
+ }
497
+
498
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
499
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
500
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
501
+ ["positive", "warning", "negative", "neutral"],
502
+ tokens,
503
+ )
504
+ return { positive, warning, negative, neutral }
505
+ }
506
+
507
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
508
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
509
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
510
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
511
+ tokens,
512
+ )
513
+ return { positive, warning, negative, neutral }
514
+ }
515
+
516
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
517
+
518
+ /**
519
+ * The colour the chart is painted on: the first opaque `background-color` up
520
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
521
+ * outside the browser.
522
+ */
523
+ function readChartSurface(el: Element | null): string | null {
524
+ if (typeof document === "undefined") return null
525
+ for (let node: Element | null = el; node; node = node.parentElement) {
526
+ const bg = getComputedStyle(node).backgroundColor.trim()
527
+ if (bg && !TRANSPARENT_RE.test(bg)) {
528
+ const color = toCanvasColor(bg)
529
+ if (color) return color
530
+ }
531
+ }
532
+ return toCanvasColor(getComputedStyle(el ?? document.documentElement).getPropertyValue("--background"))
533
+ }
534
+
535
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
536
+ const WIDTH_BUCKET = 40
537
+
538
+ /**
539
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
540
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
541
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
542
+ * component's forwarded ref.
543
+ */
544
+ function useChartSurface<E extends Element>(
545
+ forwarded: ForwardedRef<E>,
546
+ tokens?: ChartTokens | null,
547
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined; tokens: ChartTokens | null } {
548
+ const [node, setNode] = useState<E | null>(null)
549
+ const scopedTokens = useChartTokens(node)
550
+ const [surface, setSurface] = useState<string | undefined>(undefined)
551
+ const [width, setWidth] = useState<number | undefined>(undefined)
552
+ const ref = useCallback(
553
+ (el: E | null) => {
554
+ setNode(el)
555
+ if (typeof forwarded === "function") forwarded(el)
556
+ else if (forwarded) forwarded.current = el
557
+ },
558
+ [forwarded],
559
+ )
560
+ useEffect(() => {
561
+ if (!node) return
562
+ setSurface(readChartSurface(node) ?? undefined)
563
+ }, [node, tokens, scopedTokens])
564
+ useEffect(() => {
565
+ if (!node || typeof ResizeObserver === "undefined") return
566
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
567
+ update(node.getBoundingClientRect().width)
568
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
569
+ observer.observe(node)
570
+ return () => observer.disconnect()
571
+ }, [node])
572
+ return { ref, surface, width, tokens: scopedTokens }
573
+ }
574
+
575
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
576
+
577
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
578
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
579
+
580
+ /**
581
+ * The attributes of a typed chart's leftover props that belong on its root
582
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
583
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
584
+ */
585
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
586
+ const out: Record<string, unknown> = {}
587
+ for (const [key, value] of Object.entries(rest)) {
588
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
589
+ }
590
+ return out
591
+ }
592
+
593
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
594
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
595
+ "chart-1",
596
+ "chart-2",
597
+ "chart-3",
598
+ "chart-4",
599
+ "chart-5",
600
+ ]
601
+
602
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
603
+
604
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
605
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
606
+
607
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
608
+ function isChartTone(color: string): color is ChartTone {
609
+ return (CHART_TONES as readonly string[]).includes(color.trim())
610
+ }
611
+
612
+ /**
613
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
614
+ * light/dark on its own), anything else passes through unchanged.
615
+ */
616
+ function chartColorToCss(color: ChartColor): string {
617
+ const value = color.trim()
618
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
619
+ }
620
+
621
+ /**
622
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
623
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
624
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
625
+ */
626
+ function chartFillToCss(color: ChartColor): string {
627
+ const value = color.trim()
628
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
629
+ }
630
+
631
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
632
+ function chartFillName(color: ChartColor): ChartColor {
633
+ const value = color.trim()
634
+ return isChartTone(value) ? `${value}-fill` : color
635
+ }
636
+
637
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
638
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
639
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
640
+ return palette[i % palette.length]!
641
+ }
642
+
643
+ /** `colors` extended (by cycling) to exactly `count` entries. */
644
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
645
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
646
+ }
647
+
648
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
649
+ function tintCss(cssColor: string, percent: number): string {
650
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
651
+ }
652
+
653
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
654
+
655
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
656
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
657
+
658
+ /**
659
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
660
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
661
+ */
662
+ function resolveValueFormatter(
663
+ valueFormatter: ValueFormatter | undefined,
664
+ format: ValueFormat | undefined,
665
+ locale?: string,
666
+ ): ValueFormatter {
667
+ return valueFormatter ?? toValueFormatter(format, locale)
668
+ }
669
+
670
+ /**
671
+ * The formatter of value-axis ticks and on-plot labels: an explicit
672
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
673
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
674
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
675
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
676
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
677
+ * currency sign and grouping.
678
+ */
679
+ function resolveAxisFormatter(
680
+ valueFormatter: ValueFormatter | undefined,
681
+ format: ValueFormat | undefined,
682
+ localeArg?: string,
683
+ ): ValueFormatter {
684
+ if (valueFormatter) return valueFormatter
685
+ const locale = resolveLocale(localeArg)
686
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
687
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
688
+ const currency = "currency" in spec ? spec.currency : undefined
689
+ const short: ValueFormat =
690
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
691
+ return (value) => formatValue(value, short, locale)
692
+ }
693
+
694
+ interface CompactUnit {
695
+ token: string
696
+ size: number
697
+ }
698
+
699
+ const compactUnitCache = new Map<string, CompactUnit[] | null>()
700
+
701
+ /**
702
+ * The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
703
+ * `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
704
+ * word (`1,5 Mio.`), where a token cannot be swapped in place.
705
+ */
706
+ function compactUnits(locale: string): CompactUnit[] | null {
707
+ const cached = compactUnitCache.get(locale)
708
+ if (cached !== undefined) return cached
709
+ let units: CompactUnit[] | null = []
710
+ try {
711
+ const compact = new Intl.NumberFormat(locale, { notation: "compact" })
712
+ const seen = new Set<string>()
713
+ for (let exp = 3; exp <= 15; exp++) {
714
+ const parts = compact.formatToParts(10 ** exp)
715
+ const at = parts.findIndex((p) => p.type === "compact")
716
+ if (at === -1) continue
717
+ if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
718
+ units = null
719
+ break
720
+ }
721
+ const token = parts[at]!.value
722
+ if (seen.has(token)) continue
723
+ seen.add(token)
724
+ units.push({ token, size: 10 ** exp })
725
+ }
726
+ } catch {
727
+ units = null
728
+ }
729
+ const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
730
+ compactUnitCache.set(locale, sorted)
731
+ return sorted
732
+ }
733
+
734
+ const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
735
+
736
+ /**
737
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
738
+ * that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
739
+ * `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
740
+ * no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
741
+ * unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
742
+ */
743
+ function resolveAxisTickFormatter(
744
+ valueFormatter: ValueFormatter | undefined,
745
+ format: ValueFormat | undefined,
746
+ localeArg?: string,
747
+ ): (top: number) => ValueFormatter {
748
+ const locale = resolveLocale(localeArg)
749
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
750
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
751
+ const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
752
+ if (!units) return () => base
753
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
754
+ const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
755
+ return (top) => {
756
+ const unit = units.find((u) => Math.abs(top) >= u.size)
757
+ if (!unit) return base
758
+ return (value) => {
759
+ const text = base(value)
760
+ if (value === 0 || !Number.isFinite(value)) return text
761
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
762
+ return text.replace(numberToken, () => scaled)
763
+ }
764
+ }
765
+ }
766
+
767
+ /**
768
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
769
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
770
+ */
771
+ function toChartNumber(value: unknown): number | null {
772
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
773
+ if (typeof value === "bigint") return Number(value)
774
+ if (typeof value === "string" && value.trim() !== "") {
775
+ const n = Number(value)
776
+ return Number.isFinite(n) ? n : null
777
+ }
778
+ return null
779
+ }
780
+
781
+ /** Clamp `value` into `[min, max]`. */
782
+ function clamp(value: number, min: number, max: number): number {
783
+ return Math.min(max, Math.max(min, value))
784
+ }
785
+
786
+ /* ------------------------------------------------------------ aggregation */
787
+
788
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
789
+ const MAX_CHART_SERIES = 5
790
+
791
+ /** The series name the folded categories get, by language. */
792
+ const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
793
+
794
+ /** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
795
+ function otherSeriesLabel(locale?: string): string {
796
+ return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
797
+ }
798
+
799
+ const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
800
+
801
+ /** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
802
+ function isOtherName(name: string | null | undefined): boolean {
803
+ return typeof name === "string" && OTHER_NAMES.has(name)
804
+ }
805
+
806
+ interface AggregatedItems<Item extends { name: string; value: number }> {
807
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
808
+ top: Item[]
809
+ /** The items folded into `other`, in their given order. */
810
+ rest: Item[]
811
+ /** The folded remainder, or `null` when nothing was folded. */
812
+ other: { name: string; value: number } | null
813
+ }
814
+
815
+ /**
816
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
817
+ * given order and fold the rest into one `otherLabel` item. Shared by every
818
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
819
+ * BarList rows).
820
+ */
821
+ function aggregateTopN<Item extends { name: string; value: number }>(
822
+ items: readonly Item[],
823
+ n: number = MAX_CHART_SERIES,
824
+ otherLabel: string = otherSeriesLabel(),
825
+ ): AggregatedItems<Item> {
826
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
827
+ const ranked = items
828
+ .map((item, i) => ({ item, i }))
829
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
830
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
831
+ const top = items.filter((_, i) => keep.has(i))
832
+ const rest = items.filter((_, i) => !keep.has(i))
833
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
834
+ }
835
+
836
+ interface AggregatedSeries {
837
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
838
+ data: Record<string, unknown>[]
839
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
840
+ categories: string[]
841
+ /** The folded series' name, or `null`. */
842
+ otherCategory: string | null
843
+ }
844
+
845
+ /**
846
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
847
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
848
+ */
849
+ function aggregateSeries(
850
+ data: readonly Record<string, unknown>[],
851
+ categories: readonly string[],
852
+ n: number = MAX_CHART_SERIES,
853
+ otherLabel: string = otherSeriesLabel(),
854
+ ): AggregatedSeries {
855
+ const totals = categories.map((name) => ({
856
+ name,
857
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
858
+ }))
859
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
860
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
861
+ const folded = rest.map((item) => item.name)
862
+ return {
863
+ data: data.map((row) => {
864
+ let sum: number | null = null
865
+ for (const name of folded) {
866
+ const v = toChartNumber(row[name])
867
+ if (v !== null) sum = (sum ?? 0) + v
868
+ }
869
+ return { ...row, [other.name]: sum }
870
+ }),
871
+ categories: [...top.map((item) => item.name), other.name],
872
+ otherCategory: other.name,
873
+ }
874
+ }
875
+
876
+ /**
877
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
878
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
879
+ */
880
+ function aggregateSeriesKeeping(
881
+ data: readonly Record<string, unknown>[],
882
+ categories: readonly string[],
883
+ keep: string | undefined,
884
+ n: number = MAX_CHART_SERIES,
885
+ otherLabel: string = otherSeriesLabel(),
886
+ ): AggregatedSeries {
887
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
888
+ const aggregated = aggregateSeries(
889
+ data,
890
+ categories.filter((c) => c !== keep),
891
+ n,
892
+ otherLabel,
893
+ )
894
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
895
+ }
896
+
897
+ /**
898
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
899
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
900
+ * so a main series keeps its colour whether or not a comparison is drawn.
901
+ */
902
+ function seriesColorsWithComparison(
903
+ categories: readonly string[],
904
+ colors: ChartColors | undefined,
905
+ otherColor: string,
906
+ otherCategory: string | null,
907
+ allCategories: readonly string[],
908
+ comparison: string | undefined,
909
+ ): string[] {
910
+ if (comparison === undefined || !categories.includes(comparison)) {
911
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
912
+ }
913
+ const main = categories.filter((c) => c !== comparison)
914
+ const mainColors = seriesColorsFor(
915
+ main,
916
+ colors,
917
+ otherColor,
918
+ otherCategory,
919
+ allCategories.filter((c) => c !== comparison),
920
+ )
921
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
922
+ }
923
+
924
+ /**
925
+ * Colour per drawn series: the record's token for that category, else the
926
+ * array's token at the category's position in `allCategories` (cycled), else
927
+ * the token palette by drawn position. `otherCategory` — and a category the
928
+ * data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
929
+ */
930
+ function seriesColorsFor(
931
+ categories: readonly string[],
932
+ colors: ChartColors | undefined,
933
+ otherColor: string,
934
+ otherCategory: string | null = null,
935
+ allCategories: readonly string[] = categories,
936
+ ): string[] {
937
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
938
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
939
+ return categories.map((category, i) => {
940
+ if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
941
+ const fromRecord = record?.[category]
942
+ if (fromRecord) return fromRecord
943
+ if (list && list.length > 0) {
944
+ const at = allCategories.indexOf(category)
945
+ return list[(at === -1 ? i : at) % list.length]!
946
+ }
947
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
948
+ })
949
+ }
950
+
951
+ /* ------------------------------------------------------------------ Donut */
952
+
953
+ /** One drawn donut slice, largest first. */
954
+ interface DonutSlice {
955
+ name: string
956
+ /** Negative and missing values count as 0. */
957
+ value: number
958
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
959
+ color: string
960
+ /** The folded「その他」slice. */
961
+ isOther: boolean
962
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
963
+ row: Record<string, unknown>
964
+ }
965
+
966
+ interface DonutSlicesConfig {
967
+ /** Label column. */
968
+ index: string
969
+ /** Value column. */
970
+ value: string
971
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
972
+ colors?: readonly ChartSeriesColor[]
973
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
974
+ maxSlices?: number
975
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
976
+ otherColor: string
977
+ otherLabel?: string
978
+ }
979
+
980
+ /**
981
+ * Donut slices: sorted by value (largest first, ties keep input order), the
982
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
983
+ * summed into one「その他」slice in `otherColor`.
984
+ */
985
+ function donutSlices(
986
+ data: readonly Record<string, unknown>[],
987
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
988
+ ): DonutSlice[] {
989
+ const items = data
990
+ .map((row, i) => {
991
+ const n = toChartNumber(row[value])
992
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
993
+ })
994
+ .sort((a, b) => b.value - a.value || a.i - b.i)
995
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
996
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
997
+ const slices: DonutSlice[] = top.map((item, rank) => ({
998
+ name: item.name,
999
+ value: item.value,
1000
+ // A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
1001
+ color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
1002
+ isOther: false,
1003
+ row: item.row,
1004
+ }))
1005
+ if (other) {
1006
+ slices.push({
1007
+ name: other.name,
1008
+ value: other.value,
1009
+ color: otherColor,
1010
+ isOther: true,
1011
+ row: { [index]: other.name, [value]: other.value },
1012
+ })
1013
+ }
1014
+ return slices
1015
+ }
1016
+
1017
+ /* ---------------------------------------------------------------- BarList */
1018
+
1019
+ type BarListSortOrder = "ascending" | "descending" | "none"
1020
+
1021
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
1022
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
1023
+ const rows = [...data]
1024
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
1025
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
1026
+ return rows
1027
+ }
1028
+
1029
+ /** BarList-only settings. */
1030
+ interface BarListOptions {
1031
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
1032
+ sortOrder?: BarListSortOrder
1033
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
1034
+ maxItems?: number
1035
+ /** まとめた行のラベル。既定「その他」。 */
1036
+ otherLabel?: string
1037
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
1038
+ exclude?: readonly string[]
1039
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
1040
+ showShare?: boolean
1041
+ }
1042
+
1043
+ /** One drawn BarList row. */
1044
+ interface BarListRow<Row = Record<string, unknown>> {
1045
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
1046
+ key: string
1047
+ name: string
1048
+ value: number
1049
+ /** Only for real rows; the folded row never links. */
1050
+ href?: string
1051
+ /** Legacy per-row colour (`BarListItem.color`). */
1052
+ color?: ChartColor
1053
+ /** The folded「その他」row. */
1054
+ isOther: boolean
1055
+ /** The input row (`null` for the folded row). */
1056
+ row: Row | null
1057
+ }
1058
+
1059
+ interface BarListRowsConfig extends BarListOptions {
1060
+ /** Name column. Default `"name"`. */
1061
+ index?: string
1062
+ /** Value column. Default `"value"`. */
1063
+ category?: string
1064
+ }
1065
+
1066
+ /**
1067
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
1068
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
1069
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
1070
+ * ranking and are always added to「その他」.
1071
+ */
1072
+ function barListRows<Row extends object>(
1073
+ data: readonly Row[],
1074
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
1075
+ ): BarListRow<Row>[] {
1076
+ const items = data.map((row): BarListRow<Row> => {
1077
+ const cells = row as Record<string, unknown>
1078
+ const name = String(cells[index] ?? "")
1079
+ return {
1080
+ key: typeof cells.key === "string" ? cells.key : name,
1081
+ name,
1082
+ value: toChartNumber(cells[category]) ?? 0,
1083
+ href: typeof cells.href === "string" ? cells.href : undefined,
1084
+ color: typeof cells.color === "string" ? cells.color : undefined,
1085
+ isOther: false,
1086
+ row,
1087
+ }
1088
+ })
1089
+ const excluded = new Set(exclude ?? [])
1090
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
1091
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
1092
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
1093
+ const rows = sortBarListData(top, sortOrder)
1094
+ if (other || outside.length > 0) {
1095
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
1096
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
1097
+ }
1098
+ return rows
1099
+ }
1100
+
1101
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
1102
+ function barListWidths(values: readonly number[]): number[] {
1103
+ const max = Math.max(0, ...values)
1104
+ if (max === 0) return values.map(() => 0)
1105
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
1106
+ }
1107
+
1108
+ /**
1109
+ * How strongly the BarList bars are painted: every row the same tint of the bar
1110
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
1111
+ * it sits on the card in light and dark; it must stay visible against the card
1112
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
1113
+ */
1114
+ const BAR_LIST_TINT = 45
1115
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
1116
+ const BAR_LIST_OTHER_TINT = 30
1117
+
1118
+ /**
1119
+ * The fill of each BarList row: all real rows in the same tint of `color`
1120
+ * (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
1121
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
1122
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
1123
+ * for that row. A tint, not the solid token, so the label printed over the bar
1124
+ * keeps its contrast.
1125
+ */
1126
+ function barListFills(
1127
+ rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
1128
+ color: ChartColor,
1129
+ otherColor: string,
1130
+ ): string[] {
1131
+ return rows.map((row) =>
1132
+ row.isOther || isOtherName(row.name)
1133
+ ? tintCss(otherColor, BAR_LIST_OTHER_TINT)
1134
+ : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
1135
+ )
1136
+ }
1137
+
1138
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
1139
+ function barListShareText(value: number, total: number): string {
1140
+ const v = Number.isFinite(value) && value > 0 ? value : 0
1141
+ if (total <= 0 || v === 0) return "0%"
1142
+ const pct = (v / total) * 100
1143
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
1144
+ }
1145
+
1146
+ /**
1147
+ * The text at the end of each BarList row: the formatted value and, with
1148
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
1149
+ * so the shares are of the whole list): `value` and `share` apart (the share is
1150
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
1151
+ */
1152
+ function barListValueTexts(
1153
+ values: readonly number[],
1154
+ formatter: ValueFormatter,
1155
+ showShare = false,
1156
+ ): { value: string; share?: string; text: string }[] {
1157
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1158
+ return values.map((v) => {
1159
+ const value = formatter(v)
1160
+ if (!showShare) return { value, text: value }
1161
+ const share = barListShareText(v, total)
1162
+ return { value, share, text: `${value} · ${share}` }
1163
+ })
1164
+ }
1165
+
1166
+ /* -------------------------------------------------------------- DataTable */
1167
+
1168
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
1169
+ interface ChartDataTable {
1170
+ /** 表の見出し(`<caption>`)。 */
1171
+ caption?: string
1172
+ /** 列見出し。先頭がラベル列。 */
1173
+ columns: string[]
1174
+ /** 行。セルは書式済みの文字列。 */
1175
+ rows: string[][]
1176
+ }
1177
+
1178
+ /**
1179
+ * The chart's numbers as a table, for screen readers: one row per data row, the
1180
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
1181
+ * 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).
1182
+ */
1183
+ function chartDataTable(
1184
+ data: readonly Record<string, unknown>[],
1185
+ index: string,
1186
+ categories: readonly string[],
1187
+ formatter: ValueFormatter,
1188
+ labels?: Readonly<Record<string, string>>,
1189
+ indexName?: string,
1190
+ ): ChartDataTable {
1191
+ const label = (key: string) => labels?.[key] ?? key
1192
+ return {
1193
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
1194
+ rows: data.map((row) => [
1195
+ String(row[index] ?? ""),
1196
+ ...categories.map((key) => {
1197
+ const n = toChartNumber(row[key])
1198
+ return n === null ? EMPTY_VALUE : formatter(n)
1199
+ }),
1200
+ ]),
1201
+ }
1202
+ }
1203
+
1204
+ /* ------------------------------------------------------------ CategoryBar */
1205
+
1206
+ interface CategoryBarSegment {
1207
+ /** Width in percent of the whole bar. */
1208
+ width: number
1209
+ /** Where the segment starts, in percent. */
1210
+ start: number
1211
+ /** The running total at the segment's end — what its right-hand label shows. */
1212
+ end: number
1213
+ }
1214
+
1215
+ /** Lay the values side by side; negative values count as zero. */
1216
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
1217
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
1218
+ const total = clean.reduce((sum, v) => sum + v, 0)
1219
+ let running = 0
1220
+ return clean.map((v) => {
1221
+ const start = total === 0 ? 0 : (running / total) * 100
1222
+ running += v
1223
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
1224
+ })
1225
+ }
1226
+
1227
+ interface CategoryBarLabel {
1228
+ /** Position in percent of the bar. */
1229
+ position: number
1230
+ /** The running total printed there. */
1231
+ value: number
1232
+ }
1233
+
1234
+ /**
1235
+ * Tick labels under the bar: `0` at the start, then the running total at each
1236
+ * segment's end. A label closer than `minGap` percent to the one before is
1237
+ * dropped so narrow segments don't print on top of each other — except the
1238
+ * last one (the total), which replaces its neighbour instead. With a
1239
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
1240
+ * too — the marker sits right under it and the two read as one crowded spot.
1241
+ */
1242
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
1243
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
1244
+ if (segments.length === 0) return []
1245
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
1246
+ segments.forEach((s, i) => {
1247
+ const label = { position: s.start + s.width, value: s.end }
1248
+ const prev = labels[labels.length - 1]!
1249
+ if (label.position - prev.position >= minGap) labels.push(label)
1250
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
1251
+ })
1252
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1253
+ return labels.filter(
1254
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1255
+ )
1256
+ }
1257
+
1258
+ /**
1259
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1260
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1261
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1262
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1263
+ * the rest 7 px at 12 px type).
1264
+ */
1265
+ function categoryBarFitLabels(
1266
+ labels: readonly CategoryBarLabel[],
1267
+ texts: readonly string[],
1268
+ width: number,
1269
+ gap = 8,
1270
+ ): CategoryBarLabel[] {
1271
+ const textWidth = (text: string) => {
1272
+ let w = 0
1273
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1274
+ return w
1275
+ }
1276
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1277
+ const w = textWidth(text)
1278
+ if (label.position <= 0) return [0, w]
1279
+ if (label.position >= 100) return [width - w, width]
1280
+ const center = (label.position / 100) * width
1281
+ return [center - w / 2, center + w / 2]
1282
+ }
1283
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1284
+ labels.forEach((label, i) => {
1285
+ const here = extent(label, texts[i] ?? "")
1286
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1287
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1288
+ else if (touches()) return
1289
+ kept.push({ label, extent: here })
1290
+ })
1291
+ return kept.map((k) => k.label)
1292
+ }
1293
+
1294
+ /** Marker position in percent of the bar, clamped to its ends. */
1295
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
1296
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1297
+ if (total === 0) return 0
1298
+ return clamp((value / total) * 100, 0, 100)
1299
+ }
1300
+
1301
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
1302
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
1303
+ const segments = categoryBarSegments(values)
1304
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
1305
+ if (index !== -1) return index
1306
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
1307
+ return 0
1308
+ }
1309
+
1310
+ /* --------------------------------------------------------- ProgressCircle */
1311
+
1312
+ interface ProgressCircleGeometry {
1313
+ /** SVG width/height. */
1314
+ size: number
1315
+ /** Radius of the stroke's centre line. */
1316
+ normalizedRadius: number
1317
+ circumference: number
1318
+ /** `stroke-dashoffset` for the value arc. */
1319
+ offset: number
1320
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
1321
+ ratio: number
1322
+ }
1323
+
1324
+ function progressCircleGeometry(
1325
+ value: number,
1326
+ max: number,
1327
+ radius: number,
1328
+ strokeWidth: number,
1329
+ ): ProgressCircleGeometry {
1330
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
1331
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
1332
+ const circumference = 2 * Math.PI * normalizedRadius
1333
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
1334
+ }
1335
+
1336
+ /* ---------------------------------------------------------------- summary */
1337
+
1338
+ interface ChartSummaryInput {
1339
+ data: readonly Record<string, unknown>[]
1340
+ /** The x-axis key. */
1341
+ index: string
1342
+ /** Series keys; the first one is described. */
1343
+ categories: readonly string[]
1344
+ /** Title of the chart, put in front when given. */
1345
+ title?: string
1346
+ /** Same as the chart's `format` (default `"compact"`). */
1347
+ format?: ValueFormat
1348
+ /** Wins over `format`. */
1349
+ valueFormatter?: ValueFormatter
1350
+ /** Language of the sentence. Default the page's locale (`<html lang>`). */
1351
+ locale?: string
1352
+ }
1353
+
1354
+ const SUMMARY_TEXT = {
1355
+ ja: {
1356
+ up: "、前の点より増加",
1357
+ down: "、前の点より減少",
1358
+ flat: "、前の点と横ばい",
1359
+ latest: (label: string, value: string) => `最新 ${label} は ${value}`,
1360
+ top: (name: string, share: string) => `最大は ${name}(${share})`,
1361
+ },
1362
+ en: {
1363
+ up: ", up from the previous point",
1364
+ down: ", down from the previous point",
1365
+ flat: ", flat from the previous point",
1366
+ latest: (label: string, value: string) => `Latest ${label}: ${value}`,
1367
+ top: (name: string, share: string) => `Largest: ${name} (${share})`,
1368
+ },
1369
+ }
1370
+
1371
+ /**
1372
+ * One-sentence summary built from the rows, for `summary="auto"`:
1373
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
1374
+ * computed from the last two non-empty points of the first series — never
1375
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1376
+ * no usable point.
1377
+ */
1378
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1379
+ const key = input.categories[0]
1380
+ if (key === undefined) return undefined
1381
+ const points: { label: string; value: number }[] = []
1382
+ for (const row of input.data) {
1383
+ const raw = row[key]
1384
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1385
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1386
+ }
1387
+ const latest = points[points.length - 1]
1388
+ if (!latest) return undefined
1389
+ const locale = resolveLocale(input.locale)
1390
+ const t = SUMMARY_TEXT[uiLanguage(locale)]
1391
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
1392
+ const prev = points[points.length - 2]
1393
+ const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
1394
+ const head = input.title ? `${input.title}: ` : ""
1395
+ return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
1396
+ }
1397
+
1398
+ /**
1399
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
1400
+ * (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
1401
+ */
1402
+ function buildShareSummary(
1403
+ slices: readonly { name: string; value: number }[],
1404
+ title?: string,
1405
+ locale?: string,
1406
+ ): string | undefined {
1407
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1408
+ const top = slices[0]
1409
+ if (!top || total <= 0) return undefined
1410
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1411
+ return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
1412
+ }
1413
+
1414
+ /* ---------- inlined from @squadbase/squadkit registry/lib/color-ramp.ts (internal to @squadbase/vantage) ---------- */
1415
+
1416
+ /**
1417
+ * The single-hue ramp the canvas charts shade by (FilledMap, SymbolMap, Treemap): the tone mixed into the surface
1418
+ * it sits on, from 20% (the lowest value) to 100% (the highest). The same ramp as Heatmap's, computed per value so
1419
+ * no visual map is needed. Pure and DOM-free; canvas-safe colours in, `rgb()` out (internal chart helper).
1420
+ */
1421
+
1422
+ /** The lightest end of the ramp is this share of the tone mixed into the surface; the darkest end is the tone itself. */
1423
+ const RAMP_FLOOR_SHARE = 0.2
1424
+ /** At or above this share of the ramp a mark is dark: text on it takes the surface colour, below it the foreground. */
1425
+ const RAMP_LIGHT_TEXT_FROM = 0.55
1426
+
1427
+ /** `#rrggbb` / `rgb()` / `rgba()` → [r, g, b] (0–255), or null. */
1428
+ function parseRgb(color: string): [number, number, number] | null {
1429
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1430
+ if (hex) {
1431
+ const n = parseInt(hex[1]!, 16)
1432
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
1433
+ }
1434
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1435
+ return rgb ? [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])] : null
1436
+ }
1437
+
1438
+ const toLinear = (c: number) => ((c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
1439
+ 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)))
1440
+
1441
+ function toOklab([r, g, b]: [number, number, number]): [number, number, number] {
1442
+ const [lr, lg, lb] = [toLinear(r), toLinear(g), toLinear(b)]
1443
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb)
1444
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb)
1445
+ const t = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb)
1446
+ 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]
1447
+ }
1448
+
1449
+ function fromOklab([L, a, b]: [number, number, number]): string {
1450
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
1451
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
1452
+ const t = (L - 0.0894841775 * a - 1.291485548 * b) ** 3
1453
+ 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]
1454
+ return `rgb(${rgb.map(fromLinear).join(", ")})`
1455
+ }
1456
+
1457
+ /** A canvas-safe colour at `alpha`; anything unreadable comes back unchanged. */
1458
+ function withAlpha(color: string, alpha: number): string {
1459
+ const c = parseRgb(color)
1460
+ return c ? `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${alpha})` : color
1461
+ }
1462
+
1463
+ /**
1464
+ * `share` (0–1) of `color` mixed into `surface` — the canvas form of `color-mix(in oklch, <color> N%, <surface>)`.
1465
+ * An unreadable colour falls back to `color` at `share` opacity.
1466
+ */
1467
+ function mixIntoSurface(color: string, surface: string | undefined, share: number): string {
1468
+ const c = parseRgb(color)
1469
+ const s = surface ? parseRgb(surface) : null
1470
+ if (!c || !s) return withAlpha(color, share)
1471
+ const [c1, c2] = [toOklab(c), toOklab(s)]
1472
+ return fromOklab([0, 1, 2].map((i) => c2[i]! + (c1[i]! - c2[i]!) * share) as [number, number, number])
1473
+ }
1474
+
1475
+ /** Where a value sits on a `[min, max]` ramp (0–1, clamped). A flat range reads as the top. */
1476
+ function rampRatio(value: number, min: number, max: number): number {
1477
+ return max > min ? Math.min(1, Math.max(0, (value - min) / (max - min))) : 1
1478
+ }
1479
+
1480
+ /** The ramp colour at `ratio` (0 = the floor, 20% of the tone; 1 = the tone itself). */
1481
+ function rampColor(color: string, surface: string | undefined, ratio: number): string {
1482
+ return mixIntoSurface(color, surface, RAMP_FLOOR_SHARE + (1 - RAMP_FLOOR_SHARE) * Math.min(1, Math.max(0, ratio)))
1483
+ }
1484
+
1485
+ /** The CSS gradient of the ramp for an HTML legend (`tone` is a token name such as `"chart-1"`). */
1486
+ function rampGradientCss(tone: string): string {
1487
+ return `linear-gradient(to right, color-mix(in oklch, var(--${tone}) ${RAMP_FLOOR_SHARE * 100}%, var(--card)), var(--${tone}))`
1488
+ }
1489
+
1490
+ /* ---------- end of inlined code ---------- */
1491
+
1492
+ // The treemap series is this part's own.
1493
+ use([TreemapChart])
1494
+
1495
+ /** Categories coloured `--chart-1..5` (largest first); the rest share the「その他」grey. */
1496
+ const MAX_CATEGORIES = 5
1497
+
1498
+ /** Columns of `T` that hold numbers (null / undefined allowed for gaps); untyped rows keep every key. */
1499
+ type NumericColumn<T> = {
1500
+ [K in keyof T]-?: unknown extends T[K] ? K : T[K] extends number | bigint | null | undefined ? K : never
1501
+ }[keyof T] &
1502
+ string
1503
+
1504
+ export interface TreemapProps<T extends Record<string, unknown> = Record<string, unknown>> extends ChartRootAttributes {
1505
+ /** 行の配列。1 行 = 1 タイル(集計済みの値)。 */
1506
+ data: T[]
1507
+ /** タイル(葉)の名前の列名。例 `"product"`。 */
1508
+ index: keyof T & string
1509
+ /** 親の列名(2 階層にする)。例 `"category"`。省略時は 1 階層。 */
1510
+ group?: keyof T & string
1511
+ /** タイルの面積を決める数値の列名。0 以下・欠損の行は面積を持たない(データ表には残る)。 */
1512
+ value: NumericColumn<T>
1513
+ /** タイルの色を決める数値の列名(`tone` の単色の濃淡)。省略時は `group`(無ければ `index`)ごとのカテゴリ色。 */
1514
+ color?: NumericColumn<T>
1515
+ /** 列名・値 → 表示名(タイル・ツールチップ・凡例・データ表)。 */
1516
+ labels?: Record<string, string>
1517
+ /** `value` の書式。既定 `"number"`。 */
1518
+ format?: ValueFormat
1519
+ /** `color` の値の書式。省略時は `format`。 */
1520
+ colorFormat?: ValueFormat
1521
+ /** 書式を関数で直接渡す逃げ道(`value`)。`format` より優先する。 */
1522
+ valueFormatter?: ValueFormatter
1523
+ /** 数値の `color` の濃淡の色。既定 `"chart-1"`。 */
1524
+ tone?: ChartSeriesColor
1525
+ /** 凡例(カテゴリ色なら色の一覧、数値の色なら濃淡の帯)を出す。既定 `true`(カテゴリ色は `group` があるときだけ)。 */
1526
+ showLegend?: boolean
1527
+ /** ホバーでツールチップを出す。既定 `true`。 */
1528
+ showTooltip?: boolean
1529
+ /** タイルのクリック。その行を受け取る(フィルターの操作に使う)。 */
1530
+ onSelect?: (row: T) => void
1531
+ /** グラフの見出し。 */
1532
+ title?: string
1533
+ /** グラフが言っていることの 1 文要約。`"auto"` で最大のタイルとその構成比。 */
1534
+ summary?: string | "auto"
1535
+ /** 読み込み中。最終形と同じ高さのスケルトンを出す。 */
1536
+ isLoading?: boolean
1537
+ /** `data` が空のときの表示。 */
1538
+ emptyState?: ChartEmptyState
1539
+ /** プロット領域の高さ(px)。既定 288。 */
1540
+ height?: number
1541
+ /** 生成した EChartsOption に最後に深くマージする逃げ道。 */
1542
+ chartOptions?: EChartsOption
1543
+ /** グラフ右上に PNG 保存/コピーのボタンを出す。 */
1544
+ actions?: boolean | ChartActionsOptions
1545
+ /** PNG 保存時のファイル名(拡張子つき)。 */
1546
+ fileName?: string
1547
+ className?: string
1548
+ /** スクリーンリーダー向けのラベル。 */
1549
+ ariaLabel?: string
1550
+ }
1551
+
1552
+ /* ------------------------------------------------------------------ model */
1553
+
1554
+ export interface TreemapLeaf {
1555
+ name: string
1556
+ group: string | null
1557
+ value: number | null
1558
+ shade: number | null
1559
+ row: Record<string, unknown>
1560
+ }
1561
+
1562
+ export interface TreemapModel {
1563
+ /** Every row, in data order. */
1564
+ leaves: TreemapLeaf[]
1565
+ /** Leaves that take area (value > 0), grouped; groups and leaves largest first. */
1566
+ groups: { name: string | null; total: number; leaves: TreemapLeaf[] }[]
1567
+ /** The colour categories (groups, or leaves without a group), largest first. */
1568
+ categories: string[]
1569
+ total: number
1570
+ shadeMin: number
1571
+ shadeMax: number
1572
+ }
1573
+
1574
+ export function buildTreemapModel(config: {
1575
+ data: readonly Record<string, unknown>[]
1576
+ index: string
1577
+ group?: string
1578
+ value: string
1579
+ color?: string
1580
+ }): TreemapModel {
1581
+ const { data, index, group, value, color } = config
1582
+ const leaves: TreemapLeaf[] = []
1583
+ let [lo, hi] = [Infinity, -Infinity]
1584
+ for (const row of data) {
1585
+ if (!row || typeof row !== "object") continue
1586
+ const shade = color ? toChartNumber(row[color]) : null
1587
+ if (shade !== null) [lo, hi] = [Math.min(lo, shade), Math.max(hi, shade)]
1588
+ leaves.push({
1589
+ name: String(row[index] ?? EMPTY_VALUE),
1590
+ group: group ? String(row[group] ?? EMPTY_VALUE) : null,
1591
+ value: toChartNumber(row[value]),
1592
+ shade,
1593
+ row,
1594
+ })
1595
+ }
1596
+ const byGroup = new Map<string | null, TreemapLeaf[]>()
1597
+ for (const leaf of leaves) {
1598
+ if (leaf.value === null || leaf.value <= 0) continue
1599
+ const list = byGroup.get(leaf.group) ?? []
1600
+ list.push(leaf)
1601
+ byGroup.set(leaf.group, list)
1602
+ }
1603
+ const groups = [...byGroup.entries()]
1604
+ .map(([name, list]) => ({ name, total: list.reduce((s, l) => s + (l.value as number), 0), leaves: [...list].sort((a, b) => (b.value as number) - (a.value as number)) }))
1605
+ .sort((a, b) => b.total - a.total)
1606
+ const total = groups.reduce((s, g) => s + g.total, 0)
1607
+ const categories = group
1608
+ ? groups.map((g) => g.name as string)
1609
+ : [...new Set(groups.flatMap((g) => g.leaves.map((l) => l.name)))]
1610
+ const shadeMin = Number.isFinite(lo) ? lo : 0
1611
+ let shadeMax = Number.isFinite(hi) ? hi : 1
1612
+ if (shadeMax <= shadeMin) shadeMax = shadeMin + 1
1613
+ return { leaves, groups, categories, total, shadeMin, shadeMax }
1614
+ }
1615
+
1616
+ function escapeHtml(text: string): string {
1617
+ return text.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!)
1618
+ }
1619
+
1620
+ const TEXT = {
1621
+ ja: {
1622
+ join: "・",
1623
+ item: "項目",
1624
+ group: "グループ",
1625
+ share: "構成比",
1626
+ top: (name: string, share: string) => `最大は ${name}(全体の ${share})`,
1627
+ chart: (value: string) => `${value}のツリーマップ`,
1628
+ },
1629
+ en: {
1630
+ join: ", ",
1631
+ item: "Item",
1632
+ group: "Group",
1633
+ share: "Share",
1634
+ top: (name: string, share: string) => `Largest: ${name} (${share} of the total)`,
1635
+ chart: (value: string) => `Treemap of ${value}`,
1636
+ },
1637
+ }
1638
+
1639
+ const textOf = (locale?: string) => TEXT[uiLanguage(resolveLocale(locale))]
1640
+
1641
+ export interface TreemapOptionConfig {
1642
+ model: TreemapModel
1643
+ hasGroup: boolean
1644
+ colorMode: "category" | "numeric"
1645
+ /** Resolved ramp colour (numeric). */
1646
+ toneColor: string
1647
+ /** Resolved category colours in order; the entry after the fifth is the「その他」grey. */
1648
+ categoryColors: readonly string[]
1649
+ surfaceColor?: string
1650
+ /** Text on a light tile. */
1651
+ foregroundColor: string
1652
+ labels?: Record<string, string>
1653
+ valueFormatter: ValueFormatter
1654
+ colorFormatter: ValueFormatter
1655
+ colorKey?: string
1656
+ showTooltip: boolean
1657
+ chartOptions?: EChartsOption
1658
+ locale?: string
1659
+ }
1660
+
1661
+ export function buildTreemapOption(config: TreemapOptionConfig): EChartsOption {
1662
+ const { model, labels, valueFormatter } = config
1663
+ const t = textOf(config.locale)
1664
+ const label = (key: string) => labels?.[key] ?? key
1665
+ const surface = config.surfaceColor ?? "#ffffff"
1666
+ const base = config.toneColor || "#6366f1"
1667
+ const categoryColor = (name: string) => {
1668
+ const at = model.categories.indexOf(name)
1669
+ return config.categoryColors[at === -1 ? MAX_CATEGORIES : Math.min(at, MAX_CATEGORIES)] ?? base
1670
+ }
1671
+ const share = (v: number) => formatValue(model.total > 0 ? v / model.total : 0, "percent", config.locale)
1672
+ const leafNode = (leaf: TreemapLeaf) => {
1673
+ let fill: string
1674
+ let dark = true
1675
+ if (config.colorMode === "numeric") {
1676
+ const ratio = leaf.shade === null ? 0 : rampRatio(leaf.shade, model.shadeMin, model.shadeMax)
1677
+ fill = rampColor(base, config.surfaceColor, ratio)
1678
+ dark = ratio >= RAMP_LIGHT_TEXT_FROM
1679
+ } else fill = categoryColor(config.hasGroup ? (leaf.group as string) : leaf.name)
1680
+ return {
1681
+ name: label(leaf.name),
1682
+ value: leaf.value as number,
1683
+ leaf,
1684
+ itemStyle: { color: fill },
1685
+ label: { color: dark ? surface : config.foregroundColor },
1686
+ }
1687
+ }
1688
+ const tooltip = (leaf: TreemapLeaf | undefined, name: string, value: number): string => {
1689
+ const head = leaf?.group != null ? `${escapeHtml(label(leaf.group))} / ${escapeHtml(name)}` : escapeHtml(name)
1690
+ const parts = [`${head} ${escapeHtml(valueFormatter(value))}`, `${t.share} ${escapeHtml(share(value))}`]
1691
+ if (leaf && config.colorKey && config.colorMode === "numeric")
1692
+ parts.push(`${escapeHtml(label(config.colorKey))} ${leaf.shade === null ? EMPTY_VALUE : escapeHtml(config.colorFormatter(leaf.shade))}`)
1693
+ return parts.join(t.join)
1694
+ }
1695
+ const data = config.hasGroup
1696
+ ? model.groups.map((g) => ({
1697
+ name: label(g.name as string),
1698
+ value: g.total,
1699
+ itemStyle: { color: config.colorMode === "numeric" ? config.foregroundColor : categoryColor(g.name as string) },
1700
+ children: g.leaves.map(leafNode),
1701
+ }))
1702
+ : model.groups.flatMap((g) => g.leaves.map(leafNode))
1703
+ const option: EChartsOption = {
1704
+ animation: false,
1705
+ tooltip: config.showTooltip
1706
+ ? {
1707
+ trigger: "item",
1708
+ formatter: (p: unknown) => {
1709
+ const d = p as { name: string; value: number; data: { leaf?: TreemapLeaf } }
1710
+ return tooltip(d.data?.leaf, d.name, Number(d.value))
1711
+ },
1712
+ }
1713
+ : { show: false },
1714
+ series: [
1715
+ {
1716
+ id: "tiles",
1717
+ type: "treemap",
1718
+ left: 0,
1719
+ right: 0,
1720
+ top: 0,
1721
+ bottom: 0,
1722
+ roam: false,
1723
+ nodeClick: false,
1724
+ breadcrumb: { show: false },
1725
+ squareRatio: 0.5 * (1 + Math.sqrt(5)),
1726
+ label: {
1727
+ show: true,
1728
+ position: "insideTopLeft",
1729
+ overflow: "truncate",
1730
+ lineHeight: 16,
1731
+ formatter: (p: unknown) => {
1732
+ const d = p as { name: string; value: number }
1733
+ return `${d.name}\n${valueFormatter(Number(d.value))}`
1734
+ },
1735
+ },
1736
+ upperLabel: { show: config.hasGroup, height: 20, color: surface, fontWeight: 600 },
1737
+ itemStyle: { borderColor: surface, borderWidth: 1, gapWidth: 1 },
1738
+ emphasis: { disabled: true },
1739
+ levels: config.hasGroup
1740
+ ? [{ itemStyle: { borderColor: surface, borderWidth: 2, gapWidth: 2 } }, { itemStyle: { borderColor: surface, borderWidth: 0, gapWidth: 1 } }]
1741
+ : [{ itemStyle: { borderColor: surface, borderWidth: 0, gapWidth: 1 } }],
1742
+ data,
1743
+ } as never,
1744
+ ],
1745
+ }
1746
+ return config.chartOptions
1747
+ ? (mergeDeep(option as Record<string, unknown>, config.chartOptions as Record<string, unknown>) as EChartsOption)
1748
+ : option
1749
+ }
1750
+
1751
+ function mergeDeep(a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown> {
1752
+ const out: Record<string, unknown> = { ...a }
1753
+ for (const [k, v] of Object.entries(b)) {
1754
+ const cur = out[k]
1755
+ out[k] =
1756
+ v && cur && typeof v === "object" && typeof cur === "object" && !Array.isArray(v) && !Array.isArray(cur)
1757
+ ? mergeDeep(cur as Record<string, unknown>, v as Record<string, unknown>)
1758
+ : v
1759
+ }
1760
+ return out
1761
+ }
1762
+
1763
+ /** The screen-reader table: every row (in data order), with its share of the total. */
1764
+ export function treemapDataTable(
1765
+ model: TreemapModel,
1766
+ names: { index: string; group?: string; value: string; color?: string },
1767
+ formatters: { value: ValueFormatter; color: ValueFormatter },
1768
+ labels?: Record<string, string>,
1769
+ locale?: string,
1770
+ ): ChartDataTable {
1771
+ const t = textOf(locale)
1772
+ const label = (key: string) => labels?.[key] ?? key
1773
+ const share = (v: number | null) => (v === null || v <= 0 || model.total <= 0 ? EMPTY_VALUE : formatValue(v / model.total, "percent", locale))
1774
+ return {
1775
+ columns: [
1776
+ ...(names.group ? [labels?.[names.group] ?? t.group] : []),
1777
+ labels?.[names.index] ?? t.item,
1778
+ label(names.value),
1779
+ t.share,
1780
+ ...(names.color && names.color !== names.value ? [label(names.color)] : []),
1781
+ ],
1782
+ rows: model.leaves.map((leaf) => [
1783
+ ...(names.group ? [label(leaf.group ?? EMPTY_VALUE)] : []),
1784
+ label(leaf.name),
1785
+ leaf.value === null ? EMPTY_VALUE : formatters.value(leaf.value),
1786
+ share(leaf.value),
1787
+ ...(names.color && names.color !== names.value ? [leaf.shade === null ? EMPTY_VALUE : formatters.color(leaf.shade)] : []),
1788
+ ]),
1789
+ }
1790
+ }
1791
+
1792
+ /** `summary="auto"`: the largest tile and its share. */
1793
+ export function buildTreemapSummary(model: TreemapModel, title?: string, labels?: Record<string, string>, locale?: string): string | undefined {
1794
+ let best: TreemapLeaf | undefined
1795
+ for (const g of model.groups) for (const l of g.leaves) if (!best || (l.value as number) > (best.value as number)) best = l
1796
+ if (!best || model.total <= 0) return undefined
1797
+ return `${title ? `${title}: ` : ""}${textOf(locale).top(labels?.[best.name] ?? best.name, formatValue((best.value as number) / model.total, "percent", locale))}`
1798
+ }
1799
+
1800
+ /* -------------------------------------------------------------- component */
1801
+
1802
+ function colorsFor(tokens: ChartTokens | null, tone: string) {
1803
+ const resolved = resolveChartColors([tone, "var(--foreground)", ...DEFAULT_CHART_COLORS, CHART_OTHER_COLOR], tokens)
1804
+ const [toneColor = "", foreground = ""] = resolved
1805
+ return { toneColor, foreground, categories: resolved.slice(2) }
1806
+ }
1807
+
1808
+ /** Rows not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
1809
+ const NO_ROWS: never[] = []
1810
+
1811
+ function TreemapImpl<T extends Record<string, unknown>>(
1812
+ {
1813
+ data = NO_ROWS,
1814
+ index,
1815
+ group,
1816
+ value,
1817
+ color,
1818
+ labels,
1819
+ format,
1820
+ colorFormat,
1821
+ valueFormatter,
1822
+ tone = "chart-1",
1823
+ showLegend = true,
1824
+ showTooltip = true,
1825
+ onSelect,
1826
+ title,
1827
+ summary,
1828
+ isLoading,
1829
+ emptyState,
1830
+ height,
1831
+ chartOptions,
1832
+ actions,
1833
+ fileName,
1834
+ className,
1835
+ ariaLabel,
1836
+ ...rest
1837
+ }: TreemapProps<T>,
1838
+ ref: ForwardedRef<HTMLDivElement>,
1839
+ ) {
1840
+ const rows = Array.isArray(data) ? data : NO_ROWS
1841
+ const { ref: frameRef, surface, tokens } = useChartSurface(ref)
1842
+ const locale = useLocale()
1843
+ const formatter = useMemo(() => resolveValueFormatter(valueFormatter, format ?? "number", locale), [valueFormatter, format, locale])
1844
+ const colorFormatter = useMemo(() => resolveValueFormatter(undefined, colorFormat ?? format ?? "number", locale), [colorFormat, format, locale])
1845
+ const model = useMemo(() => buildTreemapModel({ data: rows, index, group, value, color }), [rows, index, group, value, color])
1846
+ const colorMode = color ? "numeric" : "category"
1847
+ const colors = useMemo(() => colorsFor(tokens, tone), [tokens, tone])
1848
+ const option = useMemo(
1849
+ () =>
1850
+ buildTreemapOption({
1851
+ model,
1852
+ hasGroup: !!group,
1853
+ colorMode,
1854
+ toneColor: colors.toneColor,
1855
+ categoryColors: colors.categories,
1856
+ surfaceColor: surface ?? undefined,
1857
+ foregroundColor: colors.foreground || tokens?.foreground || "#111111",
1858
+ labels,
1859
+ valueFormatter: formatter,
1860
+ colorFormatter,
1861
+ colorKey: color,
1862
+ showTooltip,
1863
+ chartOptions,
1864
+ locale,
1865
+ }),
1866
+ [model, group, colorMode, colors, surface, tokens, labels, formatter, colorFormatter, color, showTooltip, chartOptions, locale],
1867
+ )
1868
+ const onEvents = useMemo(
1869
+ () =>
1870
+ onSelect
1871
+ ? {
1872
+ click: (params: unknown) => {
1873
+ const leaf = (params as { data?: { leaf?: TreemapLeaf } }).data?.leaf
1874
+ if (leaf) onSelect(leaf.row as T)
1875
+ },
1876
+ }
1877
+ : undefined,
1878
+ [onSelect],
1879
+ )
1880
+ const dataTable = useMemo(
1881
+ () => treemapDataTable(model, { index, group, value, color }, { value: formatter, color: colorFormatter }, labels, locale),
1882
+ [model, index, group, value, color, formatter, colorFormatter, labels, locale],
1883
+ )
1884
+ const resolvedSummary = useMemo(
1885
+ () => (summary === "auto" ? buildTreemapSummary(model, title, labels, locale) : summary),
1886
+ [summary, model, title, labels, locale],
1887
+ )
1888
+ const label = ariaLabel ?? textOf(locale).chart(labels?.[value] ?? value ?? "")
1889
+ const legendCategories =
1890
+ model.categories.length > MAX_CATEGORIES ? [...model.categories.slice(0, MAX_CATEGORIES), otherSeriesLabel(locale)] : model.categories
1891
+ const legend = !showLegend ? null : colorMode === "numeric" ? (
1892
+ <div data-slot="treemap-legend" className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground tabular-nums">
1893
+ <span className="flex items-center gap-2">
1894
+ {color && <span>{labels?.[color] ?? color}</span>}
1895
+ <span>{colorFormatter(model.shadeMin)}</span>
1896
+ <span aria-hidden className="h-2 w-24 rounded-sm" style={{ backgroundImage: rampGradientCss(tone) }} />
1897
+ <span>{colorFormatter(model.shadeMax)}</span>
1898
+ </span>
1899
+ </div>
1900
+ ) : group ? (
1901
+ <Legend categories={legendCategories} labels={labels} />
1902
+ ) : null
1903
+ return (
1904
+ <ChartFrame
1905
+ {...chartRootProps(rest)}
1906
+ ref={frameRef}
1907
+ title={title}
1908
+ summary={resolvedSummary}
1909
+ isLoading={isLoading ?? false}
1910
+ isEmpty={rows.length === 0}
1911
+ emptyState={emptyState}
1912
+ height={height}
1913
+ variant="bar"
1914
+ ariaLabel={label}
1915
+ className={className}
1916
+ dataTable={dataTable}
1917
+ >
1918
+ <div className="flex h-full w-full flex-col gap-2">
1919
+ <div className="min-h-0 flex-1">
1920
+ <EChart option={option} onEvents={onEvents} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
1921
+ </div>
1922
+ {legend}
1923
+ </div>
1924
+ </ChartFrame>
1925
+ )
1926
+ }
1927
+
1928
+ /** Generic over the row type, so the column keys are checked against `data`. */
1929
+ export const Treemap = forwardRef(TreemapImpl as (props: TreemapProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
1930
+ T extends Record<string, unknown>,
1931
+ >(
1932
+ props: TreemapProps<T> & { ref?: Ref<HTMLDivElement> },
1933
+ ) => ReactElement) & { displayName?: string }
1934
+ Treemap.displayName = "Treemap"