@squadbase/vantage 0.6.2-dev1.9d91dda → 0.6.2-dev1.a881d95

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 (339) hide show
  1. package/dist/add-4GHF2TX2.js +6 -0
  2. package/dist/add-4GHF2TX2.js.map +1 -0
  3. package/dist/{build-TVKFIVFQ.js → build-U7GO26HR.js} +9 -9
  4. package/dist/{build-TVKFIVFQ.js.map → build-U7GO26HR.js.map} +1 -1
  5. package/dist/{check-3KHZXZMQ.js → check-MRVAIHG5.js} +7 -7
  6. package/dist/{check-3KHZXZMQ.js.map → check-MRVAIHG5.js.map} +1 -1
  7. package/dist/chunk-2IAPIOPS.js +152 -0
  8. package/dist/chunk-2IAPIOPS.js.map +1 -0
  9. package/dist/chunk-3RJEOP3J.js +174 -0
  10. package/dist/chunk-3RJEOP3J.js.map +1 -0
  11. package/dist/chunk-77CISBMG.js +7581 -0
  12. package/dist/chunk-77CISBMG.js.map +1 -0
  13. package/dist/{chunk-U2M6HGKQ.js → chunk-AABMKHEU.js} +4 -4
  14. package/dist/{chunk-U2M6HGKQ.js.map → chunk-AABMKHEU.js.map} +1 -1
  15. package/dist/{chunk-PVTHHV7X.js → chunk-ANZLVSEP.js} +28 -7
  16. package/dist/chunk-ANZLVSEP.js.map +1 -0
  17. package/dist/chunk-CKWPK4RO.js +50 -0
  18. package/dist/chunk-CKWPK4RO.js.map +1 -0
  19. package/dist/chunk-EG4PX726.js +678 -0
  20. package/dist/chunk-EG4PX726.js.map +1 -0
  21. package/dist/{chunk-QI3XQKHS.js → chunk-GNXCX4WE.js} +10 -3
  22. package/dist/chunk-GNXCX4WE.js.map +1 -0
  23. package/dist/chunk-NZ5QIIG4.js +74 -0
  24. package/dist/chunk-NZ5QIIG4.js.map +1 -0
  25. package/dist/{chunk-P7W4LR3Z.js → chunk-PJ4SPXHS.js} +24 -7
  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-CEXAQQ5W.js → chunk-S5MDTHH7.js} +180 -18
  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-LMUACBMA.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-JKLLFVEU.js → chunk-UWSQUHX6.js} +4 -99
  44. package/dist/chunk-UWSQUHX6.js.map +1 -0
  45. package/dist/cli.js +12 -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 +1761 -30
  51. package/dist/components/index.js +7 -4
  52. package/dist/delta-text-CbrOaW83.d.ts +17 -0
  53. package/dist/{dev-GDKATCC7.js → dev-O42JFQ64.js} +10 -10
  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-EJJ3BECT.js → docs-JVP4RPKT.js} +3 -3
  59. package/dist/{docs-EJJ3BECT.js.map → docs-JVP4RPKT.js.map} +1 -1
  60. package/dist/{doctor-WQXPXP6K.js → doctor-YD3XAAOT.js} +7 -7
  61. package/dist/{doctor-WQXPXP6K.js.map → doctor-YD3XAAOT.js.map} +1 -1
  62. package/dist/format-DihQkL1N.d.ts +249 -0
  63. package/dist/markdown/index.js +1 -1
  64. package/dist/markdown/index.js.map +1 -1
  65. package/dist/{preview-OGMCNQUO.js → preview-T6CLSQVX.js} +3 -3
  66. package/dist/{preview-OGMCNQUO.js.map → preview-T6CLSQVX.js.map} +1 -1
  67. package/dist/query/index.d.ts +0 -11
  68. package/dist/query/index.js +2 -2
  69. package/dist/{routes-MWBWWOJ2.js → routes-PVKNT777.js} +6 -6
  70. package/dist/{routes-MWBWWOJ2.js.map → routes-PVKNT777.js.map} +1 -1
  71. package/dist/{search-6Y422SV6.js → search-5LC4XPB5.js} +3 -3
  72. package/dist/{search-6Y422SV6.js.map → search-5LC4XPB5.js.map} +1 -1
  73. package/dist/slide/index.d.ts +272 -1
  74. package/dist/slide/index.js +1025 -4
  75. package/dist/slide/index.js.map +1 -1
  76. package/dist/table/index.js +14 -10
  77. package/dist/table/index.js.map +1 -1
  78. package/dist/ui/index.d.ts +148 -12
  79. package/dist/ui/index.js +1340 -88
  80. package/dist/ui/index.js.map +1 -1
  81. package/dist/{upgrade-HCANX4GQ.js → upgrade-6DT7ADRP.js} +7 -7
  82. package/dist/{upgrade-HCANX4GQ.js.map → upgrade-6DT7ADRP.js.map} +1 -1
  83. package/dist/vite/index.d.ts +10 -0
  84. package/dist/vite/index.js +4 -4
  85. package/docs/en/agent-skills.md +1 -1
  86. package/docs/en/changelog.md +2 -0
  87. package/docs/en/components.md +42 -17
  88. package/docs/en/doc/delta-text.md +40 -0
  89. package/docs/en/doc/doc-action-items.md +49 -0
  90. package/docs/en/doc/doc-callout.md +38 -0
  91. package/docs/en/doc/doc-data-table.md +60 -0
  92. package/docs/en/doc/doc-executive-summary.md +64 -0
  93. package/docs/en/doc/doc-figure.md +56 -0
  94. package/docs/en/doc/doc-key-findings.md +61 -0
  95. package/docs/en/doc/doc-kpi-scorecard.md +80 -0
  96. package/docs/en/doc/doc-notes-and-sources.md +43 -0
  97. package/docs/en/doc/doc-report-header.md +46 -0
  98. package/docs/en/pages-and-metadata.md +15 -0
  99. package/docs/en/parts/area-chart.md +99 -0
  100. package/docs/en/parts/bar-chart.md +91 -0
  101. package/docs/en/parts/bar-list.md +50 -0
  102. package/docs/en/parts/category-bar.md +37 -0
  103. package/docs/en/parts/chart-frame.md +39 -0
  104. package/docs/en/parts/data-table.md +22 -0
  105. package/docs/en/parts/delta.md +51 -0
  106. package/docs/en/parts/donut-chart.md +72 -0
  107. package/docs/en/parts/format.md +43 -0
  108. package/docs/en/parts/funnel-steps.md +2 -1
  109. package/docs/en/parts/heatmap.md +53 -0
  110. package/docs/en/parts/kpi-card.md +58 -0
  111. package/docs/en/parts/legend.md +35 -0
  112. package/docs/en/parts/line-chart.md +94 -0
  113. package/docs/en/parts/metric-value.md +3 -2
  114. package/docs/en/parts/progress-circle.md +33 -0
  115. package/docs/en/parts/sample-data.md +39 -0
  116. package/docs/en/parts/scatter-chart.md +56 -0
  117. package/docs/en/parts/sparkline.md +1 -1
  118. package/docs/en/parts/tracker.md +36 -0
  119. package/docs/en/parts/trend-indicator.md +17 -1
  120. package/docs/en/parts/updated-at.md +30 -0
  121. package/docs/en/parts/waterfall-chart.md +56 -0
  122. package/docs/en/slide/slide-chart-full.md +48 -0
  123. package/docs/en/slide/slide-chart-insight.md +52 -0
  124. package/docs/en/slide/slide-columns.md +46 -0
  125. package/docs/en/slide/slide-comparison.md +68 -0
  126. package/docs/en/slide/slide-cover.md +39 -0
  127. package/docs/en/slide/slide-exec-summary.md +47 -0
  128. package/docs/en/slide/slide-heading.md +38 -0
  129. package/docs/en/slide/slide-kpi-grid.md +55 -0
  130. package/docs/en/slide/slide-kpi-hero.md +58 -0
  131. package/docs/en/slide/slide-next-actions.md +49 -0
  132. package/docs/en/slide/slide-scorecard-table.md +54 -0
  133. package/docs/en/slide/slide-section.md +44 -0
  134. package/docs/en/slide/slide-source-line.md +34 -0
  135. package/docs/en/ui/alert-dialog.md +42 -0
  136. package/docs/en/ui/avatar.md +31 -0
  137. package/docs/en/ui/combobox.md +74 -0
  138. package/docs/en/ui/drawer.md +41 -0
  139. package/docs/en/ui/empty.md +1 -1
  140. package/docs/en/ui/error-state.md +4 -3
  141. package/docs/en/ui/field.md +42 -0
  142. package/docs/en/ui/hover-card.md +21 -0
  143. package/docs/en/ui/kbd.md +17 -0
  144. package/docs/en/ui/loading.md +1 -1
  145. package/docs/en/ui/pagination.md +36 -0
  146. package/docs/en/ui/radio-group.md +21 -0
  147. package/docs/en/ui/toast.md +44 -0
  148. package/docs/en/ui/toggle-group.md +4 -3
  149. package/docs/en/ui-and-theming.md +1 -1
  150. package/docs/index.json +1184 -114
  151. package/docs/ja/agent-skills.md +1 -1
  152. package/docs/ja/changelog.md +33 -0
  153. package/docs/ja/components.md +68 -101
  154. package/docs/ja/doc/delta-text.md +40 -0
  155. package/docs/ja/doc/doc-action-items.md +49 -0
  156. package/docs/ja/doc/doc-callout.md +38 -0
  157. package/docs/ja/doc/doc-data-table.md +60 -0
  158. package/docs/ja/doc/doc-executive-summary.md +64 -0
  159. package/docs/ja/doc/doc-figure.md +56 -0
  160. package/docs/ja/doc/doc-key-findings.md +61 -0
  161. package/docs/ja/doc/doc-kpi-scorecard.md +80 -0
  162. package/docs/ja/doc/doc-notes-and-sources.md +43 -0
  163. package/docs/ja/doc/doc-report-header.md +46 -0
  164. package/docs/ja/page-types/csv.md +83 -0
  165. package/docs/ja/page-types/doc.md +83 -0
  166. package/docs/ja/page-types/excel.md +82 -0
  167. package/docs/ja/page-types/slide.md +133 -0
  168. package/docs/ja/page-types.md +47 -0
  169. package/docs/ja/pages-and-metadata.md +15 -0
  170. package/docs/ja/parts/area-chart.md +85 -0
  171. package/docs/ja/parts/bar-chart.md +95 -0
  172. package/docs/ja/parts/bar-list.md +58 -0
  173. package/docs/ja/parts/category-bar.md +36 -0
  174. package/docs/ja/parts/chart-frame.md +36 -0
  175. package/docs/ja/parts/data-table.md +22 -0
  176. package/docs/ja/parts/delta.md +51 -0
  177. package/docs/ja/parts/donut-chart.md +66 -0
  178. package/docs/ja/parts/echart.md +3 -0
  179. package/docs/ja/parts/format.md +44 -0
  180. package/docs/ja/parts/funnel-steps.md +27 -8
  181. package/docs/ja/parts/heatmap.md +45 -0
  182. package/docs/ja/parts/kpi-card.md +56 -0
  183. package/docs/ja/parts/legend.md +36 -0
  184. package/docs/ja/parts/line-chart.md +84 -0
  185. package/docs/ja/parts/metric-value.md +3 -2
  186. package/docs/ja/parts/progress-circle.md +34 -0
  187. package/docs/ja/parts/sample-data.md +61 -0
  188. package/docs/ja/parts/scatter-chart.md +69 -0
  189. package/docs/ja/parts/sparkline.md +2 -2
  190. package/docs/ja/parts/tracker.md +32 -0
  191. package/docs/ja/parts/trend-indicator.md +17 -1
  192. package/docs/ja/parts/updated-at.md +27 -0
  193. package/docs/ja/parts/waterfall-chart.md +61 -0
  194. package/docs/ja/routing.md +8 -86
  195. package/docs/ja/slide/slide-chart-full.md +48 -0
  196. package/docs/ja/slide/slide-chart-insight.md +52 -0
  197. package/docs/ja/slide/slide-columns.md +46 -0
  198. package/docs/ja/slide/slide-comparison.md +68 -0
  199. package/docs/ja/slide/slide-cover.md +39 -0
  200. package/docs/ja/slide/slide-exec-summary.md +47 -0
  201. package/docs/ja/slide/slide-heading.md +38 -0
  202. package/docs/ja/slide/slide-kpi-grid.md +55 -0
  203. package/docs/ja/slide/slide-kpi-hero.md +58 -0
  204. package/docs/ja/slide/slide-next-actions.md +49 -0
  205. package/docs/ja/slide/slide-scorecard-table.md +54 -0
  206. package/docs/ja/slide/slide-section.md +44 -0
  207. package/docs/ja/slide/slide-source-line.md +34 -0
  208. package/docs/ja/ui/alert-dialog.md +41 -0
  209. package/docs/ja/ui/avatar.md +31 -0
  210. package/docs/ja/ui/combobox.md +74 -0
  211. package/docs/ja/ui/drawer.md +41 -0
  212. package/docs/ja/ui/empty.md +1 -1
  213. package/docs/ja/ui/error-state.md +4 -3
  214. package/docs/ja/ui/field.md +42 -0
  215. package/docs/ja/ui/hover-card.md +21 -0
  216. package/docs/ja/ui/kbd.md +16 -0
  217. package/docs/ja/ui/loading.md +1 -1
  218. package/docs/ja/ui/pagination.md +36 -0
  219. package/docs/ja/ui/radio-group.md +21 -0
  220. package/docs/ja/ui/toast.md +46 -0
  221. package/docs/ja/ui/toggle-group.md +4 -3
  222. package/docs/ja/ui-and-theming.md +14 -7
  223. package/package.json +41 -31
  224. package/registry/ui/accordion.tsx +76 -0
  225. package/registry/ui/alert-dialog.tsx +189 -0
  226. package/registry/ui/alert.tsx +80 -0
  227. package/registry/ui/app-shell.tsx +424 -0
  228. package/registry/ui/area-chart.tsx +3960 -0
  229. package/registry/ui/attention-list.tsx +465 -0
  230. package/registry/ui/avatar.tsx +110 -0
  231. package/registry/ui/badge.tsx +56 -0
  232. package/registry/ui/bar-chart.tsx +3954 -0
  233. package/registry/ui/bar-list.tsx +3998 -0
  234. package/registry/ui/box-plot-chart.tsx +4214 -0
  235. package/registry/ui/breadcrumb.tsx +128 -0
  236. package/registry/ui/button.tsx +62 -0
  237. package/registry/ui/calendar.tsx +223 -0
  238. package/registry/ui/card.tsx +107 -0
  239. package/registry/ui/category-bar.tsx +1498 -0
  240. package/registry/ui/chart-frame.tsx +1604 -0
  241. package/registry/ui/checkbox.tsx +30 -0
  242. package/registry/ui/collapsible.tsx +23 -0
  243. package/registry/ui/combobox.tsx +310 -0
  244. package/registry/ui/command.tsx +198 -0
  245. package/registry/ui/dashboard-card.tsx +217 -0
  246. package/registry/ui/data-table.tsx +896 -157
  247. package/registry/ui/date-range-picker.tsx +544 -0
  248. package/registry/ui/delta.tsx +350 -0
  249. package/registry/ui/dialog.tsx +161 -0
  250. package/registry/ui/donut-chart.tsx +4006 -0
  251. package/registry/ui/drawer.tsx +229 -0
  252. package/registry/ui/dropdown-menu.tsx +274 -0
  253. package/registry/ui/echart.tsx +1178 -0
  254. package/registry/ui/field.tsx +240 -0
  255. package/registry/ui/filter-bar.tsx +551 -0
  256. package/registry/ui/funnel-steps.tsx +3843 -0
  257. package/registry/ui/heatmap.tsx +2027 -0
  258. package/registry/ui/histogram-chart.tsx +4284 -0
  259. package/registry/ui/hover-card.tsx +52 -0
  260. package/registry/ui/input-group.tsx +160 -0
  261. package/registry/ui/input.tsx +24 -0
  262. package/registry/ui/kbd.tsx +30 -0
  263. package/registry/ui/kpi-card.tsx +905 -0
  264. package/registry/ui/label.tsx +22 -0
  265. package/registry/ui/legend.tsx +3817 -0
  266. package/registry/ui/line-chart.tsx +3958 -0
  267. package/registry/ui/metric-value.tsx +62 -0
  268. package/registry/ui/multi-select.tsx +382 -0
  269. package/registry/ui/page-shell.tsx +420 -0
  270. package/registry/ui/pagination.tsx +140 -0
  271. package/registry/ui/paired-chart.tsx +4086 -0
  272. package/registry/ui/placeholder.tsx +36 -0
  273. package/registry/ui/popover.tsx +92 -0
  274. package/registry/ui/progress-circle.tsx +1033 -0
  275. package/registry/ui/progress.tsx +85 -0
  276. package/registry/ui/radio-group.tsx +39 -0
  277. package/registry/ui/sample-data.tsx +230 -0
  278. package/registry/ui/scatter-chart.tsx +4503 -0
  279. package/registry/ui/scroll-area.tsx +56 -0
  280. package/registry/ui/searchable-select.tsx +352 -0
  281. package/registry/ui/section-header.tsx +43 -0
  282. package/registry/ui/segmented-control.tsx +76 -0
  283. package/registry/ui/select.tsx +255 -0
  284. package/registry/ui/separator.tsx +27 -0
  285. package/registry/ui/sheet.tsx +139 -0
  286. package/registry/ui/sidebar.tsx +725 -0
  287. package/registry/ui/skeleton.tsx +17 -0
  288. package/registry/ui/slider.tsx +56 -0
  289. package/registry/ui/sparkline.tsx +230 -0
  290. package/registry/ui/spinner.tsx +14 -0
  291. package/registry/ui/states.tsx +247 -0
  292. package/registry/ui/status-badge.tsx +286 -0
  293. package/registry/ui/switch.tsx +34 -0
  294. package/registry/ui/table.tsx +118 -0
  295. package/registry/ui/tabs.tsx +84 -0
  296. package/registry/ui/textarea.tsx +22 -0
  297. package/registry/ui/toast.tsx +250 -0
  298. package/registry/ui/toggle-group.tsx +91 -0
  299. package/registry/ui/toggle.tsx +47 -0
  300. package/registry/ui/tooltip.tsx +72 -0
  301. package/registry/ui/tracker.tsx +1015 -0
  302. package/registry/ui/trend-indicator.tsx +217 -0
  303. package/registry/ui/updated-at.tsx +276 -0
  304. package/registry/ui/waterfall-chart.tsx +4561 -0
  305. package/skills/vantage-add-feature/SKILL.md +14 -7
  306. package/skills/vantage-design/SKILL.md +60 -52
  307. package/skills/vantage-design/references/extract.md +26 -27
  308. package/skills/vantage-design/references/format.md +12 -172
  309. package/skills/vantage-design/references/presets.md +50 -110
  310. package/skills/vantage-pitfalls/SKILL.md +10 -1
  311. package/skills/vantage-slide/SKILL.md +54 -36
  312. package/templates/AGENTS.md +53 -16
  313. package/templates/agents/api.md +7 -0
  314. package/templates/agents/csv.md +2 -1
  315. package/templates/agents/doc.md +52 -3
  316. package/templates/agents/page.md +91 -10
  317. package/templates/agents/slide.md +77 -3
  318. package/templates/agents/xlsx.md +2 -1
  319. package/theme.css +247 -138
  320. package/dist/add-DY4AXANK.js +0 -6
  321. package/dist/add-DY4AXANK.js.map +0 -1
  322. package/dist/chunk-5ZOP4SQR.js +0 -47
  323. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  324. package/dist/chunk-A2UUGASH.js.map +0 -1
  325. package/dist/chunk-CEXAQQ5W.js.map +0 -1
  326. package/dist/chunk-DTDVSFRY.js +0 -29
  327. package/dist/chunk-DTDVSFRY.js.map +0 -1
  328. package/dist/chunk-JKLLFVEU.js.map +0 -1
  329. package/dist/chunk-LMUACBMA.js.map +0 -1
  330. package/dist/chunk-NKFBFDRZ.js +0 -2241
  331. package/dist/chunk-NKFBFDRZ.js.map +0 -1
  332. package/dist/chunk-P7W4LR3Z.js.map +0 -1
  333. package/dist/chunk-PVTHHV7X.js.map +0 -1
  334. package/dist/chunk-PXRX5PEC.js.map +0 -1
  335. package/dist/chunk-QI3XQKHS.js.map +0 -1
  336. package/dist/chunk-RPZAALCX.js.map +0 -1
  337. package/dist/chunk-VA776YE5.js +0 -316
  338. package/dist/chunk-VA776YE5.js.map +0 -1
  339. package/dist/dev-GDKATCC7.js.map +0 -1
