@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,17 +1,568 @@
1
1
  // Copied by `vantage add ui category-bar`. This file is yours to edit.
2
- // Generated from @squadbase/vantage src/components/category-bar.tsx by `npm run registry` (in Vantage, edit src/, not registry/).
2
+ // Generated from @squadbase/squadkit registry/charts/category-bar.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
3
5
  /**
4
6
  * CategoryBar — one bar split into coloured segments by `values`, with the
5
7
  * running totals underneath and an optional marker: a score against bands
6
8
  * (要改善 / 標準 / 良好), budget consumption, a share breakdown. Plain HTML/CSS.
7
9
  */
8
- import { forwardRef, type ComponentProps } from "react"
10
+ import { forwardRef, useMemo, type ComponentProps } from "react"
9
11
 
10
12
  import { cn } from "@squadbase/vantage/ui"
11
13
  import { Tooltip, TooltipContent, TooltipTrigger } from "@squadbase/vantage/ui"
14
+ import type { ValueFormat } from "@squadbase/vantage/components"
12
15
  import type { ChartColor, ValueFormatter } from "@squadbase/vantage/components"
16
+ import { useSyncExternalStore } from "react"
17
+ import { createContext, useCallback, useEffect, useRef, useState, type ForwardedRef, type RefObject } from "react"
18
+ import type { ChartTone } from "@squadbase/vantage/components"
19
+ import { EMPTY_VALUE, formatValue, toValueFormatter } from "@squadbase/vantage/components"
20
+ import type { ChartColors, ChartSeriesColor } from "@squadbase/vantage/components"
21
+
22
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
23
+
24
+ /**
25
+ * The display language of the parts and the defaults that follow it.
26
+ *
27
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
28
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
29
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
30
+ *
31
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
32
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
33
+ */
34
+
35
+ /** The language of the built-in wording: Japanese or English. */
36
+ type UiLanguage = "ja" | "en"
37
+
38
+ /** The locale used when `<html lang>` gives none (and on the server). */
39
+ const FALLBACK_LOCALE = "en-US"
40
+
41
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
42
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
43
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
44
+ }
13
45
 
