# Pad

> A grid of drum pads struck by pointer, touch or keyboard, with velocity and choke groups.

**In Vue**

```tsx
<script lang="ts" setup>
import Pad from "@/components/audio-ui/pad/Pad.vue";
import PadItem from "@/components/audio-ui/pad/PadItem.vue";
import {
  triggerHihat,
  triggerKick,
  triggerSnare,
} from "@/lib/drum-synthesis";
import { webAudio } from "@/lib/web-audio";

const VOLUME = 0.7;
/** How long the open hat rings, in seconds, unless the closed one chokes it. */
const OPEN_HAT_DECAY = 0.6;
/** How fast a choked sound fades out, as a time constant in seconds. */
const CHOKE_FADE = 0.01;

const PADS = [
  { label: "Kick", trigger: triggerKick, value: "kick" },
  { label: "Snare", trigger: triggerSnare, value: "snare" },
  {
    chokeGroup: "hat",
    label: "Closed hat",
    trigger: triggerHihat,
    value: "closed-hat",
  },
  {
    chokeGroup: "hat",
    label: "Open hat",
    trigger: (ctx: AudioContext, destination: AudioNode, time: number) =>
      triggerHihat(ctx, destination, time, { decay: OPEN_HAT_DECAY }),
    value: "open-hat",
  },
];

// The hits each pad still has ringing, so a choke can silence them.
const ringing = new Map<string, GainNode[]>();

/** Each hit goes through a gain of its own: how hard the pad was struck. */
function strike(value: string, details: { velocity: number }) {
  const ctx = webAudio.resume();
  const pad = PADS.find((item) => item.value === value);
  if (!(ctx && pad)) {
    return;
  }
  const hit = ctx.createGain();
  hit.gain.value = details.velocity * VOLUME;
  hit.connect(ctx.destination);
  pad.trigger(ctx, hit, ctx.currentTime);
  if (pad.chokeGroup) {
    ringing.set(value, [...(ringing.get(value) ?? []), hit]);
  }
}

/** Drum hits ring on after the pad is released: only a choke stops them. */
function choke(value: string, details: { reason: string }) {
  const ctx = webAudio.resume();
  if (!ctx || details.reason !== "choke") {
    return;
  }
  for (const hit of ringing.get(value) ?? []) {
    hit.gain.setTargetAtTime(0, ctx.currentTime, CHOKE_FADE);
  }
  ringing.delete(value);
}
</script>

<template>
  <Pad
    aria-label="Drum pads"
    style="max-width: 14rem"
    :columns="2"
    @pad-off="choke"
    @pad-on="strike"
  >
    <PadItem
      v-for="pad in PADS"
      :key="pad.value"
      :choke-group="pad.chokeGroup"
      :value="pad.value"
    >
      {{ pad.label }}
    </PadItem>
  </Pad>
</template>
```

**In Svelte**

```tsx
<script lang="ts">
import Pad from "$lib/components/audio-ui/pad/Pad.svelte";
import PadItem from "$lib/components/audio-ui/pad/PadItem.svelte";
import {
  triggerHihat,
  triggerKick,
  triggerSnare,
} from "@/lib/drum-synthesis";
import { webAudio } from "@/lib/web-audio";

const VOLUME = 0.7;
/** How long the open hat rings, in seconds, unless the closed one chokes it. */
const OPEN_HAT_DECAY = 0.6;
/** How fast a choked sound fades out, as a time constant in seconds. */
const CHOKE_FADE = 0.01;

const PADS = [
  { label: "Kick", trigger: triggerKick, value: "kick" },
  { label: "Snare", trigger: triggerSnare, value: "snare" },
  {
    chokeGroup: "hat",
    label: "Closed hat",
    trigger: triggerHihat,
    value: "closed-hat",
  },
  {
    chokeGroup: "hat",
    label: "Open hat",
    trigger: (ctx: AudioContext, destination: AudioNode, time: number) =>
      triggerHihat(ctx, destination, time, { decay: OPEN_HAT_DECAY }),
    value: "open-hat",
  },
];

// The hits each pad still has ringing, so a choke can silence them.
const ringing = new Map<string, GainNode[]>();

/** Each hit goes through a gain of its own: how hard the pad was struck. */
function strike(value: string, details: { velocity: number }) {
  const ctx = webAudio.resume();
  const pad = PADS.find((item) => item.value === value);
  if (!(ctx && pad)) {
    return;
  }
  const hit = ctx.createGain();
  hit.gain.value = details.velocity * VOLUME;
  hit.connect(ctx.destination);
  pad.trigger(ctx, hit, ctx.currentTime);
  if (pad.chokeGroup) {
    ringing.set(value, [...(ringing.get(value) ?? []), hit]);
  }
}

/** Drum hits ring on after the pad is released: only a choke stops them. */
function choke(value: string, details: { reason: string }) {
  const ctx = webAudio.resume();
  if (!ctx || details.reason !== "choke") {
    return;
  }
  for (const hit of ringing.get(value) ?? []) {
    hit.gain.setTargetAtTime(0, ctx.currentTime, CHOKE_FADE);
  }
  ringing.delete(value);
}
</script>

<Pad
  aria-label="Drum pads"
  columns={2}
  onPadOff={choke}
  onPadOn={strike}
  style="max-width: 14rem"
>
  {#each PADS as pad (pad.value)}
    <PadItem chokeGroup={pad.chokeGroup} value={pad.value}>
      {pad.label}
    </PadItem>
  {/each}
</Pad>
```

