# Meter

A value against its limit: one line with its label, a short phrase and the percent over a thin bar that turns orange when the pace runs out first and red at the limit.

Tier: free. Type: component. Category: feedback. Tags: tokens, billing.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/meter.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/meter.tsx`.

## Preview

Live preview: https://pixilui.com/components/meter

Knobs:

- `state`: `ok`, `warn`, `limit`
- `variant`: `card`, `inline`

Signature: When a phrase changes meaning it cross-fades, but a countdown that only ticks changes in place, so the line never flickers.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/meter.tsx, quiet https://pixilui.com/r/standalone/meter.quiet.tsx.

## Code

`components/pixilui/meter.tsx`

```tsx
"use client";

/*
  The meter bar, locked 27 Nov 2026 with the usage meter (design/explorations/components/locked/usage-meter):
  one line (label, phrase, percent) over a thin bar. Its look and motion are foundation.css section 8
  (.pixilui-usage-meter); this component writes the locked markup and plays a report the way the locked
  script does:

  Report    the fill eases to the new share (520ms on the out curve) and the percent counts along with it
            (a quartic slow-down, the same time). A drain (draining) is slower, 600ms on the in-out curve.
  State     ok, warn and limit change the fill and the phrase's color in 150ms.
  Phrase    a new meaning leaves up and out (120ms) while the new one rises in from a blur (200ms); the same
            meaning with new words (a countdown tick) changes in place.
  Reduced   the fill and the percent jump, the phrase changes at once.
*/

import { forwardRef, useCallback, useLayoutEffect, useRef, useState, type ComponentPropsWithoutRef, type CSSProperties } from "react";
import { cn } from "./lib/utils";
import { prefersReducedMotion } from "./lib/motion/reduced-motion";

export type MeterState = "ok" | "warn" | "limit";

export type MeterProps = Omit<ComponentPropsWithoutRef<"div">, "children"> & {
  /** The window's name, such as "5-hour limit". It truncates when narrow. */
  label: string;
  /** The used share, 0 to 100. The fill stops at 100; the percent shows the rounded value. */
  value: number;
  /** ok (the run hue), warn (orange: the pace runs out first) or limit (red, full). */
  state?: MeterState;
  /** One short phrase before the percent, such as "Resets 4:14 pm" or "Out by 2:40 pm". Not shown inline. */
  note?: string;
  /**
   * What the phrase means. A new meaning cross-fades; the same meaning with new words changes in place (a
   * countdown tick). Defaults to the phrase itself.
   */
  noteKey?: string;
  /** card: the line over a 6px bar. inline: label, a 64px bar and the percent, for status bars and composer footers. */
  variant?: "card" | "inline";
  /** The share is draining back to zero (a reset): slower, on the in-out curve. */
  draining?: boolean;
  /** The accessible name: the full sentence. Defaults to "<label>, <n>% <usedLabel>". */
  description?: string;
  /** The word after the percent in the default accessible name. */
  usedLabel?: string;
};

type Note = { id: number; key: string; text: string; phase?: "in" | "out" };