14
- /* ---------- inlined from src/components/chart-utils.ts (internal to @squadbase/vantage) ---------- */
46
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
47
+ function normalizeLocale(tag: string | null | undefined): string {
48
+ const value = tag?.trim()
49
+ if (!value) return FALLBACK_LOCALE
50
+ try {
51
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
52
+ } catch {
53
+ return FALLBACK_LOCALE
54
+ }
55
+ }
56
+
57
+ /**
58
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
59
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
60
+ */
61
+ function documentLocale(): string {
62
+ if (typeof document === "undefined") return FALLBACK_LOCALE
63
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
64
+ }
65
+
66
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
67
+ function resolveLocale(locale?: string | null): string {
68
+ return locale || documentLocale()
69
+ }
70
+
71
+ /** Picks the wording table of the locale's language. */
72
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
73
+ return table[uiLanguage(resolveLocale(locale))]
74
+ }
75
+
76
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
77
+ function defaultCurrency(locale?: string | null): string {
78
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
79
+ }
80
+
81
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
82
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
83
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
84
+ }
85
+
86
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
87
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
88
+
89
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
90
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
91
+
92
+ /**
93
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
94
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
95
+ * Monday for the rest.
96
+ */
97
+ function weekStartsOn(locale?: string | null): WeekDay {
98
+ const tag = normalizeLocale(resolveLocale(locale))
99
+ if (uiLanguage(tag) === "ja") return 1
100
+ try {
101
+ const info = new Intl.Locale(tag) as Intl.Locale & {
102
+ getWeekInfo?: () => { firstDay: number }
103
+ weekInfo?: { firstDay: number }
104
+ }
105
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
106
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
107
+ } catch {
108
+ // Fall through to the table below.
109
+ }
110
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
111
+ }
112
+
113
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
114
+
115
+ const listeners = new Set<() => void>()
116
+ let observer: MutationObserver | null = null
117
+
118
+ /** One observer on `<html lang>` for every subscribed part. */
119
+ function subscribe(onChange: () => void): () => void {
120
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
121
+ listeners.add(onChange)
122
+ if (!observer) {
123
+ observer = new MutationObserver(() => {
124
+ for (const listener of [...listeners]) listener()
125
+ })
126
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
127
+ }
128
+ return () => {
129
+ listeners.delete(onChange)
130
+ if (listeners.size === 0 && observer) {
131
+ observer.disconnect()
132
+ observer = null
133
+ }
134
+ }
135
+ }
136
+
137
+ const serverLocale = () => FALLBACK_LOCALE
138
+
139
+ /**
140
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
141
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
142
+ */
143
+ function useDocumentLocale(): string {
144
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
145
+ }
146
+
147
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
148
+ function useLocale(locale?: string | null): string {
149
+ const page = useDocumentLocale()
150
+ return locale || page
151
+ }
152
+
153
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
154
+
155
+ /**
156
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
157
+ * grey is defined — every chart takes it from here. It is the most subdued
158
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
159
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
160
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
161
+ * slice. Canvas charts resolve it through `resolveChartColors`.
162
+ */
163
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
164
+
165
+ /**
166
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
167
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
168
+ */
169
+ const ChartFrameContext = createContext(false)
170
+
171
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
172
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
173
+
174
+ interface ChartTokens {
175
+ /** Resolved `--chart-1..5`, in order. */
176
+ series: string[]
177
+ /** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
178
+ fontFamily?: string
179
+ /** Body text: titles and the default `textStyle`. */
180
+ foreground: string | null
181
+ /** Secondary text: axis labels, legend, subtitles. */
182
+ mutedForeground: string | null
183
+ /** Axis lines, ticks, split lines, tooltip border. */
184
+ border: string | null
185
+ /** Tooltip surface. */
186
+ popover: string | null
187
+ /** Semantic and surface dependencies used by typed chart options. Optional for hand-built tokens. */
188
+ colors?: Record<string, string>
189
+ /** Actual inherited painting surface (may change without a token changing). */
190
+ surface?: string | null
191
+ /** Tooltip text. */
192
+ popoverForeground: string | null
193
+ }
194
+
195
+ // Keep scope out of the public token shape. A resolved snapshot remembers where arbitrary
196
+ // var(--token) expressions must be read, without retaining unmounted charts globally.
197
+ const tokenScopes = new WeakMap<ChartTokens, Element>()
198
+ const OPTION_COLOR_TOKENS = [
199
+ "--background", "--card", "--muted", "--primary", "--destructive",
200
+ ...["positive", "negative", "warning", "neutral", "info"].flatMap((tone) =>
201
+ ["", "-fill", "-subtle"].map((suffix) => `--${tone}${suffix}`)),
202
+ ]
203
+
204
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
205
+
206
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
207
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
208
+
209
+ /**
210
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
211
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
212
+ * input is written over two different known colours: agreeing results mean the
213
+ * value parsed, differing ones mean it was dropped.
214
+ */
215
+ function toCanvasColor(value: string): string | null {
216
+ const raw = value.trim()
217
+ if (!raw) return null
218
+ if (normalizeContext === undefined) {
219
+ const canvas = document.createElement("canvas")
220
+ canvas.width = 1
221
+ canvas.height = 1
222
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
223
+ }
224
+ const ctx = normalizeContext
225
+ if (!ctx) return raw
226
+ ctx.fillStyle = "#000000"
227
+ ctx.fillStyle = raw
228
+ const onBlack = ctx.fillStyle
229
+ ctx.fillStyle = "#ffffff"
230
+ ctx.fillStyle = raw
231
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
232
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
233
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
234
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
235
+ ctx.clearRect(0, 0, 1, 1)
236
+ ctx.fillRect(0, 0, 1, 1)
237
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
238
+ return a === 255
239
+ ? `rgb(${r}, ${g}, ${b})`
240
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
241
+ }
242
+
243
+ /**
244
+ * Read the chart tokens off `el` (the document root by default — tokens live on
245
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
246
+ * to plain ECharts defaults.
247
+ */
248
+ function readChartTokens(el?: Element | null): ChartTokens | null {
249
+ if (typeof document === "undefined") return null
250
+ const target = el ?? document.documentElement
251
+ if (!target) return null
252
+ const styles = getComputedStyle(target)
253
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
254
+ const series: string[] = []
255
+ for (const token of SERIES_TOKENS) {
256
+ const color = read(token)
257
+ if (color) series.push(color)
258
+ }
259
+ const tokens: ChartTokens = {
260
+ series,
261
+ colors: Object.fromEntries(OPTION_COLOR_TOKENS.map((name) => [name, styles.getPropertyValue(name).trim()])),
262
+ surface: readChartSurface(target),
263
+ ...(styles.fontFamily ? { fontFamily: styles.fontFamily } : {}),
264
+ foreground: read("--foreground"),
265
+ mutedForeground: read("--muted-foreground"),
266
+ border: read("--border"),
267
+ popover: read("--popover"),
268
+ popoverForeground: read("--popover-foreground"),
269
+ }
270
+ tokenScopes.set(tokens, target)
271
+ return tokens
272
+ }
273
+
274
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
275
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
276
+ if (a === b) return true
277
+ if (!a || !b) return false
278
+ return (
279
+ tokenScopes.get(a) === tokenScopes.get(b) &&
280
+ a.surface === b.surface &&
281
+ Object.keys(a.colors ?? {}).length === Object.keys(b.colors ?? {}).length &&
282
+ Object.entries(a.colors ?? {}).every(([name, value]) => b.colors?.[name] === value) &&
283
+ a.series.length === b.series.length &&
284
+ a.series.every((color, i) => color === b.series[i]) &&
285
+ a.fontFamily === b.fontFamily &&
286
+ a.foreground === b.foreground &&
287
+ a.mutedForeground === b.mutedForeground &&
288
+ a.border === b.border &&
289
+ a.popover === b.popover &&
290
+ a.popoverForeground === b.popoverForeground
291
+ )
292
+ }
293
+
294
+ /**
295
+ * Watch everything that can change the resolved tokens and call `onChange` when
296
+ * something might have. It only ever says "re-read" — the caller compares with
297
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
298
+ * disposer.
299
+ *
300
+ * Two sources, not one:
301
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
302
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
303
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
304
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
305
+ * attributes alone leaves the chart painted in the previous palette until a
306
+ * reload — the tokens in the DOM are new, the canvas is not.
307
+ */
308
+ function watchChartTokens(onChange: () => void, scope?: Element | null): () => void {
309
+ if (typeof document === "undefined") return () => {}
310
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
311
+ // take it after the next frame so a swapped stylesheet has been applied.
312
+ let frame = 0
313
+ const schedule = () => {
314
+ if (frame) return
315
+ frame = requestAnimationFrame(() => {
316
+ frame = 0
317
+ onChange()
318
+ })
319
+ }
320
+
321
+ const themeObserver = new MutationObserver(schedule)
322
+ const attributeFilter = ["class", "style", "data-theme"]
323
+ // Only the chart and its ancestors can change its inherited theme. Never observe
324
+ // the document subtree: canvas/tooltip/rendering mutations would trigger every chart.
325
+ for (let node: Element | null = scope ?? document.body ?? document.documentElement; node; node = node.parentElement) {
326
+ themeObserver.observe(node, { attributes: true, attributeFilter })
327
+ }
328
+
329
+ const styleObserver = new MutationObserver(schedule)
330
+ if (document.head) {
331
+ styleObserver.observe(document.head, {
332
+ childList: true,
333
+ subtree: true,
334
+ characterData: true,
335
+ attributes: true,
336
+ attributeFilter: ["href", "media", "disabled"],
337
+ })
338
+ }
339
+
340
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
341
+ const onLoad = (event: Event) => {
342
+ if (event.target instanceof HTMLLinkElement) schedule()
343
+ }
344
+ document.addEventListener("load", onLoad, true)
345
+
346
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
347
+ media.addEventListener("change", schedule)
348
+
349
+ return () => {
350
+ if (frame) cancelAnimationFrame(frame)
351
+ themeObserver.disconnect()
352
+ styleObserver.disconnect()
353
+ document.removeEventListener("load", onLoad, true)
354
+ media.removeEventListener("change", schedule)
355
+ }
356
+ }
357
+
358
+ /** Shared shape for the four axis types ECharts themes address separately. */
359
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
360
+ const line = tokens.border ?? undefined
361
+ return {
362
+ axisLine: { show: false },
363
+ axisTick: { show: false },
364
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
365
+ // Faint horizontal rules only: the border colour at low opacity.
366
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
367
+ splitArea: { show: false },
368
+ }
369
+ }
370
+
371
+ /**
372
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
373
+ * app that sets its own palette keeps it.
374
+ */
375
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
376
+ const text = tokens.foreground ?? undefined
377
+ const muted = tokens.mutedForeground ?? undefined
378
+ const line = tokens.border ?? undefined
379
+ return {
380
+ // Let the page background show through: charts sit on cards, not on a canvas.
381
+ backgroundColor: "transparent",
382
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
383
+ textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
384
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
385
+ legend: { textStyle: { color: muted } },
386
+ categoryAxis: axisTheme(tokens, false),
387
+ valueAxis: axisTheme(tokens, true),
388
+ logAxis: axisTheme(tokens, true),
389
+ timeAxis: axisTheme(tokens, true),
390
+ tooltip: {
391
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
392
+ transitionDuration: 0,
393
+ backgroundColor: tokens.popover ?? undefined,
394
+ borderColor: line,
395
+ borderWidth: 1,
396
+ padding: [8, 12],
397
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
398
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
399
+ textStyle: {
400
+ color: tokens.popoverForeground ?? undefined,
401
+ fontSize: 12,
402
+ ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}),
403
+ },
404
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
405
+ },
406
+ }
407
+ }
408
+
409
+ /**
410
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
411
+ * they may have moved, and only replaced when a value actually changed. For
412
+ * components that build an ECharts option from token colours themselves (the
413
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
414
+ */
415
+ function useChartTokens(scope?: Element | null | RefObject<Element | null>): ChartTokens | null {
416
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
417
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
418
+ // replayed by React on every rebase and returns a fresh object each time, so the state
419
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
420
+ const tokensRef = useRef(tokens)
421
+ useEffect(() => {
422
+ const target = scope && "current" in scope ? scope.current : scope
423
+ const sync = () => {
424
+ const next = readChartTokens(target)
425
+ if (sameChartTokens(tokensRef.current, next)) return
426
+ tokensRef.current = next
427
+ setTokens(next)
428
+ }
429
+ sync()
430
+ return watchChartTokens(sync, target)
431
+ }, [scope])
432
+ return tokens
433
+ }
434
+
435
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
436
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
437
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
438
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
439
+
440
+ /**
441
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
442
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
443
+ * variants `"positive-fill"`, …) are read in the snapshot's inherited scope (`--positive`, …); `var(--token)` uses the same scope; any
444
+ * other CSS colour is normalized like the tokens are. A colour that can't be
445
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
446
+ */
447
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
448
+ return colors.map((color) => {
449
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
450
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
451
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
452
+ if (TONE_NAME_RE.test(color.trim())) {
453
+ if (typeof document === "undefined") return ""
454
+ const target = (tokens && tokenScopes.get(tokens)) ?? document.documentElement
455
+ return toCanvasColor(getComputedStyle(target).getPropertyValue(`--${color.trim()}`)) ?? ""
456
+ }
457
+ if (typeof document === "undefined") return color
458
+ let value = color.trim()
459
+ const cssVar = CSS_VAR_RE.exec(value)
460
+ const styles = getComputedStyle((tokens && tokenScopes.get(tokens)) ?? document.documentElement)
461
+ if (cssVar) {
462
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
463
+ } else if (value.includes("var(")) {
464
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
465
+ // substitute the tokens, then let the canvas resolve the rest.
466
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
467
+ }
468
+ return toCanvasColor(value) ?? ""
469
+ })
470
+ }
471
+
472
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
473
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
474
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
475
+ ["positive", "warning", "negative", "neutral"],
476
+ tokens,
477
+ )
478
+ return { positive, warning, negative, neutral }
479
+ }
480
+
481
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
482
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
483
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
484
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
485
+ tokens,
486
+ )
487
+ return { positive, warning, negative, neutral }
488
+ }
489
+
490
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
491
+
492
+ /**
493
+ * The colour the chart is painted on: the first opaque `background-color` up
494
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
495
+ * outside the browser.
496
+ */
497
+ function readChartSurface(el: Element | null): string | null {
498
+ if (typeof document === "undefined") return null
499
+ for (let node: Element | null = el; node; node = node.parentElement) {
500
+ const bg = getComputedStyle(node).backgroundColor.trim()
501
+ if (bg && !TRANSPARENT_RE.test(bg)) {
502
+ const color = toCanvasColor(bg)
503
+ if (color) return color
504
+ }
505
+ }
506
+ return toCanvasColor(getComputedStyle(el ?? document.documentElement).getPropertyValue("--background"))
507
+ }
508
+
509
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
510
+ const WIDTH_BUCKET = 40
511
+
512
+ /**
513
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
514
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
515
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
516
+ * component's forwarded ref.
517
+ */
518
+ function useChartSurface<E extends Element>(
519
+ forwarded: ForwardedRef<E>,
520
+ tokens?: ChartTokens | null,
521
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined; tokens: ChartTokens | null } {
522
+ const [node, setNode] = useState<E | null>(null)
523
+ const scopedTokens = useChartTokens(node)
524
+ const [surface, setSurface] = useState<string | undefined>(undefined)
525
+ const [width, setWidth] = useState<number | undefined>(undefined)
526
+ const ref = useCallback(
527
+ (el: E | null) => {
528
+ setNode(el)
529
+ if (typeof forwarded === "function") forwarded(el)
530
+ else if (forwarded) forwarded.current = el
531
+ },
532
+ [forwarded],
533
+ )
534
+ useEffect(() => {
535
+ if (!node) return
536
+ setSurface(readChartSurface(node) ?? undefined)
537
+ }, [node, tokens, scopedTokens])
538
+ useEffect(() => {
539
+ if (!node || typeof ResizeObserver === "undefined") return
540
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
541
+ update(node.getBoundingClientRect().width)
542
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
543
+ observer.observe(node)
544
+ return () => observer.disconnect()
545
+ }, [node])
546
+ return { ref, surface, width, tokens: scopedTokens }
547
+ }
548
+
549
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
550
+
551
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
552
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
553
+
554
+ /**
555
+ * The attributes of a typed chart's leftover props that belong on its root
556
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
557
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
558
+ */
559
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
560
+ const out: Record<string, unknown> = {}
561
+ for (const [key, value] of Object.entries(rest)) {
562
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
563
+ }
564
+ return out
565
+ }
15
566
 
