@squadbase/vantage 0.7.0-stg.18ca87d → 0.7.1-dev1.5e06644

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 (73) 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-TRMHNMMZ.js → chunk-LYUGDHSF.js} +3 -3
  7. package/dist/{chunk-TRMHNMMZ.js.map → chunk-LYUGDHSF.js.map} +1 -1
  8. package/dist/{chunk-QNOX7WLZ.js → chunk-MQUIAP66.js} +69 -4
  9. package/dist/chunk-MQUIAP66.js.map +1 -0
  10. package/dist/{chunk-2IAPIOPS.js → chunk-P2KIHF65.js} +2 -2
  11. package/dist/chunk-P2KIHF65.js.map +1 -0
  12. package/dist/{chunk-3RJEOP3J.js → chunk-XRKSIC5Z.js} +5 -3
  13. package/dist/chunk-XRKSIC5Z.js.map +1 -0
  14. package/dist/{chunk-77CISBMG.js → chunk-YJQCB3UP.js} +3387 -204
  15. package/dist/chunk-YJQCB3UP.js.map +1 -0
  16. package/dist/cli.js +2 -2
  17. package/dist/components/index.d.ts +627 -7
  18. package/dist/components/index.js +4 -4
  19. package/dist/{delta-text-CbrOaW83.d.ts → delta-text-tav2Lh5d.d.ts} +1 -1
  20. package/dist/doc/index.d.ts +2 -2
  21. package/dist/doc/index.js +4 -4
  22. package/dist/{format-DihQkL1N.d.ts → format-D34piCei.d.ts} +2 -1
  23. package/dist/geo-japan-7BMSOJRX.js +8 -0
  24. package/dist/geo-japan-7BMSOJRX.js.map +1 -0
  25. package/dist/geo-us-GVOG7VXH.js +8 -0
  26. package/dist/geo-us-GVOG7VXH.js.map +1 -0
  27. package/dist/geo-world-35HL56UU.js +8 -0
  28. package/dist/geo-world-35HL56UU.js.map +1 -0
  29. package/dist/slide/index.d.ts +2 -2
  30. package/dist/slide/index.js +3 -3
  31. package/dist/table/index.js +4 -5
  32. package/dist/table/index.js.map +1 -1
  33. package/dist/ui/index.js +2 -3
  34. package/dist/ui/index.js.map +1 -1
  35. package/dist/{upgrade-6DT7ADRP.js → upgrade-MCHMELWC.js} +3 -3
  36. package/dist/{upgrade-6DT7ADRP.js.map → upgrade-MCHMELWC.js.map} +1 -1
  37. package/docs/en/agent-skills.md +13 -14
  38. package/docs/en/changelog.md +8 -0
  39. package/docs/en/parts/draft-chart.md +42 -0
  40. package/docs/en/parts/page-shell.md +1 -1
  41. package/docs/index.json +70 -50
  42. package/docs/ja/agent-skills.md +14 -14
  43. package/docs/ja/changelog.md +8 -0
  44. package/docs/ja/parts/draft-chart.md +40 -0
  45. package/docs/ja/parts/page-shell.md +1 -1
  46. package/package.json +2 -2
  47. package/registry/parts.json +5221 -0
  48. package/registry/ui/chart-frame.tsx +8 -0
  49. package/registry/ui/combo-chart.tsx +1852 -0
  50. package/registry/ui/dashboard-card.tsx +3 -1
  51. package/registry/ui/data-table.tsx +3 -1
  52. package/registry/ui/delta.tsx +3 -1
  53. package/registry/ui/filter-bar.tsx +3 -1
  54. package/registry/ui/forecast-chart.tsx +4734 -0
  55. package/registry/ui/funnel-steps.tsx +1 -1
  56. package/registry/ui/kpi-card.tsx +3 -1
  57. package/registry/ui/metric-value.tsx +2 -2
  58. package/registry/ui/page-shell.tsx +25 -4
  59. package/registry/ui/paired-chart.tsx +1 -1
  60. package/registry/ui/pivot-table.tsx +1260 -0
  61. package/registry/ui/progress-circle.tsx +2 -2
  62. package/registry/ui/sparkline.tsx +1 -1
  63. package/registry/ui/treemap.tsx +1917 -0
  64. package/templates/AGENTS.md +1 -1
  65. package/dist/add-4GHF2TX2.js +0 -6
  66. package/dist/add-4GHF2TX2.js.map +0 -1
  67. package/dist/chunk-2IAPIOPS.js.map +0 -1
  68. package/dist/chunk-3RJEOP3J.js.map +0 -1
  69. package/dist/chunk-77CISBMG.js.map +0 -1
  70. package/dist/chunk-AABMKHEU.js.map +0 -1
  71. package/dist/chunk-NZ5QIIG4.js +0 -74
  72. package/dist/chunk-NZ5QIIG4.js.map +0 -1
  73. package/dist/chunk-QNOX7WLZ.js.map +0 -1
