Try 'magnetic button'
View code

Specification

Catalogue
No. 57 of 110
Interaction
Drag
Element
Picker
Preview
Live component
Imports
react 19.3.1, @number-flow/react 0.6.2
Added

Notes

Pick a day, see the free gaps, and place a meeting of the length you need.

Booking is the action most service sites exist for. The visitor sees busy and free time at once, the chosen time is written out in words, and their own time zone is shown when it differs.

Tap a free gap to place the meeting; drag to move it; it snaps to 15 minutes and never overlaps busy time. Placed meeting is a slider: arrow keys step through the free starts. A row of free start times below; under 440px it replaces the rail. Visitor's own clock shown after mount when it differs from the host's. Sample availability; a real build reads it from the calendar (Cal.com or similar).

The names, figures and pictures in the demo are sample content; a real build uses the client's own.

Code

React and plain CSS
"use client";

import { useEffect, useId, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent } from "react";
import { useMounted, radioArrows } from "@/components/pieces/shared";
import type { LivePreviewProps } from "@/components/live/types";
import { PieceStage } from "@/components/pieces/stage/PieceStage";
import type { Tour } from "@/components/pieces/stage/tour";
import "@/components/pieces/kit/scroll-fade.css";
import "./slot-picker.css";

// Sample week, host in London. Busy blocks are minutes after 9:00.
const DAYS = [
  { id: "2026-12-01", short: "Tue", day: 1, long: "Tuesday 1 December", busy: [[0, 60], [150, 240], [330, 390]] },
  { id: "2026-12-02", short: "Wed", day: 2, long: "Wednesday 2 December", busy: [[60, 90], [240, 420]] },
  { id: "2026-12-03", short: "Thu", day: 3, long: "Thursday 3 December", busy: [[0, 180], [270, 300]] },
  { id: "2026-12-04", short: "Fri", day: 4, long: "Friday 4 December", busy: [[120, 150], [300, 480]] },
  { id: "2026-12-07", short: "Mon", day: 7, long: "Monday 7 December", busy: [[30, 120], [210, 270], [420, 480]] },
] as const;

const DAY_MIN = 480;

// 9:00 to 17:00
const STEP = 15;

const hhmm = (m: number) => {
  const t = 9 * 60 + m;
  return `${Math.floor(t / 60)}:${String(t % 60).padStart(2, "0")}`;
};

function freeStarts(busy: readonly (readonly [number, number])[], len: number): number[] {
  const out: number[] = [];
  for (let s = 0; s + len <= DAY_MIN; s += STEP) if (!busy.some(([a, b]) => s < b && s + len > a)) out.push(s);
  return out;
}

function nearest(starts: number[], m: number): number | null {
  if (!starts.length) return null;
  return starts.reduce((best, s) => (Math.abs(s - m) < Math.abs(best - m) ? s : best), starts[0]!);
}

/** The visitor's own clock for a London time, when it differs. */
function useVisitorTime(dayId: string, start: number | null): string | null {
  const mounted = useMounted();
  if (!mounted || start === null) return null;
  const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  const t = 9 * 60 + start;
  // December: London is on GMT, so London time is UTC.
  const utc = new Date(`${dayId}T${String(Math.floor(t / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}:00Z`);
  const local = new Intl.DateTimeFormat("en-GB", { hour: "numeric", minute: "2-digit", timeZone: zone }).format(utc);
  const london = new Intl.DateTimeFormat("en-GB", { hour: "numeric", minute: "2-digit", timeZone: "Europe/London" }).format(utc);
  return local === london ? null : `${local} your time (${zone.replace(/_/g, " ")})`;
}