16
567
  /** The series tokens, in palette order — the default `colors` of every typed chart. */
17
568
  const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
@@ -24,13 +575,37 @@ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
24
575
 
25
576
  const TOKEN_NAME_RE = /^chart-[1-5]$/
26
577
 
578
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
579
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
580
+
581
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
582
+ function isChartTone(color: string): color is ChartTone {
583
+ return (CHART_TONES as readonly string[]).includes(color.trim())
584
+ }
585
+
27
586
  /**
28
587
  * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
29
588
  * light/dark on its own), anything else passes through unchanged.
30
589
  */
31
590
  function chartColorToCss(color: ChartColor): string {
32
591
  const value = color.trim()
33
- return TOKEN_NAME_RE.test(value) ? `var(--${value})` : value
592
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
593
+ }
594
+
595
+ /**
596
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
597
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
598
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
599
+ */
600
+ function chartFillToCss(color: ChartColor): string {
601
+ const value = color.trim()
602
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
603
+ }
604
+
605
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
606
+ function chartFillName(color: ChartColor): ChartColor {
607
+ const value = color.trim()
608
+ return isChartTone(value) ? `${value}-fill` : color
34
609
  }
35
610
 
36
611
  /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
@@ -54,6 +629,115 @@ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 }
54
629
  /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
55
630
  const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
