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