# KPI strip (指标卡条)

Three KPI cards with a range switch, hover-scrub sparklines, delta badges, and loading, empty and error states.

- Ref: `component/kpi-strip` (component · stats)
- Page: https://uifino.com/en/components/stats/kpi-strip
- Markdown: https://uifino.com/md/components/kpi-strip.md
- Preview image: https://uifino.com/blocks/covers/kpi-strip-dark.webp

## Install

- shadcn: `npx shadcn@latest add "https://uifino.com/r/blocks/kpi-strip.json"`
- UIFino CLI: `npx uifino@latest add component/kpi-strip`

## Dependencies

`lucide-react`

## shadcn/ui components it builds on

- `alert`, `badge`, `button`, `card`, `empty`, `skeleton`, `tabs`. The shadcn CLI installs them together with the block.

## Theme

The block reads the project's shadcn theme variables, so it follows whatever DESIGN.md the project uses and needs no options of its own.
To give the project the look of a UIFino brand or style, install its theme: `npx shadcn@latest add "https://uifino.com/r/themes/<brand-or-style-id>.json"`.

## Usage

The files under `examples/` show the block wired with content, including its loading, empty and error states where it has them.

## Files

| Path | Role | Size |
| :--- | :--- | ---: |
| components/blocks/kpi-strip/examples/content.ts | demo | 4.9 KB |
| components/blocks/kpi-strip/examples/default.tsx | demo | 380 B |
| components/blocks/kpi-strip/examples/empty.tsx | demo | 395 B |
| components/blocks/kpi-strip/examples/error.tsx | demo | 395 B |
| components/blocks/kpi-strip/examples/loading.tsx | demo | 397 B |
| components/blocks/kpi-strip/kpi-strip.tsx | source | 9.3 KB |

### components/blocks/kpi-strip/kpi-strip.tsx

