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