# Line chart

> Compare series on a shared scale, scrub to see values for a period, toggle traces and open the underlying table.

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

## Use when
- Two or more ordered measurements share a unit and need a common vertical scale.
- Readers need exact values while following changes across periods.

## Avoid when
- A short inline trend fits beside a number. Use sparkline.
- Each category has a single independent count. Use bar-chart.

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` | API response time | no | Visible measurement name and caption of its data table. |
| series | `Series[]` |  | no | Unique keys, legend labels and optional dashed lines or semantic tones (brand, neutral, success, warning, destructive). |
| data | `{ label: string; values: Record<string, number \| null \| undefined> }[]` |  | no | Ordered categories with measurements by series key. Missing and nonfinite values leave a gap. |
| unit | `string` | ms | no | Suffix on values. Pass an empty string for counts. |
| categoryLabel | `string` | Day | no | Name of the horizontal dimension in the table and scrubber. |
| detailsLabel | `string` | View data | no | Label of the native disclosure containing all points. |
| emptyLabel | `string` |  | no | Message when no series has a finite measurement. |
| class | `string` |  | no | Extra classes on the figure. |

## Accessibility
- The native range announces the period and visible series values. The table includes hidden series and works without scripting.
- Toggling a trace keeps the comparison scale fixed and leaves at least one trace visible. Reduced motion skips crosshair travel.
- Key Arrow keys / Home / End: Inspect adjacent periods or jump to an endpoint with the focused plot.
- Key Escape: Return the crosshair to the latest period.
- Key Enter / Space: Toggle a focused series or open the data table.

## Agent prompts

### Install and use

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

### Customize with real content

Adapt the Haze line-chart ui for our product. Replace the demo values of these props with our real content: label, series, data, unit, categoryLabel, detailsLabel, emptyLabel, class. Keep the layout, the heading level rules and these accessibility details: The native range announces the period and visible series values. The table includes hidden series and works without scripting. Toggling a trace keeps the comparison scale fixed and leaves at least one trace visible. Reduced motion skips crosshair travel. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using line-chart, check it fits: use it when two or more ordered measurements share a unit and need a common vertical scale.; readers need exact values while following changes across periods.. Avoid it when a short inline trend fits beside a number. use sparkline.; each category has a single independent count. use bar-chart.. Alternatives: @haze/sparkline, @haze/bar-chart, @haze/table.

## Example requests that should lead here
- Compare local and CI build times using solid and dashed lines with a keyboard crosshair and an exact-values table.

## 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 = "API response time", unit = "ms", categoryLabel = "Day", detailsLabel = "View data",
  emptyLabel = "No measurements for this period.", class: className,
  series = [{ key: "median", label: "Median", tone: "brand" }, { key: "p95", label: "95th percentile", tone: "neutral", dashed: true }],
  data = [
    { label: "Mon", values: { median: 142, p95: 219 } }, { label: "Tue", values: { median: 168, p95: 232 } },
    { label: "Wed", values: { median: 151, p95: 210 } }, { label: "Thu", values: { median: 126, p95: 197 } },
    { label: "Fri", values: { median: 138, p95: 206 } }, { label: "Sat", values: { median: 116, p95: 182 } },
    { label: "Sun", values: { median: 122, p95: 189 } },
  ],
} = Astro.props;
const tones = {
  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 defaults: Tone[] = ["brand", "neutral", "success", "warning", "destructive"];
const keys = new Set<string>();
const fields = series.filter(({ key }) => {
  if (!key || keys.has(key)) return false;
  keys.add(key);
  return true;
}).map((field, index) => ({ ...field, color: tones[field.tone ?? defaults[index % defaults.length]] }));
const numeric = data.map(({ label: period, values }) => ({ label: period, values: fields.map(({ key }) => {
  const value = values[key];
  return typeof value === "number" && Number.isFinite(value) ? value : null;
}) }));
let lowest = Infinity;
let highest = -Infinity;
for (const row of numeric) {
  for (const value of row.values) {
    if (value === null) continue;
    lowest = Math.min(lowest, value);
    highest = Math.max(highest, value);
  }
}
const available = Number.isFinite(lowest);
const scale = Math.max(Math.abs(lowest), Math.abs(highest)) || 1;
const y = (value: number) => lowest === highest ? 50 : 5 + 90 * ((highest / scale - value / scale) / (highest / scale - lowest / scale));
const grouped = new Intl.NumberFormat("en");
const compact = new Intl.NumberFormat("en", { notation: "compact", maximumSignificantDigits: 3 });
const tickLabel = (value: number) => {
  const text = compact.format(value);
  return text.length > 10 ? value.toExponential(2) : text;
};
const format = (value: number) => `${Number.isSafeInteger(value) ? grouped.format(value) : String(value)}${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((value) => value === null ? { text: "No value", y: null } : { text: format(value), y: y(value) }),
}));
const paths = fields.map((_, field) => {
  let path = "";
  points.forEach((point, index) => {
    const level = point.values[field].y;
    if (level === null) return;
    const previous = points[index - 1]?.values[field].y;
    const next = points[index + 1]?.values[field].y;
    path += `${previous == null ? "M" : "L"}${point.x},${level} `;
    if (previous == null && next == null) path += "h0.002 ";
  });
  return path;
});
const last = points.at(-1);
const ticks = !available ? [] : highest === lowest ? [highest] : [highest, highest / 2 + 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((point) => Object.fromEntries([["category", point.label], ...point.values.map((value, index) => [`s${index}`, value.text])]));
---

<figure data-haze-line-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-line-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 data-line-series aria-pressed="true" disabled type="button"
              class="group flex min-h-8 max-w-full flex-wrap items-center gap-x-2 gap-y-0.5 rounded-full border border-transparent px-2.5 py-1.5 text-start text-[0.8125rem]/4 enabled:cursor-pointer transition-colors duration-150 ease-snappy enabled:hover:bg-accent enabled:active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring aria-[pressed=false]:text-muted-foreground">
              <svg aria-hidden="true" viewBox="0 0 19 8" class="h-2 w-5"><path d="M1 4h17" fill="none" stroke-width="2.4"
                stroke-dasharray={field.dashed ? "4 3" : undefined} class={field.color} /></svg>
              <span data-series-name class="wrap-anywhere text-muted-foreground group-aria-[pressed=false]:line-through">{field.label}</span>
              <span data-line-value class="font-mono font-medium wrap-anywhere 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 max-w-full font-mono text-xs/4 text-muted-foreground sm:h-48">
          {ticks.map((tick) => <span style={`top:${y(tick)}%`} class="absolute inset-e-0 -translate-y-1/2">{tickLabel(tick)}</span>)}
          <span class="invisible">{ticks.map(tickLabel).reduce((longest, text) => text.length > longest.length ? text : longest, "")}</span>
        </div>
        <div class="min-w-0">
          <div data-line-plot dir="ltr" class="@container/plot relative mx-1 h-40 min-w-0 rounded-sm has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-4 has-[:focus-visible]: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((tick) => <path d={`M0 ${y(tick)}h100`} class="fill-none stroke-border" vector-effect="non-scaling-stroke" />)}
              {paths.map((path, index) => (
                <path data-line-path d={path} fill="none" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" vector-effect="non-scaling-stroke"
                  stroke-dasharray={fields[index].dashed ? "6 5" : undefined} class={cn(fields[index].color, "origin-bottom motion-safe:transition-[scale,opacity] motion-safe:duration-200 motion-safe:ease-snappy data-[muted]:opacity-0 motion-safe:data-[muted]:scale-y-0")} />
              ))}
            </svg>
            <div data-line-cursor aria-hidden="true" style={`--point:${last.x}cqw`} class="pointer-events-none absolute inset-y-0 left-0 w-0 translate-x-(--point) motion-safe:transition-[translate] motion-safe:duration-150 motion-safe:ease-snappy">
              <span class="absolute inset-y-0 left-0 border-s border-border-strong"></span>
              {fields.map((field, index) => (
                <span data-line-mark hidden={last.values[index].y === null} style={`top:${last.values[index].y ?? 0}%`}
                  class={cn("absolute left-0 size-2.5 -translate-1/2 rounded-full border-2 border-card motion-safe:transition-[top] motion-safe:duration-150 motion-safe:ease-snappy [&[hidden]]:hidden", field.color)}></span>
              ))}
            </div>
            {points.length > 1 && <input data-line-input hidden type="range" min="0" max={points.length - 1} step="1" value={points.length - 1}
              aria-label={`Inspect ${label} by ${categoryLabel}`} class="absolute inset-0 m-0 size-full cursor-crosshair touch-pan-y 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">{last.label}</span>}
          </div>
        </div>
      </div>
    </>
  ) : <p class="text-[0.8125rem]/5 text-muted-foreground">{emptyLabel}</p>}
  {tableRows.length > 0 && fields.length > 0 && (
    <Collapsible title={detailsLabel} class="min-w-0 rounded-lg bg-background/40">
      <Table caption={label} hideCaption columns={tableColumns} rows={tableRows} rowHeader="category" class="min-w-0 rounded-md" />
    </Collapsible>
  )}
