LabDAW

Arrangement

A DAW's arrangement: a zoomable timeline with a ruler that seeks and lanes of clips, and the parts around it, its state, clips, tracks, locators, automation and MIDI playback, each installed on its own.

An arrangement is tracks of clips along a song. It comes in two layers that install together and apart. The timeline draws and moves the clips on a zoomable ruler: lanes, ranges, a playhead and a navigator, with no notion of tempo. The arrangement parts hold what a DAW's arrangement needs around it: the state, the clips, track reordering, locators and time signatures, automation and MIDI playback. Each is a file you own, takes its state as values and reports changes through callbacks, so the arrangement can live in your own store and play through an engine of your own.

Installation

The whole arrangement installs with npx shadcn@latest add @audio-ui/arrangement-editor: every part below, with the timeline. A part installs alone by its name (@audio-ui/arranged-clip, @audio-ui/use-track-reorder…). The preview above is @audio-ui/block-timeline, which wires them into a screen around @audio-ui/arrangement-view. The steps below are the timeline on its own.

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, with the clips, the tracks and the navigator styled, is one command:

The styled component, with size variants and theme styles:

pnpm dlx shadcn@latest add @audio-ui/timeline

Or the primitive alone, to style yourself:

pnpm dlx shadcn@latest add @audio-ui/timeline-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:

pnpm dlx shadcn@latest add @audio-ui/primitives-css

The timeline

The registry component is written on the timeline primitive, which installs with it. The timeline has no notion of tempo: its units are whatever you count in (seconds, beats, pulses or steps). Musical time comes from the musical-time lib.

Overview

  • Units and zoom: duration is the length in your units, and zoom is the number of pixels per unit. Without zoom, the timeline fits its width. With it, every lane is as long as the timeline and the viewport scrolls.
  • Zooming: Cmd/Ctrl + scroll, or a trackpad pinch, zooms around the pointer. Every zoom change keeps its anchor point in place, or the middle of the view when there is none.
  • Grid: with a snapStep, the ruler snaps to the grid. Hold Cmd/Ctrl to place the playhead off the grid, and Shift to scrub four times finer.
  • Playback: pass a live source and every playhead follows it in the DOM, without a React render per frame.
  • Ranges: a TimelineRange is a stretch of the timeline, such as a loop, a selection or a clip. Drag it to move it, drag a handle to resize it, or, with drawable, drag across an empty lane to draw a new one. Ranges snap to the grid.
  • Navigator: TimelineNavigator shows the whole timeline as one bar, with the visible part inside it. Drag the window to scroll, drag an edge to zoom, and double-click to show everything. With scrollbar="hidden" on the viewport, it replaces the scrollbar.
  • Accessibility: the ruler, each range and range handle, and the navigator's window and edges hold a native <input type="range">, so every pointer action has a keyboard equivalent. The ruler's input spans the timeline: it takes focus, carries aria-label and announces the position (or the text from getAriaValueText, such as "Bar 3, beat 2"). The arrow keys move by step, Page Up / Page Down and Shift by largeStep, and Home / End go to the ends.

Usage

import {
  Timeline,
  TimelineLane,
  TimelineMark,
  TimelinePlayhead,
  TimelineRuler,
  TimelineViewport,
} from "@/components/audio-ui/timeline";
import {
  DEFAULT_TEMPO,
  describeBarsBeats,
  gridInterval,
} from "@/lib/engine/time";
const snapStep = gridInterval("adaptive", zoom, DEFAULT_TEMPO);

<Timeline
  duration={32}
  onPositionChange={(seconds) => transport.seek(seconds)}
  onZoomChange={setZoom}
  snapStep={snapStep}
  source={transport.position}
  zoom={zoom}
>
  <TimelineViewport>
    <TimelineRuler
      aria-label="Playhead"
      getAriaValueText={(seconds) => describeBarsBeats(seconds, DEFAULT_TEMPO)}
    >
      <TimelineMark value={0}>1</TimelineMark>
      <TimelineMark value={2}>2</TimelineMark>
      <TimelinePlayhead />
    </TimelineRuler>
    <TimelineLane gridStep={snapStep}>
      <TimelinePlayhead />
    </TimelineLane>
  </TimelineViewport>
</Timeline>

Ranges

const [loop, setLoop] = useState<readonly [number, number]>([8, 16]);

<TimelineLane>
  <TimelineRange aria-label="Loop" drawable onValueChange={setLoop} value={loop}>
    <TimelineRangeHandle aria-label="Loop start" edge="start" />
    <TimelineRangeHandle aria-label="Loop end" edge="end" />
  </TimelineRange>
</TimelineLane>

The range's own input moves it with Left and Right, by the timeline's step, and with Up and Down by its own length; Cmd/Ctrl + Left and Right shorten or lengthen it by a step, Cmd/Ctrl + Up and Down double or halve it; each handle's input moves its edge, which stops minLength short of the other one (the grid step by default). onValueChange receives [start, end] and eventDetails with the edge that moved ("start", "end" or "both") and the reason ("drag", "draw", "keyboard" or "input-change"). Leave the handles out for a range that only moves, or pass movable={false} for one that only resizes.

Tracks

A track is a row: a header beside a lane. Timeline.Track holds the row, Timeline.TrackHeader is the strip that names it and stays at the left edge while the lane scrolls, and Timeline.TrackResizeHandle sets its height. You hold the height: leave it out and the row shares the room it is given; set it and the row keeps it.

const [height, setHeight] = useState<number | undefined>();

<Timeline.Track
  height={height}
  onHeightChange={(next) => setHeight(next)}
  selected={selected}
>
  <Timeline.TrackHeader>
    Drums
    <Timeline.TrackResizeHandle aria-label="Height of Drums" />
  </Timeline.TrackHeader>
  <Timeline.Lane>{/* clips */}</Timeline.Lane>
</Timeline.Track>;

You put the header's controls in it, such as solo, mute and gain. The track does not know about them.

The block reorders tracks by their grip, the bar at the track's left edge: press it and drag. A copy of the track's header follows the pointer, the dragged track stays in place faded, and a line marks the place it would land in. Near the top or bottom of a view that scrolls, the view scrolls on its own while the track is held. The arrow keys move a focused grip one place up or down, and every move is one undo step with its clips. The move is moveTrack(id, index) in useArrangement; it uses a pointer drag rather than the browser's drag and drop, so it does not depend on how the browser handles a drag.

Clips

A clip is a stretch of a source (a recording, a pattern) laid on a track. It is a range that knows about its source: trimming its start moves where in the source it begins, so its content stays where it is, and it cannot show more than the source holds.

const [clip, setClip] = useState<Timeline.Clip.Value>({
  start: 8, // where it sits on the timeline
  length: 16, // how long it plays
  offset: 4, // where in the source it begins
  fadeIn: 0,
  fadeInShape: "linear", // or "fast", "slow", "smooth"
  fadeOut: 0,
});

<Timeline.Lane data-track="drums" seekable>
  <Timeline.Clip
    aria-label="Drums, Groove"
    onRemove={() => removeClip()}
    onValueChange={setClip}
    sourceLength={48}
    value={clip}
  >
    <Timeline.ClipHeader>Groove</Timeline.ClipHeader>
    <Timeline.ClipFade edge="in" />
    <Timeline.ClipFade edge="out" />
    <Timeline.ClipHandle aria-label="Groove start" edge="start" />
    <Timeline.ClipHandle aria-label="Groove end" edge="end" />
    <Timeline.ClipFadeHandle aria-label="Groove fade in" edge="in" />
    <Timeline.ClipFadeHandle aria-label="Groove fade out" edge="out" />
  </Timeline.Clip>
</Timeline.Lane>

