@squadbase/vantage 0.6.2-dev1.ac99e02 → 0.6.2-dev1.b1f45c0

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 (292) hide show
  1. package/dist/{build-MFWRPYKW.js → build-U7GO26HR.js} +7 -7
  2. package/dist/{build-MFWRPYKW.js.map → build-U7GO26HR.js.map} +1 -1
  3. package/dist/{check-ZBIH422T.js → check-MRVAIHG5.js} +5 -5
  4. package/dist/{check-ZBIH422T.js.map → check-MRVAIHG5.js.map} +1 -1
  5. package/dist/chunk-2IAPIOPS.js +152 -0
  6. package/dist/chunk-2IAPIOPS.js.map +1 -0
  7. package/dist/{chunk-5ZOP4SQR.js → chunk-2N72FKLB.js} +12 -7
  8. package/dist/chunk-2N72FKLB.js.map +1 -0
  9. package/dist/chunk-57GHR5LN.js +163 -0
  10. package/dist/chunk-57GHR5LN.js.map +1 -0
  11. package/dist/chunk-6OTTGAPO.js +44 -0
  12. package/dist/chunk-6OTTGAPO.js.map +1 -0
  13. package/dist/{chunk-OB6UBJXF.js → chunk-7S52M2SL.js} +127 -36
  14. package/dist/chunk-7S52M2SL.js.map +1 -0
  15. package/dist/{chunk-V3LF7BE7.js → chunk-ANZLVSEP.js} +4 -5
  16. package/dist/chunk-ANZLVSEP.js.map +1 -0
  17. package/dist/{chunk-XQUSGIDG.js → chunk-CKWPK4RO.js} +10 -3
  18. package/dist/chunk-CKWPK4RO.js.map +1 -0
  19. package/dist/chunk-JXFCSF3K.js +673 -0
  20. package/dist/chunk-JXFCSF3K.js.map +1 -0
  21. package/dist/{chunk-PXRX5PEC.js → chunk-PDOBHMUQ.js} +3 -3
  22. package/dist/chunk-PDOBHMUQ.js.map +1 -0
  23. package/dist/{chunk-7DZGJQ3P.js → chunk-PJ4SPXHS.js} +23 -6
  24. package/dist/chunk-PJ4SPXHS.js.map +1 -0
  25. package/dist/chunk-QOXXOFGL.js +7051 -0
  26. package/dist/chunk-QOXXOFGL.js.map +1 -0
  27. package/dist/{chunk-CEXAQQ5W.js → chunk-S5MDTHH7.js} +180 -18
  28. package/dist/chunk-S5MDTHH7.js.map +1 -0
  29. package/dist/{chunk-IBGOCWJB.js → chunk-SDJTTMLK.js} +247 -86
  30. package/dist/chunk-SDJTTMLK.js.map +1 -0
  31. package/dist/{chunk-QEWCYW3I.js → chunk-SHZM3EXB.js} +29 -8
  32. package/dist/chunk-SHZM3EXB.js.map +1 -0
  33. package/dist/{chunk-A2UUGASH.js → chunk-U736PVHY.js} +2 -2
  34. package/dist/chunk-U736PVHY.js.map +1 -0
  35. package/dist/{chunk-JKLLFVEU.js → chunk-UWSQUHX6.js} +4 -99
  36. package/dist/chunk-UWSQUHX6.js.map +1 -0
  37. package/dist/cli.js +6 -6
  38. package/dist/client/index.d.ts +2 -0
  39. package/dist/client/index.js +8 -2
  40. package/dist/client/index.js.map +1 -1
  41. package/dist/components/index.d.ts +1596 -100
  42. package/dist/components/index.js +7 -4
  43. package/dist/delta-text-CvwBGJ95.d.ts +15 -0
  44. package/dist/{dev-DCTOHQ6W.js → dev-O42JFQ64.js} +7 -7
  45. package/dist/{dev-DCTOHQ6W.js.map → dev-O42JFQ64.js.map} +1 -1
  46. package/dist/doc/index.d.ts +215 -2
  47. package/dist/doc/index.js +309 -5
  48. package/dist/doc/index.js.map +1 -1
  49. package/dist/{doctor-5E2VEZPK.js → doctor-YD3XAAOT.js} +5 -5
  50. package/dist/{doctor-5E2VEZPK.js.map → doctor-YD3XAAOT.js.map} +1 -1
  51. package/dist/format-U0cQl069.d.ts +243 -0
  52. package/dist/markdown/index.js +1 -1
  53. package/dist/markdown/index.js.map +1 -1
  54. package/dist/query/index.js +2 -2
  55. package/dist/{routes-3SGAFDMC.js → routes-PVKNT777.js} +4 -4
  56. package/dist/{routes-3SGAFDMC.js.map → routes-PVKNT777.js.map} +1 -1
  57. package/dist/slide/index.d.ts +272 -1
  58. package/dist/slide/index.js +974 -4
  59. package/dist/slide/index.js.map +1 -1
  60. package/dist/table/index.js +11 -8
  61. package/dist/table/index.js.map +1 -1
  62. package/dist/ui/index.d.ts +8 -2
  63. package/dist/ui/index.js +22 -112
  64. package/dist/ui/index.js.map +1 -1
  65. package/dist/{upgrade-DBBE6GIR.js → upgrade-6DT7ADRP.js} +4 -4
  66. package/dist/{upgrade-DBBE6GIR.js.map → upgrade-6DT7ADRP.js.map} +1 -1
  67. package/dist/vite/index.js +3 -3
  68. package/docs/en/agent-skills.md +1 -1
  69. package/docs/en/changelog.md +2 -0
  70. package/docs/en/components.md +42 -17
  71. package/docs/en/doc/delta-text.md +40 -0
  72. package/docs/en/doc/doc-action-items.md +49 -0
  73. package/docs/en/doc/doc-callout.md +38 -0
  74. package/docs/en/doc/doc-data-table.md +60 -0
  75. package/docs/en/doc/doc-executive-summary.md +64 -0
  76. package/docs/en/doc/doc-figure.md +56 -0
  77. package/docs/en/doc/doc-key-findings.md +61 -0
  78. package/docs/en/doc/doc-kpi-scorecard.md +80 -0
  79. package/docs/en/doc/doc-notes-and-sources.md +43 -0
  80. package/docs/en/doc/doc-report-header.md +46 -0
  81. package/docs/en/pages-and-metadata.md +15 -0
  82. package/docs/en/parts/area-chart.md +99 -0
  83. package/docs/en/parts/bar-chart.md +91 -0
  84. package/docs/en/parts/bar-list.md +50 -0
  85. package/docs/en/parts/category-bar.md +37 -0
  86. package/docs/en/parts/chart-frame.md +39 -0
  87. package/docs/en/parts/data-table.md +22 -0
  88. package/docs/en/parts/delta.md +51 -0
  89. package/docs/en/parts/donut-chart.md +72 -0
  90. package/docs/en/parts/format.md +43 -0
  91. package/docs/en/parts/funnel-steps.md +2 -1
  92. package/docs/en/parts/heatmap.md +53 -0
  93. package/docs/en/parts/kpi-card.md +58 -0
  94. package/docs/en/parts/legend.md +35 -0
  95. package/docs/en/parts/line-chart.md +94 -0
  96. package/docs/en/parts/metric-value.md +3 -2
  97. package/docs/en/parts/progress-circle.md +33 -0
  98. package/docs/en/parts/sample-data.md +39 -0
  99. package/docs/en/parts/scatter-chart.md +56 -0
  100. package/docs/en/parts/sparkline.md +1 -1
  101. package/docs/en/parts/tracker.md +36 -0
  102. package/docs/en/parts/trend-indicator.md +17 -1
  103. package/docs/en/parts/updated-at.md +30 -0
  104. package/docs/en/parts/waterfall-chart.md +56 -0
  105. package/docs/en/slide/slide-chart-full.md +48 -0
  106. package/docs/en/slide/slide-chart-insight.md +52 -0
  107. package/docs/en/slide/slide-columns.md +46 -0
  108. package/docs/en/slide/slide-comparison.md +68 -0
  109. package/docs/en/slide/slide-cover.md +39 -0
  110. package/docs/en/slide/slide-exec-summary.md +47 -0
  111. package/docs/en/slide/slide-heading.md +38 -0
  112. package/docs/en/slide/slide-kpi-grid.md +55 -0
  113. package/docs/en/slide/slide-kpi-hero.md +58 -0
  114. package/docs/en/slide/slide-next-actions.md +49 -0
  115. package/docs/en/slide/slide-scorecard-table.md +54 -0
  116. package/docs/en/slide/slide-section.md +44 -0
  117. package/docs/en/slide/slide-source-line.md +34 -0
  118. package/docs/en/ui/alert-dialog.md +42 -0
  119. package/docs/en/ui/avatar.md +31 -0
  120. package/docs/en/ui/combobox.md +74 -0
  121. package/docs/en/ui/drawer.md +41 -0
  122. package/docs/en/ui/empty.md +1 -1
  123. package/docs/en/ui/error-state.md +4 -3
  124. package/docs/en/ui/field.md +42 -0
  125. package/docs/en/ui/hover-card.md +21 -0
  126. package/docs/en/ui/kbd.md +17 -0
  127. package/docs/en/ui/loading.md +1 -1
  128. package/docs/en/ui/pagination.md +36 -0
  129. package/docs/en/ui/radio-group.md +21 -0
  130. package/docs/en/ui/toast.md +44 -0
  131. package/docs/en/ui/toggle-group.md +4 -3
  132. package/docs/en/ui-and-theming.md +1 -1
  133. package/docs/index.json +917 -77
  134. package/docs/ja/agent-skills.md +1 -1
  135. package/docs/ja/changelog.md +7 -0
  136. package/docs/ja/components.md +39 -16
  137. package/docs/ja/doc/delta-text.md +40 -0
  138. package/docs/ja/doc/doc-action-items.md +49 -0
  139. package/docs/ja/doc/doc-callout.md +38 -0
  140. package/docs/ja/doc/doc-data-table.md +60 -0
  141. package/docs/ja/doc/doc-executive-summary.md +64 -0
  142. package/docs/ja/doc/doc-figure.md +56 -0
  143. package/docs/ja/doc/doc-key-findings.md +61 -0
  144. package/docs/ja/doc/doc-kpi-scorecard.md +80 -0
  145. package/docs/ja/doc/doc-notes-and-sources.md +43 -0
  146. package/docs/ja/doc/doc-report-header.md +46 -0
  147. package/docs/ja/page-types/slide.md +1 -0
  148. package/docs/ja/pages-and-metadata.md +15 -0
  149. package/docs/ja/parts/area-chart.md +49 -25
  150. package/docs/ja/parts/bar-chart.md +50 -24
  151. package/docs/ja/parts/bar-list.md +31 -8
  152. package/docs/ja/parts/chart-frame.md +36 -0
  153. package/docs/ja/parts/data-table.md +22 -0
  154. package/docs/ja/parts/delta.md +51 -0
  155. package/docs/ja/parts/donut-chart.md +45 -26
  156. package/docs/ja/parts/format.md +44 -0
  157. package/docs/ja/parts/funnel-steps.md +27 -8
  158. package/docs/ja/parts/heatmap.md +45 -0
  159. package/docs/ja/parts/kpi-card.md +56 -0
  160. package/docs/ja/parts/legend.md +36 -0
  161. package/docs/ja/parts/line-chart.md +48 -22
  162. package/docs/ja/parts/metric-value.md +3 -2
  163. package/docs/ja/parts/sample-data.md +61 -0
  164. package/docs/ja/parts/scatter-chart.md +69 -0
  165. package/docs/ja/parts/sparkline.md +1 -1
  166. package/docs/ja/parts/trend-indicator.md +17 -1
  167. package/docs/ja/parts/updated-at.md +27 -0
  168. package/docs/ja/parts/waterfall-chart.md +61 -0
  169. package/docs/ja/slide/slide-chart-full.md +48 -0
  170. package/docs/ja/slide/slide-chart-insight.md +52 -0
  171. package/docs/ja/slide/slide-columns.md +46 -0
  172. package/docs/ja/slide/slide-comparison.md +68 -0
  173. package/docs/ja/slide/slide-cover.md +39 -0
  174. package/docs/ja/slide/slide-exec-summary.md +47 -0
  175. package/docs/ja/slide/slide-heading.md +38 -0
  176. package/docs/ja/slide/slide-kpi-grid.md +55 -0
  177. package/docs/ja/slide/slide-kpi-hero.md +58 -0
  178. package/docs/ja/slide/slide-next-actions.md +49 -0
  179. package/docs/ja/slide/slide-scorecard-table.md +54 -0
  180. package/docs/ja/slide/slide-section.md +44 -0
  181. package/docs/ja/slide/slide-source-line.md +34 -0
  182. package/docs/ja/ui/empty.md +1 -1
  183. package/docs/ja/ui/error-state.md +4 -3
  184. package/docs/ja/ui/loading.md +1 -1
  185. package/docs/ja/ui/toggle-group.md +4 -3
  186. package/docs/ja/ui-and-theming.md +2 -2
  187. package/package.json +26 -24
  188. package/registry/ui/accordion.tsx +4 -2
  189. package/registry/ui/alert-dialog.tsx +3 -3
  190. package/registry/ui/alert.tsx +3 -1
  191. package/registry/ui/app-shell.tsx +7 -1
  192. package/registry/ui/area-chart.tsx +2852 -166
  193. package/registry/ui/attention-list.tsx +303 -0
  194. package/registry/ui/avatar.tsx +1 -1
  195. package/registry/ui/badge.tsx +3 -1
  196. package/registry/ui/bar-chart.tsx +2851 -166
  197. package/registry/ui/bar-list.tsx +3531 -90
  198. package/registry/ui/box-plot-chart.tsx +3906 -0
  199. package/registry/ui/breadcrumb.tsx +3 -1
  200. package/registry/ui/button.tsx +3 -1
  201. package/registry/ui/calendar.tsx +3 -1
  202. package/registry/ui/card.tsx +4 -2
  203. package/registry/ui/category-bar.tsx +1025 -16
  204. package/registry/ui/chart-frame.tsx +1393 -0
  205. package/registry/ui/checkbox.tsx +3 -1
  206. package/registry/ui/collapsible.tsx +3 -1
  207. package/registry/ui/combobox.tsx +2 -2
  208. package/registry/ui/command.tsx +3 -1
  209. package/registry/ui/dashboard-card.tsx +71 -28
  210. package/registry/ui/data-table.tsx +678 -56
  211. package/registry/ui/date-range-picker.tsx +245 -64
  212. package/registry/ui/delta.tsx +191 -0
  213. package/registry/ui/dialog.tsx +5 -3
  214. package/registry/ui/donut-chart.tsx +2929 -182
  215. package/registry/ui/drawer.tsx +1 -1
  216. package/registry/ui/dropdown-menu.tsx +5 -3
  217. package/registry/ui/echart.tsx +621 -67
  218. package/registry/ui/field.tsx +1 -1
  219. package/registry/ui/filter-bar.tsx +33 -6
  220. package/registry/ui/funnel-steps.tsx +3344 -49
  221. package/registry/ui/heatmap.tsx +1786 -0
  222. package/registry/ui/histogram-chart.tsx +3986 -0
  223. package/registry/ui/hover-card.tsx +2 -2
  224. package/registry/ui/input-group.tsx +3 -1
  225. package/registry/ui/input.tsx +3 -1
  226. package/registry/ui/kbd.tsx +3 -1
  227. package/registry/ui/kpi-card.tsx +704 -0
  228. package/registry/ui/label.tsx +3 -1
  229. package/registry/ui/legend.tsx +3563 -0
  230. package/registry/ui/line-chart.tsx +2852 -160
  231. package/registry/ui/metric-value.tsx +9 -1
  232. package/registry/ui/multi-select.tsx +11 -5
  233. package/registry/ui/page-shell.tsx +106 -51
  234. package/registry/ui/pagination.tsx +3 -1
  235. package/registry/ui/paired-chart.tsx +3827 -0
  236. package/registry/ui/placeholder.tsx +8 -2
  237. package/registry/ui/popover.tsx +4 -2
  238. package/registry/ui/progress-circle.tsx +607 -12
  239. package/registry/ui/progress.tsx +3 -1
  240. package/registry/ui/radio-group.tsx +1 -1
  241. package/registry/ui/sample-data.tsx +86 -0
  242. package/registry/ui/scatter-chart.tsx +4212 -0
  243. package/registry/ui/scroll-area.tsx +3 -2
  244. package/registry/ui/searchable-select.tsx +8 -3
  245. package/registry/ui/section-header.tsx +5 -3
  246. package/registry/ui/segmented-control.tsx +7 -2
  247. package/registry/ui/select.tsx +4 -2
  248. package/registry/ui/separator.tsx +3 -1
  249. package/registry/ui/sheet.tsx +4 -2
  250. package/registry/ui/sidebar.tsx +4 -2
  251. package/registry/ui/skeleton.tsx +4 -2
  252. package/registry/ui/slider.tsx +4 -2
  253. package/registry/ui/sparkline.tsx +84 -9
  254. package/registry/ui/spinner.tsx +3 -1
  255. package/registry/ui/states.tsx +34 -5
  256. package/registry/ui/status-badge.tsx +83 -41
  257. package/registry/ui/switch.tsx +3 -1
  258. package/registry/ui/table.tsx +4 -2
  259. package/registry/ui/tabs.tsx +5 -3
  260. package/registry/ui/textarea.tsx +3 -1
  261. package/registry/ui/toast.tsx +2 -2
  262. package/registry/ui/toggle-group.tsx +3 -1
  263. package/registry/ui/toggle.tsx +3 -1
  264. package/registry/ui/tooltip.tsx +10 -4
  265. package/registry/ui/tracker.tsx +632 -19
  266. package/registry/ui/trend-indicator.tsx +15 -3
  267. package/registry/ui/updated-at.tsx +122 -0
  268. package/registry/ui/waterfall-chart.tsx +4248 -0
  269. package/skills/vantage-design/SKILL.md +60 -52
  270. package/skills/vantage-design/references/extract.md +26 -27
  271. package/skills/vantage-design/references/format.md +12 -172
  272. package/skills/vantage-design/references/presets.md +50 -110
  273. package/skills/vantage-pitfalls/SKILL.md +5 -0
  274. package/skills/vantage-slide/SKILL.md +54 -36
  275. package/templates/AGENTS.md +44 -16
  276. package/templates/agents/doc.md +48 -0
  277. package/templates/agents/page.md +33 -2
  278. package/templates/agents/slide.md +77 -3
  279. package/theme.css +247 -138
  280. package/dist/chunk-5ZOP4SQR.js.map +0 -1
  281. package/dist/chunk-7DZGJQ3P.js.map +0 -1
  282. package/dist/chunk-A2UUGASH.js.map +0 -1
  283. package/dist/chunk-AG6RZ2RR.js +0 -3208
  284. package/dist/chunk-AG6RZ2RR.js.map +0 -1
  285. package/dist/chunk-CEXAQQ5W.js.map +0 -1
  286. package/dist/chunk-IBGOCWJB.js.map +0 -1
  287. package/dist/chunk-JKLLFVEU.js.map +0 -1
  288. package/dist/chunk-OB6UBJXF.js.map +0 -1
  289. package/dist/chunk-PXRX5PEC.js.map +0 -1
  290. package/dist/chunk-QEWCYW3I.js.map +0 -1
  291. package/dist/chunk-V3LF7BE7.js.map +0 -1
  292. package/dist/chunk-XQUSGIDG.js.map +0 -1
