@squadbase/vantage 0.7.0 → 0.7.1-dev1.618b9b9

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 (74) 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 +3 -3
  65. package/templates/agents/page.md +5 -4
  66. package/dist/add-4GHF2TX2.js +0 -6
  67. package/dist/add-4GHF2TX2.js.map +0 -1
  68. package/dist/chunk-2IAPIOPS.js.map +0 -1
  69. package/dist/chunk-3RJEOP3J.js.map +0 -1
  70. package/dist/chunk-77CISBMG.js.map +0 -1
  71. package/dist/chunk-AABMKHEU.js.map +0 -1
  72. package/dist/chunk-NZ5QIIG4.js +0 -74
  73. package/dist/chunk-NZ5QIIG4.js.map +0 -1
  74. package/dist/chunk-QNOX7WLZ.js.map +0 -1
@@ -0,0 +1,1260 @@
1
+ // Copied by `vantage add ui pivot-table`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/components/pivot-table.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * PivotTable — a crosstab of already-aggregated rows.
7
+ * Row dimensions down the side (nested, with merged header
8
+ * cells), column dimensions across the top, and one or more measures in the cells (several measures become
9
+ * sub-columns). The part does not aggregate: it only places each row in its cell, and when two rows land in the
10
+ * same cell the later one wins.
11
+ *
12
+ * `highlight` shades the cells by value on a single-hue ramp (Tableau's highlight table): `true` shades every
13
+ * measure (each on its own range), a measure name shades that one only. Numbers are right-aligned in `tabular-nums`,
14
+ * a missing value reads「—」. The header stays visible while the table scrolls inside its box; a wide table scrolls
15
+ * sideways inside the card. Clicking a cell calls `onSelect` with its row.
16
+ */
17
+ import { useMemo, type CSSProperties } from "react"
18
+
19
+ import { ChartFrame } from "@squadbase/vantage/components"
20
+ import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@squadbase/vantage/ui"
21
+ import { cn } from "@squadbase/vantage/ui"
22
+ import { EMPTY_VALUE, formatValue, type ValueFormat } from "@squadbase/vantage/components"
23
+ import type { ChartEmptyState, ChartSeriesColor } from "@squadbase/vantage/components"
24
+ import { useSyncExternalStore } from "react"
25
+ import { toValueFormatter } from "@squadbase/vantage/components"
26
+ import type { ChartColor, ChartColors, ChartTone, ValueFormatter } from "@squadbase/vantage/components"
27
+
28
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
29
+
30
+ /**
31
+ * The display language of the parts and the defaults that follow it.
32
+ *
33
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
34
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
35
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
36
+ *
37
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
38
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
39
+ */
40
+
41
+ /** The language of the built-in wording: Japanese or English. */
42
+ type UiLanguage = "ja" | "en"
43
+
44
+ /** The locale used when `<html lang>` gives none (and on the server). */
45
+ const FALLBACK_LOCALE = "en-US"
46
+
47
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
48
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
49
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
50
+ }
51
+
52
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
53
+ function normalizeLocale(tag: string | null | undefined): string {
54
+ const value = tag?.trim()
55
+ if (!value) return FALLBACK_LOCALE
56
+ try {
57
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
58
+ } catch {
59
+ return FALLBACK_LOCALE
60
+ }
61
+ }
62
+
63
+ /**
64
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
65
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
66
+ */
67
+ function documentLocale(): string {
68
+ if (typeof document === "undefined") return FALLBACK_LOCALE
69
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
70
+ }
71
+
72
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
73
+ function resolveLocale(locale?: string | null): string {
74
+ return locale || documentLocale()
75
+ }
76
+
77
+ /** Picks the wording table of the locale's language. */
78
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
79
+ return table[uiLanguage(resolveLocale(locale))]
80
+ }
81
+
82
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
83
+ function defaultCurrency(locale?: string | null): string {
84
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
85
+ }
86
+
87
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
88
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
89
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
90
+ }
91
+
92
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
93
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
94
+
95
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
96
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
97
+
98
+ /**
99
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
100
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
101
+ * Monday for the rest.
102
+ */
103
+ function weekStartsOn(locale?: string | null): WeekDay {
104
+ const tag = normalizeLocale(resolveLocale(locale))
105
+ if (uiLanguage(tag) === "ja") return 1
106
+ try {
107
+ const info = new Intl.Locale(tag) as Intl.Locale & {
108
+ getWeekInfo?: () => { firstDay: number }
109
+ weekInfo?: { firstDay: number }
110
+ }
111
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
112
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
113
+ } catch {
114
+ // Fall through to the table below.
115
+ }
116
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
117
+ }
118
+
119
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
120
+
121
+ const listeners = new Set<() => void>()
122
+ let observer: MutationObserver | null = null
123
+
124
+ /** One observer on `<html lang>` for every subscribed part. */
125
+ function subscribe(onChange: () => void): () => void {
126
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
127
+ listeners.add(onChange)
128
+ if (!observer) {
129
+ observer = new MutationObserver(() => {
130
+ for (const listener of [...listeners]) listener()
131
+ })
132
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
133
+ }
134
+ return () => {
135
+ listeners.delete(onChange)
136
+ if (listeners.size === 0 && observer) {
137
+ observer.disconnect()
138
+ observer = null
139
+ }
140
+ }
141
+ }
142
+
143
+ const serverLocale = () => FALLBACK_LOCALE
144
+
145
+ /**
146
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
147
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
148
+ */
149
+ function useDocumentLocale(): string {
150
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
151
+ }
152
+
153
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
154
+ function useLocale(locale?: string | null): string {
155
+ const page = useDocumentLocale()
156
+ return locale || page
157
+ }
158
+
159
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
160
+
161
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
162
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
163
+
164
+ /**
165
+ * The attributes of a typed chart's leftover props that belong on its root
166
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
167
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
168
+ */
169
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
170
+ const out: Record<string, unknown> = {}
171
+ for (const [key, value] of Object.entries(rest)) {
172
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
173
+ }
174
+ return out
175
+ }
176
+
177
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
178
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
179
+ "chart-1",
180
+ "chart-2",
181
+ "chart-3",
182
+ "chart-4",
183
+ "chart-5",
184
+ ]
185
+
186
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
187
+
188
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
189
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
190
+
191
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
192
+ function isChartTone(color: string): color is ChartTone {
193
+ return (CHART_TONES as readonly string[]).includes(color.trim())
194
+ }
195
+
196
+ /**
197
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
198
+ * light/dark on its own), anything else passes through unchanged.
199
+ */
200
+ function chartColorToCss(color: ChartColor): string {
201
+ const value = color.trim()
202
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
203
+ }
204
+
205
+ /**
206
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
207
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
208
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
209
+ */
210
+ function chartFillToCss(color: ChartColor): string {
211
+ const value = color.trim()
212
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
213
+ }
214
+
215
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
216
+ function chartFillName(color: ChartColor): ChartColor {
217
+ const value = color.trim()
218
+ return isChartTone(value) ? `${value}-fill` : color
219
+ }
220
+
221
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
222
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
223
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
224
+ return palette[i % palette.length]!
225
+ }
226
+
227
+ /** `colors` extended (by cycling) to exactly `count` entries. */
228
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
229
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
230
+ }
231
+
232
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
233
+ function tintCss(cssColor: string, percent: number): string {
234
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
235
+ }
236
+
237
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
238
+
239
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
240
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
241
+
242
+ /**
243
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
244
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
245
+ */
246
+ function resolveValueFormatter(
247
+ valueFormatter: ValueFormatter | undefined,
248
+ format: ValueFormat | undefined,
249
+ locale?: string,
250
+ ): ValueFormatter {
251
+ return valueFormatter ?? toValueFormatter(format, locale)
252
+ }
253
+
254
+ /**
255
+ * The formatter of value-axis ticks and on-plot labels: an explicit
256
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
257
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
258
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
259
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
260
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
261
+ * currency sign and grouping.
262
+ */
263
+ function resolveAxisFormatter(
264
+ valueFormatter: ValueFormatter | undefined,
265
+ format: ValueFormat | undefined,
266
+ localeArg?: string,
267
+ ): ValueFormatter {
268
+ if (valueFormatter) return valueFormatter
269
+ const locale = resolveLocale(localeArg)
270
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
271
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
272
+ const currency = "currency" in spec ? spec.currency : undefined
273
+ const short: ValueFormat =
274
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
275
+ return (value) => formatValue(value, short, locale)
276
+ }
277
+
278
+ interface CompactUnit {
279
+ token: string
280
+ size: number
281
+ }
282
+
283
+ const compactUnitCache = new Map<string, CompactUnit[] | null>()
284
+
285
+ /**
286
+ * The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
287
+ * `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
288
+ * word (`1,5 Mio.`), where a token cannot be swapped in place.
289
+ */
290
+ function compactUnits(locale: string): CompactUnit[] | null {
291
+ const cached = compactUnitCache.get(locale)
292
+ if (cached !== undefined) return cached
293
+ let units: CompactUnit[] | null = []
294
+ try {
295
+ const compact = new Intl.NumberFormat(locale, { notation: "compact" })
296
+ const seen = new Set<string>()
297
+ for (let exp = 3; exp <= 15; exp++) {
298
+ const parts = compact.formatToParts(10 ** exp)
299
+ const at = parts.findIndex((p) => p.type === "compact")
300
+ if (at === -1) continue
301
+ if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
302
+ units = null
303
+ break
304
+ }
305
+ const token = parts[at]!.value
306
+ if (seen.has(token)) continue
307
+ seen.add(token)
308
+ units.push({ token, size: 10 ** exp })
309
+ }
310
+ } catch {
311
+ units = null
312
+ }
313
+ const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
314
+ compactUnitCache.set(locale, sorted)
315
+ return sorted
316
+ }
317
+
318
+ const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
319
+
320
+ /**
321
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
322
+ * that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
323
+ * `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
324
+ * no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
325
+ * unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
326
+ */
327
+ function resolveAxisTickFormatter(
328
+ valueFormatter: ValueFormatter | undefined,
329
+ format: ValueFormat | undefined,
330
+ localeArg?: string,
331
+ ): (top: number) => ValueFormatter {
332
+ const locale = resolveLocale(localeArg)
333
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
334
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
335
+ const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
336
+ if (!units) return () => base
337
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
338
+ const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
339
+ return (top) => {
340
+ const unit = units.find((u) => Math.abs(top) >= u.size)
341
+ if (!unit) return base
342
+ return (value) => {
343
+ const text = base(value)
344
+ if (value === 0 || !Number.isFinite(value)) return text
345
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
346
+ return text.replace(numberToken, () => scaled)
347
+ }
348
+ }
349
+ }
350
+
351
+ /**
352
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
353
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
354
+ */
355
+ function toChartNumber(value: unknown): number | null {
356
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
357
+ if (typeof value === "bigint") return Number(value)
358
+ if (typeof value === "string" && value.trim() !== "") {
359
+ const n = Number(value)
360
+ return Number.isFinite(n) ? n : null
361
+ }
362
+ return null
363
+ }
364
+
365
+ /** Clamp `value` into `[min, max]`. */
366
+ function clamp(value: number, min: number, max: number): number {
367
+ return Math.min(max, Math.max(min, value))
368
+ }
369
+
370
+ /* ------------------------------------------------------------ aggregation */
371
+
372
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
373
+ const MAX_CHART_SERIES = 5
374
+
375
+ /** The series name the folded categories get, by language. */
376
+ const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
377
+
378
+ /** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
379
+ function otherSeriesLabel(locale?: string): string {
380
+ return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
381
+ }
382
+
383
+ const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
384
+
385
+ /** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
386
+ function isOtherName(name: string | null | undefined): boolean {
387
+ return typeof name === "string" && OTHER_NAMES.has(name)
388
+ }
389
+
390
+ interface AggregatedItems<Item extends { name: string; value: number }> {
391
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
392
+ top: Item[]
393
+ /** The items folded into `other`, in their given order. */
394
+ rest: Item[]
395
+ /** The folded remainder, or `null` when nothing was folded. */
396
+ other: { name: string; value: number } | null
397
+ }
398
+
399
+ /**
400
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
401
+ * given order and fold the rest into one `otherLabel` item. Shared by every
402
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
403
+ * BarList rows).
404
+ */
405
+ function aggregateTopN<Item extends { name: string; value: number }>(
406
+ items: readonly Item[],
407
+ n: number = MAX_CHART_SERIES,
408
+ otherLabel: string = otherSeriesLabel(),
409
+ ): AggregatedItems<Item> {
410
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
411
+ const ranked = items
412
+ .map((item, i) => ({ item, i }))
413
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
414
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
415
+ const top = items.filter((_, i) => keep.has(i))
416
+ const rest = items.filter((_, i) => !keep.has(i))
417
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
418
+ }
419
+
420
+ interface AggregatedSeries {
421
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
422
+ data: Record<string, unknown>[]
423
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
424
+ categories: string[]
425
+ /** The folded series' name, or `null`. */
426
+ otherCategory: string | null
427
+ }
428
+
429
+ /**
430
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
431
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
432
+ */
433
+ function aggregateSeries(
434
+ data: readonly Record<string, unknown>[],
435
+ categories: readonly string[],
436
+ n: number = MAX_CHART_SERIES,
437
+ otherLabel: string = otherSeriesLabel(),
438
+ ): AggregatedSeries {
439
+ const totals = categories.map((name) => ({
440
+ name,
441
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
442
+ }))
443
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
444
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
445
+ const folded = rest.map((item) => item.name)
446
+ return {
447
+ data: data.map((row) => {
448
+ let sum: number | null = null
449
+ for (const name of folded) {
450
+ const v = toChartNumber(row[name])
451
+ if (v !== null) sum = (sum ?? 0) + v
452
+ }
453
+ return { ...row, [other.name]: sum }
454
+ }),
455
+ categories: [...top.map((item) => item.name), other.name],
456
+ otherCategory: other.name,
457
+ }
458
+ }
459
+
460
+ /**
461
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
462
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
463
+ */
464
+ function aggregateSeriesKeeping(
465
+ data: readonly Record<string, unknown>[],
466
+ categories: readonly string[],
467
+ keep: string | undefined,
468
+ n: number = MAX_CHART_SERIES,
469
+ otherLabel: string = otherSeriesLabel(),
470
+ ): AggregatedSeries {
471
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
472
+ const aggregated = aggregateSeries(
473
+ data,
474
+ categories.filter((c) => c !== keep),
475
+ n,
476
+ otherLabel,
477
+ )
478
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
479
+ }
480
+
481
+ /**
482
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
483
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
484
+ * so a main series keeps its colour whether or not a comparison is drawn.
485
+ */
486
+ function seriesColorsWithComparison(
487
+ categories: readonly string[],
488
+ colors: ChartColors | undefined,
489
+ otherColor: string,
490
+ otherCategory: string | null,
491
+ allCategories: readonly string[],
492
+ comparison: string | undefined,
493
+ ): string[] {
494
+ if (comparison === undefined || !categories.includes(comparison)) {
495
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
496
+ }
497
+ const main = categories.filter((c) => c !== comparison)
498
+ const mainColors = seriesColorsFor(
499
+ main,
500
+ colors,
501
+ otherColor,
502
+ otherCategory,
503
+ allCategories.filter((c) => c !== comparison),
504
+ )
505
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
506
+ }
507
+
508
+ /**
509
+ * Colour per drawn series: the record's token for that category, else the
510
+ * array's token at the category's position in `allCategories` (cycled), else
511
+ * the token palette by drawn position. `otherCategory` — and a category the
512
+ * data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
513
+ */
514
+ function seriesColorsFor(
515
+ categories: readonly string[],
516
+ colors: ChartColors | undefined,
517
+ otherColor: string,
518
+ otherCategory: string | null = null,
519
+ allCategories: readonly string[] = categories,
520
+ ): string[] {
521
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
522
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
523
+ return categories.map((category, i) => {
524
+ if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
525
+ const fromRecord = record?.[category]
526
+ if (fromRecord) return fromRecord
527
+ if (list && list.length > 0) {
528
+ const at = allCategories.indexOf(category)
529
+ return list[(at === -1 ? i : at) % list.length]!
530
+ }
531
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
532
+ })
533
+ }
534
+
535
+ /* ------------------------------------------------------------------ Donut */
536
+
537
+ /** One drawn donut slice, largest first. */
538
+ interface DonutSlice {
539
+ name: string
540
+ /** Negative and missing values count as 0. */
541
+ value: number
542
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
543
+ color: string
544
+ /** The folded「その他」slice. */
545
+ isOther: boolean
546
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
547
+ row: Record<string, unknown>
548
+ }
549
+
550
+ interface DonutSlicesConfig {
551
+ /** Label column. */
552
+ index: string
553
+ /** Value column. */
554
+ value: string
555
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
556
+ colors?: readonly ChartSeriesColor[]
557
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
558
+ maxSlices?: number
559
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
560
+ otherColor: string
561
+ otherLabel?: string
562
+ }
563
+
564
+ /**
565
+ * Donut slices: sorted by value (largest first, ties keep input order), the
566
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
567
+ * summed into one「その他」slice in `otherColor`.
568
+ */
569
+ function donutSlices(
570
+ data: readonly Record<string, unknown>[],
571
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
572
+ ): DonutSlice[] {
573
+ const items = data
574
+ .map((row, i) => {
575
+ const n = toChartNumber(row[value])
576
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
577
+ })
578
+ .sort((a, b) => b.value - a.value || a.i - b.i)
579
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
580
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
581
+ const slices: DonutSlice[] = top.map((item, rank) => ({
582
+ name: item.name,
583
+ value: item.value,
584
+ // A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
585
+ color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
586
+ isOther: false,
587
+ row: item.row,
588
+ }))
589
+ if (other) {
590
+ slices.push({
591
+ name: other.name,
592
+ value: other.value,
593
+ color: otherColor,
594
+ isOther: true,
595
+ row: { [index]: other.name, [value]: other.value },
596
+ })
597
+ }
598
+ return slices
599
+ }
600
+
601
+ /* ---------------------------------------------------------------- BarList */
602
+
603
+ type BarListSortOrder = "ascending" | "descending" | "none"
604
+
605
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
606
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
607
+ const rows = [...data]
608
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
609
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
610
+ return rows
611
+ }
612
+
613
+ /** BarList-only settings. */
614
+ interface BarListOptions {
615
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
616
+ sortOrder?: BarListSortOrder
617
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
618
+ maxItems?: number
619
+ /** まとめた行のラベル。既定「その他」。 */
620
+ otherLabel?: string
621
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
622
+ exclude?: readonly string[]
623
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
624
+ showShare?: boolean
625
+ }
626
+
627
+ /** One drawn BarList row. */
628
+ interface BarListRow<Row = Record<string, unknown>> {
629
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
630
+ key: string
631
+ name: string
632
+ value: number
633
+ /** Only for real rows; the folded row never links. */
634
+ href?: string
635
+ /** Legacy per-row colour (`BarListItem.color`). */
636
+ color?: ChartColor
637
+ /** The folded「その他」row. */
638
+ isOther: boolean
639
+ /** The input row (`null` for the folded row). */
640
+ row: Row | null
641
+ }
642
+
643
+ interface BarListRowsConfig extends BarListOptions {
644
+ /** Name column. Default `"name"`. */
645
+ index?: string
646
+ /** Value column. Default `"value"`. */
647
+ category?: string
648
+ }
649
+
650
+ /**
651
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
652
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
653
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
654
+ * ranking and are always added to「その他」.
655
+ */
656
+ function barListRows<Row extends object>(
657
+ data: readonly Row[],
658
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
659
+ ): BarListRow<Row>[] {
660
+ const items = data.map((row): BarListRow<Row> => {
661
+ const cells = row as Record<string, unknown>
662
+ const name = String(cells[index] ?? "")
663
+ return {
664
+ key: typeof cells.key === "string" ? cells.key : name,
665
+ name,
666
+ value: toChartNumber(cells[category]) ?? 0,
667
+ href: typeof cells.href === "string" ? cells.href : undefined,
668
+ color: typeof cells.color === "string" ? cells.color : undefined,
669
+ isOther: false,
670
+ row,
671
+ }
672
+ })
673
+ const excluded = new Set(exclude ?? [])
674
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
675
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
676
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
677
+ const rows = sortBarListData(top, sortOrder)
678
+ if (other || outside.length > 0) {
679
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
680
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
681
+ }
682
+ return rows
683
+ }
684
+
685
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
686
+ function barListWidths(values: readonly number[]): number[] {
687
+ const max = Math.max(0, ...values)
688
+ if (max === 0) return values.map(() => 0)
689
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
690
+ }
691
+
692
+ /**
693
+ * How strongly the BarList bars are painted: every row the same tint of the bar
694
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
695
+ * it sits on the card in light and dark; it must stay visible against the card
696
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
697
+ */
698
+ const BAR_LIST_TINT = 45
699
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
700
+ const BAR_LIST_OTHER_TINT = 30
701
+
702
+ /**
703
+ * The fill of each BarList row: all real rows in the same tint of `color`
704
+ * (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
705
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
706
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
707
+ * for that row. A tint, not the solid token, so the label printed over the bar
708
+ * keeps its contrast.
709
+ */
710
+ function barListFills(
711
+ rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
712
+ color: ChartColor,
713
+ otherColor: string,
714
+ ): string[] {
715
+ return rows.map((row) =>
716
+ row.isOther || isOtherName(row.name)
717
+ ? tintCss(otherColor, BAR_LIST_OTHER_TINT)
718
+ : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
719
+ )
720
+ }
721
+
722
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
723
+ function barListShareText(value: number, total: number): string {
724
+ const v = Number.isFinite(value) && value > 0 ? value : 0
725
+ if (total <= 0 || v === 0) return "0%"
726
+ const pct = (v / total) * 100
727
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
728
+ }
729
+
730
+ /**
731
+ * The text at the end of each BarList row: the formatted value and, with
732
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
733
+ * so the shares are of the whole list): `value` and `share` apart (the share is
734
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
735
+ */
736
+ function barListValueTexts(
737
+ values: readonly number[],
738
+ formatter: ValueFormatter,
739
+ showShare = false,
740
+ ): { value: string; share?: string; text: string }[] {
741
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
742
+ return values.map((v) => {
743
+ const value = formatter(v)
744
+ if (!showShare) return { value, text: value }
745
+ const share = barListShareText(v, total)
746
+ return { value, share, text: `${value} · ${share}` }
747
+ })
748
+ }
749
+
750
+ /* -------------------------------------------------------------- DataTable */
751
+
752
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
753
+ interface ChartDataTable {
754
+ /** 表の見出し(`<caption>`)。 */
755
+ caption?: string
756
+ /** 列見出し。先頭がラベル列。 */
757
+ columns: string[]
758
+ /** 行。セルは書式済みの文字列。 */
759
+ rows: string[][]
760
+ }
761
+
762
+ /**
763
+ * The chart's numbers as a table, for screen readers: one row per data row, the
764
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
765
+ * 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).
766
+ */
767
+ function chartDataTable(
768
+ data: readonly Record<string, unknown>[],
769
+ index: string,
770
+ categories: readonly string[],
771
+ formatter: ValueFormatter,
772
+ labels?: Readonly<Record<string, string>>,
773
+ indexName?: string,
774
+ ): ChartDataTable {
775
+ const label = (key: string) => labels?.[key] ?? key
776
+ return {
777
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
778
+ rows: data.map((row) => [
779
+ String(row[index] ?? ""),
780
+ ...categories.map((key) => {
781
+ const n = toChartNumber(row[key])
782
+ return n === null ? EMPTY_VALUE : formatter(n)
783
+ }),
784
+ ]),
785
+ }
786
+ }
787
+
788
+ /* ------------------------------------------------------------ CategoryBar */
789
+
790
+ interface CategoryBarSegment {
791
+ /** Width in percent of the whole bar. */
792
+ width: number
793
+ /** Where the segment starts, in percent. */
794
+ start: number
795
+ /** The running total at the segment's end — what its right-hand label shows. */
796
+ end: number
797
+ }
798
+
799
+ /** Lay the values side by side; negative values count as zero. */
800
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
801
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
802
+ const total = clean.reduce((sum, v) => sum + v, 0)
803
+ let running = 0
804
+ return clean.map((v) => {
805
+ const start = total === 0 ? 0 : (running / total) * 100
806
+ running += v
807
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
808
+ })
809
+ }
810
+
811
+ interface CategoryBarLabel {
812
+ /** Position in percent of the bar. */
813
+ position: number
814
+ /** The running total printed there. */
815
+ value: number
816
+ }
817
+
818
+ /**
819
+ * Tick labels under the bar: `0` at the start, then the running total at each
820
+ * segment's end. A label closer than `minGap` percent to the one before is
821
+ * dropped so narrow segments don't print on top of each other — except the
822
+ * last one (the total), which replaces its neighbour instead. With a
823
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
824
+ * too — the marker sits right under it and the two read as one crowded spot.
825
+ */
826
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
827
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
828
+ if (segments.length === 0) return []
829
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
830
+ segments.forEach((s, i) => {
831
+ const label = { position: s.start + s.width, value: s.end }
832
+ const prev = labels[labels.length - 1]!
833
+ if (label.position - prev.position >= minGap) labels.push(label)
834
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
835
+ })
836
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
837
+ return labels.filter(
838
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
839
+ )
840
+ }
841
+
842
+ /**
843
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
844
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
845
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
846
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
847
+ * the rest 7 px at 12 px type).
848
+ */
849
+ function categoryBarFitLabels(
850
+ labels: readonly CategoryBarLabel[],
851
+ texts: readonly string[],
852
+ width: number,
853
+ gap = 8,
854
+ ): CategoryBarLabel[] {
855
+ const textWidth = (text: string) => {
856
+ let w = 0
857
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
858
+ return w
859
+ }
860
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
861
+ const w = textWidth(text)
862
+ if (label.position <= 0) return [0, w]
863
+ if (label.position >= 100) return [width - w, width]
864
+ const center = (label.position / 100) * width
865
+ return [center - w / 2, center + w / 2]
866
+ }
867
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
868
+ labels.forEach((label, i) => {
869
+ const here = extent(label, texts[i] ?? "")
870
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
871
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
872
+ else if (touches()) return
873
+ kept.push({ label, extent: here })
874
+ })
875
+ return kept.map((k) => k.label)
876
+ }
877
+
878
+ /** Marker position in percent of the bar, clamped to its ends. */
879
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
880
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
881
+ if (total === 0) return 0
882
+ return clamp((value / total) * 100, 0, 100)
883
+ }
884
+
885
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
886
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
887
+ const segments = categoryBarSegments(values)
888
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
889
+ if (index !== -1) return index
890
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
891
+ return 0
892
+ }
893
+
894
+ /* --------------------------------------------------------- ProgressCircle */
895
+
896
+ interface ProgressCircleGeometry {
897
+ /** SVG width/height. */
898
+ size: number
899
+ /** Radius of the stroke's centre line. */
900
+ normalizedRadius: number
901
+ circumference: number
902
+ /** `stroke-dashoffset` for the value arc. */
903
+ offset: number
904
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
905
+ ratio: number
906
+ }
907
+
908
+ function progressCircleGeometry(
909
+ value: number,
910
+ max: number,
911
+ radius: number,
912
+ strokeWidth: number,
913
+ ): ProgressCircleGeometry {
914
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
915
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
916
+ const circumference = 2 * Math.PI * normalizedRadius
917
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
918
+ }
919
+
920
+ /* ---------------------------------------------------------------- summary */
921
+
922
+ interface ChartSummaryInput {
923
+ data: readonly Record<string, unknown>[]
924
+ /** The x-axis key. */
925
+ index: string
926
+ /** Series keys; the first one is described. */
927
+ categories: readonly string[]
928
+ /** Title of the chart, put in front when given. */
929
+ title?: string
930
+ /** Same as the chart's `format` (default `"compact"`). */
931
+ format?: ValueFormat
932
+ /** Wins over `format`. */
933
+ valueFormatter?: ValueFormatter
934
+ /** Language of the sentence. Default the page's locale (`<html lang>`). */
935
+ locale?: string
936
+ }
937
+
938
+ const SUMMARY_TEXT = {
939
+ ja: {
940
+ up: "、前の点より増加",
941
+ down: "、前の点より減少",
942
+ flat: "、前の点と横ばい",
943
+ latest: (label: string, value: string) => `最新 ${label} は ${value}`,
944
+ top: (name: string, share: string) => `最大は ${name}(${share})`,
945
+ },
946
+ en: {
947
+ up: ", up from the previous point",
948
+ down: ", down from the previous point",
949
+ flat: ", flat from the previous point",
950
+ latest: (label: string, value: string) => `Latest ${label}: ${value}`,
951
+ top: (name: string, share: string) => `Largest: ${name} (${share})`,
952
+ },
953
+ }
954
+
955
+ /**
956
+ * One-sentence summary built from the rows, for `summary="auto"`:
957
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
958
+ * computed from the last two non-empty points of the first series — never
959
+ * written by hand, so it cannot contradict the data. `undefined` when there is
960
+ * no usable point.
961
+ */
962
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
963
+ const key = input.categories[0]
964
+ if (key === undefined) return undefined
965
+ const points: { label: string; value: number }[] = []
966
+ for (const row of input.data) {
967
+ const raw = row[key]
968
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
969
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
970
+ }
971
+ const latest = points[points.length - 1]
972
+ if (!latest) return undefined
973
+ const locale = resolveLocale(input.locale)
974
+ const t = SUMMARY_TEXT[uiLanguage(locale)]
975
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
976
+ const prev = points[points.length - 2]
977
+ const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
978
+ const head = input.title ? `${input.title}: ` : ""
979
+ return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
980
+ }
981
+
982
+ /**
983
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
984
+ * (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
985
+ */
986
+ function buildShareSummary(
987
+ slices: readonly { name: string; value: number }[],
988
+ title?: string,
989
+ locale?: string,
990
+ ): string | undefined {
991
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
992
+ const top = slices[0]
993
+ if (!top || total <= 0) return undefined
994
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
995
+ return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
996
+ }
997
+
998
+ /* ---------- end of inlined code ---------- */
999
+
1000
+ /** The lightest shade is this share of the tone mixed into the card; the darkest is the tone itself. */
1001
+ const FLOOR_SHARE = 0.2
1002
+ /** The box height (px) while loading or empty (ChartFrame's default plot height). */
1003
+ const DEFAULT_CHART_HEIGHT = 288
1004
+ /** From this share of the range up, a cell is dark and its text takes the card colour. */
1005
+ const LIGHT_TEXT_FROM = 0.55
1006
+
1007
+ export interface PivotTableProps<T extends Record<string, unknown> = Record<string, unknown>> {
1008
+ /** 集計済みの行の配列。1 行 = 1 マス(行の次元 × 列の次元の組)。同じ組が複数あれば後の行が勝つ(合計はしない)。 */
1009
+ data: T[]
1010
+ /** 行の次元の列名(左から入れ子)。例 `["region", "category"]`。空なら 1 行。 */
1011
+ rows: (keyof T & string)[]
1012
+ /** 列の次元の列名(上から入れ子)。例 `["year"]`。空なら列の見出しは値の名前だけ。 */
1013
+ columns: (keyof T & string)[]
1014
+ /** マスに出す数値の列名。2 つ以上なら列の次元ごとに小列に分かれる。 */
1015
+ values: (keyof T & string)[]
1016
+ /** 値ごとの書式。例 `{ sales: "currency", margin: "percent" }`。無い値は `"number"`。 */
1017
+ formats?: Partial<Record<string, ValueFormat>>
1018
+ /** 列名・次元の値 → 表示名(見出しに反映)。 */
1019
+ labels?: Record<string, string>
1020
+ /** 値でマスを塗る(ハイライト表)。`true` で全部の値(値ごとに最小〜最大)、値の列名でその値だけ。既定 `false`。 */
1021
+ highlight?: boolean | string
1022
+ /** 塗りの色。`"chart-1"`〜`"chart-5"` か意味色。薄い → 濃いの単色。既定 `"chart-1"`。 */
1023
+ tone?: ChartSeriesColor
1024
+ /** マスのクリック。そのマスの行を受け取る(フィルターの操作に使う)。値の無いマスでは呼ばない。 */
1025
+ onSelect?: (row: T) => void
1026
+ /** 表の見出し。 */
1027
+ title?: string
1028
+ /** 表が言っていることの 1 文要約。 */
1029
+ summary?: string
1030
+ /** 読み込み中。スケルトンを出す。 */
1031
+ isLoading?: boolean
1032
+ /** `data` が空のときの表示。 */
1033
+ emptyState?: ChartEmptyState
1034
+ /** 表の箱の最大の高さ(px)。超えると箱の中で縦にスクロールし、見出しは上に残る。既定 480。 */
1035
+ maxHeight?: number
1036
+ className?: string
1037
+ /** スクリーンリーダー向けのラベル。省略時は見出し。 */
1038
+ ariaLabel?: string
1039
+ }
1040
+
1041
+ /* ------------------------------------------------------------------ model */
1042
+
1043
+ export interface PivotModel {
1044
+ /** Distinct row-dimension tuples, in data order. One empty tuple when there are no row dimensions. */
1045
+ rowKeys: string[][]
1046
+ /** Distinct column-dimension tuples, in data order. One empty tuple when there are no column dimensions. */
1047
+ colKeys: string[][]
1048
+ /** Cell → its row (the last row naming that cell). */
1049
+ cells: Map<string, Record<string, unknown>>
1050
+ /** Each value's range over the placed cells. */
1051
+ ranges: Record<string, { min: number; max: number }>
1052
+ }
1053
+
1054
+ const dimText = (v: unknown) => (v === null || v === undefined || v === "" ? EMPTY_VALUE : String(v))
1055
+ export const pivotCellKey = (rowKey: readonly string[], colKey: readonly string[]) => `${rowKey.join("\u0001")}\u0000${colKey.join("\u0001")}`
1056
+
1057
+ export function buildPivotModel(config: {
1058
+ data: readonly Record<string, unknown>[]
1059
+ rows: readonly string[]
1060
+ columns: readonly string[]
1061
+ values: readonly string[]
1062
+ }): PivotModel {
1063
+ const { data, rows, columns, values } = config
1064
+ const rowKeys = new Map<string, string[]>()
1065
+ const colKeys = new Map<string, string[]>()
1066
+ const cells = new Map<string, Record<string, unknown>>()
1067
+ for (const row of data) {
1068
+ if (!row || typeof row !== "object") continue
1069
+ const rk = rows.map((d) => dimText(row[d]))
1070
+ const ck = columns.map((d) => dimText(row[d]))
1071
+ const rId = rk.join("\u0001")
1072
+ const cId = ck.join("\u0001")
1073
+ if (!rowKeys.has(rId)) rowKeys.set(rId, rk)
1074
+ if (!colKeys.has(cId)) colKeys.set(cId, ck)
1075
+ cells.set(pivotCellKey(rk, ck), row)
1076
+ }
1077
+ const ranges: Record<string, { min: number; max: number }> = {}
1078
+ for (const value of values) {
1079
+ let [lo, hi] = [Infinity, -Infinity]
1080
+ for (const row of cells.values()) {
1081
+ const n = toChartNumber(row[value])
1082
+ if (n !== null) [lo, hi] = [Math.min(lo, n), Math.max(hi, n)]
1083
+ }
1084
+ ranges[value] = { min: Number.isFinite(lo) ? lo : 0, max: Number.isFinite(hi) ? hi : 0 }
1085
+ }
1086
+ return {
1087
+ rowKeys: rowKeys.size > 0 ? [...rowKeys.values()] : [rows.map(() => EMPTY_VALUE)],
1088
+ colKeys: colKeys.size > 0 ? [...colKeys.values()] : [columns.map(() => EMPTY_VALUE)],
1089
+ cells,
1090
+ ranges,
1091
+ }
1092
+ }
1093
+
1094
+ /** A header cell spanning consecutive keys that share the same prefix up to `level`. */
1095
+ export interface PivotSpan {
1096
+ text: string
1097
+ /** Index of the first key it covers. */
1098
+ start: number
1099
+ span: number
1100
+ }
1101
+
1102
+ /** The merged header cells of one level: runs of consecutive keys with the same prefix (levels 0…`level`). */
1103
+ export function pivotSpans(keys: readonly (readonly string[])[], level: number): PivotSpan[] {
1104
+ const out: PivotSpan[] = []
1105
+ const prefix = (k: readonly string[]) => k.slice(0, level + 1).join("\u0001")
1106
+ keys.forEach((key, i) => {
1107
+ const last = out[out.length - 1]
1108
+ if (last && prefix(keys[last.start]!) === prefix(key)) last.span++
1109
+ else out.push({ text: key[level] ?? "", start: i, span: 1 })
1110
+ })
1111
+ return out
1112
+ }
1113
+
1114
+ const TEXT = {
1115
+ ja: { table: "ピボット表" },
1116
+ en: { table: "Pivot table" },
1117
+ }
1118
+
1119
+ /* -------------------------------------------------------------- component */
1120
+
1121
+ /** Rows not given yet (a draft fills props in steps): keep the same array between renders. */
1122
+ const NO_ROWS: never[] = []
1123
+
1124
+ const asList = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [])
1125
+
1126
+ export function PivotTable<T extends Record<string, unknown>>({
1127
+ data = NO_ROWS,
1128
+ rows: rowDims,
1129
+ columns: colDims,
1130
+ values: valueKeys,
1131
+ formats,
1132
+ labels,
1133
+ highlight = false,
1134
+ tone = "chart-1",
1135
+ onSelect,
1136
+ title,
1137
+ summary,
1138
+ isLoading,
1139
+ emptyState,
1140
+ maxHeight = 480,
1141
+ className,
1142
+ ariaLabel,
1143
+ }: PivotTableProps<T>) {
1144
+ const locale = useLocale()
1145
+ const t = TEXT[uiLanguage(resolveLocale(locale))]
1146
+ const dataRows = Array.isArray(data) ? data : NO_ROWS
1147
+ const rows = useMemo(() => asList(rowDims), [rowDims])
1148
+ const columns = useMemo(() => asList(colDims), [colDims])
1149
+ const values = useMemo(() => asList(valueKeys), [valueKeys])
1150
+ const model = useMemo(() => buildPivotModel({ data: dataRows, rows, columns, values }), [dataRows, rows, columns, values])
1151
+ const label = (key: string) => labels?.[key] ?? key
1152
+ const R = rows.length
1153
+ const C = columns.length
1154
+ const V = values.length
1155
+ const valueRow = V > 1 || C === 0
1156
+ const H = C + (valueRow ? 1 : 0)
1157
+ const shaded = (value: string) => highlight === true || highlight === value
1158
+ const isEmpty = dataRows.length === 0
1159
+ const ready = !isLoading && !isEmpty
1160
+
1161
+ const cellStyle = (value: string, n: number | null): CSSProperties | undefined => {
1162
+ if (n === null || !shaded(value)) return undefined
1163
+ const { min, max } = model.ranges[value] ?? { min: 0, max: 0 }
1164
+ const ratio = max > min ? Math.min(1, Math.max(0, (n - min) / (max - min))) : 1
1165
+ const share = Math.round((FLOOR_SHARE + (1 - FLOOR_SHARE) * ratio) * 100)
1166
+ return {
1167
+ backgroundColor: `color-mix(in oklch, var(--${tone}) ${share}%, var(--card))`,
1168
+ color: ratio >= LIGHT_TEXT_FROM ? "var(--card)" : undefined,
1169
+ }
1170
+ }
1171
+
1172
+ const headerRows = Array.from({ length: H }, (_, h) => {
1173
+ const lead =
1174
+ h === H - 1
1175
+ ? rows.map((d, level) => (
1176
+ <TableHead key={`dim-${d}`} scope="col" className={cn(level === 0 && "pl-0")}>
1177
+ {label(d)}
1178
+ </TableHead>
1179
+ ))
1180
+ : h === 0 && R > 0
1181
+ ? [<TableHead key="corner" colSpan={R} rowSpan={H - 1} aria-hidden="true" />]
1182
+ : []
1183
+ const cells =
1184
+ h < C
1185
+ ? pivotSpans(model.colKeys, h).map((s) => (
1186
+ <TableHead key={`c-${h}-${s.start}`} scope="colgroup" colSpan={s.span * Math.max(1, V)} className="text-right">
1187
+ {label(s.text)}
1188
+ </TableHead>
1189
+ ))
1190
+ : model.colKeys.flatMap((_, ci) =>
1191
+ values.map((v) => (
1192
+ <TableHead key={`v-${ci}-${v}`} scope="col" className="text-right">
1193
+ {label(v)}
1194
+ </TableHead>
1195
+ )),
1196
+ )
1197
+ return (
1198
+ <TableRow key={`h-${h}`} className="hover:bg-transparent">
1199
+ {lead}
1200
+ {cells}
1201
+ </TableRow>
1202
+ )
1203
+ })
1204
+
1205
+ const rowSpans = rows.map((_, level) => new Map(pivotSpans(model.rowKeys, level).map((s) => [s.start, s.span])))
1206
+
1207
+ const body = model.rowKeys.map((rk, ri) => (
1208
+ <TableRow key={`r-${ri}`}>
1209
+ {rows.map((d, level) => {
1210
+ const span = rowSpans[level]!.get(ri)
1211
+ if (span === undefined) return null
1212
+ return (
1213
+ <TableHead key={`rh-${d}`} scope={span > 1 ? "rowgroup" : "row"} rowSpan={span} className={cn("align-top font-medium text-foreground", level === 0 && "pl-0")}>
1214
+ {label(rk[level] ?? "")}
1215
+ </TableHead>
1216
+ )
1217
+ })}
1218
+ {model.colKeys.flatMap((ck, ci) =>
1219
+ values.map((v) => {
1220
+ const row = model.cells.get(pivotCellKey(rk, ck))
1221
+ const n = row ? toChartNumber(row[v]) : null
1222
+ const text = formatValue(n, formats?.[v] ?? "number", locale)
1223
+ return (
1224
+ <TableCell key={`c-${ci}-${v}`} className="text-right tabular-nums" style={cellStyle(v, n)}>
1225
+ {onSelect && row ? (
1226
+ <button type="button" className="w-full cursor-pointer text-right tabular-nums" onClick={() => onSelect(row as T)}>
1227
+ {text}
1228
+ </button>
1229
+ ) : (
1230
+ text
1231
+ )}
1232
+ </TableCell>
1233
+ )
1234
+ }),
1235
+ )}
1236
+ </TableRow>
1237
+ ))
1238
+
1239
+ return (
1240
+ <ChartFrame
1241
+ title={title}
1242
+ summary={summary}
1243
+ isLoading={isLoading ?? false}
1244
+ isEmpty={isEmpty}
1245
+ emptyState={emptyState}
1246
+ height={ready ? "auto" : DEFAULT_CHART_HEIGHT}
1247
+ variant="list"
1248
+ plotRole="group"
1249
+ ariaLabel={ariaLabel ?? title ?? t.table}
1250
+ className={className}
1251
+ >
1252
+ <div data-slot="pivot-table" className="relative w-full overflow-auto" style={{ maxHeight }}>
1253
+ <table data-slot="table" aria-label={ariaLabel ?? title ?? t.table} className="w-full caption-bottom text-sm">
1254
+ <TableHeader className="sticky top-0 z-10 bg-card">{headerRows}</TableHeader>
1255
+ <TableBody>{body}</TableBody>
1256
+ </table>
1257
+ </div>
1258
+ </ChartFrame>
1259
+ )
1260
+ }