All of it is in the timeline's units, the source's too. Dragging the clip's header, its title bar, moves it on the grid, and over other lanes: eventDetails.lane is the Timeline.Lane under the pointer, so put your own attribute on each lane (data-track above) and read it in onValueCommitted, which also fires for a drop on another lane that left the position as it was. The clip follows the pointer vertically through --clip-drag-y. A press on the clip's body selects it and puts the cursor there, and a drag scrubs, so the body never moves the clip by accident. Its content is yours: it sets --clip-offset and --clip-source-length so a Waveform can show the stretch that is played.

Holding Alt when a drag begins marks it as a copy (eventDetails.copy): the clip you were dragging is the copy, so leave the original where it was and add the dragged one. A fade's shape is stepped by double-clicking its handle, or Enter on its input (reason is "double-click" or "keyboard"), and ClipFade draws the real ramp. The registry's TimelineClipFadeHandle also takes onShapeChange: a right-click on the handle lists the four curves, each drawn, and the arrangement's setFadeShape(id, edge, shape) sets one as a single undo step.

Laying a clip where others already are is coverClips(clips, placed, { duration }, split): the clips under it are covered rather than stacked (removed, trimmed or cut in two around it), and split makes the second piece of a cut clip from the first, so what your app keeps about a clip travels with each piece. Covering only shortens a clip, so the timeline's duration is the one limit it reads: the length of a source, which limits how far one clip stretches, never applies to the clips under it.

Cutting, copying and the like are plain functions on the clip, for the model behind your clips: splitClip(clip, at) returns the two pieces (or null when at leaves one too short), and moveClip, trimClipStart, trimClipEnd, setClipFadeIn, setClipFadeOut, setClipFadeShape and duplicateClip return the clip as it would end up, within the limits you give them.

Many clips

Dragging one clip among 1 000 takes about a millisecond of script, and the playhead moves outside React, so it costs no render. The real cost is rendering every clip again whenever one moves, which happens when the clip component is not memoized. Put one clip in a React.memo component with stable props (the clip's own value, callbacks that take its id), so React skips every clip a drag did not touch.

Selecting several clips

The primitive keeps no selection: selected and onSelectedChange are yours, so a selection is any set of ids you keep. onSelectedChange fires when a press selects a clip, and again on a press with Shift, Cmd or Ctrl held (read eventDetails.event), which is how you add to a selection or take from it. A touch screen has no modifier keys: give the clip additive (from a "select several" mode of your own) and every press is reported, so a press adds a clip to the selection or takes it from it. To move a group, read eventDetails.delta on a move, how far the dragged clip is from where the drag began, and move each other selected clip by the same amount from where it was when the drag began; moveClip keeps each on the timeline. For the group to follow the clip up and down too, onDragOffsetChange reports how far it is dragged vertically, in px, and 0 when the drag ends: shift the other selected clips by that much. A drop on another lane then moves each by as many lanes as the dragged one did. The registry's arrangement block does all of this, with Cmd/Ctrl + A to select every clip and Shift + drag across bare lane to select the clips a rectangle touches (it measures each clip's getBoundingClientRect(), so it needs nothing from the primitive).

The cursor

A Timeline.Lane with seekable puts the position where a press lands on its bare area, as the ruler does, and a drag scrubs it. Presses on the clips in it go to the clips. The cursor can then go anywhere along a track, and your track header selects the whole track. A split is then splitClip(clip, position) on the selected clip, or on each clip of the selected track that the cursor is over.

<Timeline zoom={zoom} onZoomChange={setZoom} duration={32}>
  <TimelineViewport scrollbar="hidden">…</TimelineViewport>
  <TimelineNavigator />
</Timeline>

Place it anywhere inside the timeline, outside the viewport. Dragging an edge zooms while holding the other edge in place, through onZoomChange with reason: "drag"; a double-click fits the whole timeline with reason: "double-click".

Musical time

@/lib/engine/time turns a tempo into what a timeline needs, in seconds:

  • gridInterval(division, zoom, tempo) is the grid's step: a fixed division ("1-bar", "1/8", …), or "adaptive" for the finest division still 24px apart at this zoom. Pass { triplet: true } for three in the space of two. Give the same number to snapStep and to the lanes' gridStep, so gestures land on the lines you see.
  • barLabelInterval(zoom, tempo) is how far apart the ruler's bar numbers go: whole bars, spread out until they no longer collide.
  • barsBeatsAt(seconds, tempo) and describeBarsBeats read a position as bars, beats and sixteenths.
  • gridLabel(seconds, tempo) names an interval the way a grid readout does ("1 bar", "1/16", "1/8T"), so the adaptive grid reads out the division it uses, and a menu and a readout always name a grid the same way.
  • metronomeRhythmSeconds(rhythm, tempo) is the interval of a click rhythm ("1/8", "1/8t", …), or null for "auto", which follows the beat.

Zoom and grid

Two hooks hold what the view needs to zoom and snap, so every arrangement zooms and snaps the same way:

import { GRID_DIVISION_OPTIONS, useTimelineGrid } from "@/hooks/use-timeline-grid";
import { useTimelineZoom } from "@/hooks/use-timeline-zoom";

const viewportRef = useRef<HTMLDivElement>(null);
const view = useTimelineZoom({ duration, viewportRef });
const grid = useTimelineGrid({ tempo, zoom: view.zoom });

<Timeline duration={duration} snapStep={grid.snapStep} {...view.timeline}>
  <TimelineViewport ref={viewportRef}>
    <TimelineLane gridStep={grid.snapStep}>…</TimelineLane>
  </TimelineViewport>
</Timeline>
  • useTimelineZoom fits the whole arrangement in the room beside the track headers until it is zoomed, and never goes wider. A Cmd/Ctrl + scroll zooms around the pointer; zoomAround(at, factor) keeps a time where it is on screen, as the + and - keys do around the cursor, zoomTo(start, end) fits a stretch (Z on the selection), and zoomBack() steps back through the zooms they left (X). ratio and setRatio read and set it as a share of the fitted view, and rescale(ratio) keeps it on the same bars when the tempo changes.
  • useTimelineGrid is the grid: adaptive or a fixed division, triplet, snapping. step is what the lanes draw, snapStep what gestures snap to (0 with snapping off), and label names it for the button that opens TimelineGridMenuItems with GRID_DIVISION_OPTIONS. change is what Cmd/Ctrl + 1 to 5 do, by the key's place in GRID_KEYS: a finer or wider grid, triplets, snapping, and a grid fixed where it is or following the zoom again.

Placing your own parts

Every lane sets a --timeline-unit CSS variable, the width of one unit. Parts are placed with it, so anything you draw follows the zoom the same way:

<div style={{ left: "calc(var(--timeline-unit) * 12)", position: "absolute" }} />

The arrangement

The parts on this page hold the arrangement and fill in what a DAW's arrangement needs around the timeline.

The state

  • arrangement (npx shadcn@latest add @audio-ui/arrangement) is the document: the types of a clip, a track and a mix, and what reads them. An audio clip names the recording it plays in recording, which every piece and copy of it keeps, and a track's devices and sends are its chain and what it sends to the return tracks. clipReach is how far a clip can stretch, playedNotes where a MIDI clip's notes play, and mixAt what a track plays at a point of the song. Its edits ship with use-arrangement, in lib/arrangement-state: lay puts a clip on a track so it covers what is under it, land drops a dragged group (or its copies) on another track, shiftTrack and otherSelected are what a group drop needs, and scaleValue rescales a clip when the tempo changes. Tracks are passed as an order of ids, so nothing assumes how many there are.
  • use-arrangement is the state: tracks, clips, selection, each track's mix, its device chain and its sends, the return tracks and the main track, each track's height, the tempo, the time signatures, the locators and the loop, and every operation on them. It keeps undo and redo over all of them together.
  • use-marquee-selection is the rectangle that selects the clips it touches.
