# Plot

> Curves and draggable points, for equalizers, filters and compressors.

**In Vue**

```tsx
<script lang="ts" setup>
import { ref } from "vue";
import { Plot } from "@/components/audio-ui/plot/vue";

const peak = ref({ x: 1000, y: 6 });
const response = (hz: number, point: { x: number; y: number }) =>
  point.y * Math.exp(-(Math.log2(hz / point.x) ** 2));
const curve = (hz: number) => response(hz, peak.value);
</script>

<template>
  <Plot.Root
    scale-x="log"
    :max-x="20_000"
    :max-y="12"
    :min-x="20"
    :min-y="-12"
    @value-change="(point) => { peak = point; }"
  >
    <Plot.Grid
      :x="{ ticks: [100, 1000, 10_000] }"
      :y="{ ticks: [-12, 0, 12] }"
    />
    <div data-slot="plot-graph">
      <Plot.Curve :fill-to="0" :fn="curve" />
      <Plot.Curve :fn="curve" />
    </div>
    <Plot.Handle aria-label="Peak" handle="peak" :value="peak" />
  </Plot.Root>
</template>
```

**In Svelte**

```tsx
<script lang="ts">
import { Plot } from "$lib/components/audio-ui/plot/svelte";

let peak = $state({ x: 1000, y: 6 });
const response = (hz: number, point: { x: number; y: number }) =>
  point.y * Math.exp(-(Math.log2(hz / point.x) ** 2));
const curve = (hz: number) => response(hz, peak);
</script>

<Plot.Root
  maxX={20_000}
  maxY={12}
  minX={20}
  minY={-12}
  onValueChange={(point) => {
    peak = point;
  }}
  scaleX="log"
>
  <Plot.Grid x={{ ticks: [100, 1000, 10_000] }} y={{ ticks: [-12, 0, 12] }} />
  <div data-slot="plot-graph">
    <Plot.Curve fillTo={0} fn={curve} />
    <Plot.Curve fn={curve} />
  </div>
  <Plot.Handle aria-label="Peak" handle="peak" value={peak} />
</Plot.Root>
```

**In Web**

