# Note edit menu

> A menu of commands over a piano roll's notes, with their keys: split, join, quantize, legato, time commands, transposing, fit to scale, chance and velocity.

```tsx
import { useCallback, useRef, useState } from "react";
import {
  DropdownMenuItem,
  DropdownMenuSeparator,
} from "@/components/ui/dropdown-menu";
import {
  NoteEditMenu,
  NoteEditMenuContent,
  NoteEditMenuSub,
  NoteEditMenuTrigger,
} from "@/components/audio-ui/note-edit-menu";
import {
  PianoRoll,
  PianoRollGrid,
  PianoRollKeys,
  PianoRollStrip,
  PianoRollVelocity,
  PianoRollVelocityScale,
  PianoRollViewport,
} from "@/components/audio-ui/piano-roll";
import { Timeline } from "@/components/audio-ui/timeline";
import {
  applyNoteEdit,
  canApplyNoteEdit,
  type NoteEdit,
  PITCH_EDITS,
  TIME_EDITS,
  VELOCITY_EDITS,
} from "@/lib/note-edits";
import type { Note, NoteId } from "@/components/audio-ui/piano-roll/edits";

const BOUNDS = { duration: 16, maxPitch: 72, minLength: 1, minPitch: 60 };

const PHRASE: Note[] = [
  { id: "1", length: 2, pitch: 60, start: 0, velocity: 0.9 },
  { id: "2", length: 2, pitch: 64, start: 2, velocity: 0.5 },
  { id: "3", length: 2, pitch: 67, start: 4, velocity: 0.8 },
  { id: "4", length: 2, pitch: 72, start: 6, velocity: 1 },
  { id: "5", length: 1, pitch: 71, start: 9, velocity: 0.4 },
  { id: "6", length: 3, pitch: 67, start: 10, velocity: 0.7 },
  { id: "7", length: 3, pitch: 62, start: 13, velocity: 0.6 },
];

/** Edit the selection, or every note with none selected; Reset is an item of the demo's own, beside the edits. */
export function NoteEditMenuDemo() {
  const [notes, setNotes] = useState(PHRASE);
  const [selection, setSelection] = useState<readonly NoteId[]>([]);
  const nextIdRef = useRef(0);

  const edit = useCallback(
    (item: NoteEdit) =>
      setNotes(
        applyNoteEdit(item, notes, selection, {
          at: 0,
          bounds: BOUNDS,
          loopEnd: BOUNDS.duration,
          nextId: () => {
            nextIdRef.current += 1;
            return `edit-${nextIdRef.current}`;
          },
          scale: null,
        })
      ),
    [notes, selection]
  );
  const isDisabled = useCallback(
    (item: NoteEdit) =>
      !canApplyNoteEdit(item, {
        hasNotes: notes.length > 0,
        hasScale: false,
        hasSelection: selection.length > 0,
      }),
    [notes.length, selection.length]
  );
  const reset = useCallback(() => setNotes(PHRASE), []);

  return (
    <div className="flex w-full flex-col gap-3">
      <div className="flex justify-end">
        <NoteEditMenu disabled={isDisabled} onEdit={edit}>
          <NoteEditMenuTrigger />
          <NoteEditMenuContent>
            <NoteEditMenuSub edits={TIME_EDITS} label="Time" />
            <NoteEditMenuSub edits={PITCH_EDITS} label="Pitch" />
            <NoteEditMenuSub edits={VELOCITY_EDITS} label="Velocity" />
            <DropdownMenuSeparator />
            <DropdownMenuItem
              data-agent-confirm="Puts the phrase back as it was, without the edits"
              onClick={reset}
            >
              Reset
            </DropdownMenuItem>
          </NoteEditMenuContent>
        </NoteEditMenu>
      </div>
      <Timeline duration={BOUNDS.duration} snapStep={1}>
        <PianoRoll
          className="h-72 rounded-md border"
          maxPitch={BOUNDS.maxPitch}
          minPitch={BOUNDS.minPitch}
          onSelectionChange={setSelection}
          onValueChange={setNotes}
          selection={selection}
          value={notes}
        >
          <PianoRollViewport>
            <PianoRollStrip className="flex-1" lead={<PianoRollKeys />}>
              <PianoRollGrid accentStep={4} aria-label="Notes" gridStep={1} />
            </PianoRollStrip>
            <PianoRollStrip
              className="border-t"
              lead={<PianoRollVelocityScale />}
              sticky="bottom"
            >
              <PianoRollVelocity accentStep={4} gridStep={1} />
            </PianoRollStrip>
          </PianoRollViewport>
        </PianoRoll>
      </Timeline>
    </div>
  );
}
```