const arrangement = useArrangement({
  duration, // the length of the song in seconds when it starts; a change of tempo scales it
  initialClips,
  initialLocators, // { at, name }[], in seconds
  initialLoop, // { on, range: [start, end] }
  initialTracks, // { id, name, color, kind?, mix?, devices?, sends? }[]
  initialReturns, // the return tracks, [] by default
  initialMain, // the main track, MAIN_TRACK by default
  tempo, // { bpm, beatsPerBar, beatUnit }
});

arrangement.clips; // what the arrangement holds, with tracks, tempo, signatures, locators, loop and duration
arrangement.dispatch({ type: "add-track" }); // every change is a command; it returns the state after it
arrangement.dispatch({ type: "undo" });

The state is a plain value and a change is a command of ArrangementCommand, which lib/arrangement-state's apply(state, command) takes: a pure function, so the arrangement runs, and is tested, with no React. The hook holds the state and returns it with dispatch, which returns the state after the command. A command that changes nothing returns the same state and adds no step to the history.

  • Clips: add-clip, change-clip (what Timeline.Clip reports on a drag, by id), commit-clip (lands the drag, on another track too), edit-clip, remove-clip, rename-clip, set-fade-shape (a fade's curve, as one undo step), crop-clip, clip-action (a clip's menu: duplicate, split, switch off, delete), duplicate-selection and split-cursor (at and the shortest piece step come with the command, since the host knows the playhead). A drag is a burst that settle-clip-edit closes into one step. A clip that commit-clip lands or edit-clip changes past the end of the arrangement makes it longer, duration growing to hold it in the same step.
  • Selection: select-clip (id, additive), select-clips, select-all, select-track (id, additive), clear-selection and toggle-selected. The hook returns selectedIds, selectedTracks and selection.
  • Tracks: add-track (with a name, as a dropped file gives one, and an id it takes while no track has it, so a batch can put clips on the new track; kind: "return" adds a return track, named by its letter, after the others), remove-track (a return takes every send to it with it; the main track stays), rename-track, duplicate-track (the track with its clips and its mix, placed after it), move-track, set-mix (a switch: mute, solo) and change-mix (a drag of the gain or the pan, closed by settle-clip-edit), and set-track-color (an index or a CSS hex). A track's mix is its mix, so it is undoable; mixOf(track) is what a header reads. heights, resizeTrack, folded and toggleFold stay in the hook, since they are the view and not the document. copyOf(time) is a read, not a command: what a copy would hold.
  • Devices: a track's chain is its devices, from first to last, each { id, device, state, on?, instrument?, key? }: device is the device's stable id, such as audioui.compressor, and id the place it holds, which stays the same as it moves. add-device puts one at index or at the end, move-device moves it along the chain or to another track's with to, remove-device and toggle-device (switched off, it passes the sound on unchanged) are one step each, set-device sets its state as one step and change-device is a turn of a knob, closed by settle-clip-edit. An instrument (instrument: true) goes first on a MIDI track, in place of the one there was, and no effect goes before it; it goes on no other track. A device that takes a sidechain, such as the Ducker, listens to the track its key names, that track's sound after its devices and before its volume, so a muted kick still keys: set-device-key sets it, or null for its own sound, and only a track of clips other than its own can key it. The commands take the id of any track: one of the tracks, a return or the main track.
  • Sends and returns: set-send and change-send (a drag, closed by settle-clip-edit) set how much a track sends to a return, { track, to, level }, a gain from 0 (silence, the default) to 1 (0 dB). set-send-mode sets whether a return takes what it is sent before the senders' volume, pan and switch (pre) or after. The return tracks are returns and the main track main, which the mix commands (set-mix, change-mix, rename-track, set-track-color) reach by their ids like any track; allTracks(doc) and trackOf(doc, id) read them all.
  • Time: clear-time, paste, remove-time, insert-time, consolidate-time and fade-time act on a time selection ({ range, tracks }), and copyOf(time) copies one; insert-time and remove-time move the locators, the time signatures and the automation after the stretch with the clips (marksAfterInsert, marksAfterRemove, automationAfterInsert, automationAfterRemove); a locator in a stretch removed goes with it, one at its start too, a time signature in it starts where it did, and remove-time brings the loop along (loopAfterRemove: a time inside it comes back to where the stretch began); an envelope holds its value across time inserted; set-duration keeps every automation point at its time (automationForDuration); lib/arrangement-state holds them as pure functions: copyTime, clearTime, pasteTime, deleteTime, openTime, consolidate, with crossfade for a fade where two clips meet, given to both. consolidate-time merges a MIDI track's notes; for an audio track, render its clips with renderTrackClips(doc, track, range, recordings) from arrangement-engine (they play without the track's chain), keep the result as a recording, and name it in the command's rendered, by track. audioClipsIn(clips, track, range) says which clips a track would render. useTimeSelection calls onConsolidate(time) on Cmd/Ctrl + J for that. Without one, an audio track takes a copy of its first clip.
  • Tempo, signatures, locators and the loop: set-tempo keeps the musical positions, so every time in the document is scaled to the new bar and a MIDI clip three bars long stays three bars long, as one undo step, since each step of the history carries its own tempo. A recording follows the tempo only when it is warped, through its markers, the recording itself staying as it is; one that is not warped keeps its speed, so its start follows the bar and it lasts as many seconds as before, and where that runs it into the next clip it ends there (settleOverlaps). Then add-signature, set-signature, move-signature and remove-signature, add-locator, rename-locator and remove-locator, set-loop ({ on, range }, either one) and change-loop, a drag of the range that is one step once settle-clip-edit closes it, and set-duration, which changes the song's length without a step. The hook returns tempo, signatures, locators, loop and duration.
  • History: undo and redo, and canUndo and canRedo. batch ({ commands }) applies several commands in order as one step, each seeing what the one before it did: what one gesture that makes several changes sends, such as files dropped to make a track each.

The arrangement view

arrangement-view (npx shadcn@latest add @audio-ui/arrangement-view) is the whole arrangement as one controlled element: the loop, the ruler, the locators and time signatures, a row per track with its header, meter, automation and clips, the return and group tracks, the main track last, and the row under the last track that takes dropped files. Everything plays through the main track: its row picks it, so its devices show, and it takes a device dropped on it, its volume, its pan and its envelopes, with no solo, mute, rename or delete. It is the view the preview above and the workstation draw their tracks with. State comes in through the hooks of the parts below, and every change goes out as a command or a callback, so it runs over an engine of your own.

<ArrangementView
  arrangement={arrangement} // useArrangement
  automation={automation} // useTrackAutomation
  engine={engine} // useArrangementEngine: the position and the meters
  findDevice={(id) => library.find(id)} // a device's description, for the automation chooser
  getCursor={getPosition} // where the cursor is, read when it is needed
  liveTake={null} // a take recording now, drawn as it grows
  markers={markers} // useTimelineMarkers
  onAddMidiClip={(track, at) => {}} // a double-click on a MIDI lane
  onEditClip={() => {}} // a clip's title bar pressed, or its menu's Edit
  onFiles={(files, track, at) => {}} // track is NEW_TRACK under the headers
  onSeek={seek}
  onSelectTrack={selectTrack}
  peaksOf={(clip) => peaks.get(clip.id)} // what a clip draws of its sound
  reading={[]} // files dropped and still being read
  selectedTrack={selectedTrack}
  timelineGrid={grid} // useTimelineGrid
  timelineZoom={zoom} // useTimelineZoom
  timeSelection={timeSelection} // useTimeSelection
  viewportRef={viewportRef}
/>

Past the arrangement's end, the view shows room, shaded on the tracks: four bars, or a tenth of its length on a long song. A clip moved or stretched into it makes the arrangement longer as it lands. Give the zoom the length with that room, useTimelineZoom({ duration: shownLength(duration, tempo), viewportRef }), so it fits all of it.