```tsx
import "@/components/audio-ui/plot/web";

const response = (hz, point) =>
  point.y * Math.exp(-(Math.log2(hz / point.x) ** 2));

/** Draws the plot into `element`, and returns what takes it away. A curve is a function, so it is set as a property. */
export function plotWebDemo(element) {
  element.innerHTML = `
    <audio-ui-plot max-x="20000" max-y="12" min-x="20" min-y="-12" scale-x="log">
      <audio-ui-plot-grid></audio-ui-plot-grid>
      <div data-slot="plot-graph">
        <audio-ui-plot-curve fill-to="0"></audio-ui-plot-curve>
        <audio-ui-plot-curve></audio-ui-plot-curve>
      </div>
      <audio-ui-plot-handle aria-label="Peak" handle="peak" value='{"x":1000,"y":6}'></audio-ui-plot-handle>
    </audio-ui-plot>`;
  let peak = { x: 1000, y: 6 };
  const plot = element.querySelector("audio-ui-plot");
  const handle = element.querySelector("audio-ui-plot-handle");
  const grid = element.querySelector("audio-ui-plot-grid");
  const curves = [...element.querySelectorAll("audio-ui-plot-curve")];
  const draw = () => {
    for (const curve of curves) {
      curve.fn = (hz) => response(hz, peak);
    }
  };
  if (grid) {
    grid.x = { ticks: [100, 1000, 10_000] };
    grid.y = { ticks: [-12, 0, 12] };
  }
  draw();
  const onInput = (event) => {
    peak = event.detail.value;
    handle?.setAttribute("value", JSON.stringify(peak));
    draw();
  };
  plot?.addEventListener("input", onInput);
  return () => {
    plot?.removeEventListener("input", onInput);
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import {
  Select,
  SelectContent,
  SelectGroup,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  type BiquadType,
  bandGainForHandle,
  bandHandleDb,
  biquadResponse,
  type EqBand,
  eqResponse,
} from "@/lib/engine/analysis";
import { formatFrequency, formatLevel } from "@/lib/engine/format";
import { Knob } from "@/components/audio-ui/knob";
import {
  Plot,
  PlotArea,
  PlotCursor,
  PlotCurve,
  PlotGraph,
  PlotGrid,
  PlotHandle,
  PlotTraceArea,
  useValueAtPointer,
} from "@/components/audio-ui/plot";
import { useSpectrum } from "@/hooks/use-spectrum";
import { useNoiseThroughEq } from "@/hooks/use-noise-through-eq";

type Band = EqBand & { id: number };

const BANDS: Band[] = [
  { frequency: 90, gainDb: 3, id: 1, type: "lowshelf" },
  { frequency: 1200, gainDb: -4, id: 2, q: 1.2, type: "peak" },
  { frequency: 7000, gainDb: 5, id: 3, type: "highshelf" },
];
const MAX_BANDS = 8;
/** How far a press may move and still count as a click, in pixels. */
const CLICK_TOLERANCE = 4;
const NEW_BAND_Q = 1;
const MIN_HZ = 20;
const MAX_HZ = 20_000;
const MAX_DB = 18;
const MIN_Q = 0.3;
const MAX_Q = 12;
/** How far one unit of wheel delta widens or narrows a band, as an exponent. */
const WHEEL_Q_SENSITIVITY = 0.002;
/** The scale the spectrum is drawn on, in dB of level: its own, behind the gain axis. */
const SPECTRUM_MIN_DB = -100;
const SPECTRUM_MAX_DB = -10;
const DB_TICKS = [-12, 0, 12];
/** What a band can be, from the bottom of the spectrum up. */
const BAND_TYPES: { label: string; value: BiquadType }[] = [
  { label: "Low cut", value: "lowcut" },
  { label: "Low shelf", value: "lowshelf" },
  { label: "Bell", value: "peak" },
  { label: "Notch", value: "notch" },
  { label: "High shelf", value: "highshelf" },
  { label: "High cut", value: "highcut" },
];
/** The width a band has when it was never given one. */
const DEFAULT_Q = Math.SQRT1_2;

const formatDbMark = (db: number) =>
  formatLevel(db, "dB", { decimals: 0, unit: false });
const describePointer = (point: { x: number; y: number }) =>
  `${formatFrequency(point.x)} · ${formatLevel(point.y)}`;
const describeValue = (value: number, axis: "x" | "y") =>
  axis === "x" ? formatFrequency(value) : formatLevel(value);
const clampGain = (gainDb: number) =>
  Math.min(MAX_DB, Math.max(-MAX_DB, gainDb));

interface BandHandleProps {
  active: boolean;
  bands: readonly EqBand[];
  editing: boolean;
  index: number;
  onChange: (index: number, patch: Partial<EqBand>) => void;
  onEdit: (index: number | null) => void;
  onRemove: (index: number) => void;
  onSelect: (index: number) => void;
}

interface BandAdderProps {
  bands: readonly EqBand[];
  onAdd: (frequency: number, gainDb: number) => void;
}

/** The plot's empty space: double-click it to add a band there, so its handle lands under the pointer. */
function BandAdder({ bands, onAdd }: BandAdderProps) {
  const valueAt = useValueAtPointer();
  const handleDoubleClick = useCallback(
    (event: React.MouseEvent) => {
      const point = valueAt(event.clientX, event.clientY);
      if (!point) {
        return;
      }
      // The gain that puts a new bell's handle at the pointer, on top of what is already there.
      const gainDb = point.y - eqResponse(bands)(point.x);
      onAdd(point.x, clampGain(gainDb));
    },
    [bands, onAdd, valueAt]
  );
  // A mouse gesture with a keyboard equivalent: the handles' own Enter-free
  // path is the keyboard add below the plot.
  return (
    // biome-ignore lint/a11y/noStaticElementInteractions: a pointer shortcut; adding a band has its own button.
    <div className="absolute inset-0" onDoubleClick={handleDoubleClick} />
  );
}

interface BandEditorProps {
  band: EqBand;
  index: number;
  onChange: (index: number, patch: Partial<EqBand>) => void;
}

const formatQ = (q: number) => `Q ${q.toFixed(1)}`;

/** What a band is and how wide: its type, and its Q on a logarithmic knob. */
function BandEditor({ band, index, onChange }: BandEditorProps) {
  const handleTypeChange = useCallback(
    (type: BiquadType | null) => {
      if (type) {
        onChange(index, { type });
      }
    },
    [index, onChange]
  );
  const handleWidthChange = useCallback(
    (q: number) => onChange(index, { q }),
    [index, onChange]
  );

  return (
    <div className="flex items-center justify-between gap-4">
      <div className="flex flex-col gap-2">
        <span className="font-medium text-xs">Band {index + 1}</span>
        <Select
          items={BAND_TYPES}
          onValueChange={handleTypeChange}
          value={band.type}
        >
          <SelectTrigger
            aria-label={`Band ${index + 1} type`}
            className="w-28"
            size="sm"
          >
            <SelectValue />
          </SelectTrigger>
          <SelectContent>
            <SelectGroup>
              {BAND_TYPES.map((item) => (
                <SelectItem key={item.value} value={item.value}>
                  {item.label}
                </SelectItem>
              ))}
            </SelectGroup>
          </SelectContent>
        </Select>
      </div>
      <Knob
        aria-label={`Band ${index + 1} width`}
        className="mb-5"
        formatValue={formatQ}
        max={MAX_Q}
        min={MIN_Q}
        onValueChange={handleWidthChange}
        scale="log"
        size="sm"
        step={0.01}
        value={band.q ?? DEFAULT_Q}
        valueLabel="always"
      />
    </div>
  );
}

/**
 * One band's handle. It sits on the equalizer's curve, so it follows the
 * pointer one to one; the wheel widens or narrows the band, and a
 * double-click flattens it.
 */
function BandHandle({
  active,
  bands,
  editing,
  index,
  onChange,
  onEdit,
  onRemove,
  onSelect,
}: BandHandleProps) {
  const ref = useRef<HTMLDivElement>(null);
  const band = bands[index];
  const q = band?.q;

  // Attached natively: React listens to wheel passively, so it could not
  // stop the page from scrolling while the wheel widens the band.
  useEffect(() => {
    const element = ref.current;
    if (!element) {
      return;
    }
    const handleWheel = (event: WheelEvent) => {
      event.preventDefault();
      onSelect(index);
      const next = (q ?? 1) * Math.exp(-event.deltaY * WHEEL_Q_SENSITIVITY);
      onChange(index, { q: Math.min(MAX_Q, Math.max(MIN_Q, next)) });
    };
    element.addEventListener("wheel", handleWheel, { passive: false });
    return () => element.removeEventListener("wheel", handleWheel);
  }, [index, onChange, onSelect, q]);

  const handleChange = useCallback(
    ({ x, y }: { x: number; y: number }) => {
      onSelect(index);
      onChange(index, {
        frequency: x,
        gainDb: clampGain(bandGainForHandle(bands, index, x, y)),
      });
    },
    [bands, index, onChange, onSelect]
  );
  const reset = useCallback(
    () => onChange(index, { gainDb: 0 }),
    [index, onChange]
  );
  const handleKeyDown = useCallback(
    (event: React.KeyboardEvent) => {
      if (event.key === "Delete" || event.key === "Backspace") {
        event.preventDefault();
        onRemove(index);
      } else if (event.key === "Enter") {
        event.preventDefault();
        onSelect(index);
        onEdit(index);
      }
    },
    [index, onEdit, onRemove, onSelect]
  );
  // A press that stays where it started is a click, not a drag: it opens the band's settings.
  const pressRef = useRef<{ x: number; y: number } | null>(null);
  const handlePointerDown = useCallback((event: React.PointerEvent) => {
    pressRef.current = { x: event.clientX, y: event.clientY };
  }, []);
  const handlePointerUp = useCallback(
    (event: React.PointerEvent) => {
      const start = pressRef.current;
      pressRef.current = null;
      if (
        start &&
        Math.hypot(event.clientX - start.x, event.clientY - start.y) <
          CLICK_TOLERANCE
      ) {
        onSelect(index);
        onEdit(index);
      }
    },
    [index, onEdit, onSelect]
  );
  // A right-click, or a long press on a touch screen, opens it too.
  const handleContextMenu = useCallback(
    (event: React.MouseEvent) => {
      event.preventDefault();
      onSelect(index);
      onEdit(index);
    },
    [index, onEdit, onSelect]
  );
  const handleOpenChange = useCallback(
    (open: boolean) => {
      onEdit(open ? index : null);
      if (!open) {
        // The popover took the focus: hand it back to the handle.
        ref.current?.querySelector("input")?.focus();
      }
    },
    [index, onEdit]
  );

  return (
    <Popover onOpenChange={handleOpenChange} open={editing}>
      <PlotHandle
        aria-label={`Band ${index + 1}`}
        data-selected={active || undefined}
        getAriaValueText={describeValue}
        onContextMenu={handleContextMenu}
        onDoubleClick={reset}
        onKeyDown={handleKeyDown}
        onPointerDown={handlePointerDown}
        onPointerUp={handlePointerUp}
        onValueChange={handleChange}
        ref={ref}
        value={{
          x: band?.frequency ?? MIN_HZ,
          y: bandHandleDb(bands, index),
        }}
      >
        <PopoverTrigger
          nativeButton={false}
          render={
            <span
              aria-hidden="true"
              className="pointer-events-none absolute inset-0"
            />
          }
        />
      </PlotHandle>
      <PopoverContent
        align="center"
        className="w-60 p-3"
        side="top"
        sideOffset={12}
      >
        {band ? (
          <BandEditor band={band} index={index} onChange={onChange} />
        ) : null}
      </PopoverContent>
    </Popover>
  );
}

/**
 * An equalizer. Each band's handle sits on the curve: drag it to set the
 * band's frequency and gain, scroll over it to widen or narrow the band,
 * double-click to flatten it. The selected band's own curve is drawn in
 * the foreground, the others faintly.
 */
export function PlotDemo() {
  const [bands, setBands] = useState<Band[]>(BANDS);
  const nextId = useRef(BANDS.length + 1);
  const [selectedRaw, setSelected] = useState(1);
  const [editing, setEditing] = useState<number | null>(null);
  const selected = Math.min(selectedRaw, Math.max(0, bands.length - 1));
  const response = useMemo(() => eqResponse(bands), [bands]);
  const bandCurves = useMemo(
    () => bands.map((item) => biquadResponse(item)),
    [bands]
  );
  const addBand = useCallback((frequency: number, gainDb: number) => {
    setBands((current) => {
      if (current.length >= MAX_BANDS) {
        return current;
      }
      nextId.current += 1;
      setSelected(current.length);
      return [
        ...current,
        {
          frequency,
          gainDb,
          id: nextId.current,
          q: NEW_BAND_Q,
          type: "peak",
        },
      ];
    });
  }, []);
  const removeBand = useCallback((index: number) => {
    setBands((current) => current.filter((_, at) => at !== index));
    setSelected((current) =>
      Math.max(0, current > index ? current - 1 : current)
    );
  }, []);
  const changeBand = useCallback((index: number, patch: Partial<EqBand>) => {
    setBands((current) =>
      current.map((other, at) =>
        at === index ? { ...other, ...patch } : other
      )
    );
  }, []);
  const { analyser } = useNoiseThroughEq(bands);
  const spectrum = useSpectrum(analyser, { maxHz: MAX_HZ, minHz: MIN_HZ });

  return (
    <div className="flex w-full flex-col gap-2">
      <Plot
        className="h-40"
        maxX={MAX_HZ}
        maxY={MAX_DB}
        minX={MIN_HZ}
        minY={-MAX_DB}
        scaleX="log"
      >
        <PlotCursor format={describePointer} />
        <PlotGrid
          x={{ count: 6 }}
          y={{ format: formatDbMark, ticks: DB_TICKS }}
        />
        <BandAdder bands={bands} onAdd={addBand} />
        <PlotGraph>
          <PlotTraceArea
            fillTo={SPECTRUM_MIN_DB}
            max={SPECTRUM_MAX_DB}
            min={SPECTRUM_MIN_DB}
            source={spectrum}
          />
          {bandCurves.map((curve, index) => (
            <PlotCurve
              className={
                index === selected
                  ? "stroke-primary/60 [stroke-dasharray:3_3]"
                  : "stroke-foreground/10"
              }
              fn={curve}
              // The bands never come or go, so their order is their identity.
              // biome-ignore lint/suspicious/noArrayIndexKey: fixed list.
              key={index}
            />
          ))}
          <PlotArea fillTo={0} fn={response} />
          <PlotCurve fn={response} />
        </PlotGraph>
        {bands.map((item, index) => (
          <BandHandle
            active={index === selected}
            bands={bands}
            editing={index === editing}
            index={index}
            key={item.id}
            onChange={changeBand}
            onEdit={setEditing}
            onRemove={removeBand}
            onSelect={setSelected}
          />
        ))}
      </Plot>
    </div>
  );
}
```

