# Piano

> A piano keyboard for a MIDI pitch range, played with the pointer, touch or the keyboard.

**In Vue**

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

<template>
  <Piano aria-label="Piano" :max-pitch="72" :min-pitch="48" />
</template>
```

**In Svelte**

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

<Piano aria-label="Piano" maxPitch={72} minPitch={48} />
```

**In Web**

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

const MIN_PITCH = 48;
const MAX_PITCH = 72;

/** Draws the keyboard into `element`, and returns what takes it away. Its look is the piano's sheet, on its parts and attributes. */
export function pianoWebDemo(element) {
  const keys = Array.from(
    { length: MAX_PITCH - MIN_PITCH + 1 },
    (_, index) =>
      `<audio-ui-piano-key pitch="${MIN_PITCH + index}"><button></button></audio-ui-piano-key>`
  ).join("");
  element.innerHTML = `
    <audio-ui-piano aria-label="Piano" data-size="default" min-pitch="${MIN_PITCH}" max-pitch="${MAX_PITCH}">${keys}</audio-ui-piano>`;
  return () => {
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { Piano } from "@/components/audio-ui/piano";
import { useMidiInput } from "@/hooks/use-midi-input";

/** A keyboard from C3 to C5. With a MIDI keyboard connected, the keys you hold on it light up here. */
export function PianoSizeDefaultDemo() {
  const midi = useMidiInput();
  return (
    <Piano
      activeNotes={midi.activeNotes}
      aria-label="Piano"
      maxPitch={72}
      minPitch={48}
    />
  );
}
```

Plays or shows notes, for a virtual instrument, a MIDI visualizer or a chord reference. The registry component is written on the piano primitive, which installs with it, and draws white and black keys for any MIDI range.

**In Vue, Svelte and Web**

The piano's behavior is one file, the primitive, written on the UI SDK kernel and copied into your project. A key sounds while it is pressed, by pointer or from the keyboard, and dragging across the keys glides from one to the next. Each framework renders it with a thin adapter that you also own, and one suite of tests runs against each adapter.

## Overview

- **Range:** `minPitch` and `maxPitch` are MIDI pitches (default `48` and `72`, C3 to C5), or `pitches` lists the exact keys to show. Key colors and layout follow the chromatic pattern.
- **Events:** `onNoteOn(pitch, eventDetails)` and `onNoteOff(pitch, eventDetails)` report MIDI pitches, ready for an audio engine. `eventDetails.reason` says how the note started (`"press"`, `"glide"` or `"keyboard"`), and `eventDetails.cancel()` in `onNoteOn` keeps the key silent.
- **Pointer:** press and hold a key to hold its note. Drag across keys for a glissando: each key plays as the pointer crosses it. Each touch holds its own key, so chords work on a touch screen.
- **External notes:** `activeNotes` lights keys from outside, such as a MIDI input or a sequencer's current chord, without calling `onNoteOn` or `onNoteOff`.
- **Accessibility:** each key is a button named after its pitch ("C4"), behind one tab stop. The arrow keys move between keys, and Space or Enter holds the focused key until it is released.
- **Layout:** the primitive can also lay keys out vertically (`orientation="vertical"`, lowest key at the bottom) or in equal widths (`layout="even"`). The piano roll's keyboard uses this.

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

**In React**

**CLI**

The styled component, with size variants and theme styles:

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

Or the primitive alone, to style yourself:

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

Or the primitive alone, to style yourself:

```bash
npx @audio-ui/cli add piano --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: `piano.ts`, the piano's behavior written on the kernel's helpers; `pitch.ts`, the note names it labels its keys with, which the piano roll shares; and `primitive.ts`, the little every primitive shares. Copy them into `components/audio-ui/` (`src/lib/components/audio-ui/` in Svelte).

<ItemFiles name="piano-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="piano-react" from={3} />

**Vue**

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

**Svelte**

The label's component, 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="piano-svelte" from={3} />

**JavaScript**

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

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

**In Vue, Svelte and Web**

### 5. The styled component

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

By hand:

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

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

**Vue**

One component over the adapter, with the props of the React piano.

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

**Svelte**

One component over the adapter, with the props of the React piano.

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

**JavaScript**

The custom elements take the same sheet. Set `data-size` on `audio-ui-piano`, 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 piano 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 { Piano } from "@/components/audio-ui/piano";
```

**Note events:**

```tsx
<Piano
  maxPitch={72}
  minPitch={48}
  onNoteOff={(pitch) => synth.release(pitch)}
  onNoteOn={(pitch) => synth.trigger(pitch)}
/>
```

**External notes (MIDI input, a sequencer's current chord):**

```tsx
<Piano activeNotes={midiInputNotes} maxPitch={72} minPitch={48} />
```

**A MIDI keyboard:** `useMidiInput` listens to the page's MIDI input. Browsers ask for permission, so connect it from a click: with `requestAccess`, or the ready-made button, `npx shadcn@latest add @audio-ui/midi-connect-control`.

```tsx
import { useMidiInput } from "@/hooks/use-midi-input";

const midi = useMidiInput({
  onNoteOff: (pitch) => synth.release(pitch),
  onNoteOn: (pitch, velocity) => synth.trigger(pitch, velocity),
});

<button onClick={midi.requestAccess} type="button">Connect MIDI</button>
<Piano activeNotes={midi.activeNotes} maxPitch={72} minPitch={48} />
```

Everything `useMidiInput` gives is in [Input](/docs/guides/input).

**In React**

The primitive alone, part by part:

A Root is the keyboard, and a Key is one key, a `<button>` placed along it for its `pitch` and named by its note, such as "C4". A Label inside a Key writes that name for you to style. You write a Key for each pitch: the Root's content can read the state, whose `pitches` lists them lowest first, so the keys follow `minPitch`, `maxPitch` and `pitches`. That is a function in React, the default slot in Vue and a snippet in Svelte.

**Give the Root its size.** The keys are placed with percentages, so a Root with no height or width has nothing to place them in.

**React**

```tsx
import { Piano } from "@/components/audio-ui/piano/react";

export function Keys({ on, off }: { on: (pitch: number, velocity: number) => void; off: (pitch: number) => void }) {
  return (
    <Piano.Root
      className="relative h-32 w-96"
      maxPitch={72}
      minPitch={60}
      onNoteOff={off}
      onNoteOn={(pitch, { velocity }) => on(pitch, velocity)}
    >
      {({ pitches }) =>
        pitches.map((pitch) => (
          <Piano.Key
            className="rounded-b border bg-background data-[color=black]:z-10 data-[color=black]:h-2/3 data-[color=black]:bg-foreground data-active:bg-primary"
            key={pitch}
            pitch={pitch}
          />
        ))
      }
    </Piano.Root>
  );
}
```

**Vue**

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

const emit = defineEmits<{ on: [pitch: number, velocity: number]; off: [pitch: number] }>();
</script>

<template>
  <Piano.Root
    class="relative h-32 w-96"
    :max-pitch="72"
    :min-pitch="60"
    @note-off="(pitch) => emit('off', pitch)"
    @note-on="(pitch, { velocity }) => emit('on', pitch, velocity)"
  >
    <template #default="{ state }">
      <Piano.Key
        v-for="pitch in state.pitches"
        :key="pitch"
        :pitch="pitch"
        class="rounded-b border bg-background data-[color=black]:z-10 data-[color=black]:h-2/3 data-[color=black]:bg-foreground data-active:bg-primary"
      />
    </template>
  </Piano.Root>
</template>
```

**Svelte**

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

  let { on, off }: { on: (pitch: number, velocity: number) => void; off: (pitch: number) => void } = $props();
</script>

<Piano.Root
  class="relative h-32 w-96"
  maxPitch={72}
  minPitch={60}
  onNoteOff={off}
  onNoteOn={(pitch, { velocity }) => on(pitch, velocity)}
>
  {#snippet children(state)}
    {#each state.pitches as pitch (pitch)}
      <Piano.Key class="rounded-b border bg-background data-[color=black]:z-10 data-[color=black]:h-2/3 data-[color=black]:bg-foreground data-active:bg-primary" {pitch} />
    {/each}
  {/snippet}
</Piano.Root>
```

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

**JavaScript**

```html
<style>
  audio-ui-piano { position: relative; display: block; width: 24rem; height: 8rem; }
  audio-ui-piano button { border: 1px solid #888; background: #fff; }
  audio-ui-piano button[data-color="black"] { height: 66%; background: #111; z-index: 1; }
  audio-ui-piano button[data-active] { background: #2f7d4a; }
</style>

<audio-ui-piano min-pitch="60" max-pitch="72"></audio-ui-piano>

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

  const keyboard = document.querySelector("audio-ui-piano");
  keyboard.addEventListener("noteon", (event) => console.log(event.detail.value, event.detail.velocity));
  keyboard.addEventListener("noteoff", (event) => console.log(event.detail.value));
</script>
```

In the web adapter, the keyboard makes a key for each pitch, each a wrapper around a `<button>`. To style or fill them yourself, write the `audio-ui-piano-key` elements with a `pitch` and a button inside: the keyboard then leaves them as they are, and an `audio-ui-piano-label` inside a button gets its note.

### What a note reports

- `onNoteOn` gets `velocity` from 0 to 1, a `reason` (`"press"`, `"glide"` or `"keyboard"`), a `source` and the `event`.
- `onNoteOff` gets a `reason`: `"press"`, `"glide"` or `"keyboard"`.
- In the web adapter, they are the `noteon` and `noteoff` events, with `detail: { value, reason, source, velocity }`, where `value` is the pitch.

## Interaction

### Pointer

**Behavior**

| Gesture | Effect |
| --- | --- |
| Press a key | Fires `onNoteOn`; the key stays pressed while held. |
| Release | Fires `onNoteOff`. |
| Drag across keys | Glissando: the previous key releases (`onNoteOff`) and the next one sounds (`onNoteOn`) as the pointer crosses it. |
| Multiple pointers | Each pointer (finger) holds its own key, so chords work on touch devices. |

### Keyboard

The keys share one tab stop. On the focused key:

**Keys**

| Key | Effect |
| --- | --- |
| `ArrowLeft` / `ArrowRight` (or `ArrowDown` / `ArrowUp`) | Move focus to the next lower / higher key |
| `Shift` + arrow, `PageDown` / `PageUp` | Move focus an octave down / up |
| `Space` / `Enter` | Hold the focused key: `onNoteOn` on press, `onNoteOff` on release |
| `Home` / `End` | Move focus to the lowest / highest key |

## API reference

**In React**

### Registry component

`Piano` accepts style props (`size`, `className`) plus the props of the `Piano` primitive's Root.

#### Value and state

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `minPitch` | `number` | `48` | Lowest MIDI pitch, inclusive: 60 is middle C. |
| `maxPitch` | `number` | `72` | Highest MIDI pitch, inclusive. |
| `pitches` | `number[]` |  | Only these pitches get keys, instead of `minPitch`…`maxPitch`. |
| `activeNotes` | `number[]` |  | Pitches lit from elsewhere, such as a MIDI input or a sequencer, on top of the keys pressed here. |
| `disabled` | `boolean` | `false` | Whether the keyboard is disabled. |
| `onNoteOn` | `(pitch: number, eventDetails) => void` |  | Fires when a key is pressed or glided onto. `eventDetails.cancel()` keeps it silent. |
| `onNoteOff` | `(pitch: number, eventDetails) => void` |  | Fires when a key is released, the pointer glides off it, or it loses focus while held. |
| `aria-label` | `string` |  | Accessible name for the keyboard. |
| `aria-labelledby` | `string` |  | ID of a labeling element. |

#### Layout and display

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `"sm" \| "default" \| "lg"` | `"default"` | Size variant (sets the keyboard height). |
| `className` | `string` |  | Additional CSS classes. |

Additional valid HTML attributes passed to `Piano.Root` are forwarded.

### Options

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

| Option | Type | Default | |
| --- | --- | --- | --- |
| `minPitch`, `maxPitch` | `number` | `48`, `72` | The lowest and highest MIDI pitch, inclusive: 60 is middle C. |
| `pitches` | `number[]` | | Only these pitches get keys, instead of `minPitch` to `maxPitch`. |
| `layout` | `"keyboard"` or `"even"` | `"keyboard"` | Like a piano, with the black keys between the white ones, or one equal share for each key, as the rows of a piano roll are. |
| `orientation` | `"horizontal"` or `"vertical"` | `"horizontal"` | Which way the keys run. A vertical keyboard puts the low end at the bottom. |
| `activeNotes` | `number[]` | | Pitches lit from elsewhere, such as a MIDI input or a sequencer, on top of the keys pressed here. |
| `disabled` | `boolean` | `false` | Plays nothing. |
| `onNoteOn` | `(pitch, details) => void` | | A key sounds. `details.cancel()` keeps it silent. |
| `onNoteOff` | `(pitch, details) => void` | | A key is released, the pointer glides off it, or it loses focus while held. |

### States to style from

- `data-active` on a key while it sounds, pressed here or listed in `activeNotes`.
- `data-color` on a key, `"black"` or `"white"`, `data-disabled`, `data-layout` and `data-orientation`.

### Parts

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Piano.Key` | `button` | `pitch: key` |
| `Piano.Label` | `span` | `pitch: [object Object]`, `value: [object Object]` |
| `Piano.Root` | `div` |  |

**In Web**

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

`audio-ui-piano`, `audio-ui-piano-key`, `audio-ui-piano-label`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |
| `onNoteOff` | `@note-off` | `noteoff` |
| `onNoteOn` | `@note-on` | `noteon` |

**In React**

## Examples

### External notes via activeNotes

```tsx
import { useEffect, useState } from "react";
import { Piano } from "@/components/audio-ui/piano";

const CHORD_NOTES = [48, 52, 55];
const TOGGLE_MS = 900;

/** Simulated external source (a MIDI input, a sequencer) driving activeNotes independently of pointer presses. */
export function PianoActiveNotesDemo() {
  const [chordOn, setChordOn] = useState(true);

  useEffect(() => {
    const intervalId = window.setInterval(() => {
      setChordOn((current) => !current);
    }, TOGGLE_MS);
    return () => window.clearInterval(intervalId);
  }, []);

  return (
    <Piano
      activeNotes={chordOn ? CHORD_NOTES : []}
      aria-label="Piano"
      maxPitch={72}
      minPitch={48}
    />
  );
}
```

