# Spending Ring

> Displays period spending in a centered segmented donut with dynamic active readout and a compact 2-column category legend.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/spending-ring`
- File: `src/components/haze/ui/spending-ring.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/spending-ring

## Use when
- Users inspect how monthly or period spending splits across up to six categories.
- Highlighting a single category should update the center amount, share, and period-over-period note immediately.

## Avoid when
- You need time-series trend lines across many months. Use line-chart or bar-chart instead.
- More than six spending categories need side-by-side tabular ranking.

## Alternatives
- [donut-chart](https://hazeui.com/ui/donut-chart.md)
- [usage-meter](https://hazeui.com/ui/usage-meter.md)
- [split-bar](https://hazeui.com/ui/split-bar.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| period | `string` | "October spending" | no | Period heading shown in the top-left of the card. |
| currency | `string` | "USD" | no | ISO 4217 currency code for formatting totals and category amounts. |
| categories | `SpendingCategory[]` |  | no | Spending categories with label, amount, optional comparison note, and theme tone. |
| defaultActiveIndex | `number` | 0 | no | Zero-based index of the initially highlighted category. |
| headingLevel | `2 \| 3 \| 4` | 3 | no | Heading level for the period title. |
| class | `string` |  | no | Additional classes on the outer card. |

## Accessibility
- Every category button exposes its exact label and rounded amount in text so color is never the sole cue.
- Hovering, focusing, or clicking a category updates aria-pressed, active ring thickness, and the center readout, announcing clicks in a polite live region.
- Without JavaScript, the initial active category, total spend, and full category grid remain visible.
- Key Tab: Move focus across the category buttons and preview each segment in the center readout.
- Key Enter / Space: Select a category and announce its amount, share, and comparison note.

## Agent prompts

### Install and use

Install the Haze UI component "Spending Ring" with `npx shadcn@latest add @haze/spending-ring`. 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 SpendingRing from "@/components/haze/ui/spending-ring.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/spending-ring.md

### Customize with real content

Adapt the Haze spending-ring ui for our product. Replace the demo values of these props with our real content: period, currency, categories, defaultActiveIndex, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: Every category button exposes its exact label and rounded amount in text so color is never the sole cue. Hovering, focusing, or clicking a category updates aria-pressed, active ring thickness, and the center readout, announcing clicks in a polite live region. Without JavaScript, the initial active category, total spend, and full category grid remain visible. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using spending-ring, check it fits: use it when users inspect how monthly or period spending splits across up to six categories.; highlighting a single category should update the center amount, share, and period-over-period note immediately.. Avoid it when you need time-series trend lines across many months. use line-chart or bar-chart instead.; more than six spending categories need side-by-side tabular ranking.. Alternatives: @haze/donut-chart, @haze/usage-meter, @haze/split-bar.

## Example requests that should lead here
- Build a centered monthly spending donut card for October with six interactive categories and a 2-column legend.
- Add a personal finance expense breakdown ring showing active category spend, percentage of total, and month-over-month note.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

type Tone = "brand" | "success" | "destructive" | "warning" | "ink" | "neutral";

interface SpendingCategory {
  label: string;
  amount: number;
  comparison?: string;
  tone?: Tone;
}

interface Props {
  period?: string;
  currency?: string;
  categories?: SpendingCategory[];
  defaultActiveIndex?: number;
  headingLevel?: 2 | 3 | 4;
  class?: string;
}

const {
  period = "October spending",
  currency = "USD",
  categories = [
    { label: "Housing", amount: 1250, comparison: "Same as last month", tone: "brand" },
    { label: "Groceries", amount: 486.42, comparison: "-4% vs last month", tone: "success" },
    { label: "Shopping", amount: 398, comparison: "+6% vs last month", tone: "destructive" },
    { label: "Dining out", amount: 313, comparison: "+2% vs last month", tone: "warning" },
    { label: "Transport", amount: 214, comparison: "-9% vs last month", tone: "ink" },
    { label: "Subscriptions", amount: 87, comparison: "Same as last month", tone: "neutral" },
  ],
  defaultActiveIndex = 0,
  headingLevel = 3,
  class: className,
} = Astro.props;

const Heading = ({ 2: "h2", 3: "h3", 4: "h4" } as const)[headingLevel];

const strokeTone: Record<Tone, string> = {
  brand: "text-brand",
  success: "text-success",
  destructive: "text-destructive",
  warning: "text-warning",
  ink: "text-foreground/70",
  neutral: "text-muted-foreground",
};

const dotTone: Record<Tone, string> = {
  brand: "bg-brand",
  success: "bg-success",
  destructive: "bg-destructive",
  warning: "bg-warning",
  ink: "bg-foreground/70",
  neutral: "bg-muted-foreground",
};

const toneOrder: Tone[] = ["brand", "success", "destructive", "warning", "ink", "neutral"];
const valid = categories.filter(({ amount }) => Number.isFinite(amount) && amount > 0);
const total = valid.reduce((sum, item) => sum + item.amount, 0);

const fullMoney = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency,
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});
const compactMoney = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency,
  maximumFractionDigits: 0,
});
const pctFmt = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });

