UI

Credit top-up

Prepaid AI credit purchase card with an odometer balance, 14-day daily usage bar chart and days-left estimate, preset packs with volume bonus badges, synced custom amount slider, auto top-up threshold controls, saved card switcher, and fixed-height checkout status.

import { CreditTopup } from '@uthereal/ui/credit-topup'

Credit topup playground

Credit balanceRunning low
840credits
About 2 days left at 387 a day
Add credits$10 per 1,000
Auto top-upRefills with your selected amount
Refill when below
Visa ending 4242Expires 08/2028
5,500 creditsIncludes 500 bonus
$50.00
Simulated checkout. Credits never expire.
Loading interactive preview…

Overview

CreditTopup provides a fixed-height card for buying prepaid AI credits or usage tokens. The header displays the current credit balance, a health indicator (Running low below the selected auto top-up threshold, Healthy at or above it), a days-left estimate derived from completed usage days, and a 14-day interactive bar chart highlighting today in the accent color with a hover readout for each day.

Below the header, buyers select one of up to three preset packs (with volume bonus badges computed from pricing.bonusTiers) or drag the synced custom amount slider (RangeInput). An Auto top-up section toggles automatic refills and threshold pills, a payment row cycles through saved Visa or Mastercard cards via Change, and pressing Buy credits runs the charge and rolls the new balance up in odometer style without resizing the card.

Use CreditTopup on usage-based billing pages, out-of-credits dialogs, or top-up drawers. For per-seat team billing and proration, use Seat manager. For a full subscription signup with plan cards and payment entry, use Live checkout.

Usage

'use client'
import { CreditTopup, quoteCredits } from '@uthereal/ui/credit-topup'

export function WorkspaceCredits({
  balance,
  usage,
  cards,
}: {
  balance: number
  usage: { date: string; credits: number }[]
  cards: {
    id: string
    brand: 'visa' | 'mastercard'
    last4: string
    expires: string
  }[]
}) {
  return (
    <CreditTopup
      balance={balance}
      usage={usage}
      paymentMethods={cards}
      onPurchase={async (order, signal) => {
        const res = await fetch('/api/credits/purchase', {
          method: 'POST',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify(order),
          signal,
        })
        if (!res.ok) {
          throw new Error('Card declined. Try again or change card.')
        }
      }}
      onAutoTopupChange={(settings) => {
        void fetch('/api/credits/auto-topup', {
          method: 'PUT',
          headers: { 'content-type': 'application/json' },
          body: JSON.stringify(settings),
        })
      }}
    />
  )
}

Omit balance and onPurchase to run the built-in local simulation (nothing leaves the browser: pressing Buy credits simulates a 1.2s charge and adds the purchased total plus bonus to the local balance). Import quoteCredits on the server with the same pricing object so your backend never trusts a client total.

Examples

Low balance with auto top-up enabled

Start with a low defaultBalance (420) and defaultAutoTopup={{ enabled: true, threshold: 2500 }} to activate the threshold selector immediately, flag the urgent < 1 day running-low warning, and pre-select the top +15% bonus pack.

Credit balanceRunning low
420credits
About 1 day left at 387 a day
Add credits$10 per 1,000
Auto top-upRefills with your selected amount
Refill when below
Visa ending 4242Expires 08/2028
23,000 creditsIncludes 3,000 bonus
$200.00
Simulated checkout. Credits never expire.

Healthy EUR balance with custom pricing and single card

Configure a healthy balance (14,500), EUR pricing with custom bonus tiers and slider bounds, locale="de-DE", and a single saved Mastercard (automatically hiding the Change card button).

Credit balanceHealthy
14.500credits
About 37 days left at 387 a day
Add credits9 € per 1.000
Auto top-upRefills with your selected amount
Refill when below
Mastercard ending 9012Expires 09/2029
11.000 creditsIncludes 1.000 bonus
90,00 €
Simulated checkout. Credits never expire.

Bonus pricing, health status, and checkout

Pricing helper (quoteCredits)