56
631
 
632
+ /**
633
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
634
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
635
+ */
636
+ function resolveValueFormatter(
637
+ valueFormatter: ValueFormatter | undefined,
638
+ format: ValueFormat | undefined,
639
+ locale?: string,
640
+ ): ValueFormatter {
641
+ return valueFormatter ?? toValueFormatter(format, locale)
642
+ }
643
+
644
+ /**
645
+ * The formatter of value-axis ticks and on-plot labels: an explicit
646
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
647
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
648
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
649
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
650
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
651
+ * currency sign and grouping.
652
+ */
653
+ function resolveAxisFormatter(
654
+ valueFormatter: ValueFormatter | undefined,
655
+ format: ValueFormat | undefined,
656
+ localeArg?: string,
657
+ ): ValueFormatter {
658
+ if (valueFormatter) return valueFormatter
659
+ const locale = resolveLocale(localeArg)
660
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
661
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
662
+ const currency = "currency" in spec ? spec.currency : undefined
663
+ const short: ValueFormat =
664
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
665
+ return (value) => formatValue(value, short, locale)
666
+ }
667
+
668
+ interface CompactUnit {
669
+ token: string
670
+ size: number
671
+ }
672
+
673
+ const compactUnitCache = new Map<string, CompactUnit[] | null>()
674
+
675
+ /**
676
+ * The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
677
+ * `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
678
+ * word (`1,5 Mio.`), where a token cannot be swapped in place.
679
+ */
680
+ function compactUnits(locale: string): CompactUnit[] | null {
681
+ const cached = compactUnitCache.get(locale)
682
+ if (cached !== undefined) return cached
683
+ let units: CompactUnit[] | null = []
684
+ try {
685
+ const compact = new Intl.NumberFormat(locale, { notation: "compact" })
686
+ const seen = new Set<string>()
687
+ for (let exp = 3; exp <= 15; exp++) {
688
+ const parts = compact.formatToParts(10 ** exp)
689
+ const at = parts.findIndex((p) => p.type === "compact")
690
+ if (at === -1) continue
691
+ if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
692
+ units = null
693
+ break
694
+ }
695
+ const token = parts[at]!.value
696
+ if (seen.has(token)) continue
697
+ seen.add(token)
698
+ units.push({ token, size: 10 ** exp })
699
+ }
700
+ } catch {
701
+ units = null
702
+ }
703
+ const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
704
+ compactUnitCache.set(locale, sorted)
705
+ return sorted
706
+ }
707
+
708
+ const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
709
+
710
+ /**
711
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
712
+ * that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
713
+ * `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
714
+ * no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
715
+ * unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
716
+ */
717
+ function resolveAxisTickFormatter(
718
+ valueFormatter: ValueFormatter | undefined,
719
+ format: ValueFormat | undefined,
720
+ localeArg?: string,
721
+ ): (top: number) => ValueFormatter {
722
+ const locale = resolveLocale(localeArg)
723
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
724
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
725
+ const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
726
+ if (!units) return () => base
727
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
728
+ const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
729
+ return (top) => {
730
+ const unit = units.find((u) => Math.abs(top) >= u.size)
731
+ if (!unit) return base
732
+ return (value) => {
733
+ const text = base(value)
734
+ if (value === 0 || !Number.isFinite(value)) return text
735
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
736
+ return text.replace(numberToken, () => scaled)
737
+ }
738
+ }
739
+ }
740
+
57
741
  /**
58
742
  * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
59
743
  * `DECIMAL` / `BIGINT` columns usually arrive as strings.
@@ -73,6 +757,237 @@ function clamp(value: number, min: number, max: number): number {
73
757
  return Math.min(max, Math.max(min, value))
74
758
  }
75
759
 
760
+ /* ------------------------------------------------------------ aggregation */
761
+
762
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
763
+ const MAX_CHART_SERIES = 5
764
+
765
+ /** The series name the folded categories get, by language. */
766
+ const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
767
+
768
+ /** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
769
+ function otherSeriesLabel(locale?: string): string {
770
+ return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
771
+ }
772
+
773
+ const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
774
+
775
+ /** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
776
+ function isOtherName(name: string | null | undefined): boolean {
777
+ return typeof name === "string" && OTHER_NAMES.has(name)
778
+ }
779
+
780
+ interface AggregatedItems<Item extends { name: string; value: number }> {
781
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
782
+ top: Item[]
783
+ /** The items folded into `other`, in their given order. */
784
+ rest: Item[]
785
+ /** The folded remainder, or `null` when nothing was folded. */
786
+ other: { name: string; value: number } | null
787
+ }
788
+
789
+ /**
790
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
791
+ * given order and fold the rest into one `otherLabel` item. Shared by every
792
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
793
+ * BarList rows).
794
+ */
795
+ function aggregateTopN<Item extends { name: string; value: number }>(
796
+ items: readonly Item[],
797
+ n: number = MAX_CHART_SERIES,
798
+ otherLabel: string = otherSeriesLabel(),
799
+ ): AggregatedItems<Item> {
800
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
801
+ const ranked = items
802
+ .map((item, i) => ({ item, i }))
803
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
804
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
805
+ const top = items.filter((_, i) => keep.has(i))
806
+ const rest = items.filter((_, i) => !keep.has(i))
807
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
808
+ }
809
+
810
+ interface AggregatedSeries {
811
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
812
+ data: Record<string, unknown>[]
813
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
814
+ categories: string[]
815
+ /** The folded series' name, or `null`. */
816
+ otherCategory: string | null
817
+ }
818
+
819
+ /**
820
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
821
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
822
+ */
823
+ function aggregateSeries(
824
+ data: readonly Record<string, unknown>[],
825
+ categories: readonly string[],
826
+ n: number = MAX_CHART_SERIES,
827
+ otherLabel: string = otherSeriesLabel(),
828
+ ): AggregatedSeries {
829
+ const totals = categories.map((name) => ({
830
+ name,
831
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
832
+ }))
833
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
834
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
835
+ const folded = rest.map((item) => item.name)
836
+ return {
837
+ data: data.map((row) => {
838
+ let sum: number | null = null
839
+ for (const name of folded) {
840
+ const v = toChartNumber(row[name])
841
+ if (v !== null) sum = (sum ?? 0) + v
842
+ }
843
+ return { ...row, [other.name]: sum }
844
+ }),
845
+ categories: [...top.map((item) => item.name), other.name],
846
+ otherCategory: other.name,
847
+ }
848
+ }
849
+
850
+ /**
851
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
852
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
853
+ */
854
+ function aggregateSeriesKeeping(
855
+ data: readonly Record<string, unknown>[],
856
+ categories: readonly string[],
857
+ keep: string | undefined,
858
+ n: number = MAX_CHART_SERIES,
859
+ otherLabel: string = otherSeriesLabel(),
860
+ ): AggregatedSeries {
861
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
862
+ const aggregated = aggregateSeries(
863
+ data,
864
+ categories.filter((c) => c !== keep),
865
+ n,
866
+ otherLabel,
867
+ )
868
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
869
+ }
870
+
871
+ /**
872
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
873
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
874
+ * so a main series keeps its colour whether or not a comparison is drawn.
875
+ */
876
+ function seriesColorsWithComparison(
877
+ categories: readonly string[],
878
+ colors: ChartColors | undefined,
879
+ otherColor: string,
880
+ otherCategory: string | null,
881
+ allCategories: readonly string[],
882
+ comparison: string | undefined,
883
+ ): string[] {
884
+ if (comparison === undefined || !categories.includes(comparison)) {
885
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
886
+ }
887
+ const main = categories.filter((c) => c !== comparison)
888
+ const mainColors = seriesColorsFor(
889
+ main,
890
+ colors,
891
+ otherColor,
892
+ otherCategory,
893
+ allCategories.filter((c) => c !== comparison),
894
+ )
895
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
896
+ }
897
+
898
+ /**
899
+ * Colour per drawn series: the record's token for that category, else the
900
+ * array's token at the category's position in `allCategories` (cycled), else
901
+ * the token palette by drawn position. `otherCategory` — and a category the
902
+ * data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
903
+ */
904
+ function seriesColorsFor(
905
+ categories: readonly string[],
906
+ colors: ChartColors | undefined,
907
+ otherColor: string,
908
+ otherCategory: string | null = null,
909
+ allCategories: readonly string[] = categories,
910
+ ): string[] {
911
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
912
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
913
+ return categories.map((category, i) => {
914
+ if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
915
+ const fromRecord = record?.[category]
916
+ if (fromRecord) return fromRecord
917
+ if (list && list.length > 0) {
918
+ const at = allCategories.indexOf(category)
919
+ return list[(at === -1 ? i : at) % list.length]!
920
+ }
921
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
922
+ })
923
+ }
924
+
925
+ /* ------------------------------------------------------------------ Donut */
926
+
927
+ /** One drawn donut slice, largest first. */
928
+ interface DonutSlice {
929
+ name: string
930
+ /** Negative and missing values count as 0. */
931
+ value: number
932
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
933
+ color: string
934
+ /** The folded「その他」slice. */
935
+ isOther: boolean
936
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
937
+ row: Record<string, unknown>
938
+ }
939
+
940
+ interface DonutSlicesConfig {
941
+ /** Label column. */
942
+ index: string
943
+ /** Value column. */
944
+ value: string
945
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
946
+ colors?: readonly ChartSeriesColor[]
947
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
948
+ maxSlices?: number
949
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
950
+ otherColor: string
951
+ otherLabel?: string
952
+ }
953
+
954
+ /**
955
+ * Donut slices: sorted by value (largest first, ties keep input order), the
956
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
957
+ * summed into one「その他」slice in `otherColor`.
958
+ */
959
+ function donutSlices(
960
+ data: readonly Record<string, unknown>[],
961
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
962
+ ): DonutSlice[] {
963
+ const items = data
964
+ .map((row, i) => {
965
+ const n = toChartNumber(row[value])
966
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
967
+ })
968
+ .sort((a, b) => b.value - a.value || a.i - b.i)
969
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
970
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
971
+ const slices: DonutSlice[] = top.map((item, rank) => ({
972
+ name: item.name,
973
+ value: item.value,
974
+ // A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
975
+ color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
976
+ isOther: false,
977
+ row: item.row,
978
+ }))
979
+ if (other) {
980
+ slices.push({
981
+ name: other.name,
982
+ value: other.value,
983
+ color: otherColor,
984
+ isOther: true,
985
+ row: { [index]: other.name, [value]: other.value },
986
+ })
987
+ }
988
+ return slices
989
+ }
990
+
76
991
  /* ---------------------------------------------------------------- BarList */
