@squadbase/vantage 0.6.2-dev1.42c4e48 → 0.6.2-dev1.51e401a

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