Scheduler
A recipe, not a package namespace. A scheduler places items on parallel lanes, such as rooms, people or machines, along one time axis, where an item can't go where one of the things it uses is busy, even on another lane. Items wait in a queue until they are placed. Dragging comes from useLaneDrag, and each item's Menu and a Dialog make the same moves from the keyboard. The time helpers and the conflict rule live in the recipe, so change them to fit your product. There is no Scheduler.* export.
On this page
The example is a three-day conference. Each stage is a lane, and a talk can't go where its stage or one of its speakers is busy. Drag a talk by its grip to another time, stage or day, or an end of it to change its length. Select a talk to open its menu and move it without dragging, or pick a speaker to see their talks on every stage.
import {
Alert,
Badge,
Button,
Dialog,
ErrorMessage,
Field,
Form,
Label,
Menu,
ScrollArea,
Text,
ToggleGroup,
formatTime,
useAnnouncer,
useFocusHandoff,
useLaneDrag,
useLaneDragState,
type CategoryTone,
type FormErrors,
type LanePlace,
type LaneVerdict,
type UseLaneDragResult,
} from '@tounsoo/todae';
import { Ban, EllipsisVertical, GripVertical, TriangleAlert, Undo2, Video } from 'lucide-react';
import { memo, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode, type RefObject, type SubmitEvent } from 'react';
import styles from './Scheduler.module.css';
// ─── The time axis ─────────────────────────────────────────────────────────
// The board counts minutes of open hours only, so three days with the nights
// left out are one number line: day 1 is 0 to 540, day 2 is 540 to 1080.
// useLaneDrag sees those numbers; these helpers turn them into times and back.
/** One day's open hours on the axis, from `start` to `end`, opening at `opens`. */
export type Segment = { day: Temporal.PlainDate; start: number; end: number; opens: Temporal.ZonedDateTime };
export type Timeline = { segments: readonly Segment[]; range: { start: number; end: number } };
/**
* The axis for `days`, each open from `opens` to `closes` in `timeZone`. Units are elapsed minutes,
* so a day that changes its clock is as long as it really is. A wall time a clock change skips
* or repeats becomes the later or the earlier one, as Temporal's `compatible` does.
*/
export function timeline({
days,
opens,
closes,
timeZone,
}: {
days: readonly Temporal.PlainDate[];
opens: Temporal.PlainTime;
closes: Temporal.PlainTime;
timeZone: string;
}): Timeline {
let start = 0;
const segments = days.map((day) => {
const from = day.toZonedDateTime({ timeZone, plainTime: opens });
const to = day.toZonedDateTime({ timeZone, plainTime: closes });
const segment = { day, start, end: start + (to.epochMilliseconds - from.epochMilliseconds) / 60_000, opens: from };
start = segment.end;
return segment;
});
return { segments, range: { start: 0, end: start } };
}
/**
* The segment a point is in. The end of one day and the start of the next are the same point, so
* `edge` says which side it belongs to: a start is in the later day, an end in the earlier one.
*/
export function segmentAt(axis: Timeline, units: number, edge: 'start' | 'end' = 'start'): Segment | null {
return axis.segments.find((segment) => (edge === 'start' ? units >= segment.start && units < segment.end : units > segment.start && units <= segment.end)) ?? null;
}
/** Where `at` sits on the axis, or null outside open hours. */
export function toUnits(axis: Timeline, at: Temporal.ZonedDateTime, edge: 'start' | 'end' = 'start'): number | null {
for (const segment of axis.segments) {
const minutes = (at.epochMilliseconds - segment.opens.epochMilliseconds) / 60_000;
const length = segment.end - segment.start;
if (edge === 'start' ? minutes >= 0 && minutes < length : minutes > 0 && minutes <= length) return segment.start + minutes;
}
return null;
}
/** The time at a point on the axis, or null outside it. */
export function fromUnits(axis: Timeline, units: number, edge: 'start' | 'end' = 'start'): Temporal.ZonedDateTime | null {
const segment = segmentAt(axis, units, edge);
return segment ? segment.opens.add({ minutes: units - segment.start }) : null;
}
/** Every `step` minutes from each day's opening, with each closing, for `useLaneDrag`'s `grid`. */
export function snapGrid(axis: Timeline, step: number): number[] {
const points = new Set<number>();
for (const segment of axis.segments) {
for (let at = segment.start; at < segment.end; at += step) points.add(at);
points.add(segment.end);
}
return [...points].sort((a, b) => a - b);
}
// ─── The conflict rule ─────────────────────────────────────────────────────
// Each booking lists the things it uses, such as its stage and each speaker.
// Two bookings that share one and overlap conflict, on whatever lanes they sit.
export type Booking = { id: string; start: number; end: number; keys: readonly string[] };
/** A window nothing may use: `keys` it closes, or every key. */
export type ClosedWindow = { start: number; end: number; keys: readonly string[] | 'all'; reason: string };
/**
* What stands in `item`'s way: the closed windows it overlaps, the bookings that share a key with
* it and overlap it, and those that share a key and sit less than `buffer` away.
*/
export function findConflicts(item: Booking, others: readonly Booking[], { closed = [], buffer = 0 }: { closed?: readonly ClosedWindow[]; buffer?: number } = {}) {
const shut = closed.filter((window) => window.start < item.end && item.start < window.end && (window.keys === 'all' || window.keys.some((key) => item.keys.includes(key))));
const overlaps: { id: string; key: string }[] = [];
const near: { id: string; key: string }[] = [];
for (const other of others) {
const key = other.id === item.id ? undefined : other.keys.find((each) => item.keys.includes(each));
if (key === undefined) continue;
if (other.start < item.end && item.start < other.end) overlaps.push({ id: other.id, key });
else if (other.start < item.end + buffer && item.start < other.end + buffer) near.push({ id: other.id, key });
}
return { shut, overlaps, near };
}
// ─── The event ─────────────────────────────────────────────────────────────
// Built when the module loads, so Temporal or its polyfill has to be loaded first.
const ZONE = 'America/Los_Angeles';
const DAYS = ['2027-06-02', '2027-06-03', '2027-06-04'].map((day) => Temporal.PlainDate.from(day));
const OPENS = Temporal.PlainTime.from('09:00');
const CLOSES = Temporal.PlainTime.from('18:00');
const AXIS = timeline({ days: DAYS, opens: OPENS, closes: CLOSES, timeZone: ZONE });
/** The longest talk, a whole day, so a talk an end drag made long still fits the dialog. */
const LONGEST = 540;
/** Minutes a stage needs between talks. */
const CHANGEOVER = 10;
const SHORTEST = 15;
type Stage = { id: string; name: string; seats: number; recorded: boolean; hours?: [string, string] };
type Track = 'Design' | 'Engineering' | 'Research';
type Place = { stage: string; starts: Temporal.ZonedDateTime; ends: Temporal.ZonedDateTime };
export type Talk = {
id: string;
title: string;
speakers: readonly string[];
track: Track;
format: 'Talk' | 'Panel' | 'Workshop';
length: number;
audience: number;
recorded: boolean;
at: Place | null;
};
const STAGES: Stage[] = [
{ id: 'main', name: 'Main stage', seats: 800, recorded: true },
{ id: 'hall', name: 'Hall B', seats: 300, recorded: true },
{ id: 'workshop', name: 'Workshop room', seats: 40, recorded: false, hours: ['10:00', '17:00'] },
];
const TRACKS: Record<Track, CategoryTone> = { Design: 'category-1', Engineering: 'category-4', Research: 'category-6' };
const zoned = (day: number, time: string) => DAYS[day]!.toZonedDateTime({ timeZone: ZONE, plainTime: Temporal.PlainTime.from(time) });
const place = (stage: string, day: number, time: string, minutes: number): Place => {
const starts = zoned(day, time);
return { stage, starts, ends: starts.add({ minutes }) };
};
/** Breaks and keynotes on every stage, drawn as bands, and each stage's and speaker's closed hours. */
const BANDS = [
{ day: 0, from: '09:00', to: '10:00', label: 'Opening keynote' },
...DAYS.map((_, day) => ({ day, from: '12:30', to: '13:30', label: 'Lunch' })),
{ day: 2, from: '17:00', to: '18:00', label: 'Closing keynote' },
];
/** A window on `day` from `from` to `to` on the axis. */
const span = (day: number, from: string, to: string) => ({ start: toUnits(AXIS, zoned(day, from), 'start')!, end: toUnits(AXIS, zoned(day, to), 'end')! });
const CLOSED: ClosedWindow[] = [
...BANDS.map(({ day, from, to, label }) => ({ ...span(day, from, to), keys: 'all' as const, reason: `Overlaps ${label}` })),
...STAGES.flatMap((stage) =>
stage.hours
? DAYS.flatMap((_, day) => [
{ ...span(day, '09:00', stage.hours![0]), keys: [`stage:${stage.id}`], reason: `${stage.name} isn't open yet` },
{ ...span(day, stage.hours![1], '18:00'), keys: [`stage:${stage.id}`], reason: `${stage.name} has closed` },
])
: [],
),
{ ...span(0, '09:00', '18:00'), keys: ['speaker:Leo Brandt'], reason: 'Leo Brandt arrives on day 2' },
];
const TALKS: Talk[] = [
{ id: 'tokens', title: 'Tokens that travel', speakers: ['Kenji Sato'], track: 'Engineering', format: 'Talk', length: 45, audience: 250, recorded: true, at: place('main', 0, '10:15', 45) },
{ id: 'forms', title: 'Forms people finish', speakers: ['Mira Patel'], track: 'Design', format: 'Talk', length: 30, audience: 180, recorded: true, at: place('hall', 0, '10:15', 30) },
{ id: 'theming', title: 'Hands-on theming', speakers: ['Ana Ruiz'], track: 'Engineering', format: 'Workshop', length: 90, audience: 35, recorded: false, at: place('workshop', 0, '10:30', 90) },
{ id: 'ops', title: 'Research ops at scale', speakers: ['Priya Nair'], track: 'Research', format: 'Talk', length: 30, audience: 350, recorded: true, at: place('hall', 0, '11:00', 30) },
{ id: 'motion', title: 'Motion with purpose', speakers: ['Ana Ruiz'], track: 'Design', format: 'Talk', length: 40, audience: 400, recorded: true, at: place('main', 0, '14:00', 40) },
{ id: 'audit', title: 'Auditing a design system', speakers: ['Leo Brandt'], track: 'Research', format: 'Talk', length: 45, audience: 300, recorded: true, at: place('main', 1, '10:00', 45) },
{ id: 'charts', title: 'Accessible charts', speakers: ['Sam Okafor'], track: 'Design', format: 'Talk', length: 30, audience: 220, recorded: true, at: place('hall', 1, '10:00', 30) },
{ id: 'panel', title: 'Panel: shipping 1.0', speakers: ['Kenji Sato', 'Mira Patel', 'Leo Brandt'], track: 'Engineering', format: 'Panel', length: 60, audience: 600, recorded: true, at: place('main', 1, '15:00', 60) },
{ id: 'copy', title: 'Writing UI copy', speakers: ['Priya Nair'], track: 'Design', format: 'Talk', length: 30, audience: 260, recorded: true, at: place('main', 2, '10:00', 30) },
{ id: 'browsers', title: 'Testing in real browsers', speakers: ['Sam Okafor'], track: 'Engineering', format: 'Talk', length: 45, audience: 200, recorded: true, at: place('hall', 2, '11:00', 45) },
{ id: 'dark', title: 'Dark mode, done right', speakers: ['Mira Patel'], track: 'Design', format: 'Talk', length: 30, audience: 200, recorded: true, at: null },
{ id: 'a11y-forms', title: 'Hands-on accessible forms', speakers: ['Sam Okafor'], track: 'Design', format: 'Workshop', length: 120, audience: 30, recorded: false, at: null },
{ id: 'lightning', title: 'Lightning talks', speakers: ['Ana Ruiz', 'Priya Nair', 'Leo Brandt'], track: 'Research', format: 'Panel', length: 45, audience: 400, recorded: true, at: null },
{ id: 'migrate', title: 'Migrating to 1.0', speakers: ['Kenji Sato'], track: 'Engineering', format: 'Talk', length: 30, audience: 250, recorded: true, at: null },
];
const SPEAKERS = [...new Set(TALKS.flatMap((talk) => talk.speakers))].sort();
const stageOf = (id: string) => STAGES.find((stage) => stage.id === id)!;
const keysOf = (talk: Talk, stage: string) => [`stage:${stage}`, ...talk.speakers.map((name) => `speaker:${name}`)];
/** A talk's place on the axis, which `useLaneDrag` and the rules read. */
function laneOf(at: Place): LanePlace {
return { lane: at.stage, start: toUnits(AXIS, at.starts, 'start')!, end: toUnits(AXIS, at.ends, 'end')! };
}
/** Whether `id` may go to `to`. Blocked: a closed window, a stage or speaker already busy, past closing, or an unrecorded stage. A warning: a full room, a tight changeover, or the same track at once. */
export function verdictFor(talks: readonly Talk[], id: string, to: LanePlace): LaneVerdict | null {
const talk = talks.find((each) => each.id === id)!;
const stage = stageOf(to.lane);
const day = segmentAt(AXIS, to.start, 'start');
if (!day || to.end > day.end) return { level: 'blocked', reason: 'Runs past closing' };
const placed = talks.flatMap((other) => (other.at && other.id !== id ? [{ talk: other, at: laneOf(other.at) }] : []));
const found = findConflicts(
{ id, start: to.start, end: to.end, keys: keysOf(talk, to.lane) },
placed.map(({ talk: other, at }) => ({ id: other.id, start: at.start, end: at.end, keys: keysOf(other, at.lane) })),
{ closed: CLOSED, buffer: CHANGEOVER },
);
const title = (other: string) => talks.find((each) => each.id === other)!.title;
const overlap = found.overlaps[0];
const reason = found.shut[0]?.reason
?? (overlap && (overlap.key.startsWith('stage:') ? `Overlaps ${title(overlap.id)}` : `${overlap.key.slice('speaker:'.length)} is in ${title(overlap.id)} then`))
?? (talk.recorded && !stage.recorded ? `${stage.name} isn't recorded` : null);
if (reason) return { level: 'blocked', reason, with: found.overlaps.map((each) => each.id) };
const warnings: string[] = [];
// The axis leaves the nights out, so a talk that ends one day sits next to one that opens the next.
// A changeover counts only within a day.
const startOf = (other: string) => placed.find(({ talk: each }) => each.id === other)!.at.start;
const near = found.near.filter((each) => each.key === `stage:${to.lane}` && segmentAt(AXIS, startOf(each.id), 'start')?.day.equals(day.day));
const sameTrack = placed.filter(({ talk: other, at }) => other.track === talk.track && at.lane !== to.lane && at.start < to.end && to.start < at.end);
if (talk.audience > stage.seats) warnings.push(`Expects ${talk.audience}, ${stage.name} seats ${stage.seats}`);
if (near[0]) warnings.push(`Under ${CHANGEOVER} minutes from ${title(near[0].id)}`);
if (sameTrack[0]) warnings.push(`Same track as ${sameTrack[0].talk.title}`);
if (warnings.length === 0) return null;
return { level: 'warning', reason: warnings.join('. '), with: [...near.map((each) => each.id), ...sameTrack.map(({ talk: other }) => other.id)] };
}
/** The earliest place on `stage` with no warning, or else the earliest no rule blocks, every quarter hour from day 1. */
function firstFree(talks: readonly Talk[], talk: Talk, stage: string): LanePlace | null {
let allowed: LanePlace | null = null;
for (let start = AXIS.range.start; start + talk.length <= AXIS.range.end; start += 15) {
const to = { lane: stage, start, end: start + talk.length };
const verdict = verdictFor(talks, talk.id, to);
if (verdict === null) return to;
if (verdict.level !== 'blocked') allowed ??= to;
}
return allowed;
}
// ─── Words ─────────────────────────────────────────────────────────────────
const dayLabel = (day: Temporal.PlainDate, locale: string) =>
new Intl.DateTimeFormat(locale, { weekday: 'short', month: 'short', day: 'numeric', timeZone: 'UTC' }).format(Date.UTC(day.year, day.month - 1, day.day));
const clock = (at: Temporal.ZonedDateTime, locale: string) => formatTime(at.toPlainTime(), { locale });
const during = (at: Place, locale: string) => `${dayLabel(at.starts.toPlainDate(), locale)}, ${clock(at.starts, locale)} to ${clock(at.ends, locale)}`;
// ─── The board ─────────────────────────────────────────────────────────────
type Move = (id: string, to: LanePlace | null, verdict: LaneVerdict | null) => void;
type Shared = {
talks: readonly Talk[];
lanes: UseLaneDragResult;
move: Move;
edit: (id: string) => void;
landing: RefObject<HTMLButtonElement | null>;
landed: string | null;
locale: string;
range: Timeline['range'];
};
/** Where a drag would put a talk in this stage, with what the rules say about it. */
const Preview = memo(function Preview({ drag, stage, locale, range }: { drag: UseLaneDragResult['drag']; stage: string; locale: string; range: Timeline['range'] }) {
const change = useLaneDragState(drag, (state) => (state?.to?.lane === stage ? state : null));
if (change?.to == null) return null;
const { to, verdict } = change;
const starts = fromUnits(AXIS, to.start, 'start');
// A place that runs past closing ends on the next day's axis, so it shows its start alone.
const ends = segmentAt(AXIS, to.start, 'start') === segmentAt(AXIS, to.end, 'end') ? fromUnits(AXIS, to.end, 'end') : null;
return (
<div className={styles.preview} data-level={verdict?.level} style={placeStyle(to.start, to.end, range)}>
<span className={styles.time}>{starts ? (ends ? `${clock(starts, locale)}–${clock(ends, locale)}` : clock(starts, locale)) : null}</span>
{verdict ? (
<span className={styles.reason}>
{verdict.level === 'blocked' ? <Ban size="1em" aria-hidden /> : <TriangleAlert size="1em" aria-hidden />}
{verdict.reason}
</span>
) : null}
</div>
);
});
/** A talk's menu. A placed talk passes what it shows as `children`, so the talk is its button. */
function TalkMenu({ talk, talks, move, edit, trigger, name, children }: Pick<Shared, 'talks' | 'move' | 'edit'> & { talk: Talk; trigger?: RefObject<HTMLButtonElement | null>; name: string; children?: ReactNode }) {
return (
<Menu.Root>
<Menu.Trigger ref={trigger} variant="ghost" aria-label={name} className={styles.menu}>
{children ?? (
<Button.Icon>
<EllipsisVertical />
</Button.Icon>
)}
</Menu.Trigger>
<Menu.Content>
<TalkMoves talk={talk} talks={talks} move={move} edit={edit} />
</Menu.Content>
</Menu.Root>
);
}
/** A talk's moves, each asked of the rules. Menu mounts its items on the first open, so a menu nobody opened checks nothing. */
function TalkMoves({ talk, talks, move, edit }: Pick<Shared, 'talks' | 'move' | 'edit'> & { talk: Talk }) {
const at = talk.at ? laneOf(talk.at) : null;
const open = (to: LanePlace | null) => (to !== null && verdictFor(talks, talk.id, to)?.level !== 'blocked' ? to : null);
const shift = (by: number) => (at ? open({ ...at, start: at.start + by, end: at.end + by }) : null);
const go = (to: LanePlace | null) => to && move(talk.id, to, verdictFor(talks, talk.id, to));
return (
<>
<Menu.Item onSelect={() => edit(talk.id)}>{at ? 'Change time or stage…' : 'Schedule…'}</Menu.Item>
<Menu.Separator />
{at ? (
<>
<Menu.Item disabled={shift(-15) === null} onSelect={() => go(shift(-15))}>
15 minutes earlier
</Menu.Item>
<Menu.Item disabled={shift(15) === null} onSelect={() => go(shift(15))}>
15 minutes later
</Menu.Item>
<Menu.Separator />
</>
) : null}
{STAGES.filter((stage) => stage.id !== at?.lane).map((stage) => {
const to = at ? open({ ...at, lane: stage.id }) : firstFree(talks, talk, stage.id);
return (
<Menu.Item key={stage.id} disabled={to === null} onSelect={() => go(to)}>
{at ? `Move to ${stage.name}` : `First free time on ${stage.name}`}
</Menu.Item>
);
})}
{at ? (
<>
<Menu.Separator />
<Menu.Item onSelect={() => move(talk.id, null, null)}>Back to unscheduled</Menu.Item>
</>
) : null}
</>
);
}
/** With a speaker picked, their talks are marked and the rest recede. */
type Highlight = 'picked' | 'dimmed' | undefined;
function Block({ talk, highlight, ...shared }: Shared & { talk: Talk; highlight: Highlight }) {
// A talk that changes stage, or goes back to the queue, 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: shared.landing });
const at = laneOf(talk.at!);
const verdict = verdictFor(shared.talks, talk.id, at);
// The name starts with what the talk shows, word for word and in its order: the title, its start
// time and its speakers (WCAG 2.5.3, Label in Name). The day, end, track, stage and warning follow.
const name = [
talk.title,
clock(talk.at!.starts, shared.locale),
talk.speakers.join(', '),
`${dayLabel(talk.at!.starts.toPlainDate(), shared.locale)}, until ${clock(talk.at!.ends, shared.locale)}`,
talk.track,
stageOf(at.lane).name,
verdict ? `warning: ${verdict.reason}` : null,
]
.filter(Boolean)
.join(', ');
return (
<li
ref={handoff}
{...shared.lanes.getItemProps(talk.id, at)}
className={styles.block}
// Between drags a talk shows its own warning; the hook puts this back after each drag.
data-conflict={verdict?.level}
data-highlight={highlight}
style={{
...placeStyle(at.start, at.end, shared.range),
['--track' as string]: `var(--todae-color-${TRACKS[talk.track]}-border)`,
}}
>
<span {...shared.lanes.getHandleProps(talk.id, 'start')} aria-hidden className={styles.edge} data-edge="start" />
<span {...shared.lanes.getHandleProps(talk.id, 'move')} aria-hidden className={styles.grip}>
<GripVertical size="1em" />
</span>
{/* The talk is its menu button, so its title and time take the room a separate button would. The
button's name says it all; a title the clamp cuts shows whole in a tooltip on hover or focus. The
seeded titles are English on every locale, so the title says so, and hyphenation follows it. */}
<TalkMenu talk={talk} talks={shared.talks} move={shared.move} edit={shared.edit} trigger={talk.id === shared.landed ? shared.landing : undefined} name={name}>
<span className={styles.body}>
<Text.Root as="span" lang="en" lines={2} weight="medium" className={styles.title}>
{talk.title}
</Text.Root>{' '}
<Text.Root as="span" lines={1} tooltip={false} tone="muted" className={styles.meta}>
{clock(talk.at!.starts, shared.locale)} · {talk.speakers.join(', ')}
</Text.Root>
</span>
{verdict ? <TriangleAlert className={styles.flag} size="1em" aria-hidden /> : null}
</TalkMenu>
<span {...shared.lanes.getHandleProps(talk.id, 'end')} aria-hidden className={styles.edge} data-edge="end" />
</li>
);
}
function QueueCard({ talk, highlight, ...shared }: Shared & { talk: Talk; highlight: Highlight }) {
const handoff = useFocusHandoff({ to: shared.landing });
return (
<li ref={handoff} {...shared.lanes.getItemProps(talk.id, { span: talk.length })} className={styles.card} data-highlight={highlight}>
<span {...shared.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.speakers.join(', ')}
</Text.Root>
<span className={styles.tags}>
<Badge.Root tone={TRACKS[talk.track]}>{talk.track}</Badge.Root>
<Badge.Root>{talk.format}</Badge.Root>
</span>
</span>
<TalkMenu talk={talk} talks={shared.talks} move={shared.move} edit={shared.edit} trigger={talk.id === shared.landed ? shared.landing : undefined} name={`${talk.title}, ${talk.speakers.join(', ')}, ${talk.length} minutes, unscheduled`} />
</li>
);
}
// ─── The dialog ────────────────────────────────────────────────────────────
/** Picks a talk's stage, day, start and length, for the keyboard and anyone who can't drag. */
function PlaceForm({ talk, talks, locale, onSave }: { talk: Talk; talks: readonly Talk[]; locale: string; onSave: (to: LanePlace, verdict: LaneVerdict | null) => void }) {
const ids = { stage: useId(), day: useId(), start: useId(), length: useId(), title: useId() };
// Where the fields start: the talk's place, or for a queued talk the first free time on the main
// stage. Read once, so the title and button don't change as the dialog closes after a save.
const [from] = useState(() => {
if (talk.at) return { placed: true, stage: talk.at.stage, starts: talk.at.starts };
const first = firstFree(talks, talk, 'main');
return { placed: false, stage: first?.lane ?? 'main', starts: first ? fromUnits(AXIS, first.start)! : null };
});
const [stage, setStage] = useState(from.stage);
const [day, setDay] = useState(() => String(from.starts ? DAYS.findIndex((each) => each.equals(from.starts!.toPlainDate())) : 0));
const [start, setStart] = useState<Temporal.PlainTime | null>(from.starts?.toPlainTime() ?? OPENS);
const [length, setLength] = useState<number | null>(talk.length);
const [errors, setErrors] = useState<FormErrors>({});
// An error is about the fields as they were, so a change clears it.
const edited =
<T,>(set: (value: T) => void) =>
(value: T) => {
setErrors({});
set(value);
};
// The place the fields name, or why they name none.
const target = ((): { to: LanePlace } | { error: string } | null => {
if (start === null || length === null) return null;
const at = toUnits(AXIS, DAYS[Number(day)]!.toZonedDateTime({ timeZone: ZONE, plainTime: start }));
if (at === null) return { error: `Start at ${formatTime(OPENS, { locale })} or later, and before ${formatTime(CLOSES, { locale })}.` };
return { to: { lane: stage, start: at, end: at + length } };
})();
const verdict = target && 'to' in target ? verdictFor(talks, talk.id, target.to) : null;
const submit = (event: SubmitEvent<HTMLFormElement>) => {
event.preventDefault();
if (target === null) return;
if ('error' in target) return setErrors({ start: target.error });
if (verdict?.level === 'blocked') return setErrors({ start: `${verdict.reason}.` });
onSave(target.to, verdict);
};
return (
<Form.Root errors={errors} onSubmit={submit} aria-labelledby={ids.title} className={styles.dialogForm}>
<Dialog.Header>
<Dialog.Title id={ids.title}>{from.placed ? `Move ${talk.title}` : `Schedule ${talk.title}`}</Dialog.Title>
<Dialog.Close />
</Dialog.Header>
<Dialog.Body>
<div className={styles.fields}>
<Field.Group>
<Label.Root htmlFor={ids.stage}>Stage</Label.Root>
<Field.Root id={ids.stage} name="stage">
<Field.Select value={stage} onChange={(event) => edited(setStage)(event.target.value)}>
{STAGES.map((each) => (
<option key={each.id} value={each.id}>
{each.name}
</option>
))}
</Field.Select>
</Field.Root>
</Field.Group>
<Field.Group>
<Label.Root htmlFor={ids.day}>Day</Label.Root>
<Field.Root id={ids.day} name="day">
<Field.Select value={day} onChange={(event) => edited(setDay)(event.target.value)}>
{DAYS.map((each, index) => (
<option key={index} value={index}>
{dayLabel(each, locale)}
</option>
))}
</Field.Select>
</Field.Root>
</Field.Group>
<Field.Group>
<Label.Root htmlFor={ids.start}>Starts</Label.Root>
<Field.Root id={ids.start} name="start">
<Field.TimeInput required value={start} onValueChange={edited(setStart)} locale={locale} />
</Field.Root>
<ErrorMessage.Root />
</Field.Group>
<Field.Group>
<Label.Root htmlFor={ids.length}>Minutes</Label.Root>
<Field.Root id={ids.length} name="length">
<Field.NumberInput required value={length} onValueChange={edited(setLength)} min={SHORTEST} max={LONGEST} step={5} locale={locale} />
</Field.Root>
<ErrorMessage.Root />
</Field.Group>
</div>
{verdict?.level === 'warning' ? (
<Alert.Root tone="warning" className={styles.alert}>
{verdict.reason}.
</Alert.Root>
) : null}
</Dialog.Body>
<Dialog.Footer>
<Dialog.Close>Cancel</Dialog.Close>
<Button.Root type="submit">{from.placed ? 'Move' : 'Schedule'}</Button.Root>
</Dialog.Footer>
</Form.Root>
);
}
// ─── The schedule ──────────────────────────────────────────────────────────
// 0.25rem a minute leaves a half-hour talk room for its grip and its text. 0.15625rem a minute is
// 9.375rem an hour, so a half-hour talk still shows a word or two of its title.
const ZOOM = { event: { step: 15, minute: '0.15625rem' }, day: { step: 5, minute: '0.25rem' } } as const;
function shownRange(zoom: keyof typeof ZOOM, day: number): Timeline['range'] {
if (zoom === 'event') return AXIS.range;
const segment = AXIS.segments[day]!;
return { start: segment.start, end: segment.end };
}
const overlaps = (start: number, end: number, range: Timeline['range']) => start < range.end && end > range.start;
function placeStyle(start: number, end: number, range: Timeline['range']) {
const length = range.end - range.start;
return {
insetInlineStart: `${((start - range.start) / length) * 100}%`,
inlineSize: `${((end - start) / length) * 100}%`,
};
}
export default function SchedulerExample({ locale = 'en-US' }: { locale?: string }) {
const [talks, setTalks] = useState(TALKS);
const [history, setHistory] = useState<{ talks: Talk[]; said: string }[]>([]);
const [zoom, setZoom] = useState<keyof typeof ZOOM>('day');
const [day, setDay] = useState(0);
const [speaker, setSpeaker] = useState('');
// The talk the dialog edits, and the one it shows, which stays while the dialog closes.
const [editing, setEditing] = useState<string | null>(null);
const [shown, setShown] = useState<{ id: string; opened: number } | null>(null);
const announce = useAnnouncer();
const ids = { speaker: useId(), queue: useId() };
const board = useRef<HTMLDivElement>(null);
const days = useRef<(HTMLElement | null)[]>([]);
// 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);
const startMinute = useRef<number | null>(null);
// A drag, a menu item and the dialog all move a talk here.
const move: Move = (id, to, verdict) => {
const talk = talks.find((each) => each.id === id)!;
const at = to && { stage: to.lane, starts: fromUnits(AXIS, to.start, 'start')!, ends: fromUnits(AXIS, to.end, 'end')! };
const said = `${talk.title} moved to ${at ? `${stageOf(at.stage).name}, ${during(at, locale)}` : 'unscheduled'}`;
setLanded(id);
setHistory((past) => [...past, { talks, said }]);
setTalks((list) => list.map((each) => (each.id === id ? { ...each, at, length: to ? to.end - to.start : each.length } : each)));
announce(`${said}${verdict ? `. ${verdict.reason}` : ''}`);
if (to && zoom === 'day' && !overlaps(to.start, to.end, range)) {
const index = AXIS.segments.findIndex((segment) => to.start >= segment.start && to.start < segment.end);
if (index >= 0) {
startMinute.current = to.start;
setDay(index);
}
}
};
const undo = () => {
const last = history.at(-1);
if (!last) return;
setHistory((past) => past.slice(0, -1));
setTalks(last.talks);
announce(`Undid: ${last.said}`);
};
const range = useMemo(() => shownRange(zoom, day), [zoom, day]);
const grid = useMemo(() => snapGrid(AXIS, ZOOM[zoom].step), [zoom]);
const lanes = useLaneDrag({
range,
grid,
minSpan: SHORTEST,
check: (id, to) => verdictFor(talks, id, to),
onDrop: ({ id, to, verdict }) => move(id, to, verdict),
});
// The dialog hands focus back to the talk it edits, wherever that talk is once it closes.
const edit = (id: string) => {
setLanded(id);
setShown((last) => ({ id, opened: (last?.opened ?? 0) + 1 }));
setEditing(id);
};
// In layout pixels, as scrollLeft is, so a scaled page doesn't skew it.
const minuteWidth = () => {
const width = board.current?.querySelector<HTMLElement>('[data-todae-lane]')?.offsetWidth ?? 0;
const length = range.end - range.start;
return length > 0 ? width / length : 0;
};
const zoomTo = (next: keyof typeof ZOOM) => {
const minute = minuteWidth();
const at = board.current && minute > 0 ? range.start + board.current.scrollLeft / minute : null;
if (next === 'day' && at !== null) {
const index = AXIS.segments.findIndex((segment) => at >= segment.start && at < segment.end);
if (index >= 0) setDay(index);
}
startMinute.current = at;
setZoom(next);
};
const selectDay = (index: number) => {
startMinute.current = AXIS.segments[index]!.start;
setDay(index);
};
useLayoutEffect(() => {
if (startMinute.current === null || !board.current) return;
const next = shownRange(zoom, day);
const width = board.current.querySelector<HTMLElement>('[data-todae-lane]')?.offsetWidth ?? 0;
const length = next.end - next.start;
const minute = length > 0 ? width / length : 0;
board.current.scrollLeft = (startMinute.current - next.start) * minute;
startMinute.current = null;
}, [zoom, day]);
const shared: Shared = { talks, lanes, move, edit, landing, landed, locale, range };
const highlight = (talk: Talk): Highlight => (speaker === '' ? undefined : talk.speakers.includes(speaker) ? 'picked' : 'dimmed');
const shownTalk = shown && talks.find((talk) => talk.id === shown.id);
const queue = talks.filter((talk) => talk.at === null);
return (
<div className={styles.schedule} data-zoom={zoom} style={{ ['--minute' as string]: ZOOM[zoom].minute, ['--minutes' as string]: range.end - range.start }}>
<div className={styles.controls}>
<div className={styles.jump} role="group" aria-label="Day">
{DAYS.map((each, index) => (
<Button.Root
key={index}
variant="secondary"
aria-pressed={zoom === 'day' ? index === day : undefined}
onClick={() => (zoom === 'day' ? selectDay(index) : days.current[index]?.scrollIntoView({ inline: 'start', block: 'nearest' }))}
>
{dayLabel(each, locale)}
</Button.Root>
))}
</div>
<ToggleGroup.Root aria-label="Zoom" value={zoom} onValueChange={(value: string | null) => value && zoomTo(value as keyof typeof ZOOM)}>
<ToggleGroup.Item value="event">Whole event</ToggleGroup.Item>
<ToggleGroup.Item value="day">One day</ToggleGroup.Item>
</ToggleGroup.Root>
<Field.Group className={styles.speaker}>
<Label.Root htmlFor={ids.speaker}>Highlight speaker</Label.Root>
<Field.Root id={ids.speaker} name="speaker">
<Field.Select value={speaker} onChange={(event) => setSpeaker(event.target.value)}>
<option value="">Everyone</option>
{SPEAKERS.map((name) => (
<option key={name}>{name}</option>
))}
</Field.Select>
</Field.Root>
</Field.Group>
<Button.Root variant="ghost" aria-disabled={history.length === 0 || undefined} onClick={undo}>
<Button.Icon>
<Undo2 />
</Button.Icon>
Undo
</Button.Root>
</div>
<div className={styles.workspace}>
<ScrollArea.Root {...lanes.getBoardProps()} ref={board} axis="both" focusable aria-label="Schedule" className={styles.board}>
{/* Every row is as wide as the whole axis, so a sticky stage name can stay in view to its end. */}
<div className={styles.rows}>
<div className={styles.row}>
<div className={styles.corner} />
<div className={styles.axis}>
{AXIS.segments.map((segment, index) => {
if (!overlaps(segment.start, segment.end, range)) return null;
return (
<div
key={index}
ref={(node) => {
days.current[index] = node;
}}
className={styles.day}
style={placeStyle(segment.start, segment.end, range)}
>
<Text.Root variant="label">{dayLabel(segment.day, locale)}</Text.Root>
<span className={styles.bands}>
{BANDS.filter((band) => band.day === index)
.map((band) => `${band.label} ${formatTime(Temporal.PlainTime.from(band.from), { locale })}–${formatTime(Temporal.PlainTime.from(band.to), { locale })}`)
.join(' · ')}
</span>
<span className={styles.hours} aria-hidden>
{Array.from({ length: (segment.end - segment.start) / 60 }, (_, hour) => (
<span key={hour}>{clock(segment.opens.add({ hours: hour }), locale)}</span>
))}
</span>
</div>
);
})}
</div>
</div>
{STAGES.map((stage) => (
<StageRow key={stage.id} stage={stage} shared={shared} highlight={highlight} />
))}
</div>
</ScrollArea.Root>
<section aria-labelledby={ids.queue} className={styles.queueArea}>
<Text.Root as="h3" id={ids.queue} variant="label">
Unscheduled
</Text.Root>
<ul {...lanes.getQueueProps()} className={styles.queue} aria-labelledby={ids.queue}>
{queue.map((talk) => (
<QueueCard key={talk.id} talk={talk} highlight={highlight(talk)} {...shared} />
))}
{queue.length === 0 ? <li className={styles.empty}>Every talk is scheduled</li> : null}
</ul>
</section>
</div>
<Dialog.Root open={editing !== null} onOpenChange={(open) => !open && setEditing(null)} restoreFocusRef={landing}>
{shownTalk ? (
<PlaceForm
key={shown.opened}
talk={shownTalk}
talks={talks}
locale={locale}
onSave={(to, verdict) => {
move(shownTalk.id, to, verdict);
setEditing(null);
}}
/>
) : null}
</Dialog.Root>
</div>
);
}
function StageRow({ stage, shared, highlight }: { stage: Stage; shared: Shared; highlight: (talk: Talk) => Highlight }) {
const nameId = useId();
const talks = shared.talks
.filter((talk) => {
if (talk.at?.stage !== stage.id) return false;
const at = laneOf(talk.at);
return overlaps(at.start, at.end, shared.range);
})
.sort((a, b) => a.at!.starts.epochMilliseconds - b.at!.starts.epochMilliseconds);
const closed = CLOSED.filter((window) => (window.keys === 'all' || window.keys.includes(`stage:${stage.id}`)) && overlaps(window.start, window.end, shared.range));
return (
<section className={styles.row} aria-labelledby={nameId}>
<div className={styles.name}>
<Text.Root as="h3" id={nameId} weight="medium" className={styles.stageName}>
{stage.name}
</Text.Root>
<Text.Root tone="muted" className={styles.stageMeta}>
{stage.seats} seats
{stage.recorded ? (
<>
{' · '}
<Video size="1em" aria-hidden /> Recorded
</>
) : null}
{stage.hours ? ` · Open ${stage.hours.map((time) => formatTime(Temporal.PlainTime.from(time), { locale: shared.locale })).join('–')}` : null}
</Text.Root>
</div>
<div {...shared.lanes.getLaneProps(stage.id)} className={styles.lane}>
{closed.map((window, index) => (
<span
key={index}
aria-hidden
className={styles.closed}
data-band={window.keys === 'all' || undefined}
style={placeStyle(window.start, window.end, shared.range)}
/>
))}
<ol className={styles.talks} aria-labelledby={nameId}>
{talks.map((talk) => (
<Block key={talk.id} talk={talk} highlight={highlight(talk)} {...shared} />
))}
</ol>
<Preview drag={shared.lanes.drag} stage={stage.id} locale={shared.locale} range={shared.range} />
</div>
</section>
);
}
.schedule {
--names: 10rem;
--header: 4.5rem;
--axis: calc(var(--minutes) * var(--minute));
container-type: inline-size;
display: flex;
flex-direction: column;
gap: var(--todae-space-4);
inline-size: 100%;
min-inline-size: 0;
}
.controls {
display: flex;
flex-wrap: wrap;
align-items: end;
gap: var(--todae-space-3);
}
.jump {
display: flex;
flex-wrap: wrap;
gap: var(--todae-space-1);
}
.speaker {
min-inline-size: 12rem;
}
/* The queue sits beside the board on a wide screen and under it on a
narrow one. */
.workspace {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: var(--todae-space-4);
}
@container (min-inline-size: 64rem) {
.workspace {
grid-template-columns: minmax(0, 1fr) 17rem;
align-items: start;
}
}
/* The board scrolls both ways, and its stacking stays inside it. */
.board {
isolation: isolate;
/* The scroll-padding marks exactly what the sticky names column and header
row cover, so useLaneDrag counts its auto-scroll edge from past them and
a drop over the names lands at the first place in view. The scroll-margin
on each day and talk menu adds a focus ring's room past them. */
--_ring-room: calc(var(--todae-focus-ring-width) + var(--todae-focus-ring-offset));
scroll-padding-block-start: calc(var(--header) + var(--todae-border-width));
scroll-padding-inline-start: var(--names);
max-block-size: 32rem;
border: var(--todae-border-width) solid var(--todae-color-border-subtle);
border-radius: var(--todae-radius-md);
background: var(--todae-color-bg-canvas);
overscroll-behavior-inline: contain;
}
/* The board's own ring goes outside it, where the sticky names and the talks
that scroll under its edges can't paint over it. */
.board:focus-visible {
outline-offset: 0;
}
/* The rows line up at the start and each is as wide as its content, the
names column plus the whole axis. A sticky element stays inside its
parent, so a row only as wide as the board would carry its stage name away
once the board scrolled past the row's end. The scroll area keeps room for
focus rings inside its edge; the rows start at the edge instead, so the
sticky names and header row already sit where they stick and don't slide
by that room as the board starts to scroll. --_ring-room matches the
scroll area's own room, so the two cancel. */
.rows {
display: flex;
flex-direction: column;
align-items: start;
gap: var(--todae-space-1);
margin-block-start: calc(-1 * var(--_ring-room));
margin-inline-start: calc(-1 * var(--_ring-room));
}
.row {
display: grid;
grid-template-columns: var(--names) var(--axis);
}
/* The header row stays at the top, and its corner covers the hours that
scroll under the names column. */
.row:first-child {
position: sticky;
inset-block-start: 0;
z-index: 4;
background: var(--todae-color-bg-canvas);
border-block-end: var(--todae-border-width) solid var(--todae-color-border-subtle);
}
/* Above the talks and a drag's preview, which scroll under it. */
.corner,
.name {
position: sticky;
inset-inline-start: 0;
z-index: 3;
background: var(--todae-color-bg-canvas);
border-inline-end: var(--todae-border-width) solid var(--todae-color-border-subtle);
}
.axis {
position: relative;
block-size: var(--header);
}
.day {
position: absolute;
inset-block: 0;
display: flex;
flex-direction: column;
gap: var(--todae-space-1);
padding-block-start: var(--todae-space-2);
padding-inline-start: var(--todae-space-2);
border-inline-start: var(--todae-border-width) solid var(--todae-color-border-default);
scroll-margin-inline-start: var(--_ring-room);
}
.bands {
overflow: hidden;
color: var(--todae-color-fg-muted);
font-size: var(--todae-text-label-font-size);
text-overflow: ellipsis;
white-space: nowrap;
}
.hours {
display: grid;
grid-auto-columns: 1fr;
grid-auto-flow: column;
margin-block-start: auto;
margin-inline-start: calc(-1 * var(--todae-space-2));
color: var(--todae-color-fg-muted);
font-size: var(--todae-text-label-font-size);
}
.hours > span {
padding-inline-start: var(--todae-space-1);
border-inline-start: var(--todae-border-width) solid var(--todae-color-border-subtle);
}
.name {
display: flex;
flex-direction: column;
justify-content: center;
padding-inline: var(--todae-space-3) var(--todae-space-2);
}
.stageName {
font-size: var(--todae-text-font-size);
}
.stageMeta {
font-size: var(--todae-text-label-font-size);
}
.stageMeta svg {
vertical-align: -0.125em;
}
/* The lane's box covers the whole axis, so it has no padding or border
along it. Lines mark each hour, and every day here opens on the hour. */
.lane {
position: relative;
block-size: 4.5rem;
background: repeating-linear-gradient(
to right,
var(--todae-color-border-subtle) 0 var(--todae-border-width),
transparent var(--todae-border-width) calc(60 * var(--minute))
);
}
.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(60 * var(--minute))
);
}
.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));
}
/* Breaks and keynotes cover every stage; a stage's own closed hours cover
its lane. Both are stripes, so they differ from a talk without color. */
.closed {
position: absolute;
inset-block: 0;
background: repeating-linear-gradient(
135deg,
var(--todae-color-bg-subtle) 0 0.375rem,
transparent 0.375rem 0.75rem
);
pointer-events: none;
}
.closed[data-band] {
background: repeating-linear-gradient(
135deg,
var(--todae-color-border-subtle) 0 0.125rem,
var(--todae-color-bg-subtle) 0.125rem 0.5rem
);
}
.talks {
position: absolute;
inset: 0;
margin: 0;
padding: 0;
list-style: none;
}
.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);
}
/* A talk's track is its leading edge's color, and the track's name is in the
menu button's name and on the queue's badge. */
.block {
position: absolute;
inset-block: var(--todae-space-1);
z-index: 1;
/* A talk's box is its time slot, borders and padding included, so it
doesn't run past its end without a global reset. */
box-sizing: border-box;
container-type: inline-size;
min-inline-size: 0;
overflow: hidden;
/* The end handle's width, so the menu button sits clear of it. */
padding-inline-end: var(--todae-space-2);
border-inline-start: 0.25rem solid var(--track);
}
.block[data-dragging],
.card[data-dragging] {
opacity: 0.5;
}
/* With a speaker picked, their talks take a heavy ring, a cue that isn't
color alone, and the rest recede without fading their text or controls,
so every talk keeps its contrast. In the queue, which has the subtle
background already, a receding card loses its surface instead. */
.card[data-highlight='picked'] {
box-shadow: inset 0 0 0 calc(2 * var(--todae-border-width)) var(--todae-color-fg-default);
}
/* A placed talk's ring sits above its button, so a hover or press fill
doesn't hide it. */
.block[data-highlight='picked']::after {
content: '';
position: absolute;
inset: 0;
z-index: 2;
border-radius: inherit;
box-shadow: inset 0 0 0 calc(2 * var(--todae-border-width)) var(--todae-color-fg-default);
pointer-events: none;
}
/* Inside a warning or blocked outline, so the ring doesn't thin it. */
.block[data-highlight='picked'][data-conflict='warning']::after {
inset: var(--todae-focus-ring-width);
}
.block[data-highlight='picked'][data-conflict='blocked']::after {
inset: calc(2 * var(--todae-focus-ring-width));
}
.block[data-highlight='dimmed'] {
border-color: var(--todae-color-border-subtle);
background: var(--todae-color-bg-subtle);
}
.card[data-highlight='dimmed'] {
border-style: dashed;
background: transparent;
}
/* A talk with a warning of its own, or one a drag 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);
outline-offset: calc(-1 * var(--todae-focus-ring-width));
}
.block[data-conflict='blocked'] {
outline: calc(2 * var(--todae-focus-ring-width)) solid var(--todae-color-status-critical-border);
outline-offset: calc(-2 * var(--todae-focus-ring-width));
}
.body {
display: flex;
flex: 1;
flex-direction: column;
gap: 0;
min-inline-size: 0;
}
.title,
.meta {
line-height: var(--todae-text-leading-tight);
}
/* A narrow talk breaks a long word with a hyphen where the language allows,
before the clamp breaks it anywhere. */
.title {
hyphens: auto;
}
.meta {
font-size: var(--todae-text-label-font-size);
}
/* The whole event is the overview, so a talk's title takes the smaller
label size there, as a calendar's dense views do, and a short word fits
whole in a half-hour talk. */
.schedule[data-zoom='event'] .title {
font-size: var(--todae-text-label-font-size);
}
.flag {
flex: none;
color: var(--todae-color-status-warning-fg);
}
/* A placed talk is its menu button, which fills the talk past its grip and
shows its title, time and any warning, so a narrow talk spends its room on
text, not on controls. Its ring sits inside it, so the block can't cut it. */
.block .menu {
flex: 1;
align-self: stretch;
justify-content: flex-start;
gap: var(--todae-space-1);
min-inline-size: 0;
/* Clear of the block's warning or blocked outline, which would cover the
button's focus ring. */
margin-block: calc(2 * var(--todae-focus-ring-width));
padding-block: 0;
padding-inline: var(--todae-space-1);
border: 0;
border-radius: 0;
font-size: inherit;
font-weight: inherit;
line-height: inherit;
text-align: start;
}
.block .menu:focus-visible {
outline-offset: calc(-1 * var(--todae-focus-ring-width));
}
/* The whole talk takes the button's hover and press fill, grip included, so
it reads as one card. The fill is translucent, so it is layered over the
talk's own surface rather than replacing it. */
.block .menu {
--_button-bg-hover: transparent;
--_button-bg-active: transparent;
}
.block:has(.menu:hover) {
background-image: linear-gradient(
var(--todae-button-ghost-bg-hover),
var(--todae-button-ghost-bg-hover)
);
}
.block:has(.menu:active) {
background-image: linear-gradient(
var(--todae-button-ghost-bg-active),
var(--todae-button-ghost-bg-active)
);
}
/* A talk with too little room past its leading edge and end handle for its
grip and some text, about 6rem at comfortable density, drops its grip,
ends and warning icon and keeps its text; its button still makes every
move, and its outline still marks a warning. A container query can't read
a token, so a denser or roomier product sets its own number. */
@container (max-inline-size: 6rem) {
/* Specific enough to beat the grip's own display, which comes later. */
.block .grip,
.block .edge,
.block .flag {
display: none;
}
/* With no end handle to clear, the button takes the block's end room too,
short of the outline. */
.block .menu {
margin-inline-end: calc(2 * var(--todae-focus-ring-width) - var(--todae-space-2));
}
}
.tags {
display: flex;
flex-wrap: wrap;
gap: var(--todae-space-1);
margin-block-start: var(--todae-space-1);
}
/* 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;
flex: none;
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 dialog sets the length too, so the narrow
ends aren't the only way. */
.edge {
position: absolute;
inset-block: 0;
z-index: 1;
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;
scroll-margin-block-start: var(--_ring-room);
scroll-margin-inline-start: var(--_ring-room);
}
.preview {
position: absolute;
inset-block: var(--todae-space-1);
z-index: 2;
box-sizing: border-box;
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: 5rem;
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);
}
.fields {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));
gap: var(--todae-space-3);
}
/* The form wraps the dialog's header, body and footer, so it spaces them as
the dialog's panel would. */
.dialogForm {
display: flex;
flex-direction: column;
gap: var(--todae-dialog-gap);
}
.alert {
margin-block-start: var(--todae-space-3);
}
/* Forced colors replace backgrounds and borders, so the drop targets,
conflicts and closed hours take system colors. */
@media (forced-colors: active) {
.lane[data-drop-target],
.queue[data-drop-target] {
outline-color: Highlight;
}
.block[data-conflict] {
outline-color: Mark;
}
.closed {
background: repeating-linear-gradient(135deg, GrayText 0 1px, transparent 1px 0.75rem);
}
.preview {
border-color: Highlight;
}
/* Forced colors drop the picked ring's shadow, so a picked talk takes a
double border, a style the conflict outlines don't use. A queue card's
border is that wide already, so picking a speaker doesn't move the queue. */
.card {
border-width: calc(3 * var(--todae-border-width));
}
.block[data-highlight='picked'],
.card[data-highlight='picked'] {
border: calc(3 * var(--todae-border-width)) double CanvasText;
}
}
Wed, Jun 2
Opening keynote 9:00 AM–10:00 AM · Lunch 12:30 PM–1:30 PMMain stage
800 seats · Recorded
Hall B
300 seats · Recorded
Workshop room
40 seats · Open 10:00 AM–5:00 PM
Unscheduled
Dark mode, done right
30 min · Mira Patel
Hands-on accessible forms
120 min · Sam Okafor
Lightning talks
45 min · Ana Ruiz, Priya Nair, Leo Brandt
Migrating to 1.0
30 min · Kenji Sato
The time axis
useLaneDrag places items along plain numbers, so the recipe counts minutes of open hours only: timeline() turns each day's opening and closing in the venue's time zone into a segment, and the nights drop out. Here day 1 is 0 to 540 and day 2 is 540 to 1080, so a drag from one day to the next is a drag along one lane. toUnits() and fromUnits() turn a Temporal.ZonedDateTime into a point and back, and snapGrid() lists the points a talk snaps to, every step from each opening and at each closing.
The end of one day and the start of the next are the same point, so each helper takes an edge: a start at 540 is 9:00 on day 2, and an end at 540 is 18:00 on day 1. A talk whose end lands past its day's closing is blocked as running past closing, since it would cross the night.
Units are elapsed minutes. A day the clock changes is as long as it really is, and a wall time the change skips or repeats becomes the later or the earlier one, as Temporal's compatible does. The board shows times in the venue's zone, as most event schedules do.
Stages and talks
Each stage is a section named by its heading, with its talks in an ol that the same heading names, in start order. The name, its seats, whether it's recorded and any opening hours stay in a sticky first column. Every row is as wide as the names column and the whole axis: a sticky element stays inside its parent, so a row only as wide as the board would carry its stage name away once the board scrolled past the row's end. The header row is sticky too, and its corner covers the hours as they scroll under the names. Each day's header names the day and lists its breaks and keynotes in text, which the board draws as stripes across every stage.
A talk is an li placed with inset-inline-start and inline-size as fractions of the axis, so nothing is measured. Its leading edge takes its track's category color. Past its grip, the talk is its menu button, so its title, start time and speakers take the room a separate button would. Text's lines clamps the title to two lines and the time to one, and shows a cut title whole in a tooltip on hover or keyboard focus. The button is the one part a screen reader reads, and its name says everything the talk shows, in the order it shows it, and more: the title, start time and speakers, then the day and end time, track, stage and any warning. A talk with less than about 6rem past its leading edge and end handle drops its grip, its ends and its warning icon and keeps its text, and its button still makes every move a drag would. The outline still marks a warning, and a picked talk's ring sits above the button, so neither hides while the button is hovered or pressed. Unscheduled talks wait in a queue beside the board on a wide screen and under it on a narrow one, each with its length, speakers, track and format.
The board is a ScrollArea that scrolls both ways and takes a Tab stop, so a keyboard can scroll it. It opens on "One day", which shows a single day, snaps to 5 minutes and leaves a talk of half an hour or more its grip. "Whole event" shows every day and snaps to 15. "Whole event" is for seeing the event at a glance: an hour there is 9.375rem, so a half-hour talk still shows a word or two of its title, set in the smaller label size and hyphenated where English allows, and a talk shorter than 45 minutes has no grip, so drag in "One day". A talk shorter than half an hour has little room for text at "Whole event"; its button's name and the tooltip on focus still say what it is. A zoom keeps the time at the board's start in view, and the day that time is in. In "One day" the day buttons select that day and show which one is selected. In "Whole event" they scroll the board to a day. The board's scroll-padding covers exactly the sticky names column and header row, so a day's stop and a focused talk stay clear of them, and a scroll-margin on each day and talk menu adds a focus ring's room past them.
The rules
findConflicts() is the one conflict rule. Each booking lists the keys it uses, here its stage and each speaker, and two bookings that share a key and overlap conflict, on whatever lanes they sit. A closed window takes keys too, or every key: breaks and keynotes close every stage and speaker, the workshop room's hours close that stage, and a speaker who arrives on day 2 closes their key on day 1. A buffer finds bookings that share a key and sit too close, such as talks on one stage with less than 10 minutes to change over. The axis leaves the nights out, so the end of one day sits next to the start of the next, and the recipe counts a changeover only within a day.
verdictFor() turns what it finds into the verdict useLaneDrag's check returns:
- Blocked: a closed window, a stage or speaker already busy, past closing, or a recorded talk on a stage that isn't recorded.
- Warning: more people expected than the stage seats, less than the changeover, or two talks of one track at once.
The drag, the menu and the dialog all ask verdictFor(), so they can't disagree. A talk that sits with a warning shows an outline, a warning icon where it has room, and the warning in its name between drags. A blocked place marks every talk it overlaps on its stage or with one of its speakers, even when a closed window is the reason. One that runs past closing marks none, since the rest of it would fall on the next morning. The example checks every talk against every other, which is quick for a few dozen; for hundreds, index the bookings by key, so a check reads only the dragged talk's stage and speakers.
Moving without dragging
Each talk's menu moves it 15 minutes earlier or later, to another stage at the same time, or back to the queue, and a talk in the queue goes to the first time on a stage with no warning, or else the first a rule allows. A move a rule blocks stays in the menu as unavailable, with disabled. "Change time or stage…" opens a dialog with a Field.Select for the stage and the day, a Field.TimeInput for the start and a Field.NumberInput for the length. A blocked place is a Form error on the start time, which a change to any field clears, and a warning shows in an Alert as the fields change.
A talk that changes stage leaves one list and joins another, so its old element goes away. useFocusHandoff sends focus from it to the moved talk's menu button. The Dialog stays mounted and opens from state, since a dialog removed while open has no close to restore focus on. Its restoreFocusRef holds the menu button of the talk it edits, so focus goes back to that talk wherever it is when the dialog closes. Every move is announced with useAnnouncer, with the stage, day, times and any warning.
Dragging
useLaneDrag takes the visible range, one day's segment in "One day" and the axis's range in "Whole event", the snap points inside that range, the shortest talk as minSpan, verdictFor() as check, and an onDrop that calls the same move function as the menu. Spread getBoardProps() on the element that scrolls, getLaneProps(stage) on each lane, getQueueProps() on the queue's list, getItemProps() on each talk, and getHandleProps() on its grip and its two ends. A talk in the queue drags out at its length, and a placed one dropped on the queue goes back to it.
During a drag the hook marks the lane under the pointer and the talks the place conflicts with, such as a speaker's other talk on another stage, with data-conflict, and the stylesheet outlines them without a render. A preview in each lane reads the drag with useLaneDragState and draws the place, its times and the verdict's reason with an icon. A blocked place takes no drop. useLaneDrag counts its auto-scroll edge from past the board's scroll-padding, so the board scrolls while the pointer is near the names or over them, and a drop over the names lands at the first place in view, such as the start of a day.
The grip and the ends are aria-hidden and not tab stops, since the menu and the dialog are the keyboard's way. Each has touch-action: none, so a finger drags from them while a swipe anywhere else scrolls the board.
Undo and saving
Each move keeps the schedule it replaced, and Undo puts the last one back and says what it undid. The example saves nothing. If your product saves a move and the save fails, put the talk back and say so with a Toast, since the announcement already said it moved. When two organizers edit at once, check the version you saved against before applying a move.
Accessible composition
Todae handles: useLaneDrag drags a talk from its grip or an end with a mouse, a finger or a pen, works out the snapped place from the lane's box and the text direction, asks the rules, refuses a blocked drop, marks the talks in conflict, and cancels on Escape. Menu reads a disabled move as unavailable and returns focus to its button. The Dialog moves focus in and back, and the Form puts the error on the field. useFocusHandoff moves focus from a talk that changed stage, and useAnnouncer writes each message to a live region.
You supply: A name for each stage that names its section and its list. A name for each talk's menu button that starts with what it shows, the title, start time and speakers in that order, then its day, end time, stage and any warning. A menu and a dialog that make every move a drag makes. The rules and their reasons. A cue for each verdict besides color. Grips and ends hidden from screen readers. Breaks and closed hours in text, not only as stripes. A ref on the menu button of the talk that last moved or opened the dialog. Highlighting that marks the picked talks with more than color and leaves the other talks' text and controls at full contrast.
Watch for: Controls that take a narrow item's room, which leave it showing a button and no title. A row only as wide as the board, which lets a sticky stage name scroll away. Rows that start inside the scroll area's room for focus rings, which lets the names and header row slide by that room before they stick. A scroll-padding wider than the sticky parts, which puts a drop over the names a step past a day that starts right at their edge. A dialog unmounted while open, which drops focus on the page. A changeover counted across a night. Times shown in the browser's zone when the event's are meant. A talk crossing a night on a collapsed axis. A conflict that only shows on the talk's own stage. A move that only dragging can make (WCAG 2.2 SC 2.1.1 and SC 2.5.7). A conflict shown by color alone (SC 1.4.1). Many stages of talks, each a tab stop: arrow keys inside a lane with useRovingFocus keep Tab to one stop a stage.
When to use
When: People place items on parallel lanes along time, where an item's resources can clash across lanes, such as talks on stages, shifts on a rota or bookings of rooms.
When not: One ordered list → the Reorder recipe. Items that move between stages of work with no time → the Kanban recipe. Picking one date or time → the Date and time picker recipe.