OutputRule
bonusHighest tier in pricing.bonusTiers with tier.min ≤ credits; rounded to whole credits (round(credits × percent / 100)).
totalcredits + bonus added to the workspace balance on purchase.
priceround(credits × pricing.unitPrice, 2) in pricing.currency.

Balance health and burn estimate

MetricCalculation
Daily burnRounded mean of all completed days in usage (excludes the final partial day representing today).
Days leftfloor(balance / average); displays "Less than a day left" below 1.
Health"Running low" (triangle-alert) when balance < auto.threshold; "Healthy" (circle-check) otherwise.

API reference

These serializable arguments and defaults come directly from the component schema.

ArgumentType / defaultDescription
defaultBalanceintegerDefault: 840Starting balance in credits when balance is left uncontrolled; edits do not reset a mounted instance
usageCreditUsageDay[]Default: [{"date":"2026-10-14","credits":356},{"date":"2026-10-15","credits":402},{"date":"2026-10-16","credits":388},{"date":"2026-10-17","credits":441},{"date":"2026-10-18","credits":297},{"date":"2026-10-19","credits":214},{"date":"2026-10-20","credits":198},{"date":"2026-10-21","credits":423},{"date":"2026-10-22","credits":468},{"date":"2026-10-23","credits":437},{"date":"2026-10-24","credits":489},{"date":"2026-10-25","credits":452},{"date":"2026-10-26","credits":471},{"date":"2026-10-27","credits":318}]Daily usage, oldest first; the last day is today and drives the bar chart, its hover readout and the days-left estimate
packsnumber[]Default: [1000,5000,20000]Preset pack sizes in credits, shown as a radio group with a gliding selection ring; keep it to three for the layout
pricingCreditPricingDefault: {"unitPrice":0.01,"currency":"USD","bonusTiers":[{"min":5000,"percent":10},{"min":20000,"percent":15}]}Pricing: unitPrice per credit, ISO currency and bonusTiers; every price, bonus badge, total and per-1,000 rate derives from it
rangeRangeDefault: {"min":500,"max":30000,"step":500}The custom amount slider range in credits
defaultCreditsinteger—Amount selected on mount; defaults to the second pack (or the first), and a value equal to a pack selects that pack
paymentMethodsCreditPaymentMethod[]Default: [{"id":"card_visa_4242","brand":"visa","last4":"4242","expires":"08/2028"},{"id":"card_mc_5454","brand":"mastercard","last4":"5454","expires":"03/2029"}]Saved cards; Change cycles through them and onPaymentMethodChange reports each choice
thresholdsnumber[]Default: [500,1000,2500]Choices for the auto top-up threshold; the balance reads as running low below the selected one
defaultAutoTopupCreditAutoTopupSettingsDefault: {"enabled":false,"threshold":1000}Auto top-up settings on mount
purchaseActionstring—Registered host action requested when Buy credits is pressed; the charge itself runs through the React-only onPurchase callback, or a local simulation without it
localestring—Number, currency and date locale; omitted inherits en-US
recipestudio | softDefault: "studio"Visual treatment; behavior is identical
themeCreditTopupThemeDefault: {}Mode, accent and typed theme token overrides
motionnone | subtle | expressiveDefault: "subtle"Arc motion preset; reduced motion wins
motionOptionsCreditTopupMotionOptions—Optional overrides for the balance roll, swaps and glides; durations are milliseconds
dirltr | rtl—Reading direction; omitted inherits
  • CreditUsageDay accepts { date: 'YYYY-MM-DD', credits }, ordered oldest first with today last (2–31 entries).
  • CreditPricing accepts { unitPrice, currency, bonusTiers: { min, percent }[] }, where currency is a 3-letter ISO 4217 code and bonus tier minimums are unique.
  • CreditPaymentMethod accepts { id, brand: 'visa' | 'mastercard', last4, expires: 'MM/YYYY' }. Payment method IDs, packs, and thresholds must each be unique, and range.step must be at least 1.

React integration

