{
  "schemaVersion": 1,
  "target": "react",
  "name": "stat-card",
  "version": "0.1.0",
  "category": "data",
  "title": "Stat Card",
  "description": "A metric with its label, a tabular value, the change against the previous period colored by whether it is good, and a sparkline that draws in as the number counts up.",
  "tags": [
    "stat",
    "metric",
    "kpi",
    "sparkline",
    "dashboard",
    "number"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "motion": "^14.14.0"
  },
  "registryDependencies": [
    {
      "name": "skeleton",
      "version": "0.1.0"
    }
  ],
  "docsPath": "/components/stat-card",
  "props": [
    {
      "name": "label",
      "type": "ReactNode",
      "description": "StatCard: what the number measures."
    },
    {
      "name": "value",
      "type": "number",
      "description": "StatCard: the current value."
    },
    {
      "name": "previous",
      "type": "number",
      "description": "StatCard: the previous period's value. Sets the change and where the count-up starts."
    },
    {
      "name": "change",
      "type": "number",
      "description": "StatCard: the change as a fraction (0.074 for 7.4%) when there is no previous value."
    },
    {
      "name": "goodDirection",
      "type": "\"up\" | \"down\" | \"neither\"",
      "default": "\"up\"",
      "description": "StatCard: which direction is an improvement. Use down for churn, latency or cost."
    },
    {
      "name": "period",
      "type": "ReactNode",
      "description": "StatCard: what the change compares against, such as \"vs. last month\"."
    },
    {
      "name": "comparison",
      "type": "ReactNode",
      "description": "StatCard: a secondary line, such as a target or plan limit."
    },
    {
      "name": "trend",
      "type": "number[]",
      "description": "StatCard: recent values for the sparkline, oldest first."
    },
    {
      "name": "format / locale",
      "type": "Intl.NumberFormatOptions / string",
      "description": "StatCard: number formatting for the value, such as currency, percent or a unit."
    },
    {
      "name": "formatValue",
      "type": "(value: number) => string",
      "description": "StatCard: formats the value yourself; also used while counting."
    },
    {
      "name": "loading",
      "type": "boolean",
      "default": "false",
      "description": "StatCard: a skeleton in the card's final shape."
    },
    {
      "name": "animate",
      "type": "boolean",
      "default": "true",
      "description": "StatCard: count up and draw the sparkline the first time the card scrolls into view."
    },
    {
      "name": "StatGroup label",
      "type": "string",
      "description": "Accessible name for the group of stats."
    }
  ],
  "accessibility": [
    "Each card is a group named by its label; the label and value are a description list term and definition.",
    "Screen readers get the final value once, in a visually hidden span, while the visible counting digits are hidden from them.",
    "The change is read as \"Up 7.4%\" or \"Down 26.2%\" so direction does not depend on the arrow or its color.",
    "The sparkline is an image with a text summary of its first and last values, or your own trendLabel.",
    "While loading the card is aria-busy and names what is loading.",
    "With reduced motion the value and sparkline render final at once, with no counting and no draw-in."
  ],
  "states": [
    "improving",
    "worsening",
    "unchanged",
    "no history",
    "loading"
  ],
  "files": [
    {
      "path": "ui/stat-card.tsx",
      "content": "\"use client\";\n\nimport { animate, motion, useInView } from \"motion/react\";\nimport {\n  Children,\n  createContext,\n  useContext,\n  useId,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n  type ComponentProps,\n  type ReactNode,\n} from \"react\";\nimport { Skeleton } from \"./skeleton\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\nconst ease = [0.23, 1, 0.32, 1] as const;\n/** One entrance for the number and the sparkline, so they read as a single change. */\nconst ENTRANCE_MS = 800;\n\nfunction prefersReducedMotion() {\n  return typeof window !== \"undefined\" && window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n}\n\n/** Which direction of change is an improvement. `neither` keeps the change neutral. */\nexport type StatGoodDirection = \"up\" | \"down\" | \"neither\";\n\ntype Tone = \"good\" | \"bad\" | \"neutral\";\n\nconst toneText: Record<Tone, string> = {\n  good: \"text-emerald-600 dark:text-emerald-400\",\n  bad: \"text-red-600 dark:text-red-400\",\n  neutral: \"text-zinc-500 dark:text-zinc-400\",\n};\n\nconst toneFill: Record<Tone, string> = {\n  good: \"fill-emerald-500\",\n  bad: \"fill-red-500\",\n  neutral: \"fill-zinc-400 dark:fill-zinc-500\",\n};\n\n// Inside a StatGroup the group draws the container and the dividers, so cards drop their own box.\nconst GroupContext = createContext(false);\n\nexport interface StatCardProps extends Omit<ComponentProps<\"div\">, \"children\"> {\n  /** What the number measures, such as \"Monthly recurring revenue\". */\n  label: ReactNode;\n  /** The current value. */\n  value: number;\n  /** The value for the previous period. Sets the change and where the count-up starts. */\n  previous?: number;\n  /** The change as a fraction (0.074 for 7.4%), when there is no `previous` to compute it from. */\n  change?: number;\n  /** Which direction is good. `down` suits churn, latency or cost. Defaults to `up`. */\n  goodDirection?: StatGoodDirection;\n  /** The period the change compares against, such as \"vs. last month\". */\n  period?: ReactNode;\n  /** A secondary line under the change, such as a target or the previous value. */\n  comparison?: ReactNode;\n  /** Recent values for the inline sparkline, oldest first. Needs two or more points. */\n  trend?: number[];\n  /** Accessible description of the sparkline. Defaults to a summary of the first and last points. */\n  trendLabel?: string;\n  /** `Intl.NumberFormat` options for the value, such as `{ style: \"currency\", currency: \"USD\" }`. */\n  format?: Intl.NumberFormatOptions;\n  /** Locale for number formatting. Defaults to the runtime locale. */\n  locale?: string;\n  /** Formats the value yourself; overrides `format`. Also used while counting up. */\n  formatValue?: (value: number) => string;\n  /** Shows a skeleton in the card's final shape. */\n  loading?: boolean;\n  /**\n   * Counts the number up from `previous` (or zero) and draws the sparkline once, the first time\n   * the card scrolls into view. Off, or with reduced motion preferred, everything renders final.\n   */\n  animate?: boolean;\n}\n\n/**\n * One metric: a label, the value in tabular numbers, the change against the previous period\n * colored by whether it is good, and an optional sparkline. The first time it scrolls into view,\n * the number counts from the previous value to the current one while the sparkline draws in.\n */\nexport function StatCard({\n  label,\n  value,\n  previous,\n  change: changeProp,\n  goodDirection = \"up\",\n  period,\n  comparison,\n  trend,\n  trendLabel,\n  format,\n  locale,\n  formatValue,\n  loading = false,\n  animate: animated = true,\n  className,\n  ...props\n}: StatCardProps) {\n  const grouped = useContext(GroupContext);\n  const labelId = useId();\n  const root = useRef<HTMLDivElement>(null);\n  const inView = useInView(root, { once: true, amount: 0.5 });\n  const run = animated && inView && !loading;\n\n  const display = useMemo(() => {\n    if (formatValue) return formatValue;\n    const formatter = new Intl.NumberFormat(locale, format);\n    return (n: number) => formatter.format(n);\n  }, [formatValue, locale, format]);\n\n  const change = changeProp ?? (previous != null && previous !== 0 ? (value - previous) / Math.abs(previous) : undefined);\n  const direction = change == null || Math.abs(change) < 0.0005 ? \"flat\" : change > 0 ? \"up\" : \"down\";\n  const tone: Tone = direction === \"flat\" || goodDirection === \"neither\" ? \"neutral\" : direction === goodDirection ? \"good\" : \"bad\";\n  const percent = useMemo(\n    () => new Intl.NumberFormat(locale, { style: \"percent\", maximumFractionDigits: 1, signDisplay: \"never\" }),\n    [locale],\n  );\n\n  const box = grouped\n    ? \"bg-white dark:bg-black\"\n    : \"rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)] dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\";\n\n  if (loading) {\n    return (\n      <div\n        ref={root}\n        role=\"group\"\n        aria-busy=\"true\"\n        aria-labelledby={labelId}\n        className={cx(\"grid min-w-0 gap-3 p-5\", box, className)}\n        {...props}\n      >\n        <span id={labelId} className=\"sr-only\">\n          Loading {typeof label === \"string\" ? label : \"metric\"}\n        </span>\n        <Skeleton className=\"h-4 w-28\" />\n        <Skeleton className=\"-mt-0.5 h-8 w-32\" />\n        <Skeleton className=\"h-4 w-36\" />\n        {trend ? <Skeleton className=\"mt-1 h-9 w-full\" /> : null}\n      </div>\n    );\n  }\n\n  return (\n    <div ref={root} role=\"group\" aria-labelledby={labelId} className={cx(\"grid min-w-0 gap-3 p-5 text-left\", box, className)} {...props}>\n      <dl className=\"contents\">\n        <dt id={labelId} className=\"truncate text-sm text-zinc-600 dark:text-zinc-400\">\n          {label}\n        </dt>\n        <dd className=\"-mt-1 min-w-0\">\n          <CountUp value={value} from={previous ?? 0} display={display} run={run} animated={animated} />\n        </dd>\n        {change != null || period != null ? (\n          <dd className=\"flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5 text-xs\">\n            {change != null ? (\n              <span className={cx(\"inline-flex items-center gap-0.5 font-medium tabular-nums\", toneText[tone])}>\n                <ChangeGlyph direction={direction} />\n                <span className=\"sr-only\">{direction === \"up\" ? \"Up\" : direction === \"down\" ? \"Down\" : \"No change,\"} </span>\n                {percent.format(Math.abs(change))}\n              </span>\n            ) : null}\n            {period != null ? <span className=\"text-zinc-500\">{period}</span> : null}\n          </dd>\n        ) : null}\n        {comparison != null ? <dd className=\"-mt-1.5 text-xs text-zinc-500 tabular-nums\">{comparison}</dd> : null}\n        {trend && trend.length > 1 ? (\n          <dd className=\"mt-1\">\n            <Sparkline data={trend} tone={tone} run={run} animated={animated} label={trendLabel ?? describeTrend(trend, display)} />\n          </dd>\n        ) : null}\n      </dl>\n    </div>\n  );\n}\n\nfunction CountUp({\n  value,\n  from,\n  display,\n  run,\n  animated,\n}: {\n  value: number;\n  from: number;\n  display: (n: number) => string;\n  run: boolean;\n  animated: boolean;\n}) {\n  // Server and first client render show the final value; the start value is swapped in before paint.\n  const [shown, setShown] = useState(value);\n  const played = useRef(false);\n  const last = useRef(value);\n\n  useLayoutEffect(() => {\n    if (!played.current && animated && !prefersReducedMotion()) setShown(from);\n    // Only the first mount decides the starting frame.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, []);\n\n  useLayoutEffect(() => {\n    if (!run && !played.current) return;\n    const start = played.current ? last.current : from;\n    played.current = true;\n    last.current = value;\n    if (!animated || prefersReducedMotion() || start === value) {\n      setShown(value);\n      return;\n    }\n    // The entrance counts from the previous period; later updates take a shorter count.\n    const controls = animate(start, value, {\n      duration: (start === from ? ENTRANCE_MS : 400) / 1000,\n      ease,\n      onUpdate: (n) => setShown(n),\n    });\n    return () => controls.stop();\n  }, [run, value, from, animated]);\n\n  const decimals = Number.isInteger(value) && Number.isInteger(from);\n  const text = display(decimals ? Math.round(shown) : shown);\n\n  return (\n    // The invisible final value holds the width, so counting never reflows the row.\n    <span className=\"grid min-w-0 text-[28px] leading-9 font-semibold tracking-tight text-zinc-950 tabular-nums dark:text-white\">\n      <span aria-hidden=\"true\" className=\"invisible col-start-1 row-start-1 truncate\">\n        {display(value)}\n      </span>\n      <span aria-hidden=\"true\" className=\"col-start-1 row-start-1 truncate\">\n        {text}\n      </span>\n      <span className=\"sr-only\">{display(value)}</span>\n    </span>\n  );\n}\n\nfunction ChangeGlyph({ direction }: { direction: \"up\" | \"down\" | \"flat\" }) {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 12 12\" className=\"size-3 shrink-0\">\n      {direction === \"flat\" ? (\n        <path d=\"M2.5 6h7\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" />\n      ) : (\n        <path\n          d={direction === \"up\" ? \"M6 9.5v-7M3 5.5l3-3 3 3\" : \"M6 2.5v7M3 6.5l3 3 3-3\"}\n          fill=\"none\"\n          stroke=\"currentColor\"\n          strokeWidth=\"1.5\"\n          strokeLinecap=\"round\"\n          strokeLinejoin=\"round\"\n        />\n      )}\n    </svg>\n  );\n}\n\nconst SPARK_H = 36;\nconst PAD = 3;\n\nfunction Sparkline({ data, tone, run, animated, label }: { data: number[]; tone: Tone; run: boolean; animated: boolean; label: string }) {\n  // The line spans the card's width, drawn in real pixels so the stroke and the end dot stay round.\n  const box = useRef<HTMLDivElement>(null);\n  const [width, setWidth] = useState(0);\n  useLayoutEffect(() => {\n    const el = box.current;\n    if (!el) return;\n    setWidth(Math.round(el.getBoundingClientRect().width));\n    const observer = new ResizeObserver(([entry]) => setWidth(Math.round(entry!.contentRect.width)));\n    observer.observe(el);\n    return () => observer.disconnect();\n  }, []);\n  const shape = useMemo(() => (width > 0 ? sparkPath(data, width) : null), [data, width]);\n  // It starts hidden in every render pass so server and client markup match;\n  // reduced motion and animate={false} reveal it with a zero-length transition.\n  const instant = !animated || prefersReducedMotion();\n  const shown = run || !animated;\n\n  return (\n    <div ref={box} role=\"img\" aria-label={label} className=\"h-9 w-full text-zinc-950/30 dark:text-white/35\">\n      {shape ? (\n        <svg aria-hidden=\"true\" width={width} height={SPARK_H} viewBox={`0 0 ${width} ${SPARK_H}`} className=\"block overflow-visible\">\n          <motion.path\n            d={shape.path}\n            fill=\"none\"\n            stroke=\"currentColor\"\n            strokeWidth=\"1.5\"\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n            initial={{ pathLength: 0, opacity: 0 }}\n            animate={shown ? { pathLength: 1, opacity: 1 } : { pathLength: 0, opacity: 0 }}\n            transition={instant ? { duration: 0 } : { pathLength: { duration: ENTRANCE_MS / 1000, ease }, opacity: { duration: 0.15 } }}\n          />\n          <motion.circle\n            cx={shape.end.x}\n            cy={shape.end.y}\n            r=\"2.5\"\n            className={toneFill[tone]}\n            style={{ transformOrigin: `${shape.end.x}px ${shape.end.y}px` }}\n            initial={{ opacity: 0, scale: 0.5 }}\n            animate={shown ? { opacity: 1, scale: 1 } : { opacity: 0, scale: 0.5 }}\n            transition={instant ? { duration: 0 } : { delay: (ENTRANCE_MS - 120) / 1000, duration: 0.2, ease }}\n          />\n        </svg>\n      ) : null}\n    </div>\n  );\n}\n\n/** A monotone cubic curve through the points, so the line never overshoots the data. */\nfunction sparkPath(data: number[], width: number) {\n  const min = Math.min(...data);\n  const max = Math.max(...data);\n  const span = max - min || 1;\n  const pts = data.map((v, i) => ({\n    x: PAD + (i / (data.length - 1)) * (width - PAD * 2),\n    y: max === min ? SPARK_H / 2 : PAD + (1 - (v - min) / span) * (SPARK_H - PAD * 2),\n  }));\n  const n = pts.length;\n  const slopes: number[] = [];\n  for (let i = 0; i < n - 1; i++) slopes.push((pts[i + 1]!.y - pts[i]!.y) / (pts[i + 1]!.x - pts[i]!.x));\n  const tangents = pts.map((_, i) => {\n    if (i === 0) return slopes[0]!;\n    if (i === n - 1) return slopes[n - 2]!;\n    const a = slopes[i - 1]!;\n    const b = slopes[i]!;\n    return a * b <= 0 ? 0 : (2 * a * b) / (a + b);\n  });\n  let d = `M${pts[0]!.x.toFixed(2)},${pts[0]!.y.toFixed(2)}`;\n  for (let i = 0; i < n - 1; i++) {\n    const p = pts[i]!;\n    const q = pts[i + 1]!;\n    const dx = (q.x - p.x) / 3;\n    d += `C${(p.x + dx).toFixed(2)},${(p.y + tangents[i]! * dx).toFixed(2)} ${(q.x - dx).toFixed(2)},${(q.y - tangents[i + 1]! * dx).toFixed(2)} ${q.x.toFixed(2)},${q.y.toFixed(2)}`;\n  }\n  return { path: d, end: pts[n - 1]! };\n}\n\nfunction describeTrend(data: number[], display: (n: number) => string) {\n  return `Trend over ${data.length} periods, from ${display(data[0]!)} to ${display(data[data.length - 1]!)}`;\n}\n\nexport interface StatGroupProps extends ComponentProps<\"div\"> {\n  /** Accessible name for the group, such as \"Revenue this month\". */\n  label?: string;\n}\n\nconst columns: Record<number, string> = {\n  1: \"\",\n  2: \"@md:grid-cols-2\",\n  3: \"@2xl:grid-cols-3\",\n  4: \"@md:grid-cols-2 @3xl:grid-cols-4\",\n};\n\n/**\n * Three or four StatCards in one container, separated by hairline dividers instead of boxed cards.\n * Columns follow the group's own width (container queries), so it fits a sidebar or a full page.\n */\nexport function StatGroup({ label, className, children, ...props }: StatGroupProps) {\n  const count = Math.min(Children.count(children), 4);\n  return (\n    <GroupContext.Provider value={true}>\n      <div\n        role={label ? \"group\" : undefined}\n        aria-label={label}\n        className={cx(\n          \"@container overflow-hidden rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)]\",\n          \"dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]\",\n          className,\n        )}\n        {...props}\n      >\n        {/* The 1px gaps show the divider color through, so dividers stay right at any column count. */}\n        <div className={cx(\"grid gap-px bg-zinc-950/[0.07] dark:bg-white/[0.1]\", columns[count])}>{children}</div>\n      </div>\n    </GroupContext.Provider>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "import { StatCard, StatGroup } from \"@/components/shaken/ui/stat-card\";\n\nconst usd = { style: \"currency\", currency: \"USD\", maximumFractionDigits: 0 } as const;\n\nexport default function StatCardExample() {\n  return (\n    <StatGroup label=\"Workspace metrics for November\" className=\"w-full max-w-4xl\">\n      <StatCard\n        label=\"Monthly recurring revenue\"\n        value={48_210}\n        previous={44_870}\n        period=\"vs. October\"\n        format={usd}\n        trend={[38_400, 39_150, 40_020, 41_880, 41_300, 43_120, 44_870, 48_210]}\n      />\n      <StatCard\n        label=\"Active workspaces\"\n        value={1_284}\n        previous={1_207}\n        period=\"vs. October\"\n        trend={[1_002, 1_048, 1_090, 1_131, 1_160, 1_189, 1_207, 1_284]}\n      />\n      <StatCard\n        label=\"Agent runs failed\"\n        value={0.031}\n        previous={0.042}\n        goodDirection=\"down\"\n        period=\"vs. October\"\n        format={{ style: \"percent\", minimumFractionDigits: 1, maximumFractionDigits: 1 }}\n        trend={[0.058, 0.051, 0.049, 0.047, 0.044, 0.045, 0.042, 0.031]}\n      />\n      <StatCard\n        label=\"p95 response time\"\n        value={412}\n        previous={388}\n        goodDirection=\"down\"\n        period=\"vs. October\"\n        format={{ style: \"unit\", unit: \"millisecond\", unitDisplay: \"short\" }}\n        trend={[361, 372, 365, 380, 377, 391, 388, 412]}\n      />\n    </StatGroup>\n  );\n}\n"
  }
}
