Scheduler
패키지 네임스페이스가 아니라 레시피입니다. 스케줄러는 회의실, 사람, 장비처럼 하나의 시간 축을 따라 나란히 놓인 레인에 항목을 배치하며, 항목이 쓰는 것 중 하나가 바쁜 자리에는 다른 레인이라도 놓을 수 없습니다. 항목은 배치되기 전까지 대기 목록에 있습니다. 끌기는 useLaneDrag가 맡고, 각 항목의 Menu와 Dialog가 같은 이동을 키보드로 합니다. 시간 도우미와 충돌 규칙은 레시피 안에 있으니 제품에 맞게 바꾸세요. Scheduler.* export는 없습니다.
이 페이지의 내용
예제는 사흘짜리 컨퍼런스입니다. 각 무대가 레인이고, 무대나 연사 중 한 명이 바쁜 자리에는 세션을 놓을 수 없습니다. 세션을 손잡이로 잡아 다른 시간, 무대, 날로 끌거나, 한쪽 끝을 끌어 길이를 바꿔 보세요. 끌지 않고 옮기려면 세션을 눌러 메뉴를 열고, 연사를 고르면 모든 무대에서 그 연사의 세션을 볼 수 있습니다.
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;
}
}
6월 2일 (수)
Opening keynote 오전 9:00–오전 10:00 · Lunch 오후 12:30–오후 1:30Main stage
800 seats · Recorded
Hall B
300 seats · Recorded
Workshop room
40 seats · Open 오전 10:00–오후 5:00
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
시간 축
useLaneDrag는 항목을 평범한 숫자를 따라 놓으므로, 레시피는 운영 시간의 분만 셉니다. timeline()은 행사장 시간대에서 각 날의 여는 시각과 닫는 시각을 구간으로 바꾸고, 밤은 빠집니다. 여기서 첫째 날은 0부터 540, 둘째 날은 540부터 1080이므로, 한 날에서 다음 날로 끄는 것은 한 레인을 따라 끄는 것입니다. toUnits()와 fromUnits()는 Temporal.ZonedDateTime을 점으로 바꾸고 다시 되돌리며, snapGrid()는 세션이 맞춰질 점을 각 여는 시각부터 단계마다, 그리고 각 닫는 시각에 나열합니다.
한 날의 끝과 다음 날의 시작은 같은 점이므로, 각 도우미는 edge를 받습니다. 540에서의 시작은 둘째 날 9:00이고, 540에서의 끝은 첫째 날 18:00입니다. 끝이 그날 닫는 시각을 넘는 세션은 밤을 건너게 되므로 마감 시간을 넘긴다며 막힙니다.
단위는 흐른 분입니다. 시계가 바뀌는 날은 실제 길이 그대로이고, 시계 변경이 건너뛰거나 되풀이하는 벽시계 시각은 Temporal의 compatible처럼 각각 나중 시각과 앞 시각이 됩니다. 대부분의 행사 일정처럼 보드는 행사장 시간대의 시각을 보여 줍니다.
무대와 세션
각 무대는 제목이 이름을 붙이는 section이고, 세션은 같은 제목이 이름을 붙이는 ol에 시작 순서대로 있습니다. 무대 이름, 좌석 수, 녹화 여부, 운영 시간은 고정된 첫 열에 남습니다. 모든 행은 이름 열과 축 전체를 합친 만큼 넓습니다. 고정(sticky) 요소는 부모 안에 머물기 때문에, 보드만큼만 넓은 행은 보드가 행의 끝을 지나 스크롤되면 무대 이름을 함께 데려가 버립니다. 머리글 행도 고정되고, 그 모서리는 이름 열 아래로 스크롤되는 시각을 가립니다. 각 날의 머리글은 날짜를 적고 그날의 휴식과 기조연설을 글로 나열하며, 보드는 이를 모든 무대를 가로지르는 줄무늬로 그립니다.
세션은 inset-inline-start와 inline-size를 축의 비율로 배치한 li이므로 아무것도 측정하지 않습니다. 앞쪽 가장자리는 트랙의 category 색을 띱니다. 손잡이를 뺀 나머지는 세션의 메뉴 버튼이므로, 따로 둔 버튼이 차지할 자리에 제목, 시작 시각, 연사가 들어갑니다. Text의 lines가 제목을 두 줄, 시각을 한 줄로 자르고, 잘린 제목은 마우스를 올리거나 키보드로 포커스하면 툴팁에 전부 보여 줍니다. 버튼은 화면 낭독기가 읽는 유일한 부분이고, 그 이름은 세션이 보여 주는 것을 보여 주는 순서대로, 그리고 그 이상을 모두 말합니다. 제목, 시작 시각, 연사, 그다음 날과 끝 시각, 트랙, 무대, 그리고 경고가 있다면 그 내용입니다. 앞쪽 가장자리와 끝 손잡이를 빼고 남는 폭이 약 6rem보다 좁은 세션은 손잡이, 양 끝, 경고 아이콘을 빼고 글은 남기며, 버튼은 여전히 끌기로 하는 모든 이동을 맡습니다. 경고는 여전히 외곽선으로 표시되고, 고른 세션의 테두리는 버튼 위에 그려지므로 버튼에 마우스를 올리거나 누를 때도 둘 다 가려지지 않습니다. 배치되지 않은 세션은 넓은 화면에서는 보드 옆, 좁은 화면에서는 보드 아래의 대기 목록에서 길이, 연사, 트랙, 형식과 함께 기다립니다.
보드는 양쪽으로 스크롤되고 탭 정지를 받는 ScrollArea이므로 키보드로도 스크롤할 수 있습니다. 보드는 하루만 보여 주고 5분 단위로 맞추며 30분 이상인 세션에 손잡이를 남기는 "One day"로 열립니다. "Whole event"는 모든 날을 보여 주고 15분 단위로 맞춥니다. "Whole event"는 행사 전체를 한눈에 보는 용도입니다. 한 시간이 9.375rem이라 30분짜리 세션도 더 작은 라벨 크기로 제목의 한두 단어를 보여 주고, 예시의 제목은 영어이고 lang="en"을 달았으므로 긴 단어는 영어 규칙대로 하이픈으로 나눕니다. 45분보다 짧은 세션에는 손잡이가 없으니 끌기는 "One day"에서 하세요. 30분보다 짧은 세션은 "Whole event"에서 글이 들어갈 자리가 거의 없지만, 버튼의 이름과 포커스할 때의 툴팁이 무엇인지 말해 줍니다. 확대 수준을 바꿔도 보드 시작에 보이던 시각이 그대로 남고, 그 시각이 속한 날도 남습니다. "One day"에서 날 버튼은 그날을 고르고 어느 날이 선택됐는지 보여 줍니다. "Whole event"에서 날 버튼은 보드를 그날로 스크롤합니다. 보드의 scroll-padding은 고정된 이름 열과 머리글 행이 덮는 만큼만 정확히 비워 두므로 날의 멈춤 위치와 포커스를 받은 세션이 그 바깥에 서고, 각 날과 세션 메뉴의 scroll-margin이 그 너머로 포커스 링의 여백을 더합니다.
규칙
findConflicts()가 하나뿐인 충돌 규칙입니다. 각 예약은 자신이 쓰는 키, 여기서는 무대와 각 연사를 나열하고, 키를 공유하며 겹치는 두 예약은 어느 레인에 있든 충돌합니다. 닫힌 시간대도 키를 받거나 모든 키를 받습니다. 휴식과 기조연설은 모든 무대와 연사를 닫고, 워크숍 룸의 운영 시간은 그 무대를 닫으며, 둘째 날 도착하는 연사는 첫째 날 자기 키를 닫습니다. buffer는 키를 공유하면서 너무 가까이 붙은 예약, 예를 들어 한 무대에서 전환 시간이 10분이 안 되는 세션을 찾습니다. 축은 밤을 빼므로 한 날의 끝과 다음 날의 시작이 붙어 있고, 레시피는 전환 시간을 하루 안에서만 셉니다.
verdictFor()는 찾은 것을 useLaneDrag의 check가 돌려주는 판정으로 바꿉니다.
- 막힘: 닫힌 시간대, 이미 바쁜 무대나 연사, 마감 시간 초과, 녹화하지 않는 무대에 놓인 녹화 세션.
- 경고: 무대 좌석보다 많은 예상 인원, 전환 시간 부족, 같은 트랙 세션 두 개가 동시에 열림.
끌기, 메뉴, 대화상자가 모두 verdictFor()에 묻기 때문에 서로 어긋날 수 없습니다. 경고를 안고 놓여 있는 세션은 끌기 사이에도 윤곽선, 자리가 있으면 경고 아이콘, 이름 속의 경고를 보여 줍니다. 막힌 자리는 닫힌 시간대가 이유일 때도, 같은 무대에서 또는 같은 연사와 겹치는 세션을 모두 표시합니다. 마감을 넘기는 자리는 나머지가 다음 날 아침에 걸리므로 아무 세션도 표시하지 않습니다. 예제는 모든 세션을 다른 모든 세션과 비교하는데, 수십 개라면 빠릅니다. 수백 개라면 예약을 키로 색인해 검사가 끄는 세션의 무대와 연사만 읽게 하세요.
끌지 않고 옮기기
각 세션의 메뉴는 세션을 15분 앞이나 뒤로, 같은 시각의 다른 무대로, 또는 대기 목록으로 옮기고, 대기 목록의 세션은 무대에서 경고가 없는 첫 시간으로, 그런 시간이 없으면 규칙이 허용하는 첫 시간으로 갑니다. 규칙이 막는 이동은 disabled를 받아 사용할 수 없는 항목으로 메뉴에 남습니다. "Change time or stage…"는 무대와 날을 고르는 Field.Select, 시작 시각을 받는 Field.TimeInput, 길이를 받는 Field.NumberInput이 있는 대화상자를 엽니다. 막힌 자리는 시작 시각에 붙는 Form 오류가 되고 어느 필드든 바뀌면 사라지며, 경고는 필드가 바뀔 때마다 Alert에 나타납니다.
무대를 바꾸는 세션은 한 목록을 떠나 다른 목록에 들어가므로 이전 요소가 사라집니다. useFocusHandoff가 그 요소의 포커스를 옮겨진 세션의 메뉴 버튼으로 보냅니다. 열린 채로 사라진 대화상자는 닫힘이 없어 포커스를 되돌릴 수 없으므로, Dialog는 마운트된 채 상태로 열립니다. restoreFocusRef는 대화상자가 고치는 세션의 메뉴 버튼을 가리키므로, 대화상자가 닫히면 포커스는 그 세션이 어디에 있든 그리로 돌아갑니다. 모든 이동은 무대, 날, 시각, 그리고 경고가 있으면 경고와 함께 useAnnouncer로 알립니다.
끌기
useLaneDrag는 보이는 범위("One day"에서는 하루의 segment, "Whole event"에서는 축의 range)와 그 범위 안의 스냅 지점, 가장 짧은 세션 길이인 minSpan, check로 쓰는 verdictFor(), 그리고 메뉴와 같은 이동 함수를 부르는 onDrop을 받습니다. 스크롤되는 요소에 getBoardProps()를, 각 레인에 getLaneProps(stage)를, 대기 목록에 getQueueProps()를, 각 세션에 getItemProps()를, 손잡이와 양 끝에 getHandleProps()를 펼치세요. 대기 목록의 세션은 자기 길이로 끌려 나오고, 놓인 세션을 대기 목록에 떨어뜨리면 그리로 돌아갑니다.
끄는 동안 훅은 포인터 아래의 레인과, 다른 무대에 있는 연사의 다른 세션처럼 그 자리와 충돌하는 세션에 data-conflict를 표시하고, 스타일시트는 렌더 없이 윤곽선을 그립니다. 각 레인의 미리보기는 useLaneDragState로 끌기를 읽어 자리와 시각, 판정의 이유를 아이콘과 함께 그립니다. 막힌 자리에는 놓을 수 없습니다. useLaneDrag는 자동 스크롤 가장자리를 보드의 scroll-padding 너머부터 세므로, 포인터가 이름 근처나 이름 위에 있는 동안 보드가 스크롤되고, 이름 위에서 놓으면 화면에 보이는 첫 자리, 예를 들어 날의 시작에 놓입니다.
손잡이와 양 끝은 aria-hidden이고 탭 정지가 아닙니다. 키보드로는 메뉴와 대화상자를 씁니다. 각각 touch-action: none이 있어 손가락으로 거기서 끌 수 있고, 다른 곳을 쓸면 보드가 스크롤됩니다.
되돌리기와 저장
이동할 때마다 바뀌기 전 일정을 보관하고, Undo는 마지막 일정을 되돌리며 무엇을 되돌렸는지 알립니다. 예제는 아무것도 저장하지 않습니다. 제품이 이동을 저장하다 실패하면 세션을 되돌리고 Toast로 알리세요. 알림은 이미 세션이 옮겨졌다고 말했으니까요. 두 운영자가 동시에 고친다면, 이동을 적용하기 전에 저장했던 버전과 비교하세요.
접근성을 지키는 조합
Todae가 맡는 것: useLaneDrag는 마우스, 손가락, 펜으로 세션을 손잡이나 한쪽 끝에서 끌고, 레인의 상자와 글 방향으로 맞춰진 자리를 계산하며, 규칙에 묻고, 막힌 놓기를 거절하고, 충돌하는 세션을 표시하며, Escape로 끌기를 취소합니다. Menu는 disabled 이동을 사용할 수 없다고 읽히게 하고 포커스를 버튼으로 돌려줍니다. Dialog는 포커스를 안으로 옮겼다가 되돌리고, Form은 오류를 필드에 붙입니다. useFocusHandoff는 무대를 바꾼 세션에서 포커스를 옮기고, useAnnouncer는 각 메시지를 live region에 씁니다.
직접 제공할 것: 자기 section과 목록에 이름을 붙이는 각 무대의 이름. 보여 주는 것, 곧 제목, 시작 시각, 연사로 그 순서대로 시작해 날, 끝 시각, 무대, 그리고 경고가 있다면 그 내용을 담은 각 세션 메뉴 버튼의 이름. 끌기로 하는 모든 이동을 하는 메뉴와 대화상자. 규칙과 그 이유. 색 말고도 각 판정을 구별하는 단서. 화면 낭독기에서 숨긴 손잡이와 양 끝. 줄무늬만이 아니라 글로도 적은 휴식과 닫힌 시간. 마지막으로 옮겨졌거나 대화상자를 연 세션의 메뉴 버튼에 거는 ref. 고른 세션을 색 말고도 표시하고 다른 세션의 글과 컨트롤을 온전한 대비로 남기는 강조.
주의할 점: 좁은 항목의 자리를 차지하는 컨트롤. 항목에 제목 없이 버튼만 남습니다. 보드만큼만 넓은 행. 고정된 무대 이름이 스크롤되어 사라집니다. 스크롤 영역이 포커스 링을 위해 남긴 여백 안에서 시작하는 행. 이름과 머리글 행이 고정되기 전에 그 여백만큼 밀립니다. 고정된 부분보다 넓은 scroll-padding. 이름 바로 옆에서 시작하는 날에 이름 위에서 놓으면 한 칸 뒤에 놓입니다. 열린 채로 언마운트된 대화상자. 포커스가 페이지로 떨어집니다. 밤을 건너 센 전환 시간. 행사의 시간대가 아니라 브라우저의 시간대로 보여 주는 시각. 밤을 뺀 축에서 밤을 건너는 세션. 세션 자신의 무대에서만 보이는 충돌. 끌기로만 할 수 있는 이동(WCAG 2.2 SC 2.1.1과 SC 2.5.7). 색으로만 보여 주는 충돌(SC 1.4.1). 무대마다 세션이 많아 모두 탭 정지가 되는 것. 레인 안에서 useRovingFocus로 화살표 키를 쓰면 Tab은 무대마다 한 번만 멈춥니다.
언제 쓰나요
쓸 때: 무대의 세션, 근무표의 교대, 회의실 예약처럼, 시간을 따라 나란한 레인에 항목을 놓고 항목이 쓰는 자원이 레인을 넘어 충돌할 수 있을 때.
쓰지 않을 때: 순서 있는 목록 하나 → Reorder 레시피. 시간 없이 작업 단계 사이를 옮겨 다니는 항목 → Kanban 레시피. 날짜나 시각 하나를 고를 때 → Date and time picker 레시피.