# 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.

**In Vue**

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

<template>
  <Timeline.Root
    class="[--timeline-grid-color:color-mix(in_oklab,var(--border)_70%,transparent)] [--timeline-grid-accent-color:color-mix(in_oklab,var(--foreground)_16%,transparent)] flex w-full min-w-0 flex-col data-disabled:opacity-50"
    :duration="32"
    :snap-step="1"
  >
    <Timeline.Viewport
      class="bg-background relative min-h-0 min-w-0 overscroll-x-contain"
    >
      <Timeline.Ruler
        aria-label="Position"
        class="h-7 border-b bg-background text-muted-foreground text-xs has-focus-visible:bg-muted h-6 shrink-0 cursor-pointer touch-none select-none"
      />
      <Timeline.Lane class="h-14 border-b bg-muted/30 h-16">
        <Timeline.Playhead
          class="bg-primary pointer-events-none inset-y-0 w-px"
        />
        <Timeline.Clip
          aria-label="Kick"
          class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed"
          clip="kick"
          :default-value="{ start: 2, length: 10, offset: 0, fadeIn: 0, fadeOut: 0 }"
        >
          <Timeline.ClipHeader
            class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed"
            clip="kick"
            >Kick</Timeline.ClipHeader
          >
          <Timeline.ClipHandle
            aria-label="Trim start of Kick"
            class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
            clip="kick"
            edge="start"
          />
          <Timeline.ClipHandle
            aria-label="Trim end of Kick"
            class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
            clip="kick"
            edge="end"
          />
        </Timeline.Clip>
        <Timeline.Clip
          aria-label="Fill"
          class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed"
          clip="fill"
          :default-value="{ start: 14, length: 8, offset: 0, fadeIn: 0, fadeOut: 0 }"
        >
          <Timeline.ClipHeader
            class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed"
            clip="fill"
            >Fill</Timeline.ClipHeader
          >
          <Timeline.ClipHandle
            aria-label="Trim start of Fill"
            class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
            clip="fill"
            edge="start"
          />
          <Timeline.ClipHandle
            aria-label="Trim end of Fill"
            class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
            clip="fill"
            edge="end"
          />
        </Timeline.Clip>
      </Timeline.Lane>
      <Timeline.Lane class="h-14 border-b bg-muted/30 h-16">
        <Timeline.Playhead
          class="bg-primary pointer-events-none inset-y-0 w-px"
        />
        <Timeline.Clip
          aria-label="Bass"
          class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed"
          clip="bass"
          :default-value="{ start: 6, length: 12, offset: 0, fadeIn: 0, fadeOut: 0 }"
        >
          <Timeline.ClipHeader
            class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed"
            clip="bass"
            >Bass</Timeline.ClipHeader
          >
          <Timeline.ClipHandle
            aria-label="Trim start of Bass"
            class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
            clip="bass"
            edge="start"
          />
          <Timeline.ClipHandle
            aria-label="Trim end of Bass"
            class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
            clip="bass"
            edge="end"
          />
        </Timeline.Clip>
      </Timeline.Lane>
    </Timeline.Viewport>
  </Timeline.Root>
</template>
```

**In Svelte**

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

<Timeline.Root
  class="[--timeline-grid-color:color-mix(in_oklab,var(--border)_70%,transparent)] [--timeline-grid-accent-color:color-mix(in_oklab,var(--foreground)_16%,transparent)] flex w-full min-w-0 flex-col data-disabled:opacity-50"
  duration={32}
  snapStep={1}
>
  <Timeline.Viewport
    class="bg-background relative min-h-0 min-w-0 overscroll-x-contain"
  >
    <Timeline.Ruler
      aria-label="Position"
      class="h-7 border-b bg-background text-muted-foreground text-xs has-focus-visible:bg-muted h-6 shrink-0 cursor-pointer touch-none select-none"
    />
    <Timeline.Lane class="h-14 border-b bg-muted/30 h-16">
      <Timeline.Playhead
        class="bg-primary pointer-events-none inset-y-0 w-px"
      />
      <Timeline.Clip
        aria-label="Kick"
        class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed"
        clip="kick"
        defaultValue={{
          start: 2,
          length: 10,
          offset: 0,
          fadeIn: 0,
          fadeOut: 0,
        }}
      >
        <Timeline.ClipHeader
          class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed"
          clip="kick"
          >Kick</Timeline.ClipHeader
        >
        <Timeline.ClipHandle
          aria-label="Trim start of Kick"
          class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
          clip="kick"
          edge="start"
        />
        <Timeline.ClipHandle
          aria-label="Trim end of Kick"
          class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
          clip="kick"
          edge="end"
        />
      </Timeline.Clip>
      <Timeline.Clip
        aria-label="Fill"
        class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed"
        clip="fill"
        defaultValue={{
          start: 14,
          length: 8,
          offset: 0,
          fadeIn: 0,
          fadeOut: 0,
        }}
      >
        <Timeline.ClipHeader
          class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed"
          clip="fill"
          >Fill</Timeline.ClipHeader
        >
        <Timeline.ClipHandle
          aria-label="Trim start of Fill"
          class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
          clip="fill"
          edge="start"
        />
        <Timeline.ClipHandle
          aria-label="Trim end of Fill"
          class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
          clip="fill"
          edge="end"
        />
      </Timeline.Clip>
    </Timeline.Lane>
    <Timeline.Lane class="h-14 border-b bg-muted/30 h-16">
      <Timeline.Playhead
        class="bg-primary pointer-events-none inset-y-0 w-px"
      />
      <Timeline.Clip
        aria-label="Bass"
        class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed"
        clip="bass"
        defaultValue={{
          start: 6,
          length: 12,
          offset: 0,
          fadeIn: 0,
          fadeOut: 0,
        }}
      >
        <Timeline.ClipHeader
          class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed"
          clip="bass"
          >Bass</Timeline.ClipHeader
        >
        <Timeline.ClipHandle
          aria-label="Trim start of Bass"
          class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
          clip="bass"
          edge="start"
        />
        <Timeline.ClipHandle
          aria-label="Trim end of Bass"
          class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0"
          clip="bass"
          edge="end"
        />
      </Timeline.Clip>
    </Timeline.Lane>
  </Timeline.Viewport>
</Timeline.Root>
```

**In Web**

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

/** Draws the timeline into `element`, and returns what takes it away. */
export function timelineWebDemo(element) {
  element.innerHTML = `
    <audio-ui-timeline class="[--timeline-grid-color:color-mix(in_oklab,var(--border)_70%,transparent)] [--timeline-grid-accent-color:color-mix(in_oklab,var(--foreground)_16%,transparent)] flex w-full min-w-0 flex-col data-disabled:opacity-50" duration="32" snap-step="1">
      <audio-ui-timeline-viewport class="bg-background relative min-h-0 min-w-0 overscroll-x-contain">
        <audio-ui-timeline-ruler aria-label="Position" class="h-7 border-b bg-background text-muted-foreground text-xs has-focus-visible:bg-muted h-6 shrink-0 cursor-pointer touch-none select-none"></audio-ui-timeline-ruler>
        <audio-ui-timeline-lane class="h-14 border-b bg-muted/30 h-16">
          <audio-ui-timeline-playhead class="bg-primary pointer-events-none inset-y-0 w-px"></audio-ui-timeline-playhead>
          <audio-ui-timeline-clip aria-label="Kick" class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed" clip="kick" default-value='{"start":2,"length":10,"offset":0,"fadeIn":0,"fadeOut":0}'>
            <audio-ui-timeline-clip-header class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed" clip="kick">Kick</audio-ui-timeline-clip-header>
            <audio-ui-timeline-clip-trim-start aria-label="Trim start of Kick" class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0" clip="kick" edge="start"></audio-ui-timeline-clip-trim-start>
            <audio-ui-timeline-clip-trim-end aria-label="Trim end of Kick" class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0" clip="kick" edge="end"></audio-ui-timeline-clip-trim-end>
          </audio-ui-timeline-clip>
          <audio-ui-timeline-clip aria-label="Fill" class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed" clip="fill" default-value='{"start":14,"length":8,"offset":0,"fadeIn":0,"fadeOut":0}'>
            <audio-ui-timeline-clip-header class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed" clip="fill">Fill</audio-ui-timeline-clip-header>
            <audio-ui-timeline-clip-trim-start aria-label="Trim start of Fill" class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0" clip="fill" edge="start"></audio-ui-timeline-clip-trim-start>
            <audio-ui-timeline-clip-trim-end aria-label="Trim end of Fill" class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0" clip="fill" edge="end"></audio-ui-timeline-clip-trim-end>
          </audio-ui-timeline-clip>
        </audio-ui-timeline-lane>
        <audio-ui-timeline-lane class="h-14 border-b bg-muted/30 h-16">
          <audio-ui-timeline-playhead class="bg-primary pointer-events-none inset-y-0 w-px"></audio-ui-timeline-playhead>
          <audio-ui-timeline-clip aria-label="Bass" class="rounded-[min(var(--radius-sm),6px)] overflow-hidden bg-primary/25 ring-1 ring-primary/60 ring-inset data-[selected]:bg-primary/40 data-[selected]:ring-2 data-[selected]:ring-primary has-focus-visible:ring-2 has-focus-visible:ring-ring group/clip isolate inset-y-0 touch-none data-dragging:z-10 data-disabled:cursor-not-allowed" clip="bass" default-value='{"start":6,"length":12,"offset":0,"fadeIn":0,"fadeOut":0}'>
            <audio-ui-timeline-clip-header class="bg-primary/30 data-[selected]:bg-primary/50 flex h-5 cursor-grab items-center truncate px-2 text-xs data-dragging:cursor-grabbing data-disabled:cursor-not-allowed" clip="bass">Bass</audio-ui-timeline-clip-header>
            <audio-ui-timeline-clip-trim-start aria-label="Trim start of Bass" class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0" clip="bass" edge="start"></audio-ui-timeline-clip-trim-start>
            <audio-ui-timeline-clip-trim-end aria-label="Trim end of Bass" class="bg-primary/0 hover:bg-primary/60 has-focus-visible:bg-primary absolute inset-y-0 z-10 w-2 cursor-ew-resize data-[edge=end]:right-0 data-[edge=start]:left-0" clip="bass" edge="end"></audio-ui-timeline-clip-trim-end>
          </audio-ui-timeline-clip>
        </audio-ui-timeline-lane>
      </audio-ui-timeline-viewport>
    </audio-ui-timeline>`;
  return () => {
    element.innerHTML = "";
  };
}
```

**In React**

```tsx
import { EnvelopeIcon } from "@audio-ui/icons/react";
import {
  type ComponentProps,
  type KeyboardEvent,
  useCallback,
  useLayoutEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { ParameterField } from "@/components/audio-ui/parameter-field";
import { IconPlaceholder } from "@/components/icon-placeholder";
import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuRadioGroup,
  DropdownMenuRadioItem,
  DropdownMenuSeparator,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Kbd, KbdGroup } from "@/components/ui/kbd";