What an app owns stays out of the view. peaksOf gives the peaks of the sound a clip plays, and sourceOf its recording ({ samples, channels, sampleRate }): given it, and WebGL 2 there, a clip draws its waveform on the GPU, every column its exact lowest and highest sample at any zoom and a row a channel on a tall track, all the clips on the page's one WebGL context, read from where the clip was cropped from its recording (sourceFrom); a reversed clip is drawn from its peaks. findDevice the description of a device by its id, and shortcuts the keys to show beside each kind of track in the add-track menu. onArm and armed add an Arm button to the tracks that record, onDevice makes the view take a device dragged from device-browser, and multiSelect makes a press add to the selection, for a touch screen. Leave a prop out and what it drives is not drawn.

Arranged clips

ArrangedClip (npx shadcn@latest add @audio-ui/arranged-clip) is a clip of the arrangement on its track's lane: drag its title bar to move it (with Alt, a copy), its edges to trim it into its source, the top corners of a recording to fade it, and pick a fade's curve from the menu of its handle; a MIDI clip has no fades, since its notes play whole. Held near an edge of the view, a moved or trimmed clip scrolls it, so it can go past what is on screen or to a track below; let go off the tracks (over the ruler, or the rows under the last track), a moved clip goes to the nearest track that takes it, a recording to an audio track and a MIDI clip to a MIDI one. Double-click its title to rename it in place; right-click it for its menu (edit, rename, duplicate, split at the cursor, switch off, delete), which selects it first and shows the keys the timeline runs them with: Cmd / Ctrl + D, Cmd / Ctrl + E, 0 and Delete. A MIDI clip draws its notes across its body and an audio clip its waveform, from the peaks of its source, and a looped clip has no end while a warped one lasts as long as its warp stretches its source: clipReach(clip) in lib/arrangement gives how far a clip can be stretched, undefined when it loops.

import { ArrangedClip, ArrangedClipGhost } from "@/components/audio-ui/arranged-clip";

<TimelineLane>
  {clips
    .filter((clip) => clip.track === track.id)
    .map((clip) => (
      <ArrangedClip
        clip={clip}
        describe={describe}
        key={clip.id}
        onAction={(action, id) =>
          arrangement.dispatch({
            type: "clip-action",
            action,
            id,
            at: clock.getSnapshot(),
            step: bar / 4,
          })
        }
        onChange={(id, value, details) =>
          arrangement.dispatch({ type: "change-clip", id, value, details })
        }
        onCommit={(id, details) =>
          arrangement.dispatch({
            type: "commit-clip",
            id,
            copy: Boolean(details.copy),
            track: details.lane instanceof HTMLElement ? details.lane.dataset.track : undefined,
          })
        }
        onFadeShape={(id, edge, shape) =>
          arrangement.dispatch({ type: "set-fade-shape", id, edge, shape })
        }
        onRemove={(id) => arrangement.dispatch({ type: "remove-clip", id })}
        onRename={(id, name) =>
          arrangement.dispatch({ type: "rename-clip", id, name })
        }
        onSelect={(id, additive) =>
          arrangement.dispatch({ type: "select-clip", id, additive })
        }
        selected={arrangement.selectedIds.includes(clip.id)}
        swatch={arrangement.mixOf(track).color}
        trackName={track.name}
      />
    ))}
</TimelineLane>;

While a clip is dragged with Alt, arrangement.copying lists the originals: draw an ArrangedClipGhost for each, where it stays. lift and onLift move the rest of a selection up or down with the clip being dragged across tracks.

With snapping on, a dragged clip or loop also lands on the edges of the other clips, the locators and the loop, through snapPoints. Where two clips meet, the fade-out of one and the fade-in of the next move together, as a crossfade, and a dashed line shows how far a fade being dragged can go.

useArrangedClips ships with them and wires a clip to the arrangement's commands. Spread clipProps(clip) on ArrangedClip, with what draws it (describe, peaks, swatch, trackName), and draw ghostsOn(trackId) with ArrangedClipGhost for the originals of a copy dragged with Alt. A clip dropped on a track moves to it if the track takes what it holds, and let go off the tracks it goes to the nearest one; the rest of a selection follows a clip dragged up or down. ArrangedTake draws a take while it records: from from to the live position, its levels (the loudest of each equal stretch so far, a live list) as they come in.

Arranged tracks

A track's header is TimelineTrackControls, from the timeline: its name, gain, pan, mute, solo, color, fold and menu. Where a mixer shows each track's gain and pan, as a workstation's does under the tracks, mixControls={false} on ArrangementView (or on the header) leaves them to it, and the header keeps its name, solo, mute and arm. Its meter takes a level down its right edge: TrackLevel (npx shadcn@latest add @audio-ui/track-level), given analysers={engine.meter(track.id)}, is the one that goes there. useTrackReorder moves tracks: give each track a grip, and drag the grip, or press Up or Down on it. Its Solo, Mute and Arm are one toggle group: pressed, Solo is tinted with --solo and Mute with --mute, a blue and an amber when the theme sets neither, and Arm is a red Led. SWITCH_TONES gives those two looks to switches of your own, such as a mixer's. A track's color is an index into TRACK_COLORS, or a CSS hex of the user's own (color: "#3e63dd"): the header's menu has a Color submenu with the palette and a Custom entry that opens the browser's color picker. trackSwatch(color) gives the classes and the style that paint either one, for a strip or a dot of your own.

import {
  TrackGrip,
  TrackReorderGhost,
} from "@/components/audio-ui/track-grip";
import { useTrackReorder } from "@/hooks/use-track-reorder";

const reorder = useTrackReorder({
  onMove: (id, index) => dispatch({ type: "move-track", id, index }),
  order: tracks.map((track) => track.id),
});

<TimelineTrack>
  <TimelineTrackHeader>
    <TrackGrip
      dragging={reorder.draggingId === track.id}
      trackName={track.name}
      {...reorder.gripProps(track.id)}
    />
    …
  </TimelineTrackHeader>
</TimelineTrack>;

<TrackReorderGhost
  ghost={reorder.ghost}
  ghostRef={reorder.ghostRef}
  trackName={dragged?.name}
/>;

The grip sits in its track's row, inside the Timeline. While a track is dragged, draggingId is the track, and it shows dimmed where it would land, the other rows aside. ghost is the box of its header, and TrackReorderGhost draws the copy under the pointer, fixed, which the drag moves without a render and settles into the gap. The view scrolls when the pointer nears its top or bottom edge, and Escape puts the track back. With blockOf, the tracks of a group move with it. The grip and the copy ship with the hook, in components/audio-ui/track-grip.

Groups

A track can sit in a group track: it names it in group, and a group's tracks follow it in tracks. The group is a track of its own (kind: "group"), with its chain, its mix and its sends, and the tracks in it play into it instead of into the main track. A group can hold groups.

  • { type: "group-tracks", ids } puts tracks into a new group where the first of them was. { type: "ungroup", id } dissolves one, its tracks going up a level.
  • A group moves, is duplicated and is removed with its tracks; a track moved among a group's tracks joins it.
  • TimelineTrackControls puts "Group" and "Ungroup" in a track's menu when given onGroup and onUngroup (give onUngroup to a group track only).
  • TimelineTrackControls leaves out its gain and pan when given output={false}: for a track with no output, such as a MIDI track with no instrument.
  • TimelineTrackControls leaves out its solo and mute when given switches={false}: for the main track, which everything plays through.
  • unfoldedTracks (from useArrangement) leaves out the tracks of a folded group. trackBlock and trackDepth give a group's tracks and how deep a track sits, to indent its header.
  • ArrangedGroupPreview, from arranged-clip, draws on a group's lane what its tracks play.

Time selections

useTimeSelection is a stretch of time on some tracks and what the keyboard does with it: useTimeSelection.

