# Piano roll

> A note editor on a grid: draw, move, resize and select notes, with a playable keyboard and a velocity lane.

**In Vue**

```tsx
<script lang="ts" setup>
import { ref } from "vue";
import type { Note } from "@/components/audio-ui/piano-roll/core";
import { PianoRoll } from "@/components/audio-ui/piano-roll/vue";

const NOTES: Note[] = [
  { id: "1", length: 1, pitch: 60, start: 0 },
  { id: "2", length: 0.5, pitch: 63, start: 1 },
  { id: "3", length: 1.5, pitch: 67, start: 1.5 },
  { id: "4", length: 1, pitch: 65, start: 3 },
  { id: "5", length: 2, pitch: 62, start: 4 },
  { id: "6", length: 1, pitch: 69, start: 6 },
  { id: "7", length: 1, pitch: 67, start: 7 },
  { id: "8", length: 2, pitch: 60, start: 8 },
];

const notes = ref<Note[]>(NOTES);
</script>

<template>
  <PianoRoll.Root
    mode="select"
    :duration="16"
    :max-pitch="72"
    :min-pitch="48"
    :snap-step="0.25"
    :value="notes"
    @value-change="(next: Note[]) => { notes = next; }"
  >
    <PianoRoll.Grid style="position: relative; height: 16rem">
      <PianoRoll.Rows>
        <template #default="{ pitch }">
          <PianoRoll.Row :pitch="pitch" />
        </template>
      </PianoRoll.Rows>
      <PianoRoll.Notes>
        <template #default="{ note }">
          <PianoRoll.Note :note="note">
            <PianoRoll.NoteHandle edge="start" :note="note" />
            <PianoRoll.NoteHandle edge="end" :note="note" />
          </PianoRoll.Note>
        </template>
      </PianoRoll.Notes>
      <PianoRoll.Marquee />
    </PianoRoll.Grid>
  </PianoRoll.Root>
</template>
```

**In Svelte**

```tsx
<script lang="ts">
import type { Note } from "$lib/components/audio-ui/piano-roll/core";
import { PianoRoll } from "$lib/components/audio-ui/piano-roll/svelte";

const NOTES: Note[] = [
  { id: "1", length: 1, pitch: 60, start: 0 },
  { id: "2", length: 0.5, pitch: 63, start: 1 },
  { id: "3", length: 1.5, pitch: 67, start: 1.5 },
  { id: "4", length: 1, pitch: 65, start: 3 },
  { id: "5", length: 2, pitch: 62, start: 4 },
  { id: "6", length: 1, pitch: 69, start: 6 },
  { id: "7", length: 1, pitch: 67, start: 7 },
  { id: "8", length: 2, pitch: 60, start: 8 },
];

let notes = $state<Note[]>(NOTES);
</script>

<PianoRoll.Root
  duration={16}
  maxPitch={72}
  minPitch={48}
  mode="select"
  onValueChange={(next) => {
    notes = next;
  }}
  snapStep={0.25}
  value={notes}
>
  <PianoRoll.Grid style="position: relative; height: 16rem">
    <PianoRoll.Rows>
      {#snippet children(
        pitch
      )}
        <PianoRoll.Row {pitch} />
      {/snippet}
    </PianoRoll.Rows>
    <PianoRoll.Notes>
      {#snippet children(
        note
      )}
        <PianoRoll.Note {note}>
          <PianoRoll.NoteHandle edge="start" {note} />
          <PianoRoll.NoteHandle edge="end" {note} />
        </PianoRoll.Note>
      {/snippet}
    </PianoRoll.Notes>
    <PianoRoll.Marquee />
  </PianoRoll.Grid>
</PianoRoll.Root>
```

**In Web**

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

const NOTES = [
  { id: "1", length: 1, pitch: 60, start: 0 },
  { id: "2", length: 0.5, pitch: 63, start: 1 },
  { id: "3", length: 1.5, pitch: 67, start: 1.5 },
  { id: "4", length: 1, pitch: 65, start: 3 },
  { id: "5", length: 2, pitch: 62, start: 4 },
  { id: "6", length: 1, pitch: 69, start: 6 },
  { id: "7", length: 1, pitch: 67, start: 7 },
  { id: "8", length: 2, pitch: 60, start: 8 },
];

