@squadbase/vantage 0.6.2 → 0.7.0-dev1.3b0e616

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 (355) 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-QDZA5JSL.js → chunk-AABMKHEU.js} +4 -4
  12. package/dist/{chunk-QDZA5JSL.js.map → chunk-AABMKHEU.js.map} +1 -1
  13. package/dist/{chunk-PVTHHV7X.js → chunk-ANZLVSEP.js} +28 -7
  14. package/dist/chunk-ANZLVSEP.js.map +1 -0
  15. package/dist/chunk-CKWPK4RO.js +50 -0
  16. package/dist/chunk-CKWPK4RO.js.map +1 -0
  17. package/dist/chunk-EG4PX726.js +678 -0
  18. package/dist/chunk-EG4PX726.js.map +1 -0
  19. package/dist/{chunk-3G43C6OL.js → chunk-GNXCX4WE.js} +46 -3
  20. package/dist/chunk-GNXCX4WE.js.map +1 -0
  21. package/dist/chunk-NYQJ5UY4.js +9028 -0
  22. package/dist/chunk-NYQJ5UY4.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 +2113 -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/geo-japan-7BMSOJRX.js +8 -0
  64. package/dist/geo-japan-7BMSOJRX.js.map +1 -0
  65. package/dist/geo-us-GVOG7VXH.js +8 -0
  66. package/dist/geo-us-GVOG7VXH.js.map +1 -0
  67. package/dist/geo-world-35HL56UU.js +8 -0
  68. package/dist/geo-world-35HL56UU.js.map +1 -0
  69. package/dist/markdown/index.js +1 -1
  70. package/dist/markdown/index.js.map +1 -1
  71. package/dist/{preview-QDCIVVSR.js → preview-T6CLSQVX.js} +12 -4
  72. package/dist/preview-T6CLSQVX.js.map +1 -0
  73. package/dist/query/index.d.ts +0 -11
  74. package/dist/query/index.js +2 -2
  75. package/dist/{routes-RHP5FVGD.js → routes-PVKNT777.js} +6 -6
  76. package/dist/{routes-RHP5FVGD.js.map → routes-PVKNT777.js.map} +1 -1
  77. package/dist/{search-RFBELGY7.js → search-5LC4XPB5.js} +3 -3
  78. package/dist/{search-RFBELGY7.js.map → search-5LC4XPB5.js.map} +1 -1
  79. package/dist/slide/index.d.ts +272 -1
  80. package/dist/slide/index.js +1086 -19
  81. package/dist/slide/index.js.map +1 -1
  82. package/dist/table/index.js +14 -10
  83. package/dist/table/index.js.map +1 -1
  84. package/dist/ui/index.d.ts +148 -12
  85. package/dist/ui/index.js +1340 -88
  86. package/dist/ui/index.js.map +1 -1
  87. package/dist/{upgrade-GF2P67M6.js → upgrade-6DT7ADRP.js} +7 -7
  88. package/dist/{upgrade-GF2P67M6.js.map → upgrade-6DT7ADRP.js.map} +1 -1
  89. package/dist/vite/index.d.ts +10 -0
  90. package/dist/vite/index.js +4 -4
  91. package/docs/en/agent-skills.md +1 -1
  92. package/docs/en/changelog.md +82 -0
  93. package/docs/en/cli-reference.md +30 -0
  94. package/docs/en/components.md +42 -17
  95. package/docs/en/doc/delta-text.md +40 -0
  96. package/docs/en/doc/doc-action-items.md +49 -0
  97. package/docs/en/doc/doc-callout.md +38 -0
  98. package/docs/en/doc/doc-data-table.md +60 -0
  99. package/docs/en/doc/doc-executive-summary.md +64 -0
  100. package/docs/en/doc/doc-figure.md +56 -0
  101. package/docs/en/doc/doc-key-findings.md +61 -0
  102. package/docs/en/doc/doc-kpi-scorecard.md +80 -0
  103. package/docs/en/doc/doc-notes-and-sources.md +43 -0
  104. package/docs/en/doc/doc-report-header.md +46 -0
  105. package/docs/en/pages-and-metadata.md +15 -0
  106. package/docs/en/parts/area-chart.md +99 -0
  107. package/docs/en/parts/bar-chart.md +91 -0
  108. package/docs/en/parts/bar-list.md +50 -0
  109. package/docs/en/parts/category-bar.md +37 -0
  110. package/docs/en/parts/chart-frame.md +39 -0
  111. package/docs/en/parts/data-table.md +22 -0
  112. package/docs/en/parts/delta.md +51 -0
  113. package/docs/en/parts/donut-chart.md +72 -0
  114. package/docs/en/parts/format.md +43 -0
  115. package/docs/en/parts/funnel-steps.md +2 -1
  116. package/docs/en/parts/heatmap.md +53 -0
  117. package/docs/en/parts/kpi-card.md +58 -0
  118. package/docs/en/parts/legend.md +35 -0
  119. package/docs/en/parts/line-chart.md +94 -0
  120. package/docs/en/parts/metric-value.md +3 -2
  121. package/docs/en/parts/page-shell.md +1 -1
  122. package/docs/en/parts/progress-circle.md +33 -0
  123. package/docs/en/parts/sample-data.md +39 -0
  124. package/docs/en/parts/scatter-chart.md +56 -0
  125. package/docs/en/parts/sparkline.md +1 -1
  126. package/docs/en/parts/tracker.md +36 -0
  127. package/docs/en/parts/trend-indicator.md +17 -1
  128. package/docs/en/parts/updated-at.md +30 -0
  129. package/docs/en/parts/waterfall-chart.md +56 -0
  130. package/docs/en/slide/slide-chart-full.md +48 -0
  131. package/docs/en/slide/slide-chart-insight.md +52 -0
  132. package/docs/en/slide/slide-columns.md +46 -0
  133. package/docs/en/slide/slide-comparison.md +68 -0
  134. package/docs/en/slide/slide-cover.md +39 -0
  135. package/docs/en/slide/slide-exec-summary.md +47 -0
  136. package/docs/en/slide/slide-heading.md +38 -0
  137. package/docs/en/slide/slide-kpi-grid.md +55 -0
  138. package/docs/en/slide/slide-kpi-hero.md +58 -0
  139. package/docs/en/slide/slide-next-actions.md +49 -0
  140. package/docs/en/slide/slide-scorecard-table.md +54 -0
  141. package/docs/en/slide/slide-section.md +44 -0
  142. package/docs/en/slide/slide-source-line.md +34 -0
  143. package/docs/en/ui/alert-dialog.md +42 -0
  144. package/docs/en/ui/avatar.md +31 -0
  145. package/docs/en/ui/combobox.md +74 -0
  146. package/docs/en/ui/drawer.md +41 -0
  147. package/docs/en/ui/empty.md +1 -1
  148. package/docs/en/ui/error-state.md +4 -3
  149. package/docs/en/ui/field.md +42 -0
  150. package/docs/en/ui/hover-card.md +21 -0
  151. package/docs/en/ui/kbd.md +17 -0
  152. package/docs/en/ui/loading.md +1 -1
  153. package/docs/en/ui/pagination.md +36 -0
  154. package/docs/en/ui/radio-group.md +21 -0
  155. package/docs/en/ui/toast.md +44 -0
  156. package/docs/en/ui/toggle-group.md +4 -3
  157. package/docs/en/ui-and-theming.md +1 -1
  158. package/docs/index.json +1184 -114
  159. package/docs/ja/agent-skills.md +1 -1
  160. package/docs/ja/changelog.md +84 -0
  161. package/docs/ja/cli-reference.md +29 -0
  162. package/docs/ja/components.md +68 -101
  163. package/docs/ja/doc/delta-text.md +40 -0
  164. package/docs/ja/doc/doc-action-items.md +49 -0
  165. package/docs/ja/doc/doc-callout.md +38 -0
  166. package/docs/ja/doc/doc-data-table.md +60 -0
  167. package/docs/ja/doc/doc-executive-summary.md +64 -0
  168. package/docs/ja/doc/doc-figure.md +56 -0
  169. package/docs/ja/doc/doc-key-findings.md +61 -0
  170. package/docs/ja/doc/doc-kpi-scorecard.md +80 -0
  171. package/docs/ja/doc/doc-notes-and-sources.md +43 -0
  172. package/docs/ja/doc/doc-report-header.md +46 -0
  173. package/docs/ja/page-types/csv.md +83 -0
  174. package/docs/ja/page-types/doc.md +83 -0
  175. package/docs/ja/page-types/excel.md +82 -0
  176. package/docs/ja/page-types/slide.md +133 -0
  177. package/docs/ja/page-types.md +47 -0
  178. package/docs/ja/pages-and-metadata.md +15 -0
  179. package/docs/ja/parts/area-chart.md +85 -0
  180. package/docs/ja/parts/bar-chart.md +95 -0
  181. package/docs/ja/parts/bar-list.md +58 -0
  182. package/docs/ja/parts/category-bar.md +36 -0
  183. package/docs/ja/parts/chart-frame.md +36 -0
  184. package/docs/ja/parts/data-table.md +22 -0
  185. package/docs/ja/parts/delta.md +51 -0
  186. package/docs/ja/parts/donut-chart.md +66 -0
  187. package/docs/ja/parts/echart.md +3 -0
  188. package/docs/ja/parts/format.md +44 -0
  189. package/docs/ja/parts/funnel-steps.md +27 -8
  190. package/docs/ja/parts/heatmap.md +45 -0
  191. package/docs/ja/parts/kpi-card.md +56 -0
  192. package/docs/ja/parts/legend.md +36 -0
  193. package/docs/ja/parts/line-chart.md +84 -0
  194. package/docs/ja/parts/metric-value.md +3 -2
  195. package/docs/ja/parts/page-shell.md +1 -1
  196. package/docs/ja/parts/progress-circle.md +34 -0
  197. package/docs/ja/parts/sample-data.md +61 -0
  198. package/docs/ja/parts/scatter-chart.md +69 -0
  199. package/docs/ja/parts/sparkline.md +2 -2
  200. package/docs/ja/parts/tracker.md +32 -0
  201. package/docs/ja/parts/trend-indicator.md +17 -1
  202. package/docs/ja/parts/updated-at.md +27 -0
  203. package/docs/ja/parts/waterfall-chart.md +61 -0
  204. package/docs/ja/routing.md +8 -86
  205. package/docs/ja/slide/slide-chart-full.md +48 -0
  206. package/docs/ja/slide/slide-chart-insight.md +52 -0
  207. package/docs/ja/slide/slide-columns.md +46 -0
  208. package/docs/ja/slide/slide-comparison.md +68 -0
  209. package/docs/ja/slide/slide-cover.md +39 -0
  210. package/docs/ja/slide/slide-exec-summary.md +47 -0
  211. package/docs/ja/slide/slide-heading.md +38 -0
  212. package/docs/ja/slide/slide-kpi-grid.md +55 -0
  213. package/docs/ja/slide/slide-kpi-hero.md +58 -0
  214. package/docs/ja/slide/slide-next-actions.md +49 -0
  215. package/docs/ja/slide/slide-scorecard-table.md +54 -0
  216. package/docs/ja/slide/slide-section.md +44 -0
  217. package/docs/ja/slide/slide-source-line.md +34 -0
  218. package/docs/ja/ui/alert-dialog.md +41 -0
  219. package/docs/ja/ui/avatar.md +31 -0
  220. package/docs/ja/ui/combobox.md +74 -0
  221. package/docs/ja/ui/drawer.md +41 -0
  222. package/docs/ja/ui/empty.md +1 -1
  223. package/docs/ja/ui/error-state.md +4 -3
  224. package/docs/ja/ui/field.md +42 -0
  225. package/docs/ja/ui/hover-card.md +21 -0
  226. package/docs/ja/ui/kbd.md +16 -0
  227. package/docs/ja/ui/loading.md +1 -1
  228. package/docs/ja/ui/pagination.md +36 -0
  229. package/docs/ja/ui/radio-group.md +21 -0
  230. package/docs/ja/ui/toast.md +46 -0
  231. package/docs/ja/ui/toggle-group.md +4 -3
  232. package/docs/ja/ui-and-theming.md +14 -7
  233. package/package.json +43 -29
  234. package/registry/ui/accordion.tsx +76 -0
  235. package/registry/ui/alert-dialog.tsx +189 -0
  236. package/registry/ui/alert.tsx +80 -0
  237. package/registry/ui/app-shell.tsx +424 -0
  238. package/registry/ui/area-chart.tsx +3960 -0
  239. package/registry/ui/attention-list.tsx +465 -0
  240. package/registry/ui/avatar.tsx +110 -0
  241. package/registry/ui/badge.tsx +56 -0
  242. package/registry/ui/bar-chart.tsx +3954 -0
  243. package/registry/ui/bar-list.tsx +3998 -0
  244. package/registry/ui/box-plot-chart.tsx +4214 -0
  245. package/registry/ui/breadcrumb.tsx +128 -0
  246. package/registry/ui/button.tsx +62 -0
  247. package/registry/ui/calendar.tsx +223 -0
  248. package/registry/ui/card.tsx +107 -0
  249. package/registry/ui/category-bar.tsx +1498 -0
  250. package/registry/ui/chart-frame.tsx +1604 -0
  251. package/registry/ui/checkbox.tsx +30 -0
  252. package/registry/ui/collapsible.tsx +23 -0
  253. package/registry/ui/combo-chart.tsx +1851 -0
  254. package/registry/ui/combobox.tsx +310 -0
  255. package/registry/ui/command.tsx +198 -0
  256. package/registry/ui/dashboard-card.tsx +217 -0
  257. package/registry/ui/data-table.tsx +896 -157
  258. package/registry/ui/date-range-picker.tsx +544 -0
  259. package/registry/ui/delta.tsx +350 -0
  260. package/registry/ui/dialog.tsx +161 -0
  261. package/registry/ui/donut-chart.tsx +4006 -0
  262. package/registry/ui/drawer.tsx +229 -0
  263. package/registry/ui/dropdown-menu.tsx +274 -0
  264. package/registry/ui/echart.tsx +1178 -0
  265. package/registry/ui/field.tsx +240 -0
  266. package/registry/ui/filter-bar.tsx +551 -0
  267. package/registry/ui/funnel-steps.tsx +3843 -0
  268. package/registry/ui/heatmap.tsx +2027 -0
  269. package/registry/ui/histogram-chart.tsx +4284 -0
  270. package/registry/ui/hover-card.tsx +52 -0
  271. package/registry/ui/input-group.tsx +160 -0
  272. package/registry/ui/input.tsx +24 -0
  273. package/registry/ui/kbd.tsx +30 -0
  274. package/registry/ui/kpi-card.tsx +905 -0
  275. package/registry/ui/label.tsx +22 -0
  276. package/registry/ui/legend.tsx +3817 -0
  277. package/registry/ui/line-chart.tsx +3958 -0
  278. package/registry/ui/metric-value.tsx +62 -0
  279. package/registry/ui/multi-select.tsx +382 -0
  280. package/registry/ui/page-shell.tsx +420 -0
  281. package/registry/ui/pagination.tsx +140 -0
  282. package/registry/ui/paired-chart.tsx +4086 -0
  283. package/registry/ui/pivot-table.tsx +1259 -0
  284. package/registry/ui/placeholder.tsx +36 -0
  285. package/registry/ui/popover.tsx +92 -0
  286. package/registry/ui/progress-circle.tsx +1033 -0
  287. package/registry/ui/progress.tsx +85 -0
  288. package/registry/ui/radio-group.tsx +39 -0
  289. package/registry/ui/sample-data.tsx +230 -0
  290. package/registry/ui/scatter-chart.tsx +4503 -0
  291. package/registry/ui/scroll-area.tsx +56 -0
  292. package/registry/ui/searchable-select.tsx +352 -0
  293. package/registry/ui/section-header.tsx +43 -0
  294. package/registry/ui/segmented-control.tsx +76 -0
  295. package/registry/ui/select.tsx +255 -0
  296. package/registry/ui/separator.tsx +27 -0
  297. package/registry/ui/sheet.tsx +139 -0
  298. package/registry/ui/sidebar.tsx +725 -0
  299. package/registry/ui/skeleton.tsx +17 -0
  300. package/registry/ui/slider.tsx +56 -0
  301. package/registry/ui/sparkline.tsx +230 -0
  302. package/registry/ui/spinner.tsx +14 -0
  303. package/registry/ui/states.tsx +247 -0
  304. package/registry/ui/status-badge.tsx +286 -0
  305. package/registry/ui/switch.tsx +34 -0
  306. package/registry/ui/table.tsx +118 -0
  307. package/registry/ui/tabs.tsx +84 -0
  308. package/registry/ui/textarea.tsx +22 -0
  309. package/registry/ui/toast.tsx +250 -0
  310. package/registry/ui/toggle-group.tsx +91 -0
  311. package/registry/ui/toggle.tsx +47 -0
  312. package/registry/ui/tooltip.tsx +72 -0
  313. package/registry/ui/tracker.tsx +1015 -0
  314. package/registry/ui/treemap.tsx +1916 -0
  315. package/registry/ui/trend-indicator.tsx +217 -0
  316. package/registry/ui/updated-at.tsx +276 -0
  317. package/registry/ui/waterfall-chart.tsx +4561 -0
  318. package/skills/vantage-add-feature/SKILL.md +14 -7
  319. package/skills/vantage-design/SKILL.md +62 -52
  320. package/skills/vantage-design/references/extract.md +26 -27
  321. package/skills/vantage-design/references/format.md +12 -172
  322. package/skills/vantage-design/references/presets.md +50 -110
  323. package/skills/vantage-pitfalls/SKILL.md +10 -1
  324. package/skills/vantage-slide/SKILL.md +71 -36
  325. package/templates/AGENTS.md +54 -16
  326. package/templates/agents/api.md +36 -0
  327. package/templates/agents/csv.md +2 -1
  328. package/templates/agents/doc.md +52 -3
  329. package/templates/agents/page.md +91 -10
  330. package/templates/agents/slide.md +90 -4
  331. package/templates/agents/xlsx.md +2 -1
  332. package/theme.css +247 -132
  333. package/dist/add-EISGSZAH.js +0 -6
  334. package/dist/add-EISGSZAH.js.map +0 -1
  335. package/dist/chunk-3G43C6OL.js.map +0 -1
  336. package/dist/chunk-5ZOP4SQR.js +0 -47
  337. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  338. package/dist/chunk-A2UUGASH.js.map +0 -1
  339. package/dist/chunk-BCE22JSM.js.map +0 -1
  340. package/dist/chunk-DTDVSFRY.js +0 -29
  341. package/dist/chunk-DTDVSFRY.js.map +0 -1
  342. package/dist/chunk-EP6JHXSR.js.map +0 -1
  343. package/dist/chunk-JGRMRXXZ.js.map +0 -1
  344. package/dist/chunk-KLEIVDUV.js +0 -165
  345. package/dist/chunk-KLEIVDUV.js.map +0 -1
  346. package/dist/chunk-LSRMRIXA.js +0 -2227
  347. package/dist/chunk-LSRMRIXA.js.map +0 -1
  348. package/dist/chunk-PVTHHV7X.js.map +0 -1
  349. package/dist/chunk-PXRX5PEC.js.map +0 -1
  350. package/dist/chunk-RPZAALCX.js.map +0 -1
  351. package/dist/chunk-T3FLAGI6.js +0 -316
  352. package/dist/chunk-T3FLAGI6.js.map +0 -1
  353. package/dist/dev-NZRLOQCL.js.map +0 -1
  354. package/dist/doctor-VFKEMR54.js.map +0 -1
  355. package/dist/preview-QDCIVVSR.js.map +0 -1