Locators and time signatures

TimelineLocator and TimelineSignature (npx shadcn@latest add @audio-ui/timeline-markers) go on a lane of their own, and stand on their time with their line. A locator is a named point: press it to put the cursor there, double-click it to play from there, drag it or press Left and Right to move it on the grid (Cmd/Ctrl lets go of the grid), press Enter or pick Rename in its menu to rename it, Delete to take it away. A change of time signature moves the same way. The block's M adds one at the cursor, and Alt with the arrows jumps from one to the next. A locator given onLoopToNext has "Loop to the next locator" in its menu: the loop from it to the next one, or to the end, turned on.

import { TimelineLocator, TimelineSignature } from "@/components/audio-ui/timeline-markers";

<TimelineLane>
  {locators.map((locator) => (
    <TimelineLocator
      key={locator.id}
      locator={locator}
      onJump={seek}
      onMove={moveLocator}
      onPlay={playFrom}
      onRemove={removeLocator}
      onRename={renameLocator}
      step={grid}
    />
  ))}
</TimelineLane>;

useTimelineMarkers ships with them and holds the commands: spread its locator on TimelineLocator and its signature on TimelineSignature, with editing set for the change editingSignature names. addLocator puts a locator at the cursor, addSignature a change, opened to be typed. TimelineBarMarks, inside a TimelineRuler, numbers the bars through those changes, every few bars at a far zoom, and hatches the ones a change cuts short.

useTimelineCursor is what the keys do with the cursor: M adds a locator, Alt and the arrows jump between locators and clip edges, the plain arrows move it on the grid: useTimelineCursor.

The Signature strip holds time-signature changes: its + adds one at the cursor, in the signature already there, ready to be typed (such as 7/8). From a change on, bars are counted in its signature: the ruler's numbers, the hatched partial bar a change cuts short, and the position in the transport all follow, through barsOf and barsBeatsWith from @/lib/engine/time. On a change, Left and Right move it by a grid step, Enter edits it and Delete takes it away. The grid's bar-long divisions and the tempo stay those of the song's start. Which change is being typed is yours to hold (editing and onEditingChange), so a change just added opens ready to type. parseSignature("7/8") reads what is typed.

Audio files

Drag an audio file from the desktop onto an audio track: the track is outlined while the file is over it, and let go, the file becomes a clip at the grid line under the pointer (anywhere with Cmd/Ctrl), named and as long as the file. Several files follow each other on the track, and a file let go anywhere else in the view does nothing. The block decodes a file at the engine's rate with decodeAudioChannels from lib/audio-decode (npx shadcn@latest add @audio-ui/audio-decode), keeps it as a recording the clip names (recording), and takes its peaks with computePeaks from @/lib/engine/analysis: the clip draws its waveform, and it plays.

A file comes in warped, in Beats, so it plays in time at the arrangement's tempo: analyzeBeat from @/lib/engine/analysis reads its tempo once, as it is decoded, with @audio/beat-detect, then fits the beat grid on its transients (detectTransients from @/lib/engine/analysis), so a tempo between whole BPM holds over a long file; warpOnImport warps the clip. A short file that 1, 2, 4, 8 or 16 bars fit at that tempo is taken as that loop, its tempo the one its length gives; a longer one gets a warp marker on the first beat of each bar, moved onto the nearest transient, and starts on its first beat. The clip panel's BPM shows the tempo it was read at: if a loop was read at twice or half its tempo, ÷2 or ×2 sets it right. A file with no attack, silence or noise, plays as recorded.

import { analyzeBeat } from "@/lib/engine/analysis";
import { warpOnImport } from "@/lib/arrangement";

const clip = warpOnImport(laidDown, analyzeBeat(channels, sampleRate), tempo);

Automation

Press A, or the automation button, for automation mode: each track's header gets a chooser of what its lane shows, Volume or Pan, and its lane the envelope of that parameter over its clips (automation-envelope, npx shadcn@latest add @audio-ui/automation-envelope). Until the track has one, the line stands faint at the mix's value; double-click it to add a point, drag a point to move it on the grid (its level stays free), drag the small handle on a segment to bend it, and double-click a point to take it away. Beside the line, a press reaches the lane and the clips as before. Each track's channel follows its envelopes as it plays. Moving an automated gain or pan by hand overrides it: the envelope greys, the mix plays, and Re-enable automation in the toolbar (or drawing on the envelope) brings it back. In lib/arrangement, a track keeps its automation per parameter as points across the whole arrangement, x from 0 to 1, so a tempo change keeps them in place; automationAt reads one, volumeGain and panPosition turn its values into a gain and a pan, and mixAt gives what a track plays at a point of the song.

TrackAutomationChooser and TrackAutomation (npx shadcn@latest add @audio-ui/track-automation) are those two parts: the chooser goes in the track's header (TimelineTrackControls takes it as children), the envelope in its lane. AUTOMATED_PARAMETERS lists a track's own parameters, Volume and Pan. Its devices' parameters, and its racks' macros, can have an envelope too: deviceTargets(track.devices, libraryDevice) lists them, device by device, for the chooser's targets and the envelope's, and the engine sets each to where its envelope stands every 10 ms, playing and in an export. An envelope of a device is keyed device:<device>:<parameter> (deviceParameterKey); a device removed takes its envelopes along, and a duplicate's follow its new ids. useTrackAutomation ships with them and holds the mode; tell it a device's parameters moved by hand with deviceMoved(trackId, device, parameters), and those automated play as set until reenable. For the controls to move with their envelopes as the arrangement plays, give them what these return, each rendering only when what it shows changes: useAutomatedMix(track, following) for a fader and a pan, useAutomatedDevice(track, device, denormalize, following) for a device's panel (keep only what the hand moved when it calls back: it hands over its whole state), useAutomatedRack(track, device, rack, following) for a rack's macros, with following as { duration, overridden, position }:

import { useTrackAutomation } from "@/hooks/use-track-automation";

const automation = useTrackAutomation({ dispatch, tracks });
const engine = useArrangementEngine({ doc, overridden: automation.overridden, recordings });

<TimelineTrackControls onMix={automation.changeMix} …>
  {automation.automating ? (
    <TrackAutomationChooser
      onClear={automation.clear}
      onParameterChange={automation.show}
      parameter={automation.parameterOf(track.id)}
      targets={deviceTargets(track.devices ?? [], libraryDevice)}
      track={track}
    />
  ) : null}
</TimelineTrackControls>;

automating and toggle are the mode, parameterOf and show what each lane shows. A gain or a pan moved through changeMix overrides an automated one: overridden lists, by track, what plays its mix instead, for the engine and for TrackAutomation's greyed line, until reenable (anyOverridden says when to offer it) or until edit draws that envelope again. clear takes an envelope away in one step of undo.

MIDI clips

A track can also hold MIDI: in the block, every track is, Drums, Bass, Organ, Lead and Pad, and + MIDI under the tracks adds one. A MIDI clip draws its notes across its body and, picked, opens on a piano roll in the clip panel (midi-clip-panel, npx shadcn@latest add @audio-ui/midi-clip-panel), with the same strip, and its Clip and Loop boxes in a column beside the roll. A bar over the roll carries Draw, Notes and View. Notes holds the commands of the note edit menu by what they change, Time, Pitch, Play and Velocity, and Duplicate the loop, which plays the loop's notes again after it: each acts on the selected notes or every note, and the same menu opens on a right-click on the roll, its keys working while the roll has the focus. View folds the roll to its notes and picks the lane under them, velocity or chance. Draw notes a grid step at a time, drag the loop brace on its ruler, move, stretch and edit them as in the piano roll, and each edit is one undo step of the arrangement. Double-click a bare MIDI lane for an empty clip a bar long, which loops as it is stretched. While the arrangement plays, their notes go to the instrument of the track's chain (in the block, a drum rack with a Drum Synth on every pad on Drums, a mono synth on Bass, an organ on Organ and on Lead, and a string machine on Pad), each at its frame of the audio clock, through the track's channel; a key pressed in the piano roll plays the same instrument. In lib/arrangement, a track's kind is "audio" or "midi", a MIDI clip keeps its notes in its source's time, and playedNotes gives where they play through the clip's offset and loop.