**In Web**

```tsx
import {
  triggerHihat,
  triggerKick,
  triggerSnare,
} from "@/lib/drum-synthesis";
import { webAudio } from "@/lib/web-audio";
import "@/components/audio-ui/pad/web";

const VOLUME = 0.7;
/** How long the open hat rings, in seconds, unless the closed one chokes it. */
const OPEN_HAT_DECAY = 0.6;
/** How fast a choked sound fades out, as a time constant in seconds. */
const CHOKE_FADE = 0.01;

const PADS = [
  { label: "Kick", trigger: triggerKick, value: "kick" },
  { label: "Snare", trigger: triggerSnare, value: "snare" },
  {
    chokeGroup: "hat",
    label: "Closed hat",
    trigger: triggerHihat,
    value: "closed-hat",
  },
  {
    chokeGroup: "hat",
    label: "Open hat",
    trigger: (ctx, destination, time) =>
      triggerHihat(ctx, destination, time, { decay: OPEN_HAT_DECAY }),
    value: "open-hat",
  },
];

// The hits each pad still has ringing, so a choke can silence them.
const ringing = new Map();

/** Each hit goes through a gain of its own: how hard the pad was struck. */
function strike(value, details) {
  const ctx = webAudio.resume();
  const pad = PADS.find((item) => item.value === value);
  if (!(ctx && pad)) {
    return;
  }
  const hit = ctx.createGain();
  hit.gain.value = details.velocity * VOLUME;
  hit.connect(ctx.destination);
  pad.trigger(ctx, hit, ctx.currentTime);
  if (pad.chokeGroup) {
    ringing.set(value, [...(ringing.get(value) ?? []), hit]);
  }
}

/** Drum hits ring on after the pad is released: only a choke stops them. */
function choke(value, details) {
  const ctx = webAudio.resume();
  if (!ctx || details.reason !== "choke") {
    return;
  }
  for (const hit of ringing.get(value) ?? []) {
    hit.gain.setTargetAtTime(0, ctx.currentTime, CHOKE_FADE);
  }
  ringing.delete(value);
}

/** Draws the pads into `element`, and returns what takes them away. */
export function padWebDemo(element) {
  element.innerHTML = `
    <audio-ui-pad aria-label="Drum pads" columns="2" style="--pad-columns: 2; max-width: 14rem">
      ${PADS.map(
        (pad) =>
          `<audio-ui-pad-item ${pad.chokeGroup ? `choke-group="${pad.chokeGroup}"` : ""} value="${pad.value}"><button>${pad.label}</button></audio-ui-pad-item>`
      ).join("")}
    </audio-ui-pad>`;
  const grid = element.querySelector("audio-ui-pad");
  const on = (event) => {
    const { value, velocity } = event.detail;
    strike(value, { velocity });
  };
  const off = (event) => {
    const { value, reason } = event.detail;
    choke(value, { reason });
  };
  grid?.addEventListener("padon", on);
  grid?.addEventListener("padoff", off);
  return () => {
    grid?.removeEventListener("padon", on);
    grid?.removeEventListener("padoff", off);
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { useCallback, useRef } from "react";
import { Pad, PadItem } from "@/components/audio-ui/pad";
import { useMasterBus } from "@/hooks/use-master-bus";
import {
  triggerHihat,
  triggerKick,
  triggerSnare,
} from "@/lib/drum-synthesis";
import { webAudio } from "@/lib/web-audio";
import type {
  PadOffDetails,
  PadOnDetails,
} from "@/components/audio-ui/pad/core";

const VOLUME = 0.7;
/** How long the open hat rings, in seconds, unless the closed one chokes it. */
const OPEN_HAT_DECAY = 0.6;
/** How fast a choked sound fades out, as a time constant in seconds. */
const CHOKE_FADE = 0.01;

type Trigger = (
  ctx: AudioContext,
  destination: AudioNode,
  time: number
) => void;

const PADS: {
  chokeGroup?: string;
  label: string;
  trigger: Trigger;
  value: string;
}[] = [
  { label: "Kick", trigger: triggerKick, value: "kick" },
  { label: "Snare", trigger: triggerSnare, value: "snare" },
  {
    chokeGroup: "hat",
    label: "Closed hat",
    trigger: triggerHihat,
    value: "closed-hat",
  },
  {
    chokeGroup: "hat",
    label: "Open hat",
    trigger: (ctx, destination, time) =>
      triggerHihat(ctx, destination, time, { decay: OPEN_HAT_DECAY }),
    value: "open-hat",
  },
];

/** Four drum pads: strike harder near the top. The closed hat cuts the open one short, as on a drum machine. */
export function PadDemo() {
  const master = useMasterBus(VOLUME);
  // The hits each pad still has ringing, so a choke can silence them.
  const ringing = useRef(new Map<string, GainNode[]>());

  const strike = useCallback(
    (value: string, details: PadOnDetails) => {
      const ctx = webAudio.resume();
      const pad = PADS.find((item) => item.value === value);
      if (!(ctx && master && pad)) {
        return;
      }
      // Each hit goes through a gain of its own: how hard the pad was struck.
      const hit = ctx.createGain();
      hit.gain.value = details.velocity;
      hit.connect(master);
      pad.trigger(ctx, hit, ctx.currentTime);
      if (pad.chokeGroup) {
        ringing.current.set(value, [
          ...(ringing.current.get(value) ?? []),
          hit,
        ]);
      }
    },
    [master]
  );

  // Drum hits ring on after the pad is released: only a choke stops them.
  const choke = useCallback((value: string, details: PadOffDetails) => {
    const ctx = webAudio.resume();
    if (!ctx || details.reason !== "choke") {
      return;
    }
    for (const hit of ringing.current.get(value) ?? []) {
      hit.gain.setTargetAtTime(0, ctx.currentTime, CHOKE_FADE);
    }
    ringing.current.delete(value);
  }, []);

  return (
    <Pad
      aria-label="Drum pads"
      className="max-w-56"
      columns={2}
      onPadOff={choke}
      onPadOn={strike}
    >
      {PADS.map((pad) => (
        <PadItem chokeGroup={pad.chokeGroup} key={pad.value} value={pad.value}>
          {pad.label}
        </PadItem>
      ))}
    </Pad>
  );
}
```