let offset = 0;
const segments = valid.map((item, index) => {
  const share = total > 0 ? (item.amount / total) * 100 : 0;
  const gap = valid.length <= 1 ? 0 : Math.min(0.9, share / 4);
  const seg = {
    ...item,
    index,
    tone: item.tone ?? toneOrder[index % toneOrder.length],
    start: offset + gap / 2,
    length: Math.max(0, share - gap),
    shareText: `${pctFmt.format(share)}% of total`,
    fullFormatted: fullMoney.format(item.amount),
    compactFormatted: compactMoney.format(Math.round(item.amount)),
    comparison: item.comparison ?? "Compared to last month",
  };
  offset += share;
  return seg;
});

const activeIndex = segments.length > 0 ? Math.min(Math.max(0, defaultActiveIndex), segments.length - 1) : 0;
const initial = segments[activeIndex] ?? {
  label: "No spending",
  tone: "neutral" as Tone,
  fullFormatted: fullMoney.format(0),
  shareText: "0% of total",
  comparison: "No activity recorded",
};
---

<section
  data-haze-spending-ring
  class={cn(
    "flex w-full max-w-[360px] min-w-0 flex-col rounded-2xl border border-border bg-card p-5 text-card-foreground shadow-key",
    className,
  )}
>
  <header class="flex items-baseline justify-between gap-3">
    <Heading class="min-w-0 truncate text-sm/5 font-medium text-muted-foreground">{period}</Heading>
    <span class="shrink-0 text-sm/5 font-semibold text-foreground tabular-nums">{fullMoney.format(total)}</span>
  </header>

  <div class="relative mx-auto my-4 aspect-square w-full max-w-52">
    <svg
      aria-hidden="true"
      viewBox="0 0 10 6"
      class="pointer-events-none absolute -top-1 left-1/2 h-1.5 w-2.5 -translate-x-1/2 text-foreground"
    >
      <polygon points="0,0 10,0 5,6" fill="currentColor" />
    </svg>

    <svg aria-hidden="true" viewBox="0 0 200 200" class="size-full -rotate-90">
      <circle cx="100" cy="100" r="72" class="fill-none stroke-muted stroke-[22]" />
      {segments.filter(({ length }) => length > 0).map((seg) => (
        <circle
          data-spending-arc={seg.index}
          data-active={seg.index === activeIndex ? "" : undefined}
          cx="100"
          cy="100"
          r="72"
          stroke="currentColor"
          stroke-linecap="butt"
          pathLength="100"
          stroke-dasharray={`${seg.length} ${100 - seg.length}`}
          stroke-dashoffset={-seg.start}
          class={cn(
            "fill-none stroke-[22] opacity-45 transition-[opacity,stroke-width] duration-200 ease-snappy data-[active]:stroke-[25] data-[active]:opacity-100 [[data-haze-spending-ring][data-enhanced]_&]:cursor-pointer",
            strokeTone[seg.tone],
          )}
        />
      ))}
    </svg>

    <div class="pointer-events-none absolute inset-0 flex flex-col items-center justify-center px-12 text-center">
      <div class="flex max-w-full items-center justify-center gap-1.5">
        <span
          data-spending-dot
          aria-hidden="true"
          class={cn("size-2 shrink-0 rounded-full transition-colors duration-200 ease-snappy", dotTone[initial.tone])}
        ></span>
        <span data-spending-label class="truncate text-xs/4 font-medium text-muted-foreground">
          {initial.label}
        </span>
      </div>
      <span
        data-spending-amount
        class="mt-1 max-w-full text-lg/6 font-semibold tracking-tight text-foreground tabular-nums"
      >
        {initial.fullFormatted}
      </span>
      <span data-spending-pct class="mt-0.5 text-[0.6875rem]/4 font-medium text-muted-foreground tabular-nums">
        {initial.shareText}
      </span>
    </div>
  </div>

  <p data-spending-comparison class="-mt-1 mb-3 text-center text-xs/4 text-muted-foreground">{initial.comparison}</p>

  <ul role="list" class="grid grid-cols-2 gap-x-3 gap-y-1.5 border-t border-border pt-3.5">
    {segments.map((seg) => (
      <li class="min-w-0">
        <button
          type="button"
          aria-pressed={seg.index === activeIndex ? "true" : "false"}
          data-spending-item={seg.index}
          data-spending-name={seg.label}
          data-spending-amount={seg.fullFormatted}
          data-spending-share={seg.shareText}
          data-spending-comparison={seg.comparison}
          data-spending-tone={seg.tone}
          class="group grid w-full text-xs/4 min-w-0 cursor-pointer grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5 rounded-lg px-2 py-1.5 text-start transition-[background-color,color] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-pressed:bg-accent"
        >
          <span aria-hidden="true" class={cn("size-2 shrink-0 rounded-full", dotTone[seg.tone])}></span>
          <span class="min-w-0 truncate text-xs/4 text-muted-foreground group-hover:text-foreground group-aria-pressed:font-medium group-aria-pressed:text-foreground">
            {seg.label}
          </span>
          <span class="shrink-0 text-xs/4 font-medium text-foreground tabular-nums">
            {seg.compactFormatted}
          </span>
        </button>
      </li>
    ))}
  </ul>

  <p data-spending-status aria-live="polite" class="sr-only"></p>
