{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "metric-card",
  "title": "Metric Card",
  "description": "A KPI card whose chart you can run along to read any day. Let go and the headline goes back to the total.",
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/default/metric-card/metric-card.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\nimport { cn } from \"@/lib/utils\"\n\nexport type MetricPoint = {\n  /** A calendar day as YYYY-MM-DD, or any ISO date. Shown in UTC. */\n  date: string\n  value: number\n}\n\nexport type MetricPeriod = { value: string; label: string }\n\nexport type MetricCardProps = Omit<\n  React.HTMLAttributes<HTMLDivElement>,\n  \"children\"\n> & {\n  label: string\n  /** One point per day of the current period, oldest first. */\n  data: readonly MetricPoint[]\n  /** The headline. Defaults to the sum of the data. */\n  value?: number\n  /** The same measure for the period before, for the change. */\n  previous?: number\n  /** Which way is good news. Decides which change reads as a warning. */\n  goodDirection?: \"up\" | \"down\"\n  /** Follows the change. Defaults to \"vs previous period\". */\n  comparisonLabel?: string\n  /** Passed to Intl.NumberFormat for the headline and every day. */\n  format?: Intl.NumberFormatOptions\n  /** Passed to Intl.DateTimeFormat for the day being read. */\n  dateFormat?: Intl.DateTimeFormatOptions\n  locale?: string\n  /** Shows a segmented control. The host swaps the data when it changes. */\n  periods?: readonly MetricPeriod[]\n  period?: string\n  defaultPeriod?: string\n  onPeriodChange?: (period: string) => void\n  /** Any CSS colour. Defaults to the theme's first chart colour, then primary. */\n  color?: string\n  /** Height of the chart in pixels. */\n  chartHeight?: number\n}\n\nconst VIEW_WIDTH = 1000\nconst TOP = 8\n\nconst DAY_FORMAT: Intl.DateTimeFormatOptions = {\n  weekday: \"short\",\n  month: \"short\",\n  day: \"numeric\",\n}\n\nfunction RollingNumber({ text, still }: { text: string; still: boolean }) {\n  const characters = text.split(\"\")\n\n  return (\n    <span aria-hidden=\"true\" className=\"inline-flex tabular-nums\">\n      {characters.map((character, index) => {\n        const key = characters.length - index\n        if (!/[0-9]/.test(character)) {\n          return (\n            <span className=\"inline-block\" key={`${key}${character}`}>\n              {character}\n            </span>\n          )\n        }\n        return (\n          <span\n            className=\"relative inline-block h-[1em] overflow-hidden\"\n            key={key}\n          >\n            <span className=\"invisible\">0</span>\n            <span\n              className={cn(\n                \"absolute inset-x-0 top-0 flex flex-col\",\n                !still &&\n                  \"transition-transform duration-500 ease-[cubic-bezier(0.2,0.8,0.2,1)] motion-reduce:transition-none\"\n              )}\n              data-digit={character}\n              style={{ transform: `translateY(-${Number(character)}em)` }}\n            >\n              {Array.from({ length: 10 }, (_, digit) => (\n                <span className=\"h-[1em]\" key={digit}>\n                  {digit}\n                </span>\n              ))}\n            </span>\n          </span>\n        )\n      })}\n    </span>\n  )\n}\n\nexport function MetricCard({\n  label,\n  data,\n  value,\n  previous,\n  goodDirection = \"up\",\n  comparisonLabel = \"vs previous period\",\n  format,\n  dateFormat = DAY_FORMAT,\n  locale,\n  periods,\n  period,\n  defaultPeriod,\n  onPeriodChange,\n  color = \"var(--chart-1, var(--primary))\",\n  chartHeight = 96,\n  className,\n  ...rootProps\n}: MetricCardProps) {\n  const id = React.useId().replace(/[^a-zA-Z0-9_-]/g, \"\")\n  const [active, setActive] = React.useState<number | null>(null)\n  const [ownPeriod, setOwnPeriod] = React.useState(\n    defaultPeriod ?? periods?.[0]?.value\n  )\n  const selectedPeriod = period ?? ownPeriod\n\n  const numbers = React.useMemo(\n    () => new Intl.NumberFormat(locale, format),\n    [format, locale]\n  )\n  const signed = React.useMemo(\n    () =>\n      new Intl.NumberFormat(locale, {\n        style: \"percent\",\n        maximumFractionDigits: 1,\n        signDisplay: \"exceptZero\",\n      }),\n    [locale]\n  )\n  const percent = React.useMemo(\n    () =>\n      new Intl.NumberFormat(locale, {\n        style: \"percent\",\n        maximumFractionDigits: 1,\n      }),\n    [locale]\n  )\n  const dates = React.useMemo(\n    () => new Intl.DateTimeFormat(locale, { ...dateFormat, timeZone: \"UTC\" }),\n    [dateFormat, locale]\n  )\n  const edgeDates = React.useMemo(\n    () =>\n      new Intl.DateTimeFormat(locale, {\n        month: \"short\",\n        day: \"numeric\",\n        timeZone: \"UTC\",\n      }),\n    [locale]\n  )\n\n  const total = value ?? data.reduce((sum, point) => sum + point.value, 0)\n  const point = active === null ? undefined : data[active]\n  const scrubbing = point !== undefined\n  const headline = scrubbing ? point.value : total\n\n  const change =\n    previous !== undefined && previous !== 0\n      ? (total - previous) / Math.abs(previous)\n      : null\n  const direction =\n    change === null || change === 0 ? \"flat\" : change > 0 ? \"up\" : \"down\"\n  const good = direction === \"flat\" || direction === goodDirection\n\n  const values = data.map((entry) => entry.value)\n  const min = Math.min(0, ...values)\n  const max = Math.max(0, ...values)\n  const span = max - min || 1\n  const x = (index: number) =>\n    data.length > 1 ? (index / (data.length - 1)) * VIEW_WIDTH : VIEW_WIDTH / 2\n  const y = (amount: number) =>\n    TOP + ((max - amount) / span) * (chartHeight - TOP - 1)\n  const xPercent = (index: number) => (x(index) / VIEW_WIDTH) * 100\n\n  const line = data\n    .map(\n      (entry, index) =>\n        `${index === 0 ? \"M\" : \"L\"}${x(index).toFixed(2)} ${y(entry.value).toFixed(2)}`\n    )\n    .join(\" \")\n  const fill =\n    data.length > 1 ? `${line} L${VIEW_WIDTH} ${y(0)} L0 ${y(0)} Z` : \"\"\n\n  const last = data.length - 1\n  const reading = active ?? last\n\n  function scrubTo(clientX: number, element: HTMLElement) {\n    if (!data.length) return\n    const rect = element.getBoundingClientRect()\n    const ratio = rect.width ? (clientX - rect.left) / rect.width : 1\n    setActive(Math.round(Math.min(Math.max(ratio, 0), 1) * last))\n  }\n\n  function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (event.key === \"Escape\") {\n      setActive(null)\n      return\n    }\n    const steps: Record<string, number | undefined> = {\n      ArrowLeft: reading - 1,\n      ArrowDown: reading - 1,\n      ArrowRight: reading + 1,\n      ArrowUp: reading + 1,\n      PageDown: reading - 7,\n      PageUp: reading + 7,\n      Home: 0,\n      End: last,\n    }\n    const next = steps[event.key]\n    if (next === undefined) return\n    event.preventDefault()\n    setActive(Math.min(Math.max(next, 0), last))\n  }\n\n  function choosePeriod(next: string) {\n    setOwnPeriod(next)\n    onPeriodChange?.(next)\n  }\n\n  function handlePeriodKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    if (!periods?.length) return\n    const index = periods.findIndex((entry) => entry.value === selectedPeriod)\n    const offset =\n      event.key === \"ArrowRight\" || event.key === \"ArrowDown\"\n        ? 1\n        : event.key === \"ArrowLeft\" || event.key === \"ArrowUp\"\n          ? -1\n          : 0\n    if (!offset) return\n    event.preventDefault()\n    const target =\n      (Math.max(index, 0) + offset + periods.length) % periods.length\n    const next = periods[target]\n    if (!next) return\n    choosePeriod(next.value)\n    event.currentTarget\n      .querySelectorAll<HTMLElement>('[role=\"radio\"]')\n      [target]?.focus()\n  }\n\n  const dayText = (index: number) => {\n    const entry = data[index]\n    return entry ? dates.format(new Date(entry.date)) : \"\"\n  }\n\n  const firstPoint = data[0]\n  const lastPoint = data[last]\n\n  return (\n    <div\n      aria-labelledby={`${id}-label`}\n      data-slot=\"metric-card\"\n      data-state={scrubbing ? \"scrubbing\" : \"idle\"}\n      role=\"group\"\n      className={cn(\n        \"bg-card text-card-foreground border-border w-full min-w-0 rounded-xl border p-4 sm:p-5\",\n        className\n      )}\n      {...rootProps}\n    >\n      <div className=\"flex min-h-7 flex-wrap items-center justify-between gap-2\">\n        <p className=\"text-muted-foreground text-sm\" id={`${id}-label`}>\n          {label}\n        </p>\n        {periods?.length ? (\n          <div\n            aria-label=\"Period\"\n            className=\"bg-muted inline-flex rounded-md p-0.5\"\n            onKeyDown={handlePeriodKeyDown}\n            role=\"radiogroup\"\n          >\n            {periods.map((entry) => {\n              const checked = entry.value === selectedPeriod\n              return (\n                <button\n                  aria-checked={checked}\n                  className={cn(\n                    \"focus-visible:ring-ring min-h-6 rounded-[5px] px-2 text-xs font-medium transition-colors duration-150 focus-visible:ring-2 focus-visible:outline-none motion-reduce:transition-none\",\n                    checked\n                      ? \"bg-background text-foreground shadow-sm\"\n                      : \"text-muted-foreground hover:text-foreground\"\n                  )}\n                  key={entry.value}\n                  onClick={() => choosePeriod(entry.value)}\n                  role=\"radio\"\n                  tabIndex={checked ? 0 : -1}\n                  type=\"button\"\n                >\n                  {entry.label}\n                </button>\n              )\n            })}\n          </div>\n        ) : null}\n      </div>\n\n      <p\n        className=\"mt-1 text-3xl leading-none font-semibold tracking-tight\"\n        data-slot=\"metric-card-value\"\n      >\n        <RollingNumber still={scrubbing} text={numbers.format(headline)} />\n        <span className=\"sr-only\">{numbers.format(total)}</span>\n      </p>\n\n      <div className=\"mt-2 flex min-h-5 items-center gap-2 text-xs\">\n        {scrubbing ? (\n          <span\n            aria-hidden=\"true\"\n            className=\"text-muted-foreground\"\n            data-slot=\"metric-card-date\"\n          >\n            {dayText(active ?? 0)}\n          </span>\n        ) : change !== null ? (\n          <>\n            <span\n              data-good={good || undefined}\n              data-slot=\"metric-card-change\"\n              className={cn(\n                \"inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 font-medium tabular-nums\",\n                good\n                  ? \"bg-muted text-foreground\"\n                  : \"bg-destructive/10 text-destructive\"\n              )}\n            >\n              <svg\n                aria-hidden=\"true\"\n                className={cn(\"size-2.5\", direction === \"down\" && \"rotate-180\")}\n                fill=\"currentColor\"\n                viewBox=\"0 0 10 10\"\n              >\n                {direction === \"flat\" ? (\n                  <rect height=\"2\" rx=\"1\" width=\"8\" x=\"1\" y=\"4\" />\n                ) : (\n                  <path d=\"M5 1.5 9 8H1z\" />\n                )}\n              </svg>\n              <span aria-hidden=\"true\">{signed.format(change)}</span>\n              <span className=\"sr-only\">\n                {direction === \"flat\"\n                  ? \"Unchanged\"\n                  : `${direction === \"up\" ? \"Up\" : \"Down\"} ${percent.format(Math.abs(change))}`}\n              </span>\n            </span>\n            <span className=\"text-muted-foreground\">{comparisonLabel}</span>\n          </>\n        ) : null}\n      </div>\n\n      <div className=\"relative mt-4\" style={{ height: chartHeight }}>\n        <svg\n          aria-hidden=\"true\"\n          className=\"block size-full overflow-visible\"\n          preserveAspectRatio=\"none\"\n          viewBox={`0 0 ${VIEW_WIDTH} ${chartHeight}`}\n        >\n          <defs>\n            <linearGradient id={`${id}-fill`} x1=\"0\" x2=\"0\" y1=\"0\" y2=\"1\">\n              <stop\n                offset=\"0%\"\n                style={{ stopColor: color, stopOpacity: 0.22 }}\n              />\n              <stop\n                offset=\"100%\"\n                style={{ stopColor: color, stopOpacity: 0 }}\n              />\n            </linearGradient>\n          </defs>\n          <line\n            stroke=\"var(--border)\"\n            strokeWidth=\"1\"\n            vectorEffect=\"non-scaling-stroke\"\n            x1=\"0\"\n            x2={VIEW_WIDTH}\n            y1={y(0)}\n            y2={y(0)}\n          />\n          {fill ? <path d={fill} fill={`url(#${id}-fill)`} /> : null}\n          {line ? (\n            <path\n              d={line}\n              fill=\"none\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              strokeWidth=\"2\"\n              style={{ stroke: color }}\n              vectorEffect=\"non-scaling-stroke\"\n            />\n          ) : null}\n        </svg>\n\n        {point ? (\n          <>\n            <span\n              aria-hidden=\"true\"\n              className=\"bg-border pointer-events-none absolute inset-y-0 w-px\"\n              data-slot=\"metric-card-crosshair\"\n              style={{ left: `${xPercent(active ?? 0)}%` }}\n            />\n            <span\n              aria-hidden=\"true\"\n              className=\"ring-card pointer-events-none absolute size-2.5 -translate-1/2 rounded-full ring-2\"\n              style={{\n                background: color,\n                left: `${xPercent(active ?? 0)}%`,\n                top: y(point.value),\n              }}\n            />\n          </>\n        ) : null}\n\n        {lastPoint ? (\n          <div\n            aria-label={`${label} by day`}\n            aria-valuemax={last}\n            aria-valuemin={0}\n            aria-valuenow={reading}\n            aria-valuetext={`${dayText(reading)}: ${numbers.format(data[reading]?.value ?? 0)}`}\n            className=\"focus-visible:ring-ring focus-visible:ring-offset-card absolute inset-0 cursor-crosshair touch-pan-y rounded-sm focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none\"\n            onBlur={() => setActive(null)}\n            onFocus={() => setActive(last)}\n            onKeyDown={handleKeyDown}\n            onPointerDown={(event) =>\n              scrubTo(event.clientX, event.currentTarget)\n            }\n            onPointerLeave={() => setActive(null)}\n            onPointerMove={(event) =>\n              scrubTo(event.clientX, event.currentTarget)\n            }\n            onPointerUp={(event) => {\n              if (event.pointerType !== \"mouse\") setActive(null)\n            }}\n            role=\"slider\"\n            tabIndex={0}\n          />\n        ) : null}\n      </div>\n\n      {firstPoint && lastPoint && data.length > 1 ? (\n        <div\n          aria-hidden=\"true\"\n          className=\"text-muted-foreground mt-1.5 flex justify-between text-xs tabular-nums\"\n        >\n          <span>{edgeDates.format(new Date(firstPoint.date))}</span>\n          <span>{edgeDates.format(new Date(lastPoint.date))}</span>\n        </div>\n      ) : null}\n    </div>\n  )\n}\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "chart",
    "card",
    "statistic",
    "number"
  ],
  "type": "registry:ui"
}