An equalizer, a filter response or a compressor curve: a surface with two axes, on which you draw curves and live traces and place draggable handles in the axes' units. The registry component is written on the plot primitive, which installs with it.

**In Vue, Svelte and Web**

The plot's behavior is one file, the primitive, written on the UI SDK kernel and copied into your project. It is a surface with two axes, each a range and a scale (linear, logarithmic or your own), on which you place curves, live traces, lines, bands, a grid, dots, marks and draggable handles in the axes' units: an EQ curve over `20` to `20000` Hz and `-12` to `12` dB is written in hertz and decibels. Each framework renders it with a thin adapter that you also own, and one suite of tests runs against each adapter.

## Installation

The primitives are built on the [UI SDK](https://ui-sdk.dev) kernel, in beta. Nothing of ours comes from npm: the primitive and its adapter are files you copy into your project and own, and the only packages are the kernel's. The commands name its version, `@ui-sdk/*@0.1.0-beta.14`.

**In React**

The styled component, with a frame, a graph layer and themed parts, is one command:

For the equalizer above, with its pink noise and spectrum, ready to run: `npx shadcn@latest add @audio-ui/plot-demo`.

**In React**

**CLI**

The styled component, with size variants and theme styles:

```bash
npx shadcn@latest add @audio-ui/plot
```

Or the primitive alone, to style yourself:

```bash
npx shadcn@latest add @audio-ui/plot-react
```

It writes the primitive, its adapter and `primitive.ts` into `components/audio-ui/` and installs the kernel's packages and what each file imports. The optional styles are one more command:

```bash
npx shadcn@latest add @audio-ui/primitives-css
```

**In Vue, Svelte and Web**

**CLI**

The [CLI](/docs/cli) finds your framework in `package.json` and writes the primitive, its adapter, `primitive.ts` and the sheet of your style, with an index to import once. It installs the kernel's packages:

```bash
npx @audio-ui/cli add plot
```

Or the parts alone, to style yourself:

```bash
npx @audio-ui/cli add plot --headless
```

**manual**

### 1. The kernel

**React**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/react@0.1.0-beta.14
```

**Vue**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/vue@0.1.0-beta.14 vue
```

**Svelte**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/svelte@0.1.0-beta.14 svelte
```

**JavaScript**

```bash
npm install @ui-sdk/core@0.1.0-beta.14 @ui-sdk/web@0.1.0-beta.14
```

### 2. The primitive

The same two files for every framework: `plot.ts`, the plot's behavior written on the kernel's helpers, and `primitive.ts`, the little every primitive shares. Copy them into `components/audio-ui/` (`src/lib/components/audio-ui/` in Svelte).

<ItemFiles name="plot-react" to={2} />

### 3. The adapter

Your framework's few parts, over the primitive. They import it by a relative path, from the same folder, so keep the files as shown, or update the path.

**React**

<ItemFiles name="plot-react" from={2} />

**Vue**

<ItemFiles name="plot-vue" from={2} />

**Svelte**

A component per part, and an `index.ts` that gathers them. Svelte keeps its files under `src/lib`, so the primitive goes in `src/lib/components/audio-ui/` too.

<ItemFiles name="plot-svelte" from={2} />

**JavaScript**

Import it once, and it registers the `audio-ui-plot` tags.

<ItemFiles name="plot-web" from={2} />

### 4. The styles

Optional, and the same for every framework: the anatomy of the primitives, drawn flat and square, in the look of the UI SDK docs. It reads the tokens of the UI SDK stylesheet (`--ui-*`) when the page has it, and falls back to its own. Every rule is in the `ui-sdk` layer, so a rule of yours outside the layer wins.

<ItemFiles name="primitives-css" />

Import it once.

**In React**

### 5. The styled component

Optional: size variants and theme styles over the primitive.

<ItemFiles name="plot" />

**In Vue, Svelte and Web**

### 5. The styles

Optional: the plot as the registry draws it in React, with no classes and no Tailwind. Its look is one sheet of plain CSS on the adapter's own parts, a sheet for each style (`nova`, `vega`, `maia`, `lyra`, `mira`, `luma`, `rhea`, `sera`): compose the parts as the example above does, and the sheet draws them. Only what you write yourself carries a slot of yours: `data-slot="plot-graph"` on the layer that clips the curves, and `data-slot="plot-cursor-line"` with its `data-orientation` on each line of the cursor.

The [CLI](/docs/cli) writes the adapter, the sheet and an index to import once:

```bash
npx @audio-ui/cli add plot
```

By hand:

```html
<link rel="stylesheet" href="/css/theme.css" />
<link rel="stylesheet" href="/css/nova/plot.css" />
```

Both are served at `https://www.audio-ui.dev/css/`, with the skins in `/css/skins/`.

**agent**

Paste this prompt to your agent. It does the rest: it installs the skill, adds the component and wires it to your audio.

```text
Install the audio/ui skill with `npx skills add ouestlabs/audio-ui`, then follow it to add the plot from audio/ui to my project and wire it to my audio code. Read the docs at https://www.audio-ui.dev/llms.txt first.
```

To let the agent read the docs live, connect the [MCP server](/docs/mcp). More in [Agent Skill](/docs/agents).

## Usage

**In React**

```tsx
import {
  Plot,
  PlotArea,
  PlotCurve,
  PlotGraph,
  PlotGrid,
  PlotHandle,
} from "@/components/audio-ui/plot";
import { eqResponse } from "@/lib/engine/analysis";

<Plot minX={20} maxX={20000} minY={-18} maxY={18} scaleX="log">
  <PlotGrid x={{ count: 6 }} y={{ ticks: [-12, 0, 12] }} />
  <PlotGraph>
    <PlotArea fillTo={0} fn={response} />
    <PlotCurve fn={response} />
  </PlotGraph>
  <PlotHandle
    aria-label="Band 1"
    onValueChange={({ x, y }) => setBand({ frequency: x, gainDb: y })}
    value={{ x: band.frequency, y: band.gainDb }}
  />
</Plot>;
```

`fn` is `y = fn(x)` in the axes' units. `@/lib/engine/analysis` gives you the functions for the usual curves: `eqResponse`, `biquadResponse` and `compressorOutput`, and for keeping a band's handle on the curve, `bandHandleDb` (where it sits) and `bandGainForHandle` (the gain that puts it where the pointer is).

**In React**

The primitive alone, part by part:

A Root is the surface. Everything you put in it is placed by value, not by pixel:

- **Grid**: lines and labels along each axis.
- **Curve**: a function of x, drawn as a path.
- **Trace**: a live list of values, drawn straight in the DOM.
- **Line**, **Band**, **Mark**, **Dot**: a value or a range on an axis, a point.
- **Handle**: a draggable point with a native `<input type="range">` for each axis it moves on, so the keys and a screen reader work.
- **Cursor** and **CursorReadout**: a marker that follows the pointer, and the text of the value under it.

**React**

```tsx
import { useState } from "react";
import { Plot } from "@/components/audio-ui/plot/react";

export function Eq() {
  const [peak, setPeak] = useState({ x: 1000, y: 6 });
  const response = (hz: number) => peak.y * Math.exp(-(Math.log2(hz / peak.x) ** 2));

  return (
    <Plot.Root
      className="h-48 w-full"
      maxX={20_000}
      maxY={12}
      minX={20}
      minY={-12}
      onValueChange={setPeak}
      scaleX="log"
    >
      <Plot.Grid className="text-muted" x={{ ticks: [100, 1000, 10_000] }} y={{ ticks: [-12, 0, 12] }} />
      <Plot.Curve className="text-primary" fn={response} />
      <Plot.Handle aria-label="Peak" className="size-3 rounded-full bg-primary" handle="peak" value={peak} />
    </Plot.Root>
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import { ref } from "vue";
import { Plot } from "@/components/audio-ui/plot/vue";

const peak = ref({ x: 1000, y: 6 });
const response = (hz: number) => peak.value.y * Math.exp(-(Math.log2(hz / peak.value.x) ** 2));
</script>

<template>
  <Plot.Root
    class="h-48 w-full"
    :max-x="20000"
    :max-y="12"
    :min-x="20"
    :min-y="-12"
    scale-x="log"
    @value-change="(point) => (peak = point)"
  >
    <Plot.Grid class="text-muted" :x="{ ticks: [100, 1000, 10000] }" :y="{ ticks: [-12, 0, 12] }" />
    <Plot.Curve class="text-primary" :fn="response" />
    <Plot.Handle aria-label="Peak" class="size-3 rounded-full bg-primary" handle="peak" :value="peak" />
  </Plot.Root>
</template>
```

**Svelte**

```svelte
<script lang="ts">
  import { Plot } from "$lib/components/audio-ui/plot/svelte";

  let peak = $state({ x: 1000, y: 6 });
  const response = (hz: number) => peak.y * Math.exp(-(Math.log2(hz / peak.x) ** 2));
</script>

<Plot.Root class="h-48 w-full" maxX={20_000} maxY={12} minX={20} minY={-12} onValueChange={(point) => (peak = point)} scaleX="log">
  <Plot.Grid class="text-muted" x={{ ticks: [100, 1000, 10_000] }} y={{ ticks: [-12, 0, 12] }} />
  <Plot.Curve class="text-primary" fn={response} />
  <Plot.Handle aria-label="Peak" class="size-3 rounded-full bg-primary" handle="peak" value={peak} />
</Plot.Root>
```

With the latest SvelteKit, import through `#lib` in place of `$lib`: `#lib/components/audio-ui/plot/svelte`.

**JavaScript**

```html
<audio-ui-plot min-x="20" max-x="20000" min-y="-12" max-y="12" scale-x="log" style="display: block; height: 12rem">
  <audio-ui-plot-grid></audio-ui-plot-grid>
  <audio-ui-plot-curve></audio-ui-plot-curve>
  <audio-ui-plot-handle handle="peak" default-value='{"x":1000,"y":6}' aria-label="Peak"></audio-ui-plot-handle>
</audio-ui-plot>

<script type="module">
  import "./audio-ui/plot/web.ts";

  const plot = document.querySelector("audio-ui-plot");
  plot.querySelector("audio-ui-plot-grid").x = { ticks: [100, 1000, 10000] };
  const curve = plot.querySelector("audio-ui-plot-curve");
  const draw = ({ x, y }) => {
    curve.fn = (hz) => y * Math.exp(-(Math.log2(hz / x) ** 2));
  };
  draw({ x: 1000, y: 6 });
  plot.addEventListener("input", (event) => draw(event.detail.value));
</script>
```

In the web adapter, what is not text is a property, not an attribute: a Curve's `fn`, a Trace's `source`, a Grid's `x` and `y`, a CursorReadout's `format`. A Dot's and a Handle's `value` can be a JSON attribute. Each part binds a microtask after it connects: read the element's state after that.

### Live traces and dots

A Trace takes a `source`, a live list of values (a spectrum, a waveform) in the shape of an external store: `getSnapshot()` returns the values and `subscribe(listener)` is called on each frame. Its path is written straight onto the DOM, so a spectrum at 60 frames renders nothing. A Dot takes a `value` or a `source` of a point the same way. Any object with those two methods works, with nothing to install, and the registry's `useSpectrum` gives you one over an analyser.

**In React**

## Handles

A handle holds a native `<input type="range">` per axis, so it works from the keyboard: the arrow keys move it by a hundredth of the axis, a tenth with <kbd>Shift</kbd>, and <kbd>Home</kbd> / <kbd>End</kbd> go to the ends. Dragging moves it from where it is rather than jumping to the pointer, and four times finer with <kbd>Shift</kbd>. A double click, an <kbd>Alt</kbd> + click or <kbd>Delete</kbd> return it to `defaultValue`, or the middle of the plot (`reason: "reset"`). `axis="x"` or `axis="y"` holds it to one axis.

**In React**

## Live signals

`PlotTrace` draws a list of y values from a `source` straight in the DOM, with no React render per frame: the spectrum of the sound behind an equalizer, on a scale of its own (`min`, `max`). `PlotDot` is a point that follows a live `{ x, y }`, such as the input level riding a compressor's curve. The `use-spectrum` hook turns an `AnalyserNode` into the source a trace wants, resampled onto a logarithmic frequency axis, and the default example plays pink noise through the equalizer so you hear what you draw.

```tsx
const spectrum = useSpectrum(analyser, { minHz: 20, maxHz: 20000 });

<PlotGraph>
  <PlotTraceArea fillTo={-100} min={-100} max={-10} source={spectrum} />
  <PlotCurve fn={response} />
</PlotGraph>;
```

The hook's options are in [Analysis](/docs/guides/analysis#spectrum).

## Interaction

**Handles**

- A press and a drag move the point on the axes it has (`axis` is `"both"`, `"x"` or `"y"`). Shift with a drag moves it finely, Alt with a press or Delete returns it to its `defaultValue`.
- On a handle's inputs, the arrows move it by a small step, Shift with an arrow by a large one, Home and End go to the ends of the range.

**Cursor**

- It follows a mouse or a pen over the plot, and sets `data-active` while the pointer is on it. It takes no touch, which would scroll.
- Its `--plot-cursor-x` and `--plot-cursor-y` CSS variables hold its place, in percent.

A disabled plot takes none of these.

## API reference

**In React**

### Registry component

`PlotCursor` takes a `format` function, `(value) => string`, for its readout; `PlotTraceArea` is a `Trace` drawn as a filled area. The rest take the primitive's props.

### Options

Set on the Root, as props (an attribute in kebab case in the web adapter).

| Option | Type | Default | |
| --- | --- | --- | --- |
| `minX`, `maxX`, `minY`, `maxY` | `number` | `0`, `1` | The range of each axis, in your units. |
| `scaleX`, `scaleY` | `"linear"`, `"log"` or `{ to, from }` | `"linear"` | How values spread along an axis: a `{ to, from }` pair maps values into an even space and back. |
| `disabled` | `boolean` | `false` | Takes no gesture. |
| `onValueChange` | `(value, details) => void` | | A handle moved. `details.cancel()` refuses it. |
| `onValueCommitted` | `(value, details) => void` | | A handle's gesture, key or input ended. |

A Handle takes `handle` (its name), `axis`, `value` or `defaultValue` (`{ x, y }`) and `disabled`. A Grid takes `x` and `y`, each `{ ticks, count, labels, format }`. A Curve takes `fn` and `fillTo`, and a Trace `source`, `min`, `max` and `fillTo`. A Line and a Mark take `axis` and `value`, a Band `axis`, `from` and `to`.

### What a change reports

`details` carries:

- `handle`: the name of the handle that moved, since one plot holds several.
- `reason`: what moved it, `"drag"`, `"keyboard"`, `"input-change"` or `"reset"`.
- `source`: `"mouse"`, `"touch"`, `"pen"`, `"keyboard"`, `"programmatic"` or `"agent"`.
- `event` and `cancel()`: the DOM event behind it, and the refusal. A controlled handle keeps the value you give it.

In the web adapter, `onValueChange` is an `input` event and `onValueCommitted` a `change` event, with `detail: { handle, value, reason, source }`, and `event.preventDefault()` refuses a change.

### Styling

The parts draw geometry and carry no look of their own: until you style them, a Curve is a filled black shape, the grid lines have no stroke and the labels sit at the corner of their value. The examples above give a Curve `text-primary`, which only colors it once the path has a stroke. A starting point, in plain CSS, that you then own:

```css
[data-slot="plot"] { color: #555; }
[data-slot="plot-curve"] path { fill: none; stroke: currentColor; stroke-width: 2; }
[data-slot="plot-grid"] [data-part="line"] { stroke: #ddd; }
[data-slot="plot-grid"] [data-part="line"][data-zero] { stroke: #aaa; }
[data-slot="plot-grid"] [data-part="label"][data-axis="x"] { bottom: 4px; transform: translateX(-50%); }
[data-slot="plot-grid"] [data-part="label"][data-axis="y"] { left: 6px; transform: translateY(-50%); }
```

The registry's styled `plot` element already carries these.

### States to style from

- `data-dragging` on a handle while it is held, `data-handle` for its name and `data-axis` for the axes it moves on.
- `data-active` on the Cursor while the pointer is over the plot.
- `data-fill` on a Curve or a Trace given `fillTo`: an area, to draw apart from a line.
- `data-disabled` on every part.

### Parts

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Plot.Band` | `svg` | `axis: string`, `from: number`, `to: number` |
| `Plot.Cursor` | `div` |  |
| `Plot.CursorReadout` | `div` | `format: value` |
| `Plot.Curve` | `svg` | `fillTo: number`, `fn: value`, `samples: number` |
| `Plot.Dot` | `div` | `source: value`, `value: value` |
| `Plot.Grid` | `div` | `x: value`, `y: value` |
| `Plot.Handle` | `div` | `axis: string`, `defaultValue: value`, `disabled: boolean`, `handle: key`, `value: value` |
| `Plot.Line` | `svg` | `axis: string`, `value: number` |
| `Plot.Mark` | `div` | `axis: string`, `value: number` |
| `Plot.Root` | `div` |  |
| `Plot.Trace` | `svg` | `fillTo: number`, `max: number`, `min: number`, `source: value` |

**In Web**

The tags the web adapter registers: the inputs inside a part are made for you.

`audio-ui-plot`, `audio-ui-plot-band`, `audio-ui-plot-cursor`, `audio-ui-plot-cursor-readout`, `audio-ui-plot-curve`, `audio-ui-plot-dot`, `audio-ui-plot-grid`, `audio-ui-plot-handle`, `audio-ui-plot-input-x`, `audio-ui-plot-input-y`, `audio-ui-plot-line`, `audio-ui-plot-mark`, `audio-ui-plot-trace`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |
| `onValueChange` | `@value-change` | `input` |
| `onValueCommitted` | `@value-committed` | `change` |

