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