# Animated Stat for UI SDK (/docs/components/stat)

The KPI card of an admin dashboard: a label, one big number, the change as a coloured pill with an arrow, a comparison line, an optional icon and room for a sparkline, with a loading state at the parts' own size. When the numbers change the value rolls digit by digit, the delta's arrow turns to its new direction and the sparkline tweens. StatGroup sets several on one surface with hairlines between them, four across, then two, then one, by container queries.

<ComponentPreview slug="stat" source="{&#x22;code&#x22;:&#x22;\&#x22;use client\&#x22;\n\nimport { Receipt, RotateCcw, ShoppingBag, Wallet } from \&#x22;lucide-react\&#x22;\nimport * as React from \&#x22;react\&#x22;\n\nimport { SegmentedControl, SegmentedControlItem } from \&#x22;@/components/keyframery/segmented-control\&#x22;\nimport { Sparkline } from \&#x22;@/components/keyframery/sparkline\&#x22;\nimport { Stat, StatChart, StatComparison, StatDelta, StatGroup, StatIcon, StatLabel, StatValue } from \&#x22;@/components/keyframery/stat\&#x22;\n\n/* The demo plays itself: the store's week, then its month, then its quarter. Every value rolls,\n   the deltas turn (revenue dipped this week but grew over the month), the sparklines tween into\n   the longer span, and it goes back to the week. */\nconst period = (n: number) => `[aria-label=\&#x22;Period\&#x22;] [data-slot=\&#x22;segmented-control-item\&#x22;]:nth-of-type(${n})`\n\n/* 180 days of a small store, oldest first: steady growth, a weekly rhythm, a soft last week (fewer\n   orders, but larger ones) and a run of returns in the last few days. The same on every load. */\nconst DAYS = 180\nconst wave = (i: number, seed: number) => Math.sin((i + seed) * ((2 * Math.PI) / 7)) * 0.08 + Math.sin(i * 12.9898 + seed * 78.233) * 0.05\nconst history = Array.from({ length: DAYS }, (_, i) => {\n  const back = DAYS - 1 - i\n  const soft = back < 7 ? 0.82 : 1\n  const orders = Math.round((38 + i * 0.16) * (1 + wave(i, 2)) * soft)\n  const basket = (61 + i * 0.035) * (1 + wave(i, 5) * 0.4) * (back < 7 ? 1.07 : 1)\n  const revenue = Math.round(orders * basket)\n  const rate = Math.max(0.6, 2.9 - i * 0.006 + wave(i, 3) * 2 + (back < 4 ? 1.1 : 0)) / 100\n  return { orders, revenue, refunds: orders * rate }\n})\n\nfunction totals(from: number, to: number) {\n  const rows = history.slice(from, to)\n  const revenue = rows.reduce((s, r) => s + r.revenue, 0)\n  const orders = rows.reduce((s, r) => s + r.orders, 0)\n  const refunds = rows.reduce((s, r) => s + r.refunds, 0)\n  return { revenue, orders, aov: revenue / orders, refundRate: refunds / orders }\n}\n\nconst money = (v: number) => `$${Math.round(v).toLocaleString(\&#x22;en-US\&#x22;)}`\nconst cents = (v: number) => `$${v.toFixed(2)}`\nconst count = (v: number) => Math.round(v).toLocaleString(\&#x22;en-US\&#x22;)\nconst rate = (v: number) => `${(v * 100).toFixed(1)}%`\n\ntype Days = \&#x22;7\&#x22; | \&#x22;30\&#x22; | \&#x22;90\&#x22;\ntype Chart = \&#x22;area\&#x22; | \&#x22;line\&#x22; | \&#x22;bar\&#x22; | \&#x22;none\&#x22;\n\nexport default function StatDemo({\n  days = \&#x22;7\&#x22;,\n  chart = \&#x22;area\&#x22;,\n  icons = true,\n  comparison = true,\n  loading = false,\n  refundsDownIsGood = true,\n  stats = 4,\n  title = \&#x22;Store overview\&#x22;,\n  columns = 4,\n  size = 28,\n  padding = 20,\n  radius = 16,\n  positive = \&#x22;\&#x22;,\n  negative = \&#x22;\&#x22;,\n  surface = \&#x22;\&#x22;,\n  divider = \&#x22;\&#x22;,\n}: {\n  days?: Days\n  chart?: Chart\n  icons?: boolean\n  comparison?: boolean\n  loading?: boolean\n  refundsDownIsGood?: boolean\n  stats?: number\n  title?: string\n  columns?: number\n  size?: number\n  padding?: number\n  radius?: number\n  positive?: string\n  negative?: string\n  surface?: string\n  divider?: string\n}) {\n  const [span, setSpan] = React.useState<Days>(days)\n  React.useEffect(() => setSpan(days), [days])\n  const n = Number(span)\n  const now = totals(DAYS - n, DAYS)\n  const before = totals(DAYS - 2 * n, DAYS - n)\n  const change = (a: number, b: number) => (a - b) / b\n  const recent = history.slice(DAYS - n)\n  const labels = recent.map((_, i) => {\n    const d = new Date(2026, 10, 19)\n    d.setDate(d.getDate() - (n - 1 - i))\n    return d.toLocaleDateString(\&#x22;en-US\&#x22;, { month: \&#x22;short\&#x22;, day: \&#x22;numeric\&#x22; })\n  })\n  const versus = `vs previous ${n} days`\n\n  const cards = [\n    { label: \&#x22;Revenue\&#x22;, icon: Wallet, value: now.revenue, format: money, delta: change(now.revenue, before.revenue), series: recent.map((r) => r.revenue), daily: money },\n    { label: \&#x22;Orders\&#x22;, icon: ShoppingBag, value: now.orders, format: count, delta: change(now.orders, before.orders), series: recent.map((r) => r.orders), daily: (v: number) => `${count(v)} orders` },\n    { label: \&#x22;Average order\&#x22;, icon: Receipt, value: now.aov, format: cents, delta: change(now.aov, before.aov), series: recent.map((r) => r.revenue / r.orders), daily: cents },\n    { label: \&#x22;Refund rate\&#x22;, icon: RotateCcw, value: now.refundRate, format: rate, delta: change(now.refundRate, before.refundRate), series: recent.map((r) => r.refunds / r.orders), daily: rate, downIsGood: refundsDownIsGood },\n  ].slice(0, stats)\n\n  const vars = {\n    \&#x22;--stat-value-size\&#x22;: `${size}px`,\n    \&#x22;--stat-padding\&#x22;: `${padding}px`,\n    \&#x22;--stat-radius\&#x22;: `${radius}px`,\n    \&#x22;--stat-group-columns\&#x22;: Math.min(columns, stats),\n    ...(positive ? { \&#x22;--stat-positive\&#x22;: positive } : null),\n    ...(negative ? { \&#x22;--stat-negative\&#x22;: negative } : null),\n    ...(surface ? { \&#x22;--stat-surface\&#x22;: surface } : null),\n    ...(divider ? { \&#x22;--stat-divider\&#x22;: divider } : null),\n  } as React.CSSProperties\n\n  return (\n    <div className=\&#x22;@container w-full max-w-[1040px]\&#x22; style={vars}>\n      <div className=\&#x22;mb-3 flex flex-wrap items-center justify-between gap-3 px-1\&#x22;>\n        <div className=\&#x22;text-[15px] font-semibold tracking-tight\&#x22;>{title}</div>\n        <SegmentedControl aria-label=\&#x22;Period\&#x22; value={span} onValueChange={(next) => next && setSpan(next as Days)}>\n          <SegmentedControlItem value=\&#x22;7\&#x22;>7 days</SegmentedControlItem>\n          <SegmentedControlItem value=\&#x22;30\&#x22;>30 days</SegmentedControlItem>\n          <SegmentedControlItem value=\&#x22;90\&#x22;>90 days</SegmentedControlItem>\n        </SegmentedControl>\n      </div>\n      <StatGroup aria-label={`${title}, last ${n} days`}>\n        {cards.map((c) => (\n          <Stat key={c.label} label={c.label} value={c.value} formatValue={c.format} delta={c.delta} downIsGood={c.downIsGood} loading={loading}>\n            <StatLabel />\n            {icons ? (\n              <StatIcon>\n                <c.icon />\n              </StatIcon>\n            ) : null}\n            <StatValue />\n            <StatDelta />\n            {comparison ? <StatComparison>{versus}</StatComparison> : null}\n            {chart === \&#x22;none\&#x22; ? null : (\n              <StatChart>\n                <Sparkline\n                  type={chart}\n                  data={c.series}\n                  labels={labels}\n                  label={`${c.label} per day`}\n                  period={`last ${n} days`}\n                  formatValue={c.daily}\n                  downIsGood={c.downIsGood}\n                />\n              </StatChart>\n            )}\n          </Stat>\n        ))}\n      </StatGroup>\n    </div>\n  )\n}&#x22;,&#x22;bindings&#x22;:{&#x22;days&#x22;:[2297,2300],&#x22;chart&#x22;:[2312,2318],&#x22;icons&#x22;:[2330,2334],&#x22;comparison&#x22;:[2351,2355],&#x22;loading&#x22;:[2369,2374],&#x22;refundsDownIsGood&#x22;:[2398,2402],&#x22;stats&#x22;:[2414,2415],&#x22;title&#x22;:[2427,2443],&#x22;columns&#x22;:[2457,2458],&#x22;size&#x22;:[2469,2471],&#x22;padding&#x22;:[2485,2487],&#x22;radius&#x22;:[2500,2502],&#x22;positive&#x22;:[2517,2519],&#x22;negative&#x22;:[2534,2536],&#x22;surface&#x22;:[2550,2552],&#x22;divider&#x22;:[2566,2568]},&#x22;root&#x22;:[4702,6314],&#x22;importOffset&#x22;:410}" />