Drums

Drums are MIDI too, as the block's are: a MIDI track whose instrument is a drum rack, each pad playing a Drum Synth through its own effects, so every hit is a note you can edit, every sound a device you can shape. Give the clip panel the rack's pads, pads, as { note, name } from top to bottom, and a drum clip opens on its steps: a row per pad (drum-step-editor, npx shadcn@latest add @audio-ui/drum-step-editor, over the sequencer). Press a step to switch it, and drag across to paint; with Repeat on, in the bar where Draw is on the roll, a press on a step that plays makes it a roll, two, three or four hits across the step, and back to one. A step is drawn fainter the softer it plays, so a ghost note shows as one, and while the clip plays, the view keeps the step being played in sight. A pad's name sounds it through onPadOn, and its menu fills the row every 2, 4 or 8 steps, or clears it. The steps are the clip's notes, seen another way: Roll, in the View menu, shows the same notes on the piano roll, its keys named after the pads, with their velocity and chance in the lane under them, and a note off the grid still lights its step. drum-steps (npx shadcn@latest add @audio-ui/drum-steps) holds the reading and the edits, stepsOf (each step's velocity, chance, shift and repeats), withStep, withStepLevel, withStepRepeats and filledEvery, for a step editor of your own. DrumStepEditor draws its own Repeat toggle, or none given repeating, for a host that draws it, as the panel does.

The Groove box swings a clip, drums or not: its off-beats, the eighths or the sixteenths, play late, up to a third of a step, a triplet's feel, while its notes stay on the grid. A clip keeps it as swing: { amount, division }, and playedNotes(clip, beat) plays it, given how long a beat lasts; swungTime is the curve. Give the panel swing and onSwingChange, which passes null for a straight clip. Give it position, the arrangement's position as a live value, and start, where the clip starts on it, and while the arrangement plays the clip, a playhead runs across its roll and the steps light the one playing; useClipPlayhead, from clip-view, is where the clip panels read it.

The Scale menu, in the bar with onScaleChange, picks the clip's scale: on, the roll marks its rows and Fold keeps them as well as the ones with notes. A clip keeps it as scale: { root, name, on }, off as well as on. Its menu offers the keys keyNotes and keyAudio are likeliest in, three at most: pass every MIDI clip of the song but the drums', and the sound of its audio clips, each recording's audioChroma times how long it plays, as a single part is often ambiguous. With the scale on, Up and Down in Notes > Pitch move notes by steps of the scale, and Fit to scale moves those out of it onto its nearest pitch, the selected notes or every one. A drum clip has no Scale menu, and its Notes menu no Pitch commands nor Legato.

The block plays the whole arrangement through the arrangement engine (npx shadcn@latest add @audio-ui/arrangement-engine): its audio clips, its notes, each track's chain and mix, its automation. With an engine of your own, play the clips from playedNotes.

The clip panel

Under the tracks, the clip panel (clip-panel, npx shadcn@latest add @audio-ui/clip-panel) shows the clip you pick, as a detail view follows the selection. It starts closed, and a press that picks a clip, trims it, fades it or moves it does not open it; its × hides it. It opens on a click of a clip's head, a double-click on a clip's body, the clip menu's Edit, or Cmd / Ctrl + Alt + 3, but not on a press that moves, trims or fades a clip, so you can work on a clip with the panel closed. Laid out as a DAW's clip view (clip-view holds the frame), a strip along its top carries the caret that rolls the panel up to that strip, the clip's switch, its name (type to rename it) and a word on it; under it, its properties sit in boxes beside the editor: Clip (where it starts and ends in its source), Loop (the switch, where the loop sits and how long it is, ÷2 and ×2) and Sample (Warp and its mode, Gain and Transpose: how the clip plays its source), all in bars.beats.16ths you can type or step with the arrow keys. Loop and Sample fold to a strip from their heading and give their width to the editor; what is rolled up or folded stays so from clip to clip, and the panel stays at the bottom of the block as the tracks scroll. Given a height of its own, a dock under the tracks, the panel fills it: the boxes reach its bottom, and the waveform, or a MIDI clip's roll, takes the room there is. Its source has a timeline of its own: a ruler in bars, the stretch the clip plays to drag at both ends, or with Loop on the stretch that repeats (a looped clip can then be stretched past its source on the timeline), the waveform under them, and an overview bar under the waveform to zoom and scroll with, as the arrangement's. With Warp on, the source is stretched between markers that pin a time in it to a time on the clip: drag a marker, or press its arrows, to stretch what is on either side; double-click the waveform to add one, Delete to take one away, and type the source's own tempo in BPM to play it in time at the arrangement's, or ÷2 and ×2 beside it to halve or double that tempo, as when a loop was read at twice or half its tempo; Speed shows what that makes of it. Its mode says how a speed other than the recording's sounds: Repitch moves the pitch with the speed, as a tape does, and is where a clip starts; Warp on picks Beats, slices a sixteenth note long that each keep their attack, for drums and loops; Tones plays grains lined up on each other, for held notes and voices. In Beats and Tones, Transpose moves the pitch and leaves the speed alone. Given the arrangement's live position and the clip's start, the panel draws a playhead where playback reads the source while it plays the clip, round its loop. The waveform is drawn over the stretch in view alone, so it stays sharp however far in you zoom, and a warp that squeezes the source keeps every peak it holds. It plays by speed alone, so pitch follows (shown as a rate and its semitones), and a warped clip lasts as long as its warp stretches its source on the timeline. Reverse, from the Process menu with nothing selected, plays the same stretch of the source backwards: the region and the loop are mirrored with it (reversedSettings), so a clip that played the first bar of a recording plays that bar backwards, not the last one. The map is warpedTime, unwarpedTime, warpRate and the marker functions in @/lib/engine/time. These are kept on the clip (gain, transpose, reversed, loop, warp, sourceFrom in lib/arrangement), and the engine plays them as they are set. Beside the boxes, its source is drawn by ClipWaveform (npx shadcn@latest add @audio-ui/clip-waveform), the waveform of a clip on its track, which draws only what the view shows and follows a zoom in the frame it happens. Given the recording's samples (a ClipSamples: its frames, and read(from, to), which returns the frames at once or as a promise), the panel zooms past the detail of the peaks, down to 40 px between two samples: each column then spans its lowest and highest sample, and past one sample per pixel the waveform is a line through them, with a dot on each that grows in from 6 px apart. The canvas's data-detail says which it draws: peaks, samples or line. Where WebGL 2 is there, the source is drawn on the GPU instead (waveform-lane), when its samples are held in memory or, streamed from a file, give their leaves: the lane then reads only the frames it shows, and given the recording's channels, a reader each, a stereo source is drawn a row a channel once the rows are tall enough to read. The View menu, in the bar over the source, draws the source as its waveform, by band when the host gives bands (splitBands of @/lib/engine/analysis), or as its spectrogram on octaves, mel, ERB or hertz with its frequency axis and the reading under the pointer (Sound Lane); a streamed source draws its spectrogram from its spectra. view and onViewChange hold it outside the panel, as the DAW keeps it from clip to clip. The panel edits its source as an audio editor does, each action in one place. The bar over it carries Edit and View, and Process given onProcess, and says what is picked. A drag on the sound selects a stretch, a press puts the caret down, Shift extends the selection and a double-click selects it all. The selection is a frame (selection-frame): its edges drag, a handle in each top corner fades it in and out along a curve, and a line across it sets its level. A right-click opens Crop, Louder, Quieter and Select all and, given onProcess, Cut, Copy, Paste, Delete and the Process menu; their keys (Cmd / Ctrl + X, C, V, A, Backspace, K, Shift + Up or Down, Escape) run them while the sound has the focus. With nothing selected, Reverse, Louder and Quieter set the clip, as quick as its other settings, and Crop cuts the source down to what the clip plays: onCrop(range, settings) gives the stretch kept and the clip's settings on it, for the host to set where the clip's source begins (sourceFrom) and how long it is. On a selection, Crop keeps the selection, and the rest reach the host as an operation and the stretch it acts on, in the source's own time played forwards (or null for the operations of the Process menu on all of it): the host runs it with applySoundOperation of sound-operations into a recording of its own, then sets what processedSettings(settings, operation, length, range) gives. The fades and level drawn on the frame are such an operation, { type: "shape" }, baked as they let go. What the clip played follows the sound: before the stretch it stays, after it it moves by as much as the stretch grew or shrank, inside it it scales with Stretch and Speed; an operation that changes the length turns the warp off first. onCopy(range) keeps a stretch to paste, onPaste(range) puts it in place of the selection or at the caret, and canPaste says there is something to paste. The other clips of the same recording are left as they were. The samples it reads are kept and read ahead of the zoom that needs them, so a zoom never shows the peaks before the samples. The range under the ruler holds what the clip plays, or its loop: two handles, with the waveform dimmed outside them. Warp markers too close to hold show as ticks along the top until you zoom in. A press anywhere on a box's heading folds it, and a press anywhere on its strip unfolds it.

Keyboard

A drag across the bare lanes selects a stretch of time on the tracks it sweeps, drawn over them; the time commands below work on it. The block's own keys work once a press on a lane has put the focus in it:

Keys · 20

Left / Right
Move the cursor by a grid step. Home and End go to the start and to the end of the last clip.
Alt + Left / Right
Jump to the previous or next locator or clip edge, on the picked tracks (on every track when none is picked).
Up / Down
Pick the track above or below.
+ / -
Zoom in or out around the cursor.
Z, X
Zoom onto the selected clips (the loop, when none is selected), and step back to the zoom before.
Cmd / Ctrl + 1, 2
A finer or a wider grid.
Cmd / Ctrl + 3, 4, 5
Triplets on or off, snapping on or off, and a grid fixed where it is or following the zoom again.
M
Add a locator at the cursor.
S, Cmd / Ctrl + E
Split the selected clips at the cursor.
Cmd / Ctrl + L
Put the loop around the time selection, or around the selected clips.
Cmd / Ctrl + C, X, V
Copy or cut the time selection (the selected clips when there is none), and paste it at the cursor, from the picked track down.
Delete
Empty the time selection on its tracks.
Cmd / Ctrl + D, J
With a time selection: repeat it right after itself, and make one clip per track of it.
Cmd / Ctrl + Shift + X, V, D, Delete
The same on time itself, on every track: cut it out, paste it in, repeat it, or take it out, moving what comes after.
Cmd / Ctrl + I
Open a stretch of silence at the cursor, as long as the time selection (a bar when there is none).
0
Switch the selected clips off, or back on.
Cmd / Ctrl + Alt + F
Fade the clips whose edges the time selection covers, in or out; two clips that meet across it crossfade.
Delete on a fade handle
Take the fade away.
Cmd / Ctrl + Alt + 3
Show or hide the clip panel.
On the loop
Left / Right move it by a grid step, Up / Down by its own length; with Cmd / Ctrl, Left / Right shorten or lengthen it and Up / Down double or halve it.

Other DAWs

The dawproject lib (npx shadcn@latest add @audio-ui/dawproject) writes an arrangement to a .dawproject file and reads one back. DAWproject is the open exchange format several DAWs read and write: a zip of project.xml, metadata.xml and the audio.

import { exportDawproject, importDawproject } from "@/lib/dawproject";

// Out: every recording a clip plays, by its id, with the file it goes in.
const { file, report } = await exportDawproject(doc, recordings, readBytes);

// In: the arrangement, and the bytes of each recording under the id its clips name.
const { doc: opened, recordings: files, report: lost } = await importDawproject(blob);
  • What crosses over: the tracks, the return tracks and the main track, with their volume, pan, mute, solo and sends. Audio clips with their fades, loop, warp and warp mode (algorithm: a name another DAW gives keeps the pitch, as Beats does), MIDI clips with their notes. The automation of volume and pan. The locators, the tempo and the time signatures. The equalizer, compressor, gate and limiter, whose settings the format describes.
  • What is left out: a reversed clip, a clip's gain, the loop and any other device. Each loss is a line of report.
  • Times: written in seconds, and read in seconds or beats.

Undo and redo

The undo-history lib (npx shadcn@latest add @audio-ui/undo-history) implements undo and redo as values: every function takes the present and returns the new present, and keeps no state of its own. Keep the history in a ref and the document in state, so two undos in one tick are fed the first one's result instead of reading the same stack twice.

let history = emptyHistory<Clip[]>();

// A change made in one go: delete, split, duplicate.
history = recordChange(history, clips);

// A drag reports every tick: open a burst on the first, close it on commit,
// and the whole drag is one entry.
history = beginChange(history, clips);
history = settleChange(history);

const step = undo(history, clips); // { history, present } or null

A new change clears redo, since the redo branch no longer follows from the present. HISTORY_LIMIT bounds the depth. The arrangement block uses it for its undo and redo buttons and for Cmd/Ctrl + Z, with Shift (or Y) to redo.

Usage

The primitive alone, part by part:

A Root owns the position, the zoom and the grid. Everything else is a part you place in it:

  • Viewport: the scrolling window. Cmd/Ctrl with the wheel, or a pinch, zooms around the pointer; a clip dragged near its edges scrolls it.
  • Ruler: the lane that moves the position. A press jumps to the pointer, a drag scrubs, Shift scrubs four times finer. It holds the native <input type="range"> that takes the keys and carries the name.
  • Lane: a strip the parts are placed on. Its --timeline-unit CSS variable is the width of one unit. With seekable, a press on its bare area moves the position.
  • Track, TrackHeader, TrackResizeHandle: a row with a header that stays at the left edge, and a handle that asks for a new height.
  • Playhead: follows the position through its --timeline-offset variable, with no render.
  • Mark: a point at a value. With movable, a drag or the arrows move it.
  • Range, RangeHandle: a stretch laid over a lane, such as a loop.
  • Clip, ClipHeader, ClipHandle, ClipFade, ClipFadeHandle: a stretch of a source that moves, trims and fades.
  • Navigator, NavigatorWindow, NavigatorHandle: a bar with the stretch the viewport shows, which a drag scrolls and zooms.
import type { ClipValue } from "@/components/audio-ui/timeline/core";
import { Timeline } from "@/components/audio-ui/timeline/react";

export function Arrangement({ clip, onClip }: { clip: ClipValue; onClip: (clip: ClipValue) => void }) {
  return (
    <Timeline.Root
      duration={64}
      onClipChange={(value) => onClip(value)}
      snapStep={1}
    >
      <Timeline.Viewport>
        <Timeline.Ruler aria-label="Position" className="h-6" />
        <Timeline.Lane className="h-16">
          <Timeline.Playhead className="inset-y-0 w-px bg-primary" />
          <Timeline.Clip aria-label="Take 1" className="inset-y-1 rounded bg-card" clip="take-1" value={clip}>
            <Timeline.ClipHeader className="h-4" clip="take-1" />
            <Timeline.ClipHandle aria-label="Trim start" className="absolute inset-y-0 left-0 w-1" clip="take-1" edge="start" />
            <Timeline.ClipHandle aria-label="Trim end" className="absolute inset-y-0 right-0 w-1" clip="take-1" edge="end" />
          </Timeline.Clip>
        </Timeline.Lane>
      </Timeline.Viewport>
    </Timeline.Root>
  );
}

Named parts

A clip, a range, a track and a mark each hold a controller of their own, and a part that belongs to one carries its name: clip="take-1" on the Clip, its header, its handles and its fades. What they report goes through the Root, with the name in the details. A Mark takes its value for a name unless it has one, which is enough for a mark that does not move.

A live position

Give the Root a source, a live position in the shape of an external store: getSnapshot() returns it and subscribe(listener) is called on each tick. The Playhead, the Ruler's input and a seek follow it straight in the DOM, with no render. createSource from the primitive item makes one, and useTransportClock from the registry gives you one on the audio clock.

Interaction

  • Ruler: a press seeks, a drag scrubs, and the end commits. Shift with a drag selects a stretch instead when the Root has onSelectionChange, to loop it.
  • Clip: a press on its body selects it and moves the position there. Dragging its header moves it on the grid unless Cmd/Ctrl is held, over other lanes too, and scrolls the viewport near its edges. A handle trims an edge, which moves where in the source the clip begins instead of stretching it; a fade handle sets a fade, and a double click or Enter steps its shape.
  • Range: its body moves it, its handles resize it, and with drawable a drag across the bare lane draws a new one.
  • Track: its resize handle asks for a height by a drag or the arrows (Down is taller); a double click gives the height up.
  • Navigator: dragging the window scrolls, dragging an edge zooms and holds the other edge still, and a double click shows everything.
  • The arrows move by step, Shift or Page Up and Page Down by largeStep, on every input.

A disabled timeline takes none of these.

API reference

Registry component

Timeline

Props · 14

Parts

Components · 16

TimelineViewport
The scrolling window. Zooms around the pointer with Cmd/Ctrl + scroll. scrollbar="hidden" drops the native scrollbar.
TimelineRuler
The lane that seeks. Holds the input; takes aria-label and getAriaValueText.
TimelineLane
A strip the timeline's parts are placed on. gridStep draws a line every that many units.
TimelineTrack
A row: a header beside a lane. height, selected, onHeightChange.
TimelineTrackHeader
The strip that names a track, kept at the left edge.
TimelineTrackResizeHandle
Sets the track's height, by dragging or with the keys.
TimelineMark
Something placed at value: a bar number, a cue. With onValueChange or onValueCommitted it moves: a drag takes it along the lane, on the grid unless Cmd/Ctrl is held, landing on a snapPoints place within a few px, and Left and Right on something focused inside it move it by step. A press that stays one keeps its click; a drag does not click.
TimelinePlayhead
Follows the position on the lane it sits in.
TimelineRange
A stretch of the timeline: value, defaultValue, minLength, movable, drawable, onValueChange, onValueCommitted. It sets minDrawnWidth to 32, and while it is drawn wider than it is long, a line along its bottom shows its true length against the ruler.
TimelineRangeHandle
Resizes one edge of the range.
TimelineClip
A stretch of a source: value, sourceLength, selected, onValueChange, onValueCommitted, onRemove. Dragged over other lanes too.
TimelineClipHeader
The clip's title bar: drag it to move the clip.
TimelineClipHandle
Trims one edge of the clip.
TimelineClipFade
Draws a fade, as a line with its shading. Takes edge.
TimelineClipFadeHandle
Sets a fade, at the clip's top corner: a square that shows when the clip is hovered or selected. Takes edge.
TimelineNavigator
The whole timeline as one bar, scrolling and zooming the viewport.

The Timeline primitive that installs with it exposes the same parts as Timeline.Root, Timeline.Viewport, Timeline.Ruler, Timeline.Lane, Timeline.Track with its Timeline.TrackHeader and Timeline.TrackResizeHandle, Timeline.Mark, Timeline.Playhead, Timeline.Range, Timeline.RangeHandle, Timeline.Clip, Timeline.ClipHeader, Timeline.ClipHandle, Timeline.ClipFade, Timeline.ClipFadeHandle, and Timeline.Navigator with its Timeline.NavigatorWindow and Timeline.NavigatorHandle. Clips, ranges, tracks and marks are named by a clip, range, track or mark prop, which the parts that belong to one repeat, and what they report goes to the Root with that name in the details. Every part accepts a render prop and className / style as functions of state, and exposes data-disabled, data-fitted and data-scrubbing.

ArrangedClip

Props · 12

useArrangedClips

Props · 6

TimelineLocator and TimelineSignature

Props · 7

useTimelineMarkers

Props · 4

useTrackAutomation

Props · 6

TrackAutomationChooser and TrackAutomation

Props · 9

Options

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

OptionTypeDefault
position, defaultPositionnumber0The playback position, controlled or starting.
source{ getSnapshot, subscribe }A live position, followed with no render.
zoom, defaultZoomnumberfits the widthpx per unit. Unset, the timeline fits its width until zoomed.
minZoom, maxZoomnumber0, InfinityThe zoom's limits.
durationnumber1The length of the timeline, in your units.
snapStep, snapOffsetnumber0The grid every gesture lands on unless Cmd/Ctrl is held. 0 is no grid.
snapPointsnumber[]Places that pull a press, or a dragged clip or range, onto them from a few px away.
step, largeStepnumberthe grid step, ten stepsThe keys' steps.
disabledbooleanfalseTakes no gesture.
onPositionChange, onPositionCommitted(value, details) => voidA seek, and its end.
onZoomChange(zoom, details) => voidThe zoom changed, already clamped.
onSelectionChange, onSelectionCommitted(range, details) => voidA Shift drag on the ruler, or on a seekable lane.
onClipChange, onClipCommitted(clip, details) => voidA clip moved, trimmed or faded. details.clip names it and details.target says what moved.
onClipSelectedChange, onClipRemove, onClipDragOffsetChangeA press selects a clip, Delete asks to remove it, a move drags it up or down.
onRangeChange, onRangeCommitted(range, details) => voidA range moved, resized or drawn, with details.range and details.edge.
onTrackHeightChange, onTrackHeightCommitted(height, details) => voidA track's resize handle asks for a height, undefined to give it up.
onMarkChange, onMarkCommitted(value, details) => voidA movable mark moved.

A Clip takes clip, value or defaultValue ({ start, length, offset, fadeIn, fadeOut }, with the fade shapes), selected, movable, minLength and sourceLength. A Range takes range, value, drawable, movable, minLength and minDrawnWidth. A Track takes track, height, minHeight, maxHeight, step, largeStep and selected. A Lane takes seekable.

What a change reports

details carries:

  • reason: "press", "drag", "keyboard", "input-change", "wheel", "double-click" or "draw".
  • source: "mouse", "touch", "pen", "keyboard", "programmatic" or "agent".
  • event and cancel(): the DOM event behind it, and the refusal. A controlled value keeps what you give it.
  • The name of the clip, range, track or mark, and for a clip or a range what moved.

In the web adapter, the position is the input and change events, and the rest are zoomchange, selectionchange, clipchange, clipcommit, clipselect, clipremove, rangechange, rangecommit, trackheightchange, trackheightcommit, markchange and markcommit, each with a detail of the value and its reasons. event.preventDefault() refuses a change.

States to style from

  • data-scrubbing on the Root while a pointer moves the position, data-fitted while no zoom is set, data-disabled on every part.
  • data-selected, data-dragging and data-fading (in or out) on a clip and its parts, data-edge on a handle, data-clip, data-range, data-track for the name.
  • A clip sets --clip-offset, --clip-source-length, --clip-fade-in, --clip-fade-out, their -max and --clip-unit for what you draw inside it, such as a waveform.

Parts

Parts · 19

Events

Events · 16

Built by Ouest Labs, the source code is available on GitHub.
RSS