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