## Installation [#installation]

**CLI**

```bash
npx shadcn@latest add @keyframery/stat
```

This adds `components/keyframery/stat.tsx` and its primitive to your project, and installs UI SDK. The motion tokens are added to your global CSS the first time you install a component.

**Manual**

**Install the dependencies**

```bash
npm install @ui-sdk/core@0.1.0-beta.9 @ui-sdk/react@0.1.0-beta.9 lucide-react clsx tailwind-merge
```

**Add the motion tokens**

Copy the [motion tokens](/docs/installation#what-the-cli-adds-to-your-css) into your global CSS, and this file into `lib/keyframery.tsx`. Every component shares them.

**lib/keyframery.tsx**

```tsx
"use client"

/* Speed for Keyframery components, as a prop.

   Every duration in the components is written as calc(Nms * var(--kf-speed, 1)). These helpers set
   that variable for you, so nobody has to know it exists:

     <Tabs speed="fast">                      one component
     <KeyframeryProvider speed="slow">        the whole app

   Parts that render in a portal (popups, menus, dialogs) are not inside the component in the page,
   so they pick the speed up through React context instead of the CSS cascade. */

import * as React from "react"

/** `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or any multiplier: `0.8` is 20% quicker. */
export type Speed = "fast" | "normal" | "slow" | number

export type SpeedProps = {
  /** How fast the component moves. `"fast"` (0.6×), `"normal"` (1×), `"slow"` (1.4×), or a multiplier like `0.8`. Popups follow it too. */
  speed?: Speed
}

export type MotionStyleName = "springy" | "calm" | "snappy" | "playful"

const presets = { fast: 0.6, normal: 1, slow: 1.4 } as const

export function speedValue(speed: Speed | undefined): number | undefined {
  if (speed === undefined) return undefined
  return typeof speed === "number" ? speed : presets[speed]
}

const SpeedContext = React.createContext<number | undefined>(undefined)

type SpeedStyle = React.CSSProperties & { "--kf-speed"?: number }

/* Wraps a component's parts. Without `speed` it adds nothing to the page. With it, a
   `display: contents` element carries the variable to the parts in place, and context carries it
   to the parts in a portal. */
export function Speed({ speed, children }: SpeedProps & { children?: React.ReactNode }) {
  const value = speedValue(speed)
  if (value === undefined) return children
  const style: SpeedStyle = { display: "contents", "--kf-speed": value }
  return (
    <SpeedContext value={value}>
      <span data-slot="speed" style={style}>
        {children}
      </span>
    </SpeedContext>
  )
}

/* For parts that render in a portal: adds the speed of the component they belong to. `style` can
   be an object or UI SDK's function of the part's state. */
export function useSpeedStyle<S>(style: S): S {
  return withSpeed(style, React.useContext(SpeedContext))
}

/* Adds a speed to a part's own `style`, for a part that takes `speed` and renders in a portal. */
export function withSpeed<S>(style: S, speed: Speed | undefined): S {
  const value = speedValue(speed)
  if (value === undefined) return style
  if (typeof style === "function")
    return ((state: unknown) => ({ "--kf-speed": value, ...(style as (s: unknown) => React.CSSProperties)(state) })) as S
  return { "--kf-speed": value, ...(style as React.CSSProperties | undefined) } as S
}

/* UI SDK parts take `children` as content or as a function of the part's state. A styled part
   that adds elements of its own (a chevron, a moving key) wraps either form with this, so the
   function form keeps working. */
export function mapChildren<State>(
  children: React.ReactNode | ((state: State) => React.ReactNode),
  wrap: (content: React.ReactNode) => React.ReactNode,
): React.ReactNode | ((state: State) => React.ReactNode) {
  return typeof children === "function" ? (state: State) => wrap(children(state)) : wrap(children)
}

/* Sets speed and motion style for the whole app, popups included. A component's own `speed` prop
   still wins inside that component. Server-rendered pages can put `data-motion` on <html> directly
   to avoid a change after hydration. */
export function KeyframeryProvider({
  speed,
  motion,
  children,
}: SpeedProps & {
  /** The motion style for the whole app: `"springy"` (the default), `"calm"`, `"snappy"` or `"playful"`. */
  motion?: MotionStyleName
  children?: React.ReactNode
}) {
  const value = speedValue(speed)
  React.useLayoutEffect(() => {
    const html = document.documentElement
    if (motion) html.setAttribute("data-motion", motion)
    if (value !== undefined) html.style.setProperty("--kf-speed", String(value))
    return () => {
      if (motion) html.removeAttribute("data-motion")
      if (value !== undefined) html.style.removeProperty("--kf-speed")
    }
  }, [motion, value])
  return children
}
```

**Copy the component**

**components/keyframery/stat.tsx**

```tsx
"use client"

export * from "@/components/keyframery/primitives/stat"

/* Styled stats: the animated primitive plus the Keyframery look. A stat is a quiet card: a muted
   label with an optional icon in a small well, one big number, the delta as a tinted pill with an
   arrow, the comparison beside it, and room for a sparkline under them. In a StatGroup the stats
   share one surface, split by hairlines: four across on a wide container, two, then one, by
   container queries.

   The delta's colour means status: green for good news, the destructive colour for bad, muted for
   flat. `downIsGood` turns it round. Its arrow turns to the new direction on a spring.

   Theming: set these CSS variables on a stat, a group or anything around them. Each falls back to
   the theme's own token, so it looks the same until you set one.
     --stat-surface      the card                       (default: --background, --card in dark)
     --stat-divider      the hairlines in a group       (default: --border)
     --stat-label        the label                      (default: --muted-foreground)
     --stat-positive     good news                      (default: green oklch(0.55 0.15 150), lighter in dark)
     --stat-negative     bad news                       (default: --destructive)
     --stat-value-size   the number's size              (default: 28px)
     --stat-radius       the corners                    (default: 16px)
     --stat-padding      the inset                      (default: 1.25rem) */

import { ArrowUpRight } from "lucide-react"
import * as React from "react"

import {
  Roll,
  Stat as StatPrimitive,
  StatChart as StatChartPrimitive,
  StatComparison as StatComparisonPrimitive,
  StatDelta as StatDeltaPrimitive,
  StatGroup as StatGroupPrimitive,
  StatIcon as StatIconPrimitive,
  StatLabel as StatLabelPrimitive,
  StatValue as StatValuePrimitive,
} from "@/components/keyframery/primitives/stat"
import { Speed, type SpeedProps } from "@/lib/keyframery"
import { cn } from "@/lib/utils"

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* A placeholder at the part's own size while loading: the ink goes, a soft block stays. */
const placeholder =
  "data-loading:rounded-[6px] data-loading:text-transparent! data-loading:bg-[color-mix(in_oklab,var(--foreground)_7%,transparent)]! data-loading:shadow-none! dark:data-loading:bg-[color-mix(in_oklab,var(--foreground)_9%,transparent)]!"

const surface = cn(
  "rounded-[var(--stat-radius,16px)] bg-[var(--stat-surface,var(--background))]",
  "shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_2px_rgb(0_0_0/0.04),0_12px_32px_-14px_rgb(0_0_0/0.14)]",
  "dark:bg-[var(--stat-surface,var(--card))] dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07)]",
)

/* Tone colours, as variables the delta and the chart both read. */
const tones = cn(
  "[--stat-tone:var(--muted-foreground)]",
  "data-[tone=positive]:[--stat-tone:var(--stat-positive,oklch(0.55_0.15_150))] dark:data-[tone=positive]:[--stat-tone:var(--stat-positive,oklch(0.74_0.16_150))]",
  "data-[tone=negative]:[--stat-tone:var(--stat-negative,var(--destructive))]",
)

function Stat({ speed, className, ...props }: React.ComponentProps<typeof StatPrimitive> & SpeedProps) {
  return (
    <Speed speed={speed}>
      <StatPrimitive
        className={withClass(
          cn(
            "flex flex-wrap content-start items-start gap-x-3 p-[var(--stat-padding,1.25rem)] text-foreground",
            "[&_:is([data-slot=stat-icon],[data-slot=stat-delta])>svg]:size-3.5 [&_:is([data-slot=stat-icon],[data-slot=stat-delta])>svg]:shrink-0 [&_:is([data-slot=stat-icon],[data-slot=stat-delta])>svg]:stroke-[1.75]",
            surface,
            tones,
          ),
          className,
        )}
        {...props}
      />
    </Speed>
  )
}

function StatLabel({ className, ...props }: React.ComponentProps<typeof StatLabelPrimitive>) {
  return (
    <StatLabelPrimitive
      className={withClass(
        cn("min-w-0 flex-1 truncate py-px text-[13px] leading-[1.3] font-medium text-[color:var(--stat-label,var(--muted-foreground))]", placeholder, "data-loading:flex-none"),
        className,
      )}
      {...props}
    />
  )
}

/* A small well beside the label. Put a lucide icon in it. */
function StatIcon({ className, ...props }: React.ComponentProps<typeof StatIconPrimitive>) {
  return (
    <StatIconPrimitive
      className={withClass(
        cn(
          "ml-auto -mt-1 -mr-1 grid size-7 shrink-0 place-items-center rounded-[8px] bg-muted text-muted-foreground",
          "shadow-[inset_0_1px_2px_rgb(0_0_0/0.06),inset_0_0_0_1px_rgb(0_0_0/0.03)] dark:shadow-[inset_0_1px_2px_rgb(0_0_0/0.45),inset_0_0_0_1px_rgb(255_255_255/0.04)]",
          "data-loading:text-transparent",
        ),
        className,
      )}
      {...props}
    />
  )
}

function StatValue({ className, ...props }: React.ComponentProps<typeof StatValuePrimitive>) {
  return (
    <StatValuePrimitive
      className={withClass(
        cn(
          "mt-2.5 w-full text-[length:var(--stat-value-size,28px)] leading-[1.1] font-semibold tracking-tight tabular-nums",
          "data-loading:text-transparent data-loading:[&_[data-roll]]:rounded-[6px] data-loading:[&_[data-roll]]:bg-[color-mix(in_oklab,var(--foreground)_7%,transparent)] dark:data-loading:[&_[data-roll]]:bg-[color-mix(in_oklab,var(--foreground)_9%,transparent)]",
          "[&_[data-roll]]:transition-[background-color] [&_[data-roll]]:duration-[calc(420ms*var(--kf-speed,1))] [&_[data-roll]]:ease-house",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* A tinted pill: the arrow turns to the direction on a spring, the number Rolls, the colour
   crossfades when the news changes. */
function StatDelta({ className, children, ...props }: React.ComponentProps<typeof StatDeltaPrimitive>) {
  return (
    <StatDeltaPrimitive
      className={withClass(
        cn(
          "mt-2.5 inline-flex h-5 shrink-0 items-center gap-0.5 rounded-full pr-1.5 pl-1 text-[12px] leading-none font-medium tabular-nums",
          "bg-[color-mix(in_oklch,var(--stat-tone)_12%,transparent)] text-[color:var(--stat-tone)]",
          "data-[tone=neutral]:bg-[color-mix(in_oklch,var(--foreground)_6%,transparent)]",
          /* Status colour switches at once (a crossfade from red to green passes through brown); the arrow's turn carries the change. */
          "[transition-property:opacity,filter]",
          "[&>svg]:transition-[rotate] [&>svg]:duration-[calc(560ms*var(--kf-speed,1))] [&>svg]:ease-spring motion-reduce:[&>svg]:transition-none",
          "data-[trend=down]:[&>svg]:rotate-90 data-[trend=flat]:[&>svg]:rotate-45",
          placeholder,
        ),
        className,
      )}
      {...props}
    >
      {children ??
        ((state) => (
          <>
            <ArrowUpRight aria-hidden />
            <span className="sr-only">{state.words}</span>
            <span aria-hidden>
              <Roll text={state.text} />
            </span>
          </>
        ))}
    </StatDeltaPrimitive>
  )
}

function StatComparison({ className, ...props }: React.ComponentProps<typeof StatComparisonPrimitive>) {
  return (
    <StatComparisonPrimitive
      className={withClass(cn("mt-2.5 min-w-0 flex-1 truncate text-[12px] leading-5 text-muted-foreground", placeholder, "data-loading:flex-none"), className)}
      {...props}
    />
  )
}

/* Room for a sparkline under the numbers. A Sparkline inside takes the delta's colour. */
function StatChart({ className, ...props }: React.ComponentProps<typeof StatChartPrimitive>) {
  return (
    <StatChartPrimitive
      className={withClass(
        cn(
          "mt-4 w-full",
          "[&_[data-slot=sparkline]]:[--sparkline-tone:var(--sparkline-color,var(--stat-tone))] [&_[data-slot=sparkline]]:[--sparkline-height:var(--stat-chart-height,2.75rem)]",
          "data-[tone=neutral]:[&_[data-slot=sparkline]]:[--sparkline-tone:var(--sparkline-color,var(--chart-1))]",
          "data-loading:[&>*]:opacity-0",
          placeholder,
        ),
        className,
      )}
      {...props}
    />
  )
}

/* One surface; the stats inside drop their own and are split by hairlines, which each stat draws on
   its left and top edge and the grid clips at its own edges, so any column count works. */
function StatGroup({ className, gridClassName, ...props }: React.ComponentProps<typeof StatGroupPrimitive>) {
  return (
    <StatGroupPrimitive
      className={withClass(cn("@container/stats w-full", surface), className)}
      gridClassName={cn(
        "overflow-hidden rounded-[inherit] grid-cols-1 @[26rem]/stats:grid-cols-2 @[48rem]/stats:grid-cols-[repeat(var(--stat-group-columns,4),minmax(0,1fr))]",
        "[&>[data-slot=stat]]:rounded-none [&>[data-slot=stat]]:bg-transparent",
        "[&>[data-slot=stat]]:shadow-[-1px_0_0_var(--stat-divider,var(--border)),0_-1px_0_var(--stat-divider,var(--border))]",
        gridClassName,
      )}
      {...props}
    />
  )
}

export { Stat, StatChart, StatComparison, StatDelta, StatGroup, StatIcon, StatLabel, StatValue }
```

**components/keyframery/primitives/stat.tsx**

```tsx
"use client"

/* Animated stats, on UI SDK's core. UI SDK ships no stat, so the behaviour is defined in
   `@/components/core/stat` with `definePrimitive` and rendered here: `Stat` with `StatLabel`,
   `StatValue`, `StatDelta`, `StatComparison`, `StatIcon` and `StatChart` (which holds a Sparkline),
   and `StatGroup` for several on one surface. This file adds motion only. Colours, radii, type and
   spacing stay yours (style `data-trend`, `data-tone` and `data-loading`).

   - Cascade: on arrival the parts rise out of a light blur one after another, label first.
   - Roll: the value and the delta roll digit by digit to each new number.
   - Flip: when the delta changes direction its colour crossfades (the styled arrow turns).
   - Loading: the parts keep their own geometry while loading; when it ends their ink fades back
     in, one after another. */

import type { StateOf } from "@ui-sdk/core"
import { createParts, type PartProps, usePart, usePrimitive } from "@ui-sdk/react/primitive"
import * as React from "react"

import { stat, statGroup, type StatOptions } from "@/components/keyframery/core/stat-core"
import { cn } from "@/lib/utils"

type StatPart<Slot extends "root" | "label" | "value" | "delta" | "comparison" | "icon" | "chart", Tag extends keyof React.JSX.IntrinsicElements = "div"> = PartProps<Tag, StateOf<typeof stat, Slot>>

/* UI SDK parts take a class name or a function of the part's state. Keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* ---------------------------------------------------------------- Roll */

/* Roll: every digit is a column of 0 to 9 that slides to its value on a spring; other characters
   stay put. Positions are keyed from the right, so a new leading digit is added instead of
   everything shifting. Screen readers get the plain text. */
function Roll({ text, className }: { text: string; className?: string }) {
  const chars = text.split("")
  return (
    <>
      <span className="sr-only">{text}</span>
      <span data-roll="" aria-hidden className={cn("inline-flex h-[1lh] overflow-hidden whitespace-pre tabular-nums", className)}>
        {chars.map((c, i) => {
          const key = chars.length - i
          return /\d/.test(c) ? (
            <span
              key={key}
              style={{ "--d": Number(c), "--k": key } as React.CSSProperties}
              className="flex flex-col transition-[translate] duration-[calc(560ms*var(--kf-speed,1))] ease-spring [transition-delay:calc(min(var(--k),8)*calc(18ms*var(--kf-speed,1)))] [translate:0_calc(var(--d)*-1lh)] motion-reduce:transition-none!"
            >
              {Array.from({ length: 10 }, (_, d) => (
                <span key={d} className="h-[1lh]">
                  {d}
                </span>
              ))}
            </span>
          ) : (
            <span key={key}>{c}</span>
          )
        })}
      </span>
    </>
  )
}

/* ---------------------------------------------------------------- motion */

const keyframes = "@keyframes kf-stat-part{from{opacity:0;translate:0 10px;filter:blur(5px)}}"

/* Each part rises in after the one before it; while loading its ink is hidden (the styled part
   draws the placeholder), and when loading ends the ink comes back in the same order. */
const partMotion = cn(
  "animate-[kf-stat-part_calc(560ms*var(--kf-speed,1))_var(--ease-spring)_backwards] motion-reduce:animate-none",
  "[animation-delay:calc(calc(40ms*var(--kf-speed,1))+(min(sibling-index(),8)-1)*calc(60ms*var(--kf-speed,1)))]",
  "transition-[color,background-color,opacity,filter] duration-[calc(420ms*var(--kf-speed,1))] ease-house",
  "[transition-delay:calc((min(sibling-index(),8)-1)*calc(50ms*var(--kf-speed,1)))] data-loading:[transition-delay:0ms]",
  "motion-reduce:transition-none",
)

/* ---------------------------------------------------------------- stat */

type StatProps = StatOptions & Omit<StatPart<"root">, keyof StatOptions>

/** One number. With no children it shows its label, value and delta. */
function Stat({ label, value, formatValue, delta, formatDelta, downIsGood, flatThreshold, loading, className, children, ...props }: StatProps) {
  const handle = usePrimitive(stat, { label, value, formatValue, delta, formatDelta, downIsGood, flatThreshold, loading })
  return (
    <>
      <style href="kf-stat" precedence="default">
        {keyframes}
      </style>
      {usePart(
        handle,
        "root",
        {},
        {
          ...props,
          className: withClass("group/stat relative min-w-0", className),
          children: children ?? (
            <>
              <StatLabel />
              <StatValue />
              <StatDelta />
            </>
          ),
        },
        "div",
      )}
    </>
  )
}

/** The label. With no children it shows the stat's `label`. */
function StatLabel({ className, children, ...props }: StatPart<"label">) {
  return usePart(stat, "label", {}, { ...props, className: withClass(partMotion, className), children: children ?? ((state) => state.label) }, "div")
}

/** The number. With no children its formatted value Rolls to each new number. */
function StatValue({ className, children, ...props }: StatPart<"value">) {
  return usePart(stat, "value", {}, { ...props, className: withClass(partMotion, className), children: children ?? ((state) => <Roll text={state.text} />) }, "div")
}

/** The change. With no children: its direction in words for screen readers, and its size, which Rolls. */
function StatDelta({ className, children, ...props }: StatPart<"delta">) {
  return usePart(
    stat,
    "delta",
    {},
    {
      ...props,
      className: withClass(partMotion, className),
      children:
        children ??
        ((state) => (
          <>
            <span className="sr-only">{state.words}</span>
            <span aria-hidden>{state.trend === "up" ? "+" : state.trend === "down" ? "−" : ""}</span>
            <span aria-hidden>
              <Roll text={state.text} />
            </span>
          </>
        )),
    },
    "div",
  )
}

/** What the delta compares against, like "vs last 30 days". */
function StatComparison({ className, ...props }: StatPart<"comparison">) {
  return usePart(stat, "comparison", {}, { ...props, className: withClass(partMotion, className) }, "div")
}

/** A small icon for the number. */
function StatIcon({ className, ...props }: StatPart<"icon">) {
  return usePart(stat, "icon", {}, { ...props, className: withClass(partMotion, className) }, "div")
}

/** Holds a Sparkline (or any small chart) under the number. Its `data-tone` matches the delta. */
function StatChart({ className, ...props }: StatPart<"chart">) {
  return usePart(stat, "chart", {}, { ...props, className: withClass(partMotion, className) }, "div")
}

/* ---------------------------------------------------------------- group */

const group = createParts(statGroup, { root: "div", grid: "div" })

/** Several stats as one object. Name it with `aria-label`. Its children go in its grid. */
function StatGroup({ className, children, gridClassName, ...props }: React.ComponentProps<typeof group.Root> & { gridClassName?: string }) {
  return (
    <group.Root className={withClass("relative min-w-0", className)} {...props}>
      <group.Grid className={cn("grid", gridClassName)}>{children as React.ReactNode}</group.Grid>
    </group.Root>
  )
}

export { Roll, Stat, StatChart, StatComparison, StatDelta, StatGroup, StatIcon, StatLabel, type StatProps, StatValue }
export { defaultFormatDelta, type StatTone, type StatTrend } from "@/components/keyframery/core/stat-core"
```

**components/keyframery/core/stat-core.ts**

```ts
/* Stats, as UI SDK primitives. UI SDK ships no stat, so they are defined with its core: the same
   definitions render in React, Vue, Svelte, Solid and web components.

   `stat` is the KPI card of a dashboard: a label, a value, a delta with its direction (up, down or
   flat), a comparison line, an optional icon and an optional slot for a sparkline, with a loading
   state. The delta's direction is state, and so is whether it is good news: `downIsGood` turns the
   meaning round for numbers that should fall, like refunds. Agents read the label, the value and
   the delta.

   `statGroup` lays several stats out as one object: one surface, dividers between them. */

import { definePrimitive } from "@ui-sdk/core"

type StatTrend = "up" | "down" | "flat"
/** Whether the delta is good news: `positive`, `negative`, or `neutral` when it is flat. */
type StatTone = "positive" | "negative" | "neutral"
type StatValueFormatter = (value: number) => string
type StatDeltaFormatter = (delta: number) => string

type StatOptions = {
  /** What the number is, like "Revenue". Names the stat for screen readers and agents. */
  label?: string
  /** The number. `null` while there is none. */
  value?: number | null
  /** Formats the value, like `(v) => "$" + v.toLocaleString()`. */
  formatValue?: StatValueFormatter
  /** The change against the comparison period, as a share: 0.124 is up 12.4%. `null` for none. */
  delta?: number | null
  /** Formats the delta's size (always positive; the sign is drawn by the direction). Defaults to "12.4%". */
  formatDelta?: StatDeltaFormatter
  /** A fall is good news (refunds, churn, costs): the tone turns round. */
  downIsGood?: boolean
  /** A delta smaller than this counts as flat. Defaults to 0.0005 (0.05%). */
  flatThreshold?: number
  /** Shows placeholders at the parts' own size instead of the numbers. */
  loading?: boolean
}

type StatState = {
  label: string
  value: number | null
  valueText: string
  delta: number | null
  deltaText: string
  trend: StatTrend
  tone: StatTone
  loading: boolean
  downIsGood: boolean
}

const groupFormat = new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 })
const defaultFormatValue: StatValueFormatter = (value) => groupFormat.format(value)
/** "12%", or "4.2%" under ten. */
const defaultFormatDelta: StatDeltaFormatter = (delta) => {
  const value = Math.abs(delta) * 100
  return `${value < 10 ? (Math.round(value * 10) / 10).toFixed(1) : Math.round(value)}%`
}

function stateOf(options: StatOptions): StatState {
  const value = typeof options.value === "number" && Number.isFinite(options.value) ? options.value : null
  const delta = typeof options.delta === "number" && Number.isFinite(options.delta) ? options.delta : null
  const threshold = options.flatThreshold ?? 0.0005
  const downIsGood = options.downIsGood ?? false
  const trend: StatTrend = delta === null || Math.abs(delta) <= threshold ? "flat" : delta > 0 ? "up" : "down"
  const tone: StatTone = trend === "flat" ? "neutral" : (trend === "up") !== downIsGood ? "positive" : "negative"
  const format = options.formatValue ?? defaultFormatValue
  return {
    label: options.label ?? "",
    value,
    valueText: value === null ? "—" : format(value),
    delta,
    deltaText: delta === null ? "" : (options.formatDelta ?? defaultFormatDelta)(delta),
    trend,
    tone,
    loading: options.loading ?? false,
    downIsGood,
  }
}

/** What the delta says in words: "up 12%", "down 3.1%", "no change". */
function deltaWords(state: Pick<StatState, "trend" | "deltaText" | "delta">) {
  if (state.delta === null) return ""
  return state.trend === "flat" ? "no change" : `${state.trend} ${state.deltaText}`
}

const stat = definePrimitive({
  name: "stat",
  options: {
    label: "string",
    value: "value",
    formatValue: "value",
    delta: "value",
    formatDelta: "value",
    downIsGood: "boolean",
    flatThreshold: "number",
    loading: "boolean",
  },
  /* Read-only: an agent reads the label, the value, the delta and its news, and sets nothing. */
  controlled: ["label", "value", "valueText", "delta", "deltaText", "trend", "tone", "loading"],
  state: (options: StatOptions): StatState => stateOf(options),
  sync: (options) => stateOf(options),
  api: () => ({}),
  slots: (slot) => ({
    /* A group named by its label. While loading it is busy. */
    root: slot<{}, { label: string; trend: StatTrend; tone: StatTone; loading: boolean }>({
      role: "group",
      state: (state) => ({ label: state.label, trend: state.trend, tone: state.tone, loading: state.loading }),
      attrs: (state) => ({
        "aria-label": state.label || undefined,
        "aria-busy": state.loading ? "true" : undefined,
        "data-trend": state.trend,
        "data-tone": state.tone,
        "data-loading": state.loading ? "" : undefined,
      }),
    }),
    /* The label. With no children it shows `label`. */
    label: slot<{}, { label: string }>({
      state: (state) => ({ label: state.label }),
      attrs: (state) => ({ "data-loading": state.loading ? "" : undefined }),
    }),
    /* The number. With no children it shows the formatted value. */
    value: slot<{}, { text: string; value: number | null }>({
      state: (state) => ({ text: state.valueText, value: state.value }),
      attrs: (state) => ({ "data-loading": state.loading ? "" : undefined }),
    }),
    /* The change, with its direction and whether it is good news. */
    delta: slot<{}, { text: string; words: string; trend: StatTrend; tone: StatTone }>({
      present: (state) => state.delta !== null || state.loading,
      state: (state) => ({ text: state.deltaText, words: deltaWords(state), trend: state.trend, tone: state.tone }),
      attrs: (state) => ({
        "data-trend": state.trend,
        "data-tone": state.tone,
        "data-loading": state.loading ? "" : undefined,
      }),
    }),
    /* What the delta compares against, like "vs last 30 days". */
    comparison: slot({
      attrs: (state) => ({ "data-loading": state.loading ? "" : undefined }),
    }),
    /* A small icon for the number. Decorative. */
    icon: slot({
      attrs: (state) => ({ "aria-hidden": "true", "data-loading": state.loading ? "" : undefined }),
    }),
    /* Holds a sparkline (or any small chart) under the number. */
    chart: slot<{}, { trend: StatTrend; tone: StatTone }>({
      state: (state) => ({ trend: state.trend, tone: state.tone }),
      attrs: (state) => ({ "data-tone": state.tone, "data-loading": state.loading ? "" : undefined }),
    }),
  }),
  agent: { actions: [] },
})

/* A row of stats on one surface. Layout and dividers are the renderer's; the group names them. */
const statGroup = definePrimitive({
  name: "stat-group",
  state: () => ({}),
  api: () => ({}),
  slots: (slot) => ({
    /* A group of stats. Name it with `aria-label`, like "Store, last 30 days". */
    root: slot({ role: "group" }),
    /* The grid the stats sit in. */
    grid: slot({}),
  }),
  agent: { actions: [] },
})

export {
  defaultFormatDelta,
  deltaWords,
  stat,
  type StatDeltaFormatter,
  statGroup,
  type StatOptions,
  type StatState,
  type StatTone,
  type StatTrend,
  type StatValueFormatter,
}
```

**Check the import paths**

The files import from `@/components/keyframery/…` and `@/lib/…`. Change those if your project's aliases differ.

## Usage [#usage]

```tsx
import { Stat } from "@/components/keyframery/stat"

export default function Usage() {
  return <Stat label="Revenue" value={48210} formatValue={(v) => `$${v.toLocaleString("en-US")}`} delta={0.124} />
}
```

## Examples [#examples]

### A stat with every part [#a-stat-with-every-part]

The label, an icon, the value, the delta with its comparison, and a sparkline that takes the delta's colour.

<ExamplePreview name="stat/card">
  ```tsx
  import { Wallet } from "lucide-react"

  import { Sparkline } from "@/components/keyframery/sparkline"
  import { Stat, StatChart, StatComparison, StatDelta, StatIcon, StatLabel, StatValue } from "@/components/keyframery/stat"

  const money = (v: number) => `$${Math.round(v).toLocaleString("en-US")}`
  const daily = [3120, 3380, 3290, 3610, 3540, 3880, 4020, 3950, 4210, 4380, 4290, 4620, 4710, 4890]

  export default function StatCard() {
    return (
      <Stat className="w-full max-w-[300px]" label="Revenue" value={daily.reduce((a, b) => a + b, 0)} formatValue={money} delta={0.124}>
        <StatLabel />
        <StatIcon>
          <Wallet />
        </StatIcon>
        <StatValue />
        <StatDelta />
        <StatComparison>vs previous 14 days</StatComparison>
        <StatChart>
          <Sparkline type="area" data={daily} label="Revenue per day" period="last 14 days" formatValue={money} />
        </StatChart>
      </Stat>
    )
  }
  ```
</ExamplePreview>

### A row of stats [#a-row-of-stats]

StatGroup puts stats on one surface with hairlines between them: four across on a wide container, two, then one. Refunds should fall, so `downIsGood` colours their fall green.

<ExamplePreview name="stat/group">
  ```tsx
  import { Stat, StatComparison, StatDelta, StatGroup, StatLabel, StatValue } from "@/components/keyframery/stat"

  const stats = [
    { label: "Revenue", value: 124505, format: (v: number) => `$${v.toLocaleString("en-US")}`, delta: 0.065 },
    { label: "Orders", value: 1839, format: (v: number) => v.toLocaleString("en-US"), delta: 0.031 },
    { label: "Average order", value: 67.7, format: (v: number) => `$${v.toFixed(2)}`, delta: -0.012 },
    { label: "Refund rate", value: 0.02, format: (v: number) => `${(v * 100).toFixed(1)}%`, delta: -0.027, downIsGood: true },
  ]

  export default function StatRow() {
    return (
      <StatGroup aria-label="Store, last 30 days">
        {stats.map((s) => (
          <Stat key={s.label} label={s.label} value={s.value} formatValue={s.format} delta={s.delta} downIsGood={s.downIsGood}>
            <StatLabel />
            <StatValue />
            <StatDelta />
            <StatComparison>vs previous 30 days</StatComparison>
          </Stat>
        ))}
      </StatGroup>
    )
  }
  ```
</ExamplePreview>

### Loading at its own size [#loading-at-its-own-size]

While `loading`, each part keeps its geometry as a soft block; when it ends the numbers fade back in, one part after another.

<ExamplePreview name="stat/loading">
  ```tsx
  import * as React from "react"

  import { Switch } from "@/components/keyframery/switch"
  import { Stat, StatComparison, StatDelta, StatLabel, StatValue } from "@/components/keyframery/stat"

  export default function StatLoading() {
    const [loading, setLoading] = React.useState(true)
    return (
      <div className="grid w-full max-w-[280px] gap-4">
        <label className="flex items-center gap-2 text-[13px]">
          <Switch checked={loading} onCheckedChange={setLoading} />
          Loading
        </label>
        <Stat label="Orders" value={1839} formatValue={(v) => v.toLocaleString("en-US")} delta={0.031} loading={loading}>
          <StatLabel />
          <StatValue />
          <StatDelta />
          <StatComparison>vs previous 30 days</StatComparison>
        </Stat>
      </div>
    )
  }
  ```
</ExamplePreview>

## Motion [#motion]

| Move        | What you see                                                                                                                                       |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Cascade** | On arrival the label, value, delta and chart rise out of a light blur one after another; when loading ends their ink comes back in the same order. |
| **Roll**    | The value and the delta roll digit by digit to each new number, the right-hand digits a beat ahead.                                                |
| **Spring**  | The delta's arrow turns to its new direction (up, down or level) on a spring; its colour, which means status, switches at once.                    |
| **Draw**    | A sparkline in the stat draws itself and tweens into the new period's shape.                                                                       |

Timing and springiness follow the [motion style](/docs/motion-styles) you set. To change how fast this stat moves, pass `speed`:

```tsx
<Stat speed="fast">
  …
</Stat>
```

`"fast"` is 0.6×, `"slow"` 1.4×, and a number sets the multiplier. With reduced motion turned on, nothing moves: changes happen at once or with a short fade.

## Theming [#theming]

Set these CSS variables on the component or a parent. Leave them unset to follow the light and dark theme. The open Customize panel below the preview lets you try these settings.

| Variable               | What it changes                          | Default                                            |
| ---------------------- | ---------------------------------------- | -------------------------------------------------- |
| `--stat-surface`       | The card, and the group's shared surface | --background; --card in dark                       |
| `--stat-divider`       | The hairlines between stats in a group   | --border                                           |
| `--stat-label`         | The label                                | --muted-foreground                                 |
| `--stat-positive`      | Good news: the delta and the sparkline   | oklch(0.55 0.15 150); oklch(0.74 0.16 150) in dark |
| `--stat-negative`      | Bad news: the delta and the sparkline    | --destructive                                      |
| `--stat-value-size`    | The number's size                        | 28px                                               |
| `--stat-radius`        | The corners                              | 16px                                               |
| `--stat-padding`       | The inset                                | 1.25rem                                            |
| `--stat-group-columns` | Columns in a group on a wide container   | 4                                                  |
| `--stat-chart-height`  | The height of a sparkline in StatChart   | 2.75rem                                            |

## API reference [#api-reference]

Every part takes `className` and `children`, along with the props of the element it renders. The parts are rendered by UI SDK, so they also take `render`, to draw your own element, and a function of their state for `className` and `style`.

### Stat [#stat]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;speed&#x22;,&#x22;type&#x22;:&#x22;\&#x22;fast\&#x22; | \&#x22;normal\&#x22; | \&#x22;slow\&#x22; | number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;How fast it moves: \&#x22;fast\&#x22;, \&#x22;normal\&#x22;, \&#x22;slow\&#x22; or a multiplier.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;label&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;What the number is, like \&#x22;Revenue\&#x22;. Shown by StatLabel and names the stat for screen readers and agents.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;value&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The number. `null` shows a dash.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;formatValue&#x22;,&#x22;type&#x22;:&#x22;StatValueFormatter&#x22;,&#x22;full&#x22;:&#x22;StatValueFormatter&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Formats the value, like `(v) => \&#x22;$\&#x22; + v.toLocaleString()`.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;delta&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;The change against the comparison period, as a share: 0.124 is up 12.4%. `null` hides the delta.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;formatDelta&#x22;,&#x22;type&#x22;:&#x22;StatDeltaFormatter&#x22;,&#x22;full&#x22;:&#x22;StatDeltaFormatter&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Formats the delta's size (the arrow carries the sign). Defaults to \&#x22;12%\&#x22;, or \&#x22;4.2%\&#x22; under ten.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;downIsGood&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A fall is good news (refunds, churn, costs): a negative delta turns green and a positive one red. A Sparkline inside StatChart follows the delta's colour.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;flatThreshold&#x22;,&#x22;type&#x22;:&#x22;number&#x22;,&#x22;full&#x22;:&#x22;number&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;A delta smaller than this counts as flat (muted, arrow level). Defaults to 0.0005.&#x22;,&#x22;required&#x22;:false},{&#x22;name&#x22;:&#x22;loading&#x22;,&#x22;type&#x22;:&#x22;boolean&#x22;,&#x22;full&#x22;:&#x22;boolean&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Shows placeholders at each part's own size. Keep passing the last value so the placeholders keep their width.&#x22;,&#x22;required&#x22;:false}]" />

### StatGroup [#statgroup]

Renders a `<div>`, and takes its props too.

<PropsTable rows="[{&#x22;name&#x22;:&#x22;gridClassName&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;Classes for the grid the stats sit in.&#x22;,&#x22;required&#x22;:false}]" />

### Roll [#roll]

<PropsTable rows="[{&#x22;name&#x22;:&#x22;text&#x22;,&#x22;type&#x22;:&#x22;string&#x22;,&#x22;full&#x22;:&#x22;string&#x22;,&#x22;default&#x22;:null,&#x22;description&#x22;:&#x22;&#x22;,&#x22;required&#x22;:true}]" />

### Other parts [#other-parts]

These take the props of the element they render, and nothing else:

* `StatChart`: a `<div>`
* `StatComparison`: a `<div>`
* `StatDelta`: a `<div>`
* `StatIcon`: a `<div>`
* `StatLabel`: a `<div>`
* `StatValue`: a `<div>`

## Keyboard [#keyboard]

| Key            | What it does                                                                                           |
| -------------- | ------------------------------------------------------------------------------------------------------ |
| <kbd>Tab</kbd> | A stat takes no focus of its own; Tab reaches a sparkline inside it, whose points take the arrow keys. |

## Accessibility [#accessibility]

Roles, keyboard and focus are declared on the component's UI SDK primitive, and state is announced through the matching ARIA attributes. More in [Accessibility](/docs/accessibility).

## Built on UI SDK's core [#built-on-ui-sdks-core]

UI SDK doesn't ship a stat, so this one is defined with its core: one `definePrimitive` in `components/keyframery/core/stat-core.ts`, with no React in it. UI SDK's adapters can render that same definition in Vue, Svelte, Solid and web components. To keep your own styling and take only the motion, import from `@/components/keyframery/primitives/stat`.

## Questions

### How does the animated Stat for UI SDK move?

Cascade: On arrival the label, value, delta and chart rise out of a light blur one after another; when loading ends their ink comes back in the same order. Roll: The value and the delta roll digit by digit to each new number, the right-hand digits a beat ahead. Spring: The delta's arrow turns to its new direction (up, down or level) on a spring; its colour, which means status, switches at once. Draw: A sparkline in the stat draws itself and tweens into the new period's shape.

### Do I need Motion or Framer Motion for the animated Stat?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### UI SDK has no stat. How is this one built on UI SDK?

Its behaviour is one definition written with UI SDK's core (`definePrimitive`), in `components/keyframery/core/stat-core.ts`. Its parts are rendered by UI SDK's adapter, so they take `render`, state-based class names and `data-slot`, like every UI SDK component.

### What happens to the Stat when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
