Skip to content
Shaken UI
Sign in

Time Picker

Save

A time field split into hours, minutes, optional seconds and AM/PM segments, with an optional list of slots that glides the chosen or current time into view.

Category
Forms
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Time Picker preview
Daily digest at
0830
Reserve the GPU queue
1400

Held for 15 minutes from 14:00

Installation

npx @shakenui/cli add time-picker

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add time-picker --dry-run

Usage

time-picker-example.tsx
"use client";

import { useState } from "react";
import { TimePicker } from "@/components/shaken/ui/time-picker";

// Slots already booked by other teams for the shared GPU queue.
const booked = ["10:30", "10:45", "13:00", "13:15", "13:30", "15:45"];

export default function TimePickerExample() {
  const [slot, setSlot] = useState<string | null>("14:00");

  return (
    <div className="flex flex-wrap items-start justify-center gap-6">
      <div className="grid gap-1.5">
        <span id="digest-label" className="text-sm font-medium text-zinc-950 dark:text-white">
          Daily digest at
        </span>
        <TimePicker aria-labelledby="digest-label" defaultValue="08:30" name="digestTime" />
      </div>
      <div className="grid gap-1.5">
        <span id="queue-label" className="text-sm font-medium text-zinc-950 dark:text-white">
          Reserve the GPU queue
        </span>
        <TimePicker
          aria-labelledby="queue-label"
          value={slot}
          onValueChange={setSlot}
          slotInterval={15}
          minTime="09:00"
          maxTime="18:00"
          disabledTimes={booked}
        />
        <p className="text-xs text-zinc-500">{slot ? `Held for 15 minutes from ${slot}` : "Pick a 15 minute slot"}</p>
      </div>
    </div>
  );
}

States

Every state, rendered from local fixture data.

Time Picker states
Empty
----
24-hour with seconds
031500
12-hour
0930AM
Slots every 30 minutes
1100
Outside working hours
2130
Disabled
1200

API

PropTypeDefaultDescription
value / defaultValue / onValueChangestring | null—The time as 24-hour "HH:mm" (or "HH:mm:ss" with showSeconds). onValueChange receives null once a segment is cleared.
hourCycle12 | 24—12 adds an AM/PM segment. Defaults to the locale's preference.
showSecondsbooleanfalseAdds a seconds segment.
slotIntervalnumber—Minutes between slots. Setting it adds a button that opens the slot list.
minTime / maxTimestring—Bounds as "HH:mm". The slot list starts and ends here; a typed time outside them marks the field invalid.
disabledTimes / isTimeDisabledstring[] / (time) => boolean—Times that cannot be picked, such as booked slots.
showNowbooleantrueDraws a line in the slot list at the current time.
invalid / disabledboolean—Error styling from outside, and turning the field off.
namestring—Submits the value with a hidden input.
aria-label / aria-labelledby / id / className / localestring—Names the field group, plus attributes, classes, and the locale for AM/PM and slot labels.
parseTime / toTimeStringfunctions—Exported helpers that read and write the HH:mm strings.

Accessibility

  • The field is a role="group" named by aria-label or aria-labelledby; each segment is a role="spinbutton" named Hours, Minutes, Seconds or AM/PM with aria-valuenow, min, max and a value text ("Empty" when blank).
  • Up and Down step a segment (Page Up and Page Down in larger steps), Left and Right move between segments, digits type a value and advance when it is complete, A and P set the period, Backspace clears a segment.
  • An out-of-range or disabled time sets aria-invalid on the group and shows in red text and border, not color alone.
  • The slot list is a role="listbox" that takes focus on open, with aria-activedescendant; Up, Down, Home, End, Page Up and Page Down move the active option (skipping disabled ones), Enter or Space picks it, Escape closes and focus returns to the button.
  • Disabled slots have aria-disabled and are struck through. The now line is decorative.
  • Opening glides the list over 380ms toward the selected or current time; with reduced motion it is placed at once. Keyboard moves inside the list never animate.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/time-picker.tsxtime-picker
  • Also installs popover@0.2.2registry dependency
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/time-picker/0.1.1.json.

ui/time-picker.tsxShow
ui/time-picker.tsx
"use client";

