Slot picker
A two-step appointment chooser. A week strip of day pills (weekday, date and a small count of open times) with previous and next week arrows sits above a grid of time slots for the chosen day, grouped into Morning, Afternoon and Evening. Unavailable slots are struck through and disabled. Picking a slot expands it in place into a confirm row ('Tue 18 Nov, 10:30 to 11:00 · Confirm') instead of a separate button. A time zone switch re-renders every label in the viewer's or the host's zone with Intl, and a 15/30/60 minute toggle regenerates the slots. Slots come from an async getSlots(date, duration) or a fixed map, with skeletons while a day loads, min and max dates and a jump to the next open day. The strip and each slot group are keyboard radiogroups, focus moves to Confirm after a choice, and the chosen time is announced. At phone width the strip shows five days and swipes.
Source
import * as React from "react";
import { Check, ChevronLeft, ChevronRight, Globe2, Loader2 } from "lucide-react";
import { cn } from "@/lib/utils";
export type Slot = { start: Date; available: boolean };
export type SlotZone = { label: string; tz: string };
export type SlotChoice = { start: Date; end: Date; tz: string };
export type SlotPickerProps = {
/** Slots for a day (local midnight) and a duration in minutes. */
getSlots?: (date: Date, duration: number) => Promise<Slot[]> | Slot[];
/** Or a fixed map keyed "yyyy-mm-dd". */
slots?: Record<string, Slot[]>;
durations?: number[];
defaultDuration?: number;
/** The first zone is the default; usually the viewer's, then the host's. */
timeZones?: SlotZone[];
weekStart?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
min?: Date;
max?: Date;
defaultDate?: Date;
/** A slot start to preselect once its day has loaded. */
defaultValue?: Date;
onConfirm?: (choice: SlotChoice) => Promise<unknown> | void;
/** Shown at the top of the card, e.g. the host and the meeting name. */
header?: React.ReactNode;
locale?: string;
className?: string;
};
const ring = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card";
const day = (date: Date) => new Date(date.getFullYear(), date.getMonth(), date.getDate());
const addDays = (date: Date, amount: number) => new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount);
const iso = (date: Date) => `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
const startOfWeek = (date: Date, weekStart: number) => addDays(day(date), -((date.getDay() - weekStart + 7) % 7));
const PARTS = ["Morning", "Afternoon", "Evening"] as const;
function hourIn(date: Date, tz: string) {
return Number(new Intl.DateTimeFormat("en-US", { hour: "numeric", hourCycle: "h23", timeZone: tz }).format(date));
}
function offsetName(tz: string) {
try {
return new Intl.DateTimeFormat("en-US", { timeZone: tz, timeZoneName: "shortOffset" }).formatToParts(new Date()).find((part) => part.type === "timeZoneName")?.value || "";
} catch {
return "";
}
}
export function SlotPicker({
getSlots,
slots,
durations = [15, 30, 60],
defaultDuration,
timeZones,
weekStart = 1,
min,
max,
defaultDate,
defaultValue,
onConfirm,
header,
locale,
className,
}: SlotPickerProps) {
const zones = React.useMemo<SlotZone[]>(
() => (timeZones?.length ? timeZones : [{ label: "Your time", tz: Intl.DateTimeFormat().resolvedOptions().timeZone }]),
[timeZones],
);
const first = day(defaultValue || defaultDate || min || new Date());
const [selectedDay, setSelectedDay] = React.useState(first);
const [weekFrom, setWeekFrom] = React.useState(() => startOfWeek(first, weekStart));
const [duration, setDuration] = React.useState(defaultDuration ?? durations[Math.min(1, durations.length - 1)]);
const [zone, setZone] = React.useState(0);
const [cache, setCache] = React.useState<Record<string, Slot[]>>({});
const [chosen, setChosen] = React.useState<number | null>(defaultValue ? defaultValue.getTime() : null);
const [status, setStatus] = React.useState<"idle" | "saving" | "done">("idle");
const [announce, setAnnounce] = React.useState("");
/* No entrance motion on first paint or a preselected slot; only in answer to the user. */
const [animate, setAnimate] = React.useState(false);
const requested = React.useRef(new Set<string>());
const stripRef = React.useRef<HTMLDivElement>(null);
const slotsRef = React.useRef<HTMLDivElement>(null);
const confirmRef = React.useRef<HTMLButtonElement>(null);
const focusConfirm = React.useRef(false);
const id = React.useId();
const tz = zones[zone].tz;
const days = React.useMemo(() => Array.from({ length: 7 }, (_, index) => addDays(weekFrom, index)), [weekFrom]);
const outOfBounds = (date: Date) => (!!min && date < day(min)) || (!!max && date > day(max));
const cacheKey = (date: Date) => `${iso(date)}|${duration}`;
/* Load every day in the visible week once per duration. */
React.useEffect(() => {
for (const date of days) {
const k = cacheKey(date);
if (outOfBounds(date) || requested.current.has(k)) continue;
requested.current.add(k);
const result = slots ? slots[iso(date)] || [] : getSlots ? getSlots(date, duration) : [];
Promise.resolve(result).then(
(list) => setCache((prev) => ({ ...prev, [k]: list })),
() => requested.current.delete(k),
);
}
}, [days, duration, getSlots, slots]);
const daySlots = cache[cacheKey(selectedDay)];
const loading = !outOfBounds(selectedDay) && !daySlots;
const fmtTime = (date: Date) => new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit", timeZone: tz }).format(date);
const fmtDay = (date: Date) => new Intl.DateTimeFormat(locale, { weekday: "short", day: "numeric", month: "short", timeZone: tz }).format(date);
const describe = (start: number) => `${fmtDay(new Date(start))}, ${fmtTime(new Date(start))} to ${fmtTime(new Date(start + duration * 60_000))}`;
const groups = React.useMemo(() => {
const result: Record<(typeof PARTS)[number], Slot[]> = { Morning: [], Afternoon: [], Evening: [] };
for (const slot of daySlots || []) {
const hour = hourIn(slot.start, tz);
result[hour < 12 ? "Morning" : hour < 17 ? "Afternoon" : "Evening"].push(slot);
}
return result;
}, [daySlots, tz]);
const availableCount = daySlots?.filter((slot) => slot.available).length ?? 0;
React.useEffect(() => {
if (focusConfirm.current && chosen != null) {
focusConfirm.current = false;
confirmRef.current?.focus();
}
}, [chosen]);
/* Keep the selected day pill in view inside the swipeable strip. */
React.useEffect(() => {
const strip = stripRef.current;
const pill = strip?.querySelector<HTMLElement>('[aria-checked="true"]');
if (!strip || !pill) return;
if (pill.offsetLeft < strip.scrollLeft || pill.offsetLeft + pill.offsetWidth > strip.scrollLeft + strip.clientWidth)
strip.scrollTo({ left: pill.offsetLeft - 8, behavior: "smooth" });
}, [selectedDay, weekFrom]);
const pickDay = (date: Date, focus = false) => {
if (outOfBounds(date)) return;
setAnimate(true);
const from = startOfWeek(date, weekStart);
if (from.getTime() !== weekFrom.getTime()) setWeekFrom(from);
setSelectedDay(date);
setChosen(null);
setStatus("idle");
if (focus) requestAnimationFrame(() => stripRef.current?.querySelector<HTMLElement>(`[data-day="${iso(date)}"]`)?.focus());
};
const shiftWeek = (amount: number) => {
const next = addDays(weekFrom, amount * 7);
setWeekFrom(next);
const target = addDays(selectedDay, amount * 7);
const firstValid = Array.from({ length: 7 }, (_, index) => addDays(next, index)).find((date) => !outOfBounds(date));
pickDay(outOfBounds(target) ? firstValid || target : target);
};
const onDayKey = (event: React.KeyboardEvent, date: Date) => {
const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
if (!step) return;
event.preventDefault();
let next = addDays(date, step);
for (let i = 0; i < 14 && outOfBounds(next); i++) next = addDays(next, step);
if (!outOfBounds(next)) pickDay(next, true);
};
const choose = (slot: Slot, moveFocus: boolean) => {
if (!slot.available) return;
setAnimate(true);
focusConfirm.current = moveFocus;
setChosen(slot.start.getTime());
setStatus("idle");
setAnnounce(`Selected ${describe(slot.start.getTime())}`);
};
const onSlotKey = (event: React.KeyboardEvent, list: Slot[], index: number) => {
const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
choose(list[index], true);
return;
}
if (!step) return;
event.preventDefault();
for (let i = 1; i <= list.length; i++) {
const next = list[(index + step * i + list.length * 2) % list.length];
if (next.available) {
choose(next, false);
requestAnimationFrame(() => slotsRef.current?.querySelector<HTMLElement>(`[data-slot="${next.start.getTime()}"]`)?.focus());
return;
}
}
};
const confirm = async () => {
if (chosen == null || status === "saving") return;
setStatus("saving");
const choice = { start: new Date(chosen), end: new Date(chosen + duration * 60_000), tz };
try {
await onConfirm?.(choice);
setStatus("done");
setAnnounce(`Booked ${describe(chosen)}`);
} catch {
setStatus("idle");
setAnnounce("Could not book that time. Try again.");
}
};
const monthLabel = new Intl.DateTimeFormat(locale, { month: "long", year: "numeric" }).format(days[3]);
const nextOpen = !loading && availableCount === 0
? days.find((date) => date > selectedDay && cache[cacheKey(date)]?.some((slot) => slot.available))
: undefined;
return (
<section className={cn("@container overflow-hidden rounded-2xl border border-border bg-card text-card-foreground shadow-sm", className)}>
<style href="chm-slot-picker" precedence="default">{`@keyframes chm-sp-expand{from{clip-path:inset(0 calc(100% - 7rem) 0 0 round .75rem);opacity:.6}to{clip-path:inset(0 0 0 0 round .75rem);opacity:1}}@keyframes chm-sp-fade{from{opacity:0}to{opacity:1}}`}</style>
{header && <div className="border-b border-border px-4 py-4 sm:px-5">{header}</div>}
<div className="px-4 pt-4 sm:px-5">
<div className="flex items-center justify-between gap-3">
<h3 id={`${id}-month`} className="text-sm font-semibold">{monthLabel}</h3>
<div className="flex items-center gap-1">
<button type="button" aria-label="Previous week" onClick={() => shiftWeek(-1)} disabled={!!min && weekFrom <= day(min)} className={cn("grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-30", ring)}>
<ChevronLeft className="size-4" aria-hidden="true" />
</button>
<button type="button" aria-label="Next week" onClick={() => shiftWeek(1)} disabled={!!max && addDays(weekFrom, 6) >= day(max)} className={cn("grid size-8 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground disabled:opacity-30", ring)}>
<ChevronRight className="size-4" aria-hidden="true" />
</button>
</div>
</div>
<div
ref={stripRef}
role="radiogroup"
aria-labelledby={`${id}-month`}
className="mt-3 grid snap-x snap-mandatory auto-cols-[calc((100%-2rem)/5)] grid-flow-col gap-2 overflow-x-auto pb-1 [scrollbar-width:none] @xl:auto-cols-[calc((100%-3rem)/7)]"
>
{days.map((date) => {
const off = outOfBounds(date);
const on = date.getTime() === selectedDay.getTime();
const list = cache[cacheKey(date)];
const free = list?.filter((slot) => slot.available).length;
return (
<button
key={iso(date)}
type="button"
role="radio"
data-day={iso(date)}
aria-checked={on}
aria-disabled={off || undefined}
aria-label={`${new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric", month: "long" }).format(date)}${off ? ", unavailable" : free != null ? `, ${free} open ${free === 1 ? "time" : "times"}` : ""}`}
tabIndex={on ? 0 : -1}
onClick={() => pickDay(date)}
onKeyDown={(event) => onDayKey(event, date)}
className={cn(
"flex snap-start flex-col items-center gap-0.5 rounded-xl border py-2 transition-colors",
on ? "border-primary bg-primary text-primary-foreground" : "border-border hover:bg-accent",
off && "cursor-not-allowed opacity-40 hover:bg-transparent",
ring,
)}
>
<span className={cn("text-[11px] font-medium uppercase tracking-wide", on ? "text-primary-foreground/75" : "text-muted-foreground")}>
{new Intl.DateTimeFormat(locale, { weekday: "short" }).format(date)}
</span>
<span className="text-lg font-semibold leading-tight tabular-nums">{date.getDate()}</span>
<span className="flex h-3.5 items-center gap-1 text-[10px] tabular-nums" aria-hidden="true">
{!off && free != null && (
<>
<span className={cn("size-1.5 rounded-full", free === 0 ? "bg-muted-foreground/40" : on ? "bg-primary-foreground" : "bg-emerald-500")} />
<span className={on ? "text-primary-foreground/80" : "text-muted-foreground"}>{free}</span>
</>
)}
</span>
</button>
);
})}
</div>
<div className="mt-3 flex flex-wrap items-center justify-between gap-x-4 gap-y-2 border-t border-border py-3 text-[13px]">
{zones.length > 1 ? (
<div className="flex items-center gap-2" role="group" aria-label="Time zone">
<Globe2 className="size-3.5 text-muted-foreground" aria-hidden="true" />
<div className="flex rounded-lg bg-muted p-0.5">
{zones.map((item, index) => (
<button
key={item.tz + item.label}
type="button"
aria-pressed={zone === index}
onClick={() => setZone(index)}
className={cn("rounded-md px-2 py-1 transition-colors", zone === index ? "bg-background font-medium text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground", ring)}
>
{item.label} <span className="text-muted-foreground">{offsetName(item.tz)}</span>
</button>
))}
</div>
</div>
) : (
<span className="flex items-center gap-2 text-muted-foreground">
<Globe2 className="size-3.5" aria-hidden="true" />
{zones[0].label} · {offsetName(tz)}
</span>
)}
<div role="radiogroup" aria-label="Duration" className="flex rounded-lg bg-muted p-0.5">
{durations.map((minutes) => (
<button
key={minutes}
type="button"
role="radio"
aria-checked={duration === minutes}
tabIndex={duration === minutes ? 0 : -1}
onClick={() => {
setAnimate(true);
setDuration(minutes);
setChosen(null);
setStatus("idle");
}}
onKeyDown={(event) => {
const index = durations.indexOf(minutes);
const step = event.key === "ArrowRight" || event.key === "ArrowDown" ? 1 : event.key === "ArrowLeft" || event.key === "ArrowUp" ? -1 : 0;
if (!step) return;
event.preventDefault();
const next = durations[(index + step + durations.length) % durations.length];
setAnimate(true);
setDuration(next);
setChosen(null);
const group = event.currentTarget.parentElement;
requestAnimationFrame(() => group?.querySelector<HTMLElement>(`[data-min="${next}"]`)?.focus());
}}
data-min={minutes}
className={cn("rounded-md px-2.5 py-1 tabular-nums transition-colors", duration === minutes ? "bg-background font-medium text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground", ring)}
>
{minutes} min
</button>
))}
</div>
</div>
</div>
<div ref={slotsRef} className="min-h-[15rem] border-t border-border bg-muted/30 px-4 py-4 sm:px-5" aria-busy={loading}>
{loading ? (
<div className="space-y-5" aria-label="Loading times">
{[6, 8, 4].map((n, g) => (
<div key={g}>
<span className="block h-3 w-20 rounded bg-muted motion-safe:animate-pulse" />
<div className="mt-2.5 grid grid-cols-3 gap-2 @md:grid-cols-4 @2xl:grid-cols-6">
{Array.from({ length: n }, (_, i) => <span key={i} className="h-10 rounded-xl bg-muted motion-safe:animate-pulse" />)}
</div>
</div>
))}
</div>
) : availableCount === 0 ? (
<div className="grid min-h-[13rem] place-items-center text-center text-sm text-muted-foreground">
<div>
<p>No open times on this day.</p>
{nextOpen && (
<button type="button" onClick={() => pickDay(nextOpen, true)} className={cn("mt-2 rounded-md px-2 py-1 font-medium text-foreground underline underline-offset-4", ring)}>
{new Intl.DateTimeFormat(locale, { weekday: "long", day: "numeric" }).format(nextOpen)}
</button>
)}
</div>
</div>
) : (
<div className={cn("space-y-5", animate && "motion-safe:animate-[chm-sp-fade_.2s_ease-out]")}>
{PARTS.map((part) => {
const list = groups[part];
if (!list.length) return null;
const tabbable = list.find((slot) => slot.start.getTime() === chosen) || list.find((slot) => slot.available);
return (
<div key={part}>
<h4 id={`${id}-${part}`} className="text-xs font-medium uppercase tracking-wide text-muted-foreground">{part}</h4>
<div role="radiogroup" aria-labelledby={`${id}-${part}`} className="mt-2.5 grid grid-cols-3 gap-2 @md:grid-cols-4 @2xl:grid-cols-6">
{list.map((slot, index) => {
const time = slot.start.getTime();
const on = time === chosen;
const radio = (
<button
type="button"
role="radio"
data-slot={time}
aria-checked={on}
aria-disabled={!slot.available || undefined}
aria-label={`${fmtTime(slot.start)}${slot.available ? "" : ", unavailable"}`}
tabIndex={slot === tabbable ? 0 : -1}
onClick={() => choose(slot, true)}
onKeyDown={(event) => onSlotKey(event, list, index)}
className={cn(
"h-10 rounded-xl border text-sm font-medium tabular-nums transition-colors",
on
? "w-28 shrink-0 border-primary bg-primary text-primary-foreground"
: slot.available
? "border-border bg-card hover:border-foreground/30 hover:bg-accent"
: "cursor-not-allowed border-transparent bg-transparent text-muted-foreground/60 line-through decoration-muted-foreground/50",
ring,
)}
>
{fmtTime(slot.start)}
</button>
);
if (!on) return <React.Fragment key={time}>{radio}</React.Fragment>;
return (
<div
key={time}
className={cn("col-span-full flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-primary/30 bg-card p-1 pr-1.5 shadow-sm", animate && "motion-safe:animate-[chm-sp-expand_.32s_cubic-bezier(.2,.8,.2,1)]")}
>
{radio}
<span className="order-last min-w-0 basis-full px-2 pb-1 text-sm @lg:order-none @lg:flex-1 @lg:basis-auto @lg:p-0">
<span className="font-medium">{describe(time)}</span>
</span>
<button
ref={confirmRef}
type="button"
onClick={confirm}
className={cn(
"ml-auto inline-flex h-9 items-center gap-1.5 rounded-lg px-4 text-sm font-semibold transition-colors",
status === "done" ? "bg-emerald-600 text-white" : "bg-primary text-primary-foreground hover:opacity-90",
ring,
)}
>
{status === "saving" && <Loader2 className="size-4 motion-safe:animate-spin" aria-hidden="true" />}
{status === "done" && <Check className="size-4" aria-hidden="true" />}
{status === "done" ? "Booked" : "Confirm"}
</button>
</div>
);
})}
</div>
</div>
);
})}
</div>
)}
</div>
<p className="sr-only" role="status" aria-live="polite">{announce}</p>
</section>
);
}