</figure>

<script>
  interface Point { label: string; x: number; values: { text: string; y: number | null }[] }
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const plot = root.querySelector<HTMLElement>("[data-line-plot]");
    const cursor = root.querySelector<HTMLElement>("[data-line-cursor]");
    const period = root.querySelector<HTMLElement>("[data-line-period]");
    if (!plot || !cursor || !period) return;
    const points: Point[] = JSON.parse(root.dataset.points ?? "[]");
    if (!points.length) return;
    const input = root.querySelector<HTMLInputElement>("[data-line-input]");
    const choices = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-line-series]"));
    const names = choices.map((choice) => choice.querySelector("[data-series-name]")?.textContent ?? "");
    const readings = root.querySelectorAll<HTMLElement>("[data-line-value]");
    const paths = root.querySelectorAll<SVGPathElement>("[data-line-path]");
    const markers = root.querySelectorAll<HTMLElement>("[data-line-mark]");
    const latest = points.length - 1;
    let active = latest;

    const show = (index: number) => {
      active = index;
      const point = points[active];
      const announced = [point.label];
      period.textContent = point.label;
      cursor.style.setProperty("--point", `${point.x}cqw`);
      point.values.forEach(({ text, y }, series) => {
        const visible = choices[series].getAttribute("aria-pressed") === "true";
        readings[series].textContent = text;
        markers[series].hidden = !visible || y === null;
        if (y !== null) markers[series].style.top = `${y}%`;
        if (visible) announced.push(`${names[series]} ${text}`);
      });
      if (input) {
        input.value = String(active);
        input.setAttribute("aria-valuetext", announced.join(", "));
      }
    };

    if (choices.length > 1) {
      choices.forEach((choice, index) => {
        choice.disabled = false;
        choice.addEventListener("click", () => {
          const visible = choices.filter((button) => button.getAttribute("aria-pressed") === "true");
          const willShow = choice.getAttribute("aria-pressed") !== "true";
          if (!willShow && visible.length === 1) return;
          choice.setAttribute("aria-pressed", String(willShow));
          paths[index].toggleAttribute("data-muted", !willShow);
          const remaining = choices.filter((button) => button.getAttribute("aria-pressed") === "true");
          choices.forEach((button) => button.setAttribute("aria-disabled", String(remaining.length === 1 && button === remaining[0])));
          show(active);
        });
      });
    }
    if (input) {
      input.hidden = false;
      input.addEventListener("input", () => show(Number(input.value)));
      plot.addEventListener("pointermove", (event) => {
        if (event.pointerType === "touch") return;
        const bounds = plot.getBoundingClientRect();
        const ratio = Math.max(0, Math.min(1, (event.clientX - bounds.left) / bounds.width));
        show(Math.round(ratio * latest));
      });
      plot.addEventListener("pointerleave", () => { if (document.activeElement !== input) show(latest); });
      input.addEventListener("blur", () => show(latest));
      input.addEventListener("keydown", (event) => { if (event.key === "Escape") show(latest); });
    }
    show(latest);
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-line-chart]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-line-chart-listener")) {
    document.documentElement.setAttribute("data-haze-line-chart-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
