useLaneDrag
useLaneDrag({ range, onDrop }) lets a person drag items along lanes that share one axis, such as talks on a conference's stages or shifts on a rota. A drag places an item from a queue, moves it along its lane or to another lane, resizes either end, or takes it back to the queue. Pass onCreate and a press on empty lane space drags out a new place. check says whether a place conflicts with other items, and a drop calls onDrop(change).
On this page
import { useLaneDrag } from '@tounsoo/todae';
import { GripVertical } from 'lucide-react';
const lanes = useLaneDrag({
range: { start: 0, end: 480 },
grid: quarterHours,
check: (id, to) => conflicts(talks, id, to),
onDrop: ({ id, to }) => schedule(id, to),
});
<div {...lanes.getBoardProps()}>
{stages.map((stage) => (
<div key={stage.id} {...lanes.getLaneProps(stage.id)}>
{talksOn(stage).map((talk) => (
<div key={talk.id} {...lanes.getItemProps(talk.id, talk.at)}>
<span {...lanes.getHandleProps(talk.id, 'start')} aria-hidden style={{ touchAction: 'none' }} />
<span {...lanes.getHandleProps(talk.id, 'move')} aria-hidden style={{ cursor: 'grab', touchAction: 'none' }}>
<GripVertical />
</span>
{talk.title}
<span {...lanes.getHandleProps(talk.id, 'end')} aria-hidden style={{ touchAction: 'none' }} />
</div>
))}
</div>
))}
</div>
<ul {...lanes.getQueueProps()}>
{unscheduled.map((talk) => (
<li key={talk.id} {...lanes.getItemProps(talk.id, { span: talk.length })}>
<span {...lanes.getHandleProps(talk.id, 'move')} aria-hidden style={{ cursor: 'grab', touchAction: 'none' }}>
<GripVertical />
</span>
{talk.title}
</li>
))}
</ul>
Drag a talk by its grip to another time or stage, or an end of it to change its length. Each talk's menu does the same from the keyboard. The Scheduler recipe builds a multi-day board with conflicts across lanes on the hook.
import {
Button,
Menu,
Text,
useAnnouncer,
useFocusHandoff,
useLaneDrag,
useLaneDragState,
type LanePlace,
type LaneVerdict,
type UseLaneDragResult,
} from '@tounsoo/todae';
import { Ban, EllipsisVertical, GripVertical, TriangleAlert } from 'lucide-react';
import { memo, useId, useRef, useState, type RefObject } from 'react';
import styles from './Schedule.module.css';
// One day from 9:00 to 17:00, counted in minutes from 9:00. Talks snap to quarter hours.
const DAY = { start: 0, end: 480 };
const GRID = Array.from({ length: DAY.end / 15 + 1 }, (_, i) => i * 15);
const CHANGEOVER = 15;
type Stage = { id: string; name: string };
type Talk = { id: string; title: string; speaker: string; length: number; at: LanePlace | null };
const STAGES: Stage[] = [
{ id: 'main', name: 'Main hall' },
{ id: 'a', name: 'Room A' },
{ id: 'b', name: 'Room B' },
];
const TALKS: Talk[] = [
{ id: 'keynote', title: 'Opening keynote', speaker: 'Ana Ruiz', length: 60, at: { lane: 'main', start: 0, end: 60 } },
{ id: 'tokens', title: 'Tokens that travel', speaker: 'Kenji Sato', length: 45, at: { lane: 'a', start: 75, end: 120 } },
{ id: 'forms', title: 'Forms people finish', speaker: 'Mira Patel', length: 30, at: { lane: 'b', start: 90, end: 120 } },
{ id: 'motion', title: 'Motion with purpose', speaker: 'Ana Ruiz', length: 45, at: { lane: 'a', start: 180, end: 225 } },
{ id: 'audit', title: 'Auditing a design system', speaker: 'Leo Brandt', length: 30, at: null },
{ id: 'panel', title: 'Panel: shipping 1.0', speaker: 'Kenji Sato', length: 60, at: null },
{ id: 'dark', title: 'Dark mode, done right', speaker: 'Mira Patel', length: 30, at: null },
];
const clock = (minutes: number) => `${9 + Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}`;
const stageName = (id: string) => STAGES.find((stage) => stage.id === id)!.name;
/** Whether `talk` may go to `to`: a stage holds one talk at a time, a speaker gives one talk at a time, and a stage needs a changeover between talks. */
function verdictFor(talks: readonly Talk[], id: string, to: LanePlace): LaneVerdict | null {
const talk = talks.find((each) => each.id === id)!;
const blocked: Talk[] = [];
const warned: Talk[] = [];
let reason = '';
for (const other of talks) {
const at = other.at;
if (other.id === id || at === null) continue;
const overlaps = at.start < to.end && to.start < at.end;
if (overlaps && at.lane === to.lane) {
blocked.push(other);
reason ||= `Overlaps ${other.title}`;
} else if (overlaps && other.speaker === talk.speaker) {
blocked.push(other);
reason ||= `${talk.speaker} is in ${stageName(at.lane)} then`;
} else if (at.lane === to.lane && at.start < to.end + CHANGEOVER && to.start < at.end + CHANGEOVER) {
warned.push(other);
}
}
if (blocked.length > 0) return { level: 'blocked', reason, with: blocked.map((other) => other.id) };
if (warned.length > 0) return { level: 'warning', reason: `No changeover beside ${warned[0]!.title}`, with: warned.map((other) => other.id) };
return null;
}
/** The earliest place on `lane` that no rule blocks, for the menu's Schedule items. */
function firstFree(talks: readonly Talk[], talk: Talk, lane: string): LanePlace | null {
for (let start = DAY.start; start + talk.length <= DAY.end; start += 15) {
const to = { lane, start, end: start + talk.length };
if (verdictFor(talks, talk.id, to)?.level !== 'blocked') return to;
}
return null;
}
type Move = (id: string, to: LanePlace | null, verdict: LaneVerdict | null) => void;
/** Where a drag would put a talk in this stage, with what the rules say about it. */
const Preview = memo(function Preview({ drag, stage, talks }: { drag: UseLaneDragResult['drag']; stage: string; talks: readonly Talk[] }) {
const change = useLaneDragState(drag, (state) => (state?.to?.lane === stage ? state : null));
if (change?.to == null) return null;
const { to, verdict } = change;
const talk = talks.find((each) => each.id === change.id)!;
return (
<div
className={styles.preview}
data-level={verdict?.level}
style={{ insetInlineStart: `${(to.start / DAY.end) * 100}%`, inlineSize: `${((to.end - to.start) / DAY.end) * 100}%` }}
>
<span className={styles.time}>
{clock(to.start)}–{clock(to.end)}
</span>
{verdict ? (
<span className={styles.reason}>
{verdict.level === 'blocked' ? <Ban size="1em" aria-hidden /> : <TriangleAlert size="1em" aria-hidden />}
{verdict.reason}
</span>
) : (
<span className={styles.reason}>{talk.title}</span>
)}
</div>
);
});
function TalkMenu({ talk, talks, move, trigger }: { talk: Talk; talks: readonly Talk[]; move: Move; trigger?: RefObject<HTMLButtonElement | null> }) {
const at = talk.at;
// The talk's place with its start and end moved, or null where it doesn't fit the day or a rule blocks it.
const shift = (start: number, end: number) => {
if (at === null) return null;
const to = { lane: at.lane, start: at.start + start, end: at.end + end };
const fits = to.start >= DAY.start && to.end <= DAY.end && to.end - to.start >= 15;
return fits && verdictFor(talks, talk.id, to)?.level !== 'blocked' ? to : null;
};
const items = [
{ label: '15 minutes earlier', to: shift(-15, -15) },
{ label: '15 minutes later', to: shift(15, 15) },
{ label: 'Start 15 minutes earlier', to: shift(-15, 0) },
{ label: 'Start 15 minutes later', to: shift(15, 0) },
{ label: 'End 15 minutes earlier', to: shift(0, -15) },
{ label: 'End 15 minutes later', to: shift(0, 15) },
];
return (
<Menu.Root>
<Menu.Trigger ref={trigger} variant="ghost" aria-label={`Move ${talk.title}`} className={styles.menu}>
<Button.Icon>
<EllipsisVertical />
</Button.Icon>
</Menu.Trigger>
<Menu.Content>
{at !== null ? (
<>
{items.map(({ label, to }) => (
<Menu.Item key={label} disabled={to === null} onSelect={() => to && move(talk.id, to, verdictFor(talks, talk.id, to))}>
{label}
</Menu.Item>
))}
<Menu.Separator />
</>
) : null}
{STAGES.filter((stage) => stage.id !== at?.lane).map((stage) => {
const to = at === null ? firstFree(talks, talk, stage.id) : { ...at, lane: stage.id };
const open = to !== null && verdictFor(talks, talk.id, to)?.level !== 'blocked';
return (
<Menu.Item key={stage.id} disabled={!open} onSelect={() => to && move(talk.id, to, verdictFor(talks, talk.id, to))}>
{at === null ? `Schedule in ${stage.name}` : `Move to ${stage.name}`}
</Menu.Item>
);
})}
{at !== null ? (
<>
<Menu.Separator />
<Menu.Item onSelect={() => move(talk.id, null, null)}>Back to unscheduled</Menu.Item>
</>
) : null}
</Menu.Content>
</Menu.Root>
);
}
function Block({
talk,
talks,
lanes,
move,
landing,
landed,
}: {
talk: Talk;
talks: readonly Talk[];
lanes: UseLaneDragResult;
move: Move;
landing: RefObject<HTMLButtonElement | null>;
landed: string | null;
}) {
// A talk moved to another stage, or off the board, leaves its old element while its menu holds
// focus. Focus goes on to the talk's menu button in its new place.
const handoff = useFocusHandoff({ to: landing });
const at = talk.at!;
return (
<div
ref={handoff}
{...lanes.getItemProps(talk.id, at)}
className={styles.block}
style={{ insetInlineStart: `${(at.start / DAY.end) * 100}%`, inlineSize: `${((at.end - at.start) / DAY.end) * 100}%` }}
>
<span {...lanes.getHandleProps(talk.id, 'start')} aria-hidden className={styles.edge} data-edge="start" />
<span {...lanes.getHandleProps(talk.id, 'move')} aria-hidden className={styles.grip}>
<GripVertical size="1em" />
</span>
<span className={styles.body}>
<Text.Root weight="medium" lines={1}>
{talk.title}
</Text.Root>
<Text.Root tone="muted" lines={1}>
{clock(at.start)}–{clock(at.end)} · {talk.speaker}
</Text.Root>
</span>
<TalkMenu talk={talk} talks={talks} move={move} trigger={talk.id === landed ? landing : undefined} />
<span {...lanes.getHandleProps(talk.id, 'end')} aria-hidden className={styles.edge} data-edge="end" />
</div>
);
}
function QueueCard({
talk,
talks,
lanes,
move,
landing,
landed,
}: {
talk: Talk;
talks: readonly Talk[];
lanes: UseLaneDragResult;
move: Move;
landing: RefObject<HTMLButtonElement | null>;
landed: string | null;
}) {
const handoff = useFocusHandoff({ to: landing });
return (
<li ref={handoff} {...lanes.getItemProps(talk.id, { span: talk.length })} className={styles.card}>
<span {...lanes.getHandleProps(talk.id, 'move')} aria-hidden className={styles.grip}>
<GripVertical size="1em" />
</span>
<span className={styles.body}>
<Text.Root weight="medium">{talk.title}</Text.Root>
<Text.Root tone="muted">
{talk.length} min · {talk.speaker}
</Text.Root>
</span>
<TalkMenu talk={talk} talks={talks} move={move} trigger={talk.id === landed ? landing : undefined} />
</li>
);
}
export default function ScheduleExample() {
const [talks, setTalks] = useState(TALKS);
const announce = useAnnouncer();
const queueId = useId();
// The menu button of the talk that last changed place, which takes focus from its old element.
const landing = useRef<HTMLButtonElement | null>(null);
const [landed, setLanded] = useState<string | null>(null);
// A drag and a menu item both move a talk here. A talk keeps the length it was last given.
const move: Move = (id, to, verdict) => {
const talk = talks.find((each) => each.id === id)!;
setLanded(id);
setTalks((list) => list.map((each) => (each.id === id ? { ...each, at: to, length: to === null ? each.length : to.end - to.start } : each)));
const where = to === null ? 'unscheduled' : `${stageName(to.lane)}, ${clock(to.start)} to ${clock(to.end)}`;
announce(`${talk.title} moved to ${where}${verdict ? `. ${verdict.reason}` : ''}`);
};
const lanes = useLaneDrag({
range: DAY,
grid: GRID,
minSpan: 15,
check: (id, to) => verdictFor(talks, id, to),
onDrop: ({ id, to, verdict }) => move(id, to, verdict),
});
const queue = talks.filter((talk) => talk.at === null);
return (
<div className={styles.schedule}>
<div {...lanes.getBoardProps()} className={styles.board}>
<div className={styles.hours} aria-hidden>
<div className={styles.ticks}>
{Array.from({ length: 8 }, (_, hour) => (
<span key={hour}>{clock(hour * 60)}</span>
))}
</div>
</div>
{STAGES.map((stage) => (
<section key={stage.id} className={styles.stage} aria-label={stage.name}>
<Text.Root variant="label" className={styles.name}>
{stage.name}
</Text.Root>
<div {...lanes.getLaneProps(stage.id)} className={styles.lane}>
{talks
.filter((talk) => talk.at?.lane === stage.id)
.map((talk) => (
<Block key={talk.id} talk={talk} talks={talks} lanes={lanes} move={move} landing={landing} landed={landed} />
))}
<Preview drag={lanes.drag} stage={stage.id} talks={talks} />
</div>
</section>
))}
</div>
<section aria-labelledby={queueId} className={styles.queueArea}>
<Text.Root id={queueId} variant="label">
Unscheduled
</Text.Root>
<ul {...lanes.getQueueProps()} className={styles.queue}>
{queue.map((talk) => (
<QueueCard key={talk.id} talk={talk} talks={talks} lanes={lanes} move={move} landing={landing} landed={landed} />
))}
{queue.length === 0 ? <li className={styles.empty}>Every talk is scheduled</li> : null}
</ul>
</section>
</div>
);
}
/* The board scrolls sideways: each stage's lane is at least 120rem wide, at
least 4px a minute at the default font size, so a half-hour talk has room
for its grip, title and menu button. The stage names stay in view as it scrolls. */
.schedule {
display: flex;
flex-direction: column;
gap: var(--todae-space-4);
inline-size: 100%;
}
/* The board is one grid: a column for the stage names and one for the day.
Each row spans both on a subgrid, so it is as wide as the whole day, not only
the visible board. A sticky name can't leave its row, so a row as narrow as
the board would carry its name away once the board scrolled past it. A talk
scrolled into view stops clear of the names. */
.board {
--schedule-name: 7rem;
--schedule-day: 120rem;
display: grid;
grid-template-columns: var(--schedule-name) minmax(var(--schedule-day), 1fr);
row-gap: var(--todae-space-2);
overflow-x: auto;
padding-block-end: var(--todae-space-2);
scroll-padding-inline-start: var(--schedule-name);
}
.hours,
.stage {
display: grid;
grid-column: 1 / -1;
grid-template-columns: subgrid;
}
/* The corner covers the hours' start, so the hours pass under it as the board
scrolls, as the lanes pass under the names. */
.hours::before,
.name {
grid-column: 1;
position: sticky;
inset-inline-start: 0;
z-index: 2;
background: var(--todae-color-bg-canvas);
}
.hours::before {
content: '';
}
.ticks {
grid-column: 2;
display: grid;
grid-template-columns: repeat(8, minmax(0, 1fr));
color: var(--todae-color-fg-muted);
font-size: var(--todae-text-label-font-size);
}
.name {
display: flex;
align-items: center;
padding-inline-end: var(--todae-space-2);
}
/* The lane's box covers the day, 9:00 to 17:00, so it has no padding or
border along the axis. Lines mark each hour. */
.lane {
grid-column: 2;
position: relative;
block-size: 4rem;
border-radius: var(--todae-radius-md);
background:
repeating-linear-gradient(
to right,
var(--todae-color-border-subtle) 0 var(--todae-border-width),
transparent var(--todae-border-width) calc(100% / 8)
),
var(--todae-color-bg-subtle);
}
.lane:dir(rtl) {
background:
repeating-linear-gradient(
to left,
var(--todae-color-border-subtle) 0 var(--todae-border-width),
transparent var(--todae-border-width) calc(100% / 8)
),
var(--todae-color-bg-subtle);
}
.lane[data-drop-target] {
outline: var(--todae-focus-ring-width) dashed var(--todae-color-accent-default);
outline-offset: calc(-1 * var(--todae-focus-ring-width));
}
.block,
.card {
display: flex;
align-items: center;
gap: var(--todae-space-1);
border: var(--todae-border-width) solid var(--todae-color-border-default);
border-radius: var(--todae-radius-sm);
background: var(--todae-color-bg-surface);
font-size: var(--todae-text-font-size);
line-height: var(--todae-text-leading-tight);
}
.block {
position: absolute;
inset-block: var(--todae-space-1);
z-index: 1;
min-inline-size: 0;
padding-inline: var(--todae-space-1);
}
.block[data-dragging],
.card[data-dragging] {
opacity: 0.5;
}
/* A talk the dragged one would conflict with: a dashed outline for a
warning, a thick solid one for a block, so the two differ without color. */
.block[data-conflict='warning'] {
outline: var(--todae-focus-ring-width) dashed var(--todae-color-status-warning-border);
}
.block[data-conflict='blocked'] {
outline: calc(2 * var(--todae-focus-ring-width)) solid var(--todae-color-status-critical-border);
}
.body {
display: flex;
flex: 1;
flex-direction: column;
min-inline-size: 0;
}
/* The grip runs the talk's height, so it is easy to hit. Touch drags from it
alone, so a swipe elsewhere still scrolls the board. */
.grip {
display: flex;
align-items: center;
align-self: stretch;
padding-inline: var(--todae-space-1);
color: var(--todae-color-fg-muted);
cursor: grab;
touch-action: none;
}
/* Each end resizes the talk. The menu moves either end by a quarter hour as
well, so the narrow ends aren't the only way. */
.edge {
position: absolute;
inset-block: 0;
inline-size: var(--todae-space-2);
cursor: col-resize;
touch-action: none;
}
.edge[data-edge='start'] {
inset-inline-start: 0;
}
.edge[data-edge='end'] {
inset-inline-end: 0;
}
.menu {
flex: none;
}
.preview {
position: absolute;
inset-block: var(--todae-space-1);
z-index: 1;
display: flex;
flex-direction: column;
justify-content: center;
overflow: hidden;
padding-inline: var(--todae-space-2);
border: var(--todae-focus-ring-width) dashed var(--todae-color-accent-default);
border-radius: var(--todae-radius-sm);
background: var(--todae-color-accent-soft);
font-size: var(--todae-text-label-font-size);
pointer-events: none;
}
.preview[data-level='warning'] {
border-color: var(--todae-color-status-warning-border);
background: var(--todae-color-status-warning-bg);
color: var(--todae-color-status-warning-fg);
}
.preview[data-level='blocked'] {
border-style: solid;
border-color: var(--todae-color-status-critical-border);
background: var(--todae-color-status-critical-bg);
color: var(--todae-color-status-critical-fg);
}
.time {
font-weight: var(--todae-text-weight-medium);
}
.reason {
display: flex;
align-items: center;
gap: var(--todae-space-1);
white-space: nowrap;
}
.queueArea {
display: flex;
flex-direction: column;
gap: var(--todae-space-2);
}
.queue {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(14rem, 1fr));
gap: var(--todae-space-2);
min-block-size: 4rem;
margin: 0;
padding: var(--todae-space-2);
border-radius: var(--todae-radius-md);
background: var(--todae-color-bg-subtle);
list-style: none;
}
.card {
padding: var(--todae-space-2) var(--todae-space-1);
}
.queue[data-drop-target] {
outline: var(--todae-focus-ring-width) dashed var(--todae-color-accent-default);
outline-offset: calc(-1 * var(--todae-focus-ring-width));
}
.empty {
color: var(--todae-color-fg-muted);
}
/* Forced colors replace backgrounds and borders, so the drop targets and
conflicts take system colors. */
@media (forced-colors: active) {
.lane[data-drop-target],
.queue[data-drop-target] {
outline-color: Highlight;
}
.block[data-conflict] {
outline-color: Mark;
}
.preview {
border-color: Highlight;
}
}
Main hall
Opening keynote
9:00–10:00 · Ana Ruiz
Room A
Tokens that travel
10:15–11:00 · Kenji Sato
Motion with purpose
12:00–12:45 · Ana Ruiz
Room B
Forms people finish
10:30–11:00 · Mira Patel
Unscheduled
Auditing a design system
30 min · Leo Brandt
Panel: shipping 1.0
60 min · Kenji Sato
Dark mode, done right
30 min · Mira Patel
Places
Every lane covers the same range along the axis, in units you choose, such as minutes from the start of the first day. A place is { lane, start, end } in those units, with the lane's key from getLaneProps(lane). The hook maps the pointer to a value from the lane element's own box, so that box covers range exactly: give it no padding or border along the axis. With axis="inline", the default, the range runs in the text direction, so it starts at the right in a right-to-left page; with axis="block", it runs down, as in a day view's columns.
grid lists the points a start or end snaps to, in ascending order, such as every quarter hour. The hook finds the nearest one by binary search, so a long grid costs little per move, and a day you count in your own units, such as one with the nights left out, snaps the same way. Without grid, places don't snap.
getItemProps(id, at) takes a placed item's place, or { span } for an item in the queue, the length it takes when it is placed. The hook reads them from the item's element when a drag starts.
- Move.
getHandleProps(id, 'move')drags the item. A placed item keeps the point it was grabbed at under the pointer, and an item from the queue starts at the pointer. The item keeps its length and stays insiderange, starting at the nearest grid point that fits. An item longer thanrangehas no place, so its drag drops nothing. - Resize.
getHandleProps(id, 'start')andgetHandleProps(id, 'end')move that end along the item's own lane. An end stopsminSpanfrom the other, and never reaches it. - Back to the queue. A placed item dropped on the element with
getQueueProps()leaves the board.
A drop that changes a place calls onDrop(change), where change is { id, kind, from, to, verdict }. kind is assign, move, resize-start, resize-end or unassign. from is the item's place when the drag started, or null for an item from the queue, and to is where it goes, or null for unassign. A resize changes the item's length, so give its { span } the new length if it goes back to the queue. A drop outside the lanes and the queue, or one that leaves the item where it was, calls nothing. A create is not a drop, so onDrop never sees kind: 'create'.
Creating a place
Pass onCreate and a press on empty lane space drags out a new place along that lane's axis. Leave onCreate out and empty space starts nothing, so a board that only moves and resizes stays as it was. The press has to miss every item and its handles. It also misses a button, a link, a control with role="button", or anything you can tab to, which keeps its own press. The span follows the pointer backward as well as forward, and the hook orders it so start is less than end. It stays in the lane where the press went down, and both ends stay inside range.
Dragged forward, the press floors to the grid cell that contains it, the largest grid point at or below the press. Dragged back, that same cell runs up to the next grid point, so the pressed slot stays in the span, and a press that lands on a grid point uses the point after it. The end that follows the pointer snaps to the nearest grid point, and a tie keeps the earlier one. The span is at least minSpan. A press that never moves past the drag threshold is a click. The click places a slot minSpan long starting at that cell, so the slot contains the click, and shifts the slot back into range when it would stick out the end. That click does not reach the lane. minSpan defaults to 0, and then a click does nothing and the lane's own click still fires, because a place has to have length. A drag that snaps to a single point does nothing then too.
While the pointer is down, read the place with useLaneDragState. The value is a LaneCreateDrag. kind is create, id is null because there is no item yet, from is null, verdict is null, and to is the place. check does not run. Draw to yourself. The hook renders nothing. On release, onCreate runs once with that place. A place that cannot fit calls nothing, which is what a click does when range is shorter than minSpan. onDrop is not called.
Escape cancels the drag, clears the place, and does not call onCreate. A cancelled pointer, a pointer that comes back up with no button down, or the window losing focus ends it the same way. Give the lane touch-action: none, or the browser takes a finger to scroll.
This gesture has no keyboard path, and the hook announces nothing, because it does not know what the place means. Give the empty lane no role and no label. A control there would take focus for a gesture the keyboard cannot do. Put a button or a dialog beside the board, such as New event below, and announce the item when you add it.
import { Button, useAnnouncer, useLaneDrag, useLaneDragState, type LanePlace } from '@tounsoo/todae';
import { useRef, useState } from 'react';
import styles from './Create.module.css';
// One morning, 9:00 to 12:00, counted in minutes from 9:00. Places snap to
// quarter hours, and a click takes half an hour.
const DAY = 180;
const GRID = Array.from({ length: DAY / 15 + 1 }, (_, i) => i * 15);
const SLOT = 30;
type CalendarEvent = { id: string; at: LanePlace };
const clock = (minute: number) => {
const total = 9 * 60 + minute;
return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
};
const placeStyle = (at: LanePlace) => ({
insetBlockStart: `${(at.start / DAY) * 100}%`,
blockSize: `${((at.end - at.start) / DAY) * 100}%`,
});
export default function CreateExample() {
const [events, setEvents] = useState<CalendarEvent[]>([]);
const nextId = useRef(1);
const announce = useAnnouncer();
const say = (at: LanePlace, verb: string) => announce(`${verb} ${clock(at.start)} to ${clock(at.end)}.`);
const add = (at: LanePlace) => {
const id = `event-${nextId.current}`;
nextId.current += 1;
setEvents((list) => [...list, { id, at }]);
say(at, 'Added');
};
const lanes = useLaneDrag({
range: { start: 0, end: DAY },
axis: 'block',
grid: GRID,
minSpan: SLOT,
onCreate: add,
onDrop: ({ id, to }) => {
if (to === null) return;
setEvents((list) => list.map((event) => (event.id === id ? { ...event, at: to } : event)));
say(to, 'Moved to');
},
});
const preview = useLaneDragState(lanes.drag, (state) => (state?.to?.lane === 'day' ? state.to : null));
const nextStart = events.reduce((end, event) => Math.max(end, event.at.end), 0);
return (
<div className={styles.root}>
<div className={styles.toolbar}>
<Button.Root
type="button"
variant="secondary"
disabled={nextStart + SLOT > DAY}
onClick={() => add({ lane: 'day', start: nextStart, end: nextStart + SLOT })}
>
New event
</Button.Root>
<p className={styles.note}>Drag empty space to choose a time. New event does it from the keyboard.</p>
</div>
<div className={styles.frame}>
<div className={styles.times} aria-hidden>
{[0, 60, 120].map((minute) => (
<span key={minute} style={{ insetBlockStart: `${(minute / DAY) * 100}%` }}>
{clock(minute)}
</span>
))}
</div>
<div {...lanes.getBoardProps()} className={styles.board}>
<div {...lanes.getLaneProps('day')} className={styles.lane}>
{events.map((event) => (
<div key={event.id} {...lanes.getItemProps(event.id, event.at)} className={styles.event} style={placeStyle(event.at)}>
<span {...lanes.getHandleProps(event.id, 'move')} className={styles.move} aria-hidden />
<span className={styles.label}>
{clock(event.at.start)} to {clock(event.at.end)}
</span>
</div>
))}
{preview ? <div className={styles.ghost} aria-hidden style={placeStyle(preview)} /> : null}
</div>
</div>
</div>
</div>
);
}
.root {
display: flex;
flex-direction: column;
gap: var(--todae-space-3);
}
.toolbar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: var(--todae-space-3);
}
.note {
margin: 0;
color: var(--todae-color-fg-muted);
font-size: var(--todae-text-label-font-size);
}
.frame {
display: flex;
gap: var(--todae-space-2);
}
.times {
position: relative;
flex: none;
inline-size: 3rem;
}
.times span {
position: absolute;
color: var(--todae-color-fg-muted);
font-size: var(--todae-text-label-font-size);
line-height: var(--todae-text-leading-tight);
transform: translateY(-50%);
}
/* The lane's box is the morning, 9:00 to 12:00, so it has no padding or border
along the axis. touch-action is none so a finger draws a place instead of
scrolling the page. */
.board {
flex: 1;
min-inline-size: 0;
}
.lane {
position: relative;
block-size: 24rem;
touch-action: none;
border-radius: var(--todae-radius-md);
background:
repeating-linear-gradient(
to bottom,
var(--todae-color-border-subtle) 0 var(--todae-border-width),
transparent var(--todae-border-width) calc(100% / 3)
),
var(--todae-color-bg-subtle);
}
.event,
.ghost {
position: absolute;
inset-inline: var(--todae-space-1);
border-radius: var(--todae-radius-sm);
}
.event {
z-index: 1;
display: flex;
align-items: center;
border: var(--todae-border-width) solid var(--todae-color-border-default);
background: var(--todae-color-bg-surface);
font-size: var(--todae-text-label-font-size);
}
.ghost {
border: var(--todae-border-width) dashed var(--todae-color-accent-default);
background: var(--todae-color-bg-surface);
}
.move {
position: absolute;
inset: 0;
touch-action: none;
cursor: grab;
}
.label {
padding-inline: var(--todae-space-2);
pointer-events: none;
}
Checking a place
check(id, to) runs each time the place under the pointer changes, not on every pointer move, and once more at the drop, so a rule that changed meanwhile still holds. It returns null or a verdict: { level, reason, with }. A blocked place takes no drop. A warning place does, and onDrop gets the verdict, so you can say why. with lists the ids of the other items the place conflicts with, which is how a rule that crosses lanes shows: in the example, a speaker in Room A at 10:30 blocks their other talk at 10:30 on any stage. The rules are yours, and the hook knows nothing about times, stages or speakers. Taking an item back to the queue isn't checked: to keep an item on the board, such as a talk that's been announced, leave its unassign out of onDrop. A check that throws ends the drag without a drop, and its error still reaches the page.
Showing the drag
The hook renders nothing and sets state on the elements during a drag, so the board doesn't render on every pointer move:
data-draggingon the dragged item and on the board. A create has no item, so the mark goes on the lane instead, along with the board.data-drop-targeton the lane the item would go to, or on the queue forunassign. A create marks the lane it is drawing in.data-conflict, the verdict's level, on that lane and on each item inwith. A create is not checked, so it sets no verdict.
When the drag ends, each element gets back the value it had, so an item can carry its own data-conflict between drags.
Style those, and draw the item's future place with useLaneDragState(lanes.drag, select). It returns select of the drag under way, or of null when there is none, and renders again only when that selection changes. Select the drag while its place is in one lane, as the example's preview does, and that lane renders each time the place in it changes, not on every pointer move, and not while the drag is in other lanes. Pass isEqual as a third argument when select builds a new object each time.
const change = useLaneDragState(lanes.drag, (state) => (state?.to?.lane === stage.id ? state : null));
The owner of useLaneDrag renders as a drag starts and ends. Keep the dragged item, its lane and the board mounted during a drag: a render that replaces one of them ends the drag without a drop. While the pointer is inside the element with getBoardProps() and near its edge, the board scrolls, so make that element the one that scrolls. Outside it, such as over a queue beside it, the board stays still.
When something sticky covers the board's lanes, such as a column of stage names, give the board a scroll-padding on that side that runs up to where the lanes begin, as a length or a percentage. The example sets scroll-padding-inline-start to the names' width. The board's edge then counts from past that strip, so the board scrolls while the pointer is near the strip or over it, and a drop over the strip lands wholly in view, at the first place past it, where the item fits there. Held there, the board scrolls back to the start of the day and the item follows, snapping fully into view as the pointer enters the strip. The strip has to catch the pointer, so leave pointer-events on the sticky part. A pointer over a bare part of the strip drops at the first place in view too. The browser's own scrolling, such as scrollIntoView, keeps clear of the strip too. Any scroll-padding the board has counts this way, so keep it to the part that is covered.
Touch and the pointer
A mouse, a finger and a pen drag the same way, with pointer events. The item drags once the pointer moves a few pixels from the press, so a click or a tap on a handle drags nothing, and the click a drop sends to its handle is dropped. A press on a button or link inside a handle is that control's, and the browser's own drag of an image or link inside a handle is stopped. Every handle needs touch-action: none, or the browser takes a finger to scroll the page and the drag ends. A lane that creates places needs it too. Keep them small, such as a grip, so a swipe on the rest of the board still scrolls it. A drag ends without a drop when its release is lost, as when the pointer moves with no button down or the window loses focus, so a test that sends pointer events by hand gives every move buttons: 1.
Escape cancels a drag and leaves every item where it was, before a Dialog around the board, which stays open until the next Escape.
Accessible composition
Todae handles: Dragging an item from a handle with a mouse, a finger or a pen. Dragging out a new place on empty lane space when you pass onCreate, and cancelling that drag on Escape. Working out the place a drop lands on from the lane's box and the text direction, snapping it, and keeping it inside the range. Asking your check and refusing a blocked drop. Marking the dragged item, the drop target and the items in conflict.
You supply: Another way to place, move, resize and unschedule an item that needs no dragging and works from the keyboard, such as the example's menu or a dialog with a time field. Dragging has no keyboard path. A way to create an item without dragging, such as the New event button or a dialog. The hook announces nothing for a create, because it does not know what the place means. Handles hidden from screen readers with aria-hidden, since that other way is the one they use. The rules in check, and a reason a person can read. A cue for each verdict besides color, such as the example's icons and outline styles. The announcement of a change. For an item that moves to another lane, a place for the focus its old element held.
Watch for: Drag as the only way to place, move or create an item (WCAG 2.2 SC 2.1.1 and SC 2.5.7). An empty lane that is a button or a tab stop. That would take focus for a gesture the keyboard cannot do. A conflict shown by color alone (SC 1.4.1). A handle that is a button or a tab stop. It does nothing from the keyboard. Resize ends narrower than 24 CSS pixels, which pass SC 2.5.8 only because another control does the same. A move handle that covers the whole item on a touch screen, which keeps a swipe over the items from scrolling the board. Touch dragging is tested with pointer events, not on a phone.
When to use
When: Letting a person place items on lanes along a shared axis, such as talks on stages over a conference's days or shifts on a rota, beside a way to move them without dragging.
When not: Reordering a list → useReorder. Moving cards between columns with no axis → useReorderGroup. Picking a time → Field with a time input.
Props
| Name | Type | Description |
|---|---|---|
range Required | { start: number; end: number } | The span every lane's element covers along the axis, in the board's units, such as minutes from the first day's start. |
onDrop Required | (change: LaneDragChange) => void | Called on a drop that changes an item's place, with the change. A create calls onCreate instead. |
axis | 'inline' | 'block' | The direction the range runs in each lane. `inline` follows the text direction, and `block` runs down. Default `inline`. Default: 'inline' |
grid | readonly number[] | The points a start or end snaps to, in ascending order. Without it, places don't snap. |
minSpan | number | The shortest span a resize leaves, and the span a click on empty lane space creates, from the grid cell that contains the press. Default 0, so that click does nothing. Default: 0 |
check | (id: string, to: LanePlace) => LaneVerdict | null | Says whether the item `id` may go to `to`, each time the place under the pointer changes and again at the drop. |
onCreate | (place: LanePlace) => void | Called once when a press on empty lane space ends on a new place. Omit it and empty space starts nothing. A drag sets the span between the press and the pointer. Dragged forward, the press floors to the grid cell that contains it. Dragged back, that cell runs up to the next grid point. The end under the pointer snaps to the nearest grid point. A press that stays inside the drag threshold creates a slot `minSpan` long from that cell, swallows the lane's click, and does nothing when `minSpan` is 0. |
disabled | boolean | Turn dragging off. While `disabled` is true, a drag under way can't be dropped. Default: false |
| Name | Type | Description |
|---|---|---|
drag Required | LaneDragStore | The `drag` that `useLaneDrag` returns. |
select Required | (state: LaneDragChange | LaneCreateDrag | null) => T | Picks what this component shows from the drag under way, or from null when there is none. |
isEqual | (a: T, b: T) => boolean | Says when two selections are the same, so a selection built anew on each move renders only when it changes. Default `Object.is`. Default: Object.is |