@@ -0,0 +1,1852 @@
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
+ * 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
+ /* ---------- end of inlined code ---------- */
1397
+
1398
+ export type ComboSeriesType = "bar" | "line" | "area"
1399
+ export type ComboAxis = "left" | "right"
1400
+
1401
+ /** One measure of a ComboChart. */
1402
+ export interface ComboSeries<K extends string = string> {
1403
+ /** 値の列名。 */
1404
+ key: K
1405
+ /** 描き方。`"bar"`(棒)・`"line"`(線)・`"area"`(面)。 */
1406
+ type: ComboSeriesType
1407
+ /** どちらの値の軸で読むか。既定 `"left"`。`"right"` の系列が 1 つでもあると右軸を出す。 */
1408
+ axis?: ComboAxis
1409
+ /** 凡例・ツールチップの表示名。省略時は `labels[key]`、無ければ列名。 */
1410
+ label?: string
1411
+ /** 色。`"chart-1"`〜`"chart-5"` か意味色。省略時は系列の順にトークン色。 */
1412
+ color?: ChartSeriesColor
1413
+ }
1414
+
1415
+ /** A dashed horizontal (vertical with `layout="vertical"`) line at a value of one axis. */
1416
+ export interface ComboReferenceLine {
1417
+ /** 線を引く値。 */
1418
+ value: number
1419
+ /** どちらの軸の値か。既定 `"left"`。 */
1420
+ axis?: ComboAxis
1421
+ /** 線のラベル。省略時は軸の書式で値を書く。 */
1422
+ label?: string
1423
+ }
1424
+
1425
+ export interface ComboChartProps<T extends Record<string, unknown> = Record<string, unknown>> extends ChartRootAttributes {
1426
+ /** 行の配列。1 行 = カテゴリ軸の 1 つの値(集計済み)。 */
1427
+ data: T[]
1428
+ /** カテゴリ軸(横軸)の列名。例 `"month"`・`"product"`。行の順に並ぶ。 */
1429
+ index: keyof T & string
1430
+ /** 描く系列。`{ key, type: "bar" | "line" | "area", axis?: "left" | "right", label? }` の配列。描く順(後ろほど手前)。 */
1431
+ series: ComboSeries<keyof T & string>[]
1432
+ /** 左軸(と左軸の系列のツールチップ・データ表)の書式。既定 `"compact"` 相当の短い表記。 */
1433
+ format?: ValueFormat
1434
+ /** 右軸の書式。例 パレート図の累積比なら `"percent"`。省略時は `format`。 */
1435
+ rightFormat?: ValueFormat
1436
+ /** 列名・カテゴリの値 → 表示名。 */
1437
+ labels?: Record<string, string>
1438
+ /** 参照線(目標・平均など)。`{ value, axis?, label? }` の配列。 */
1439
+ referenceLines?: ComboReferenceLine[]
1440
+ /** 同じ軸の棒どうし・面どうしを積み上げる。既定 `false`(棒は横に並べる)。 */
1441
+ stacked?: boolean
1442
+ /** `"vertical"` でカテゴリを縦軸に並べる(横棒)。左軸は下、右軸は上になる。既定 `"horizontal"`。 */
1443
+ layout?: "horizontal" | "vertical"
1444
+ /** 凡例を出す。既定 `true`(系列が 2 つ以上のとき)。 */
1445
+ showLegend?: boolean
1446
+ /** ホバーでツールチップを出す。既定 `true`。 */
1447
+ showTooltip?: boolean
1448
+ /** 棒・点のクリック。その行を受け取る(フィルターの操作に使う)。 */
1449
+ onSelect?: (row: T) => void
1450
+ /** グラフの見出し。 */
1451
+ title?: string
1452
+ /** グラフが言っていることの 1 文要約。 */
1453
+ summary?: string
1454
+ /** 読み込み中。最終形と同じ高さのスケルトンを出す。 */
1455
+ isLoading?: boolean
1456
+ /** `data` が空のときの表示。 */
1457
+ emptyState?: ChartEmptyState
1458
+ /** プロット領域の高さ(px)。既定 288。 */
1459
+ height?: number
1460
+ /** 生成した EChartsOption に最後に深くマージする逃げ道。 */
1461
+ chartOptions?: EChartsOption
1462
+ /** グラフ右上に PNG 保存/コピーのボタンを出す。 */
1463
+ actions?: boolean | ChartActionsOptions
1464
+ /** PNG 保存時のファイル名(拡張子つき)。 */
1465
+ fileName?: string
1466
+ className?: string
1467
+ /** スクリーンリーダー向けのラベル。 */
1468
+ ariaLabel?: string
1469
+ }
1470
+
1471
+ /* ------------------------------------------------------------------ model */
1472
+
1473
+ /** ECharts' "nice" step for a raw step: 1 / 2 / 3 / 5 × 10ⁿ (the same rule its value axis uses). */
1474
+ function niceStep(raw: number): number {
1475
+ if (!(raw > 0) || !Number.isFinite(raw)) return 1
1476
+ const exp10 = 10 ** Math.floor(Math.log10(raw))
1477
+ const f = raw / exp10
1478
+ return (f < 1.5 ? 1 : f < 2.5 ? 2 : f < 4 ? 3 : f < 7 ? 5 : 10) * exp10
1479
+ }
1480
+
1481
+ const round = (n: number) => Number(n.toPrecision(12))
1482
+
1483
+ export interface ComboAxisScale {
1484
+ min: number
1485
+ max: number
1486
+ interval: number
1487
+ /** The tick label formatter (one unit across the axis). */
1488
+ tick: ValueFormatter
1489
+ }
1490
+
1491
+ /**
1492
+ * The scale of one value axis over `[lo, hi]`: always includes 0, ends on whole steps, and widens the step until
1493
+ * no two tick labels read the same (`¥1M, ¥1M, ¥2M` from a step of 0.5M in a compact format becomes 1M steps).
1494
+ */
1495
+ export function comboAxisScale(lo: number, hi: number, splitNumber: number, ticks: (top: number) => ValueFormatter): ComboAxisScale {
1496
+ let low = Math.min(0, Number.isFinite(lo) ? lo : 0)
1497
+ let high = Math.max(0, Number.isFinite(hi) ? hi : 0)
1498
+ if (high <= low) high = low + 1
1499
+ let step = niceStep((high - low) / Math.max(1, splitNumber))
1500
+ for (let attempt = 0; ; attempt++) {
1501
+ const min = round(Math.floor(low / step) * step)
1502
+ const max = round(Math.ceil(high / step) * step)
1503
+ const tick = ticks(Math.max(Math.abs(min), Math.abs(max)))
1504
+ const count = Math.round((max - min) / step)
1505
+ const labels = Array.from({ length: count + 1 }, (_, i) => tick(round(min + i * step)))
1506
+ if (new Set(labels).size === labels.length || attempt >= 6) return { min, max, interval: step, tick }
1507
+ step = niceStep(step * 2)
1508
+ }
1509
+ }
1510
+
1511
+ /** The plot height (px) when `height` is not given (ChartFrame's default). */
1512
+ const DEFAULT_CHART_HEIGHT = 288
1513
+
1514
+ /** How many intervals a value axis carries at a plot height: 3 under 200px, 4 under 300px, else 5. */
1515
+ const splitCountFor = (height: number) => (height < 200 ? 3 : height < 300 ? 4 : 5)
1516
+
1517
+ function escapeHtml(text: string): string {
1518
+ return text.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!)
1519
+ }
1520
+
1521
+ const TEXT = {
1522
+ ja: { item: "項目", chart: "複合グラフ" },
1523
+ en: { item: "Item", chart: "Combination chart" },
1524
+ }
1525
+ const textOf = (locale?: string) => TEXT[uiLanguage(resolveLocale(locale))]
1526
+
1527
+ export interface ComboChartOptionConfig {
1528
+ data: readonly Record<string, unknown>[]
1529
+ index: string
1530
+ series: readonly ComboSeries[]
1531
+ /** Resolved (canvas-safe) colour per series; `""` leaves the theme palette. */
1532
+ palette: readonly string[]
1533
+ /** Resolved colour of the reference lines. */
1534
+ referenceColor: string
1535
+ labels?: Record<string, string>
1536
+ formatters: Record<ComboAxis, ValueFormatter>
1537
+ ticks: Record<ComboAxis, (top: number) => ValueFormatter>
1538
+ referenceLines?: readonly ComboReferenceLine[]
1539
+ stacked?: boolean
1540
+ layout?: "horizontal" | "vertical"
1541
+ showLegend?: boolean
1542
+ showTooltip?: boolean
1543
+ plotHeight?: number
1544
+ chartOptions?: EChartsOption
1545
+ }
1546
+
1547
+ const axisOf = (s: { axis?: ComboAxis }): ComboAxis => (s.axis === "right" ? "right" : "left")
1548
+
1549
+ /** The series a ComboChart can draw: entries with a key and a known type. */
1550
+ export function comboSeriesList(series: unknown): ComboSeries[] {
1551
+ if (!Array.isArray(series)) return []
1552
+ return series.filter(
1553
+ (s): s is ComboSeries => !!s && typeof s === "object" && typeof (s as ComboSeries).key === "string" && ["bar", "line", "area"].includes((s as ComboSeries).type),
1554
+ )
1555
+ }
1556
+
1557
+ export function buildComboChartOption(config: ComboChartOptionConfig): EChartsOption {
1558
+ const { data, index, labels, formatters } = config
1559
+ const series = comboSeriesList(config.series)
1560
+ const label = (key: string) => labels?.[key] ?? key
1561
+ const seriesName = (s: ComboSeries) => s.label ?? label(s.key)
1562
+ const vertical = config.layout === "vertical"
1563
+ const categories = data.map((row) => String(row?.[index] ?? ""))
1564
+ const values = series.map((s) => data.map((row) => toChartNumber(row?.[s.key])))
1565
+ const hasRight = series.some((s) => axisOf(s) === "right")
1566
+ const axes: ComboAxis[] = hasRight ? ["left", "right"] : ["left"]
1567
+
1568
+ // Each axis' extent: its series (stacked bars / areas by their running sums), and its reference lines.
1569
+ const extent = (axis: ComboAxis): [number, number] => {
1570
+ let [lo, hi] = [0, 0]
1571
+ const add = (v: number | null) => {
1572
+ if (v !== null && Number.isFinite(v)) [lo, hi] = [Math.min(lo, v), Math.max(hi, v)]
1573
+ }
1574
+ const stacks = new Map<string, { pos: number[]; neg: number[] }>()
1575
+ series.forEach((s, i) => {
1576
+ if (axisOf(s) !== axis) return
1577
+ if (config.stacked && s.type !== "line") {
1578
+ const stack = stacks.get(s.type) ?? { pos: data.map(() => 0), neg: data.map(() => 0) }
1579
+ values[i]!.forEach((v, j) => {
1580
+ if (v === null) return
1581
+ if (v >= 0) stack.pos[j]! += v
1582
+ else stack.neg[j]! += v
1583
+ })
1584
+ stacks.set(s.type, stack)
1585
+ } else values[i]!.forEach(add)
1586
+ })
1587
+ for (const stack of stacks.values()) [...stack.pos, ...stack.neg].forEach(add)
1588
+ for (const ref of config.referenceLines ?? []) if (axisOf(ref) === axis) add(toChartNumber(ref.value))
1589
+ return [lo, hi]
1590
+ }
1591
+ const split = splitCountFor(config.plotHeight ?? DEFAULT_CHART_HEIGHT)
1592
+ const scales = Object.fromEntries(axes.map((axis) => [axis, comboAxisScale(...extent(axis), split, config.ticks[axis])])) as Record<ComboAxis, ComboAxisScale>
1593
+
1594
+ const valueAxes = axes.map((axis) => ({
1595
+ type: "value" as const,
1596
+ position: vertical ? (axis === "left" ? ("bottom" as const) : ("top" as const)) : axis,
1597
+ min: scales[axis].min,
1598
+ max: scales[axis].max,
1599
+ interval: scales[axis].interval,
1600
+ axisLine: { show: false },
1601
+ axisTick: { show: false },
1602
+ splitLine: { show: axis === "left" },
1603
+ axisLabel: { formatter: (v: number) => scales[axis].tick(v), hideOverlap: vertical ? true : undefined },
1604
+ }))
1605
+ const categoryAxis = {
1606
+ type: "category" as const,
1607
+ data: categories,
1608
+ inverse: vertical,
1609
+ axisTick: { show: false },
1610
+ axisLabel: { formatter: (v: string) => label(v), hideOverlap: true },
1611
+ }
1612
+
1613
+ const axisIndex = (s: { axis?: ComboAxis }) => (axisOf(s) === "right" ? 1 : 0)
1614
+ const drawn = series.map((s, i) => {
1615
+ const color = config.palette[i] || undefined
1616
+ const common = {
1617
+ id: `series-${i}`,
1618
+ name: seriesName(s),
1619
+ data: values[i],
1620
+ [vertical ? "xAxisIndex" : "yAxisIndex"]: axisIndex(s),
1621
+ emphasis: { focus: "none" as const },
1622
+ }
1623
+ if (s.type === "bar")
1624
+ return {
1625
+ ...common,
1626
+ type: "bar" as const,
1627
+ stack: config.stacked ? `bar-${axisOf(s)}` : undefined,
1628
+ barMaxWidth: 40,
1629
+ itemStyle: { color, borderRadius: vertical ? [0, 2, 2, 0] : [2, 2, 0, 0] },
1630
+ }
1631
+ return {
1632
+ ...common,
1633
+ type: "line" as const,
1634
+ stack: config.stacked && s.type === "area" ? `area-${axisOf(s)}` : undefined,
1635
+ symbol: "circle",
1636
+ symbolSize: 6,
1637
+ showSymbol: data.length <= 24,
1638
+ connectNulls: false,
1639
+ lineStyle: { width: 2, color },
1640
+ itemStyle: { color },
1641
+ areaStyle: s.type === "area" ? { color, opacity: 0.18 } : undefined,
1642
+ z: 3,
1643
+ }
1644
+ })
1645
+ const references = axes.flatMap((axis) => {
1646
+ const lines = (config.referenceLines ?? []).filter((r) => axisOf(r) === axis && toChartNumber(r.value) !== null)
1647
+ if (lines.length === 0) return []
1648
+ return [
1649
+ {
1650
+ id: `reference-${axis}`,
1651
+ type: "line" as const,
1652
+ data: data.map(() => null),
1653
+ [vertical ? "xAxisIndex" : "yAxisIndex"]: axis === "right" ? 1 : 0,
1654
+ silent: true,
1655
+ symbol: "none",
1656
+ tooltip: { show: false },
1657
+ markLine: {
1658
+ silent: true,
1659
+ symbol: "none",
1660
+ lineStyle: { type: "dashed" as const, color: config.referenceColor || undefined, width: 1 },
1661
+ label: { position: "insideEndTop" as const, color: config.referenceColor || undefined },
1662
+ data: lines.map((r) => ({
1663
+ [vertical ? "xAxis" : "yAxis"]: toChartNumber(r.value),
1664
+ label: { formatter: r.label ?? config.formatters[axis](toChartNumber(r.value) as number) },
1665
+ })),
1666
+ },
1667
+ },
1668
+ ]
1669
+ })
1670
+
1671
+ const showLegend = (config.showLegend ?? true) && series.length > 1
1672
+ const tooltip = (params: unknown): string => {
1673
+ const items = (Array.isArray(params) ? params : [params]) as { seriesIndex: number; dataIndex: number; marker?: string }[]
1674
+ const first = items[0]
1675
+ if (!first) return ""
1676
+ const head = escapeHtml(label(categories[first.dataIndex] ?? ""))
1677
+ const lines = items
1678
+ .filter((p) => p.seriesIndex < series.length)
1679
+ .map((p) => {
1680
+ const s = series[p.seriesIndex]!
1681
+ const v = values[p.seriesIndex]![p.dataIndex]
1682
+ return `${p.marker ?? ""}${escapeHtml(seriesName(s))} ${v === null || v === undefined ? EMPTY_VALUE : escapeHtml(formatters[axisOf(s)](v))}`
1683
+ })
1684
+ return [head, ...lines].join("<br/>")
1685
+ }
1686
+ const option: EChartsOption = {
1687
+ animation: false,
1688
+ legend: { show: showLegend, top: 0, left: 0, data: series.map(seriesName) },
1689
+ tooltip: config.showTooltip === false ? { show: false } : { trigger: "axis", axisPointer: { type: "shadow" }, formatter: tooltip },
1690
+ grid: { left: 8, right: 8, top: showLegend ? 36 : 12, bottom: 8, containLabel: true },
1691
+ xAxis: vertical ? valueAxes : categoryAxis,
1692
+ yAxis: vertical ? categoryAxis : valueAxes,
1693
+ series: [...drawn, ...references] as never,
1694
+ }
1695
+ return config.chartOptions
1696
+ ? (mergeDeep(option as Record<string, unknown>, config.chartOptions as Record<string, unknown>) as EChartsOption)
1697
+ : option
1698
+ }
1699
+
1700
+ function mergeDeep(a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown> {
1701
+ const out: Record<string, unknown> = { ...a }
1702
+ for (const [k, v] of Object.entries(b)) {
1703
+ const cur = out[k]
1704
+ out[k] =
1705
+ v && cur && typeof v === "object" && typeof cur === "object" && !Array.isArray(v) && !Array.isArray(cur)
1706
+ ? mergeDeep(cur as Record<string, unknown>, v as Record<string, unknown>)
1707
+ : v
1708
+ }
1709
+ return out
1710
+ }
1711
+
1712
+ /** The screen-reader table: one row per category, one column per series, each in its axis' format. */
1713
+ export function comboChartDataTable(
1714
+ data: readonly Record<string, unknown>[],
1715
+ index: string,
1716
+ series: readonly ComboSeries[],
1717
+ formatters: Record<ComboAxis, ValueFormatter>,
1718
+ labels?: Record<string, string>,
1719
+ locale?: string,
1720
+ ): ChartDataTable {
1721
+ const list = comboSeriesList(series)
1722
+ const label = (key: string) => labels?.[key] ?? key
1723
+ return {
1724
+ columns: [labels?.[index] ?? textOf(locale).item, ...list.map((s) => s.label ?? label(s.key))],
1725
+ rows: data.map((row) => [
1726
+ label(String(row?.[index] ?? "")),
1727
+ ...list.map((s) => {
1728
+ const n = toChartNumber(row?.[s.key])
1729
+ return n === null ? EMPTY_VALUE : formatters[axisOf(s)](n)
1730
+ }),
1731
+ ]),
1732
+ }
1733
+ }
1734
+
1735
+ /* -------------------------------------------------------------- component */
1736
+
1737
+ /** Rows / series not given yet (a draft fills props in steps): keep the same array between renders. */
1738
+ const NO_ROWS: never[] = []
1739
+
1740
+ function ComboChartImpl<T extends Record<string, unknown>>(
1741
+ {
1742
+ data = NO_ROWS,
1743
+ index,
1744
+ series = NO_ROWS,
1745
+ format,
1746
+ rightFormat,
1747
+ labels,
1748
+ referenceLines,
1749
+ stacked = false,
1750
+ layout = "horizontal",
1751
+ showLegend = true,
1752
+ showTooltip = true,
1753
+ onSelect,
1754
+ title,
1755
+ summary,
1756
+ isLoading,
1757
+ emptyState,
1758
+ height,
1759
+ chartOptions,
1760
+ actions,
1761
+ fileName,
1762
+ className,
1763
+ ariaLabel,
1764
+ ...rest
1765
+ }: ComboChartProps<T>,
1766
+ ref: ForwardedRef<HTMLDivElement>,
1767
+ ) {
1768
+ const rows = Array.isArray(data) ? data : NO_ROWS
1769
+ const list = useMemo(() => comboSeriesList(series), [series])
1770
+ const { ref: frameRef, tokens } = useChartSurface(ref)
1771
+ const locale = useLocale()
1772
+ const formatters = useMemo(
1773
+ () => ({ left: resolveValueFormatter(undefined, format, locale), right: resolveValueFormatter(undefined, rightFormat ?? format, locale) }),
1774
+ [format, rightFormat, locale],
1775
+ )
1776
+ const ticks = useMemo(
1777
+ () => ({ left: resolveAxisTickFormatter(undefined, format, locale), right: resolveAxisTickFormatter(undefined, rightFormat ?? format, locale) }),
1778
+ [format, rightFormat, locale],
1779
+ )
1780
+ const palette = useMemo(() => resolveColors(tokens, list), [tokens, list])
1781
+ const option = useMemo(
1782
+ () =>
1783
+ buildComboChartOption({
1784
+ data: rows,
1785
+ index,
1786
+ series: list,
1787
+ palette: palette.series,
1788
+ referenceColor: palette.reference,
1789
+ labels,
1790
+ formatters,
1791
+ ticks,
1792
+ referenceLines,
1793
+ stacked,
1794
+ layout,
1795
+ showLegend,
1796
+ showTooltip,
1797
+ plotHeight: height,
1798
+ chartOptions,
1799
+ }),
1800
+ [rows, index, list, palette, labels, formatters, ticks, referenceLines, stacked, layout, showLegend, showTooltip, height, chartOptions],
1801
+ )
1802
+ const onEvents = useMemo(
1803
+ () =>
1804
+ onSelect
1805
+ ? {
1806
+ click: (params: unknown) => {
1807
+ const p = params as { componentType?: string; seriesIndex?: number; dataIndex?: number }
1808
+ if (p.componentType !== "series" || (p.seriesIndex ?? Infinity) >= list.length) return
1809
+ const row = rows[p.dataIndex ?? -1]
1810
+ if (row) onSelect(row)
1811
+ },
1812
+ }
1813
+ : undefined,
1814
+ [onSelect, rows, list.length],
1815
+ )
1816
+ const dataTable = useMemo(() => comboChartDataTable(rows, index, list, formatters, labels, locale), [rows, index, list, formatters, labels, locale])
1817
+ const label = ariaLabel ?? textOf(locale).chart
1818
+ return (
1819
+ <ChartFrame
1820
+ {...chartRootProps(rest)}
1821
+ ref={frameRef}
1822
+ title={title}
1823
+ summary={summary}
1824
+ isLoading={isLoading ?? false}
1825
+ isEmpty={rows.length === 0}
1826
+ emptyState={emptyState}
1827
+ height={height}
1828
+ variant="bar"
1829
+ ariaLabel={label}
1830
+ className={className}
1831
+ dataTable={dataTable}
1832
+ >
1833
+ <EChart option={option} onEvents={onEvents} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary }} />
1834
+ </ChartFrame>
1835
+ )
1836
+ }
1837
+
1838
+ function resolveColors(tokens: ChartTokens | null, series: readonly ComboSeries[]) {
1839
+ const resolved = resolveChartColors(
1840
+ ["var(--muted-foreground)", ...series.map((s, i) => s.color ?? DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!)],
1841
+ tokens,
1842
+ )
1843
+ return { reference: resolved[0] ?? "", series: resolved.slice(1) }
1844
+ }
1845
+
1846
+ /** Generic over the row type, so `index` and the series keys are checked against `data`. */
1847
+ export const ComboChart = forwardRef(ComboChartImpl as (props: ComboChartProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
1848
+ T extends Record<string, unknown>,
1849
+ >(
1850
+ props: ComboChartProps<T> & { ref?: Ref<HTMLDivElement> },
1851
+ ) => ReactElement) & { displayName?: string }
1852
+ ComboChart.displayName = "ComboChart"