{
  "schemaVersion": 1,
  "target": "react",
  "name": "usage-meter",
  "version": "0.1.0",
  "category": "ai-elements",
  "title": "Usage Meter",
  "description": "Account or plan usage against an allowance, such as tokens, requests, or spend this month: a segmented bar for the breakdown, percentage and amount left, amber and red states near and at the limit, and the time until it resets.",
  "tags": [
    "ai",
    "usage",
    "billing",
    "quota",
    "tokens",
    "plan",
    "meter",
    "base-ui"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {
    "@base-ui/react": "^1.9.0"
  },
  "registryDependencies": [],
  "docsPath": "/components/usage-meter",
  "props": [
    {
      "name": "limit",
      "type": "number",
      "description": "The plan or budget allowance."
    },
    {
      "name": "used",
      "type": "number",
      "default": "sum of segments",
      "description": "Amount used so far."
    },
    {
      "name": "segments",
      "type": "{ label: string; value: number }[]",
      "description": "Parts of the usage, drawn as adjacent pieces of the bar in decreasing shades, with a small breakdown in the card."
    },
    {
      "name": "label / plan",
      "type": "ReactNode",
      "default": "\"Usage\"",
      "description": "What is measured, and the plan name beside it in the card."
    },
    {
      "name": "unit",
      "type": "string",
      "description": "Word after amounts, such as tokens or requests."
    },
    {
      "name": "currency",
      "type": "string",
      "description": "ISO 4217 code. Formats every amount as money."
    },
    {
      "name": "format",
      "type": "(value: number) => string",
      "description": "Your own amount format. Overrides currency."
    },
    {
      "name": "resetsAt",
      "type": "Date | number | string",
      "description": "When the allowance resets, shown as Resets in 42 min, Resets in 3 h, or Resets in 5 days."
    },
    {
      "name": "warnAt",
      "type": "number",
      "default": "0.8",
      "description": "Share of the limit where the meter turns amber. It turns red at the limit."
    },
    {
      "name": "variant",
      "type": "\"card\" | \"inline\"",
      "default": "\"card\"",
      "description": "A card with the breakdown and footer, or one quiet line for headers and settings rows."
    },
    {
      "name": "action",
      "type": "ReactNode",
      "description": "A control in the card footer, such as an upgrade button."
    },
    {
      "name": "message",
      "type": "ReactNode",
      "description": "Replaces the footer's status sentence."
    },
    {
      "name": "formatUsage / formatReset",
      "type": "(value: number) => string",
      "description": "The default amount format (8,940 or 1.53M) and reset sentence on their own."
    }
  ],
  "accessibility": [
    "The meter is a Base UI Meter (role=\"meter\") named by its label, with a value text that states the exact amount, the limit, the percentage, nearing or reaching the limit, and the reset time.",
    "Nearing and reaching the limit are written out in text as well as shown in amber and red.",
    "The breakdown is a description list; color swatches are decorative and repeat the bar's shades.",
    "The reset time is computed after mount and refreshed every 30 seconds, so server and client markup match.",
    "With reduced motion the bar shows its value without the sweep and the numbers appear without counting."
  ],
  "states": [
    "normal",
    "warning",
    "limit",
    "inline",
    "card"
  ],
  "files": [
    {
      "path": "agent/usage-meter.tsx",
      "content": "\"use client\";\n\nimport { Meter } from \"@base-ui/react/meter\";\nimport { type ReactNode, useEffect, useRef, useState } from \"react\";\n\nfunction cx(...classes: Array<string | false | null | undefined>) {\n  return classes.filter(Boolean).join(\" \");\n}\n\n/** One part of the usage, such as input, output, or cache tokens. */\nexport interface UsageSegment {\n  label: string;\n  value: number;\n}\n\nexport interface UsageMeterProps {\n  /** The plan or budget allowance. */\n  limit: number;\n  /** Amount used so far. Defaults to the sum of `segments`. */\n  used?: number;\n  /** Parts of the usage, drawn as adjacent pieces of the bar in decreasing shades. Up to four read well. */\n  segments?: UsageSegment[];\n  /** What is measured, e.g. \"Tokens this month\". */\n  label?: ReactNode;\n  /** Plan name shown beside the label in the card. */\n  plan?: ReactNode;\n  /** Word after amounts, e.g. \"tokens\" or \"requests\". Ignored for currency. */\n  unit?: string;\n  /** ISO 4217 code. Formats every amount as money. */\n  currency?: string;\n  /** Formats amounts yourself. Overrides `currency`. */\n  format?: (value: number) => string;\n  /** When the allowance resets. Shown as \"Resets in 3 h\". */\n  resetsAt?: Date | number | string;\n  /** Share of the limit (0 to 1) where the meter turns amber. @default 0.8 */\n  warnAt?: number;\n  /** inline is one quiet line for headers and settings rows; card adds the breakdown. @default \"card\" */\n  variant?: \"inline\" | \"card\";\n  /** A control in the card footer, such as an upgrade button. */\n  action?: ReactNode;\n  /** Replaces the footer's status sentence. */\n  message?: ReactNode;\n  className?: string;\n}\n\ntype Level = \"normal\" | \"warn\" | \"limit\";\n\nconst ease = \"ease-[cubic-bezier(0.23,1,0.32,1)]\";\nconst DURATION = 520;\n\nconst shades: Record<Level, string[]> = {\n  normal: [\"bg-zinc-950 dark:bg-white\", \"bg-zinc-950/55 dark:bg-white/60\", \"bg-zinc-950/30 dark:bg-white/35\", \"bg-zinc-950/15 dark:bg-white/20\"],\n  warn: [\"bg-amber-500\", \"bg-amber-500/65\", \"bg-amber-500/40\", \"bg-amber-500/25\"],\n  limit: [\"bg-red-500\", \"bg-red-500/65\", \"bg-red-500/40\", \"bg-red-500/25\"],\n};\n\nconst levelText: Record<Level, string> = {\n  normal: \"text-zinc-950 dark:text-white\",\n  warn: \"text-amber-600 dark:text-amber-400\",\n  limit: \"text-red-600 dark:text-red-400\",\n};\n\nconst grouped = new Intl.NumberFormat(\"en\");\nconst compact = new Intl.NumberFormat(\"en\", { notation: \"compact\", maximumSignificantDigits: 3 });\n\n/** Exact below 100,000 (8,940), compact above (1.53M). */\nexport function formatUsage(value: number): string {\n  const rounded = Math.round(value);\n  return Math.abs(rounded) < 100_000 ? grouped.format(rounded) : compact.format(rounded);\n}\n\n/** \"Resets in 42 min\", \"Resets in 3 h\", \"Resets in 5 days\". */\nexport function formatReset(ms: number): string {\n  if (ms <= 60_000) return \"Resets in under a minute\";\n  const minutes = Math.round(ms / 60_000);\n  if (minutes < 60) return `Resets in ${minutes} min`;\n  const hours = Math.round(ms / 3_600_000);\n  if (hours < 48) return `Resets in ${hours} h`;\n  return `Resets in ${Math.round(ms / 86_400_000)} days`;\n}\n\nfunction usePrefersReducedMotion() {\n  const [reduce, setReduce] = useState(false);\n  useEffect(() => {\n    const query = window.matchMedia(\"(prefers-reduced-motion: reduce)\");\n    setReduce(query.matches);\n    const onChange = () => setReduce(query.matches);\n    query.addEventListener(\"change\", onChange);\n    return () => query.removeEventListener(\"change\", onChange);\n  }, []);\n  return reduce;\n}\n\n/** Counts from the last shown value to `target` with a quint ease-out; jumps under reduced motion. */\nfunction useCountTo(target: number, reduce: boolean) {\n  const [value, setValue] = useState(0);\n  const shown = useRef(0);\n  useEffect(() => {\n    if (reduce) {\n      shown.current = target;\n      setValue(target);\n      return;\n    }\n    const from = shown.current;\n    const start = performance.now();\n    let raf = 0;\n    const tick = (now: number) => {\n      const t = Math.min(1, (now - start) / DURATION);\n      const next = from + (target - from) * (1 - Math.pow(1 - t, 5));\n      shown.current = next;\n      setValue(next);\n      if (t < 1) raf = requestAnimationFrame(tick);\n    };\n    raf = requestAnimationFrame(tick);\n    return () => cancelAnimationFrame(raf);\n  }, [target, reduce]);\n  return value;\n}\n\n/** The reset sentence, computed after mount so server and client render the same markup. */\nfunction useResetLabel(resetsAt: UsageMeterProps[\"resetsAt\"]) {\n  const [now, setNow] = useState<number | null>(null);\n  useEffect(() => {\n    if (resetsAt == null) return;\n    setNow(Date.now());\n    const id = setInterval(() => setNow(Date.now()), 30_000);\n    return () => clearInterval(id);\n  }, [resetsAt]);\n  if (resetsAt == null || now == null) return null;\n  const at = new Date(resetsAt).getTime();\n  return Number.isNaN(at) ? null : formatReset(at - now);\n}\n\n/**\n * Account or plan usage against an allowance: tokens, requests, or spend this period. A segmented\n * bar shows what the usage is made of, the bar sweeps to its value as the numbers count up, and it\n * turns amber at a threshold and red at the limit, with the time until it resets.\n */\nexport function UsageMeter({\n  limit,\n  used: usedProp,\n  segments = [],\n  label = \"Usage\",\n  plan,\n  unit,\n  currency,\n  format: formatProp,\n  resetsAt,\n  warnAt = 0.8,\n  variant = \"card\",\n  action,\n  message,\n  className,\n}: UsageMeterProps) {\n  const used = Math.max(0, usedProp ?? segments.reduce((sum, segment) => sum + segment.value, 0));\n  const ratio = limit > 0 ? used / limit : 0;\n  const level: Level = ratio >= 1 ? \"limit\" : ratio >= warnAt ? \"warn\" : \"normal\";\n  const reduce = usePrefersReducedMotion();\n  const count = useCountTo(used, reduce);\n  const reset = useResetLabel(resetsAt);\n\n  const money = currency ? new Intl.NumberFormat(\"en\", { style: \"currency\", currency, maximumFractionDigits: 2, minimumFractionDigits: 2 }) : null;\n  const format = formatProp ?? ((value: number) => (money ? money.format(value) : formatUsage(value)));\n  const suffix = unit && !money && !formatProp ? ` ${unit}` : \"\";\n\n  // The fill sweeps from empty on mount and between values after that, by clipping a full-width layer.\n  const [swept, setSwept] = useState(0);\n  useEffect(() => {\n    const raf = requestAnimationFrame(() => setSwept(Math.min(1, ratio)));\n    return () => cancelAnimationFrame(raf);\n  }, [ratio]);\n\n  const parts = segments.length ? segments : [{ label: typeof label === \"string\" ? label : \"Used\", value: used }];\n  const scaleBase = Math.max(limit, parts.reduce((sum, part) => sum + part.value, 0), 1);\n  let offset = 0;\n  const pieces = parts.map((part, index) => {\n    const left = offset;\n    const width = (Math.max(0, part.value) / scaleBase) * 100;\n    offset += width;\n    return { ...part, left, width, shade: shades[level][Math.min(index, 3)]! };\n  });\n\n  const percent = limit > 0 ? Math.round((count / limit) * 100) : 0;\n  const remaining = Math.max(0, limit - count);\n  const levelWord = level === \"limit\" ? \", limit reached\" : level === \"warn\" ? \", nearing the limit\" : \"\";\n  const exact = (value: number) => (money || formatProp ? format(value) : grouped.format(Math.round(value)));\n  const valueText = `${exact(used)} of ${exact(limit)}${suffix} used, ${Math.round(ratio * 100)}%${levelWord}${reset ? `. ${reset}` : \"\"}`;\n  const statusSentence =\n    message ??\n    (level === \"limit\" ? \"Limit reached\" : level === \"warn\" ? `${format(remaining)}${suffix} left, nearing your limit` : `${format(remaining)}${suffix} left`);\n\n  const bar = (\n    <Meter.Track\n      className={cx(\n        \"relative overflow-hidden rounded-full bg-zinc-950/[0.06] dark:bg-white/[0.1]\",\n        variant === \"card\" ? \"h-2\" : \"h-1.5 w-20 shrink-0 sm:w-24\",\n      )}\n    >\n      {variant === \"card\" && warnAt > 0 && warnAt < 1 ? (\n        <span aria-hidden=\"true\" className=\"absolute inset-y-0 w-px bg-zinc-950/20 dark:bg-white/25\" style={{ left: `${warnAt * 100}%` }} />\n      ) : null}\n      <span\n        aria-hidden=\"true\"\n        className={cx(\"absolute inset-0 transition-[clip-path] motion-reduce:transition-none\", ease)}\n        style={{ clipPath: `inset(0 ${100 - swept * 100}% 0 0)`, transitionDuration: `${DURATION}ms` }}\n      >\n        {pieces.map((piece, index) => (\n          <span\n            key={`${piece.label}-${index}`}\n            className={cx(\"absolute inset-y-0 transition-colors duration-200 ease-out motion-reduce:transition-none\", piece.shade)}\n            style={{\n              left: `${piece.left}%`,\n              width: index === pieces.length - 1 ? `${piece.width}%` : `max(0px, calc(${piece.width}% - 2px))`,\n            }}\n          />\n        ))}\n      </span>\n    </Meter.Track>\n  );\n\n  if (variant === \"inline\") {\n    return (\n      <Meter.Root\n        value={Math.min(used, limit)}\n        min={0}\n        max={limit}\n        getAriaValueText={() => valueText}\n        className={cx(\"inline-flex max-w-full flex-wrap items-center gap-x-2.5 gap-y-1 text-xs\", className)}\n      >\n        <Meter.Label className=\"text-zinc-600 dark:text-zinc-400\">{label}</Meter.Label>\n        {bar}\n        <span aria-hidden=\"true\" className={cx(\"font-mono tabular-nums\", levelText[level])}>\n          {percent}%\n        </span>\n        {level !== \"normal\" ? (\n          <span aria-hidden=\"true\" className={levelText[level]}>\n            {level === \"limit\" ? \"Limit reached\" : \"Nearing limit\"}\n          </span>\n        ) : null}\n        {reset ? (\n          <span aria-hidden=\"true\" className=\"text-zinc-500\">\n            {reset}\n          </span>\n        ) : null}\n      </Meter.Root>\n    );\n  }\n\n  return (\n    <Meter.Root\n      value={Math.min(used, limit)}\n      min={0}\n      max={limit}\n      getAriaValueText={() => valueText}\n      className={cx(\n        \"w-full max-w-sm 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    >\n      <div className=\"p-4\">\n        <div className=\"flex items-baseline justify-between gap-3\">\n          <Meter.Label className=\"min-w-0 truncate text-sm font-semibold text-zinc-950 dark:text-white\">{label}</Meter.Label>\n          {plan != null ? <span className=\"shrink-0 text-xs text-zinc-500\">{plan}</span> : null}\n        </div>\n\n        <div aria-hidden=\"true\" className=\"mt-3 flex items-baseline justify-between gap-3\">\n          <p className=\"min-w-0 truncate text-sm text-zinc-500\">\n            <span className=\"font-mono text-lg font-medium text-zinc-950 tabular-nums dark:text-white\">{format(count)}</span>\n            <span className=\"font-mono tabular-nums\"> / {format(limit)}</span>\n            {suffix}\n          </p>\n          <span className={cx(\"shrink-0 font-mono text-sm tabular-nums transition-colors duration-200 motion-reduce:transition-none\", levelText[level])}>\n            {percent}%\n          </span>\n        </div>\n\n        <div className=\"mt-2.5\">{bar}</div>\n\n        {segments.length > 1 ? (\n          <dl className=\"mt-3.5 grid gap-x-3 gap-y-2\" style={{ gridTemplateColumns: `repeat(${Math.min(pieces.length, 3)}, minmax(0, 1fr))` }}>\n            {pieces.map((piece, index) => {\n              const share = used > 0 ? Math.round((segments[index]!.value / used) * 100) : 0;\n              return (\n                <div key={`${piece.label}-${index}`} className=\"min-w-0\">\n                  <dt className=\"flex items-center gap-1.5 text-xs text-zinc-500\">\n                    <span aria-hidden=\"true\" className={cx(\"size-2 shrink-0 rounded-[2px] transition-colors duration-200 motion-reduce:transition-none\", piece.shade)} />\n                    <span className=\"truncate\">{piece.label}</span>\n                  </dt>\n                  <dd className=\"mt-0.5 flex flex-wrap gap-x-1.5 font-mono text-xs text-zinc-950 tabular-nums dark:text-white\">\n                    <span>{format(used > 0 ? (segments[index]!.value * count) / used : 0)}</span>\n                    <span className=\"text-zinc-500\">{share}%</span>\n                  </dd>\n                </div>\n              );\n            })}\n          </dl>\n        ) : null}\n      </div>\n\n      <div className=\"flex min-h-12 flex-wrap items-center justify-between gap-x-3 gap-y-2 border-t border-zinc-950/[0.07] px-4 py-2.5 text-xs dark:border-white/[0.08]\">\n        <div className=\"min-w-0\">\n          <p className={cx(level === \"normal\" ? \"text-zinc-600 dark:text-zinc-400\" : levelText[level])}>{statusSentence}</p>\n          {reset ? <p className=\"mt-0.5 text-zinc-500\">{reset}</p> : null}\n        </div>\n        {action != null ? <div className=\"shrink-0\">{action}</div> : null}\n      </div>\n    </Meter.Root>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { UsageMeter } from \"@/components/shaken/agent/usage-meter\";\n\n// In your app, resetsAt comes from the billing period end.\nconst resetsAt = Date.now() + 3 * 60 * 60 * 1000;\n\nexport default function UsageMeterExample() {\n  return (\n    <div className=\"grid w-full max-w-sm gap-6\">\n      <UsageMeter\n        label=\"Tokens this month\"\n        plan=\"Team plan\"\n        unit=\"tokens\"\n        limit={2_000_000}\n        segments={[\n          { label: \"Input\", value: 812_400 },\n          { label: \"Output\", value: 431_900 },\n          { label: \"Cache reads\", value: 286_300 },\n        ]}\n        resetsAt={resetsAt}\n        action={\n          <button\n            type=\"button\"\n            className=\"inline-flex h-8 cursor-pointer items-center rounded-lg border border-zinc-950/12 bg-white px-3 text-sm font-medium text-zinc-950 transition-colors duration-150 ease-out hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-500 motion-reduce:transition-none dark:border-white/15 dark:bg-black dark:text-white dark:hover:border-white/25 dark:hover:bg-white/[0.06]\"\n          >\n            Upgrade\n          </button>\n        }\n      />\n      <UsageMeter variant=\"inline\" label=\"Requests today\" limit={10_000} used={8_940} resetsAt={resetsAt} />\n    </div>\n  );\n}\n"
  }
}