/** A value against its limit: one line (label, phrase, percent) over a thin bar in the state's hue. */
export const Meter = forwardRef<HTMLDivElement, MeterProps>(function Meter(
  { label, value, state = "ok", note, noteKey, variant = "card", draining = false, description, usedLabel = "used", className, style, ...props },
  forwarded,
) {
  const ref = useRef<HTMLDivElement | null>(null);
  const valueRef = useRef<HTMLSpanElement | null>(null);
  const setRef = useCallback(
    (el: HTMLDivElement | null) => {
      ref.current = el;
      if (typeof forwarded === "function") forwarded(el);
      else if (forwarded) forwarded.current = el;
    },
    [forwarded],
  );
  const percent = Math.round(value);

  // the phrase: a new meaning swaps (the old one leaves over the new), the same meaning changes in place
  const [notes, setNotes] = useState<{ list: Note[]; next: number }>(() => ({ list: note === undefined ? [] : [{ id: 0, key: noteKey ?? note, text: note }], next: 1 }));
  const current = notes.list.find((n) => n.phase !== "out");
  if (note !== undefined && current?.text !== note) {
    const key = noteKey ?? note;
    if (current && current.key === key) setNotes({ ...notes, list: notes.list.map((n) => (n === current ? { ...n, text: note } : n)) });
    else {
      const leaving = current && !prefersReducedMotion() ? [{ ...current, phase: "out" as const }] : [];
      const kept = notes.list.filter((n) => n.phase === "out" && !prefersReducedMotion());
      setNotes({ list: [...kept, ...leaving, { id: notes.next, key, text: note, phase: current ? "in" : undefined }], next: notes.next + 1 });
    }
  }
  const drop = (id: number) => setNotes((s) => ({ ...s, list: s.list.filter((n) => n.id !== id) }));

  // the percent counts with the fill, over the same time (the locked count()); React writes the first value only
  const [first] = useState(percent);
  const shown = useRef(percent);
  useLayoutEffect(() => {
    const el = ref.current;
    const v = valueRef.current;
    if (!el || !v) return;
    const from = shown.current;
    shown.current = percent;
    const paint = (n: number) => {
      v.textContent = `${n}%`;
    };
    if (from === percent || prefersReducedMotion()) return paint(percent);
    const ms = parseFloat(getComputedStyle(el).getPropertyValue(draining ? "--pixilui-meter-drain-time" : "--pixilui-meter-fill-time"));
    if (!ms) return paint(percent);
    const t0 = performance.now();
    const ease = (k: number) => 1 - Math.pow(1 - k, 4);
    let raf = 0;
    const step = (now: number) => {
      const k = Math.min(1, (now - t0) / ms);
      paint(Math.round(from + (percent - from) * ease(k)));
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [percent, draining]);

  return (
    <div
      ref={setRef}
      className={cn("pixilui-usage-meter font-body", className)}
      data-variant={variant === "inline" ? "inline" : undefined}
      data-state={state}
      data-draining={draining ? "" : undefined}
      role="meter"
      aria-valuemin={0}
      aria-valuemax={100}
      aria-valuenow={percent}
      aria-label={description ?? `${label}, ${percent}% ${usedLabel}`}
      style={{ "--pixilui-usage-meter-value": Math.min(100, value), ...style } as CSSProperties}
      {...props}
    >
      <div className="pixilui-usage-meter-head">
        <span className="pixilui-usage-meter-label">{label}</span>
        <span className="pixilui-usage-meter-note">
          {notes.list.map((n) => (
            <span key={n.id} data-in={n.phase === "in" ? "" : undefined} data-out={n.phase === "out" ? "" : undefined} onAnimationEnd={n.phase === "out" ? () => drop(n.id) : undefined}>
              {n.text}
            </span>
          ))}
        </span>
        <span ref={valueRef} className="pixilui-usage-meter-value">{`${first}%`}</span>
      </div>
      <div className="pixilui-usage-meter-bar">
        <span className="pixilui-usage-meter-fill" />
      </div>
    </div>
  );
});
```

## Usage

When to use:

- Context used in a conversation, seats on a plan, storage, any share of a limit.
- A compact share in a status bar or a composer footer (variant="inline").

When not to use:

- Usage windows that reset on a clock: use Usage meter, which writes the phrases for you.
- Progress of a task toward done: use a progress bar or the run's status.

```tsx
import { Meter, type MeterState } from "@/components/pixilui/meter";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  state: ["ok", "warn", "limit"],
  variant: ["card", "inline"],
} as const;

const values: Record<MeterState, number> = { ok: 41, warn: 88, limit: 100 };
const notes: Record<MeterState, string> = { ok: "118k of 200k tokens", warn: "24k tokens left", limit: "Start a new chat" };

/** Context used in a conversation, in each state. */
export default function MeterDemo({ state = "ok", variant = "card" }: KnobValues<typeof knobs>) {
  return (
    <div className="w-full max-w-sm">
      <Meter label="Context" value={values[state]} state={state} note={notes[state]} variant={variant} />
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  | The window's name, such as "5-hour limit". It truncates when narrow. |
| `value` (required) | `number` |  | The used share, 0 to 100. The fill stops at 100; the percent shows the rounded value. |
| `state` | `"ok" \| "warn" \| "limit"` | `"ok"` | ok (the run hue), warn (orange: the pace runs out first) or limit (red, full). |
| `note` | `string` |  | One short phrase before the percent, such as "Resets 4:14 pm" or "Out by 2:40 pm". Not shown inline. |
| `noteKey` | `string` |  | What the phrase means. A new meaning cross-fades; the same meaning with new words changes in place (a countdown tick). Defaults to the phrase itself. |
| `variant` | `"card" \| "inline"` | `"card"` | card: the line over a 6px bar. inline: label, a 64px bar and the percent, for status bars and composer footers. |
| `draining` | `boolean` | `false` | The share is draining back to zero (a reset): slower, on the in-out curve. |
| `description` | `string` |  | The accessible name: the full sentence. Defaults to "<label>, <n>% <usedLabel>". |
| `usedLabel` | `string` | `"used"` | The word after the percent in the default accessible name. |

Also accepts every native `<div>` attribute, and a ref to it.

## Keyboard

- `Tab`: Never takes focus: it reports, it is not a control.

## Accessibility

- A meter named by its whole sentence (description), so the share is never color alone.
- The phrase changes are visible text; put a live region on the place that should announce them.

## Motion

- The fill follows the value on the out curve; draining back to zero after a reset is slower, on the in-out curve.
- A phrase with a new meaning cross-fades (the system's swap); the same meaning with new words, like a countdown tick, changes in place.
- Reduced motion: instant.

## Responsive

- Fills its container; the label truncates first, the phrase and percent stay whole.

## Performance

- One fill transition and at most two phrases at a time.

## Notes for AI

- <Meter label="Context" value={41} variant="inline" /> or <Meter label="Seats" value={92} state="warn" note="12 left" />.
- state: ok (the run hue), warn (orange) or limit (red). noteKey groups phrases that mean the same thing so they change in place.
- Every word is a prop: label, note, description, usedLabel.

## Related

- [Usage meter](https://pixilui.com/components/usage-meter/markdown): How much of a usage window is spent and when it resets, in the viewer's own time, turning orange with "Out by 2:40 pm" when the pace would run out before the reset.
- [Status dot](https://pixilui.com/components/status-dot/markdown): The one mark for a run's state, queued, running, waiting on you, done, failed or stopped, at four sizes, so a plan, a log and an inbox read the same.
