@squadbase/vantage 0.7.0-dev1.275b4ed → 0.7.0-dev1.3b0e616

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