@squadbase/vantage 0.6.2-stg.3a2ba98 → 0.7.0-dev1.275b4ed

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 (346) hide show
  1. package/dist/add-4GHF2TX2.js +6 -0
  2. package/dist/add-4GHF2TX2.js.map +1 -0
  3. package/dist/{build-O5TVNH4E.js → build-U7GO26HR.js} +9 -9
  4. package/dist/{build-O5TVNH4E.js.map → build-U7GO26HR.js.map} +1 -1
  5. package/dist/{check-WFBEDHDR.js → check-MRVAIHG5.js} +7 -7
  6. package/dist/{check-WFBEDHDR.js.map → check-MRVAIHG5.js.map} +1 -1
  7. package/dist/chunk-2IAPIOPS.js +152 -0
  8. package/dist/chunk-2IAPIOPS.js.map +1 -0
  9. package/dist/chunk-3RJEOP3J.js +174 -0
  10. package/dist/chunk-3RJEOP3J.js.map +1 -0
  11. package/dist/chunk-77CISBMG.js +7581 -0
  12. package/dist/chunk-77CISBMG.js.map +1 -0
  13. package/dist/{chunk-QDZA5JSL.js → chunk-AABMKHEU.js} +4 -4
  14. package/dist/{chunk-QDZA5JSL.js.map → chunk-AABMKHEU.js.map} +1 -1
  15. package/dist/{chunk-PVTHHV7X.js → chunk-ANZLVSEP.js} +28 -7
  16. package/dist/chunk-ANZLVSEP.js.map +1 -0
  17. package/dist/chunk-CKWPK4RO.js +50 -0
  18. package/dist/chunk-CKWPK4RO.js.map +1 -0
  19. package/dist/chunk-EG4PX726.js +678 -0
  20. package/dist/chunk-EG4PX726.js.map +1 -0
  21. package/dist/{chunk-3G43C6OL.js → chunk-GNXCX4WE.js} +46 -3
  22. package/dist/chunk-GNXCX4WE.js.map +1 -0
  23. package/dist/chunk-NZ5QIIG4.js +74 -0
  24. package/dist/chunk-NZ5QIIG4.js.map +1 -0
  25. package/dist/{chunk-BCE22JSM.js → chunk-PJ4SPXHS.js} +52 -16
  26. package/dist/chunk-PJ4SPXHS.js.map +1 -0
  27. package/dist/{chunk-RPZAALCX.js → chunk-QNOX7WLZ.js} +256 -165
  28. package/dist/chunk-QNOX7WLZ.js.map +1 -0
  29. package/dist/{chunk-ZVANIULZ.js → chunk-RNTDBX6S.js} +4 -4
  30. package/dist/{chunk-ZVANIULZ.js.map → chunk-RNTDBX6S.js.map} +1 -1
  31. package/dist/{chunk-PXRX5PEC.js → chunk-ROHNXP7J.js} +73 -4
  32. package/dist/chunk-ROHNXP7J.js.map +1 -0
  33. package/dist/chunk-S5MDTHH7.js +466 -0
  34. package/dist/chunk-S5MDTHH7.js.map +1 -0
  35. package/dist/chunk-SDJTTMLK.js +1877 -0
  36. package/dist/chunk-SDJTTMLK.js.map +1 -0
  37. package/dist/{chunk-EP6JHXSR.js → chunk-SHZM3EXB.js} +68 -12
  38. package/dist/chunk-SHZM3EXB.js.map +1 -0
  39. package/dist/chunk-TRMHNMMZ.js +61 -0
  40. package/dist/chunk-TRMHNMMZ.js.map +1 -0
  41. package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
  42. package/dist/chunk-U736PVHY.js.map +1 -0
  43. package/dist/{chunk-JGRMRXXZ.js → chunk-UWSQUHX6.js} +4 -99
  44. package/dist/chunk-UWSQUHX6.js.map +1 -0
  45. package/dist/cli.js +15 -11
  46. package/dist/cli.js.map +1 -1
  47. package/dist/client/index.d.ts +34 -3
  48. package/dist/client/index.js +211 -12
  49. package/dist/client/index.js.map +1 -1
  50. package/dist/components/index.d.ts +1768 -30
  51. package/dist/components/index.js +7 -4
  52. package/dist/delta-text-CbrOaW83.d.ts +17 -0
  53. package/dist/{dev-NZRLOQCL.js → dev-O42JFQ64.js} +24 -13
  54. package/dist/dev-O42JFQ64.js.map +1 -0
  55. package/dist/doc/index.d.ts +215 -2
  56. package/dist/doc/index.js +423 -5
  57. package/dist/doc/index.js.map +1 -1
  58. package/dist/{docs-ZGDJUHJI.js → docs-JVP4RPKT.js} +3 -3
  59. package/dist/{docs-ZGDJUHJI.js.map → docs-JVP4RPKT.js.map} +1 -1
  60. package/dist/{doctor-VFKEMR54.js → doctor-YD3XAAOT.js} +8 -8
  61. package/dist/doctor-YD3XAAOT.js.map +1 -0
  62. package/dist/format-DihQkL1N.d.ts +249 -0
  63. package/dist/markdown/index.js +1 -1
  64. package/dist/markdown/index.js.map +1 -1
  65. package/dist/{preview-QDCIVVSR.js → preview-T6CLSQVX.js} +12 -4
  66. package/dist/preview-T6CLSQVX.js.map +1 -0
  67. package/dist/query/index.d.ts +0 -11
  68. package/dist/query/index.js +2 -2
  69. package/dist/{routes-RHP5FVGD.js → routes-PVKNT777.js} +6 -6
  70. package/dist/{routes-RHP5FVGD.js.map → routes-PVKNT777.js.map} +1 -1
  71. package/dist/{search-RFBELGY7.js → search-5LC4XPB5.js} +3 -3
  72. package/dist/{search-RFBELGY7.js.map → search-5LC4XPB5.js.map} +1 -1
  73. package/dist/slide/index.d.ts +272 -1
  74. package/dist/slide/index.js +1086 -19
  75. package/dist/slide/index.js.map +1 -1
  76. package/dist/table/index.js +14 -10
  77. package/dist/table/index.js.map +1 -1
  78. package/dist/ui/index.d.ts +148 -12
  79. package/dist/ui/index.js +1340 -88
  80. package/dist/ui/index.js.map +1 -1
  81. package/dist/{upgrade-GF2P67M6.js → upgrade-6DT7ADRP.js} +7 -7
  82. package/dist/{upgrade-GF2P67M6.js.map → upgrade-6DT7ADRP.js.map} +1 -1
  83. package/dist/vite/index.d.ts +10 -0
  84. package/dist/vite/index.js +4 -4
  85. package/docs/en/agent-skills.md +1 -1
  86. package/docs/en/changelog.md +82 -0
  87. package/docs/en/cli-reference.md +30 -0
  88. package/docs/en/components.md +42 -17
  89. package/docs/en/doc/delta-text.md +40 -0
  90. package/docs/en/doc/doc-action-items.md +49 -0
  91. package/docs/en/doc/doc-callout.md +38 -0
  92. package/docs/en/doc/doc-data-table.md +60 -0
  93. package/docs/en/doc/doc-executive-summary.md +64 -0
  94. package/docs/en/doc/doc-figure.md +56 -0
  95. package/docs/en/doc/doc-key-findings.md +61 -0
  96. package/docs/en/doc/doc-kpi-scorecard.md +80 -0
  97. package/docs/en/doc/doc-notes-and-sources.md +43 -0
  98. package/docs/en/doc/doc-report-header.md +46 -0
  99. package/docs/en/pages-and-metadata.md +15 -0
  100. package/docs/en/parts/area-chart.md +99 -0
  101. package/docs/en/parts/bar-chart.md +91 -0
  102. package/docs/en/parts/bar-list.md +50 -0
  103. package/docs/en/parts/category-bar.md +37 -0
  104. package/docs/en/parts/chart-frame.md +39 -0
  105. package/docs/en/parts/data-table.md +22 -0
  106. package/docs/en/parts/delta.md +51 -0
  107. package/docs/en/parts/donut-chart.md +72 -0
  108. package/docs/en/parts/format.md +43 -0
  109. package/docs/en/parts/funnel-steps.md +2 -1
  110. package/docs/en/parts/heatmap.md +53 -0
  111. package/docs/en/parts/kpi-card.md +58 -0
  112. package/docs/en/parts/legend.md +35 -0
  113. package/docs/en/parts/line-chart.md +94 -0
  114. package/docs/en/parts/metric-value.md +3 -2
  115. package/docs/en/parts/page-shell.md +1 -1
  116. package/docs/en/parts/progress-circle.md +33 -0
  117. package/docs/en/parts/sample-data.md +39 -0
  118. package/docs/en/parts/scatter-chart.md +56 -0
  119. package/docs/en/parts/sparkline.md +1 -1
  120. package/docs/en/parts/tracker.md +36 -0
  121. package/docs/en/parts/trend-indicator.md +17 -1
  122. package/docs/en/parts/updated-at.md +30 -0
  123. package/docs/en/parts/waterfall-chart.md +56 -0
  124. package/docs/en/slide/slide-chart-full.md +48 -0
  125. package/docs/en/slide/slide-chart-insight.md +52 -0
  126. package/docs/en/slide/slide-columns.md +46 -0
  127. package/docs/en/slide/slide-comparison.md +68 -0
  128. package/docs/en/slide/slide-cover.md +39 -0
  129. package/docs/en/slide/slide-exec-summary.md +47 -0
  130. package/docs/en/slide/slide-heading.md +38 -0
  131. package/docs/en/slide/slide-kpi-grid.md +55 -0
  132. package/docs/en/slide/slide-kpi-hero.md +58 -0
  133. package/docs/en/slide/slide-next-actions.md +49 -0
  134. package/docs/en/slide/slide-scorecard-table.md +54 -0
  135. package/docs/en/slide/slide-section.md +44 -0
  136. package/docs/en/slide/slide-source-line.md +34 -0
  137. package/docs/en/ui/alert-dialog.md +42 -0
  138. package/docs/en/ui/avatar.md +31 -0
  139. package/docs/en/ui/combobox.md +74 -0
  140. package/docs/en/ui/drawer.md +41 -0
  141. package/docs/en/ui/empty.md +1 -1
  142. package/docs/en/ui/error-state.md +4 -3
  143. package/docs/en/ui/field.md +42 -0
  144. package/docs/en/ui/hover-card.md +21 -0
  145. package/docs/en/ui/kbd.md +17 -0
  146. package/docs/en/ui/loading.md +1 -1
  147. package/docs/en/ui/pagination.md +36 -0
  148. package/docs/en/ui/radio-group.md +21 -0
  149. package/docs/en/ui/toast.md +44 -0
  150. package/docs/en/ui/toggle-group.md +4 -3
  151. package/docs/en/ui-and-theming.md +1 -1
  152. package/docs/index.json +1184 -114
  153. package/docs/ja/agent-skills.md +1 -1
  154. package/docs/ja/changelog.md +84 -0
  155. package/docs/ja/cli-reference.md +29 -0
  156. package/docs/ja/components.md +68 -101
  157. package/docs/ja/doc/delta-text.md +40 -0
  158. package/docs/ja/doc/doc-action-items.md +49 -0
  159. package/docs/ja/doc/doc-callout.md +38 -0
  160. package/docs/ja/doc/doc-data-table.md +60 -0
  161. package/docs/ja/doc/doc-executive-summary.md +64 -0
  162. package/docs/ja/doc/doc-figure.md +56 -0
  163. package/docs/ja/doc/doc-key-findings.md +61 -0
  164. package/docs/ja/doc/doc-kpi-scorecard.md +80 -0
  165. package/docs/ja/doc/doc-notes-and-sources.md +43 -0
  166. package/docs/ja/doc/doc-report-header.md +46 -0
  167. package/docs/ja/page-types/csv.md +83 -0
  168. package/docs/ja/page-types/doc.md +83 -0
  169. package/docs/ja/page-types/excel.md +82 -0
  170. package/docs/ja/page-types/slide.md +133 -0
  171. package/docs/ja/page-types.md +47 -0
  172. package/docs/ja/pages-and-metadata.md +15 -0
  173. package/docs/ja/parts/area-chart.md +85 -0
  174. package/docs/ja/parts/bar-chart.md +95 -0
  175. package/docs/ja/parts/bar-list.md +58 -0
  176. package/docs/ja/parts/category-bar.md +36 -0
  177. package/docs/ja/parts/chart-frame.md +36 -0
  178. package/docs/ja/parts/data-table.md +22 -0
  179. package/docs/ja/parts/delta.md +51 -0
  180. package/docs/ja/parts/donut-chart.md +66 -0
  181. package/docs/ja/parts/echart.md +3 -0
  182. package/docs/ja/parts/format.md +44 -0
  183. package/docs/ja/parts/funnel-steps.md +27 -8
  184. package/docs/ja/parts/heatmap.md +45 -0
  185. package/docs/ja/parts/kpi-card.md +56 -0
  186. package/docs/ja/parts/legend.md +36 -0
  187. package/docs/ja/parts/line-chart.md +84 -0
  188. package/docs/ja/parts/metric-value.md +3 -2
  189. package/docs/ja/parts/page-shell.md +1 -1
  190. package/docs/ja/parts/progress-circle.md +34 -0
  191. package/docs/ja/parts/sample-data.md +61 -0
  192. package/docs/ja/parts/scatter-chart.md +69 -0
  193. package/docs/ja/parts/sparkline.md +2 -2
  194. package/docs/ja/parts/tracker.md +32 -0
  195. package/docs/ja/parts/trend-indicator.md +17 -1
  196. package/docs/ja/parts/updated-at.md +27 -0
  197. package/docs/ja/parts/waterfall-chart.md +61 -0
  198. package/docs/ja/routing.md +8 -86
  199. package/docs/ja/slide/slide-chart-full.md +48 -0
  200. package/docs/ja/slide/slide-chart-insight.md +52 -0
  201. package/docs/ja/slide/slide-columns.md +46 -0
  202. package/docs/ja/slide/slide-comparison.md +68 -0
  203. package/docs/ja/slide/slide-cover.md +39 -0
  204. package/docs/ja/slide/slide-exec-summary.md +47 -0
  205. package/docs/ja/slide/slide-heading.md +38 -0
  206. package/docs/ja/slide/slide-kpi-grid.md +55 -0
  207. package/docs/ja/slide/slide-kpi-hero.md +58 -0
  208. package/docs/ja/slide/slide-next-actions.md +49 -0
  209. package/docs/ja/slide/slide-scorecard-table.md +54 -0
  210. package/docs/ja/slide/slide-section.md +44 -0
  211. package/docs/ja/slide/slide-source-line.md +34 -0
  212. package/docs/ja/ui/alert-dialog.md +41 -0
  213. package/docs/ja/ui/avatar.md +31 -0
  214. package/docs/ja/ui/combobox.md +74 -0
  215. package/docs/ja/ui/drawer.md +41 -0
  216. package/docs/ja/ui/empty.md +1 -1
  217. package/docs/ja/ui/error-state.md +4 -3
  218. package/docs/ja/ui/field.md +42 -0
  219. package/docs/ja/ui/hover-card.md +21 -0
  220. package/docs/ja/ui/kbd.md +16 -0
  221. package/docs/ja/ui/loading.md +1 -1
  222. package/docs/ja/ui/pagination.md +36 -0
  223. package/docs/ja/ui/radio-group.md +21 -0
  224. package/docs/ja/ui/toast.md +46 -0
  225. package/docs/ja/ui/toggle-group.md +4 -3
  226. package/docs/ja/ui-and-theming.md +14 -7
  227. package/package.json +43 -29
  228. package/registry/ui/accordion.tsx +76 -0
  229. package/registry/ui/alert-dialog.tsx +189 -0
  230. package/registry/ui/alert.tsx +80 -0
  231. package/registry/ui/app-shell.tsx +424 -0
  232. package/registry/ui/area-chart.tsx +3960 -0
  233. package/registry/ui/attention-list.tsx +465 -0
  234. package/registry/ui/avatar.tsx +110 -0
  235. package/registry/ui/badge.tsx +56 -0
  236. package/registry/ui/bar-chart.tsx +3954 -0
  237. package/registry/ui/bar-list.tsx +3998 -0
  238. package/registry/ui/box-plot-chart.tsx +4214 -0
  239. package/registry/ui/breadcrumb.tsx +128 -0
  240. package/registry/ui/button.tsx +62 -0
  241. package/registry/ui/calendar.tsx +223 -0
  242. package/registry/ui/card.tsx +107 -0
  243. package/registry/ui/category-bar.tsx +1498 -0
  244. package/registry/ui/chart-frame.tsx +1604 -0
  245. package/registry/ui/checkbox.tsx +30 -0
  246. package/registry/ui/collapsible.tsx +23 -0
  247. package/registry/ui/combobox.tsx +310 -0
  248. package/registry/ui/command.tsx +198 -0
  249. package/registry/ui/dashboard-card.tsx +217 -0
  250. package/registry/ui/data-table.tsx +896 -157
  251. package/registry/ui/date-range-picker.tsx +544 -0
  252. package/registry/ui/delta.tsx +350 -0
  253. package/registry/ui/dialog.tsx +161 -0
  254. package/registry/ui/donut-chart.tsx +4006 -0
  255. package/registry/ui/drawer.tsx +229 -0
  256. package/registry/ui/dropdown-menu.tsx +274 -0
  257. package/registry/ui/echart.tsx +1178 -0
  258. package/registry/ui/field.tsx +240 -0
  259. package/registry/ui/filter-bar.tsx +551 -0
  260. package/registry/ui/funnel-steps.tsx +3843 -0
  261. package/registry/ui/heatmap.tsx +2027 -0
  262. package/registry/ui/histogram-chart.tsx +4284 -0
  263. package/registry/ui/hover-card.tsx +52 -0
  264. package/registry/ui/input-group.tsx +160 -0
  265. package/registry/ui/input.tsx +24 -0
  266. package/registry/ui/kbd.tsx +30 -0
  267. package/registry/ui/kpi-card.tsx +905 -0
  268. package/registry/ui/label.tsx +22 -0
  269. package/registry/ui/legend.tsx +3817 -0
  270. package/registry/ui/line-chart.tsx +3958 -0
  271. package/registry/ui/metric-value.tsx +62 -0
  272. package/registry/ui/multi-select.tsx +382 -0
  273. package/registry/ui/page-shell.tsx +420 -0
  274. package/registry/ui/pagination.tsx +140 -0
  275. package/registry/ui/paired-chart.tsx +4086 -0
  276. package/registry/ui/placeholder.tsx +36 -0
  277. package/registry/ui/popover.tsx +92 -0
  278. package/registry/ui/progress-circle.tsx +1033 -0
  279. package/registry/ui/progress.tsx +85 -0
  280. package/registry/ui/radio-group.tsx +39 -0
  281. package/registry/ui/sample-data.tsx +230 -0
  282. package/registry/ui/scatter-chart.tsx +4503 -0
  283. package/registry/ui/scroll-area.tsx +56 -0
  284. package/registry/ui/searchable-select.tsx +352 -0
  285. package/registry/ui/section-header.tsx +43 -0
  286. package/registry/ui/segmented-control.tsx +76 -0
  287. package/registry/ui/select.tsx +255 -0
  288. package/registry/ui/separator.tsx +27 -0
  289. package/registry/ui/sheet.tsx +139 -0
  290. package/registry/ui/sidebar.tsx +725 -0
  291. package/registry/ui/skeleton.tsx +17 -0
  292. package/registry/ui/slider.tsx +56 -0
  293. package/registry/ui/sparkline.tsx +230 -0
  294. package/registry/ui/spinner.tsx +14 -0
  295. package/registry/ui/states.tsx +247 -0
  296. package/registry/ui/status-badge.tsx +286 -0
  297. package/registry/ui/switch.tsx +34 -0
  298. package/registry/ui/table.tsx +118 -0
  299. package/registry/ui/tabs.tsx +84 -0
  300. package/registry/ui/textarea.tsx +22 -0
  301. package/registry/ui/toast.tsx +250 -0
  302. package/registry/ui/toggle-group.tsx +91 -0
  303. package/registry/ui/toggle.tsx +47 -0
  304. package/registry/ui/tooltip.tsx +72 -0
  305. package/registry/ui/tracker.tsx +1015 -0
  306. package/registry/ui/trend-indicator.tsx +217 -0
  307. package/registry/ui/updated-at.tsx +276 -0
  308. package/registry/ui/waterfall-chart.tsx +4561 -0
  309. package/skills/vantage-add-feature/SKILL.md +14 -7
  310. package/skills/vantage-design/SKILL.md +62 -52
  311. package/skills/vantage-design/references/extract.md +26 -27
  312. package/skills/vantage-design/references/format.md +12 -172
  313. package/skills/vantage-design/references/presets.md +50 -110
  314. package/skills/vantage-pitfalls/SKILL.md +10 -1
  315. package/skills/vantage-slide/SKILL.md +71 -36
  316. package/templates/AGENTS.md +54 -16
  317. package/templates/agents/api.md +36 -0
  318. package/templates/agents/csv.md +2 -1
  319. package/templates/agents/doc.md +52 -3
  320. package/templates/agents/page.md +91 -10
  321. package/templates/agents/slide.md +90 -4
  322. package/templates/agents/xlsx.md +2 -1
  323. package/theme.css +247 -132
  324. package/dist/add-EISGSZAH.js +0 -6
  325. package/dist/add-EISGSZAH.js.map +0 -1
  326. package/dist/chunk-3G43C6OL.js.map +0 -1
  327. package/dist/chunk-5ZOP4SQR.js +0 -47
  328. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  329. package/dist/chunk-A2UUGASH.js.map +0 -1
  330. package/dist/chunk-BCE22JSM.js.map +0 -1
  331. package/dist/chunk-DTDVSFRY.js +0 -29
  332. package/dist/chunk-DTDVSFRY.js.map +0 -1
  333. package/dist/chunk-EP6JHXSR.js.map +0 -1
  334. package/dist/chunk-JGRMRXXZ.js.map +0 -1
  335. package/dist/chunk-KLEIVDUV.js +0 -165
  336. package/dist/chunk-KLEIVDUV.js.map +0 -1
  337. package/dist/chunk-LSRMRIXA.js +0 -2227
  338. package/dist/chunk-LSRMRIXA.js.map +0 -1
  339. package/dist/chunk-PVTHHV7X.js.map +0 -1
  340. package/dist/chunk-PXRX5PEC.js.map +0 -1
  341. package/dist/chunk-RPZAALCX.js.map +0 -1
  342. package/dist/chunk-T3FLAGI6.js +0 -316
  343. package/dist/chunk-T3FLAGI6.js.map +0 -1
  344. package/dist/dev-NZRLOQCL.js.map +0 -1
  345. package/dist/doctor-VFKEMR54.js.map +0 -1
  346. package/dist/preview-QDCIVVSR.js.map +0 -1