/** Draws the piano roll into `element`, and returns what takes it away. The rows and the notes are made for you: styled here from their tags. */
export function pianoRollWebDemo(element) {
  element.innerHTML = `
    <style>
      audio-ui-piano-roll-row { border-bottom: 1px solid var(--border); }
      audio-ui-piano-roll-row[data-color="black"] { background: var(--muted); }
      audio-ui-piano-roll-note { border: 1px solid var(--primary); background: color-mix(in oklab, var(--primary) 70%, transparent); cursor: grab; }
      audio-ui-piano-roll-note[data-selected] { background: var(--primary); outline: 1px solid var(--foreground); }
      audio-ui-piano-roll-note-start, audio-ui-piano-roll-note-end { width: 0.375rem; cursor: ew-resize; }
      audio-ui-piano-roll-marquee { border: 1px solid var(--primary); background: color-mix(in oklab, var(--primary) 10%, transparent); z-index: 10; }
    </style>
    <audio-ui-piano-roll default-value='${JSON.stringify(NOTES)}' duration="16" max-pitch="72" min-pitch="48" mode="select" snap-step="0.25">
      <audio-ui-piano-roll-grid style="position: relative; height: 16rem">
        <audio-ui-piano-roll-rows></audio-ui-piano-roll-rows>
        <audio-ui-piano-roll-notes handles></audio-ui-piano-roll-notes>
        <audio-ui-piano-roll-marquee></audio-ui-piano-roll-marquee>
      </audio-ui-piano-roll-grid>
    </audio-ui-piano-roll>`;
  return () => {
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import {
  type ChangeEvent,
  type DragEvent,
  type KeyboardEvent as ReactKeyboardEvent,
  type RefObject,
  useCallback,
  useEffect,
  useId,
  useMemo,
  useRef,
  useState,
} from "react";
import { IconPlaceholder } from "@/components/icon-placeholder";
import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import {
  DropdownMenuCheckboxItem,
  DropdownMenuGroup,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
} from "@/components/ui/dropdown-menu";
import {
  downloadMidiFile,
  downloadMusicXmlFile,
  MIDI_FILE_ACCEPT,
  MUSICXML_FILE_ACCEPT,
  readMidiFile,
  readMusicXmlFile,
} from "@/lib/engine/files";
import { rollScale, type Scale } from "@/lib/engine/pitch";
import type { Tempo } from "@/lib/engine/time";
import { Fader } from "@/components/audio-ui/fader";
import {
  NoteEditMenu,
  NoteEditMenuContent,
  NoteEditMenuItems,
  NoteEditMenuSub,
  NoteEditMenuTrigger,
} from "@/components/audio-ui/note-edit-menu";
import { NoteFind } from "@/components/audio-ui/note-find";
import {
  PianoRoll,
  PianoRollGrid,
  PianoRollKeys,
  PianoRollSelectionSpan,
  PianoRollStretchHandle,
  PianoRollStrip,
  PianoRollVelocity,
  PianoRollVelocityScale,
  PianoRollViewport,
} from "@/components/audio-ui/piano-roll";
import {
  ScaleMenu,
  ScaleMenuContent,
  ScaleMenuDetect,
  ScaleMenuName,
  ScaleMenuRoot,
  ScaleMenuToggle,
  ScaleMenuTrigger,
} from "@/components/audio-ui/scale-menu";
import {
  Timeline,
  TimelineLane,
  TimelineMark,
  TimelineNavigator,
  TimelinePlayhead,
  TimelineRange,
  TimelineRangeHandle,
  TimelineRuler,
} from "@/components/audio-ui/timeline";
import { Transport } from "@/components/audio-ui/transport";
import { useUndoHistory } from "@/hooks/use-undo-history";
import { useMasterBus } from "@/hooks/use-master-bus";
import {
  DEFAULT_NOTE_ENVELOPE,
  type Meter,
  meterOf,
  usePianoRollPlayback,
} from "@/hooks/use-piano-roll-playback";
import { useSynthVoices } from "@/hooks/use-synth-voices";
import { useMidiInput } from "@/hooks/use-midi-input";
import type { TransportRegion } from "@/hooks/use-transport-clock";
import {
  applyNoteEdit,
  canApplyNoteEdit,
  type NoteEdit,
  noteEditForKey,
  PITCH_EDITS,
  PLAY_EDITS,
  TIME_EDITS,
  VELOCITY_EDITS,
} from "@/lib/note-edits";
import { cn } from "@/lib/utils";
import { webAudio } from "@/lib/web-audio";
import {
  findNotes,
  type Note,
  type NoteId,
  type NoteLevel,
  type NoteQuery,
  selectionSpan,
  toggleMuted,
} from "@/components/audio-ui/piano-roll/edits";
import { pitchClassName } from "@/components/audio-ui/pitch";

/** C2 to C6: more than fits, so the roll scrolls and opens on middle C. */
const MIN_PITCH = 36;
/** The files the roll imports: a MIDI file, or a MusicXML score. */
const FILE_ACCEPT = `${MIDI_FILE_ACCEPT},${MUSICXML_FILE_ACCEPT}`;
const MIDI_FILE_NAME = /\.midi?$/i;
const MAX_PITCH = 84;
const DEFAULT_VOLUME = 0.7;
/** The clip is four bars long, in whatever signature it is in. */
const BARS = 4;
/** The widest a step gets, in px: zoomed in all the way, a beat still shows its steps. */
const MAX_ZOOM = 64;
/** The room a ruler label needs, in px: bars, beats and sixteenths each get labels once they are this far apart. */
const LABEL_SPACING = 40;
/** The shortest a note gets from an edit: one step, the grid's. */
const MIN_LENGTH = 1;

const describeStep = (step: number) => `Step ${Math.floor(step) + 1}`;
/** "C4, step 5, 2 steps": where a note is, in the grid's own terms. */
const describeNote = (note: Note) =>
  `${pitchClassName(note.pitch)}${Math.floor(note.pitch / 12) - 1}, step ${note.start + 1}, ${note.length} ${note.length === 1 ? "step" : "steps"}`;

type LoopRegion = TransportRegion;

interface RulerMark {
  label: string;
  level: "bar" | "beat" | "step";
  step: number;
}

const DEPTH = { bar: 1, beat: 2, step: 3 } as const;

/** Where a step falls in its bar and beat, and which of the three it starts. */
function placeOf(step: number, meter: Meter) {
  const bar = Math.floor(step / meter.stepsPerBar);
  const inBar = step % meter.stepsPerBar;
  const beat = Math.floor(inBar / meter.stepsPerBeat);
  const inBeat = inBar % meter.stepsPerBeat;
  let level: RulerMark["level"] = "step";
  if (inBar === 0) {
    level = "bar";
  } else if (inBeat === 0) {
    level = "beat";
  }
  const label = [bar + 1, beat + 1, inBeat + 1]
    .slice(0, DEPTH[level])
    .join(".");
  return { bar, label, level };
}

/**
 * The ruler's labels at `unit` px a step: every bar, then every beat (1.2),
 * then every sixteenth (1.2.3), each once they are `LABEL_SPACING` apart.
 * Zoomed out further than bars allow, every second or fourth bar.
 */
function rulerMarks(unit: number, meter: Meter): RulerMark[] {
  let barEvery = 1;
  while (
    barEvery * meter.stepsPerBar * unit < LABEL_SPACING &&
    barEvery < BARS
  ) {
    barEvery *= 2;
  }
  const shown = {
    bar: true,
    beat: meter.stepsPerBeat * unit >= LABEL_SPACING,
    step: unit >= LABEL_SPACING,
  };
  const marks: RulerMark[] = [];
  for (let step = 0; step < meter.duration; step += 1) {
    const { bar, label, level } = placeOf(step, meter);
    if (shown[level] && (level !== "bar" || bar % barEvery === 0)) {
      marks.push({ label, level, step });
    }
  }
  return marks;
}

/** The px a step takes when the whole clip fits the view, the furthest out the roll zooms: the viewport's width past the keys, over the clip's steps. */
function useFitZoom(
  viewportRef: RefObject<HTMLDivElement | null>,
  duration: number
) {
  const [fit, setFit] = useState(0);
  useEffect(() => {
    const viewport = viewportRef.current;
    if (!viewport) {
      return;
    }
    const measure = () => {
      const lead = viewport.querySelector<HTMLElement>(
        '[data-slot="piano-roll-strip"] > div'
      );
      setFit((viewport.clientWidth - (lead?.offsetWidth ?? 0)) / duration);
    };
    measure();
    // Measured again on the next frame, outside the layout pass that resized it.
    let frame = 0;
    const observer = new ResizeObserver(() => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(measure);
    });
    observer.observe(viewport);
    return () => {
      cancelAnimationFrame(frame);
      observer.disconnect();
    };
  }, [duration, viewportRef]);
  return fit;
}

/** The ruler's labels follow the zoom: the grid's width over its steps is the px a step takes. */
function useStepWidth(duration: number) {
  const gridRef = useRef<HTMLDivElement>(null);
  const [unit, setUnit] = useState(0);
  useEffect(() => {
    const grid = gridRef.current;
    if (!grid) {
      return;
    }
    // Measured on the next frame, outside the layout pass that resized it.
    let frame = 0;
    const observer = new ResizeObserver(([entry]) => {
      cancelAnimationFrame(frame);
      frame = requestAnimationFrame(() =>
        setUnit((entry?.contentRect.width ?? 0) / duration)
      );
    });
    observer.observe(grid);
    return () => {
      cancelAnimationFrame(frame);
      observer.disconnect();
    };
  }, [duration]);
  return { gridRef, unit };
}

/** The edits used most, at the top of the Notes menu where they are reached first. */
const TOP_EDITS = ["split", "join", "quantize", "mute"];
/** The Notes menu's submenus: the edits without a key of their own, by what they change. */
const EDIT_MENUS = [
  { edits: TIME_EDITS, label: "Time" },
  { edits: PITCH_EDITS, label: "Pitch" },
  { edits: VELOCITY_EDITS, label: "Velocity" },
  { edits: PLAY_EDITS, label: "Chance" },
].map((menu) => ({
  ...menu,
  edits: menu.edits.filter((item) => !TOP_EDITS.includes(item.id)),
}));
const KEYED_EDITS = [...TIME_EDITS, ...PLAY_EDITS].filter((item) =>
  TOP_EDITS.includes(item.id)
);

/** Whether a key press belongs to a field or a menu, which keep their keys. */
function typedIntoControl(event: { target: EventTarget | null }) {
  const target = event.target as HTMLElement | null;
  return Boolean(
    target?.closest("input, textarea, select, [role=menu], [role=listbox]")
  );
}

/** Cuts the notes past a clip's new end: what a shorter signature leaves out. */
function notesWithin(notes: Note[], duration: number): Note[] {
  return notes
    .filter((note) => note.start < duration)
    .map((note) => ({
      ...note,
      length: Math.min(note.length, duration - note.start),
    }));
}

export function BlockPianoRoll() {
  const volumeId = useId();
  const volumeLabelId = useId();
  const volumeValueId = useId();
  const helpId = useId();

  const [volume, setVolume] = useState(DEFAULT_VOLUME);
  /** Folded, only the pitches carrying notes get a row (F). */
  const [folded, setFolded] = useState(false);
  const toggleFolded = useCallback(() => setFolded((current) => !current), []);
  const [drawing, setDrawing] = useState(true);
  /** What the lane under the grid shows and edits: each note's velocity, or its chance. */
  const [laneLevel, setLaneLevel] = useState<NoteLevel>("velocity");
  const toggleLaneLevel = useCallback(
    () =>
      setLaneLevel((current) =>
        current === "velocity" ? "chance" : "velocity"
      ),
    []
  );
  const toggleDrawing = useCallback(
    () => setDrawing((current) => !current),
    []
  );
  const [scaleOn, setScaleOn] = useState(false);
  /** Limited to the scale, only its rows and the notes' get a row (G): it marks the scale too. */
  const [scaleOnly, setScaleOnly] = useState(false);
  const toggleScaleOnly = useCallback((on: boolean) => {
    setScaleOnly(on);
    if (on) {
      setScaleOn(true);
    }
  }, []);
  const [scaleChoice, setScaleChoice] = useState<Scale>({
    name: "major",
    root: 0,
  });
  const scale = scaleOn ? scaleChoice : null;
  const rolled = useMemo(() => (scale ? rollScale(scale) : null), [scale]);
  const [selection, setSelection] = useState<readonly NoteId[]>([]);
  const viewportRef = useRef<HTMLDivElement>(null);
  // Opens on middle C, halfway down the range.
  useEffect(() => {
    const viewport = viewportRef.current;
    if (viewport) {
      viewport.scrollTop = (viewport.scrollHeight - viewport.clientHeight) / 2;
    }
  }, []);
  const [tempo, setTempo] = useState<Tempo>({
    beatsPerBar: 4,
    beatUnit: 4,
    bpm: 120,
  });
  const meter = useMemo(() => meterOf(tempo, BARS), [tempo]);
  const [looping, setLooping] = useState(true);
  /** Px a step, once zoomed from the keys or the navigator; null fits the clip. */
  const [zoomed, setZoomed] = useState<number | null>(null);
  const fit = useFitZoom(viewportRef, meter.duration);
  const [metronome, setMetronome] = useState(false);
  const [loopRegion, setLoopRegion] = useState<LoopRegion | null>(null);
  const loopRange: readonly [number, number] = loopRegion
    ? [loopRegion.start, loopRegion.end]
    : [0, meter.duration];
  /** The loop range moves freely under the pointer; the loop itself is in whole steps. */
  const changeLoopRegion = useCallback(
    ([start, end]: readonly [number, number]) => {
      setLoopRegion({ end: Math.round(end), start: Math.round(start) });
    },
    []
  );
  const masterGain = useMasterBus(volume);

  const voices = useSynthVoices({ destination: masterGain });
  const { releaseNote, triggerNote } = voices;

  const [notes, setNotes] = useState<Note[]>([]);
  const history = useUndoHistory(notes, setNotes);
  const {
    clock,
    commitLoopRegion,
    isPlaying,
    onNoteOff,
    onNoteOn,
    pause,
    play,
    playingPitches,
    position,
    seek,
    stop,
  } = usePianoRollPlayback({
    destination: masterGain,
    looping,
    loopRegion,
    meter,
    metronome,
    notes,
    tempo,
    voices,
  });

  // A MIDI keyboard plays the roll's voices and lights its keys, once the page's MIDI input is connected.
  const midiNoteOn = useCallback(
    (pitch: number, velocity: number) => {
      webAudio.resume();
      triggerNote(pitch, DEFAULT_NOTE_ENVELOPE, velocity);
    },
    [triggerNote]
  );
  const midiNoteOff = useCallback(
    (pitch: number) => releaseNote(pitch, DEFAULT_NOTE_ENVELOPE),
    [releaseNote]
  );
  const midi = useMidiInput({ onNoteOff: midiNoteOff, onNoteOn: midiNoteOn });
  const activePitches = useMemo(
    () => [...playingPitches, ...midi.activeNotes],
    [midi.activeNotes, playingPitches]
  );

  /** A double-click on the loop goes back to looping the whole clip. */
  const clearLoopRegion = useCallback(() => {
    setLoopRegion(null);
    commitLoopRegion();
  }, [commitLoopRegion]);

  const playPause = isPlaying ? pause : play;

  /** A new signature lays the clip out in its own bars: notes past its new end go, and the loop goes back to the whole clip. */
  const changeTempo = useCallback(
    (next: Tempo) => {
      const { duration } = meterOf(next, BARS);
      if (duration !== meter.duration) {
        setLoopRegion(null);
        if (notes.some((note) => note.start + note.length > duration)) {
          history.edit(notesWithin(notes, duration));
        }
      }
      setTempo(next);
    },
    [history, meter.duration, notes]
  );

  const nextIdRef = useRef(0);
  const applyEdit = useCallback(
    (item: NoteEdit) => {
      const next = applyNoteEdit(item, notes, selection, {
        at: position.getSnapshot(),
        bounds: {
          duration: meter.duration,
          maxPitch: MAX_PITCH,
          minLength: MIN_LENGTH,
          minPitch: MIN_PITCH,
        },
        loopEnd: loopRegion?.end ?? meter.duration,
        nextId: () => {
          nextIdRef.current += 1;
          return `edit-${nextIdRef.current}`;
        },
        scale,
      });
      history.edit(next);
    },
    [history, loopRegion, meter.duration, notes, position, scale, selection]
  );
  const isEditDisabled = useCallback(
    (item: NoteEdit) =>
      !canApplyNoteEdit(item, {
        hasNotes: notes.length > 0,
        hasScale: scale !== null,
        hasSelection: selection.length > 0,
      }),
    [notes.length, scale, selection.length]
  );

  /** A zoom out to the whole clip, or past it, goes back to fitting it. */
  const changeZoom = useCallback(
    (zoom: number) => setZoomed(zoom > fit + 0.01 ? zoom : null),
    [fit]
  );
  /** Zooms so `start` to `end` fills the view, and scrolls it into place. */
  const zoomOnto = useCallback(
    (start: number, end: number) => {
      const viewport = viewportRef.current;
      if (!viewport || end <= start) {
        return;
      }
      const zoom = Math.min(MAX_ZOOM, (fit * meter.duration) / (end - start));
      changeZoom(zoom);
      requestAnimationFrame(() => {
        viewport.scrollLeft = start * zoom;
      });
    },
    [changeZoom, fit, meter.duration]
  );
  /** Onto the selected notes, or the loop with none. */
  const zoomToSelection = () => {
    const span = selectionSpan(notes, new Set(selection));
    const [start, end] = span ? [span.start, span.end] : loopRange;
    zoomOnto(start, end);
  };
  const zoomOut = () => setZoomed(null);
  /** Selects the notes a Find query matches, in the scale marked when it asks for one. */
  const findAndSelect = useCallback(
    (query: NoteQuery) => setSelection(findNotes(notes, query)),
    [notes]
  );
  /** Selects the notes that are not selected, and deselects those that are. */
  const invertSelection = useCallback(() => {
    const selected = new Set(selection);
    setSelection(
      notes.filter((note) => !selected.has(note.id)).map((note) => note.id)
    );
  }, [notes, selection]);
  /** Cmd/Ctrl with Z undoes (with Shift, redoes), with Shift + A inverts the selection, with E, J and U split, join and quantize. */
  const commandKey = (key: string, shiftKey: boolean) => {
    if (key === "z") {
      if (shiftKey) {
        history.redo();
      } else {
        history.undo();
      }
      return true;
    }
    if (key === "a" && shiftKey) {
      invertSelection();
      return true;
    }
    const item = noteEditForKey(key, shiftKey);
    if (item && !isEditDisabled(item)) {
      applyEdit(item);
      return true;
    }
    return false;
  };
  /** B draws, F folds onto the notes, G limits the rows to the scale and K marks it, 0 deactivates the selection, Z zooms onto it and X out to the whole clip. */
  const plainKeys: Record<string, (() => void) | undefined> = {
    0: () => {
      if (selection.length > 0) {
        history.edit(toggleMuted(notes, new Set(selection)));
      }
    },
    b: toggleDrawing,
    f: toggleFolded,
    g: () => toggleScaleOnly(!scaleOnly),
    k: () => setScaleOn((current) => !current),
    x: zoomOut,
    z: zoomToSelection,
  };
  const plainKey = (key: string) => {
    const action = plainKeys[key];
    action?.();
    return action !== undefined;
  };
  /** The editor's keys, from anywhere inside it. */
  const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
    if (event.defaultPrevented || event.altKey || typedIntoControl(event)) {
      return;
    }
    const key = event.key.toLowerCase();
    const handled =
      event.metaKey || event.ctrlKey
        ? commandKey(key, event.shiftKey)
        : plainKey(key);
    if (handled) {
      event.preventDefault();
    }
  };

  useEffect(() => {
    const handleSpace = (e: KeyboardEvent) => {
      // A note takes Space for itself, to select it.
      if (e.code !== "Space" || e.defaultPrevented) {
        return;
      }
      const tag = (e.target as HTMLElement | null)?.tagName;
      if (tag === "INPUT" || tag === "TEXTAREA" || tag === "BUTTON") {
        return;
      }
      e.preventDefault();
      playPause();
    };
    window.addEventListener("keydown", handleSpace);
    return () => window.removeEventListener("keydown", handleSpace);
  }, [playPause]);

  const fileInputRef = useRef<HTMLInputElement | null>(null);
  const [isDraggingFile, setIsDraggingFile] = useState(false);

  const importFile = useCallback(
    async (file: File) => {
      const grid = {
        duration: meter.duration,
        maxPitch: MAX_PITCH,
        minPitch: MIN_PITCH,
      };
      // A MIDI file by its name or its type; anything else is read as a score.
      const imported =
        MIDI_FILE_NAME.test(file.name) || file.type.includes("midi")
          ? await readMidiFile(file, grid)
          : await readMusicXmlFile(file, grid);
      stop();
      history.edit(imported.notes);
      setTempo((current) => ({ ...current, bpm: imported.bpm }));
    },
    [history, meter.duration, stop]
  );

  const handleImport = useCallback(() => {
    fileInputRef.current?.click();
  }, []);

  const handleFileInputChange = useCallback(
    (e: ChangeEvent<HTMLInputElement>) => {
      const file = e.target.files?.[0];
      e.target.value = "";
      if (file) {
        importFile(file);
      }
    },
    [importFile]
  );

  const handleDragOver = useCallback((e: DragEvent<HTMLDivElement>) => {
    if (!e.dataTransfer.types.includes("Files")) {
      return;
    }
    e.preventDefault();
    setIsDraggingFile(true);
  }, []);

  const handleDragLeave = useCallback((e: DragEvent<HTMLDivElement>) => {
    if (e.currentTarget.contains(e.relatedTarget as Node | null)) {
      return;
    }
    setIsDraggingFile(false);
  }, []);

  const handleDrop = useCallback(
    (e: DragEvent<HTMLDivElement>) => {
      const [file] = e.dataTransfer.files;
      if (!file) {
        return;
      }
      e.preventDefault();
      setIsDraggingFile(false);
      importFile(file);
    },
    [importFile]
  );

  const handleExport = useCallback(
    () =>
      downloadMidiFile(notes, { bpm: tempo.bpm, filename: "piano-roll.mid" }),
    [notes, tempo.bpm]
  );
  const handleExportMusicXml = useCallback(
    () =>
      downloadMusicXmlFile(notes, {
        bpm: tempo.bpm,
        filename: "piano-roll.musicxml",
      }),
    [notes, tempo.bpm]
  );
  const clearNotes = useCallback(() => history.edit([]), [history]);

  const { gridRef, unit } = useStepWidth(meter.duration);
  const marks = useMemo(() => rulerMarks(unit, meter), [meter, unit]);

  return (
    <div
      className="rounded-xl @container/panel relative flex w-full min-w-0 flex-col gap-4 border bg-card p-4"
      onDragLeave={handleDragLeave}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      onKeyDown={handleKeyDown}
      role="group"
    >
      <input
        accept={FILE_ACCEPT}
        className="sr-only"
        onChange={handleFileInputChange}
        ref={fileInputRef}
        type="file"
      />
      {isDraggingFile ? (
        <div
          aria-hidden="true"
          className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center rounded-[inherit] border-2 border-primary border-dashed bg-background/80 font-medium text-sm"
        >
          Drop a MIDI or MusicXML file to import
        </div>
      ) : null}
      {/* Narrow, the tools go under the transport rather than over its position. */}
      <div className="flex flex-wrap items-center justify-between gap-2 p-1">
        <Transport
          className="min-w-0 flex-1 basis-full flex-nowrap @lg/panel:basis-0"
          looping={looping}
          metronome={metronome}
          onLoopingChange={setLooping}
          onMetronomeChange={setMetronome}
          onPlayPause={playPause}
          onStop={stop}
          onTempoChange={changeTempo}
          playing={isPlaying}
          source={clock}
          tempo={tempo}
        />
        <div className="flex shrink-0 items-center gap-2">
          <ButtonGroup className="hidden @3xl/panel:flex">
            <Button
              aria-label="Undo"
              disabled={!history.canUndo}
              onClick={history.undo}
              size="icon"
              variant="outline"
            >
              <IconPlaceholder
                hugeicons="Undo02Icon"
                lucide="Undo2Icon"
                phosphor="ArrowUUpLeftIcon"
                remixicon="RiArrowGoBackLine"
                tabler="IconArrowBackUp"
              />
            </Button>
            <Button
              aria-label="Redo"
              disabled={!history.canRedo}
              onClick={history.redo}
              size="icon"
              variant="outline"
            >
              <IconPlaceholder
                hugeicons="Redo02Icon"
                lucide="Redo2Icon"
                phosphor="ArrowUUpRightIcon"
                remixicon="RiArrowGoForwardLine"
                tabler="IconArrowForwardUp"
              />
            </Button>
          </ButtonGroup>
          <ButtonGroup>
            <Button
              aria-label="Draw"
              aria-pressed={drawing}
              onClick={toggleDrawing}
              size="icon"
              title="Draw (B)"
              variant={drawing ? "default" : "outline"}
            >
              <IconPlaceholder
                hugeicons="PencilEdit01Icon"
                lucide="PencilIcon"
                phosphor="PencilSimpleIcon"
                remixicon="RiPencilLine"
                tabler="IconPencil"
              />
            </Button>
            <ScaleMenu
              enabled={scaleOn}
              onEnabledChange={setScaleOn}
              onScaleChange={setScaleChoice}
              scale={scaleChoice}
            >
              <ScaleMenuTrigger />
              <ScaleMenuContent>
                <ScaleMenuToggle>
                  Mark the scale
                  <DropdownMenuShortcut>K</DropdownMenuShortcut>
                </ScaleMenuToggle>
                <DropdownMenuCheckboxItem
                  checked={scaleOnly}
                  onCheckedChange={toggleScaleOnly}
                >
                  Only its rows
                  <DropdownMenuShortcut>G</DropdownMenuShortcut>
                </DropdownMenuCheckboxItem>
                <DropdownMenuSeparator />
                <ScaleMenuRoot />
                <ScaleMenuName />
                <DropdownMenuSeparator />
                <ScaleMenuDetect notes={notes} />
              </ScaleMenuContent>
            </ScaleMenu>
            <NoteFind onFind={findAndSelect} scale={scale} />
            <NoteEditMenu disabled={isEditDisabled} onEdit={applyEdit}>
              <NoteEditMenuTrigger />
              <NoteEditMenuContent>
                <DropdownMenuGroup>
                  <NoteEditMenuItems edits={KEYED_EDITS} />
                </DropdownMenuGroup>
                <DropdownMenuSeparator />
                <DropdownMenuGroup>
                  {EDIT_MENUS.map((menu) => (
                    <NoteEditMenuSub
                      edits={menu.edits}
                      key={menu.label}
                      label={menu.label}
                    />
                  ))}
                </DropdownMenuGroup>
                <DropdownMenuSeparator />
                <DropdownMenuGroup>
                  <DropdownMenuItem onClick={handleImport}>
                    Import a MIDI or MusicXML file
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    disabled={notes.length === 0}
                    onClick={handleExport}
                  >
                    Export as a MIDI file
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    disabled={notes.length === 0}
                    onClick={handleExportMusicXml}
                  >
                    Export as MusicXML
                  </DropdownMenuItem>
                  <DropdownMenuItem
                    data-agent-confirm="Deletes every note of the roll"
                    disabled={notes.length === 0}
                    onClick={clearNotes}
                    variant="destructive"
                  >
                    Clear
                  </DropdownMenuItem>
                </DropdownMenuGroup>
              </NoteEditMenuContent>
            </NoteEditMenu>
          </ButtonGroup>
        </div>
      </div>
      <Timeline
        duration={meter.duration}
        maxZoom={MAX_ZOOM}
        minZoom={fit}
        onPositionChange={seek}
        onZoomChange={changeZoom}
        snapStep={1}
        source={position}
        // Always held here, never below the whole clip: once measured, fitting it is a zoom like any other.
        zoom={fit > 0 ? Math.max(zoomed ?? fit, fit) : undefined}
      >
        <PianoRoll
          activePitches={activePitches}
          className="h-104"
          drawStyle="paint"
          folded={scaleOnly && scale ? "scale" : folded}
          getNoteLabel={describeNote}
          maxPitch={MAX_PITCH}
          minPitch={MIN_PITCH}
          mode={drawing ? "draw" : "select"}
          onNoteOff={onNoteOff}
          onNoteOn={onNoteOn}
          onSelectionChange={setSelection}
          onValueChange={history.change}
          onValueCommitted={history.commit}
          scale={rolled}
          selection={selection}
          value={notes}
        >
          <PianoRollStrip className="border-b">
            <TimelineNavigator className="mx-2 my-1.5" />
          </PianoRollStrip>
          <PianoRollViewport ref={viewportRef}>
            <PianoRollStrip
              className="border-b"
              lead={
                <Button
                  aria-pressed={folded}
                  className="h-full w-full rounded-none text-[10px] uppercase tracking-wide"
                  onClick={toggleFolded}
                  size="sm"
                  type="button"
                  variant={folded ? "default" : "ghost"}
                >
                  Fold
                </Button>
              }
              sticky="top"
            >
              <TimelineLane className="h-5 cursor-cell bg-background">
                <TimelineRange
                  aria-label="Loop region"
                  className={cn(!looping && "opacity-40")}
                  drawable
                  getAriaValueText={describeStep}
                  onDoubleClick={clearLoopRegion}
                  onValueChange={changeLoopRegion}
                  onValueCommitted={commitLoopRegion}
                  value={loopRange}
                >
                  <TimelineRangeHandle aria-label="Loop start" edge="start" />
                  <TimelineRangeHandle aria-label="Loop end" edge="end" />
                </TimelineRange>
              </TimelineLane>
              <TimelineRuler
                aria-label="Playhead"
                className="h-4.5 border-b-0 text-[10px]"
                getAriaValueText={describeStep}
              >
                {marks.map((mark) => (
                  <TimelineMark
                    className={cn(
                      "ps-1",
                      mark.level !== "bar" && "text-muted-foreground"
                    )}
                    key={mark.step}
                    value={mark.step}
                  >
                    {mark.label}
                  </TimelineMark>
                ))}
                <PianoRollSelectionSpan className="bg-primary/25">
                  <PianoRollStretchHandle edge="start" />
                  <PianoRollStretchHandle edge="end" />
                </PianoRollSelectionSpan>
                <TimelinePlayhead />
              </TimelineRuler>
            </PianoRollStrip>
            <PianoRollStrip className="flex-1" lead={<PianoRollKeys />}>
              <PianoRollGrid
                accentStep={meter.stepsPerBeat}
                aria-describedby={helpId}
                aria-label="Notes"
                gridStep={1}
                ref={gridRef}
              >
                <TimelinePlayhead />
              </PianoRollGrid>
            </PianoRollStrip>
            <PianoRollStrip
              className="border-t"
              lead={
                <>
                  <Button
                    aria-label={`Lane: ${laneLevel}, show ${laneLevel === "velocity" ? "chance" : "velocity"}`}
                    className="h-5 w-full shrink-0 rounded-none text-[9px] uppercase tracking-wide"
                    onClick={toggleLaneLevel}
                    size="sm"
                    type="button"
                    variant="ghost"
                  >
                    {laneLevel === "velocity" ? "Vel" : "Chance"}
                  </Button>
                  <PianoRollVelocityScale level={laneLevel} />
                </>
              }
              sticky="bottom"
            >
              <PianoRollVelocity
                accentStep={meter.stepsPerBeat}
                gridStep={1}
                level={laneLevel}
              />
            </PianoRollStrip>
          </PianoRollViewport>
        </PianoRoll>
      </Timeline>
      <p className="sr-only" id={helpId}>
        With drawing on (B), drag across the grid to paint notes, one a grid
        step, following the pointer's pitch or with Alt keeping the first; drag
        across the velocity or chance lane to paint each bar to the pointer's
        height. With drawing off, drag to select. Drag a note to move it, with
        Alt to copy it, and drag its edges to change its length; drag an edge of
        the selection on the ruler to stretch it in time. Shift and a click adds
        a note to the selection; Shift and a key selects every note on its row.
        Cmd or Ctrl and a drag on a velocity bar sets how far it may stray. The
        arrow keys move the focused note, Shift with Left or Right changes its
        length, Shift with Up or Down moves it an octave, and Delete removes it.
        Cmd or Ctrl with E chops the selection on the grid, or splits the notes
        at the playhead, with J joins, with U quantizes, with I inserts the
        selection's time, with Shift and D duplicates it, with Shift and Delete
        deletes it, with Shift and A inverts the selection, and with Z undoes. 0
        deactivates the selection, F folds onto the notes, K marks the scale and
        G keeps only its rows, Z zooms onto the selection and X out.
      </p>
      <div className="flex flex-wrap items-center justify-between gap-4">
        <div aria-label="Volume" className="flex-1" role="group">
          <div className="flex w-full min-w-0 flex-col gap-3">
            <div className="flex w-full min-w-0 items-center justify-between gap-4 [&>*:not(output):not(span)]:min-w-0 [&>*:not(output):not(span)]:flex-1">
              <span
                className="text-center text-muted-foreground text-xs"
                id={volumeLabelId}
              >
                Volume
              </span>
              <Fader
                aria-describedby={volumeValueId}
                aria-labelledby={volumeLabelId}
                id={volumeId}
                max={1}
                min={0}
                onValueChange={setVolume}
                orientation="horizontal"
                step={0.01}
                value={volume}
                valueLabel="hidden"
              />
              <output
                aria-live="polite"
                className="min-w-12 text-center font-mono text-muted-foreground text-xs tabular-nums"
                id={volumeValueId}
              >
                {Math.round(volume * 100)}%
              </output>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
```

A piano roll for writing a phrase: a keyboard down the side, notes on a grid, and a velocity bar under each note. It sits inside a [Timeline](/docs/components/base/arrangement), so notes use the timeline's units, snap to its grid and follow its zoom.

**In Vue, Svelte and Web**

The piano roll's behavior is a few files, the primitive, written on the UI SDK kernel and copied into your project. It is a grid of MIDI notes you draw, move, resize and select, with rows by pitch (folded to the notes or to a scale), a marquee, bars for the velocity or the chance to play, and the commands of an editor on the keys. Each framework renders it with a thin adapter that you also own, and one suite of tests runs against each adapter.

## Overview

- **Notes:** press on the grid to draw a note or to start a selection rectangle, depending on the mode. Drag a note to move it, drag an edge to resize it, and double-click to delete it. Selected notes move and resize together.
- **Keys:** pressing a key on the side plays its note. The rows light up for the pitches playing.
- **Velocity:** each note has a bar in its own lane, drawn from the bottom.
- **Keyboard:** every edit works without a pointer, including copy, paste, duplicate and quantize.
- **Accessibility:** each note is a toggle button named after its pitch and span. Each velocity bar holds a native `<input type="range">`.

## 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, on a timeline, with its keyboard and lanes, is one command:

**In React**

**CLI**

The styled component, with size variants and theme styles:

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

Or the primitive alone, to style yourself:

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

Or the parts alone, to style yourself:

```bash
npx @audio-ui/cli add piano-roll --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 files for every framework: `piano-roll.ts`, the roll itself, beside its controller, the edits it makes and its rows; `pitch.ts`, the note names of its rows, which the piano shares; `grid.ts`, the grid it snaps to, which the timeline 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-roll-react" to={7} />

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

**Vue**

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

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

**JavaScript**

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

<ItemFiles name="piano-roll-web" from={7} />

### 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="piano-roll" />

**In Vue, Svelte and Web**

### 5. The styles

Optional: the piano roll 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. The layout is yours: give the grid its height, and lay the keys and the velocity lane out beside it. The keys and the grid take `data-size` (`sm`, `default` or `lg`), and a key's label `data-octave` on a C, which names its octave. The piano roll follows your theme: the skins dress controls and displays, not editors.

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

```bash
npx @audio-ui/cli add piano-roll
```

By hand:

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

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

**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 roll 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**

A note's `id` is a `string` or a `number`, so type the notes you keep with the roll's `Note`, or a state of literals such as `{ id: "a", … }` is narrower than what `onValueChange` gives back:

```tsx
import type { Note } from "@/components/audio-ui/piano-roll/core";

const [notes, setNotes] = useState<Note[]>([]);
```

```tsx
import { Timeline, TimelineNavigator } from "@/components/audio-ui/timeline";
import {
  PianoRoll,
  PianoRollGrid,
  PianoRollKeys,
  PianoRollStrip,
  PianoRollVelocity,
  PianoRollVelocityScale,
  PianoRollViewport,
} from "@/components/audio-ui/piano-roll";

<Timeline duration={16} snapStep={1}>
  <PianoRoll
    className="h-96"
    maxPitch={72}
    minPitch={48}
    onNoteOn={(pitch, details) => play(pitch, details.velocity)}
    onValueChange={setNotes}
    value={notes}
  >
    <PianoRollViewport>
      <PianoRollStrip className="flex-1" lead={<PianoRollKeys />}>
        <PianoRollGrid aria-label="Notes" gridStep={1} />
      </PianoRollStrip>
      <PianoRollStrip lead={<PianoRollVelocityScale />} sticky="bottom">
        <PianoRollVelocity gridStep={1} />
      </PianoRollStrip>
    </PianoRollViewport>
  </PianoRoll>
</Timeline>;
```

A note is `{ id, pitch, start, length, velocity?, deviation?, muted?, chance? }`: `pitch` is a MIDI number (60 is middle C), `start` and `length` are in the timeline's units, `velocity` is 0 to 1 (full when left out), `deviation` is how far the velocity may stray each time it plays (-1 to 1, up or down), `muted` deactivates it (it stays on the roll, silent) and `chance` is how likely it is to play each time round, 0 to 1. The roll draws them; playing them is yours, so a sequencer skips a muted note, rolls the dice for its chance and strays its velocity by up to its deviation. `value` and `selection` are controlled; `defaultValue` and `defaultSelection` leave them to the roll. The roll reports every edit through `onValueChange` and, when a gesture or a key press ends, `onValueCommitted`; `eventDetails.edit` tells what happened (`"add"`, `"move"`, `"resize"`, `"remove"`, `"duplicate"`, `"paste"`, `"quantize"`, `"stretch"`, `"velocity"`, `"chance"` or `"deviation"`) and `eventDetails.cancel()` keeps the notes as they were.

`onNoteOn` and `onNoteOff` say when a pitch should sound or stop: a key pressed, a note drawn, picked up or moved to a new pitch.

`scale` marks the rows of a scale (`data-in-scale` on each `PianoRoll.Row` in it, `data-out-of-scale` on the others, and `data-scale-root` on its root's): the styles leave the scale's rows clear, shade the others in place of the black keys, and edge the root's in the primary color, and `folded="scale"` keeps only those rows and the ones carrying notes. The roll takes a scale as its pitch classes and its root; `@/lib/engine/pitch` holds the scales by name (`SCALES`, `inScale`, `nearestInScale`) and `rollScale`, which gives one in that shape, and `edits.ts`, which installs with the roll, the edits a toolbar or a menu applies to the selection, each returning the new notes: `splitNotes`, `chopNotes`, `joinNotes`, `legatoNotes`, `reverseNotes`, `invertNotes`, `stretchNotes`, `fitNotesToScale`, `rampVelocity`, `humanizeNotes`, `toggleMuted`, `setChance`, `setDeviation` and `changeLevel`, and the time commands `deleteTime`, `insertTime` and `duplicateTime`; `selectionSpan` gives the time a selection covers and `findNotes` the notes a query matches, by pitch, velocity, length, chance, scale, state or count.

The toolbar of the preview above is three menus that install on their own: the [Scale menu](/docs/components/base/scale-menu) picks the scale the roll marks, [Note find](/docs/components/base/note-find) selects notes by what they are, and the [Note edit menu](/docs/components/base/note-edit-menu) runs the commands above on the selection.

### Playing the notes

```tsx
import { useEffect, useRef, useState } from "react";
import type { Tempo } from "@/lib/engine/time";
import {
  PianoRoll,
  PianoRollGrid,
  PianoRollKeys,
  PianoRollStrip,
  PianoRollViewport,
} from "@/components/audio-ui/piano-roll";
import {
  Timeline,
  TimelinePlayhead,
} from "@/components/audio-ui/timeline";
import { useMasterBus } from "@/hooks/use-master-bus";
import {
  meterOf,
  usePianoRollPlayback,
} from "@/hooks/use-piano-roll-playback";
import { usePlaySwitch } from "@/hooks/use-play-switch";
import { useSynthVoices } from "@/hooks/use-synth-voices";
import type { Note } from "@/components/audio-ui/piano-roll/edits";

const TEMPO: Tempo = { beatsPerBar: 4, beatUnit: 4, bpm: 110 };
const METER = meterOf(TEMPO, 1);

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 },
];

/** A bar on loop: edit the notes while it plays, and the next pass plays them. It plays while the play switch of its session is on. */
export function PianoRollPlaybackDemo() {
  const [notes, setNotes] = useState(PHRASE);
  const output = useMasterBus(0.7);
  const voices = useSynthVoices({ destination: output });
  const playback = usePianoRollPlayback({
    destination: output,
    meter: METER,
    metronome: true,
    notes,
    tempo: TEMPO,
    voices,
  });
  const { playing } = usePlaySwitch();
  // Only the switch starts and stops it: editing a note must not restart it.
  const controls = useRef(playback);
  controls.current = playback;
  useEffect(() => {
    if (playing) {
      controls.current.play();
    } else {
      controls.current.stop();
    }
  }, [playing]);

  return (
    <div className="flex w-full flex-col gap-3">
      <Timeline
        duration={METER.duration}
        onPositionChange={playback.seek}
        snapStep={1}
        source={playback.position}
      >
        <PianoRoll
          activePitches={playback.playingPitches}
          className="h-64 rounded-md border"
          maxPitch={72}
          minPitch={60}
          onNoteOff={playback.onNoteOff}
          onNoteOn={playback.onNoteOn}
          onValueChange={setNotes}
          value={notes}
        >
          <PianoRollViewport>
            <PianoRollStrip className="flex-1" lead={<PianoRollKeys />}>
              <PianoRollGrid
                accentStep={METER.stepsPerBeat}
                aria-label="Notes"
                gridStep={1}
              >
                <TimelinePlayhead />
              </PianoRollGrid>
            </PianoRollStrip>
          </PianoRollViewport>
        </PianoRoll>
      </Timeline>
    </div>
  );
}
```

`usePianoRollPlayback` plays the notes you hold through a synth: play, pause and stop, a loop or once through, a metronome, and the notes the roll auditions.

Usage and API: [`usePianoRollPlayback`](/docs/hooks/use-piano-roll-playback).

### Undo and redo

`useUndoHistory` undoes and redoes any value you hold.

Usage and API: [`useUndoHistory`](/docs/hooks/use-undo-history).

### MIDI files

```tsx
import { type ChangeEvent, useCallback, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import {
  downloadMidiFile,
  MIDI_FILE_ACCEPT,
  readMidiFile,
} from "@/lib/engine/files";
import {
  PianoRoll,
  PianoRollGrid,
  PianoRollKeys,
  PianoRollStrip,
  PianoRollViewport,
} from "@/components/audio-ui/piano-roll";
import { Timeline } from "@/components/audio-ui/timeline";
import type { Note } from "@/components/audio-ui/piano-roll/edits";

const DURATION = 32;
const MIN_PITCH = 48;
const MAX_PITCH = 84;

const PHRASE: Note[] = [
  { id: "1", length: 4, pitch: 60, start: 0, velocity: 0.9 },
  { id: "2", length: 4, pitch: 64, start: 4, velocity: 0.6 },
  { id: "3", length: 4, pitch: 67, start: 8, velocity: 0.8 },
  { id: "4", length: 4, pitch: 72, start: 12, velocity: 1 },
  { id: "5", length: 8, pitch: 65, start: 16, velocity: 0.7 },
  { id: "6", length: 8, pitch: 62, start: 24, velocity: 0.6 },
];

/** Export the clip as a .mid file, or import one onto its grid, with the file's tempo. */
export function PianoRollMidiFileDemo() {
  const [notes, setNotes] = useState(PHRASE);
  const [bpm, setBpm] = useState(120);
  const inputRef = useRef<HTMLInputElement>(null);

  const openFile = useCallback(() => inputRef.current?.click(), []);
  const exportFile = useCallback(
    () => downloadMidiFile(notes, { bpm, filename: "clip.mid" }),
    [bpm, notes]
  );
  const importFile = async (event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    event.target.value = "";
    if (file) {
      const imported = await readMidiFile(file, {
        duration: DURATION,
        maxPitch: MAX_PITCH,
        minPitch: MIN_PITCH,
      });
      setNotes(imported.notes);
      setBpm(imported.bpm);
    }
  };

  return (
    <div className="flex w-full flex-col gap-3">
      <div className="flex items-center justify-between gap-2">
        <p className="font-mono text-muted-foreground text-xs tabular-nums">
          {bpm} BPM
        </p>
        <div className="flex gap-2">
          <input
            accept={MIDI_FILE_ACCEPT}
            className="sr-only"
            onChange={importFile}
            ref={inputRef}
            type="file"
          />
          <Button onClick={openFile} size="sm" variant="outline">
            Import
          </Button>
          <Button disabled={notes.length === 0} onClick={exportFile} size="sm">
            Export
          </Button>
        </div>
      </div>
      <Timeline duration={DURATION} snapStep={1}>
        <PianoRoll
          className="h-64 rounded-md border"
          maxPitch={MAX_PITCH}
          minPitch={MIN_PITCH}
          onValueChange={setNotes}
          value={notes}
        >
          <PianoRollViewport>
            <PianoRollStrip className="flex-1" lead={<PianoRollKeys />}>
              <PianoRollGrid accentStep={4} aria-label="Notes" gridStep={1} />
            </PianoRollStrip>
          </PianoRollViewport>
        </PianoRoll>
      </Timeline>
    </div>
  );
}
```

The `midi-file` library reads a `.mid` file onto the roll's steps and writes one back.

Usage and API: [`midi-file`](/docs/engine/files#midi-files).

### MusicXML files

The `musicxml-file` library does the same for a score, the format notation apps write: it reads a `.musicxml` or `.xml` file, or one compressed as `.mxl`, onto the roll's steps and writes one back. `npx shadcn@latest add @audio-ui/musicxml-file`.

```tsx
import {
  downloadMusicXmlFile,
  MUSICXML_FILE_ACCEPT,
  readMusicXmlFile,
} from "@/lib/engine/files";

const { bpm, notes, title } = await readMusicXmlFile(file, { duration: 64 });

<Button onClick={() => downloadMusicXmlFile(notes, { bpm, filename: "clip.musicxml" })}>
  Export as MusicXML
</Button>
```

`readMusicXmlFile` takes the grid `readMidiFile` takes and returns the score's first tempo and its title. It reads every part into the one clip, in the beats they were written in, through changes of tempo: chords, ties across the bar line, a second voice. It drops the grace notes, which take no time, plays the repeats once, as written, and reads a transposing instrument as written, not as it sounds. The score is parsed by `@audio/musicxml`. `writeMusicXmlFile` writes the notes on their grid, so a notation app shows them where they are. `readMusicXmlFileParts(file)` reads a score as parts, as `readMidiFileParts` does a MIDI file. A compressed score is opened with `fflate`.

### Driving it from an agent

`createPianoRollTools` gives a language model the tools to write on the roll from what a user asks ("a walking bassline in C minor", "up an octave"): `setNotes`, `addNotes`, `removeNotes`, `transpose`, `clear` and `setTempo`, each a description, a zod schema and an `apply` that returns the next state. `npx shadcn@latest add @audio-ui/piano-roll-tools`.

```tsx
import { tool } from "ai";
import { createPianoRollTools } from "@/lib/piano-roll-tools";

const roll = createPianoRollTools({ maxPitch: 72, minPitch: 48, stepCount: 16 });

const tools = Object.fromEntries(
  Object.entries(roll).map(([name, t]) => [
    name,
    tool({
      description: t.description,
      execute: (args) => {
        setState((state) => t.apply(state, args as never));
        return `applied ${name}`;
      },
      inputSchema: t.schema,
    }),
  ])
);
```

The pitch range and the grid are in the schemas, and every note a model writes is clamped into them, so whatever it answers lands on the roll's rows and steps. The tools read and write `{ notes, bpm }` and depend on no agent library: the example wires them to the AI SDK, and any tool-calling API takes the same description and schema.

**In React**

The primitive alone, part by part:

A Root holds the notes and their selection. The roll is a column of parts you place in it:

- **Grid**: the surface the notes are drawn on, a lane of the timeline. A press draws a note in draw mode, or starts a marquee in select mode; a double click adds or removes a note; Enter adds one at the playback position.
- **Rows** and **Row**: a row for each pitch drawn, to style from `data-color`, `data-in-scale`, `data-scale-root`, `data-octave` and `data-active`.
- **Notes** and **Note**: a note for each note of the roll, in reading order. A press selects it and a drag moves it. A **NoteHandle** resizes an edge.
- **Marquee**: the box a drag across the bare grid draws. **SelectionSpan** shows the stretch the selection covers, and a **StretchHandle** in it stretches the selected notes.
- **VelocityLane** and **Velocity**: a bar under each note, whose height is its velocity (or its chance, with `level="chance"`), set by a drag or through its native input.
- **Keys**: gives the pitches drawn, the ones sounding and the audition calls, to draw a vertical [piano](/docs/components/base/piano#installation) beside the grid. The part is a grid of one cell, so the piano drawn inside takes its whole height and width: stretch the part beside the grid, and the keys line up with the rows.

**React**

```tsx
import type { Note } from "@/components/audio-ui/piano-roll/core";
import { Piano } from "@/components/audio-ui/piano/react";
import { PianoRoll } from "@/components/audio-ui/piano-roll/react";

export function Roll({ notes, onNotes }: { notes: Note[]; onNotes: (notes: Note[]) => void }) {
  return (
    <PianoRoll.Root
      className="flex"
      duration={16}
      maxPitch={72}
      minPitch={48}
      mode="select"
      onValueChange={onNotes}
      snapStep={0.25}
      value={notes}
    >
      <PianoRoll.Keys className="w-16">
        {({ active, keyOff, keyOn, pitches }) => (
          <Piano.Root
            activeNotes={active}
            layout="even"
            onNoteOff={keyOff}
            onNoteOn={keyOn}
            orientation="vertical"
            pitches={pitches}
          >
            {({ pitches }) => pitches.map((pitch) => <Piano.Key key={pitch} pitch={pitch} />)}
          </Piano.Root>
        )}
      </PianoRoll.Keys>
      <PianoRoll.Grid className="relative h-64 flex-1">
        <PianoRoll.Rows>{(pitch) => <PianoRoll.Row className="data-[color=black]:bg-muted" pitch={pitch} />}</PianoRoll.Rows>
        <PianoRoll.Notes>
          {(note) => (
            <PianoRoll.Note className="rounded bg-primary data-selected:ring-2" note={note}>
              <PianoRoll.NoteHandle className="absolute inset-y-0 right-0 w-1" edge="end" note={note} />
            </PianoRoll.Note>
          )}
        </PianoRoll.Notes>
        <PianoRoll.Marquee className="border border-primary bg-primary/10" />
      </PianoRoll.Grid>
    </PianoRoll.Root>
  );
}
```

**Vue**

```vue
<script setup lang="ts">
import type { Note } from "@/components/audio-ui/piano-roll/core";
import { PianoRoll } from "@/components/audio-ui/piano-roll/vue";

defineProps<{ notes: Note[] }>();
const emit = defineEmits<{ notes: [notes: Note[]] }>();
</script>

<template>
  <PianoRoll.Root
    :duration="16"
    :max-pitch="72"
    :min-pitch="48"
    :snap-step="0.25"
    :value="notes"
    @value-change="(next: Note[]) => emit('notes', next)"
  >
    <PianoRoll.Grid class="relative h-64">
      <PianoRoll.Rows>
        <template #default="{ pitch }"><PianoRoll.Row :pitch="pitch" /></template>
      </PianoRoll.Rows>
      <PianoRoll.Notes>
        <template #default="{ note }">
          <PianoRoll.Note class="rounded bg-primary data-selected:ring-2" :note="note">
            <PianoRoll.NoteHandle class="absolute inset-y-0 right-0 w-1" edge="end" :note="note" />
          </PianoRoll.Note>
        </template>
      </PianoRoll.Notes>
      <PianoRoll.Marquee class="border border-primary bg-primary/10" />
    </PianoRoll.Grid>
  </PianoRoll.Root>
</template>
```

**Svelte**

```svelte
<script lang="ts">
  import type { Note } from "$lib/components/audio-ui/piano-roll/core";
  import { PianoRoll } from "$lib/components/audio-ui/piano-roll/svelte";

  let { notes, onNotes }: { notes: Note[]; onNotes: (notes: Note[]) => void } = $props();
</script>

<PianoRoll.Root duration={16} maxPitch={72} minPitch={48} onValueChange={onNotes} snapStep={0.25} value={notes}>
  <PianoRoll.Grid class="relative h-64">
    <PianoRoll.Rows>
      {#snippet children(pitch)}
        <PianoRoll.Row {pitch} />
      {/snippet}
    </PianoRoll.Rows>
    <PianoRoll.Notes>
      {#snippet children(note)}
        <PianoRoll.Note class="rounded bg-primary data-selected:ring-2" {note}>
          <PianoRoll.NoteHandle class="absolute inset-y-0 right-0 w-1" edge="end" {note} />
        </PianoRoll.Note>
      {/snippet}
    </PianoRoll.Notes>
    <PianoRoll.Marquee class="border border-primary bg-primary/10" />
  </PianoRoll.Grid>
</PianoRoll.Root>
```

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

**JavaScript**

```html
<audio-ui-piano-roll duration="16" min-pitch="48" max-pitch="72" snap-step="0.25">
  <audio-ui-piano-roll-grid style="height: 16rem">
    <audio-ui-piano-roll-rows></audio-ui-piano-roll-rows>
    <audio-ui-piano-roll-notes handles></audio-ui-piano-roll-notes>
    <audio-ui-piano-roll-marquee></audio-ui-piano-roll-marquee>
  </audio-ui-piano-roll-grid>
</audio-ui-piano-roll>

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

  const roll = document.querySelector("audio-ui-piano-roll");
  roll.value = [{ id: 1, pitch: 60, start: 0, length: 2 }];
  roll.addEventListener("input", (event) => console.log(event.detail.value, event.detail.reason));
</script>
```

In the web adapter the rows, the notes (with a handle for each edge, with the `handles` attribute) and the velocity bars are made for you, one for each pitch or note, and style from their tags and `data-*` attributes. A note keeps its place among the others while it is dragged. The Keys part gives nothing in the web adapter: draw an `audio-ui-piano` beside the grid and set its `pitches` from the roll's.

### The timeline it sits on

The roll reads a timeline's length, grid, zoom and playback position. The UI SDK has no provider to read them from, so you give them to the Root, as the values you give the [Timeline](/docs/components/base/arrangement#installation):

- `duration`, `snapStep`, `snapOffset` and `snapPoints`: the length, the grid every gesture lands on unless Cmd/Ctrl is held, and what pulls a note onto it.
- `zoom`: px per unit, or unset while the roll fits its width. Control it, and give the same value to the Timeline, so the roll and the ruler stay aligned.
- `source` or `position`: the playback position, which Enter and the shortcuts that add at the playhead read. A `source` is a live value in the shape of an external store.

The Grid and the VelocityLane are lanes the Timeline's viewport finds in its DOM, so a roll inside a Timeline's Viewport scrolls and zooms with the ruler.

## Interaction

### Pointer

**Gestures**

| Gesture | Effect |
| --- | --- |
| Press on empty grid | With `mode="draw"`, draws a note whose end follows the pointer. With `mode="select"`, starts a selection rectangle (a double-click draws). `Shift` adds to the selection. |
| Drag a note | Moves it, with the selection when it is part of it. On the grid unless <kbd>Cmd</kbd> / <kbd>Ctrl</kbd> is held. |
| `Alt` + drag a note | Moves a copy. |
| Drag a note's edge | Resizes it: the end changes the length, the start trims it from the front. |
| `Shift` + click a note | Toggles it in the selection. |
| Double-click a note | Deletes it. |
| Drag a velocity bar | Changes the velocity of the selection by the same amount. |
| `Cmd` / `Ctrl` + drag a velocity bar | Sets how far the velocity of the selection may stray each time it plays. |
| Drag across a velocity or chance lane | With `mode="draw"`, paints every bar under the pointer to its height. |
| Drag a stretch handle | Stretches the selection in time from its other edge. |
| Press a key | Plays it; with `Shift`, selects every note on its row. |

### Keyboard

**Keys**

| Key | Effect |
| --- | --- |
| Arrow keys on a note | `Left` / `Right` move it by a grid step, `Up` / `Down` by a semitone. With `Shift`: resize it, or move an octave. |
| `Enter`, `Space` on a note | Toggle it in the selection. |
| `Delete`, `Backspace` | Remove the selected notes. |
| `Enter` on the grid | Adds a note at the playback position. |
| `Escape`, `Cmd` / `Ctrl` + `A` | Clear the selection, select every note. |
| `Cmd` / `Ctrl` + `D` | Repeat the selection right after itself and select the copies. |
| `Cmd` / `Ctrl` + `C`, `X`, `V` | Copy, cut, and paste at the playback position. |
| `Q` | Snap the starts of the selection (every note, with none selected) to the grid. |
| Arrow keys, `Page Up` / `Down`, `Home` / `End` on a velocity bar | Change the velocity by 5%, by 25%, or to silent or full. |

## API reference

**In React**

### Registry components

`PianoRoll` takes the `Root` props. The rest lay the editor out on two columns, the keys' and the timeline's:

**Components**

| Name | Description |
| --- | --- |
| `PianoRollViewport` | Scrolls the roll both ways, without scrollbars: put a `TimelineNavigator` above it to scroll and zoom across. |
| `PianoRollStrip` | A row of the editor: `lead` in the keys' column, stuck to the left edge, the lanes in `children` beside it. `sticky` keeps it at the `"top"` or `"bottom"` of the viewport. |
| `PianoRollKeys` | The keyboard down the side, one key per row. `size` is `"sm"`, `"default"` or `"lg"`; `names`, by pitch, writes a name on a key in place of its note's, such as a drum rack's pads. |
| `PianoRollGrid` | The notes, on their rows. `gridStep` draws a line every step, `accentStep` a firmer one, such as each beat; anything placed on the timeline, such as a `TimelinePlayhead`, goes in `children`. |
| `PianoRollVelocity` | Each note's velocity as a bar. |
| `PianoRollVelocityScale` | The scale beside the velocity lane, for the `lead` of its strip. |

### Options

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

| Option | Type | Default | |
| --- | --- | --- | --- |
| `value`, `defaultValue` | `Note[]` | `[]` | The notes: `{ id, pitch, start, length, velocity?, chance?, deviation?, muted? }`. Controlled, or the starting ones. |
| `selection`, `defaultSelection` | `NoteId[]` | `[]` | The ids of the notes selected. |
| `mode` | `"draw"` or `"select"` | `"select"` | What a press on the grid does. |
| `drawStyle` | `"paint"` or `"stretch"` | | How a drag in draw mode draws. |
| `minPitch`, `maxPitch` | `number` | `48`, `72` | The pitches the rows cover. |
| `folded` | `boolean` or `"scale"` | `false` | Draw only the pitches carrying notes, and with `"scale"` those in the scale too. |
| `scale` | `{ root, scale }` | | Marks the rows in a scale. |
| `minLength` | `number` | the grid step | The shortest note. |
| `activePitches` | `number[]` | | Pitches sounding from elsewhere: they light their rows and keys. |
| `getNoteLabel` | `(note) => string` | pitch name and span | Names a note for assistive technology. |
| `createNoteId` | `() => NoteId` | `"note-<n>"` | Makes the id of a note drawn, added or duplicated. |
| `disabled` | `boolean` | `false` | Takes no gesture. |
| `duration`, `snapStep`, `snapOffset`, `snapPoints`, `zoom`, `source`, `position`, `step` | | | The timeline's values, above. |
| `onValueChange`, `onValueCommitted` | `(notes, details) => void` | | The notes changed, and a gesture that changed them ended. |
| `onSelectionChange` | `(ids, details) => void` | | The selection changed. |
| `onNoteOn`, `onNoteOff` | `(pitch, details) => void` | | A key or a note auditioned a pitch. |

A Note, a NoteHandle and a Velocity take the `note` they belong to. A Velocity takes `level` (`"velocity"` or `"chance"`), and so does the VelocityLane.

### What a change reports

`details` carries:

- `reason`: what changed the notes, such as `"draw"`, `"drag"`, `"keyboard"`, `"paste"` or a command's name.
- `source`: `"mouse"`, `"touch"`, `"pen"`, `"keyboard"`, `"programmatic"` or `"agent"`.
- `event` and `cancel()`: the DOM event behind it, and the refusal. A controlled roll keeps the notes you give it.

In the web adapter, the notes are the `input` and `change` events, and the selection and the keys are `selectionchange`, `noteon` and `noteoff`, with a `detail` of the value and its reason. `event.preventDefault()` refuses a change.

### States to style from

- On the Root and every part: `data-mode`, `data-editing` while a pointer edits, `data-folded`, `data-disabled`; on the Root `data-has-selection`.
- On a note and its parts: `data-selected`, `data-muted`, `data-note` for its id. A note sets `--piano-roll-velocity` and `--piano-roll-chance`, a bar `--piano-roll-level` and `--piano-roll-deviation`, for what you draw inside them.
- On a row: `data-color` (`black` or `white`), `data-in-scale`, `data-out-of-scale`, `data-scale-root`, `data-octave`, `data-active`, and `data-pitch`.

### Parts

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `PianoRoll.Grid` | `div` |  |
| `PianoRoll.Keys` | `div` |  |
| `PianoRoll.Marquee` | `div` |  |
| `PianoRoll.Note` | `div` | `note: key` |
| `PianoRoll.NoteHandle` | composed of other parts |  |
| `PianoRoll.Notes` | `div` |  |
| `PianoRoll.Root` | `div` |  |
| `PianoRoll.Row` | `div` | `pitch: key` |
| `PianoRoll.Rows` | `div` |  |
| `PianoRoll.SelectionSpan` | `div` |  |
| `PianoRoll.StretchHandle` | composed of other parts |  |
| `PianoRoll.Velocity` | `div` | `getAriaValueText: value`, `level: string`, `note: key` |
| `PianoRoll.VelocityLane` | `div` | `level: string` |

**In Web**

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

`audio-ui-piano-roll`, `audio-ui-piano-roll-grid`, `audio-ui-piano-roll-keys`, `audio-ui-piano-roll-marquee`, `audio-ui-piano-roll-note`, `audio-ui-piano-roll-note-end`, `audio-ui-piano-roll-note-start`, `audio-ui-piano-roll-notes`, `audio-ui-piano-roll-row`, `audio-ui-piano-roll-rows`, `audio-ui-piano-roll-selection-span`, `audio-ui-piano-roll-stretch-end`, `audio-ui-piano-roll-stretch-start`, `audio-ui-piano-roll-velocity`, `audio-ui-piano-roll-velocity-input`, `audio-ui-piano-roll-velocity-lane`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |
| `onNoteOff` | `@note-off` | `noteoff` |
| `onNoteOn` | `@note-on` | `noteon` |
| `onSelectionChange` | `@selection-change` | `selectionchange` |
| `onValueChange` | `@value-change` | `input` |
| `onValueCommitted` | `@value-committed` | `change` |

