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

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