Triggers sounds, for a drum machine, a sampler or a clip launcher. The registry component is written on the pad primitive, which installs with it, and lays the pads out in a grid of `columns`.

**In Vue, Svelte and Web**

The pad grid's behavior is one file, the primitive, written on the UI SDK kernel and copied into your project. A pad sounds while it is held, by pointer or from the keyboard. Each framework renders it with a thin adapter that you also own, and one suite of tests runs against each adapter.

## Overview

- **Events:** `onPadOn(value, eventDetails)` and `onPadOff(value, eventDetails)` report the pad's `value`, ready for an audio engine. `eventDetails.velocity` says how hard it was struck, from 0 to 1, and `eventDetails.cancel()` in `onPadOn` keeps the pad silent.
- **Velocity:** a pen or a pressure-sensitive screen strikes as hard as it presses. Other pointers strike harder toward the top of the pad. The keyboard strikes at `0.8`. Each pad exposes its last velocity as `--pad-velocity`, so the flash can follow it.
- **Choke groups:** pads sharing a `chokeGroup` stop each other, like a closed hihat cutting an open one. Striking one fires `onPadOff` with `reason: "choke"` for the last pad struck in its group, held or still ringing.
- **Pointer:** each pointer holds its own pad, so several play at once on a touch screen. Sliding off a pad does not strike the next one.
- **External pads:** `activePads` lights pads from outside, such as the steps of a sequencer, without calling `onPadOn` or `onPadOff`.
- **Accessibility:** each pad is a button named by its content, behind one tab stop. The arrow keys move between pads, and Space or Enter holds the focused pad until it is released.

