# Envelope

> An editor for a breakpoint ramp, such as an ADSR shape or an automation curve.

**In Vue**

```tsx
<script lang="ts" setup>
import Envelope from "@/components/audio-ui/envelope/Envelope.vue";

const POINTS = [
  { x: 0, y: 0 },
  { x: 0.15, y: 1 },
  { x: 0.6, y: 0.5 },
  { x: 1, y: 0 },
];
</script>

<template>
  <Envelope aria-label="Envelope" :default-value="POINTS" />
</template>
```

**In Svelte**

```tsx
<script lang="ts">
import Envelope from "$lib/components/audio-ui/envelope/Envelope.svelte";

const POINTS = [
  { x: 0, y: 0 },
  { x: 0.15, y: 1 },
  { x: 0.6, y: 0.5 },
  { x: 1, y: 0 },
];
</script>

<Envelope aria-label="Envelope" defaultValue={POINTS} />
```

**In Web**

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

/** The frame's room for the end points, which the grid's lines are measured from. */
const INSET = "0.875rem";
const STEP = `calc((100% - 2 * ${INSET}) * 0.25)`;

/** Draws the envelope into `element`, and returns what takes it away. Its look is the envelope's sheet; the points and the curve handles are made for you. */
export function envelopeWebDemo(element) {
  element.innerHTML = `
    <div data-size="default" data-slot="envelope-frame" style="background-image: linear-gradient(to right, var(--border) 1px, transparent 1px), linear-gradient(to bottom, var(--border) 1px, transparent 1px); background-position: ${INSET} 0, 0 ${INSET}; background-size: ${STEP} 100%, 100% ${STEP}">
      <audio-ui-envelope aria-label="Envelope" role="group" value='[{"x":0,"y":0},{"x":0.15,"y":1},{"x":0.6,"y":0.5},{"x":1,"y":0}]'>
        <audio-ui-envelope-graph>
          <audio-ui-envelope-fill></audio-ui-envelope-fill>
          <audio-ui-envelope-line></audio-ui-envelope-line>
        </audio-ui-envelope-graph>
      </audio-ui-envelope>
    </div>`;
  return () => {
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { Envelope } from "@/components/audio-ui/envelope";

export function EnvelopeSizeDefaultDemo() {
  return <Envelope aria-label="Envelope" />;
}
```

Edits a ramp made of breakpoints, such as an ADSR shape or an automation curve. The registry component is written on the envelope primitive, which installs with it, and draws the points, the segments between them and a grid.

**In Vue, Svelte and Web**

The envelope's behavior is one file, the primitive, written on the UI SDK kernel and copied into your project. It edits breakpoints, such as an ADSR shape or an automation curve: points to drag, add and remove, and segments to bend. Each framework renders it with a thin adapter that you also own. The gestures, the keys, the grid and the limits on the number of points are the same in all four, and one suite of tests runs against each adapter.

## Overview

- **Value:** `value` is a list of `{ x, y, curve? }` points. Both axes are normalized to 0…1, and the points are sorted by `x`. Map that range to your own unit, such as time or level.
- **Curves:** a point's `curve`, from -1 to 1, bends the segment that leaves it. 0, or no value, draws a straight line. A positive curve holds the start of the segment and steepens its end; a negative curve is its mirror image, rushing the start and holding the end. The bend is the exponential of an analog envelope stage, `(e^(k·t) - 1) / (e^k - 1)` with `k` the curve times 11, so neither end turns vertical. The last point has no segment.
- **Pointer:** drag a point to move it. Double-click empty space to add a point, or double-click a point to remove it. A point stays between its neighbors, so points never cross.
- **Point count:** points are added and removed between `minPoints` (default `2`, a start and an end) and `maxPoints`. Set both to the same number to fix the shape.
- **Grid:** `snap` sets the grid that points snap to, for example `0.25` for quarters, or one step per axis, `{ x: 0.125, y: 0 }`, to snap across and leave the level free. Hold Cmd/Ctrl to move off the grid. Without `snap`, points move freely. The registry component draws the grid.
- **Fine control:** hold Shift while dragging to move a point at a quarter of the pointer's speed. The registry component shows the point's value above it while it is dragged or focused.
- **Accessibility:** the points share one tab stop. The arrow keys move the focused point, Page Up and Page Down (or Home and End) move between points, and Delete or Backspace removes it. Each point is a `role="slider"`. The registry component names the points "Point n of N". With the primitive, set `aria-label` and `getAriaValueText` yourself.

## 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 grid, sizes and themed points, is one command:

**In React**

**CLI**

The styled component, with size variants and theme styles:

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

Or the primitive alone, to style yourself:

```bash
npx shadcn@latest add @audio-ui/envelope-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 styled component with what draws it: 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 envelope
```

Or the primitive alone, to style yourself:

```bash
npx @audio-ui/cli add envelope --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 three files for every framework: `envelope.ts`, the envelope's behavior written on the kernel's helpers; `geometry.ts`, the envelope's points and segments with nothing to draw; and `primitive.ts`, the little every primitive shares. Copy them into `components/audio-ui/` (`src/lib/components/audio-ui/` in Svelte).

<ItemFiles name="envelope-react" to={3} />

### 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="envelope-react" from={3} />

**Vue**

<ItemFiles name="envelope-vue" from={3} />

**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="envelope-svelte" from={3} />

**JavaScript**

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

<ItemFiles name="envelope-web" from={3} />

### 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.

```bash
npm install class-variance-authority
```

<ItemFiles name="envelope" />

**In Vue, Svelte and Web**

### 5. The styled component

Optional: the envelope as the registry draws it in React, with no classes and no Tailwind. Its look is one sheet of plain CSS on its parts, a sheet for each style (`nova`, `vega`, `maia`, `lyra`, `mira`, `luma`, `rhea`, `sera`). Copy the sheet of your style into your project, with the theme's tokens when the page has no shadcn theme.

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

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

By hand:

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

Both are served at `https://www.audio-ui.dev/css/`.

**Vue**

One component over the adapter, with the props of the React envelope: the frame and its grid from `snap`, and the labels of the points and the segments.

<ItemFiles name="envelope-element-vue" />

**Svelte**

One component over the adapter, with the props of the React envelope: the frame and its grid from `snap`, and the labels of the points and the segments.

<ItemFiles name="envelope-element-svelte" />

**JavaScript**

The custom elements make the points and the segments. Wrap `audio-ui-envelope` in the frame the example above writes, `data-slot="envelope-frame"` with `data-size` and the grid as its background.

**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 envelope 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 { Envelope } from "@/components/audio-ui/envelope";
```

**Uncontrolled:** set only the initial points.

```tsx
<Envelope
  defaultValue={[
    { x: 0, y: 0 },
    { x: 0.2, y: 1 },
    { x: 0.6, y: 0.5 },
    { x: 1, y: 0 },
  ]}
/>
```

**Controlled:** drive the points from state.

```tsx
const [points, setPoints] = useState(initialPoints);

<Envelope
  onValueChange={setPoints}
  onValueCommitted={(next, details) => console.log("Committed:", next, details.reason)}
  value={points}
/>
```

**In React**

The primitive alone, part by part:

A Root owns the points. A Graph is the surface they are edited on: it takes the double click that adds a point, and the Alt drag that bends a segment. A Line and a Fill draw the curve and the area under it, each as an `<svg>` stretched over the Graph. A Point is a handle for one point and a Segment a handle on the middle of the stretch between two.

You write a Point for each point and a Segment for each stretch, with their `index`: the Root's content can read its state, whose `value` is the points, so the handles follow the points as they are added and removed. That is a function in React, the default slot in Vue and a snippet in Svelte.

**Give the Graph its size and a position.** The pointer is read against the Graph's box, so a Graph with no height cannot take a click. Make it `position: relative` or `absolute`, and the Line and the Fill, which are absolute, take its box.

**React**

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

export function Amp() {
  const [points, setPoints] = useState([
    { x: 0, y: 0 },
    { x: 0.15, y: 1 },
    { x: 0.6, y: 0.5 },
    { x: 1, y: 0 },
  ]);
  return (
    <Envelope.Root className="relative h-40 w-80" onValueChange={setPoints} value={points}>
      {({ value }) => (
        <>
          <Envelope.Graph className="absolute inset-0 rounded-md bg-muted">
            <Envelope.Fill className="text-primary/20" />
            <Envelope.Line className="text-primary" />
          </Envelope.Graph>
          {value.map((_, index) => (
            <Envelope.Point
              aria-label={`Point ${index + 1}`}
              className="size-3 rounded-full bg-primary"
              index={index}
              key={index}
            />
          ))}
          {value.slice(0, -1).map((_, index) => (
            <Envelope.Segment
              aria-label={`Curve ${index + 1}`}
              className="size-2 rounded-full bg-muted-foreground"
              index={index}
              key={index}
            />
          ))}
        </>
      )}
    </Envelope.Root>
  );
}
```

**Vue**

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

const points = ref([
  { x: 0, y: 0 },
  { x: 0.15, y: 1 },
  { x: 0.6, y: 0.5 },
  { x: 1, y: 0 },
]);
</script>

<template>
  <Envelope.Root class="relative h-40 w-80" :value="points" @value-change="(next) => (points = next)">
    <template #default="{ state }">
      <Envelope.Graph class="absolute inset-0 rounded-md bg-muted">
        <Envelope.Fill class="text-primary/20" />
        <Envelope.Line class="text-primary" />
      </Envelope.Graph>
      <Envelope.Point
        v-for="(_, index) in state.value"
        :key="index"
        :aria-label="`Point ${index + 1}`"
        :index="index"
        class="size-3 rounded-full bg-primary"
      />
      <Envelope.Segment
        v-for="(_, index) in state.value.slice(0, -1)"
        :key="index"
        :aria-label="`Curve ${index + 1}`"
        :index="index"
        class="size-2 rounded-full bg-muted-foreground"
      />
    </template>
  </Envelope.Root>
</template>
```

**Svelte**

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

  let points = $state([
    { x: 0, y: 0 },
    { x: 0.15, y: 1 },
    { x: 0.6, y: 0.5 },
    { x: 1, y: 0 },
  ]);
</script>

<Envelope.Root class="relative h-40 w-80" value={points} onValueChange={(next) => (points = next)}>
  {#snippet children(state)}
    <Envelope.Graph class="absolute inset-0 rounded-md bg-muted">
      <Envelope.Fill class="text-primary/20" />
      <Envelope.Line class="text-primary" />
    </Envelope.Graph>
    {#each state.value as _, index (index)}
      <Envelope.Point aria-label={`Point ${index + 1}`} class="size-3 rounded-full bg-primary" {index} />
    {/each}
    {#each state.value.slice(0, -1) as _, index (index)}
      <Envelope.Segment aria-label={`Curve ${index + 1}`} class="size-2 rounded-full bg-muted-foreground" {index} />
    {/each}
  {/snippet}
</Envelope.Root>
```

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

**JavaScript**

```html
<style>
  audio-ui-envelope { position: relative; width: 20rem; height: 10rem; }
  audio-ui-envelope-graph { position: absolute; inset: 0; background: #eee; }
  audio-ui-envelope-fill { color: #cfe8d6; }
  audio-ui-envelope-line { color: #2f7d4a; }
  audio-ui-envelope-point { width: 12px; height: 12px; border-radius: 50%; background: #2f7d4a; }
  audio-ui-envelope-segment { width: 8px; height: 8px; border-radius: 50%; background: #888; }
</style>

<audio-ui-envelope value='[{"x":0,"y":0},{"x":0.15,"y":1},{"x":0.6,"y":0.5},{"x":1,"y":0}]'>
  <audio-ui-envelope-graph>
    <audio-ui-envelope-fill></audio-ui-envelope-fill>
    <audio-ui-envelope-line></audio-ui-envelope-line>
  </audio-ui-envelope-graph>
</audio-ui-envelope>

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

  document.querySelector("audio-ui-envelope").addEventListener("input", (event) => {
    console.log(event.detail.value, event.detail.reason, event.detail.index);
  });
</script>
```

The envelope makes the Points and the Segments itself, one for each, named "Point 1" and "Curve 1": a double click adds one and removes one, and the markup would not follow. Each part binds a microtask after it connects, all together.

## Interaction

### Pointer

**Behavior**

| Gesture | Effect |
| --- | --- |
| Drag a point | Moves it; `x` stays between its neighbors and `y` within 0…1. Dragging never deletes a point. While dragging, the point follows the pointer even if a controlled `value` updates late. |
| Double-click empty space | Adds a point at that location, unless at `maxPoints`. Added on a bent segment it sits on the curve, and each half is bent to keep its shape. |
| Double-click a point | Removes it, unless at `minPoints`. |
| Hold Shift while dragging a point | Moves it at a quarter of the pointer's speed, for fine adjustments. The point does not jump when Shift is pressed or released mid-drag. |
| Alt + drag a segment | Bends it, like a DAW's automation lane: the segment's midpoint follows the pointer. A flat segment, or a press away from any segment, does nothing. |
| Alt + double-click a segment | Straightens it, instead of adding a point. |
| Alt + click a point | Removes it, unless at `minPoints`. |
| Drag a segment's handle | Bends the segment: its midpoint follows the pointer up or down. A segment between two points of the same level has nothing to bend. |
| Double-click a segment's handle | Straightens the segment. |
| Commit event | `onValueCommitted` fires when a drag that moved a point ends, and right away for an add or a remove. |

A refused add or remove sets `data-blocked` for a moment on the graph or the point, which the registry styles turn into a short shake.

### Keyboard

The points share one tab stop. On the focused point:

**Keys**

| Key | Effect |
| --- | --- |
| `ArrowUp` / `ArrowDown` | Nudge the focused point's `y` by `step` |
| `ArrowLeft` / `ArrowRight` | Nudge the focused point's `x` by `step` (clamped between neighbors) |
| `Shift` + arrow | Nudge by 10 steps |
| `PageUp` / `PageDown` | Move focus to the next or previous point |
| `Home` / `End` | Move focus to the first or last point |
| `Delete` / `Backspace` | Remove the focused point, unless at `minPoints` |

Each segment has a handle on its curve. The handles share one tab stop:

**Keys**

| Key | Effect |
| --- | --- |
| `ArrowLeft` / `ArrowRight` | Move to the previous or next segment's handle |
| `ArrowUp` / `ArrowDown` | Lift or lower the handle, bending the segment by 5 steps |
| `Shift` + arrow | Bend by 50 steps |
| `Delete` / `Backspace` | Straighten the segment |

## API reference

**In React**

### Registry component

`Envelope` accepts style props (`size`, `className`) plus the props of the `Envelope` primitive's Root. `aria-label` / `aria-labelledby` name the envelope group.

#### Value and state

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `value` | `{ x: number; y: number; curve?: number }[]` |  | Controlled points, normalized 0-1, sorted by `x`. `curve`, -1 to 1, bends the segment leaving the point. |
| `defaultValue` | `{ x: number; y: number; curve?: number }[]` | `ADSR-like 5-point shape` | Uncontrolled starting points. Defaults to an ADSR-like shape. |
| `minPoints` | `number` | `2` | Floor on the number of points; removal is blocked at this count. |
| `maxPoints` | `number` |  | Ceiling on the number of points; adding is blocked at this count. Equal to `minPoints`, the shape is fixed. |
| `step` | `number` | `0.01` | Keyboard step on both axes, in normalized units. |
| `disabled` | `boolean` | `false` | Whether the envelope is disabled. |
| `format` | `Intl.NumberFormatOptions` |  | Formats point coordinates for each point's `aria-valuetext`. |
| `onValueChange` | `(points, eventDetails) => void` |  | Fires on every change: drag, keyboard, add and remove. |
| `onValueCommitted` | `(points, eventDetails) => void` |  | Fires when an interaction that changed the points ends. |

#### Layout and display

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `"sm" \| "default" \| "lg"` | `"default"` | Size variant (sets the envelope height). |
| `curves` | `boolean` | `true` | Whether a handle on each segment bends it. |
| `formatValue` | `(point: { x: number; y: number }) => string` | `from the domains` | Prints a point's value in its label and its accessible value text. |
| `xDomain / yDomain` | `[number, number]` | `percent` | The values each axis runs from and to, so the labels read in real units: `xDomain={[0, 2000]}`. |
| `xUnit / yUnit` | `string` |  | The unit written after the value, such as `"ms"` or `"dB"`. |
| `className` | `string` |  | Classes for the graph surface. |

The `Envelope` primitive that installs with it exposes `Envelope.Root`, `Envelope.Graph` (the SVG surface; double-click to add), `Envelope.Line` and `Envelope.Fill` (the curve and the area under it), `Envelope.Point` (the draggable handle) and `Envelope.Segment` (the handle on a segment's midpoint, which bends it). You write one of each per point and per segment, with its `index`, from the Root's children given as a function of its state, whose `value` is the points. Every part accepts a `render` prop and `className` / `style` as functions of state; points expose `data-dragging`, `data-removable`, `data-blocked`, `data-disabled` and `data-index`, and segment handles `data-dragging`, `data-flat` and `data-disabled`.

### Options

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

| Option | Type | Default | |
| --- | --- | --- | --- |
| `value`, `defaultValue` | `{ x, y, curve? }[]` | an ADSR-like shape | The controlled points, or the starting ones. Each is normalized to 0 to 1 on both axes, sorted by `x`, and `curve`, from -1 to 1, bends the stretch that leaves it. |
| `minPoints`, `maxPoints` | `number` | `2`, none | How few and how many points there may be. Equal, the shape is fixed. |
| `snap` | `number` or `{ x, y }` | `0` | The grid the pointer snaps points to, in normalized units: `0.25` snaps to quarters, `0` is no grid, `{ x: 0.125, y: 0 }` snaps across and leaves the level free. |
| `step` | `number` | `0.01` | The keyboard step on both axes. |
| `format`, `locale` | `Intl.NumberFormat` options, a locale | | How a point's coordinates are written for its `aria-valuetext`. |
| `disabled` | `boolean` | `false` | Takes no gesture. |
| `onValueChange` | `(points, details) => void` | | Every change, which `details.cancel()` refuses. |
| `onValueCommitted` | `(points, details) => void` | | The end of a gesture. |

The Line takes a `strokeWidth`, in pixels, which stays the same however the Graph is stretched. A Point takes `getAriaValueText(point, index)` to announce itself in your own words, and a Segment `getAriaValueText(curve, index)`.

### What a change reports

`details` carries what moved the points and how:

- `reason`: `"drag"`, `"keyboard"`, `"add"`, `"remove"` or `"curve"` (a bend).
- `index`: the point or the segment that moved, or the index of the point that was added or removed.
- `source`: `"mouse"`, `"touch"`, `"pen"`, `"keyboard"` or `"programmatic"`, for analytics. It is never a reason to behave differently.
- `event`: the DOM event behind it, when there is one.
- `cancel()`: refuses the change. A controlled envelope keeps the points you give it.

While a pointer drags, the points follow it even if a controlled `value` lags behind.

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

### States to style from

- `data-disabled` on every part. `data-dragging` on the Root, the Graph, the Line and the Fill while a point or a segment is dragged, and on a Point or a Segment only while it is the one dragged.
- `data-blocked` on the Graph, briefly, when an addition was refused, and on a Point when its removal was refused: a feedback to animate. It is raised a frame after the change, so that an animation can play again.
- `data-removable` on a Point while there are more than `minPoints`, and `data-index` on a Point and a Segment.
- `data-flat` and `data-curve` on a Segment.

### Accessibility

A Point is a `role="slider"` on its level, from 0 to 1, and its `aria-valuetext` reads its coordinates, `0.5, 1`, with the format and the locale of the Root. A Segment is a slider on its curve, from -1 to 1. Give each an `aria-label`: the Graph, the Line and the Fill are hidden from assistive technology.

### Parts

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Envelope.Fill` | `svg` | `strokeWidth: number` |
| `Envelope.Graph` | `div` |  |
| `Envelope.Line` | `svg` | `strokeWidth: number` |
| `Envelope.Point` | `div` | `getAriaValueText: value`, `index: key` |
| `Envelope.Root` | `div` |  |
| `Envelope.Segment` | `div` | `getAriaValueText: value`, `index: key` |

**In Web**

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

`audio-ui-envelope`, `audio-ui-envelope-fill`, `audio-ui-envelope-graph`, `audio-ui-envelope-line`, `audio-ui-envelope-point`, `audio-ui-envelope-segment`

### Events

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

**In React**

## Examples

### ADSR with its stages read out

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

/** The span the envelope's x axis stands for, in milliseconds. */
const SPAN_MS = 2000;

const INITIAL_POINTS = [
  { x: 0, y: 0 },
  { x: 0.08, y: 1 },
  { x: 0.28, y: 0.6 },
  { x: 0.72, y: 0.6 },
  { x: 1, y: 0 },
];

const toMs = (share: number) => `${Math.round(share * SPAN_MS)} ms`;

/**
 * An ADSR from five points: the second is the end of the attack, the third
 * the end of the decay, and the fourth the start of the release. The
 * consumer maps the normalized axes to its own units, here milliseconds
 * and a level.
 */
export function EnvelopeAdsrDemo() {
  const [points, setPoints] = useState(INITIAL_POINTS);
  const [, peak, decayEnd, releaseStart] = points;

  return (
    <div className="flex w-full flex-col gap-3">
      <Envelope
        aria-label="ADSR envelope"
        maxPoints={5}
        minPoints={5}
        onValueChange={setPoints}
        value={points}
        xDomain={[0, SPAN_MS]}
        xUnit="ms"
        yDomain={[0, 100]}
        yUnit="%"
      />
      {peak && decayEnd && releaseStart ? (
        <dl className="grid grid-cols-4 gap-2 text-center font-mono text-xs tabular-nums">
          <div>
            <dt className="text-muted-foreground">Attack</dt>
            <dd>{toMs(peak.x)}</dd>
          </div>
          <div>
            <dt className="text-muted-foreground">Decay</dt>
            <dd>{toMs(decayEnd.x - peak.x)}</dd>
          </div>
          <div>
            <dt className="text-muted-foreground">Sustain</dt>
            <dd>{Math.round(decayEnd.y * 100)}%</dd>
          </div>
          <div>
            <dt className="text-muted-foreground">Release</dt>
            <dd>{toMs(1 - releaseStart.x)}</dd>
          </div>
        </dl>
      ) : null}
    </div>
  );
}
```

