Usage Meter
SaveAccount 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.
- Category
- AI elements
- Version
- 0.1.0
- Frameworks
- Next.js, Vite + React
- Styling
- Tailwind CSS v4
Preview
Usage Meter preview
Tokens this monthTeam plan
- Input
- 053%
- Output
- 028%
- Cache reads
- 019%
2M tokens left
Requests today
Installation
npx @shakenui/cli add usage-meterReview the plan first. A dry run lists every file and package without changing anything:
npx @shakenui/cli add usage-meter --dry-runUsage
usage-meter-example.tsx
"use client";
import { UsageMeter } from "@/components/shaken/agent/usage-meter";
// In your app, resetsAt comes from the billing period end.
const resetsAt = Date.now() + 3 * 60 * 60 * 1000;
export default function UsageMeterExample() {
return (
<div className="grid w-full max-w-sm gap-6">
<UsageMeter
label="Tokens this month"
plan="Team plan"
unit="tokens"
limit={2_000_000}
segments={[
{ label: "Input", value: 812_400 },
{ label: "Output", value: 431_900 },
{ label: "Cache reads", value: 286_300 },
]}
resetsAt={resetsAt}
action={
<button
type="button"
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]"
>
Upgrade
</button>
}
/>
<UsageMeter variant="inline" label="Requests today" limit={10_000} used={8_940} resetsAt={resetsAt} />
</div>
);
}States
Every state, rendered from local fixture data.
Usage Meter states
TokensTeam plan
- Input
- 053%
- Output
- 028%
- Cache reads
- 020%
2M tokens left
TokensTeam plan
- Input
- 053%
- Output
- 028%
- Cache reads
- 020%
2M tokens left, nearing your limit
TokensTeam plan
- Input
- 053%
- Output
- 028%
- Cache reads
- 020%
Limit reached
Requests today
Requests today
Requests today
Spend this weekBudget
$50.00 left
API
| Prop | Type | Default | Description |
|---|---|---|---|
| limit | number | — | The plan or budget allowance. |
| used | number | sum of segments | Amount used so far. |
| segments | { label: string; value: number }[] | — | Parts of the usage, drawn as adjacent pieces of the bar in decreasing shades, with a small breakdown in the card. |
| label / plan | ReactNode | "Usage" | What is measured, and the plan name beside it in the card. |
| unit | string | — | Word after amounts, such as tokens or requests. |
| currency | string | — | ISO 4217 code. Formats every amount as money. |
| format | (value: number) => string | — | Your own amount format. Overrides currency. |
| resetsAt | Date | number | string | — | When the allowance resets, shown as Resets in 42 min, Resets in 3 h, or Resets in 5 days. |
| warnAt | number | 0.8 | Share of the limit where the meter turns amber. It turns red at the limit. |
| variant | "card" | "inline" | "card" | A card with the breakdown and footer, or one quiet line for headers and settings rows. |
| action | ReactNode | — | A control in the card footer, such as an upgrade button. |
| message | ReactNode | — | Replaces the footer's status sentence. |
| formatUsage / formatReset | (value: number) => string | — | 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.
Files
Installed into src/components/shaken, or components/shaken when the project has no src directory.
src/components/shaken/agent/usage-meter.tsxusage-meter- npm packages: @base-ui/react@^1.9.0React and Tailwind CSS v4 required
Source
The exact source the CLI installs, from /r/items/react/usage-meter/0.1.0.json.
agent/usage-meter.tsxShowHide
agent/usage-meter.tsx
"use client";
import { Meter } from "@base-ui/react/meter";
import { type ReactNode, useEffect, useRef, useState } from "react";
function cx(...classes: Array<string | false | null | undefined>) {
return classes.filter(Boolean).join(" ");
}
/** One part of the usage, such as input, output, or cache tokens. */
export interface UsageSegment {
label: string;
value: number;
}
export interface UsageMeterProps {
/** The plan or budget allowance. */
limit: number;
/** Amount used so far. Defaults to the sum of `segments`. */
used?: number;
/** Parts of the usage, drawn as adjacent pieces of the bar in decreasing shades. Up to four read well. */
segments?: UsageSegment[];
/** What is measured, e.g. "Tokens this month". */
label?: ReactNode;
/** Plan name shown beside the label in the card. */
plan?: ReactNode;
/** Word after amounts, e.g. "tokens" or "requests". Ignored for currency. */
unit?: string;
/** ISO 4217 code. Formats every amount as money. */
currency?: string;
/** Formats amounts yourself. Overrides `currency`. */
format?: (value: number) => string;
/** When the allowance resets. Shown as "Resets in 3 h". */
resetsAt?: Date | number | string;
/** Share of the limit (0 to 1) where the meter turns amber. @default 0.8 */
warnAt?: number;
/** inline is one quiet line for headers and settings rows; card adds the breakdown. @default "card" */
variant?: "inline" | "card";
/** A control in the card footer, such as an upgrade button. */
action?: ReactNode;
/** Replaces the footer's status sentence. */
message?: ReactNode;
className?: string;
}
type Level = "normal" | "warn" | "limit";
const ease = "ease-[cubic-bezier(0.23,1,0.32,1)]";
const DURATION = 520;
const shades: Record<Level, string[]> = {
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"],
warn: ["bg-amber-500", "bg-amber-500/65", "bg-amber-500/40", "bg-amber-500/25"],
limit: ["bg-red-500", "bg-red-500/65", "bg-red-500/40", "bg-red-500/25"],
};
const levelText: Record<Level, string> = {
normal: "text-zinc-950 dark:text-white",
warn: "text-amber-600 dark:text-amber-400",
limit: "text-red-600 dark:text-red-400",
};
const grouped = new Intl.NumberFormat("en");
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumSignificantDigits: 3 });
/** Exact below 100,000 (8,940), compact above (1.53M). */
export function formatUsage(value: number): string {
const rounded = Math.round(value);
return Math.abs(rounded) < 100_000 ? grouped.format(rounded) : compact.format(rounded);
}
/** "Resets in 42 min", "Resets in 3 h", "Resets in 5 days". */
export function formatReset(ms: number): string {
if (ms <= 60_000) return "Resets in under a minute";
const minutes = Math.round(ms / 60_000);
if (minutes < 60) return `Resets in ${minutes} min`;
const hours = Math.round(ms / 3_600_000);
if (hours < 48) return `Resets in ${hours} h`;
return `Resets in ${Math.round(ms / 86_400_000)} days`;
}
function usePrefersReducedMotion() {
const [reduce, setReduce] = useState(false);
useEffect(() => {
const query = window.matchMedia("(prefers-reduced-motion: reduce)");
setReduce(query.matches);
const onChange = () => setReduce(query.matches);
query.addEventListener("change", onChange);
return () => query.removeEventListener("change", onChange);
}, []);
return reduce;
}
/** Counts from the last shown value to `target` with a quint ease-out; jumps under reduced motion. */
function useCountTo(target: number, reduce: boolean) {
const [value, setValue] = useState(0);
const shown = useRef(0);
useEffect(() => {
if (reduce) {
shown.current = target;
setValue(target);
return;
}
const from = shown.current;
const start = performance.now();
let raf = 0;
const tick = (now: number) => {
const t = Math.min(1, (now - start) / DURATION);
const next = from + (target - from) * (1 - Math.pow(1 - t, 5));
shown.current = next;
setValue(next);
if (t < 1) raf = requestAnimationFrame(tick);
};
raf = requestAnimationFrame(tick);
return () => cancelAnimationFrame(raf);
}, [target, reduce]);
return value;
}
/** The reset sentence, computed after mount so server and client render the same markup. */
function useResetLabel(resetsAt: UsageMeterProps["resetsAt"]) {
const [now, setNow] = useState<number | null>(null);
useEffect(() => {
if (resetsAt == null) return;
setNow(Date.now());
const id = setInterval(() => setNow(Date.now()), 30_000);
return () => clearInterval(id);
}, [resetsAt]);
if (resetsAt == null || now == null) return null;
const at = new Date(resetsAt).getTime();
return Number.isNaN(at) ? null : formatReset(at - now);
}
/**
* Account or plan usage against an allowance: tokens, requests, or spend this period. A segmented
* bar shows what the usage is made of, the bar sweeps to its value as the numbers count up, and it
* turns amber at a threshold and red at the limit, with the time until it resets.
*/
export function UsageMeter({
limit,
used: usedProp,
segments = [],
label = "Usage",
plan,
unit,
currency,
format: formatProp,
resetsAt,
warnAt = 0.8,
variant = "card",
action,
message,
className,
}: UsageMeterProps) {
const used = Math.max(0, usedProp ?? segments.reduce((sum, segment) => sum + segment.value, 0));
const ratio = limit > 0 ? used / limit : 0;
const level: Level = ratio >= 1 ? "limit" : ratio >= warnAt ? "warn" : "normal";
const reduce = usePrefersReducedMotion();
const count = useCountTo(used, reduce);
const reset = useResetLabel(resetsAt);
const money = currency ? new Intl.NumberFormat("en", { style: "currency", currency, maximumFractionDigits: 2, minimumFractionDigits: 2 }) : null;
const format = formatProp ?? ((value: number) => (money ? money.format(value) : formatUsage(value)));
const suffix = unit && !money && !formatProp ? ` ${unit}` : "";
// The fill sweeps from empty on mount and between values after that, by clipping a full-width layer.
const [swept, setSwept] = useState(0);
useEffect(() => {
const raf = requestAnimationFrame(() => setSwept(Math.min(1, ratio)));
return () => cancelAnimationFrame(raf);
}, [ratio]);
const parts = segments.length ? segments : [{ label: typeof label === "string" ? label : "Used", value: used }];
const scaleBase = Math.max(limit, parts.reduce((sum, part) => sum + part.value, 0), 1);
let offset = 0;
const pieces = parts.map((part, index) => {
const left = offset;
const width = (Math.max(0, part.value) / scaleBase) * 100;
offset += width;
return { ...part, left, width, shade: shades[level][Math.min(index, 3)]! };
});
const percent = limit > 0 ? Math.round((count / limit) * 100) : 0;
const remaining = Math.max(0, limit - count);
const levelWord = level === "limit" ? ", limit reached" : level === "warn" ? ", nearing the limit" : "";
const exact = (value: number) => (money || formatProp ? format(value) : grouped.format(Math.round(value)));
const valueText = `${exact(used)} of ${exact(limit)}${suffix} used, ${Math.round(ratio * 100)}%${levelWord}${reset ? `. ${reset}` : ""}`;
const statusSentence =
message ??
(level === "limit" ? "Limit reached" : level === "warn" ? `${format(remaining)}${suffix} left, nearing your limit` : `${format(remaining)}${suffix} left`);
const bar = (
<Meter.Track
className={cx(
"relative overflow-hidden rounded-full bg-zinc-950/[0.06] dark:bg-white/[0.1]",
variant === "card" ? "h-2" : "h-1.5 w-20 shrink-0 sm:w-24",
)}
>
{variant === "card" && warnAt > 0 && warnAt < 1 ? (
<span aria-hidden="true" className="absolute inset-y-0 w-px bg-zinc-950/20 dark:bg-white/25" style={{ left: `${warnAt * 100}%` }} />
) : null}
<span
aria-hidden="true"
className={cx("absolute inset-0 transition-[clip-path] motion-reduce:transition-none", ease)}
style={{ clipPath: `inset(0 ${100 - swept * 100}% 0 0)`, transitionDuration: `${DURATION}ms` }}
>
{pieces.map((piece, index) => (
<span
key={`${piece.label}-${index}`}
className={cx("absolute inset-y-0 transition-colors duration-200 ease-out motion-reduce:transition-none", piece.shade)}
style={{
left: `${piece.left}%`,
width: index === pieces.length - 1 ? `${piece.width}%` : `max(0px, calc(${piece.width}% - 2px))`,
}}
/>
))}
</span>
</Meter.Track>
);
if (variant === "inline") {
return (
<Meter.Root
value={Math.min(used, limit)}
min={0}
max={limit}
getAriaValueText={() => valueText}
className={cx("inline-flex max-w-full flex-wrap items-center gap-x-2.5 gap-y-1 text-xs", className)}
>
<Meter.Label className="text-zinc-600 dark:text-zinc-400">{label}</Meter.Label>
{bar}
<span aria-hidden="true" className={cx("font-mono tabular-nums", levelText[level])}>
{percent}%
</span>
{level !== "normal" ? (
<span aria-hidden="true" className={levelText[level]}>
{level === "limit" ? "Limit reached" : "Nearing limit"}
</span>
) : null}
{reset ? (
<span aria-hidden="true" className="text-zinc-500">
{reset}
</span>
) : null}
</Meter.Root>
);
}
return (
<Meter.Root
value={Math.min(used, limit)}
min={0}
max={limit}
getAriaValueText={() => valueText}
className={cx(
"w-full max-w-sm rounded-xl border border-zinc-950/10 bg-white shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
"dark:border-white/10 dark:bg-black dark:shadow-[inset_0_1px_0_rgb(255_255_255/0.06)]",
className,
)}
>
<div className="p-4">
<div className="flex items-baseline justify-between gap-3">
<Meter.Label className="min-w-0 truncate text-sm font-semibold text-zinc-950 dark:text-white">{label}</Meter.Label>
{plan != null ? <span className="shrink-0 text-xs text-zinc-500">{plan}</span> : null}
</div>
<div aria-hidden="true" className="mt-3 flex items-baseline justify-between gap-3">
<p className="min-w-0 truncate text-sm text-zinc-500">
<span className="font-mono text-lg font-medium text-zinc-950 tabular-nums dark:text-white">{format(count)}</span>
<span className="font-mono tabular-nums"> / {format(limit)}</span>
{suffix}
</p>
<span className={cx("shrink-0 font-mono text-sm tabular-nums transition-colors duration-200 motion-reduce:transition-none", levelText[level])}>
{percent}%
</span>
</div>
<div className="mt-2.5">{bar}</div>
{segments.length > 1 ? (
<dl className="mt-3.5 grid gap-x-3 gap-y-2" style={{ gridTemplateColumns: `repeat(${Math.min(pieces.length, 3)}, minmax(0, 1fr))` }}>
{pieces.map((piece, index) => {
const share = used > 0 ? Math.round((segments[index]!.value / used) * 100) : 0;
return (
<div key={`${piece.label}-${index}`} className="min-w-0">
<dt className="flex items-center gap-1.5 text-xs text-zinc-500">
<span aria-hidden="true" className={cx("size-2 shrink-0 rounded-[2px] transition-colors duration-200 motion-reduce:transition-none", piece.shade)} />
<span className="truncate">{piece.label}</span>
</dt>
<dd className="mt-0.5 flex flex-wrap gap-x-1.5 font-mono text-xs text-zinc-950 tabular-nums dark:text-white">
<span>{format(used > 0 ? (segments[index]!.value * count) / used : 0)}</span>
<span className="text-zinc-500">{share}%</span>
</dd>
</div>
);
})}
</dl>
) : null}
</div>
<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]">
<div className="min-w-0">
<p className={cx(level === "normal" ? "text-zinc-600 dark:text-zinc-400" : levelText[level])}>{statusSentence}</p>
{reset ? <p className="mt-0.5 text-zinc-500">{reset}</p> : null}
</div>
{action != null ? <div className="shrink-0">{action}</div> : null}
</div>
</Meter.Root>
);
}