@squadbase/vantage 0.6.2-dev1.ac99e02 → 0.6.2-dev1.d7c0911
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/dist/{build-MFWRPYKW.js → build-X5NVCQKT.js} +4 -4
- package/dist/{build-MFWRPYKW.js.map → build-X5NVCQKT.js.map} +1 -1
- package/dist/{chunk-IBGOCWJB.js → chunk-2ICNHUG6.js} +186 -82
- package/dist/chunk-2ICNHUG6.js.map +1 -0
- package/dist/{chunk-5ZOP4SQR.js → chunk-2N72FKLB.js} +12 -7
- package/dist/chunk-2N72FKLB.js.map +1 -0
- package/dist/{chunk-PXRX5PEC.js → chunk-PDOBHMUQ.js} +3 -3
- package/dist/chunk-PDOBHMUQ.js.map +1 -0
- package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
- package/dist/chunk-U736PVHY.js.map +1 -0
- package/dist/{chunk-QEWCYW3I.js → chunk-WAMZWZJB.js} +13 -3
- package/dist/chunk-WAMZWZJB.js.map +1 -0
- package/dist/chunk-WRSX2MDK.js +7866 -0
- package/dist/chunk-WRSX2MDK.js.map +1 -0
- package/dist/{chunk-OB6UBJXF.js → chunk-XPQSTZUU.js} +125 -35
- package/dist/chunk-XPQSTZUU.js.map +1 -0
- package/dist/cli.js +3 -3
- package/dist/components/index.d.ts +1831 -99
- package/dist/components/index.js +4 -4
- package/dist/{dev-DCTOHQ6W.js → dev-4XEDTELV.js} +4 -4
- package/dist/{dev-DCTOHQ6W.js.map → dev-4XEDTELV.js.map} +1 -1
- package/dist/doc/index.js +2 -2
- package/dist/doc/index.js.map +1 -1
- package/dist/markdown/index.js +1 -1
- package/dist/markdown/index.js.map +1 -1
- package/dist/table/index.js +5 -5
- package/dist/table/index.js.map +1 -1
- package/dist/ui/index.d.ts +4 -1
- package/dist/ui/index.js +21 -111
- package/dist/ui/index.js.map +1 -1
- package/dist/{upgrade-DBBE6GIR.js → upgrade-JHXZBGQS.js} +3 -3
- package/dist/{upgrade-DBBE6GIR.js.map → upgrade-JHXZBGQS.js.map} +1 -1
- package/dist/vite/index.js +2 -2
- package/docs/en/components.md +29 -15
- package/docs/en/parts/data-table.md +22 -0
- package/docs/en/parts/delta.md +50 -0
- package/docs/en/parts/format.md +43 -0
- package/docs/en/parts/kpi-card.md +57 -0
- package/docs/en/parts/metric-value.md +3 -2
- package/docs/en/parts/sparkline.md +1 -1
- package/docs/en/parts/trend-indicator.md +17 -1
- package/docs/en/ui-and-theming.md +1 -1
- package/docs/index.json +92 -32
- package/docs/ja/changelog.md +5 -0
- package/docs/ja/components.md +27 -15
- package/docs/ja/parts/data-table.md +22 -0
- package/docs/ja/parts/delta.md +50 -0
- package/docs/ja/parts/format.md +44 -0
- package/docs/ja/parts/kpi-card.md +55 -0
- package/docs/ja/parts/metric-value.md +3 -2
- package/docs/ja/parts/sparkline.md +1 -1
- package/docs/ja/parts/trend-indicator.md +17 -1
- package/docs/ja/ui-and-theming.md +2 -2
- package/package.json +2 -1
- package/registry/ui/accordion.tsx +4 -2
- package/registry/ui/alert-dialog.tsx +3 -3
- package/registry/ui/alert.tsx +3 -1
- package/registry/ui/app-shell.tsx +7 -1
- package/registry/ui/area-chart.tsx +2781 -157
- package/registry/ui/avatar.tsx +1 -1
- package/registry/ui/badge.tsx +3 -1
- package/registry/ui/bar-chart.tsx +2780 -157
- package/registry/ui/bar-list.tsx +3471 -93
- package/registry/ui/breadcrumb.tsx +3 -1
- package/registry/ui/button.tsx +3 -1
- package/registry/ui/calendar.tsx +3 -1
- package/registry/ui/card.tsx +4 -2
- package/registry/ui/category-bar.tsx +990 -16
- package/registry/ui/chart-frame.tsx +1358 -0
- package/registry/ui/checkbox.tsx +3 -1
- package/registry/ui/collapsible.tsx +3 -1
- package/registry/ui/combobox.tsx +2 -2
- package/registry/ui/command.tsx +3 -1
- package/registry/ui/dashboard-card.tsx +69 -26
- package/registry/ui/data-table.tsx +678 -56
- package/registry/ui/date-range-picker.tsx +245 -64
- package/registry/ui/delta.tsx +188 -0
- package/registry/ui/dialog.tsx +5 -3
- package/registry/ui/donut-chart.tsx +2857 -173
- package/registry/ui/drawer.tsx +1 -1
- package/registry/ui/dropdown-menu.tsx +5 -3
- package/registry/ui/echart.tsx +448 -44
- package/registry/ui/field.tsx +1 -1
- package/registry/ui/filter-bar.tsx +33 -6
- package/registry/ui/funnel-steps.tsx +3316 -49
- package/registry/ui/heatmap.tsx +1752 -0
- package/registry/ui/hover-card.tsx +2 -2
- package/registry/ui/input-group.tsx +3 -1
- package/registry/ui/input.tsx +3 -1
- package/registry/ui/kbd.tsx +3 -1
- package/registry/ui/kpi-card.tsx +677 -0
- package/registry/ui/label.tsx +3 -1
- package/registry/ui/legend.tsx +3500 -0
- package/registry/ui/line-chart.tsx +2781 -151
- package/registry/ui/metric-value.tsx +9 -1
- package/registry/ui/multi-select.tsx +11 -5
- package/registry/ui/page-shell.tsx +104 -49
- package/registry/ui/pagination.tsx +3 -1
- package/registry/ui/placeholder.tsx +8 -2
- package/registry/ui/popover.tsx +4 -2
- package/registry/ui/progress-circle.tsx +607 -12
- package/registry/ui/progress.tsx +3 -1
- package/registry/ui/radio-group.tsx +1 -1
- package/registry/ui/sample-data.tsx +86 -0
- package/registry/ui/scatter-chart.tsx +4150 -0
- package/registry/ui/scroll-area.tsx +3 -2
- package/registry/ui/searchable-select.tsx +8 -3
- package/registry/ui/section-header.tsx +4 -2
- package/registry/ui/segmented-control.tsx +7 -2
- package/registry/ui/select.tsx +4 -2
- package/registry/ui/separator.tsx +3 -1
- package/registry/ui/sheet.tsx +4 -2
- package/registry/ui/sidebar.tsx +4 -2
- package/registry/ui/skeleton.tsx +4 -2
- package/registry/ui/slider.tsx +3 -1
- package/registry/ui/sparkline.tsx +84 -9
- package/registry/ui/spinner.tsx +3 -1
- package/registry/ui/states.tsx +34 -5
- package/registry/ui/status-badge.tsx +81 -39
- package/registry/ui/switch.tsx +3 -1
- package/registry/ui/table.tsx +4 -2
- package/registry/ui/tabs.tsx +5 -3
- package/registry/ui/textarea.tsx +3 -1
- package/registry/ui/toast.tsx +2 -2
- package/registry/ui/toggle-group.tsx +3 -1
- package/registry/ui/toggle.tsx +3 -1
- package/registry/ui/tooltip.tsx +4 -2
- package/registry/ui/tracker.tsx +624 -17
- package/registry/ui/trend-indicator.tsx +13 -1
- package/registry/ui/updated-at.tsx +122 -0
- package/registry/ui/waterfall-chart.tsx +4186 -0
- package/templates/AGENTS.md +13 -1
- package/theme.css +237 -136
- package/dist/chunk-5ZOP4SQR.js.map +0 -1
- package/dist/chunk-A2UUGASH.js.map +0 -1
- package/dist/chunk-AG6RZ2RR.js +0 -3208
- package/dist/chunk-AG6RZ2RR.js.map +0 -1
- package/dist/chunk-IBGOCWJB.js.map +0 -1
- package/dist/chunk-OB6UBJXF.js.map +0 -1
- package/dist/chunk-PXRX5PEC.js.map +0 -1
- package/dist/chunk-QEWCYW3I.js.map +0 -1
|
@@ -0,0 +1,4150 @@
|
|
|
1
|
+
// Copied by `vantage add ui scatter-chart`. This file is yours to edit.
|
|
2
|
+
// Generated from @squadbase/squadkit registry/charts/scatter-chart.tsx by `npm run registry` (in Vantage, edit packages/squadkit, not registry/).
|
|
3
|
+
"use client"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* ScatterChart — a typed scatter / bubble chart over `EChart`: pass rows and the
|
|
7
|
+
* two numeric column keys for the axes (`x` / `y`) instead of an ECharts option.
|
|
8
|
+
* 広告費 × 売上、客単価 × 購入頻度 のように 2 つの数値の関係と外れ値を見る。
|
|
9
|
+
*
|
|
10
|
+
* `size` turns the dots into bubbles (area proportional to the value, from 0),
|
|
11
|
+
* `series` splits the dots into series coloured with the `--chart-1..5` tokens in
|
|
12
|
+
* fixed order (more than 5 fold into one grey「その他」series), `index` names each
|
|
13
|
+
* dot in the tooltip. Both axes fit the data by default — a scatter is read by
|
|
14
|
+
* position, not by length, so it does not start at 0 (`fitToData={false}` does).
|
|
15
|
+
* Rows whose x or y is missing are left out. `labelKey` prints each dot's name beside it (dots whose
|
|
16
|
+
* labels would collide are thinned, never overprinted; on a narrow plot (under 480px) only the 2 highest dots are
|
|
17
|
+
* named, each label turned inward so it stays inside the plot, the legend moves under the plot and the y axis carries
|
|
18
|
+
* 3 intervals), `referenceLines` draws neutral guide lines at
|
|
19
|
+
* fixed x / y values, `highlight` brings some series forward and fades the rest. Renders inside `ChartFrame` (title,
|
|
20
|
+
* summary, loading skeleton, empty state, and a visually-hidden table of the dots).
|
|
21
|
+
*/
|
|
22
|
+
import { forwardRef, useMemo, type ForwardedRef, type ReactElement, type Ref } from "react"
|
|
23
|
+
import { use } from "echarts/core"
|
|
24
|
+
import { ScatterChart as EScatterChart } from "echarts/charts"
|
|
25
|
+
import { GraphicComponent } from "echarts/components"
|
|
26
|
+
import type { EChartsOption } from "echarts"
|
|
27
|
+
|
|
28
|
+
import { ChartFrame } from "@squadbase/vantage/components"
|
|
29
|
+
import { EChart } from "@squadbase/vantage/components"
|
|
30
|
+
import { EMPTY_VALUE, type ValueFormat } from "@squadbase/vantage/components"
|
|
31
|
+
import type { ChartCommonProps, ChartEmptyState, ChartSeriesColor, NumericKeys, ValueFormatter } from "@squadbase/vantage/components"
|
|
32
|
+
import { createContext, useCallback, useEffect, useRef, useState } from "react"
|
|
33
|
+
import type { ChartTone } from "@squadbase/vantage/components"
|
|
34
|
+
import { type ReactNode } from "react"
|
|
35
|
+
import { computeComparison, defaultChangeDisplay, formatChange, toneForValue, type ComparisonKind, type PeriodGrain } from "@squadbase/vantage/components"
|
|
36
|
+
import { DEFAULT_LOCALE } from "@squadbase/vantage/components"
|
|
37
|
+
import type { ChartThreshold, ChartAnnotation, ChartEventPayload, ChartForecast, ChartForecastRow, ChartHighlight } from "@squadbase/vantage/components"
|
|
38
|
+
import { formatValue, toValueFormatter } from "@squadbase/vantage/components"
|
|
39
|
+
import type { ChartColor, ChartColors } from "@squadbase/vantage/components"
|
|
40
|
+
|
|
41
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The colour of the folded「その他」series / slice / row. The ONLY place this
|
|
45
|
+
* grey is defined — every chart takes it from here. It is the most subdued
|
|
46
|
+
* colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
|
|
47
|
+
* `--background`, so it recedes in light and dark alike (and brand themes follow
|
|
48
|
+
* it). `--neutral-subtle` alone sits too close to the background to read as a
|
|
49
|
+
* slice. Canvas charts resolve it through `resolveChartColors`.
|
|
50
|
+
*/
|
|
51
|
+
const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* True inside `ChartFrame`. The frame's plot area carries the chart's single
|
|
55
|
+
* `role="img"` and label, so `EChart` drops its own when it sees this.
|
|
56
|
+
*/
|
|
57
|
+
const ChartFrameContext = createContext(false)
|
|
58
|
+
|
|
59
|
+
/** Series palette, in order. Missing tokens are skipped, not defaulted. */
|
|
60
|
+
const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
|
|
61
|
+
|
|
62
|
+
interface ChartTokens {
|
|
63
|
+
/** Resolved `--chart-1..5`, in order. */
|
|
64
|
+
series: string[]
|
|
65
|
+
/** Body text: titles and the default `textStyle`. */
|
|
66
|
+
foreground: string | null
|
|
67
|
+
/** Secondary text: axis labels, legend, subtitles. */
|
|
68
|
+
mutedForeground: string | null
|
|
69
|
+
/** Axis lines, ticks, split lines, tooltip border. */
|
|
70
|
+
border: string | null
|
|
71
|
+
/** Tooltip surface. */
|
|
72
|
+
popover: string | null
|
|
73
|
+
/** Tooltip text. */
|
|
74
|
+
popoverForeground: string | null
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let normalizeContext: CanvasRenderingContext2D | null | undefined
|
|
78
|
+
|
|
79
|
+
/** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
|
|
80
|
+
const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Serialize a CSS colour into a canvas-safe form, or `null` if the browser
|
|
84
|
+
* rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
|
|
85
|
+
* input is written over two different known colours: agreeing results mean the
|
|
86
|
+
* value parsed, differing ones mean it was dropped.
|
|
87
|
+
*/
|
|
88
|
+
function toCanvasColor(value: string): string | null {
|
|
89
|
+
const raw = value.trim()
|
|
90
|
+
if (!raw) return null
|
|
91
|
+
if (normalizeContext === undefined) {
|
|
92
|
+
const canvas = document.createElement("canvas")
|
|
93
|
+
canvas.width = 1
|
|
94
|
+
canvas.height = 1
|
|
95
|
+
normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
|
|
96
|
+
}
|
|
97
|
+
const ctx = normalizeContext
|
|
98
|
+
if (!ctx) return raw
|
|
99
|
+
ctx.fillStyle = "#000000"
|
|
100
|
+
ctx.fillStyle = raw
|
|
101
|
+
const onBlack = ctx.fillStyle
|
|
102
|
+
ctx.fillStyle = "#ffffff"
|
|
103
|
+
ctx.fillStyle = raw
|
|
104
|
+
if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
|
|
105
|
+
if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
|
|
106
|
+
// Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
|
|
107
|
+
// Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
|
|
108
|
+
ctx.clearRect(0, 0, 1, 1)
|
|
109
|
+
ctx.fillRect(0, 0, 1, 1)
|
|
110
|
+
const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
|
|
111
|
+
return a === 255
|
|
112
|
+
? `rgb(${r}, ${g}, ${b})`
|
|
113
|
+
: `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Read the chart tokens off `el` (the document root by default — tokens live on
|
|
118
|
+
* `:root` and inherit). Returns `null` outside the browser so callers fall back
|
|
119
|
+
* to plain ECharts defaults.
|
|
120
|
+
*/
|
|
121
|
+
function readChartTokens(el?: Element | null): ChartTokens | null {
|
|
122
|
+
if (typeof document === "undefined") return null
|
|
123
|
+
const target = el ?? document.documentElement
|
|
124
|
+
if (!target) return null
|
|
125
|
+
const styles = getComputedStyle(target)
|
|
126
|
+
const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
|
|
127
|
+
const series: string[] = []
|
|
128
|
+
for (const token of SERIES_TOKENS) {
|
|
129
|
+
const color = read(token)
|
|
130
|
+
if (color) series.push(color)
|
|
131
|
+
}
|
|
132
|
+
return {
|
|
133
|
+
series,
|
|
134
|
+
foreground: read("--foreground"),
|
|
135
|
+
mutedForeground: read("--muted-foreground"),
|
|
136
|
+
border: read("--border"),
|
|
137
|
+
popover: read("--popover"),
|
|
138
|
+
popoverForeground: read("--popover-foreground"),
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
|
|
143
|
+
function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
|
|
144
|
+
if (a === b) return true
|
|
145
|
+
if (!a || !b) return false
|
|
146
|
+
return (
|
|
147
|
+
a.series.length === b.series.length &&
|
|
148
|
+
a.series.every((color, i) => color === b.series[i]) &&
|
|
149
|
+
a.foreground === b.foreground &&
|
|
150
|
+
a.mutedForeground === b.mutedForeground &&
|
|
151
|
+
a.border === b.border &&
|
|
152
|
+
a.popover === b.popover &&
|
|
153
|
+
a.popoverForeground === b.popoverForeground
|
|
154
|
+
)
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Watch everything that can change the resolved tokens and call `onChange` when
|
|
159
|
+
* something might have. It only ever says "re-read" — the caller compares with
|
|
160
|
+
* `sameChartTokens` and decides whether anything actually moved. Returns a
|
|
161
|
+
* disposer.
|
|
162
|
+
*
|
|
163
|
+
* Two sources, not one:
|
|
164
|
+
* - light/dark flips, which land as `class` / `data-theme` (or an inline
|
|
165
|
+
* `style`) on `<html>`/`<body>`, or as an OS preference change
|
|
166
|
+
* - stylesheet changes. In dev, editing `styles.css` rewrites the injected
|
|
167
|
+
* `<style>` in `<head>` and touches nothing else, so watching the theme
|
|
168
|
+
* attributes alone leaves the chart painted in the previous palette until a
|
|
169
|
+
* reload — the tokens in the DOM are new, the canvas is not.
|
|
170
|
+
*/
|
|
171
|
+
function watchChartTokens(onChange: () => void): () => void {
|
|
172
|
+
if (typeof document === "undefined") return () => {}
|
|
173
|
+
// Style edits arrive as bursts of mutations; coalesce them into one read, and
|
|
174
|
+
// take it after the next frame so a swapped stylesheet has been applied.
|
|
175
|
+
let frame = 0
|
|
176
|
+
const schedule = () => {
|
|
177
|
+
if (frame) return
|
|
178
|
+
frame = requestAnimationFrame(() => {
|
|
179
|
+
frame = 0
|
|
180
|
+
onChange()
|
|
181
|
+
})
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const themeObserver = new MutationObserver(schedule)
|
|
185
|
+
const attributeFilter = ["class", "style", "data-theme"]
|
|
186
|
+
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter })
|
|
187
|
+
if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter })
|
|
188
|
+
|
|
189
|
+
const styleObserver = new MutationObserver(schedule)
|
|
190
|
+
if (document.head) {
|
|
191
|
+
styleObserver.observe(document.head, {
|
|
192
|
+
childList: true,
|
|
193
|
+
subtree: true,
|
|
194
|
+
characterData: true,
|
|
195
|
+
attributes: true,
|
|
196
|
+
attributeFilter: ["href", "media", "disabled"],
|
|
197
|
+
})
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// A swapped `<link>` only applies once the sheet has loaded, after its mutation.
|
|
201
|
+
const onLoad = (event: Event) => {
|
|
202
|
+
if (event.target instanceof HTMLLinkElement) schedule()
|
|
203
|
+
}
|
|
204
|
+
document.addEventListener("load", onLoad, true)
|
|
205
|
+
|
|
206
|
+
const media = window.matchMedia("(prefers-color-scheme: dark)")
|
|
207
|
+
media.addEventListener("change", schedule)
|
|
208
|
+
|
|
209
|
+
return () => {
|
|
210
|
+
if (frame) cancelAnimationFrame(frame)
|
|
211
|
+
themeObserver.disconnect()
|
|
212
|
+
styleObserver.disconnect()
|
|
213
|
+
document.removeEventListener("load", onLoad, true)
|
|
214
|
+
media.removeEventListener("change", schedule)
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** Shared shape for the four axis types ECharts themes address separately. */
|
|
219
|
+
function axisTheme(tokens: ChartTokens, splitLine: boolean) {
|
|
220
|
+
const line = tokens.border ?? undefined
|
|
221
|
+
return {
|
|
222
|
+
axisLine: { show: false },
|
|
223
|
+
axisTick: { show: false },
|
|
224
|
+
axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
|
|
225
|
+
// Faint horizontal rules only: the border colour at low opacity.
|
|
226
|
+
splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
|
|
227
|
+
splitArea: { show: false },
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Build the ECharts theme. `option.color` still wins over `theme.color`, so an
|
|
233
|
+
* app that sets its own palette keeps it.
|
|
234
|
+
*/
|
|
235
|
+
function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
|
|
236
|
+
const text = tokens.foreground ?? undefined
|
|
237
|
+
const muted = tokens.mutedForeground ?? undefined
|
|
238
|
+
const line = tokens.border ?? undefined
|
|
239
|
+
return {
|
|
240
|
+
// Let the page background show through: charts sit on cards, not on a canvas.
|
|
241
|
+
backgroundColor: "transparent",
|
|
242
|
+
...(tokens.series.length > 0 ? { color: tokens.series } : {}),
|
|
243
|
+
textStyle: { color: text },
|
|
244
|
+
title: { textStyle: { color: text }, subtextStyle: { color: muted } },
|
|
245
|
+
legend: { textStyle: { color: muted } },
|
|
246
|
+
categoryAxis: axisTheme(tokens, false),
|
|
247
|
+
valueAxis: axisTheme(tokens, true),
|
|
248
|
+
logAxis: axisTheme(tokens, true),
|
|
249
|
+
timeAxis: axisTheme(tokens, true),
|
|
250
|
+
tooltip: {
|
|
251
|
+
// ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
|
|
252
|
+
transitionDuration: 0,
|
|
253
|
+
backgroundColor: tokens.popover ?? undefined,
|
|
254
|
+
borderColor: line,
|
|
255
|
+
borderWidth: 1,
|
|
256
|
+
padding: [8, 12],
|
|
257
|
+
// Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
|
|
258
|
+
extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
|
|
259
|
+
textStyle: { color: tokens.popoverForeground ?? undefined, fontSize: 12 },
|
|
260
|
+
axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* The resolved tokens, kept current: re-read whenever `watchChartTokens` says
|
|
267
|
+
* they may have moved, and only replaced when a value actually changed. For
|
|
268
|
+
* components that build an ECharts option from token colours themselves (the
|
|
269
|
+
* typed charts), so their palette follows light/dark like `EChart`'s theme.
|
|
270
|
+
*/
|
|
271
|
+
function useChartTokens(): ChartTokens | null {
|
|
272
|
+
const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
|
|
273
|
+
// Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
|
|
274
|
+
// replayed by React on every rebase and returns a fresh object each time, so the state
|
|
275
|
+
// never settles ("Maximum update depth exceeded" once the tokens change after mount).
|
|
276
|
+
const tokensRef = useRef(tokens)
|
|
277
|
+
useEffect(() => {
|
|
278
|
+
const sync = () => {
|
|
279
|
+
const next = readChartTokens()
|
|
280
|
+
if (sameChartTokens(tokensRef.current, next)) return
|
|
281
|
+
tokensRef.current = next
|
|
282
|
+
setTokens(next)
|
|
283
|
+
}
|
|
284
|
+
sync()
|
|
285
|
+
return watchChartTokens(sync)
|
|
286
|
+
}, [])
|
|
287
|
+
return tokens
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
|
|
291
|
+
const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
|
|
292
|
+
const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
|
|
293
|
+
const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
|
|
297
|
+
* the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
|
|
298
|
+
* variants `"positive-fill"`, …) are read off the document root (`--positive`, …); `var(--token)` is read off the document root; any
|
|
299
|
+
* other CSS colour is normalized like the tokens are. A colour that can't be
|
|
300
|
+
* resolved comes back as `""`, which ECharts treats as "use the palette".
|
|
301
|
+
*/
|
|
302
|
+
function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
|
|
303
|
+
return colors.map((color) => {
|
|
304
|
+
const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
|
|
305
|
+
if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
|
|
306
|
+
// Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
|
|
307
|
+
if (TONE_NAME_RE.test(color.trim())) {
|
|
308
|
+
if (typeof document === "undefined") return ""
|
|
309
|
+
return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue(`--${color.trim()}`)) ?? ""
|
|
310
|
+
}
|
|
311
|
+
if (typeof document === "undefined") return color
|
|
312
|
+
let value = color.trim()
|
|
313
|
+
const cssVar = CSS_VAR_RE.exec(value)
|
|
314
|
+
const styles = getComputedStyle(document.documentElement)
|
|
315
|
+
if (cssVar) {
|
|
316
|
+
value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
|
|
317
|
+
} else if (value.includes("var(")) {
|
|
318
|
+
// A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
|
|
319
|
+
// substitute the tokens, then let the canvas resolve the rest.
|
|
320
|
+
value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
|
|
321
|
+
}
|
|
322
|
+
return toCanvasColor(value) ?? ""
|
|
323
|
+
})
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
|
|
327
|
+
function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
|
|
328
|
+
const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
|
|
329
|
+
["positive", "warning", "negative", "neutral"],
|
|
330
|
+
tokens,
|
|
331
|
+
)
|
|
332
|
+
return { positive, warning, negative, neutral }
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
|
|
336
|
+
function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
|
|
337
|
+
const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
|
|
338
|
+
["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
|
|
339
|
+
tokens,
|
|
340
|
+
)
|
|
341
|
+
return { positive, warning, negative, neutral }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* The colour the chart is painted on: the first opaque `background-color` up
|
|
348
|
+
* from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
|
|
349
|
+
* outside the browser.
|
|
350
|
+
*/
|
|
351
|
+
function readChartSurface(el: Element | null): string | null {
|
|
352
|
+
if (typeof document === "undefined") return null
|
|
353
|
+
for (let node: Element | null = el; node; node = node.parentElement) {
|
|
354
|
+
const bg = getComputedStyle(node).backgroundColor.trim()
|
|
355
|
+
if (bg && !TRANSPARENT_RE.test(bg)) {
|
|
356
|
+
const color = toCanvasColor(bg)
|
|
357
|
+
if (color) return color
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue("--background"))
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
|
|
364
|
+
const WIDTH_BUCKET = 40
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* The surface colour behind a chart (see `readChartSurface`), re-read when the
|
|
368
|
+
* tokens move (light/dark), and the plot's width (rounded down to 40px;
|
|
369
|
+
* `undefined` until measured). Returns a ref for the plot that also feeds the
|
|
370
|
+
* component's forwarded ref.
|
|
371
|
+
*/
|
|
372
|
+
function useChartSurface<E extends Element>(
|
|
373
|
+
forwarded: ForwardedRef<E>,
|
|
374
|
+
tokens: ChartTokens | null,
|
|
375
|
+
): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined } {
|
|
376
|
+
const [node, setNode] = useState<E | null>(null)
|
|
377
|
+
const [surface, setSurface] = useState<string | undefined>(undefined)
|
|
378
|
+
const [width, setWidth] = useState<number | undefined>(undefined)
|
|
379
|
+
const ref = useCallback(
|
|
380
|
+
(el: E | null) => {
|
|
381
|
+
setNode(el)
|
|
382
|
+
if (typeof forwarded === "function") forwarded(el)
|
|
383
|
+
else if (forwarded) forwarded.current = el
|
|
384
|
+
},
|
|
385
|
+
[forwarded],
|
|
386
|
+
)
|
|
387
|
+
useEffect(() => {
|
|
388
|
+
if (!node) return
|
|
389
|
+
setSurface(readChartSurface(node) ?? undefined)
|
|
390
|
+
}, [node, tokens])
|
|
391
|
+
useEffect(() => {
|
|
392
|
+
if (!node || typeof ResizeObserver === "undefined") return
|
|
393
|
+
const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
|
|
394
|
+
update(node.getBoundingClientRect().width)
|
|
395
|
+
const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
|
|
396
|
+
observer.observe(node)
|
|
397
|
+
return () => observer.disconnect()
|
|
398
|
+
}, [node])
|
|
399
|
+
return { ref, surface, width }
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-options.ts (internal to @squadbase/vantage) ---------- */
|
|
403
|
+
|
|
404
|
+
type CartesianChartKind = "area" | "bar" | "line"
|
|
405
|
+
type CartesianStackType = "default" | "stacked" | "percent"
|
|
406
|
+
type CartesianCurveType = "linear" | "smooth" | "step"
|
|
407
|
+
type AreaFill = "gradient" | "solid" | "none"
|
|
408
|
+
type BarLayout = "horizontal" | "vertical"
|
|
409
|
+
|
|
410
|
+
/** AreaChart-only settings. */
|
|
411
|
+
interface AreaChartOptions {
|
|
412
|
+
/** `"stacked"` は積み上げ、`"percent"` は各点の合計を 100% にした積み上げ。既定 `"default"`。 */
|
|
413
|
+
type?: CartesianStackType
|
|
414
|
+
/** 線の形。既定 `"linear"`。 */
|
|
415
|
+
curveType?: CartesianCurveType
|
|
416
|
+
/** 面の塗り。既定 `"gradient"`。 */
|
|
417
|
+
fill?: AreaFill
|
|
418
|
+
/** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
|
|
419
|
+
connectNulls?: boolean
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** LineChart-only settings. */
|
|
423
|
+
interface LineChartOptions {
|
|
424
|
+
/** 線の形。既定 `"linear"`。 */
|
|
425
|
+
curveType?: CartesianCurveType
|
|
426
|
+
/** 値の欠けた点(`null` など)をまたいで線をつなぐ。既定 `false`。 */
|
|
427
|
+
connectNulls?: boolean
|
|
428
|
+
/** 値軸を 0 からではなくデータの範囲に合わせる。既定 `false`(0 起点)。最小の目盛ラベルは先頭の x ラベルと重なるので出さない(グリッド線は残る)。 */
|
|
429
|
+
fitToData?: boolean
|
|
430
|
+
/**
|
|
431
|
+
* 目標線(`target`)のラベルの置き場所。`"start"`(既定)は線の左端の上(最大・最新の強調と近いときは下)。
|
|
432
|
+
* `"end"` は線の右端の上。`"legend"` は凡例だけに出し、線の上には出さない(線の周りが混み合うとき)。
|
|
433
|
+
* 目標の呼び名は、どれを選んでも凡例に出る。
|
|
434
|
+
*/
|
|
435
|
+
targetLabelPosition?: LineTargetLabelPosition
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** Where a line chart prints its target label: at the line's left end, its right end, or in the legend only. */
|
|
439
|
+
type LineTargetLabelPosition = "start" | "end" | "legend"
|
|
440
|
+
|
|
441
|
+
/** BarChart-only settings. */
|
|
442
|
+
interface BarChartOptions<T extends Record<string, unknown> = Record<string, unknown>> {
|
|
443
|
+
/** `"stacked"` は積み上げ、`"percent"` は各カテゴリの合計を 100% にした積み上げ。既定 `"default"`(横並び)。 */
|
|
444
|
+
type?: CartesianStackType
|
|
445
|
+
/**
|
|
446
|
+
* 棒の向き。既定 `"horizontal"`(カテゴリが横に並ぶ縦棒)。`"vertical"` はカテゴリを
|
|
447
|
+
* 縦に並べた横棒で、ラベルの長いランキングに向く(先頭の行が一番上)。
|
|
448
|
+
*/
|
|
449
|
+
layout?: BarLayout
|
|
450
|
+
/** カテゴリ間の隙間(`"20%"` や px)。省略時は ECharts の既定。 */
|
|
451
|
+
barCategoryGap?: string | number
|
|
452
|
+
/**
|
|
453
|
+
* 値が 0 の棒に「0」の値ラベルを付ける。棒が描かれない 0 が「データなし」に見えるのを防ぐ
|
|
454
|
+
* (在庫 0・件数 0 など)。積み上げでは付けない。0 以外の棒の見た目は変わらない。既定 `true`。
|
|
455
|
+
*/
|
|
456
|
+
showZeroValues?: boolean
|
|
457
|
+
/**
|
|
458
|
+
* 棒ごとの目標値が入った `data` の列名(行ごとの目標。店舗別の月次目標など)。各棒に短い目標マーカーを
|
|
459
|
+
* 引き、ツールチップに「目標 … (達成率 …%)」を足す。凡例に目標の呼び名(`targetLabel`、既定「目標」)が出る。
|
|
460
|
+
* 1 系列の棒と積み上げ(達成率は合計に対して)で使える。横並びの複数系列と 100% 積み上げでは描かない。
|
|
461
|
+
* 値が欠けた(null・0 以下の)行はマーカーを引かない。
|
|
462
|
+
*
|
|
463
|
+
* 優先順位: `targetKey` を渡すと 1 本の目標線 `target` は描かない(`targetLabel` はマーカーの呼び名として使う)。
|
|
464
|
+
* 値による色分け `thresholds` とは併用できる(色は棒、マーカーは目標)。値軸は最大の目標を含む。
|
|
465
|
+
* 例: `barOptions={{ targetKey: "月次目標" }}`
|
|
466
|
+
*/
|
|
467
|
+
targetKey?: NumericKeys<T>
|
|
468
|
+
/**
|
|
469
|
+
* 横棒(`layout: "vertical"`)の 1 系列で伝えたい 1 本。`index` の値で渡す(例 `"東京店"`)。
|
|
470
|
+
* 横棒は淡い色(`--chart-1` の薄い塗り)が既定で、この 1 本だけ濃い色(系列色そのまま)になる。省略すると全部が淡い色。
|
|
471
|
+
* 縦棒・複数系列・積み上げでは効かない(色は変わらない)。意味色の `thresholds` に当たった棒はそちらの色が優先。
|
|
472
|
+
* 例: `barOptions={{ layout: "vertical", highlight: "東京店" }}`
|
|
473
|
+
*/
|
|
474
|
+
highlight?: string | number
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Props every cartesian typed chart (Area / Bar / Line) shares. */
|
|
478
|
+
interface CartesianChartBaseProps<T extends Record<string, unknown> = Record<string, unknown>>
|
|
479
|
+
extends ChartCommonProps<T> {
|
|
480
|
+
/**
|
|
481
|
+
* 最大値と最新値に値ラベルを付ける(最初の系列だけ・系列が 2 つ以下のときだけ・最大 2 つ)。
|
|
482
|
+
* 100% 積み上げの面グラフでは、最初の系列(一番下の帯)の最初と最新の比率(「24%」「31%」)を帯の中に付ける。
|
|
483
|
+
* 既定は Line / Area が `"auto"`、Bar は `index` が日付・年月・年のときだけ `"auto"`。
|
|
484
|
+
*/
|
|
485
|
+
highlight?: ChartHighlight
|
|
486
|
+
/**
|
|
487
|
+
* ここから先は確定前(速報)の点。index の値で渡す(例 `"2026-09"`)。薄い色・点線(棒は薄い塗りと破線の縁)で
|
|
488
|
+
* 描き、凡例・ツールチップに `provisionalLabel` を出す。線・面は確定の最終点とつなぐ。`forecast`(予測)とは別物。
|
|
489
|
+
* 例: `provisionalFrom="2026-09"`
|
|
490
|
+
*/
|
|
491
|
+
provisionalFrom?: string | number
|
|
492
|
+
/** 速報の呼び名(凡例・ツールチップ)。既定「速報」。例: `provisionalLabel="暫定"` */
|
|
493
|
+
provisionalLabel?: string
|
|
494
|
+
/**
|
|
495
|
+
* グラフが言っていることの 1 文要約(自由文)。`"auto"` なら data から機械的に組む
|
|
496
|
+
* (「<見出し>: 最新 <index値> は <値>、前の点より増加/減少」。向きは最新 2 点の値で決まる)。
|
|
497
|
+
* 増減の向きを文に書くなら `"auto"` を使うか data から作る — 手書きの向きは data とずれて誤る。
|
|
498
|
+
* 省略時は要約なし(既存どおり)。例: `summary="auto"`
|
|
499
|
+
*/
|
|
500
|
+
summary?: string | "auto"
|
|
501
|
+
/** 目標値。点線の水平線で示し、値軸は必ずこの値を含む。棒ごとの目標(`barOptions.targetKey`)を渡したときは描かない。 */
|
|
502
|
+
target?: number
|
|
503
|
+
/** 目標線のラベル。既定「目標 <書式化した値>」。`barOptions.targetKey` のときはマーカーの呼び名(既定「目標」)。 */
|
|
504
|
+
targetLabel?: string
|
|
505
|
+
/**
|
|
506
|
+
* 任意の位置への注記(縦の線、または `to` で区間の帯)。折れ線・面・縦の棒(`barOptions.layout` が既定のとき)で使え、
|
|
507
|
+
* 横棒では描かない。`at` / `to` は `index` の値。色は中立で、ツールチップにも文言が出る。例:
|
|
508
|
+
* `annotations={[{ at: "2026-04", label: "料金改定" }, { at: "2026-08", to: "2026-09", label: "キャンペーン" }]}`
|
|
509
|
+
*/
|
|
510
|
+
annotations?: ChartAnnotation[]
|
|
511
|
+
/** 凡例を出す。既定 `true`。 */
|
|
512
|
+
showLegend?: boolean
|
|
513
|
+
/** ホバー時のツールチップを出す。既定 `true`。 */
|
|
514
|
+
showTooltip?: boolean
|
|
515
|
+
/** 値軸の目盛り線を出す。既定 `true`。 */
|
|
516
|
+
showGridLines?: boolean
|
|
517
|
+
showXAxis?: boolean
|
|
518
|
+
showYAxis?: boolean
|
|
519
|
+
/** x 軸のラベルを最初と最後だけにする。 */
|
|
520
|
+
startEndOnly?: boolean
|
|
521
|
+
/** y 軸ラベルの幅(px)。並べた複数グラフのプロット領域を揃えたいときに固定する。 */
|
|
522
|
+
yAxisWidth?: number
|
|
523
|
+
/**
|
|
524
|
+
* 値軸の下限。Bar / Area は常に 0 起点なので、0 以下の値だけ有効(負の値の下に余白を取る。正の値は無視)。
|
|
525
|
+
* Line は指定した値から始める。データが下限を下回るときは軸を広げる(切り詰めない)。
|
|
526
|
+
* 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
|
|
527
|
+
*/
|
|
528
|
+
minValue?: number
|
|
529
|
+
/**
|
|
530
|
+
* 値軸の上限(横棒は横軸)。データが上限を超えるときは軸を広げる(切り詰めない)。
|
|
531
|
+
* 並べて比べる複数のグラフには同じ値を渡して軸をそろえる。
|
|
532
|
+
*/
|
|
533
|
+
maxValue?: number
|
|
534
|
+
/** @deprecated `lineOptions.fitToData` を使う。Bar / Area では無視される(常に 0 起点)。 */
|
|
535
|
+
autoMinValue?: boolean
|
|
536
|
+
/** `false` で値軸の目盛りを整数に限る。 */
|
|
537
|
+
allowDecimals?: boolean
|
|
538
|
+
xAxisLabel?: string
|
|
539
|
+
yAxisLabel?: string
|
|
540
|
+
/**
|
|
541
|
+
* 点(棒)のクリックで呼ばれる。クリックした行に `eventType` / `categoryClicked` を
|
|
542
|
+
* 足して渡し、同じ点をもう一度クリックすると `null`。渡すと選択以外が薄くなる。
|
|
543
|
+
*/
|
|
544
|
+
onValueChange?: (value: ChartEventPayload) => void
|
|
545
|
+
/** @deprecated `isLoading` を使う。 */
|
|
546
|
+
loading?: boolean
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/** The point a user clicked, used to dim everything else. */
|
|
550
|
+
interface ChartActivePoint {
|
|
551
|
+
category: string
|
|
552
|
+
index: number
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** The forecast as the builder takes it: untyped keys, already validated by the component's props. */
|
|
556
|
+
type CartesianForecastConfig = Omit<ChartForecast, "category"> & { category?: string }
|
|
557
|
+
|
|
558
|
+
/** The comparison series as the builder takes it (see `ChartComparison`); `label` names the baseline for `vs: "custom"`. */
|
|
559
|
+
interface CartesianComparisonConfig {
|
|
560
|
+
/** One of `categories`; drawn as a thin muted line, outside the `--chart-*` order. */
|
|
561
|
+
category: string
|
|
562
|
+
vs: ComparisonKind
|
|
563
|
+
label?: string
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
interface CartesianChartConfig {
|
|
567
|
+
kind: CartesianChartKind
|
|
568
|
+
data: readonly Record<string, unknown>[]
|
|
569
|
+
index: string
|
|
570
|
+
categories: readonly string[]
|
|
571
|
+
/** Resolved series colours, by category position. `""`/missing → theme palette. */
|
|
572
|
+
palette: readonly string[]
|
|
573
|
+
/** Display names for `index` values and category names (axis, legend, tooltip). Missing keys show as they are. */
|
|
574
|
+
labels?: Readonly<Record<string, string>>
|
|
575
|
+
/** Bar only, not stacked: colour each bar by its value (first matching rule wins). With several series (side by side) a bar that matches takes the tone as its fill and keeps its series colour as the edge. */
|
|
576
|
+
thresholds?: readonly ChartThreshold[]
|
|
577
|
+
/** Resolved colour of each tone (`resolveChartColors`); a tone missing here keeps the series colour. */
|
|
578
|
+
toneColors?: Partial<Record<ChartTone, string>>
|
|
579
|
+
/** Tooltip values. */
|
|
580
|
+
valueFormatter: (value: number) => string
|
|
581
|
+
/** Value-axis ticks, highlight and target labels (short form, e.g. ¥1億). Default `valueFormatter`. */
|
|
582
|
+
axisFormatter?: (value: number) => string
|
|
583
|
+
/**
|
|
584
|
+
* The value-axis tick formatter for an axis whose largest tick is the given number (`resolveAxisTickFormatter`):
|
|
585
|
+
* all ticks read in one unit (¥0.5億 / ¥1億). Default: `axisFormatter` for every tick.
|
|
586
|
+
*/
|
|
587
|
+
axisTicks?: (top: number) => (value: number) => string
|
|
588
|
+
/** Locale of the time-axis labels. Default `"ja-JP"`. */
|
|
589
|
+
locale?: string
|
|
590
|
+
type?: CartesianStackType
|
|
591
|
+
/** Bar only. `"vertical"` lays the categories down the y axis (horizontal bars). */
|
|
592
|
+
layout?: BarLayout
|
|
593
|
+
curveType?: CartesianCurveType
|
|
594
|
+
fill?: AreaFill
|
|
595
|
+
connectNulls?: boolean
|
|
596
|
+
showLegend?: boolean
|
|
597
|
+
showTooltip?: boolean
|
|
598
|
+
showGridLines?: boolean
|
|
599
|
+
showXAxis?: boolean
|
|
600
|
+
showYAxis?: boolean
|
|
601
|
+
startEndOnly?: boolean
|
|
602
|
+
yAxisWidth?: number
|
|
603
|
+
/** Bar / Area: only a value ≤ 0 takes effect (they start at 0). Line: the axis' start. The axis widens to the data. */
|
|
604
|
+
minValue?: number
|
|
605
|
+
/** The axis' top; the axis widens to the data. */
|
|
606
|
+
maxValue?: number
|
|
607
|
+
/** Line only: legacy alias of `fitToData`. */
|
|
608
|
+
autoMinValue?: boolean
|
|
609
|
+
/** Line only: let the value axis follow the data instead of starting at 0. */
|
|
610
|
+
fitToData?: boolean
|
|
611
|
+
allowDecimals?: boolean
|
|
612
|
+
xAxisLabel?: string
|
|
613
|
+
yAxisLabel?: string
|
|
614
|
+
barCategoryGap?: string | number
|
|
615
|
+
/** Always draw the line/area points (needed to click them). */
|
|
616
|
+
showDots?: boolean
|
|
617
|
+
active?: ChartActivePoint | null
|
|
618
|
+
/** Default: `"auto"` for line/area, for bar only when `index` holds dates. */
|
|
619
|
+
highlight?: ChartHighlight
|
|
620
|
+
/** Bar only: the index value of the one horizontal bar drawn in the full colour (`BarChartOptions.highlight`). */
|
|
621
|
+
barHighlight?: string | number
|
|
622
|
+
target?: number
|
|
623
|
+
targetLabel?: string
|
|
624
|
+
/** Line only: where the target label sits (see `LineChartOptions.targetLabelPosition`). Default `"start"`. */
|
|
625
|
+
targetLabelPosition?: LineTargetLabelPosition
|
|
626
|
+
/** Bar only: a data column holding each bar's target (see `BarChartOptions.targetKey`). */
|
|
627
|
+
targetKey?: string
|
|
628
|
+
/** Notes at an index value or over a range (vertical bars, line, area). */
|
|
629
|
+
annotations?: readonly ChartAnnotation[]
|
|
630
|
+
/** Bar only, not stacked: label bars whose value is 0 with「0」(default true). */
|
|
631
|
+
showZeroValues?: boolean
|
|
632
|
+
/** Line / Area only; ignored for bar and for percent stacking. */
|
|
633
|
+
forecast?: CartesianForecastConfig
|
|
634
|
+
/**
|
|
635
|
+
* Line / Area only; ignored for bar and for percent stacking. The series `category` is drawn as a muted 1.5px solid line
|
|
636
|
+
* (no markers, no fill, outside a stack) and the first other series' tooltip row gets its difference from it.
|
|
637
|
+
*/
|
|
638
|
+
comparison?: CartesianComparisonConfig
|
|
639
|
+
/** The `format` of the values, for the comparison's difference in the tooltip (percent → points). Default: relative change. */
|
|
640
|
+
comparisonFormat?: ValueFormat
|
|
641
|
+
/** Index value of the first provisional point (see `CartesianChartBaseProps.provisionalFrom`). */
|
|
642
|
+
provisionalFrom?: string | number
|
|
643
|
+
provisionalLabel?: string
|
|
644
|
+
/** The PNG action buttons are shown (top right): the legend keeps clear of them. */
|
|
645
|
+
reserveActions?: boolean
|
|
646
|
+
/** Colour of the target / forecast guide lines (resolved muted text). */
|
|
647
|
+
guideColor?: string
|
|
648
|
+
/**
|
|
649
|
+
* The surface the chart sits on (resolved). Highlight labels get it as a
|
|
650
|
+
* backdrop, so a guide line passing behind them never runs through the text.
|
|
651
|
+
*/
|
|
652
|
+
labelBackground?: string
|
|
653
|
+
/** Colour of the highlight labels (resolved foreground). */
|
|
654
|
+
labelColor?: string
|
|
655
|
+
/**
|
|
656
|
+
* The plot's width in px, when known. Sets how many time labels fit, how many value ticks a
|
|
657
|
+
* horizontal bar chart carries, and drops the max highlight when it would print over the latest one.
|
|
658
|
+
*/
|
|
659
|
+
plotWidth?: number
|
|
660
|
+
/** The plot's height in px (the `height` prop), when known: under 200 the value axis carries 3 intervals, else 4–5. */
|
|
661
|
+
plotHeight?: number
|
|
662
|
+
reducedMotion?: boolean
|
|
663
|
+
/** Deep-merged onto the generated option last. */
|
|
664
|
+
chartOptions?: EChartsOption
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
/* ----------------------------------------------------------------- motion */
|
|
668
|
+
|
|
669
|
+
/**
|
|
670
|
+
* The typed charts' motion: no entrance animation, a short ease on updates so a
|
|
671
|
+
* filter change reads as a change. Reduced motion turns animation off.
|
|
672
|
+
*/
|
|
673
|
+
function chartMotion(reducedMotion: boolean): EChartsOption {
|
|
674
|
+
if (reducedMotion) return { animation: false }
|
|
675
|
+
return { animation: true, animationDuration: 0, animationDurationUpdate: 300, animationEasingUpdate: "cubicOut" }
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/* ----------------------------------------------------------------- merge */
|
|
679
|
+
|
|
680
|
+
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
681
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false
|
|
682
|
+
const proto = Object.getPrototypeOf(value)
|
|
683
|
+
return proto === Object.prototype || proto === null
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Deep-merge `override` onto `base` without mutating either: plain objects merge
|
|
688
|
+
* key by key, arrays merge by position (so `series: [{ … }]` tweaks the first
|
|
689
|
+
* series), anything else in `override` replaces. `undefined` keeps the base.
|
|
690
|
+
*/
|
|
691
|
+
function mergeChartOptions<T>(base: T, override: unknown): T {
|
|
692
|
+
if (override === undefined) return base
|
|
693
|
+
if (Array.isArray(override)) {
|
|
694
|
+
if (!Array.isArray(base)) return override as T
|
|
695
|
+
const length = Math.max(base.length, override.length)
|
|
696
|
+
return Array.from({ length }, (_, i) => (i < override.length ? mergeChartOptions(base[i], override[i]) : base[i])) as T
|
|
697
|
+
}
|
|
698
|
+
if (isPlainRecord(override) && isPlainRecord(base)) {
|
|
699
|
+
const out: Record<string, unknown> = { ...base }
|
|
700
|
+
for (const key of Object.keys(override)) out[key] = mergeChartOptions(base[key], override[key])
|
|
701
|
+
return out as T
|
|
702
|
+
}
|
|
703
|
+
return override as T
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/* -------------------------------------------------------------- highlight */
|
|
707
|
+
|
|
708
|
+
const TIME_INDEX_RE =
|
|
709
|
+
/^\d{4}(?:[-/]\d{1,2}(?:[-/]\d{1,2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2})?)?)?)?$/
|
|
710
|
+
|
|
711
|
+
/**
|
|
712
|
+
* Whether the x values look like time: ISO dates / date-times, `YYYY-MM`,
|
|
713
|
+
* `YYYY`, or `Date` objects. Blank cells are ignored; nothing at all → `false`.
|
|
714
|
+
*/
|
|
715
|
+
function isTimeIndex(values: readonly unknown[]): boolean {
|
|
716
|
+
const present = values.filter((v) => v !== null && v !== undefined && v !== "")
|
|
717
|
+
if (present.length === 0) return false
|
|
718
|
+
return present.every((v) =>
|
|
719
|
+
v instanceof Date ? !Number.isNaN(v.getTime()) : typeof v === "string" && TIME_INDEX_RE.test(v.trim()),
|
|
720
|
+
)
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
/* -------------------------------------------------------------- time axis */
|
|
724
|
+
|
|
725
|
+
type TimeGranularity = "year" | "month" | "day"
|
|
726
|
+
|
|
727
|
+
interface ParsedTime {
|
|
728
|
+
year: number
|
|
729
|
+
/** 1–12. */
|
|
730
|
+
month: number
|
|
731
|
+
day: number
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
const TIME_PARTS_RE = /^(\d{4})(?:[-/](\d{1,2})(?:[-/](\d{1,2}))?)?$/
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* The x values as calendar dates, with the finest granularity they carry — or
|
|
738
|
+
* `null` when any value is not a plain year / month / date (date-times with a
|
|
739
|
+
* clock part stay as they are: one label per hour would need its own format).
|
|
740
|
+
*/
|
|
741
|
+
function parseTimeIndex(values: readonly unknown[]): { granularity: TimeGranularity; times: (ParsedTime | null)[] } | null {
|
|
742
|
+
if (!isTimeIndex(values)) return null
|
|
743
|
+
const ranks: readonly TimeGranularity[] = ["year", "month", "day"]
|
|
744
|
+
let rank = 0
|
|
745
|
+
const finer = (g: TimeGranularity) => {
|
|
746
|
+
rank = Math.max(rank, ranks.indexOf(g))
|
|
747
|
+
}
|
|
748
|
+
const times: (ParsedTime | null)[] = []
|
|
749
|
+
for (const v of values) {
|
|
750
|
+
if (v === null || v === undefined || v === "") {
|
|
751
|
+
times.push(null)
|
|
752
|
+
continue
|
|
753
|
+
}
|
|
754
|
+
if (v instanceof Date) {
|
|
755
|
+
if (v.getHours() !== 0 || v.getMinutes() !== 0 || v.getSeconds() !== 0) return null
|
|
756
|
+
finer(v.getDate() === 1 ? "month" : "day")
|
|
757
|
+
times.push({ year: v.getFullYear(), month: v.getMonth() + 1, day: v.getDate() })
|
|
758
|
+
continue
|
|
759
|
+
}
|
|
760
|
+
const text = String(v).trim()
|
|
761
|
+
// A trailing midnight (`2025-09-01T00:00:00Z`) is still a date; any other time of day is not.
|
|
762
|
+
const date = text.replace(/[T ]00:00(?::00(?:\.0+)?)?(?:Z|[+-]\d{2}:?\d{2})?$/, "")
|
|
763
|
+
const m = TIME_PARTS_RE.exec(date)
|
|
764
|
+
if (!m) return null
|
|
765
|
+
finer(m[3] !== undefined ? "day" : m[2] !== undefined ? "month" : "year")
|
|
766
|
+
times.push({ year: Number(m[1]), month: Number(m[2] ?? 1), day: Number(m[3] ?? 1) })
|
|
767
|
+
}
|
|
768
|
+
// Date objects on the 1st read as months only when every value falls on a 1st.
|
|
769
|
+
if (rank === 1 && values.some((v) => v instanceof Date) && times.some((t) => t !== null && t.day !== 1)) rank = 2
|
|
770
|
+
return { granularity: ranks[rank]!, times }
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
const timeFormatCache = new Map<string, Intl.DateTimeFormat>()
|
|
774
|
+
|
|
775
|
+
function timeFormat(locale: string, options: Intl.DateTimeFormatOptions): Intl.DateTimeFormat {
|
|
776
|
+
const key = `${locale}|${JSON.stringify(options)}`
|
|
777
|
+
let format = timeFormatCache.get(key)
|
|
778
|
+
if (!format) {
|
|
779
|
+
format = new Intl.DateTimeFormat(locale, options)
|
|
780
|
+
timeFormatCache.set(key, format)
|
|
781
|
+
}
|
|
782
|
+
return format
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
const toDate = (t: ParsedTime) => new Date(t.year, t.month - 1, t.day)
|
|
786
|
+
|
|
787
|
+
/** How many x labels a time axis shows at most (the step is picked so the labels never crowd). */
|
|
788
|
+
const TIME_AXIS_MAX_LABELS = 6
|
|
789
|
+
|
|
790
|
+
/** Calendar-friendly label steps per granularity (every 3 months, every week …). */
|
|
791
|
+
const TIME_AXIS_STEPS: Record<TimeGranularity, readonly number[]> = {
|
|
792
|
+
year: [1, 2, 5, 10, 20, 50, 100],
|
|
793
|
+
month: [1, 2, 3, 4, 6, 12, 24, 36, 60, 120],
|
|
794
|
+
day: [1, 2, 7, 14, 28, 56, 91, 182, 364],
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/**
|
|
798
|
+
* Every how many points a time axis prints a label: the smallest calendar step
|
|
799
|
+
* (1, 2, 3, 4, 6, 12 months; 1, 2, 7, 14 days; …) that keeps the labels at or
|
|
800
|
+
* under `maxLabels`. Deterministic, so the year-change label is never skipped by
|
|
801
|
+
* ECharts' own overlap thinning. `null` when the values are not dates.
|
|
802
|
+
*/
|
|
803
|
+
function timeAxisLabelStep(values: readonly unknown[], maxLabels: number = TIME_AXIS_MAX_LABELS): number | null {
|
|
804
|
+
const parsed = parseTimeIndex(values)
|
|
805
|
+
if (!parsed) return null
|
|
806
|
+
const count = values.length
|
|
807
|
+
const max = Math.max(1, maxLabels)
|
|
808
|
+
const steps = TIME_AXIS_STEPS[parsed.granularity]
|
|
809
|
+
return steps.find((step) => Math.ceil(count / step) <= max) ?? Math.ceil(count / max)
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* Category-axis labels for time-like x values, in `locale`: monthly data reads
|
|
814
|
+
* `4月`, with the year (`2025年1月`) on the first shown label and on any shown
|
|
815
|
+
* label whose year differs from the previous *shown* one; daily data reads
|
|
816
|
+
* `4/1` (`2025/4/1` likewise); yearly data `2025年`. `shown(i)` says which
|
|
817
|
+
* labels the axis prints (default: all) — hidden ones never carry the year.
|
|
818
|
+
* `null` when the values are not dates — the axis then shows them as they are.
|
|
819
|
+
*/
|
|
820
|
+
function timeAxisLabels(
|
|
821
|
+
values: readonly unknown[],
|
|
822
|
+
locale: string = DEFAULT_LOCALE,
|
|
823
|
+
shown: (i: number) => boolean = () => true,
|
|
824
|
+
): string[] | null {
|
|
825
|
+
const parsed = parseTimeIndex(values)
|
|
826
|
+
if (!parsed) return null
|
|
827
|
+
const { granularity, times } = parsed
|
|
828
|
+
let prevYear: number | null = null
|
|
829
|
+
return times.map((t, i) => {
|
|
830
|
+
if (t === null) return String(values[i] ?? "")
|
|
831
|
+
const visible = shown(i)
|
|
832
|
+
const withYear = visible && (prevYear === null || t.year !== prevYear)
|
|
833
|
+
if (visible) prevYear = t.year
|
|
834
|
+
const options: Intl.DateTimeFormatOptions =
|
|
835
|
+
granularity === "year"
|
|
836
|
+
? { year: "numeric" }
|
|
837
|
+
: granularity === "month"
|
|
838
|
+
? withYear
|
|
839
|
+
? { year: "numeric", month: "short" }
|
|
840
|
+
: { month: "short" }
|
|
841
|
+
: withYear
|
|
842
|
+
? { year: "numeric", month: "numeric", day: "numeric" }
|
|
843
|
+
: { month: "numeric", day: "numeric" }
|
|
844
|
+
return timeFormat(locale, options).format(toDate(t))
|
|
845
|
+
})
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** The tooltip titles for time-like x values (`2025年9月`, `2025年9月1日`), or `null` when they are not dates. */
|
|
849
|
+
function timeTooltipLabels(values: readonly unknown[], locale: string = DEFAULT_LOCALE): string[] | null {
|
|
850
|
+
const parsed = parseTimeIndex(values)
|
|
851
|
+
if (!parsed) return null
|
|
852
|
+
const options: Intl.DateTimeFormatOptions =
|
|
853
|
+
parsed.granularity === "year"
|
|
854
|
+
? { year: "numeric" }
|
|
855
|
+
: parsed.granularity === "month"
|
|
856
|
+
? { year: "numeric", month: "long" }
|
|
857
|
+
: { year: "numeric", month: "long", day: "numeric" }
|
|
858
|
+
return parsed.times.map((t, i) => (t === null ? String(values[i] ?? "") : timeFormat(locale, options).format(toDate(t))))
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
interface HighlightPoint {
|
|
862
|
+
kind: "max" | "latest" | "start"
|
|
863
|
+
index: number
|
|
864
|
+
value: number
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/**
|
|
868
|
+
* The points `highlight="auto"` labels on one series: the latest (last
|
|
869
|
+
* non-null) point, and the maximum unless it *is* the latest or sits next to it
|
|
870
|
+
* (`|i - latest| ≤ 1`, the labels would collide) — at most 2, max first.
|
|
871
|
+
*/
|
|
872
|
+
function pickHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
|
|
873
|
+
let latest = -1
|
|
874
|
+
for (let i = values.length - 1; i >= 0; i--) {
|
|
875
|
+
if (values[i] !== null && values[i] !== undefined) {
|
|
876
|
+
latest = i
|
|
877
|
+
break
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
if (latest === -1) return []
|
|
881
|
+
const latestValue = values[latest]!
|
|
882
|
+
let max = -1
|
|
883
|
+
values.forEach((v, i) => {
|
|
884
|
+
if (v !== null && v !== undefined && (max === -1 || v > values[max]!)) max = i
|
|
885
|
+
})
|
|
886
|
+
const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: latestValue }
|
|
887
|
+
if (max === -1 || max === latest || latestValue >= values[max]! || Math.abs(max - latest) <= 1) return [latestPoint]
|
|
888
|
+
return [{ kind: "max", index: max, value: values[max]! }, latestPoint]
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/**
|
|
892
|
+
* The points a 100% stacked area labels: the first and the latest (last
|
|
893
|
+
* non-null) share of one band — "24% → 31%" is the claim such a chart makes.
|
|
894
|
+
*/
|
|
895
|
+
function pickShareHighlightPoints(values: readonly (number | null)[]): HighlightPoint[] {
|
|
896
|
+
const first = values.findIndex((v) => v !== null && v !== undefined)
|
|
897
|
+
if (first === -1) return []
|
|
898
|
+
let latest = first
|
|
899
|
+
for (let i = values.length - 1; i > first; i--) {
|
|
900
|
+
if (values[i] !== null && values[i] !== undefined) {
|
|
901
|
+
latest = i
|
|
902
|
+
break
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
const latestPoint: HighlightPoint = { kind: "latest", index: latest, value: values[latest]! }
|
|
906
|
+
return latest === first ? [latestPoint] : [{ kind: "start", index: first, value: values[first]! }, latestPoint]
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** Whether a chart of `kind` labels its highlights by default. */
|
|
910
|
+
function defaultChartHighlight(
|
|
911
|
+
kind: CartesianChartKind,
|
|
912
|
+
data: readonly Record<string, unknown>[],
|
|
913
|
+
index: string,
|
|
914
|
+
): ChartHighlight {
|
|
915
|
+
if (kind !== "bar") return "auto"
|
|
916
|
+
return isTimeIndex(data.map((row) => row[index])) ? "auto" : "none"
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
/* ---------------------------------------------------------------- helpers */
|
|
920
|
+
|
|
921
|
+
/** Same coercion as `toChartNumber` in chart-utils (kept local: inlined modules can't import each other). */
|
|
922
|
+
function cellNumber(value: unknown): number | null {
|
|
923
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null
|
|
924
|
+
if (typeof value === "bigint") return Number(value)
|
|
925
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
926
|
+
const n = Number(value)
|
|
927
|
+
return Number.isFinite(n) ? n : null
|
|
928
|
+
}
|
|
929
|
+
return null
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* Series values per category. `"percent"` turns each row into shares of that
|
|
934
|
+
* row's total (0–100); a row whose total is 0 stays at 0.
|
|
935
|
+
*/
|
|
936
|
+
function cartesianSeriesValues(
|
|
937
|
+
data: readonly Record<string, unknown>[],
|
|
938
|
+
categories: readonly string[],
|
|
939
|
+
type: CartesianStackType = "default",
|
|
940
|
+
): (number | null)[][] {
|
|
941
|
+
const raw = categories.map((category) => data.map((row) => cellNumber(row[category])))
|
|
942
|
+
if (type !== "percent") return raw
|
|
943
|
+
return raw.map((values) =>
|
|
944
|
+
values.map((value, i) => {
|
|
945
|
+
if (value === null) return null
|
|
946
|
+
const total = categories.reduce((sum, _, k) => sum + Math.abs(raw[k]![i] ?? 0), 0)
|
|
947
|
+
return total === 0 ? 0 : (Math.abs(value) / total) * 100
|
|
948
|
+
}),
|
|
949
|
+
)
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/** A colour with alpha, for gradient stops. Understands `#rgb`, `#rrggbb`, `rgb()`/`rgba()`. */
|
|
953
|
+
function withAlpha(color: string, alpha: number): string {
|
|
954
|
+
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())
|
|
955
|
+
if (hex) {
|
|
956
|
+
const h = hex[1]!
|
|
957
|
+
const full = h.length === 3 ? h.replace(/./g, (c) => c + c) : h
|
|
958
|
+
const n = Number.parseInt(full, 16)
|
|
959
|
+
return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
|
|
960
|
+
}
|
|
961
|
+
const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
|
|
962
|
+
if (rgb) return `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})`
|
|
963
|
+
return color
|
|
964
|
+
}
|
|
965
|
+
|
|
966
|
+
const HTML_ESCAPES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }
|
|
967
|
+
|
|
968
|
+
function escapeHtml(value: string): string {
|
|
969
|
+
return value.replace(/[&<>"']/g, (c) => HTML_ESCAPES[c]!)
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
interface TooltipRow {
|
|
973
|
+
name: string
|
|
974
|
+
color: string
|
|
975
|
+
value: number | null
|
|
976
|
+
/** Percent stacking: the row's share of its point's total (0–100). */
|
|
977
|
+
share?: number
|
|
978
|
+
/** A muted line right under the row (a comparison's difference). */
|
|
979
|
+
note?: string
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
const shareFormat = new Intl.NumberFormat(DEFAULT_LOCALE, { maximumFractionDigits: 1 })
|
|
983
|
+
const formatShare = (share: number) => `${shareFormat.format(share)}%`
|
|
984
|
+
|
|
985
|
+
/** The tooltip body: a title, then one `● name value` row per series, then muted one-line `notes` (target, annotation). */
|
|
986
|
+
function tooltipHtml(
|
|
987
|
+
title: string,
|
|
988
|
+
rows: readonly TooltipRow[],
|
|
989
|
+
valueFormatter: (value: number) => string,
|
|
990
|
+
notes: readonly string[] = [],
|
|
991
|
+
): string {
|
|
992
|
+
const lines = rows.map(
|
|
993
|
+
(row) =>
|
|
994
|
+
`<div style="display:flex;align-items:center;gap:8px;line-height:20px">` +
|
|
995
|
+
`<span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${escapeHtml(row.color)}"></span>` +
|
|
996
|
+
`<span style="flex:1;opacity:.8">${escapeHtml(row.name)}</span>` +
|
|
997
|
+
`<span style="font-weight:600;font-variant-numeric:tabular-nums;margin-left:12px">${
|
|
998
|
+
row.value === null ? EMPTY_VALUE : escapeHtml(valueFormatter(row.value))
|
|
999
|
+
}${
|
|
1000
|
+
row.share === undefined ? "" : `<span style="opacity:.6;margin-left:4px">(${escapeHtml(formatShare(row.share))})</span>`
|
|
1001
|
+
}</span></div>` +
|
|
1002
|
+
(row.note === undefined
|
|
1003
|
+
? ""
|
|
1004
|
+
: `<div style="padding-left:16px;line-height:18px;font-size:12px;opacity:.7;font-variant-numeric:tabular-nums">${escapeHtml(row.note)}</div>`),
|
|
1005
|
+
)
|
|
1006
|
+
const noteLines = notes.map(
|
|
1007
|
+
(note) => `<div style="margin-top:4px;line-height:18px;font-size:12px;opacity:.7">${escapeHtml(note)}</div>`,
|
|
1008
|
+
)
|
|
1009
|
+
return `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(title)}</div>${lines.join("")}${noteLines.join("")}`
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
/* ------------------------------------------------- per-bar targets / notes */
|
|
1013
|
+
|
|
1014
|
+
/** Default name of the per-bar target marker (legend, tooltip). */
|
|
1015
|
+
const BAR_TARGET_LABEL = "目標"
|
|
1016
|
+
|
|
1017
|
+
/** How far (px) the target marker reaches past each side of its bar. */
|
|
1018
|
+
const TARGET_MARKER_OVERHANG = 4
|
|
1019
|
+
|
|
1020
|
+
/**
|
|
1021
|
+
* The `renderItem` of the per-bar target marker: a 2px tick across the bar. Its length
|
|
1022
|
+
* is the bar's own width as ECharts lays it out (`api.barLayout`, one column — a single
|
|
1023
|
+
* series or a stack) plus a little overhang; without that it falls back to the
|
|
1024
|
+
* category band times `barHalfWidth`.
|
|
1025
|
+
*/
|
|
1026
|
+
function targetMarkerRenderer(horizontalBars: boolean, barCategoryGap: string | number | undefined, color: string | undefined) {
|
|
1027
|
+
type Api = {
|
|
1028
|
+
value(dim: number): number
|
|
1029
|
+
coord(value: number[]): number[]
|
|
1030
|
+
size(value: number[]): number[]
|
|
1031
|
+
barLayout?(opt: { count: number; barCategoryGap?: string | number }): { width: number }[]
|
|
1032
|
+
}
|
|
1033
|
+
return (_params: unknown, api: Api) => {
|
|
1034
|
+
const [x = 0, y = 0] = api.coord([api.value(0), api.value(1)])
|
|
1035
|
+
const band = Math.abs(horizontalBars ? (api.size([0, 1])[1] ?? 0) : (api.size([1, 0])[0] ?? 0))
|
|
1036
|
+
const barWidth = api.barLayout?.({ count: 1, barCategoryGap })?.[0]?.width
|
|
1037
|
+
const length = (barWidth && barWidth > 0 ? barWidth : band * 2 * barHalfWidth(barCategoryGap)) + TARGET_MARKER_OVERHANG * 2
|
|
1038
|
+
return {
|
|
1039
|
+
type: "line",
|
|
1040
|
+
silent: true,
|
|
1041
|
+
shape: horizontalBars
|
|
1042
|
+
? { x1: x, y1: y - length / 2, x2: x, y2: y + length / 2 }
|
|
1043
|
+
: { x1: x - length / 2, y1: y, x2: x + length / 2, y2: y },
|
|
1044
|
+
style: { stroke: color, lineWidth: 2, lineCap: "butt" },
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
/**
|
|
1050
|
+
* Each row's target from the `targetKey` column. A missing, non-numeric or
|
|
1051
|
+
* non-positive cell is `null` (no marker for that bar).
|
|
1052
|
+
*/
|
|
1053
|
+
function barTargetValues(data: readonly Record<string, unknown>[], targetKey: string): (number | null)[] {
|
|
1054
|
+
return data.map((row) => {
|
|
1055
|
+
const value = cellNumber(row[targetKey])
|
|
1056
|
+
return value !== null && value > 0 ? value : null
|
|
1057
|
+
})
|
|
1058
|
+
}
|
|
1059
|
+
|
|
1060
|
+
/** `value` as a share of `target` in percent; `null` without a value or a positive target. */
|
|
1061
|
+
function achievementRate(value: number | null | undefined, target: number | null | undefined): number | null {
|
|
1062
|
+
if (value === null || value === undefined || target === null || target === undefined || !(target > 0)) return null
|
|
1063
|
+
return (value / target) * 100
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
/** The tooltip line of a bar with a target: 「目標 ¥1,200万(達成率 85.3%)」. `null` without a target. */
|
|
1067
|
+
function barTargetNote(
|
|
1068
|
+
label: string,
|
|
1069
|
+
value: number | null,
|
|
1070
|
+
target: number | null,
|
|
1071
|
+
valueFormatter: (value: number) => string,
|
|
1072
|
+
): string | null {
|
|
1073
|
+
if (target === null) return null
|
|
1074
|
+
const rate = achievementRate(value, target)
|
|
1075
|
+
return `${label} ${valueFormatter(target)}${rate === null ? "" : `(達成率 ${formatShare(rate)})`}`
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
/** Half the width of a bar in category-axis units, from `barCategoryGap` (`"20%"`; a px gap or none → ECharts' 20%). */
|
|
1079
|
+
function barHalfWidth(barCategoryGap?: string | number): number {
|
|
1080
|
+
const gap = typeof barCategoryGap === "string" && /^\d+(\.\d+)?%$/.test(barCategoryGap.trim()) ? parseFloat(barCategoryGap) / 100 : 0.2
|
|
1081
|
+
return 0.5 / (1 + gap)
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
/** An annotation placed on the category axis: positions are indexes into the x labels. */
|
|
1085
|
+
interface ResolvedAnnotation {
|
|
1086
|
+
from: number
|
|
1087
|
+
/** Set for a range (`to` after `from`); a single position leaves it out. */
|
|
1088
|
+
to?: number
|
|
1089
|
+
label: string
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
/**
|
|
1093
|
+
* Place annotations on the x labels by `String(value)` equality. An annotation
|
|
1094
|
+
* whose `at` is not an `index` value is dropped; `to` before `at` swaps them; a
|
|
1095
|
+
* `to` that is unknown or equal to `at` makes it a single position.
|
|
1096
|
+
*/
|
|
1097
|
+
function resolveAnnotations(
|
|
1098
|
+
annotations: readonly ChartAnnotation[] | undefined,
|
|
1099
|
+
indexValues: readonly unknown[],
|
|
1100
|
+
): ResolvedAnnotation[] {
|
|
1101
|
+
if (!annotations?.length) return []
|
|
1102
|
+
const position = new Map<string, number>()
|
|
1103
|
+
indexValues.forEach((value, i) => {
|
|
1104
|
+
const key = String(value ?? "")
|
|
1105
|
+
if (!position.has(key)) position.set(key, i)
|
|
1106
|
+
})
|
|
1107
|
+
const out: ResolvedAnnotation[] = []
|
|
1108
|
+
for (const note of annotations) {
|
|
1109
|
+
const from = position.get(String(note.at))
|
|
1110
|
+
if (from === undefined || !note.label) continue
|
|
1111
|
+
const end = note.to === undefined ? undefined : position.get(String(note.to))
|
|
1112
|
+
if (end === undefined || end === from) out.push({ from, label: note.label })
|
|
1113
|
+
else out.push({ from: Math.min(from, end), to: Math.max(from, end), label: note.label })
|
|
1114
|
+
}
|
|
1115
|
+
return out
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
/** Gap (px) under which two neighbouring vertical labels (12px text) would print over each other. */
|
|
1119
|
+
const ANNOTATION_LABEL_GAP = 16
|
|
1120
|
+
/** Assumed spacing (px) between two index positions when the plot's width is unknown. */
|
|
1121
|
+
const ANNOTATION_ASSUMED_GAP = 40
|
|
1122
|
+
|
|
1123
|
+
/**
|
|
1124
|
+
* Which end of its line each single-position annotation's label sits on. Labels
|
|
1125
|
+
* run along the line; neighbours closer than a label's height alternate between
|
|
1126
|
+
* the top and the bottom end, so they never print over one another. `lines` are
|
|
1127
|
+
* the annotation positions (index units) in any order; the result follows that order.
|
|
1128
|
+
*/
|
|
1129
|
+
function annotationLabelEnds(lines: readonly number[], pointGap: number | null): ("top" | "bottom")[] {
|
|
1130
|
+
const gap = pointGap ?? ANNOTATION_ASSUMED_GAP
|
|
1131
|
+
const order = lines.map((at, i) => ({ at, i })).sort((a, b) => a.at - b.at || a.i - b.i)
|
|
1132
|
+
const ends: ("top" | "bottom")[] = Array(lines.length).fill("top")
|
|
1133
|
+
for (let k = 1; k < order.length; k++) {
|
|
1134
|
+
const prev = order[k - 1]!
|
|
1135
|
+
const cur = order[k]!
|
|
1136
|
+
if ((cur.at - prev.at) * gap < ANNOTATION_LABEL_GAP) ends[cur.i] = ends[prev.i] === "top" ? "bottom" : "top"
|
|
1137
|
+
}
|
|
1138
|
+
return ends
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
interface AxisTooltipParam {
|
|
1142
|
+
seriesId?: string
|
|
1143
|
+
seriesName?: string
|
|
1144
|
+
dataIndex?: number
|
|
1145
|
+
color?: unknown
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
const DIMMED = 0.3
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
/** Series ids. Ours are stable across updates so ECharts can transition them; `__` marks the helpers. */
|
|
1152
|
+
const SERIES_ID_PREFIX = "series:"
|
|
1153
|
+
const FORECAST_SERIES_ID = "__forecast"
|
|
1154
|
+
const PROVISIONAL_SERIES_PREFIX = "__provisional:"
|
|
1155
|
+
/** Provisional points are drawn at this opacity (lines, areas, bars). */
|
|
1156
|
+
const PROVISIONAL_OPACITY = 0.55
|
|
1157
|
+
/** Horizontal bars (one series, not stacked) are painted at this share of the series colour; the highlighted bar is solid. Same tint as BarList. */
|
|
1158
|
+
const LIGHT_BAR_ALPHA = 0.7
|
|
1159
|
+
const FORECAST_BAND_BASE_ID = "__forecast-band-base"
|
|
1160
|
+
const FORECAST_BAND_RANGE_ID = "__forecast-band-range"
|
|
1161
|
+
const OVERLAY_SERIES_ID = "__overlay"
|
|
1162
|
+
const TARGET_MARKER_SERIES_ID = "__target-marker"
|
|
1163
|
+
const TARGET_LEGEND_SERIES_ID = "__target-legend"
|
|
1164
|
+
/** A flat tick (8×8 legend box, aspect kept): the per-bar target's legend icon. */
|
|
1165
|
+
const TARGET_LEGEND_ICON = "path://M0,0 L100,0 L100,24 L0,24 Z"
|
|
1166
|
+
|
|
1167
|
+
const DEFAULT_FORECAST_LABEL = "予測"
|
|
1168
|
+
|
|
1169
|
+
/** The label at the top of a forecast's boundary line: the forecast's name (as in the legend) and an arrow toward the forecast side. */
|
|
1170
|
+
function forecastBoundaryText(label: string = DEFAULT_FORECAST_LABEL): string {
|
|
1171
|
+
return `${label} →`
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
/** A comparison series: a thin, muted, solid line with no markers (60% of `--muted-foreground`). */
|
|
1175
|
+
const COMPARISON_LINE_WIDTH = 1.5
|
|
1176
|
+
const COMPARISON_OPACITY = 0.6
|
|
1177
|
+
/** Target line: 1px dotted. Forecast: 2px dashed. Different widths *and* patterns, so the two never read as one. */
|
|
1178
|
+
const TARGET_LINE_DASH = [2, 3]
|
|
1179
|
+
const FORECAST_LINE_DASH = [6, 4]
|
|
1180
|
+
/** Legend icons for the two (8×8 box, aspect kept): a row of dots / of dashes in the line's own proportions. */
|
|
1181
|
+
const TARGET_DOTTED_ICON = "path://M0,0 L12,0 L12,10 L0,10 Z M30,0 L42,0 L42,10 L30,10 Z M60,0 L72,0 L72,10 L60,10 Z M88,0 L100,0 L100,10 L88,10 Z"
|
|
1182
|
+
const FORECAST_DASHED_ICON = "path://M0,0 L42,0 L42,24 L0,24 Z M58,0 L100,0 L100,24 L58,24 Z"
|
|
1183
|
+
|
|
1184
|
+
/** The forecast band's fill opacity: on a dark surface it needs more to show against the background. */
|
|
1185
|
+
const FORECAST_BAND_ALPHA_LIGHT = 0.15
|
|
1186
|
+
const FORECAST_BAND_ALPHA_DARK = 0.22
|
|
1187
|
+
|
|
1188
|
+
/** Whether a resolved surface colour (`#rrggbb` / `rgb()`) is dark (relative luminance under 0.4). `false` when it can't be read. */
|
|
1189
|
+
function isDarkSurface(color: string | undefined): boolean {
|
|
1190
|
+
if (!color) return false
|
|
1191
|
+
const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
|
|
1192
|
+
const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
|
|
1193
|
+
let channels: number[]
|
|
1194
|
+
if (hex) {
|
|
1195
|
+
const n = Number.parseInt(hex[1]!, 16)
|
|
1196
|
+
channels = [(n >> 16) & 255, (n >> 8) & 255, n & 255]
|
|
1197
|
+
} else if (rgb) channels = [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])]
|
|
1198
|
+
else return false
|
|
1199
|
+
const [r, g, b] = channels.map((c) => {
|
|
1200
|
+
const v = c / 255
|
|
1201
|
+
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4
|
|
1202
|
+
}) as [number, number, number]
|
|
1203
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.4
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
interface AxisExtent {
|
|
1207
|
+
min: number
|
|
1208
|
+
max: number
|
|
1209
|
+
}
|
|
1210
|
+
|
|
1211
|
+
/** The label of a stack's total (highlight and tooltip). */
|
|
1212
|
+
const STACK_TOTAL_LABEL = "合計"
|
|
1213
|
+
|
|
1214
|
+
/** Per point, the sum of the stacked series; `null` where every series is missing. */
|
|
1215
|
+
function stackTotalsOf(values: readonly (readonly (number | null)[])[]): (number | null)[] {
|
|
1216
|
+
const length = Math.max(0, ...values.map((v) => v.length))
|
|
1217
|
+
return Array.from({ length }, (_, i) => {
|
|
1218
|
+
let total: number | null = null
|
|
1219
|
+
for (const series of values) {
|
|
1220
|
+
const v = series[i]
|
|
1221
|
+
if (v !== null && v !== undefined) total = (total ?? 0) + v
|
|
1222
|
+
}
|
|
1223
|
+
return total
|
|
1224
|
+
})
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
const LEGEND_LINE_HEIGHT = 24
|
|
1228
|
+
/** A rough width budget per legend line (px): a narrow card fits about this much. */
|
|
1229
|
+
const LEGEND_LINE_BUDGET = 320
|
|
1230
|
+
|
|
1231
|
+
/** How many lines the plain legend takes, estimated from its labels (12px text + 8px dot + gaps). */
|
|
1232
|
+
function legendLines(items: readonly string[], plotWidth?: number, reserve = 0): number {
|
|
1233
|
+
const width = items.reduce((sum, name) => sum + [...name].length * 12 + 8 + 5 + 16, 0)
|
|
1234
|
+
const budget = Math.max(80, (plotWidth ? Math.min(LEGEND_LINE_BUDGET, plotWidth) : LEGEND_LINE_BUDGET) - reserve)
|
|
1235
|
+
return Math.min(3, Math.max(1, Math.ceil(width / budget)))
|
|
1236
|
+
}
|
|
1237
|
+
|
|
1238
|
+
/** Width (px) kept free at the legend's right for the PNG action buttons (two 32px buttons + gaps). */
|
|
1239
|
+
const ACTIONS_RESERVE = 80
|
|
1240
|
+
|
|
1241
|
+
/** Room (px) one time label (`2026年1月`) needs, gap included. */
|
|
1242
|
+
const TIME_LABEL_WIDTH = 80
|
|
1243
|
+
/** Room (px) one highlight label (`¥6,240万`) needs, gap included. */
|
|
1244
|
+
const HIGHLIGHT_LABEL_WIDTH = 96
|
|
1245
|
+
|
|
1246
|
+
/** A highlight this close under the target (share of the larger of the two) can reach its label. */
|
|
1247
|
+
const TARGET_NEAR_SHARE = 0.12
|
|
1248
|
+
/** Under this plot width (px) a target label that would run into the latest value's label is dropped from the line. */
|
|
1249
|
+
const TARGET_LABEL_NARROW_WIDTH = 480
|
|
1250
|
+
/** A typical value-axis label column (`¥8,000万`), px. */
|
|
1251
|
+
const Y_AXIS_ESTIMATE = 72
|
|
1252
|
+
/** Breathing room between two labels, px — the estimate is rough. */
|
|
1253
|
+
const LABEL_SLACK = 24
|
|
1254
|
+
|
|
1255
|
+
/** Rough width (px) of 12px text: full-width characters 12, the rest 7. */
|
|
1256
|
+
function estimateTextWidth(text: string): number {
|
|
1257
|
+
let w = 0
|
|
1258
|
+
for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
|
|
1259
|
+
return w
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
/**
|
|
1263
|
+
* How many intervals a horizontal value axis (a horizontal bar chart's x) can carry in `plot` px
|
|
1264
|
+
* without its tick labels touching: each tick takes the widest of `samples` (the axis' end labels
|
|
1265
|
+
* printed) plus a gap. At least 1, at most 5 (ECharts' default, which it rounds to a tidy step).
|
|
1266
|
+
*/
|
|
1267
|
+
function valueAxisSplitNumber(plot: number, samples: readonly string[]): number {
|
|
1268
|
+
const widest = samples.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
|
|
1269
|
+
return Math.max(1, Math.min(5, Math.floor(plot / (widest + LABEL_SLACK))))
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/** Room (px) above a vertical bar chart's plot for the label of an annotation band. */
|
|
1273
|
+
const BAND_LABEL_ROOM = 18
|
|
1274
|
+
|
|
1275
|
+
/** The grid's right margin on a line / area chart (px): the last x label hangs past the plot. */
|
|
1276
|
+
const LINE_RIGHT_MARGIN = 32
|
|
1277
|
+
|
|
1278
|
+
/** Room (px) above the plot for a forecast's boundary label (「予測 →」). */
|
|
1279
|
+
const FORECAST_LABEL_ROOM = 18
|
|
1280
|
+
|
|
1281
|
+
/**
|
|
1282
|
+
* Which side of the forecast boundary line the flat boundary label reads from: `"left"` starts at the line and runs
|
|
1283
|
+
* over the forecast side; `"right"` ends at the line and runs over the actuals, when the forecast side (the room right
|
|
1284
|
+
* of the line, grid margin included) is narrower than the text, so it never runs off the chart.
|
|
1285
|
+
* `forecastSpan` is `null` when the width is unknown.
|
|
1286
|
+
*/
|
|
1287
|
+
function forecastLabelAlign(forecastSpan: number | null, text: string = forecastBoundaryText()): "left" | "right" {
|
|
1288
|
+
return forecastSpan !== null && forecastSpan >= estimateTextWidth(text) + 8 ? "left" : "right"
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
/** ECharts' "nice" tick step for a raw step (1 / 2 / 3 / 5 × 10ⁿ, rounded): the same rule its value axis uses. */
|
|
1292
|
+
function niceStep(raw: number): number {
|
|
1293
|
+
if (!(raw > 0) || !Number.isFinite(raw)) return 1
|
|
1294
|
+
const exp10 = 10 ** Math.floor(Math.log10(raw))
|
|
1295
|
+
const f = raw / exp10
|
|
1296
|
+
return (f < 1.5 ? 1 : f < 2.5 ? 2 : f < 4 ? 3 : f < 7 ? 5 : 10) * exp10
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
/**
|
|
1300
|
+
* The largest tick (by size) a value axis over `[lo, hi]` will carry once ECharts has niced its ends — the number
|
|
1301
|
+
* that decides the unit the ticks read in (`resolveAxisTickFormatter`). `max`, when fixed, is the axis' top as is.
|
|
1302
|
+
*/
|
|
1303
|
+
function estimateAxisTop(lo: number, hi: number, splitNumber: number, max?: number): number {
|
|
1304
|
+
const top = Math.max(Math.abs(lo), Math.abs(hi))
|
|
1305
|
+
if (!(top > 0)) return 0
|
|
1306
|
+
const step = niceStep((hi - lo) / splitNumber)
|
|
1307
|
+
const niceHi = max !== undefined && max >= hi ? max : Math.ceil(hi / step) * step
|
|
1308
|
+
const niceLo = Math.floor(lo / step) * step
|
|
1309
|
+
return Math.max(Math.abs(niceHi), Math.abs(niceLo))
|
|
1310
|
+
}
|
|
1311
|
+
|
|
1312
|
+
/** Plot heights (px) under this carry 3 value intervals, not 4–5. */
|
|
1313
|
+
const SHORT_PLOT_HEIGHT = 200
|
|
1314
|
+
/** Plot heights under this carry 4 value intervals; taller ones 5. */
|
|
1315
|
+
const TALL_PLOT_HEIGHT = 300
|
|
1316
|
+
/** The plot height assumed when it isn't known (the charts' default `height`). */
|
|
1317
|
+
const ASSUMED_PLOT_HEIGHT = 288
|
|
1318
|
+
|
|
1319
|
+
/** How many intervals a vertical value axis carries: 3 under 200px of plot height, 4 under 300px, else 5. */
|
|
1320
|
+
function valueAxisSplitCount(plotHeight: number = ASSUMED_PLOT_HEIGHT): number {
|
|
1321
|
+
return plotHeight < SHORT_PLOT_HEIGHT ? 3 : plotHeight < TALL_PLOT_HEIGHT ? 4 : 5
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
/** The grain of time-like x values (`"month"` for `2026-04`), or `null` when they aren't plain years / months / days. */
|
|
1325
|
+
function indexGrain(values: readonly unknown[]): PeriodGrain | null {
|
|
1326
|
+
const parsed = parseTimeIndex(values)
|
|
1327
|
+
return parsed ? parsed.granularity : null
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/**
|
|
1331
|
+
* The tooltip line under the main series' row when a comparison series is drawn: the arrow, the signed change and the
|
|
1332
|
+
* comparison's name, as `Delta` writes it ("↑ +12.4% 前年同月比"; a minus is U+2212). "比較なし 前年同月比" when
|
|
1333
|
+
* either value is missing or the baseline is 0.
|
|
1334
|
+
*/
|
|
1335
|
+
function comparisonNote(
|
|
1336
|
+
current: number | null,
|
|
1337
|
+
previous: number | null,
|
|
1338
|
+
comparison: Pick<CartesianComparisonConfig, "vs" | "label">,
|
|
1339
|
+
grain?: PeriodGrain,
|
|
1340
|
+
format?: ValueFormat,
|
|
1341
|
+
locale: string = DEFAULT_LOCALE,
|
|
1342
|
+
): string {
|
|
1343
|
+
const result = computeComparison(
|
|
1344
|
+
current,
|
|
1345
|
+
comparison.vs === "custom"
|
|
1346
|
+
? { previous, vs: "custom", label: comparison.label ?? "", grain }
|
|
1347
|
+
: { previous, vs: comparison.vs, label: comparison.label, grain },
|
|
1348
|
+
)
|
|
1349
|
+
const text = formatChange(result, defaultChangeDisplay(format), locale, format)
|
|
1350
|
+
if (text === null) return `比較なし ${result.label}`
|
|
1351
|
+
const arrow = result.direction === "up" ? "↑" : result.direction === "down" ? "↓" : "→"
|
|
1352
|
+
return `${arrow} ${text.replace(/^-/, "−")} ${result.label}`
|
|
1353
|
+
}
|
|
1354
|
+
|
|
1355
|
+
/** Bars and areas start at 0: the length / area *is* the value. */
|
|
1356
|
+
const zeroBasedMin = (extent: AxisExtent) => Math.min(0, extent.min)
|
|
1357
|
+
|
|
1358
|
+
/**
|
|
1359
|
+
* A value axis' `min` / `max` from the limits a caller asked for, so that charts shown side by side can share one scale.
|
|
1360
|
+
* A limit never cuts the data: when the data runs past it, the axis widens to the data (`max(maxValue, data max)`).
|
|
1361
|
+
* `zeroBased` (bars, areas, waterfall): the axis always reaches 0, so a `minValue` above 0 is ignored and only a
|
|
1362
|
+
* negative one (room below 0) takes effect. Without a limit asked for, that edge is `undefined` (ECharts' own choice)
|
|
1363
|
+
* — except a zero-based `min`, which is always given.
|
|
1364
|
+
*/
|
|
1365
|
+
function valueAxisLimits(
|
|
1366
|
+
limits: { minValue?: number; maxValue?: number },
|
|
1367
|
+
zeroBased: boolean,
|
|
1368
|
+
): { min: ((extent: AxisExtent) => number) | undefined; max: ((extent: AxisExtent) => number) | undefined } {
|
|
1369
|
+
const lo = Number.isFinite(limits.minValue) ? limits.minValue : undefined
|
|
1370
|
+
const hi = Number.isFinite(limits.maxValue) ? limits.maxValue : undefined
|
|
1371
|
+
return {
|
|
1372
|
+
min: zeroBased
|
|
1373
|
+
? (extent) => Math.min(0, lo ?? 0, extent.min)
|
|
1374
|
+
: lo === undefined
|
|
1375
|
+
? undefined
|
|
1376
|
+
: (extent) => Math.min(lo, extent.min),
|
|
1377
|
+
max: hi === undefined ? undefined : (extent) => Math.max(hi, extent.max),
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
function buildCartesianOption(cfg: CartesianChartConfig): EChartsOption {
|
|
1382
|
+
const {
|
|
1383
|
+
kind,
|
|
1384
|
+
data,
|
|
1385
|
+
index,
|
|
1386
|
+
categories,
|
|
1387
|
+
palette,
|
|
1388
|
+
labels: nameLabels,
|
|
1389
|
+
thresholds,
|
|
1390
|
+
toneColors,
|
|
1391
|
+
valueFormatter,
|
|
1392
|
+
axisFormatter = valueFormatter,
|
|
1393
|
+
locale = DEFAULT_LOCALE,
|
|
1394
|
+
type = "default",
|
|
1395
|
+
layout = "horizontal",
|
|
1396
|
+
curveType = "linear",
|
|
1397
|
+
fill = "gradient",
|
|
1398
|
+
connectNulls = false,
|
|
1399
|
+
showLegend = true,
|
|
1400
|
+
showTooltip = true,
|
|
1401
|
+
showGridLines = true,
|
|
1402
|
+
showXAxis = true,
|
|
1403
|
+
showYAxis = true,
|
|
1404
|
+
startEndOnly = false,
|
|
1405
|
+
yAxisWidth,
|
|
1406
|
+
minValue,
|
|
1407
|
+
maxValue,
|
|
1408
|
+
autoMinValue = false,
|
|
1409
|
+
fitToData,
|
|
1410
|
+
allowDecimals = true,
|
|
1411
|
+
xAxisLabel,
|
|
1412
|
+
yAxisLabel,
|
|
1413
|
+
barCategoryGap,
|
|
1414
|
+
showDots = false,
|
|
1415
|
+
active = null,
|
|
1416
|
+
target,
|
|
1417
|
+
targetLabel,
|
|
1418
|
+
targetLabelPosition = "start",
|
|
1419
|
+
targetKey,
|
|
1420
|
+
showZeroValues = true,
|
|
1421
|
+
guideColor,
|
|
1422
|
+
labelBackground,
|
|
1423
|
+
labelColor,
|
|
1424
|
+
plotWidth,
|
|
1425
|
+
plotHeight,
|
|
1426
|
+
reducedMotion = false,
|
|
1427
|
+
chartOptions,
|
|
1428
|
+
reserveActions = false,
|
|
1429
|
+
} = cfg
|
|
1430
|
+
const provisionalLabel = cfg.provisionalLabel ?? DEFAULT_PROVISIONAL_LABEL
|
|
1431
|
+
|
|
1432
|
+
const stacked = kind !== "line" && type !== "default"
|
|
1433
|
+
const percent = kind !== "line" && type === "percent"
|
|
1434
|
+
const horizontalBars = kind === "bar" && layout === "vertical"
|
|
1435
|
+
/*
|
|
1436
|
+
* -- comparison: a plain line, outside the stack and the palette. Never with bars or a 100% stack
|
|
1437
|
+
* (shares of a total have no "last year" line).
|
|
1438
|
+
*/
|
|
1439
|
+
const comparison = kind !== "bar" && !percent ? cfg.comparison : undefined
|
|
1440
|
+
const compIdx = comparison ? categories.indexOf(comparison.category) : -1
|
|
1441
|
+
/** Positions of the series that are not the comparison: the stack, the highlight and the forecast read these. */
|
|
1442
|
+
const mainIdx = categories.map((_, i) => i).filter((i) => i !== compIdx)
|
|
1443
|
+
const seriesType = kind === "line" ? "default" : type
|
|
1444
|
+
const values = (() => {
|
|
1445
|
+
if (compIdx === -1) return cartesianSeriesValues(data, categories, seriesType)
|
|
1446
|
+
const main = cartesianSeriesValues(data, mainIdx.map((i) => categories[i]!), seriesType)
|
|
1447
|
+
const compared = cartesianSeriesValues(data, [categories[compIdx]!], "default")[0]!
|
|
1448
|
+
return categories.map((_, i) => (i === compIdx ? compared : main[mainIdx.indexOf(i)]!))
|
|
1449
|
+
})()
|
|
1450
|
+
const comparisonColor = guideColor ? withAlpha(guideColor, COMPARISON_OPACITY) : undefined
|
|
1451
|
+
|
|
1452
|
+
/* -- x labels: the actual rows, then the forecast rows that extend them */
|
|
1453
|
+
const labels = data.map((row) => String(row[index] ?? ""))
|
|
1454
|
+
const rawIndex: unknown[] = data.map((row) => row[index])
|
|
1455
|
+
const lastActual = labels.length - 1
|
|
1456
|
+
// First provisional point (-1: none). Looked up among the actual rows only; unrelated to `forecast`.
|
|
1457
|
+
const provStart = categories.length > 0 ? provisionalStart(rawIndex, cfg.provisionalFrom) : -1
|
|
1458
|
+
const forecast =
|
|
1459
|
+
kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 && data.length > 0 && categories.length > 0
|
|
1460
|
+
? cfg.forecast
|
|
1461
|
+
: undefined
|
|
1462
|
+
const forecastAt: number[] = []
|
|
1463
|
+
if (forecast) {
|
|
1464
|
+
const position = new Map(labels.map((label, i) => [label, i]))
|
|
1465
|
+
for (const row of forecast.data) {
|
|
1466
|
+
const label = String(row[index] ?? "")
|
|
1467
|
+
let at = position.get(label)
|
|
1468
|
+
if (at === undefined || at <= lastActual) {
|
|
1469
|
+
// A forecast row never overwrites an actual point; repeated labels append.
|
|
1470
|
+
at = labels.length
|
|
1471
|
+
labels.push(label)
|
|
1472
|
+
rawIndex.push(row[index])
|
|
1473
|
+
position.set(label, at)
|
|
1474
|
+
}
|
|
1475
|
+
forecastAt.push(at)
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
const pad = (series: (number | null)[]) =>
|
|
1479
|
+
series.length < labels.length ? [...series, ...Array<null>(labels.length - series.length).fill(null)] : series
|
|
1480
|
+
const last = labels.length - 1
|
|
1481
|
+
/*
|
|
1482
|
+
* -- time-like x values read as dates in the locale (`4月`, `2026年1月`), at a
|
|
1483
|
+
* fixed calendar step so the year-change label is never thinned away.
|
|
1484
|
+
*/
|
|
1485
|
+
const timeStep = startEndOnly
|
|
1486
|
+
? null
|
|
1487
|
+
: timeAxisLabelStep(
|
|
1488
|
+
rawIndex,
|
|
1489
|
+
plotWidth ? Math.max(2, Math.min(TIME_AXIS_MAX_LABELS, Math.floor(plotWidth / TIME_LABEL_WIDTH))) : undefined,
|
|
1490
|
+
)
|
|
1491
|
+
// Plain (non-date) x labels of a line chart: thinned to every n-th so they never touch, never rotated.
|
|
1492
|
+
const plainStep = (() => {
|
|
1493
|
+
if (kind !== "line" || startEndOnly || timeStep !== null || !plotWidth || labels.length < 3) return 1
|
|
1494
|
+
const widest = Math.max(...labels.map((l) => estimateTextWidth(nameLabels && hasLabel(nameLabels, l) ? labelOf(l, nameLabels) : l)))
|
|
1495
|
+
const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN)
|
|
1496
|
+
return Math.max(1, Math.ceil(((widest + 12) * (labels.length - 1)) / plot))
|
|
1497
|
+
})()
|
|
1498
|
+
const shownLabel = startEndOnly
|
|
1499
|
+
? (i: number) => i === 0 || i === last
|
|
1500
|
+
: timeStep !== null
|
|
1501
|
+
? (i: number) => i % timeStep === 0
|
|
1502
|
+
: plainStep > 1
|
|
1503
|
+
? (i: number) => i % plainStep === 0
|
|
1504
|
+
: null
|
|
1505
|
+
const timeLabels = timeAxisLabels(rawIndex, locale, shownLabel ?? undefined)
|
|
1506
|
+
const compGrain = comparison ? (indexGrain(rawIndex.slice(0, lastActual + 1)) ?? undefined) : undefined
|
|
1507
|
+
const tooltipTitles = (timeTooltipLabels(rawIndex, locale) ?? labels).map((title, i) =>
|
|
1508
|
+
nameLabels ? (hasLabel(nameLabels, labels[i] ?? "") ? labelOf(labels[i] ?? "", nameLabels) : title) : title,
|
|
1509
|
+
)
|
|
1510
|
+
|
|
1511
|
+
/*
|
|
1512
|
+
* -- highlight: max + latest. Normal stacking labels the stack's total (on the
|
|
1513
|
+
* top layer); otherwise the first series, ≤ 2 series. A 100% stacked area
|
|
1514
|
+
* labels the first series' (the bottom band's) first and latest share inside
|
|
1515
|
+
* the band; a 100% stacked bar labels nothing.
|
|
1516
|
+
*/
|
|
1517
|
+
const highlight = cfg.highlight ?? defaultChartHighlight(kind, data, index)
|
|
1518
|
+
const stackTotals = stacked && !percent ? stackTotalsOf(mainIdx.map((i) => values[i]!)) : null
|
|
1519
|
+
const highlightSeries = (stackTotals ? mainIdx[mainIdx.length - 1] : mainIdx[0]) ?? 0
|
|
1520
|
+
const shareHighlight = percent && kind === "area"
|
|
1521
|
+
const picked =
|
|
1522
|
+
highlight !== "auto" || mainIdx.length === 0 || (percent && !shareHighlight)
|
|
1523
|
+
? []
|
|
1524
|
+
: shareHighlight
|
|
1525
|
+
? categories.length <= 2
|
|
1526
|
+
? pickShareHighlightPoints(values[0] ?? [])
|
|
1527
|
+
: []
|
|
1528
|
+
: stackTotals
|
|
1529
|
+
? pickHighlightPoints(stackTotals)
|
|
1530
|
+
: mainIdx.length <= 2
|
|
1531
|
+
? pickHighlightPoints(values[highlightSeries] ?? [])
|
|
1532
|
+
: []
|
|
1533
|
+
// On a narrow plot the max and the latest label would print over each other: keep the latest.
|
|
1534
|
+
const pointGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
|
|
1535
|
+
const highlightPoints =
|
|
1536
|
+
picked.length === 2 && pointGap !== null && Math.abs(picked[1]!.index - picked[0]!.index) * pointGap < HIGHLIGHT_LABEL_WIDTH
|
|
1537
|
+
? [picked[1]!]
|
|
1538
|
+
: picked
|
|
1539
|
+
|
|
1540
|
+
/*
|
|
1541
|
+
* Points (and the outer bars) sit at the plot's edges: pull the first / last
|
|
1542
|
+
* label inward so it isn't clipped. A label on the forecast boundary sits left
|
|
1543
|
+
* of the boundary line instead of across it.
|
|
1544
|
+
*/
|
|
1545
|
+
const boundaryIndex = kind !== "bar" && !percent && cfg.forecast && cfg.forecast.data.length > 0 ? lastActual : -1
|
|
1546
|
+
const edgeAlign = (i: number) =>
|
|
1547
|
+
horizontalBars || labels.length < 2
|
|
1548
|
+
? undefined
|
|
1549
|
+
: i === boundaryIndex && i !== last
|
|
1550
|
+
? { align: "right" as const, offset: [-6, 0] }
|
|
1551
|
+
: i === last
|
|
1552
|
+
? { align: "right" as const, ...(kind === "bar" ? { offset: [8, 0] } : {}) }
|
|
1553
|
+
: i === 0
|
|
1554
|
+
? { align: "left" as const, ...(kind === "bar" ? { offset: [-8, 0] } : {}) }
|
|
1555
|
+
: undefined
|
|
1556
|
+
|
|
1557
|
+
/*
|
|
1558
|
+
* The target label sits at the plot's start (left), above its line, so it stays clear of the latest value's label at
|
|
1559
|
+
* the right end. Near the label (horizontally, estimated from `plotWidth`) a line / area highlight just under the
|
|
1560
|
+
* target prints below its point, and one just over it moves the target label under the line instead. On a plot
|
|
1561
|
+
* narrower than 480px, when the *latest* point's label would still run into the target label, the target label leaves
|
|
1562
|
+
* the line altogether — the legend names the target.
|
|
1563
|
+
*/
|
|
1564
|
+
// `barOptions.targetKey` (a target per bar) takes over from the single `target` line.
|
|
1565
|
+
const perBarTarget = kind === "bar" && Boolean(targetKey)
|
|
1566
|
+
const hasTarget = !perBarTarget && target !== undefined && Number.isFinite(target)
|
|
1567
|
+
const targetText = hasTarget ? (targetLabel ?? `目標 ${axisFormatter(target)}`) : ""
|
|
1568
|
+
const highlightText = (value: number) =>
|
|
1569
|
+
shareHighlight ? `${Math.round(value)}%` : `${stackTotals ? `${STACK_TOTAL_LABEL} ` : ""}${axisFormatter(value)}`
|
|
1570
|
+
/** Whether `p`'s label sits within the target's value band and under the target label (at the right end). */
|
|
1571
|
+
const nearTargetLabel = (p: HighlightPoint, side: "under" | "over") => {
|
|
1572
|
+
if (!hasTarget || !plotWidth || kind === "bar" || labels.length < 2) return false
|
|
1573
|
+
if (side === "under" ? p.value > target : p.value <= target) return false
|
|
1574
|
+
const scale = Math.max(Math.abs(target), ...highlightPoints.map((h) => Math.abs(h.value)))
|
|
1575
|
+
if (scale === 0 || Math.abs(target - p.value) / scale > TARGET_NEAR_SHARE) return false
|
|
1576
|
+
const plot = Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - 32)
|
|
1577
|
+
const x = (p.index / (labels.length - 1)) * plot
|
|
1578
|
+
const w = estimateTextWidth(highlightText(p.value)) + 8
|
|
1579
|
+
const align = edgeAlign(p.index)?.align
|
|
1580
|
+
const left = align === "right" ? x - w - 6 : align === "left" ? x : x - w / 2
|
|
1581
|
+
return left < estimateTextWidth(targetText) + 8 + LABEL_SLACK
|
|
1582
|
+
}
|
|
1583
|
+
const hideTargetLabel =
|
|
1584
|
+
(kind === "line" && targetLabelPosition === "legend") ||
|
|
1585
|
+
!shareHighlight &&
|
|
1586
|
+
plotWidth !== undefined &&
|
|
1587
|
+
plotWidth < TARGET_LABEL_NARROW_WIDTH &&
|
|
1588
|
+
highlightPoints.some((p) => p.index === labels.length - 1 && (nearTargetLabel(p, "under") || nearTargetLabel(p, "over")))
|
|
1589
|
+
const below = (p: HighlightPoint) => !shareHighlight && !hideTargetLabel && nearTargetLabel(p, "under")
|
|
1590
|
+
const targetLabelBelow = !shareHighlight && !hideTargetLabel && highlightPoints.some((p) => nearTargetLabel(p, "over"))
|
|
1591
|
+
|
|
1592
|
+
// One series (or a stack, against its total) can be compared to a target; grouped series and 100% stacks cannot.
|
|
1593
|
+
const barTargets: (number | null)[] | null =
|
|
1594
|
+
perBarTarget && targetKey && !percent && (stacked || categories.length === 1) ? barTargetValues(data, targetKey) : null
|
|
1595
|
+
const barTargetName = targetLabel ?? BAR_TARGET_LABEL
|
|
1596
|
+
const barTargetColor = labelColor ?? guideColor
|
|
1597
|
+
|
|
1598
|
+
const markPointFor = (c: number, color: string | undefined) =>
|
|
1599
|
+
c === highlightSeries && highlightPoints.length > 0
|
|
1600
|
+
? {
|
|
1601
|
+
silent: true,
|
|
1602
|
+
symbol: "circle",
|
|
1603
|
+
symbolSize: kind === "bar" ? 0 : 7,
|
|
1604
|
+
itemStyle: { color, borderColor: "transparent" },
|
|
1605
|
+
label: {
|
|
1606
|
+
show: true,
|
|
1607
|
+
position: horizontalBars ? ("right" as const) : ("top" as const),
|
|
1608
|
+
distance: 6,
|
|
1609
|
+
fontSize: 12,
|
|
1610
|
+
fontWeight: 500,
|
|
1611
|
+
color: labelColor,
|
|
1612
|
+
...(labelBackground ? { backgroundColor: labelBackground, padding: [2, 4], borderRadius: 2 } : {}),
|
|
1613
|
+
formatter: (p: { value?: unknown }) => highlightText(Number(p.value)),
|
|
1614
|
+
},
|
|
1615
|
+
data: highlightPoints.map((p) => {
|
|
1616
|
+
// Below the point; on the forecast boundary, on the forecast side (the actual line comes in from the left).
|
|
1617
|
+
const label = shareHighlight
|
|
1618
|
+
? // Inside the bottom band, under its upper edge: the label reads as that band's share.
|
|
1619
|
+
{ ...edgeAlign(p.index), position: "bottom" as const }
|
|
1620
|
+
: below(p)
|
|
1621
|
+
? p.index === boundaryIndex && p.index !== last
|
|
1622
|
+
? { position: "bottom" as const, align: "left" as const, offset: [6, 0] }
|
|
1623
|
+
: { ...edgeAlign(p.index), position: "bottom" as const }
|
|
1624
|
+
: edgeAlign(p.index)
|
|
1625
|
+
return {
|
|
1626
|
+
name: p.kind,
|
|
1627
|
+
value: p.value,
|
|
1628
|
+
coord: horizontalBars ? [p.value, p.index] : [p.index, p.value],
|
|
1629
|
+
...(label ? { label } : {}),
|
|
1630
|
+
}
|
|
1631
|
+
}),
|
|
1632
|
+
}
|
|
1633
|
+
: undefined
|
|
1634
|
+
|
|
1635
|
+
// Threshold colours: bars side by side (one series or several). A stacked segment is a part, not a level to judge, so stacks keep their series colours.
|
|
1636
|
+
const byValue = kind === "bar" && !stacked && Boolean(thresholds?.length)
|
|
1637
|
+
const multiSeries = categories.length > 1
|
|
1638
|
+
// Horizontal bars of one series read light; only the highlighted bar is solid (the one the page is about).
|
|
1639
|
+
const lightBars = kind === "bar" && horizontalBars && !stacked && !multiSeries
|
|
1640
|
+
const series: Record<string, unknown>[] = categories.map((category, c) => {
|
|
1641
|
+
const solid = palette[c] || undefined
|
|
1642
|
+
const color = lightBars && solid ? withAlpha(solid, LIGHT_BAR_ALPHA) : solid
|
|
1643
|
+
const dimSeries = active !== null && active.category !== category
|
|
1644
|
+
const seriesData = pad(values[c]!)
|
|
1645
|
+
if (kind === "bar") {
|
|
1646
|
+
const rounded = horizontalBars ? [0, 4, 4, 0] : [4, 4, 0, 0]
|
|
1647
|
+
// Stacked: only the topmost segment is rounded.
|
|
1648
|
+
const radius = stacked && c !== categories.length - 1 ? 0 : rounded
|
|
1649
|
+
return {
|
|
1650
|
+
id: SERIES_ID_PREFIX + category,
|
|
1651
|
+
type: "bar" as const,
|
|
1652
|
+
name: category,
|
|
1653
|
+
stack: stacked ? "total" : undefined,
|
|
1654
|
+
barCategoryGap,
|
|
1655
|
+
itemStyle: { color, borderRadius: radius },
|
|
1656
|
+
markPoint: markPointFor(c, solid),
|
|
1657
|
+
markLine: undefined,
|
|
1658
|
+
data: seriesData.map((value, i) => {
|
|
1659
|
+
const tone = byValue ? toneForValue(value, thresholds) : undefined
|
|
1660
|
+
const toneColor = tone ? toneColors?.[tone] || undefined : undefined
|
|
1661
|
+
const isHighlight = lightBars && cfg.barHighlight !== undefined && String(rawIndex[i]) === String(cfg.barHighlight)
|
|
1662
|
+
const dimmed = active !== null && !(active.category === category && active.index === i)
|
|
1663
|
+
// Provisional bars: lighter fill and a dashed edge, never the solid look of a confirmed bar.
|
|
1664
|
+
const provisional = provStart !== -1 && i >= provStart && i <= lastActual
|
|
1665
|
+
const zeroLabel =
|
|
1666
|
+
showZeroValues && !stacked && value === 0
|
|
1667
|
+
? {
|
|
1668
|
+
show: true,
|
|
1669
|
+
position: horizontalBars ? ("right" as const) : ("top" as const),
|
|
1670
|
+
distance: 4,
|
|
1671
|
+
fontSize: 12,
|
|
1672
|
+
color: labelColor,
|
|
1673
|
+
formatter: () => axisFormatter(0),
|
|
1674
|
+
}
|
|
1675
|
+
: undefined
|
|
1676
|
+
if (!dimmed && !toneColor && !isHighlight && !provisional && !zeroLabel) return value
|
|
1677
|
+
return {
|
|
1678
|
+
value,
|
|
1679
|
+
...(zeroLabel ? { label: zeroLabel } : {}),
|
|
1680
|
+
itemStyle: {
|
|
1681
|
+
...(isHighlight && solid ? { color: solid } : {}),
|
|
1682
|
+
...(toneColor ? { color: toneColor } : {}),
|
|
1683
|
+
// Several series: the series colour stays on the edge so the legend still points at the bar.
|
|
1684
|
+
...(toneColor && multiSeries && color && !provisional ? { borderColor: color, borderWidth: 2 } : {}),
|
|
1685
|
+
...(provisional ? { opacity: PROVISIONAL_OPACITY, borderColor: toneColor ?? color, borderWidth: 1, borderType: "dashed" as const } : {}),
|
|
1686
|
+
...(dimmed ? { opacity: DIMMED } : {}),
|
|
1687
|
+
},
|
|
1688
|
+
}
|
|
1689
|
+
}),
|
|
1690
|
+
}
|
|
1691
|
+
}
|
|
1692
|
+
if (c === compIdx) {
|
|
1693
|
+
// The comparison: thin, muted, solid, no markers, no fill, never stacked — behind the main series.
|
|
1694
|
+
return {
|
|
1695
|
+
id: SERIES_ID_PREFIX + category,
|
|
1696
|
+
type: "line" as const,
|
|
1697
|
+
name: category,
|
|
1698
|
+
z: 1,
|
|
1699
|
+
smooth: curveType === "smooth",
|
|
1700
|
+
step: curveType === "step" ? ("middle" as const) : undefined,
|
|
1701
|
+
connectNulls,
|
|
1702
|
+
symbol: "none",
|
|
1703
|
+
showSymbol: false,
|
|
1704
|
+
lineStyle: { width: COMPARISON_LINE_WIDTH, type: "solid" as const, color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
|
|
1705
|
+
itemStyle: { color: comparisonColor, opacity: dimSeries ? DIMMED : 1 },
|
|
1706
|
+
areaStyle: undefined,
|
|
1707
|
+
markPoint: undefined,
|
|
1708
|
+
markLine: undefined,
|
|
1709
|
+
data: seriesData,
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
const areaStyle =
|
|
1713
|
+
kind !== "area" || fill === "none"
|
|
1714
|
+
? undefined
|
|
1715
|
+
: fill === "solid" || !color
|
|
1716
|
+
? { opacity: fill === "solid" ? 0.3 : 0.2 }
|
|
1717
|
+
: {
|
|
1718
|
+
color: {
|
|
1719
|
+
type: "linear" as const,
|
|
1720
|
+
x: 0,
|
|
1721
|
+
y: 0,
|
|
1722
|
+
x2: 0,
|
|
1723
|
+
y2: 1,
|
|
1724
|
+
colorStops: [
|
|
1725
|
+
{ offset: 0, color: withAlpha(color, 0.28) },
|
|
1726
|
+
{ offset: 1, color: withAlpha(color, 0) },
|
|
1727
|
+
],
|
|
1728
|
+
},
|
|
1729
|
+
}
|
|
1730
|
+
return {
|
|
1731
|
+
id: SERIES_ID_PREFIX + category,
|
|
1732
|
+
type: "line" as const,
|
|
1733
|
+
name: category,
|
|
1734
|
+
stack: stacked ? "total" : undefined,
|
|
1735
|
+
smooth: curveType === "smooth",
|
|
1736
|
+
step: curveType === "step" ? ("middle" as const) : undefined,
|
|
1737
|
+
connectNulls,
|
|
1738
|
+
symbol: "circle",
|
|
1739
|
+
symbolSize: 6,
|
|
1740
|
+
showSymbol: showDots || data.length === 1,
|
|
1741
|
+
// 100% stacked: the top band's upper edge is the 100% line, not a value — drawn, it reads as「this band = 100%」.
|
|
1742
|
+
lineStyle:
|
|
1743
|
+
percent && c === categories.length - 1
|
|
1744
|
+
? { width: 0, color, opacity: 0 }
|
|
1745
|
+
: { width: 2, color, opacity: dimSeries ? DIMMED : 1 },
|
|
1746
|
+
itemStyle: { color, opacity: dimSeries ? DIMMED : 1 },
|
|
1747
|
+
areaStyle: areaStyle && dimSeries ? { ...areaStyle, opacity: DIMMED * 0.3 } : areaStyle,
|
|
1748
|
+
markPoint: markPointFor(c, color),
|
|
1749
|
+
markLine: undefined,
|
|
1750
|
+
data: provStart === -1 ? seriesData : splitProvisional(seriesData, provStart).confirmed,
|
|
1751
|
+
}
|
|
1752
|
+
})
|
|
1753
|
+
|
|
1754
|
+
/* -- provisional: a dashed, lighter continuation of every series from `provStart`, joined to the last confirmed point */
|
|
1755
|
+
if (kind !== "bar" && provStart !== -1) {
|
|
1756
|
+
categories.forEach((category, c) => {
|
|
1757
|
+
// The comparison is not provisional: it keeps its own line to the end.
|
|
1758
|
+
if (c === compIdx) return
|
|
1759
|
+
const color = palette[c] || undefined
|
|
1760
|
+
const dimSeries = active !== null && active.category !== category
|
|
1761
|
+
const solid = series[c] as { areaStyle?: { opacity?: number } }
|
|
1762
|
+
const opacity = (dimSeries ? DIMMED : 1) * PROVISIONAL_OPACITY
|
|
1763
|
+
series.push({
|
|
1764
|
+
id: PROVISIONAL_SERIES_PREFIX + category,
|
|
1765
|
+
type: "line" as const,
|
|
1766
|
+
name: provisionalLabel,
|
|
1767
|
+
// Its own stack: the joint point repeats the confirmed value and must not pile onto it.
|
|
1768
|
+
stack: stacked ? "provisional" : undefined,
|
|
1769
|
+
smooth: curveType === "smooth",
|
|
1770
|
+
step: curveType === "step" ? ("middle" as const) : undefined,
|
|
1771
|
+
connectNulls: false,
|
|
1772
|
+
symbol: "circle",
|
|
1773
|
+
symbolSize: 6,
|
|
1774
|
+
showSymbol: showDots || data.length === 1,
|
|
1775
|
+
lineStyle:
|
|
1776
|
+
percent && c === categories.length - 1
|
|
1777
|
+
? { width: 0, color, opacity: 0 }
|
|
1778
|
+
: { width: 2, type: "dashed" as const, color, opacity },
|
|
1779
|
+
itemStyle: { color, opacity },
|
|
1780
|
+
areaStyle: solid.areaStyle ? { ...solid.areaStyle, opacity: (solid.areaStyle.opacity ?? 1) * PROVISIONAL_OPACITY } : undefined,
|
|
1781
|
+
markPoint: undefined,
|
|
1782
|
+
markLine: undefined,
|
|
1783
|
+
data: splitProvisional(pad(values[c]!), provStart).provisional,
|
|
1784
|
+
})
|
|
1785
|
+
})
|
|
1786
|
+
}
|
|
1787
|
+
// A bar legend entry for the provisional style (an empty line series: it takes no bar slot).
|
|
1788
|
+
if (kind === "bar" && provStart !== -1) {
|
|
1789
|
+
series.push({
|
|
1790
|
+
id: PROVISIONAL_SERIES_PREFIX + "legend",
|
|
1791
|
+
type: "line" as const,
|
|
1792
|
+
name: provisionalLabel,
|
|
1793
|
+
silent: true,
|
|
1794
|
+
symbol: "none",
|
|
1795
|
+
showSymbol: false,
|
|
1796
|
+
tooltip: { show: false },
|
|
1797
|
+
legendHoverLink: false,
|
|
1798
|
+
lineStyle: { opacity: 0 },
|
|
1799
|
+
itemStyle: { color: palette[0] || undefined, opacity: PROVISIONAL_OPACITY },
|
|
1800
|
+
markPoint: undefined,
|
|
1801
|
+
markLine: undefined,
|
|
1802
|
+
data: [],
|
|
1803
|
+
})
|
|
1804
|
+
}
|
|
1805
|
+
|
|
1806
|
+
/* -- forecast: dashed continuation (+ optional band) of one series */
|
|
1807
|
+
const forecastLabel = forecast?.label ?? DEFAULT_FORECAST_LABEL
|
|
1808
|
+
const forecastBandAlpha = isDarkSurface(labelBackground) ? FORECAST_BAND_ALPHA_DARK : FORECAST_BAND_ALPHA_LIGHT
|
|
1809
|
+
const forecastValues: (number | null)[] = []
|
|
1810
|
+
if (forecast) {
|
|
1811
|
+
const category =
|
|
1812
|
+
forecast.category !== undefined && categories.includes(forecast.category) && forecast.category !== comparison?.category
|
|
1813
|
+
? forecast.category
|
|
1814
|
+
: categories[mainIdx[0] ?? 0]!
|
|
1815
|
+
const c = categories.indexOf(category)
|
|
1816
|
+
const color = palette[c] || undefined
|
|
1817
|
+
const actual = values[c]!
|
|
1818
|
+
let start = -1
|
|
1819
|
+
for (let i = actual.length - 1; i >= 0; i--) {
|
|
1820
|
+
if (actual[i] !== null) {
|
|
1821
|
+
start = i
|
|
1822
|
+
break
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
const line: (number | null)[] = Array<null>(labels.length).fill(null)
|
|
1826
|
+
const lower: (number | null)[] = Array<null>(labels.length).fill(null)
|
|
1827
|
+
const range: (number | null)[] = Array<null>(labels.length).fill(null)
|
|
1828
|
+
if (start !== -1) {
|
|
1829
|
+
line[start] = actual[start]!
|
|
1830
|
+
lower[start] = actual[start]!
|
|
1831
|
+
range[start] = 0
|
|
1832
|
+
}
|
|
1833
|
+
let hasBand = false
|
|
1834
|
+
forecast.data.forEach((row: ChartForecastRow, k) => {
|
|
1835
|
+
const at = forecastAt[k]!
|
|
1836
|
+
line[at] = cellNumber(row.value)
|
|
1837
|
+
const lo = cellNumber(row.lower)
|
|
1838
|
+
const hi = cellNumber(row.upper)
|
|
1839
|
+
if (lo !== null && hi !== null) {
|
|
1840
|
+
hasBand = true
|
|
1841
|
+
lower[at] = Math.min(lo, hi)
|
|
1842
|
+
range[at] = Math.abs(hi - lo)
|
|
1843
|
+
}
|
|
1844
|
+
})
|
|
1845
|
+
forecastValues.push(...line)
|
|
1846
|
+
const helper = {
|
|
1847
|
+
type: "line" as const,
|
|
1848
|
+
silent: true,
|
|
1849
|
+
symbol: "none",
|
|
1850
|
+
showSymbol: false,
|
|
1851
|
+
connectNulls: true,
|
|
1852
|
+
tooltip: { show: false },
|
|
1853
|
+
legendHoverLink: false,
|
|
1854
|
+
emphasis: { disabled: true },
|
|
1855
|
+
markPoint: undefined,
|
|
1856
|
+
markLine: undefined,
|
|
1857
|
+
}
|
|
1858
|
+
if (hasBand) {
|
|
1859
|
+
series.push(
|
|
1860
|
+
{
|
|
1861
|
+
...helper,
|
|
1862
|
+
id: FORECAST_BAND_BASE_ID,
|
|
1863
|
+
name: FORECAST_BAND_BASE_ID,
|
|
1864
|
+
stack: FORECAST_BAND_BASE_ID,
|
|
1865
|
+
lineStyle: { opacity: 0 },
|
|
1866
|
+
areaStyle: undefined,
|
|
1867
|
+
data: lower,
|
|
1868
|
+
},
|
|
1869
|
+
{
|
|
1870
|
+
...helper,
|
|
1871
|
+
id: FORECAST_BAND_RANGE_ID,
|
|
1872
|
+
name: FORECAST_BAND_RANGE_ID,
|
|
1873
|
+
stack: FORECAST_BAND_BASE_ID,
|
|
1874
|
+
lineStyle: { opacity: 0 },
|
|
1875
|
+
areaStyle: color ? { color: withAlpha(color, forecastBandAlpha), opacity: 1 } : { opacity: forecastBandAlpha },
|
|
1876
|
+
data: range,
|
|
1877
|
+
},
|
|
1878
|
+
)
|
|
1879
|
+
}
|
|
1880
|
+
series.push({
|
|
1881
|
+
...helper,
|
|
1882
|
+
id: FORECAST_SERIES_ID,
|
|
1883
|
+
name: forecastLabel,
|
|
1884
|
+
silent: false,
|
|
1885
|
+
tooltip: undefined,
|
|
1886
|
+
emphasis: undefined,
|
|
1887
|
+
smooth: curveType === "smooth",
|
|
1888
|
+
// Always dashed (2px, 6-4) and lighter — a forecast must never read as a measurement, nor as the 1px dotted target.
|
|
1889
|
+
lineStyle: { width: 2, type: FORECAST_LINE_DASH, color, opacity: 0.7 },
|
|
1890
|
+
itemStyle: { color, opacity: 0.7 },
|
|
1891
|
+
areaStyle: undefined,
|
|
1892
|
+
data: line,
|
|
1893
|
+
})
|
|
1894
|
+
}
|
|
1895
|
+
|
|
1896
|
+
/* -- overlay: target line, forecast boundary, and the extent that keeps the target on the axis */
|
|
1897
|
+
/**
|
|
1898
|
+
* Horizontal bars: the target line is vertical and its label lies flat above the plot, centred
|
|
1899
|
+
* on the line — unless that would run past the plot's right (or left) edge, e.g. a target near
|
|
1900
|
+
* the axis max on a narrow chart; then it hangs to the line's left (right) instead. The axis max
|
|
1901
|
+
* is estimated from the data (ECharts rounds it up, which only moves the line left of the guess).
|
|
1902
|
+
*/
|
|
1903
|
+
const horizontalTargetAlign = ((): "left" | "center" | "right" => {
|
|
1904
|
+
if (!horizontalBars || !hasTarget) return "center"
|
|
1905
|
+
const totals = labels.map((_, i) =>
|
|
1906
|
+
stacked
|
|
1907
|
+
? values.reduce((sum, v) => sum + Math.max(0, v[i] ?? 0), 0)
|
|
1908
|
+
: Math.max(0, ...values.map((v) => v[i] ?? 0)),
|
|
1909
|
+
)
|
|
1910
|
+
const top = percent ? 100 : (maxValue ?? Math.max(target, ...totals))
|
|
1911
|
+
if (!(top > 0)) return "center"
|
|
1912
|
+
const ratio = Math.min(1, Math.max(0, target / top))
|
|
1913
|
+
const half = (estimateTextWidth(targetText) + 8) / 2
|
|
1914
|
+
if (!plotWidth) return ratio > 0.85 ? "right" : ratio < 0.15 ? "left" : "center"
|
|
1915
|
+
const right = highlightPoints.length > 0 ? 64 : 16
|
|
1916
|
+
const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
|
|
1917
|
+
const plot = Math.max(1, plotWidth - categoryColumn - right - 4)
|
|
1918
|
+
const at = ratio * plot
|
|
1919
|
+
if (plot - at + right < half) return "right"
|
|
1920
|
+
if (at + categoryColumn < half) return "left"
|
|
1921
|
+
return "center"
|
|
1922
|
+
})()
|
|
1923
|
+
const markLines: unknown[] = []
|
|
1924
|
+
const markAreas: unknown[] = []
|
|
1925
|
+
if (hasTarget && target !== undefined) {
|
|
1926
|
+
markLines.push({
|
|
1927
|
+
name: "target",
|
|
1928
|
+
[horizontalBars ? "xAxis" : "yAxis"]: target,
|
|
1929
|
+
// 1px dotted — the forecast is 2px dashed, so the two never read as one line.
|
|
1930
|
+
lineStyle: { type: TARGET_LINE_DASH, width: 1, color: guideColor },
|
|
1931
|
+
label: {
|
|
1932
|
+
show: !hideTargetLabel,
|
|
1933
|
+
// The start (left) of the line, above it — under it when a highlight sits just above the target there.
|
|
1934
|
+
// Horizontal bars: the line is vertical, so the label goes flat above its top end, outside the plot (no rotation, clear of the bars).
|
|
1935
|
+
// The category axis is inverted there (first row on top), so the line runs top → bottom and its top end is the *start*.
|
|
1936
|
+
position: horizontalBars
|
|
1937
|
+
? "start"
|
|
1938
|
+
: kind === "line" && targetLabelPosition === "end"
|
|
1939
|
+
? "insideEndTop"
|
|
1940
|
+
: targetLabelBelow
|
|
1941
|
+
? "insideStartBottom"
|
|
1942
|
+
: "insideStartTop",
|
|
1943
|
+
...(horizontalBars ? { rotate: 0, align: horizontalTargetAlign, verticalAlign: "bottom" as const, distance: 4 } : {}),
|
|
1944
|
+
color: guideColor,
|
|
1945
|
+
formatter: targetText,
|
|
1946
|
+
},
|
|
1947
|
+
})
|
|
1948
|
+
}
|
|
1949
|
+
if (forecast) {
|
|
1950
|
+
const forecastSpan =
|
|
1951
|
+
plotWidth && labels.length > 1
|
|
1952
|
+
? (Math.max(1, plotWidth - (showYAxis ? (yAxisWidth ?? Y_AXIS_ESTIMATE) : 0) - LINE_RIGHT_MARGIN) / (labels.length - 1)) *
|
|
1953
|
+
(labels.length - 1 - lastActual) +
|
|
1954
|
+
LINE_RIGHT_MARGIN
|
|
1955
|
+
: null
|
|
1956
|
+
markLines.push({
|
|
1957
|
+
name: "forecast-boundary",
|
|
1958
|
+
xAxis: lastActual,
|
|
1959
|
+
lineStyle: { type: "dashed", width: 1, color: guideColor },
|
|
1960
|
+
// Flat (text-xs, muted), just above the plot's top edge at the top of the line (`grid.top` makes the room; the legend
|
|
1961
|
+
// sits above that): along the line at its foot it ran into the x axis labels on a narrow chart.
|
|
1962
|
+
label: {
|
|
1963
|
+
show: true,
|
|
1964
|
+
position: "end",
|
|
1965
|
+
rotate: 0,
|
|
1966
|
+
align: forecastLabelAlign(forecastSpan, forecastBoundaryText(forecastLabel)),
|
|
1967
|
+
verticalAlign: "bottom" as const,
|
|
1968
|
+
distance: 4,
|
|
1969
|
+
fontSize: 12,
|
|
1970
|
+
color: guideColor,
|
|
1971
|
+
formatter: forecastBoundaryText(forecastLabel),
|
|
1972
|
+
},
|
|
1973
|
+
})
|
|
1974
|
+
}
|
|
1975
|
+
/* -- annotations: a thin neutral line, or a faint band for a range, on the category axis (vertical layouts only) */
|
|
1976
|
+
const notes = horizontalBars ? [] : resolveAnnotations(cfg.annotations, rawIndex)
|
|
1977
|
+
const noteGap = plotWidth && labels.length > 1 ? plotWidth / (kind === "bar" ? labels.length : labels.length - 1) : null
|
|
1978
|
+
if (notes.length > 0) {
|
|
1979
|
+
const singles = notes.filter((n) => n.to === undefined)
|
|
1980
|
+
const ends = annotationLabelEnds(singles.map((n) => n.from), noteGap)
|
|
1981
|
+
const background = labelBackground ? { backgroundColor: labelBackground, padding: [1, 3], borderRadius: 2 } : {}
|
|
1982
|
+
singles.forEach((note, k) => {
|
|
1983
|
+
markLines.push({
|
|
1984
|
+
name: `annotation:${note.label}`,
|
|
1985
|
+
xAxis: note.from,
|
|
1986
|
+
lineStyle: { type: "solid", width: 1, color: guideColor },
|
|
1987
|
+
// Along the line, at the top (the legend sits above the plot) or at its foot when a neighbour is close.
|
|
1988
|
+
label: {
|
|
1989
|
+
show: true,
|
|
1990
|
+
position: ends[k] === "top" ? "insideEndTop" : "insideStartBottom",
|
|
1991
|
+
color: guideColor,
|
|
1992
|
+
...background,
|
|
1993
|
+
formatter: note.label,
|
|
1994
|
+
},
|
|
1995
|
+
})
|
|
1996
|
+
})
|
|
1997
|
+
const over = kind === "bar" ? 0.5 : 0
|
|
1998
|
+
for (const note of notes) {
|
|
1999
|
+
if (note.to === undefined) continue
|
|
2000
|
+
const widthPx = noteGap === null ? null : (note.to - note.from + (kind === "bar" ? 1 : 0)) * noteGap
|
|
2001
|
+
const fits = widthPx === null ? [...note.label].length <= 6 : estimateTextWidth(note.label) + 8 <= widthPx
|
|
2002
|
+
markAreas.push([
|
|
2003
|
+
{
|
|
2004
|
+
name: note.label,
|
|
2005
|
+
xAxis: note.from - over,
|
|
2006
|
+
itemStyle: { color: guideColor ? withAlpha(guideColor, 0.12) : undefined },
|
|
2007
|
+
// The band's foot (bars: just above the plot — inside, the text would run into the value label of a tall bar,
|
|
2008
|
+
// and `grid.top` makes the room); a band narrower than its text reads the text upright along the band instead.
|
|
2009
|
+
label: {
|
|
2010
|
+
show: true,
|
|
2011
|
+
position: kind === "bar" ? "top" : fits ? "insideBottom" : "inside",
|
|
2012
|
+
rotate: fits ? 0 : 90,
|
|
2013
|
+
color: guideColor,
|
|
2014
|
+
fontSize: 12,
|
|
2015
|
+
formatter: note.label,
|
|
2016
|
+
},
|
|
2017
|
+
},
|
|
2018
|
+
{ xAxis: note.to + over },
|
|
2019
|
+
])
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
// The target is a legend entry too (an empty line series carries the name): the line may lose its label on a narrow plot.
|
|
2023
|
+
if (hasTarget) {
|
|
2024
|
+
series.push({
|
|
2025
|
+
id: TARGET_LEGEND_SERIES_ID,
|
|
2026
|
+
type: "line" as const,
|
|
2027
|
+
name: targetText,
|
|
2028
|
+
silent: true,
|
|
2029
|
+
symbol: "none",
|
|
2030
|
+
showSymbol: false,
|
|
2031
|
+
tooltip: { show: false },
|
|
2032
|
+
legendHoverLink: false,
|
|
2033
|
+
emphasis: { disabled: true },
|
|
2034
|
+
lineStyle: { opacity: 0 },
|
|
2035
|
+
itemStyle: { color: guideColor },
|
|
2036
|
+
markPoint: undefined,
|
|
2037
|
+
markLine: undefined,
|
|
2038
|
+
data: [],
|
|
2039
|
+
})
|
|
2040
|
+
}
|
|
2041
|
+
if (markLines.length > 0 || markAreas.length > 0) {
|
|
2042
|
+
series.push({
|
|
2043
|
+
id: OVERLAY_SERIES_ID,
|
|
2044
|
+
name: OVERLAY_SERIES_ID,
|
|
2045
|
+
type: "line" as const,
|
|
2046
|
+
silent: true,
|
|
2047
|
+
symbol: "none",
|
|
2048
|
+
showSymbol: false,
|
|
2049
|
+
tooltip: { show: false },
|
|
2050
|
+
legendHoverLink: false,
|
|
2051
|
+
emphasis: { disabled: true },
|
|
2052
|
+
lineStyle: { opacity: 0 },
|
|
2053
|
+
itemStyle: { color: guideColor },
|
|
2054
|
+
// A single invisible point at the target, so the value axis always reaches it.
|
|
2055
|
+
data: labels.map((_, i) => (i === 0 && hasTarget && target !== undefined ? target : null)),
|
|
2056
|
+
markPoint: undefined,
|
|
2057
|
+
// `precision`: ECharts rounds a mark line's value to 2 decimals by default (a 0.035 target would land on 0.04 — off a fitted axis,
|
|
2058
|
+
// where the line is then dropped). `z` keeps the guide lines above the series' own lines.
|
|
2059
|
+
markLine: markLines.length > 0 ? { silent: true, symbol: "none", animation: false, precision: 20, z: 6, data: markLines } : undefined,
|
|
2060
|
+
markArea: markAreas.length > 0 ? { silent: true, animation: false, data: markAreas } : undefined,
|
|
2061
|
+
})
|
|
2062
|
+
}
|
|
2063
|
+
/*
|
|
2064
|
+
* -- per-bar targets: a short marker across each bar at its target. A custom
|
|
2065
|
+
* series (the marker's length follows the bar's width, in px, whatever the chart's
|
|
2066
|
+
* size) whose data also keeps the value axis reaching the largest target. It is
|
|
2067
|
+
* the legend's entry too: the marker is named, with a tick as its icon.
|
|
2068
|
+
*/
|
|
2069
|
+
if (barTargets) {
|
|
2070
|
+
series.push({
|
|
2071
|
+
id: TARGET_MARKER_SERIES_ID,
|
|
2072
|
+
type: "custom" as const,
|
|
2073
|
+
name: barTargetName,
|
|
2074
|
+
silent: true,
|
|
2075
|
+
animation: false,
|
|
2076
|
+
z: 5,
|
|
2077
|
+
tooltip: { show: false },
|
|
2078
|
+
legendHoverLink: false,
|
|
2079
|
+
emphasis: { disabled: true },
|
|
2080
|
+
itemStyle: { color: barTargetColor },
|
|
2081
|
+
encode: { x: 0, y: 1 },
|
|
2082
|
+
data: barTargets.flatMap((value, i) => (value === null ? [] : [horizontalBars ? [value, i] : [i, value]])),
|
|
2083
|
+
renderItem: targetMarkerRenderer(horizontalBars, barCategoryGap, barTargetColor),
|
|
2084
|
+
})
|
|
2085
|
+
}
|
|
2086
|
+
|
|
2087
|
+
const categoryAxis = {
|
|
2088
|
+
id: horizontalBars ? "y" : "x",
|
|
2089
|
+
type: "category" as const,
|
|
2090
|
+
data: labels,
|
|
2091
|
+
show: horizontalBars ? showYAxis : showXAxis,
|
|
2092
|
+
boundaryGap: kind === "bar",
|
|
2093
|
+
inverse: horizontalBars,
|
|
2094
|
+
axisTick: { show: false },
|
|
2095
|
+
axisLabel: {
|
|
2096
|
+
hideOverlap: true,
|
|
2097
|
+
rotate: kind === "line" ? 0 : undefined,
|
|
2098
|
+
interval: shownLabel ?? ("auto" as const),
|
|
2099
|
+
formatter:
|
|
2100
|
+
timeLabels || nameLabels
|
|
2101
|
+
? (value: string, i: number) => {
|
|
2102
|
+
const time = timeLabels?.[i]
|
|
2103
|
+
if (time === "") return ""
|
|
2104
|
+
return hasLabel(nameLabels, value) ? labelOf(value, nameLabels) : (time ?? value)
|
|
2105
|
+
}
|
|
2106
|
+
: undefined,
|
|
2107
|
+
width: horizontalBars ? yAxisWidth : undefined,
|
|
2108
|
+
overflow: horizontalBars && yAxisWidth != null ? ("truncate" as const) : undefined,
|
|
2109
|
+
},
|
|
2110
|
+
name: horizontalBars ? yAxisLabel : xAxisLabel,
|
|
2111
|
+
nameLocation: "middle" as const,
|
|
2112
|
+
nameGap: horizontalBars ? (yAxisWidth ?? 48) + 8 : 28,
|
|
2113
|
+
}
|
|
2114
|
+
const fit = kind === "line" && (fitToData ?? autoMinValue)
|
|
2115
|
+
// A horizontal bar chart's value ticks run along the (narrow) width: as many as fit side by side.
|
|
2116
|
+
const valueSplitNumber = (() => {
|
|
2117
|
+
if (!horizontalBars || !plotWidth) return undefined
|
|
2118
|
+
const top = percent
|
|
2119
|
+
? 100
|
|
2120
|
+
: (maxValue ?? Math.max(0, ...(stacked ? stackTotalsOf(values) : values.flat()).map((v) => v ?? 0)))
|
|
2121
|
+
const categoryColumn = showYAxis ? (yAxisWidth ?? Math.min(160, Math.max(0, ...labels.map(estimateTextWidth)))) + 8 : 0
|
|
2122
|
+
const plot = plotWidth - categoryColumn - (highlightPoints.length > 0 ? 64 : 16) - 4
|
|
2123
|
+
const text = percent ? (v: number) => `${v}%` : (v: number) => axisFormatter(v)
|
|
2124
|
+
return valueAxisSplitNumber(plot, [text(0), text(top)])
|
|
2125
|
+
})()
|
|
2126
|
+
const limits = valueAxisLimits({ minValue, maxValue }, kind !== "line")
|
|
2127
|
+
// Vertical value axes carry 3 intervals on a short plot, else 4–5 (a horizontal bar chart's follows its width, above).
|
|
2128
|
+
const splitNumber = horizontalBars ? valueSplitNumber : valueAxisSplitCount(plotHeight)
|
|
2129
|
+
/*
|
|
2130
|
+
* Ticks read in one unit — the unit of the axis' largest tick (¥0.5億 / ¥1億, never ¥5,000万 beside ¥1億). The largest
|
|
2131
|
+
* tick is estimated from the data the way ECharts nices its ends.
|
|
2132
|
+
*/
|
|
2133
|
+
const tickFormatter = (() => {
|
|
2134
|
+
if (!cfg.axisTicks || percent) return axisFormatter
|
|
2135
|
+
const extentValues: number[] = []
|
|
2136
|
+
const addAll = (list: readonly (number | null)[]) => {
|
|
2137
|
+
for (const v of list) if (v !== null && Number.isFinite(v)) extentValues.push(v)
|
|
2138
|
+
}
|
|
2139
|
+
if (stackTotals) addAll(stackTotals)
|
|
2140
|
+
else values.forEach(addAll)
|
|
2141
|
+
addAll(forecastValues)
|
|
2142
|
+
if (forecast) addAll(forecast.data.flatMap((row) => [cellNumber(row.lower), cellNumber(row.upper)]))
|
|
2143
|
+
if (barTargets) addAll(barTargets)
|
|
2144
|
+
if (hasTarget && target !== undefined) extentValues.push(target)
|
|
2145
|
+
if (maxValue !== undefined && Number.isFinite(maxValue)) extentValues.push(maxValue)
|
|
2146
|
+
if (minValue !== undefined && Number.isFinite(minValue)) extentValues.push(minValue)
|
|
2147
|
+
if (extentValues.length === 0) return axisFormatter
|
|
2148
|
+
const zeroBased = kind !== "line" || !fit
|
|
2149
|
+
const hi = Math.max(...extentValues, zeroBased ? 0 : -Infinity)
|
|
2150
|
+
const lo = Math.min(...extentValues, zeroBased ? 0 : Infinity)
|
|
2151
|
+
return cfg.axisTicks(estimateAxisTop(lo, hi, splitNumber ?? 5, maxValue !== undefined && Number.isFinite(maxValue) ? maxValue : undefined))
|
|
2152
|
+
})()
|
|
2153
|
+
const valueAxis = {
|
|
2154
|
+
id: horizontalBars ? "x" : "y",
|
|
2155
|
+
type: "value" as const,
|
|
2156
|
+
show: horizontalBars ? showXAxis : showYAxis,
|
|
2157
|
+
// Bars and areas always start at 0 (a positive `minValue` can't lift them, a negative one makes room below);
|
|
2158
|
+
// lines do too unless asked to fit the data. A limit never cuts the data: the axis widens to it.
|
|
2159
|
+
min: percent ? 0 : kind === "line" ? (minValue === undefined ? (fit ? undefined : zeroBasedMin) : limits.min) : limits.min,
|
|
2160
|
+
max: percent ? 100 : limits.max,
|
|
2161
|
+
scale: fit && minValue == null,
|
|
2162
|
+
splitNumber,
|
|
2163
|
+
minInterval: allowDecimals ? undefined : 1,
|
|
2164
|
+
axisLine: { show: false },
|
|
2165
|
+
axisTick: { show: false },
|
|
2166
|
+
splitLine: { show: showGridLines },
|
|
2167
|
+
axisLabel: {
|
|
2168
|
+
formatter: percent ? (v: number) => `${v}%` : (v: number) => tickFormatter(v),
|
|
2169
|
+
// Fitted to the data: the lowest tick would print over the first x label at the bottom left. The gridline stays.
|
|
2170
|
+
showMinLabel: fit && minValue == null && !horizontalBars ? false : undefined,
|
|
2171
|
+
// Horizontal: ticks that would still touch on a narrow plot are dropped.
|
|
2172
|
+
hideOverlap: horizontalBars ? true : undefined,
|
|
2173
|
+
// A fixed width lines up side-by-side plots, but a value tick is never cut: the grid contains it.
|
|
2174
|
+
width: horizontalBars ? undefined : yAxisWidth,
|
|
2175
|
+
},
|
|
2176
|
+
name: horizontalBars ? xAxisLabel : yAxisLabel,
|
|
2177
|
+
nameLocation: "middle" as const,
|
|
2178
|
+
nameGap: horizontalBars ? 28 : (yAxisWidth ?? 48) + 8,
|
|
2179
|
+
}
|
|
2180
|
+
|
|
2181
|
+
const legendItems = [
|
|
2182
|
+
...categories,
|
|
2183
|
+
...(forecast ? [forecastLabel] : []),
|
|
2184
|
+
...(provStart !== -1 ? [provisionalLabel] : []),
|
|
2185
|
+
...(barTargets ? [barTargetName] : []),
|
|
2186
|
+
...(hasTarget ? [targetText] : []),
|
|
2187
|
+
]
|
|
2188
|
+
const option = {
|
|
2189
|
+
...chartMotion(reducedMotion),
|
|
2190
|
+
legend: {
|
|
2191
|
+
show: showLegend,
|
|
2192
|
+
top: 0,
|
|
2193
|
+
right: reserveActions ? ACTIONS_RESERVE : 0,
|
|
2194
|
+
// Plain wraps onto a second line at narrow widths instead of hiding items behind arrows.
|
|
2195
|
+
type: "plain",
|
|
2196
|
+
icon: "circle",
|
|
2197
|
+
itemWidth: 8,
|
|
2198
|
+
itemHeight: 8,
|
|
2199
|
+
itemGap: 16,
|
|
2200
|
+
// The target marker is a tick, not a dot.
|
|
2201
|
+
// The target is a row of dots and the forecast a row of dashes — their lines' patterns — and a per-bar target a tick.
|
|
2202
|
+
data: legendItems.map((name) =>
|
|
2203
|
+
barTargets && name === barTargetName
|
|
2204
|
+
? { name, icon: TARGET_LEGEND_ICON }
|
|
2205
|
+
: forecast && name === forecastLabel
|
|
2206
|
+
? { name, icon: FORECAST_DASHED_ICON }
|
|
2207
|
+
: hasTarget && name === targetText
|
|
2208
|
+
? { name, icon: TARGET_DOTTED_ICON }
|
|
2209
|
+
: name,
|
|
2210
|
+
),
|
|
2211
|
+
formatter: nameLabels ? (name: string) => labelOf(name, nameLabels) : undefined,
|
|
2212
|
+
},
|
|
2213
|
+
grid: {
|
|
2214
|
+
top:
|
|
2215
|
+
(showLegend ? 12 + LEGEND_LINE_HEIGHT * legendLines(legendItems, plotWidth, reserveActions ? ACTIONS_RESERVE : 0) : 12) +
|
|
2216
|
+
// The flat target label of a horizontal bar chart sits above the plot.
|
|
2217
|
+
(horizontalBars && hasTarget ? 18 : 0) +
|
|
2218
|
+
// The label of a band over bars sits above the plot's top edge.
|
|
2219
|
+
(kind === "bar" && notes.some((n) => n.to !== undefined) ? BAND_LABEL_ROOM : 0) +
|
|
2220
|
+
// The boundary label of a forecast sits above the plot's top edge too.
|
|
2221
|
+
(forecast ? FORECAST_LABEL_ROOM : 0),
|
|
2222
|
+
// Lines start and end on the outermost ticks, so the last x label (and an edge
|
|
2223
|
+
// highlight) hangs past the plot; a horizontal bar's highlight sits past its end.
|
|
2224
|
+
right: horizontalBars ? (highlightPoints.length > 0 ? 64 : 16) : kind === "bar" ? 16 : LINE_RIGHT_MARGIN,
|
|
2225
|
+
bottom: xAxisLabel ? 24 : 4,
|
|
2226
|
+
left: yAxisLabel ? 24 : 4,
|
|
2227
|
+
containLabel: true,
|
|
2228
|
+
},
|
|
2229
|
+
tooltip: {
|
|
2230
|
+
show: showTooltip,
|
|
2231
|
+
trigger: "axis",
|
|
2232
|
+
axisPointer: { type: kind === "bar" ? "shadow" : "line" },
|
|
2233
|
+
formatter: (params: unknown) => {
|
|
2234
|
+
const list = (Array.isArray(params) ? params : [params]) as AxisTooltipParam[]
|
|
2235
|
+
const i = list[0]?.dataIndex ?? 0
|
|
2236
|
+
const row = i <= lastActual ? (data[i] ?? {}) : {}
|
|
2237
|
+
const rows: TooltipRow[] = []
|
|
2238
|
+
// The main series' difference from the comparison: one muted line under its row.
|
|
2239
|
+
const primary = mainIdx[0]
|
|
2240
|
+
const noteFor = (at: number): { note?: string } => {
|
|
2241
|
+
if (!comparison || compIdx === -1 || at !== primary || i > lastActual) return {}
|
|
2242
|
+
return {
|
|
2243
|
+
note: comparisonNote(
|
|
2244
|
+
cellNumber(row[categories[at]!]),
|
|
2245
|
+
cellNumber(row[comparison.category]),
|
|
2246
|
+
comparison,
|
|
2247
|
+
compGrain,
|
|
2248
|
+
cfg.comparisonFormat,
|
|
2249
|
+
locale,
|
|
2250
|
+
),
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
2253
|
+
const shares = percent ? cartesianSeriesValues(i <= lastActual ? [row] : [], categories, "percent") : null
|
|
2254
|
+
for (const p of list) {
|
|
2255
|
+
const color = typeof p.color === "string" ? p.color : "currentColor"
|
|
2256
|
+
if (p.seriesId === FORECAST_SERIES_ID) {
|
|
2257
|
+
// At and before the boundary the forecast repeats the actual value.
|
|
2258
|
+
if (i > lastActual) rows.push({ name: p.seriesName ?? forecastLabel, color, value: forecastValues[i] ?? null })
|
|
2259
|
+
continue
|
|
2260
|
+
}
|
|
2261
|
+
if (p.seriesId?.startsWith("__")) continue
|
|
2262
|
+
if (i > lastActual) continue
|
|
2263
|
+
const name = p.seriesName ?? ""
|
|
2264
|
+
const at = categories.indexOf(name)
|
|
2265
|
+
const share = shares && at !== -1 ? (shares[at]![0] ?? undefined) : undefined
|
|
2266
|
+
rows.push({
|
|
2267
|
+
name: labelOf(name, nameLabels),
|
|
2268
|
+
color: at === compIdx ? (comparisonColor ?? color) : color,
|
|
2269
|
+
value: cellNumber(row[name]),
|
|
2270
|
+
...(share !== undefined ? { share } : {}),
|
|
2271
|
+
...(at !== -1 ? noteFor(at) : {}),
|
|
2272
|
+
})
|
|
2273
|
+
}
|
|
2274
|
+
if (stackTotals && i <= lastActual && rows.length > 1) {
|
|
2275
|
+
rows.push({ name: STACK_TOTAL_LABEL, color: "transparent", value: stackTotals[i] ?? null })
|
|
2276
|
+
}
|
|
2277
|
+
const provisional = provStart !== -1 && i >= provStart && i <= lastActual
|
|
2278
|
+
if (provisional) {
|
|
2279
|
+
// The confirmed series are empty here: rows come from the data, under a 「速報」 title.
|
|
2280
|
+
rows.length = 0
|
|
2281
|
+
categories.forEach((name, at) => {
|
|
2282
|
+
const share = shares ? (shares[at]![0] ?? undefined) : undefined
|
|
2283
|
+
rows.push({
|
|
2284
|
+
name,
|
|
2285
|
+
color: at === compIdx ? (comparisonColor ?? "currentColor") : palette[at] || "currentColor",
|
|
2286
|
+
value: cellNumber(row[name]),
|
|
2287
|
+
...(share !== undefined ? { share } : {}),
|
|
2288
|
+
...noteFor(at),
|
|
2289
|
+
})
|
|
2290
|
+
})
|
|
2291
|
+
if (stackTotals && rows.length > 1) rows.push({ name: STACK_TOTAL_LABEL, color: "transparent", value: stackTotals[i] ?? null })
|
|
2292
|
+
}
|
|
2293
|
+
const title = tooltipTitles[i] ?? labels[i] ?? ""
|
|
2294
|
+
const lines: string[] = []
|
|
2295
|
+
if (barTargets && i <= lastActual) {
|
|
2296
|
+
const total = stackTotals ? (stackTotals[i] ?? null) : (values[0]?.[i] ?? null)
|
|
2297
|
+
const note = barTargetNote(barTargetName, total, barTargets[i] ?? null, valueFormatter)
|
|
2298
|
+
if (note) lines.push(note)
|
|
2299
|
+
}
|
|
2300
|
+
for (const note of notes) {
|
|
2301
|
+
if (note.to === undefined ? note.from === i : note.from <= i && i <= note.to) lines.push(note.label)
|
|
2302
|
+
}
|
|
2303
|
+
return tooltipHtml(provisional ? `${title}(${provisionalLabel})` : title, rows, valueFormatter, lines)
|
|
2304
|
+
},
|
|
2305
|
+
},
|
|
2306
|
+
xAxis: horizontalBars ? valueAxis : categoryAxis,
|
|
2307
|
+
yAxis: horizontalBars ? categoryAxis : valueAxis,
|
|
2308
|
+
series,
|
|
2309
|
+
}
|
|
2310
|
+
return mergeChartOptions(option as EChartsOption, chartOptions)
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2313
|
+
/* ------------------------------------------------------------------ donut */
|
|
2314
|
+
|
|
2315
|
+
type DonutVariant = "donut" | "pie"
|
|
2316
|
+
|
|
2317
|
+
/** What the donut prints in its hole (`donutOptions.centerLabel`). */
|
|
2318
|
+
type DonutCenterLabel = "none" | "total" | "top"
|
|
2319
|
+
|
|
2320
|
+
/**
|
|
2321
|
+
* The center of the donut as one of the three built-ins or a custom node.
|
|
2322
|
+
* Default `"none"`; the legacy `showLabel` (`false` → none, an explicit `true` →
|
|
2323
|
+
* total, the old default) and `label` (a custom node) still win over the default.
|
|
2324
|
+
*/
|
|
2325
|
+
function resolveDonutCenter(
|
|
2326
|
+
centerLabel: DonutChartOptions["centerLabel"],
|
|
2327
|
+
{ showLabel, label }: { showLabel?: boolean; label?: ReactNode } = {},
|
|
2328
|
+
): { kind: DonutCenterLabel } | { kind: "custom"; node: ReactNode } {
|
|
2329
|
+
if (showLabel === false) return { kind: "none" }
|
|
2330
|
+
if (centerLabel === "none") return { kind: "none" }
|
|
2331
|
+
if (centerLabel === "total") return { kind: "total" }
|
|
2332
|
+
if (centerLabel === "top") return { kind: "top" }
|
|
2333
|
+
if (centerLabel !== undefined && centerLabel !== null && centerLabel !== false) return { kind: "custom", node: centerLabel }
|
|
2334
|
+
if (label !== undefined && label !== null && label !== false) return { kind: "custom", node: label }
|
|
2335
|
+
return { kind: showLabel === true ? "total" : "none" }
|
|
2336
|
+
}
|
|
2337
|
+
|
|
2338
|
+
/** Below this plot width (px) the outside labels can't fit beside the ring. */
|
|
2339
|
+
const DONUT_OUTSIDE_LABEL_MIN_WIDTH = 440
|
|
2340
|
+
|
|
2341
|
+
/**
|
|
2342
|
+
* How many slices get an outside label. A share is printed once: the legend
|
|
2343
|
+
* carries every slice's share, so with a legend there are no outside labels;
|
|
2344
|
+
* without one the 2 largest are labelled when the plot is wide enough
|
|
2345
|
+
* (`plotWidth` `null` = not measured yet → labelled).
|
|
2346
|
+
*/
|
|
2347
|
+
function donutOutsideLabelCount(plotWidth: number | null, showLegend: boolean): number {
|
|
2348
|
+
if (showLegend) return 0
|
|
2349
|
+
return plotWidth !== null && plotWidth < DONUT_OUTSIDE_LABEL_MIN_WIDTH ? 0 : DONUT_OUTSIDE_LABELS
|
|
2350
|
+
}
|
|
2351
|
+
|
|
2352
|
+
/** The `"top"` center: the largest real slice's name (`label`) and share (`amount`); `null` when there is none. */
|
|
2353
|
+
function donutTopText(
|
|
2354
|
+
slices: readonly DonutOptionSlice[],
|
|
2355
|
+
labels?: Readonly<Record<string, string>>,
|
|
2356
|
+
): { label: string; amount: string } | null {
|
|
2357
|
+
const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
|
|
2358
|
+
const top = [...slices].filter((s) => !s.isOther && sliceValue(s.value) > 0).sort((a, b) => sliceValue(b.value) - sliceValue(a.value))[0]
|
|
2359
|
+
return top ? { label: labelOf(top.name, labels), amount: donutShareText(top.value, total) } : null
|
|
2360
|
+
}
|
|
2361
|
+
|
|
2362
|
+
/** DonutChart-only settings. */
|
|
2363
|
+
interface DonutChartOptions {
|
|
2364
|
+
/** `"donut"`(中央に穴とラベル)か `"pie"`。既定 `"donut"`。 */
|
|
2365
|
+
variant?: DonutVariant
|
|
2366
|
+
/** @deprecated `centerLabel` を使う。`false` は `centerLabel: "none"` と同じ。`true` を明示すると `"total"` 扱い(以前の既定)。 */
|
|
2367
|
+
showLabel?: boolean
|
|
2368
|
+
/**
|
|
2369
|
+
* 穴の中央に出すもの。`"none"`(既定。何も出さない。合計は KPI と重複しがち)/ `"total"`(「合計」と
|
|
2370
|
+
* 合計を書式化した値。`totalLabel` / `unit` を添える)/ `"top"`(最大の切片の名前と構成比)。
|
|
2371
|
+
* それ以外のノードを渡すとそのまま中央に置く。donut のみ。
|
|
2372
|
+
*/
|
|
2373
|
+
centerLabel?: DonutCenterLabel | ReactNode
|
|
2374
|
+
/** 中央ラベルの見出し(何の合計か)。既定「合計」。 */
|
|
2375
|
+
totalLabel?: string
|
|
2376
|
+
/** 中央ラベルの合計に添える単位(`"セッション"` → 「9.2万 セッション」)。 */
|
|
2377
|
+
unit?: string
|
|
2378
|
+
/** 凡例(名前と構成比、大きい順)を出す。広いときは右、狭いときは下。既定 `true`。構成比は凡例だけが持つ(凡例を消すと、広いときだけ大きい 2 切片に外ラベルで名前と構成比が出る)。 */
|
|
2379
|
+
showLegend?: boolean
|
|
2380
|
+
/** 個別に描く切片の数。超えた分は大きさ順の残りを「その他」1 切片にまとめる。既定 5。 */
|
|
2381
|
+
maxSlices?: number
|
|
2382
|
+
}
|
|
2383
|
+
|
|
2384
|
+
/** A slice as the builder takes it: already sorted, folded and coloured (see `donutSlices`). */
|
|
2385
|
+
interface DonutOptionSlice {
|
|
2386
|
+
name: string
|
|
2387
|
+
value: number
|
|
2388
|
+
/** The folded「その他」slice: never labelled outside. */
|
|
2389
|
+
isOther?: boolean
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
/** How many of the largest slices get an outside label (「自然検索 41%」) by default. */
|
|
2393
|
+
const DONUT_OUTSIDE_LABELS = 2
|
|
2394
|
+
|
|
2395
|
+
const DEFAULT_TOTAL_LABEL = "合計"
|
|
2396
|
+
|
|
2397
|
+
const sliceValue = (value: number) => (Number.isFinite(value) && value > 0 ? value : 0)
|
|
2398
|
+
|
|
2399
|
+
/** A slice's share of `total` as text: whole percent, `<1%` for a sliver, `0%` for nothing. */
|
|
2400
|
+
function donutShareText(value: number, total: number): string {
|
|
2401
|
+
const v = sliceValue(value)
|
|
2402
|
+
if (total <= 0 || v === 0) return "0%"
|
|
2403
|
+
const pct = (v / total) * 100
|
|
2404
|
+
return pct < 1 ? "<1%" : `${Math.round(pct)}%`
|
|
2405
|
+
}
|
|
2406
|
+
|
|
2407
|
+
/** One legend row: name, share text and the slice's position (for its colour). */
|
|
2408
|
+
interface DonutLegendItem {
|
|
2409
|
+
name: string
|
|
2410
|
+
value: number
|
|
2411
|
+
share: string
|
|
2412
|
+
isOther: boolean
|
|
2413
|
+
/** Index into the slices / palette. */
|
|
2414
|
+
slice: number
|
|
2415
|
+
}
|
|
2416
|
+
|
|
2417
|
+
/**
|
|
2418
|
+
* The donut legend: every slice with its share, largest first, the folded
|
|
2419
|
+
* 「その他」 last (it is a remainder, not a rank).
|
|
2420
|
+
*/
|
|
2421
|
+
function donutLegendItems(slices: readonly DonutOptionSlice[]): DonutLegendItem[] {
|
|
2422
|
+
const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
|
|
2423
|
+
return slices
|
|
2424
|
+
.map((s, slice) => ({ name: s.name, value: sliceValue(s.value), share: donutShareText(s.value, total), isOther: Boolean(s.isOther), slice }))
|
|
2425
|
+
.sort((a, b) => Number(a.isOther) - Number(b.isOther) || b.value - a.value || a.slice - b.slice)
|
|
2426
|
+
}
|
|
2427
|
+
|
|
2428
|
+
/**
|
|
2429
|
+
* The default center label: what is totalled (「合計」), the formatted total
|
|
2430
|
+
* (`amount`, the big line), the unit (a small line under it) and both as one
|
|
2431
|
+
* string (`value`, 「9.2万 セッション」).
|
|
2432
|
+
*/
|
|
2433
|
+
function donutCenterText(
|
|
2434
|
+
total: number,
|
|
2435
|
+
valueFormatter: (value: number) => string,
|
|
2436
|
+
{ totalLabel = DEFAULT_TOTAL_LABEL, unit }: { totalLabel?: string; unit?: string } = {},
|
|
2437
|
+
): { label: string; value: string; amount: string; unit?: string } {
|
|
2438
|
+
const amount = valueFormatter(total)
|
|
2439
|
+
return { label: totalLabel, value: unit ? `${amount} ${unit}` : amount, amount, ...(unit ? { unit } : {}) }
|
|
2440
|
+
}
|
|
2441
|
+
|
|
2442
|
+
/** The ring's inner radius, in percent of the plot's shorter side / 2 — with and without outside labels. */
|
|
2443
|
+
const DONUT_INNER_WITH_LABELS = 50
|
|
2444
|
+
const DONUT_INNER_PLAIN = 72
|
|
2445
|
+
|
|
2446
|
+
/**
|
|
2447
|
+
* The hole's diameter as a fraction of the plot's shorter side (ECharts reads a
|
|
2448
|
+
* `%` radius against half of it), so an HTML center label can be sized to fit.
|
|
2449
|
+
*/
|
|
2450
|
+
function donutHoleRatio(withOutsideLabels: boolean): number {
|
|
2451
|
+
return (withOutsideLabels ? DONUT_INNER_WITH_LABELS : DONUT_INNER_PLAIN) / 100
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
interface DonutChartConfig {
|
|
2455
|
+
/** Slices in draw order (largest first, 「その他」 last). */
|
|
2456
|
+
slices: readonly DonutOptionSlice[]
|
|
2457
|
+
/** Resolved slice colours, by slice position. `""`/missing → theme palette. */
|
|
2458
|
+
palette: readonly string[]
|
|
2459
|
+
/** Display names for slice names (tooltip, outside labels). Missing keys show as they are. */
|
|
2460
|
+
labels?: Readonly<Record<string, string>>
|
|
2461
|
+
valueFormatter: (value: number) => string
|
|
2462
|
+
/** The value column's name, shown in the tooltip row. */
|
|
2463
|
+
valueName?: string
|
|
2464
|
+
variant?: DonutVariant
|
|
2465
|
+
showTooltip?: boolean
|
|
2466
|
+
/** How many of the largest (non-「その他」) slices get an outside label. Default `DONUT_OUTSIDE_LABELS` (2); 0 = none. */
|
|
2467
|
+
outsideLabels?: number
|
|
2468
|
+
/** Name of the selected slice; the others are dimmed. */
|
|
2469
|
+
active?: string | null
|
|
2470
|
+
/** Colour of the outside labels (resolved foreground). Default: the theme's text colour. */
|
|
2471
|
+
labelColor?: string
|
|
2472
|
+
reducedMotion?: boolean
|
|
2473
|
+
/** Deep-merged onto the generated option last. */
|
|
2474
|
+
chartOptions?: EChartsOption
|
|
2475
|
+
}
|
|
2476
|
+
|
|
2477
|
+
/** Sum of the `value` column, ignoring gaps and negative cells. */
|
|
2478
|
+
function donutTotal(data: readonly Record<string, unknown>[], value: string): number {
|
|
2479
|
+
return data.reduce((sum, row) => {
|
|
2480
|
+
const n = cellNumber(row[value])
|
|
2481
|
+
return n !== null && n > 0 ? sum + n : sum
|
|
2482
|
+
}, 0)
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
interface ItemTooltipParam {
|
|
2486
|
+
name?: string
|
|
2487
|
+
value?: unknown
|
|
2488
|
+
percent?: number
|
|
2489
|
+
color?: unknown
|
|
2490
|
+
}
|
|
2491
|
+
|
|
2492
|
+
/**
|
|
2493
|
+
* The donut / pie option. Only the `outsideLabels` largest slices carry an
|
|
2494
|
+
* outside label (name + share); the legend, center label and tooltip carry the
|
|
2495
|
+
* rest. No entrance animation, a short ease on updates.
|
|
2496
|
+
*/
|
|
2497
|
+
function buildDonutOption(cfg: DonutChartConfig): EChartsOption {
|
|
2498
|
+
const {
|
|
2499
|
+
slices,
|
|
2500
|
+
palette,
|
|
2501
|
+
labels: nameLabels,
|
|
2502
|
+
valueFormatter,
|
|
2503
|
+
valueName = "",
|
|
2504
|
+
variant = "donut",
|
|
2505
|
+
showTooltip = true,
|
|
2506
|
+
outsideLabels = DONUT_OUTSIDE_LABELS,
|
|
2507
|
+
active = null,
|
|
2508
|
+
labelColor,
|
|
2509
|
+
reducedMotion = false,
|
|
2510
|
+
chartOptions,
|
|
2511
|
+
} = cfg
|
|
2512
|
+
const total = slices.reduce((sum, s) => sum + sliceValue(s.value), 0)
|
|
2513
|
+
// The largest real slices, by value (the slices arrive sorted, but don't rely on it).
|
|
2514
|
+
const labelled = new Set(
|
|
2515
|
+
slices
|
|
2516
|
+
.map((s, i) => ({ i, v: sliceValue(s.value), other: Boolean(s.isOther) }))
|
|
2517
|
+
.filter((s) => !s.other && s.v > 0)
|
|
2518
|
+
.sort((a, b) => b.v - a.v || a.i - b.i)
|
|
2519
|
+
.slice(0, Math.max(0, outsideLabels))
|
|
2520
|
+
.map((s) => s.i),
|
|
2521
|
+
)
|
|
2522
|
+
const withLabels = labelled.size > 0
|
|
2523
|
+
// Room for the outside labels: the ring shrinks inside the plot.
|
|
2524
|
+
const outer = withLabels ? "70%" : "100%"
|
|
2525
|
+
const option = {
|
|
2526
|
+
...chartMotion(reducedMotion),
|
|
2527
|
+
tooltip: {
|
|
2528
|
+
show: showTooltip,
|
|
2529
|
+
trigger: "item",
|
|
2530
|
+
formatter: (params: unknown) => {
|
|
2531
|
+
const p = params as ItemTooltipParam
|
|
2532
|
+
const n = cellNumber(p.value)
|
|
2533
|
+
const share = typeof p.percent === "number" ? ` (${p.percent.toFixed(1)}%)` : ""
|
|
2534
|
+
return tooltipHtml(
|
|
2535
|
+
`${labelOf(p.name ?? "", nameLabels)}${share}`,
|
|
2536
|
+
[{ name: valueName, color: typeof p.color === "string" ? p.color : "currentColor", value: n }],
|
|
2537
|
+
valueFormatter,
|
|
2538
|
+
)
|
|
2539
|
+
},
|
|
2540
|
+
},
|
|
2541
|
+
series: [
|
|
2542
|
+
{
|
|
2543
|
+
id: "slices",
|
|
2544
|
+
type: "pie",
|
|
2545
|
+
radius: variant === "donut" ? [`${donutHoleRatio(withLabels) * 100}%`, outer] : [0, outer],
|
|
2546
|
+
center: ["50%", "50%"],
|
|
2547
|
+
avoidLabelOverlap: true,
|
|
2548
|
+
// Plain text: no outline / shadow, which reads as a halo on a dark surface.
|
|
2549
|
+
label: {
|
|
2550
|
+
show: false,
|
|
2551
|
+
position: "outside",
|
|
2552
|
+
color: labelColor,
|
|
2553
|
+
textBorderWidth: 0,
|
|
2554
|
+
textBorderColor: "transparent",
|
|
2555
|
+
textShadowBlur: 0,
|
|
2556
|
+
textShadowColor: "transparent",
|
|
2557
|
+
},
|
|
2558
|
+
labelLine: { show: false, length: 8, length2: 8 },
|
|
2559
|
+
// A hairline gap between slices instead of a border — no background colour to match.
|
|
2560
|
+
padAngle: slices.length > 1 ? 1 : 0,
|
|
2561
|
+
itemStyle: { borderRadius: variant === "donut" ? 2 : 0 },
|
|
2562
|
+
emphasis: { scale: true, scaleSize: 4 },
|
|
2563
|
+
data: slices.map((slice, i) => ({
|
|
2564
|
+
name: slice.name,
|
|
2565
|
+
value: sliceValue(slice.value),
|
|
2566
|
+
itemStyle: { color: palette[i] || undefined, opacity: active !== null && active !== slice.name ? DIMMED : 1 },
|
|
2567
|
+
...(labelled.has(i)
|
|
2568
|
+
? {
|
|
2569
|
+
label: { show: true, formatter: () => `${labelOf(slice.name, nameLabels)} ${donutShareText(slice.value, total)}` },
|
|
2570
|
+
labelLine: { show: true },
|
|
2571
|
+
}
|
|
2572
|
+
: {}),
|
|
2573
|
+
})),
|
|
2574
|
+
},
|
|
2575
|
+
],
|
|
2576
|
+
}
|
|
2577
|
+
return mergeChartOptions(option as EChartsOption, chartOptions)
|
|
2578
|
+
}
|
|
2579
|
+
|
|
2580
|
+
/* -------------------------------------------------------------- selection */
|
|
2581
|
+
|
|
2582
|
+
/** Toggle: clicking the active point again clears the selection. */
|
|
2583
|
+
function nextChartSelection(
|
|
2584
|
+
current: ChartActivePoint | null,
|
|
2585
|
+
category: string,
|
|
2586
|
+
index: number,
|
|
2587
|
+
): ChartActivePoint | null {
|
|
2588
|
+
return current && current.category === category && current.index === index ? null : { category, index }
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2591
|
+
/** What `onValueChange` receives: the clicked row plus what was clicked (ours win over row keys). */
|
|
2592
|
+
function chartSelectionPayload(
|
|
2593
|
+
selection: ChartActivePoint | null,
|
|
2594
|
+
data: readonly Record<string, unknown>[],
|
|
2595
|
+
eventType: NonNullable<ChartEventPayload>["eventType"],
|
|
2596
|
+
): ChartEventPayload {
|
|
2597
|
+
if (!selection) return null
|
|
2598
|
+
return { ...data[selection.index], eventType, categoryClicked: selection.category }
|
|
2599
|
+
}
|
|
2600
|
+
|
|
2601
|
+
interface ChartClickParams {
|
|
2602
|
+
componentType?: string
|
|
2603
|
+
seriesName?: string
|
|
2604
|
+
name?: string
|
|
2605
|
+
dataIndex?: number
|
|
2606
|
+
}
|
|
2607
|
+
|
|
2608
|
+
/**
|
|
2609
|
+
* Click-to-select for the typed charts: the `onEvents` to hand `EChart`, and
|
|
2610
|
+
* the active point to dim the rest with. Inert (no handler, nothing active)
|
|
2611
|
+
* without `onValueChange`.
|
|
2612
|
+
*/
|
|
2613
|
+
function useChartSelection(
|
|
2614
|
+
data: readonly Record<string, unknown>[],
|
|
2615
|
+
onValueChange: ((value: ChartEventPayload) => void) | undefined,
|
|
2616
|
+
eventType: NonNullable<ChartEventPayload>["eventType"],
|
|
2617
|
+
): { active: ChartActivePoint | null; onEvents: Record<string, (params: unknown) => void> | undefined } {
|
|
2618
|
+
const [active, setActive] = useState<ChartActivePoint | null>(null)
|
|
2619
|
+
// Handlers read the latest props without re-subscribing on every render.
|
|
2620
|
+
const latest = useRef({ data, onValueChange, active })
|
|
2621
|
+
latest.current = { data, onValueChange, active }
|
|
2622
|
+
const interactive = onValueChange !== undefined
|
|
2623
|
+
const onEvents = useMemo(() => {
|
|
2624
|
+
if (!interactive) return undefined
|
|
2625
|
+
return {
|
|
2626
|
+
click: (raw: unknown) => {
|
|
2627
|
+
const p = raw as ChartClickParams
|
|
2628
|
+
if (p.componentType !== "series" || typeof p.dataIndex !== "number") return
|
|
2629
|
+
const category = eventType === "slice" ? (p.name ?? "") : (p.seriesName ?? "")
|
|
2630
|
+
const next = nextChartSelection(latest.current.active, category, p.dataIndex)
|
|
2631
|
+
latest.current.active = next
|
|
2632
|
+
setActive(next)
|
|
2633
|
+
latest.current.onValueChange?.(chartSelectionPayload(next, latest.current.data, eventType))
|
|
2634
|
+
},
|
|
2635
|
+
}
|
|
2636
|
+
}, [interactive, eventType])
|
|
2637
|
+
return { active: interactive ? active : null, onEvents }
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
/**
|
|
2641
|
+
* Display name for `key`: `labels[key]` when present, else `key` itself.
|
|
2642
|
+
* (Own keys only, so `"constructor"` is not looked up on the prototype.)
|
|
2643
|
+
*/
|
|
2644
|
+
function labelOf(key: string, labels?: Readonly<Record<string, string>>): string {
|
|
2645
|
+
return hasLabel(labels, key) ? labels![key]! : key
|
|
2646
|
+
}
|
|
2647
|
+
|
|
2648
|
+
/** `data` with each row's `index` cell replaced by its display name (rows are copied, not mutated). */
|
|
2649
|
+
function labelRows<Row extends Record<string, unknown>>(
|
|
2650
|
+
data: readonly Row[],
|
|
2651
|
+
index: string,
|
|
2652
|
+
labels?: Readonly<Record<string, string>>,
|
|
2653
|
+
): Row[] {
|
|
2654
|
+
if (!labels) return data as Row[]
|
|
2655
|
+
return data.map((row) => ({ ...row, [index]: labelOf(String(row[index] ?? ""), labels) }))
|
|
2656
|
+
}
|
|
2657
|
+
|
|
2658
|
+
/** Whether `labels` renames `key` (own keys only). */
|
|
2659
|
+
function hasLabel(labels: Readonly<Record<string, string>> | undefined, key: string): boolean {
|
|
2660
|
+
return Boolean(labels) && Object.prototype.hasOwnProperty.call(labels, key)
|
|
2661
|
+
}
|
|
2662
|
+
|
|
2663
|
+
/* ------------------------------------------------------------ provisional */
|
|
2664
|
+
|
|
2665
|
+
/** The default label for points that are not final yet. */
|
|
2666
|
+
const DEFAULT_PROVISIONAL_LABEL = "速報"
|
|
2667
|
+
|
|
2668
|
+
/**
|
|
2669
|
+
* Position of the first provisional point: the first entry of `indexValues`
|
|
2670
|
+
* that equals `from` (compared as text, so `"2026-09"` and a Date-less string
|
|
2671
|
+
* key both work). `-1` when `from` is unset or not among the values — the chart
|
|
2672
|
+
* then draws everything as confirmed.
|
|
2673
|
+
*/
|
|
2674
|
+
function provisionalStart(indexValues: readonly unknown[], from: string | number | undefined | null): number {
|
|
2675
|
+
if (from === undefined || from === null) return -1
|
|
2676
|
+
const key = String(from)
|
|
2677
|
+
return indexValues.findIndex((value) => String(value ?? "") === key)
|
|
2678
|
+
}
|
|
2679
|
+
|
|
2680
|
+
/**
|
|
2681
|
+
* Split one series at `start` (see `provisionalStart`). `confirmed` keeps the
|
|
2682
|
+
* points before `start`; `provisional` keeps `start` onward plus the last
|
|
2683
|
+
* confirmed point, so the dashed line joins the solid one. `start <= 0` or
|
|
2684
|
+
* `-1` leaves nothing to join (all provisional / none provisional).
|
|
2685
|
+
*/
|
|
2686
|
+
function splitProvisional(
|
|
2687
|
+
values: readonly (number | null)[],
|
|
2688
|
+
start: number,
|
|
2689
|
+
): { confirmed: (number | null)[]; provisional: (number | null)[] } {
|
|
2690
|
+
if (start < 0) return { confirmed: [...values], provisional: values.map(() => null) }
|
|
2691
|
+
return {
|
|
2692
|
+
confirmed: values.map((v, i) => (i < start ? v : null)),
|
|
2693
|
+
provisional: values.map((v, i) => (i >= Math.max(0, start - 1) ? v : null)),
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
|
|
2697
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
|
|
2698
|
+
|
|
2699
|
+
const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
|
|
2700
|
+
const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
|
|
2701
|
+
|
|
2702
|
+
/**
|
|
2703
|
+
* The attributes of a typed chart's leftover props that belong on its root
|
|
2704
|
+
* element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
|
|
2705
|
+
* An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
|
|
2706
|
+
*/
|
|
2707
|
+
function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
|
|
2708
|
+
const out: Record<string, unknown> = {}
|
|
2709
|
+
for (const [key, value] of Object.entries(rest)) {
|
|
2710
|
+
if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
|
|
2711
|
+
}
|
|
2712
|
+
return out
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2715
|
+
/** The series tokens, in palette order — the default `colors` of every typed chart. */
|
|
2716
|
+
const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
|
|
2717
|
+
"chart-1",
|
|
2718
|
+
"chart-2",
|
|
2719
|
+
"chart-3",
|
|
2720
|
+
"chart-4",
|
|
2721
|
+
"chart-5",
|
|
2722
|
+
]
|
|
2723
|
+
|
|
2724
|
+
const TOKEN_NAME_RE = /^chart-[1-5]$/
|
|
2725
|
+
|
|
2726
|
+
/** The meaning colours; each is a theme token of the same name (`--positive`, …). */
|
|
2727
|
+
const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
|
|
2728
|
+
|
|
2729
|
+
/** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
|
|
2730
|
+
function isChartTone(color: string): color is ChartTone {
|
|
2731
|
+
return (CHART_TONES as readonly string[]).includes(color.trim())
|
|
2732
|
+
}
|
|
2733
|
+
|
|
2734
|
+
/**
|
|
2735
|
+
* A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
|
|
2736
|
+
* light/dark on its own), anything else passes through unchanged.
|
|
2737
|
+
*/
|
|
2738
|
+
function chartColorToCss(color: ChartColor): string {
|
|
2739
|
+
const value = color.trim()
|
|
2740
|
+
return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
|
|
2741
|
+
}
|
|
2742
|
+
|
|
2743
|
+
/**
|
|
2744
|
+
* A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
|
|
2745
|
+
* colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
|
|
2746
|
+
* lightness step from the page in light and dark. `--positive` etc. are for text and icons.
|
|
2747
|
+
*/
|
|
2748
|
+
function chartFillToCss(color: ChartColor): string {
|
|
2749
|
+
const value = color.trim()
|
|
2750
|
+
return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
|
|
2751
|
+
}
|
|
2752
|
+
|
|
2753
|
+
/** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
|
|
2754
|
+
function chartFillName(color: ChartColor): ChartColor {
|
|
2755
|
+
const value = color.trim()
|
|
2756
|
+
return isChartTone(value) ? `${value}-fill` : color
|
|
2757
|
+
}
|
|
2758
|
+
|
|
2759
|
+
/** The `i`-th colour, cycling through `colors` (the token palette when empty). */
|
|
2760
|
+
function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
|
|
2761
|
+
const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
|
|
2762
|
+
return palette[i % palette.length]!
|
|
2763
|
+
}
|
|
2764
|
+
|
|
2765
|
+
/** `colors` extended (by cycling) to exactly `count` entries. */
|
|
2766
|
+
function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
|
|
2767
|
+
return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
|
|
2768
|
+
}
|
|
2769
|
+
|
|
2770
|
+
/** A translucent version of a CSS colour (works for `var(--…)` too). */
|
|
2771
|
+
function tintCss(cssColor: string, percent: number): string {
|
|
2772
|
+
return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
|
|
2773
|
+
}
|
|
2774
|
+
|
|
2775
|
+
const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
|
|
2776
|
+
|
|
2777
|
+
/** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
|
|
2778
|
+
const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
|
|
2779
|
+
|
|
2780
|
+
/**
|
|
2781
|
+
* The formatter a chart actually uses: an explicit `valueFormatter` wins, else
|
|
2782
|
+
* `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
|
|
2783
|
+
*/
|
|
2784
|
+
function resolveValueFormatter(
|
|
2785
|
+
valueFormatter: ValueFormatter | undefined,
|
|
2786
|
+
format: ValueFormat | undefined,
|
|
2787
|
+
locale?: string,
|
|
2788
|
+
): ValueFormatter {
|
|
2789
|
+
return valueFormatter ?? toValueFormatter(format, locale)
|
|
2790
|
+
}
|
|
2791
|
+
|
|
2792
|
+
/**
|
|
2793
|
+
* The formatter of value-axis ticks and on-plot labels: an explicit
|
|
2794
|
+
* `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
|
|
2795
|
+
* the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
|
|
2796
|
+
* too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
|
|
2797
|
+
* form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
|
|
2798
|
+
* so an axis tick and a KPI / tooltip of the same `format` always print the same
|
|
2799
|
+
* currency sign and grouping.
|
|
2800
|
+
*/
|
|
2801
|
+
function resolveAxisFormatter(
|
|
2802
|
+
valueFormatter: ValueFormatter | undefined,
|
|
2803
|
+
format: ValueFormat | undefined,
|
|
2804
|
+
locale: string = DEFAULT_LOCALE,
|
|
2805
|
+
): ValueFormatter {
|
|
2806
|
+
if (valueFormatter) return valueFormatter
|
|
2807
|
+
const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
|
|
2808
|
+
if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
|
|
2809
|
+
const currency = "currency" in spec ? spec.currency : undefined
|
|
2810
|
+
const short: ValueFormat =
|
|
2811
|
+
spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
|
|
2812
|
+
return (value) => formatValue(value, short, locale)
|
|
2813
|
+
}
|
|
2814
|
+
|
|
2815
|
+
/** The unit words of a ja number (`1.2万` / `3.4億` / `1兆`) and their sizes, largest first. */
|
|
2816
|
+
const JA_UNITS = [
|
|
2817
|
+
{ char: "兆", size: 1e12 },
|
|
2818
|
+
{ char: "億", size: 1e8 },
|
|
2819
|
+
{ char: "万", size: 1e4 },
|
|
2820
|
+
] as const
|
|
2821
|
+
|
|
2822
|
+
const JA_NUMBER_TOKEN_RE = /\d[\d,]*(?:\.\d+)?(?:兆|億|万)?/
|
|
2823
|
+
|
|
2824
|
+
/**
|
|
2825
|
+
* The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
|
|
2826
|
+
* that largest tick, so 万 and 億 never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`).
|
|
2827
|
+
* Only the ja short forms (`compact` / `number` / `currency`, no `valueFormatter`) have units to align;
|
|
2828
|
+
* any other format — and an axis whose largest tick is under 1万 — keeps `resolveAxisFormatter`'s output as it is.
|
|
2829
|
+
*/
|
|
2830
|
+
function resolveAxisTickFormatter(
|
|
2831
|
+
valueFormatter: ValueFormatter | undefined,
|
|
2832
|
+
format: ValueFormat | undefined,
|
|
2833
|
+
locale: string = DEFAULT_LOCALE,
|
|
2834
|
+
): (top: number) => ValueFormatter {
|
|
2835
|
+
const base = resolveAxisFormatter(valueFormatter, format, locale)
|
|
2836
|
+
const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
|
|
2837
|
+
const aligns =
|
|
2838
|
+
!valueFormatter && locale.toLowerCase().startsWith("ja") && (spec.type === "compact" || spec.type === "number" || spec.type === "currency")
|
|
2839
|
+
if (!aligns) return () => base
|
|
2840
|
+
const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
|
|
2841
|
+
return (top) => {
|
|
2842
|
+
const unit = JA_UNITS.find((u) => Math.abs(top) >= u.size)
|
|
2843
|
+
if (!unit) return base
|
|
2844
|
+
return (value) => {
|
|
2845
|
+
const text = base(value)
|
|
2846
|
+
if (value === 0 || !Number.isFinite(value)) return text
|
|
2847
|
+
const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.char}`
|
|
2848
|
+
return text.replace(JA_NUMBER_TOKEN_RE, () => scaled)
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
}
|
|
2852
|
+
|
|
2853
|
+
/**
|
|
2854
|
+
* A data cell as a number, or `null` for a gap. Numeric strings count — SQL
|
|
2855
|
+
* `DECIMAL` / `BIGINT` columns usually arrive as strings.
|
|
2856
|
+
*/
|
|
2857
|
+
function toChartNumber(value: unknown): number | null {
|
|
2858
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null
|
|
2859
|
+
if (typeof value === "bigint") return Number(value)
|
|
2860
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
2861
|
+
const n = Number(value)
|
|
2862
|
+
return Number.isFinite(n) ? n : null
|
|
2863
|
+
}
|
|
2864
|
+
return null
|
|
2865
|
+
}
|
|
2866
|
+
|
|
2867
|
+
/** Clamp `value` into `[min, max]`. */
|
|
2868
|
+
function clamp(value: number, min: number, max: number): number {
|
|
2869
|
+
return Math.min(max, Math.max(min, value))
|
|
2870
|
+
}
|
|
2871
|
+
|
|
2872
|
+
/* ------------------------------------------------------------ aggregation */
|
|
2873
|
+
|
|
2874
|
+
/** How many categories a chart colours individually; the rest fold into「その他」. */
|
|
2875
|
+
const MAX_CHART_SERIES = 5
|
|
2876
|
+
|
|
2877
|
+
/** The series name the folded categories get. */
|
|
2878
|
+
const OTHER_SERIES_LABEL = "その他"
|
|
2879
|
+
|
|
2880
|
+
interface AggregatedItems<Item extends { name: string; value: number }> {
|
|
2881
|
+
/** The `n` largest items, in their given order. All items when there are `n` or fewer. */
|
|
2882
|
+
top: Item[]
|
|
2883
|
+
/** The items folded into `other`, in their given order. */
|
|
2884
|
+
rest: Item[]
|
|
2885
|
+
/** The folded remainder, or `null` when nothing was folded. */
|
|
2886
|
+
other: { name: string; value: number } | null
|
|
2887
|
+
}
|
|
2888
|
+
|
|
2889
|
+
/**
|
|
2890
|
+
* Keep the `n` largest items (by value; ties keep the earlier one) in their
|
|
2891
|
+
* given order and fold the rest into one `otherLabel` item. Shared by every
|
|
2892
|
+
* chart that caps its categories (Area / Line / Bar series, Donut slices,
|
|
2893
|
+
* BarList rows).
|
|
2894
|
+
*/
|
|
2895
|
+
function aggregateTopN<Item extends { name: string; value: number }>(
|
|
2896
|
+
items: readonly Item[],
|
|
2897
|
+
n: number = MAX_CHART_SERIES,
|
|
2898
|
+
otherLabel: string = OTHER_SERIES_LABEL,
|
|
2899
|
+
): AggregatedItems<Item> {
|
|
2900
|
+
if (items.length <= n) return { top: [...items], rest: [], other: null }
|
|
2901
|
+
const ranked = items
|
|
2902
|
+
.map((item, i) => ({ item, i }))
|
|
2903
|
+
.sort((a, b) => b.item.value - a.item.value || a.i - b.i)
|
|
2904
|
+
const keep = new Set(ranked.slice(0, n).map((r) => r.i))
|
|
2905
|
+
const top = items.filter((_, i) => keep.has(i))
|
|
2906
|
+
const rest = items.filter((_, i) => !keep.has(i))
|
|
2907
|
+
return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
|
|
2908
|
+
}
|
|
2909
|
+
|
|
2910
|
+
interface AggregatedSeries {
|
|
2911
|
+
/** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
|
|
2912
|
+
data: Record<string, unknown>[]
|
|
2913
|
+
/** Series to draw: the kept categories in their given order, then `otherCategory`. */
|
|
2914
|
+
categories: string[]
|
|
2915
|
+
/** The folded series' name, or `null`. */
|
|
2916
|
+
otherCategory: string | null
|
|
2917
|
+
}
|
|
2918
|
+
|
|
2919
|
+
/**
|
|
2920
|
+
* Cap a cartesian chart at `n` series: rank the categories by the sum of their
|
|
2921
|
+
* values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
|
|
2922
|
+
*/
|
|
2923
|
+
function aggregateSeries(
|
|
2924
|
+
data: readonly Record<string, unknown>[],
|
|
2925
|
+
categories: readonly string[],
|
|
2926
|
+
n: number = MAX_CHART_SERIES,
|
|
2927
|
+
otherLabel: string = OTHER_SERIES_LABEL,
|
|
2928
|
+
): AggregatedSeries {
|
|
2929
|
+
const totals = categories.map((name) => ({
|
|
2930
|
+
name,
|
|
2931
|
+
value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
|
|
2932
|
+
}))
|
|
2933
|
+
const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
|
|
2934
|
+
if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
|
|
2935
|
+
const folded = rest.map((item) => item.name)
|
|
2936
|
+
return {
|
|
2937
|
+
data: data.map((row) => {
|
|
2938
|
+
let sum: number | null = null
|
|
2939
|
+
for (const name of folded) {
|
|
2940
|
+
const v = toChartNumber(row[name])
|
|
2941
|
+
if (v !== null) sum = (sum ?? 0) + v
|
|
2942
|
+
}
|
|
2943
|
+
return { ...row, [other.name]: sum }
|
|
2944
|
+
}),
|
|
2945
|
+
categories: [...top.map((item) => item.name), other.name],
|
|
2946
|
+
otherCategory: other.name,
|
|
2947
|
+
}
|
|
2948
|
+
}
|
|
2949
|
+
|
|
2950
|
+
/**
|
|
2951
|
+
* `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
|
|
2952
|
+
* at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
|
|
2953
|
+
*/
|
|
2954
|
+
function aggregateSeriesKeeping(
|
|
2955
|
+
data: readonly Record<string, unknown>[],
|
|
2956
|
+
categories: readonly string[],
|
|
2957
|
+
keep: string | undefined,
|
|
2958
|
+
n: number = MAX_CHART_SERIES,
|
|
2959
|
+
): AggregatedSeries {
|
|
2960
|
+
if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n)
|
|
2961
|
+
const aggregated = aggregateSeries(
|
|
2962
|
+
data,
|
|
2963
|
+
categories.filter((c) => c !== keep),
|
|
2964
|
+
n,
|
|
2965
|
+
)
|
|
2966
|
+
return { ...aggregated, categories: [...aggregated.categories, keep] }
|
|
2967
|
+
}
|
|
2968
|
+
|
|
2969
|
+
/**
|
|
2970
|
+
* `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
|
|
2971
|
+
* builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
|
|
2972
|
+
* so a main series keeps its colour whether or not a comparison is drawn.
|
|
2973
|
+
*/
|
|
2974
|
+
function seriesColorsWithComparison(
|
|
2975
|
+
categories: readonly string[],
|
|
2976
|
+
colors: ChartColors | undefined,
|
|
2977
|
+
otherColor: string,
|
|
2978
|
+
otherCategory: string | null,
|
|
2979
|
+
allCategories: readonly string[],
|
|
2980
|
+
comparison: string | undefined,
|
|
2981
|
+
): string[] {
|
|
2982
|
+
if (comparison === undefined || !categories.includes(comparison)) {
|
|
2983
|
+
return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
|
|
2984
|
+
}
|
|
2985
|
+
const main = categories.filter((c) => c !== comparison)
|
|
2986
|
+
const mainColors = seriesColorsFor(
|
|
2987
|
+
main,
|
|
2988
|
+
colors,
|
|
2989
|
+
otherColor,
|
|
2990
|
+
otherCategory,
|
|
2991
|
+
allCategories.filter((c) => c !== comparison),
|
|
2992
|
+
)
|
|
2993
|
+
return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
|
|
2994
|
+
}
|
|
2995
|
+
|
|
2996
|
+
/**
|
|
2997
|
+
* Colour per drawn series: the record's token for that category, else the
|
|
2998
|
+
* array's token at the category's position in `allCategories` (cycled), else
|
|
2999
|
+
* the token palette by drawn position. `otherCategory` — and a category the
|
|
3000
|
+
* data itself names「その他」(`OTHER_SERIES_LABEL`) — always gets `otherColor`.
|
|
3001
|
+
*/
|
|
3002
|
+
function seriesColorsFor(
|
|
3003
|
+
categories: readonly string[],
|
|
3004
|
+
colors: ChartColors | undefined,
|
|
3005
|
+
otherColor: string,
|
|
3006
|
+
otherCategory: string | null = null,
|
|
3007
|
+
allCategories: readonly string[] = categories,
|
|
3008
|
+
): string[] {
|
|
3009
|
+
const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
|
|
3010
|
+
const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
|
|
3011
|
+
return categories.map((category, i) => {
|
|
3012
|
+
if ((otherCategory !== null && category === otherCategory) || category === OTHER_SERIES_LABEL) return otherColor
|
|
3013
|
+
const fromRecord = record?.[category]
|
|
3014
|
+
if (fromRecord) return fromRecord
|
|
3015
|
+
if (list && list.length > 0) {
|
|
3016
|
+
const at = allCategories.indexOf(category)
|
|
3017
|
+
return list[(at === -1 ? i : at) % list.length]!
|
|
3018
|
+
}
|
|
3019
|
+
return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
|
|
3020
|
+
})
|
|
3021
|
+
}
|
|
3022
|
+
|
|
3023
|
+
/* ------------------------------------------------------------------ Donut */
|
|
3024
|
+
|
|
3025
|
+
/** One drawn donut slice, largest first. */
|
|
3026
|
+
interface DonutSlice {
|
|
3027
|
+
name: string
|
|
3028
|
+
/** Negative and missing values count as 0. */
|
|
3029
|
+
value: number
|
|
3030
|
+
/** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
|
|
3031
|
+
color: string
|
|
3032
|
+
/** The folded「その他」slice. */
|
|
3033
|
+
isOther: boolean
|
|
3034
|
+
/** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
|
|
3035
|
+
row: Record<string, unknown>
|
|
3036
|
+
}
|
|
3037
|
+
|
|
3038
|
+
interface DonutSlicesConfig {
|
|
3039
|
+
/** Label column. */
|
|
3040
|
+
index: string
|
|
3041
|
+
/** Value column. */
|
|
3042
|
+
value: string
|
|
3043
|
+
/** Slice colours by rank (cycled). Default: the token palette in order. */
|
|
3044
|
+
colors?: readonly ChartSeriesColor[]
|
|
3045
|
+
/** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
|
|
3046
|
+
maxSlices?: number
|
|
3047
|
+
/** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
|
|
3048
|
+
otherColor: string
|
|
3049
|
+
otherLabel?: string
|
|
3050
|
+
}
|
|
3051
|
+
|
|
3052
|
+
/**
|
|
3053
|
+
* Donut slices: sorted by value (largest first, ties keep input order), the
|
|
3054
|
+
* `maxSlices` largest kept and coloured by rank in fixed token order, the rest
|
|
3055
|
+
* summed into one「その他」slice in `otherColor`.
|
|
3056
|
+
*/
|
|
3057
|
+
function donutSlices(
|
|
3058
|
+
data: readonly Record<string, unknown>[],
|
|
3059
|
+
{ index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = OTHER_SERIES_LABEL }: DonutSlicesConfig,
|
|
3060
|
+
): DonutSlice[] {
|
|
3061
|
+
const items = data
|
|
3062
|
+
.map((row, i) => {
|
|
3063
|
+
const n = toChartNumber(row[value])
|
|
3064
|
+
return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
|
|
3065
|
+
})
|
|
3066
|
+
.sort((a, b) => b.value - a.value || a.i - b.i)
|
|
3067
|
+
const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
|
|
3068
|
+
const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
|
|
3069
|
+
const slices: DonutSlice[] = top.map((item, rank) => ({
|
|
3070
|
+
name: item.name,
|
|
3071
|
+
value: item.value,
|
|
3072
|
+
color: palette[rank % palette.length]!,
|
|
3073
|
+
isOther: false,
|
|
3074
|
+
row: item.row,
|
|
3075
|
+
}))
|
|
3076
|
+
if (other) {
|
|
3077
|
+
slices.push({
|
|
3078
|
+
name: other.name,
|
|
3079
|
+
value: other.value,
|
|
3080
|
+
color: otherColor,
|
|
3081
|
+
isOther: true,
|
|
3082
|
+
row: { [index]: other.name, [value]: other.value },
|
|
3083
|
+
})
|
|
3084
|
+
}
|
|
3085
|
+
return slices
|
|
3086
|
+
}
|
|
3087
|
+
|
|
3088
|
+
/* ---------------------------------------------------------------- BarList */
|
|
3089
|
+
|
|
3090
|
+
type BarListSortOrder = "ascending" | "descending" | "none"
|
|
3091
|
+
|
|
3092
|
+
/** Sort a copy of the rows by value; `"none"` keeps the given order. */
|
|
3093
|
+
function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
|
|
3094
|
+
const rows = [...data]
|
|
3095
|
+
if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
|
|
3096
|
+
else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
|
|
3097
|
+
return rows
|
|
3098
|
+
}
|
|
3099
|
+
|
|
3100
|
+
/** BarList-only settings. */
|
|
3101
|
+
interface BarListOptions {
|
|
3102
|
+
/** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
|
|
3103
|
+
sortOrder?: BarListSortOrder
|
|
3104
|
+
/** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
|
|
3105
|
+
maxItems?: number
|
|
3106
|
+
/** まとめた行のラベル。既定「その他」。 */
|
|
3107
|
+
otherLabel?: string
|
|
3108
|
+
/** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
|
|
3109
|
+
exclude?: readonly string[]
|
|
3110
|
+
/** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
|
|
3111
|
+
showShare?: boolean
|
|
3112
|
+
}
|
|
3113
|
+
|
|
3114
|
+
/** One drawn BarList row. */
|
|
3115
|
+
interface BarListRow<Row = Record<string, unknown>> {
|
|
3116
|
+
/** React key: the row's `key`, else its name (`"__other"` for the folded row). */
|
|
3117
|
+
key: string
|
|
3118
|
+
name: string
|
|
3119
|
+
value: number
|
|
3120
|
+
/** Only for real rows; the folded row never links. */
|
|
3121
|
+
href?: string
|
|
3122
|
+
/** Legacy per-row colour (`BarListItem.color`). */
|
|
3123
|
+
color?: ChartColor
|
|
3124
|
+
/** The folded「その他」row. */
|
|
3125
|
+
isOther: boolean
|
|
3126
|
+
/** The input row (`null` for the folded row). */
|
|
3127
|
+
row: Row | null
|
|
3128
|
+
}
|
|
3129
|
+
|
|
3130
|
+
interface BarListRowsConfig extends BarListOptions {
|
|
3131
|
+
/** Name column. Default `"name"`. */
|
|
3132
|
+
index?: string
|
|
3133
|
+
/** Value column. Default `"value"`. */
|
|
3134
|
+
category?: string
|
|
3135
|
+
}
|
|
3136
|
+
|
|
3137
|
+
/**
|
|
3138
|
+
* The rows a BarList draws: read name / value (numeric strings count, gaps are
|
|
3139
|
+
* 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
|
|
3140
|
+
* the folded remainder as one「その他」row. Rows named in `exclude` skip the
|
|
3141
|
+
* ranking and are always added to「その他」.
|
|
3142
|
+
*/
|
|
3143
|
+
function barListRows<Row extends object>(
|
|
3144
|
+
data: readonly Row[],
|
|
3145
|
+
{ index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = OTHER_SERIES_LABEL, exclude }: BarListRowsConfig = {},
|
|
3146
|
+
): BarListRow<Row>[] {
|
|
3147
|
+
const items = data.map((row): BarListRow<Row> => {
|
|
3148
|
+
const cells = row as Record<string, unknown>
|
|
3149
|
+
const name = String(cells[index] ?? "")
|
|
3150
|
+
return {
|
|
3151
|
+
key: typeof cells.key === "string" ? cells.key : name,
|
|
3152
|
+
name,
|
|
3153
|
+
value: toChartNumber(cells[category]) ?? 0,
|
|
3154
|
+
href: typeof cells.href === "string" ? cells.href : undefined,
|
|
3155
|
+
color: typeof cells.color === "string" ? cells.color : undefined,
|
|
3156
|
+
isOther: false,
|
|
3157
|
+
row,
|
|
3158
|
+
}
|
|
3159
|
+
})
|
|
3160
|
+
const excluded = new Set(exclude ?? [])
|
|
3161
|
+
const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
|
|
3162
|
+
const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
|
|
3163
|
+
const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
|
|
3164
|
+
const rows = sortBarListData(top, sortOrder)
|
|
3165
|
+
if (other || outside.length > 0) {
|
|
3166
|
+
const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
|
|
3167
|
+
rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
|
|
3168
|
+
}
|
|
3169
|
+
return rows
|
|
3170
|
+
}
|
|
3171
|
+
|
|
3172
|
+
/** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
|
|
3173
|
+
function barListWidths(values: readonly number[]): number[] {
|
|
3174
|
+
const max = Math.max(0, ...values)
|
|
3175
|
+
if (max === 0) return values.map(() => 0)
|
|
3176
|
+
return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
|
|
3177
|
+
}
|
|
3178
|
+
|
|
3179
|
+
/**
|
|
3180
|
+
* How strongly the BarList bars are painted: every row the same tint of the bar
|
|
3181
|
+
* colour (rank is the bar's length, not its weight). A tint over transparent, so
|
|
3182
|
+
* it sits on the card in light and dark; it must stay visible against the card
|
|
3183
|
+
* while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
|
|
3184
|
+
*/
|
|
3185
|
+
const BAR_LIST_TINT = 45
|
|
3186
|
+
/** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
|
|
3187
|
+
const BAR_LIST_OTHER_TINT = 30
|
|
3188
|
+
|
|
3189
|
+
/**
|
|
3190
|
+
* The fill of each BarList row: all real rows in the same tint of `color`
|
|
3191
|
+
* (`BAR_LIST_TINT`), the folded「その他」row in a tint of `otherColor`
|
|
3192
|
+
* (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
|
|
3193
|
+
* ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
|
|
3194
|
+
* for that row. A tint, not the solid token, so the label printed over the bar
|
|
3195
|
+
* keeps its contrast.
|
|
3196
|
+
*/
|
|
3197
|
+
function barListFills(
|
|
3198
|
+
rows: readonly Pick<BarListRow, "isOther" | "color">[],
|
|
3199
|
+
color: ChartColor,
|
|
3200
|
+
otherColor: string,
|
|
3201
|
+
): string[] {
|
|
3202
|
+
return rows.map((row) =>
|
|
3203
|
+
row.isOther ? tintCss(otherColor, BAR_LIST_OTHER_TINT) : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
|
|
3204
|
+
)
|
|
3205
|
+
}
|
|
3206
|
+
|
|
3207
|
+
/** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
|
|
3208
|
+
function barListShareText(value: number, total: number): string {
|
|
3209
|
+
const v = Number.isFinite(value) && value > 0 ? value : 0
|
|
3210
|
+
if (total <= 0 || v === 0) return "0%"
|
|
3211
|
+
const pct = (v / total) * 100
|
|
3212
|
+
return pct < 1 ? "<1%" : `${Math.round(pct)}%`
|
|
3213
|
+
}
|
|
3214
|
+
|
|
3215
|
+
/**
|
|
3216
|
+
* The text at the end of each BarList row: the formatted value and, with
|
|
3217
|
+
* `showShare`, its share of the total of all drawn rows (including「その他」,
|
|
3218
|
+
* so the shares are of the whole list): `value` and `share` apart (the share is
|
|
3219
|
+
* drawn muted), `text` as one string (「¥8,240万 · 43%」).
|
|
3220
|
+
*/
|
|
3221
|
+
function barListValueTexts(
|
|
3222
|
+
values: readonly number[],
|
|
3223
|
+
formatter: ValueFormatter,
|
|
3224
|
+
showShare = false,
|
|
3225
|
+
): { value: string; share?: string; text: string }[] {
|
|
3226
|
+
const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
|
|
3227
|
+
return values.map((v) => {
|
|
3228
|
+
const value = formatter(v)
|
|
3229
|
+
if (!showShare) return { value, text: value }
|
|
3230
|
+
const share = barListShareText(v, total)
|
|
3231
|
+
return { value, share, text: `${value} · ${share}` }
|
|
3232
|
+
})
|
|
3233
|
+
}
|
|
3234
|
+
|
|
3235
|
+
/* -------------------------------------------------------------- DataTable */
|
|
3236
|
+
|
|
3237
|
+
/** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
|
|
3238
|
+
interface ChartDataTable {
|
|
3239
|
+
/** 表の見出し(`<caption>`)。 */
|
|
3240
|
+
caption?: string
|
|
3241
|
+
/** 列見出し。先頭がラベル列。 */
|
|
3242
|
+
columns: string[]
|
|
3243
|
+
/** 行。セルは書式済みの文字列。 */
|
|
3244
|
+
rows: string[][]
|
|
3245
|
+
}
|
|
3246
|
+
|
|
3247
|
+
/**
|
|
3248
|
+
* The chart's numbers as a table, for screen readers: one row per data row, the
|
|
3249
|
+
* `index` cell then each category through `formatter` (gaps → `—`). `labels`
|
|
3250
|
+
* 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).
|
|
3251
|
+
*/
|
|
3252
|
+
function chartDataTable(
|
|
3253
|
+
data: readonly Record<string, unknown>[],
|
|
3254
|
+
index: string,
|
|
3255
|
+
categories: readonly string[],
|
|
3256
|
+
formatter: ValueFormatter,
|
|
3257
|
+
labels?: Readonly<Record<string, string>>,
|
|
3258
|
+
indexName?: string,
|
|
3259
|
+
): ChartDataTable {
|
|
3260
|
+
const label = (key: string) => labels?.[key] ?? key
|
|
3261
|
+
return {
|
|
3262
|
+
columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
|
|
3263
|
+
rows: data.map((row) => [
|
|
3264
|
+
String(row[index] ?? ""),
|
|
3265
|
+
...categories.map((key) => {
|
|
3266
|
+
const n = toChartNumber(row[key])
|
|
3267
|
+
return n === null ? EMPTY_VALUE : formatter(n)
|
|
3268
|
+
}),
|
|
3269
|
+
]),
|
|
3270
|
+
}
|
|
3271
|
+
}
|
|
3272
|
+
|
|
3273
|
+
/* ------------------------------------------------------------ CategoryBar */
|
|
3274
|
+
|
|
3275
|
+
interface CategoryBarSegment {
|
|
3276
|
+
/** Width in percent of the whole bar. */
|
|
3277
|
+
width: number
|
|
3278
|
+
/** Where the segment starts, in percent. */
|
|
3279
|
+
start: number
|
|
3280
|
+
/** The running total at the segment's end — what its right-hand label shows. */
|
|
3281
|
+
end: number
|
|
3282
|
+
}
|
|
3283
|
+
|
|
3284
|
+
/** Lay the values side by side; negative values count as zero. */
|
|
3285
|
+
function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
|
|
3286
|
+
const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
|
|
3287
|
+
const total = clean.reduce((sum, v) => sum + v, 0)
|
|
3288
|
+
let running = 0
|
|
3289
|
+
return clean.map((v) => {
|
|
3290
|
+
const start = total === 0 ? 0 : (running / total) * 100
|
|
3291
|
+
running += v
|
|
3292
|
+
return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
|
|
3293
|
+
})
|
|
3294
|
+
}
|
|
3295
|
+
|
|
3296
|
+
interface CategoryBarLabel {
|
|
3297
|
+
/** Position in percent of the bar. */
|
|
3298
|
+
position: number
|
|
3299
|
+
/** The running total printed there. */
|
|
3300
|
+
value: number
|
|
3301
|
+
}
|
|
3302
|
+
|
|
3303
|
+
/**
|
|
3304
|
+
* Tick labels under the bar: `0` at the start, then the running total at each
|
|
3305
|
+
* segment's end. A label closer than `minGap` percent to the one before is
|
|
3306
|
+
* dropped so narrow segments don't print on top of each other — except the
|
|
3307
|
+
* last one (the total), which replaces its neighbour instead. With a
|
|
3308
|
+
* `markerPosition`, an inner label closer than `minGap` to the marker is dropped
|
|
3309
|
+
* too — the marker sits right under it and the two read as one crowded spot.
|
|
3310
|
+
*/
|
|
3311
|
+
function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
|
|
3312
|
+
const segments = categoryBarSegments(values).filter((s) => s.width > 0)
|
|
3313
|
+
if (segments.length === 0) return []
|
|
3314
|
+
const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
|
|
3315
|
+
segments.forEach((s, i) => {
|
|
3316
|
+
const label = { position: s.start + s.width, value: s.end }
|
|
3317
|
+
const prev = labels[labels.length - 1]!
|
|
3318
|
+
if (label.position - prev.position >= minGap) labels.push(label)
|
|
3319
|
+
else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
|
|
3320
|
+
})
|
|
3321
|
+
if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
|
|
3322
|
+
return labels.filter(
|
|
3323
|
+
(label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
|
|
3324
|
+
)
|
|
3325
|
+
}
|
|
3326
|
+
|
|
3327
|
+
/**
|
|
3328
|
+
* `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
|
|
3329
|
+
* (`texts`, same order): a label that would touch the one before is dropped — except the last (the
|
|
3330
|
+
* total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
|
|
3331
|
+
* edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
|
|
3332
|
+
* the rest 7 px at 12 px type).
|
|
3333
|
+
*/
|
|
3334
|
+
function categoryBarFitLabels(
|
|
3335
|
+
labels: readonly CategoryBarLabel[],
|
|
3336
|
+
texts: readonly string[],
|
|
3337
|
+
width: number,
|
|
3338
|
+
gap = 8,
|
|
3339
|
+
): CategoryBarLabel[] {
|
|
3340
|
+
const textWidth = (text: string) => {
|
|
3341
|
+
let w = 0
|
|
3342
|
+
for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
|
|
3343
|
+
return w
|
|
3344
|
+
}
|
|
3345
|
+
const extent = (label: CategoryBarLabel, text: string): [number, number] => {
|
|
3346
|
+
const w = textWidth(text)
|
|
3347
|
+
if (label.position <= 0) return [0, w]
|
|
3348
|
+
if (label.position >= 100) return [width - w, width]
|
|
3349
|
+
const center = (label.position / 100) * width
|
|
3350
|
+
return [center - w / 2, center + w / 2]
|
|
3351
|
+
}
|
|
3352
|
+
const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
|
|
3353
|
+
labels.forEach((label, i) => {
|
|
3354
|
+
const here = extent(label, texts[i] ?? "")
|
|
3355
|
+
const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
|
|
3356
|
+
if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
|
|
3357
|
+
else if (touches()) return
|
|
3358
|
+
kept.push({ label, extent: here })
|
|
3359
|
+
})
|
|
3360
|
+
return kept.map((k) => k.label)
|
|
3361
|
+
}
|
|
3362
|
+
|
|
3363
|
+
/** Marker position in percent of the bar, clamped to its ends. */
|
|
3364
|
+
function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
|
|
3365
|
+
const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
|
|
3366
|
+
if (total === 0) return 0
|
|
3367
|
+
return clamp((value / total) * 100, 0, 100)
|
|
3368
|
+
}
|
|
3369
|
+
|
|
3370
|
+
/** Index of the segment the marker sits on (the last one for a value past the end). */
|
|
3371
|
+
function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
|
|
3372
|
+
const segments = categoryBarSegments(values)
|
|
3373
|
+
const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
|
|
3374
|
+
if (index !== -1) return index
|
|
3375
|
+
for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
|
|
3376
|
+
return 0
|
|
3377
|
+
}
|
|
3378
|
+
|
|
3379
|
+
/* --------------------------------------------------------- ProgressCircle */
|
|
3380
|
+
|
|
3381
|
+
interface ProgressCircleGeometry {
|
|
3382
|
+
/** SVG width/height. */
|
|
3383
|
+
size: number
|
|
3384
|
+
/** Radius of the stroke's centre line. */
|
|
3385
|
+
normalizedRadius: number
|
|
3386
|
+
circumference: number
|
|
3387
|
+
/** `stroke-dashoffset` for the value arc. */
|
|
3388
|
+
offset: number
|
|
3389
|
+
/** The value as a fraction of `max`, clamped to `[0, 1]`. */
|
|
3390
|
+
ratio: number
|
|
3391
|
+
}
|
|
3392
|
+
|
|
3393
|
+
function progressCircleGeometry(
|
|
3394
|
+
value: number,
|
|
3395
|
+
max: number,
|
|
3396
|
+
radius: number,
|
|
3397
|
+
strokeWidth: number,
|
|
3398
|
+
): ProgressCircleGeometry {
|
|
3399
|
+
const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
|
|
3400
|
+
const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
|
|
3401
|
+
const circumference = 2 * Math.PI * normalizedRadius
|
|
3402
|
+
return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
|
|
3403
|
+
}
|
|
3404
|
+
|
|
3405
|
+
/* ---------------------------------------------------------------- summary */
|
|
3406
|
+
|
|
3407
|
+
interface ChartSummaryInput {
|
|
3408
|
+
data: readonly Record<string, unknown>[]
|
|
3409
|
+
/** The x-axis key. */
|
|
3410
|
+
index: string
|
|
3411
|
+
/** Series keys; the first one is described. */
|
|
3412
|
+
categories: readonly string[]
|
|
3413
|
+
/** Title of the chart, put in front when given. */
|
|
3414
|
+
title?: string
|
|
3415
|
+
/** Same as the chart's `format` (default `"compact"`). */
|
|
3416
|
+
format?: ValueFormat
|
|
3417
|
+
/** Wins over `format`. */
|
|
3418
|
+
valueFormatter?: ValueFormatter
|
|
3419
|
+
}
|
|
3420
|
+
|
|
3421
|
+
/**
|
|
3422
|
+
* One-sentence summary built from the rows, for `summary="auto"`:
|
|
3423
|
+
* 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」. The direction is
|
|
3424
|
+
* computed from the last two non-empty points of the first series — never
|
|
3425
|
+
* written by hand, so it cannot contradict the data. `undefined` when there is
|
|
3426
|
+
* no usable point.
|
|
3427
|
+
*/
|
|
3428
|
+
function buildChartSummary(input: ChartSummaryInput): string | undefined {
|
|
3429
|
+
const key = input.categories[0]
|
|
3430
|
+
if (key === undefined) return undefined
|
|
3431
|
+
const points: { label: string; value: number }[] = []
|
|
3432
|
+
for (const row of input.data) {
|
|
3433
|
+
const raw = row[key]
|
|
3434
|
+
const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
|
|
3435
|
+
if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
|
|
3436
|
+
}
|
|
3437
|
+
const latest = points[points.length - 1]
|
|
3438
|
+
if (!latest) return undefined
|
|
3439
|
+
const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact")
|
|
3440
|
+
const prev = points[points.length - 2]
|
|
3441
|
+
const direction = !prev ? "" : latest.value > prev.value ? "、前の点より増加" : latest.value < prev.value ? "、前の点より減少" : "、前の点と横ばい"
|
|
3442
|
+
const head = input.title ? `${input.title}: ` : ""
|
|
3443
|
+
return `${head}最新 ${latest.label} は ${text(latest.value)}${direction}`
|
|
3444
|
+
}
|
|
3445
|
+
|
|
3446
|
+
/**
|
|
3447
|
+
* `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」 from the slices
|
|
3448
|
+
* (largest first). `undefined` when there is nothing to describe.
|
|
3449
|
+
*/
|
|
3450
|
+
function buildShareSummary(
|
|
3451
|
+
slices: readonly { name: string; value: number }[],
|
|
3452
|
+
title?: string,
|
|
3453
|
+
): string | undefined {
|
|
3454
|
+
const total = slices.reduce((sum, s) => sum + s.value, 0)
|
|
3455
|
+
const top = slices[0]
|
|
3456
|
+
if (!top || total <= 0) return undefined
|
|
3457
|
+
const share = `${Math.round((top.value / total) * 1000) / 10}%`
|
|
3458
|
+
return `${title ? `${title}: ` : ""}最大は ${top.name}(${share})`
|
|
3459
|
+
}
|
|
3460
|
+
|
|
3461
|
+
/* ---------- end of inlined code ---------- */
|
|
3462
|
+
|
|
3463
|
+
// The scatter series is this part's own (`EChart` registers bar / line / pie); `graphic` carries the series heading.
|
|
3464
|
+
use([EScatterChart, GraphicComponent])
|
|
3465
|
+
|
|
3466
|
+
/** 散布図に引く基準線 1 本(`x` なら縦線、`y` なら横線)。中立色の破線で、点の色とは混ざらない。 */
|
|
3467
|
+
export interface ScatterReferenceLine {
|
|
3468
|
+
/** `"x"` は横軸の値に縦線、`"y"` は縦軸の値に横線を引く。 */
|
|
3469
|
+
axis: "x" | "y"
|
|
3470
|
+
/** 線を引く位置(軸の値そのまま。`format` が percent の列でも、列と同じ単位の数値を渡す)。軸の範囲に収まらないときは軸が線まで広がる。 */
|
|
3471
|
+
value: number
|
|
3472
|
+
/** 線の脇に書く短い名前(「目標 25%」)。省略すると線だけ。 */
|
|
3473
|
+
label?: string
|
|
3474
|
+
}
|
|
3475
|
+
|
|
3476
|
+
export interface ScatterChartProps<T extends Record<string, unknown> = Record<string, unknown>>
|
|
3477
|
+
extends Omit<ChartCommonProps<T>, "index" | "categories" | "colors" | "summary" | "labels" | "format" | "valueFormatter"> {
|
|
3478
|
+
/** 行の配列。1 行 = 1 つの点。数値の列は number か数値文字列。x か y が数値でない行は描かない。 */
|
|
3479
|
+
data: T[]
|
|
3480
|
+
/** 横軸に使う数値の列名。例 `"adSpend"`。 */
|
|
3481
|
+
x: NumericKeys<T>
|
|
3482
|
+
/** 縦軸に使う数値の列名。例 `"revenue"`。 */
|
|
3483
|
+
y: NumericKeys<T>
|
|
3484
|
+
/** 点の大きさ(面積)に使う数値の列名。渡すとバブルチャートになる。0 を基準に面積が比例し、null・0 以下は最小の大きさ。ツールチップに値が出る。 */
|
|
3485
|
+
size?: NumericKeys<T>
|
|
3486
|
+
/** 点の名前に使う列名(店舗名・キャンペーン名など)。ツールチップの見出しとデータ表の先頭列になる。 */
|
|
3487
|
+
index?: keyof T & string
|
|
3488
|
+
/**
|
|
3489
|
+
* 点の脇に書く文字の列名(店舗名など)。重なる点のラベルは自動で間引く(ホバーのツールチップには常に出る)。
|
|
3490
|
+
* `index` が無いときはツールチップの見出しとデータ表の名前にもなる。`highlight` を使うと、強調しない系列のラベルは出さない。
|
|
3491
|
+
*/
|
|
3492
|
+
labelKey?: keyof T & string
|
|
3493
|
+
/** 系列分けに使う列名(`"channel"` など)。値ごとに色を分け、凡例を出す。6 つ以上は点の多い 5 つ +「その他」(灰色)にまとまる。 */
|
|
3494
|
+
series?: keyof T & string
|
|
3495
|
+
/** 凡例の見出し(「店の規模」)。`series` があって凡例が出るときだけ、凡例の左に小さく書く。 */
|
|
3496
|
+
seriesLabel?: string
|
|
3497
|
+
/**
|
|
3498
|
+
* 前面に出す系列(`series` 列の値。`"退職"` か `["退職", "休職"]`)。指定した系列は不透明で手前に、指定外は薄く背面に描く。
|
|
3499
|
+
* 数が多い点の中に埋もれる少数の系列を見せたいときに使う。値が系列に一つも当たらないときは強調しない。
|
|
3500
|
+
*/
|
|
3501
|
+
highlight?: string | string[]
|
|
3502
|
+
/**
|
|
3503
|
+
* 基準線(目標・平均・しきい値)。`axis: "x" | "y"` と軸の値で縦線・横線を引く。例 `[{ axis: "y", value: 25, label: "粗利率 25%" }]`
|
|
3504
|
+
* 色は中立色(点の系列色とは別)。線は点の下に敷かず、軸の範囲を線まで広げる。
|
|
3505
|
+
*/
|
|
3506
|
+
referenceLines?: ScatterReferenceLine[]
|
|
3507
|
+
/** 系列色(`"chart-1"`〜`"chart-5"` か意味色)。配列は系列の出現順、record は系列名ごと。省略時はトークン順。「その他」は常に灰色。 */
|
|
3508
|
+
colors?: ChartSeriesColor[] | Partial<Record<string, ChartSeriesColor>>
|
|
3509
|
+
/** 列名・系列の値 → 表示名(軸のタイトル・凡例・ツールチップ・データ表に反映)。例 `{ adSpend: "広告費", revenue: "売上" }`。無いキーはそのまま。データ表の列名の既定は「名前」「系列」「横軸」「縦軸」「大きさ」で、直すには各キーを渡す。 */
|
|
3510
|
+
labels?: Record<string, string>
|
|
3511
|
+
/** 数値の書式。x・y・size の既定の書式(`"compact"` など。`{ type: "number", unit: "件" }` も可)。軸ごとに変えるなら `xFormat` / `yFormat` / `sizeFormat`。既定 `"compact"`。 */
|
|
3512
|
+
format?: ValueFormat
|
|
3513
|
+
/** 横軸と x の値の書式。`format` より優先。 */
|
|
3514
|
+
xFormat?: ValueFormat
|
|
3515
|
+
/** 縦軸と y の値の書式。`format` より優先。 */
|
|
3516
|
+
yFormat?: ValueFormat
|
|
3517
|
+
/** `size` の値の書式(ツールチップ・データ表)。`format` より優先。 */
|
|
3518
|
+
sizeFormat?: ValueFormat
|
|
3519
|
+
/** 書式を関数で直接渡す逃げ道。x・y・size すべてに使われ、`format` 系より優先する。 */
|
|
3520
|
+
valueFormatter?: ValueFormatter
|
|
3521
|
+
/**
|
|
3522
|
+
* 縦軸(y)の下限。散布図は 0 起点にしないので、指定した値から始める。データが下限を下回るときは軸を広げる(切り詰めない)。
|
|
3523
|
+
* 並べて比べる複数の散布図には同じ `minValue` / `maxValue` と `xMinValue` / `xMaxValue` を渡して軸をそろえる。
|
|
3524
|
+
*/
|
|
3525
|
+
minValue?: number
|
|
3526
|
+
/** 縦軸(y)の上限。データが上限を超えるときは軸を広げる(切り詰めない)。並べて比べるときは同じ値を渡す。 */
|
|
3527
|
+
maxValue?: number
|
|
3528
|
+
/** 横軸(x)の下限。データが下限を下回るときは軸を広げる。並べて比べるときは同じ値を渡す。 */
|
|
3529
|
+
xMinValue?: number
|
|
3530
|
+
/** 横軸(x)の上限。データが上限を超えるときは軸を広げる。並べて比べるときは同じ値を渡す。 */
|
|
3531
|
+
xMaxValue?: number
|
|
3532
|
+
/** 両軸をデータの範囲に合わせる。既定 `true`(散布図は位置で読むので 0 起点にしない)。`false` で両軸を 0 から始める。 */
|
|
3533
|
+
fitToData?: boolean
|
|
3534
|
+
/** 凡例(系列が 2 つ以上のときだけ)を出す。既定 `true`。 */
|
|
3535
|
+
showLegend?: boolean
|
|
3536
|
+
/** ホバー時のツールチップを出す。既定 `true`。 */
|
|
3537
|
+
showTooltip?: boolean
|
|
3538
|
+
/**
|
|
3539
|
+
* グラフが言っていることの 1 文要約(自由文)。`"auto"` なら「<見出し>: <点の数>点。<y の列> が最大なのは <名前>(<値>)」を組む(`index` が無いときは最大値だけ)。
|
|
3540
|
+
* 省略時は要約なし。例: `summary="auto"`
|
|
3541
|
+
*/
|
|
3542
|
+
summary?: string | "auto"
|
|
3543
|
+
/** `data` が空(または描ける点が無い)ときの表示。 */
|
|
3544
|
+
emptyState?: ChartEmptyState
|
|
3545
|
+
/** 見出しが無いときのプロット領域の読み上げ名。省略時は「<y の列>×<x の列>の散布図」。 */
|
|
3546
|
+
ariaLabel?: string
|
|
3547
|
+
}
|
|
3548
|
+
|
|
3549
|
+
/* ------------------------------------------------------------------ model */
|
|
3550
|
+
|
|
3551
|
+
export interface ScatterPoint {
|
|
3552
|
+
x: number
|
|
3553
|
+
y: number
|
|
3554
|
+
/** `null` when there is no size column or the cell is missing. */
|
|
3555
|
+
size: number | null
|
|
3556
|
+
/** The point's name (`index` column), or `""`. */
|
|
3557
|
+
name: string
|
|
3558
|
+
/** The series value from the `series` column, or `""`. */
|
|
3559
|
+
series: string
|
|
3560
|
+
/** The `labelKey` text printed beside the dot (`""` / absent without a `labelKey` column). */
|
|
3561
|
+
label?: string
|
|
3562
|
+
row: Record<string, unknown>
|
|
3563
|
+
}
|
|
3564
|
+
|
|
3565
|
+
/** Rows → points. A row whose x or y is not a number is left out. */
|
|
3566
|
+
export function scatterPoints(
|
|
3567
|
+
data: readonly Record<string, unknown>[],
|
|
3568
|
+
config: { x: string; y: string; size?: string; index?: string; series?: string; labelKey?: string },
|
|
3569
|
+
): ScatterPoint[] {
|
|
3570
|
+
const points: ScatterPoint[] = []
|
|
3571
|
+
for (const row of data) {
|
|
3572
|
+
const x = toChartNumber(row[config.x])
|
|
3573
|
+
const y = toChartNumber(row[config.y])
|
|
3574
|
+
if (x === null || y === null) continue
|
|
3575
|
+
points.push({
|
|
3576
|
+
x,
|
|
3577
|
+
y,
|
|
3578
|
+
size: config.size ? toChartNumber(row[config.size]) : null,
|
|
3579
|
+
// Without an `index` column the label column names the dot too (tooltip, table).
|
|
3580
|
+
name: config.index ? String(row[config.index] ?? "") : config.labelKey ? String(row[config.labelKey] ?? "") : "",
|
|
3581
|
+
series: config.series ? String(row[config.series] ?? "") : "",
|
|
3582
|
+
label: config.labelKey ? String(row[config.labelKey] ?? "") : "",
|
|
3583
|
+
row,
|
|
3584
|
+
})
|
|
3585
|
+
}
|
|
3586
|
+
return points
|
|
3587
|
+
}
|
|
3588
|
+
|
|
3589
|
+
export interface ScatterSeries {
|
|
3590
|
+
/** The series name (the `series` value, or「その他」for the folded series). `""` without a `series` column. */
|
|
3591
|
+
name: string
|
|
3592
|
+
isOther: boolean
|
|
3593
|
+
points: ScatterPoint[]
|
|
3594
|
+
}
|
|
3595
|
+
|
|
3596
|
+
/**
|
|
3597
|
+
* Points → series. Series keep their order of first appearance (that order is the
|
|
3598
|
+
* colour order). More than `max` of them: the `max` with the most points are kept
|
|
3599
|
+
* and the rest fold into one trailing「その他」series.
|
|
3600
|
+
*/
|
|
3601
|
+
export function scatterSeries(points: readonly ScatterPoint[], max: number = MAX_CHART_SERIES): ScatterSeries[] {
|
|
3602
|
+
const order: string[] = []
|
|
3603
|
+
const counts = new Map<string, number>()
|
|
3604
|
+
for (const p of points) {
|
|
3605
|
+
if (!counts.has(p.series)) order.push(p.series)
|
|
3606
|
+
counts.set(p.series, (counts.get(p.series) ?? 0) + 1)
|
|
3607
|
+
}
|
|
3608
|
+
if (order.length <= Math.max(1, max)) {
|
|
3609
|
+
return order.map((name) => ({ name, isOther: false, points: points.filter((p) => p.series === name) }))
|
|
3610
|
+
}
|
|
3611
|
+
const ranked = order.map((name, at) => ({ name, at, n: counts.get(name) ?? 0 })).sort((a, b) => b.n - a.n || a.at - b.at)
|
|
3612
|
+
const kept = new Set(ranked.slice(0, Math.max(1, max)).map((r) => r.name))
|
|
3613
|
+
const result: ScatterSeries[] = order
|
|
3614
|
+
.filter((name) => kept.has(name))
|
|
3615
|
+
.map((name) => ({ name, isOther: false, points: points.filter((p) => p.series === name) }))
|
|
3616
|
+
result.push({ name: OTHER_SERIES_LABEL, isOther: true, points: points.filter((p) => !kept.has(p.series)) })
|
|
3617
|
+
return result
|
|
3618
|
+
}
|
|
3619
|
+
|
|
3620
|
+
/** The opacity of a series that is not brought forward by `highlight`. */
|
|
3621
|
+
export const SCATTER_FADED_OPACITY = 0.2
|
|
3622
|
+
|
|
3623
|
+
/** Dot diameter without a size column, and the bubble range (px) with one. */
|
|
3624
|
+
export const SCATTER_DOT_SIZE = 10
|
|
3625
|
+
export const SCATTER_MIN_BUBBLE = 8
|
|
3626
|
+
export const SCATTER_MAX_BUBBLE = 40
|
|
3627
|
+
|
|
3628
|
+
/**
|
|
3629
|
+
* Bubble diameter (px) for a size value: the area is proportional to the value
|
|
3630
|
+
* from 0 (so the diameter goes with its square root), the largest value gets
|
|
3631
|
+
* `SCATTER_MAX_BUBBLE`. A missing, zero or negative value gets the minimum.
|
|
3632
|
+
*/
|
|
3633
|
+
export function scatterBubbleSize(value: number | null | undefined, max: number): number {
|
|
3634
|
+
if (value === null || value === undefined || !(value > 0) || !(max > 0)) return SCATTER_MIN_BUBBLE
|
|
3635
|
+
return Math.max(SCATTER_MIN_BUBBLE, SCATTER_MAX_BUBBLE * Math.sqrt(Math.min(1, value / max)))
|
|
3636
|
+
}
|
|
3637
|
+
|
|
3638
|
+
/** The point's tooltip title: its name, else its series. */
|
|
3639
|
+
function pointTitle(point: ScatterPoint, labels?: Record<string, string>): string {
|
|
3640
|
+
return labelOf(point.name || point.series, labels)
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3643
|
+
/** `summary="auto"`: the point count and the highest y. `undefined` with no points. */
|
|
3644
|
+
export function buildScatterSummary(
|
|
3645
|
+
points: readonly ScatterPoint[],
|
|
3646
|
+
yName: string,
|
|
3647
|
+
yFormatter: ValueFormatter,
|
|
3648
|
+
title?: string,
|
|
3649
|
+
labels?: Record<string, string>,
|
|
3650
|
+
): string | undefined {
|
|
3651
|
+
if (points.length === 0) return undefined
|
|
3652
|
+
let best = points[0]!
|
|
3653
|
+
for (const p of points) if (p.y > best.y) best = p
|
|
3654
|
+
const head = title ? `${title}: ` : ""
|
|
3655
|
+
const who = best.name ? `${labelOf(best.name, labels)}(${yFormatter(best.y)})` : yFormatter(best.y)
|
|
3656
|
+
return `${head}${points.length}点。${labelOf(yName, labels)}が最大なのは ${who}`
|
|
3657
|
+
}
|
|
3658
|
+
|
|
3659
|
+
/** Cap of the screen-reader table (a scatter can hold thousands of dots). */
|
|
3660
|
+
export const SCATTER_TABLE_MAX_ROWS = 100
|
|
3661
|
+
|
|
3662
|
+
/** The screen-reader table: one row per dot (the first `SCATTER_TABLE_MAX_ROWS`). */
|
|
3663
|
+
export function scatterDataTable(
|
|
3664
|
+
points: readonly ScatterPoint[],
|
|
3665
|
+
config: {
|
|
3666
|
+
x: string
|
|
3667
|
+
y: string
|
|
3668
|
+
size?: string
|
|
3669
|
+
index?: string
|
|
3670
|
+
series?: string
|
|
3671
|
+
formatters: { x: ValueFormatter; y: ValueFormatter; size: ValueFormatter }
|
|
3672
|
+
labels?: Record<string, string>
|
|
3673
|
+
referenceLines?: readonly ScatterReferenceLine[]
|
|
3674
|
+
},
|
|
3675
|
+
): ChartDataTable {
|
|
3676
|
+
const label = (key: string) => labelOf(key, config.labels)
|
|
3677
|
+
// Column headers: the caller's `labels`, else a plain Japanese name (not the data key).
|
|
3678
|
+
const column = (key: string, fallback: string) => config.labels?.[key] ?? fallback
|
|
3679
|
+
const columns = [
|
|
3680
|
+
...(config.index ? [column(config.index, "名前")] : []),
|
|
3681
|
+
...(config.series ? [column(config.series, "系列")] : []),
|
|
3682
|
+
column(config.x, "横軸"),
|
|
3683
|
+
column(config.y, "縦軸"),
|
|
3684
|
+
...(config.size ? [column(config.size, "大きさ")] : []),
|
|
3685
|
+
]
|
|
3686
|
+
const shown = points.slice(0, SCATTER_TABLE_MAX_ROWS)
|
|
3687
|
+
const rows = shown.map((p, i) => {
|
|
3688
|
+
const cells = [
|
|
3689
|
+
...(config.index ? [label(p.name)] : []),
|
|
3690
|
+
...(config.series ? [label(p.series)] : []),
|
|
3691
|
+
config.formatters.x(p.x),
|
|
3692
|
+
config.formatters.y(p.y),
|
|
3693
|
+
...(config.size ? [p.size === null ? EMPTY_VALUE : config.formatters.size(p.size)] : []),
|
|
3694
|
+
]
|
|
3695
|
+
// The first column is the row header; without an `index` column, number the dots.
|
|
3696
|
+
return config.index ? cells : [String(i + 1), ...cells]
|
|
3697
|
+
})
|
|
3698
|
+
const base = points.length > shown.length ? `${label(config.y)}×${label(config.x)}(先頭 ${shown.length} 点)` : `${label(config.y)}×${label(config.x)}`
|
|
3699
|
+
// The guide lines carry information the dots do not: read them out with the table.
|
|
3700
|
+
const guides = (config.referenceLines ?? []).map((line) => {
|
|
3701
|
+
const key = line.axis === "x" ? config.x : config.y
|
|
3702
|
+
const text = config.formatters[line.axis](line.value)
|
|
3703
|
+
return line.label ? `${line.label}(${label(key)} ${text})` : `${label(key)} ${text}`
|
|
3704
|
+
})
|
|
3705
|
+
return {
|
|
3706
|
+
caption: guides.length > 0 ? `${base}。基準線: ${guides.join("、")}` : base,
|
|
3707
|
+
columns: config.index ? columns : ["#", ...columns],
|
|
3708
|
+
rows,
|
|
3709
|
+
}
|
|
3710
|
+
}
|
|
3711
|
+
|
|
3712
|
+
/* ----------------------------------------------------------------- option */
|
|
3713
|
+
|
|
3714
|
+
export interface ScatterOptionConfig {
|
|
3715
|
+
series: readonly ScatterSeries[]
|
|
3716
|
+
/** One resolved (canvas-safe) colour per series; `""` leaves the theme palette. */
|
|
3717
|
+
palette: readonly string[]
|
|
3718
|
+
x: string
|
|
3719
|
+
y: string
|
|
3720
|
+
size?: string
|
|
3721
|
+
/** The `series` column, to name the series in a tooltip that is titled by the point's name. */
|
|
3722
|
+
seriesKey?: string
|
|
3723
|
+
labels?: Record<string, string>
|
|
3724
|
+
formatters: { x: ValueFormatter; y: ValueFormatter; size: ValueFormatter }
|
|
3725
|
+
axisFormatters: { x: ValueFormatter; y: ValueFormatter }
|
|
3726
|
+
fitToData?: boolean
|
|
3727
|
+
showLegend?: boolean
|
|
3728
|
+
showTooltip?: boolean
|
|
3729
|
+
/** Heading before the legend (the `series` column's meaning). */
|
|
3730
|
+
seriesLabel?: string
|
|
3731
|
+
/** Series names brought forward; the rest fade and sit behind. Names that match no series are ignored. */
|
|
3732
|
+
highlight?: readonly string[]
|
|
3733
|
+
/** Neutral guide lines; the axes widen to include them. */
|
|
3734
|
+
referenceLines?: readonly ScatterReferenceLine[]
|
|
3735
|
+
/** Print `ScatterPoint.label` beside the dots (overlapping labels are thinned). */
|
|
3736
|
+
showPointLabels?: boolean
|
|
3737
|
+
/** Text colours (resolved tokens): point labels in the foreground, guide lines and the heading muted. */
|
|
3738
|
+
textColors?: { label?: string; muted?: string }
|
|
3739
|
+
/** Make room under the legend for the PNG buttons. */
|
|
3740
|
+
reserveActions?: boolean
|
|
3741
|
+
/** The plot's width (px), when known: the x ticks are thinned to as many as fit side by side. */
|
|
3742
|
+
plotWidth?: number | null
|
|
3743
|
+
chartOptions?: EChartsOption
|
|
3744
|
+
/** Axis limits (see `ScatterChartProps`): `minValue` / `maxValue` are y's, `xMinValue` / `xMaxValue` x's. The axis widens to the data. */
|
|
3745
|
+
minValue?: number
|
|
3746
|
+
maxValue?: number
|
|
3747
|
+
xMinValue?: number
|
|
3748
|
+
xMaxValue?: number
|
|
3749
|
+
}
|
|
3750
|
+
|
|
3751
|
+
/** Under this plot width (px) the chart is "narrow": 2 point labels at most (inward), the legend under the plot, fewer y ticks. */
|
|
3752
|
+
export const SCATTER_NARROW_WIDTH = 480
|
|
3753
|
+
/** Most point labels printed on a narrow plot. */
|
|
3754
|
+
export const SCATTER_NARROW_MAX_LABELS = 2
|
|
3755
|
+
/** Intervals on the y axis of a narrow plot (ECharts' own default is 5). */
|
|
3756
|
+
const SCATTER_NARROW_Y_SPLIT = 3
|
|
3757
|
+
|
|
3758
|
+
/**
|
|
3759
|
+
* The dots that keep their name on a narrow plot: the `SCATTER_NARROW_MAX_LABELS` highest ones (by y) that have a
|
|
3760
|
+
* label, among the series that are in front. Returns `"series index:point index"` keys.
|
|
3761
|
+
*/
|
|
3762
|
+
export function scatterNarrowLabelKeys(series: readonly ScatterSeries[], isFront: (s: ScatterSeries) => boolean): Set<string> {
|
|
3763
|
+
const labelled = series.flatMap((s, si) => (isFront(s) ? s.points.map((p, pi) => ({ key: `${si}:${pi}`, y: p.y, label: p.label })) : []))
|
|
3764
|
+
return new Set(
|
|
3765
|
+
labelled
|
|
3766
|
+
.filter((p) => Boolean(p.label))
|
|
3767
|
+
.sort((a, b) => b.y - a.y)
|
|
3768
|
+
.slice(0, SCATTER_NARROW_MAX_LABELS)
|
|
3769
|
+
.map((p) => p.key),
|
|
3770
|
+
)
|
|
3771
|
+
}
|
|
3772
|
+
|
|
3773
|
+
/** The grid's left and right margins (px) and the gap kept between two x tick labels. */
|
|
3774
|
+
const SCATTER_GRID_X = 48
|
|
3775
|
+
const X_TICK_GAP = 36
|
|
3776
|
+
|
|
3777
|
+
/**
|
|
3778
|
+
* How many x-axis intervals fit in `plotWidth` (px) without the tick labels touching: the plot is its width less
|
|
3779
|
+
* the grid margins and the y tick column, each tick takes the widest label (`xSamples`, the axis' extent printed)
|
|
3780
|
+
* plus a gap. At least 1, at most 6 (ECharts' own default is 5, and rounds to a tidy step either way).
|
|
3781
|
+
*/
|
|
3782
|
+
export function scatterXSplitNumber(plotWidth: number, xSamples: readonly string[], ySamples: readonly string[]): number {
|
|
3783
|
+
const widest = (texts: readonly string[]) => texts.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
|
|
3784
|
+
const plot = plotWidth - SCATTER_GRID_X - (widest(ySamples) + 8)
|
|
3785
|
+
return Math.max(1, Math.min(6, Math.floor(plot / (widest(xSamples) + X_TICK_GAP))))
|
|
3786
|
+
}
|
|
3787
|
+
|
|
3788
|
+
const ROW_STYLE = "display:flex;align-items:center;gap:8px;line-height:20px"
|
|
3789
|
+
|
|
3790
|
+
/** The ECharts option: one scatter series per `ScatterSeries`, value axes titled with the column names. */
|
|
3791
|
+
export function buildScatterOption(config: ScatterOptionConfig): EChartsOption {
|
|
3792
|
+
const { series, palette, labels, formatters, fitToData = true, showTooltip = true } = config
|
|
3793
|
+
const multi = series.length > 1
|
|
3794
|
+
const narrow = Boolean(config.plotWidth && config.plotWidth < SCATTER_NARROW_WIDTH)
|
|
3795
|
+
const showLegend = (config.showLegend ?? true) && multi
|
|
3796
|
+
const maxSize = config.size
|
|
3797
|
+
? series.reduce((m, s) => s.points.reduce((mm, p) => Math.max(mm, p.size ?? 0), m), 0)
|
|
3798
|
+
: 0
|
|
3799
|
+
const names = series.map((s) => (s.name === "" ? labelOf(config.y, labels) : labelOf(s.name, labels)))
|
|
3800
|
+
const extent = (pick: (p: ScatterPoint) => number) => {
|
|
3801
|
+
const values = series.flatMap((s) => s.points.map(pick))
|
|
3802
|
+
return values.length > 0 ? [Math.min(...values), Math.max(...values)] : []
|
|
3803
|
+
}
|
|
3804
|
+
const sample = (values: number[], fmt: ValueFormatter) => values.map((v) => fmt(v))
|
|
3805
|
+
const splitNumber = config.plotWidth
|
|
3806
|
+
? scatterXSplitNumber(
|
|
3807
|
+
config.plotWidth,
|
|
3808
|
+
sample(extent((p) => p.x), config.axisFormatters.x),
|
|
3809
|
+
sample(extent((p) => p.y), config.axisFormatters.y),
|
|
3810
|
+
)
|
|
3811
|
+
: undefined
|
|
3812
|
+
const guides = (config.referenceLines ?? []).filter((line) => Number.isFinite(line.value))
|
|
3813
|
+
const guideValues = (type: "x" | "y") => guides.filter((line) => line.axis === type).map((line) => line.value)
|
|
3814
|
+
// A guide line outside the data's range still has to be on the plot: only then is that edge of the axis set, a little past
|
|
3815
|
+
// the line (a guide inside the data's range leaves ECharts' own tidy ticks alone).
|
|
3816
|
+
const bound = (type: "x" | "y", edge: "min" | "max") => {
|
|
3817
|
+
const at = guideValues(type)
|
|
3818
|
+
const [lo, hi] = extent((p) => p[type])
|
|
3819
|
+
if (at.length === 0 || lo === undefined || hi === undefined) return {}
|
|
3820
|
+
const target = edge === "min" ? Math.min(...at) : Math.max(...at)
|
|
3821
|
+
if (edge === "min" ? target >= lo : target <= hi) return {}
|
|
3822
|
+
const span = Math.max(hi - lo, Math.abs(target - (edge === "min" ? hi : lo)))
|
|
3823
|
+
const pad = span * 0.08
|
|
3824
|
+
return { [edge]: edge === "min" ? target - pad : target + pad }
|
|
3825
|
+
}
|
|
3826
|
+
const highlighted = new Set((config.highlight ?? []).filter((name) => series.some((s) => s.name === name)))
|
|
3827
|
+
const emphasized = highlighted.size > 0
|
|
3828
|
+
const headingWidth = config.seriesLabel && showLegend ? estimateTextWidth(config.seriesLabel) + 12 : 0
|
|
3829
|
+
// The y axis name sits left of the tick labels: its gap grows with the widest tick label, so a short one (「40」) does
|
|
3830
|
+
// not leave the rotated name outside the plot's left edge (the grid's 24 px margin is where the labels start).
|
|
3831
|
+
const yTickWidth = sample(extent((p) => p.y), config.axisFormatters.y).reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
|
|
3832
|
+
const yNameGap = yTickWidth + 20
|
|
3833
|
+
// A limit asked for (`minValue` …) and the edge a guide line needs: the axis reaches whichever is further out, and the data.
|
|
3834
|
+
const requested = { x: { min: config.xMinValue, max: config.xMaxValue }, y: { min: config.minValue, max: config.maxValue } }
|
|
3835
|
+
const limit = (type: "x" | "y", edge: "min" | "max") => {
|
|
3836
|
+
const guide = bound(type, edge)[edge]
|
|
3837
|
+
const asked = requested[type][edge]
|
|
3838
|
+
if (asked === undefined || !Number.isFinite(asked)) return bound(type, edge)
|
|
3839
|
+
const at = [guide, asked].filter((v): v is number => v !== undefined)
|
|
3840
|
+
return edge === "min"
|
|
3841
|
+
? { min: (extent: { min: number; max: number }) => Math.min(...at, extent.min) }
|
|
3842
|
+
: { max: (extent: { min: number; max: number }) => Math.max(...at, extent.max) }
|
|
3843
|
+
}
|
|
3844
|
+
const axis = (key: string, axisFormatter: ValueFormatter, type: "x" | "y") => ({
|
|
3845
|
+
type: "value" as const,
|
|
3846
|
+
scale: fitToData,
|
|
3847
|
+
...limit(type, "min"),
|
|
3848
|
+
...limit(type, "max"),
|
|
3849
|
+
// Few ticks on a narrow plot, and any that would still touch are dropped.
|
|
3850
|
+
...(type === "x" && splitNumber ? { splitNumber } : {}),
|
|
3851
|
+
...(type === "y" && narrow ? { splitNumber: SCATTER_NARROW_Y_SPLIT } : {}),
|
|
3852
|
+
name: labelOf(key, labels),
|
|
3853
|
+
nameLocation: "middle" as const,
|
|
3854
|
+
nameGap: type === "x" ? 28 : yNameGap,
|
|
3855
|
+
axisLine: { show: false },
|
|
3856
|
+
axisTick: { show: false },
|
|
3857
|
+
splitLine: { show: true },
|
|
3858
|
+
axisLabel: { formatter: (v: number) => axisFormatter(v), ...(type === "x" ? { hideOverlap: true } : {}) },
|
|
3859
|
+
})
|
|
3860
|
+
// A narrow plot wraps the legend onto more lines: the grid starts below the last one, so the top y tick never sits under it.
|
|
3861
|
+
const legendLineCount = (() => {
|
|
3862
|
+
if (!showLegend || !config.plotWidth) return 1
|
|
3863
|
+
const room = Math.max(80, config.plotWidth - headingWidth - (config.reserveActions ? 72 : 0))
|
|
3864
|
+
const need = names.reduce((sum, name) => sum + estimateTextWidth(name) + 8 + 5 + 16, 0)
|
|
3865
|
+
return Math.min(3, Math.max(1, Math.ceil(need / room)))
|
|
3866
|
+
})()
|
|
3867
|
+
// Narrow: the legend sits under the plot (the top stays free for the dots and the PNG buttons).
|
|
3868
|
+
const legendBelow = narrow && showLegend
|
|
3869
|
+
const xs = extent((p) => p.x)
|
|
3870
|
+
const keptLabels = narrow && config.showPointLabels ? scatterNarrowLabelKeys(series, (s) => !emphasized || highlighted.has(s.name)) : null
|
|
3871
|
+
const option = {
|
|
3872
|
+
...chartMotion(false),
|
|
3873
|
+
legend: {
|
|
3874
|
+
show: showLegend,
|
|
3875
|
+
...(legendBelow ? { bottom: 0 } : { top: 0 }),
|
|
3876
|
+
// With a heading the legend reads from the left, after it; otherwise it sits at the right edge.
|
|
3877
|
+
...(headingWidth > 0 ? { left: headingWidth } : legendBelow ? { left: 0 } : { right: config.reserveActions ? 72 : 0 }),
|
|
3878
|
+
type: "plain",
|
|
3879
|
+
icon: "circle",
|
|
3880
|
+
itemWidth: 8,
|
|
3881
|
+
itemHeight: 8,
|
|
3882
|
+
itemGap: 16,
|
|
3883
|
+
data: names,
|
|
3884
|
+
},
|
|
3885
|
+
// A vertical guide's name sits above the plot's top edge: keep that line free.
|
|
3886
|
+
grid: {
|
|
3887
|
+
top:
|
|
3888
|
+
(showLegend && !legendBelow ? 12 + 24 * legendLineCount : 12) +
|
|
3889
|
+
(guides.some((line) => line.axis === "x" && line.label) && (!showLegend || legendBelow) ? 14 : 0),
|
|
3890
|
+
right: 24,
|
|
3891
|
+
bottom: legendBelow ? 24 + 24 * legendLineCount : 24,
|
|
3892
|
+
left: 24,
|
|
3893
|
+
containLabel: true,
|
|
3894
|
+
},
|
|
3895
|
+
...(headingWidth > 0
|
|
3896
|
+
? {
|
|
3897
|
+
graphic: [
|
|
3898
|
+
{
|
|
3899
|
+
type: "text" as const,
|
|
3900
|
+
left: 0,
|
|
3901
|
+
...(legendBelow ? { bottom: 4 } : { top: 2 }),
|
|
3902
|
+
silent: true,
|
|
3903
|
+
style: { text: config.seriesLabel, fill: config.textColors?.muted, fontSize: 12 },
|
|
3904
|
+
},
|
|
3905
|
+
],
|
|
3906
|
+
}
|
|
3907
|
+
: {}),
|
|
3908
|
+
tooltip: {
|
|
3909
|
+
show: showTooltip,
|
|
3910
|
+
trigger: "item",
|
|
3911
|
+
formatter: (params: unknown) => {
|
|
3912
|
+
const p = (params as { data?: { point?: ScatterPoint }; color?: unknown }).data?.point
|
|
3913
|
+
if (!p) return ""
|
|
3914
|
+
const color = escapeHtml(typeof (params as { color?: unknown }).color === "string" ? ((params as { color: string }).color) : "currentColor")
|
|
3915
|
+
const line = (name: string, text: string, dot = false) =>
|
|
3916
|
+
`<div style="${ROW_STYLE}">` +
|
|
3917
|
+
(dot ? `<span style="display:inline-block;width:8px;height:8px;border-radius:9999px;background:${color}"></span>` : "") +
|
|
3918
|
+
`<span style="flex:1;opacity:.8">${escapeHtml(name)}</span>` +
|
|
3919
|
+
`<span style="font-weight:500;font-variant-numeric:tabular-nums;margin-left:12px">${escapeHtml(text)}</span></div>`
|
|
3920
|
+
const title = pointTitle(p, labels)
|
|
3921
|
+
const rows = [
|
|
3922
|
+
...(p.name && p.series && config.seriesKey ? [line(labelOf(config.seriesKey, labels), labelOf(p.series, labels), true)] : []),
|
|
3923
|
+
line(labelOf(config.x, labels), formatters.x(p.x), !(p.name && p.series && config.seriesKey)),
|
|
3924
|
+
line(labelOf(config.y, labels), formatters.y(p.y)),
|
|
3925
|
+
...(config.size ? [line(labelOf(config.size, labels), p.size === null ? EMPTY_VALUE : formatters.size(p.size))] : []),
|
|
3926
|
+
]
|
|
3927
|
+
return `${title ? `<div style="font-weight:500;margin-bottom:4px">${escapeHtml(title)}</div>` : ""}${rows.join("")}`
|
|
3928
|
+
},
|
|
3929
|
+
},
|
|
3930
|
+
xAxis: axis(config.x, config.axisFormatters.x, "x"),
|
|
3931
|
+
yAxis: axis(config.y, config.axisFormatters.y, "y"),
|
|
3932
|
+
series: series.map((s, i) => {
|
|
3933
|
+
const front = !emphasized || highlighted.has(s.name)
|
|
3934
|
+
return {
|
|
3935
|
+
id: `series:${s.name}`,
|
|
3936
|
+
name: names[i],
|
|
3937
|
+
type: "scatter" as const,
|
|
3938
|
+
// Brought-forward series draw above the rest (and later), the others stay behind.
|
|
3939
|
+
z: front && emphasized ? 3 : 2,
|
|
3940
|
+
symbolSize: config.size
|
|
3941
|
+
? (value: unknown) => scatterBubbleSize(Array.isArray(value) ? (value[2] as number | null) : null, maxSize)
|
|
3942
|
+
: SCATTER_DOT_SIZE,
|
|
3943
|
+
itemStyle: { color: palette[i] || undefined, opacity: !front ? SCATTER_FADED_OPACITY : config.size ? 0.7 : emphasized ? 1 : 0.85 },
|
|
3944
|
+
emphasis: { focus: "self" as const, scale: 1.1 },
|
|
3945
|
+
...(config.showPointLabels && front
|
|
3946
|
+
? {
|
|
3947
|
+
label: {
|
|
3948
|
+
show: keptLabels === null,
|
|
3949
|
+
position: "right" as const,
|
|
3950
|
+
distance: 6,
|
|
3951
|
+
fontSize: 11,
|
|
3952
|
+
color: config.textColors?.label,
|
|
3953
|
+
// Plain text: an outline / shadow reads as a halo on a dark surface.
|
|
3954
|
+
textBorderWidth: 0,
|
|
3955
|
+
textShadowBlur: 0,
|
|
3956
|
+
formatter: (p: { data?: { point?: ScatterPoint } }) => p.data?.point?.label ?? "",
|
|
3957
|
+
},
|
|
3958
|
+
labelLayout: { hideOverlap: true, moveOverlap: "shiftY" as const },
|
|
3959
|
+
}
|
|
3960
|
+
: {}),
|
|
3961
|
+
// The guide lines hang off the first series (a markLine belongs to one).
|
|
3962
|
+
...(i === 0 && guides.length > 0
|
|
3963
|
+
? {
|
|
3964
|
+
markLine: {
|
|
3965
|
+
silent: true,
|
|
3966
|
+
symbol: "none",
|
|
3967
|
+
animation: false,
|
|
3968
|
+
// ECharts rounds a mark line's value to 2 decimals unless told otherwise.
|
|
3969
|
+
precision: 20,
|
|
3970
|
+
lineStyle: { type: "dashed" as const, width: 1, color: config.textColors?.muted },
|
|
3971
|
+
data: guides.map((line) => ({
|
|
3972
|
+
...(line.axis === "x" ? { xAxis: line.value } : { yAxis: line.value }),
|
|
3973
|
+
label: {
|
|
3974
|
+
show: Boolean(line.label),
|
|
3975
|
+
formatter: line.label ?? "",
|
|
3976
|
+
position: line.axis === "x" ? ("end" as const) : ("insideEndTop" as const),
|
|
3977
|
+
color: config.textColors?.muted,
|
|
3978
|
+
fontSize: 11,
|
|
3979
|
+
},
|
|
3980
|
+
})),
|
|
3981
|
+
},
|
|
3982
|
+
}
|
|
3983
|
+
: {}),
|
|
3984
|
+
data: s.points.map((point, pi) => ({
|
|
3985
|
+
value: [point.x, point.y, point.size],
|
|
3986
|
+
point,
|
|
3987
|
+
// Narrow: only the kept dots are named, and the name turns inward so it stays inside the plot.
|
|
3988
|
+
...(keptLabels && config.showPointLabels && front && keptLabels.has(`${i}:${pi}`)
|
|
3989
|
+
? { label: { show: true, position: xs.length === 2 && point.x > (xs[0]! + xs[1]!) / 2 ? ("left" as const) : ("right" as const) } }
|
|
3990
|
+
: {}),
|
|
3991
|
+
})),
|
|
3992
|
+
}
|
|
3993
|
+
}),
|
|
3994
|
+
}
|
|
3995
|
+
return mergeChartOptions(option as EChartsOption, config.chartOptions)
|
|
3996
|
+
}
|
|
3997
|
+
|
|
3998
|
+
/** The colours of the series, in order — the same function `Legend` uses, so the two always match. */
|
|
3999
|
+
export function scatterSeriesColors(
|
|
4000
|
+
series: readonly ScatterSeries[],
|
|
4001
|
+
colors: ScatterChartProps["colors"],
|
|
4002
|
+
): string[] {
|
|
4003
|
+
const other = series.find((s) => s.isOther)?.name ?? null
|
|
4004
|
+
return seriesColorsFor(
|
|
4005
|
+
series.map((s) => s.name),
|
|
4006
|
+
colors,
|
|
4007
|
+
CHART_OTHER_COLOR,
|
|
4008
|
+
other,
|
|
4009
|
+
)
|
|
4010
|
+
}
|
|
4011
|
+
|
|
4012
|
+
/* -------------------------------------------------------------- component */
|
|
4013
|
+
|
|
4014
|
+
/** Rows not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
|
|
4015
|
+
const NO_ROWS: never[] = []
|
|
4016
|
+
|
|
4017
|
+
function ScatterChartImpl<T extends Record<string, unknown>>(
|
|
4018
|
+
{
|
|
4019
|
+
data = NO_ROWS,
|
|
4020
|
+
x,
|
|
4021
|
+
y,
|
|
4022
|
+
size,
|
|
4023
|
+
index,
|
|
4024
|
+
labelKey,
|
|
4025
|
+
series: seriesKey,
|
|
4026
|
+
seriesLabel,
|
|
4027
|
+
highlight,
|
|
4028
|
+
referenceLines,
|
|
4029
|
+
colors,
|
|
4030
|
+
labels,
|
|
4031
|
+
format,
|
|
4032
|
+
xFormat,
|
|
4033
|
+
yFormat,
|
|
4034
|
+
sizeFormat,
|
|
4035
|
+
valueFormatter,
|
|
4036
|
+
fitToData = true,
|
|
4037
|
+
showLegend = true,
|
|
4038
|
+
showTooltip = true,
|
|
4039
|
+
title,
|
|
4040
|
+
summary,
|
|
4041
|
+
actions,
|
|
4042
|
+
fileName,
|
|
4043
|
+
isLoading,
|
|
4044
|
+
emptyState,
|
|
4045
|
+
height,
|
|
4046
|
+
chartOptions,
|
|
4047
|
+
minValue,
|
|
4048
|
+
maxValue,
|
|
4049
|
+
xMinValue,
|
|
4050
|
+
xMaxValue,
|
|
4051
|
+
ariaLabel,
|
|
4052
|
+
className,
|
|
4053
|
+
...rest
|
|
4054
|
+
}: ScatterChartProps<T>,
|
|
4055
|
+
ref: ForwardedRef<HTMLDivElement>,
|
|
4056
|
+
) {
|
|
4057
|
+
const tokens = useChartTokens()
|
|
4058
|
+
const { ref: frameRef, width: plotWidth } = useChartSurface(ref, tokens)
|
|
4059
|
+
// Tooltips and the table read in full; axis ticks read short.
|
|
4060
|
+
const formatters = useMemo(
|
|
4061
|
+
() => ({
|
|
4062
|
+
x: resolveValueFormatter(valueFormatter, xFormat ?? format),
|
|
4063
|
+
y: resolveValueFormatter(valueFormatter, yFormat ?? format),
|
|
4064
|
+
size: resolveValueFormatter(valueFormatter, sizeFormat ?? format),
|
|
4065
|
+
}),
|
|
4066
|
+
[valueFormatter, xFormat, yFormat, sizeFormat, format],
|
|
4067
|
+
)
|
|
4068
|
+
const axisFormatters = useMemo(
|
|
4069
|
+
() => ({
|
|
4070
|
+
x: resolveAxisFormatter(valueFormatter, xFormat ?? format),
|
|
4071
|
+
y: resolveAxisFormatter(valueFormatter, yFormat ?? format),
|
|
4072
|
+
}),
|
|
4073
|
+
[valueFormatter, xFormat, yFormat, format],
|
|
4074
|
+
)
|
|
4075
|
+
const points = useMemo(
|
|
4076
|
+
() => scatterPoints(data, { x, y, size, index, series: seriesKey, labelKey }),
|
|
4077
|
+
[data, x, y, size, index, seriesKey, labelKey],
|
|
4078
|
+
)
|
|
4079
|
+
const series = useMemo(() => scatterSeries(points), [points])
|
|
4080
|
+
const palette = useMemo(
|
|
4081
|
+
() => resolveChartColors(scatterSeriesColors(series, colors).map(chartFillName), tokens),
|
|
4082
|
+
[series, colors, tokens],
|
|
4083
|
+
)
|
|
4084
|
+
const highlightList = useMemo(() => (highlight === undefined ? undefined : Array.isArray(highlight) ? highlight : [highlight]), [highlight])
|
|
4085
|
+
const option = useMemo(
|
|
4086
|
+
() =>
|
|
4087
|
+
buildScatterOption({
|
|
4088
|
+
series,
|
|
4089
|
+
palette,
|
|
4090
|
+
x,
|
|
4091
|
+
y,
|
|
4092
|
+
size,
|
|
4093
|
+
seriesKey,
|
|
4094
|
+
seriesLabel,
|
|
4095
|
+
highlight: highlightList,
|
|
4096
|
+
referenceLines,
|
|
4097
|
+
showPointLabels: Boolean(labelKey),
|
|
4098
|
+
textColors: { label: tokens?.foreground ?? undefined, muted: tokens?.mutedForeground ?? undefined },
|
|
4099
|
+
labels,
|
|
4100
|
+
formatters,
|
|
4101
|
+
axisFormatters,
|
|
4102
|
+
fitToData,
|
|
4103
|
+
showLegend,
|
|
4104
|
+
showTooltip,
|
|
4105
|
+
reserveActions: Boolean(actions),
|
|
4106
|
+
plotWidth,
|
|
4107
|
+
chartOptions,
|
|
4108
|
+
minValue,
|
|
4109
|
+
maxValue,
|
|
4110
|
+
xMinValue,
|
|
4111
|
+
xMaxValue,
|
|
4112
|
+
}),
|
|
4113
|
+
[series, palette, x, y, size, seriesKey, seriesLabel, highlightList, referenceLines, labelKey, tokens, labels, formatters, axisFormatters, fitToData, showLegend, showTooltip, actions, plotWidth, chartOptions, minValue, maxValue, xMinValue, xMaxValue],
|
|
4114
|
+
)
|
|
4115
|
+
const dataTable = useMemo(
|
|
4116
|
+
() => scatterDataTable(points, { x, y, size, index: index ?? labelKey, series: seriesKey, formatters, labels, referenceLines }),
|
|
4117
|
+
[points, x, y, size, index, labelKey, seriesKey, formatters, labels, referenceLines],
|
|
4118
|
+
)
|
|
4119
|
+
const resolvedSummary = useMemo(
|
|
4120
|
+
() => (summary === "auto" ? buildScatterSummary(points, y, formatters.y, title, labels) : summary),
|
|
4121
|
+
[summary, points, y, formatters, title, labels],
|
|
4122
|
+
)
|
|
4123
|
+
const label = ariaLabel ?? `${labelOf(y, labels)}×${labelOf(x, labels)}の散布図`
|
|
4124
|
+
return (
|
|
4125
|
+
<ChartFrame
|
|
4126
|
+
{...chartRootProps(rest)}
|
|
4127
|
+
ref={frameRef}
|
|
4128
|
+
title={title}
|
|
4129
|
+
summary={resolvedSummary}
|
|
4130
|
+
isLoading={isLoading ?? false}
|
|
4131
|
+
isEmpty={points.length === 0}
|
|
4132
|
+
emptyState={emptyState}
|
|
4133
|
+
height={height}
|
|
4134
|
+
variant="line"
|
|
4135
|
+
ariaLabel={label}
|
|
4136
|
+
className={className}
|
|
4137
|
+
dataTable={dataTable}
|
|
4138
|
+
>
|
|
4139
|
+
<EChart option={option} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
|
|
4140
|
+
</ChartFrame>
|
|
4141
|
+
)
|
|
4142
|
+
}
|
|
4143
|
+
|
|
4144
|
+
/** Generic over the row type, so `x` / `y` / `size` / `index` / `series` keys are checked against `data`. */
|
|
4145
|
+
export const ScatterChart = forwardRef(ScatterChartImpl as (props: ScatterChartProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
|
|
4146
|
+
T extends Record<string, unknown>,
|
|
4147
|
+
>(
|
|
4148
|
+
props: ScatterChartProps<T> & { ref?: Ref<HTMLDivElement> },
|
|
4149
|
+
) => ReactElement) & { displayName?: string }
|
|
4150
|
+
ScatterChart.displayName = "ScatterChart"
|