Custom Drag Setup
For most use cases, ClipInteractionProvider handles all clip drag/move/trim/snap/collision setup automatically. This guide covers the manual approach — configuring DragDropProvider directly when you need full control over sensors, modifiers, or drag behavior.
When to Use Manual Setup
Use this approach when you need to:
- Add custom modifiers beyond snap-to-grid and collision detection
- Customize drag start behavior (e.g., custom track selection logic)
- Use custom sensors or activation constraints
- Handle drag events with side effects not covered by the provider
For standard clip interactions, use ClipInteractionProvider instead — it eliminates ~120 lines of boilerplate.
Required Imports
import { useMemo } from 'react';
import { DragDropProvider } from '@dnd-kit/react';
import { RestrictToHorizontalAxis } from '@dnd-kit/abstract/modifiers';
import {
useAudioSettings, // sampleRate: what a pixel is in seconds
useZoom,
useTimeline, // The loaded tracks, to select the dragged clip's track
useArrangement, // The arrangement's tracks, for the collision modifier
useEditorControls,
useClipDragHandlers,
useDragSensors,
ClipCollisionModifier,
SnapToGridModifier, // Only if using snap-to-grid
ClipInteractionOptions, // Tells the clips they can be dragged and trimmed
WaveformEditor,
} from '@waveform-playlist/browser';
Basic Setup (No Snap)
The minimal setup for interactive clips with collision detection:
function PlaylistWithDrag() {
const { tracks } = useTimeline();
const arrangement = useArrangement();
const { samplesPerPixel } = useZoom();
const { sampleRate } = useAudioSettings();
const { setSelectedTrackId } = useEditorControls();
// Configure drag sensors (pointer activation with 1px distance threshold)
const sensors = useDragSensors();
// Get drag event handlers for clip move and boundary trim
const {
onDragStart: handleDragStart,
onDragMove,
onDragEnd,
} = useClipDragHandlers();
// Auto-select track when dragging starts
const onDragStart = (event) => {
// The id, not `trackIndex`: the row is the one the clip was drawn in.
const trackId = event.operation?.source?.data?.trackId;
if (tracks.some((track) => track.id === trackId)) {
setSelectedTrackId(trackId);
}
handleDragStart(event);
};
// Memoized: an array built in the JSX is a new `modifiers` prop on every render.
const modifiers = useMemo(
() => [
RestrictToHorizontalAxis,
// A function of the arrangement's tracks: clips still loading are
// neighbours too, as for the moveClip of the drop.
ClipCollisionModifier.configure({
tracks: () => arrangement.getTracks(),
samplesPerPixel,
sampleRate,
}),
],
[arrangement, samplesPerPixel, sampleRate]
);
return (
<DragDropProvider
sensors={sensors}
onDragStart={onDragStart}
onDragMove={onDragMove}
onDragEnd={onDragEnd}
modifiers={modifiers}
>
<ClipInteractionOptions enabled>
<WaveformEditor />
</ClipInteractionOptions>
</DragDropProvider>
);
}
:::note Key Components
useDragSensors()— Configures pointer activation. Pass{ touchOptimized: true }for mobile (250ms touch delay).useClipDragHandlers()— ReturnsonDragStart,onDragMove,onDragEndfor clip movement and boundary trimming, on the provider's arrangement (it reads it from context, so the component must be underWebAudioProvider; it throws elsewhere). A move is onearrangement.moveClip()on drop; a trim is previewed in the view while it is dragged and is onearrangement.trimClip()on release, so the tracks change once per drag and not per pointer move. Each is one undo step, and one made while no engine is attached is kept. From a clip drag's start to its end (or the unmount of the component that holds the handlers),useEditorControls().undo()/redo()and the undo keys do nothing, so a drag in aDragDropProviderof your own is covered too. A track-reorder drag is covered whenClipInteractionProviderhandles it; anonDragEndof your own for track reordering is not.ClipCollisionModifier— Prevents clips from overlapping on the same track. Give it the arrangement's tracks,tracks: () => arrangement.getTracks(): a move stops at a clip still loading asarrangement.moveClip()does on the drop (where its length is known from adurationor peaks, else at its start).useTimeline().tracksholds loaded clips only, so a move drawn from them can pass over a clip still loading and then land short of where it was drawn. A function also keeps the configured modifier stable, so you can memoise themodifiersarray without rebuilding it each time tracks change.- Feedback plugin config is per-entity — the clip components declare their own
@dnd-kitFeedback settings (no drop animation on clip moves, no Feedback on trim handles) viauseDraggable({ plugins }), so a plainDragDropProviderneeds nopluginsprop for them. RestrictToHorizontalAxis— Constrains drag to horizontal movement only.
:::
Adding Snap-to-Grid
Beats & Bars Snap
For musical grid snapping, add SnapToGridModifier in beats mode and a snapSamplePosition callback for boundary trim snapping:
import {
samplesToTicks,
ticksToSamples,
snapToGrid,
ticksPerBeat,
ticksPerBar,
} from '@waveform-playlist/core';
import { useBeatsAndBars } from '@waveform-playlist/ui-components';
function PlaylistWithBeatsSnap() {
const arrangement = useArrangement();
const { sampleRate } = useAudioSettings();
const { samplesPerPixel } = useZoom();
const beatsAndBars = useBeatsAndBars();
const { bpm, timeSignature, snapTo } = beatsAndBars;
// Snap function for boundary trims (snaps absolute sample position to grid)
const snapSamplePosition = useMemo(() => {
if (snapTo === 'off') return undefined;
const gridTicks =
snapTo === 'bar' ? ticksPerBar(timeSignature) : ticksPerBeat(timeSignature);
return (samplePos: number) => {
const ticks = samplesToTicks(samplePos, bpm, sampleRate);
const snapped = snapToGrid(ticks, gridTicks);
return ticksToSamples(snapped, bpm, sampleRate);
};
}, [snapTo, bpm, timeSignature, sampleRate]);
const sensors = useDragSensors();
const { onDragStart, onDragMove, onDragEnd } = useClipDragHandlers({
snapSamplePosition, // Snaps boundary trims to grid
});
// Build modifiers array — snap modifier only when snap is enabled
const modifiers = useMemo(() => {
const mods = [RestrictToHorizontalAxis];
if (snapTo !== 'off') {
mods.push(
SnapToGridModifier.configure({
mode: 'beats',
snapTo,
bpm,
timeSignature,
samplesPerPixel,
sampleRate,
})
);
}
mods.push(
ClipCollisionModifier.configure({
tracks: () => arrangement.getTracks(),
samplesPerPixel,
sampleRate,
})
);
return mods;
}, [snapTo, bpm, timeSignature, arrangement, samplesPerPixel, sampleRate]);
return (
<DragDropProvider
sensors={sensors}
onDragStart={onDragStart}
onDragMove={onDragMove}
onDragEnd={onDragEnd}
modifiers={modifiers}
>
<ClipInteractionOptions enabled>
<WaveformEditor />
</ClipInteractionOptions>
</DragDropProvider>
);
}
Timescale Snap
For time-based grid snapping (derived from the current zoom level):
import { getScaleInfo } from '@waveform-playlist/ui-components';
// In your component:
const gridSamples = Math.round(
(getScaleInfo(samplesPerPixel).smallStep / 1000) * sampleRate
);
// Snap modifier for clip moves
SnapToGridModifier.configure({
mode: 'timescale',
gridSamples,
samplesPerPixel,
})
// Snap function for boundary trims
const snapSamplePosition = (samplePos: number) =>
Math.round(samplePos / gridSamples) * gridSamples;
Modifier Order
The order of modifiers matters:
[RestrictToHorizontalAxis, SnapToGridModifier?, ClipCollisionModifier]
- RestrictToHorizontalAxis — Applied first (efficient, constrains axis)
- SnapToGridModifier — Applied second (snaps to grid, if enabled)
- ClipCollisionModifier — Applied last (validates snapped position against other clips)
Two Types of Snapping
There are two separate snap mechanisms:
| Mechanism | What it snaps | Where configured |
|---|---|---|
SnapToGridModifier | Clip moves (whole clip dragging) | modifiers array on DragDropProvider |
snapSamplePosition | Boundary trims (adjusting clip edges) | useClipDragHandlers() option |
Both snap the absolute position to the grid, not the drag delta. This means an off-grid clip will snap to the nearest grid line when moved.
Annotation Edges Need No Wiring Here
A clip drag setup has no annotation branch. <WaveformAnnotationBoxes> has its own DragDropProvider around the row of boxes and calls useAnnotationDragHandlers itself, so the drag of an annotation edge never reaches a DragDropProvider of yours above the view, and your clip handlers do not have to tell the two kinds of drag apart.
<DragDropProvider
sensors={sensors}
onDragStart={onDragStart}
onDragMove={onDragMove}
onDragEnd={onDragEnd}
modifiers={modifiers} // the memoized list of the Basic Setup
>
<ClipInteractionOptions enabled>
{/* The clip handlers above; the annotation boxes inside the view handle their own edges. */}
<WaveformEditor />
</ClipInteractionOptions>
</DragDropProvider>
Whether an edge can be dragged is the provider's editable option, and linkEndpoints decides whether it takes its neighbour along (see the Annotations guide). The one setting the annotation drag takes from above is touchOptimized of ClipInteractionOptions (or ClipInteractionProvider): with it, a touch on an edge handle must be held 250 ms before the drag starts.
useAnnotationDragHandlers stays exported for a row of boxes you draw yourself; that row needs a DragDropProvider of its own.
Touch-Optimized Sensors
For mobile, configure touch-optimized sensors with a 250ms delay:
const sensors = useDragSensors({ touchOptimized: true });
This uses delay-based activation for touch events (distinguishes drag from scroll) while keeping distance-based activation for mouse/pen.
The sensors do not change the size of the trim handles. Widen them with touchOptimized on ClipInteractionOptions:
<ClipInteractionOptions enabled touchOptimized>
<WaveformEditor />
</ClipInteractionOptions>
<ClipInteractionProvider touchOptimized> does both by itself.
The Custom Drag Setup example runs this setup, with a checkbox for each of the two options.
ClipInteractionOptions
Clips read two options from context: whether they can be dragged and trimmed, and whether their trim handles are widened for touch (24px instead of 8px). Waveform takes neither as a prop. ClipInteractionProvider sets both for you; with your own DragDropProvider, ClipInteractionOptions is how you set them:
| Prop | Type | Default | Description |
|---|---|---|---|
enabled | boolean | inherited, false at the top | Clips below can be dragged and trimmed. Without it they show no trim handles and their headers do not drag |
touchOptimized | boolean | inherited, false at the top | Clips below get 24px trim handles |
A prop you leave out keeps the value from the nearest ClipInteractionOptions or ClipInteractionProvider above, so it can also be nested to change one option for part of the tree. ClipInteractionProvider follows the same rule for its own touchOptimized: left out, it takes the value from above for its sensors and for the handles.
<ClipInteractionProvider touchOptimized>
{/* Touch-delay sensors, but the normal 8px handles */}
<ClipInteractionOptions touchOptimized={false}>
<WaveformEditor />
</ClipInteractionOptions>
</ClipInteractionProvider>
Hook Reference
useDragSensors(options?)
| Option | Type | Default | Description |
|---|---|---|---|
touchOptimized | boolean | false | Enable 250ms touch delay |
touchDelay | number | 250 | Delay in ms for touch activation |
touchTolerance | number | 5 | Pixel tolerance during touch delay |
useClipDragHandlers(options?)
| Option | Type | Required | Description |
|---|---|---|---|
snapSamplePosition | (sample: number) => number | No | Snap function for boundary trims |
The tracks, the engine and the zoom level are not options: the hook works on the arrangement of the nearest WebAudioProvider (useArrangement()) at its zoom level (useZoom()) and throws outside one and under MediaElementProvider. It commits the clip and track picked up at drag start, by their ids (so a reorder or a clip arriving earlier in the row during the drag does not move another clip); a move whose clip is no longer in that track at the drop is dropped with a console warning. The draggable ids are clip/<trackId>/<clipId> for the move and clip-boundary-left/<trackId>/<clipId>, clip-boundary-right/<trackId>/<clipId> for the trim handles; the drag data keeps clipId, trackIndex and clipIndex, and carries trackId, the id of the clip's track, for every clip <WaveformTracks> draws. The hook, ClipCollisionModifier and the track selection of ClipInteractionProvider find the track by trackId, and by trackIndex only for data that has none. Each move of a trim handle is constrained by arrangement.constrainTrimDelta and drawn as a preview of the dragged clip only; the release makes one arrangement.trimClip(). A move or a trim released while no engine is attached (before the first build, during a rebuild) is kept, and the next engine plays it. See useClipDragHandlers and useClipSplitting read the arrangement from the provider.
ClipCollisionModifier.configure(options)
| Option | Type | Description |
|---|---|---|
tracks | readonly ArrangementTrack[] | (() => readonly ArrangementTrack[]) | The tracks to collide with, or a function returning them (keeps the configured modifier stable while tracks change). Pass the arrangement's, () => arrangement.getTracks(): clips still loading are neighbours as they are for moveClip. useTimeline().tracks (loaded clips only) is accepted too |
samplesPerPixel | number | Current zoom level |
sampleRate | number | The provider's sample rate (useAudioSettings().sampleRate). Required: clip times are seconds, and a pixel is samplesPerPixel / sampleRate seconds. Without it the modifier leaves the drag unconstrained and warns once |
SnapToGridModifier.configure(options)
Beats mode:
| Option | Type | Description |
|---|---|---|
mode | 'beats' | Snap in PPQN tick space |
snapTo | 'bar' | 'beat' | Grid resolution |
bpm | number | Beats per minute |
timeSignature | [number, number] | Time signature |
samplesPerPixel | number | Current zoom level |
sampleRate | number | Audio sample rate |
Timescale mode:
| Option | Type | Description |
|---|---|---|
mode | 'timescale' | Snap by sample count |
gridSamples | number | Samples per grid line |
samplesPerPixel | number | Current zoom level |
See Also
- Beats & Bars — Musical timescale with
ClipInteractionProvider - Annotations guide — the annotation boxes and the drag of their edges
- LLM API Reference — Complete TypeScript interfaces