dashboardcn
blockkpi-row-cardsource: ok · hit
KPI Row Card
A card with a period switcher, a row of KPI tiles with sparklines and deltas, and a footer summary.
npx shadcn add "https://dashboardcn.com/r/kpi-row-card.json"free
Where it goes
footerstats
Visual style
particle
Interaction
animated-counter
Tags auto-generated by rules on 9/24/2026 — empty means no evidence, not lack of support.
Dependencies
Bundle weight · mediumchartsrecharts
iconslucide-react
Registry dependencies
cardtabstooltip
Files6 · source cached 10/9/2026, 11:52:42 PM
registry/dashboardcn/blocks/kpi-row-card.tsx
"use client"
import * as React from "react"
import { ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { type NumberFormat } from "@/registry/dashboardcn/lib/format"
import {
Card,
CardAction,
CardContent,
CardDescription,
CardFooter,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { DeltaBadge, getDeltaDirection } from "@/registry/dashboardcn/ui/delta-badge"
import { PeriodTabs, type PeriodOption } from "@/registry/dashboardcn/ui/period-tabs"
import { Sparkline } from "@/registry/dashboardcn/ui/sparkline"
import { MetricValue } from "@/registry/dashboardcn/ui/metric-value"
export interface KpiRowMetric {
label: string
value: number | string
delta?: number
/** Short word next to the delta, e.g. "Rising". */
note?: string
trend?: number[]
format?: NumberFormat
currency?: string
invertDelta?: boolean
icon?: React.ReactNode
}
export interface KpiRowCardProps extends React.ComponentProps<typeof Card> {
title: string
description?: string
metrics: KpiRowMetric[]
/** Period options for the switcher. Omit to hide it. */
periods?: PeriodOption[]
period?: string
defaultPeriod?: string
onPeriodChange?: (period: string) => void
/** Text in the footer, e.g. a summary sentence. */
footer?: React.ReactNode
/** Footer link. */
action?: { label: string; href: string }
}
/** A card with a row of KPI tiles, each with a sparkline and delta. */
function KpiRowCard({
title,
description,
metrics,
periods,
period,
defaultPeriod,
onPeriodChange,
footer,
action,
className,
...props
}: KpiRowCardProps) {
return (
<Card data-slot="kpi-row-card" className={cn("@container/card gap-4", className)} {...props}>
<CardHeader className="@max-sm/card:[grid-template-columns:minmax(0,1fr)]!">
<CardTitle>{title}</CardTitle>
{description ? <CardDescription>{description}</CardDescription> : null}
{periods ? (
<CardAction className="@max-sm/card:[grid-area:auto]! @max-sm/card:justify-self-start!">
<PeriodTabs
options={periods}
value={period}
defaultValue={defaultPeriod ?? periods[0]?.value}
onValueChange={onPeriodChange}
/>
</CardAction>
) : null}
</CardHeader>
<CardContent>
<div className="@container">
<div className="grid gap-6 @lg:grid-cols-2 @3xl:grid-cols-4 @3xl:divide-x">
{metrics.map((metric) => {
const direction = getDeltaDirection(metric.delta)
const positive =
direction === "flat"
? null
: (direction === "up") !== Boolean(metric.invertDelta)
const color =
positive === true
? "var(--color-emerald-500)"
: positive === false
? "var(--color-red-500)"
: "var(--muted-foreground)"
return (
<div
key={metric.label}
data-slot="kpi-row-metric"
className="flex flex-col gap-2 @3xl:px-6 @3xl:first:pl-0 @3xl:last:pr-0"
>
<div className="text-muted-foreground flex items-center gap-1.5 text-sm [&>svg]:size-4">
{metric.icon}
{metric.label}
</div>
<div className="flex items-end justify-between gap-3">
<div className="flex flex-col gap-1">
<MetricValue
value={metric.value}
format={metric.format}
currency={metric.currency}
className="text-2xl font-semibold tracking-tight"
/>
<span className="flex items-center gap-1.5 text-xs">
{metric.delta !== undefined ? (
<DeltaBadge
delta={metric.delta}
invert={metric.invertDelta}
variant="soft"
showIcon={false}
/>
) : null}
{metric.note ? (
<span className="text-muted-foreground">{metric.note}</span>
) : null}
</span>
</div>
{metric.trend && metric.trend.length > 1 ? (
<Sparkline
data={metric.trend}
variant="line"
color={color}
className="h-9 w-20 shrink-0"
/>
) : null}
</div>
</div>
)
})}
</div>
</div>
</CardContent>
{footer || action ? (
<CardFooter className="text-muted-foreground justify-between gap-4 border-t pt-4 text-xs [.border-t]:pt-4">
<div>{footer}</div>
{action ? (
<a
href={action.href}
className="text-foreground inline-flex shrink-0 items-center gap-1 font-medium hover:underline"
>
{action.label}
<ArrowRight className="size-3.5" />
</a>
) : null}
</CardFooter>
) : null}
</Card>
)
}
export { KpiRowCard }
registry/dashboardcn/ui/delta-badge.tsx
import * as React from "react"
import { Minus, TrendingDown, TrendingUp } from "lucide-react"
import { cn } from "@/lib/utils"
import { formatDelta } from "@/registry/dashboardcn/lib/format"
export type DeltaDirection = "up" | "down" | "flat"
export function getDeltaDirection(delta: number | undefined): DeltaDirection {
if (delta === undefined || delta === 0 || !Number.isFinite(delta)) return "flat"
return delta > 0 ? "up" : "down"
}
const directionIcon: Record<DeltaDirection, React.ElementType> = {
up: TrendingUp,
down: TrendingDown,
flat: Minus,
}
export interface DeltaBadgeProps extends React.ComponentProps<"span"> {
/** Fractional change, e.g. 0.124 for +12.4%. */
delta: number
/** Treat a decrease as good and an increase as bad (churn, latency, errors). */
invert?: boolean
variant?: "outline" | "soft" | "text"
showIcon?: boolean
}
function DeltaBadge({
delta,
invert = false,
variant = "outline",
showIcon = true,
className,
children,
...props
}: DeltaBadgeProps) {
const direction = getDeltaDirection(delta)
const positive = direction === "flat" ? null : (direction === "up") !== invert
const Icon = directionIcon[direction]
return (
<span
data-slot="delta-badge"
data-direction={direction}
data-positive={positive}
className={cn(
"inline-flex items-center gap-1 text-xs font-medium tabular-nums",
variant === "outline" && "rounded-md border px-1.5 py-0.5",
variant === "soft" && "rounded-md px-1.5 py-0.5",
variant === "soft" && positive === true && "bg-emerald-500/10",
variant === "soft" && positive === false && "bg-red-500/10",
variant === "soft" && positive === null && "bg-muted",
positive === true && "text-emerald-600 dark:text-emerald-400",
positive === false && "text-red-600 dark:text-red-400",
positive === null && "text-muted-foreground",
className
)}
{...props}
>
{showIcon ? <Icon className="size-3" aria-hidden="true" /> : null}
{children ?? formatDelta(delta)}
</span>
)
}
export { DeltaBadge }
registry/dashboardcn/ui/period-tabs.tsx
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
export interface PeriodOption {
value: string
label: string
}
export const defaultPeriods: PeriodOption[] = [
{ value: "week", label: "Week" },
{ value: "month", label: "Month" },
{ value: "year", label: "Year" },
]
export interface PeriodTabsProps
extends Omit<React.ComponentProps<typeof Tabs>, "children"> {
options?: PeriodOption[]
size?: "sm" | "default"
/** Slide a single pill between tabs instead of swapping backgrounds. */
animated?: boolean
}
interface IndicatorRect {
left: number
top: number
width: number
height: number
}
/** Small segmented control for switching a chart's time range. */
function PeriodTabs({
options = defaultPeriods,
size = "sm",
animated = false,
className,
value,
defaultValue,
onValueChange,
...props
}: PeriodTabsProps) {
const listRef = React.useRef<HTMLDivElement>(null)
const [internalValue, setInternalValue] = React.useState(
defaultValue ?? options[0]?.value
)
const active = value ?? internalValue
const [rect, setRect] = React.useState<IndicatorRect | null>(null)
const measure = React.useCallback(() => {
const list = listRef.current
if (!list) return
const trigger = list.querySelector<HTMLElement>('[data-state="active"]')
if (!trigger) return
setRect({
left: trigger.offsetLeft,
top: trigger.offsetTop,
width: trigger.offsetWidth,
height: trigger.offsetHeight,
})
}, [])
React.useLayoutEffect(() => {
if (!animated) return
measure()
}, [animated, active, options, size, measure])
React.useEffect(() => {
if (!animated || !listRef.current) return
const observer = new ResizeObserver(measure)
observer.observe(listRef.current)
return () => observer.disconnect()
}, [animated, measure])
return (
<Tabs
data-slot="period-tabs"
className={cn("w-fit", className)}
value={value}
defaultValue={defaultValue}
onValueChange={(next) => {
setInternalValue(next)
onValueChange?.(next)
}}
{...props}
>
<TabsList
ref={listRef}
className={cn(
"relative",
size === "sm" && "group-data-[orientation=horizontal]/tabs:h-8 p-1"
)}
>
{animated && rect ? (
<span
aria-hidden
data-slot="period-tabs-indicator"
className="pointer-events-none absolute rounded-md bg-background shadow-sm transition-[left,top,width,height] duration-300 ease-[cubic-bezier(0.25,1,0.5,1)] motion-reduce:transition-none dark:border dark:border-input dark:bg-input/30"
style={rect}
/>
) : null}
{options.map((option) => (
<TabsTrigger
key={option.value}
value={option.value}
className={cn(
size === "sm" && "h-6 px-2.5 text-xs",
animated &&
"relative z-10 data-[state=active]:bg-transparent group-data-[variant=default]/tabs-list:data-[state=active]:shadow-none dark:data-[state=active]:border-transparent dark:data-[state=active]:bg-transparent"
)}
>
{option.label}
</TabsTrigger>
))}
</TabsList>
</Tabs>
)
}
export { PeriodTabs }
registry/dashboardcn/ui/sparkline.tsx
"use client"
import * as React from "react"
import {
Area,
AreaChart,
AreaRevealShape,
Line,
LineChart,
ResponsiveContainer,
type AreaRevealShapeProps,
} from "recharts"
import { cn } from "@/lib/utils"
export interface SparklineProps extends React.ComponentProps<"div"> {
/** Series to plot, oldest first. */
data: number[]
variant?: "area" | "line"
/** Area fill: a plain gradient, or a dot grid that fades out toward the line. */
fill?: "gradient" | "dots"
/** Any CSS color. Defaults to the theme primary. */
color?: string
curve?: "monotone" | "linear" | "step"
strokeWidth?: number
/** Animate after hydration and when data changes. Respects reduced motion. */
animate?: boolean
animationDuration?: number
}
const reducedMotionQuery = "(prefers-reduced-motion: reduce)"
function subscribeToReducedMotion(onChange: () => void) {
const query = window.matchMedia(reducedMotionQuery)
query.addEventListener("change", onChange)
return () => query.removeEventListener("change", onChange)
}
function getReducedMotionSnapshot() {
return window.matchMedia(reducedMotionQuery).matches
}
function getReducedMotionServerSnapshot() {
return true
}
/** Area shape that masks the fill to a dot grid while keeping the stroke solid. */
function DotGridAreaShape({
maskId,
...props
}: AreaRevealShapeProps & { maskId: string }) {
return (
<>
<g mask={`url(#${maskId})`}>
<AreaRevealShape {...props} stroke="none" />
</g>
<AreaRevealShape {...props} id={undefined} fill="none" />
</>
)
}
function Sparkline({
data,
variant = "area",
fill = "gradient",
color = "var(--primary)",
curve = "monotone",
strokeWidth = 1.5,
animate = true,
animationDuration = 500,
className,
...props
}: SparklineProps) {
const id = React.useId()
const reducedMotion = React.useSyncExternalStore(
subscribeToReducedMotion,
getReducedMotionSnapshot,
getReducedMotionServerSnapshot
)
const animationActive = animate && !reducedMotion
const dots = variant === "area" && fill === "dots"
const points = React.useMemo(() => data.map((y, i) => ({ i, y })), [data])
const margin = { top: 2, right: 0, bottom: 0, left: 0 }
return (
<div
data-slot="sparkline"
aria-hidden="true"
className={cn("h-10 w-full", className)}
{...props}
>
<ResponsiveContainer width="100%" height="100%">
{variant === "line" ? (
<LineChart data={points} margin={margin}>
<Line
type={curve}
dataKey="y"
stroke={color}
strokeWidth={strokeWidth}
dot={false}
isAnimationActive={animationActive}
animationDuration={animationDuration}
animationEasing="ease-out"
/>
</LineChart>
) : (
<AreaChart data={points} margin={margin}>
<defs>
<linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor={color} stopOpacity={dots ? 0.08 : 0.3} />
<stop offset="100%" stopColor={color} stopOpacity={dots ? 0.9 : 0} />
</linearGradient>
{dots ? (
<>
<pattern
id={`${id}-dots`}
patternUnits="userSpaceOnUse"
width={4}
height={4}
>
<circle cx={2} cy={2} r={0.9} fill="#fff" />
</pattern>
<mask
id={`${id}-mask`}
maskUnits="userSpaceOnUse"
x={0}
y={0}
width="100%"
height="100%"
>
<rect width="100%" height="100%" fill={`url(#${id}-dots)`} />
</mask>
</>
) : null}
</defs>
<Area
type={curve}
dataKey="y"
stroke={color}
strokeWidth={strokeWidth}
fill={`url(#${id})`}
fillOpacity={dots ? 1 : undefined}
dot={false}
isAnimationActive={animationActive}
animationDuration={animationDuration}
animationEasing="ease-out"
shape={
dots
? (shapeProps: AreaRevealShapeProps) => (
<DotGridAreaShape {...shapeProps} maskId={`${id}-mask`} />
)
: undefined
}
/>
</AreaChart>
)}
</ResponsiveContainer>
</div>
)
}
export { Sparkline }
registry/dashboardcn/ui/metric-value.tsx
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
import { formatNumber, type NumberFormat } from "@/registry/dashboardcn/lib/format"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
/** Values at or above this are abbreviated by default. */
export const DEFAULT_COMPACT_FROM = 100_000
export interface MetricValueProps extends Omit<React.ComponentProps<"span">, "children"> {
/** Strings render as-is. */
value: number | string
format?: NumberFormat
currency?: string
maximumFractionDigits?: number
/** Values at or above this are abbreviated (e.g. $158K) with the full value in a tooltip. Set to Infinity to always show the full value. */
compactFrom?: number
/** Text after the number, e.g. a unit. */
suffix?: React.ReactNode
}
/** A formatted number. Large values are abbreviated and reveal the full value on hover. */
function MetricValue({
value,
format,
currency,
maximumFractionDigits,
compactFrom = DEFAULT_COMPACT_FROM,
suffix,
className,
...props
}: MetricValueProps) {
const classes = cn("tabular-nums", className)
if (typeof value !== "number") {
return (
<span data-slot="metric-value" className={classes} {...props}>
{value}
{suffix}
</span>
)
}
const full = formatNumber(value, { format, currency, maximumFractionDigits })
const abbreviate = format !== "percent" && Math.abs(value) >= compactFrom
if (!abbreviate) {
return (
<span data-slot="metric-value" className={classes} {...props}>
{full}
{suffix}
</span>
)
}
return (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<span
data-slot="metric-value"
data-compact=""
className={cn(classes, "cursor-default")}
{...props}
>
{formatNumber(value, { format, currency, compact: true })}
{suffix}
</span>
</TooltipTrigger>
<TooltipContent className="tabular-nums">
{full}
{suffix}
</TooltipContent>
</Tooltip>
</TooltipProvider>
)
}
export { MetricValue }
registry/dashboardcn/lib/format.ts
export type NumberFormat = "number" | "compact" | "currency" | "percent"
export interface FormatNumberOptions {
format?: NumberFormat
/** ISO 4217 code, used when format is "currency". Defaults to USD. */
currency?: string
locale?: string
maximumFractionDigits?: number
/** Abbreviate large values, e.g. "$158K" instead of "$158,143". */
compact?: boolean
}
const formatterCache = new Map<string, Intl.NumberFormat>()
function getFormatter(locale: string, options: Intl.NumberFormatOptions) {
const key = locale + JSON.stringify(options)
let formatter = formatterCache.get(key)
if (!formatter) {
formatter = new Intl.NumberFormat(locale, options)
formatterCache.set(key, formatter)
}
return formatter
}
/**
* Format a metric value for display.
*
* formatNumber(1234567) -> "1,234,567"
* formatNumber(1234567, { format: "compact" }) -> "1.2M"
* formatNumber(48.2, { format: "currency" }) -> "$48.20"
* formatNumber(158143, { format: "currency", compact: true }) -> "$158K"
* formatNumber(0.124, { format: "percent" }) -> "12.4%"
*/
export function formatNumber(
value: number,
{
format = "number",
currency = "USD",
locale = "en-US",
maximumFractionDigits,
compact = false,
}: FormatNumberOptions = {}
): string {
if (!Number.isFinite(value)) return "—"
// Compact values keep three significant digits: $158K, $1.23M, 41.2K.
const compactOptions: Intl.NumberFormatOptions = compact
? maximumFractionDigits === undefined
? { notation: "compact", maximumSignificantDigits: 3 }
: { notation: "compact", maximumFractionDigits }
: {}
switch (format) {
case "compact":
return getFormatter(locale, {
notation: "compact",
maximumFractionDigits: maximumFractionDigits ?? 1,
}).format(value)
case "currency":
return getFormatter(locale, {
style: "currency",
currency,
maximumFractionDigits: maximumFractionDigits ?? 2,
...compactOptions,
}).format(value)
case "percent":
return getFormatter(locale, {
style: "percent",
maximumFractionDigits: maximumFractionDigits ?? 1,
}).format(value)
default:
return getFormatter(locale, {
maximumFractionDigits: maximumFractionDigits ?? 0,
...compactOptions,
}).format(value)
}
}
/**
* Format a fractional change as a signed percentage.
*
* formatDelta(0.124) -> "+12.4%"
* formatDelta(-0.03) -> "-3.0%"
* formatDelta(0) -> "0.0%"
*/
export function formatDelta(delta: number, locale = "en-US"): string {
if (!Number.isFinite(delta)) return "—"
return getFormatter(locale, {
style: "percent",
signDisplay: "exceptZero",
maximumFractionDigits: 1,
minimumFractionDigits: 1,
}).format(delta)
}
/**
* Fractional change between two values. Returns 0 when there is no baseline.
*/
export function computeDelta(current: number, previous: number): number {
if (!previous) return 0
return (current - previous) / Math.abs(previous)
}