77
992
 
78
993
  type BarListSortOrder = "ascending" | "descending" | "none"
@@ -85,6 +1000,78 @@ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOr
85
1000
  return rows
86
1001
  }
87
1002
 
1003
+ /** BarList-only settings. */
1004
+ interface BarListOptions {
1005
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
1006
+ sortOrder?: BarListSortOrder
1007
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
1008
+ maxItems?: number
1009
+ /** まとめた行のラベル。既定「その他」。 */
1010
+ otherLabel?: string
1011
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
1012
+ exclude?: readonly string[]
1013
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
1014
+ showShare?: boolean
1015
+ }
1016
+
1017
+ /** One drawn BarList row. */
1018
+ interface BarListRow<Row = Record<string, unknown>> {
1019
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
1020
+ key: string
1021
+ name: string
1022
+ value: number
1023
+ /** Only for real rows; the folded row never links. */
1024
+ href?: string
1025
+ /** Legacy per-row colour (`BarListItem.color`). */
1026
+ color?: ChartColor
1027
+ /** The folded「その他」row. */
1028
+ isOther: boolean
1029
+ /** The input row (`null` for the folded row). */
1030
+ row: Row | null
1031
+ }
1032
+
1033
+ interface BarListRowsConfig extends BarListOptions {
1034
+ /** Name column. Default `"name"`. */
1035
+ index?: string
1036
+ /** Value column. Default `"value"`. */
1037
+ category?: string
1038
+ }
1039
+
1040
+ /**
1041
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
1042
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
1043
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
1044
+ * ranking and are always added to「その他」.
1045
+ */
1046
+ function barListRows<Row extends object>(
1047
+ data: readonly Row[],
1048
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
1049
+ ): BarListRow<Row>[] {
1050
+ const items = data.map((row): BarListRow<Row> => {
1051
+ const cells = row as Record<string, unknown>
1052
+ const name = String(cells[index] ?? "")
1053
+ return {
1054
+ key: typeof cells.key === "string" ? cells.key : name,
1055
+ name,
1056
+ value: toChartNumber(cells[category]) ?? 0,
1057
+ href: typeof cells.href === "string" ? cells.href : undefined,
1058
+ color: typeof cells.color === "string" ? cells.color : undefined,
1059
+ isOther: false,
1060
+ row,
1061
+ }
1062
+ })
1063
+ const excluded = new Set(exclude ?? [])
1064
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
1065
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
1066
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
1067
+ const rows = sortBarListData(top, sortOrder)
1068
+ if (other || outside.length > 0) {
1069
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
1070
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
1071
+ }
1072
+ return rows
1073
+ }
1074
+
88
1075
  /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
