@squadbase/vantage 0.6.1 → 0.6.2-dev1.01caa72

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