# Usage meter

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.

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

## Install

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

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

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

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

## Preview

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

Knobs:

- `session`: `ok`, `out-by`, `limit`, `just-reset`

Signature: When the pace would run out first, the bar turns orange and the phrase changes from "Resets 4:14 pm" to "Out by 2:40 pm", in your own time.

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/usage-meter.tsx, quiet https://pixilui.com/r/standalone/usage-meter.quiet.tsx.

## Code

`components/pixilui/usage-meter.tsx`

```tsx
"use client";

/*
  The usage meter, locked 27 Nov 2026 (design/explorations/components/locked/usage-meter): how much of a usage
  window is spent and when it resets, in the viewer's own time. Each window is the locked meter bar
  (../meter/meter); this component decides what the bar says, as the locked script does:

  State     limit at 100%; warn (orange) when the pace reaches 100% before the reset; ok otherwise.
  Phrase    "Resets 4:14 pm" (or "Resets Tue 6:30 pm" more than a day away); "Out by 2:40 pm" when the pace
            runs out first; "Resets in 42:10", counting down live, at the limit; "Just reset" after a reset.
  Time      printed in the viewer's time zone, so it is read only in the browser: the first render (and the
            server's) shows the bar without its phrase, which arrives once the clock is known. Pass now to
            fix the clock (tests, a frozen preview).
  Sentence  the full sentence is the accessible name and the tooltip.
*/

import { forwardRef, useSyncExternalStore, type ComponentPropsWithoutRef } from "react";
import { cn } from "./lib/utils";
import { Meter, type MeterState } from "./meter";

/** A missing list prop (plain JavaScript, a guessing agent): one stable empty list, so nothing throws or re-renders. */
const NONE: never[] = [];

export type UsageMeterWords = {
  /** The phrase while under the limit: when it resets ("4:14 pm", or "Tue 6:30 pm" more than a day away). */
  resetsAt: (time: string) => string;
  /** The phrase when the pace runs out before the reset. */
  outBy: (time: string) => string;
  /** The phrase at the limit, with the countdown ("42:10"). */
  resetsIn: (countdown: string) => string;
  /** The phrase after a reset. */
  justReset: string;
  /** The sentence under the limit. */
  sentence: (label: string, used: number, resetTime: string) => string;
  /** The sentence when the pace runs out first. */
  sentenceOutBy: (label: string, used: number, outTime: string, resetTime: string) => string;
  /** The sentence at the limit. */
  sentenceLimit: (label: string, countdown: string, resetTime: string) => string;
  /** The sentence after a reset. */
  sentenceReset: (label: string) => string;
  /** The word after the percent when there is no reset time. */
  used: string;
};

export const usageMeterWords: UsageMeterWords = {
  resetsAt: (t) => `Resets ${t}`,
  outBy: (t) => `Out by ${t}`,
  resetsIn: (c) => `Resets in ${c}`,
  justReset: "Just reset",
  sentence: (label, used, reset) => `${label}: ${used}% used. Resets at ${reset}.`,
  sentenceOutBy: (label, used, out, reset) => `${label}: ${used}% used. At this pace you run out at ${out}, before the reset at ${reset}.`,
  sentenceLimit: (label, cd, reset) => `${label}: limit reached. Resets in ${cd}, at ${reset}.`,
  sentenceReset: (label) => `${label}: just reset.`,
  used: "used",
};

export type UsageMeterWindowProps = Omit<ComponentPropsWithoutRef<"div">, "children"> & {
  /** The window's name: "5-hour limit", "Weekly · all models". */
  label: string;
  /** The used share, 0 to 100. */
  used: number;
  /** Where the current rate lands by the reset, as a share. It decides the warning; it is never drawn. Defaults to used. */
  pace?: number;
  /** When the window resets, as epoch ms. Without it the bar shows no phrase. */
  resetAt?: number;
  /** The window just reset: the fill drains to zero and the phrase says so. */
  reset?: boolean;
  /** A fixed clock (epoch ms), for tests and frozen previews. Without it the meter reads the browser's clock after mount. */
  now?: number;
  /** card: the line over a 6px bar. inline: label, a 64px bar and the percent. */
  variant?: "card" | "inline";
  /** The locale times print in; the time zone is always the viewer's. */
  locale?: string;
  /** Every word the meter says. */
  words?: Partial<UsageMeterWords>;
};

/* ------------------------------------------------------------------ the clock */

/** A shared clock that ticks while a meter watches it; null until the first subscriber (so never on the server). */
function clock(interval: number) {
  let now: number | null = null;
  let timer: ReturnType<typeof setInterval> | undefined;
  const subs = new Set<() => void>();
  return {
    subscribe(cb: () => void) {
      subs.add(cb);
      if (!timer) {
        now = Date.now();
        timer = setInterval(() => {
          now = Date.now();
          subs.forEach((f) => f());
        }, interval);
      }
      return () => {
        subs.delete(cb);
        if (!subs.size) {
          clearInterval(timer);
          timer = undefined;
        }
      };
    },
    get: () => now,
  };
}
// a countdown ticks four times a second (the reference page's 250ms); a reset time only needs the minute
const fast = clock(250);
const slow = clock(15_000);
const never = () => () => {};
const none = () => null;

function useNow(fixed: number | undefined, counting: boolean): number | null {
  const c = counting ? fast : slow;
  const live = useSyncExternalStore(fixed === undefined ? c.subscribe : never, fixed === undefined ? c.get : none, none);
  return fixed ?? live;
}

/* ------------------------------------------------------------------ phrases */

const DAY = 24 * 3600e3;
const countdown = (ms: number) => {
  const s = Math.max(0, Math.ceil(ms / 1000));
  const h = Math.floor(s / 3600);
  const m = Math.floor((s % 3600) / 60);
  const ss = String(s % 60).padStart(2, "0");
  return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
};
const stateOf = (used: number, pace: number): MeterState => (used >= 100 ? "limit" : pace >= 100 ? "warn" : "ok");

/** One usage window: its share, its phrase (when it resets, or when the pace runs out first) and its sentence. */
export const UsageMeterWindow = forwardRef<HTMLDivElement, UsageMeterWindowProps>(function UsageMeterWindow(
  { label, used, pace = used, resetAt, reset = false, now: fixed, variant = "card", locale = "en-US", words: given, ...props },
  ref,
) {
  const words = { ...usageMeterWords, ...given };
  const limit = used >= 100;
  const now = useNow(resetAt === undefined ? 0 : fixed, limit && !reset);
  const fmt = (t: number, o: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, o).format(t).replace(" AM", " am").replace(" PM", " pm");
  const time = (t: number) => fmt(t, { hour: "numeric", minute: "2-digit" });
  const n = Math.round(used);

  let note: string | undefined;
  let noteKey: string | undefined;
  let description: string | undefined;
  let title: string | undefined;
  if (resetAt !== undefined && now !== null) {
    if (reset) {
      note = words.justReset;
      description = words.sentenceReset(label);
    } else if (limit) {
      note = words.resetsIn(countdown(resetAt - now));
      noteKey = "countdown"; // a tick is not a new meaning
      description = words.sentenceLimit(label, countdown(resetAt - now), time(resetAt));
    } else if (pace >= 100 && pace > used) {
      const out = now + ((resetAt - now) * (100 - used)) / (pace - used);
      note = words.outBy(time(out));
      description = words.sentenceOutBy(label, n, time(out), time(resetAt));
    } else {
      note = words.resetsAt(resetAt - now > DAY ? `${fmt(resetAt, { weekday: "short" })} ${time(resetAt)}` : time(resetAt));
      description = words.sentence(label, n, time(resetAt));
    }
    title = description;
  }
  return (
    <Meter
      ref={ref}
      label={label}
      value={used}
      state={reset ? "ok" : stateOf(used, pace)}
      draining={reset}
      note={note}
      noteKey={noteKey}
      variant={variant}
      description={description}
      usedLabel={words.used}
      title={title}
      {...props}
    />
  );
});

export type UsageMeterProps = Omit<ComponentPropsWithoutRef<"div">, "children"> & {
  /** The windows, in order: the five-hour session first, then the weekly ones. */
  windows: (Omit<UsageMeterWindowProps, "now" | "locale" | "words" | "variant"> & { id: string })[];
  /** A fixed clock (epoch ms) for every window. */
  now?: number;
  /** The locale times print in. */
  locale?: string;
  /** Every word the meters say. */
  words?: Partial<UsageMeterWords>;
};

/** Usage windows together, the five-hour session and the weekly ones, each saying when it resets in your time. */
export const UsageMeter = forwardRef<HTMLDivElement, UsageMeterProps>(function UsageMeter({ windows = NONE, now, locale, words, className, ...props }, ref) {
  return (
    <div ref={ref} className={cn("grid gap-4.5 font-body", className)} {...props}>
      {windows.map(({ id, ...w }) => (
        <UsageMeterWindow key={id} {...w} now={now} locale={locale} words={words} />
      ))}
    </div>
  );
});
```

