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