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, so notes use the timeline's units, snap to its grid and follow its zoom.
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 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.
The styled component, on a timeline, with its keyboard and lanes, is one command:
The styled component, with size variants and theme styles:
Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/piano-roll
Or the primitive alone, to style yourself:
Copy to Clipboardpnpm dlx 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:
Copy to Clipboardpnpm dlx shadcn@latest add @audio-ui/primitives-css
Usage
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:
Copy to Clipboardimport type { Note } from "@/components/audio-ui/piano-roll/core"; const [notes, setNotes] = useState<Note[]>([]);
Copy to Clipboardimport { 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 picks the scale the roll marks, Note find selects notes by what they are, and the Note edit menu runs the commands above on the selection.
Playing the notes
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.
Undo and redo
useUndoHistory undoes and redoes any value you hold.
Usage and API: useUndoHistory.
MIDI files
The midi-file library reads a .mid file onto the roll's steps and writes one back.
Usage and API: midi-file.
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.
Copy to Clipboardimport { 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.
Copy to Clipboardimport { 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.
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-octaveanddata-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 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.
Copy to Clipboardimport 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> ); }
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:
duration,snapStep,snapOffsetandsnapPoints: 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.sourceorposition: the playback position, which Enter and the shortcuts that add at the playhead read. Asourceis 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 · 11
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.mode="draw", paints every bar under the pointer to its height.Shift, selects every note on its row.Keyboard
Keys · 9
Left / Right move it by a grid step, Up / Down by a semitone. With Shift: resize it, or move an octave.API reference
Registry components
PianoRoll takes the Root props. The rest lay the editor out on two columns, the keys' and the timeline's:
Components · 6
PianoRollViewportTimelineNavigator above it to scroll and zoom across.PianoRollStriplead 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.PianoRollKeyssize 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.PianoRollGridgridStep 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.PianoRollVelocityPianoRollVelocityScalelead 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".eventandcancel(): 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-editingwhile a pointer edits,data-folded,data-disabled; on the Rootdata-has-selection. - On a note and its parts:
data-selected,data-muted,data-notefor its id. A note sets--piano-roll-velocityand--piano-roll-chance, a bar--piano-roll-leveland--piano-roll-deviation, for what you draw inside them. - On a row:
data-color(blackorwhite),data-in-scale,data-out-of-scale,data-scale-root,data-octave,data-active, anddata-pitch.
Parts
Parts · 13
note: key.pitch: key.getAriaValueText: value, level: string, note: key.level: string.Events
Events · 5
@note-off. Web: the noteoff event.@note-on. Web: the noteon event.@selection-change. Web: the selectionchange event.@value-change. Web: the input event.@value-committed. Web: the change event.