# Donut Chart

> Displays the shares of a total as a ring and links its segments to an interactive legend.

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

## Use when
- Several named categories make up a single total.
- Users need the proportions plus exact values for each category.

## Avoid when
- Compare a long list of categories with very similar values.

## Alternatives
- [bar-list](https://hazeui.com/ui/bar-list.md)
- [stat](https://hazeui.com/ui/stat.md)
- [sparkline](https://hazeui.com/ui/sparkline.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` | Requests by channel | no | Description of the measured total. |
| totalLabel | `string` | Total | no | Label beneath the default center value. |
| segments | `Segment[]` |  | no | Named nonnegative values with an optional theme tone. |
| unit | `string` |  | no | Optional suffix for values. |
| emptyLabel | `string` |  | no | Message shown when no valid segments exist. |
| class | `string` |  | no | Classes for the chart panel. |

## Accessibility
- The legend contains a visible count and share for every segment.
- The buttons report selection without relying on ring color.
- Key Tab: Move between legend buttons.
- Key Enter / Space: Inspect the focused segment or return to the total.

## Agent prompts

### Install and use

Install the Haze UI component "Donut Chart" with `npx shadcn@latest add @haze/donut-chart`. 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 DonutChart from "@/components/haze/ui/donut-chart.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/donut-chart.md

### Customize with real content

Adapt the Haze donut-chart ui for our product. Replace the demo values of these props with our real content: label, totalLabel, segments, unit, emptyLabel, class. Keep the layout, the heading level rules and these accessibility details: The legend contains a visible count and share for every segment. The buttons report selection without relying on ring color. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using donut-chart, check it fits: use it when several named categories make up a single total.; users need the proportions plus exact values for each category.. Avoid it when compare a long list of categories with very similar values.. Alternatives: @haze/bar-list, @haze/stat, @haze/sparkline.

## Example requests that should lead here
- Show the proportion of requests from direct traffic, search, and referral.
- Add a plan distribution chart with selectable legend entries.

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

type Tone = "brand" | "success" | "warning" | "destructive" | "neutral";
interface Segment { label: string; value: number; tone?: Tone }
interface Props {
  label?: string;
  totalLabel?: string;
  segments?: Segment[];
  unit?: string;
  emptyLabel?: string;
  class?: string;
}

const {
  label = "Requests by channel", totalLabel = "Total", unit = "", emptyLabel = "No requests in this period.", class: className,
  segments = [
    { label: "Direct", value: 842, tone: "brand" },
    { label: "Search", value: 385, tone: "success" },
    { label: "Referral", value: 197, tone: "warning" },
  ],
} = Astro.props;
const colors = {
  brand: "stroke-brand bg-brand",
  success: "stroke-success bg-success",
  warning: "stroke-warning bg-warning",
  destructive: "stroke-destructive bg-destructive",
  neutral: "stroke-muted-foreground bg-muted-foreground",
};
const tones: Tone[] = ["brand", "success", "warning", "destructive", "neutral"];
const visible = segments.filter(({ value }) => Number.isFinite(value) && value >= 0);
const largest = visible.reduce((max, { value }) => Math.max(max, value), 0);
const scaledTotal = largest ? visible.reduce((total, { value }) => total + (value / largest), 0) : 0;
const total = scaledTotal * largest;
const formatter = new Intl.NumberFormat("en", { maximumFractionDigits: 2 });
const formatted = (value: number) => unit ? `${formatter.format(value)} ${unit}` : formatter.format(value);
let offset = 0;
const arcs = visible.map((segment, index) => {
  const percent = largest ? (segment.value / largest) / scaledTotal * 100 : 0;
  const gap = percent === 100 ? 0 : Math.min(1.25, percent / 5);
  const arc = { ...segment, index, start: offset + gap / 2, length: percent - gap, percent, tone: segment.tone ?? tones[index % tones.length] };
  offset += percent;
  return arc;
});
---

<figure data-haze-donut-chart class={cn("@container grid min-w-0 gap-3 rounded-xl border border-border bg-card p-4.5 text-card-foreground", className)}>
  <figcaption class="text-[0.9375rem]/5 font-medium tracking-[-0.01em]">{label}</figcaption>
  {arcs.length ? (
    <div class="grid items-center gap-3 @sm:grid-cols-[minmax(8.5rem,0.9fr)_1.3fr]">
      <div class="relative mx-auto grid size-36 place-items-center">
        <svg aria-hidden="true" viewBox="0 0 120 120" class="absolute inset-0 size-full -rotate-90">
          <circle cx="60" cy="60" r="50" stroke-width="9" class="fill-none stroke-border" />
          {arcs.filter(({ length }) => length > 0).map(({ index, start, length, tone }) => (
            <circle data-donut-arc={index} cx="60" cy="60" r="50" stroke-width="9" pathLength="100"
              stroke-dasharray={`${length} ${100 - length}`} stroke-dashoffset={-start}
              class={cn("fill-none transition-opacity duration-200 ease-snappy data-[dimmed]:opacity-45", colors[tone])} />
          ))}
        </svg>
        <div class="relative grid w-25 place-items-center gap-0.5 rounded-full bg-card text-center">
          <span data-donut-value data-total={formatted(total)} class="max-w-full text-lg/6 font-semibold tracking-tight tabular-nums wrap-anywhere">{formatted(total)}</span>
          <span data-donut-caption data-total-label={totalLabel} class="line-clamp-2 text-[0.75rem]/4 text-muted-foreground wrap-anywhere">{totalLabel}</span>
        </div>
      </div>
      <ul class="grid min-w-0 gap-0.5" role="list">
        {arcs.map(({ label: name, value, percent, tone, index }) => (
          <li class="min-w-0">
            <button type="button" disabled aria-pressed="false" data-donut-option={index} data-donut-label={name} data-donut-count={formatted(value)}
              class="grid min-h-8 w-full min-w-0 grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-2 rounded-lg px-2 py-1.5 text-start text-[0.8125rem]/5 transition-colors duration-150 ease-snappy enabled:cursor-pointer enabled:hover:bg-accent enabled:active:scale-[0.985] focus-visible:outline-2 focus-visible:outline-ring aria-pressed:bg-accent">
              <span aria-hidden="true" class={cn("size-2 rounded-full", colors[tone])}></span>
              <span class="grid min-w-0 gap-0.5 wrap-anywhere">{name}<span class="text-[0.75rem]/4 text-muted-foreground tabular-nums">{formatted(value)}</span></span>
              <span class="text-muted-foreground tabular-nums">{formatter.format(percent)}%</span>
            </button>
          </li>
        ))}
      </ul>
    </div>
  ) : <p class="text-[0.8125rem]/5 text-muted-foreground">{emptyLabel}</p>}
</figure>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const value = root.querySelector<HTMLElement>("[data-donut-value]");
    const caption = root.querySelector<HTMLElement>("[data-donut-caption]");
    if (!value || !caption) return;
    const arcs = root.querySelectorAll<SVGCircleElement>("[data-donut-arc]");
    const options = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-donut-option]"));
    const setActive = (option?: HTMLButtonElement) => {
      value.textContent = option?.dataset.donutCount ?? value.dataset.total ?? "";
      caption.textContent = option?.dataset.donutLabel ?? caption.dataset.totalLabel ?? "";
      options.forEach((button) => button.setAttribute("aria-pressed", String(button === option)));
      arcs.forEach((arc) => {
        arc.toggleAttribute("data-dimmed", Boolean(option) && arc.dataset.donutArc !== option?.dataset.donutOption);
      });
    };
    for (const option of options) {
      option.disabled = false;
      option.addEventListener("click", () => setActive(option.getAttribute("aria-pressed") === "true" ? undefined : option));
    }
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-donut-chart]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-donut-chart-listener")) {
    document.documentElement.setAttribute("data-haze-donut-chart-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