## 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, laid out in a grid of `columns`, is one command:

**In React**

**CLI**

The styled component, with size variants and theme styles:

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

Or the primitive alone, to style yourself:

```bash
npx shadcn@latest add @audio-ui/pad-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 pad
```

Or the primitive alone, to style yourself:

```bash
npx @audio-ui/cli add pad --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: `pad.ts`, the pad grid'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="pad-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="pad-react" from={2} />

**Vue**

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

**Svelte**

The parts, made from the primitive in `parts.ts`, and an `index.ts` that names them. Svelte keeps its files under `src/lib`, so the primitive goes in `src/lib/components/audio-ui/` too.

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

**JavaScript**

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

<ItemFiles name="pad-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="pad" />

**In Vue, Svelte and Web**

### 5. The styled component

Optional: the pads 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 pad
```

By hand:

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

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

**Vue**

Two components over the adapter, `Pad` and `PadItem`, with the props of the React pads.

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

**Svelte**

Two components over the adapter, `Pad` and `PadItem`, with the props of the React pads.

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

**JavaScript**

The custom elements take the same sheet. Set `--pad-columns` on `audio-ui-pad` to its `columns`, as the styled component does.

**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 pad 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 { Pad, PadItem } from "@/components/audio-ui/pad";
```

**Pad events:**

```tsx
<Pad
  aria-label="Drum pads"
  columns={2}
  onPadOn={(value, { velocity }) => sampler.trigger(value, velocity)}
>
  <PadItem value="kick">Kick</PadItem>
  <PadItem value="snare">Snare</PadItem>
</Pad>
```

**Choke groups (a closed hat cuts the open one):**

```tsx
<Pad
  aria-label="Hats"
  columns={2}
  onPadOff={(value, { reason }) => {
    if (reason === "choke") {
      sampler.stop(value);
    }
  }}
  onPadOn={(value, { velocity }) => sampler.trigger(value, velocity)}
>
  <PadItem chokeGroup="hat" value="closed-hat">
    Closed hat
  </PadItem>
  <PadItem chokeGroup="hat" value="open-hat">
    Open hat
  </PadItem>
</Pad>
```

**In React**

The primitive alone, part by part:

A Root groups the pads, and an Item is one pad, a `<button>` identified by its `value`. Write an Item for each pad, in reading order: the order they have in the document is the order the arrow keys walk.

**React**

```tsx
import { Pad } from "@/components/audio-ui/pad/react";

const KIT = ["Kick", "Snare", "Hat", "Clap"];

export function Drums({ play }: { play: (name: string, velocity: number) => void }) {
  return (
    <Pad.Root className="grid grid-cols-2 gap-2" columns={2} onPadOn={(value, { velocity }) => play(value, velocity)}>
      {KIT.map((name) => (
        <Pad.Item className="size-20 rounded-md bg-muted data-active:bg-primary" key={name} value={name}>
          {name}
        </Pad.Item>
      ))}
    </Pad.Root>
  );
}
```

**Vue**

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

const kit = ["Kick", "Snare", "Hat", "Clap"];
const emit = defineEmits<{ play: [name: string, velocity: number] }>();
</script>

<template>
  <Pad.Root class="grid grid-cols-2 gap-2" :columns="2" @pad-on="(value, { velocity }) => emit('play', value, velocity)">
    <Pad.Item v-for="name in kit" :key="name" :value="name" class="size-20 rounded-md bg-muted data-active:bg-primary">
      {{ name }}
    </Pad.Item>
  </Pad.Root>
</template>
```

**Svelte**

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

  const kit = ["Kick", "Snare", "Hat", "Clap"];
  let { play }: { play: (name: string, velocity: number) => void } = $props();
</script>

