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
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.
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).
Bonus pricing, health status, and checkout
Pricing helper (quoteCredits)
| Output | Rule |
|---|---|
bonus | Highest tier in pricing.bonusTiers with tier.min ≤ credits; rounded to whole credits (round(credits × percent / 100)). |
total | credits + bonus added to the workspace balance on purchase. |
price | round(credits × pricing.unitPrice, 2) in pricing.currency. |
Balance health and burn estimate
| Metric | Calculation |
|---|---|
| Daily burn | Rounded mean of all completed days in usage (excludes the final partial day representing today). |
| Days left | floor(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.
| Argument | Type / default | Description |
|---|---|---|
defaultBalance | integerDefault: 840 | Starting balance in credits when balance is left uncontrolled; edits do not reset a mounted instance |
usage | CreditUsageDay[]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 |
packs | number[]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 |
pricing | CreditPricingDefault: {"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 |
range | RangeDefault: {"min":500,"max":30000,"step":500} | The custom amount slider range in credits |
defaultCredits | integer— | Amount selected on mount; defaults to the second pack (or the first), and a value equal to a pack selects that pack |
paymentMethods | CreditPaymentMethod[]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 |
thresholds | number[]Default: [500,1000,2500] | Choices for the auto top-up threshold; the balance reads as running low below the selected one |
defaultAutoTopup | CreditAutoTopupSettingsDefault: {"enabled":false,"threshold":1000} | Auto top-up settings on mount |
purchaseAction | string— | 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 |
locale | string— | Number, currency and date locale; omitted inherits en-US |
recipe | studio | softDefault: "studio" | Visual treatment; behavior is identical |
theme | CreditTopupThemeDefault: {} | Mode, accent and typed theme token overrides |
motion | none | subtle | expressiveDefault: "subtle" | Arc motion preset; reduced motion wins |
motionOptions | CreditTopupMotionOptions— | Optional overrides for the balance roll, swaps and glides; durations are milliseconds |
dir | ltr | rtl— | Reading direction; omitted inherits |
CreditUsageDayaccepts{ date: 'YYYY-MM-DD', credits }, ordered oldest first with today last (2–31entries).CreditPricingaccepts{ unitPrice, currency, bonusTiers: { min, percent }[] }, wherecurrencyis a 3-letter ISO 4217 code and bonus tier minimums are unique.CreditPaymentMethodaccepts{ id, brand: 'visa' | 'mastercard', last4, expires: 'MM/YYYY' }. Payment method IDs,packs, andthresholdsmust each be unique, andrange.stepmust be at least1.
React integration
| Prop | Purpose |
|---|---|
balance | Controlled 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. |
preset | Application defaults overridden by explicit instance arguments. |
tokens | CSS variables applied after the typed theme, forwarded to the root card and composed Button, Switch, and RangeInput children. |
ref, className, style | Applied to the root <section> element. |
| Native attributes | id, aria-*, data-*, and remaining <section> props forwarded to the root element. |
Keyboard & accessibility
| Key | Action |
|---|---|
Tab | Moves across preset packs, custom slider, auto top-up switch, thresholds, Change, and Buy credits. |
ArrowLeft / ArrowRight | Moves between packs or enabled threshold chips (respects RTL) and selects as it goes. |
Home / End | Jumps to the first or last pack or threshold chip. |
Arrow / PageUp / PageDown | Adjusts the custom amount slider by range.step or larger increments. |
Space / Enter | Toggles Auto top-up, cycles the saved card, or purchases credits. |
- Preset packs and threshold pills implement WAI-ARIA
role="radiogroup"with rovingtabIndex; each pack'saria-labelreads the credit count, formatted price, and bonus percentage. - Every
OdometerNumberandRollingNumber(balance, total credits, bonus credits, and price) keeps its animated digitsaria-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
28remand tighten padding below26rem. 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 group | CSS 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": []
}