@squadbase/vantage 0.6.1 → 0.6.2-dev1.25d59a0

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