89
1076
  function barListWidths(values: readonly number[]): number[] {
90
1077
  const max = Math.max(0, ...values)
@@ -92,6 +1079,102 @@ function barListWidths(values: readonly number[]): number[] {
92
1079
  return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
93
1080
  }
94
1081
 
1082
+ /**
1083
+ * How strongly the BarList bars are painted: every row the same tint of the bar
1084
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
1085
+ * it sits on the card in light and dark; it must stay visible against the card
1086
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
1087
+ */
1088
+ const BAR_LIST_TINT = 45
1089
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
1090
+ const BAR_LIST_OTHER_TINT = 30
1091
+
1092
+ /**
1093
+ * The fill of each BarList row: all real rows in the same tint of `color`
1094
+ * (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
1095
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
1096
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
1097
+ * for that row. A tint, not the solid token, so the label printed over the bar
1098
+ * keeps its contrast.
1099
+ */
1100
+ function barListFills(
1101
+ rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
1102
+ color: ChartColor,
1103
+ otherColor: string,
1104
+ ): string[] {
1105
+ return rows.map((row) =>
1106
+ row.isOther || isOtherName(row.name)
1107
+ ? tintCss(otherColor, BAR_LIST_OTHER_TINT)
1108
+ : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
1109
+ )
1110
+ }
1111
+
1112
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
1113
+ function barListShareText(value: number, total: number): string {
1114
+ const v = Number.isFinite(value) && value > 0 ? value : 0
1115
+ if (total <= 0 || v === 0) return "0%"
1116
+ const pct = (v / total) * 100
1117
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
1118
+ }
1119
+
1120
+ /**
1121
+ * The text at the end of each BarList row: the formatted value and, with
1122
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
1123
+ * so the shares are of the whole list): `value` and `share` apart (the share is
1124
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
1125
+ */
1126
+ function barListValueTexts(
1127
+ values: readonly number[],
1128
+ formatter: ValueFormatter,
1129
+ showShare = false,
1130
+ ): { value: string; share?: string; text: string }[] {
1131
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1132
+ return values.map((v) => {
1133
+ const value = formatter(v)
1134
+ if (!showShare) return { value, text: value }
1135
+ const share = barListShareText(v, total)
1136
+ return { value, share, text: `${value} · ${share}` }
1137
+ })
1138
+ }
1139
+
1140
+ /* -------------------------------------------------------------- DataTable */
1141
+
1142
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
1143
+ interface ChartDataTable {
1144
+ /** 表の見出し(`<caption>`)。 */
1145
+ caption?: string
1146
+ /** 列見出し。先頭がラベル列。 */
1147
+ columns: string[]
1148
+ /** 行。セルは書式済みの文字列。 */
1149
+ rows: string[][]
1150
+ }
1151
+
1152
+ /**
1153
+ * The chart's numbers as a table, for screen readers: one row per data row, the
1154
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
1155
+ * 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).
1156
+ */
1157
+ function chartDataTable(
1158
+ data: readonly Record<string, unknown>[],
1159
+ index: string,
1160
+ categories: readonly string[],
1161
+ formatter: ValueFormatter,
1162
+ labels?: Readonly<Record<string, string>>,
1163
+ indexName?: string,
1164
+ ): ChartDataTable {
1165
+ const label = (key: string) => labels?.[key] ?? key
1166
+ return {
1167
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
1168
+ rows: data.map((row) => [
1169
+ String(row[index] ?? ""),
1170
+ ...categories.map((key) => {
1171
+ const n = toChartNumber(row[key])
1172
+ return n === null ? EMPTY_VALUE : formatter(n)
1173
+ }),
1174
+ ]),
1175
+ }
1176
+ }
1177
+
95
1178
  /* ------------------------------------------------------------ CategoryBar */
96
1179
 
97
1180
  interface CategoryBarSegment {
@@ -126,9 +1209,11 @@ interface CategoryBarLabel {
126
1209
  * Tick labels under the bar: `0` at the start, then the running total at each
127
1210
  * segment's end. A label closer than `minGap` percent to the one before is
128
1211
  * dropped so narrow segments don't print on top of each other — except the
129
- * last one (the total), which replaces its neighbour instead.
1212
+ * last one (the total), which replaces its neighbour instead. With a
1213
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
1214
+ * too — the marker sits right under it and the two read as one crowded spot.
130
1215
  */
131
- function categoryBarLabels(values: readonly number[], minGap = 8): CategoryBarLabel[] {
1216
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
132
1217
  const segments = categoryBarSegments(values).filter((s) => s.width > 0)
133
1218
  if (segments.length === 0) return []
134
1219
  const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
@@ -138,7 +1223,46 @@ function categoryBarLabels(values: readonly number[], minGap = 8): CategoryBarLa
138
1223
  if (label.position - prev.position >= minGap) labels.push(label)
139
1224
  else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
140
1225
  })
141
- return labels
1226
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1227
+ return labels.filter(
1228
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1229
+ )
1230
+ }
1231
+
1232
+ /**
1233
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1234
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1235
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1236
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1237
+ * the rest 7 px at 12 px type).
1238
+ */
1239
+ function categoryBarFitLabels(
1240
+ labels: readonly CategoryBarLabel[],
1241
+ texts: readonly string[],
1242
+ width: number,
1243
+ gap = 8,
1244
+ ): CategoryBarLabel[] {
1245
+ const textWidth = (text: string) => {
1246
+ let w = 0
1247
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1248
+ return w
1249
+ }
1250
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1251
+ const w = textWidth(text)
1252
+ if (label.position <= 0) return [0, w]
1253
+ if (label.position >= 100) return [width - w, width]
1254
+ const center = (label.position / 100) * width
1255
+ return [center - w / 2, center + w / 2]
1256
+ }
1257
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1258
+ labels.forEach((label, i) => {
1259
+ const here = extent(label, texts[i] ?? "")
1260
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1261
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1262
+ else if (touches()) return
1263
+ kept.push({ label, extent: here })
1264
+ })
1265
+ return kept.map((k) => k.label)
142
1266
  }