import { analyzeBeat, computePeaks, normalizePeaks } from "@/lib/engine/analysis";
import { decodeAudioChannels } from "@/lib/engine/files";
import {
  barsBeatsWith,
  type MetronomeRhythm,
  secondsPerBar,
  type Tempo,
} from "@/lib/engine/time";
import {
  ArrangementView,
  shownLength,
} from "@/components/audio-ui/arrangement-view";
import { Meter } from "@/components/audio-ui/meter";
import { TRACK_COLORS } from "@/components/audio-ui/timeline";
import { Transport } from "@/components/audio-ui/transport";
import {
  ClipPanel,
  type ClipSettings,
} from "@/components/audio-ui/clip-panel";
import {
  MidiClipPanel,
  type MidiClipRegion,
} from "@/components/audio-ui/midi-clip-panel";
import { channelEqDevice } from "@/components/audio-ui/devices/channel-eq/device";
import { compressorDevice } from "@/components/audio-ui/devices/compressor/device";
import { limiterDevice } from "@/components/audio-ui/devices/limiter/device";
import {
  monoSynthDevice,
  monoSynthPreset,
} from "@/components/audio-ui/devices/mono-synth/device";
import { organDevice } from "@/components/audio-ui/devices/organ/device";
import { reverbDevice } from "@/components/audio-ui/devices/reverb/device";
import {
  stringMachineDevice,
  stringMachinePreset,
} from "@/components/audio-ui/devices/string-machine/device";
import { vibeDevice } from "@/components/audio-ui/devices/vibe/device";
import { useAudioLevels } from "@/hooks/use-audio-levels";
import { useArrangement } from "@/hooks/use-arrangement";
import { useArrangementEngine } from "@/hooks/use-arrangement-engine";
import { useTrackAutomation } from "@/hooks/use-track-automation";
import { useTimeSelection } from "@/hooks/use-time-selection";
import { useTimelineCursor } from "@/hooks/use-timeline-cursor";
import {
  GRID_KEYS,
  useTimelineGrid,
} from "@/hooks/use-timeline-grid";
import { useTimelineMarkers } from "@/hooks/use-timeline-markers";
import { useTimelineZoom } from "@/hooks/use-timeline-zoom";
import {
  type Arranged,
  type ArrangementTrack,
  type ClipSwing,
  DRUM_RACK_DEVICE,
  NEW_TRACK,
  type TimeSelection,
  type TrackKind,
  UNITY_MIX,
  warpOnImport,
} from "@/lib/arrangement";
import { renderTrackClips } from "@/lib/arrangement-engine";
import {
  audioClipsIn,
  MAIN_TRACK,
} from "@/lib/arrangement-state";
import type { RecordingSource } from "@/lib/clip-player";
import {
  SONG_SCORE,
  SONG_TEMPO,
  type SongNote,
  type SongScorePart,
} from "@/lib/demo-song";
import { drumKit } from "@/lib/drum-kit";
import { webAudio } from "@/lib/web-audio";

const BARS = 24;

/** No device library here: the arrangement takes no device. */
const noDevice = () => undefined;

const NO_READING: readonly {
  at: number;
  key: number;
  name: string;
  track: string;
}[] = [];

/** The arrangement is laid out at the song's tempo: a tempo change keeps its musical positions. */
const BAR = secondsPerBar(SONG_TEMPO);
/** Whether a key went to a field you type in, where it is the field's own. */
function typing(target: EventTarget) {
  return (
    (target instanceof HTMLInputElement && target.type !== "range") ||
    target instanceof HTMLTextAreaElement ||
    (target instanceof HTMLElement && target.isContentEditable)
  );
}
/** The zoom presets, as shares of the fitted view: Fit shows everything. */
const ZOOM_PRESETS = [1, 2, 4, 8];
/** The zoom's steps are loupes, not a minus and a plus. */
const ZOOM_STEPPERS = {
  decrement: "Zoom out",
  icons: {
    decrement: (
      <IconPlaceholder
        hugeicons="ZoomOutAreaIcon"
        lucide="ZoomOutIcon"
        phosphor="MagnifyingGlassMinusIcon"
        remixicon="RiZoomOutLine"
        tabler="IconZoomOut"
      />
    ),
    increment: (
      <IconPlaceholder
        hugeicons="ZoomInAreaIcon"
        lucide="ZoomInIcon"
        phosphor="MagnifyingGlassPlusIcon"
        remixicon="RiZoomInLine"
        tabler="IconZoomIn"
      />
    ),
  },
  increment: "Zoom in",
};

/** How the zoom is shown: as a share of the fitted view. */
const PERCENT: Intl.NumberFormatOptions = {
  maximumFractionDigits: 0,
  style: "percent",
};

const bars = (count: number) => count * BAR;

/** The song's parts, in order, and the bar each starts on. */
const PARTS = [
  { at: 0, id: "intro", name: "Intro" },
  { at: 4, id: "verse", name: "Verse" },
  { at: 12, id: "chorus", name: "Chorus" },
  { at: 20, id: "outro", name: "Outro" },
] as const;

/** The named points the timeline starts with: the parts of the song. */
const LOCATORS = PARTS.map(({ at, id, name }) => ({ at: bars(at), id, name }));

/** The loop it starts with, switched on: the whole song, whose outro leads back into its intro. */
const LOOP = { on: true, range: [0, bars(BARS)] } as const;

/** A device on a chain, at its own defaults with `patch` over them. */
const device = <State extends object>(
  id: string,
  described: { defaults: () => State; id: string },
  patch: Partial<State> = {},
  instrument = false
) => ({
  device: described.id,
  id,
  ...(instrument ? { instrument: true } : {}),
  state: { ...described.defaults(), ...patch },
});

const REVERB = "return-1";

/**
 * The organ's volume across the song, as shares of it: at its level, faded
 * over the intro's last bar, silent through the verse, back for the chorus.
 */
const ORGAN_FADE = [
  { x: 0, y: 0.773 },
  { curve: 0.366, x: 0.125, y: 0.773 },
  { curve: -0.355, x: 0.1667, y: 0.303 },
  { x: 0.1736, y: 0 },
  { curve: 0.216, x: 0.4861, y: 0 },
  { x: 0.5, y: 0.773 },
  { x: 1, y: 0.773 },
];

/**
 * The song as a project: every track MIDI, played by the registry's
 * instruments (a drum rack with a Drum Synth on every pad for the drums, its
 * snare and clap in a small room, a mono synth's sub bass, a tonewheel organ
 * on three drawbars for the chords, another on its 8', 4' and 2' with the
 * rotary stopped, through a vibe in vibrato, for the lead, and a string
 * machine on the pad), and a
 * reverb on a return track the organ, the lead and the pad send to. The drums
 * and the bass lead the mix, the organ and the lead stand a little apart, and
 * the pad lies under them. The organ fades out over the intro's last bar and
 * comes back for the chorus.
 */
const TRACKS: ArrangementTrack[] = [
  {
    color: 0,
    devices: [
      {
        device: DRUM_RACK_DEVICE,
        id: "drum-kit",
        instrument: true,
        rack: drumKit(),
        state: {},
      },
    ],
    id: "drums",
    kind: "midi",
    mix: { ...UNITY_MIX, gain: 10 ** (-3 / 20) },
    name: "Drums",
  },
  {
    color: 1,
    devices: [
      device(
        "bass-synth",
        monoSynthDevice,
        { ...monoSynthPreset("Sub Bass"), volume: 7 },
        true
      ),
    ],
    id: "bass",
    kind: "midi",
    mix: { ...UNITY_MIX, gain: 10 ** (2 / 20) },
    name: "Bass",
  },
  {
    automation: { volume: ORGAN_FADE },
    color: 2,
    devices: [
      device(
        "organ",
        organDevice,
        {
          click: 1,
          drawbar1: 0,
          drawbar2: 0,
          drawbar3: 8,
          drawbar4: 6,
          drawbar5: 5,
          drive: 1,
          rotary: "slow",
          volume: 6,
        },
        true
      ),
    ],
    id: "organ",
    kind: "midi",
    mix: { ...UNITY_MIX, gain: 10 ** (-12 / 20), pan: -0.15 },
    name: "Organ",
    sends: { [REVERB]: 0.25 },
  },
  {
    color: 3,
    devices: [
      device(
        "lead-organ",
        organDevice,
        {
          click: 3,
          drawbar1: 0,
          drawbar2: 0,
          drawbar3: 6,
          drawbar4: 0,
          drawbar5: 8,
          drawbar7: 4,
          drive: 0,
          rotary: "stop",
          volume: 7,
        },
        true
      ),
      device("lead-vibe", vibeDevice, {
        intensity: 6,
        mode: "vibrato",
        speed: 4,
        volume: 7,
      }),
    ],
    id: "lead",
    kind: "midi",
    mix: { ...UNITY_MIX, gain: 10 ** (-16 / 20), pan: 0.15 },
    name: "Lead",
    sends: { [REVERB]: 0.35 },
  },
  {
    color: 1,
    devices: [
      device(
        "pad-strings",
        stringMachineDevice,
        stringMachinePreset("Swell"),
        true
      ),
    ],
    id: "pad",
    kind: "midi",
    // A bed under the band, felt more than heard.
    mix: { ...UNITY_MIX, gain: 10 ** (-15 / 20) },
    name: "Pad",
    sends: { [REVERB]: 0.4 },
  },
];

/**
 * The master on the main track: a touch of air and presence on a dark mix
 * and a little less of the lowest lows, a gentle compression that holds the
 * band together, and a limiter that brings it up under a ceiling of -1 dB.
 */
const MAIN: ArrangementTrack = {
  ...MAIN_TRACK,
  devices: [
    device("master-eq", channelEqDevice, {
      highDb: 3,
      lowDb: -1.5,
      midDb: 1.5,
      midHz: 3000,
    }),
    device("master-glue", compressorDevice, {
      attackMs: 30,
      ratio: 2,
      releaseMs: 200,
      thresholdDb: -20,
    }),
    device("master-limiter", limiterDevice, {
      ceilingDb: -1,
      gainDb: 8,
      releaseMs: 120,
    }),
  ],
};

const RETURNS: ArrangementTrack[] = [
  {
    color: 0,
    devices: [device("reverb", reverbDevice, { mix: 100 })],
    id: REVERB,
    name: "A Reverb",
  },
];

const NO_ANALYSERS: readonly AnalyserNode[] = [];
const NO_PEAKS: number[] = [];

/** What a meter shows before the engine runs. */
const SILENCE = {
  getSnapshot: () => ({ levels: [-60, -60], peaks: [-60, -60] }),
  subscribe: () => () => undefined,
};

const BEAT = BAR / 4;

/** The edges of a clip from bar `from` to bar `to`. */
const placedAt = (from: number, to: number) => ({
  fadeIn: 0,
  fadeOut: 0,
  length: bars(to - from),
  offset: 0,
  start: bars(from),
});

/** The song's notes as a MIDI clip holds them: in seconds, at the song's tempo. */
/** A clip with the clip panel's settings: it keeps its place, and what it plays ends as early as the timeline needs, its fades inside it. */
function withClipSettings(
  clip: Arranged,
  next: ClipSettings,
  duration: number
): Arranged {
  const length = Math.min(next.length, duration - clip.value.start);
  const fadeIn = Math.min(clip.value.fadeIn, length);
  return {
    ...clip,
    gain: next.gain,
    loop: next.loop ?? undefined,
    reversed: next.reversed,
    transpose: next.transpose,
    warpMode: next.warpMode,
    warp: next.warp ?? undefined,
    value: {
      ...clip.value,
      fadeIn,
      fadeOut: Math.min(clip.value.fadeOut, length - fadeIn),
      length,
      offset: next.offset,
    },
  };
}