@@ -0,0 +1,704 @@
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 { DEFAULT_LOCALE, 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
+
104
+ export interface KpiCardSource {
105
+ /** Period the data covers (e.g. "2023-04 以降"). ISO year-months / dates in it are written by the card ("2023年4月 以降"). */
106
+ period?: string
107
+ /** Number of rows aggregated; formatted by the card ("48,210件から集計"). */
108
+ count?: number
109
+ /**
110
+ * 集計から除いた行数。出典の脚注に「12件を除外」と添える(ja 以外は「12 excluded」)。0 や負の値は出さない。
111
+ * 除外の理由(テスト用アカウント、欠損など)は `note` に書く。
112
+ * @example source={{ count: 48_210, excluded: 12, note: "テスト用アカウントを除外" }}
113
+ */
114
+ excluded?: number
115
+ /** Data source name (e.g. "Snowflake"). */
116
+ name?: string
117
+ /** 換算・税抜などの脚注。フッターに出す。例: `note: "税抜、1 ドル=150 円で換算"`。数字を使う説明は summary ではなくここへ。 */
118
+ note?: string
119
+ }
120
+
121
+ export interface KpiCardProps extends Omit<ComponentProps<"div">, "children"> {
122
+ /** Metric name (tier 1). */
123
+ label: string
124
+ /** Current value (tier 2). null / undefined renders "—". */
125
+ value: number | null | undefined
126
+ /**
127
+ * Value format, also used for previous / target / remaining. Default `"compact"`.
128
+ * `"currency"` is JPY in 万・億; `"percent"` takes a ratio (0.021 → 2.1%) and
129
+ * switches the delta to points. See `formatValue` for the full table.
130
+ */
131
+ format?: ValueFormat
132
+ /** Default `"ja-JP"`. */
133
+ locale?: string
134
+ /**
135
+ * What the value is compared against; drives the delta (tier 3) and previous line (tier 4).
136
+ * 前期・前年・目標以外は `vs: "custom"` + `label`(バッジの呼び名。末尾の「比」を外した語が前期実績行の呼び名になる)。
137
+ * @example comparison={{ previous: 617, vs: "custom", label: "昨日比" }}
138
+ */
139
+ comparison?: Comparison
140
+ /**
141
+ * 前年比と前月比など、複数の比較を併記する。先頭だけが前期実績行と summary に使われ、2 つ目以降は Delta 行のみ。`comparison` も渡したらそれが先頭。バッジは値の下に並ぶ。
142
+ * @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: "先週の同じ曜日比" }]}
143
+ */
144
+ comparisons?: Comparison[]
145
+ /**
146
+ * 確定前の値。値の隣に「速報」バッジを出し、目標の「達成」を言い切らず、最高記録の判定も出さない。
147
+ * @example provisional / provisional={{ label: "暫定" }}
148
+ */
149
+ provisional?: boolean | { label?: string }
150
+ /** Which direction is good: `"up"` (default) or `"down"` (churn, error rate). Wins over `polarity`. */
151
+ betterWhen?: "up" | "down"
152
+ /** @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. */
153
+ polarity?: Polarity
154
+ /** `"relative"` ("+12.4%"), `"points"` ("-0.5pt") or `"difference"` ("+¥530万", in `format`). Default: points for a `percent` format, else relative. */
155
+ change?: ChangeDisplay
156
+ /** Absolute ratio below which the change reads as flat. Default 0.01. */
157
+ neutralBand?: number
158
+ /** Show the previous actual ("前月 400"). Default true; needs `comparison`. */
159
+ showPrevious?: boolean
160
+ /** Conclusion sentence template (tier 5); see the placeholders above. */
161
+ summary?: string
162
+ /**
163
+ * Target for the current period. Under the value it adds a 6px bar (actual, the pace
164
+ * projection, a tick at the target) and one line "目標の 49%・このペースなら 98%"
165
+ * (the projection only while `period` is in progress). With `betterWhen="down"`
166
+ * or a rate target (points) there is no bar: "目標 … まであと …" in the footer.
167
+ */
168
+ target?: number
169
+ /**
170
+ * 目標行・見込み行での目標の呼び名。既定「目標」。予算・計画・ノルマなど業務の言葉に合わせる。
171
+ * @example targetLabel="予算" // 予算まであと ¥2,934万(98.1% 達成)
172
+ */
173
+ targetLabel?: string
174
+ /**
175
+ * 目標に対する進み具合の出し方。`"achievement"` は達成率(現在値 ÷ 目標。「98.1% 達成」)、`"points"` は目標との差(「あと 2.8pt」)。
176
+ * 既定は `format` から決まる: `percent`(率)は `"points"`(率を率で割った達成度は読めない)、それ以外は `"achievement"`。
177
+ * `"points"` のとき `{achievement}` は目標との符号付きの差("-2.8pt")になり、見込み行は出ない。
178
+ */
179
+ targetDisplay?: "achievement" | "points"
180
+ /** Current period; with `target`, adds a pace projection while the period is in progress. */
181
+ period?: KpiPeriod
182
+ /** Series ending at the current period (last point = `value`); adds a record badge. */
183
+ history?: ReadonlyArray<number | null | undefined>
184
+ /** Grain of `history` (and of the comparison labels). Default: inferred from `period`, else `"month"` for the record. */
185
+ historyGrain?: PeriodGrain
186
+ /**
187
+ * `history` が 6 点以上あるとき、フッター末尾に軸なしのスパークライン(高さ 32px・`--chart-1`・最新点だけドット)を出す。既定 true。
188
+ * 推移を出したくないカードは `showHistory={false}`(記録バッジは `history` があれば出る)。
189
+ * @example showHistory={false}
190
+ */
191
+ showHistory?: boolean
192
+ /** Data source footnote. */
193
+ source?: KpiCardSource
194
+ /** When the data was last refreshed: "3 分前に更新". 出し方は `updatedAtDisplay`。 */
195
+ updatedAt?: Date | string | number
196
+ /**
197
+ * `updatedAt` の出し方。`"relative"`(既定)は「3 分前に更新」、`"absolute"` は「2026/10/20 14:30 に更新」、
198
+ * `"both"` は「2026/10/20 14:30 に更新(3 分前)」。絶対時刻は実行環境のタイムゾーンで出す(`timeZone` で固定できる)。
199
+ * 画面を印刷・スクリーンショットで残すなら、時間が経っても読める `"absolute"` か `"both"`。
200
+ * @example updatedAtDisplay="absolute"
201
+ */
202
+ updatedAtDisplay?: "relative" | "absolute" | "both"
203
+ /**
204
+ * `updatedAt` の絶対時刻(`updatedAtDisplay` が `"absolute"` / `"both"`)を出すタイムゾーン(IANA 名。例 `"Asia/Tokyo"`)。
205
+ * 既定は実行環境(ブラウザ)のタイムゾーン。サーバーとブラウザで表示が食い違う(SSR)なら固定する。「3 分前」には影響しない。
206
+ * @example updatedAtDisplay="absolute" timeZone="Asia/Tokyo"
207
+ */
208
+ timeZone?: string
209
+ /** Reference time for the projection and relative time (for deterministic rendering). */
210
+ now?: Date | number
211
+ /** Render a skeleton with the final shape instead of the values. */
212
+ isLoading?: boolean
213
+ /**
214
+ * `"sm"` は Sheet の中など狭い場所で 2 枚を横に並べるときの小さいサイズ。値の文字と余白が一段小さくなり、スパークラインは出さない。既定 `"default"`。
215
+ * @example size="sm"
216
+ */
217
+ size?: "default" | "sm"
218
+ }
219
+
220
+ /** Points of `history` from which the footer shows a sparkline (the same bar as the record badge). */
221
+ const SPARKLINE_MIN_POINTS = 6
222
+
223
+ /** Height of the footer sparkline, in px. */
224
+ const SPARKLINE_HEIGHT = 32
225
+
226
+ /**
227
+ * 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
228
+ * `CardAction` slot) and drops under the value below that — a container query,
229
+ * so a narrow card needs no prop.
230
+ */
231
+ const DELTA_PLACEMENT =
232
+ "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"
233
+
234
+ /**
235
+ * The header is the size container (`@container/card`), not the card: a container sets layout containment, which turns the
236
+ * card's `grid-rows-subgrid` into a plain grid and the rows stop lining up. Its content box is the card minus both paddings
237
+ * (32px; 24px for `sm`), so 218px / 288px here are the 250px / 320px card widths. It also owns the gap above the footer.
238
+ */
239
+ const HEADER_CLASS = "@container/card pb-(--card-spacing)"
240
+ /** 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. */
241
+ const LONG_VALUE_CHARS = 10
242
+ const DELTA_UNDER_PLACEMENT = "col-start-1 row-span-1 row-start-3 justify-self-start"
243
+ // No grey footer band: value, comparison and notes share one surface, 8px apart (the footer only keeps its subgrid row).
244
+ const KPI_FOOTER_CLASS = "flex-col items-start gap-2 rounded-none border-t-0 bg-transparent pt-0 text-sm"
245
+
246
+ const PLACEHOLDER = /\{(\w+)\}/g
247
+
248
+ const isJapanese = (locale: string) => locale.toLowerCase().startsWith("ja")
249
+
250
+ const isMissing = (v: string | null | undefined) => v === null || v === undefined || v === ""
251
+
252
+ /**
253
+ * Fill `{name}` placeholders from `values`. Unknown names stay as written.
254
+ *
255
+ * Without `fallback`, a known name whose value is null / undefined / empty
256
+ * becomes "—". With `fallback`, any such missing value replaces the whole
257
+ * sentence with `fallback` (which may be null to drop it).
258
+ */
259
+ export function fillKpiTemplate(template: string, values: Readonly<Record<string, string | null | undefined>>): string
260
+ export function fillKpiTemplate(
261
+ template: string,
262
+ values: Readonly<Record<string, string | null | undefined>>,
263
+ fallback: string | null,
264
+ ): string | null
265
+ export function fillKpiTemplate(
266
+ template: string,
267
+ values: Readonly<Record<string, string | null | undefined>>,
268
+ fallback?: string | null,
269
+ ): string | null {
270
+ let missing = false
271
+ const filled = template.replace(PLACEHOLDER, (match, name: string) => {
272
+ if (!Object.prototype.hasOwnProperty.call(values, name)) return match
273
+ const v = values[name]
274
+ if (isMissing(v)) {
275
+ missing = true
276
+ return EMPTY_VALUE
277
+ }
278
+ return v as string
279
+ })
280
+ return missing && fallback !== undefined ? fallback : filled
281
+ }
282
+
283
+ const SHALLOW_SUMMARY_PLACEHOLDERS = new Set(["delta", "difference"])
284
+
285
+ let shallowSummaryWarned = false
286
+
287
+ /** @internal Lets tests observe the once-only dev warning again. */
288
+ export function resetKpiSummaryWarning() {
289
+ shallowSummaryWarned = false
290
+ }
291
+
292
+ /** True when every placeholder is `{delta}` / `{difference}` — the template only restates the badge. */
293
+ function isShallowSummary(template: string): boolean {
294
+ const names = Array.from(template.matchAll(PLACEHOLDER), (m) => m[1] as string)
295
+ return names.length > 0 && names.every((n) => SHALLOW_SUMMARY_PLACEHOLDERS.has(n))
296
+ }
297
+
298
+ // Bundlers replace `process.env.NODE_ENV` textually; a browser without that define has no `process`.
299
+ declare const process: { env: { NODE_ENV?: string } }
300
+
301
+ function isProduction(): boolean {
302
+ try {
303
+ return process.env.NODE_ENV === "production"
304
+ } catch {
305
+ return true
306
+ }
307
+ }
308
+
309
+ function warnShallowSummary(template: string) {
310
+ if (shallowSummaryWarned || isProduction() || !isShallowSummary(template)) return
311
+ shallowSummaryWarned = true
312
+ console.warn(
313
+ `[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. "{label}は目標の {achievement} まで来ています。").`,
314
+ )
315
+ }
316
+
317
+ /** 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. */
318
+ function digitGroups(text: string): string[] {
319
+ return text.match(/[^,,]*[,,]|[^,,]+$/g) ?? [text]
320
+ }
321
+
322
+ export function KpiCard({
323
+ label,
324
+ value,
325
+ format,
326
+ locale = DEFAULT_LOCALE,
327
+ comparison: comparisonProp,
328
+ comparisons,
329
+ provisional,
330
+ betterWhen,
331
+ polarity: polarityProp,
332
+ change,
333
+ neutralBand,
334
+ showPrevious = true,
335
+ summary,
336
+ target,
337
+ targetLabel = "目標",
338
+ targetDisplay,
339
+ period,
340
+ history,
341
+ historyGrain,
342
+ showHistory = true,
343
+ source,
344
+ updatedAt,
345
+ updatedAtDisplay = "relative",
346
+ timeZone,
347
+ now,
348
+ isLoading = false,
349
+ size = "default",
350
+ className,
351
+ ...props
352
+ }: KpiCardProps) {
353
+ const allComparisons = [...(comparisonProp ? [comparisonProp] : []), ...(comparisons ?? [])]
354
+ const comparison = allComparisons[0]
355
+ const isProvisional = provisional !== undefined && provisional !== false
356
+ const provisionalLabel = typeof provisional === "object" && provisional.label ? provisional.label : "速報"
357
+ const sample = useSampleMark()
358
+ // `betterWhen` is the documented name and wins over the older `polarity`.
359
+ const polarity: Polarity | undefined = betterWhen ? (betterWhen === "down" ? "lower-is-better" : "higher-is-better") : polarityProp
360
+ const neutral = polarity === "neutral"
361
+ const hasPrevious = comparison !== undefined && showPrevious
362
+ // Two or more badges would squeeze the value from the right; they get their own row under it instead.
363
+ const stacked = allComparisons.length > 1
364
+ const hasTarget = target !== undefined
365
+ const grain = comparison?.grain ?? historyGrain ?? inferPeriodGrain(period)
366
+ const record = isProvisional || neutral ? null : detectRecord(history, historyGrain ?? grain, polarity)
367
+ const sourceParts = source
368
+ ? [
369
+ source.period !== undefined ? formatDatesInText(source.period, locale) : undefined,
370
+ source.count !== undefined ? `${formatValue(source.count, "number", locale)}件から集計` : undefined,
371
+ source.excluded !== undefined && Number.isFinite(source.excluded) && source.excluded > 0
372
+ ? isJapanese(locale)
373
+ ? `${formatValue(source.excluded, "number", locale)}件を除外`
374
+ : `${formatValue(source.excluded, "number", locale)} excluded`
375
+ : undefined,
376
+ source.name,
377
+ source.note,
378
+ ].filter((p): p is string => typeof p === "string" && p !== "")
379
+ : []
380
+ const hasUpdated = updatedAt !== undefined
381
+ const historyPoints = (history ?? []).filter((v): v is number => typeof v === "number" && Number.isFinite(v))
382
+ const small = size === "sm"
383
+ const showSparkline = !small && showHistory && historyPoints.length >= SPARKLINE_MIN_POINTS
384
+ const isRate = formatKind(format) === "percent"
385
+ const byPoints = (targetDisplay ?? (isRate ? "points" : "achievement")) === "points"
386
+ const lower = polarity === "lower-is-better"
387
+ // The bar reads "how far toward the target"; a rate (points) or a lower-is-better target has no such fill.
388
+ const targetBar = hasTarget && !neutral && !byPoints && !lower
389
+ if (summary !== undefined) warnShallowSummary(summary)
390
+ // Two rows of the parent grid (body, footer), shared by subgrid; a plain two-row grid when standalone.
391
+ const cardClass = cn("row-span-2 grid content-start gap-y-0 grid-rows-subgrid", className)
392
+ const valueSize = small ? "text-xl @[218px]/card:text-2xl" : "text-2xl @[218px]/card:text-4xl"
393
+
394
+ if (isLoading) {
395
+ return (
396
+ <Card
397
+ data-slot="kpi-card"
398
+ data-loading=""
399
+ aria-busy="true"
400
+ size={size}
401
+ className={cardClass}
402
+ {...props}
403
+ >
404
+ <CardHeader className={HEADER_CLASS}>
405
+ <CardDescription className="col-start-1">
406
+ <span className="sr-only">{label}</span>
407
+ <Skeleton aria-hidden="true" className="h-5 w-24" />
408
+ </CardDescription>
409
+ <CardTitle className="col-start-1 flex items-center gap-2">
410
+ <Skeleton aria-hidden="true" className={small ? "h-7 w-28 @[218px]/card:h-8" : "h-8 w-32 @[218px]/card:h-9"} />
411
+ {/* The mark stays while loading, so the header does not shift when the values arrive. */}
412
+ {sample && <SampleBadge label={sample.label} />}
413
+ </CardTitle>
414
+ {comparison &&
415
+ (stacked ? (
416
+ <div className="flex flex-wrap gap-1">
417
+ {allComparisons.map((_, i) => (
418
+ <Skeleton key={i} aria-hidden="true" className="h-5 w-24 rounded-4xl" />
419
+ ))}
420
+ </div>
421
+ ) : (
422
+ <CardAction className={DELTA_PLACEMENT}>
423
+ <Skeleton aria-hidden="true" className="h-5 w-24 rounded-4xl" />
424
+ </CardAction>
425
+ ))}
426
+ {hasPrevious && <Skeleton aria-hidden="true" className="h-5 w-16" />}
427
+ {targetBar ? (
428
+ <div className="col-span-full mt-1 flex flex-col gap-1.5">
429
+ <Skeleton aria-hidden="true" className="h-2 w-full rounded-full" />
430
+ <Skeleton aria-hidden="true" className="h-5 w-3/5" />
431
+ </div>
432
+ ) : null}
433
+ </CardHeader>
434
+ {(summary || record || (hasTarget && !targetBar) || sourceParts.length > 0 || hasUpdated || showSparkline) && (
435
+ <CardFooter className={KPI_FOOTER_CLASS}>
436
+ {summary && <Skeleton aria-hidden="true" className="h-5 w-4/5" />}
437
+ {record && <Skeleton aria-hidden="true" className="h-5 w-28 rounded-4xl" />}
438
+ {hasTarget && !targetBar && <Skeleton aria-hidden="true" className="h-5 w-3/5" />}
439
+ {sourceParts.length > 0 && <Skeleton aria-hidden="true" className="h-4 w-3/4" />}
440
+ {hasUpdated && <Skeleton aria-hidden="true" className="h-4 w-20" />}
441
+ {showSparkline && <Skeleton aria-hidden="true" className="mt-auto h-8 w-full" />}
442
+ </CardFooter>
443
+ )}
444
+ </Card>
445
+ )
446
+ }
447
+
448
+ const fmt = (v: number | null | undefined) => formatValue(v, format, locale)
449
+ /** An unsigned distance in the metric's unit — points for a rate. */
450
+ const fmtDistance = (v: number) => (isRate ? formatPoints(v, locale, { signDisplay: "never" }) : fmt(v))
451
+ const pct = (v: number) => formatValue(v, { type: "percent", digits: 0 }, locale)
452
+ const tl = targetLabel
453
+ const display = change ?? defaultChangeDisplay(format)
454
+ // Value digits only carry over to a change in points; a relative change keeps its own fixed digits.
455
+ const digits =
456
+ display === "points" && typeof format === "object" && format !== null && "digits" in format ? format.digits : undefined
457
+ const graded = comparison ? { ...comparison, grain } : undefined
458
+ const result = graded ? computeComparison(value, graded, { polarity, neutralBand }) : null
459
+ const baseline = graded ? comparisonBaseline(graded.vs, grain, graded.label, graded.toDate) : null
460
+ const progress = hasTarget && !neutral ? computeTargetProgress(value, target, { period, now, polarity }) : null
461
+ // A linear pace only makes sense for an accumulating total, not for a rate.
462
+ const projectedValue =
463
+ !isRate && !byPoints && progress?.projected != null && progress.elapsed ? (value as number) / progress.elapsed : null
464
+
465
+ const summaryText = summary
466
+ ? fillKpiTemplate(
467
+ summary,
468
+ {
469
+ value: fmt(value),
470
+ label,
471
+ delta: result ? formatChange(result, display, locale, format, digits) : null,
472
+ difference:
473
+ result?.difference != null
474
+ ? isRate
475
+ ? formatPoints(result.difference, locale)
476
+ : formatDelta(result.difference, format, locale)
477
+ : null,
478
+ previous: result?.previous != null ? fmt(result.previous) : null,
479
+ target: hasTarget ? fmt(target) : null,
480
+ achievement: progress
481
+ ? byPoints
482
+ ? formatPoints((value as number) - (target as number), locale)
483
+ : pct(progress.achievement)
484
+ : null,
485
+ remaining: progress ? fmtDistance(progress.remaining) : null,
486
+ },
487
+ result && result.direction === "none" && baseline ? `${baseline}の実績がないため、比較できません。` : null,
488
+ )
489
+ : null
490
+
491
+ // Target bar: actual, the pace projection and a tick at the target on one scale.
492
+ const bar = targetBar && progress ? progressBar() : null
493
+
494
+ function progressBar() {
495
+ const actual = Math.max(value as number, 0)
496
+ const projected = projectedValue !== null && projectedValue > actual ? projectedValue : actual
497
+ const scale = Math.max(target as number, actual, projected)
498
+ const at = (v: number) => (scale > 0 ? (v / scale) * 100 : 0)
499
+ const parts = [`${tl}の ${pct(progress!.achievement)}`]
500
+ if (projectedValue !== null && progress!.projected != null)
501
+ parts.push(`このペースなら ${formatValue(progress!.projected, { type: "percent", digits: 0 }, locale)}`)
502
+ return {
503
+ actualAt: at(actual),
504
+ projectedAt: at(projected),
505
+ targetAt: at(target as number),
506
+ lead: parts[0] as string,
507
+ pace: parts[1] ?? null,
508
+ }
509
+ }
510
+
511
+ let targetText: string | null = null
512
+ if (hasTarget && !bar) {
513
+ if (!progress) targetText = `${tl} ${fmt(target)}`
514
+ else if (isProvisional)
515
+ targetText = progress.achieved
516
+ ? byPoints
517
+ ? `${tl} ${fmt(target)} に到達(確定前)`
518
+ : `${tl} ${fmt(target)} に対して現時点 ${pct(progress.achievement)}(確定前)`
519
+ : byPoints
520
+ ? `${tl} ${fmt(target)} まであと ${fmtDistance(progress.remaining)}(確定前)`
521
+ : `${tl}まであと ${fmtDistance(progress.remaining)}(現時点 ${pct(progress.achievement)}・確定前)`
522
+ else if (lower)
523
+ targetText = progress.achieved
524
+ ? `${tl} ${fmt(target)} を達成`
525
+ : `${tl} ${fmt(target)} まであと ${fmtDistance(progress.remaining)}`
526
+ else if (byPoints)
527
+ targetText = progress.achieved
528
+ ? `${tl} ${fmt(target)} に到達`
529
+ : `${tl} ${fmt(target)} まであと ${fmtDistance(progress.remaining)}`
530
+ else
531
+ targetText = progress.achieved
532
+ ? `${tl} ${fmt(target)} に到達(${pct(progress.achievement)} 達成)`
533
+ : `${tl}まであと ${fmtDistance(progress.remaining)}(${pct(progress.achievement)} 達成)`
534
+ }
535
+
536
+ const hasFooter =
537
+ Boolean(summaryText) || record !== null || Boolean(targetText) || sourceParts.length > 0 || hasUpdated || showSparkline
538
+
539
+ const deltas = allComparisons.map((c, i) => (
540
+ <Delta
541
+ key={i}
542
+ value={value}
543
+ comparison={i === 0 ? (graded ?? c) : { ...c, grain: c.grain ?? grain }}
544
+ polarity={polarity}
545
+ neutralBand={neutralBand}
546
+ format={format}
547
+ change={display}
548
+ digits={digits}
549
+ locale={locale}
550
+ />
551
+ ))
552
+
553
+ const valueText = fmt(value)
554
+ const longValue = valueText.length > LONG_VALUE_CHARS
555
+
556
+ return (
557
+ <Card data-slot="kpi-card" size={size} className={cardClass} {...props}>
558
+ <CardHeader className={HEADER_CLASS}>
559
+ <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">
560
+ {label}
561
+ </CardDescription>
562
+ <CardTitle
563
+ data-slot="kpi-card-value"
564
+ title={valueText}
565
+ className={cn(
566
+ "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",
567
+ // Fixed size: the step follows the card width only, never the length of the value.
568
+ valueSize,
569
+ )}
570
+ >
571
+ <span data-slot="kpi-card-value-text" className={longValue ? "min-w-0 break-words" : "whitespace-nowrap"}>
572
+ {longValue
573
+ ? digitGroups(valueText).map((group, i) => (
574
+ <span key={i} className="whitespace-nowrap">
575
+ {group}
576
+ <wbr />
577
+ </span>
578
+ ))
579
+ : valueText}
580
+ </span>
581
+ {isProvisional && (
582
+ <Badge data-slot="kpi-card-provisional" variant="outline" className="align-middle">
583
+ {provisionalLabel}
584
+ </Badge>
585
+ )}
586
+ {sample && <SampleBadge label={sample.label} />}
587
+ </CardTitle>
588
+ {comparison &&
589
+ (stacked ? (
590
+ <div data-slot="kpi-card-comparisons" className="flex flex-wrap items-center gap-1">
591
+ {deltas}
592
+ </div>
593
+ ) : (
594
+ <CardAction className={longValue ? DELTA_UNDER_PLACEMENT : DELTA_PLACEMENT}>{deltas}</CardAction>
595
+ ))}
596
+ {hasPrevious && comparison && (
597
+ <div data-slot="kpi-card-previous" className="col-span-full text-sm text-muted-foreground tabular-nums">
598
+ {result?.previous != null ? `${baseline} ${fmt(result.previous)}` : `${baseline}の実績なし`}
599
+ </div>
600
+ )}
601
+ {bar && progress && (
602
+ <div data-slot="kpi-card-target-progress" className="col-span-full mt-1 flex min-w-0 flex-col gap-1.5">
603
+ <div
604
+ data-slot="kpi-card-target-bar"
605
+ role="progressbar"
606
+ aria-label={`${tl}に対する進捗`}
607
+ aria-valuemin={0}
608
+ aria-valuemax={target}
609
+ aria-valuenow={Math.min(Math.max(value as number, 0), target as number)}
610
+ aria-valuetext={`${tl} ${fmt(target)} に対して ${fmt(value)}(${pct(progress.achievement)})`}
611
+ className="relative h-2 w-full overflow-hidden rounded-full bg-muted"
612
+ >
613
+ <div className="absolute inset-y-0 left-0 bg-chart-1" style={{ width: `${bar.actualAt}%` }} />
614
+ {bar.projectedAt > bar.actualAt && (
615
+ <div
616
+ data-slot="kpi-card-target-bar-projection"
617
+ className="absolute inset-y-0 bg-chart-1/30 dark:bg-chart-1/45"
618
+ style={{ left: `${bar.actualAt}%`, width: `${bar.projectedAt - bar.actualAt}%` }}
619
+ />
620
+ )}
621
+ <div
622
+ data-slot="kpi-card-target-bar-tick"
623
+ className="absolute inset-y-0 w-px bg-foreground"
624
+ style={{ left: `${bar.targetAt}%`, transform: bar.targetAt >= 100 ? "translateX(-1px)" : undefined }}
625
+ />
626
+ </div>
627
+ <p
628
+ data-slot="kpi-card-target"
629
+ title={[bar.lead, bar.pace].filter(Boolean).join("・")}
630
+ className="truncate text-sm text-muted-foreground tabular-nums"
631
+ >
632
+ {bar.lead}
633
+ {bar.pace && (
634
+ <>
635
+ ・<span data-slot="kpi-card-projection" data-estimate="">{bar.pace}</span>
636
+ </>
637
+ )}
638
+ {isProvisional && "(確定前)"}
639
+ </p>
640
+ </div>
641
+ )}
642
+ </CardHeader>
643
+ {hasFooter && (
644
+ <CardFooter className={KPI_FOOTER_CLASS}>
645
+ {summaryText && (
646
+ <p data-slot="kpi-card-summary" title={summaryText} className="line-clamp-2 text-sm leading-relaxed text-muted-foreground tabular-nums">
647
+ {summaryText}
648
+ </p>
649
+ )}
650
+ {record && (
651
+ <Badge data-slot="kpi-card-record" variant="outline">
652
+ {record.label}
653
+ </Badge>
654
+ )}
655
+ {targetText && (
656
+ <p data-slot="kpi-card-target" className="text-muted-foreground tabular-nums">
657
+ {targetText}
658
+ </p>
659
+ )}
660
+ {sourceParts.length > 0 && (
661
+ <p
662
+ data-slot="kpi-card-source"
663
+ title={sourceParts.join("・")}
664
+ className="line-clamp-2 w-full text-xs leading-normal text-muted-foreground tabular-nums"
665
+ >
666
+ {sourceParts.join("・")}
667
+ </p>
668
+ )}
669
+ {hasUpdated && (
670
+ <p data-slot="kpi-card-updated" className="text-xs leading-normal text-muted-foreground">
671
+ {updatedAtText(updatedAt, updatedAtDisplay, locale, now, timeZone)}
672
+ </p>
673
+ )}
674
+ {showSparkline && (
675
+ // mt-auto: the footers of a row are as tall as the tallest, so the sparklines share one bottom edge.
676
+ <div data-slot="kpi-card-history" className="mt-auto w-full pt-2 text-chart-1">
677
+ <Sparkline
678
+ data={historyPoints.map((v) => ({ value: v }))}
679
+ height={SPARKLINE_HEIGHT}
680
+ color="text-chart-1"
681
+ highlight="latest"
682
+ aria-label={`${label}の推移(直近 ${historyPoints.length} 点)`}
683
+ />
684
+ </div>
685
+ )}
686
+ </CardFooter>
687
+ )}
688
+ </Card>
689
+ )
690
+ }
691
+
692
+ /** 「3 分前に更新」「2026/10/20 14:30 に更新」「2026/10/20 14:30 に更新(3 分前)」。 */
693
+ function updatedAtText(
694
+ updatedAt: Date | string | number,
695
+ display: "relative" | "absolute" | "both",
696
+ locale: string,
697
+ now: Date | number | undefined,
698
+ timeZone?: string,
699
+ ): string {
700
+ const relative = formatRelativeTime(updatedAt, { now, locale })
701
+ if (display === "relative") return `${relative}に更新`
702
+ const absolute = formatDate(updatedAt, "datetime", locale, { timeZone })
703
+ return display === "absolute" ? `${absolute} に更新` : `${absolute} に更新(${relative})`
704
+ }