143
1267
 
144
1268
  /** Marker position in percent of the bar, clamped to its ends. */
@@ -183,6 +1307,84 @@ function progressCircleGeometry(
183
1307
  return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
184
1308
  }
185
1309
 
1310
+ /* ---------------------------------------------------------------- summary */
1311
+
1312
+ interface ChartSummaryInput {
1313
+ data: readonly Record<string, unknown>[]
1314
+ /** The x-axis key. */
1315
+ index: string
1316
+ /** Series keys; the first one is described. */
1317
+ categories: readonly string[]
1318
+ /** Title of the chart, put in front when given. */
1319
+ title?: string
1320
+ /** Same as the chart's `format` (default `"compact"`). */
1321
+ format?: ValueFormat
1322
+ /** Wins over `format`. */
1323
+ valueFormatter?: ValueFormatter
1324
+ /** Language of the sentence. Default the page's locale (`<html lang>`). */
1325
+ locale?: string
1326
+ }
1327
+
1328
+ const SUMMARY_TEXT = {
1329
+ ja: {
1330
+ up: "、前の点より増加",
1331
+ down: "、前の点より減少",
1332
+ flat: "、前の点と横ばい",
1333
+ latest: (label: string, value: string) => `最新 ${label} は ${value}`,
1334
+ top: (name: string, share: string) => `最大は ${name}(${share})`,
1335
+ },
1336
+ en: {
1337
+ up: ", up from the previous point",
1338
+ down: ", down from the previous point",
1339
+ flat: ", flat from the previous point",
1340
+ latest: (label: string, value: string) => `Latest ${label}: ${value}`,
1341
+ top: (name: string, share: string) => `Largest: ${name} (${share})`,
1342
+ },
1343
+ }
1344
+
1345
+ /**
1346
+ * One-sentence summary built from the rows, for `summary="auto"`:
1347
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
1348
+ * computed from the last two non-empty points of the first series — never
1349
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1350
+ * no usable point.
1351
+ */
1352
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1353
+ const key = input.categories[0]
1354
+ if (key === undefined) return undefined
1355
+ const points: { label: string; value: number }[] = []
1356
+ for (const row of input.data) {
1357
+ const raw = row[key]
1358
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1359
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1360
+ }
1361
+ const latest = points[points.length - 1]
1362
+ if (!latest) return undefined
1363
+ const locale = resolveLocale(input.locale)
1364
+ const t = SUMMARY_TEXT[uiLanguage(locale)]
1365
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
1366
+ const prev = points[points.length - 2]
1367
+ const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
1368
+ const head = input.title ? `${input.title}: ` : ""
1369
+ return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
1370
+ }
1371
+
1372
+ /**
1373
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
1374
+ * (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
1375
+ */
1376
+ function buildShareSummary(
1377
+ slices: readonly { name: string; value: number }[],
1378
+ title?: string,
1379
+ locale?: string,
1380
+ ): string | undefined {
1381
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1382
+ const top = slices[0]
1383
+ if (!top || total <= 0) return undefined
1384
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1385
+ return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
1386
+ }
1387
+
186
1388
  /* ---------- end of inlined code ---------- */