## Installation

**CLI**

```bash
npx shadcn@latest add @audio-ui/note-edit-menu
```

**Manual**

**1. Add the engine's scales:**

```bash
npx shadcn@latest add @audio-ui/engine-pitch
```

**2. Copy and paste the following code into your project.**

<ItemFiles name="note-edit-menu" to={1} />

**3. Copy and paste the commands the menu lists.**

<ItemFiles name="note-edit-menu" from={1} />

**4. Update the import paths to match your project setup.**

**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 note edit menu 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).

## Anatomy

```tsx
<NoteEditMenu>
  <NoteEditMenuTrigger />
  <NoteEditMenuContent>
    <NoteEditMenuItems />
    <NoteEditMenuSub />
  </NoteEditMenuContent>
</NoteEditMenu>
```

## Usage

```tsx
import {
  NoteEditMenu,
  NoteEditMenuContent,
  NoteEditMenuSub,
  NoteEditMenuTrigger,
} from "@/components/audio-ui/note-edit-menu";
import {
  applyNoteEdit,
  canApplyNoteEdit,
  PITCH_EDITS,
  TIME_EDITS,
  VELOCITY_EDITS,
} from "@/lib/note-edits";

<NoteEditMenu
  disabled={(edit) =>
    !canApplyNoteEdit(edit, {
      hasNotes: notes.length > 0,
      hasScale: scale !== null,
      hasSelection: selection.length > 0,
    })
  }
  onEdit={(edit) =>
    setNotes(
      applyNoteEdit(edit, notes, selection, {
        at: playhead, // in steps: where Split cuts with nothing selected
        bounds: { duration: 64, maxPitch: 84, minLength: 1, minPitch: 36 },
        loopEnd: 64, // what Legato stretches the last notes to
        nextId: () => crypto.randomUUID(), // an id for each note an edit makes
        scale, // what Up, Down and Fit to scale follow, or null
        step: 1, // the grid: what Split cuts on and Quantize snaps to
      })
    )
  }
>
  <NoteEditMenuTrigger />
  <NoteEditMenuContent>
    <NoteEditMenuSub edits={TIME_EDITS} label="Time" />
    <NoteEditMenuSub edits={PITCH_EDITS} label="Pitch" />
    <NoteEditMenuSub edits={VELOCITY_EDITS} label="Velocity" />
  </NoteEditMenuContent>
</NoteEditMenu>;
```

The item installs two files: the menu, and `lib/note-edits.ts`, the commands it lists. A command is data, `{ id, label, shortcut?, edit }`, so the menu needs no prop per command: `NoteEditMenuItems` lists commands as items, `NoteEditMenuSub` lists them in a submenu, and you pick which go where. Each item shows its key beside it (`⌘E`), and `disabled` greys out the commands that can't run: there must be notes, a time command needs a selection and Fit to scale a scale.

`onEdit` gets the command picked. `applyNoteEdit` runs it on the selected notes, or on every note with none selected, and returns the new notes. Hand them to `useUndoHistory`'s `edit` and every command undoes in one step (see [Piano roll](/docs/components/base/piano-roll#undo-and-redo)).

### The commands

- `TIME_EDITS`: Split (⌘E), Chop in two, Join (⌘J), Quantize (⌘U), Legato, Reverse, Twice as long, Half as long, Duplicate time (⇧⌘D), Delete time (⇧⌘⌫), Insert time (⌘I).
- `PITCH_EDITS`: Up, Down, Octave up (⇧↑), Octave down (⇧↓), Invert, Fit to scale. Up and Down move a step of the scale when one is marked, else a semitone.
- `PLAY_EDITS`: Deactivate (0), Always play, Play 75%, 50% or 25% of the time.
- `VELOCITY_EDITS`: Crescendo, Decrescendo, Humanize.

Split cuts the selected notes on every grid step, `step`, or, with nothing selected, the notes under the playhead at `at`. The work is done by the edits of the piano roll (`piano-roll/edits.ts`) (`splitNotes`, `quantizeNotes`, `fitNotesToScale`…); `note-edits` names them, groups them and gives them keys.

### Items of your own

`NoteEditMenuContent` is a dropdown menu's content, so commands that are not note edits sit beside the parts as plain items. The piano roll block puts its file commands there:

```tsx
<NoteEditMenuContent>
  <NoteEditMenuItems edits={KEYED_EDITS} />
  <DropdownMenuSeparator />
  <NoteEditMenuSub edits={TIME_EDITS} label="Time" />
  <DropdownMenuSeparator />
  <DropdownMenuItem onClick={importFile}>Import a MIDI file</DropdownMenuItem>
  <DropdownMenuItem onClick={exportFile}>Export as a MIDI file</DropdownMenuItem>
  <DropdownMenuItem onClick={clear} variant="destructive">
    Clear
  </DropdownMenuItem>
</NoteEditMenuContent>
```

### On a right-click

`NoteEditMenuProvider` gives the parts what they read without a menu of its own, so the same commands fill a menu that opens otherwise, such as a right-click's. The MIDI clip panel opens its Notes menu both ways:

```tsx
<ContextMenu>
  <ContextMenuTrigger>{roll}</ContextMenuTrigger>
  <ContextMenuContent>
    <NoteEditMenuProvider disabled={cannotEdit} onEdit={runEdit}>
      <NoteEditMenuSub edits={TIME_EDITS} label="Time" />
      <NoteEditMenuSub edits={PITCH_EDITS} label="Pitch" />
    </NoteEditMenuProvider>
  </ContextMenuContent>
</ContextMenu>
```

### Commands of your own

A command of your own is a `NoteEdit` too:

```tsx
import { moveNotes } from "@/components/audio-ui/piano-roll/edits";
import type { NoteEdit } from "@/lib/note-edits";

const FIFTH_UP: NoteEdit = {
  edit: (notes, ids, { bounds }) => moveNotes(notes, ids, 0, 7, bounds),
  id: "fifth-up",
  label: "A fifth up",
};
```

### Without the menu

The same commands run from the keyboard, a toolbar or an agent's tool. `noteEditForKey(key, shiftKey)` returns the command Cmd/Ctrl with `key` runs (Shift too for the time commands), or nothing. `key` is lower case:

```tsx
const onKeyDown = (event: KeyboardEvent) => {
  if (!(event.metaKey || event.ctrlKey)) return;
  const edit = noteEditForKey(event.key.toLowerCase(), event.shiftKey);
  if (edit && canApplyNoteEdit(edit, state)) {
    event.preventDefault();
    setNotes(applyNoteEdit(edit, notes, selection, context));
  }
};
```

## API reference

### NoteEditMenu

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `onEdit` | `(edit: NoteEdit) => void` |  | A command was picked: run it with `applyNoteEdit`. |
| `disabled` | `(edit: NoteEdit) => boolean` |  | Whether a command can't run now. Every command can when left out. |

### Parts

**Components**

| Name | Description |
| --- | --- |
| `NoteEditMenuTrigger` | The button that opens the menu, "Notes" with a caret unless given children. Takes the button's props. |
| `NoteEditMenuContent` | The menu. Aligned to the trigger's end unless given `align`. |
| `NoteEditMenuItems` | A menu item per command in `edits`, with its key beside it. |
| `NoteEditMenuSub` | A submenu named `label`, holding a menu item per command in `edits`. |
| `NoteEditMenuProvider` | What the items read, without a menu of its own: wrap the content of a menu that opens otherwise, such as a right-click's. Takes `onEdit` and `disabled`. |

### note-edits

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `applyNoteEdit` | `(edit, notes, selection, context) => Note[]` |  | Runs `edit` on the selected notes, or on every note with none selected. |
| `canApplyNoteEdit` | `(edit, { hasNotes, hasScale, hasSelection }) => boolean` |  | Whether `edit` can run now. |
| `noteEditForKey` | `(key, shiftKey) => NoteEdit \| undefined` |  | The command Cmd/Ctrl (and Shift) with `key` runs. |
| `TIME_EDITS, PITCH_EDITS, PLAY_EDITS, VELOCITY_EDITS` | `NoteEdit[]` |  | The commands, by what they change. |

The context `applyNoteEdit` takes:

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `at` | `number` |  | Where the playhead is, in steps. |
| `bounds` | `{ duration, minPitch, maxPitch, minLength }` |  | The roll's length and pitches, and the shortest a note gets from a command. |
| `loopEnd` | `number` |  | Where the loop ends, in steps. |
| `nextId` | `() => NoteId` |  | A new id for each note a command makes. Each call must return a different one. |
| `scale` | `Scale \| null` |  | The scale marked on the roll: what Up, Down and Fit to scale follow. |
| `step` | `number` | `1` | The grid, in steps: what Split cuts on, Quantize snaps to and Humanize moves by a quarter of. |