function SlotPickerDemo() {
  const [dayIdx, setDayIdx] = useState(1);
  const [len, setLen] = useState(30);
  const [start, setStart] = useState<number | null>(null);
  const [sent, setSent] = useState(false);
  const track = useRef<HTMLDivElement>(null);
  const dragging = useRef<number | null>(null);
  const doneRef = useRef<HTMLElement>(null);
  const requestRef = useRef<HTMLButtonElement>(null);
  const moved = useRef(false);
  const day = DAYS[dayIdx]!;
  const starts = useMemo(() => freeStarts(day.busy, len), [day, len]);
  const visitor = useVisitorTime(day.id, start);
  const uid = useId();

  // The view swaps on send and on change: focus follows it instead of dropping to the page.
  useEffect(() => {
    if (!moved.current) return;
    if (sent) doneRef.current?.focus();
    else requestRef.current?.focus();
  }, [sent]);

  // Changing the day or length keeps the time if it still fits.
  const [seenStarts, setSeenStarts] = useState(starts);
  if (seenStarts !== starts) {
    setSeenStarts(starts);
    if (start !== null && !starts.includes(start)) setStart(null);
  }

  const minuteAt = (clientX: number) => {
    const r = track.current?.getBoundingClientRect();
    if (!r) return 0;
    return ((clientX - r.left) / r.width) * DAY_MIN - len / 2;
  };
  const onDown = (e: PointerEvent<HTMLDivElement>) => {
    const s = nearest(starts, minuteAt(e.clientX));
    if (s === null) return;
    setStart(s);
    dragging.current = e.pointerId;
    e.currentTarget.setPointerCapture(e.pointerId);
  };
  const onMove = (e: PointerEvent<HTMLDivElement>) => {
    if (dragging.current !== e.pointerId) return;
    const s = nearest(starts, minuteAt(e.clientX));
    if (s !== null) setStart(s);
  };
  const onSlotKey = (e: KeyboardEvent<HTMLDivElement>) => {
    if (start === null) return;
    const i = starts.indexOf(start);
    const map: Record<string, number> = { ArrowRight: i + 1, ArrowLeft: i - 1, ArrowUp: i + 1, ArrowDown: i - 1, Home: 0, End: starts.length - 1 };
    const n = map[e.key];
    if (n === undefined) return;
    e.preventDefault();
    setStart(starts[Math.min(starts.length - 1, Math.max(0, n))] ?? null);
  };

  if (sent && start !== null)
    return (
      <div className="dm">
        <div className="slot-done" role="status">
          <strong ref={doneRef} tabIndex={-1}>
            Request sent
          </strong>
          <p>
            {day.long}, {hhmm(start)} to {hhmm(start + len)} London time. The host confirms by email.
          </p>
          <button
            type="button"
            className="dm-btn"
            onClick={() => {
              moved.current = true;
              setSent(false);
            }}
          >
            Change the time
          </button>
        </div>
      </div>
    );

  return (
    <div className="dm">
      <div className="slot">
        <div className="slot-days" role="radiogroup" aria-label="Day" onKeyDown={radioArrows}>
          {DAYS.map((d, i) => (
            <button key={d.id} type="button" role="radio" aria-checked={i === dayIdx} aria-label={d.long} className="slot-day" onClick={() => setDayIdx(i)}>
              <span>{d.short}</span>
              <strong>{d.day}</strong>
            </button>
          ))}
        </div>
        <div className="slot-row">
          <span className="slot-label" id={`${uid}-len`}>
            Length
          </span>
          <div className="slot-lens" role="radiogroup" aria-labelledby={`${uid}-len`} onKeyDown={radioArrows}>
            {[20, 30, 45].map((m) => (
              <button key={m} type="button" role="radio" aria-checked={len === m} onClick={() => setLen(m)}>
                {m} min
              </button>
            ))}
          </div>
        </div>

        <div className="slot-track-wrap">
          <div ref={track} className="slot-track" onPointerDown={onDown} onPointerMove={onMove} onPointerUp={() => (dragging.current = null)}>
            {day.busy.map(([a, b]) => (
              <span key={a} className="slot-busy" style={{ left: `${(a / DAY_MIN) * 100}%`, width: `${((b - a) / DAY_MIN) * 100}%` }}>
                {b - a >= 60 ? "Busy" : ""}
              </span>
            ))}
            {start !== null && (
              <div
                className="slot-pick"
                role="slider"
                tabIndex={0}
                aria-label="Meeting time"
                aria-valuemin={starts[0]}
                aria-valuemax={starts[starts.length - 1]}
                aria-valuenow={start}
                aria-valuetext={`${hhmm(start)} to ${hhmm(start + len)}`}
                style={{ left: `${(start / DAY_MIN) * 100}%`, width: `${(len / DAY_MIN) * 100}%` }}
                onKeyDown={onSlotKey}
              />
            )}
          </div>
          <div className="slot-hours" aria-hidden="true">
            {["9", "11", "13", "15", "17"].map((h) => (
              <span key={h}>{h}:00</span>
            ))}
          </div>
        </div>

        <div className="slot-chips scroll-fade" role="radiogroup" aria-label="Free start times" onKeyDown={radioArrows}>
          {starts.length === 0 && <p className="dm-small">No free time this day</p>}
          {starts
            .filter((s) => s % 30 === 0)
            .map((s) => (
              <button key={s} type="button" role="radio" aria-checked={start === s} onClick={() => setStart(s)}>
                {hhmm(s)}
              </button>
            ))}
        </div>

        <div className="slot-foot">
          <p className="slot-when" aria-live="polite">
            {start === null ? (
              <>Tap a free time{starts.length ? "" : ", or try another day"}</>
            ) : (
              <>
                <strong>
                  {day.short} {day.day} Dec, {hhmm(start)} to {hhmm(start + len)}
                </strong>{" "}
                <span>London time{visitor ? `, ${visitor}` : ""}</span>
              </>
            )}
          </p>
          <button
            ref={requestRef}
            type="button"
            className="dm-btn"
            data-variant="solid"
            disabled={start === null}
            onClick={() => {
              moved.current = true;
              setSent(true);
            }}
          >
            Request
          </button>
        </div>
      </div>
    </div>
  );
}

// What a hovered card shows: the piece used the way a visitor would.
const TOUR: Tour = [
  { click: ".slot-day", nth: 2, wait: 900 },
  { click: ".slot-chips button", nth: 3, wait: 1600 },
];

export default function SlotPickerEntry(props: LivePreviewProps) {
  return (
    <PieceStage {...props} label="Booking rail with free times" sample tour={TOUR}>
      <SlotPickerDemo />
    </PieceStage>
  );
}

More like this

Time ruler you can fling

DragPickers and booking

Price range over the prices it filters

DragForms and inputs

Weekly hours editor

Press, Layout AnimationPickers and booking

Select with a gliding highlight

HoverForms and inputs

Tabs you can swipe

Drag, Layout AnimationTabs

Cookie choice that folds away

FeedbackOverlays and toasts