PropPurpose
balanceControlled credit balance. Any update rolls the odometer numerals live; omit for uncontrolled local state seeded by defaultBalance.
onPurchase(order, signal)Charges CreditOrder ({ credits, bonus, total, price, currency, paymentMethodId }). Reject with an Error to show Try again.
onPurchased(order, bal)Called after a successful purchase with the completed order and resulting balance.
onAutoTopupChange(next)Called when the switch or threshold changes, with { enabled, threshold, credits } (credits includes bonus).
onPaymentMethodChange(id)Called when Change cycles to another saved card.
onAction(action)Called with purchaseAction when Buy credits is pressed.
presetApplication defaults overridden by explicit instance arguments.
tokensCSS variables applied after the typed theme, forwarded to the root card and composed Button, Switch, and RangeInput children.
ref, className, styleApplied to the root <section> element.
Native attributesid, aria-*, data-*, and remaining <section> props forwarded to the root element.

Keyboard & accessibility

KeyAction
TabMoves across preset packs, custom slider, auto top-up switch, thresholds, Change, and Buy credits.
ArrowLeft / ArrowRightMoves between packs or enabled threshold chips (respects RTL) and selects as it goes.
Home / EndJumps to the first or last pack or threshold chip.
Arrow / PageUp / PageDownAdjusts the custom amount slider by range.step or larger increments.
Space / EnterToggles Auto top-up, cycles the saved card, or purchases credits.
  • Preset packs and threshold pills implement WAI-ARIA role="radiogroup" with roving tabIndex; each pack's aria-label reads the credit count, formatted price, and bonus percentage.
  • Every OdometerNumber and RollingNumber (balance, total credits, bonus credits, and price) keeps its animated digits aria-hidden="true" beside a visually hidden plain text value.
  • Balance health combines an icon and text label rather than color alone, and the usage bar chart exposes role="img" with a spoken summary of the window length and average daily burn.
  • A pre-mounted polite role="status" region announces card charges, added credits (noting "Nothing was charged." when simulated), auto top-up updates, and errors without shifting card height.
  • Container queries stack the usage chart beneath the balance below 28rem and tighten padding below 26rem. Logical CSS properties mirror cleanly in RTL (dir="rtl"), and @media (forced-colors: active) maps rings, pills, bars, badges, and focus outlines to system colors.

Motion & theming

After a purchase or controlled balance change, the balance rolls odometer-style (OdometerNumber), while total credits, bonus credits, and price roll smoothly as the slider moves (RollingNumber). The pack selection ring and threshold pill glide on shared layoutId morph springs, and health, days-left, saved card, and status lines crossfade in fixed grid slots so the card height never changes.

Under prefers-reduced-motion: reduce, odometer rolls, digit rolls, layoutId glides, and press scales turn off while swaps remain short 120ms opacity crossfades. Setting motion="none" makes every transition immediate (0ms).

theme accepts mode, accent, and typed tokens across these groups:

Token groupCSS custom properties
core--ui-surface, --ui-surface-raised, --ui-text, --ui-text-secondary, --ui-muted, --ui-border, --ui-highlight, --ui-accent, --ui-accent-foreground, --ui-danger, --ui-focus-ring, --ui-radius, --ui-border-width, --ui-shadow, --ui-disabled-opacity, --ui-font, --ui-font-size, --ui-font-weight
extended--ui-surface-sunken, --ui-border-strong, --ui-border-subtle, --ui-track, --ui-info, --ui-success, --ui-warning, --ui-tone-foreground, --ui-overlay, --ui-tint-strength
shape--ui-radius-sm, --ui-popup-radius, --ui-surface-radius
accentTones--ui-accent-strong, --ui-accent-subtle
control--ui-control-height, --ui-control-padding-x, --ui-control-gap, --ui-icon-size
type--ui-font-mono, --ui-font-display

An application-wide UtherealProvider supplies defaults.

Composition

In an agent composition, CreditTopup is a leaf block. Provide literal validated usage, up to three unique packs, pricing with unitPrice and currency, unique payment method IDs, and wire purchaseAction to a registered host action. See Building with agents.

{
  "type": "CreditTopup",
  "props": {
    "defaultBalance": 840,
    "packs": [1000, 5000, 20000],
    "defaultAutoTopup": {
      "enabled": true,
      "threshold": 1000
    },
    "purchaseAction": "purchase_ai_credits"
  },
  "children": []
}

On this page