# Stat

> A big number with a short label on the same baseline, where each digit rolls to its new value.

Docs: https://plumbago.ochotzas.com/components/stat

## Installation

```sh
npx plumbago add stat
```

This copies `components/ui/stat.tsx` into your project, along with `cn`.

## Usage

```tsx
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"

<Stat>
  <StatValue>3</StatValue>
  <StatLabel>of 7 done</StatLabel>
</Stat>
```

## Examples

### Preview

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { Button } from "@/components/ui/button"
import { Island } from "@/components/ui/island"
import { Progress } from "@/components/ui/progress"
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"
import { useState } from "react"

export default function StatDemo() {
  const [done, setDone] = useState(3)

  return (
    <Island className="flex w-full max-w-xs flex-col gap-4">
      <Stat>
        <StatValue>{done}</StatValue>
        <StatLabel>of 7 done</StatLabel>
        <Progress value={done} max={7} aria-label="Tasks done" />
      </Stat>
      <Button variant="secondary" onClick={() => setDone(done === 7 ? 0 : done + 1)}>
        <BlurSwap text={done === 7 ? "Start over" : "Mark one done"} align="center" />
      </Button>
    </Island>
  )
}
```

### Rolling total

```tsx
import { Button } from "@/components/ui/button"
import { Island } from "@/components/ui/island"
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"
import { useState } from "react"

function partySize() {
  return 2 + Math.floor(Math.random() * 5)
}

export default function StatRollingTotal() {
  const [covers, setCovers] = useState(9993)

  return (
    <Island className="flex w-full max-w-xs flex-col gap-4">
      <Stat>
        <StatValue>{covers.toLocaleString("en-US")}</StatValue>
        <StatLabel>covers this month</StatLabel>
      </Stat>
      <Button variant="secondary" onClick={() => setCovers(covers + partySize())}>
        Seat a table
      </Button>
    </Island>
  )
}
```

### With trend

```tsx
import { Island } from "@/components/ui/island"
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"

export default function StatWithTrend() {
  return (
    <Island className="w-full max-w-xs">
      <Stat>
        <StatValue>€8,420</StatValue>
        <StatLabel>taken this week</StatLabel>
        <span className="basis-full text-footnote font-semibold text-success">+12% on last week</span>
      </Stat>
    </Island>
  )
}
```

### Row

```tsx
import { Island } from "@/components/ui/island"
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"

const stats = [
  { value: 128, label: "orders today" },
  { value: 14, label: "min average wait" },
  { value: 6, label: "tables free" },
]

export default function StatRow() {
  return (
    <div className="@container w-full">
      <div className="grid gap-3 @2xl:grid-cols-3">
        {stats.map((stat) => (
          <Island key={stat.label}>
            <Stat>
              <StatValue>{stat.value}</StatValue>
              <StatLabel>{stat.label}</StatLabel>
            </Stat>
          </Island>
        ))}
      </div>
    </div>
  )
}
```

### Plain

```tsx
import { Stat, StatLabel, StatValue } from "@/components/ui/stat"

export default function StatPlain() {
  return (
    <Stat>
      <StatValue>1,284</StatValue>
      <StatLabel>covers this month</StatLabel>
    </Stat>
  )
}
```

## Source

```tsx
import { cn } from "@/lib/cn"
import { type ComponentProps, type CSSProperties, useEffect, useLayoutEffect, useRef, useState } from "react"

type PartProps<T extends keyof React.JSX.IntrinsicElements = "div"> = Omit<ComponentProps<T>, "className"> & { className?: string }

const DIGITS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
const STAGGER_MS = 25
const ROLL_MS = 350
const LEAVE_MS = 500
const MAX_ROLL_BLUR_PX = 2

export type StatProps = PartProps<"div">

export function Stat({ className, ...props }: StatProps) {
  return <div data-slot="stat" className={cn("flex flex-wrap items-baseline gap-x-2 gap-y-3", className)} {...props} />
}

export type StatValueProps = Omit<PartProps<"span">, "children"> & {
  children: string | number
}

type Slot = { key: string; character: string; position: number; leaving: boolean }

type SlotState = { text: string; nextLeavingId: number; slots: Slot[] }

const isDigit = (character: string) => /^\d$/.test(character)

function slotsFor(text: string): Slot[] {
  const characters = [...text]
  return characters.map((character, index) => {
    const position = characters.length - 1 - index
    return { key: `${position}:${isDigit(character) ? "digit" : character}`, character, position, leaving: false }
  })
}

