@squadbase/vantage 0.6.2-dev1.b332e5a → 0.6.2-dev1.d7c0911
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/add-4GHF2TX2.js +6 -0
- package/dist/add-4GHF2TX2.js.map +1 -0
- package/dist/{build-TVKFIVFQ.js → build-X5NVCQKT.js} +7 -7
- package/dist/{build-TVKFIVFQ.js.map → build-X5NVCQKT.js.map} +1 -1
- package/dist/{check-3KHZXZMQ.js → check-ZBIH422T.js} +5 -5
- package/dist/{check-3KHZXZMQ.js.map → check-ZBIH422T.js.map} +1 -1
- package/dist/chunk-2ICNHUG6.js +1820 -0
- package/dist/chunk-2ICNHUG6.js.map +1 -0
- package/dist/{chunk-5ZOP4SQR.js → chunk-2N72FKLB.js} +12 -7
- package/dist/chunk-2N72FKLB.js.map +1 -0
- package/dist/{chunk-P7W4LR3Z.js → chunk-7DZGJQ3P.js} +3 -3
- package/dist/{chunk-P7W4LR3Z.js.map → chunk-7DZGJQ3P.js.map} +1 -1
- package/dist/{chunk-U2M6HGKQ.js → chunk-AABMKHEU.js} +4 -4
- package/dist/{chunk-U2M6HGKQ.js.map → chunk-AABMKHEU.js.map} +1 -1
- package/dist/{chunk-QI3XQKHS.js → chunk-GNXCX4WE.js} +10 -3
- package/dist/chunk-GNXCX4WE.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-ZVANIULZ.js → chunk-RNTDBX6S.js} +4 -4
- package/dist/{chunk-ZVANIULZ.js.map → chunk-RNTDBX6S.js.map} +1 -1
- package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
- package/dist/chunk-U736PVHY.js.map +1 -0
- package/dist/{chunk-PVTHHV7X.js → chunk-V3LF7BE7.js} +27 -5
- package/dist/chunk-V3LF7BE7.js.map +1 -0
- package/dist/{chunk-LMUACBMA.js → chunk-WAMZWZJB.js} +53 -8
- package/dist/chunk-WAMZWZJB.js.map +1 -0
- package/dist/chunk-WRSX2MDK.js +7866 -0
- package/dist/chunk-WRSX2MDK.js.map +1 -0
- package/dist/{chunk-RPZAALCX.js → chunk-XPQSTZUU.js} +254 -164
- package/dist/chunk-XPQSTZUU.js.map +1 -0
- package/dist/{chunk-DTDVSFRY.js → chunk-XQUSGIDG.js} +17 -3
- package/dist/chunk-XQUSGIDG.js.map +1 -0
- package/dist/cli.js +12 -11
- package/dist/cli.js.map +1 -1
- package/dist/client/index.d.ts +32 -3
- package/dist/client/index.js +205 -12
- package/dist/client/index.js.map +1 -1
- package/dist/components/index.d.ts +1975 -28
- package/dist/components/index.js +4 -4
- package/dist/{dev-GDKATCC7.js → dev-4XEDTELV.js} +8 -8
- package/dist/dev-4XEDTELV.js.map +1 -0
- package/dist/doc/index.js +2 -2
- package/dist/doc/index.js.map +1 -1
- package/dist/{docs-EJJ3BECT.js → docs-JVP4RPKT.js} +3 -3
- package/dist/{docs-EJJ3BECT.js.map → docs-JVP4RPKT.js.map} +1 -1
- package/dist/{doctor-WQXPXP6K.js → doctor-5E2VEZPK.js} +5 -5
- package/dist/{doctor-WQXPXP6K.js.map → doctor-5E2VEZPK.js.map} +1 -1
- package/dist/markdown/index.js +1 -1
- package/dist/markdown/index.js.map +1 -1
- package/dist/{preview-OGMCNQUO.js → preview-T6CLSQVX.js} +3 -3
- package/dist/{preview-OGMCNQUO.js.map → preview-T6CLSQVX.js.map} +1 -1
- package/dist/query/index.d.ts +0 -11
- package/dist/query/index.js +2 -2
- package/dist/{routes-MWBWWOJ2.js → routes-3SGAFDMC.js} +4 -4
- package/dist/{routes-MWBWWOJ2.js.map → routes-3SGAFDMC.js.map} +1 -1
- package/dist/{search-6Y422SV6.js → search-5LC4XPB5.js} +3 -3
- package/dist/{search-6Y422SV6.js.map → search-5LC4XPB5.js.map} +1 -1
- package/dist/table/index.js +10 -9
- package/dist/table/index.js.map +1 -1
- package/dist/ui/index.d.ts +144 -11
- package/dist/ui/index.js +1339 -87
- package/dist/ui/index.js.map +1 -1
- package/dist/{upgrade-HCANX4GQ.js → upgrade-JHXZBGQS.js} +6 -6
- package/dist/{upgrade-HCANX4GQ.js.map → upgrade-JHXZBGQS.js.map} +1 -1
- package/dist/vite/index.d.ts +10 -0
- package/dist/vite/index.js +3 -3
- package/docs/en/components.md +29 -15
- package/docs/en/parts/data-table.md +22 -0
- package/docs/en/parts/delta.md +50 -0
- package/docs/en/parts/format.md +43 -0
- package/docs/en/parts/kpi-card.md +57 -0
- package/docs/en/parts/metric-value.md +3 -2
- package/docs/en/parts/sparkline.md +1 -1
- package/docs/en/parts/trend-indicator.md +17 -1
- package/docs/en/ui-and-theming.md +1 -1
- package/docs/index.json +366 -76
- package/docs/ja/changelog.md +31 -0
- package/docs/ja/components.md +57 -101
- package/docs/ja/page-types/csv.md +83 -0
- package/docs/ja/page-types/doc.md +83 -0
- package/docs/ja/page-types/excel.md +82 -0
- package/docs/ja/page-types/slide.md +132 -0
- package/docs/ja/page-types.md +47 -0
- package/docs/ja/parts/area-chart.md +61 -0
- package/docs/ja/parts/bar-chart.md +69 -0
- package/docs/ja/parts/bar-list.md +35 -0
- package/docs/ja/parts/category-bar.md +36 -0
- package/docs/ja/parts/data-table.md +22 -0
- package/docs/ja/parts/delta.md +50 -0
- package/docs/ja/parts/donut-chart.md +47 -0
- package/docs/ja/parts/echart.md +3 -0
- package/docs/ja/parts/format.md +44 -0
- package/docs/ja/parts/kpi-card.md +55 -0
- package/docs/ja/parts/line-chart.md +58 -0
- package/docs/ja/parts/metric-value.md +3 -2
- package/docs/ja/parts/progress-circle.md +34 -0
- package/docs/ja/parts/sparkline.md +2 -2
- package/docs/ja/parts/tracker.md +32 -0
- package/docs/ja/parts/trend-indicator.md +17 -1
- package/docs/ja/routing.md +8 -86
- package/docs/ja/ui/alert-dialog.md +41 -0
- package/docs/ja/ui/avatar.md +31 -0
- package/docs/ja/ui/combobox.md +74 -0
- package/docs/ja/ui/drawer.md +41 -0
- package/docs/ja/ui/field.md +42 -0
- package/docs/ja/ui/hover-card.md +21 -0
- package/docs/ja/ui/kbd.md +16 -0
- package/docs/ja/ui/pagination.md +36 -0
- package/docs/ja/ui/radio-group.md +21 -0
- package/docs/ja/ui/toast.md +46 -0
- package/docs/ja/ui-and-theming.md +14 -7
- package/package.json +13 -4
- package/registry/ui/accordion.tsx +76 -0
- package/registry/ui/alert-dialog.tsx +189 -0
- package/registry/ui/alert.tsx +80 -0
- package/registry/ui/app-shell.tsx +287 -0
- package/registry/ui/area-chart.tsx +3639 -0
- package/registry/ui/avatar.tsx +110 -0
- package/registry/ui/badge.tsx +56 -0
- package/registry/ui/bar-chart.tsx +3636 -0
- package/registry/ui/bar-list.tsx +3680 -0
- package/registry/ui/breadcrumb.tsx +128 -0
- package/registry/ui/button.tsx +62 -0
- package/registry/ui/calendar.tsx +223 -0
- package/registry/ui/card.tsx +107 -0
- package/registry/ui/category-bar.tsx +1255 -0
- package/registry/ui/chart-frame.tsx +1358 -0
- package/registry/ui/checkbox.tsx +30 -0
- package/registry/ui/collapsible.tsx +23 -0
- package/registry/ui/combobox.tsx +310 -0
- package/registry/ui/command.tsx +198 -0
- package/registry/ui/dashboard-card.tsx +217 -0
- package/registry/ui/data-table.tsx +693 -146
- package/registry/ui/date-range-picker.tsx +390 -0
- package/registry/ui/delta.tsx +188 -0
- package/registry/ui/dialog.tsx +161 -0
- package/registry/ui/donut-chart.tsx +3688 -0
- package/registry/ui/drawer.tsx +229 -0
- package/registry/ui/dropdown-menu.tsx +274 -0
- package/registry/ui/echart.tsx +890 -0
- package/registry/ui/field.tsx +240 -0
- package/registry/ui/filter-bar.tsx +392 -0
- package/registry/ui/funnel-steps.tsx +3541 -0
- package/registry/ui/heatmap.tsx +1752 -0
- package/registry/ui/hover-card.tsx +52 -0
- package/registry/ui/input-group.tsx +160 -0
- package/registry/ui/input.tsx +24 -0
- package/registry/ui/kbd.tsx +30 -0
- package/registry/ui/kpi-card.tsx +677 -0
- package/registry/ui/label.tsx +22 -0
- package/registry/ui/legend.tsx +3500 -0
- package/registry/ui/line-chart.tsx +3637 -0
- package/registry/ui/metric-value.tsx +62 -0
- package/registry/ui/multi-select.tsx +232 -0
- package/registry/ui/page-shell.tsx +282 -0
- package/registry/ui/pagination.tsx +140 -0
- package/registry/ui/placeholder.tsx +36 -0
- package/registry/ui/popover.tsx +92 -0
- package/registry/ui/progress-circle.tsx +867 -0
- package/registry/ui/progress.tsx +85 -0
- package/registry/ui/radio-group.tsx +39 -0
- package/registry/ui/sample-data.tsx +86 -0
- package/registry/ui/scatter-chart.tsx +4150 -0
- package/registry/ui/scroll-area.tsx +56 -0
- package/registry/ui/searchable-select.tsx +214 -0
- package/registry/ui/section-header.tsx +43 -0
- package/registry/ui/segmented-control.tsx +76 -0
- package/registry/ui/select.tsx +255 -0
- package/registry/ui/separator.tsx +27 -0
- package/registry/ui/sheet.tsx +139 -0
- package/registry/ui/sidebar.tsx +725 -0
- package/registry/ui/skeleton.tsx +17 -0
- package/registry/ui/slider.tsx +56 -0
- package/registry/ui/sparkline.tsx +230 -0
- package/registry/ui/spinner.tsx +14 -0
- package/registry/ui/states.tsx +90 -0
- package/registry/ui/status-badge.tsx +121 -0
- package/registry/ui/switch.tsx +34 -0
- package/registry/ui/table.tsx +118 -0
- package/registry/ui/tabs.tsx +84 -0
- package/registry/ui/textarea.tsx +22 -0
- package/registry/ui/toast.tsx +250 -0
- package/registry/ui/toggle-group.tsx +91 -0
- package/registry/ui/toggle.tsx +47 -0
- package/registry/ui/tooltip.tsx +68 -0
- package/registry/ui/tracker.tsx +843 -0
- package/registry/ui/trend-indicator.tsx +74 -0
- package/registry/ui/updated-at.tsx +122 -0
- package/registry/ui/waterfall-chart.tsx +4186 -0
- package/skills/vantage-add-feature/SKILL.md +9 -7
- package/skills/vantage-pitfalls/SKILL.md +5 -1
- package/templates/AGENTS.md +22 -1
- package/templates/agents/csv.md +2 -1
- package/templates/agents/doc.md +4 -3
- package/templates/agents/page.md +20 -6
- package/templates/agents/xlsx.md +2 -1
- package/theme.css +237 -136
- package/dist/add-DY4AXANK.js +0 -6
- package/dist/add-DY4AXANK.js.map +0 -1
- package/dist/chunk-5ZOP4SQR.js.map +0 -1
- package/dist/chunk-A2UUGASH.js.map +0 -1
- package/dist/chunk-DTDVSFRY.js.map +0 -1
- package/dist/chunk-LMUACBMA.js.map +0 -1
- package/dist/chunk-NKFBFDRZ.js +0 -2241
- package/dist/chunk-NKFBFDRZ.js.map +0 -1
- package/dist/chunk-PVTHHV7X.js.map +0 -1
- package/dist/chunk-PXRX5PEC.js.map +0 -1
- package/dist/chunk-QI3XQKHS.js.map +0 -1
- package/dist/chunk-RPZAALCX.js.map +0 -1
- package/dist/chunk-VA776YE5.js +0 -316
- package/dist/chunk-VA776YE5.js.map +0 -1
- package/dist/dev-GDKATCC7.js.map +0 -1
|
@@ -0,0 +1,890 @@
|
|
|
1
|
+
// Copied by `vantage add ui echart`. This file is yours to edit.
|
|
2
|
+
// Generated from @squadbase/squadkit registry/charts/echart.tsx by `npm run registry` (in Vantage, edit packages/squadkit, not registry/).
|
|
3
|
+
"use client"
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* EChart — a thin Apache ECharts wrapper. It owns the canvas lifecycle (init,
|
|
7
|
+
* resize, dispose), forwards `option` and event handlers, drives the loading
|
|
8
|
+
* spinner, and can copy/download the chart as a PNG.
|
|
9
|
+
*
|
|
10
|
+
* Colours follow the design tokens: `--chart-1..5` become the series palette,
|
|
11
|
+
* and the text/border/popover tokens style axes, legend and tooltip. They're
|
|
12
|
+
* resolved once at init (see `chart-theme.ts`) and re-read whenever they can
|
|
13
|
+
* have changed — a light/dark flip, or a stylesheet swap such as editing
|
|
14
|
+
* `styles.css` while the dev server is running. `theme` opts out entirely;
|
|
15
|
+
* `option.color` overrides just the palette and keeps the rest.
|
|
16
|
+
*
|
|
17
|
+
* Pitfall: the canvas can't read CSS. A colour written into the option as
|
|
18
|
+
* `"var(--chart-1)"`, `"chart-1"` or `"oklch(…)"` paints black (or nothing).
|
|
19
|
+
* Leave colours out and the tokens apply; when you must set one yourself, pass
|
|
20
|
+
* it through `useResolvedChartColors` and use the result:
|
|
21
|
+
*
|
|
22
|
+
* @example
|
|
23
|
+
* const [accent] = useResolvedChartColors(["chart-2"])
|
|
24
|
+
* const option = { series: [{ type: "line", data, lineStyle: { color: accent } }] }
|
|
25
|
+
* return <EChart option={option} />
|
|
26
|
+
*
|
|
27
|
+
* Updates merge instead of replacing (`replaceMerge` on every component type in
|
|
28
|
+
* play), so series with a stable `id` transition to their new values while
|
|
29
|
+
* anything dropped from the option is still removed. With
|
|
30
|
+
* `prefers-reduced-motion: reduce` every animation is off.
|
|
31
|
+
*
|
|
32
|
+
* ECharts is loaded modularly (`echarts/core`): only the bar / line / pie series (and `custom`, which draws
|
|
33
|
+
* the per-bar target marker),
|
|
34
|
+
* the components the typed charts emit and the canvas renderer are registered
|
|
35
|
+
* below. To draw anything else with `<EChart>` (scatter, funnel, dataZoom, …),
|
|
36
|
+
* register it once in your own code:
|
|
37
|
+
*
|
|
38
|
+
* @example
|
|
39
|
+
* import { use } from "echarts/core"
|
|
40
|
+
* import { ScatterChart } from "echarts/charts"
|
|
41
|
+
* use([ScatterChart])
|
|
42
|
+
*/
|
|
43
|
+
import { forwardRef, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react"
|
|
44
|
+
import { init, use } from "echarts/core"
|
|
45
|
+
import { BarChart, CustomChart, LineChart, PieChart } from "echarts/charts"
|
|
46
|
+
import {
|
|
47
|
+
GridComponent,
|
|
48
|
+
LegendComponent,
|
|
49
|
+
MarkAreaComponent,
|
|
50
|
+
MarkLineComponent,
|
|
51
|
+
MarkPointComponent,
|
|
52
|
+
TooltipComponent,
|
|
53
|
+
} from "echarts/components"
|
|
54
|
+
import { CanvasRenderer } from "echarts/renderers"
|
|
55
|
+
import type { ECharts, EChartsOption } from "echarts"
|
|
56
|
+
import { Check, Copy, Download } from "lucide-react"
|
|
57
|
+
|
|
58
|
+
import { cn } from "@squadbase/vantage/ui"
|
|
59
|
+
import { Button } from "@squadbase/vantage/ui"
|
|
60
|
+
import type { ChartActionsOptions } from "@squadbase/vantage/components"
|
|
61
|
+
import { createContext, type ForwardedRef } from "react"
|
|
62
|
+
import type { ChartTone } from "@squadbase/vantage/components"
|
|
63
|
+
|
|
64
|
+
/* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The colour of the folded「その他」series / slice / row. The ONLY place this
|
|
68
|
+
* grey is defined — every chart takes it from here. It is the most subdued
|
|
69
|
+
* colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
|
|
70
|
+
* `--background`, so it recedes in light and dark alike (and brand themes follow
|
|
71
|
+
* it). `--neutral-subtle` alone sits too close to the background to read as a
|
|
72
|
+
* slice. Canvas charts resolve it through `resolveChartColors`.
|
|
73
|
+
*/
|
|
74
|
+
const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* True inside `ChartFrame`. The frame's plot area carries the chart's single
|
|
78
|
+
* `role="img"` and label, so `EChart` drops its own when it sees this.
|
|
79
|
+
*/
|
|
80
|
+
const ChartFrameContext = createContext(false)
|
|
81
|
+
|
|
82
|
+
/** Series palette, in order. Missing tokens are skipped, not defaulted. */
|
|
83
|
+
const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
|
|
84
|
+
|
|
85
|
+
interface ChartTokens {
|
|
86
|
+
/** Resolved `--chart-1..5`, in order. */
|
|
87
|
+
series: string[]
|
|
88
|
+
/** Body text: titles and the default `textStyle`. */
|
|
89
|
+
foreground: string | null
|
|
90
|
+
/** Secondary text: axis labels, legend, subtitles. */
|
|
91
|
+
mutedForeground: string | null
|
|
92
|
+
/** Axis lines, ticks, split lines, tooltip border. */
|
|
93
|
+
border: string | null
|
|
94
|
+
/** Tooltip surface. */
|
|
95
|
+
popover: string | null
|
|
96
|
+
/** Tooltip text. */
|
|
97
|
+
popoverForeground: string | null
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
let normalizeContext: CanvasRenderingContext2D | null | undefined
|
|
101
|
+
|
|
102
|
+
/** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
|
|
103
|
+
const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Serialize a CSS colour into a canvas-safe form, or `null` if the browser
|
|
107
|
+
* rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
|
|
108
|
+
* input is written over two different known colours: agreeing results mean the
|
|
109
|
+
* value parsed, differing ones mean it was dropped.
|
|
110
|
+
*/
|
|
111
|
+
function toCanvasColor(value: string): string | null {
|
|
112
|
+
const raw = value.trim()
|
|
113
|
+
if (!raw) return null
|
|
114
|
+
if (normalizeContext === undefined) {
|
|
115
|
+
const canvas = document.createElement("canvas")
|
|
116
|
+
canvas.width = 1
|
|
117
|
+
canvas.height = 1
|
|
118
|
+
normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
|
|
119
|
+
}
|
|
120
|
+
const ctx = normalizeContext
|
|
121
|
+
if (!ctx) return raw
|
|
122
|
+
ctx.fillStyle = "#000000"
|
|
123
|
+
ctx.fillStyle = raw
|
|
124
|
+
const onBlack = ctx.fillStyle
|
|
125
|
+
ctx.fillStyle = "#ffffff"
|
|
126
|
+
ctx.fillStyle = raw
|
|
127
|
+
if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
|
|
128
|
+
if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
|
|
129
|
+
// Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
|
|
130
|
+
// Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
|
|
131
|
+
ctx.clearRect(0, 0, 1, 1)
|
|
132
|
+
ctx.fillRect(0, 0, 1, 1)
|
|
133
|
+
const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
|
|
134
|
+
return a === 255
|
|
135
|
+
? `rgb(${r}, ${g}, ${b})`
|
|
136
|
+
: `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Read the chart tokens off `el` (the document root by default — tokens live on
|
|
141
|
+
* `:root` and inherit). Returns `null` outside the browser so callers fall back
|
|
142
|
+
* to plain ECharts defaults.
|
|
143
|
+
*/
|
|
144
|
+
function readChartTokens(el?: Element | null): ChartTokens | null {
|
|
145
|
+
if (typeof document === "undefined") return null
|
|
146
|
+
const target = el ?? document.documentElement
|
|
147
|
+
if (!target) return null
|
|
148
|
+
const styles = getComputedStyle(target)
|
|
149
|
+
const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
|
|
150
|
+
const series: string[] = []
|
|
151
|
+
for (const token of SERIES_TOKENS) {
|
|
152
|
+
const color = read(token)
|
|
153
|
+
if (color) series.push(color)
|
|
154
|
+
}
|
|
155
|
+
return {
|
|
156
|
+
series,
|
|
157
|
+
foreground: read("--foreground"),
|
|
158
|
+
mutedForeground: read("--muted-foreground"),
|
|
159
|
+
border: read("--border"),
|
|
160
|
+
popover: read("--popover"),
|
|
161
|
+
popoverForeground: read("--popover-foreground"),
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
|
|
166
|
+
function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
|
|
167
|
+
if (a === b) return true
|
|
168
|
+
if (!a || !b) return false
|
|
169
|
+
return (
|
|
170
|
+
a.series.length === b.series.length &&
|
|
171
|
+
a.series.every((color, i) => color === b.series[i]) &&
|
|
172
|
+
a.foreground === b.foreground &&
|
|
173
|
+
a.mutedForeground === b.mutedForeground &&
|
|
174
|
+
a.border === b.border &&
|
|
175
|
+
a.popover === b.popover &&
|
|
176
|
+
a.popoverForeground === b.popoverForeground
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Watch everything that can change the resolved tokens and call `onChange` when
|
|
182
|
+
* something might have. It only ever says "re-read" — the caller compares with
|
|
183
|
+
* `sameChartTokens` and decides whether anything actually moved. Returns a
|
|
184
|
+
* disposer.
|
|
185
|
+
*
|
|
186
|
+
* Two sources, not one:
|
|
187
|
+
* - light/dark flips, which land as `class` / `data-theme` (or an inline
|
|
188
|
+
* `style`) on `<html>`/`<body>`, or as an OS preference change
|
|
189
|
+
* - stylesheet changes. In dev, editing `styles.css` rewrites the injected
|
|
190
|
+
* `<style>` in `<head>` and touches nothing else, so watching the theme
|
|
191
|
+
* attributes alone leaves the chart painted in the previous palette until a
|
|
192
|
+
* reload — the tokens in the DOM are new, the canvas is not.
|
|
193
|
+
*/
|
|
194
|
+
function watchChartTokens(onChange: () => void): () => void {
|
|
195
|
+
if (typeof document === "undefined") return () => {}
|
|
196
|
+
// Style edits arrive as bursts of mutations; coalesce them into one read, and
|
|
197
|
+
// take it after the next frame so a swapped stylesheet has been applied.
|
|
198
|
+
let frame = 0
|
|
199
|
+
const schedule = () => {
|
|
200
|
+
if (frame) return
|
|
201
|
+
frame = requestAnimationFrame(() => {
|
|
202
|
+
frame = 0
|
|
203
|
+
onChange()
|
|
204
|
+
})
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const themeObserver = new MutationObserver(schedule)
|
|
208
|
+
const attributeFilter = ["class", "style", "data-theme"]
|
|
209
|
+
themeObserver.observe(document.documentElement, { attributes: true, attributeFilter })
|
|
210
|
+
if (document.body) themeObserver.observe(document.body, { attributes: true, attributeFilter })
|
|
211
|
+
|
|
212
|
+
const styleObserver = new MutationObserver(schedule)
|
|
213
|
+
if (document.head) {
|
|
214
|
+
styleObserver.observe(document.head, {
|
|
215
|
+
childList: true,
|
|
216
|
+
subtree: true,
|
|
217
|
+
characterData: true,
|
|
218
|
+
attributes: true,
|
|
219
|
+
attributeFilter: ["href", "media", "disabled"],
|
|
220
|
+
})
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// A swapped `<link>` only applies once the sheet has loaded, after its mutation.
|
|
224
|
+
const onLoad = (event: Event) => {
|
|
225
|
+
if (event.target instanceof HTMLLinkElement) schedule()
|
|
226
|
+
}
|
|
227
|
+
document.addEventListener("load", onLoad, true)
|
|
228
|
+
|
|
229
|
+
const media = window.matchMedia("(prefers-color-scheme: dark)")
|
|
230
|
+
media.addEventListener("change", schedule)
|
|
231
|
+
|
|
232
|
+
return () => {
|
|
233
|
+
if (frame) cancelAnimationFrame(frame)
|
|
234
|
+
themeObserver.disconnect()
|
|
235
|
+
styleObserver.disconnect()
|
|
236
|
+
document.removeEventListener("load", onLoad, true)
|
|
237
|
+
media.removeEventListener("change", schedule)
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Shared shape for the four axis types ECharts themes address separately. */
|
|
242
|
+
function axisTheme(tokens: ChartTokens, splitLine: boolean) {
|
|
243
|
+
const line = tokens.border ?? undefined
|
|
244
|
+
return {
|
|
245
|
+
axisLine: { show: false },
|
|
246
|
+
axisTick: { show: false },
|
|
247
|
+
axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
|
|
248
|
+
// Faint horizontal rules only: the border colour at low opacity.
|
|
249
|
+
splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
|
|
250
|
+
splitArea: { show: false },
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Build the ECharts theme. `option.color` still wins over `theme.color`, so an
|
|
256
|
+
* app that sets its own palette keeps it.
|
|
257
|
+
*/
|
|
258
|
+
function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
|
|
259
|
+
const text = tokens.foreground ?? undefined
|
|
260
|
+
const muted = tokens.mutedForeground ?? undefined
|
|
261
|
+
const line = tokens.border ?? undefined
|
|
262
|
+
return {
|
|
263
|
+
// Let the page background show through: charts sit on cards, not on a canvas.
|
|
264
|
+
backgroundColor: "transparent",
|
|
265
|
+
...(tokens.series.length > 0 ? { color: tokens.series } : {}),
|
|
266
|
+
textStyle: { color: text },
|
|
267
|
+
title: { textStyle: { color: text }, subtextStyle: { color: muted } },
|
|
268
|
+
legend: { textStyle: { color: muted } },
|
|
269
|
+
categoryAxis: axisTheme(tokens, false),
|
|
270
|
+
valueAxis: axisTheme(tokens, true),
|
|
271
|
+
logAxis: axisTheme(tokens, true),
|
|
272
|
+
timeAxis: axisTheme(tokens, true),
|
|
273
|
+
tooltip: {
|
|
274
|
+
// ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
|
|
275
|
+
transitionDuration: 0,
|
|
276
|
+
backgroundColor: tokens.popover ?? undefined,
|
|
277
|
+
borderColor: line,
|
|
278
|
+
borderWidth: 1,
|
|
279
|
+
padding: [8, 12],
|
|
280
|
+
// Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
|
|
281
|
+
extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
|
|
282
|
+
textStyle: { color: tokens.popoverForeground ?? undefined, fontSize: 12 },
|
|
283
|
+
axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
|
|
284
|
+
},
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/**
|
|
289
|
+
* The resolved tokens, kept current: re-read whenever `watchChartTokens` says
|
|
290
|
+
* they may have moved, and only replaced when a value actually changed. For
|
|
291
|
+
* components that build an ECharts option from token colours themselves (the
|
|
292
|
+
* typed charts), so their palette follows light/dark like `EChart`'s theme.
|
|
293
|
+
*/
|
|
294
|
+
function useChartTokens(): ChartTokens | null {
|
|
295
|
+
const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
|
|
296
|
+
// Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
|
|
297
|
+
// replayed by React on every rebase and returns a fresh object each time, so the state
|
|
298
|
+
// never settles ("Maximum update depth exceeded" once the tokens change after mount).
|
|
299
|
+
const tokensRef = useRef(tokens)
|
|
300
|
+
useEffect(() => {
|
|
301
|
+
const sync = () => {
|
|
302
|
+
const next = readChartTokens()
|
|
303
|
+
if (sameChartTokens(tokensRef.current, next)) return
|
|
304
|
+
tokensRef.current = next
|
|
305
|
+
setTokens(next)
|
|
306
|
+
}
|
|
307
|
+
sync()
|
|
308
|
+
return watchChartTokens(sync)
|
|
309
|
+
}, [])
|
|
310
|
+
return tokens
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
|
|
314
|
+
const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
|
|
315
|
+
const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
|
|
316
|
+
const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
|
|
320
|
+
* the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
|
|
321
|
+
* variants `"positive-fill"`, …) are read off the document root (`--positive`, …); `var(--token)` is read off the document root; any
|
|
322
|
+
* other CSS colour is normalized like the tokens are. A colour that can't be
|
|
323
|
+
* resolved comes back as `""`, which ECharts treats as "use the palette".
|
|
324
|
+
*/
|
|
325
|
+
function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
|
|
326
|
+
return colors.map((color) => {
|
|
327
|
+
const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
|
|
328
|
+
if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
|
|
329
|
+
// Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
|
|
330
|
+
if (TONE_NAME_RE.test(color.trim())) {
|
|
331
|
+
if (typeof document === "undefined") return ""
|
|
332
|
+
return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue(`--${color.trim()}`)) ?? ""
|
|
333
|
+
}
|
|
334
|
+
if (typeof document === "undefined") return color
|
|
335
|
+
let value = color.trim()
|
|
336
|
+
const cssVar = CSS_VAR_RE.exec(value)
|
|
337
|
+
const styles = getComputedStyle(document.documentElement)
|
|
338
|
+
if (cssVar) {
|
|
339
|
+
value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
|
|
340
|
+
} else if (value.includes("var(")) {
|
|
341
|
+
// A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
|
|
342
|
+
// substitute the tokens, then let the canvas resolve the rest.
|
|
343
|
+
value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
|
|
344
|
+
}
|
|
345
|
+
return toCanvasColor(value) ?? ""
|
|
346
|
+
})
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
|
|
350
|
+
function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
|
|
351
|
+
const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
|
|
352
|
+
["positive", "warning", "negative", "neutral"],
|
|
353
|
+
tokens,
|
|
354
|
+
)
|
|
355
|
+
return { positive, warning, negative, neutral }
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
|
|
359
|
+
function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
|
|
360
|
+
const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
|
|
361
|
+
["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
|
|
362
|
+
tokens,
|
|
363
|
+
)
|
|
364
|
+
return { positive, warning, negative, neutral }
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* The colour the chart is painted on: the first opaque `background-color` up
|
|
371
|
+
* from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
|
|
372
|
+
* outside the browser.
|
|
373
|
+
*/
|
|
374
|
+
function readChartSurface(el: Element | null): string | null {
|
|
375
|
+
if (typeof document === "undefined") return null
|
|
376
|
+
for (let node: Element | null = el; node; node = node.parentElement) {
|
|
377
|
+
const bg = getComputedStyle(node).backgroundColor.trim()
|
|
378
|
+
if (bg && !TRANSPARENT_RE.test(bg)) {
|
|
379
|
+
const color = toCanvasColor(bg)
|
|
380
|
+
if (color) return color
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return toCanvasColor(getComputedStyle(document.documentElement).getPropertyValue("--background"))
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
|
|
387
|
+
const WIDTH_BUCKET = 40
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* The surface colour behind a chart (see `readChartSurface`), re-read when the
|
|
391
|
+
* tokens move (light/dark), and the plot's width (rounded down to 40px;
|
|
392
|
+
* `undefined` until measured). Returns a ref for the plot that also feeds the
|
|
393
|
+
* component's forwarded ref.
|
|
394
|
+
*/
|
|
395
|
+
function useChartSurface<E extends Element>(
|
|
396
|
+
forwarded: ForwardedRef<E>,
|
|
397
|
+
tokens: ChartTokens | null,
|
|
398
|
+
): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined } {
|
|
399
|
+
const [node, setNode] = useState<E | null>(null)
|
|
400
|
+
const [surface, setSurface] = useState<string | undefined>(undefined)
|
|
401
|
+
const [width, setWidth] = useState<number | undefined>(undefined)
|
|
402
|
+
const ref = useCallback(
|
|
403
|
+
(el: E | null) => {
|
|
404
|
+
setNode(el)
|
|
405
|
+
if (typeof forwarded === "function") forwarded(el)
|
|
406
|
+
else if (forwarded) forwarded.current = el
|
|
407
|
+
},
|
|
408
|
+
[forwarded],
|
|
409
|
+
)
|
|
410
|
+
useEffect(() => {
|
|
411
|
+
if (!node) return
|
|
412
|
+
setSurface(readChartSurface(node) ?? undefined)
|
|
413
|
+
}, [node, tokens])
|
|
414
|
+
useEffect(() => {
|
|
415
|
+
if (!node || typeof ResizeObserver === "undefined") return
|
|
416
|
+
const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
|
|
417
|
+
update(node.getBoundingClientRect().width)
|
|
418
|
+
const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
|
|
419
|
+
observer.observe(node)
|
|
420
|
+
return () => observer.disconnect()
|
|
421
|
+
}, [node])
|
|
422
|
+
return { ref, surface, width }
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
/* ---------- end of inlined code ---------- */
|
|
426
|
+
|
|
427
|
+
// What the typed charts (Bar / Line / Area / Donut) emit. Other series and
|
|
428
|
+
// components are the consumer's to `use()` — see the note at the top.
|
|
429
|
+
use([
|
|
430
|
+
BarChart,
|
|
431
|
+
CustomChart,
|
|
432
|
+
LineChart,
|
|
433
|
+
PieChart,
|
|
434
|
+
GridComponent,
|
|
435
|
+
LegendComponent,
|
|
436
|
+
MarkAreaComponent,
|
|
437
|
+
MarkLineComponent,
|
|
438
|
+
MarkPointComponent,
|
|
439
|
+
TooltipComponent,
|
|
440
|
+
CanvasRenderer,
|
|
441
|
+
])
|
|
442
|
+
|
|
443
|
+
export interface EChartProps {
|
|
444
|
+
/**
|
|
445
|
+
* ECharts のオプション。
|
|
446
|
+
*
|
|
447
|
+
* 型推論を効かせるため、必ず `EChartsOption` を annotation するか
|
|
448
|
+
* `satisfies EChartsOption` を付けること。付けないと `type: "category"` などの
|
|
449
|
+
* literal が `string` に拡張され、ビルドが失敗する。
|
|
450
|
+
*
|
|
451
|
+
* @example
|
|
452
|
+
* import type { EChartsOption } from "@/components/echart"
|
|
453
|
+
*
|
|
454
|
+
* const option: EChartsOption = {
|
|
455
|
+
* xAxis: { type: "category", data: ["A", "B"] },
|
|
456
|
+
* yAxis: { type: "value" },
|
|
457
|
+
* series: [{ type: "bar", data: [1, 2] }],
|
|
458
|
+
* }
|
|
459
|
+
* <EChart option={option} />
|
|
460
|
+
*/
|
|
461
|
+
option: EChartsOption
|
|
462
|
+
/**
|
|
463
|
+
* チャートの高さ。数値は px、文字列は CSS 値(例: `"50vh"`)として扱う。
|
|
464
|
+
*
|
|
465
|
+
* 省略した場合は外側ラッパーに `h-[400px]` がデフォルトで当たるが、`className` に
|
|
466
|
+
* `h-full` や `h-[360px]` などの高さクラスを渡せばそちらが優先される
|
|
467
|
+
* (`h-full` を使う場合は親要素に確定した高さが必要)。
|
|
468
|
+
* `height` と `className` の高さを両方指定した場合は `height`(インライン style)が勝つ。
|
|
469
|
+
*/
|
|
470
|
+
height?: string | number
|
|
471
|
+
loading?: boolean
|
|
472
|
+
/**
|
|
473
|
+
* `echarts.init` にそのまま渡すテーマ(名前または登録済みテーマオブジェクト)。
|
|
474
|
+
*
|
|
475
|
+
* 渡すとデザイントークン追従は**完全に無効**になり、明暗の切り替えにも追従しなく
|
|
476
|
+
* なる。系列色だけ変えたいなら `option.color` を使う ― option はテーマより優先
|
|
477
|
+
* されるので、軸・凡例・ツールチップのトークン追従は残る。
|
|
478
|
+
*/
|
|
479
|
+
theme?: string | object
|
|
480
|
+
onEvents?: Record<string, (params: unknown) => void>
|
|
481
|
+
ariaLabel?: string
|
|
482
|
+
className?: string
|
|
483
|
+
/**
|
|
484
|
+
* true にするとチャート右上に PNG コピー / ダウンロードボタンを表示する。
|
|
485
|
+
* `exportHeader` があれば PNG の上にその見出しを含める(`{ includeTitle: false }` で含めない)。
|
|
486
|
+
*/
|
|
487
|
+
actions?: boolean | ChartActionsOptions
|
|
488
|
+
/** ダウンロード時のファイル名(拡張子含む)。省略時は "chart.png" */
|
|
489
|
+
fileName?: string
|
|
490
|
+
/**
|
|
491
|
+
* PNG の上に含める見出しと要約。型付きグラフは自分の `title` / `summary` を渡す。
|
|
492
|
+
* 自分で `ChartFrame` を組むときも同じものを渡すと、保存した画像だけで何のグラフか分かる。
|
|
493
|
+
*/
|
|
494
|
+
exportHeader?: ChartExportHeader
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/** The heading a saved PNG carries above the plot. */
|
|
498
|
+
export interface ChartExportHeader {
|
|
499
|
+
title?: string
|
|
500
|
+
summary?: string
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
const HEADER_PAD_X = 16
|
|
504
|
+
const HEADER_PAD_TOP = 16
|
|
505
|
+
const HEADER_PAD_BOTTOM = 12
|
|
506
|
+
const HEADER_LINE_HEIGHT = 20
|
|
507
|
+
const HEADER_GAP = 4
|
|
508
|
+
const HEADER_FONT_SIZE = 14
|
|
509
|
+
|
|
510
|
+
export interface ChartExportHeaderLine {
|
|
511
|
+
text: string
|
|
512
|
+
kind: "title" | "summary"
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Break `text` into lines no wider than `maxWidth` (px, via `measure`), character
|
|
517
|
+
* by character so Japanese wraps without spaces. Always at least one line for
|
|
518
|
+
* non-empty text; a single over-wide character still gets its own line.
|
|
519
|
+
*/
|
|
520
|
+
export function wrapChartText(text: string, maxWidth: number, measure: (text: string) => number): string[] {
|
|
521
|
+
const lines: string[] = []
|
|
522
|
+
let line = ""
|
|
523
|
+
for (const ch of text) {
|
|
524
|
+
if (ch === "\n") {
|
|
525
|
+
lines.push(line)
|
|
526
|
+
line = ""
|
|
527
|
+
continue
|
|
528
|
+
}
|
|
529
|
+
if (line !== "" && measure(line + ch) > maxWidth) {
|
|
530
|
+
lines.push(line)
|
|
531
|
+
line = ch.trim() === "" ? "" : ch
|
|
532
|
+
} else {
|
|
533
|
+
line += ch
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
if (line !== "" || lines.length === 0) lines.push(line)
|
|
537
|
+
return lines.filter((l, i) => l !== "" || i < lines.length - 1)
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* The lines and total height (CSS px) of the PNG's heading band for a plot
|
|
542
|
+
* `width` px wide. `measure` takes (text, kind) and returns its width in px.
|
|
543
|
+
* No title and no summary → no band (`height` 0).
|
|
544
|
+
*/
|
|
545
|
+
export function chartExportHeaderLayout(
|
|
546
|
+
header: ChartExportHeader | undefined,
|
|
547
|
+
width: number,
|
|
548
|
+
measure: (text: string, kind: "title" | "summary") => number,
|
|
549
|
+
): { lines: ChartExportHeaderLine[]; height: number } {
|
|
550
|
+
const title = header?.title?.trim()
|
|
551
|
+
const summary = header?.summary?.trim()
|
|
552
|
+
if (!title && !summary) return { lines: [], height: 0 }
|
|
553
|
+
const room = Math.max(40, width - HEADER_PAD_X * 2)
|
|
554
|
+
const lines: ChartExportHeaderLine[] = [
|
|
555
|
+
...(title ? wrapChartText(title, room, (t) => measure(t, "title")).map((text) => ({ text, kind: "title" as const })) : []),
|
|
556
|
+
...(summary ? wrapChartText(summary, room, (t) => measure(t, "summary")).map((text) => ({ text, kind: "summary" as const })) : []),
|
|
557
|
+
]
|
|
558
|
+
const gap = title && summary ? HEADER_GAP : 0
|
|
559
|
+
return { lines, height: HEADER_PAD_TOP + lines.length * HEADER_LINE_HEIGHT + gap + HEADER_PAD_BOTTOM }
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function loadImage(src: string): Promise<HTMLImageElement> {
|
|
563
|
+
return new Promise((resolve, reject) => {
|
|
564
|
+
const image = new Image()
|
|
565
|
+
image.onload = () => resolve(image)
|
|
566
|
+
image.onerror = () => reject(new Error("PNG の読み込みに失敗しました"))
|
|
567
|
+
image.src = src
|
|
568
|
+
})
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Draw a heading band (title in foreground, summary muted) above the exported plot and return the new PNG. */
|
|
572
|
+
async function pngWithHeader(
|
|
573
|
+
dataUrl: string,
|
|
574
|
+
header: ChartExportHeader,
|
|
575
|
+
look: { background: string; color: string; mutedColor: string; fontFamily: string },
|
|
576
|
+
pixelRatio: number,
|
|
577
|
+
): Promise<string> {
|
|
578
|
+
const image = await loadImage(dataUrl)
|
|
579
|
+
const width = image.width / pixelRatio
|
|
580
|
+
const plotHeight = image.height / pixelRatio
|
|
581
|
+
const canvas = document.createElement("canvas")
|
|
582
|
+
const ctx = canvas.getContext("2d")
|
|
583
|
+
if (!ctx) return dataUrl
|
|
584
|
+
const font = (kind: "title" | "summary") => `${kind === "title" ? 500 : 400} ${HEADER_FONT_SIZE}px ${look.fontFamily}`
|
|
585
|
+
ctx.font = font("title")
|
|
586
|
+
const layout = chartExportHeaderLayout(header, width, (text, kind) => {
|
|
587
|
+
ctx.font = font(kind)
|
|
588
|
+
return ctx.measureText(text).width
|
|
589
|
+
})
|
|
590
|
+
if (layout.height === 0) return dataUrl
|
|
591
|
+
canvas.width = Math.round(image.width)
|
|
592
|
+
canvas.height = Math.round((layout.height + plotHeight) * pixelRatio)
|
|
593
|
+
ctx.scale(pixelRatio, pixelRatio)
|
|
594
|
+
ctx.fillStyle = look.background
|
|
595
|
+
ctx.fillRect(0, 0, width, layout.height + plotHeight)
|
|
596
|
+
ctx.textBaseline = "middle"
|
|
597
|
+
let y = HEADER_PAD_TOP
|
|
598
|
+
let previous: "title" | "summary" | null = null
|
|
599
|
+
for (const line of layout.lines) {
|
|
600
|
+
if (previous === "title" && line.kind === "summary") y += HEADER_GAP
|
|
601
|
+
ctx.font = font(line.kind)
|
|
602
|
+
ctx.fillStyle = line.kind === "title" ? look.color : look.mutedColor
|
|
603
|
+
ctx.fillText(line.text, HEADER_PAD_X, y + HEADER_LINE_HEIGHT / 2)
|
|
604
|
+
y += HEADER_LINE_HEIGHT
|
|
605
|
+
previous = line.kind
|
|
606
|
+
}
|
|
607
|
+
ctx.drawImage(image, 0, layout.height, width, plotHeight)
|
|
608
|
+
return canvas.toDataURL("image/png")
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/**
|
|
612
|
+
* Canvas-safe versions of theme colours, kept current across light/dark.
|
|
613
|
+
* Takes `"chart-1"`〜`"chart-5"`, `"var(--token)"` or any CSS colour; one that
|
|
614
|
+
* can't be resolved comes back as `""` (ECharts then uses the palette).
|
|
615
|
+
* Use it whenever a colour goes into a raw `EChart` option by hand.
|
|
616
|
+
*
|
|
617
|
+
* @example
|
|
618
|
+
* const [line, band] = useResolvedChartColors(["chart-1", "var(--muted-foreground)"])
|
|
619
|
+
*/
|
|
620
|
+
export function useResolvedChartColors(colors: readonly string[]): string[] {
|
|
621
|
+
const tokens = useChartTokens()
|
|
622
|
+
const key = colors.join("\u0000")
|
|
623
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps -- `key` stands for the array's contents
|
|
624
|
+
return useMemo(() => resolveChartColors(colors, tokens), [key, tokens])
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
type EChartsEventHandler = (params: unknown) => void
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* ECharts component main types. Listed in `replaceMerge`, a type keeps only the
|
|
631
|
+
* components whose `id` matches (merged, so they can transition) and drops the
|
|
632
|
+
* rest — including every one of them when the new option no longer has the type.
|
|
633
|
+
*/
|
|
634
|
+
const COMPONENT_MAIN_TYPES = new Set([
|
|
635
|
+
"title", "legend", "grid", "xAxis", "yAxis", "polar", "radiusAxis", "angleAxis", "radar",
|
|
636
|
+
"dataZoom", "visualMap", "tooltip", "axisPointer", "toolbox", "brush", "geo", "parallel",
|
|
637
|
+
"parallelAxis", "singleAxis", "graphic", "calendar", "dataset", "series", "matrix", "thumbnail",
|
|
638
|
+
])
|
|
639
|
+
|
|
640
|
+
export interface EChartSetOptionOpts {
|
|
641
|
+
notMerge: boolean
|
|
642
|
+
replaceMerge?: string[]
|
|
643
|
+
lazyUpdate: boolean
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* How to apply `next` after `prev`: the first option and timeline / media
|
|
648
|
+
* options replace everything; otherwise merge, replacing every component type
|
|
649
|
+
* either option uses so nothing stale survives.
|
|
650
|
+
*/
|
|
651
|
+
export function echartSetOptionOpts(prev: EChartsOption | null, next: EChartsOption): EChartSetOptionOpts {
|
|
652
|
+
const special = (o: EChartsOption) => "timeline" in o || "baseOption" in o || "options" in o || "media" in o
|
|
653
|
+
if (!prev || special(prev) || special(next)) return { notMerge: true, lazyUpdate: true }
|
|
654
|
+
const types = new Set<string>()
|
|
655
|
+
for (const key of [...Object.keys(prev), ...Object.keys(next)]) if (COMPONENT_MAIN_TYPES.has(key)) types.add(key)
|
|
656
|
+
return { notMerge: false, replaceMerge: [...types], lazyUpdate: true }
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** `option` as applied: reduced motion forces `animation: false`; otherwise animation stays explicit so it can flip back. */
|
|
660
|
+
export function withMotionPreference(option: EChartsOption, reducedMotion: boolean): EChartsOption {
|
|
661
|
+
return { ...option, animation: reducedMotion ? false : (option.animation ?? true) }
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const REDUCED_MOTION_QUERY = "(prefers-reduced-motion: reduce)"
|
|
665
|
+
|
|
666
|
+
/** `prefers-reduced-motion: reduce`, kept current. `false` on the server. */
|
|
667
|
+
export function usePrefersReducedMotion(): boolean {
|
|
668
|
+
const [reduced, setReduced] = useState(
|
|
669
|
+
() => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(REDUCED_MOTION_QUERY).matches,
|
|
670
|
+
)
|
|
671
|
+
useEffect(() => {
|
|
672
|
+
if (typeof window === "undefined" || typeof window.matchMedia !== "function") return
|
|
673
|
+
const media = window.matchMedia(REDUCED_MOTION_QUERY)
|
|
674
|
+
const sync = () => setReduced(media.matches)
|
|
675
|
+
sync()
|
|
676
|
+
media.addEventListener("change", sync)
|
|
677
|
+
return () => media.removeEventListener("change", sync)
|
|
678
|
+
}, [])
|
|
679
|
+
return reduced
|
|
680
|
+
}
|
|
681
|
+
|
|
682
|
+
export const EChart = forwardRef<HTMLDivElement, EChartProps>(function EChart(
|
|
683
|
+
{
|
|
684
|
+
option,
|
|
685
|
+
height,
|
|
686
|
+
loading = false,
|
|
687
|
+
theme,
|
|
688
|
+
onEvents,
|
|
689
|
+
ariaLabel,
|
|
690
|
+
className,
|
|
691
|
+
actions = false,
|
|
692
|
+
fileName = "chart.png",
|
|
693
|
+
exportHeader,
|
|
694
|
+
},
|
|
695
|
+
ref,
|
|
696
|
+
) {
|
|
697
|
+
const containerRef = useRef<HTMLDivElement | null>(null)
|
|
698
|
+
const [instance, setInstance] = useState<ECharts | null>(null)
|
|
699
|
+
const [copied, setCopied] = useState(false)
|
|
700
|
+
// 初回はレンダー前に読めるので、マウント直後の作り直しが起きない
|
|
701
|
+
const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
|
|
702
|
+
const reducedMotion = usePrefersReducedMotion()
|
|
703
|
+
// What the current instance last received, to pick the merge mode of the next update.
|
|
704
|
+
const appliedRef = useRef<EChartsOption | null>(null)
|
|
705
|
+
|
|
706
|
+
// 明暗の切り替えとスタイルシートの差し替え(dev で styles.css を書き換えたときなど)を
|
|
707
|
+
// 拾ってトークンを読み直す ― 何を見張るかは `watchChartTokens` 側が持つ。値が変わら
|
|
708
|
+
// ないときは state を更新せず、再 init を防ぐ。比較は updater 関数の中ではなく ref で行う:
|
|
709
|
+
// DOM を読む updater は React に何度も再生され、そのたびに新しいオブジェクトを返して
|
|
710
|
+
// 再描画が止まらなくなる(変数を後から当てた直後に Maximum update depth exceeded)。
|
|
711
|
+
const tokensRef = useRef(tokens)
|
|
712
|
+
useEffect(() => {
|
|
713
|
+
if (theme !== undefined) return
|
|
714
|
+
const sync = () => {
|
|
715
|
+
const next = readChartTokens()
|
|
716
|
+
if (sameChartTokens(tokensRef.current, next)) return
|
|
717
|
+
tokensRef.current = next
|
|
718
|
+
setTokens(next)
|
|
719
|
+
}
|
|
720
|
+
sync()
|
|
721
|
+
return watchChartTokens(sync)
|
|
722
|
+
}, [theme])
|
|
723
|
+
|
|
724
|
+
const autoTheme = useMemo(() => (tokens ? buildChartTheme(tokens) : undefined), [tokens])
|
|
725
|
+
const resolvedTheme = theme ?? autoTheme
|
|
726
|
+
|
|
727
|
+
// init / re-init: ECharts はテーマの差し替えに対応しないので、テーマが変わったら
|
|
728
|
+
// インスタンスを破棄して作り直す(トークンが実際に変わったときだけここに来る)
|
|
729
|
+
useEffect(() => {
|
|
730
|
+
const container = containerRef.current
|
|
731
|
+
if (!container) return
|
|
732
|
+
const inst = init(container, resolvedTheme, { renderer: "canvas" })
|
|
733
|
+
appliedRef.current = null
|
|
734
|
+
// `data-rendering` stays on until the (animated) paint is done, so anything
|
|
735
|
+
// capturing the page — printing a document — can wait for real pixels.
|
|
736
|
+
container.dataset.rendering = ""
|
|
737
|
+
inst.on("finished", () => {
|
|
738
|
+
delete container.dataset.rendering
|
|
739
|
+
})
|
|
740
|
+
setInstance(inst)
|
|
741
|
+
|
|
742
|
+
// At most one resize per frame (the sidebar animates the width).
|
|
743
|
+
let frame = 0
|
|
744
|
+
const observer = new ResizeObserver(() => {
|
|
745
|
+
cancelAnimationFrame(frame)
|
|
746
|
+
frame = requestAnimationFrame(() => {
|
|
747
|
+
if (!inst.isDisposed()) inst.resize()
|
|
748
|
+
})
|
|
749
|
+
})
|
|
750
|
+
observer.observe(container)
|
|
751
|
+
|
|
752
|
+
return () => {
|
|
753
|
+
observer.disconnect()
|
|
754
|
+
cancelAnimationFrame(frame)
|
|
755
|
+
inst.dispose()
|
|
756
|
+
}
|
|
757
|
+
}, [resolvedTheme])
|
|
758
|
+
|
|
759
|
+
useEffect(() => {
|
|
760
|
+
if (!instance) return
|
|
761
|
+
if (containerRef.current) containerRef.current.dataset.rendering = ""
|
|
762
|
+
const next = withMotionPreference(option, reducedMotion)
|
|
763
|
+
instance.setOption(next, echartSetOptionOpts(appliedRef.current, next))
|
|
764
|
+
appliedRef.current = next
|
|
765
|
+
}, [instance, option, reducedMotion])
|
|
766
|
+
|
|
767
|
+
useEffect(() => {
|
|
768
|
+
if (!instance) return
|
|
769
|
+
if (loading) instance.showLoading()
|
|
770
|
+
else instance.hideLoading()
|
|
771
|
+
}, [instance, loading])
|
|
772
|
+
|
|
773
|
+
useEffect(() => {
|
|
774
|
+
if (!instance || !onEvents) return
|
|
775
|
+
const entries = Object.entries(onEvents)
|
|
776
|
+
for (const [event, handler] of entries) {
|
|
777
|
+
instance.on(event, handler as EChartsEventHandler)
|
|
778
|
+
}
|
|
779
|
+
return () => {
|
|
780
|
+
if (instance.isDisposed()) return
|
|
781
|
+
for (const [event, handler] of entries) {
|
|
782
|
+
instance.off(event, handler as EChartsEventHandler)
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
}, [instance, onEvents])
|
|
786
|
+
|
|
787
|
+
const includeTitle = typeof actions === "object" ? (actions.includeTitle ?? true) : true
|
|
788
|
+
const getPngDataUrl = useCallback(async (): Promise<string | null> => {
|
|
789
|
+
if (!instance) return null
|
|
790
|
+
// Export over the nearest opaque background (card, then page) so the PNG
|
|
791
|
+
// matches what is on screen in dark too. Computed styles resolve to rgb(a),
|
|
792
|
+
// so this stays canvas-safe whatever the token.
|
|
793
|
+
let backgroundColor = "#ffffff"
|
|
794
|
+
for (let el: HTMLElement | null = containerRef.current; el; el = el.parentElement) {
|
|
795
|
+
const bg = getComputedStyle(el).backgroundColor
|
|
796
|
+
if (bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent") {
|
|
797
|
+
backgroundColor = bg
|
|
798
|
+
break
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
const pixelRatio = 2
|
|
802
|
+
const dataUrl = instance.getDataURL({ type: "png", pixelRatio, backgroundColor })
|
|
803
|
+
if (!includeTitle || !exportHeader || !(exportHeader.title || exportHeader.summary) || !containerRef.current) return dataUrl
|
|
804
|
+
try {
|
|
805
|
+
const style = getComputedStyle(containerRef.current)
|
|
806
|
+
return await pngWithHeader(
|
|
807
|
+
dataUrl,
|
|
808
|
+
exportHeader,
|
|
809
|
+
{ background: backgroundColor, color: style.color, mutedColor: tokens?.mutedForeground ?? style.color, fontFamily: style.fontFamily },
|
|
810
|
+
pixelRatio,
|
|
811
|
+
)
|
|
812
|
+
} catch {
|
|
813
|
+
return dataUrl
|
|
814
|
+
}
|
|
815
|
+
}, [instance, includeTitle, exportHeader, tokens])
|
|
816
|
+
|
|
817
|
+
const handleCopy = useCallback(async () => {
|
|
818
|
+
const dataUrl = await getPngDataUrl()
|
|
819
|
+
if (!dataUrl) return
|
|
820
|
+
try {
|
|
821
|
+
const blob = await (await fetch(dataUrl)).blob()
|
|
822
|
+
await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })])
|
|
823
|
+
setCopied(true)
|
|
824
|
+
setTimeout(() => setCopied(false), 2000)
|
|
825
|
+
} catch {
|
|
826
|
+
// ClipboardItem 未対応ブラウザでは silent fail
|
|
827
|
+
}
|
|
828
|
+
}, [getPngDataUrl])
|
|
829
|
+
|
|
830
|
+
const handleDownload = useCallback(async () => {
|
|
831
|
+
const dataUrl = await getPngDataUrl()
|
|
832
|
+
if (!dataUrl) return
|
|
833
|
+
const link = document.createElement("a")
|
|
834
|
+
link.href = dataUrl
|
|
835
|
+
link.download = fileName
|
|
836
|
+
link.click()
|
|
837
|
+
}, [getPngDataUrl, fileName])
|
|
838
|
+
|
|
839
|
+
// 高さの解決: height prop を渡した場合はインライン style が勝つ。未指定なら
|
|
840
|
+
// h-[400px] をデフォルトで当て、className の高さクラスに後勝ちさせる。
|
|
841
|
+
const inFrame = useContext(ChartFrameContext)
|
|
842
|
+
const styleHeight =
|
|
843
|
+
height == null ? undefined : typeof height === "number" ? `${height}px` : height
|
|
844
|
+
|
|
845
|
+
return (
|
|
846
|
+
<div
|
|
847
|
+
ref={ref}
|
|
848
|
+
data-slot="echart"
|
|
849
|
+
className={cn("group relative w-full", height == null && "h-[400px]", className)}
|
|
850
|
+
style={styleHeight != null ? { height: styleHeight } : undefined}
|
|
851
|
+
>
|
|
852
|
+
{/* `role="img"` wraps the canvas only, so the action buttons stay reachable. Inside a ChartFrame the plot area is the one image. */}
|
|
853
|
+
<div
|
|
854
|
+
ref={containerRef}
|
|
855
|
+
data-slot="echart-canvas"
|
|
856
|
+
className="h-full w-full"
|
|
857
|
+
role={inFrame ? undefined : "img"}
|
|
858
|
+
aria-label={inFrame ? undefined : (ariaLabel ?? "チャート")}
|
|
859
|
+
/>
|
|
860
|
+
{actions && (
|
|
861
|
+
<div
|
|
862
|
+
data-slot="echart-actions"
|
|
863
|
+
className="absolute top-2 right-2 z-10 flex gap-1 pointer-events-none opacity-0 transition-opacity group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100 [@media(hover:none)]:pointer-events-auto [@media(hover:none)]:opacity-100"
|
|
864
|
+
>
|
|
865
|
+
<Button
|
|
866
|
+
type="button"
|
|
867
|
+
variant="ghost"
|
|
868
|
+
size="icon-sm"
|
|
869
|
+
onClick={handleCopy}
|
|
870
|
+
aria-label={copied ? "コピーしました" : "PNG をクリップボードにコピー"}
|
|
871
|
+
>
|
|
872
|
+
{copied ? <Check className="size-4" /> : <Copy className="size-4" />}
|
|
873
|
+
</Button>
|
|
874
|
+
<Button
|
|
875
|
+
type="button"
|
|
876
|
+
variant="ghost"
|
|
877
|
+
size="icon-sm"
|
|
878
|
+
onClick={handleDownload}
|
|
879
|
+
aria-label="PNG をダウンロード"
|
|
880
|
+
>
|
|
881
|
+
<Download className="size-4" />
|
|
882
|
+
</Button>
|
|
883
|
+
</div>
|
|
884
|
+
)}
|
|
885
|
+
</div>
|
|
886
|
+
)
|
|
887
|
+
})
|
|
888
|
+
EChart.displayName = "EChart"
|
|
889
|
+
|
|
890
|
+
export type { EChartsOption } from "echarts"
|