@@ -0,0 +1,1604 @@
1
+ // Copied by `vantage add ui chart-frame`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/charts/chart-frame.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * ChartFrame — the frame every typed chart renders in: an optional title and a
7
+ * one-sentence summary above a plot area of fixed height. The plot is labelled
8
+ * by the title and described by the summary, so a screen reader hears what the
9
+ * chart says, not just that there is one.
10
+ *
11
+ * The plot area is the frame's one `role="img"` (`EChart` inside it drops its
12
+ * own); `dataTable` adds the numbers as a visually-hidden table beside it, so a
13
+ * screen reader can read the values the canvas only draws.
14
+ *
15
+ * The plot area keeps its height in every state: while loading it shows a
16
+ * skeleton shaped like the final chart, and with no data it says so (and offers
17
+ * one action) instead of drawing empty axes.
18
+ */
19
+ import { forwardRef, useId, type HTMLAttributes, type ReactNode } from "react"
20
+
21
+ import { cn } from "@squadbase/vantage/ui"
22
+ import type { ChartEmptyState } from "@squadbase/vantage/components"
23
+ import { useSyncExternalStore } from "react"
24
+ import { createContext, useCallback, useEffect, useRef, useState, type ForwardedRef, type RefObject } from "react"
25
+ import type { ChartTone } from "@squadbase/vantage/components"
26
+ import { EMPTY_VALUE, formatValue, toValueFormatter, type ValueFormat } from "@squadbase/vantage/components"
27
+ import type { ChartColor, ChartColors, ChartSeriesColor, ValueFormatter } 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
+ }
153
+
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)
177
+
178
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
179
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
180
+
181
+ interface ChartTokens {
182
+ /** Resolved `--chart-1..5`, in order. */
183
+ series: string[]
184
+ /** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
185
+ fontFamily?: string
186
+ /** Body text: titles and the default `textStyle`. */
187
+ foreground: string | null
188
+ /** Secondary text: axis labels, legend, subtitles. */
189
+ mutedForeground: string | null
190
+ /** Axis lines, ticks, split lines, tooltip border. */
191
+ border: string | null
192
+ /** Tooltip surface. */
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
198
+ /** Tooltip text. */
199
+ popoverForeground: string | null
200
+ }
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
+
211
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
212
+
213
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
214
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
215
+
216
+ /**
217
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
218
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
219
+ * input is written over two different known colours: agreeing results mean the
220
+ * value parsed, differing ones mean it was dropped.
221
+ */
222
+ function toCanvasColor(value: string): string | null {
223
+ const raw = value.trim()
224
+ if (!raw) return null
225
+ if (normalizeContext === undefined) {
226
+ const canvas = document.createElement("canvas")
227
+ canvas.width = 1
228
+ canvas.height = 1
229
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
230
+ }
231
+ const ctx = normalizeContext
232
+ if (!ctx) return raw
233
+ ctx.fillStyle = "#000000"
234
+ ctx.fillStyle = raw
235
+ const onBlack = ctx.fillStyle
236
+ ctx.fillStyle = "#ffffff"
237
+ ctx.fillStyle = raw
238
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
239
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
240
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
241
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
242
+ ctx.clearRect(0, 0, 1, 1)
243
+ ctx.fillRect(0, 0, 1, 1)
244
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
245
+ return a === 255
246
+ ? `rgb(${r}, ${g}, ${b})`
247
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
248
+ }
249
+
250
+ /**
251
+ * Read the chart tokens off `el` (the document root by default — tokens live on
252
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
253
+ * to plain ECharts defaults.
254
+ */
255
+ function readChartTokens(el?: Element | null): ChartTokens | null {
256
+ if (typeof document === "undefined") return null
257
+ const target = el ?? document.documentElement
258
+ if (!target) return null
259
+ const styles = getComputedStyle(target)
260
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
261
+ const series: string[] = []
262
+ for (const token of SERIES_TOKENS) {
263
+ const color = read(token)
264
+ if (color) series.push(color)
265
+ }
266
+ const tokens: ChartTokens = {
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 } : {}),
271
+ foreground: read("--foreground"),
272
+ mutedForeground: read("--muted-foreground"),
273
+ border: read("--border"),
274
+ popover: read("--popover"),
275
+ popoverForeground: read("--popover-foreground"),
276
+ }
277
+ tokenScopes.set(tokens, target)
278
+ return tokens
279
+ }
280
+
281
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
282
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
283
+ if (a === b) return true
284
+ if (!a || !b) return false
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) &&
290
+ a.series.length === b.series.length &&
291
+ a.series.every((color, i) => color === b.series[i]) &&
292
+ a.fontFamily === b.fontFamily &&
293
+ a.foreground === b.foreground &&
294
+ a.mutedForeground === b.mutedForeground &&
295
+ a.border === b.border &&
296
+ a.popover === b.popover &&
297
+ a.popoverForeground === b.popoverForeground
298
+ )
299
+ }
300
+
301
+ /**
302
+ * Watch everything that can change the resolved tokens and call `onChange` when
303
+ * something might have. It only ever says "re-read" — the caller compares with
304
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
305
+ * disposer.
306
+ *
307
+ * Two sources, not one:
308
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
309
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
310
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
311
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
312
+ * attributes alone leaves the chart painted in the previous palette until a
313
+ * reload — the tokens in the DOM are new, the canvas is not.
314
+ */
315
+ function watchChartTokens(onChange: () => void, scope?: Element | null): () => void {
316
+ if (typeof document === "undefined") return () => {}
317
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
318
+ // take it after the next frame so a swapped stylesheet has been applied.
319
+ let frame = 0
320
+ const schedule = () => {
321
+ if (frame) return
322
+ frame = requestAnimationFrame(() => {
323
+ frame = 0
324
+ onChange()
325
+ })
326
+ }
327
+
328
+ const themeObserver = new MutationObserver(schedule)
329
+ const attributeFilter = ["class", "style", "data-theme"]
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
+ }
335
+
336
+ const styleObserver = new MutationObserver(schedule)
337
+ if (document.head) {
338
+ styleObserver.observe(document.head, {
339
+ childList: true,
340
+ subtree: true,
341
+ characterData: true,
342
+ attributes: true,
343
+ attributeFilter: ["href", "media", "disabled"],
344
+ })
345
+ }
346
+
347
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
348
+ const onLoad = (event: Event) => {
349
+ if (event.target instanceof HTMLLinkElement) schedule()
350
+ }
351
+ document.addEventListener("load", onLoad, true)
352
+
353
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
354
+ media.addEventListener("change", schedule)
355
+
356
+ return () => {
357
+ if (frame) cancelAnimationFrame(frame)
358
+ themeObserver.disconnect()
359
+ styleObserver.disconnect()
360
+ document.removeEventListener("load", onLoad, true)
361
+ media.removeEventListener("change", schedule)
362
+ }
363
+ }
364
+
365
+ /** Shared shape for the four axis types ECharts themes address separately. */
366
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
367
+ const line = tokens.border ?? undefined
368
+ return {
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 } },
374
+ splitArea: { show: false },
375
+ }
376
+ }
377
+
378
+ /**
379
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
380
+ * app that sets its own palette keeps it.
381
+ */
382
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
383
+ const text = tokens.foreground ?? undefined
384
+ const muted = tokens.mutedForeground ?? undefined
385
+ const line = tokens.border ?? undefined
386
+ return {
387
+ // Let the page background show through: charts sit on cards, not on a canvas.
388
+ backgroundColor: "transparent",
389
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
390
+ textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
391
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
392
+ legend: { textStyle: { color: muted } },
393
+ categoryAxis: axisTheme(tokens, false),
394
+ valueAxis: axisTheme(tokens, true),
395
+ logAxis: axisTheme(tokens, true),
396
+ timeAxis: axisTheme(tokens, true),
397
+ tooltip: {
398
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
399
+ transitionDuration: 0,
400
+ backgroundColor: tokens.popover ?? undefined,
401
+ borderColor: line,
402
+ borderWidth: 1,
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
+ },
411
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
412
+ },
413
+ }
414
+ }
415
+
416
+ /**
417
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
418
+ * they may have moved, and only replaced when a value actually changed. For
419
+ * components that build an ECharts option from token colours themselves (the
420
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
421
+ */
422
+ function useChartTokens(scope?: Element | null | RefObject<Element | null>): ChartTokens | null {
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)
428
+ useEffect(() => {
429
+ const target = scope && "current" in scope ? scope.current : scope
430
+ const sync = () => {
431
+ const next = readChartTokens(target)
432
+ if (sameChartTokens(tokensRef.current, next)) return
433
+ tokensRef.current = next
434
+ setTokens(next)
435
+ }
436
+ sync()
437
+ return watchChartTokens(sync, target)
438
+ }, [scope])
439
+ return tokens
440
+ }
441
+
442
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
443
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
444
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
445
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
446
+
447
+ /**
448
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
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
451
+ * other CSS colour is normalized like the tokens are. A colour that can't be
452
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
453
+ */
454
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
455
+ return colors.map((color) => {
456
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
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
+ }
464
+ if (typeof document === "undefined") return color
465
+ let value = color.trim()
466
+ const cssVar = CSS_VAR_RE.exec(value)
467
+ const styles = getComputedStyle((tokens && tokenScopes.get(tokens)) ?? document.documentElement)
468
+ if (cssVar) {
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())
474
+ }
475
+ return toCanvasColor(value) ?? ""
476
+ })
477
+ }
478
+
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
+ }
573
+
574
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
575
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
576
+ "chart-1",
577
+ "chart-2",
578
+ "chart-3",
579
+ "chart-4",
580
+ "chart-5",
581
+ ]
582
+
583
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
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
+
593
+ /**
594
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
595
+ * light/dark on its own), anything else passes through unchanged.
596
+ */
597
+ function chartColorToCss(color: ChartColor): string {
598
+ const value = color.trim()
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
616
+ }
617
+
618
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
619
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
620
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
621
+ return palette[i % palette.length]!
622
+ }
623
+
624
+ /** `colors` extended (by cycling) to exactly `count` entries. */
625
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
626
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
627
+ }
628
+
629
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
630
+ function tintCss(cssColor: string, percent: number): string {
631
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
632
+ }
633
+
634
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
635
+
636
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
637
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
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
+
748
+ /**
749
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
750
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
751
+ */
752
+ function toChartNumber(value: unknown): number | null {
753
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
754
+ if (typeof value === "bigint") return Number(value)
755
+ if (typeof value === "string" && value.trim() !== "") {
756
+ const n = Number(value)
757
+ return Number.isFinite(n) ? n : null
758
+ }
759
+ return null
760
+ }
761
+
762
+ /** Clamp `value` into `[min, max]`. */
763
+ function clamp(value: number, min: number, max: number): number {
764
+ return Math.min(max, Math.max(min, value))
765
+ }
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
+
998
+ /* ---------------------------------------------------------------- BarList */
999
+
1000
+ type BarListSortOrder = "ascending" | "descending" | "none"
1001
+
1002
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
1003
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
1004
+ const rows = [...data]
1005
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
1006
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
1007
+ return rows
1008
+ }
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
+
1082
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
1083
+ function barListWidths(values: readonly number[]): number[] {
1084
+ const max = Math.max(0, ...values)
1085
+ if (max === 0) return values.map(() => 0)
1086
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
1087
+ }
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
+
1185
+ /* ------------------------------------------------------------ CategoryBar */
1186
+
1187
+ interface CategoryBarSegment {
1188
+ /** Width in percent of the whole bar. */
1189
+ width: number
1190
+ /** Where the segment starts, in percent. */
1191
+ start: number
1192
+ /** The running total at the segment's end — what its right-hand label shows. */
1193
+ end: number
1194
+ }
1195
+
1196
+ /** Lay the values side by side; negative values count as zero. */
1197
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
1198
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
1199
+ const total = clean.reduce((sum, v) => sum + v, 0)
1200
+ let running = 0
1201
+ return clean.map((v) => {
1202
+ const start = total === 0 ? 0 : (running / total) * 100
1203
+ running += v
1204
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
1205
+ })
1206
+ }
1207
+
1208
+ interface CategoryBarLabel {
1209
+ /** Position in percent of the bar. */
1210
+ position: number
1211
+ /** The running total printed there. */
1212
+ value: number
1213
+ }
1214
+
1215
+ /**
1216
+ * Tick labels under the bar: `0` at the start, then the running total at each
1217
+ * segment's end. A label closer than `minGap` percent to the one before is
1218
+ * dropped so narrow segments don't print on top of each other — except the
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.
1222
+ */
1223
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
1224
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
1225
+ if (segments.length === 0) return []
1226
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
1227
+ segments.forEach((s, i) => {
1228
+ const label = { position: s.start + s.width, value: s.end }
1229
+ const prev = labels[labels.length - 1]!
1230
+ if (label.position - prev.position >= minGap) labels.push(label)
1231
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
1232
+ })
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)
1273
+ }
1274
+
1275
+ /** Marker position in percent of the bar, clamped to its ends. */
1276
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
1277
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1278
+ if (total === 0) return 0
1279
+ return clamp((value / total) * 100, 0, 100)
1280
+ }
1281
+
1282
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
1283
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
1284
+ const segments = categoryBarSegments(values)
1285
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
1286
+ if (index !== -1) return index
1287
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
1288
+ return 0
1289
+ }
1290
+
1291
+ /* --------------------------------------------------------- ProgressCircle */
1292
+
1293
+ interface ProgressCircleGeometry {
1294
+ /** SVG width/height. */
1295
+ size: number
1296
+ /** Radius of the stroke's centre line. */
1297
+ normalizedRadius: number
1298
+ circumference: number
1299
+ /** `stroke-dashoffset` for the value arc. */
1300
+ offset: number
1301
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
1302
+ ratio: number
1303
+ }
1304
+
1305
+ function progressCircleGeometry(
1306
+ value: number,
1307
+ max: number,
1308
+ radius: number,
1309
+ strokeWidth: number,
1310
+ ): ProgressCircleGeometry {
1311
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
1312
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
1313
+ const circumference = 2 * Math.PI * normalizedRadius
1314
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
1315
+ }
1316
+
1317
+ /* ---------------------------------------------------------------- summary */
1318
+
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
+ /* ---------- end of inlined code ---------- */
1396
+
1397
+ /** The shape the loading skeleton takes, matching the chart it stands in for. */
1398
+ export type ChartSkeletonVariant = "line" | "area" | "bar" | "donut" | "list"
1399
+
1400
+ /** The plot height of every typed chart unless `height` says otherwise (px). */
1401
+ export const DEFAULT_CHART_HEIGHT = 288
1402
+
1403
+ const TEXT = {
1404
+ ja: { emptyTitle: "表示できるデータがありません", loading: "読み込み中" },
1405
+ en: { emptyTitle: "No data to display", loading: "Loading" },
1406
+ }
1407
+
1408
+ export interface ChartFrameProps extends Omit<HTMLAttributes<HTMLElement>, "title" | "children"> {
1409
+ /** グラフの見出し。プロット領域の `aria-labelledby` になる。 */
1410
+ title?: string
1411
+ /** 1 文の要約。見出しの下に出し、プロット領域の `aria-describedby` になる。 */
1412
+ summary?: string
1413
+ /** 読み込み中。`variant` の形のスケルトンを同じ高さで出す。 */
1414
+ isLoading?: boolean
1415
+ /** データが無い。高さを保ったまま `emptyState` を出す。 */
1416
+ isEmpty?: boolean
1417
+ emptyState?: ChartEmptyState
1418
+ /** プロット領域の高さ。数値は px。既定 288。 */
1419
+ height?: number | string
1420
+ /** スケルトンの形。既定 `"line"`。 */
1421
+ variant?: ChartSkeletonVariant
1422
+ /** 見出しが無いときのプロット領域のラベル。 */
1423
+ ariaLabel?: string
1424
+ /**
1425
+ * プロット領域の役割。既定 `"img"`(canvas のグラフ)。行がボタンやリンクになる
1426
+ * HTML のグラフ(BarList・FunnelSteps)は `"group"` にして、中身を読ませる。
1427
+ */
1428
+ plotRole?: "img" | "group"
1429
+ /** 値の表。画面には出さず(`sr-only`)、スクリーンリーダー向けに図の中に置く。`chartDataTable` で作る。 */
1430
+ dataTable?: ChartDataTable
1431
+ /** プロット(チャート本体)。読み込み中・空のときは描かない。 */
1432
+ children?: ReactNode
1433
+ }
1434
+
1435
+ /**
1436
+ * The frame. `ref` points at the plot area (the element with the fixed height),
1437
+ * `className` / other attributes go to the outer `<figure>`.
1438
+ */
1439
+ export const ChartFrame = forwardRef<HTMLDivElement, ChartFrameProps>(function ChartFrame(
1440
+ {
1441
+ title,
1442
+ summary,
1443
+ isLoading = false,
1444
+ isEmpty = false,
1445
+ emptyState,
1446
+ height = DEFAULT_CHART_HEIGHT,
1447
+ variant = "line",
1448
+ ariaLabel,
1449
+ plotRole = "img",
1450
+ dataTable,
1451
+ className,
1452
+ children,
1453
+ ...props
1454
+ },
1455
+ ref,
1456
+ ) {
1457
+ const id = useId()
1458
+ const t = TEXT[uiLanguage(useLocale())]
1459
+ const titleId = title ? `${id}-title` : undefined
1460
+ const summaryId = summary ? `${id}-summary` : undefined
1461
+ const state = isLoading ? "loading" : isEmpty ? "empty" : "ready"
1462
+
1463
+ return (
1464
+ <figure data-slot="chart-frame" className={cn("m-0 flex w-full min-w-0 flex-col gap-3", className)} {...props}>
1465
+ {(title || summary) && (
1466
+ <figcaption data-slot="chart-frame-header" className="flex flex-col gap-1">
1467
+ {title && (
1468
+ <h3 id={titleId} data-slot="chart-frame-title" className="text-sm leading-snug font-semibold">
1469
+ {title}
1470
+ </h3>
1471
+ )}
1472
+ {summary && (
1473
+ <p id={summaryId} data-slot="chart-frame-summary" className="text-sm leading-relaxed text-muted-foreground">
1474
+ {summary}
1475
+ </p>
1476
+ )}
1477
+ </figcaption>
1478
+ )}
1479
+ <div
1480
+ ref={ref}
1481
+ data-slot="chart-frame-body"
1482
+ data-state={state}
1483
+ role={state === "ready" ? plotRole : "group"}
1484
+ aria-label={titleId ? undefined : ariaLabel}
1485
+ aria-labelledby={titleId}
1486
+ aria-describedby={summaryId}
1487
+ aria-busy={isLoading || undefined}
1488
+ className="relative w-full min-w-0"
1489
+ style={{ height: typeof height === "number" ? `${height}px` : height }}
1490
+ >
1491
+ {state === "loading" ? (
1492
+ <ChartSkeleton variant={variant} loadingText={t.loading} />
1493
+ ) : state === "empty" ? (
1494
+ <ChartEmpty {...emptyState} defaultTitle={t.emptyTitle} />
1495
+ ) : (
1496
+ <ChartFrameContext.Provider value>{children}</ChartFrameContext.Provider>
1497
+ )}
1498
+ </div>
1499
+ {state === "ready" && dataTable && dataTable.rows.length > 0 && (
1500
+ <ChartDataTableView table={dataTable} fallbackCaption={title ?? ariaLabel} />
1501
+ )}
1502
+ </figure>
1503
+ )
1504
+ })
1505
+ ChartFrame.displayName = "ChartFrame"
1506
+
1507
+ /* ---------------------------------------------------------------- skeleton */
1508
+
1509
+ const BAR_HEIGHTS = [58, 74, 46, 88, 64, 80, 52]
1510
+ const LIST_WIDTHS = [92, 76, 64, 48, 36]
1511
+ const LINE_POINTS = "0,70 16,58 33,62 50,40 66,46 83,28 100,34"
1512
+
1513
+ function ChartSkeleton({ variant, loadingText }: { variant: ChartSkeletonVariant; loadingText: string }) {
1514
+ const pulse = "animate-pulse motion-reduce:animate-none"
1515
+ return (
1516
+ <div data-slot="chart-skeleton" data-variant={variant} className="absolute inset-0 flex flex-col gap-3">
1517
+ <div aria-hidden="true" className="contents">
1518
+ {variant === "list" ? (
1519
+ <div className={cn("flex flex-1 flex-col justify-around", pulse)}>
1520
+ {LIST_WIDTHS.map((w) => (
1521
+ <div key={w} className="flex items-center gap-3">
1522
+ <div className="h-5 rounded-sm bg-muted" style={{ width: `${w}%` }} />
1523
+ </div>
1524
+ ))}
1525
+ </div>
1526
+ ) : variant === "donut" ? (
1527
+ <div className={cn("flex flex-1 items-center justify-center", pulse)}>
1528
+ <svg viewBox="0 0 100 100" className="h-full max-h-full w-auto text-muted">
1529
+ <circle cx="50" cy="50" r="40" fill="none" stroke="currentColor" strokeWidth="14" />
1530
+ </svg>
1531
+ </div>
1532
+ ) : variant === "bar" ? (
1533
+ <div className={cn("flex flex-1 items-end gap-3 px-1", pulse)}>
1534
+ {BAR_HEIGHTS.map((h, i) => (
1535
+ <div key={i} className="flex-1 rounded-t-sm bg-muted" style={{ height: `${h}%` }} />
1536
+ ))}
1537
+ </div>
1538
+ ) : (
1539
+ // A soft muted silhouette only — no stroke, no baseline, nothing that reads as a data line.
1540
+ <div className={cn("relative flex-1", pulse)}>
1541
+ <svg viewBox="0 0 100 100" preserveAspectRatio="none" className="absolute inset-0 h-full w-full text-muted">
1542
+ <polygon points={`${LINE_POINTS} 100,100 0,100`} fill="currentColor" opacity={variant === "area" ? 0.8 : 0.5} />
1543
+ </svg>
1544
+ </div>
1545
+ )}
1546
+ </div>
1547
+ <span className="sr-only">{loadingText}</span>
1548
+ </div>
1549
+ )
1550
+ }
1551
+
1552
+ /* --------------------------------------------------------------- data table */
1553
+
1554
+ function ChartDataTableView({ table, fallbackCaption }: { table: ChartDataTable; fallbackCaption?: string }) {
1555
+ const caption = table.caption ?? fallbackCaption
1556
+ // The wrapper is the visually-hidden box: `sr-only` on the <table> itself still
1557
+ // lets table auto-layout give it a real width, which overflows narrow pages.
1558
+ return (
1559
+ <div data-slot="chart-frame-table-wrapper" className="sr-only">
1560
+ <table data-slot="chart-frame-table">
1561
+ {caption && <caption>{caption}</caption>}
1562
+ <thead>
1563
+ <tr>
1564
+ {table.columns.map((column, i) => (
1565
+ <th key={i} scope="col">
1566
+ {column}
1567
+ </th>
1568
+ ))}
1569
+ </tr>
1570
+ </thead>
1571
+ <tbody>
1572
+ {table.rows.map((row, r) => (
1573
+ <tr key={r}>
1574
+ {row.map((cell, c) =>
1575
+ c === 0 ? (
1576
+ <th key={c} scope="row">
1577
+ {cell}
1578
+ </th>
1579
+ ) : (
1580
+ <td key={c}>{cell}</td>
1581
+ ),
1582
+ )}
1583
+ </tr>
1584
+ ))}
1585
+ </tbody>
1586
+ </table>
1587
+ </div>
1588
+ )
1589
+ }
1590
+
1591
+ /* ------------------------------------------------------------------- empty */
1592
+
1593
+ function ChartEmpty({ title, description, action, defaultTitle }: ChartEmptyState & { defaultTitle: string }) {
1594
+ return (
1595
+ <div
1596
+ data-slot="chart-empty"
1597
+ className="absolute inset-0 flex flex-col items-center justify-center gap-1 rounded-md border border-dashed border-border p-6 text-center"
1598
+ >
1599
+ <p className="text-sm font-medium text-balance">{title ?? defaultTitle}</p>
1600
+ {description && <p className="max-w-prose text-sm text-balance text-muted-foreground">{description}</p>}
1601
+ {action && <div className="mt-3">{action}</div>}
1602
+ </div>
1603
+ )
1604
+ }