@@ -0,0 +1,1259 @@
1
+ // Copied by `vantage add ui pivot-table`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/components/pivot-table.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * PivotTable — a crosstab of already-aggregated rows: row dimensions down the side (nested, with merged header
7
+ * cells), column dimensions across the top, and one or more measures in the cells (several measures become
8
+ * sub-columns). The part does not aggregate: it only places each row in its cell, and when two rows land in the
9
+ * same cell the later one wins.
10
+ *
11
+ * `highlight` shades the cells by value on a single-hue ramp (Tableau's highlight table): `true` shades every
12
+ * measure (each on its own range), a measure name shades that one only. Numbers are right-aligned in `tabular-nums`,
13
+ * a missing value reads「—」. The header stays visible while the table scrolls inside its box; a wide table scrolls
14
+ * sideways inside the card. Clicking a cell calls `onSelect` with its row.
15
+ */
16
+ import { useMemo, type CSSProperties } from "react"
17
+
18
+ import { ChartFrame } from "@squadbase/vantage/components"
19
+ import { TableBody, TableCell, TableHead, TableHeader, TableRow } from "@squadbase/vantage/ui"
20
+ import { cn } from "@squadbase/vantage/ui"
21
+ import { EMPTY_VALUE, formatValue, type ValueFormat } from "@squadbase/vantage/components"
22
+ import type { ChartEmptyState, ChartSeriesColor } from "@squadbase/vantage/components"
23
+ import { useSyncExternalStore } from "react"
24
+ import { toValueFormatter } from "@squadbase/vantage/components"
25
+ import type { ChartColor, ChartColors, ChartTone, ValueFormatter } from "@squadbase/vantage/components"
26
+
27
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
28
+
29
+ /**
30
+ * The display language of the parts and the defaults that follow it.
31
+ *
32
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
33
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
34
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
35
+ *
36
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
37
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
38
+ */
39
+
40
+ /** The language of the built-in wording: Japanese or English. */
41
+ type UiLanguage = "ja" | "en"
42
+
43
+ /** The locale used when `<html lang>` gives none (and on the server). */
44
+ const FALLBACK_LOCALE = "en-US"
45
+
46
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
47
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
48
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
49
+ }
50
+
51
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
52
+ function normalizeLocale(tag: string | null | undefined): string {
53
+ const value = tag?.trim()
54
+ if (!value) return FALLBACK_LOCALE
55
+ try {
56
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
57
+ } catch {
58
+ return FALLBACK_LOCALE
59
+ }
60
+ }
61
+
62
+ /**
63
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
64
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
65
+ */
66
+ function documentLocale(): string {
67
+ if (typeof document === "undefined") return FALLBACK_LOCALE
68
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
69
+ }
70
+
71
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
72
+ function resolveLocale(locale?: string | null): string {
73
+ return locale || documentLocale()
74
+ }
75
+
76
+ /** Picks the wording table of the locale's language. */
77
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
78
+ return table[uiLanguage(resolveLocale(locale))]
79
+ }
80
+
81
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
82
+ function defaultCurrency(locale?: string | null): string {
83
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
84
+ }
85
+
86
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
87
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
88
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
89
+ }
90
+
91
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
92
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
93
+
94
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
95
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
96
+
97
+ /**
98
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
99
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
100
+ * Monday for the rest.
101
+ */
102
+ function weekStartsOn(locale?: string | null): WeekDay {
103
+ const tag = normalizeLocale(resolveLocale(locale))
104
+ if (uiLanguage(tag) === "ja") return 1
105
+ try {
106
+ const info = new Intl.Locale(tag) as Intl.Locale & {
107
+ getWeekInfo?: () => { firstDay: number }
108
+ weekInfo?: { firstDay: number }
109
+ }
110
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
111
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
112
+ } catch {
113
+ // Fall through to the table below.
114
+ }
115
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
116
+ }
117
+
118
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
119
+
120
+ const listeners = new Set<() => void>()
121
+ let observer: MutationObserver | null = null
122
+
123
+ /** One observer on `<html lang>` for every subscribed part. */
124
+ function subscribe(onChange: () => void): () => void {
125
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
126
+ listeners.add(onChange)
127
+ if (!observer) {
128
+ observer = new MutationObserver(() => {
129
+ for (const listener of [...listeners]) listener()
130
+ })
131
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
132
+ }
133
+ return () => {
134
+ listeners.delete(onChange)
135
+ if (listeners.size === 0 && observer) {
136
+ observer.disconnect()
137
+ observer = null
138
+ }
139
+ }
140
+ }
141
+
142
+ const serverLocale = () => FALLBACK_LOCALE
143
+
144
+ /**
145
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
146
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
147
+ */
148
+ function useDocumentLocale(): string {
149
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
150
+ }
151
+
152
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
153
+ function useLocale(locale?: string | null): string {
154
+ const page = useDocumentLocale()
155
+ return locale || page
156
+ }
157
+
158
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
159
+
160
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
161
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
162
+
163
+ /**
164
+ * The attributes of a typed chart's leftover props that belong on its root
165
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
166
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
167
+ */
168
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
169
+ const out: Record<string, unknown> = {}
170
+ for (const [key, value] of Object.entries(rest)) {
171
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
172
+ }
173
+ return out
174
+ }
175
+
176
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
177
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
178
+ "chart-1",
179
+ "chart-2",
180
+ "chart-3",
181
+ "chart-4",
182
+ "chart-5",
183
+ ]
184
+
185
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
186
+
187
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
188
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
189
+
190
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
191
+ function isChartTone(color: string): color is ChartTone {
192
+ return (CHART_TONES as readonly string[]).includes(color.trim())
193
+ }
194
+
195
+ /**
196
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
197
+ * light/dark on its own), anything else passes through unchanged.
198
+ */
199
+ function chartColorToCss(color: ChartColor): string {
200
+ const value = color.trim()
201
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
202
+ }
203
+
204
+ /**
205
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
206
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
207
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
208
+ */
209
+ function chartFillToCss(color: ChartColor): string {
210
+ const value = color.trim()
211
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
212
+ }
213
+
214
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
215
+ function chartFillName(color: ChartColor): ChartColor {
216
+ const value = color.trim()
217
+ return isChartTone(value) ? `${value}-fill` : color
218
+ }
219
+
220
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
221
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
222
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
223
+ return palette[i % palette.length]!
224
+ }
225
+
226
+ /** `colors` extended (by cycling) to exactly `count` entries. */
227
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
228
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
229
+ }
230
+
231
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
232
+ function tintCss(cssColor: string, percent: number): string {
233
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
234
+ }
235
+
236
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
237
+
238
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
239
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
240
+
241
+ /**
242
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
243
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
244
+ */
245
+ function resolveValueFormatter(
246
+ valueFormatter: ValueFormatter | undefined,
247
+ format: ValueFormat | undefined,
248
+ locale?: string,
249
+ ): ValueFormatter {
250
+ return valueFormatter ?? toValueFormatter(format, locale)
251
+ }
252
+
253
+ /**
254
+ * The formatter of value-axis ticks and on-plot labels: an explicit
255
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
256
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
257
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
258
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
259
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
260
+ * currency sign and grouping.
261
+ */
262
+ function resolveAxisFormatter(
263
+ valueFormatter: ValueFormatter | undefined,
264
+ format: ValueFormat | undefined,
265
+ localeArg?: string,
266
+ ): ValueFormatter {
267
+ if (valueFormatter) return valueFormatter
268
+ const locale = resolveLocale(localeArg)
269
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
270
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
271
+ const currency = "currency" in spec ? spec.currency : undefined
272
+ const short: ValueFormat =
273
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
274
+ return (value) => formatValue(value, short, locale)
275
+ }
276
+
277
+ interface CompactUnit {
278
+ token: string
279
+ size: number
280
+ }
281
+
282
+ const compactUnitCache = new Map<string, CompactUnit[] | null>()
283
+
284
+ /**
285
+ * The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
286
+ * `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
287
+ * word (`1,5 Mio.`), where a token cannot be swapped in place.
288
+ */
289
+ function compactUnits(locale: string): CompactUnit[] | null {
290
+ const cached = compactUnitCache.get(locale)
291
+ if (cached !== undefined) return cached
292
+ let units: CompactUnit[] | null = []
293
+ try {
294
+ const compact = new Intl.NumberFormat(locale, { notation: "compact" })
295
+ const seen = new Set<string>()
296
+ for (let exp = 3; exp <= 15; exp++) {
297
+ const parts = compact.formatToParts(10 ** exp)
298
+ const at = parts.findIndex((p) => p.type === "compact")
299
+ if (at === -1) continue
300
+ if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
301
+ units = null
302
+ break
303
+ }
304
+ const token = parts[at]!.value
305
+ if (seen.has(token)) continue
306
+ seen.add(token)
307
+ units.push({ token, size: 10 ** exp })
308
+ }
309
+ } catch {
310
+ units = null
311
+ }
312
+ const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
313
+ compactUnitCache.set(locale, sorted)
314
+ return sorted
315
+ }
316
+
317
+ const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
318
+
319
+ /**
320
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
321
+ * that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
322
+ * `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
323
+ * no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
324
+ * unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
325
+ */
326
+ function resolveAxisTickFormatter(
327
+ valueFormatter: ValueFormatter | undefined,
328
+ format: ValueFormat | undefined,
329
+ localeArg?: string,
330
+ ): (top: number) => ValueFormatter {
331
+ const locale = resolveLocale(localeArg)
332
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
333
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
334
+ const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
335
+ if (!units) return () => base
336
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
337
+ const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
338
+ return (top) => {
339
+ const unit = units.find((u) => Math.abs(top) >= u.size)
340
+ if (!unit) return base
341
+ return (value) => {
342
+ const text = base(value)
343
+ if (value === 0 || !Number.isFinite(value)) return text
344
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
345
+ return text.replace(numberToken, () => scaled)
346
+ }
347
+ }
348
+ }
349
+
350
+ /**
351
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
352
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
353
+ */
354
+ function toChartNumber(value: unknown): number | null {
355
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
356
+ if (typeof value === "bigint") return Number(value)
357
+ if (typeof value === "string" && value.trim() !== "") {
358
+ const n = Number(value)
359
+ return Number.isFinite(n) ? n : null
360
+ }
361
+ return null
362
+ }
363
+
364
+ /** Clamp `value` into `[min, max]`. */
365
+ function clamp(value: number, min: number, max: number): number {
366
+ return Math.min(max, Math.max(min, value))
367
+ }
368
+
369
+ /* ------------------------------------------------------------ aggregation */
370
+
371
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
372
+ const MAX_CHART_SERIES = 5
373
+
374
+ /** The series name the folded categories get, by language. */
375
+ const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
376
+
377
+ /** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
378
+ function otherSeriesLabel(locale?: string): string {
379
+ return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
380
+ }
381
+
382
+ const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
383
+
384
+ /** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
385
+ function isOtherName(name: string | null | undefined): boolean {
386
+ return typeof name === "string" && OTHER_NAMES.has(name)
387
+ }
388
+
389
+ interface AggregatedItems<Item extends { name: string; value: number }> {
390
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
391
+ top: Item[]
392
+ /** The items folded into `other`, in their given order. */
393
+ rest: Item[]
394
+ /** The folded remainder, or `null` when nothing was folded. */
395
+ other: { name: string; value: number } | null
396
+ }
397
+
398
+ /**
399
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
400
+ * given order and fold the rest into one `otherLabel` item. Shared by every
401
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
402
+ * BarList rows).
403
+ */
404
+ function aggregateTopN<Item extends { name: string; value: number }>(
405
+ items: readonly Item[],
406
+ n: number = MAX_CHART_SERIES,
407
+ otherLabel: string = otherSeriesLabel(),
408
+ ): AggregatedItems<Item> {
409
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
410
+ const ranked = items
411
+ .map((item, i) => ({ item, i }))
412
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
413
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
414
+ const top = items.filter((_, i) => keep.has(i))
415
+ const rest = items.filter((_, i) => !keep.has(i))
416
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
417
+ }
418
+
419
+ interface AggregatedSeries {
420
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
421
+ data: Record<string, unknown>[]
422
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
423
+ categories: string[]
424
+ /** The folded series' name, or `null`. */
425
+ otherCategory: string | null
426
+ }
427
+
428
+ /**
429
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
430
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
431
+ */
432
+ function aggregateSeries(
433
+ data: readonly Record<string, unknown>[],
434
+ categories: readonly string[],
435
+ n: number = MAX_CHART_SERIES,
436
+ otherLabel: string = otherSeriesLabel(),
437
+ ): AggregatedSeries {
438
+ const totals = categories.map((name) => ({
439
+ name,
440
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
441
+ }))
442
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
443
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
444
+ const folded = rest.map((item) => item.name)
445
+ return {
446
+ data: data.map((row) => {
447
+ let sum: number | null = null
448
+ for (const name of folded) {
449
+ const v = toChartNumber(row[name])
450
+ if (v !== null) sum = (sum ?? 0) + v
451
+ }
452
+ return { ...row, [other.name]: sum }
453
+ }),
454
+ categories: [...top.map((item) => item.name), other.name],
455
+ otherCategory: other.name,
456
+ }
457
+ }
458
+
459
+ /**
460
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
461
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
462
+ */
463
+ function aggregateSeriesKeeping(
464
+ data: readonly Record<string, unknown>[],
465
+ categories: readonly string[],
466
+ keep: string | undefined,
467
+ n: number = MAX_CHART_SERIES,
468
+ otherLabel: string = otherSeriesLabel(),
469
+ ): AggregatedSeries {
470
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
471
+ const aggregated = aggregateSeries(
472
+ data,
473
+ categories.filter((c) => c !== keep),
474
+ n,
475
+ otherLabel,
476
+ )
477
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
478
+ }
479
+
480
+ /**
481
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
482
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
483
+ * so a main series keeps its colour whether or not a comparison is drawn.
484
+ */
485
+ function seriesColorsWithComparison(
486
+ categories: readonly string[],
487
+ colors: ChartColors | undefined,
488
+ otherColor: string,
489
+ otherCategory: string | null,
490
+ allCategories: readonly string[],
491
+ comparison: string | undefined,
492
+ ): string[] {
493
+ if (comparison === undefined || !categories.includes(comparison)) {
494
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
495
+ }
496
+ const main = categories.filter((c) => c !== comparison)
497
+ const mainColors = seriesColorsFor(
498
+ main,
499
+ colors,
500
+ otherColor,
501
+ otherCategory,
502
+ allCategories.filter((c) => c !== comparison),
503
+ )
504
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
505
+ }
506
+
507
+ /**
508
+ * Colour per drawn series: the record's token for that category, else the
509
+ * array's token at the category's position in `allCategories` (cycled), else
510
+ * the token palette by drawn position. `otherCategory` — and a category the
511
+ * data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
512
+ */
513
+ function seriesColorsFor(
514
+ categories: readonly string[],
515
+ colors: ChartColors | undefined,
516
+ otherColor: string,
517
+ otherCategory: string | null = null,
518
+ allCategories: readonly string[] = categories,
519
+ ): string[] {
520
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
521
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
522
+ return categories.map((category, i) => {
523
+ if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
524
+ const fromRecord = record?.[category]
525
+ if (fromRecord) return fromRecord
526
+ if (list && list.length > 0) {
527
+ const at = allCategories.indexOf(category)
528
+ return list[(at === -1 ? i : at) % list.length]!
529
+ }
530
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
531
+ })
532
+ }
533
+
534
+ /* ------------------------------------------------------------------ Donut */
535
+
536
+ /** One drawn donut slice, largest first. */
537
+ interface DonutSlice {
538
+ name: string
539
+ /** Negative and missing values count as 0. */
540
+ value: number
541
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
542
+ color: string
543
+ /** The folded「その他」slice. */
544
+ isOther: boolean
545
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
546
+ row: Record<string, unknown>
547
+ }
548
+
549
+ interface DonutSlicesConfig {
550
+ /** Label column. */
551
+ index: string
552
+ /** Value column. */
553
+ value: string
554
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
555
+ colors?: readonly ChartSeriesColor[]
556
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
557
+ maxSlices?: number
558
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
559
+ otherColor: string
560
+ otherLabel?: string
561
+ }
562
+
563
+ /**
564
+ * Donut slices: sorted by value (largest first, ties keep input order), the
565
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
566
+ * summed into one「その他」slice in `otherColor`.
567
+ */
568
+ function donutSlices(
569
+ data: readonly Record<string, unknown>[],
570
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
571
+ ): DonutSlice[] {
572
+ const items = data
573
+ .map((row, i) => {
574
+ const n = toChartNumber(row[value])
575
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
576
+ })
577
+ .sort((a, b) => b.value - a.value || a.i - b.i)
578
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
579
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
580
+ const slices: DonutSlice[] = top.map((item, rank) => ({
581
+ name: item.name,
582
+ value: item.value,
583
+ // A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
584
+ color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
585
+ isOther: false,
586
+ row: item.row,
587
+ }))
588
+ if (other) {
589
+ slices.push({
590
+ name: other.name,
591
+ value: other.value,
592
+ color: otherColor,
593
+ isOther: true,
594
+ row: { [index]: other.name, [value]: other.value },
595
+ })
596
+ }
597
+ return slices
598
+ }
599
+
600
+ /* ---------------------------------------------------------------- BarList */
601
+
602
+ type BarListSortOrder = "ascending" | "descending" | "none"
603
+
604
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
605
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
606
+ const rows = [...data]
607
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
608
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
609
+ return rows
610
+ }
611
+
612
+ /** BarList-only settings. */
613
+ interface BarListOptions {
614
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
615
+ sortOrder?: BarListSortOrder
616
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
617
+ maxItems?: number
618
+ /** まとめた行のラベル。既定「その他」。 */
619
+ otherLabel?: string
620
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
621
+ exclude?: readonly string[]
622
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
623
+ showShare?: boolean
624
+ }
625
+
626
+ /** One drawn BarList row. */
627
+ interface BarListRow<Row = Record<string, unknown>> {
628
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
629
+ key: string
630
+ name: string
631
+ value: number
632
+ /** Only for real rows; the folded row never links. */
633
+ href?: string
634
+ /** Legacy per-row colour (`BarListItem.color`). */
635
+ color?: ChartColor
636
+ /** The folded「その他」row. */
637
+ isOther: boolean
638
+ /** The input row (`null` for the folded row). */
639
+ row: Row | null
640
+ }
641
+
642
+ interface BarListRowsConfig extends BarListOptions {
643
+ /** Name column. Default `"name"`. */
644
+ index?: string
645
+ /** Value column. Default `"value"`. */
646
+ category?: string
647
+ }
648
+
649
+ /**
650
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
651
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
652
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
653
+ * ranking and are always added to「その他」.
654
+ */
655
+ function barListRows<Row extends object>(
656
+ data: readonly Row[],
657
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
658
+ ): BarListRow<Row>[] {
659
+ const items = data.map((row): BarListRow<Row> => {
660
+ const cells = row as Record<string, unknown>
661
+ const name = String(cells[index] ?? "")
662
+ return {
663
+ key: typeof cells.key === "string" ? cells.key : name,
664
+ name,
665
+ value: toChartNumber(cells[category]) ?? 0,
666
+ href: typeof cells.href === "string" ? cells.href : undefined,
667
+ color: typeof cells.color === "string" ? cells.color : undefined,
668
+ isOther: false,
669
+ row,
670
+ }
671
+ })
672
+ const excluded = new Set(exclude ?? [])
673
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
674
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
675
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
676
+ const rows = sortBarListData(top, sortOrder)
677
+ if (other || outside.length > 0) {
678
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
679
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
680
+ }
681
+ return rows
682
+ }
683
+
684
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
685
+ function barListWidths(values: readonly number[]): number[] {
686
+ const max = Math.max(0, ...values)
687
+ if (max === 0) return values.map(() => 0)
688
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
689
+ }
690
+
691
+ /**
692
+ * How strongly the BarList bars are painted: every row the same tint of the bar
693
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
694
+ * it sits on the card in light and dark; it must stay visible against the card
695
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
696
+ */
697
+ const BAR_LIST_TINT = 45
698
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
699
+ const BAR_LIST_OTHER_TINT = 30
700
+
701
+ /**
702
+ * The fill of each BarList row: all real rows in the same tint of `color`
703
+ * (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
704
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
705
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
706
+ * for that row. A tint, not the solid token, so the label printed over the bar
707
+ * keeps its contrast.
708
+ */
709
+ function barListFills(
710
+ rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
711
+ color: ChartColor,
712
+ otherColor: string,
713
+ ): string[] {
714
+ return rows.map((row) =>
715
+ row.isOther || isOtherName(row.name)
716
+ ? tintCss(otherColor, BAR_LIST_OTHER_TINT)
717
+ : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
718
+ )
719
+ }
720
+
721
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
722
+ function barListShareText(value: number, total: number): string {
723
+ const v = Number.isFinite(value) && value > 0 ? value : 0
724
+ if (total <= 0 || v === 0) return "0%"
725
+ const pct = (v / total) * 100
726
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
727
+ }
728
+
729
+ /**
730
+ * The text at the end of each BarList row: the formatted value and, with
731
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
732
+ * so the shares are of the whole list): `value` and `share` apart (the share is
733
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
734
+ */
735
+ function barListValueTexts(
736
+ values: readonly number[],
737
+ formatter: ValueFormatter,
738
+ showShare = false,
739
+ ): { value: string; share?: string; text: string }[] {
740
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
741
+ return values.map((v) => {
742
+ const value = formatter(v)
743
+ if (!showShare) return { value, text: value }
744
+ const share = barListShareText(v, total)
745
+ return { value, share, text: `${value} · ${share}` }
746
+ })
747
+ }
748
+
749
+ /* -------------------------------------------------------------- DataTable */
750
+
751
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
752
+ interface ChartDataTable {
753
+ /** 表の見出し(`<caption>`)。 */
754
+ caption?: string
755
+ /** 列見出し。先頭がラベル列。 */
756
+ columns: string[]
757
+ /** 行。セルは書式済みの文字列。 */
758
+ rows: string[][]
759
+ }
760
+
761
+ /**
762
+ * The chart's numbers as a table, for screen readers: one row per data row, the
763
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
764
+ * 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).
765
+ */
766
+ function chartDataTable(
767
+ data: readonly Record<string, unknown>[],
768
+ index: string,
769
+ categories: readonly string[],
770
+ formatter: ValueFormatter,
771
+ labels?: Readonly<Record<string, string>>,
772
+ indexName?: string,
773
+ ): ChartDataTable {
774
+ const label = (key: string) => labels?.[key] ?? key
775
+ return {
776
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
777
+ rows: data.map((row) => [
778
+ String(row[index] ?? ""),
779
+ ...categories.map((key) => {
780
+ const n = toChartNumber(row[key])
781
+ return n === null ? EMPTY_VALUE : formatter(n)
782
+ }),
783
+ ]),
784
+ }
785
+ }
786
+
787
+ /* ------------------------------------------------------------ CategoryBar */
788
+
789
+ interface CategoryBarSegment {
790
+ /** Width in percent of the whole bar. */
791
+ width: number
792
+ /** Where the segment starts, in percent. */
793
+ start: number
794
+ /** The running total at the segment's end — what its right-hand label shows. */
795
+ end: number
796
+ }
797
+
798
+ /** Lay the values side by side; negative values count as zero. */
799
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
800
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
801
+ const total = clean.reduce((sum, v) => sum + v, 0)
802
+ let running = 0
803
+ return clean.map((v) => {
804
+ const start = total === 0 ? 0 : (running / total) * 100
805
+ running += v
806
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
807
+ })
808
+ }
809
+
810
+ interface CategoryBarLabel {
811
+ /** Position in percent of the bar. */
812
+ position: number
813
+ /** The running total printed there. */
814
+ value: number
815
+ }
816
+
817
+ /**
818
+ * Tick labels under the bar: `0` at the start, then the running total at each
819
+ * segment's end. A label closer than `minGap` percent to the one before is
820
+ * dropped so narrow segments don't print on top of each other — except the
821
+ * last one (the total), which replaces its neighbour instead. With a
822
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
823
+ * too — the marker sits right under it and the two read as one crowded spot.
824
+ */
825
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
826
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
827
+ if (segments.length === 0) return []
828
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
829
+ segments.forEach((s, i) => {
830
+ const label = { position: s.start + s.width, value: s.end }
831
+ const prev = labels[labels.length - 1]!
832
+ if (label.position - prev.position >= minGap) labels.push(label)
833
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
834
+ })
835
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
836
+ return labels.filter(
837
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
838
+ )
839
+ }
840
+
841
+ /**
842
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
843
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
844
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
845
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
846
+ * the rest 7 px at 12 px type).
847
+ */
848
+ function categoryBarFitLabels(
849
+ labels: readonly CategoryBarLabel[],
850
+ texts: readonly string[],
851
+ width: number,
852
+ gap = 8,
853
+ ): CategoryBarLabel[] {
854
+ const textWidth = (text: string) => {
855
+ let w = 0
856
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
857
+ return w
858
+ }
859
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
860
+ const w = textWidth(text)
861
+ if (label.position <= 0) return [0, w]
862
+ if (label.position >= 100) return [width - w, width]
863
+ const center = (label.position / 100) * width
864
+ return [center - w / 2, center + w / 2]
865
+ }
866
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
867
+ labels.forEach((label, i) => {
868
+ const here = extent(label, texts[i] ?? "")
869
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
870
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
871
+ else if (touches()) return
872
+ kept.push({ label, extent: here })
873
+ })
874
+ return kept.map((k) => k.label)
875
+ }
876
+
877
+ /** Marker position in percent of the bar, clamped to its ends. */
878
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
879
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
880
+ if (total === 0) return 0
881
+ return clamp((value / total) * 100, 0, 100)
882
+ }
883
+
884
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
885
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
886
+ const segments = categoryBarSegments(values)
887
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
888
+ if (index !== -1) return index
889
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
890
+ return 0
891
+ }
892
+
893
+ /* --------------------------------------------------------- ProgressCircle */
894
+
895
+ interface ProgressCircleGeometry {
896
+ /** SVG width/height. */
897
+ size: number
898
+ /** Radius of the stroke's centre line. */
899
+ normalizedRadius: number
900
+ circumference: number
901
+ /** `stroke-dashoffset` for the value arc. */
902
+ offset: number
903
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
904
+ ratio: number
905
+ }
906
+
907
+ function progressCircleGeometry(
908
+ value: number,
909
+ max: number,
910
+ radius: number,
911
+ strokeWidth: number,
912
+ ): ProgressCircleGeometry {
913
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
914
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
915
+ const circumference = 2 * Math.PI * normalizedRadius
916
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
917
+ }
918
+
919
+ /* ---------------------------------------------------------------- summary */
920
+
921
+ interface ChartSummaryInput {
922
+ data: readonly Record<string, unknown>[]
923
+ /** The x-axis key. */
924
+ index: string
925
+ /** Series keys; the first one is described. */
926
+ categories: readonly string[]
927
+ /** Title of the chart, put in front when given. */
928
+ title?: string
929
+ /** Same as the chart's `format` (default `"compact"`). */
930
+ format?: ValueFormat
931
+ /** Wins over `format`. */
932
+ valueFormatter?: ValueFormatter
933
+ /** Language of the sentence. Default the page's locale (`<html lang>`). */
934
+ locale?: string
935
+ }
936
+
937
+ const SUMMARY_TEXT = {
938
+ ja: {
939
+ up: "、前の点より増加",
940
+ down: "、前の点より減少",
941
+ flat: "、前の点と横ばい",
942
+ latest: (label: string, value: string) => `最新 ${label} は ${value}`,
943
+ top: (name: string, share: string) => `最大は ${name}(${share})`,
944
+ },
945
+ en: {
946
+ up: ", up from the previous point",
947
+ down: ", down from the previous point",
948
+ flat: ", flat from the previous point",
949
+ latest: (label: string, value: string) => `Latest ${label}: ${value}`,
950
+ top: (name: string, share: string) => `Largest: ${name} (${share})`,
951
+ },
952
+ }
953
+
954
+ /**
955
+ * One-sentence summary built from the rows, for `summary="auto"`:
956
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
957
+ * computed from the last two non-empty points of the first series — never
958
+ * written by hand, so it cannot contradict the data. `undefined` when there is
959
+ * no usable point.
960
+ */
961
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
962
+ const key = input.categories[0]
963
+ if (key === undefined) return undefined
964
+ const points: { label: string; value: number }[] = []
965
+ for (const row of input.data) {
966
+ const raw = row[key]
967
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
968
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
969
+ }
970
+ const latest = points[points.length - 1]
971
+ if (!latest) return undefined
972
+ const locale = resolveLocale(input.locale)
973
+ const t = SUMMARY_TEXT[uiLanguage(locale)]
974
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
975
+ const prev = points[points.length - 2]
976
+ const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
977
+ const head = input.title ? `${input.title}: ` : ""
978
+ return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
979
+ }
980
+
981
+ /**
982
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
983
+ * (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
984
+ */
985
+ function buildShareSummary(
986
+ slices: readonly { name: string; value: number }[],
987
+ title?: string,
988
+ locale?: string,
989
+ ): string | undefined {
990
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
991
+ const top = slices[0]
992
+ if (!top || total <= 0) return undefined
993
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
994
+ return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
995
+ }
996
+
997
+ /* ---------- end of inlined code ---------- */
998
+
999
+ /** The lightest shade is this share of the tone mixed into the card; the darkest is the tone itself. */
1000
+ const FLOOR_SHARE = 0.2
1001
+ /** The box height (px) while loading or empty (ChartFrame's default plot height). */
1002
+ const DEFAULT_CHART_HEIGHT = 288
1003
+ /** From this share of the range up, a cell is dark and its text takes the card colour. */
1004
+ const LIGHT_TEXT_FROM = 0.55
1005
+
1006
+ export interface PivotTableProps<T extends Record<string, unknown> = Record<string, unknown>> {
1007
+ /** 集計済みの行の配列。1 行 = 1 マス(行の次元 × 列の次元の組)。同じ組が複数あれば後の行が勝つ(合計はしない)。 */
1008
+ data: T[]
1009
+ /** 行の次元の列名(左から入れ子)。例 `["region", "category"]`。空なら 1 行。 */
1010
+ rows: (keyof T & string)[]
1011
+ /** 列の次元の列名(上から入れ子)。例 `["year"]`。空なら列の見出しは値の名前だけ。 */
1012
+ columns: (keyof T & string)[]
1013
+ /** マスに出す数値の列名。2 つ以上なら列の次元ごとに小列に分かれる。 */
1014
+ values: (keyof T & string)[]
1015
+ /** 値ごとの書式。例 `{ sales: "currency", margin: "percent" }`。無い値は `"number"`。 */
1016
+ formats?: Partial<Record<string, ValueFormat>>
1017
+ /** 列名・次元の値 → 表示名(見出しに反映)。 */
1018
+ labels?: Record<string, string>
1019
+ /** 値でマスを塗る(ハイライト表)。`true` で全部の値(値ごとに最小〜最大)、値の列名でその値だけ。既定 `false`。 */
1020
+ highlight?: boolean | string
1021
+ /** 塗りの色。`"chart-1"`〜`"chart-5"` か意味色。薄い → 濃いの単色。既定 `"chart-1"`。 */
1022
+ tone?: ChartSeriesColor
1023
+ /** マスのクリック。そのマスの行を受け取る(フィルターの操作に使う)。値の無いマスでは呼ばない。 */
1024
+ onSelect?: (row: T) => void
1025
+ /** 表の見出し。 */
1026
+ title?: string
1027
+ /** 表が言っていることの 1 文要約。 */
1028
+ summary?: string
1029
+ /** 読み込み中。スケルトンを出す。 */
1030
+ isLoading?: boolean
1031
+ /** `data` が空のときの表示。 */
1032
+ emptyState?: ChartEmptyState
1033
+ /** 表の箱の最大の高さ(px)。超えると箱の中で縦にスクロールし、見出しは上に残る。既定 480。 */
1034
+ maxHeight?: number
1035
+ className?: string
1036
+ /** スクリーンリーダー向けのラベル。省略時は見出し。 */
1037
+ ariaLabel?: string
1038
+ }
1039
+
1040
+ /* ------------------------------------------------------------------ model */
1041
+
1042
+ export interface PivotModel {
1043
+ /** Distinct row-dimension tuples, in data order. One empty tuple when there are no row dimensions. */
1044
+ rowKeys: string[][]
1045
+ /** Distinct column-dimension tuples, in data order. One empty tuple when there are no column dimensions. */
1046
+ colKeys: string[][]
1047
+ /** Cell → its row (the last row naming that cell). */
1048
+ cells: Map<string, Record<string, unknown>>
1049
+ /** Each value's range over the placed cells. */
1050
+ ranges: Record<string, { min: number; max: number }>
1051
+ }
1052
+
1053
+ const dimText = (v: unknown) => (v === null || v === undefined || v === "" ? EMPTY_VALUE : String(v))
1054
+ export const pivotCellKey = (rowKey: readonly string[], colKey: readonly string[]) => `${rowKey.join("\u0001")}\u0000${colKey.join("\u0001")}`
1055
+
1056
+ export function buildPivotModel(config: {
1057
+ data: readonly Record<string, unknown>[]
1058
+ rows: readonly string[]
1059
+ columns: readonly string[]
1060
+ values: readonly string[]
1061
+ }): PivotModel {
1062
+ const { data, rows, columns, values } = config
1063
+ const rowKeys = new Map<string, string[]>()
1064
+ const colKeys = new Map<string, string[]>()
1065
+ const cells = new Map<string, Record<string, unknown>>()
1066
+ for (const row of data) {
1067
+ if (!row || typeof row !== "object") continue
1068
+ const rk = rows.map((d) => dimText(row[d]))
1069
+ const ck = columns.map((d) => dimText(row[d]))
1070
+ const rId = rk.join("\u0001")
1071
+ const cId = ck.join("\u0001")
1072
+ if (!rowKeys.has(rId)) rowKeys.set(rId, rk)
1073
+ if (!colKeys.has(cId)) colKeys.set(cId, ck)
1074
+ cells.set(pivotCellKey(rk, ck), row)
1075
+ }
1076
+ const ranges: Record<string, { min: number; max: number }> = {}
1077
+ for (const value of values) {
1078
+ let [lo, hi] = [Infinity, -Infinity]
1079
+ for (const row of cells.values()) {
1080
+ const n = toChartNumber(row[value])
1081
+ if (n !== null) [lo, hi] = [Math.min(lo, n), Math.max(hi, n)]
1082
+ }
1083
+ ranges[value] = { min: Number.isFinite(lo) ? lo : 0, max: Number.isFinite(hi) ? hi : 0 }
1084
+ }
1085
+ return {
1086
+ rowKeys: rowKeys.size > 0 ? [...rowKeys.values()] : [rows.map(() => EMPTY_VALUE)],
1087
+ colKeys: colKeys.size > 0 ? [...colKeys.values()] : [columns.map(() => EMPTY_VALUE)],
1088
+ cells,
1089
+ ranges,
1090
+ }
1091
+ }
1092
+
1093
+ /** A header cell spanning consecutive keys that share the same prefix up to `level`. */
1094
+ export interface PivotSpan {
1095
+ text: string
1096
+ /** Index of the first key it covers. */
1097
+ start: number
1098
+ span: number
1099
+ }
1100
+
1101
+ /** The merged header cells of one level: runs of consecutive keys with the same prefix (levels 0…`level`). */
1102
+ export function pivotSpans(keys: readonly (readonly string[])[], level: number): PivotSpan[] {
1103
+ const out: PivotSpan[] = []
1104
+ const prefix = (k: readonly string[]) => k.slice(0, level + 1).join("\u0001")
1105
+ keys.forEach((key, i) => {
1106
+ const last = out[out.length - 1]
1107
+ if (last && prefix(keys[last.start]!) === prefix(key)) last.span++
1108
+ else out.push({ text: key[level] ?? "", start: i, span: 1 })
1109
+ })
1110
+ return out
1111
+ }
1112
+
1113
+ const TEXT = {
1114
+ ja: { table: "ピボット表" },
1115
+ en: { table: "Pivot table" },
1116
+ }
1117
+
1118
+ /* -------------------------------------------------------------- component */
1119
+
1120
+ /** Rows not given yet (a draft fills props in steps): keep the same array between renders. */
1121
+ const NO_ROWS: never[] = []
1122
+
1123
+ const asList = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : [])
1124
+
1125
+ export function PivotTable<T extends Record<string, unknown>>({
1126
+ data = NO_ROWS,
1127
+ rows: rowDims,
1128
+ columns: colDims,
1129
+ values: valueKeys,
1130
+ formats,
1131
+ labels,
1132
+ highlight = false,
1133
+ tone = "chart-1",
1134
+ onSelect,
1135
+ title,
1136
+ summary,
1137
+ isLoading,
1138
+ emptyState,
1139
+ maxHeight = 480,
1140
+ className,
1141
+ ariaLabel,
1142
+ }: PivotTableProps<T>) {
1143
+ const locale = useLocale()
1144
+ const t = TEXT[uiLanguage(resolveLocale(locale))]
1145
+ const dataRows = Array.isArray(data) ? data : NO_ROWS
1146
+ const rows = useMemo(() => asList(rowDims), [rowDims])
1147
+ const columns = useMemo(() => asList(colDims), [colDims])
1148
+ const values = useMemo(() => asList(valueKeys), [valueKeys])
1149
+ const model = useMemo(() => buildPivotModel({ data: dataRows, rows, columns, values }), [dataRows, rows, columns, values])
1150
+ const label = (key: string) => labels?.[key] ?? key
1151
+ const R = rows.length
1152
+ const C = columns.length
1153
+ const V = values.length
1154
+ const valueRow = V > 1 || C === 0
1155
+ const H = C + (valueRow ? 1 : 0)
1156
+ const shaded = (value: string) => highlight === true || highlight === value
1157
+ const isEmpty = dataRows.length === 0
1158
+ const ready = !isLoading && !isEmpty
1159
+
1160
+ const cellStyle = (value: string, n: number | null): CSSProperties | undefined => {
1161
+ if (n === null || !shaded(value)) return undefined
1162
+ const { min, max } = model.ranges[value] ?? { min: 0, max: 0 }
1163
+ const ratio = max > min ? Math.min(1, Math.max(0, (n - min) / (max - min))) : 1
1164
+ const share = Math.round((FLOOR_SHARE + (1 - FLOOR_SHARE) * ratio) * 100)
1165
+ return {
1166
+ backgroundColor: `color-mix(in oklch, var(--${tone}) ${share}%, var(--card))`,
1167
+ color: ratio >= LIGHT_TEXT_FROM ? "var(--card)" : undefined,
1168
+ }
1169
+ }
1170
+
1171
+ const headerRows = Array.from({ length: H }, (_, h) => {
1172
+ const lead =
1173
+ h === H - 1
1174
+ ? rows.map((d, level) => (
1175
+ <TableHead key={`dim-${d}`} scope="col" className={cn(level === 0 && "pl-0")}>
1176
+ {label(d)}
1177
+ </TableHead>
1178
+ ))
1179
+ : h === 0 && R > 0
1180
+ ? [<TableHead key="corner" colSpan={R} rowSpan={H - 1} aria-hidden="true" />]
1181
+ : []
1182
+ const cells =
1183
+ h < C
1184
+ ? pivotSpans(model.colKeys, h).map((s) => (
1185
+ <TableHead key={`c-${h}-${s.start}`} scope="colgroup" colSpan={s.span * Math.max(1, V)} className="text-right">
1186
+ {label(s.text)}
1187
+ </TableHead>
1188
+ ))
1189
+ : model.colKeys.flatMap((_, ci) =>
1190
+ values.map((v) => (
1191
+ <TableHead key={`v-${ci}-${v}`} scope="col" className="text-right">
1192
+ {label(v)}
1193
+ </TableHead>
1194
+ )),
1195
+ )
1196
+ return (
1197
+ <TableRow key={`h-${h}`} className="hover:bg-transparent">
1198
+ {lead}
1199
+ {cells}
1200
+ </TableRow>
1201
+ )
1202
+ })
1203
+
1204
+ const rowSpans = rows.map((_, level) => new Map(pivotSpans(model.rowKeys, level).map((s) => [s.start, s.span])))
1205
+
1206
+ const body = model.rowKeys.map((rk, ri) => (
1207
+ <TableRow key={`r-${ri}`}>
1208
+ {rows.map((d, level) => {
1209
+ const span = rowSpans[level]!.get(ri)
1210
+ if (span === undefined) return null
1211
+ return (
1212
+ <TableHead key={`rh-${d}`} scope={span > 1 ? "rowgroup" : "row"} rowSpan={span} className={cn("align-top font-medium text-foreground", level === 0 && "pl-0")}>
1213
+ {label(rk[level] ?? "")}
1214
+ </TableHead>
1215
+ )
1216
+ })}
1217
+ {model.colKeys.flatMap((ck, ci) =>
1218
+ values.map((v) => {
1219
+ const row = model.cells.get(pivotCellKey(rk, ck))
1220
+ const n = row ? toChartNumber(row[v]) : null
1221
+ const text = formatValue(n, formats?.[v] ?? "number", locale)
1222
+ return (
1223
+ <TableCell key={`c-${ci}-${v}`} className="text-right tabular-nums" style={cellStyle(v, n)}>
1224
+ {onSelect && row ? (
1225
+ <button type="button" className="w-full cursor-pointer text-right tabular-nums" onClick={() => onSelect(row as T)}>
1226
+ {text}
1227
+ </button>
1228
+ ) : (
1229
+ text
1230
+ )}
1231
+ </TableCell>
1232
+ )
1233
+ }),
1234
+ )}
1235
+ </TableRow>
1236
+ ))
1237
+
1238
+ return (
1239
+ <ChartFrame
1240
+ title={title}
1241
+ summary={summary}
1242
+ isLoading={isLoading ?? false}
1243
+ isEmpty={isEmpty}
1244
+ emptyState={emptyState}
1245
+ height={ready ? "auto" : DEFAULT_CHART_HEIGHT}
1246
+ variant="list"
1247
+ plotRole="group"
1248
+ ariaLabel={ariaLabel ?? title ?? t.table}
1249
+ className={className}
1250
+ >
1251
+ <div data-slot="pivot-table" className="relative w-full overflow-auto" style={{ maxHeight }}>
1252
+ <table data-slot="table" aria-label={ariaLabel ?? title ?? t.table} className="w-full caption-bottom text-sm">
1253
+ <TableHeader className="sticky top-0 z-10 bg-card">{headerRows}</TableHeader>
1254
+ <TableBody>{body}</TableBody>
1255
+ </table>
1256
+ </div>
1257
+ </ChartFrame>
1258
+ )
1259
+ }