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