const notesOf = (notes: readonly SongNote[]): Arranged["notes"] =>
  notes.map(({ length, pitch, start, velocity }, index) => ({
    id: `n${index}`,
    length: length * BEAT,
    pitch,
    start: start * BEAT,
    velocity,
  }));

/** A take of the song: notes a MIDI clip loops. Its track is the word before its dash. */
type Take = SongScorePart;

/** How many bars a take lasts before it loops: up to the bar its last note ends in. */
const barsOf = (take: Take) =>
  Math.ceil(
    Math.max(...SONG_SCORE[take].map((note) => note.start + note.length)) / 4
  );

/** A clip of `take` from bar `from` to bar `to`, on its track, looping it. */
function clipOf(
  id: string,
  name: string,
  take: Take,
  from: number,
  to: number
): Arranged {
  const loop = bars(barsOf(take));
  return {
    id,
    loop: [0, loop],
    name,
    notes: notesOf(SONG_SCORE[take]),
    sourceLength: loop,
    track: take.split("-")[0] ?? take,
    value: placedAt(from, to),
  };
}

/**
 * What each part of the song plays, all of it on the same loop. The drums
 * and the organ open it, the verse is the drums and the bass alone, the
 * chorus is the whole band, harder, under the lead's hook, and the organ
 * and the hook close it, back where the song started.
 */
const PLAYS: Record<(typeof PARTS)[number]["id"], readonly Take[]> = {
  chorus: ["drums-chorus", "bass-chorus", "organ", "lead"],
  intro: ["drums-verse", "organ"],
  outro: ["organ", "lead"],
  verse: ["drums-verse", "bass-verse"],
};

/**
 * The song's clips, each named after the part it plays in. The bar before
 * each chorus ends on a snare roll, in place of the part's own drums.
 */
const CLIPS: Arranged[] = [
  ...PARTS.flatMap((part, index) => {
    const end = PARTS[index + 1]?.at ?? BARS;
    const fill = PARTS[index + 1]?.id === "chorus";
    const clips = PLAYS[part.id].map((take) =>
      clipOf(
        `${part.id}-${take}`,
        part.name,
        take,
        part.at,
        fill && take.startsWith("drums-") ? end - 1 : end
      )
    );
    return fill
      ? [
          ...clips,
          clipOf(`${part.id}-fill`, "Fill", "drums-fill", end - 1, end),
        ]
      : clips;
  }),
  // The pad swells in on the third bar and holds to the end: each time round, the song opens without it.
  clipOf("pad", "Pad", "pad", 2, BARS),
];

const SHORTCUTS: { action: string; keys: string[] }[] = [
  { action: "Split at the cursor", keys: ["S"] },
  { action: "Split at the cursor", keys: ["Cmd/Ctrl", "E"] },
  { action: "Duplicate the clip", keys: ["Cmd/Ctrl", "D"] },
  { action: "Remove the clip, or the tracks picked", keys: ["Delete"] },
  { action: "Add a track to the tracks picked", keys: ["Shift", "Click"] },
  { action: "Duplicate the tracks picked", keys: ["Cmd/Ctrl", "D"] },
  { action: "Add a locator at the cursor", keys: ["M"] },
  { action: "Loop the selection", keys: ["Cmd/Ctrl", "L"] },
  { action: "Rename a locator", keys: ["Enter"] },
  {
    action: "Jump to the previous or next locator",
    keys: ["Alt", "Left", "Right"],
  },
  { action: "Nudge a clip or an edge", keys: ["Left", "Right"] },
  { action: "Nudge further", keys: ["Shift", "Left", "Right"] },
  { action: "Copy a clip while dragging", keys: ["Alt", "Drag"] },
  { action: "Move or trim off the grid", keys: ["Cmd/Ctrl", "Drag"] },
  { action: "Zoom around the pointer", keys: ["Cmd/Ctrl", "Scroll"] },
  { action: "Resize a track", keys: ["Up", "Down"] },
  { action: "Add a clip to the selection", keys: ["Shift", "Click"] },
  { action: "Undo", keys: ["Cmd/Ctrl", "Z"] },
  { action: "Redo", keys: ["Cmd/Ctrl", "Shift", "Z"] },
  { action: "Select every clip", keys: ["Cmd/Ctrl", "A"] },
  { action: "Show or hide the automation", keys: ["A"] },
  { action: "Select by dragging a rectangle", keys: ["Shift", "Drag"] },
  { action: "Clear the selection", keys: ["Esc"] },
];

/** How many slices of a recording the block keeps: the lanes and the clip panel draw the stretch of them a clip holds. */
const RECORDING_PEAKS = 16_384;
/** The end of a file's name that says its format. */
const EXTENSION = /\.[^.]+$/;
/** The files the browser can try to decode as sound when it does not give their type. */

/** A recording the clips play: the demo's, or a file dropped on a track. Its sound, its peaks and how long it lasts, in seconds. */
interface Recording {
  length: number;
  peaks: number[];
  source: RecordingSource;
}

/** A decoded sound as a recording: its channels at the engine's rate, and the peaks its clips draw. */
function recordingOf(
  channels: readonly Float32Array[],
  sampleRate: number
): Recording {
  return {
    length: (channels[0]?.length ?? 0) / sampleRate,
    peaks: amplitudes(channels),
    source: { channels, sampleRate },
  };
}

/** Whether a drag carries files from the desktop, rather than something of the page. */

/** One amplitude per slice, from 0 to 1, as the clip panel draws them. */
function amplitudes(channels: readonly Float32Array[]): number[] {
  const { max, min } = normalizePeaks(computePeaks(channels, RECORDING_PEAKS));
  return Array.from(max, (high, index) => Math.max(high, -(min[index] ?? 0)));
}

/** The peaks of a recording over the stretch of it a clip's source holds: a recording keeps its own seconds. */
function recordedPeaks(recording: Recording, clip: Arranged): number[] {
  const { length } = recording;
  const from = clip.sourceFrom ?? 0;
  const { peaks } = recording;
  const first = Math.max(0, Math.floor((from / length) * peaks.length));
  const last = Math.min(
    peaks.length,
    Math.ceil(((from + clip.sourceLength) / length) * peaks.length)
  );
  return peaks.slice(first, Math.max(first + 1, last));
}

/** Closes the clip panel. */
function CloseClipView({ onClose }: { onClose: () => void }) {
  return (
    <Button
      aria-label="Close the clip panel"
      onClick={onClose}
      size="icon-sm"
      variant="ghost"
    >
      <IconPlaceholder
        aria-hidden="true"
        className="size-4"
        hugeicons="Cancel01Icon"
        lucide="XIcon"
        phosphor="XIcon"
        remixicon="RiCloseLine"
        tabler="IconX"
      />
    </Button>
  );
}

/** The clip panel stays in view at the bottom of the window while the tracks scroll past above it. */
const DOCKED = "sticky bottom-0 z-40 shadow-lg";

/** The clip panel under the tracks, for the clip being edited, or a word on how to pick one. */
function ClipDock({
  bar,
  beatsPerBar,
  clip,
  collapsed,
  format,
  midi,
  onActiveChange,
  onClose,
  onCollapsedChange,
  onCrop,
  onValueChange,
  onValueCommitted,
  peaks,
  position,
  foldedBoxes,
  onFoldedBoxesChange,
  onRename,
}: {
  bar: number;
  beatsPerBar: number;
  clip: Arranged | undefined;
  /** Whether the panel is collapsed to its title: held here, so it stays so from clip to clip. */
  collapsed: boolean;
  format: (seconds: number) => string;
  /** What a MIDI clip's panel edits and sounds. */
  midi: Pick<
    ComponentProps<typeof MidiClipPanel>,
    | "onNoteOff"
    | "onNoteOn"
    | "onNotesChange"
    | "onPadOn"
    | "onRegionChange"
    | "onSwingChange"
    | "pads"
  >;
  onActiveChange: (active: boolean) => void;
  onClose: () => void;
  /** The arrangement's position, live, which an audio clip's panel shows where it plays. */
  position: ComponentProps<typeof ClipPanel>["position"];
  onCollapsedChange: (collapsed: boolean) => void;
  onCrop: NonNullable<ComponentProps<typeof ClipPanel>["onCrop"]>;
  onValueChange: (next: ClipSettings) => void;
  onValueCommitted: () => void;
  /** The ids of the boxes folded in the panel: held here, so they stay folded from clip to clip. */
  foldedBoxes: readonly string[];
  onFoldedBoxesChange: (folded: string[]) => void;
  onRename: (id: string, name: string) => void;
  peaks: number[];
}) {
  const rename = useCallback(
    (name: string) => clip && onRename(clip.id, name),
    [clip, onRename]
  );
  if (!clip) {
    return null;
  }
  if (clip.notes) {
    return (
      <MidiClipPanel
        active={!clip.disabled}
        bar={bar}
        beat={bar / beatsPerBar}
        className={DOCKED}
        collapsed={collapsed}
        foldedBoxes={foldedBoxes}
        key={clip.id}
        name={clip.name}
        notes={clip.notes}
        onActiveChange={onActiveChange}
        onCollapsedChange={onCollapsedChange}
        onFoldedBoxesChange={onFoldedBoxesChange}
        onNotesCommitted={onValueCommitted}
        onRename={rename}
        position={position}
        region={{
          length: clip.value.length,
          loop: clip.loop ?? null,
          offset: clip.value.offset,
          sourceLength: clip.sourceLength,
        }}
        start={clip.value.start}
        swing={clip.swing}
        {...midi}
      >
        <CloseClipView onClose={onClose} />
      </MidiClipPanel>
    );
  }
  return (
    <ClipPanel
      active={!clip.disabled}
      bar={bar}
      beatsPerBar={beatsPerBar}
      className={DOCKED}
      collapsed={collapsed}
      foldedBoxes={foldedBoxes}
      format={format}
      name={clip.name}
      onActiveChange={onActiveChange}
      onCollapsedChange={onCollapsedChange}
      onCrop={onCrop}
      onFoldedBoxesChange={onFoldedBoxesChange}
      onRename={rename}
      onValueChange={onValueChange}
      onValueCommitted={onValueCommitted}
      position={position}
      start={clip.value.start}
      value={{
        gain: clip.gain ?? 0,
        length: clip.value.length,
        loop: clip.loop ?? null,
        offset: clip.value.offset,
        reversed: Boolean(clip.reversed),
        sourceLength: clip.sourceLength,
        transpose: clip.transpose ?? 0,
        warpMode: clip.warpMode,
        warp: clip.warp ?? null,
      }}
      values={peaks}
    >
      <CloseClipView onClose={onClose} />
    </ClipPanel>
  );
}

/** The main track's level, as the engine meters it: what the arrangement sends to the speakers. */
function MainLevel({
  analysers,
}: {
  analysers: readonly AnalyserNode[] | null;
}) {
  const levels = useAudioLevels(analysers ?? NO_ANALYSERS);
  return (
    <Meter
      aria-label="Master output level"
      className="data-[orientation=horizontal]:[--meter-thickness:--spacing(3)]"
      orientation="horizontal"
      peakMarks="hidden"
      size="sm"
      source={analysers ? levels : SILENCE}
      warnThreshold={-12}
    />
  );
}

