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