</section>

<script>
  const DOT_CLASSES: Record<string, string> = {
    brand: "bg-brand",
    success: "bg-success",
    destructive: "bg-destructive",
    warning: "bg-warning",
    ink: "bg-foreground/70",
    neutral: "bg-muted-foreground",
  };
  const ALL_DOT_CLASSES = Object.values(DOT_CLASSES);

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const dotEl = root.querySelector<HTMLElement>("[data-spending-dot]");
    const labelEl = root.querySelector<HTMLElement>("[data-spending-label]");
    const amountEl = root.querySelector<HTMLElement>("[data-spending-amount]");
    const pctEl = root.querySelector<HTMLElement>("[data-spending-pct]");
    const comparisonEl = root.querySelector<HTMLElement>("[data-spending-comparison]");
    const statusEl = root.querySelector<HTMLElement>("[data-spending-status]");
    if (!dotEl || !labelEl || !amountEl || !pctEl || !comparisonEl) return;

    const arcs = Array.from(root.querySelectorAll<SVGCircleElement>("[data-spending-arc]"));
    const buttons = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-spending-item]"));
    if (!buttons.length) return;

    const select = (index: string, announce = false) => {
      const target = buttons.find((btn) => btn.dataset.spendingItem === index);
      if (!target) return;

      const tone = target.dataset.spendingTone ?? "neutral";
      dotEl.classList.remove(...ALL_DOT_CLASSES);
      dotEl.classList.add(DOT_CLASSES[tone] ?? "bg-muted-foreground");

      labelEl.textContent = target.dataset.spendingName ?? "";
      amountEl.textContent = target.dataset.spendingAmount ?? "";
      pctEl.textContent = target.dataset.spendingShare ?? "";
      comparisonEl.textContent = target.dataset.spendingComparison ?? "";

      buttons.forEach((btn) => btn.setAttribute("aria-pressed", String(btn === target)));
      arcs.forEach((arc) => {
        const isActive = arc.dataset.spendingArc === index;
        arc.toggleAttribute("data-active", isActive);
      });

      if (announce && statusEl) {
        statusEl.textContent = `${target.dataset.spendingName}: ${target.dataset.spendingAmount}, ${target.dataset.spendingShare}. ${target.dataset.spendingComparison}.`;
      }
    };

    for (const button of buttons) {
      const index = button.dataset.spendingItem ?? "0";
      button.addEventListener("mouseenter", () => select(index, false));
      button.addEventListener("focus", () => select(index, false));
      button.addEventListener("click", () => select(index, true));
    }

    for (const arc of arcs) {
      const index = arc.dataset.spendingArc ?? "0";
      arc.addEventListener("mouseenter", () => select(index, false));
      arc.addEventListener("click", () => select(index, true));
    }

    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-spending-ring]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-spending-ring-listener")) {
    document.documentElement.setAttribute("data-haze-spending-ring-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