/** A decoded buffer's channels. */
function channelsOf(buffer: AudioBuffer) {
  return Array.from({ length: buffer.numberOfChannels }, (_, channel) =>
    buffer.getChannelData(channel)
  );
}

/** The recordings the audio clips play, by id: the files dropped on the tracks, which `keepRecording` adds. */
function useRecordings() {
  const [recordings, setRecordings] = useState<ReadonlyMap<string, Recording>>(
    () => new Map()
  );
  const keepRecording = useCallback(
    (id: string, recording: Recording) =>
      setRecordings((current) => new Map(current).set(id, recording)),
    []
  );
  // What the engine plays: the sounds alone, the same map until a recording comes or goes.
  const sources = useMemo(
    () =>
      new Map([...recordings].map(([id, recording]) => [id, recording.source])),
    [recordings]
  );
  return { keepRecording, recordings, sources };
}

/** The engine as the transport: play from the playhead or pause where the sound is, and a seek that, while playing, plays from there. */
function useEngineTransport({
  play,
  playing,
  position,
  stop,
}: ReturnType<typeof useArrangementEngine>) {
  const playPause = useCallback(() => {
    if (playing) {
      stop();
    } else {
      play(position.getSnapshot());
    }
  }, [play, playing, position, stop]);
  const seek = useCallback(
    (seconds: number) => {
      if (playing) {
        play(seconds);
      } else {
        position.set(seconds);
      }
    },
    [play, playing, position]
  );
  return { playPause, seek };
}

/**
 * An arrangement that plays: a bar ruler that seeks on the grid, a loop strip,
 * a lane per track with clips to move between tracks, trim and fade, a cursor
 * to put anywhere on a track and split at, and a playhead following the sound.
 * The arrangement engine plays it on the audio clock: the audio clips loop the
 * demo's recordings, the MIDI clips play through each track's synth, and every
 * track through its mix. Cmd/Ctrl + scroll zooms around the pointer, and the
 * bar below scrolls and zooms. Made to be opened at full size, where the
 * tracks take the screen.
 */
