# Area chart

> Multi-series SVG area chart with filled bands, series toggles, pointer crosshair scrubber, and accessible data table fallback.

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

## Use when
- Visualizing cumulative or volume trends over time
- Comparing one primary metric against a baseline with shaded area fills

## Avoid when
- Discrete categorical comparisons belong in bar-chart
- Single inline numeric trends with no axes belong in sparkline

## Alternatives
- [line-chart](https://hazeui.com/ui/line-chart.md)
- [bar-chart](https://hazeui.com/ui/bar-chart.md)
- [streamgraph](https://hazeui.com/ui/streamgraph.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` | "Monthly active workspaces" | no | Chart heading. |
| data | `Datum[]` |  | no | Time-series points with named numeric values. |
| series | `Series[]` |  | no | Series definitions controlling tone, label, and optional dashed line. |
| unit | `string` | "" | no | Optional unit suffix shown after readouts. |
| class | `string` |  | no | Extra classes. |

## Accessibility
- Keyboard users can inspect points via an underlying range input alongside the collapsible data table.
- Series toggle pills expose aria-pressed state and keep non-color line style distinctions.
- Key ArrowLeft / ArrowRight: Step through time buckets when the plot slider is focused.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze area-chart ui for our product. Replace the demo values of these props with our real content: label, data, series, unit, class. Keep the layout, the heading level rules and these accessibility details: Keyboard users can inspect points via an underlying range input alongside the collapsible data table. Series toggle pills expose aria-pressed state and keep non-color line style distinctions. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using area-chart, check it fits: use it when visualizing cumulative or volume trends over time; comparing one primary metric against a baseline with shaded area fills. Avoid it when discrete categorical comparisons belong in bar-chart; single inline numeric trends with no axes belong in sparkline. Alternatives: @haze/line-chart, @haze/bar-chart, @haze/streamgraph.

## Example requests that should lead here
- Add a multi-series area chart showing active workspaces vs trials with interactive hover inspection

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";
import Collapsible from "./collapsible.astro";
import Table from "./table.astro";

type Tone = "brand" | "neutral" | "success" | "warning" | "destructive";
interface Series {
  key: string;
  label: string;
  tone?: Tone;
  dashed?: boolean;
}
interface Datum {
  label: string;
  values: Record<string, number | null | undefined>;
}
interface Props {
  label?: string;
  data?: Datum[];
  series?: Series[];
  unit?: string;
  categoryLabel?: string;
  detailsLabel?: string;
  emptyLabel?: string;
  class?: string;
}

const {
  label = "Monthly active workspaces",
  unit = "",
  categoryLabel = "Month",
  detailsLabel = "View data",
  emptyLabel = "No measurements for this period.",
  class: className,
  series = [
    { key: "active", label: "Active", tone: "brand" },
    { key: "trial", label: "Trial", tone: "success", dashed: true },
  ],
  data = [
    { label: "Apr", values: { active: 1420, trial: 410 } },
    { label: "May", values: { active: 1680, trial: 495 } },
    { label: "Jun", values: { active: 1940, trial: 560 } },
    { label: "Jul", values: { active: 2290, trial: 640 } },
    { label: "Aug", values: { active: 2740, trial: 710 } },
    { label: "Sep", values: { active: 3180, trial: 820 } },
  ],
} = Astro.props;

const strokeTones: Record<Tone, string> = {
  brand: "stroke-brand bg-brand",
  neutral: "stroke-muted-foreground bg-muted-foreground",
  success: "stroke-success bg-success",
  warning: "stroke-warning bg-warning",
  destructive: "stroke-destructive bg-destructive",
};
const fillTones: Record<Tone, string> = {
  brand: "fill-brand/14",
  neutral: "fill-foreground/8",
  success: "fill-success/14",
  warning: "fill-warning/14",
  destructive: "fill-destructive/14",
};
const defaults: Tone[] = ["brand", "success", "neutral", "warning", "destructive"];
const seenKeys = new Set<string>();
const fields = series
  .filter(({ key }) => {
    if (!key || seenKeys.has(key)) return false;
    seenKeys.add(key);
    return true;
  })
  .map((field, index) => {
    const tone = field.tone ?? defaults[index % defaults.length];
    return { ...field, strokeCls: strokeTones[tone], fillCls: fillTones[tone] };
  });

const numeric = data.map(({ label: period, values }) => ({
  label: period,
  values: fields.map(({ key }) => {
    const v = values[key];
    return typeof v === "number" && Number.isFinite(v) ? v : null;
  }),
}));

let lowest = Infinity;
let highest = -Infinity;
for (const row of numeric) {
  for (const val of row.values) {
    if (val === null) continue;
    lowest = Math.min(lowest, val);
    highest = Math.max(highest, val);
  }
}
lowest = Number.isFinite(lowest) ? Math.min(0, lowest) : 0;
const available = Number.isFinite(highest);
const span = available ? highest - lowest || 1 : 1;
const y = (val: number) => 6 + 88 * ((highest - val) / span);
const baselineY = y(0);
const grouped = new Intl.NumberFormat("en");
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumSignificantDigits: 3 });
const tickLabel = (val: number) => {
  const txt = compact.format(val);
  return txt.length > 10 ? val.toExponential(2) : txt;
};
const format = (val: number) => `${Number.isSafeInteger(val) ? grouped.format(val) : String(val)}${unit ? ` ${unit}` : ""}`;

const points = numeric.map((row, index) => ({
  label: row.label,
  x: numeric.length === 1 ? 50 : (index * 100) / (numeric.length - 1),
  values: row.values.map((val) => (val === null ? { text: "—", y: null } : { text: format(val), y: y(val) })),
}));

const shapes = fields.map((_, fi) => {
  const pts = points
    .map((pt) => ({ x: pt.x, y: pt.values[fi].y }))
    .filter((pt): pt is { x: number; y: number } => pt.y !== null);
  if (!pts.length) return { line: "", area: "" };
  const line = pts.map((pt, i) => `${i === 0 ? "M" : "L"}${pt.x.toFixed(2)},${pt.y.toFixed(2)}`).join(" ");
  const area = `${line} L${pts.at(-1)!.x.toFixed(2)},${baselineY.toFixed(2)} L${pts[0].x.toFixed(2)},${baselineY.toFixed(2)} Z`;
  return { line, area };
});

const last = points.at(-1);
const ticks = !available ? [] : highest === lowest ? [highest] : [highest, (highest + lowest) / 2, lowest];
const tableColumns = [
  { key: "category", label: categoryLabel },
  ...fields.map((field, index) => ({ key: `s${index}`, label: field.label, align: "right" as const })),
];
const tableRows = points.map((pt) =>
  Object.fromEntries([["category", pt.label], ...pt.values.map((v, idx) => [`s${idx}`, v.text])]),
);
---

<figure
  data-haze-area-chart
  data-points={JSON.stringify(points)}
  class={cn("grid min-w-0 gap-4 rounded-xl border border-border bg-card p-4.5 text-card-foreground", className)}
>
  <figcaption class="flex min-w-0 flex-wrap items-baseline justify-between gap-x-4 gap-y-1">
    <span class="text-[1.0625rem]/6 font-medium tracking-[-0.01em] wrap-anywhere">{label}</span>
    {available && last && <span data-area-period class="font-mono text-xs/5 wrap-anywhere text-muted-foreground">{last.label}</span>}
  </figcaption>

  {
    available && last ? (
      <>
        <ul role="list" class="flex min-w-0 flex-wrap gap-2">
          {fields.map((field, index) => (
            <li class="min-w-0 max-w-full">
              <button
                type="button"
                data-area-series={String(index)}
                aria-pressed="true"
                class="group inline-flex min-h-8 max-w-full cursor-pointer items-center gap-2 rounded-full border border-frame bg-muted/40 px-2.5 py-1 text-start text-[0.8125rem]/4 transition-colors duration-150 ease-snappy hover:bg-accent active:scale-[0.97] aria-[pressed=false]:opacity-50 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring"
              >
                <span aria-hidden="true" class={cn("size-2 shrink-0 rounded-full", field.strokeCls.split(" ")[1])}></span>
                <span class="font-medium text-foreground">{field.label}</span>
                <span data-area-val={String(index)} class="font-mono text-xs text-muted-foreground tabular-nums">
                  {last.values[index]?.text}
                </span>
              </button>
            </li>
          ))}
        </ul>

        <div class="grid min-w-0 grid-cols-[fit-content(28%)_minmax(0,1fr)] items-start gap-x-2">
          <div aria-hidden="true" class="relative h-40 min-w-0 font-mono text-xs/4 text-muted-foreground sm:h-48">
            {ticks.map((t) => (
              <span style={`top:${y(t)}%`} class="absolute inset-e-0 -translate-y-1/2">
                {tickLabel(t)}
              </span>
            ))}
            <span class="invisible">
              {ticks.map(tickLabel).reduce((longest, txt) => (txt.length > longest.length ? txt : longest), "")}
            </span>
          </div>

          <div class="min-w-0">
            <div
              data-area-plot
              dir="ltr"
              class="relative mx-1 h-40 touch-pan-y cursor-crosshair rounded-sm focus-within:outline-2 focus-within:outline-offset-4 focus-within:outline-ring sm:h-48"
            >
              <svg aria-hidden="true" viewBox="0 0 100 100" preserveAspectRatio="none" class="absolute inset-0 size-full overflow-visible">
                {ticks.map((t) => (
                  <path
                    d={`M0 ${y(t)}h100`}
                    class="fill-none stroke-border"
                    vector-effect="non-scaling-stroke"
                    stroke-dasharray={t === 0 ? undefined : "2 4"}
                  />
                ))}
                {fields.map((field, index) => (
                  <g data-area-group={String(index)} class="transition-opacity duration-200">
                    {shapes[index]?.area && <path d={shapes[index].area} class={field.fillCls} />}
                    {shapes[index]?.line && (
                      <path
                        d={shapes[index].line}
                        fill="none"
                        stroke-width="2"
                        vector-effect="non-scaling-stroke"
                        stroke-dasharray={field.dashed ? "4 3" : undefined}
                        class={field.strokeCls.split(" ")[0]}
                      />
                    )}
                  </g>
                ))}
                <line
                  data-area-cursor
                  x1="100"
                  y1="0"
                  x2="100"
                  y2="100"
                  vector-effect="non-scaling-stroke"
                  class="stroke-border-strong opacity-0 transition-opacity duration-150"
                  stroke-dasharray="2 3"
                />
              </svg>
              <input
                data-area-input
                type="range"
                min="0"
                max={Math.max(0, points.length - 1)}
                step="1"
                value={Math.max(0, points.length - 1)}
                aria-label={`Inspect ${label} by ${categoryLabel}`}
                class="pointer-events-none absolute inset-0 m-0 size-full cursor-crosshair opacity-0"
              />
            </div>

            <div dir="ltr" class="mt-2 flex min-w-0 justify-between gap-2 font-mono text-xs/4 text-muted-foreground">
              <span class="min-w-0 wrap-anywhere">{points[0].label}</span>
              {points.length > 1 && <span class="min-w-0 text-end wrap-anywhere">{points[points.length - 1].label}</span>}
            </div>
          </div>
        </div>

        <Collapsible title={detailsLabel} class="min-w-0 rounded-lg bg-muted/40">
          <Table caption={label} hideCaption columns={tableColumns} rows={tableRows} rowHeader="category" class="min-w-0 rounded-md" />
        </Collapsible>
      </>
    ) : (
      <p class="text-[0.8125rem]/5 text-muted-foreground">{emptyLabel}</p>
    )
  }
</figure>

<script>
  function initAreaCharts() {
    document.querySelectorAll<HTMLElement>("[data-haze-area-chart]:not([data-enhanced])").forEach((root) => {
      root.setAttribute("data-enhanced", "");
      const points: { label: string; x: number; values: { text: string; y: number | null }[] }[] = JSON.parse(
        root.dataset.points ?? "[]",
      );
      if (!points.length) return;

      const plot = root.querySelector<HTMLElement>("[data-area-plot]");
      const input = root.querySelector<HTMLInputElement>("[data-area-input]");
      const periodEl = root.querySelector<HTMLElement>("[data-area-period]");
      const cursor = root.querySelector<SVGLineElement>("[data-area-cursor]");
      const valEls = Array.from(root.querySelectorAll<HTMLElement>("[data-area-val]"));

      const setPoint = (idx: number, showCursor = true) => {
        const pt = points[idx];
        if (!pt) return;
        if (periodEl) periodEl.textContent = pt.label;
        valEls.forEach((el, i) => {
          el.textContent = pt.values[i]?.text ?? "—";
        });
        if (cursor) {
          cursor.setAttribute("x1", String(pt.x));
          cursor.setAttribute("x2", String(pt.x));
          cursor.style.opacity = showCursor ? "1" : "0";
        }
      };

      plot?.addEventListener("pointermove", (ev) => {
        const rect = plot.getBoundingClientRect();
        if (!rect.width) return;
        const ratio = Math.max(0, Math.min(1, (ev.clientX - rect.left) / rect.width));
        const idx = Math.round(ratio * (points.length - 1));
        if (input) input.value = String(idx);
        setPoint(idx, true);
      });
      plot?.addEventListener("pointerleave", () => {
        setPoint(points.length - 1, false);
      });
      input?.addEventListener("input", () => setPoint(Number(input.value), true));

      root.querySelectorAll<HTMLButtonElement>("[data-area-series]").forEach((btn) => {
        btn.addEventListener("click", () => {
          const idx = btn.dataset.areaSeries;
          const next = btn.getAttribute("aria-pressed") !== "true";
          btn.setAttribute("aria-pressed", String(next));
          const group = root.querySelector<SVGGElement>(`[data-area-group="${idx}"]`);
          if (group) group.style.opacity = next ? "1" : "0";
        });
      });
    });
  }

  initAreaCharts();
  if (!document.documentElement.hasAttribute("data-haze-area-chart-listener")) {
    document.documentElement.setAttribute("data-haze-area-chart-listener", "");
    document.addEventListener("astro:page-load", initAreaCharts);
  }
</script>
```