import { type KeyboardEvent, useEffect, useId, useMemo, useRef, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

// Times travel as 24-hour strings, "09:30" or "09:30:15", so they drop into forms and APIs as is.

export interface TimeParts {
  hours: number;
  minutes: number;
  seconds: number;
}

/** Reads "HH:mm" or "HH:mm:ss" (24-hour). Returns null for anything else. */
export function parseTime(value: string | null | undefined): TimeParts | null {
  const match = value ? /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(value.trim()) : null;
  if (!match) return null;
  const hours = Number(match[1]);
  const minutes = Number(match[2]);
  const seconds = Number(match[3] ?? 0);
  if (hours > 23 || minutes > 59 || seconds > 59) return null;
  return { hours, minutes, seconds };
}

const pad = (value: number) => String(value).padStart(2, "0");

/** Formats parts as "HH:mm", or "HH:mm:ss" with seconds. */
export function toTimeString(parts: TimeParts, withSeconds = false) {
  return `${pad(parts.hours)}:${pad(parts.minutes)}${withSeconds ? `:${pad(parts.seconds)}` : ""}`;
}

const toSeconds = (parts: TimeParts) => parts.hours * 3600 + parts.minutes * 60 + parts.seconds;

/** 12 or 24 from the locale's preferred hour cycle. */
function localeHourCycle(locale?: string): 12 | 24 {
  try {
    const cycle = new Intl.DateTimeFormat(locale, { hour: "numeric" }).resolvedOptions().hourCycle;
    return cycle === "h11" || cycle === "h12" ? 12 : 24;
  } catch {
    return 24;
  }
}

type Segment = "hours" | "minutes" | "seconds" | "period";
type Draft = { hours: number | null; minutes: number | null; seconds: number | null };

const EMPTY: Draft = { hours: null, minutes: null, seconds: null };

function toDraft(value: string | null | undefined): Draft {
  const parts = parseTime(value);
  return parts ? { ...parts } : EMPTY;
}

export interface TimePickerProps {
  /** The time as "HH:mm" (or "HH:mm:ss" with `showSeconds`), 24-hour. Null when empty. */
  value?: string | null;
  defaultValue?: string | null;
  /** Called with a complete time, or null once a segment is cleared. */
  onValueChange?: (value: string | null) => void;
  /** 12 shows an AM/PM segment. Defaults to the locale's preference. */
  hourCycle?: 12 | 24;
  /** Adds a seconds segment. */
  showSeconds?: boolean;
  /** BCP 47 locale for the AM/PM labels and the slot list. Defaults to the browser's. */
  locale?: string;
  /** Minutes between slots. Setting it adds a button that opens a list of times. */
  slotInterval?: number;
  /** Earliest valid time, "HH:mm". The slot list starts here. */
  minTime?: string;
  /** Latest valid time, "HH:mm". The slot list ends here. */
  maxTime?: string;
  /** Times that cannot be picked, "HH:mm". */
  disabledTimes?: string[];
  /** A predicate for times that cannot be picked. Receives "HH:mm". */
  isTimeDisabled?: (time: string) => boolean;
  /** Draws a line in the slot list at the current time. */
  showNow?: boolean;
  /** Turns the whole field off. */
  disabled?: boolean;
  /** Marks the field invalid from outside, for example after server validation. */
  invalid?: boolean;
  /** Submits the value under this name with a hidden input. */
  name?: string;
  /** Labels the field group. Pair with a visible label through `aria-labelledby` where you can. */
  "aria-label"?: string;
  "aria-labelledby"?: string;
  id?: string;
  className?: string;
}

/**
 * A time field split into segments (hours, minutes, optional seconds, AM/PM by locale). Each
 * segment is a spinbutton: type digits, or use the arrow keys; Left and Right move between them,
 * Backspace clears one. With `slotInterval` a list of times opens beside it and glides the
 * selected time, or the current time, into the middle of the list.
 */
export function TimePicker({
  value: valueProp,
  defaultValue,
  onValueChange,
  hourCycle: hourCycleProp,
  showSeconds = false,
  locale,
  slotInterval,
  minTime,
  maxTime,
  disabledTimes,
  isTimeDisabled,
  showNow = true,
  disabled = false,
  invalid: invalidProp = false,
  name,
  id,
  className,
  ...aria
}: TimePickerProps) {
  const [hourCycle, setHourCycle] = useState<12 | 24>(hourCycleProp ?? 24);
  useEffect(() => setHourCycle(hourCycleProp ?? localeHourCycle(locale)), [hourCycleProp, locale]);

  const [draft, setDraft] = useState<Draft>(() => toDraft(valueProp !== undefined ? valueProp : defaultValue));
  // AM or PM picked before the hour is typed.
  const [pendingPm, setPendingPm] = useState(false);
  const lastEmitted = useRef<string | null>(valueProp ?? defaultValue ?? null);

  // A controlled value that changes from outside replaces the draft.
  useEffect(() => {
    if (valueProp === undefined || valueProp === lastEmitted.current) return;
    lastEmitted.current = valueProp;
    setDraft(toDraft(valueProp));
  }, [valueProp]);

  const segments: Segment[] = ["hours", "minutes", ...(showSeconds ? (["seconds"] as const) : []), ...(hourCycle === 12 ? (["period"] as const) : [])];
  const refs = useRef<Partial<Record<Segment, HTMLSpanElement | null>>>({});
  const typed = useRef<{ segment: Segment | null; text: string; at: number }>({ segment: null, text: "", at: 0 });

  const complete = draft.hours !== null && draft.minutes !== null && (!showSeconds || draft.seconds !== null);
  const current = complete ? toTimeString({ hours: draft.hours!, minutes: draft.minutes!, seconds: draft.seconds ?? 0 }, showSeconds) : null;
  const isPm = draft.hours !== null ? draft.hours >= 12 : pendingPm;

  const disabledSet = useMemo(() => new Set(disabledTimes ?? []), [disabledTimes]);
  const min = parseTime(minTime);
  const max = parseTime(maxTime);

  function blocked(time: string) {
    const parts = parseTime(time);
    if (!parts) return false;
    if (min && toSeconds(parts) < toSeconds(min)) return true;
    if (max && toSeconds(parts) > toSeconds(max)) return true;
    return disabledSet.has(time.slice(0, 5)) || (isTimeDisabled?.(time.slice(0, 5)) ?? false);
  }

  const invalid = invalidProp || (current !== null && blocked(current));

  function commit(next: Draft) {
    setDraft(next);
    const done = next.hours !== null && next.minutes !== null && (!showSeconds || next.seconds !== null);
    const out = done ? toTimeString({ hours: next.hours!, minutes: next.minutes!, seconds: next.seconds ?? 0 }, showSeconds) : null;
    if (out === lastEmitted.current) return;
    lastEmitted.current = out;
    onValueChange?.(out);
  }

  function focusSegment(segment: Segment | undefined) {
    if (segment) refs.current[segment]?.focus();
  }

  function step(segment: Segment, delta: number) {
    if (segment === "period") {
      togglePeriod();
      return;
    }
    const limit = segment === "hours" ? 24 : 60;
    const now = draft[segment];
    let next: number;
    if (segment === "hours" && hourCycle === 12) {
      // Step the 12-hour face (12, 1, ... 11) and keep the period.
      const face = now === null ? null : now % 12;
      const base = face === null ? (delta > 0 ? 0 : 11) : (face + delta + 12) % 12;
      next = base + (isPm ? 12 : 0);
    } else {
      next = now === null ? (delta > 0 ? 0 : limit - 1) : (now + delta + limit) % limit;
    }
    commit({ ...draft, [segment]: next });
  }

  function togglePeriod(toPm?: boolean) {
    const pm = toPm ?? !isPm;
    if (draft.hours === null) {
      setPendingPm(pm);
      return;
    }
    const face = draft.hours % 12;
    commit({ ...draft, hours: face + (pm ? 12 : 0) });
  }

  function typeDigit(segment: Exclude<Segment, "period">, digit: number) {
    const now = Date.now();
    const buffer = typed.current.segment === segment && now - typed.current.at < 1200 ? typed.current.text : "";
    const text = buffer + digit;
    const twelve = segment === "hours" && hourCycle === 12;
    const maxValue = segment === "hours" ? (twelve ? 12 : 23) : 59;
    let number = Number(text);
    let advance = false;
    if (text.length >= 2 || number * 10 > maxValue) {
      if (number > maxValue) number = digit;
      advance = true;
    }
    if (twelve && advance && number === 0) number = 12;
    let stored = number;
    if (twelve) stored = (number % 12) + (isPm ? 12 : 0);
    typed.current = advance ? { segment: null, text: "", at: 0 } : { segment, text, at: now };
    commit({ ...draft, [segment]: stored });
    if (advance) focusSegment(segments[segments.indexOf(segment) + 1]);
  }

  function onSegmentKeyDown(segment: Segment, event: KeyboardEvent<HTMLSpanElement>) {
    if (disabled) return;
    const index = segments.indexOf(segment);
    const key = event.key;
    if (key === "ArrowUp" || key === "ArrowDown") {
      event.preventDefault();
      step(segment, key === "ArrowUp" ? 1 : -1);
    } else if (key === "PageUp" || key === "PageDown") {
      event.preventDefault();
      if (segment !== "period") step(segment, (key === "PageUp" ? 1 : -1) * (segment === "hours" ? 2 : 10));
    } else if (key === "ArrowLeft" || key === "ArrowRight") {
      event.preventDefault();
      focusSegment(segments[index + (key === "ArrowLeft" ? -1 : 1)]);
    } else if (key === "Backspace" || key === "Delete") {
      event.preventDefault();
      typed.current = { segment: null, text: "", at: 0 };
      if (segment === "period") return;
      if (draft[segment] === null) focusSegment(segments[index - 1]);
      else commit({ ...draft, [segment]: null });
    } else if (/^\d$/.test(key) && segment !== "period") {
      event.preventDefault();
      typeDigit(segment, Number(key));
    } else if (segment === "period" && /^[ap]$/i.test(key)) {
      event.preventDefault();
      togglePeriod(key.toLowerCase() === "p");
    } else if (segment === "period" && (key === " " || key === "Enter")) {
      event.preventDefault();
      togglePeriod();
    } else if (key === ":" || key === "." || key === "/") {
      event.preventDefault();
      focusSegment(segments[index + 1]);
    }
  }

  const periodLabels = useMemo(() => {
    try {
      const format = new Intl.DateTimeFormat(locale, { hour: "numeric", hourCycle: "h12" });
      const label = (hour: number) => format.formatToParts(new Date(2026, 0, 1, hour)).find((part) => part.type === "dayPeriod")?.value;
      return { am: label(9) ?? "AM", pm: label(21) ?? "PM" };
    } catch {
      return { am: "AM", pm: "PM" };
    }
  }, [locale]);

  function display(segment: Segment) {
    if (segment === "period") return isPm ? periodLabels.pm : periodLabels.am;
    const value = draft[segment];
    if (value === null) return "--";
    if (segment === "hours" && hourCycle === 12) return pad(value % 12 || 12);
    return pad(value);
  }

  const labels: Record<Segment, string> = { hours: "Hours", minutes: "Minutes", seconds: "Seconds", period: "AM/PM" };

  return (
    <div
      id={id}
      role="group"
      aria-label={aria["aria-label"]}
      aria-labelledby={aria["aria-labelledby"]}
      aria-disabled={disabled || undefined}
      aria-invalid={invalid || undefined}
      data-slot="time-picker"
      className={cx(
        "inline-flex h-9 items-center gap-0.5 rounded-lg border bg-white ps-2 text-sm text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
        "dark:bg-black dark:text-white dark:shadow-none",
        "transition-[border-color] duration-150 ease-out motion-reduce:transition-none",
        invalid
          ? "border-red-500/50 dark:border-red-500/50"
          : "border-zinc-950/12 hover:border-zinc-950/20 focus-within:border-zinc-950/25 dark:border-white/15 dark:hover:border-white/25 dark:focus-within:border-white/30",
        slotInterval ? "pe-1" : "pe-2",
        disabled && "pointer-events-none opacity-45",
        className,
      )}
    >
      <ClockGlyph className="me-1 size-4 shrink-0 text-zinc-500" />
      {segments.map((segment, index) => {
        const value = segment === "period" ? (isPm ? 1 : 0) : draft[segment];
        const empty = segment !== "period" && value === null;
        const twelve = segment === "hours" && hourCycle === 12;
        return (
          <span key={segment} className="contents">
            {index > 0 && segment !== "period" ? (
              <span aria-hidden="true" className="text-zinc-400 dark:text-zinc-600">
                :
              </span>
            ) : null}
            <span
              ref={(node) => {
                refs.current[segment] = node;
              }}
              role="spinbutton"
              tabIndex={disabled ? -1 : 0}
              aria-label={labels[segment]}
              aria-valuemin={segment === "period" ? 0 : twelve ? 1 : 0}
              aria-valuemax={segment === "period" ? 1 : segment === "hours" ? (twelve ? 12 : 23) : 59}
              aria-valuenow={empty ? undefined : segment === "hours" && twelve ? (draft.hours! % 12 || 12) : (value as number)}
              aria-valuetext={empty ? "Empty" : display(segment)}
              onKeyDown={(event) => onSegmentKeyDown(segment, event)}
              onBlur={() => {
                typed.current = { segment: null, text: "", at: 0 };
              }}
              className={cx(
                "rounded-[5px] px-[3px] py-0.5 text-center tabular-nums outline-hidden select-none",
                segment === "period" ? "ms-1 min-w-[2.5ch]" : "min-w-[2.4ch]",
                "transition-[background-color,color] duration-100 ease-out motion-reduce:transition-none",
                "caret-transparent focus:bg-zinc-950 focus:text-white dark:focus:bg-white dark:focus:text-black",
                empty ? "text-zinc-400 dark:text-zinc-600" : invalid ? "text-red-600 dark:text-red-400" : "text-zinc-950 dark:text-white",
              )}
            >
              {display(segment)}
            </span>
          </span>
        );
      })}
      {name ? <input type="hidden" name={name} value={current ?? ""} /> : null}
      {slotInterval ? (
        <SlotMenu
          interval={slotInterval}
          value={current}
          showSeconds={showSeconds}
          hourCycle={hourCycle}
          locale={locale}
          min={min}
          max={max}
          blocked={blocked}
          showNow={showNow}
          disabled={disabled}
          onPick={(time) => commit(toDraft(time))}
        />
      ) : null}
    </div>
  );
}

const ROW = 32;

function SlotMenu({
  interval,
  value,
  showSeconds,
  hourCycle,
  locale,
  min,
  max,
  blocked,
  showNow,
  disabled,
  onPick,
}: {
  interval: number;
  value: string | null;
  showSeconds: boolean;
  hourCycle: 12 | 24;
  locale?: string;
  min: TimeParts | null;
  max: TimeParts | null;
  blocked: (time: string) => boolean;
  showNow: boolean;
  disabled: boolean;
  onPick: (time: string) => void;
}) {
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(0);
  const [now, setNow] = useState<number | null>(null);
  const listRef = useRef<HTMLDivElement | null>(null);
  // The list mounts a render after `open` flips (it lives in a portal), so the glide waits for it.
  const [listNode, setListNode] = useState<HTMLDivElement | null>(null);
  const listId = `time-slots${useId().replace(/:/g, "")}`;

  const startMinute = min ? min.hours * 60 + min.minutes : 0;
  const endMinute = max ? max.hours * 60 + max.minutes : 24 * 60 - 1;
  const slots = useMemo(() => {
    const out: { time: string; minute: number }[] = [];
    const stepBy = Math.max(1, Math.round(interval));
    for (let minute = startMinute; minute <= endMinute; minute += stepBy) {
      out.push({ time: toTimeString({ hours: Math.floor(minute / 60), minutes: minute % 60, seconds: 0 }), minute });
    }
    return out;
  }, [interval, startMinute, endMinute]);

  const format = useMemo(
    () => new Intl.DateTimeFormat(locale, { hour: "numeric", minute: "2-digit", hourCycle: hourCycle === 12 ? "h12" : "h23" }),
    [locale, hourCycle],
  );

  const selectedIndex = value ? slots.findIndex((slot) => slot.time === value.slice(0, 5)) : -1;

  function nearest(minute: number) {
    let best = 0;
    slots.forEach((slot, index) => {
      if (Math.abs(slot.minute - minute) < Math.abs(slots[best]!.minute - minute)) best = index;
    });
    return best;
  }

  function enabledFrom(index: number, direction: 1 | -1) {
    for (let i = index; i >= 0 && i < slots.length; i += direction) if (!blocked(slots[i]!.time)) return i;
    return null;
  }

  function onOpenChange(next: boolean) {
    if (next) {
      const date = new Date();
      const minute = date.getHours() * 60 + date.getMinutes();
      setNow(minute);
      const valueMinute = value ? Number(value.slice(0, 2)) * 60 + Number(value.slice(3, 5)) : null;
      const start = selectedIndex >= 0 ? selectedIndex : nearest(valueMinute ?? minute);
      setActive(enabledFrom(start, 1) ?? enabledFrom(start, -1) ?? start);
    }
    setOpen(next);
  }

  // Opening lands a few rows short of the target, then glides the rest of the way so the eye
  // can follow where it settled. Reduced motion places it at once.
  useEffect(() => {
    const list = listNode;
    if (!open || !list) return;
    const target = Math.max(0, active * ROW + ROW / 2 - list.clientHeight / 2 + 4);
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    if (reduce) {
      list.scrollTop = target;
      return;
    }
    // A short quint ease-out driven by hand: native smooth scrolling gets cut off when the popup
    // moves focus into the list.
    const from = Math.max(0, target - ROW * 3);
    list.scrollTop = from;
    const start = performance.now();
    let frame = 0;
    const tick = (now: number) => {
      const t = Math.min(1, (now - start) / 380);
      list.scrollTop = from + (target - from) * (1 - (1 - t) ** 5);
      if (t < 1) frame = requestAnimationFrame(tick);
    };
    frame = requestAnimationFrame(tick);
    const stop = () => cancelAnimationFrame(frame);
    list.addEventListener("wheel", stop, { once: true, passive: true });
    list.addEventListener("pointerdown", stop, { once: true });
    return () => {
      stop();
      list.removeEventListener("wheel", stop);
      list.removeEventListener("pointerdown", stop);
    };
    // Only on open: keyboard moves scroll the active row into view on their own, without gliding.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [open, listNode]);

  function moveTo(index: number) {
    setActive(index);
    const list = listRef.current;
    const row = list?.querySelector<HTMLElement>(`[data-index="${index}"]`);
    row?.scrollIntoView({ block: "nearest" });
  }

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    const moves: Record<string, () => number | null> = {
      ArrowDown: () => enabledFrom(active + 1, 1),
      ArrowUp: () => enabledFrom(active - 1, -1),
      PageDown: () => enabledFrom(Math.min(slots.length - 1, active + Math.round(60 / interval)), 1) ?? enabledFrom(slots.length - 1, -1),
      PageUp: () => enabledFrom(Math.max(0, active - Math.round(60 / interval)), -1) ?? enabledFrom(0, 1),
      Home: () => enabledFrom(0, 1),
      End: () => enabledFrom(slots.length - 1, -1),
    };
    if (moves[event.key]) {
      event.preventDefault();
      const next = moves[event.key]!();
      if (next !== null) moveTo(next);
      return;
    }
    if (event.key === "Enter" || event.key === " ") {
      event.preventDefault();
      const slot = slots[active];
      if (slot && !blocked(slot.time)) {
        onPick(showSeconds ? `${slot.time}:00` : slot.time);
        setOpen(false);
      }
    }
  }

  // The current time as a y offset between rows.
  const nowOffset =
    showNow && now !== null && now >= startMinute && now <= endMinute ? ((now - startMinute) / Math.max(1, interval)) * ROW + ROW / 2 : null;

  return (
    <Popover open={open} onOpenChange={onOpenChange}>
      <PopoverTrigger
        disabled={disabled}
        aria-label="Show times"
        className={cx(
          "ms-auto inline-flex size-7 shrink-0 items-center justify-center rounded-md text-zinc-500",
          "transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
          "hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white",
          "data-[popup-open]:bg-zinc-950/[0.06] data-[popup-open]:text-zinc-950 dark:data-[popup-open]:bg-white/[0.09] dark:data-[popup-open]:text-white",
          "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500",
        )}
      >
        <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
          <path d="M4.5 6.5 8 10l3.5-3.5" />
        </svg>
      </PopoverTrigger>
      <PopoverContent align="end" sideOffset={6} initialFocus={listRef} className="w-44 p-0">
        <div
          ref={(node) => {
            listRef.current = node;
            setListNode(node);
          }}
          id={listId}
          role="listbox"
          tabIndex={0}
          aria-label="Times"
          aria-activedescendant={`${listId}-${active}`}
          onKeyDown={onKeyDown}
          className="relative max-h-64 overflow-y-auto overscroll-contain rounded-xl p-1 outline-hidden [scrollbar-width:thin] [mask-image:linear-gradient(transparent,black_10px,black_calc(100%-10px),transparent)] focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500"
        >
          {/* The rail: a hairline with a tick per slot, longer on the hour. */}
          <div aria-hidden="true" className="pointer-events-none absolute top-1 bottom-1 left-[19px] w-px bg-zinc-950/[0.07] dark:bg-white/[0.08]" style={{ height: slots.length * ROW }} />
          {nowOffset !== null ? (
            <div aria-hidden="true" className="pointer-events-none absolute inset-x-1 z-[1] flex items-center" style={{ top: 4 + nowOffset }}>
              <span className="ms-[12px] size-[7px] -translate-y-1/2 rounded-full border-[1.5px] border-white bg-sky-500 dark:border-black" />
              <span className="h-px flex-1 -translate-y-1/2 bg-sky-500/45" />
            </div>
          ) : null}
          {slots.map((slot, index) => {
            const isBlocked = blocked(slot.time);
            const selected = index === selectedIndex;
            const onHour = slot.minute % 60 === 0;
            return (
              <div
                key={slot.time}
                id={`${listId}-${index}`}
                data-index={index}
                role="option"
                aria-selected={selected}
                aria-disabled={isBlocked || undefined}
                onPointerMove={() => !isBlocked && active !== index && setActive(index)}
                onClick={() => {
                  if (isBlocked) return;
                  onPick(showSeconds ? `${slot.time}:00` : slot.time);
                  setOpen(false);
                }}
                className={cx(
                  "relative flex h-8 items-center gap-3 rounded-md ps-[34px] pe-2 text-sm tabular-nums",
                  "transition-[background-color,color] duration-100 ease-out motion-reduce:transition-none",
                  isBlocked
                    ? "cursor-not-allowed text-zinc-400 line-through decoration-zinc-950/25 dark:text-zinc-600 dark:decoration-white/25"
                    : selected
                      ? "cursor-default bg-zinc-950 font-medium text-white dark:bg-white dark:text-black"
                      : cx(
                          "cursor-default",
                          index === active ? "bg-zinc-950/[0.05] text-zinc-950 dark:bg-white/[0.08] dark:text-white" : "text-zinc-700 dark:text-zinc-300",
                        ),
                )}
              >
                <span
                  aria-hidden="true"
                  className={cx(
                    "absolute top-1/2 h-px -translate-y-1/2",
                    onHour ? "left-[11px] w-[9px]" : "left-[15px] w-[5px]",
                    selected ? "bg-white/50 dark:bg-black/40" : "bg-zinc-950/20 dark:bg-white/25",
                  )}
                />
                {format.format(new Date(2026, 0, 1, Math.floor(slot.minute / 60), slot.minute % 60))}
                {selected ? (
                  <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="ms-auto size-3.5">
                    <path d="m3.5 8.5 3 3 6-7" />
                  </svg>
                ) : null}
              </div>
            );
          })}
        </div>
      </PopoverContent>
    </Popover>
  );
}

function ClockGlyph({ className }: { className?: string }) {
  return (
    <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" className={className}>
      <circle cx="8" cy="8" r="5.75" />
      <path d="M8 5v3l2 1.25" />
    </svg>
  );
}