export function BlockTimeline() {
  const arrangement = useArrangement({
    colors: TRACK_COLORS.length,
    duration: BARS * BAR,
    initialClips: CLIPS,
    initialLocators: LOCATORS,
    initialLoop: LOOP,
    initialMain: MAIN,
    initialReturns: RETURNS,
    initialTracks: TRACKS,
    tempo: SONG_TEMPO,
  });
  const {
    dispatch,
    doc,
    duration,
    locators,
    loop: { on: looping, range: loop },
    signatures,
    tempo,
    canRedo,
    canUndo,
    clips,
    copyOf,
    selectedIds,
    selectedTracks,
    selection,
    tracks,
  } = arrangement;
  // What the lanes, the headers and the keys report, as the commands that change the selection.
  const clearSelection = useCallback(
    () => dispatch({ type: "clear-selection" }),
    [dispatch]
  );
  const selectAll = useCallback(
    () => dispatch({ type: "select-all" }),
    [dispatch]
  );
  const selectClip = useCallback(
    (id: string, additive: boolean) =>
      dispatch({ type: "select-clip", id, additive }),
    [dispatch]
  );
  const selectTrack = useCallback(
    (id: string, additive = false) =>
      dispatch({ type: "select-track", id, additive }),
    [dispatch]
  );
  const toggleSelected = useCallback(
    () => dispatch({ type: "toggle-selected" }),
    [dispatch]
  );
  const bar = secondsPerBar(tempo);
  const describe = useCallback(
    (seconds: number) => {
      const { bar: number, beat } = barsBeatsWith(seconds, tempo, signatures);
      return `Bar ${number}, beat ${beat}`;
    },
    [signatures, tempo]
  );
  const [metronome, setMetronome] = useState(false);
  const [rhythm, setRhythm] = useState<MetronomeRhythm>("auto");
  // Automation mode, and the automated gains and pans moved by hand, which play their mix until enabled again.
  const automation = useTrackAutomation({ dispatch, tracks });
  const { keepRecording, recordings, sources } = useRecordings();
  // The arrangement plays on the audio clock: its clips, its notes through each MIDI track's synth, its mix.
  const engine = useArrangementEngine({
    doc,
    metronome: { on: metronome, rhythm },
    overridden: automation.overridden,
    recordings: sources,
  });
  const clock = engine.position;
  const { playing } = engine;
  const { playPause, seek } = useEngineTransport(engine);
  // The clips, as the commands that change them. A split cuts at the playhead, no closer to a clip's edge than a sixteenth of the bar.
  const getPosition = useCallback(() => clock.getSnapshot(), [clock]);
  // A stretch of time on some tracks, drawn by dragging across bare lanes, and what the keys do with it.
  // Cmd/Ctrl + J: each audio track's clips rendered into one recording, as they play, then one clip per track, one step of undo.
  const consolidateTime = useCallback(
    async (time: TimeSelection) => {
      const sampleRate = webAudio.getContext()?.sampleRate;
      const rendered: Record<string, string> = {};
      await time.tracks.reduce(async (done, track) => {
        await done;
        if (audioClipsIn(doc.clips, track, time.range).length === 0) {
          return;
        }
        const buffer = await renderTrackClips(doc, track, time.range, sources, {
          sampleRate,
        });
        if (buffer) {
          const id = `consolidated-${crypto.randomUUID()}`;
          keepRecording(id, recordingOf(channelsOf(buffer), buffer.sampleRate));
          rendered[track] = id;
        }
      }, Promise.resolve());
      dispatch({ rendered, time, type: "consolidate-time" });
    },
    [dispatch, doc, keepRecording, sources]
  );
  const timeSelection = useTimeSelection({
    bar,
    clips,
    copyOf,
    dispatch,
    getPosition,
    onConsolidate: consolidateTime,
    selectedIds,
    selectedTracks,
    tracks,
  });
  const { clear: letGoOfTime, time: selectedTime } = timeSelection;
  const splitStep = bar / 4;
  const addClip = useCallback(
    (clip: Arranged) => dispatch({ type: "add-clip", clip }),
    [dispatch]
  );
  const duplicateSelection = useCallback(() => {
    const next = dispatch({ type: "duplicate-selection" });
    // The copies are the selection the command leaves, in the order it lists them.
    return (next.selection?.clips ?? []).flatMap((id) =>
      next.doc.clips.filter((clip) => clip.id === id)
    );
  }, [dispatch]);
  const editClip = useCallback(
    (id: string, change: (clip: Arranged) => Arranged) =>
      dispatch({ type: "edit-clip", id, change }),
    [dispatch]
  );
  const settleClipEdit = useCallback(
    () => dispatch({ type: "settle-clip-edit" }),
    [dispatch]
  );
  const splitAtCursor = useCallback(
    () =>
      dispatch({ type: "split-cursor", at: getPosition(), step: splitStep }),
    [dispatch, getPosition, splitStep]
  );
  // The tracks, the time selection and the history, as the commands that change them.
  const addTrack = useCallback(
    (afterId?: string, kind?: TrackKind) => {
      const next = dispatch({ type: "add-track", afterId, kind });
      // The track it added is the one numbered last.
      return next.doc.tracks.find(
        (track) => track.id === `track-${next.trackCount}`
      );
    },
    [dispatch]
  );
  const duplicateTrack = useCallback(
    (id: string) => dispatch({ type: "duplicate-track", id }),
    [dispatch]
  );
  const redo = useCallback(() => dispatch({ type: "redo" }), [dispatch]);
  const removeTrack = useCallback(
    (id: string) => dispatch({ type: "remove-track", id }),
    [dispatch]
  );
  const undo = useCallback(() => dispatch({ type: "undo" }), [dispatch]);
  // The timeline fits the width it is given until it is zoomed, and its grid follows the zoom.
  const viewportRef = useRef<HTMLDivElement>(null);
  // The zoom fits the arrangement and the room past its end.
  const view = useTimelineZoom({
    duration: shownLength(duration, tempo),
    viewportRef,
  });
  const { zoom } = view;
  const grid = useTimelineGrid({ tempo, zoom });
  const { snapStep, step: gridSeconds } = grid;
  // Whether the bar has room for the zoom control; the menu lists the zoom steps only when it does not.
  const zoomSlotRef = useRef<HTMLDivElement>(null);
  const [zoomInBar, setZoomInBar] = useState(true);
  // Below the bar's room, the tempo and the undo and redo move into the more-controls menu.
  const narrowProbeRef = useRef<HTMLDivElement>(null);
  const [narrow, setNarrow] = useState(false);
  // The shortcuts are caught on the panel, so a press on the lane, which takes no focus, hands it over.
  const panelRef = useRef<HTMLDivElement>(null);
  useLayoutEffect(() => {
    const element = panelRef.current;
    if (!element) {
      return;
    }
    const measure = () => {
      if (zoomSlotRef.current) {
        setZoomInBar(getComputedStyle(zoomSlotRef.current).display !== "none");
      }
      if (narrowProbeRef.current) {
        setNarrow(getComputedStyle(narrowProbeRef.current).display !== "none");
      }
    };
    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(element);
    return () => {
      cancelAnimationFrame(frame);
      observer.disconnect();
    };
  }, []);
  // A change of tempo, or the undo of one, changes the bar: the playhead and the zoom keep their places in it.
  const lastBar = useRef(bar);
  const { rescale } = view;
  useLayoutEffect(() => {
    if (lastBar.current === bar) {
      return;
    }
    const ratio = bar / lastBar.current;
    lastBar.current = bar;
    clock.set(clock.getSnapshot() * ratio);
    rescale(ratio);
  }, [bar, clock, rescale]);
  // Multi-select: a press on a clip adds it to the selection, and a drag on bare lane draws a rectangle. For touch, which has no Shift.
  const [multi, setMulti] = useState(false);
  // A touch screen has no Shift: in multi-select mode every press on a header adds to the tracks picked.
  // Stop goes back to the top, as a DAW's does.
  const { stop: stopEngine } = engine;
  const stop = useCallback(() => {
    stopEngine();
    clock.set(0);
  }, [clock, stopEngine]);
  // The zoom as a share of the fitted view: 100% shows everything.
  const zoomPreset = ZOOM_PRESETS.find(
    (ratio) => Math.abs(ratio - view.ratio) < 0.01
  );
  const { setRatio: changeZoom } = view;
  const changeZoomPreset = useCallback(
    (value: string) => changeZoom(Number(value)),
    [changeZoom]
  );
  // A press on a track puts the keys back on the panel, which catches them: the lane takes no focus.
  const focusTrack = useCallback(
    (id: string) => {
      selectTrack(id);
      panelRef.current?.focus({
        focusVisible: false,
        preventScroll: true,
      } as FocusOptions);
    },
    [selectTrack]
  );
  const jumpToLocator = useCallback((at: number) => seek(at), [seek]);
  const playFromLocator = useCallback(
    (at: number) => {
      engine.position.set(at);
      engine.play(at);
    },
    [engine]
  );
  // The locators and the time signatures, with the commands behind them.
  const markers = useTimelineMarkers({
    dispatch,
    getPosition,
    onJump: jumpToLocator,
    onPlay: playFromLocator,
    step: snapStep,
  });
  // M, the arrows, Home and End: what the keys do with the cursor.
  const cursorKeys = useTimelineCursor({
    clips,
    duration,
    getPosition,
    locators,
    onAddLocator: markers.addLocator,
    onPickTrack: selectTrack,
    onSeek: seek,
    selectedIds,
    selectedTracks,
    step: gridSeconds,
    tracks,
  });

  /** Puts the loop around the selected clip, or around the clips of the selected track. */
  const loopSelection = useCallback(() => {
    const chosen = clips.filter(
      (clip) =>
        selectedIds.includes(clip.id) || selectedTracks.includes(clip.track)
    );
    if (chosen.length === 0) {
      return;
    }
    dispatch({
      type: "set-loop",
      loop: {
        on: true,
        range: [
          Math.min(...chosen.map((clip) => clip.value.start)),
          Math.max(
            ...chosen.map((clip) => clip.value.start + clip.value.length)
          ),
        ],
      },
    });
  }, [clips, dispatch, selectedIds, selectedTracks]);

  // The copies are there to be seen: bring them into view once they are drawn.
  const duplicateAndShow = useCallback(() => {
    const copies = duplicateSelection();
    requestAnimationFrame(() => {
      document
        .querySelector(`[data-clip-id="${copies[0]?.id}"]`)
        ?.scrollIntoView({ block: "nearest", inline: "nearest" });
    });
  }, [duplicateSelection]);
  /** Cmd/Ctrl + A selects every clip, Cmd/Ctrl + D duplicates the selection; returns whether the key was one of these. */
  const handleSelectionKey = useCallback(
    (event: KeyboardEvent<HTMLDivElement>) => {
      const key = event.key.toLowerCase();
      if (!(event.metaKey || event.ctrlKey)) {
        return false;
      }
      if (key === "z" || key === "y") {
        event.preventDefault();
        if (key === "y" || event.shiftKey) {
          redo();
        } else {
          undo();
        }
        return true;
      }
      if (key === "a") {
        event.preventDefault();
        selectAll();
        return true;
      }
      if (key === "d" && selectedIds.length > 0) {
        event.preventDefault();
        duplicateAndShow();
        return true;
      }
      if (key === "d" && selectedTracks.length > 0) {
        event.preventDefault();
        for (const id of selectedTracks) {
          duplicateTrack(id);
        }
        return true;
      }
      return false;
    },
    [
      duplicateAndShow,
      duplicateTrack,
      redo,
      selectAll,
      selectedIds,
      selectedTracks,
      undo,
    ]
  );
  /** Delete takes away the tracks picked by their headers (a clip handles its own Delete); returns whether the key was it. */
  const handleTrackKey = useCallback(
    (event: KeyboardEvent<HTMLDivElement>) => {
      const del = event.key === "Delete" || event.key === "Backspace";
      if (!(del && selectedTracks.length > 0 && selectedIds.length === 0)) {
        return false;
      }
      event.preventDefault();
      removeTrack(selectedTracks[0] ?? "");
      return true;
    },
    [removeTrack, selectedIds.length, selectedTracks]
  );
  /** Picking a clip lets go of the time selection. */
  // The clip panel shows the clip picked, as a DAW's detail view follows the selection, for as long as it is open. It starts closed, and picking a clip does not open it: a click of a clip's head does.
  const [clipViewOpen, setClipViewOpen] = useState(false);
  // Collapsed to its title, the panel leaves the tracks the room, from clip to clip.
  const [clipViewCollapsed, setClipViewCollapsed] = useState(false);
  const [clipBoxesFolded, setClipBoxesFolded] = useState<string[]>([]);
  // The clips, as the commands that change them. The menu's Edit opens the clip panel, and picking a clip lets go of the time selected.
  const openClipView = useCallback(() => setClipViewOpen(true), []);
  // What each audio clip draws of its recording, once the recording is there.
  const peaksOf = useCallback(
    (clip: Arranged) => {
      const recording = clip.recording
        ? recordings.get(clip.recording)
        : undefined;
      return recording ? recordedPeaks(recording, clip) : undefined;
    },
    [recordings]
  );
  // The clip panel, under the tracks: it edits the first selected clip.
  const editedClip = clips.find((clip) => clip.id === selectedIds[0]);
  const editedPeaks = useMemo(
    () => (editedClip && peaksOf(editedClip)) ?? NO_PEAKS,
    [editedClip, peaksOf]
  );
  // A MIDI clip's notes, from the clip panel's piano roll: a drag is one undo step.
  const changeNotes = useCallback(
    (notes: NonNullable<Arranged["notes"]>) => {
      if (editedClip) {
        editClip(editedClip.id, (clip) => ({ ...clip, notes }));
      }
    },
    [editClip, editedClip]
  );
  // A double-click on bare MIDI lane makes an empty clip a bar long there, looping, and opens it.
  const midiClipCount = useRef(0);
  const addMidiClipAt = useCallback(
    (trackId: string, start: number) => {
      midiClipCount.current += 1;
      addClip({
        id: `midi-${midiClipCount.current}`,
        loop: [0, bar],
        name: "MIDI clip",
        notes: [],
        sourceLength: bar,
        track: trackId,
        value: { fadeIn: 0, fadeOut: 0, length: bar, offset: 0, start },
      });
      letGoOfTime();
      setClipViewOpen(true);
    },
    [addClip, bar, letGoOfTime]
  );
  const renameClip = useCallback(
    (id: string, name: string) => dispatch({ type: "rename-clip", id, name }),
    [dispatch]
  );
  const changeClipSettings = useCallback(
    (next: ClipSettings) => {
      if (editedClip) {
        editClip(editedClip.id, (clip) =>
          withClipSettings(clip, next, duration)
        );
      }
    },
    [duration, editClip, editedClip]
  );
  // Where a MIDI clip plays, from its clip panel: it keeps its place, and ends where the timeline does at most.
  const changeMidiRegion = useCallback(
    (region: MidiClipRegion) => {
      if (!editedClip) {
        return;
      }
      editClip(editedClip.id, (clip) => ({
        ...clip,
        loop: region.loop ?? undefined,
        value: {
          ...clip.value,
          length: Math.min(region.length, duration - clip.value.start),
          offset: region.offset,
        },
      }));
    },
    [duration, editClip, editedClip]
  );
  // A key pressed in the piano roll plays the track's synth.
  const editedTrack = editedClip?.track;
  const auditionOn = useCallback(
    (pitch: number, details: { velocity: number }) => {
      if (editedTrack) {
        engine.engine?.noteOn(editedTrack, pitch, details.velocity);
      }
    },
    [editedTrack, engine.engine]
  );
  const auditionOff = useCallback(
    (pitch: number) => {
      if (editedTrack) {
        engine.engine?.noteOff(editedTrack, pitch);
      }
    },
    [editedTrack, engine.engine]
  );
  // A drum clip's pads: those of the drum rack its track plays, lowest note on top.
  const editedRack = tracks
    .find((item) => item.id === editedTrack)
    ?.devices?.find((item) => item.device === DRUM_RACK_DEVICE)?.rack;
  const editedPads = useMemo(
    () =>
      editedRack?.chains
        .flatMap((chain) =>
          chain.pad ? [{ name: chain.name, note: chain.pad.note }] : []
        )
        .sort((a, b) => a.note - b.note),
    [editedRack]
  );
  // A pad's name pressed in the steps: the track plays it, let go at once, as a drum rings on.
  const auditionPad = useCallback(
    (note: number) => {
      if (editedTrack) {
        engine.engine?.noteOn(editedTrack, note, 0.8);
        engine.engine?.noteOff(editedTrack, note);
      }
    },
    [editedTrack, engine.engine]
  );
  const changeSwing = useCallback(
    (swing: ClipSwing | null) => {
      if (editedClip) {
        editClip(editedClip.id, ({ swing: _was, ...clip }) =>
          swing ? { ...clip, swing } : clip
        );
      }
    },
    [editClip, editedClip]
  );
  const midiEditing = useMemo(
    () => ({
      onNoteOff: auditionOff,
      onNoteOn: auditionOn,
      onNotesChange: changeNotes,
      onPadOn: auditionPad,
      onRegionChange: changeMidiRegion,
      onSwingChange: changeSwing,
      pads: editedPads,
    }),
    [
      auditionOff,
      auditionOn,
      auditionPad,
      changeMidiRegion,
      changeNotes,
      changeSwing,
      editedPads,
    ]
  );
  // The clip panel's switch: off, the clip stays on its track and is not heard.
  const setEditedActive = useCallback(
    (active: boolean) => {
      if (editedClip) {
        editClip(editedClip.id, (clip) => ({ ...clip, disabled: !active }));
        settleClipEdit();
      }
    },
    [editClip, editedClip, settleClipEdit]
  );
  // Crop, from the clip panel: its source cut down to the stretch kept, and the clip on what is left of it.
  const cropEdited = useCallback(
    (range: readonly [number, number], next: ClipSettings) => {
      if (editedClip) {
        editClip(editedClip.id, (clip) => ({
          ...withClipSettings(clip, next, duration),
          sourceFrom: (clip.sourceFrom ?? 0) + range[0],
          sourceLength: next.sourceLength,
        }));
        settleClipEdit();
      }
    },
    [duration, editClip, editedClip, settleClipEdit]
  );
  const closeClipView = useCallback(() => setClipViewOpen(false), []);
  /**
   * Cmd/Ctrl + Alt + 3 shows or hides the clip panel, read from the key's place
   * as Alt changes the letter on a Mac, and 0 switches the selected clips off
   * or on. Returns whether the key was one of these.
   */
  const handleClipKey = (event: KeyboardEvent<HTMLDivElement>) => {
    if (typing(event.target)) {
      return false;
    }
    const mod = event.metaKey || event.ctrlKey;
    if (mod && event.altKey && event.code === "Digit3") {
      event.preventDefault();
      setClipViewOpen((open) => !open);
      return true;
    }
    if (
      !(mod || event.altKey) &&
      (event.key === "0" || event.code === "Digit0") &&
      selectedIds.length > 0
    ) {
      event.preventDefault();
      toggleSelected();
      return true;
    }
    return false;
  };
  /** A shows or hides the automation; returns whether the key was it. */
  const handleAutomationKey = (event: KeyboardEvent<HTMLDivElement>) => {
    if (
      event.key.toLowerCase() !== "a" ||
      event.metaKey ||
      event.ctrlKey ||
      event.altKey ||
      event.shiftKey ||
      typing(event.target)
    ) {
      return false;
    }
    event.preventDefault();
    automation.toggle();
    return true;
  };
  // S, or Cmd/Ctrl + E, splits at the cursor, Cmd/Ctrl + D duplicates the clip; Escape drops the selection.
  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    if (event.key === "Escape") {
      clearSelection();
      letGoOfTime();
      return;
    }
    const key = event.key.toLowerCase();
    if (
      timeSelection.handleKey(event) ||
      handleClipKey(event) ||
      handleTrackKey(event) ||
      cursorKeys.handleKey(event) ||
      handleAutomationKey(event)
    ) {
      return;
    }
    if (key === "l" && (event.metaKey || event.ctrlKey) && selection) {
      event.preventDefault();
      loopSelection();
      return;
    }
    if (handleSelectionKey(event)) {
      return;
    }
    const split =
      (key === "s" && !(event.metaKey || event.ctrlKey || event.altKey)) ||
      (key === "e" && (event.metaKey || event.ctrlKey));
    if (split && selection) {
      event.preventDefault();
      splitAtCursor();
    }
  };

  // The grid the lanes draw is the grid everything snaps to. Snap off draws no lines and snaps nothing: a step of 0 is no grid.
  // A file dragged over an audio track marks it; let go there, it becomes a clip at the grid line under the
  // pointer (anywhere with Cmd/Ctrl), named and as long as the file, and the files after it follow it on the track.
  // A file with a beat is warped in time at the arrangement's tempo (CLP-019).
  const fileCount = useRef(0);
  const addFiles = useCallback(
    async (files: File[], trackId: string, start: number) => {
      // Decoded at the engine's rate, so they play as they are. A file that is not sound is left out.
      const context = webAudio.getContext();
      if (!context) {
        return;
      }
      const decoded = await Promise.all(
        files.map((file) =>
          file
            .arrayBuffer()
            .then((bytes) => decodeAudioChannels(context, bytes))
            .catch(() => null)
        )
      );
      // Under the headers, each file makes a track of its own, from the start; on a track, they follow one another.
      const own = trackId === NEW_TRACK;
      let at = start;
      for (const [index, file] of files.entries()) {
        const channels = decoded[index];
        const length = (channels?.[0]?.length ?? 0) / context.sampleRate;
        const onto = own ? addTrack(undefined, "audio")?.id : trackId;
        if (!(channels && onto && length > 0 && at < duration)) {
          continue;
        }
        fileCount.current += 1;
        const id = `file${fileCount.current}`;
        keepRecording(id, recordingOf(channels, context.sampleRate));
        const clip = warpOnImport(
          {
            id,
            name: file.name.replace(EXTENSION, ""),
            recording: id,
            sourceLength: length,
            track: onto,
            value: { fadeIn: 0, fadeOut: 0, length, offset: 0, start: at },
          },
          analyzeBeat(channels, context.sampleRate),
          tempo
        );
        addClip({
          ...clip,
          value: {
            ...clip.value,
            length: Math.min(clip.value.length, duration - at),
          },
        });
        selectClip(id, false);
        at += own ? 0 : clip.value.length;
      }
    },
    [addClip, addTrack, duration, keepRecording, selectClip, tempo]
  );
  // What the time strips report, as the commands that change the arrangement.
  const changeTempo = useCallback(
    (next: Tempo) => dispatch({ type: "set-tempo", tempo: next }),
    [dispatch]
  );
  const changeLooping = useCallback(
    (on: boolean) => dispatch({ type: "set-loop", loop: { on } }),
    [dispatch]
  );
  // Z zooms onto the selection, + and - zoom around the cursor, X steps back through the zooms they left behind.
  const { zoomAround, zoomBack, zoomTo } = view;
  const zoomAroundCursor = useCallback(
    (factor: number) => zoomAround(clock.getSnapshot(), factor),
    [clock, zoomAround]
  );
  const zoomToSelection = useCallback(() => {
    if (selectedTime) {
      zoomTo(...selectedTime.range);
      return;
    }
    const chosen = clips.filter(
      (clip) =>
        selectedIds.includes(clip.id) || selectedTracks.includes(clip.track)
    );
    if (chosen.length === 0) {
      zoomTo(...loop);
      return;
    }
    zoomTo(
      Math.min(...chosen.map((clip) => clip.value.start)),
      Math.max(...chosen.map((clip) => clip.value.start + clip.value.length))
    );
  }, [clips, loop, selectedIds, selectedTime, selectedTracks, zoomTo]);

  /** The navigation keys: the grid with Cmd/Ctrl + 1 to 5, the zoom with +, -, Z and X, and the cursor from the panel. */
  const handleNavigationKey = useCallback(
    (event: KeyboardEvent<HTMLDivElement>) => {
      if (event.metaKey || event.ctrlKey) {
        const change = GRID_KEYS[event.code];
        if (!(change && !event.altKey && !event.shiftKey)) {
          return false;
        }
        event.preventDefault();
        grid.change(change);
        return true;
      }
      if (typing(event.target) || event.altKey) {
        return false;
      }
      const key = event.key.toLowerCase();
      const zoomKeys: Record<string, () => void> = {
        "+": () => zoomAroundCursor(2),
        "-": () => zoomAroundCursor(0.5),
        "=": () => zoomAroundCursor(2),
        x: zoomBack,
        z: zoomToSelection,
      };
      const zoomKey = event.shiftKey && key !== "+" ? undefined : zoomKeys[key];
      if (zoomKey) {
        event.preventDefault();
        zoomKey();
        return true;
      }
      // Anywhere else in the panel, a clip's or the loop's own input takes its arrows.
      return (
        event.target === event.currentTarget && cursorKeys.handleArrowKey(event)
      );
    },
    [
      cursorKeys.handleArrowKey,
      grid.change,
      zoomAroundCursor,
      zoomBack,
      zoomToSelection,
    ]
  );
  const handlePanelKey = (event: KeyboardEvent<HTMLDivElement>) => {
    if (!handleNavigationKey(event)) {
      handleKeyDown(event);
    }
  };

  return (
    // biome-ignore lint/a11y/noStaticElementInteractions: the editor's shortcuts, caught from the controls inside it
    <div
      className="rounded-xl @container/panel flex w-full min-w-0 flex-col gap-4 border bg-card p-4 outline-none"
      onKeyDown={handlePanelKey}
      ref={panelRef}
      tabIndex={-1}
    >
      <div className="flex items-center justify-between gap-2 p-1">
        <div className="flex min-w-0 flex-1 items-center gap-2">
          <div className="@3xl/panel:hidden" ref={narrowProbeRef} />
          <Transport
            className="min-w-0 flex-1 flex-nowrap"
            looping={looping}
            metronome={metronome}
            onLoopingChange={changeLooping}
            onMetronomeChange={setMetronome}
            onPlayPause={playPause}
            onRhythmChange={setRhythm}
            onStop={stop}
            onTempoChange={changeTempo}
            playing={playing}
            rhythm={rhythm}
            signatures={signatures}
            source={clock}
            tempo={tempo}
          />
          <div className="hidden h-7 w-10 shrink-0 items-center @3xl/panel:flex">
            <MainLevel analysers={engine.meter(doc.main.id)} />
          </div>
        </div>
        <div className="flex min-w-0 items-center gap-2">
          {automation.anyOverridden ? (
            <Button
              aria-label="Re-enable automation"
              className="text-primary"
              onClick={automation.reenable}
              size="icon"
              variant="outline"
            >
              <IconPlaceholder
                hugeicons="RotateLeft01Icon"
                lucide="RotateCcwIcon"
                phosphor="ArrowCounterClockwiseIcon"
                remixicon="RiArrowGoBackLine"
                tabler="IconRotate"
              />
            </Button>
          ) : null}
          <Button
            aria-label="Automation mode"
            aria-pressed={automation.automating}
            className="hidden @3xl/panel:inline-flex"
            onClick={automation.toggle}
            size="icon"
            variant={automation.automating ? "default" : "outline"}
          >
            {/* An envelope: what automation draws over a lane. */}
            <EnvelopeIcon className="size-4" weight="bold" />
          </Button>
          <ButtonGroup className="hidden @3xl/panel:flex">
            <Button
              aria-label="Undo"
              disabled={!canUndo}
              onClick={undo}
              size="icon"
              variant="outline"
            >
              <IconPlaceholder
                hugeicons="Undo02Icon"
                lucide="Undo2Icon"
                phosphor="ArrowUUpLeftIcon"
                remixicon="RiArrowGoBackLine"
                tabler="IconArrowBackUp"
              />
            </Button>
            <Button
              aria-label="Redo"
              disabled={!canRedo}
              onClick={redo}
              size="icon"
              variant="outline"
            >
              <IconPlaceholder
                hugeicons="Redo02Icon"
                lucide="Redo2Icon"
                phosphor="ArrowUUpRightIcon"
                remixicon="RiArrowGoForwardLine"
                tabler="IconArrowForwardUp"
              />
            </Button>
          </ButtonGroup>
          <div
            className="hidden items-center gap-2 @7xl/panel:flex"
            ref={zoomSlotRef}
          >
            <ParameterField
              className="w-44"
              format={PERCENT}
              hideLabel
              label="Zoom"
              largeStep={1}
              max={view.maxRatio}
              min={1}
              onValueChange={changeZoom}
              step={0.25}
              steppers={ZOOM_STEPPERS}
              unit="Zoom"
              value={view.ratio}
            />
          </div>
          <DropdownMenu>
            <DropdownMenuTrigger
              render={
                <Button
                  aria-label="More controls"
                  size="icon"
                  variant="outline"
                />
              }
            >
              <IconPlaceholder
                hugeicons="MoreHorizontalIcon"
                lucide="EllipsisIcon"
                phosphor="DotsThreeIcon"
                remixicon="RiMoreLine"
                tabler="IconDots"
              />
            </DropdownMenuTrigger>
            <DropdownMenuContent align="end" className="w-auto min-w-48">
              {narrow ? (
                <>
                  <DropdownMenuItem disabled={!canUndo} onClick={undo}>
                    Undo
                  </DropdownMenuItem>
                  <DropdownMenuItem disabled={!canRedo} onClick={redo}>
                    Redo
                  </DropdownMenuItem>
                  <DropdownMenuSeparator />
                </>
              ) : null}
              <DropdownMenuCheckboxItem
                checked={multi}
                onCheckedChange={setMulti}
              >
                Multi-select
              </DropdownMenuCheckboxItem>
              <DropdownMenuCheckboxItem
                checked={automation.automating}
                onCheckedChange={automation.setAutomating}
              >
                Automation
              </DropdownMenuCheckboxItem>
              <DropdownMenuSeparator />
              <DropdownMenuSub>
                <DropdownMenuSubTrigger>
                  Keyboard shortcuts
                </DropdownMenuSubTrigger>
                <DropdownMenuSubContent className="flex max-h-(--available-height) w-auto flex-col">
                  <div className="scrollbar flex min-h-0 flex-col gap-2 overflow-y-auto p-2 text-sm whitespace-nowrap">
                    {SHORTCUTS.map((shortcut) => (
                      <div
                        className="flex items-center justify-between gap-3"
                        key={`${shortcut.action}-${shortcut.keys.join("+")}`}
                      >
                        <span>{shortcut.action}</span>
                        <KbdGroup>
                          {shortcut.keys.map((key) => (
                            <Kbd key={key}>{key}</Kbd>
                          ))}
                        </KbdGroup>
                      </div>
                    ))}
                  </div>
                </DropdownMenuSubContent>
              </DropdownMenuSub>
              {zoomInBar ? null : (
                <>
                  <DropdownMenuSeparator />
                  <DropdownMenuSub>
                    <DropdownMenuSubTrigger>Zoom</DropdownMenuSubTrigger>
                    <DropdownMenuSubContent className="w-auto">
                      <div className="p-2">
                        <ParameterField
                          className="w-44"
                          format={PERCENT}
                          hideLabel
                          label="Zoom"
                          largeStep={1}
                          max={view.maxRatio}
                          min={1}
                          onValueChange={changeZoom}
                          step={0.25}
                          steppers={ZOOM_STEPPERS}
                          unit="Zoom"
                          value={view.ratio}
                        />
                      </div>
                      <DropdownMenuSeparator />
                      <DropdownMenuRadioGroup
                        onValueChange={changeZoomPreset}
                        value={
                          zoomPreset === undefined ? "" : String(zoomPreset)
                        }
                      >
                        {ZOOM_PRESETS.map((ratio) => (
                          <DropdownMenuRadioItem
                            disabled={ratio > view.maxRatio}
                            key={ratio}
                            value={String(ratio)}
                          >
                            {ratio === 1 ? "Fit" : `${ratio * 100} %`}
                          </DropdownMenuRadioItem>
                        ))}
                      </DropdownMenuRadioGroup>
                    </DropdownMenuSubContent>
                  </DropdownMenuSub>
                </>
              )}
            </DropdownMenuContent>
          </DropdownMenu>
        </div>
      </div>
      <ArrangementView
        arrangement={arrangement}
        automation={automation}
        engine={engine}
        findDevice={noDevice}
        getCursor={getPosition}
        liveTake={null}
        markers={markers}
        multiSelect={multi}
        onAddMidiClip={addMidiClipAt}
        onEditClip={openClipView}
        onFiles={addFiles}
        onSeek={seek}
        onSelectTrack={focusTrack}
        peaksOf={peaksOf}
        reading={NO_READING}
        selectedTrack={selectedTracks[0] ?? null}
        timelineGrid={grid}
        timelineZoom={view}
        timeSelection={timeSelection}
        viewportRef={viewportRef}
      />
      {clipViewOpen ? (
        <ClipDock
          bar={bar}
          beatsPerBar={tempo.beatsPerBar}
          clip={editedClip}
          collapsed={clipViewCollapsed}
          foldedBoxes={clipBoxesFolded}
          format={describe}
          midi={midiEditing}
          onActiveChange={setEditedActive}
          onClose={closeClipView}
          onCollapsedChange={setClipViewCollapsed}
          onCrop={cropEdited}
          onFoldedBoxesChange={setClipBoxesFolded}
          onRename={renameClip}
          onValueChange={changeClipSettings}
          onValueCommitted={settleClipEdit}
          peaks={editedPeaks}
          position={clock}
        />
      ) : null}
    </div>
  );
}
```

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.

**In Vue, Svelte and Web**

The timeline's behavior is a few files, the primitive, written on the UI SDK kernel and copied into your project. It is the surface of an arrangement: a playback position and a zoom in units of your own (seconds, beats, steps), lanes the parts are placed on, tracks, marks, ranges such as a loop, and clips that move, trim and fade. Each framework renders it with a thin adapter that you also own, and one suite of tests runs against each adapter.

## Installation

**In React**

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](https://ui-sdk.dev) kernel, in beta. Nothing of ours comes from npm: the primitive and its adapter are files you copy into your project and own, and the only packages are the kernel's. The commands name its version, `@ui-sdk/*@0.1.0-beta.14`.

**In React**

The styled component, with the clips, the tracks and the navigator styled, is one command:

**In React**

**CLI**

The styled component, with size variants and theme styles:

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

Or the primitive alone, to style yourself:

```bash
npx 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:

```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 and `primitive.ts` into `components/audio-ui/` (under `src/lib/` in SvelteKit). It installs the kernel's packages:

```bash
npx @audio-ui/cli add timeline
```

The optional styles are one more name:

```bash
npx @audio-ui/cli add primitives-css
```

**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: `timeline.ts`, the timeline itself, with a controller for each of its gestures beside it (the position and the zoom, the tracks, the ranges, the clips, the navigator); `grid.ts`, the grid they snap to, and `frame.ts`, which scrolls a view while a drag is held at its edge, both shared with the piano roll and the waveform; and `primitive.ts`, the little every primitive shares. Copy them into `components/audio-ui/` (`src/lib/components/audio-ui/` in Svelte).

<ItemFiles name="timeline-react" to={18} />

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

**Vue**

<ItemFiles name="timeline-vue" from={18} />

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

**JavaScript**

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

<ItemFiles name="timeline-web" from={18} />

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

**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 timeline 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).

**In React**

## 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`, <kbd>Page Up</kbd> / <kbd>Page Down</kbd> and Shift by `largeStep`, and <kbd>Home</kbd> / <kbd>End</kbd> go to the ends.

### Usage

```tsx
import {
  Timeline,
  TimelineLane,
  TimelineMark,
  TimelinePlayhead,
  TimelineRuler,
  TimelineViewport,
} from "@/components/audio-ui/timeline";
import {
  DEFAULT_TEMPO,
  describeBarsBeats,
  gridInterval,
} from "@/lib/engine/time";
```

```tsx
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

```tsx
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.

```tsx
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.

```tsx
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.

### Navigator

```tsx
<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:

```tsx
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`](/docs/hooks/use-timeline-zoom) 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`](/docs/hooks/use-timeline-grid) 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:

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

**In React**

## 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.

```tsx
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.

```tsx
<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.

```tsx
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`](/docs/hooks/use-track-reorder) 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.

```tsx
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`](/docs/hooks/use-time-selection).

### 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.

```tsx
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`](/docs/hooks/use-timeline-cursor).

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`](/docs/engine/analysis#a-recording-as-it-comes-in) 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.

```ts
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 }`:

```tsx
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](/docs/components/base/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](/docs/components/base/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](/docs/components/base/rack#drum-racks), each pad playing a [Drum Synth](/docs/components/base/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](/docs/components/base/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](/docs/guides/playback) (`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](/docs/components/base/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](/docs/components/base/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`](/docs/lib/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**

| Key | Effect |
| --- | --- |
| `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.

```ts
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.

```ts
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

**In React**

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.

**React**

```tsx
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>
  );
}
```

**Vue**

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

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

<template>
  <Timeline.Root :duration="64" :snap-step="1" @clip-change="(next: object) => emit('clip', next)">
    <Timeline.Viewport>
      <Timeline.Ruler aria-label="Position" class="h-6" />
      <Timeline.Lane class="h-16">
        <Timeline.Playhead class="inset-y-0 w-px bg-primary" />
        <Timeline.Clip aria-label="Take 1" class="inset-y-1 rounded bg-card" clip="take-1" :value="clip">
          <Timeline.ClipHeader class="h-4" clip="take-1" />
          <Timeline.ClipHandle aria-label="Trim start" class="absolute inset-y-0 left-0 w-1" clip="take-1" edge="start" />
          <Timeline.ClipHandle aria-label="Trim end" class="absolute inset-y-0 right-0 w-1" clip="take-1" edge="end" />
        </Timeline.Clip>
      </Timeline.Lane>
    </Timeline.Viewport>
  </Timeline.Root>
</template>
```

**Svelte**

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

  let { clip, onClip }: { clip: object; onClip: (clip: object) => void } = $props();
</script>

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

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

**JavaScript**

```html
<audio-ui-timeline duration="64" snap-step="1">
  <audio-ui-timeline-viewport>
    <audio-ui-timeline-ruler aria-label="Position"></audio-ui-timeline-ruler>
    <audio-ui-timeline-lane>
      <audio-ui-timeline-playhead></audio-ui-timeline-playhead>
      <audio-ui-timeline-clip
        clip="take-1"
        aria-label="Take 1"
        default-value='{"start":8,"length":16,"offset":0,"fadeIn":0,"fadeOut":0}'
      >
        <audio-ui-timeline-clip-header clip="take-1"></audio-ui-timeline-clip-header>
        <audio-ui-timeline-clip-trim-start clip="take-1" aria-label="Trim start"></audio-ui-timeline-clip-trim-start>
        <audio-ui-timeline-clip-trim-end clip="take-1" aria-label="Trim end"></audio-ui-timeline-clip-trim-end>
      </audio-ui-timeline-clip>
    </audio-ui-timeline-lane>
  </audio-ui-timeline-viewport>
</audio-ui-timeline>

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

  document.querySelector("audio-ui-timeline").addEventListener("clipchange", (event) => {
    console.log(event.detail.clip, event.detail.value, event.detail.target);
  });
</script>
```

In the web adapter, a live `source` is a property, and so is a Grid's `snapPoints` as a JSON attribute. A clip, a range, a track and a mark are named by an attribute (`clip`, `range`, `track`, `mark`) that the parts that belong to it repeat. The inputs, and a fade's curve, are made for you. Each part binds a microtask after it connects: read the element's state after that.

### 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

**In React**

### Registry component

#### Timeline

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `duration` | `number` | `1` | Length of the timeline, in your units. |
| `zoom` | `number` |  | Zoom, in px per unit. |
| `defaultZoom` | `number` |  | Uncontrolled starting zoom, in px per unit. Unset, the timeline fits its width until zoomed. |
| `minZoom / maxZoom` | `number` | `0 / Infinity` | Bounds the zoom is clamped to. |
| `onZoomChange` | `(zoom, eventDetails) => void` |  | Fires when the zoom changes, already clamped. `eventDetails.cancel()` keeps the zoom where it was. |
| `position` | `number` |  | Playback position, from 0 to `duration`. |
| `defaultPosition` | `number` | `0` | Uncontrolled starting position. |
| `source` | `{ getSnapshot, subscribe }` |  | A live position followed outside React; takes precedence over `position`. |
| `onPositionChange` | `(value, eventDetails) => void` |  | Fires while the position is moved: press, drag, keyboard and input changes. |
| `onPositionCommitted` | `(value, eventDetails) => void` |  | Fires when a gesture that moved the position ends. |
| `snapStep` | `number` | `0` | Distance between grid lines, in your units. 0 is no grid. |
| `snapOffset` | `number` | `0` | Where the grid's lines start, in your units. |
| `step / largeStep` | `number` | `snapStep / ten steps` | Keyboard steps. |
| `disabled` | `boolean` | `false` | Disables seeking and zooming. |

#### Parts

**Components**

| Name | Description |
| --- | --- |
| `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

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `clip` | `Arranged` |  | The clip: its place (`value`), its source and its notes. |
| `selected` | `boolean` |  | Whether it is in the selection. |
| `swatch` | `number \| string` |  | Its color: its track's, an index into `TRACK_COLORS` or a CSS hex of the user's own. |
| `peaks` | `ArrayLike<number> \| { max, min }` |  | An audio clip's source as peaks spread evenly over its `sourceLength`, amplitudes from 0 to 1 or the lowest and highest samples of each slice: its waveform is drawn from them, the stretch it plays, round its loop, mirrored when reversed, stretched by its warp (`clipWaveform` in `lib/arrangement` reads it the same way). |
| `trackName` | `string` |  | Its track's name, for its label. |
| `describe` | `(time) => string` |  | A time in words, such as "Bar 3, beat 2". |
| `onChange, onCommit` | `(id, value, details) => void, (id, details) => void` |  | The clip moved, trimmed or faded, and the gesture ended. |
| `onSelect` | `(id, additive) => void` |  | It was pressed: `additive` with Shift, Cmd or Ctrl, or with `multi`. |
| `onAction` | `(action, id) => void` |  | Picked from its menu: `"edit"`, `"duplicate"`, `"split"`, `"toggle"` or `"remove"`. |
| `onRename, onRemove, onFadeShape` | `(id, …) => void` |  | Renamed in place, deleted with its key, and a fade's curve picked. |
| `multi` | `boolean` | `false` | Whether a press adds it to the selection, for a touch screen. |
| `copying, lift, onLift` | `boolean, number, (id, offset) => void` |  | For group drags: whether it is a copy being dragged, how far it is held up or down, and how far it is dragged. |

### useArrangedClips

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `clips, copying, selectedIds, tracks, dispatch` | `as useArrangement returns them` |  | The arrangement. A return track takes no clip: leave it out of `tracks`. |
| `getPosition, splitStep` | `() => number, number` |  | Where the menu's split cuts, and the closest it comes to a clip's edge. |
| `viewportRef` | `Ref` |  | The viewport the tracks scroll in: a clip let go off them goes to the nearest. |
| `onEdit, onPress` | `(id) => void, () => void` |  | "Edit" chosen from a clip's menu, and a clip pressed, for what else it lets go of. |
| `clipProps(clip), ghostsOn(trackId)` | `props, Arranged[]` |  | What an `ArrangedClip` takes, and the originals of the clips being copied on a track. |
| `onRemove, onRename` | `(id) => void, (id, name) => void` |  | The same commands, for a clip's other editors. |

### TimelineLocator and TimelineSignature

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `locator` | `{ at, name }` |  | A locator. |
| `onJump, onRemove, onRename` | `(at) => void, (at) => void, (at, name) => void` |  | Pressed, deleted and renamed. |
| `onLoopToNext` | `(id) => void` |  | Its menu's "Loop to the next locator": the loop from it to the next one, or to the end. Without it, the menu has no such entry. |
| `change` | `{ id, at, beatsPerBar, beatUnit }` |  | A time-signature change. |
| `editing, onEditingChange` | `boolean, (id \| null) => void` |  | Whether it is being typed. |
| `onMove, onSet, onRemove` | `(id, to) => void, (id, beats, unit) => void, (id) => void` |  | Moved by `step` with the arrows, typed, deleted. |
| `step` | `number` |  | How far the arrows move a change: the grid. |

### useTimelineMarkers

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `dispatch, getPosition` | `(command) => state, () => number` |  | The arrangement's commands, and where the cursor is. |
| `onJump, onPlay, step` | `(at) => void, (at) => void, number` |  | A marker pressed, a locator double-clicked to play from, and how far the arrows move one. |
| `locator, signature` | `props` |  | To spread on `TimelineLocator` and `TimelineSignature`. |
| `addLocator, addSignature, editingSignature` | `() => void, () => void, string \| null` |  | New markers at the cursor, and the change being typed. |

### useTrackAutomation

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `dispatch, tracks` | `(command) => void, ArrangementTrack[]` |  | The arrangement's commands, and the tracks whose automation a change by hand overrides. |
| `automating, setAutomating, toggle` | `boolean, (on) => void, () => void` |  | Automation mode. |
| `parameterOf, show` | `(trackId) => parameter, (trackId, parameter) => void` |  | What a track's lane shows, Volume until another is chosen. |
| `changeMix` | `(trackId, patch) => void` |  | A mix changed by hand: a fader's drag is a burst, a switch a step, and an automated gain or pan is overridden. |
| `overridden, anyOverridden, reenable` | `Record<trackId, parameter[]>, boolean, () => void` |  | What plays its mix instead of its envelope, and the way back. |
| `edit, clear` | `(trackId, parameter, points) => void, (trackId, parameter) => void` |  | Draws an envelope, which plays again; takes one away. |

### TrackAutomationChooser and TrackAutomation

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `track` | `ArrangementTrack` |  | The track, with its `automation`. |
| `parameter` | `AutomatedParameter` |  | What the lane shows: `"volume"`, `"pan"`, or a device's parameter by its key. |
| `targets` | `AutomationTarget[]` |  | The track's devices' parameters it can automate, as `deviceTargets` gives them: the chooser lists them by device, and the envelope reads and stands by them. |
| `onParameterChange, onClear` | `(trackId, parameter) => void` |  | The chooser's: another parameter picked, and its envelope cleared. |
| `output` | `boolean` | `true` | Whether the track has an output. One without, such as a MIDI track with no instrument, has no volume or pan: the chooser lists only its devices' parameters. |
| `mix` | `Mix` |  | The track's mix, where a line with no points stands. |
| `onChange, onCommit` | `(trackId, parameter, points) => void, () => void` |  | The envelope was edited, and the gesture ended. |
| `duration, snapStep, describe` | `number, number, (time) => string` |  | The arrangement's length, the grid a point snaps to in time, and a time in words. |
| `overridden` | `AutomatedParameter[]` |  | The parameters moved by hand since, drawn greyed. |

### Options

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

| Option | Type | Default | |
| --- | --- | --- | --- |
| `position`, `defaultPosition` | `number` | `0` | The playback position, controlled or starting. |
| `source` | `{ getSnapshot, subscribe }` | | A live position, followed with no render. |
| `zoom`, `defaultZoom` | `number` | fits the width | px per unit. Unset, the timeline fits its width until zoomed. |
| `minZoom`, `maxZoom` | `number` | `0`, `Infinity` | The zoom's limits. |
| `duration` | `number` | `1` | The length of the timeline, in your units. |
| `snapStep`, `snapOffset` | `number` | `0` | The grid every gesture lands on unless Cmd/Ctrl is held. 0 is no grid. |
| `snapPoints` | `number[]` | | Places that pull a press, or a dragged clip or range, onto them from a few px away. |
| `step`, `largeStep` | `number` | the grid step, ten steps | The keys' steps. |
| `disabled` | `boolean` | `false` | Takes no gesture. |
| `onPositionChange`, `onPositionCommitted` | `(value, details) => void` | | A seek, and its end. |
| `onZoomChange` | `(zoom, details) => void` | | The zoom changed, already clamped. |
| `onSelectionChange`, `onSelectionCommitted` | `(range, details) => void` | | A Shift drag on the ruler, or on a seekable lane. |
| `onClipChange`, `onClipCommitted` | `(clip, details) => void` | | A clip moved, trimmed or faded. `details.clip` names it and `details.target` says what moved. |
| `onClipSelectedChange`, `onClipRemove`, `onClipDragOffsetChange` | | | A press selects a clip, Delete asks to remove it, a move drags it up or down. |
| `onRangeChange`, `onRangeCommitted` | `(range, details) => void` | | A range moved, resized or drawn, with `details.range` and `details.edge`. |
| `onTrackHeightChange`, `onTrackHeightCommitted` | `(height, details) => void` | | A track's resize handle asks for a height, `undefined` to give it up. |
| `onMarkChange`, `onMarkCommitted` | `(value, details) => void` | | A 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

**In React, Vue and Svelte**

| Part | Element | Props |
| --- | --- | --- |
| `Timeline.Clip` | `div` | `additive: boolean`, `clip: key`, `defaultSelected: boolean`, `defaultValue: value`, `disabled: boolean`, `minLength: number`, `movable: boolean`, `selected: boolean`, `sourceLength: number`, `value: value` |
| `Timeline.ClipFade` | composed of other parts |  |
| `Timeline.ClipFadeHandle` | composed of other parts |  |
| `Timeline.ClipHandle` | composed of other parts |  |
| `Timeline.ClipHeader` | `div` | `clip: key` |
| `Timeline.Lane` | `div` | `id: id`, `seekable: boolean`, `selects: boolean` |
| `Timeline.Mark` | `div` | `mark: key`, `movable: boolean`, `step: number`, `value: number` |
| `Timeline.Navigator` | `div` | `minWindowWidth: number` |
| `Timeline.NavigatorHandle` | composed of other parts |  |
| `Timeline.NavigatorWindow` | `div` |  |
| `Timeline.Playhead` | `div` | `id: id` |
| `Timeline.Range` | `div` | `defaultValue: value`, `disabled: boolean`, `drawable: boolean`, `minDrawnWidth: number`, `minLength: number`, `movable: boolean`, `range: key`, `value: value` |
| `Timeline.RangeHandle` | composed of other parts |  |
| `Timeline.Root` | `div` |  |
| `Timeline.Ruler` | `div` |  |
| `Timeline.Track` | `div` | `height: number`, `largeStep: number`, `maxHeight: number`, `minHeight: number`, `selected: boolean`, `step: number`, `track: key` |
| `Timeline.TrackHeader` | `div` |  |
| `Timeline.TrackResizeHandle` | `div` | `track: key` |
| `Timeline.Viewport` | `div` |  |

**In Web**

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

`audio-ui-timeline`, `audio-ui-timeline-clip`, `audio-ui-timeline-clip-fade-in`, `audio-ui-timeline-clip-fade-in-handle`, `audio-ui-timeline-clip-fade-in-input`, `audio-ui-timeline-clip-fade-out`, `audio-ui-timeline-clip-fade-out-handle`, `audio-ui-timeline-clip-fade-out-input`, `audio-ui-timeline-clip-header`, `audio-ui-timeline-clip-input`, `audio-ui-timeline-clip-trim-end`, `audio-ui-timeline-clip-trim-end-input`, `audio-ui-timeline-clip-trim-start`, `audio-ui-timeline-clip-trim-start-input`, `audio-ui-timeline-lane`, `audio-ui-timeline-mark`, `audio-ui-timeline-navigator`, `audio-ui-timeline-navigator-end`, `audio-ui-timeline-navigator-end-input`, `audio-ui-timeline-navigator-start`, `audio-ui-timeline-navigator-start-input`, `audio-ui-timeline-navigator-window`, `audio-ui-timeline-navigator-window-input`, `audio-ui-timeline-playhead`, `audio-ui-timeline-range`, `audio-ui-timeline-range-end`, `audio-ui-timeline-range-end-input`, `audio-ui-timeline-range-input`, `audio-ui-timeline-range-start`, `audio-ui-timeline-range-start-input`, `audio-ui-timeline-ruler`, `audio-ui-timeline-ruler-input`, `audio-ui-timeline-track`, `audio-ui-timeline-track-header`, `audio-ui-timeline-track-resize-handle`, `audio-ui-timeline-track-resize-input`, `audio-ui-timeline-viewport`

### Events

| React and Svelte | Vue | Web |
| --- | --- | --- |
| `onClipChange` | `@clip-change` | `clipchange` |
| `onClipCommitted` | `@clip-committed` | `clipcommit` |
| `onClipDragOffsetChange` | `@clip-drag-offset-change` | none |
| `onClipRemove` | `@clip-remove` | `clipremove` |
| `onClipSelectedChange` | `@clip-selected-change` | `clipselect` |
| `onMarkChange` | `@mark-change` | `markchange` |
| `onMarkCommitted` | `@mark-committed` | `markcommit` |
| `onPositionChange` | `@position-change` | `input` |
| `onPositionCommitted` | `@position-committed` | `change` |
| `onRangeChange` | `@range-change` | `rangechange` |
| `onRangeCommitted` | `@range-committed` | `rangecommit` |
| `onSelectionChange` | `@selection-change` | `selectionchange` |
| `onSelectionCommitted` | `@selection-committed` | `selectioncommit` |
| `onTrackHeightChange` | `@track-height-change` | `trackheightchange` |
| `onTrackHeightCommitted` | `@track-height-committed` | `trackheightcommit` |
| `onZoomChange` | `@zoom-change` | `zoomchange` |

