# Billing Toggle

> Switches monthly and annual billing with a sliding thumb, savings badge, and animated price.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/billing-toggle`
- File: `src/components/haze/ui/billing-toggle.astro`
- npm dependencies: none
- Registry dependencies: @haze/animated-number, @haze/utils
- Docs page: https://hazeui.com/ui/billing-toggle

## Use when
- Show two billing cycles for one plan.
- Put the annual savings alongside the billing choice.

## Avoid when
- The choices change views or filters instead of a price.

## Alternatives
- [toggle-group](https://hazeui.com/ui/toggle-group.md)
- [radio-group](https://hazeui.com/ui/radio-group.md)
- [animated-number](https://hazeui.com/ui/animated-number.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique ID for the billing control. Defaults the form field name. |
| name | `string` |  | no | Native radio field name. |
| legend | `string` | Billing cycle | no | Visible group label. |
| monthlyLabel | `string` | Monthly | no | Text on the monthly option. |
| annualLabel | `string` | Annual | no | Text on the annual option. |
| monthly | `number` | 24 | no | Price per month when billed monthly. |
| annual | `number` | 19 | no | Price per month when billed annually. |
| value | `"monthly" \| "annual"` | monthly | no | Initial selection. |
| currency | `string` | USD | no | ISO currency code for the display. |
| locale | `string` | en-US | no | Locale for currency and numbers. |
| badge | `string` |  | no | Override the calculated savings badge. An empty string hides it. |
| class | `string` |  | no | Classes on the fieldset. |

## Accessibility
- Native radios work with or without scripts. The billing cadence appears beside the amount, and price changes are announced when scripts are active.
- Key Arrow keys: Switch billing cycle from a focused option.

## Agent prompts

### Install and use

Install the Haze UI component "Billing Toggle" with `npx shadcn@latest add @haze/billing-toggle`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import BillingToggle from "@/components/haze/ui/billing-toggle.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/billing-toggle.md

### Customize with real content

Adapt the Haze billing-toggle ui for our product. Replace the demo values of these props with our real content: id, name, legend, monthlyLabel, annualLabel, monthly, annual, value, currency, locale, badge, class. Keep the layout, the heading level rules and these accessibility details: Native radios work with or without scripts. The billing cadence appears beside the amount, and price changes are announced when scripts are active. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using billing-toggle, check it fits: use it when show two billing cycles for one plan.; put the annual savings alongside the billing choice.. Avoid it when the choices change views or filters instead of a price.. Alternatives: @haze/toggle-group, @haze/radio-group, @haze/animated-number.

## Example requests that should lead here
- Let people compare monthly and annual rates, and show how much the annual plan saves.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";
import AnimatedNumber from "./animated-number.astro";

interface Props {
  id: string;
  name?: string;
  legend?: string;
  monthlyLabel?: string;
  annualLabel?: string;
  monthly?: number;
  annual?: number;
  value?: "monthly" | "annual";
  currency?: string;
  locale?: string;
  badge?: string;
  class?: string;
}

const {
  id, name = id, legend = "Billing cycle", monthlyLabel = "Monthly", annualLabel = "Annual",
  monthly = 24, annual = 19, value = "monthly", currency = "USD", locale = "en-US", badge, class: className,
} = Astro.props;
const monthlyPrice = Number.isFinite(monthly) ? Math.max(0, monthly) : 0;
const annualPrice = Number.isFinite(annual) ? Math.max(0, annual) : 0;
const currencyDigits = new Intl.NumberFormat(locale, { style: "currency", currency }).resolvedOptions().maximumFractionDigits ?? 2;
const fractionDigits = [monthlyPrice, annualPrice].some(price => !Number.isInteger(price)) ? currencyDigits : 0;
const currencyFormatter = new Intl.NumberFormat(locale, { style: "currency", currency, minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits });
const currencyParts = currencyFormatter.formatToParts(1);
const firstDigit = currencyParts.findIndex(part => part.type === "integer");
const lastDigit = currencyParts.findLastIndex(part => part.type === "fraction" || part.type === "integer");
const prefix = currencyParts.slice(0, firstDigit).map(part => part.value).join("");
const suffix = currencyParts.slice(lastDigit + 1).map(part => part.value).join("");
const savings = monthlyPrice > annualPrice ? Math.round(100 * (1 - annualPrice / monthlyPrice)) : 0;
const badgeText = badge ?? (savings > 0 ? `Save ${savings}%` : "");
const options = [
  { value: "monthly", label: monthlyLabel, price: monthlyPrice },
  { value: "annual", label: annualLabel, price: annualPrice },
] as const;
const optionClass = "relative z-10 flex min-h-8 min-w-0 cursor-pointer flex-wrap content-center items-center justify-center gap-x-1.5 gap-y-0.5 rounded-sm px-3 py-1 text-center text-[0.8125rem]/5 font-medium wrap-anywhere text-muted-foreground hover:text-foreground has-checked:text-foreground has-focus-visible:outline-2 has-focus-visible:-outline-offset-2 has-focus-visible:outline-ring forced-colors:has-checked:outline";
---

<fieldset id={id} data-haze-billing-toggle class={cn("group/billing min-w-0 max-w-full border-0 p-0", className)}>
  <legend class="mb-2 text-[0.8125rem]/5 font-medium">{legend}</legend>
  <div class="relative isolate grid w-fit max-w-full grid-cols-[repeat(2,minmax(0,1fr))] rounded-lg border border-frame bg-muted p-1">
    <div aria-hidden="true" class="pointer-events-none absolute inset-1">
      <span data-billing-thumb class="block h-full w-1/2 rounded-sm border border-frame bg-card shadow-key group-has-[input[value=annual]:checked]/billing:translate-x-full motion-safe:transition-transform motion-safe:duration-300 motion-safe:ease-snappy rtl:group-has-[input[value=annual]:checked]/billing:-translate-x-full"></span>
    </div>
    {options.map(option => (
      <label class={optionClass}>
        <input type="radio" name={name} value={option.value} checked={option.value === value} data-price={option.price} class="peer sr-only" />
        {option.label}
        {option.value === "annual" && badgeText && (
          <span class="rounded-sm bg-accent px-1.5 py-0.5 text-[0.6875rem]/4 text-muted-foreground peer-checked:bg-accent peer-checked:text-foreground motion-safe:transition-colors motion-safe:duration-200 motion-safe:ease-snappy">{badgeText}</span>
        )}
      </label>
    ))}
  </div>
  <div class="mt-3 flex min-w-0 flex-wrap items-baseline gap-x-2">
    <span class="hidden text-xl/7 font-semibold tabular-nums group-has-[input[value=monthly]:checked]/billing:inline group-data-[enhanced]/billing:!hidden">{currencyFormatter.format(monthlyPrice)}</span>
    <span class="hidden text-xl/7 font-semibold tabular-nums group-has-[input[value=annual]:checked]/billing:inline group-data-[enhanced]/billing:!hidden">{currencyFormatter.format(annualPrice)}</span>
    <AnimatedNumber value={value === "annual" ? annualPrice : monthlyPrice} {locale} {prefix} {suffix} {fractionDigits} announce class="hidden text-xl/7 font-semibold group-data-[enhanced]/billing:inline-grid" />
    <span class="text-xs/5 text-muted-foreground group-has-[input[value=annual]:checked]/billing:hidden">per month, billed monthly</span>
    <span class="hidden text-xs/5 text-muted-foreground group-has-[input[value=annual]:checked]/billing:inline">per month, billed annually</span>
  </div>
</fieldset>

<script>
  function enhance(root: HTMLFieldSetElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const number = root.querySelector<HTMLElement>("[data-haze-animated-number]");
    if (!number) return;
    const sync = () => {
      const current = root.querySelector<HTMLInputElement>("input:checked");
      if (current?.dataset.price !== undefined) number.dataset.value = current.dataset.price;
    };
    root.addEventListener("change", sync);
    root.form?.addEventListener("reset", () => queueMicrotask(sync));
    sync();
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLFieldSetElement>("[data-haze-billing-toggle]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-billing-toggle-listener")) {
    document.documentElement.setAttribute("data-haze-billing-toggle-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