```tsx
"use client";

import { useState } from "react";
import { ArrowDownRight, ArrowUpRight, ChartNoAxesColumn, RotateCw } from "lucide-react";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "@/components/ui/empty";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { cn } from "@/lib/utils";

export interface KpiPoint {
  readonly label: string;
  readonly value: number;
  readonly formatted: string;
}

export interface KpiItem {
  readonly id: string;
  readonly label: string;
  readonly value: string;
  readonly delta: string;
  readonly direction: "up" | "down";
  readonly good: boolean;
  readonly featured?: boolean;
  readonly note: string;
  readonly series: readonly KpiPoint[];
}

export interface KpiRange {
  readonly id: string;
  readonly label: string;
  readonly items: readonly KpiItem[];
}

export interface KpiStripLabels {
  readonly range: string;
  readonly empty: string;
  readonly emptyHint: string;
  readonly error: string;
  readonly errorHint: string;
  readonly retry: string;
  readonly vsPrevious: string;
  readonly improved: string;
  readonly worsened: string;
}

export interface KpiStripProps {
  readonly title: string;
  readonly ranges: readonly KpiRange[];
  readonly labels: KpiStripLabels;
  readonly defaultRangeId?: string;
  readonly status?: "ready" | "loading" | "empty" | "error";
  readonly onRetry?: () => void;
  readonly className?: string;
}

const WIDTH = 240;
const HEIGHT = 56;
const PAD = 4;

function toCoords(series: readonly KpiPoint[]) {
  const values = series.map((point) => point.value);
  const min = Math.min(...values);
  const span = Math.max(Math.max(...values) - min, 1e-6);
  return series.map((point, index) => ({
    x: (index / (series.length - 1)) * WIDTH,
    y: HEIGHT - PAD - ((point.value - min) / span) * (HEIGHT - PAD * 2)
  }));
}

function Sparkline({
  series,
  active,
  onActive
}: {
  readonly series: readonly KpiPoint[];
  readonly active: number | null;
  readonly onActive: (index: number | null) => void;
}) {
  if (series.length < 2) return null;
  const coords = toCoords(series);
  const line = coords.map((c, i) => `${i === 0 ? "M" : "L"}${c.x.toFixed(1)} ${c.y.toFixed(1)}`).join(" ");
  const area = `${line} L${WIDTH} ${HEIGHT} L0 ${HEIGHT} Z`;
  const marker = coords[active ?? coords.length - 1] ?? coords[coords.length - 1] ?? { x: WIDTH, y: HEIGHT / 2 };
  const first = series[0]!;
  const last = series[series.length - 1]!;
  const move = (index: number) => onActive(Math.min(series.length - 1, Math.max(0, index)));

  return (
    <div
      role="img"
      tabIndex={0}
      aria-label={`${first.label} ${first.formatted} - ${last.label} ${last.formatted}`}
      className="relative h-14 w-full cursor-crosshair touch-pan-y rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring"
      onFocus={() => onActive(series.length - 1)}
      onBlur={() => onActive(null)}
      onKeyDown={(event) => {
        const current = active ?? series.length - 1;
        if (event.key === "ArrowLeft") {
          event.preventDefault();
          move(current - 1);
        } else if (event.key === "ArrowRight") {
          event.preventDefault();
          move(current + 1);
        } else if (event.key === "Home") {
          event.preventDefault();
          move(0);
        } else if (event.key === "End") {
          event.preventDefault();
          move(series.length - 1);
        }
      }}
      onPointerMove={(event) => {
        const box = event.currentTarget.getBoundingClientRect();
        const ratio = (event.clientX - box.left) / box.width;
        onActive(Math.min(series.length - 1, Math.max(0, Math.round(ratio * (series.length - 1)))));
      }}
      onPointerLeave={() => onActive(null)}
    >
      <svg viewBox={`0 0 ${WIDTH} ${HEIGHT}`} preserveAspectRatio="none" className="size-full text-chart-1" aria-hidden="true">
        <path d={area} fill="currentColor" fillOpacity={0.1} />
        <path d={line} fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinejoin="round" vectorEffect="non-scaling-stroke" />
      </svg>
      {active !== null && <span className="absolute inset-y-0 w-px bg-border" style={{ left: `${(marker.x / WIDTH) * 100}%` }} />}
      <span
        className={cn(
          "absolute -translate-x-1/2 -translate-y-1/2 rounded-full bg-chart-1 ring-2 ring-card",
          active === null ? "size-1.5" : "size-2"
        )}
        style={{ left: `${(marker.x / WIDTH) * 100}%`, top: `${(marker.y / HEIGHT) * 100}%` }}
      />
    </div>
  );
}

function KpiCard({ item, labels }: { readonly item: KpiItem; readonly labels: KpiStripLabels }) {
  const [active, setActive] = useState<number | null>(null);
  const point = active === null ? null : item.series[active];
  const Arrow = item.direction === "up" ? ArrowUpRight : ArrowDownRight;

  return (
    <Card className={cn("min-w-0 gap-4", item.featured && "@2xl:col-span-2 @4xl:col-span-1")}>
      <CardHeader>
        <CardDescription className="min-w-0">{item.label}</CardDescription>
        <CardTitle className={cn("whitespace-nowrap tabular-nums", item.featured ? "text-3xl" : "text-2xl")}>{point ? point.formatted : item.value}</CardTitle>
        <CardAction>
          {point ? (
            <span className="text-xs tabular-nums text-muted-foreground">{point.label}</span>
          ) : (
            <Badge variant="outline" className={cn("tabular-nums", !item.good && "text-destructive")}>
              <Arrow />
              <span className="sr-only">{item.good ? labels.improved : labels.worsened}</span>
              {item.delta}
            </Badge>
          )}
        </CardAction>
      </CardHeader>
      <CardContent>
        <Sparkline series={item.series} active={active} onActive={setActive} />
      </CardContent>
      <CardFooter>
        <p className="text-sm text-muted-foreground">{item.note}</p>
      </CardFooter>
    </Card>
  );
}

function KpiSkeleton({ featured }: { readonly featured: boolean }) {
  return (
    <Card className={cn("gap-4", featured && "@2xl:col-span-2 @4xl:col-span-1")} aria-hidden="true">
      <CardHeader>
        <Skeleton className="h-4 w-24" />
        <Skeleton className="h-8 w-32" />
      </CardHeader>
      <CardContent>
        <Skeleton className="h-14 w-full" />
      </CardContent>
      <CardFooter>
        <Skeleton className="h-4 w-40" />
      </CardFooter>
    </Card>
  );
}

export function KpiStrip({ title, ranges, labels, defaultRangeId, status = "ready", onRetry, className }: KpiStripProps) {
  const [rangeId, setRangeId] = useState(defaultRangeId ?? ranges[0]?.id ?? "");
  const range = ranges.find((r) => r.id === rangeId) ?? ranges[0];
  const items = range?.items ?? [];
  const hasFeatured = items.some((item) => item.featured);
  const gridClass = cn("grid grid-cols-1 gap-4", hasFeatured ? "@2xl:grid-cols-2 @4xl:grid-cols-3" : "@2xl:grid-cols-3");
  const skeletonCount = items.length || 3;

  return (
    <section className={cn("@container w-full min-w-0 text-foreground", className)}>
      <div className="mb-4 flex flex-wrap items-center justify-between gap-3">
        <h2 className="text-base font-medium">{title}</h2>
        <div className="flex flex-wrap items-center gap-3">
          <span className="text-xs text-muted-foreground">{labels.vsPrevious}</span>
          {ranges.length > 1 && (
            <Tabs value={range?.id} onValueChange={setRangeId}>
              <TabsList aria-label={labels.range}>
                {ranges.map((r) => (
                  <TabsTrigger key={r.id} value={r.id} disabled={status !== "ready"} className="text-muted-foreground">
                    {r.label}
                  </TabsTrigger>
                ))}
              </TabsList>
            </Tabs>
          )}
        </div>
      </div>

      {status === "loading" ? (
        <div className={gridClass} aria-busy="true">
          {Array.from({ length: skeletonCount }, (_, index) => (
            <KpiSkeleton key={index} featured={hasFeatured && index === 0} />
          ))}
        </div>
      ) : status === "error" ? (
        <Alert variant="destructive" className="flex flex-col items-start gap-3 @lg:flex-row @lg:items-center">
          <div className="min-w-0 flex-1">
            <AlertTitle>{labels.error}</AlertTitle>
            <AlertDescription>{labels.errorHint}</AlertDescription>
          </div>
          <Button variant="outline" size="sm" onClick={onRetry}>
            <RotateCw />
            {labels.retry}
          </Button>
        </Alert>
      ) : status === "empty" || items.length === 0 ? (
        <Empty className="rounded-xl border border-dashed">
          <EmptyHeader>
            <EmptyMedia variant="icon">
              <ChartNoAxesColumn />
            </EmptyMedia>
            <EmptyTitle>{labels.empty}</EmptyTitle>
            <EmptyDescription>{labels.emptyHint}</EmptyDescription>
          </EmptyHeader>
        </Empty>
      ) : (
        <div className={gridClass}>
          {items.map((item) => (
            <KpiCard key={`${range?.id}-${item.id}`} item={item} labels={labels} />
          ))}
        </div>
      )}
    </section>
  );
}
```

Not inlined (5 files, 6.4 KB). Full sources: https://uifino.com/r/blocks/kpi-strip.json