function nextSlotState(state: SlotState, text: string): SlotState {
  const arriving = slotsFor(text)
  const arrivingKeys = new Set(arriving.map((slot) => slot.key))
  let nextLeavingId = state.nextLeavingId
  const leaving = state.slots
    .filter((slot) => slot.leaving || !arrivingKeys.has(slot.key))
    .map((slot) => (slot.leaving ? slot : { ...slot, key: `leaving-${nextLeavingId++}`, leaving: true }))
  const slots = [...leaving, ...arriving].sort((a, b) => b.position - a.position || Number(b.leaving) - Number(a.leaving))
  return { text, nextLeavingId, slots }
}

const slotStyle = cn(
  "grid grid-cols-[1fr] opacity-100 transition-[grid-template-columns,opacity,filter] duration-spring ease-spring",
  "motion-reduce:transition-opacity",
)
const arrivingStyle = "starting:grid-cols-[0fr] starting:opacity-0 motion-safe:starting:blur-[3px]"
const leavingStyle = cn(
  "grid-cols-[0fr] opacity-0 duration-base ease-in motion-safe:blur-[3px]",
  "starting:grid-cols-[1fr] starting:opacity-100 motion-safe:starting:blur-none",
)

export function StatValue({ children, className, ...props }: StatValueProps) {
  const text = String(children)
  const [mounted, setMounted] = useState(false)
  const [state, setState] = useState<SlotState>(() => ({ text, nextLeavingId: 0, slots: slotsFor(text) }))

  if (text !== state.text) setState(nextSlotState(state, text))

  useEffect(() => {
    setMounted(true)
  }, [])

  const leavingKeys = state.slots
    .filter((slot) => slot.leaving)
    .map((slot) => slot.key)
    .join()

  useEffect(() => {
    if (!leavingKeys) return
    const timeout = setTimeout(() => setState((current) => ({ ...current, slots: current.slots.filter((slot) => !slot.leaving) })), LEAVE_MS)
    return () => clearTimeout(timeout)
  }, [leavingKeys])

  return (
    <span data-slot="stat-value" className={cn("inline-flex h-[1lh] overflow-clip text-stat font-bold text-ink tabular-nums", className)} {...props}>
      <span className="sr-only">{text}</span>
      {state.slots.map((slot) => (
        <span key={slot.key} aria-hidden="true" className={cn(slotStyle, slot.leaving ? leavingStyle : mounted && arrivingStyle)}>
          <span className="min-w-0 overflow-clip">
            {isDigit(slot.character) ? <StatDigit digit={Number(slot.character)} delay={slot.position * STAGGER_MS} /> : <span>{slot.character}</span>}
          </span>
        </span>
      ))}
    </span>
  )
}

function StatDigit({ digit, delay }: { digit: number; delay: number }) {
  const columnRef = useRef<HTMLSpanElement>(null)
  const previousDigit = useRef(digit)

  useLayoutEffect(() => {
    const column = columnRef.current
    const distance = Math.abs(digit - previousDigit.current)
    previousDigit.current = digit
    if (!column || distance === 0 || typeof column.animate !== "function") return
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return
    const blur = Math.min(MAX_ROLL_BLUR_PX, distance * 0.5)
    column.animate([{ filter: "blur(0px)" }, { filter: `blur(${blur}px)`, offset: 0.3 }, { filter: "blur(0px)" }], {
      duration: ROLL_MS,
      delay,
      easing: "ease-out",
    })
  }, [digit, delay])

  return (
    <span data-slot="stat-digit" className="inline-flex h-[1lh] overflow-clip">
      <span
        ref={columnRef}
        className={cn(
          "flex translate-y-[calc(var(--stat-digit)*-1lh)] flex-col transition-transform duration-spring ease-spring",
          "motion-reduce:grid motion-reduce:translate-y-0 motion-reduce:transition-none",
        )}
        style={{ "--stat-digit": digit, transitionDelay: `${delay}ms` } as CSSProperties}
      >
        {DIGITS.map((value) => (
          <span
            key={value}
            data-current={value === digit ? "" : undefined}
            className={cn(
              "block h-[1lh]",
              "motion-reduce:col-start-1 motion-reduce:row-start-1 motion-reduce:opacity-0 motion-reduce:transition-opacity motion-reduce:duration-base motion-reduce:data-current:opacity-100",
            )}
          >
            {value}
          </span>
        ))}
      </span>
    </span>
  )
}

export function StatLabel({ className, ...props }: PartProps<"span">) {
  return <span data-slot="stat-label" className={cn("text-footnote text-ink-2", className)} {...props} />
}
```
