@squadbase/vantage 0.6.1 → 0.6.2-dev1.05a930b

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