@@ -0,0 +1,905 @@
1
+ // Copied by `vantage add ui kpi-card`. This file is yours to edit.
2
+ // Generated from @squadbase/squadkit registry/components/kpi-card.tsx by `pnpm run registry` (in Vantage, edit packages/squadkit, not registry/).
3
+ "use client"
4
+
5
+ /**
6
+ * KpiCard — one metric in five tiers, following shadcn dashboard-01 SectionCards:
7
+ *
8
+ * 1. label (CardDescription, muted)
9
+ * 2. value (CardTitle, tabular-nums; text-4xl once the card is ≥ 320px wide (a comparison label is ~180px, so narrower cards would overlap the value))
10
+ * 3. delta (CardAction: arrow + sign + colour + comparison label — `Delta`)
11
+ * 4. previous actual ("前月 ¥4,290万"; on by default, `showPrevious={false}` hides it)
12
+ * 5. conclusion (`summary`: a *template* whose placeholders the card fills)
13
+ *
14
+ * with optional extras: a target bar under the value (a 6px straight bar — actual
15
+ * in `--chart-1`, the pace projection in `--chart-1/30` (`/45` in dark: 1.33:1 → 1.6:1 against the track, as light has), a 1px tick at the target —
16
+ * and one line "目標の 49%・このペースなら 98%"), then in the footer a record badge
17
+ * from `history`, the data source footnote, the last update time and, with ≥ 6
18
+ * points of `history`, an axis-less sparkline (`showHistory={false}` hides it).
19
+ *
20
+ * Everything derivable is computed here — direction, rate, colour, remaining,
21
+ * achievement, projection, record — so no two props can disagree. Pass enums and
22
+ * numbers only. `history` is the series ending at the current period: its last
23
+ * point should equal `value`.
24
+ *
25
+ * - **Cards in a row line up by subgrid, not by fixed heights.** The card spans two rows of its
26
+ * parent grid (`row-span-2` + `grid-template-rows: subgrid`): row 1 is the body (label, value,
27
+ * delta, previous actual, target bar), row 2 the footer. Cards placed directly in one grid
28
+ * (`grid grid-cols-2 lg:grid-cols-4 gap-4`) therefore share the value baseline and the footer's
29
+ * top edge, and the sparkline sits at the footer's bottom. Outside such a grid the card is a
30
+ * plain grid of the same two rows. The label is one line (truncated, full text in `title`).
31
+ * When the card is narrower than 250px the delta moves from the right of the value to
32
+ * under it (container query, no prop).
33
+ * - **Nothing empty is drawn.** A card with no summary, record badge, target line, source,
34
+ * update time or sparkline has no footer in the DOM; there is no placeholder for the target
35
+ * bar either. No `h-*` / `min-h-*` is used to line cards up.
36
+ * - **`size="sm"`** is for two cards side by side in a narrow place (a Sheet): one step smaller
37
+ * value and padding, and no sparkline.
38
+ * - **`source` is at most two lines** (`line-clamp-2`, full text in `title`).
39
+ * - **Labels follow the grain.** The grain is `comparison.grain`, else
40
+ * `historyGrain`, else inferred from `period`; a monthly card reads "前月比" /
41
+ * "前年同月比" and projects to "月末". Without any of them it reads "前期比".
42
+ * Any other baseline is `vs: "custom"` with a `label` ("昨日比"); the previous
43
+ * line takes its name from it ("昨日 617"), the same way a `label` on any `vs` does.
44
+ * - **Two or more comparisons sit under the value**, not beside it, so the value
45
+ * keeps its place and its width whatever the card holds.
46
+ * - **`betterWhen` drives everything.** With `betterWhen="down"` the target
47
+ * is met at or below it, and the record badge marks the lowest value.
48
+ * - **Rates change in points.** With a `percent` format the delta and
49
+ * `{difference}` are in percentage points ("-0.5pt"); `change="relative"` opts
50
+ * back into the change rate. The target line follows: "目標 95% まであと 2.8pt"
51
+ * instead of a ratio of rates ("97.1% 達成"); `targetDisplay="achievement"` opts back.
52
+ * - **The value has a fixed size.** It never shrinks to fit: a long value wraps its
53
+ * 速報 badge instead of truncating, so neighbouring cards keep one baseline.
54
+ * - **A summary longer than 2 lines is clamped** (full text in `title`), so keep it to one fact.
55
+ *
56
+ * Summary placeholders: `{value}` `{delta}` `{difference}` `{previous}` `{label}`
57
+ * `{target}` `{achievement}` `{remaining}`. Unknown placeholders are left as-is.
58
+ * If a placeholder's value is missing (e.g. no previous period), the whole
59
+ * sentence is replaced with "前月の実績がないため、比較できません。" — or dropped
60
+ * when there is no comparison — so "—" never lands inside a sentence. Write the
61
+ * sentence around them and never put numbers in the template itself.
62
+ *
63
+ * The summary says one fact *beyond* the comparison — composition, target, record,
64
+ * rate. A template made only of `{delta}` / `{difference}` repeats what the badge
65
+ * and the previous actual already say, so it logs a dev warning (once).
66
+ *
67
+ * @example
68
+ * import { KpiCard } from "@/components/kpi-card"
69
+ * // Vantage: import { KpiCard } from "@squadbase/vantage/components"
70
+ *
71
+ * <KpiCard
72
+ * label="売上(今月)"
73
+ * value={48_200_000}
74
+ * format="currency"
75
+ * comparison={{ previous: 42_900_000, vs: "prior-period" }}
76
+ * summary="{label}は前月から {difference}({delta})伸びています。"
77
+ * target={60_000_000}
78
+ * period={{ start: "2026-10-01", end: "2026-11-01" }}
79
+ * />
80
+ */
81
+ import type { ComponentProps } from "react"
82
+
83
+ import { cn } from "@squadbase/vantage/ui"
84
+ import {
85
+ comparisonBaseline,
86
+ computeComparison,
87
+ defaultChangeDisplay,
88
+ formatChange,
89
+ type ChangeDisplay,
90
+ type Comparison,
91
+ type PeriodGrain,
92
+ type Polarity,
93
+ } from "@squadbase/vantage/components"
94
+ import { EMPTY_VALUE, formatDate, formatDatesInText, formatDelta, formatKind, formatPoints, formatValue, type ValueFormat } from "@squadbase/vantage/components"
95
+ import { computeTargetProgress, detectRecord, inferPeriodGrain, type KpiPeriod } from "@squadbase/vantage/components"
96
+ import { formatRelativeTime } from "@squadbase/vantage/components"
97
+ import { Sparkline } from "@squadbase/vantage/components"
98
+ import { Badge } from "@squadbase/vantage/ui"
99
+ import { Card, CardAction, CardDescription, CardFooter, CardHeader, CardTitle } from "@squadbase/vantage/ui"
100
+ import { Skeleton } from "@squadbase/vantage/ui"
101
+ import { Delta } from "@squadbase/vantage/components"
102
+ import { SampleBadge, useSampleMark } from "@squadbase/vantage/components"
103
+ import { useSyncExternalStore } from "react"
104
+
105
+ /* ---------- inlined from @squadbase/squadkit registry/lib/locale.ts (internal to @squadbase/vantage) ---------- */
106
+
107
+ /**
108
+ * The display language of the parts and the defaults that follow it.
109
+ *
110
+ * The language comes from `<html lang>`: a tag starting with `ja` reads Japanese, anything else English.
111
+ * Without a usable `lang` (missing, invalid, or no `document` — SSR, Node) the locale is `FALLBACK_LOCALE`
112
+ * (`en-US`). A `locale` passed explicitly (a prop, an argument) always wins.
113
+ *
114
+ * Parts read the locale through `useLocale` (`hooks/use-locale`) and pass it down; the pure helpers here
115
+ * and in `format` / `comparison` / `chart-*` take it as an argument and fall back to `documentLocale()`.
116
+ */
117
+
118
+ /** The language of the built-in wording: Japanese or English. */
119
+ type UiLanguage = "ja" | "en"
120
+
121
+ /** The locale used when `<html lang>` gives none (and on the server). */
122
+ const FALLBACK_LOCALE = "en-US"
123
+
124
+ /** `"ja"` when `locale` starts with `ja` (`ja`, `ja-JP`), else `"en"`. A missing locale is `"en"`. */
125
+ function uiLanguage(locale: string | null | undefined): UiLanguage {
126
+ return typeof locale === "string" && locale.trim().toLowerCase().startsWith("ja") ? "ja" : "en"
127
+ }
128
+
129
+ /** A BCP 47 tag in its canonical form (`en-gb` → `en-GB`), or `FALLBACK_LOCALE` when it is empty or invalid. */
130
+ function normalizeLocale(tag: string | null | undefined): string {
131
+ const value = tag?.trim()
132
+ if (!value) return FALLBACK_LOCALE
133
+ try {
134
+ return Intl.getCanonicalLocales(value)[0] ?? FALLBACK_LOCALE
135
+ } catch {
136
+ return FALLBACK_LOCALE
137
+ }
138
+ }
139
+
140
+ /**
141
+ * The locale of the page: `document.documentElement.lang`, canonicalized. `FALLBACK_LOCALE` when it is empty or
142
+ * invalid, or there is no `document`. Parts read it through `useLocale`, never while rendering.
143
+ */
144
+ function documentLocale(): string {
145
+ if (typeof document === "undefined") return FALLBACK_LOCALE
146
+ return normalizeLocale(document.documentElement?.getAttribute("lang"))
147
+ }
148
+
149
+ /** `locale` when given, else the page's locale (`documentLocale()`). */
150
+ function resolveLocale(locale?: string | null): string {
151
+ return locale || documentLocale()
152
+ }
153
+
154
+ /** Picks the wording table of the locale's language. */
155
+ function pickLocale<T>(table: { ja: T; en: T }, locale?: string | null): T {
156
+ return table[uiLanguage(resolveLocale(locale))]
157
+ }
158
+
159
+ /** The currency `format="currency"` uses without a `currency`: JPY for Japanese, USD otherwise. */
160
+ function defaultCurrency(locale?: string | null): string {
161
+ return uiLanguage(resolveLocale(locale)) === "ja" ? "JPY" : "USD"
162
+ }
163
+
164
+ /** The month a fiscal year starts in (1–12) when none is given: April for Japanese, January otherwise. */
165
+ function defaultFiscalYearStartMonth(locale?: string | null): number {
166
+ return uiLanguage(resolveLocale(locale)) === "ja" ? 4 : 1
167
+ }
168
+
169
+ /** A day of the week, 0 = Sunday … 6 = Saturday (the `Date#getDay` / date-fns numbering). */
170
+ type WeekDay = 0 | 1 | 2 | 3 | 4 | 5 | 6
171
+
172
+ /** Locales whose week starts on Sunday when the runtime has no week data. */
173
+ const SUNDAY_FIRST = new Set(["en", "en-US", "en-CA"])
174
+
175
+ /**
176
+ * The first day of the week: Monday for Japanese; otherwise the locale's convention from `Intl.Locale`
177
+ * (`en-US` Sunday, `en-GB` Monday). Without week data in the runtime: Sunday for `en` / `en-US` / `en-CA`,
178
+ * Monday for the rest.
179
+ */
180
+ function weekStartsOn(locale?: string | null): WeekDay {
181
+ const tag = normalizeLocale(resolveLocale(locale))
182
+ if (uiLanguage(tag) === "ja") return 1
183
+ try {
184
+ const info = new Intl.Locale(tag) as Intl.Locale & {
185
+ getWeekInfo?: () => { firstDay: number }
186
+ weekInfo?: { firstDay: number }
187
+ }
188
+ const firstDay = info.getWeekInfo?.().firstDay ?? info.weekInfo?.firstDay
189
+ if (typeof firstDay === "number" && firstDay >= 1 && firstDay <= 7) return (firstDay % 7) as WeekDay
190
+ } catch {
191
+ // Fall through to the table below.
192
+ }
193
+ return SUNDAY_FIRST.has(tag) ? 0 : 1
194
+ }
195
+
196
+ /* ---------- inlined from @squadbase/squadkit registry/hooks/use-locale.ts (internal to @squadbase/vantage) ---------- */
197
+
198
+ const listeners = new Set<() => void>()
199
+ let observer: MutationObserver | null = null
200
+
201
+ /** One observer on `<html lang>` for every subscribed part. */
202
+ function subscribe(onChange: () => void): () => void {
203
+ if (typeof document === "undefined" || typeof MutationObserver === "undefined") return () => {}
204
+ listeners.add(onChange)
205
+ if (!observer) {
206
+ observer = new MutationObserver(() => {
207
+ for (const listener of [...listeners]) listener()
208
+ })
209
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ["lang"] })
210
+ }
211
+ return () => {
212
+ listeners.delete(onChange)
213
+ if (listeners.size === 0 && observer) {
214
+ observer.disconnect()
215
+ observer = null
216
+ }
217
+ }
218
+ }
219
+
220
+ const serverLocale = () => FALLBACK_LOCALE
221
+
222
+ /**
223
+ * The page's locale (`<html lang>`), following changes made while the page runs. On the server and during
224
+ * hydration it is `FALLBACK_LOCALE` (`en-US`), so the markup matches; it switches right after.
225
+ */
226
+ function useDocumentLocale(): string {
227
+ return useSyncExternalStore(subscribe, documentLocale, serverLocale)
228
+ }
229
+
230
+ /** The locale a part renders in: its `locale` prop when given, else the page's (`useDocumentLocale`). */
231
+ function useLocale(locale?: string | null): string {
232
+ const page = useDocumentLocale()
233
+ return locale || page
234
+ }
235
+
236
+ /* ---------- end of inlined code ---------- */
237
+
238
+ export interface KpiCardSource {
239
+ /** Period the data covers (e.g. "2023-04 以降"). ISO year-months / dates in it are written by the card ("2023年4月 以降"). */
240
+ period?: string
241
+ /** Number of rows aggregated; formatted by the card ("48,210件から集計"). */
242
+ count?: number
243
+ /**
244
+ * 集計から除いた行数。出典の脚注に「12件を除外」と添える(ja 以外は「12 excluded」)。0 や負の値は出さない。
245
+ * 除外の理由(テスト用アカウント、欠損など)は `note` に書く。
246
+ * @example source={{ count: 48_210, excluded: 12, note: "テスト用アカウントを除外" }}
247
+ */
248
+ excluded?: number
249
+ /** Data source name (e.g. "Snowflake"). */
250
+ name?: string
251
+ /** 換算・税抜などの脚注。フッターに出す。例: `note: "税抜、1 ドル=150 円で換算"`。数字を使う説明は summary ではなくここへ。 */
252
+ note?: string
253
+ }
254
+
255
+ export interface KpiCardProps extends Omit<ComponentProps<"div">, "children"> {
256
+ /** Metric name (tier 1). */
257
+ label: string
258
+ /** Current value (tier 2). null / undefined renders "—". */
259
+ value: number | null | undefined
260
+ /**
261
+ * Value format, also used for previous / target / remaining. Default `"compact"`.
262
+ * `"currency"` is JPY in 万・億 on a ja page (USD in K・M・B otherwise); `"percent"` takes a ratio (0.021 → 2.1%) and
263
+ * switches the delta to points. See `formatValue` for the full table.
264
+ */
265
+ format?: ValueFormat
266
+ /** Locale of the numbers and the built-in wording. Default: the page's (`<html lang>`, else `"en-US"`). */
267
+ locale?: string
268
+ /**
269
+ * What the value is compared against; drives the delta (tier 3) and previous line (tier 4).
270
+ * 前期・前年・目標以外は `vs: "custom"` + `label`(バッジの呼び名。末尾の「比」を外した語が前期実績行の呼び名になる)。
271
+ * @example comparison={{ previous: 617, vs: "custom", label: "昨日比" }}
272
+ */
273
+ comparison?: Comparison
274
+ /**
275
+ * 前年比と前月比など、複数の比較を併記する。先頭だけが前期実績行と summary に使われ、2 つ目以降は Delta 行のみ。`comparison` も渡したらそれが先頭。バッジは値の下に並ぶ。
276
+ * @example comparisons={[{ previous: 4_290, vs: "prior-period", grain: "month" }, { previous: 3_900, vs: "prior-year", grain: "month" }]} / comparisons={[{ previous: 617, vs: "custom", label: "昨日比" }, { previous: 590, vs: "custom", label: "先週の同じ曜日比" }]}
277
+ */
278
+ comparisons?: Comparison[]
279
+ /**
280
+ * 確定前の値。値の隣に「速報」バッジを出し、目標の「達成」を言い切らず、最高記録の判定も出さない。
281
+ * @example provisional / provisional={{ label: "暫定" }}
282
+ */
283
+ provisional?: boolean | { label?: string }
284
+ /** Which direction is good: `"up"` (default) or `"down"` (churn, error rate). Wins over `polarity`. */
285
+ betterWhen?: "up" | "down"
286
+ /** @deprecated Older name of `betterWhen` (`"higher-is-better"` / `"lower-is-better"`). `"neutral"` (never colours the change, skips the target and record logic) is only reachable here. `betterWhen` wins if both are given. */
287
+ polarity?: Polarity
288
+ /** `"relative"` ("+12.4%"), `"points"` ("-0.5pt") or `"difference"` ("+¥530万", in `format`). Default: points for a `percent` format, else relative. */
289
+ change?: ChangeDisplay
290
+ /** Absolute ratio below which the change reads as flat. Default 0.01. */
291
+ neutralBand?: number
292
+ /** Show the previous actual ("前月 400"). Default true; needs `comparison`. */
293
+ showPrevious?: boolean
294
+ /** Conclusion sentence template (tier 5); see the placeholders above. */
295
+ summary?: string
296
+ /**
297
+ * Target for the current period. Under the value it adds a 6px bar (actual, the pace
298
+ * projection, a tick at the target) and one line "目標の 49%・このペースなら 98%"
299
+ * (the projection only while `period` is in progress). With `betterWhen="down"`
300
+ * or a rate target (points) there is no bar: "目標 … まであと …" in the footer.
301
+ */
302
+ target?: number
303
+ /**
304
+ * 目標行・見込み行での目標の呼び名。既定「目標」。予算・計画・ノルマなど業務の言葉に合わせる。
305
+ * @example targetLabel="予算" // 予算まであと ¥2,934万(98.1% 達成)
306
+ */
307
+ targetLabel?: string
308
+ /**
309
+ * 目標に対する進み具合の出し方。`"achievement"` は達成率(現在値 ÷ 目標。「98.1% 達成」)、`"points"` は目標との差(「あと 2.8pt」)。
310
+ * 既定は `format` から決まる: `percent`(率)は `"points"`(率を率で割った達成度は読めない)、それ以外は `"achievement"`。
311
+ * `"points"` のとき `{achievement}` は目標との符号付きの差("-2.8pt")になり、見込み行は出ない。
312
+ */
313
+ targetDisplay?: "achievement" | "points"
314
+ /** Current period; with `target`, adds a pace projection while the period is in progress. */
315
+ period?: KpiPeriod
316
+ /** Series ending at the current period (last point = `value`); adds a record badge. */
317
+ history?: ReadonlyArray<number | null | undefined>
318
+ /** Grain of `history` (and of the comparison labels). Default: inferred from `period`, else `"month"` for the record. */
319
+ historyGrain?: PeriodGrain
320
+ /**
321
+ * `history` が 6 点以上あるとき、フッター末尾に軸なしのスパークライン(高さ 32px・`--chart-1`・最新点だけドット)を出す。既定 true。
322
+ * 推移を出したくないカードは `showHistory={false}`(記録バッジは `history` があれば出る)。
323
+ * @example showHistory={false}
324
+ */
325
+ showHistory?: boolean
326
+ /** Data source footnote. */
327
+ source?: KpiCardSource
328
+ /** When the data was last refreshed: "3 分前に更新". 出し方は `updatedAtDisplay`。 */
329
+ updatedAt?: Date | string | number
330
+ /**
331
+ * `updatedAt` の出し方。`"relative"`(既定)は「3 分前に更新」、`"absolute"` は「2026/10/20 14:30 に更新」、
332
+ * `"both"` は「2026/10/20 14:30 に更新(3 分前)」。絶対時刻は実行環境のタイムゾーンで出す(`timeZone` で固定できる)。
333
+ * 画面を印刷・スクリーンショットで残すなら、時間が経っても読める `"absolute"` か `"both"`。
334
+ * @example updatedAtDisplay="absolute"
335
+ */
336
+ updatedAtDisplay?: "relative" | "absolute" | "both"
337
+ /**
338
+ * `updatedAt` の絶対時刻(`updatedAtDisplay` が `"absolute"` / `"both"`)を出すタイムゾーン(IANA 名。例 `"Asia/Tokyo"`)。
339
+ * 既定は実行環境(ブラウザ)のタイムゾーン。サーバーとブラウザで表示が食い違う(SSR)なら固定する。「3 分前」には影響しない。
340
+ * @example updatedAtDisplay="absolute" timeZone="Asia/Tokyo"
341
+ */
342
+ timeZone?: string
343
+ /** Reference time for the projection and relative time (for deterministic rendering). */
344
+ now?: Date | number
345
+ /** Render a skeleton with the final shape instead of the values. */
346
+ isLoading?: boolean
347
+ /**
348
+ * `"sm"` は Sheet の中など狭い場所で 2 枚を横に並べるときの小さいサイズ。値の文字と余白が一段小さくなり、スパークラインは出さない。既定 `"default"`。
349
+ * @example size="sm"
350
+ */
351
+ size?: "default" | "sm"
352
+ }
353
+
354
+ /** Points of `history` from which the footer shows a sparkline (the same bar as the record badge). */
355
+ const SPARKLINE_MIN_POINTS = 6
356
+
357
+ /** Height of the footer sparkline, in px. */
358
+ const SPARKLINE_HEIGHT = 32
359
+
360
+ /**
361
+ * The delta sits right of the value once the card is ≥ 320px wide (a comparison label is ~180px, so narrower cards would overlap the value) (the shadcn
362
+ * `CardAction` slot) and drops under the value below that — a container query,
363
+ * so a narrow card needs no prop.
364
+ */
365
+ const DELTA_PLACEMENT =
366
+ "col-start-1 row-span-1 row-start-3 justify-self-start @[288px]/card:col-start-2 @[288px]/card:row-span-2 @[288px]/card:row-start-1 @[288px]/card:justify-self-end"
367
+
368
+ /**
369
+ * The header is the size container (`@container/card`), not the card: a container sets layout containment, which turns the
370
+ * card's `grid-rows-subgrid` into a plain grid and the rows stop lining up. Its content box is the card minus both paddings
371
+ * (32px; 24px for `sm`), so 218px / 288px here are the 250px / 320px card widths. It also owns the gap above the footer.
372
+ */
373
+ const HEADER_CLASS = "@container/card pb-(--card-spacing)"
374
+ /** A value this long (a huge standard-notation currency) may wrap between digit groups, and its delta then moves under it so the number gets the full row. Ordinary values stay on one line beside the delta. */
375
+ const LONG_VALUE_CHARS = 10
376
+ const DELTA_UNDER_PLACEMENT = "col-start-1 row-span-1 row-start-3 justify-self-start"
377
+ // No grey footer band: value, comparison and notes share one surface, 8px apart (the footer only keeps its subgrid row).
378
+ const KPI_FOOTER_CLASS = "flex-col items-start gap-2 rounded-none border-t-0 bg-transparent pt-0 text-sm"
379
+
380
+ const PLACEHOLDER = /\{(\w+)\}/g
381
+
382
+ const TEXT = {
383
+ ja: {
384
+ target: "目標",
385
+ provisional: "速報",
386
+ joiner: "・",
387
+ countFrom: (count: string) => `${count}件から集計`,
388
+ excluded: (count: string) => `${count}件を除外`,
389
+ noBaseline: (baseline: string) => `${baseline}の実績がないため、比較できません。`,
390
+ previous: (baseline: string, value: string) => `${baseline} ${value}`,
391
+ noPrevious: (baseline: string) => `${baseline}の実績なし`,
392
+ barLead: (tl: string, pct: string) => `${tl}の ${pct}`,
393
+ pace: (pct: string) => `このペースなら ${pct}`,
394
+ provisionalSuffix: "(確定前)",
395
+ provisionalReached: (tl: string, target: string) => `${tl} ${target} に到達(確定前)`,
396
+ provisionalSoFar: (tl: string, target: string, pct: string) => `${tl} ${target} に対して現時点 ${pct}(確定前)`,
397
+ provisionalToGo: (tl: string, target: string, distance: string) => `${tl} ${target} まであと ${distance}(確定前)`,
398
+ provisionalToGoRate: (tl: string, distance: string, pct: string) => `${tl}まであと ${distance}(現時点 ${pct}・確定前)`,
399
+ met: (tl: string, target: string) => `${tl} ${target} を達成`,
400
+ toGo: (tl: string, target: string, distance: string) => `${tl} ${target} まであと ${distance}`,
401
+ reached: (tl: string, target: string) => `${tl} ${target} に到達`,
402
+ reachedRate: (tl: string, target: string, pct: string) => `${tl} ${target} に到達(${pct} 達成)`,
403
+ toGoRate: (tl: string, distance: string, pct: string) => `${tl}まであと ${distance}(${pct} 達成)`,
404
+ progressLabel: (tl: string) => `${tl}に対する進捗`,
405
+ progressValue: (tl: string, target: string, value: string, pct: string) => `${tl} ${target} に対して ${value}(${pct})`,
406
+ history: (label: string, points: number) => `${label}の推移(直近 ${points} 点)`,
407
+ updatedRelative: (relative: string) => `${relative}に更新`,
408
+ updatedAbsolute: (absolute: string) => `${absolute} に更新`,
409
+ updatedBoth: (absolute: string, relative: string) => `${absolute} に更新(${relative})`,
410
+ summaryExample: "{label}は目標の {achievement} まで来ています。",
411
+ },
412
+ en: {
413
+ target: "Target",
414
+ provisional: "Preliminary",
415
+ joiner: " · ",
416
+ countFrom: (count: string) => `Based on ${count} records`,
417
+ excluded: (count: string) => `${count} excluded`,
418
+ noBaseline: (baseline: string) => `No ${baseline} data to compare against.`,
419
+ previous: (baseline: string, value: string) => `${capitalize(baseline)}: ${value}`,
420
+ noPrevious: (baseline: string) => `No ${baseline} data`,
421
+ barLead: (tl: string, pct: string) => `${tl}: ${pct}`,
422
+ pace: (pct: string) => `On pace for ${pct}`,
423
+ provisionalSuffix: " (preliminary)",
424
+ provisionalReached: (tl: string, target: string) => `${tl} ${target}: reached (preliminary)`,
425
+ provisionalSoFar: (tl: string, target: string, pct: string) => `${tl} ${target}: ${pct} so far (preliminary)`,
426
+ provisionalToGo: (tl: string, target: string, distance: string) => `${tl} ${target}: ${distance} to go (preliminary)`,
427
+ provisionalToGoRate: (tl: string, distance: string, pct: string) => `${tl}: ${distance} to go (${pct} so far, preliminary)`,
428
+ met: (tl: string, target: string) => `${tl} ${target}: met`,
429
+ toGo: (tl: string, target: string, distance: string) => `${tl} ${target}: ${distance} to go`,
430
+ reached: (tl: string, target: string) => `${tl} ${target}: reached`,
431
+ reachedRate: (tl: string, target: string, pct: string) => `${tl} ${target}: reached (${pct} achieved)`,
432
+ toGoRate: (tl: string, distance: string, pct: string) => `${tl}: ${distance} to go (${pct} achieved)`,
433
+ progressLabel: (tl: string) => `Progress toward ${tl}`,
434
+ progressValue: (tl: string, target: string, value: string, pct: string) => `${value} of ${tl} ${target} (${pct})`,
435
+ history: (label: string, points: number) => `${label} trend (last ${points} points)`,
436
+ updatedRelative: (relative: string) => `Updated ${relative}`,
437
+ updatedAbsolute: (absolute: string) => `Updated ${absolute}`,
438
+ updatedBoth: (absolute: string, relative: string) => `Updated ${absolute} (${relative})`,
439
+ summaryExample: "{label} is at {achievement} of target.",
440
+ },
441
+ } satisfies Record<UiLanguage, unknown>
442
+
443
+ type KpiText = (typeof TEXT)[UiLanguage]
444
+
445
+ function capitalize(text: string): string {
446
+ return text.charAt(0).toUpperCase() + text.slice(1)
447
+ }
448
+
449
+ const isMissing = (v: string | null | undefined) => v === null || v === undefined || v === ""
450
+
451
+ /**
452
+ * Fill `{name}` placeholders from `values`. Unknown names stay as written.
453
+ *
454
+ * Without `fallback`, a known name whose value is null / undefined / empty
455
+ * becomes "—". With `fallback`, any such missing value replaces the whole
456
+ * sentence with `fallback` (which may be null to drop it).
457
+ */
458
+ export function fillKpiTemplate(template: string, values: Readonly<Record<string, string | null | undefined>>): string
459
+ export function fillKpiTemplate(
460
+ template: string,
461
+ values: Readonly<Record<string, string | null | undefined>>,
462
+ fallback: string | null,
463
+ ): string | null
464
+ export function fillKpiTemplate(
465
+ template: string,
466
+ values: Readonly<Record<string, string | null | undefined>>,
467
+ fallback?: string | null,
468
+ ): string | null {
469
+ let missing = false
470
+ const filled = template.replace(PLACEHOLDER, (match, name: string) => {
471
+ if (!Object.prototype.hasOwnProperty.call(values, name)) return match
472
+ const v = values[name]
473
+ if (isMissing(v)) {
474
+ missing = true
475
+ return EMPTY_VALUE
476
+ }
477
+ return v as string
478
+ })
479
+ return missing && fallback !== undefined ? fallback : filled
480
+ }
481
+
482
+ const SHALLOW_SUMMARY_PLACEHOLDERS = new Set(["delta", "difference"])
483
+
484
+ let shallowSummaryWarned = false
485
+
486
+ /** @internal Lets tests observe the once-only dev warning again. */
487
+ export function resetKpiSummaryWarning() {
488
+ shallowSummaryWarned = false
489
+ }
490
+
491
+ /** True when every placeholder is `{delta}` / `{difference}` — the template only restates the badge. */
492
+ function isShallowSummary(template: string): boolean {
493
+ const names = Array.from(template.matchAll(PLACEHOLDER), (m) => m[1] as string)
494
+ return names.length > 0 && names.every((n) => SHALLOW_SUMMARY_PLACEHOLDERS.has(n))
495
+ }
496
+
497
+ // Bundlers replace `process.env.NODE_ENV` textually; a browser without that define has no `process`.
498
+ declare const process: { env: { NODE_ENV?: string } }
499
+
500
+ function isProduction(): boolean {
501
+ try {
502
+ return process.env.NODE_ENV === "production"
503
+ } catch {
504
+ return true
505
+ }
506
+ }
507
+
508
+ function warnShallowSummary(template: string, t: KpiText) {
509
+ if (shallowSummaryWarned || isProduction() || !isShallowSummary(template)) return
510
+ shallowSummaryWarned = true
511
+ console.warn(
512
+ `[KpiCard] summary="${template}" only repeats the delta badge and the previous actual. Say one fact beyond the comparison — composition, target, record or rate (e.g. "${t.summaryExample}").`,
513
+ )
514
+ }
515
+
516
+ /** Splits formatted text after each thousands separator so a huge standard-notation value wraps between digit groups instead of clipping. The text itself is unchanged. */
517
+ function digitGroups(text: string): string[] {
518
+ return text.match(/[^,,]*[,,]|[^,,]+$/g) ?? [text]
519
+ }
520
+
521
+ export function KpiCard({
522
+ label,
523
+ value,
524
+ format,
525
+ locale: localeProp,
526
+ comparison: comparisonProp,
527
+ comparisons,
528
+ provisional,
529
+ betterWhen,
530
+ polarity: polarityProp,
531
+ change,
532
+ neutralBand,
533
+ showPrevious = true,
534
+ summary,
535
+ target,
536
+ targetLabel,
537
+ targetDisplay,
538
+ period,
539
+ history,
540
+ historyGrain,
541
+ showHistory = true,
542
+ source,
543
+ updatedAt,
544
+ updatedAtDisplay = "relative",
545
+ timeZone,
546
+ now,
547
+ isLoading = false,
548
+ size = "default",
549
+ className,
550
+ ...props
551
+ }: KpiCardProps) {
552
+ const locale = useLocale(localeProp)
553
+ const t = TEXT[uiLanguage(locale)]
554
+ const allComparisons = [...(comparisonProp ? [comparisonProp] : []), ...(comparisons ?? [])]
555
+ const comparison = allComparisons[0]
556
+ const isProvisional = provisional !== undefined && provisional !== false
557
+ const provisionalLabel = typeof provisional === "object" && provisional.label ? provisional.label : t.provisional
558
+ const sample = useSampleMark()
559
+ // `betterWhen` is the documented name and wins over the older `polarity`.
560
+ const polarity: Polarity | undefined = betterWhen ? (betterWhen === "down" ? "lower-is-better" : "higher-is-better") : polarityProp
561
+ const neutral = polarity === "neutral"
562
+ const hasPrevious = comparison !== undefined && showPrevious
563
+ // Two or more badges would squeeze the value from the right; they get their own row under it instead.
564
+ const stacked = allComparisons.length > 1
565
+ const hasTarget = target !== undefined
566
+ const grain = comparison?.grain ?? historyGrain ?? inferPeriodGrain(period)
567
+ const record = isProvisional || neutral ? null : detectRecord(history, historyGrain ?? grain, polarity, locale)
568
+ const sourceParts = source
569
+ ? [
570
+ source.period !== undefined ? formatDatesInText(source.period, locale) : undefined,
571
+ source.count !== undefined ? t.countFrom(formatValue(source.count, "number", locale)) : undefined,
572
+ source.excluded !== undefined && Number.isFinite(source.excluded) && source.excluded > 0
573
+ ? t.excluded(formatValue(source.excluded, "number", locale))
574
+ : undefined,
575
+ source.name,
576
+ source.note,
577
+ ].filter((p): p is string => typeof p === "string" && p !== "")
578
+ : []
579
+ const hasUpdated = updatedAt !== undefined
580
+ const historyPoints = (history ?? []).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
581
+ const small = size === "sm"
582
+ const showSparkline = !small && showHistory && historyPoints.length >= SPARKLINE_MIN_POINTS
583
+ const isRate = formatKind(format) === "percent"
584
+ const byPoints = (targetDisplay ?? (isRate ? "points" : "achievement")) === "points"
585
+ const lower = polarity === "lower-is-better"
586
+ // The bar reads "how far toward the target"; a rate (points) or a lower-is-better target has no such fill.
587
+ const targetBar = hasTarget && !neutral && !byPoints && !lower
588
+ if (summary !== undefined) warnShallowSummary(summary, t)
589
+ // Two rows of the parent grid (body, footer), shared by subgrid; a plain two-row grid when standalone.
590
+ const cardClass = cn("row-span-2 grid content-start gap-y-0 grid-rows-subgrid", className)
591
+ const valueSize = small ? "text-xl @[218px]/card:text-2xl" : "text-2xl @[218px]/card:text-4xl"
592
+
593
+ if (isLoading) {
594
+ return (
595
+ <Card
596
+ data-slot="kpi-card"
597
+ data-loading=""
598
+ aria-busy="true"
599
+ size={size}
600
+ className={cardClass}
601
+ {...props}
602
+ >
603
+ <CardHeader className={HEADER_CLASS}>
604
+ <CardDescription className="col-start-1">
605
+ <span className="sr-only">{label}</span>
606
+ <Skeleton aria-hidden="true" className="h-5 w-24" />
607
+ </CardDescription>
608
+ <CardTitle className="col-start-1 flex items-center gap-2">
609
+ <Skeleton aria-hidden="true" className={small ? "h-7 w-28 @[218px]/card:h-8" : "h-8 w-32 @[218px]/card:h-9"} />
610
+ {/* The mark stays while loading, so the header does not shift when the values arrive. */}
611
+ {sample && <SampleBadge label={sample.label} />}
612
+ </CardTitle>
613
+ {comparison &&
614
+ (stacked ? (
615
+ <div className="flex flex-wrap gap-1">
616
+ {allComparisons.map((_, i) => (
617
+ <Skeleton key={i} aria-hidden="true" className="h-5 w-24 rounded-4xl" />
618
+ ))}
619
+ </div>
620
+ ) : (
621
+ <CardAction className={DELTA_PLACEMENT}>
622
+ <Skeleton aria-hidden="true" className="h-5 w-24 rounded-4xl" />
623
+ </CardAction>
624
+ ))}
625
+ {hasPrevious && <Skeleton aria-hidden="true" className="h-5 w-16" />}
626
+ {targetBar ? (
627
+ <div className="col-span-full mt-1 flex flex-col gap-1.5">
628
+ <Skeleton aria-hidden="true" className="h-2 w-full rounded-full" />
629
+ <Skeleton aria-hidden="true" className="h-5 w-3/5" />
630
+ </div>
631
+ ) : null}
632
+ </CardHeader>
633
+ {(summary || record || (hasTarget && !targetBar) || sourceParts.length > 0 || hasUpdated || showSparkline) && (
634
+ <CardFooter className={KPI_FOOTER_CLASS}>
635
+ {summary && <Skeleton aria-hidden="true" className="h-5 w-4/5" />}
636
+ {record && <Skeleton aria-hidden="true" className="h-5 w-28 rounded-4xl" />}
637
+ {hasTarget && !targetBar && <Skeleton aria-hidden="true" className="h-5 w-3/5" />}
638
+ {sourceParts.length > 0 && <Skeleton aria-hidden="true" className="h-4 w-3/4" />}
639
+ {hasUpdated && <Skeleton aria-hidden="true" className="h-4 w-20" />}
640
+ {showSparkline && <Skeleton aria-hidden="true" className="mt-auto h-8 w-full" />}
641
+ </CardFooter>
642
+ )}
643
+ </Card>
644
+ )
645
+ }
646
+
647
+ const fmt = (v: number | null | undefined) => formatValue(v, format, locale)
648
+ /** An unsigned distance in the metric's unit — points for a rate. */
649
+ const fmtDistance = (v: number) => (isRate ? formatPoints(v, locale, { signDisplay: "never" }) : fmt(v))
650
+ const pct = (v: number) => formatValue(v, { type: "percent", digits: 0 }, locale)
651
+ const tl = targetLabel ?? t.target
652
+ const display = change ?? defaultChangeDisplay(format)
653
+ // Value digits only carry over to a change in points; a relative change keeps its own fixed digits.
654
+ const digits =
655
+ display === "points" && typeof format === "object" && format !== null && "digits" in format ? format.digits : undefined
656
+ const graded = comparison ? { ...comparison, grain } : undefined
657
+ const result = graded ? computeComparison(value, graded, { polarity, neutralBand, locale }) : null
658
+ const baseline = graded ? comparisonBaseline(graded.vs, grain, graded.label, graded.toDate, locale) : null
659
+ const progress = hasTarget && !neutral ? computeTargetProgress(value, target, { period, now, polarity }) : null
660
+ // A linear pace only makes sense for an accumulating total, not for a rate.
661
+ const projectedValue =
662
+ !isRate && !byPoints && progress?.projected != null && progress.elapsed ? (value as number) / progress.elapsed : null
663
+
664
+ const summaryText = summary
665
+ ? fillKpiTemplate(
666
+ summary,
667
+ {
668
+ value: fmt(value),
669
+ label,
670
+ delta: result ? formatChange(result, display, locale, format, digits) : null,
671
+ difference:
672
+ result?.difference != null
673
+ ? isRate
674
+ ? formatPoints(result.difference, locale)
675
+ : formatDelta(result.difference, format, locale)
676
+ : null,
677
+ previous: result?.previous != null ? fmt(result.previous) : null,
678
+ target: hasTarget ? fmt(target) : null,
679
+ achievement: progress
680
+ ? byPoints
681
+ ? formatPoints((value as number) - (target as number), locale)
682
+ : pct(progress.achievement)
683
+ : null,
684
+ remaining: progress ? fmtDistance(progress.remaining) : null,
685
+ },
686
+ result && result.direction === "none" && baseline ? t.noBaseline(baseline) : null,
687
+ )
688
+ : null
689
+
690
+ // Target bar: actual, the pace projection and a tick at the target on one scale.
691
+ const bar = targetBar && progress ? progressBar() : null
692
+
693
+ function progressBar() {
694
+ const actual = Math.max(value as number, 0)
695
+ const projected = projectedValue !== null && projectedValue > actual ? projectedValue : actual
696
+ const scale = Math.max(target as number, actual, projected)
697
+ const at = (v: number) => (scale > 0 ? (v / scale) * 100 : 0)
698
+ const parts = [t.barLead(tl, pct(progress!.achievement))]
699
+ if (projectedValue !== null && progress!.projected != null)
700
+ parts.push(t.pace(formatValue(progress!.projected, { type: "percent", digits: 0 }, locale)))
701
+ return {
702
+ actualAt: at(actual),
703
+ projectedAt: at(projected),
704
+ targetAt: at(target as number),
705
+ lead: parts[0] as string,
706
+ pace: parts[1] ?? null,
707
+ }
708
+ }
709
+
710
+ let targetText: string | null = null
711
+ if (hasTarget && !bar) {
712
+ if (!progress) targetText = `${tl} ${fmt(target)}`
713
+ else if (isProvisional)
714
+ targetText = progress.achieved
715
+ ? byPoints
716
+ ? t.provisionalReached(tl, fmt(target))
717
+ : t.provisionalSoFar(tl, fmt(target), pct(progress.achievement))
718
+ : byPoints
719
+ ? t.provisionalToGo(tl, fmt(target), fmtDistance(progress.remaining))
720
+ : t.provisionalToGoRate(tl, fmtDistance(progress.remaining), pct(progress.achievement))
721
+ else if (lower)
722
+ targetText = progress.achieved
723
+ ? t.met(tl, fmt(target))
724
+ : t.toGo(tl, fmt(target), fmtDistance(progress.remaining))
725
+ else if (byPoints)
726
+ targetText = progress.achieved
727
+ ? t.reached(tl, fmt(target))
728
+ : t.toGo(tl, fmt(target), fmtDistance(progress.remaining))
729
+ else
730
+ targetText = progress.achieved
731
+ ? t.reachedRate(tl, fmt(target), pct(progress.achievement))
732
+ : t.toGoRate(tl, fmtDistance(progress.remaining), pct(progress.achievement))
733
+ }
734
+
735
+ const hasFooter =
736
+ Boolean(summaryText) || record !== null || Boolean(targetText) || sourceParts.length > 0 || hasUpdated || showSparkline
737
+
738
+ const deltas = allComparisons.map((c, i) => (
739
+ <Delta
740
+ key={i}
741
+ value={value}
742
+ comparison={i === 0 ? (graded ?? c) : { ...c, grain: c.grain ?? grain }}
743
+ polarity={polarity}
744
+ neutralBand={neutralBand}
745
+ format={format}
746
+ change={display}
747
+ digits={digits}
748
+ locale={locale}
749
+ />
750
+ ))
751
+
752
+ const valueText = fmt(value)
753
+ const longValue = valueText.length > LONG_VALUE_CHARS
754
+
755
+ return (
756
+ <Card data-slot="kpi-card" size={size} className={cardClass} {...props}>
757
+ <CardHeader className={HEADER_CLASS}>
758
+ <CardDescription data-slot="kpi-card-label" title={label} className="col-start-1 min-w-0 truncate text-[13px] leading-snug font-medium text-muted-foreground">
759
+ {label}
760
+ </CardDescription>
761
+ <CardTitle
762
+ data-slot="kpi-card-value"
763
+ title={valueText}
764
+ className={cn(
765
+ "col-start-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 leading-none font-semibold tracking-tight tabular-nums",
766
+ // Fixed size: the step follows the card width only, never the length of the value.
767
+ valueSize,
768
+ )}
769
+ >
770
+ <span data-slot="kpi-card-value-text" className={longValue ? "min-w-0 break-words" : "whitespace-nowrap"}>
771
+ {longValue
772
+ ? digitGroups(valueText).map((group, i) => (
773
+ <span key={i} className="whitespace-nowrap">
774
+ {group}
775
+ <wbr />
776
+ </span>
777
+ ))
778
+ : valueText}
779
+ </span>
780
+ {isProvisional && (
781
+ <Badge data-slot="kpi-card-provisional" variant="outline" className="align-middle">
782
+ {provisionalLabel}
783
+ </Badge>
784
+ )}
785
+ {sample && <SampleBadge label={sample.label} />}
786
+ </CardTitle>
787
+ {comparison &&
788
+ (stacked ? (
789
+ <div data-slot="kpi-card-comparisons" className="flex flex-wrap items-center gap-1">
790
+ {deltas}
791
+ </div>
792
+ ) : (
793
+ <CardAction className={longValue ? DELTA_UNDER_PLACEMENT : DELTA_PLACEMENT}>{deltas}</CardAction>
794
+ ))}
795
+ {hasPrevious && comparison && (
796
+ <div data-slot="kpi-card-previous" className="col-span-full text-sm text-muted-foreground tabular-nums">
797
+ {result?.previous != null ? t.previous(baseline ?? "", fmt(result.previous)) : t.noPrevious(baseline ?? "")}
798
+ </div>
799
+ )}
800
+ {bar && progress && (
801
+ <div data-slot="kpi-card-target-progress" className="col-span-full mt-1 flex min-w-0 flex-col gap-1.5">
802
+ <div
803
+ data-slot="kpi-card-target-bar"
804
+ role="progressbar"
805
+ aria-label={t.progressLabel(tl)}
806
+ aria-valuemin={0}
807
+ aria-valuemax={target}
808
+ aria-valuenow={Math.min(Math.max(value as number, 0), target as number)}
809
+ aria-valuetext={t.progressValue(tl, fmt(target), fmt(value), pct(progress.achievement))}
810
+ className="relative h-2 w-full overflow-hidden rounded-full bg-muted"
811
+ >
812
+ <div className="absolute inset-y-0 left-0 bg-chart-1" style={{ width: `${bar.actualAt}%` }} />
813
+ {bar.projectedAt > bar.actualAt && (
814
+ <div
815
+ data-slot="kpi-card-target-bar-projection"
816
+ className="absolute inset-y-0 bg-chart-1/30 dark:bg-chart-1/45"
817
+ style={{ left: `${bar.actualAt}%`, width: `${bar.projectedAt - bar.actualAt}%` }}
818
+ />
819
+ )}
820
+ <div
821
+ data-slot="kpi-card-target-bar-tick"
822
+ className="absolute inset-y-0 w-px bg-foreground"
823
+ style={{ left: `${bar.targetAt}%`, transform: bar.targetAt >= 100 ? "translateX(-1px)" : undefined }}
824
+ />
825
+ </div>
826
+ <p
827
+ data-slot="kpi-card-target"
828
+ title={[bar.lead, bar.pace].filter(Boolean).join(t.joiner)}
829
+ className="truncate text-sm text-muted-foreground tabular-nums"
830
+ >
831
+ {bar.lead}
832
+ {bar.pace && (
833
+ <>
834
+ {t.joiner}
835
+ <span data-slot="kpi-card-projection" data-estimate="">{bar.pace}</span>
836
+ </>
837
+ )}
838
+ {isProvisional && t.provisionalSuffix}
839
+ </p>
840
+ </div>
841
+ )}
842
+ </CardHeader>
843
+ {hasFooter && (
844
+ <CardFooter className={KPI_FOOTER_CLASS}>
845
+ {summaryText && (
846
+ <p data-slot="kpi-card-summary" title={summaryText} className="line-clamp-2 text-sm leading-relaxed text-muted-foreground tabular-nums">
847
+ {summaryText}
848
+ </p>
849
+ )}
850
+ {record && (
851
+ <Badge data-slot="kpi-card-record" variant="outline">
852
+ {record.label}
853
+ </Badge>
854
+ )}
855
+ {targetText && (
856
+ <p data-slot="kpi-card-target" className="text-muted-foreground tabular-nums">
857
+ {targetText}
858
+ </p>
859
+ )}
860
+ {sourceParts.length > 0 && (
861
+ <p
862
+ data-slot="kpi-card-source"
863
+ title={sourceParts.join(t.joiner)}
864
+ className="line-clamp-2 w-full text-xs leading-normal text-muted-foreground tabular-nums"
865
+ >
866
+ {sourceParts.join(t.joiner)}
867
+ </p>
868
+ )}
869
+ {hasUpdated && (
870
+ <p data-slot="kpi-card-updated" className="text-xs leading-normal text-muted-foreground">
871
+ {updatedAtText(updatedAt, updatedAtDisplay, locale, t, now, timeZone)}
872
+ </p>
873
+ )}
874
+ {showSparkline && (
875
+ // mt-auto: the footers of a row are as tall as the tallest, so the sparklines share one bottom edge.
876
+ <div data-slot="kpi-card-history" className="mt-auto w-full pt-2 text-chart-1">
877
+ <Sparkline
878
+ data={historyPoints.map((v) => ({ value: v }))}
879
+ height={SPARKLINE_HEIGHT}
880
+ color="text-chart-1"
881
+ highlight="latest"
882
+ aria-label={t.history(label, historyPoints.length)}
883
+ />
884
+ </div>
885
+ )}
886
+ </CardFooter>
887
+ )}
888
+ </Card>
889
+ )
890
+ }
891
+
892
+ /** 「3 分前に更新」「2026/10/20 14:30 に更新」「2026/10/20 14:30 に更新(3 分前)」(英語は "Updated 3 minutes ago" など)。 */
893
+ function updatedAtText(
894
+ updatedAt: Date | string | number,
895
+ display: "relative" | "absolute" | "both",
896
+ locale: string,
897
+ t: KpiText,
898
+ now: Date | number | undefined,
899
+ timeZone?: string,
900
+ ): string {
901
+ const relative = formatRelativeTime(updatedAt, { now, locale })
902
+ if (display === "relative") return t.updatedRelative(relative)
903
+ const absolute = formatDate(updatedAt, "datetime", locale, { timeZone })
904
+ return display === "absolute" ? t.updatedAbsolute(absolute) : t.updatedBoth(absolute, relative)
905
+ }