<Pad.Root class="grid grid-cols-2 gap-2" columns={2} onPadOn={(value, { velocity }) => play(value, velocity)}>
  {#each kit as name (name)}
    <Pad.Item class="size-20 rounded-md bg-muted data-active:bg-primary" value={name}>{name}</Pad.Item>
  {/each}
</Pad.Root>
```

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

**JavaScript**

```html
<audio-ui-pad columns="2">
  <audio-ui-pad-item value="Kick"><button>Kick</button></audio-ui-pad-item>
  <audio-ui-pad-item value="Snare"><button>Snare</button></audio-ui-pad-item>
  <audio-ui-pad-item value="Hat"><button>Hat</button></audio-ui-pad-item>
  <audio-ui-pad-item value="Clap"><button>Clap</button></audio-ui-pad-item>
</audio-ui-pad>

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

  const grid = document.querySelector("audio-ui-pad");
  grid.addEventListener("padon", (event) => play(event.detail.value, event.detail.velocity));
</script>
```

In the web adapter, an Item wraps the button: the button inside it is the pad. The two callbacks are the `padon` and `padoff` events.

### What a strike reports

- `onPadOn` gets `velocity` from 0 to 1, a `reason` (`"press"` or `"keyboard"`), a `source` (`"mouse"`, `"touch"`, `"pen"` or `"keyboard"`) and the `event`.
- `onPadOff` gets a `reason`: `"press"`, `"keyboard"`, or `"choke"` when another pad of its group cut it.

## Interaction

### Pointer

**Behavior**

| Gesture | Effect |
| --- | --- |
| Press a pad | Fires `onPadOn` with a velocity; the pad stays active while held. |
| Release | Fires `onPadOff`. |
| Multiple pointers | Each pointer (finger) holds its own pad, so several play at once on touch devices. |

### Keyboard

The pads share one tab stop. On the focused pad:

**Keys**

| Key | Effect |
| --- | --- |
| `ArrowLeft` / `ArrowRight` | Move focus to the previous / next pad in reading order |
| `ArrowUp` / `ArrowDown` | Move focus a row up / down |
| `Space` / `Enter` | Hold the focused pad: `onPadOn` on press, `onPadOff` on release |
| `Home` / `End` | Move focus to the first / last pad |

## API reference

**In React**

### Registry component

`Pad` accepts `className` and `style` plus the props of the `Pad` primitive's Root, and sets the grid's columns from `columns`. `PadItem` accepts the props of the primitive's `Pad.Item`.

Additional valid HTML attributes passed to `Pad.Root` and `Pad.Item` are forwarded.

### Options

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

| Option | Type | Default | |
| --- | --- | --- | --- |
| `columns` | `number` | `4` | How many pads a row holds: what the up and down arrows move by. Lay the grid out to match. |
| `activePads` | `string[]` | | Pads lit from elsewhere, such as a sequencer or a MIDI input, on top of the ones held here. |
| `disabled` | `boolean` | `false` | Strikes nothing. |
| `onPadOn` | `(value, details) => void` | | A pad is struck. `details.cancel()` keeps it silent. |
| `onPadOff` | `(value, details) => void` | | A pad is released, loses focus while held, or is choked. |

An Item takes its `value`, a `disabled`, and a `chokeGroup`: pads that share one stop each other, so striking one stops the last one struck, held or still ringing, as an open and a closed hi-hat do.

### States to style from

- `data-active` on a pad while it sounds, held here or listed in `activePads`, and `data-disabled` on the Root and the pads.
- `--pad-velocity` on a pad, from 0 to 1: how hard it was last struck, for a flash that follows the force.

### Parts

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Pad.Item` | `button` | `chokeGroup: string`, `disabled: boolean`, `value: key` |
| `Pad.Root` | `div` |  |

**In Web**

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

`audio-ui-pad`, `audio-ui-pad-item`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |
| `onPadOff` | `@pad-off` | `padoff` |
| `onPadOn` | `@pad-on` | `padon` |

**In React**

## Examples

### Drum rack

Sixteen pads, each its own sound: strike a pad to play and select it, then shape it with the knobs. The three hihats share a choke group.

```tsx
import { useCallback, useRef, useState } from "react";
import { Knob } from "@/components/audio-ui/knob";
import { Pad, PadItem } from "@/components/audio-ui/pad";
import { useMasterBus } from "@/hooks/use-master-bus";
import {
  type DrumOptions,
  triggerHihat,
  triggerKick,
  triggerSnare,
} from "@/lib/drum-synthesis";
import { webAudio } from "@/lib/web-audio";
import type {
  PadOffDetails,
  PadOnDetails,
} from "@/components/audio-ui/pad/core";

const VOLUME = 0.7;
/** How fast a choked sound fades out, as a time constant in seconds. */
const CHOKE_FADE = 0.01;

const VOICES = { hat: triggerHihat, kick: triggerKick, snare: triggerSnare };

interface Sound {
  chokeGroup?: string;
  /** Seconds. */
  decay: number;
  id: string;
  label: string;
  /** Gain, from 0 to 1. */
  level: number;
  /** Semitones from the voice's own pitch. */
  tune: number;
  voice: keyof typeof VOICES;
}

/** Sixteen sounds from three voices, four to a row. The hats share a choke group. */
const KIT: Sound[] = [
  { decay: 0.2, id: "kick", label: "Kick", level: 0.9, tune: 0, voice: "kick" },
  { decay: 0.45, id: "sub", label: "Sub", level: 0.8, tune: -5, voice: "kick" },
  {
    decay: 0.15,
    id: "snare",
    label: "Snare",
    level: 0.8,
    tune: 0,
    voice: "snare",
  },
  { decay: 0.04, id: "rim", label: "Rim", level: 0.7, tune: 7, voice: "snare" },
  {
    decay: 0.3,
    id: "low-tom",
    label: "Low tom",
    level: 0.8,
    tune: 7,
    voice: "kick",
  },
  {
    decay: 0.25,
    id: "mid-tom",
    label: "Mid tom",
    level: 0.8,
    tune: 12,
    voice: "kick",
  },
  {
    decay: 0.22,
    id: "clap",
    label: "Clap",
    level: 0.8,
    tune: -3,
    voice: "snare",
  },
  {
    decay: 0.06,
    id: "snap",
    label: "Snap",
    level: 0.7,
    tune: 12,
    voice: "snare",
  },
  {
    chokeGroup: "hat",
    decay: 0.05,
    id: "closed-hat",
    label: "Closed hat",
    level: 0.7,
    tune: 0,
    voice: "hat",
  },
  {
    chokeGroup: "hat",
    decay: 0.03,
    id: "pedal-hat",
    label: "Pedal hat",
    level: 0.6,
    tune: -3,
    voice: "hat",
  },
  {
    chokeGroup: "hat",
    decay: 0.6,
    id: "open-hat",
    label: "Open hat",
    level: 0.6,
    tune: 0,
    voice: "hat",
  },
  {
    decay: 0.09,
    id: "shaker",
    label: "Shaker",
    level: 0.5,
    tune: 5,
    voice: "hat",
  },
  {
    decay: 0.2,
    id: "high-tom",
    label: "High tom",
    level: 0.8,
    tune: 17,
    voice: "kick",
  },
  {
    decay: 0.05,
    id: "perc",
    label: "Perc",
    level: 0.7,
    tune: 24,
    voice: "kick",
  },
  { decay: 1.2, id: "ride", label: "Ride", level: 0.4, tune: -7, voice: "hat" },
  {
    decay: 1.8,
    id: "crash",
    label: "Crash",
    level: 0.45,
    tune: -12,
    voice: "hat",
  },
];

const formatTune = (tune: number) => `${tune > 0 ? "+" : ""}${tune} st`;
const formatDecay = (seconds: number) =>
  seconds < 1 ? `${Math.round(seconds * 1000)} ms` : `${seconds.toFixed(2)} s`;
const formatLevel = (level: number) => `${Math.round(level * 100)}%`;

/**
 * A drum rack: sixteen pads, each its own sound. Strike a pad to play it and
 * select it, then shape it with the knobs: tune, decay and level. Strikes are
 * harder near the top of a pad; the hats cut each other short.
 */
export function BlockDrumRack() {
  const [kit, setKit] = useState(KIT);
  const kitRef = useRef(kit);
  kitRef.current = kit;
  const [selected, setSelected] = useState(0);
  const master = useMasterBus(VOLUME);
  // The hits each pad still has ringing, so a choke can silence them.
  const ringing = useRef(new Map<string, GainNode[]>());

  const strike = useCallback(
    (id: string, details: PadOnDetails) => {
      const ctx = webAudio.resume();
      const index = kitRef.current.findIndex((item) => item.id === id);
      const sound = kitRef.current[index];
      if (!(ctx && master && sound)) {
        return;
      }
      setSelected(index);
      // Each hit goes through a gain of its own: how hard it was struck, at the pad's level.
      const hit = ctx.createGain();
      hit.gain.value = details.velocity * sound.level;
      hit.connect(master);
      const options: DrumOptions = { decay: sound.decay, tune: sound.tune };
      VOICES[sound.voice](ctx, hit, ctx.currentTime, options);
      if (sound.chokeGroup) {
        ringing.current.set(id, [...(ringing.current.get(id) ?? []), hit]);
      }
    },
    [master]
  );

  // Drum hits ring on after the pad is released: only a choke stops them.
  const choke = useCallback((id: string, details: PadOffDetails) => {
    const ctx = webAudio.resume();
    if (!ctx || details.reason !== "choke") {
      return;
    }
    for (const hit of ringing.current.get(id) ?? []) {
      hit.gain.setTargetAtTime(0, ctx.currentTime, CHOKE_FADE);
    }
    ringing.current.delete(id);
  }, []);

  const edit = useCallback(
    (change: Partial<Pick<Sound, "decay" | "level" | "tune">>) =>
      setKit((current) =>
        current.map((item, index) =>
          index === selected ? { ...item, ...change } : item
        )
      ),
    [selected]
  );
  const setTune = useCallback((tune: number) => edit({ tune }), [edit]);
  const setDecay = useCallback((decay: number) => edit({ decay }), [edit]);
  const setLevel = useCallback((level: number) => edit({ level }), [edit]);

  const sound = kit[selected] ?? KIT[0];
  const factory = KIT[selected] ?? KIT[0];

  return (
    <div className="rounded-xl @container/panel w-full min-w-0 border bg-card p-4">
      <div className="mx-auto flex w-full max-w-96 flex-col gap-4 @2xl/panel:max-w-none @2xl/panel:flex-row">
        <section
          aria-label={`${sound.label} settings`}
          className="flex min-w-0 flex-1 flex-col"
        >
          <div className="flex flex-wrap items-start justify-around gap-4">
            <div className="flex flex-col items-center gap-1.5">
              <span
                aria-hidden="true"
                className="text-muted-foreground text-xs"
              >
                Tune
              </span>
              <Knob
                anchor={0}
                aria-label={`${sound.label} tune`}
                defaultValue={factory.tune}
                formatValue={formatTune}
                max={12}
                min={-12}
                onValueChange={setTune}
                step={1}
                value={sound.tune}
                valueLabel="always"
              />
            </div>
            <div className="flex flex-col items-center gap-1.5">
              <span
                aria-hidden="true"
                className="text-muted-foreground text-xs"
              >
                Decay
              </span>
              <Knob
                aria-label={`${sound.label} decay`}
                defaultValue={factory.decay}
                formatValue={formatDecay}
                max={2}
                min={0.02}
                onValueChange={setDecay}
                scale="log"
                step={0.001}
                value={sound.decay}
                valueLabel="always"
              />
            </div>
            <div className="flex flex-col items-center gap-1.5">
              <span
                aria-hidden="true"
                className="text-muted-foreground text-xs"
              >
                Level
              </span>
              <Knob
                aria-label={`${sound.label} level`}
                defaultValue={factory.level}
                formatValue={formatLevel}
                max={1}
                min={0}
                onValueChange={setLevel}
                step={0.01}
                value={sound.level}
                valueLabel="always"
              />
            </div>
          </div>
        </section>
        <Pad
          aria-label="Drum rack"
          className="w-full shrink-0 @2xl/panel:w-96"
          columns={4}
          onPadOff={choke}
          onPadOn={strike}
        >
          {kit.map((item, index) => (
            <PadItem
              chokeGroup={item.chokeGroup}
              className="data-[selected]:ring-2 data-[selected]:ring-primary/40"
              data-selected={index === selected ? "" : undefined}
              key={item.id}
              value={item.id}
            >
              {item.label}
            </PadItem>
          ))}
        </Pad>
      </div>
    </div>
  );
}
```