## Usage

When to use:

- Plan limits on a rolling window: the five-hour session and the weekly limits.
- A compact session meter in a composer footer (variant="inline").

When not to use:

- A share with no clock: use Meter.
- A bill in money: write the amount.

```tsx
import { UsageMeter } from "@/components/pixilui/usage-meter";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  session: ["ok", "out-by", "limit", "just-reset"],
} as const;

const H = 3600e3;
const shapes = {
  ok: { used: 38, pace: 64, reset: false },
  "out-by": { used: 84, pace: 112, reset: false },
  limit: { used: 100, pace: 100, reset: false },
  "just-reset": { used: 0, pace: 0, reset: true },
};

// a fixed moment, so the preview and its snapshots hold still; the times still print in the viewer's own time zone
const NOW = Date.UTC(2026, 10, 27, 14, 0, 0);

/** The five-hour session and two weekly windows, reset times in your own time. */
export default function UsageMeterDemo({ session = "ok" }: KnobValues<typeof knobs>) {
  const s = shapes[session];
  return (
    <div className="w-full max-w-sm">
      <UsageMeter
        now={NOW}
        windows={[
          { id: "session", label: "5-hour limit", ...s, resetAt: NOW + (session === "limit" ? 0.7 : 2.25) * H },
          { id: "weekly", label: "Weekly · all models", used: 43, pace: 70, resetAt: NOW + 100.5 * H },
          { id: "opus", label: "Weekly · Opus", used: 24, pace: 44, resetAt: NOW + 100.5 * H },
        ]}
      />
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `windows` (required) | `(Omit<UsageMeterWindowProps, "now" \| "locale" \| "words" \| "variant"> & { id: string })[]` | `NONE` | The windows, in order: the five-hour session first, then the weekly ones. |
| `now` | `number` |  | A fixed clock (epoch ms) for every window. |
| `locale` | `string` |  | The locale times print in. |
| `words` | `Partial<UsageMeterWords>` |  | Every word the meters say. |

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

## Keyboard

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

## Accessibility

- Each window is a meter named by its whole sentence: "5-hour limit: 84% used. At this pace you run out at 2:40 pm, before the reset at 4:14 pm."
- Times print in the viewer's own time zone; the locale is a prop.

## Motion

- The fill follows the share; at a reset it drains back to zero, slower.
- The phrase cross-fades when its meaning changes (resets, out by, resets in, just reset); the countdown ticks in place.
- Reduced motion: instant.

## Responsive

- Windows stack in a grid; each fills its width.

## Performance

- One shared clock for every meter on the page, ticking only while one watches it: four times a second during a countdown, else every 15 seconds. None on the server.

## Notes for AI

- <UsageMeter windows={[{ id: "session", label: "5-hour limit", used: 84, pace: 112, resetAt }]} /> where pace is where the share will be at the reset at the current rate.
- resetAt is epoch ms; pass now to fix the clock (tests, screenshots); reset marks a window that just reset.
- words replaces every phrase and sentence, so the meter translates.

## Related

- [Meter](https://pixilui.com/components/meter/markdown): 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.
- [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.