187
1389
 
188
1390
  export interface CategoryBarMarker {
@@ -190,30 +1392,45 @@ export interface CategoryBarMarker {
190
1392
  value: number
191
1393
  /** ホバーで出す説明。 */
192
1394
  tooltip?: string
193
- /** 位置の変化をアニメーションする。 */
1395
+ /** 位置の変化をアニメーションする。既定 `false`(`prefers-reduced-motion` では常に無効)。 */
194
1396
  showAnimation?: boolean
195
1397
  }
196
1398
 
197
1399
  export interface CategoryBarProps extends Omit<ComponentProps<"div">, "children"> {
198
1400
  /** 各区間の幅(相対値)。合計が 100 である必要はない。負の値は 0 扱い。 */
199
1401
  values: number[]
200
- /** 区間の色(順に対応)。`"chart-1"`〜`"chart-5"` か CSS カラー。省略時はトークン順。 */
1402
+ /** 区間の色(順に対応)。`"chart-1"`〜`"chart-5"`・意味色(`"positive"` など。面用の `--<tone>-fill` で塗る)・CSS カラー。省略時はトークン順。 */
201
1403
  colors?: ChartColor[]
202
1404
  marker?: CategoryBarMarker
203
1405
  /** バーの上に区切りの累計値を出す。既定 `true`。 */
204
1406
  showLabels?: boolean
205
- /** 区切りの数値の書式。 */
1407
+ /**
1408
+ * 区切りの数値の書式(`"compact"` / `"currency"` / `{ type, currency }`)。他のグラフの
1409
+ * 軸と同じ短縮形で出す(`"currency"` → `¥780万`)。既定 `"compact"`。
1410
+ */
1411
+ format?: ValueFormat
1412
+ /** 書式を関数で直接渡す逃げ道。`format` より優先する。 */
206
1413
  valueFormatter?: ValueFormatter
207
1414
  }
208
1415
 
1416
+ /** Values not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
1417
+ const NO_ROWS: never[] = []
1418
+
209
1419
  export const CategoryBar = forwardRef<HTMLDivElement, CategoryBarProps>(function CategoryBar(
210
- { values, colors, marker, showLabels = true, valueFormatter = defaultValueFormatter, className, ...props },
211
- ref,
1420
+ { values = NO_ROWS, colors, marker, showLabels = true, format, valueFormatter: valueFormatterProp, className, ...props },
1421
+ forwardedRef,
212
1422
  ) {
1423
+ // The bar's width thins the running totals that would print over each other.
1424
+ const { ref, width } = useChartSurface(forwardedRef, null)
1425
+ const locale = useLocale()
1426
+ const valueFormatter = useMemo(() => resolveAxisFormatter(valueFormatterProp, format, locale), [valueFormatterProp, format, locale])
213
1427
  const segments = categoryBarSegments(values)
214
- const labels = showLabels ? categoryBarLabels(values) : []
215
1428
  const markerPosition = marker ? categoryBarMarkerPosition(marker.value, values) : 0
216
- const markerColor = marker ? chartColorToCss(chartColorAt(colors, categoryBarMarkerSegment(marker.value, values))) : ""
1429
+ const allLabels = showLabels ? categoryBarLabels(values, undefined, marker ? markerPosition : undefined) : []
1430
+ const labels = width
1431
+ ? categoryBarFitLabels(allLabels, allLabels.map((label) => valueFormatter(label.value)), width)
1432
+ : allLabels
1433
+ const markerColor = marker ? chartFillToCss(chartColorAt(colors, categoryBarMarkerSegment(marker.value, values))) : ""
217
1434
 
218
1435
  const markerDot = (
219
1436
  <span
@@ -248,7 +1465,7 @@ export const CategoryBar = forwardRef<HTMLDivElement, CategoryBarProps>(function
248
1465
  key={i}
249
1466
  data-slot="category-bar-segment"
250
1467
  className="h-full"
251
- style={{ flex: `${segment.width} 1 0%`, background: chartColorToCss(chartColorAt(colors, i)) }}
1468
+ style={{ flex: `${segment.width} 1 0%`, background: chartFillToCss(chartColorAt(colors, i)) }}
252
1469
  />
253
1470
  ) : null,
254
1471
  )}
@@ -258,7 +1475,7 @@ export const CategoryBar = forwardRef<HTMLDivElement, CategoryBarProps>(function
258
1475
  data-slot="category-bar-marker"
259
1476
  className={cn(
260
1477
  "absolute -translate-x-1/2",
261
- marker.showAnimation && "transition-[left] duration-700 ease-out",
1478
+ marker.showAnimation && "transition-[left] duration-700 ease-out motion-reduce:transition-none",
262
1479
  )}
263
1480
  style={{ left: `${markerPosition}%` }}
264
1481
  >