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