@squadbase/vantage 0.6.2 → 0.7.0-dev1.19083f7

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,2027 @@
1
+ // Copied by `vantage add ui heatmap`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/charts/heatmap.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * Heatmap — a typed heatmap over `EChart`: pass rows, the column keys for the
7
+ * x axis / y axis (`x` / `y`) and the number to shade by (`value`) instead of an
8
+ * ECharts option. Cohort retention (週 × コホート), weekday × hour counts, …
9
+ *
10
+ * Shading is a single-colour ramp (light → dark) of one theme colour
11
+ * (`--chart-1` by default; `tone` moves it to another series token or a meaning
12
+ * colour) and follows light/dark. A cell with no value (null / missing row) is left
13
+ * unpainted (transparent, no text), never shaded like 0; the tooltip and the table say「—」.
14
+ * The shading range is the data's min–max unless `scale` fixes it. The ramp's lowest end is the tone mixed 20% into
15
+ * the surface (`color-mix(in oklch, var(--chart-1) 20%, var(--card))`), so the lowest cell never melts into the
16
+ * background in dark mode; the legend's gradient starts at the same colour.
17
+ * Renders inside `ChartFrame` (title, summary, loading skeleton, empty state)
18
+ * with the numbers as a screen-reader table.
19
+ */
20
+ import { forwardRef, useMemo, type ForwardedRef, type ReactElement, type Ref } from "react"
21
+ import { use } from "echarts/core"
22
+ import { HeatmapChart } from "echarts/charts"
23
+ import { VisualMapComponent } from "echarts/components"
24
+ import type { EChartsOption } from "echarts"
25
+
26
+ import { ChartFrame } from "@squadbase/vantage/components"
27
+ import { EChart } from "@squadbase/vantage/components"
28
+ import { EMPTY_VALUE, type ValueFormat } from "@squadbase/vantage/components"
29
+ import type { ChartActionsOptions, ChartEmptyState, ChartRootAttributes, ChartSeriesColor, ValueFormatter } from "@squadbase/vantage/components"
30
+ import { useSyncExternalStore } from "react"
31
+ import { createContext, useCallback, useEffect, useRef, useState, type RefObject } from "react"
32
+ import type { ChartTone } from "@squadbase/vantage/components"
33
+ import { formatValue, toValueFormatter } from "@squadbase/vantage/components"
34
+ import type { ChartColor, ChartColors } from "@squadbase/vantage/components"
35
+
36
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
37
+
38
+ /**
39
+ * The display language of the parts and the defaults that follow it.
40
+ *
41
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
42
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
43
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
44
+ *
45
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
46
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
47
+ */
48
+
49
+ /** The language of the built-in wording: Japanese or English. */
50
+ type UiLanguage = "ja" | "en"
51
+
52
+ /** The locale used when `<html lang>` gives none (and on the server). */
53
+ const FALLBACK_LOCALE = "en-US"
54
+
55
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
56
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
57
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
58
+ }
59
+
60
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
61
+ function normalizeLocale(tag: string | null | undefined): string {
62
+ const value = tag?.trim()
63
+ if (!value) return FALLBACK_LOCALE
64
+ try {
65
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
66
+ } catch {
67
+ return FALLBACK_LOCALE
68
+ }
69
+ }
70
+
71
+ /**
72
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
73
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
74
+ */
75
+ function documentLocale(): string {
76
+ if (typeof document === "undefined") return FALLBACK_LOCALE
77
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
78
+ }
79
+
80
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
81
+ function resolveLocale(locale?: string | null): string {
82
+ return locale || documentLocale()
83
+ }
84
+
85
+ /** Picks the wording table of the locale's language. */
86
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
87
+ return table[uiLanguage(resolveLocale(locale))]
88
+ }
89
+
90
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
91
+ function defaultCurrency(locale?: string | null): string {
92
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
93
+ }
94
+
95
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
96
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
97
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
98
+ }
99
+
100
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
101
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
102
+
103
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
104
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
105
+
106
+ /**
107
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
108
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
109
+ * Monday for the rest.
110
+ */
111
+ function weekStartsOn(locale?: string | null): WeekDay {
112
+ const tag = normalizeLocale(resolveLocale(locale))
113
+ if (uiLanguage(tag) === "ja") return 1
114
+ try {
115
+ const info = new Intl.Locale(tag) as Intl.Locale & {
116
+ getWeekInfo?: () => { firstDay: number }
117
+ weekInfo?: { firstDay: number }
118
+ }
119
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
120
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
121
+ } catch {
122
+ // Fall through to the table below.
123
+ }
124
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
125
+ }
126
+
127
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
128
+
129
+ const listeners = new Set<() => void>()
130
+ let observer: MutationObserver | null = null
131
+
132
+ /** One observer on `<html lang>` for every subscribed part. */
133
+ function subscribe(onChange: () => void): () => void {
134
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
135
+ listeners.add(onChange)
136
+ if (!observer) {
137
+ observer = new MutationObserver(() => {
138
+ for (const listener of [...listeners]) listener()
139
+ })
140
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
141
+ }
142
+ return () => {
143
+ listeners.delete(onChange)
144
+ if (listeners.size === 0 && observer) {
145
+ observer.disconnect()
146
+ observer = null
147
+ }
148
+ }
149
+ }
150
+
151
+ const serverLocale = () => FALLBACK_LOCALE
152
+
153
+ /**
154
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
155
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
156
+ */
157
+ function useDocumentLocale(): string {
158
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
159
+ }
160
+
161
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
162
+ function useLocale(locale?: string | null): string {
163
+ const page = useDocumentLocale()
164
+ return locale || page
165
+ }
166
+
167
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-theme.ts (internal to @squadbase/vantage) ---------- */
168
+
169
+ /**
170
+ * The colour of the folded「その他」series / slice / row. The ONLY place this
171
+ * grey is defined — every chart takes it from here. It is the most subdued
172
+ * colour in a chart, not the darkest: the theme's `--neutral` mixed halfway into
173
+ * `--background`, so it recedes in light and dark alike (and brand themes follow
174
+ * it). `--neutral-subtle` alone sits too close to the background to read as a
175
+ * slice. Canvas charts resolve it through `resolveChartColors`.
176
+ */
177
+ const CHART_OTHER_COLOR = "color-mix(in oklab, var(--neutral) 50%, var(--background))"
178
+
179
+ /**
180
+ * True inside `ChartFrame`. The frame's plot area carries the chart's single
181
+ * `role="img"` and label, so `EChart` drops its own when it sees this.
182
+ */
183
+ const ChartFrameContext = createContext(false)
184
+
185
+ /** Series palette, in order. Missing tokens are skipped, not defaulted. */
186
+ const SERIES_TOKENS = ["--chart-1", "--chart-2", "--chart-3", "--chart-4", "--chart-5"] as const
187
+
188
+ interface ChartTokens {
189
+ /** Resolved `--chart-1..5`, in order. */
190
+ series: string[]
191
+ /** Computed `font-family` of the container, so canvas text matches the DOM. Optional. */
192
+ fontFamily?: string
193
+ /** Body text: titles and the default `textStyle`. */
194
+ foreground: string | null
195
+ /** Secondary text: axis labels, legend, subtitles. */
196
+ mutedForeground: string | null
197
+ /** Axis lines, ticks, split lines, tooltip border. */
198
+ border: string | null
199
+ /** Tooltip surface. */
200
+ popover: string | null
201
+ /** Semantic and surface dependencies used by typed chart options. Optional for hand-built tokens. */
202
+ colors?: Record<string, string>
203
+ /** Actual inherited painting surface (may change without a token changing). */
204
+ surface?: string | null
205
+ /** Tooltip text. */
206
+ popoverForeground: string | null
207
+ }
208
+
209
+ // Keep scope out of the public token shape. A resolved snapshot remembers where arbitrary
210
+ // var(--token) expressions must be read, without retaining unmounted charts globally.
211
+ const tokenScopes = new WeakMap<ChartTokens, Element>()
212
+ const OPTION_COLOR_TOKENS = [
213
+ "--background", "--card", "--muted", "--primary", "--destructive",
214
+ ...["positive", "negative", "warning", "neutral", "info"].flatMap((tone) =>
215
+ ["", "-fill", "-subtle"].map((suffix) => `--${tone}${suffix}`)),
216
+ ]
217
+
218
+ let normalizeContext: CanvasRenderingContext2D | null | undefined
219
+
220
+ /** The forms `fillStyle` serializes legacy colours to, and zrender can parse. */
221
+ const ZRENDER_COLOR_RE = /^(?:#[0-9a-f]{6}|rgba?\()/i
222
+
223
+ /**
224
+ * Serialize a CSS colour into a canvas-safe form, or `null` if the browser
225
+ * rejects it. Assigning an invalid value to `fillStyle` is a no-op, so the same
226
+ * input is written over two different known colours: agreeing results mean the
227
+ * value parsed, differing ones mean it was dropped.
228
+ */
229
+ function toCanvasColor(value: string): string | null {
230
+ const raw = value.trim()
231
+ if (!raw) return null
232
+ if (normalizeContext === undefined) {
233
+ const canvas = document.createElement("canvas")
234
+ canvas.width = 1
235
+ canvas.height = 1
236
+ normalizeContext = canvas.getContext("2d", { willReadFrequently: true })
237
+ }
238
+ const ctx = normalizeContext
239
+ if (!ctx) return raw
240
+ ctx.fillStyle = "#000000"
241
+ ctx.fillStyle = raw
242
+ const onBlack = ctx.fillStyle
243
+ ctx.fillStyle = "#ffffff"
244
+ ctx.fillStyle = raw
245
+ if (onBlack !== ctx.fillStyle || typeof onBlack !== "string") return null
246
+ if (ZRENDER_COLOR_RE.test(onBlack)) return onBlack
247
+ // Still `oklch()` / `lab()` / `color(...)`: paint it and read the pixel back.
248
+ // Wide-gamut colours clip to sRGB, which is all zrender can express anyway.
249
+ ctx.clearRect(0, 0, 1, 1)
250
+ ctx.fillRect(0, 0, 1, 1)
251
+ const [r = 0, g = 0, b = 0, a = 0] = ctx.getImageData(0, 0, 1, 1).data
252
+ return a === 255
253
+ ? `rgb(${r}, ${g}, ${b})`
254
+ : `rgba(${r}, ${g}, ${b}, ${Math.round((a / 255) * 1000) / 1000})`
255
+ }
256
+
257
+ /**
258
+ * Read the chart tokens off `el` (the document root by default — tokens live on
259
+ * `:root` and inherit). Returns `null` outside the browser so callers fall back
260
+ * to plain ECharts defaults.
261
+ */
262
+ function readChartTokens(el?: Element | null): ChartTokens | null {
263
+ if (typeof document === "undefined") return null
264
+ const target = el ?? document.documentElement
265
+ if (!target) return null
266
+ const styles = getComputedStyle(target)
267
+ const read = (name: string) => toCanvasColor(styles.getPropertyValue(name))
268
+ const series: string[] = []
269
+ for (const token of SERIES_TOKENS) {
270
+ const color = read(token)
271
+ if (color) series.push(color)
272
+ }
273
+ const tokens: ChartTokens = {
274
+ series,
275
+ colors: Object.fromEntries(OPTION_COLOR_TOKENS.map((name) => [name, styles.getPropertyValue(name).trim()])),
276
+ surface: readChartSurface(target),
277
+ ...(styles.fontFamily ? { fontFamily: styles.fontFamily } : {}),
278
+ foreground: read("--foreground"),
279
+ mutedForeground: read("--muted-foreground"),
280
+ border: read("--border"),
281
+ popover: read("--popover"),
282
+ popoverForeground: read("--popover-foreground"),
283
+ }
284
+ tokenScopes.set(tokens, target)
285
+ return tokens
286
+ }
287
+
288
+ /** Structural equality, so a theme toggle that changes nothing doesn't re-init. */
289
+ function sameChartTokens(a: ChartTokens | null, b: ChartTokens | null): boolean {
290
+ if (a === b) return true
291
+ if (!a || !b) return false
292
+ return (
293
+ tokenScopes.get(a) === tokenScopes.get(b) &&
294
+ a.surface === b.surface &&
295
+ Object.keys(a.colors ?? {}).length === Object.keys(b.colors ?? {}).length &&
296
+ Object.entries(a.colors ?? {}).every(([name, value]) => b.colors?.[name] === value) &&
297
+ a.series.length === b.series.length &&
298
+ a.series.every((color, i) => color === b.series[i]) &&
299
+ a.fontFamily === b.fontFamily &&
300
+ a.foreground === b.foreground &&
301
+ a.mutedForeground === b.mutedForeground &&
302
+ a.border === b.border &&
303
+ a.popover === b.popover &&
304
+ a.popoverForeground === b.popoverForeground
305
+ )
306
+ }
307
+
308
+ /**
309
+ * Watch everything that can change the resolved tokens and call `onChange` when
310
+ * something might have. It only ever says "re-read" — the caller compares with
311
+ * `sameChartTokens` and decides whether anything actually moved. Returns a
312
+ * disposer.
313
+ *
314
+ * Two sources, not one:
315
+ * - light/dark flips, which land as `class` / `data-theme` (or an inline
316
+ * `style`) on `<html>`/`<body>`, or as an OS preference change
317
+ * - stylesheet changes. In dev, editing `styles.css` rewrites the injected
318
+ * `<style>` in `<head>` and touches nothing else, so watching the theme
319
+ * attributes alone leaves the chart painted in the previous palette until a
320
+ * reload — the tokens in the DOM are new, the canvas is not.
321
+ */
322
+ function watchChartTokens(onChange: () => void, scope?: Element | null): () => void {
323
+ if (typeof document === "undefined") return () => {}
324
+ // Style edits arrive as bursts of mutations; coalesce them into one read, and
325
+ // take it after the next frame so a swapped stylesheet has been applied.
326
+ let frame = 0
327
+ const schedule = () => {
328
+ if (frame) return
329
+ frame = requestAnimationFrame(() => {
330
+ frame = 0
331
+ onChange()
332
+ })
333
+ }
334
+
335
+ const themeObserver = new MutationObserver(schedule)
336
+ const attributeFilter = ["class", "style", "data-theme"]
337
+ // Only the chart and its ancestors can change its inherited theme. Never observe
338
+ // the document subtree: canvas/tooltip/rendering mutations would trigger every chart.
339
+ for (let node: Element | null = scope ?? document.body ?? document.documentElement; node; node = node.parentElement) {
340
+ themeObserver.observe(node, { attributes: true, attributeFilter })
341
+ }
342
+
343
+ const styleObserver = new MutationObserver(schedule)
344
+ if (document.head) {
345
+ styleObserver.observe(document.head, {
346
+ childList: true,
347
+ subtree: true,
348
+ characterData: true,
349
+ attributes: true,
350
+ attributeFilter: ["href", "media", "disabled"],
351
+ })
352
+ }
353
+
354
+ // A swapped `<link>` only applies once the sheet has loaded, after its mutation.
355
+ const onLoad = (event: Event) => {
356
+ if (event.target instanceof HTMLLinkElement) schedule()
357
+ }
358
+ document.addEventListener("load", onLoad, true)
359
+
360
+ const media = window.matchMedia("(prefers-color-scheme: dark)")
361
+ media.addEventListener("change", schedule)
362
+
363
+ return () => {
364
+ if (frame) cancelAnimationFrame(frame)
365
+ themeObserver.disconnect()
366
+ styleObserver.disconnect()
367
+ document.removeEventListener("load", onLoad, true)
368
+ media.removeEventListener("change", schedule)
369
+ }
370
+ }
371
+
372
+ /** Shared shape for the four axis types ECharts themes address separately. */
373
+ function axisTheme(tokens: ChartTokens, splitLine: boolean) {
374
+ const line = tokens.border ?? undefined
375
+ return {
376
+ axisLine: { show: false },
377
+ axisTick: { show: false },
378
+ axisLabel: { show: true, color: tokens.mutedForeground ?? undefined, fontSize: 12 },
379
+ // Faint horizontal rules only: the border colour at low opacity.
380
+ splitLine: { show: splitLine, lineStyle: { color: line ? [line] : undefined, opacity: 0.5, width: 1 } },
381
+ splitArea: { show: false },
382
+ }
383
+ }
384
+
385
+ /**
386
+ * Build the ECharts theme. `option.color` still wins over `theme.color`, so an
387
+ * app that sets its own palette keeps it.
388
+ */
389
+ function buildChartTheme(tokens: ChartTokens): Record<string, unknown> {
390
+ const text = tokens.foreground ?? undefined
391
+ const muted = tokens.mutedForeground ?? undefined
392
+ const line = tokens.border ?? undefined
393
+ return {
394
+ // Let the page background show through: charts sit on cards, not on a canvas.
395
+ backgroundColor: "transparent",
396
+ ...(tokens.series.length > 0 ? { color: tokens.series } : {}),
397
+ textStyle: { color: text, ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}) },
398
+ title: { textStyle: { color: text }, subtextStyle: { color: muted } },
399
+ legend: { textStyle: { color: muted } },
400
+ categoryAxis: axisTheme(tokens, false),
401
+ valueAxis: axisTheme(tokens, true),
402
+ logAxis: axisTheme(tokens, true),
403
+ timeAxis: axisTheme(tokens, true),
404
+ tooltip: {
405
+ // ECharts' default 0.4s transform lags the tooltip ~300ms behind the cursor.
406
+ transitionDuration: 0,
407
+ backgroundColor: tokens.popover ?? undefined,
408
+ borderColor: line,
409
+ borderWidth: 1,
410
+ padding: [8, 12],
411
+ // Rounded card with a soft shadow; in dark mode the shadow barely shows, so the border carries the edge.
412
+ extraCssText: "border-radius:8px;box-shadow:var(--shadow-card, 0 4px 12px rgb(0 0 0 / 0.08));",
413
+ textStyle: {
414
+ color: tokens.popoverForeground ?? undefined,
415
+ fontSize: 12,
416
+ ...(tokens.fontFamily ? { fontFamily: tokens.fontFamily } : {}),
417
+ },
418
+ axisPointer: { lineStyle: { color: line }, crossStyle: { color: line } },
419
+ },
420
+ }
421
+ }
422
+
423
+ /**
424
+ * The resolved tokens, kept current: re-read whenever `watchChartTokens` says
425
+ * they may have moved, and only replaced when a value actually changed. For
426
+ * components that build an ECharts option from token colours themselves (the
427
+ * typed charts), so their palette follows light/dark like `EChart`'s theme.
428
+ */
429
+ function useChartTokens(scope?: Element | null | RefObject<Element | null>): ChartTokens | null {
430
+ const [tokens, setTokens] = useState<ChartTokens | null>(() => readChartTokens())
431
+ // Compared here, not inside a `setTokens` updater: an updater that reads the DOM is
432
+ // replayed by React on every rebase and returns a fresh object each time, so the state
433
+ // never settles ("Maximum update depth exceeded" once the tokens change after mount).
434
+ const tokensRef = useRef(tokens)
435
+ useEffect(() => {
436
+ const target = scope && "current" in scope ? scope.current : scope
437
+ const sync = () => {
438
+ const next = readChartTokens(target)
439
+ if (sameChartTokens(tokensRef.current, next)) return
440
+ tokensRef.current = next
441
+ setTokens(next)
442
+ }
443
+ sync()
444
+ return watchChartTokens(sync, target)
445
+ }, [scope])
446
+ return tokens
447
+ }
448
+
449
+ const SERIES_TOKEN_NAME_RE = /^chart-([1-5])$/
450
+ const TONE_NAME_RE = /^(?:positive|warning|negative|neutral|info)(?:-fill)?$/
451
+ const CSS_VAR_RE = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/
452
+ const EMBEDDED_VAR_RE = /var\(\s*(--[\w-]+)\s*\)/g
453
+
454
+ /**
455
+ * Turn chart colours into canvas-safe strings. `"chart-1"`〜`"chart-5"` come from
456
+ * the resolved series tokens; `"positive"` / `"warning"` / `"negative"` / `"neutral"` (and the area
457
+ * variants `"positive-fill"`, …) are read in the snapshot's inherited scope (`--positive`, …); `var(--token)` uses the same scope; any
458
+ * other CSS colour is normalized like the tokens are. A colour that can't be
459
+ * resolved comes back as `""`, which ECharts treats as "use the palette".
460
+ */
461
+ function resolveChartColors(colors: readonly string[], tokens: ChartTokens | null): string[] {
462
+ return colors.map((color) => {
463
+ const token = SERIES_TOKEN_NAME_RE.exec(color.trim())
464
+ if (token) return tokens?.series[Number(token[1]) - 1] ?? ""
465
+ // Meaning colours are the theme tokens of the same name: same path as `var(--positive)`.
466
+ if (TONE_NAME_RE.test(color.trim())) {
467
+ if (typeof document === "undefined") return ""
468
+ const target = (tokens && tokenScopes.get(tokens)) ?? document.documentElement
469
+ return toCanvasColor(getComputedStyle(target).getPropertyValue(`--${color.trim()}`)) ?? ""
470
+ }
471
+ if (typeof document === "undefined") return color
472
+ let value = color.trim()
473
+ const cssVar = CSS_VAR_RE.exec(value)
474
+ const styles = getComputedStyle((tokens && tokenScopes.get(tokens)) ?? document.documentElement)
475
+ if (cssVar) {
476
+ value = styles.getPropertyValue(cssVar[1]!).trim() || (cssVar[2] ?? "").trim()
477
+ } else if (value.includes("var(")) {
478
+ // A colour function over tokens (`color-mix(… var(--muted-foreground) …)`):
479
+ // substitute the tokens, then let the canvas resolve the rest.
480
+ value = value.replace(EMBEDDED_VAR_RE, (_, name: string) => styles.getPropertyValue(name).trim())
481
+ }
482
+ return toCanvasColor(value) ?? ""
483
+ })
484
+ }
485
+
486
+ /** Every meaning colour resolved for the canvas (`""` when it can't be resolved). */
487
+ function resolveToneColors(tokens: ChartTokens | null): Record<ChartTone, string> {
488
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
489
+ ["positive", "warning", "negative", "neutral"],
490
+ tokens,
491
+ )
492
+ return { positive, warning, negative, neutral }
493
+ }
494
+
495
+ /** The area (`--<tone>-fill`) colours of every meaning tone, resolved for the canvas (`""` when it can't be resolved). */
496
+ function resolveFillColors(tokens: ChartTokens | null): Record<ChartTone, string> {
497
+ const [positive = "", warning = "", negative = "", neutral = ""] = resolveChartColors(
498
+ ["positive-fill", "warning-fill", "negative-fill", "neutral-fill"],
499
+ tokens,
500
+ )
501
+ return { positive, warning, negative, neutral }
502
+ }
503
+
504
+ const TRANSPARENT_RE = /^(?:transparent|rgba\([^)]*,\s*0(?:\.0+)?\))$/i
505
+
506
+ /**
507
+ * The colour the chart is painted on: the first opaque `background-color` up
508
+ * from `el` (a card, the page), else `--background`. Canvas-safe, or `null`
509
+ * outside the browser.
510
+ */
511
+ function readChartSurface(el: Element | null): string | null {
512
+ if (typeof document === "undefined") return null
513
+ for (let node: Element | null = el; node; node = node.parentElement) {
514
+ const bg = getComputedStyle(node).backgroundColor.trim()
515
+ if (bg && !TRANSPARENT_RE.test(bg)) {
516
+ const color = toCanvasColor(bg)
517
+ if (color) return color
518
+ }
519
+ }
520
+ return toCanvasColor(getComputedStyle(el ?? document.documentElement).getPropertyValue("--background"))
521
+ }
522
+
523
+ /** Widths are bucketed so a resize only rebuilds the option when the label budget can change. */
524
+ const WIDTH_BUCKET = 40
525
+
526
+ /**
527
+ * The surface colour behind a chart (see `readChartSurface`), re-read when the
528
+ * tokens move (light/dark), and the plot's width (rounded down to 40px;
529
+ * `undefined` until measured). Returns a ref for the plot that also feeds the
530
+ * component's forwarded ref.
531
+ */
532
+ function useChartSurface<E extends Element>(
533
+ forwarded: ForwardedRef<E>,
534
+ tokens?: ChartTokens | null,
535
+ ): { ref: (el: E | null) => void; surface: string | undefined; width: number | undefined; tokens: ChartTokens | null } {
536
+ const [node, setNode] = useState<E | null>(null)
537
+ const scopedTokens = useChartTokens(node)
538
+ const [surface, setSurface] = useState<string | undefined>(undefined)
539
+ const [width, setWidth] = useState<number | undefined>(undefined)
540
+ const ref = useCallback(
541
+ (el: E | null) => {
542
+ setNode(el)
543
+ if (typeof forwarded === "function") forwarded(el)
544
+ else if (forwarded) forwarded.current = el
545
+ },
546
+ [forwarded],
547
+ )
548
+ useEffect(() => {
549
+ if (!node) return
550
+ setSurface(readChartSurface(node) ?? undefined)
551
+ }, [node, tokens, scopedTokens])
552
+ useEffect(() => {
553
+ if (!node || typeof ResizeObserver === "undefined") return
554
+ const update = (w: number) => setWidth(Math.floor(w / WIDTH_BUCKET) * WIDTH_BUCKET)
555
+ update(node.getBoundingClientRect().width)
556
+ const observer = new ResizeObserver((entries) => update(entries[0]?.contentRect.width ?? 0))
557
+ observer.observe(node)
558
+ return () => observer.disconnect()
559
+ }, [node])
560
+ return { ref, surface, width, tokens: scopedTokens }
561
+ }
562
+
563
+ /* ---------- inlined from @squadbase/squadkit registry/lib/chart-utils.ts (internal to @squadbase/vantage) ---------- */
564
+
565
+ const ROOT_PROP_KEYS = new Set(["id", "style", "role", "tabIndex", "lang", "hidden"])
566
+ const ROOT_PROP_PREFIX_RE = /^(data|aria)-/
567
+
568
+ /**
569
+ * The attributes of a typed chart's leftover props that belong on its root
570
+ * element: `id` / `style` / `role` / `tabIndex` / `lang` / `hidden`, `data-*` and `aria-*`.
571
+ * An allowlist, so a chart's own (or deprecated, ignored) props never reach the DOM.
572
+ */
573
+ function chartRootProps(rest: Record<string, unknown>): Record<string, unknown> {
574
+ const out: Record<string, unknown> = {}
575
+ for (const [key, value] of Object.entries(rest)) {
576
+ if (value !== undefined && (ROOT_PROP_KEYS.has(key) || ROOT_PROP_PREFIX_RE.test(key))) out[key] = value
577
+ }
578
+ return out
579
+ }
580
+
581
+ /** The series tokens, in palette order — the default `colors` of every typed chart. */
582
+ const DEFAULT_CHART_COLORS: readonly ChartColor[] = [
583
+ "chart-1",
584
+ "chart-2",
585
+ "chart-3",
586
+ "chart-4",
587
+ "chart-5",
588
+ ]
589
+
590
+ const TOKEN_NAME_RE = /^chart-[1-5]$/
591
+
592
+ /** The meaning colours; each is a theme token of the same name (`--positive`, …). */
593
+ const CHART_TONES: readonly ChartTone[] = ["positive", "warning", "negative", "neutral"]
594
+
595
+ /** Whether `color` is a meaning colour (`"positive"` / `"warning"` / `"negative"` / `"neutral"`). */
596
+ function isChartTone(color: string): color is ChartTone {
597
+ return (CHART_TONES as readonly string[]).includes(color.trim())
598
+ }
599
+
600
+ /**
601
+ * A chart colour as a CSS value: `"chart-2"` → `var(--chart-2)` (so it follows
602
+ * light/dark on its own), anything else passes through unchanged.
603
+ */
604
+ function chartColorToCss(color: ChartColor): string {
605
+ const value = color.trim()
606
+ return TOKEN_NAME_RE.test(value) || isChartTone(value) ? `var(--${value})` : value
607
+ }
608
+
609
+ /**
610
+ * A chart colour for an AREA (bar, slice, segment, ring): like `chartColorToCss`, but a meaning
611
+ * colour resolves to its area token (`"positive"` → `var(--positive-fill)`), which keeps the same
612
+ * lightness step from the page in light and dark. `--positive` etc. are for text and icons.
613
+ */
614
+ function chartFillToCss(color: ChartColor): string {
615
+ const value = color.trim()
616
+ return isChartTone(value) ? `var(--${value}-fill)` : chartColorToCss(color)
617
+ }
618
+
619
+ /** The colour name to resolve for an area: a meaning colour becomes its `-fill` token (`"positive"` → `"positive-fill"`), the rest is unchanged. */
620
+ function chartFillName(color: ChartColor): ChartColor {
621
+ const value = color.trim()
622
+ return isChartTone(value) ? `${value}-fill` : color
623
+ }
624
+
625
+ /** The `i`-th colour, cycling through `colors` (the token palette when empty). */
626
+ function chartColorAt(colors: readonly ChartColor[] | undefined, i: number): ChartColor {
627
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
628
+ return palette[i % palette.length]!
629
+ }
630
+
631
+ /** `colors` extended (by cycling) to exactly `count` entries. */
632
+ function chartColorsFor(colors: readonly ChartColor[] | undefined, count: number): ChartColor[] {
633
+ return Array.from({ length: count }, (_, i) => chartColorAt(colors, i))
634
+ }
635
+
636
+ /** A translucent version of a CSS colour (works for `var(--…)` too). */
637
+ function tintCss(cssColor: string, percent: number): string {
638
+ return `color-mix(in oklab, ${cssColor} ${percent}%, transparent)`
639
+ }
640
+
641
+ const numberFormat = new Intl.NumberFormat("ja-JP", { maximumFractionDigits: 2 })
642
+
643
+ /** Default `valueFormatter`: grouped digits, up to two decimals (`1,234.5`). */
644
+ const defaultValueFormatter: ValueFormatter = (value) => numberFormat.format(value)
645
+
646
+ /**
647
+ * The formatter a chart actually uses: an explicit `valueFormatter` wins, else
648
+ * `format` (default `"compact"`, so ¥1億 / 9.2万 on axes) via `toValueFormatter`.
649
+ */
650
+ function resolveValueFormatter(
651
+ valueFormatter: ValueFormatter | undefined,
652
+ format: ValueFormat | undefined,
653
+ locale?: string,
654
+ ): ValueFormatter {
655
+ return valueFormatter ?? toValueFormatter(format, locale)
656
+ }
657
+
658
+ /**
659
+ * The formatter of value-axis ticks and on-plot labels: an explicit
660
+ * `valueFormatter` wins; else `"compact"` / `"number"` / `"currency"` read in
661
+ * the short form (`1億`, `¥1億`, `¥4,520万` — a tick of `¥100,000,000` is
662
+ * too wide to read), and `"percent"` / `"multiple"` as `format` says. The short
663
+ * form goes through `formatValue` (compact notation, `digits` / `unit` dropped),
664
+ * so an axis tick and a KPI / tooltip of the same `format` always print the same
665
+ * currency sign and grouping.
666
+ */
667
+ function resolveAxisFormatter(
668
+ valueFormatter: ValueFormatter | undefined,
669
+ format: ValueFormat | undefined,
670
+ localeArg?: string,
671
+ ): ValueFormatter {
672
+ if (valueFormatter) return valueFormatter
673
+ const locale = resolveLocale(localeArg)
674
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
675
+ if (spec.type !== "compact" && spec.type !== "number" && spec.type !== "currency") return toValueFormatter(format, locale)
676
+ const currency = "currency" in spec ? spec.currency : undefined
677
+ const short: ValueFormat =
678
+ spec.type === "currency" ? { type: "currency", currency, notation: "compact" } : { type: "compact" }
679
+ return (value) => formatValue(value, short, locale)
680
+ }
681
+
682
+ interface CompactUnit {
683
+ token: string
684
+ size: number
685
+ }
686
+
687
+ const compactUnitCache = new Map<string, CompactUnit[] | null>()
688
+
689
+ /**
690
+ * The compact-notation unit words of a locale and their sizes, largest first: `兆` / `億` / `万` in ja,
691
+ * `T` / `B` / `M` / `K` in en. `null` when the locale's compact form puts anything between the number and its
692
+ * word (`1,5 Mio.`), where a token cannot be swapped in place.
693
+ */
694
+ function compactUnits(locale: string): CompactUnit[] | null {
695
+ const cached = compactUnitCache.get(locale)
696
+ if (cached !== undefined) return cached
697
+ let units: CompactUnit[] | null = []
698
+ try {
699
+ const compact = new Intl.NumberFormat(locale, { notation: "compact" })
700
+ const seen = new Set<string>()
701
+ for (let exp = 3; exp <= 15; exp++) {
702
+ const parts = compact.formatToParts(10 ** exp)
703
+ const at = parts.findIndex((p) => p.type === "compact")
704
+ if (at === -1) continue
705
+ if (parts[at - 1]?.type !== "integer" || at !== parts.length - 1) {
706
+ units = null
707
+ break
708
+ }
709
+ const token = parts[at]!.value
710
+ if (seen.has(token)) continue
711
+ seen.add(token)
712
+ units.push({ token, size: 10 ** exp })
713
+ }
714
+ } catch {
715
+ units = null
716
+ }
717
+ const sorted = units && units.length > 0 ? units.sort((a, b) => b.size - a.size) : null
718
+ compactUnitCache.set(locale, sorted)
719
+ return sorted
720
+ }
721
+
722
+ const escapeRegExp = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")
723
+
724
+ /**
725
+ * The value-axis tick formatter for an axis whose largest tick is `top`: every tick reads in the unit of
726
+ * that largest tick, so units never mix on one axis (`¥0.5億` / `¥1億` / `¥1.5億`, not `¥5,000万` / `¥1億`;
727
+ * `$0.5M` / `$1M` / `$1.5M`, not `$500K` / `$1M`). Only the short forms (`compact` / `number` / `currency`,
728
+ * no `valueFormatter`) have units to align; any other format — an axis whose largest tick is under the smallest
729
+ * unit (1万 / 1K), or a locale whose compact form cannot be aligned in place — keeps `resolveAxisFormatter`'s output as it is.
730
+ */
731
+ function resolveAxisTickFormatter(
732
+ valueFormatter: ValueFormatter | undefined,
733
+ format: ValueFormat | undefined,
734
+ localeArg?: string,
735
+ ): (top: number) => ValueFormatter {
736
+ const locale = resolveLocale(localeArg)
737
+ const base = resolveAxisFormatter(valueFormatter, format, locale)
738
+ const spec = format === undefined ? { type: "compact" as const } : typeof format === "string" ? { type: format } : format
739
+ const units = !valueFormatter && (spec.type === "compact" || spec.type === "number" || spec.type === "currency") ? compactUnits(locale) : null
740
+ if (!units) return () => base
741
+ const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 3 })
742
+ const numberToken = new RegExp(`\\d[\\d,]*(?:\\.\\d+)?(?:${units.map((u) => escapeRegExp(u.token)).join("|")})?`)
743
+ return (top) => {
744
+ const unit = units.find((u) => Math.abs(top) >= u.size)
745
+ if (!unit) return base
746
+ return (value) => {
747
+ const text = base(value)
748
+ if (value === 0 || !Number.isFinite(value)) return text
749
+ const scaled = `${number.format(Math.abs(value) / unit.size)}${unit.token}`
750
+ return text.replace(numberToken, () => scaled)
751
+ }
752
+ }
753
+ }
754
+
755
+ /**
756
+ * A data cell as a number, or `null` for a gap. Numeric strings count — SQL
757
+ * `DECIMAL` / `BIGINT` columns usually arrive as strings.
758
+ */
759
+ function toChartNumber(value: unknown): number | null {
760
+ if (typeof value === "number") return Number.isFinite(value) ? value : null
761
+ if (typeof value === "bigint") return Number(value)
762
+ if (typeof value === "string" && value.trim() !== "") {
763
+ const n = Number(value)
764
+ return Number.isFinite(n) ? n : null
765
+ }
766
+ return null
767
+ }
768
+
769
+ /** Clamp `value` into `[min, max]`. */
770
+ function clamp(value: number, min: number, max: number): number {
771
+ return Math.min(max, Math.max(min, value))
772
+ }
773
+
774
+ /* ------------------------------------------------------------ aggregation */
775
+
776
+ /** How many categories a chart colours individually; the rest fold into「その他」. */
777
+ const MAX_CHART_SERIES = 5
778
+
779
+ /** The series name the folded categories get, by language. */
780
+ const OTHER_SERIES_LABELS: Record<UiLanguage, string> = { ja: "その他", en: "Other" }
781
+
782
+ /** The series name the folded categories get in `locale` ("Other" / "その他"). Default the page's locale (`<html lang>`). */
783
+ function otherSeriesLabel(locale?: string): string {
784
+ return OTHER_SERIES_LABELS[uiLanguage(resolveLocale(locale))]
785
+ }
786
+
787
+ const OTHER_NAMES = new Set(Object.values(OTHER_SERIES_LABELS))
788
+
789
+ /** Whether a category / row is the "other" bucket by name (「その他」 or "Other", whatever the page language). */
790
+ function isOtherName(name: string | null | undefined): boolean {
791
+ return typeof name === "string" && OTHER_NAMES.has(name)
792
+ }
793
+
794
+ interface AggregatedItems<Item extends { name: string; value: number }> {
795
+ /** The `n` largest items, in their given order. All items when there are `n` or fewer. */
796
+ top: Item[]
797
+ /** The items folded into `other`, in their given order. */
798
+ rest: Item[]
799
+ /** The folded remainder, or `null` when nothing was folded. */
800
+ other: { name: string; value: number } | null
801
+ }
802
+
803
+ /**
804
+ * Keep the `n` largest items (by value; ties keep the earlier one) in their
805
+ * given order and fold the rest into one `otherLabel` item. Shared by every
806
+ * chart that caps its categories (Area / Line / Bar series, Donut slices,
807
+ * BarList rows).
808
+ */
809
+ function aggregateTopN<Item extends { name: string; value: number }>(
810
+ items: readonly Item[],
811
+ n: number = MAX_CHART_SERIES,
812
+ otherLabel: string = otherSeriesLabel(),
813
+ ): AggregatedItems<Item> {
814
+ if (items.length <= n) return { top: [...items], rest: [], other: null }
815
+ const ranked = items
816
+ .map((item, i) => ({ item, i }))
817
+ .sort((a, b) => b.item.value - a.item.value || a.i - b.i)
818
+ const keep = new Set(ranked.slice(0, n).map((r) => r.i))
819
+ const top = items.filter((_, i) => keep.has(i))
820
+ const rest = items.filter((_, i) => !keep.has(i))
821
+ return { top, rest, other: { name: otherLabel, value: rest.reduce((sum, item) => sum + item.value, 0) } }
822
+ }
823
+
824
+ interface AggregatedSeries {
825
+ /** Rows to draw: the input rows, plus an `otherCategory` column when categories were folded. */
826
+ data: Record<string, unknown>[]
827
+ /** Series to draw: the kept categories in their given order, then `otherCategory`. */
828
+ categories: string[]
829
+ /** The folded series' name, or `null`. */
830
+ otherCategory: string | null
831
+ }
832
+
833
+ /**
834
+ * Cap a cartesian chart at `n` series: rank the categories by the sum of their
835
+ * values, keep the top `n` and add a per-row sum of the rest as `otherLabel`.
836
+ */
837
+ function aggregateSeries(
838
+ data: readonly Record<string, unknown>[],
839
+ categories: readonly string[],
840
+ n: number = MAX_CHART_SERIES,
841
+ otherLabel: string = otherSeriesLabel(),
842
+ ): AggregatedSeries {
843
+ const totals = categories.map((name) => ({
844
+ name,
845
+ value: data.reduce((sum, row) => sum + (toChartNumber(row[name]) ?? 0), 0),
846
+ }))
847
+ const { top, rest, other } = aggregateTopN(totals, n, otherLabel)
848
+ if (!other) return { data: [...data], categories: [...categories], otherCategory: null }
849
+ const folded = rest.map((item) => item.name)
850
+ return {
851
+ data: data.map((row) => {
852
+ let sum: number | null = null
853
+ for (const name of folded) {
854
+ const v = toChartNumber(row[name])
855
+ if (v !== null) sum = (sum ?? 0) + v
856
+ }
857
+ return { ...row, [other.name]: sum }
858
+ }),
859
+ categories: [...top.map((item) => item.name), other.name],
860
+ otherCategory: other.name,
861
+ }
862
+ }
863
+
864
+ /**
865
+ * `aggregateSeries` that never folds `keep` (a comparison series) into「その他」: the others are capped
866
+ * at `n` as usual and `keep` is appended last, so it is drawn on top of the cap and never takes the first slot.
867
+ */
868
+ function aggregateSeriesKeeping(
869
+ data: readonly Record<string, unknown>[],
870
+ categories: readonly string[],
871
+ keep: string | undefined,
872
+ n: number = MAX_CHART_SERIES,
873
+ otherLabel: string = otherSeriesLabel(),
874
+ ): AggregatedSeries {
875
+ if (keep === undefined || !categories.includes(keep)) return aggregateSeries(data, categories, n, otherLabel)
876
+ const aggregated = aggregateSeries(
877
+ data,
878
+ categories.filter((c) => c !== keep),
879
+ n,
880
+ otherLabel,
881
+ )
882
+ return { ...aggregated, categories: [...aggregated.categories, keep] }
883
+ }
884
+
885
+ /**
886
+ * `seriesColorsFor` for a chart with a comparison series: the comparison takes no `--chart-*` token (the
887
+ * builder paints it in muted grey; its slot here is `""`), and the others are assigned as if it were absent,
888
+ * so a main series keeps its colour whether or not a comparison is drawn.
889
+ */
890
+ function seriesColorsWithComparison(
891
+ categories: readonly string[],
892
+ colors: ChartColors | undefined,
893
+ otherColor: string,
894
+ otherCategory: string | null,
895
+ allCategories: readonly string[],
896
+ comparison: string | undefined,
897
+ ): string[] {
898
+ if (comparison === undefined || !categories.includes(comparison)) {
899
+ return seriesColorsFor(categories, colors, otherColor, otherCategory, allCategories)
900
+ }
901
+ const main = categories.filter((c) => c !== comparison)
902
+ const mainColors = seriesColorsFor(
903
+ main,
904
+ colors,
905
+ otherColor,
906
+ otherCategory,
907
+ allCategories.filter((c) => c !== comparison),
908
+ )
909
+ return categories.map((c) => (c === comparison ? "" : (mainColors[main.indexOf(c)] ?? "")))
910
+ }
911
+
912
+ /**
913
+ * Colour per drawn series: the record's token for that category, else the
914
+ * array's token at the category's position in `allCategories` (cycled), else
915
+ * the token palette by drawn position. `otherCategory` — and a category the
916
+ * data itself names「その他」/ "Other" (`OTHER_SERIES_LABELS`) — always gets `otherColor`.
917
+ */
918
+ function seriesColorsFor(
919
+ categories: readonly string[],
920
+ colors: ChartColors | undefined,
921
+ otherColor: string,
922
+ otherCategory: string | null = null,
923
+ allCategories: readonly string[] = categories,
924
+ ): string[] {
925
+ const list = Array.isArray(colors) ? (colors as ChartSeriesColor[]) : undefined
926
+ const record = !Array.isArray(colors) && colors ? (colors as Partial<Record<string, ChartSeriesColor>>) : undefined
927
+ return categories.map((category, i) => {
928
+ if ((otherCategory !== null && category === otherCategory) || isOtherName(category)) return otherColor
929
+ const fromRecord = record?.[category]
930
+ if (fromRecord) return fromRecord
931
+ if (list && list.length > 0) {
932
+ const at = allCategories.indexOf(category)
933
+ return list[(at === -1 ? i : at) % list.length]!
934
+ }
935
+ return DEFAULT_CHART_COLORS[i % DEFAULT_CHART_COLORS.length]!
936
+ })
937
+ }
938
+
939
+ /* ------------------------------------------------------------------ Donut */
940
+
941
+ /** One drawn donut slice, largest first. */
942
+ interface DonutSlice {
943
+ name: string
944
+ /** Negative and missing values count as 0. */
945
+ value: number
946
+ /** A chart token (`"chart-1"`…), or `otherColor` for the folded slice. */
947
+ color: string
948
+ /** The folded「その他」slice. */
949
+ isOther: boolean
950
+ /** The input row, or a synthesized `{ [index]: "その他", [value]: sum }` for the folded slice. */
951
+ row: Record<string, unknown>
952
+ }
953
+
954
+ interface DonutSlicesConfig {
955
+ /** Label column. */
956
+ index: string
957
+ /** Value column. */
958
+ value: string
959
+ /** Slice colours by rank (cycled). Default: the token palette in order. */
960
+ colors?: readonly ChartSeriesColor[]
961
+ /** How many slices are drawn individually; the rest fold into「その他」. Default 5. */
962
+ maxSlices?: number
963
+ /** Colour of the folded slice (pass `CHART_OTHER_COLOR`). */
964
+ otherColor: string
965
+ otherLabel?: string
966
+ }
967
+
968
+ /**
969
+ * Donut slices: sorted by value (largest first, ties keep input order), the
970
+ * `maxSlices` largest kept and coloured by rank in fixed token order, the rest
971
+ * summed into one「その他」slice in `otherColor`.
972
+ */
973
+ function donutSlices(
974
+ data: readonly Record<string, unknown>[],
975
+ { index, value, colors, maxSlices = MAX_CHART_SERIES, otherColor, otherLabel = otherSeriesLabel() }: DonutSlicesConfig,
976
+ ): DonutSlice[] {
977
+ const items = data
978
+ .map((row, i) => {
979
+ const n = toChartNumber(row[value])
980
+ return { name: String(row[index] ?? ""), value: n !== null && n > 0 ? n : 0, row, i }
981
+ })
982
+ .sort((a, b) => b.value - a.value || a.i - b.i)
983
+ const { top, other } = aggregateTopN(items, Math.max(1, maxSlices), otherLabel)
984
+ const palette = colors && colors.length > 0 ? colors : DEFAULT_CHART_COLORS
985
+ const slices: DonutSlice[] = top.map((item, rank) => ({
986
+ name: item.name,
987
+ value: item.value,
988
+ // A row the data itself names「その他」/ "Other" is the same remainder: grey, like the folded slice.
989
+ color: isOtherName(item.name) ? otherColor : palette[rank % palette.length]!,
990
+ isOther: false,
991
+ row: item.row,
992
+ }))
993
+ if (other) {
994
+ slices.push({
995
+ name: other.name,
996
+ value: other.value,
997
+ color: otherColor,
998
+ isOther: true,
999
+ row: { [index]: other.name, [value]: other.value },
1000
+ })
1001
+ }
1002
+ return slices
1003
+ }
1004
+
1005
+ /* ---------------------------------------------------------------- BarList */
1006
+
1007
+ type BarListSortOrder = "ascending" | "descending" | "none"
1008
+
1009
+ /** Sort a copy of the rows by value; `"none"` keeps the given order. */
1010
+ function sortBarListData<T extends { value: number }>(data: readonly T[], sortOrder: BarListSortOrder): T[] {
1011
+ const rows = [...data]
1012
+ if (sortOrder === "ascending") rows.sort((a, b) => a.value - b.value)
1013
+ else if (sortOrder === "descending") rows.sort((a, b) => b.value - a.value)
1014
+ return rows
1015
+ }
1016
+
1017
+ /** BarList-only settings. */
1018
+ interface BarListOptions {
1019
+ /** 並べ順。既定 `"descending"`(大きい順)。`"none"` は渡した順。「その他」は常に最後。 */
1020
+ sortOrder?: BarListSortOrder
1021
+ /** 個別に出す行の数。超えた分は合計して「その他」の 1 行にまとめる。既定 5。 */
1022
+ maxItems?: number
1023
+ /** まとめた行のラベル。既定「その他」。 */
1024
+ otherLabel?: string
1025
+ /** 順位に入れず、常に「その他」へ足す行の名前。例 `["(not set)", "Unassigned"]`。 */
1026
+ exclude?: readonly string[]
1027
+ /** 値の横に構成比(「その他」も含めた全行の合計に対する割合。整数 %)を添える。例「¥8,240万 · 43%」。既定 `false`。 */
1028
+ showShare?: boolean
1029
+ }
1030
+
1031
+ /** One drawn BarList row. */
1032
+ interface BarListRow<Row = Record<string, unknown>> {
1033
+ /** React key: the row's `key`, else its name (`"__other"` for the folded row). */
1034
+ key: string
1035
+ name: string
1036
+ value: number
1037
+ /** Only for real rows; the folded row never links. */
1038
+ href?: string
1039
+ /** Legacy per-row colour (`BarListItem.color`). */
1040
+ color?: ChartColor
1041
+ /** The folded「その他」row. */
1042
+ isOther: boolean
1043
+ /** The input row (`null` for the folded row). */
1044
+ row: Row | null
1045
+ }
1046
+
1047
+ interface BarListRowsConfig extends BarListOptions {
1048
+ /** Name column. Default `"name"`. */
1049
+ index?: string
1050
+ /** Value column. Default `"value"`. */
1051
+ category?: string
1052
+ }
1053
+
1054
+ /**
1055
+ * The rows a BarList draws: read name / value (numeric strings count, gaps are
1056
+ * 0), keep the `maxItems` largest (via `aggregateTopN`), sort them, and append
1057
+ * the folded remainder as one「その他」row. Rows named in `exclude` skip the
1058
+ * ranking and are always added to「その他」.
1059
+ */
1060
+ function barListRows<Row extends object>(
1061
+ data: readonly Row[],
1062
+ { index = "name", category = "value", sortOrder = "descending", maxItems = MAX_CHART_SERIES, otherLabel = otherSeriesLabel(), exclude }: BarListRowsConfig = {},
1063
+ ): BarListRow<Row>[] {
1064
+ const items = data.map((row): BarListRow<Row> => {
1065
+ const cells = row as Record<string, unknown>
1066
+ const name = String(cells[index] ?? "")
1067
+ return {
1068
+ key: typeof cells.key === "string" ? cells.key : name,
1069
+ name,
1070
+ value: toChartNumber(cells[category]) ?? 0,
1071
+ href: typeof cells.href === "string" ? cells.href : undefined,
1072
+ color: typeof cells.color === "string" ? cells.color : undefined,
1073
+ isOther: false,
1074
+ row,
1075
+ }
1076
+ })
1077
+ const excluded = new Set(exclude ?? [])
1078
+ const ranked = excluded.size > 0 ? items.filter((item) => !excluded.has(item.name)) : items
1079
+ const outside = excluded.size > 0 ? items.filter((item) => excluded.has(item.name)) : []
1080
+ const { top, other } = aggregateTopN(ranked, Math.max(0, maxItems), otherLabel)
1081
+ const rows = sortBarListData(top, sortOrder)
1082
+ if (other || outside.length > 0) {
1083
+ const value = (other?.value ?? 0) + outside.reduce((sum, item) => sum + item.value, 0)
1084
+ rows.push({ key: "__other", name: otherLabel, value, isOther: true, row: null })
1085
+ }
1086
+ return rows
1087
+ }
1088
+
1089
+ /** Bar widths in percent of the largest value (at least a sliver for non-zero values). */
1090
+ function barListWidths(values: readonly number[]): number[] {
1091
+ const max = Math.max(0, ...values)
1092
+ if (max === 0) return values.map(() => 0)
1093
+ return values.map((v) => (v <= 0 ? 0 : Math.max(1, (v / max) * 100)))
1094
+ }
1095
+
1096
+ /**
1097
+ * How strongly the BarList bars are painted: every row the same tint of the bar
1098
+ * colour (rank is the bar's length, not its weight). A tint over transparent, so
1099
+ * it sits on the card in light and dark; it must stay visible against the card
1100
+ * while the label printed over the bar keeps its contrast (see `tests/contrast.test.ts`).
1101
+ */
1102
+ const BAR_LIST_TINT = 45
1103
+ /** 「その他」: a tint of the other colour, so it is the palest fill in the list (light and dark). */
1104
+ const BAR_LIST_OTHER_TINT = 30
1105
+
1106
+ /**
1107
+ * The fill of each BarList row: all real rows in the same tint of `color`
1108
+ * (`BAR_LIST_TINT`), the folded「その他」row (and a row the data names「その他」/ "Other") in a tint of `otherColor`
1109
+ * (`BAR_LIST_OTHER_TINT`) — the palest fill, a remainder never outweighs a
1110
+ * ranked row. A legacy per-row `color` (or a threshold tone) replaces `color`
1111
+ * for that row. A tint, not the solid token, so the label printed over the bar
1112
+ * keeps its contrast.
1113
+ */
1114
+ function barListFills(
1115
+ rows: readonly (Pick<BarListRow, "isOther" | "color"> & { name?: string })[],
1116
+ color: ChartColor,
1117
+ otherColor: string,
1118
+ ): string[] {
1119
+ return rows.map((row) =>
1120
+ row.isOther || isOtherName(row.name)
1121
+ ? tintCss(otherColor, BAR_LIST_OTHER_TINT)
1122
+ : tintCss(chartColorToCss(row.color ?? color), BAR_LIST_TINT),
1123
+ )
1124
+ }
1125
+
1126
+ /** A row's share of `total` as text: whole percent (fixed, no decimals), `<1%` for a sliver, `0%` for nothing. */
1127
+ function barListShareText(value: number, total: number): string {
1128
+ const v = Number.isFinite(value) && value > 0 ? value : 0
1129
+ if (total <= 0 || v === 0) return "0%"
1130
+ const pct = (v / total) * 100
1131
+ return pct < 1 ? "<1%" : `${Math.round(pct)}%`
1132
+ }
1133
+
1134
+ /**
1135
+ * The text at the end of each BarList row: the formatted value and, with
1136
+ * `showShare`, its share of the total of all drawn rows (including「その他」,
1137
+ * so the shares are of the whole list): `value` and `share` apart (the share is
1138
+ * drawn muted), `text` as one string (「¥8,240万 · 43%」).
1139
+ */
1140
+ function barListValueTexts(
1141
+ values: readonly number[],
1142
+ formatter: ValueFormatter,
1143
+ showShare = false,
1144
+ ): { value: string; share?: string; text: string }[] {
1145
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1146
+ return values.map((v) => {
1147
+ const value = formatter(v)
1148
+ if (!showShare) return { value, text: value }
1149
+ const share = barListShareText(v, total)
1150
+ return { value, share, text: `${value} · ${share}` }
1151
+ })
1152
+ }
1153
+
1154
+ /* -------------------------------------------------------------- DataTable */
1155
+
1156
+ /** The visually-hidden table `ChartFrame` renders next to the plot (`dataTable`). */
1157
+ interface ChartDataTable {
1158
+ /** 表の見出し(`<caption>`)。 */
1159
+ caption?: string
1160
+ /** 列見出し。先頭がラベル列。 */
1161
+ columns: string[]
1162
+ /** 行。セルは書式済みの文字列。 */
1163
+ rows: string[][]
1164
+ }
1165
+
1166
+ /**
1167
+ * The chart's numbers as a table, for screen readers: one row per data row, the
1168
+ * `index` cell then each category through `formatter` (gaps → `—`). `labels`
1169
+ * 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).
1170
+ */
1171
+ function chartDataTable(
1172
+ data: readonly Record<string, unknown>[],
1173
+ index: string,
1174
+ categories: readonly string[],
1175
+ formatter: ValueFormatter,
1176
+ labels?: Readonly<Record<string, string>>,
1177
+ indexName?: string,
1178
+ ): ChartDataTable {
1179
+ const label = (key: string) => labels?.[key] ?? key
1180
+ return {
1181
+ columns: [labels?.[index] ?? indexName ?? index, ...categories.map(label)],
1182
+ rows: data.map((row) => [
1183
+ String(row[index] ?? ""),
1184
+ ...categories.map((key) => {
1185
+ const n = toChartNumber(row[key])
1186
+ return n === null ? EMPTY_VALUE : formatter(n)
1187
+ }),
1188
+ ]),
1189
+ }
1190
+ }
1191
+
1192
+ /* ------------------------------------------------------------ CategoryBar */
1193
+
1194
+ interface CategoryBarSegment {
1195
+ /** Width in percent of the whole bar. */
1196
+ width: number
1197
+ /** Where the segment starts, in percent. */
1198
+ start: number
1199
+ /** The running total at the segment's end — what its right-hand label shows. */
1200
+ end: number
1201
+ }
1202
+
1203
+ /** Lay the values side by side; negative values count as zero. */
1204
+ function categoryBarSegments(values: readonly number[]): CategoryBarSegment[] {
1205
+ const clean = values.map((v) => (Number.isFinite(v) && v > 0 ? v : 0))
1206
+ const total = clean.reduce((sum, v) => sum + v, 0)
1207
+ let running = 0
1208
+ return clean.map((v) => {
1209
+ const start = total === 0 ? 0 : (running / total) * 100
1210
+ running += v
1211
+ return { width: total === 0 ? 0 : (v / total) * 100, start, end: running }
1212
+ })
1213
+ }
1214
+
1215
+ interface CategoryBarLabel {
1216
+ /** Position in percent of the bar. */
1217
+ position: number
1218
+ /** The running total printed there. */
1219
+ value: number
1220
+ }
1221
+
1222
+ /**
1223
+ * Tick labels under the bar: `0` at the start, then the running total at each
1224
+ * segment's end. A label closer than `minGap` percent to the one before is
1225
+ * dropped so narrow segments don't print on top of each other — except the
1226
+ * last one (the total), which replaces its neighbour instead. With a
1227
+ * `markerPosition`, an inner label closer than `minGap` to the marker is dropped
1228
+ * too — the marker sits right under it and the two read as one crowded spot.
1229
+ */
1230
+ function categoryBarLabels(values: readonly number[], minGap = 8, markerPosition?: number): CategoryBarLabel[] {
1231
+ const segments = categoryBarSegments(values).filter((s) => s.width > 0)
1232
+ if (segments.length === 0) return []
1233
+ const labels: CategoryBarLabel[] = [{ position: 0, value: 0 }]
1234
+ segments.forEach((s, i) => {
1235
+ const label = { position: s.start + s.width, value: s.end }
1236
+ const prev = labels[labels.length - 1]!
1237
+ if (label.position - prev.position >= minGap) labels.push(label)
1238
+ else if (i === segments.length - 1 && labels.length > 1) labels[labels.length - 1] = label
1239
+ })
1240
+ if (markerPosition === undefined || !Number.isFinite(markerPosition)) return labels
1241
+ return labels.filter(
1242
+ (label, i) => i === 0 || i === labels.length - 1 || Math.abs(label.position - markerPosition) >= minGap,
1243
+ )
1244
+ }
1245
+
1246
+ /**
1247
+ * `labels` thinned to what fits side by side on a bar `width` px wide, given each label's printed text
1248
+ * (`texts`, same order): a label that would touch the one before is dropped — except the last (the
1249
+ * total), which replaces its neighbour instead. The first sits at the left edge, the last at the right
1250
+ * edge, the rest centred on their position. The width is a rough estimate (full-width characters 12 px,
1251
+ * the rest 7 px at 12 px type).
1252
+ */
1253
+ function categoryBarFitLabels(
1254
+ labels: readonly CategoryBarLabel[],
1255
+ texts: readonly string[],
1256
+ width: number,
1257
+ gap = 8,
1258
+ ): CategoryBarLabel[] {
1259
+ const textWidth = (text: string) => {
1260
+ let w = 0
1261
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1262
+ return w
1263
+ }
1264
+ const extent = (label: CategoryBarLabel, text: string): [number, number] => {
1265
+ const w = textWidth(text)
1266
+ if (label.position <= 0) return [0, w]
1267
+ if (label.position >= 100) return [width - w, width]
1268
+ const center = (label.position / 100) * width
1269
+ return [center - w / 2, center + w / 2]
1270
+ }
1271
+ const kept: { label: CategoryBarLabel; extent: [number, number] }[] = []
1272
+ labels.forEach((label, i) => {
1273
+ const here = extent(label, texts[i] ?? "")
1274
+ const touches = () => kept.length > 0 && kept[kept.length - 1]!.extent[1] + gap > here[0]
1275
+ if (i === labels.length - 1) while (kept.length > 1 && touches()) kept.pop()
1276
+ else if (touches()) return
1277
+ kept.push({ label, extent: here })
1278
+ })
1279
+ return kept.map((k) => k.label)
1280
+ }
1281
+
1282
+ /** Marker position in percent of the bar, clamped to its ends. */
1283
+ function categoryBarMarkerPosition(value: number, values: readonly number[]): number {
1284
+ const total = values.reduce((sum, v) => sum + (Number.isFinite(v) && v > 0 ? v : 0), 0)
1285
+ if (total === 0) return 0
1286
+ return clamp((value / total) * 100, 0, 100)
1287
+ }
1288
+
1289
+ /** Index of the segment the marker sits on (the last one for a value past the end). */
1290
+ function categoryBarMarkerSegment(value: number, values: readonly number[]): number {
1291
+ const segments = categoryBarSegments(values)
1292
+ const index = segments.findIndex((s) => s.width > 0 && value <= s.end)
1293
+ if (index !== -1) return index
1294
+ for (let i = segments.length - 1; i >= 0; i--) if (segments[i]!.width > 0) return i
1295
+ return 0
1296
+ }
1297
+
1298
+ /* --------------------------------------------------------- ProgressCircle */
1299
+
1300
+ interface ProgressCircleGeometry {
1301
+ /** SVG width/height. */
1302
+ size: number
1303
+ /** Radius of the stroke's centre line. */
1304
+ normalizedRadius: number
1305
+ circumference: number
1306
+ /** `stroke-dashoffset` for the value arc. */
1307
+ offset: number
1308
+ /** The value as a fraction of `max`, clamped to `[0, 1]`. */
1309
+ ratio: number
1310
+ }
1311
+
1312
+ function progressCircleGeometry(
1313
+ value: number,
1314
+ max: number,
1315
+ radius: number,
1316
+ strokeWidth: number,
1317
+ ): ProgressCircleGeometry {
1318
+ const ratio = max > 0 && Number.isFinite(value) ? clamp(value / max, 0, 1) : 0
1319
+ const normalizedRadius = Math.max(0, radius - strokeWidth / 2)
1320
+ const circumference = 2 * Math.PI * normalizedRadius
1321
+ return { size: radius * 2, normalizedRadius, circumference, offset: circumference * (1 - ratio), ratio }
1322
+ }
1323
+
1324
+ /* ---------------------------------------------------------------- summary */
1325
+
1326
+ interface ChartSummaryInput {
1327
+ data: readonly Record<string, unknown>[]
1328
+ /** The x-axis key. */
1329
+ index: string
1330
+ /** Series keys; the first one is described. */
1331
+ categories: readonly string[]
1332
+ /** Title of the chart, put in front when given. */
1333
+ title?: string
1334
+ /** Same as the chart's `format` (default `"compact"`). */
1335
+ format?: ValueFormat
1336
+ /** Wins over `format`. */
1337
+ valueFormatter?: ValueFormatter
1338
+ /** Language of the sentence. Default the page's locale (`<html lang>`). */
1339
+ locale?: string
1340
+ }
1341
+
1342
+ const SUMMARY_TEXT = {
1343
+ ja: {
1344
+ up: "、前の点より増加",
1345
+ down: "、前の点より減少",
1346
+ flat: "、前の点と横ばい",
1347
+ latest: (label: string, value: string) => `最新 ${label} は ${value}`,
1348
+ top: (name: string, share: string) => `最大は ${name}(${share})`,
1349
+ },
1350
+ en: {
1351
+ up: ", up from the previous point",
1352
+ down: ", down from the previous point",
1353
+ flat: ", flat from the previous point",
1354
+ latest: (label: string, value: string) => `Latest ${label}: ${value}`,
1355
+ top: (name: string, share: string) => `Largest: ${name} (${share})`,
1356
+ },
1357
+ }
1358
+
1359
+ /**
1360
+ * One-sentence summary built from the rows, for `summary="auto"`:
1361
+ * 「<title>: 最新 <index> は <値>、前の点より増加/減少/横ばい」("<title>: Latest <index>: <value>, up from the previous point"). The direction is
1362
+ * computed from the last two non-empty points of the first series — never
1363
+ * written by hand, so it cannot contradict the data. `undefined` when there is
1364
+ * no usable point.
1365
+ */
1366
+ function buildChartSummary(input: ChartSummaryInput): string | undefined {
1367
+ const key = input.categories[0]
1368
+ if (key === undefined) return undefined
1369
+ const points: { label: string; value: number }[] = []
1370
+ for (const row of input.data) {
1371
+ const raw = row[key]
1372
+ const value = raw === null || raw === undefined || raw === "" ? NaN : Number(raw)
1373
+ if (Number.isFinite(value)) points.push({ label: String(row[input.index] ?? ""), value })
1374
+ }
1375
+ const latest = points[points.length - 1]
1376
+ if (!latest) return undefined
1377
+ const locale = resolveLocale(input.locale)
1378
+ const t = SUMMARY_TEXT[uiLanguage(locale)]
1379
+ const text = input.valueFormatter ?? toValueFormatter(input.format ?? "compact", locale)
1380
+ const prev = points[points.length - 2]
1381
+ const direction = !prev ? "" : latest.value > prev.value ? t.up : latest.value < prev.value ? t.down : t.flat
1382
+ const head = input.title ? `${input.title}: ` : ""
1383
+ return `${head}${t.latest(latest.label, text(latest.value))}${direction}`
1384
+ }
1385
+
1386
+ /**
1387
+ * `summary="auto"` for a donut: 「<title>: 最大は <名前>(<構成比>)」("<title>: Largest: <name> (<share>)") from the slices
1388
+ * (largest first). `undefined` when there is nothing to describe. `locale` picks the language; default the page's.
1389
+ */
1390
+ function buildShareSummary(
1391
+ slices: readonly { name: string; value: number }[],
1392
+ title?: string,
1393
+ locale?: string,
1394
+ ): string | undefined {
1395
+ const total = slices.reduce((sum, s) => sum + s.value, 0)
1396
+ const top = slices[0]
1397
+ if (!top || total <= 0) return undefined
1398
+ const share = `${Math.round((top.value / total) * 1000) / 10}%`
1399
+ return `${title ? `${title}: ` : ""}${SUMMARY_TEXT[uiLanguage(resolveLocale(locale))].top(top.name, share)}`
1400
+ }
1401
+
1402
+ /* ---------- end of inlined code ---------- */
1403
+
1404
+ // HeatmapChart and the (hidden) visual map that shades the cells are this part's own.
1405
+ use([HeatmapChart, VisualMapComponent])
1406
+
1407
+ /** The lightest end of the ramp is this share of the tone colour mixed into the surface; the darkest end is the colour itself. */
1408
+ export const HEATMAP_FLOOR_SHARE = 0.2
1409
+ /** Cells at or above this share of the ramp get the surface colour as text (dark cell), below it the foreground. */
1410
+ export const HEATMAP_LIGHT_TEXT_FROM = 0.55
1411
+
1412
+ /** Columns of `T` that hold numbers (null / undefined allowed for gaps); untyped rows keep every key. */
1413
+ type NumericColumn<T> = {
1414
+ [K in keyof T]-?: unknown extends T[K] ? K : T[K] extends number | bigint | null | undefined ? K : never
1415
+ }[keyof T] &
1416
+ string
1417
+
1418
+ export interface HeatmapProps<T extends Record<string, unknown> = Record<string, unknown>> extends ChartRootAttributes {
1419
+ /** 行の配列。1 行 = 1 マス(x と y の組)。同じ組が複数あれば後の行が勝つ。値は number か数値文字列。 */
1420
+ data: T[]
1421
+ /** 横軸(列)に使う列名。例 `"hour"`・`"week"`。 */
1422
+ x: keyof T & string
1423
+ /** 縦軸(行)に使う列名。例 `"weekday"`・`"cohort"`。先頭の行が一番上。 */
1424
+ y: keyof T & string
1425
+ /** マスの濃さを決める数値の列名。null・欠損・数値でない値のマスは塗らない(0 とは別。ツールチップとデータ表は「—」)。 */
1426
+ value: NumericColumn<T>
1427
+ /** 横軸の並び順(と表示するマス)。省略時は `data` の出現順。ここに無い x の行は描かない。 */
1428
+ xLabels?: string[]
1429
+ /** 縦軸の並び順(と表示するマス)。省略時は `data` の出現順。ここに無い y の行は描かない。 */
1430
+ yLabels?: string[]
1431
+ /**
1432
+ * 列名・軸の値 → 表示名(軸・ツールチップ・データ表に反映)。
1433
+ * 例 `{ mon: "月曜", value: "件数", breached: "SLA 未達" }`。無いキーはそのまま。データ表の先頭列名は `y` のキーを渡すと直る(既定は「項目」)。
1434
+ */
1435
+ labels?: Record<string, string>
1436
+ /** 数値の書式(`"number"` / `"percent"` / `{ type: "number", unit: "件" }` など)。マス内・ツールチップ・データ表で同じ書式。既定 `"number"`。 */
1437
+ format?: ValueFormat
1438
+ /** 書式を関数で直接渡す逃げ道。`format` より優先する。 */
1439
+ valueFormatter?: ValueFormatter
1440
+ /**
1441
+ * 濃淡の色。`"chart-1"`〜`"chart-5"` か意味色(`"positive"` / `"warning"` / `"negative"` / `"neutral"`)。
1442
+ * 薄い → 濃いの単色グラデーション(レインボーにしない)。既定 `"chart-1"`。
1443
+ */
1444
+ tone?: ChartSeriesColor
1445
+ /**
1446
+ * 濃さの固定スケール。省略時はデータの最小〜最大(自動)。比べたい上限・下限が決まっているときだけ渡す。`min` 以下が最も薄く、`max` 以上が最も濃い(範囲外の値は端に丸める)。凡例の両端もこの値になる。
1447
+ * 継続率(0〜100)なら `{ min: 0, max: 100 }`。片方だけでもよく、省略した側はデータの最小・最大。
1448
+ * `minValue` / `maxValue` より優先する。
1449
+ */
1450
+ scale?: { min?: number; max?: number }
1451
+ /** @deprecated `scale={{ min }}` を使う。濃さの下限(この値以下が最も薄い)。 */
1452
+ minValue?: number
1453
+ /** @deprecated `scale={{ max }}` を使う。濃さの上限(この値以上が最も濃い)。 */
1454
+ maxValue?: number
1455
+ /** マスの中に値を書く(`format` どおり)。既定 `false`。 */
1456
+ showValues?: boolean
1457
+ /** 凡例(薄い → 濃いの帯と両端の値)を出す。既定 `true`。 */
1458
+ showLegend?: boolean
1459
+ /** ホバーでツールチップを出す。既定 `true`。 */
1460
+ showTooltip?: boolean
1461
+ /**
1462
+ * ツールチップとデータ表に添える列(同じ行の別の数値)。例 `["breached"]` →「月曜 9時台 電話 12件・SLA 未達 2件」の「SLA 未達 2件」。
1463
+ * 列名の表示は `labels`、値は `format`(単位つきの書式なら同じ単位)で出る。
1464
+ */
1465
+ details?: NumericColumn<T>[]
1466
+ /**
1467
+ * この列が真(`true` / 0 でない数)の行のマスに、注意色(`--negative`)の枠を付ける。
1468
+ * 例 SLA 未達が集中したマス。色だけでなく枠の太さでも区別でき、ツールチップに「要注意」と出る。
1469
+ */
1470
+ flag?: keyof T & string
1471
+ /** グラフの見出し。 */
1472
+ title?: string
1473
+ /** グラフが言っていることの 1 文要約。`"auto"` で最大のマスから自動生成。 */
1474
+ summary?: string | "auto"
1475
+ /** 読み込み中。最終形と同じ高さのスケルトンを出す。 */
1476
+ isLoading?: boolean
1477
+ /** `data` が空のときの表示。 */
1478
+ emptyState?: ChartEmptyState
1479
+ /** プロット領域の高さ(px)。既定 288。 */
1480
+ height?: number
1481
+ /** 生成した EChartsOption に最後に深くマージする逃げ道。 */
1482
+ chartOptions?: EChartsOption
1483
+ /** グラフ右上に PNG 保存/コピーのボタンを出す。見出しがあれば PNG の上に含める(`{ includeTitle: false }` で含めない)。 */
1484
+ actions?: boolean | ChartActionsOptions
1485
+ /** PNG 保存時のファイル名(拡張子つき)。 */
1486
+ fileName?: string
1487
+ className?: string
1488
+ /** スクリーンリーダー向けのラベル。省略時は `<yの列>×<xの列>のヒートマップ`。 */
1489
+ ariaLabel?: string
1490
+ }
1491
+
1492
+ /* ------------------------------------------------------------------ model */
1493
+
1494
+ export interface HeatmapCell {
1495
+ /** Index into `xs`. */
1496
+ xi: number
1497
+ /** Index into `ys`. */
1498
+ yi: number
1499
+ /** `null` for a gap. */
1500
+ value: number | null
1501
+ flagged: boolean
1502
+ row: Record<string, unknown> | null
1503
+ }
1504
+
1505
+ export interface HeatmapModel {
1506
+ xs: string[]
1507
+ ys: string[]
1508
+ /** One per grid position (`xs.length * ys.length`), row-major by y. */
1509
+ cells: HeatmapCell[]
1510
+ min: number
1511
+ max: number
1512
+ hasGap: boolean
1513
+ }
1514
+
1515
+ function truthy(raw: unknown): boolean {
1516
+ if (typeof raw === "number") return raw !== 0 && !Number.isNaN(raw)
1517
+ return raw === true || raw === "true"
1518
+ }
1519
+
1520
+ /** Rows → the grid: axes in order, one cell per (x, y) with `null` for gaps, and the shading range. */
1521
+ export function buildHeatmapModel(config: {
1522
+ data: readonly Record<string, unknown>[]
1523
+ x: string
1524
+ y: string
1525
+ value: string
1526
+ xLabels?: readonly string[]
1527
+ yLabels?: readonly string[]
1528
+ flag?: string
1529
+ scale?: { min?: number; max?: number }
1530
+ /** @deprecated Use `scale`. */
1531
+ minValue?: number
1532
+ /** @deprecated Use `scale`. */
1533
+ maxValue?: number
1534
+ }): HeatmapModel {
1535
+ const { data, x, y, value, flag } = config
1536
+ const order = (key: string, given: readonly string[] | undefined) => {
1537
+ if (given) return [...given]
1538
+ const seen: string[] = []
1539
+ for (const row of data) {
1540
+ const k = String(row[key] ?? "")
1541
+ if (!seen.includes(k)) seen.push(k)
1542
+ }
1543
+ return seen
1544
+ }
1545
+ const xs = order(x, config.xLabels)
1546
+ const ys = order(y, config.yLabels)
1547
+ const byCell = new Map<string, Record<string, unknown>>()
1548
+ for (const row of data) byCell.set(`${String(row[x] ?? "")}\u0000${String(row[y] ?? "")}`, row)
1549
+ const cells: HeatmapCell[] = []
1550
+ let lo = Infinity
1551
+ let hi = -Infinity
1552
+ let hasGap = false
1553
+ ys.forEach((yk, yi) =>
1554
+ xs.forEach((xk, xi) => {
1555
+ const row = byCell.get(`${xk}\u0000${yk}`) ?? null
1556
+ const n = row ? toChartNumber(row[value]) : null
1557
+ if (n === null) hasGap = true
1558
+ else {
1559
+ lo = Math.min(lo, n)
1560
+ hi = Math.max(hi, n)
1561
+ }
1562
+ cells.push({ xi, yi, value: n, flagged: !!(row && flag && truthy(row[flag])), row })
1563
+ }),
1564
+ )
1565
+ const min = config.scale?.min ?? config.minValue ?? (Number.isFinite(lo) ? lo : 0)
1566
+ let max = config.scale?.max ?? config.maxValue ?? (Number.isFinite(hi) ? hi : 1)
1567
+ if (max <= min) max = min + 1
1568
+ return { xs, ys, cells, min, max, hasGap }
1569
+ }
1570
+
1571
+ /** The share (0–1) of the ramp a value sits at. */
1572
+ export function heatmapRatio(value: number, min: number, max: number): number {
1573
+ return max > min ? Math.min(1, Math.max(0, (value - min) / (max - min))) : 1
1574
+ }
1575
+
1576
+ /** A canvas-safe colour (`#rrggbb` / `rgb()` / `rgba()`) at `alpha`; anything else comes back unchanged. */
1577
+ export function withAlpha(color: string, alpha: number): string {
1578
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1579
+ if (hex) {
1580
+ const n = parseInt(hex[1]!, 16)
1581
+ return `rgba(${(n >> 16) & 255}, ${(n >> 8) & 255}, ${n & 255}, ${alpha})`
1582
+ }
1583
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1584
+ return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, ${alpha})` : color
1585
+ }
1586
+
1587
+ /** `#rrggbb` / `rgb()` / `rgba()` → [r, g, b] (0–255), or null. */
1588
+ function parseRgb(color: string): [number, number, number] | null {
1589
+ const hex = /^#([0-9a-f]{6})$/i.exec(color.trim())
1590
+ if (hex) {
1591
+ const n = parseInt(hex[1]!, 16)
1592
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255]
1593
+ }
1594
+ const rgb = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(color.trim())
1595
+ return rgb ? [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])] : null
1596
+ }
1597
+
1598
+ const toLinear = (c: number) => ((c /= 255) <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)
1599
+ const fromLinear = (c: number) => Math.round(255 * Math.min(1, Math.max(0, c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055)))
1600
+
1601
+ function toOklab([r, g, b]: [number, number, number]): [number, number, number] {
1602
+ const [lr, lg, lb] = [toLinear(r), toLinear(g), toLinear(b)]
1603
+ const l = Math.cbrt(0.4122214708 * lr + 0.5363325363 * lg + 0.0514459929 * lb)
1604
+ const m = Math.cbrt(0.2119034982 * lr + 0.6806995451 * lg + 0.1073969566 * lb)
1605
+ const t = Math.cbrt(0.0883024619 * lr + 0.2817188376 * lg + 0.6299787005 * lb)
1606
+ return [0.2104542553 * l + 0.793617785 * m - 0.0040720468 * t, 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * t, 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * t]
1607
+ }
1608
+
1609
+ function fromOklab([L, a, b]: [number, number, number]): string {
1610
+ const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3
1611
+ const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3
1612
+ const t = (L - 0.0894841775 * a - 1.291485548 * b) ** 3
1613
+ const rgb = [4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * t, -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * t, -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * t]
1614
+ return `rgb(${rgb.map(fromLinear).join(", ")})`
1615
+ }
1616
+
1617
+ /**
1618
+ * `share` of `color` mixed into `surface` — the canvas form of `color-mix(in oklch, <color> 20%, <surface>)`. The
1619
+ * surface is a neutral, so its hue is powerless and the oklch mix is the straight line in Oklab. An unreadable
1620
+ * colour falls back to `color` at `share` opacity.
1621
+ */
1622
+ export function mixIntoSurface(color: string, surface: string | undefined, share: number): string {
1623
+ const c = parseRgb(color)
1624
+ const s = surface ? parseRgb(surface) : null
1625
+ if (!c || !s) return withAlpha(color, share)
1626
+ const [c1, c2] = [toOklab(c), toOklab(s)]
1627
+ return fromOklab([0, 1, 2].map((i) => c2[i]! + (c1[i]! - c2[i]!) * share) as [number, number, number])
1628
+ }
1629
+
1630
+ function escapeHtml(text: string): string {
1631
+ return text.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!)
1632
+ }
1633
+
1634
+ /** Rough width (px) of 12px text: full-width characters 12, the rest 7 (as `chart-options` estimates it; kept local, like `escapeHtml`, so this part inlines on its own). */
1635
+ function estimateTextWidth(text: string): number {
1636
+ let w = 0
1637
+ for (const ch of text) w += /[\u3000-\u9fff\uff00-\uffef]/.test(ch) ? 12 : 7
1638
+ return w
1639
+ }
1640
+
1641
+ /** The grid's left and right margins (px), and the room a cell's text needs beside its edges. */
1642
+ const HEATMAP_GRID_X = 16
1643
+ const HEATMAP_CELL_PADDING = 4
1644
+ /** `plotWidth` is floored to a 40 px bucket (`useChartSurface`): the true width is half a bucket more on average. */
1645
+ const HEATMAP_BUCKET_MID = 20
1646
+
1647
+ /**
1648
+ * The font size (px) of the numbers inside the cells at a plot width: 12 when the widest text fits a cell,
1649
+ * 10 when only the smaller size does, `null` (no numbers: the shade and the tooltip carry them) when neither.
1650
+ * Cells are the plot — its width less the margins and the row-name column — shared by the columns.
1651
+ */
1652
+ export function heatmapCellFontSize(
1653
+ plotWidth: number,
1654
+ columns: number,
1655
+ rowNames: readonly string[],
1656
+ texts: readonly string[],
1657
+ ): 12 | 10 | null {
1658
+ const widest = (items: readonly string[]) => items.reduce((m, t) => Math.max(m, estimateTextWidth(t)), 0)
1659
+ const cell = (plotWidth + HEATMAP_BUCKET_MID - HEATMAP_GRID_X - (widest(rowNames) + 8)) / Math.max(1, columns)
1660
+ const text = widest(texts)
1661
+ if (text + HEATMAP_CELL_PADDING <= cell) return 12
1662
+ return (text * 10) / 12 + HEATMAP_CELL_PADDING <= cell ? 10 : null
1663
+ }
1664
+
1665
+ const TEXT = {
1666
+ ja: {
1667
+ join: "・",
1668
+ flagged: "要注意",
1669
+ item: "項目",
1670
+ top: (y: string, x: string, value: string) => `最大は ${y} ${x} の ${value}`,
1671
+ chart: (y: string, x: string) => `${y}×${x}のヒートマップ`,
1672
+ },
1673
+ en: {
1674
+ join: ", ",
1675
+ flagged: "Needs attention",
1676
+ item: "Item",
1677
+ top: (y: string, x: string, value: string) => `Highest: ${y} ${x} (${value})`,
1678
+ chart: (y: string, x: string) => `Heatmap of ${y} × ${x}`,
1679
+ },
1680
+ }
1681
+
1682
+ const textOf = (locale?: string) => TEXT[uiLanguage(resolveLocale(locale))]
1683
+
1684
+ export interface HeatmapOptionConfig {
1685
+ model: HeatmapModel
1686
+ x: string
1687
+ y: string
1688
+ value: string
1689
+ /** Resolved (canvas-safe) tone colour; `""` leaves it to the theme palette. */
1690
+ color: string
1691
+ /** Resolved colour of the flag outline. */
1692
+ flagColor: string
1693
+ /** Resolved muted colour, for the missing-value cells and the axis. */
1694
+ mutedColor: string
1695
+ /** The colour the chart sits on (a card): the ramp's lowest end mixes the tone into it. */
1696
+ surfaceColor?: string
1697
+ /** Text on a dark cell / on a light cell. */
1698
+ darkCellText: string
1699
+ lightCellText: string
1700
+ labels?: Record<string, string>
1701
+ valueFormatter: ValueFormatter
1702
+ details?: readonly string[]
1703
+ showValues: boolean
1704
+ showTooltip: boolean
1705
+ /** The plot's width (px), when known: the numbers shrink (or go) when the cells are too narrow for them. */
1706
+ plotWidth?: number | null
1707
+ chartOptions?: EChartsOption
1708
+ /** Language of the tooltip. Default the page's locale (`<html lang>`). */
1709
+ locale?: string
1710
+ }
1711
+
1712
+ /**
1713
+ * The ECharts option: a shaded series (visual map, hidden), a grey series for gaps, category axes.
1714
+ * ECharts requires every heatmap series to be bound to a visual map (it throws「Heatmap must use with
1715
+ * visualMap」otherwise) and skips cells whose value is not a number, so the gap series gets its own
1716
+ * hidden visual map with a single grey and carries a placeholder `0` as its value (the label and the
1717
+ * tooltip read「—」from the cell, never the placeholder).
1718
+ */
1719
+ export function buildHeatmapOption(config: HeatmapOptionConfig): EChartsOption {
1720
+ const { model, labels, valueFormatter } = config
1721
+ const t = textOf(config.locale)
1722
+ const label = (key: string) => labels?.[key] ?? key
1723
+ const present = model.cells.filter((c) => c.value !== null)
1724
+ const missing = model.cells.filter((c) => c.value === null)
1725
+ const base = config.color || "#6366f1"
1726
+ const range = [mixIntoSurface(base, config.surfaceColor, HEATMAP_FLOOR_SHARE), base]
1727
+ const gapColor = "rgba(0, 0, 0, 0)"
1728
+ const flagged = (cell: HeatmapCell) =>
1729
+ cell.flagged ? { borderColor: config.flagColor, borderWidth: 3, borderType: "solid" as const } : { borderColor: "transparent", borderWidth: 1 }
1730
+
1731
+ const tooltip = (cell: HeatmapCell): string => {
1732
+ const head = `${escapeHtml(label(model.ys[cell.yi]!))} ${escapeHtml(label(model.xs[cell.xi]!))}`
1733
+ const main = cell.value === null ? EMPTY_VALUE : escapeHtml(valueFormatter(cell.value))
1734
+ const extras = (config.details ?? [])
1735
+ .map((key) => {
1736
+ const n = cell.row ? toChartNumber(cell.row[key]) : null
1737
+ return `${escapeHtml(label(key))} ${n === null ? EMPTY_VALUE : escapeHtml(valueFormatter(n))}`
1738
+ })
1739
+ .join(t.join)
1740
+ const flag = cell.flagged ? `${t.join}${t.flagged}` : ""
1741
+ return `${head} ${main}${extras ? `${t.join}${extras}` : ""}${flag}`
1742
+ }
1743
+
1744
+ const cellFont = config.plotWidth
1745
+ ? heatmapCellFontSize(
1746
+ config.plotWidth,
1747
+ model.xs.length,
1748
+ model.ys.map(label),
1749
+ model.cells.flatMap((cell) => (cell.value === null ? [] : [valueFormatter(cell.value)])),
1750
+ )
1751
+ : 12
1752
+ const point = (cell: HeatmapCell) => ({ value: [cell.xi, cell.yi, cell.value], cell })
1753
+ const option: EChartsOption = {
1754
+ animation: false,
1755
+ tooltip: config.showTooltip
1756
+ ? { trigger: "item", formatter: (p: unknown) => tooltip((p as { data: { cell: HeatmapCell } }).data.cell) }
1757
+ : { show: false },
1758
+ grid: { left: 8, right: 8, top: 8, bottom: 8, containLabel: true },
1759
+ xAxis: {
1760
+ type: "category",
1761
+ data: model.xs,
1762
+ splitArea: { show: false },
1763
+ axisTick: { show: false },
1764
+ axisLine: { show: false },
1765
+ axisLabel: { formatter: (v: string) => label(v), hideOverlap: true },
1766
+ },
1767
+ yAxis: {
1768
+ type: "category",
1769
+ data: model.ys,
1770
+ inverse: true,
1771
+ splitArea: { show: false },
1772
+ axisTick: { show: false },
1773
+ axisLine: { show: false },
1774
+ axisLabel: { formatter: (v: string) => label(v) },
1775
+ },
1776
+ visualMap: [
1777
+ {
1778
+ type: "continuous",
1779
+ show: false,
1780
+ min: model.min,
1781
+ max: model.max,
1782
+ dimension: 2,
1783
+ seriesIndex: 0,
1784
+ inRange: { color: range },
1785
+ outOfRange: { color: range },
1786
+ },
1787
+ {
1788
+ type: "continuous",
1789
+ show: false,
1790
+ min: 0,
1791
+ max: 1,
1792
+ dimension: 2,
1793
+ seriesIndex: 1,
1794
+ inRange: { color: [gapColor, gapColor] },
1795
+ outOfRange: { color: [gapColor, gapColor] },
1796
+ },
1797
+ ],
1798
+ series: [
1799
+ {
1800
+ id: "values",
1801
+ type: "heatmap",
1802
+ data: present.map((cell) => ({
1803
+ ...point(cell),
1804
+ itemStyle: flagged(cell),
1805
+ label: {
1806
+ color:
1807
+ heatmapRatio(cell.value as number, model.min, model.max) >= HEATMAP_LIGHT_TEXT_FROM
1808
+ ? config.darkCellText
1809
+ : config.lightCellText,
1810
+ },
1811
+ })),
1812
+ label: {
1813
+ show: config.showValues && cellFont !== null,
1814
+ fontSize: cellFont ?? 12,
1815
+ formatter: (p: unknown) => valueFormatter((p as { value: [number, number, number] }).value[2]),
1816
+ },
1817
+ itemStyle: { borderColor: "transparent", borderWidth: 1, borderRadius: 2 },
1818
+ emphasis: { itemStyle: { borderColor: config.lightCellText, borderWidth: 2 } },
1819
+ z: 2,
1820
+ },
1821
+ {
1822
+ id: "gaps",
1823
+ type: "heatmap",
1824
+ data: missing.map((cell) => ({ value: [cell.xi, cell.yi, 0], cell, itemStyle: flagged(cell) })),
1825
+ label: { show: false },
1826
+ itemStyle: {
1827
+ color: gapColor,
1828
+ borderColor: "transparent",
1829
+ borderWidth: 1,
1830
+ borderRadius: 2,
1831
+ },
1832
+ emphasis: { disabled: true },
1833
+ z: 1,
1834
+ },
1835
+ ],
1836
+ }
1837
+ return config.chartOptions ? mergeDeep(option as Record<string, unknown>, config.chartOptions as Record<string, unknown>) as EChartsOption : option
1838
+ }
1839
+
1840
+ function mergeDeep(a: Record<string, unknown>, b: Record<string, unknown>): Record<string, unknown> {
1841
+ const out: Record<string, unknown> = { ...a }
1842
+ for (const [k, v] of Object.entries(b)) {
1843
+ const cur = out[k]
1844
+ out[k] =
1845
+ v && cur && typeof v === "object" && typeof cur === "object" && !Array.isArray(v) && !Array.isArray(cur)
1846
+ ? mergeDeep(cur as Record<string, unknown>, v as Record<string, unknown>)
1847
+ : v
1848
+ }
1849
+ return out
1850
+ }
1851
+
1852
+ /** The screen-reader table: one row per y, one column per x; gaps read「—」. */
1853
+ export function heatmapDataTable(
1854
+ model: HeatmapModel,
1855
+ names: { x: string; y: string },
1856
+ formatter: ValueFormatter,
1857
+ labels?: Record<string, string>,
1858
+ locale?: string,
1859
+ ): ChartDataTable {
1860
+ const label = (key: string) => labels?.[key] ?? key
1861
+ const rows = model.ys.map((yk, yi) => [
1862
+ label(yk),
1863
+ ...model.xs.map((_, xi) => {
1864
+ const v = model.cells[yi * model.xs.length + xi]?.value
1865
+ return v === null || v === undefined ? EMPTY_VALUE : formatter(v)
1866
+ }),
1867
+ ])
1868
+ return { caption: `${label(names.y)}×${label(names.x)}`, columns: [labels?.[names.y] ?? textOf(locale).item, ...model.xs.map(label)], rows }
1869
+ }
1870
+
1871
+ /**
1872
+ * `summary="auto"`: the strongest cell, e.g. 「最大は 月曜 9時台 の 12件」 / "Highest: Mon 9am (12)". `undefined` with no usable cell.
1873
+ * `locale` picks the language; default the page's (`<html lang>`).
1874
+ */
1875
+ export function buildHeatmapSummary(
1876
+ model: HeatmapModel,
1877
+ formatter: ValueFormatter,
1878
+ title?: string,
1879
+ labels?: Record<string, string>,
1880
+ locale?: string,
1881
+ ): string | undefined {
1882
+ let best: HeatmapCell | undefined
1883
+ for (const cell of model.cells) if (cell.value !== null && (!best || cell.value > (best.value as number))) best = cell
1884
+ if (!best) return undefined
1885
+ const label = (key: string) => labels?.[key] ?? key
1886
+ const head = title ? `${title}: ` : ""
1887
+ return `${head}${textOf(locale).top(label(model.ys[best.yi]!), label(model.xs[best.xi]!), formatter(best.value as number))}`
1888
+ }
1889
+
1890
+ /* -------------------------------------------------------------- component */
1891
+
1892
+ function colorsFor(tokens: ChartTokens | null, tone: string) {
1893
+ const [color = "", flag = "", muted = ""] = resolveChartColors([tone, "negative", "var(--muted-foreground)"], tokens)
1894
+ return { color, flag, muted }
1895
+ }
1896
+
1897
+ /** Rows not given yet (a draft fills props in steps): draw the empty state, keep the same array between renders. */
1898
+ const NO_ROWS: never[] = []
1899
+
1900
+ function HeatmapImpl<T extends Record<string, unknown>>(
1901
+ {
1902
+ data = NO_ROWS,
1903
+ x,
1904
+ y,
1905
+ value,
1906
+ xLabels,
1907
+ yLabels,
1908
+ labels,
1909
+ format,
1910
+ valueFormatter,
1911
+ tone = "chart-1",
1912
+ scale,
1913
+ minValue,
1914
+ maxValue,
1915
+ showValues = false,
1916
+ showLegend = true,
1917
+ showTooltip = true,
1918
+ details,
1919
+ flag,
1920
+ title,
1921
+ summary,
1922
+ isLoading,
1923
+ emptyState,
1924
+ height,
1925
+ chartOptions,
1926
+ actions,
1927
+ fileName,
1928
+ className,
1929
+ ariaLabel,
1930
+ ...rest
1931
+ }: HeatmapProps<T>,
1932
+ ref: ForwardedRef<HTMLDivElement>,
1933
+ ) {
1934
+ const { ref: frameRef, surface, width: plotWidth, tokens } = useChartSurface(ref)
1935
+ const locale = useLocale()
1936
+ const formatter = useMemo(() => resolveValueFormatter(valueFormatter, format ?? "number", locale), [valueFormatter, format, locale])
1937
+ const model = useMemo(
1938
+ () => buildHeatmapModel({ data, x, y, value, xLabels, yLabels, flag, scale, minValue, maxValue }),
1939
+ [data, x, y, value, xLabels, yLabels, flag, scale?.min, scale?.max, minValue, maxValue],
1940
+ )
1941
+ const colors = useMemo(() => colorsFor(tokens, tone), [tokens, tone])
1942
+ const option = useMemo(
1943
+ () =>
1944
+ buildHeatmapOption({
1945
+ model,
1946
+ x,
1947
+ y,
1948
+ value,
1949
+ color: colors.color,
1950
+ flagColor: colors.flag,
1951
+ mutedColor: colors.muted,
1952
+ surfaceColor: surface ?? undefined,
1953
+ darkCellText: surface ?? "#ffffff",
1954
+ lightCellText: tokens?.foreground ?? "",
1955
+ labels,
1956
+ valueFormatter: formatter,
1957
+ details: details as string[] | undefined,
1958
+ showValues,
1959
+ showTooltip,
1960
+ plotWidth,
1961
+ chartOptions,
1962
+ locale,
1963
+ }),
1964
+ [model, x, y, value, colors, surface, tokens, labels, formatter, details, showValues, showTooltip, plotWidth, chartOptions, locale],
1965
+ )
1966
+ const dataTable = useMemo(() => heatmapDataTable(model, { x, y }, formatter, labels, locale), [model, x, y, formatter, labels, locale])
1967
+ const resolvedSummary = useMemo(
1968
+ () => (summary === "auto" ? buildHeatmapSummary(model, formatter, title, labels, locale) : summary),
1969
+ [summary, model, formatter, title, labels, locale],
1970
+ )
1971
+ const label = ariaLabel ?? textOf(locale).chart(labels?.[y] ?? y, labels?.[x] ?? x)
1972
+ const legend = showLegend ? (
1973
+ <HeatmapLegend model={model} formatter={formatter} tone={tone} />
1974
+ ) : null
1975
+ return (
1976
+ <ChartFrame
1977
+ {...chartRootProps(rest)}
1978
+ ref={frameRef}
1979
+ title={title}
1980
+ summary={resolvedSummary}
1981
+ isLoading={isLoading ?? false}
1982
+ isEmpty={data.length === 0}
1983
+ emptyState={emptyState}
1984
+ height={height}
1985
+ variant="bar"
1986
+ ariaLabel={label}
1987
+ className={className}
1988
+ dataTable={dataTable}
1989
+ >
1990
+ <div className="flex h-full w-full flex-col gap-2">
1991
+ <div className="min-h-0 flex-1">
1992
+ <EChart option={option} height="100%" ariaLabel={label} actions={actions} fileName={fileName} exportHeader={{ title, summary: resolvedSummary }} />
1993
+ </div>
1994
+ {legend}
1995
+ </div>
1996
+ </ChartFrame>
1997
+ )
1998
+ }
1999
+
2000
+ function HeatmapLegend({
2001
+ model,
2002
+ formatter,
2003
+ tone,
2004
+ }: {
2005
+ model: HeatmapModel
2006
+ formatter: ValueFormatter
2007
+ tone: string
2008
+ }) {
2009
+ const ramp = `linear-gradient(to right, color-mix(in oklch, var(--${tone}) ${HEATMAP_FLOOR_SHARE * 100}%, var(--card)), var(--${tone}))`
2010
+ return (
2011
+ <div data-slot="heatmap-legend" className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground tabular-nums">
2012
+ <span className="flex items-center gap-2">
2013
+ <span>{formatter(model.min)}</span>
2014
+ <span aria-hidden className="h-2 w-24 rounded-sm" style={{ backgroundImage: ramp }} />
2015
+ <span>{formatter(model.max)}</span>
2016
+ </span>
2017
+ </div>
2018
+ )
2019
+ }
2020
+
2021
+ /** Generic over the row type, so `x` / `y` / `value` keys are checked against `data`. */
2022
+ export const Heatmap = forwardRef(HeatmapImpl as (props: HeatmapProps, ref: ForwardedRef<HTMLDivElement>) => ReactElement) as (<
2023
+ T extends Record<string, unknown>,
2024
+ >(
2025
+ props: HeatmapProps<T> & { ref?: Ref<HTMLDivElement> },
2026
+ ) => ReactElement) & { displayName?: string }
2027
+ Heatmap.displayName = "Heatmap"