{
  "schemaVersion": 1,
  "target": "react",
  "name": "time-picker",
  "version": "0.1.1",
  "category": "forms",
  "title": "Time Picker",
  "description": "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.",
  "tags": [
    "time",
    "picker",
    "field",
    "slots",
    "form",
    "popover"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [
    {
      "name": "popover",
      "version": "0.2.2"
    }
  ],
  "docsPath": "/components/time-picker",
  "props": [
    {
      "name": "value / defaultValue / onValueChange",
      "type": "string | null",
      "description": "The time as 24-hour \"HH:mm\" (or \"HH:mm:ss\" with showSeconds). onValueChange receives null once a segment is cleared."
    },
    {
      "name": "hourCycle",
      "type": "12 | 24",
      "description": "12 adds an AM/PM segment. Defaults to the locale's preference."
    },
    {
      "name": "showSeconds",
      "type": "boolean",
      "default": "false",
      "description": "Adds a seconds segment."
    },
    {
      "name": "slotInterval",
      "type": "number",
      "description": "Minutes between slots. Setting it adds a button that opens the slot list."
    },
    {
      "name": "minTime / maxTime",
      "type": "string",
      "description": "Bounds as \"HH:mm\". The slot list starts and ends here; a typed time outside them marks the field invalid."
    },
    {
      "name": "disabledTimes / isTimeDisabled",
      "type": "string[] / (time) => boolean",
      "description": "Times that cannot be picked, such as booked slots."
    },
    {
      "name": "showNow",
      "type": "boolean",
      "default": "true",
      "description": "Draws a line in the slot list at the current time."
    },
    {
      "name": "invalid / disabled",
      "type": "boolean",
      "description": "Error styling from outside, and turning the field off."
    },
    {
      "name": "name",
      "type": "string",
      "description": "Submits the value with a hidden input."
    },
    {
      "name": "aria-label / aria-labelledby / id / className / locale",
      "type": "string",
      "description": "Names the field group, plus attributes, classes, and the locale for AM/PM and slot labels."
    },
    {
      "name": "parseTime / toTimeString",
      "type": "functions",
      "description": "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."
  ],
  "states": [
    "empty",
    "filled",
    "12-hour",
    "with seconds",
    "invalid",
    "disabled",
    "slot list open"
  ],
  "files": [
    {
      "path": "ui/time-picker.tsx",
      "content": "\"use client\";\n\nimport { type KeyboardEvent, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"./popover\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\n// Times travel as 24-hour strings, \"09:30\" or \"09:30:15\", so they drop into forms and APIs as is.\n\nexport interface TimeParts {\n  hours: number;\n  minutes: number;\n  seconds: number;\n}\n\n/** Reads \"HH:mm\" or \"HH:mm:ss\" (24-hour). Returns null for anything else. */\nexport function parseTime(value: string | null | undefined): TimeParts | null {\n  const match = value ? /^(\\d{1,2}):(\\d{2})(?::(\\d{2}))?$/.exec(value.trim()) : null;\n  if (!match) return null;\n  const hours = Number(match[1]);\n  const minutes = Number(match[2]);\n  const seconds = Number(match[3] ?? 0);\n  if (hours > 23 || minutes > 59 || seconds > 59) return null;\n  return { hours, minutes, seconds };\n}\n\nconst pad = (value: number) => String(value).padStart(2, \"0\");\n\n/** Formats parts as \"HH:mm\", or \"HH:mm:ss\" with seconds. */\nexport function toTimeString(parts: TimeParts, withSeconds = false) {\n  return `${pad(parts.hours)}:${pad(parts.minutes)}${withSeconds ? `:${pad(parts.seconds)}` : \"\"}`;\n}\n\nconst toSeconds = (parts: TimeParts) => parts.hours * 3600 + parts.minutes * 60 + parts.seconds;\n\n/** 12 or 24 from the locale's preferred hour cycle. */\nfunction localeHourCycle(locale?: string): 12 | 24 {\n  try {\n    const cycle = new Intl.DateTimeFormat(locale, { hour: \"numeric\" }).resolvedOptions().hourCycle;\n    return cycle === \"h11\" || cycle === \"h12\" ? 12 : 24;\n  } catch {\n    return 24;\n  }\n}\n\ntype Segment = \"hours\" | \"minutes\" | \"seconds\" | \"period\";\ntype Draft = { hours: number | null; minutes: number | null; seconds: number | null };\n\nconst EMPTY: Draft = { hours: null, minutes: null, seconds: null };\n\nfunction toDraft(value: string | null | undefined): Draft {\n  const parts = parseTime(value);\n  return parts ? { ...parts } : EMPTY;\n}\n\nexport interface TimePickerProps {\n  /** The time as \"HH:mm\" (or \"HH:mm:ss\" with `showSeconds`), 24-hour. Null when empty. */\n  value?: string | null;\n  defaultValue?: string | null;\n  /** Called with a complete time, or null once a segment is cleared. */\n  onValueChange?: (value: string | null) => void;\n  /** 12 shows an AM/PM segment. Defaults to the locale's preference. */\n  hourCycle?: 12 | 24;\n  /** Adds a seconds segment. */\n  showSeconds?: boolean;\n  /** BCP 47 locale for the AM/PM labels and the slot list. Defaults to the browser's. */\n  locale?: string;\n  /** Minutes between slots. Setting it adds a button that opens a list of times. */\n  slotInterval?: number;\n  /** Earliest valid time, \"HH:mm\". The slot list starts here. */\n  minTime?: string;\n  /** Latest valid time, \"HH:mm\". The slot list ends here. */\n  maxTime?: string;\n  /** Times that cannot be picked, \"HH:mm\". */\n  disabledTimes?: string[];\n  /** A predicate for times that cannot be picked. Receives \"HH:mm\". */\n  isTimeDisabled?: (time: string) => boolean;\n  /** Draws a line in the slot list at the current time. */\n  showNow?: boolean;\n  /** Turns the whole field off. */\n  disabled?: boolean;\n  /** Marks the field invalid from outside, for example after server validation. */\n  invalid?: boolean;\n  /** Submits the value under this name with a hidden input. */\n  name?: string;\n  /** Labels the field group. Pair with a visible label through `aria-labelledby` where you can. */\n  \"aria-label\"?: string;\n  \"aria-labelledby\"?: string;\n  id?: string;\n  className?: string;\n}\n\n/**\n * A time field split into segments (hours, minutes, optional seconds, AM/PM by locale). Each\n * segment is a spinbutton: type digits, or use the arrow keys; Left and Right move between them,\n * Backspace clears one. With `slotInterval` a list of times opens beside it and glides the\n * selected time, or the current time, into the middle of the list.\n */\nexport function TimePicker({\n  value: valueProp,\n  defaultValue,\n  onValueChange,\n  hourCycle: hourCycleProp,\n  showSeconds = false,\n  locale,\n  slotInterval,\n  minTime,\n  maxTime,\n  disabledTimes,\n  isTimeDisabled,\n  showNow = true,\n  disabled = false,\n  invalid: invalidProp = false,\n  name,\n  id,\n  className,\n  ...aria\n}: TimePickerProps) {\n  const [hourCycle, setHourCycle] = useState<12 | 24>(hourCycleProp ?? 24);\n  useEffect(() => setHourCycle(hourCycleProp ?? localeHourCycle(locale)), [hourCycleProp, locale]);\n\n  const [draft, setDraft] = useState<Draft>(() => toDraft(valueProp !== undefined ? valueProp : defaultValue));\n  // AM or PM picked before the hour is typed.\n  const [pendingPm, setPendingPm] = useState(false);\n  const lastEmitted = useRef<string | null>(valueProp ?? defaultValue ?? null);\n\n  // A controlled value that changes from outside replaces the draft.\n  useEffect(() => {\n    if (valueProp === undefined || valueProp === lastEmitted.current) return;\n    lastEmitted.current = valueProp;\n    setDraft(toDraft(valueProp));\n  }, [valueProp]);\n\n  const segments: Segment[] = [\"hours\", \"minutes\", ...(showSeconds ? ([\"seconds\"] as const) : []), ...(hourCycle === 12 ? ([\"period\"] as const) : [])];\n  const refs = useRef<Partial<Record<Segment, HTMLSpanElement | null>>>({});\n  const typed = useRef<{ segment: Segment | null; text: string; at: number }>({ segment: null, text: \"\", at: 0 });\n\n  const complete = draft.hours !== null && draft.minutes !== null && (!showSeconds || draft.seconds !== null);\n  const current = complete ? toTimeString({ hours: draft.hours!, minutes: draft.minutes!, seconds: draft.seconds ?? 0 }, showSeconds) : null;\n  const isPm = draft.hours !== null ? draft.hours >= 12 : pendingPm;\n\n  const disabledSet = useMemo(() => new Set(disabledTimes ?? []), [disabledTimes]);\n  const min = parseTime(minTime);\n  const max = parseTime(maxTime);\n\n  function blocked(time: string) {\n    const parts = parseTime(time);\n    if (!parts) return false;\n    if (min && toSeconds(parts) < toSeconds(min)) return true;\n    if (max && toSeconds(parts) > toSeconds(max)) return true;\n    return disabledSet.has(time.slice(0, 5)) || (isTimeDisabled?.(time.slice(0, 5)) ?? false);\n  }\n\n  const invalid = invalidProp || (current !== null && blocked(current));\n\n  function commit(next: Draft) {\n    setDraft(next);\n    const done = next.hours !== null && next.minutes !== null && (!showSeconds || next.seconds !== null);\n    const out = done ? toTimeString({ hours: next.hours!, minutes: next.minutes!, seconds: next.seconds ?? 0 }, showSeconds) : null;\n    if (out === lastEmitted.current) return;\n    lastEmitted.current = out;\n    onValueChange?.(out);\n  }\n\n  function focusSegment(segment: Segment | undefined) {\n    if (segment) refs.current[segment]?.focus();\n  }\n\n  function step(segment: Segment, delta: number) {\n    if (segment === \"period\") {\n      togglePeriod();\n      return;\n    }\n    const limit = segment === \"hours\" ? 24 : 60;\n    const now = draft[segment];\n    let next: number;\n    if (segment === \"hours\" && hourCycle === 12) {\n      // Step the 12-hour face (12, 1, ... 11) and keep the period.\n      const face = now === null ? null : now % 12;\n      const base = face === null ? (delta > 0 ? 0 : 11) : (face + delta + 12) % 12;\n      next = base + (isPm ? 12 : 0);\n    } else {\n      next = now === null ? (delta > 0 ? 0 : limit - 1) : (now + delta + limit) % limit;\n    }\n    commit({ ...draft, [segment]: next });\n  }\n\n  function togglePeriod(toPm?: boolean) {\n    const pm = toPm ?? !isPm;\n    if (draft.hours === null) {\n      setPendingPm(pm);\n      return;\n    }\n    const face = draft.hours % 12;\n    commit({ ...draft, hours: face + (pm ? 12 : 0) });\n  }\n\n  function typeDigit(segment: Exclude<Segment, \"period\">, digit: number) {\n    const now = Date.now();\n    const buffer = typed.current.segment === segment && now - typed.current.at < 1200 ? typed.current.text : \"\";\n    const text = buffer + digit;\n    const twelve = segment === \"hours\" && hourCycle === 12;\n    const maxValue = segment === \"hours\" ? (twelve ? 12 : 23) : 59;\n    let number = Number(text);\n    let advance = false;\n    if (text.length >= 2 || number * 10 > maxValue) {\n      if (number > maxValue) number = digit;\n      advance = true;\n    }\n    if (twelve && advance && number === 0) number = 12;\n    let stored = number;\n    if (twelve) stored = (number % 12) + (isPm ? 12 : 0);\n    typed.current = advance ? { segment: null, text: \"\", at: 0 } : { segment, text, at: now };\n    commit({ ...draft, [segment]: stored });\n    if (advance) focusSegment(segments[segments.indexOf(segment) + 1]);\n  }\n\n  function onSegmentKeyDown(segment: Segment, event: KeyboardEvent<HTMLSpanElement>) {\n    if (disabled) return;\n    const index = segments.indexOf(segment);\n    const key = event.key;\n    if (key === \"ArrowUp\" || key === \"ArrowDown\") {\n      event.preventDefault();\n      step(segment, key === \"ArrowUp\" ? 1 : -1);\n    } else if (key === \"PageUp\" || key === \"PageDown\") {\n      event.preventDefault();\n      if (segment !== \"period\") step(segment, (key === \"PageUp\" ? 1 : -1) * (segment === \"hours\" ? 2 : 10));\n    } else if (key === \"ArrowLeft\" || key === \"ArrowRight\") {\n      event.preventDefault();\n      focusSegment(segments[index + (key === \"ArrowLeft\" ? -1 : 1)]);\n    } else if (key === \"Backspace\" || key === \"Delete\") {\n      event.preventDefault();\n      typed.current = { segment: null, text: \"\", at: 0 };\n      if (segment === \"period\") return;\n      if (draft[segment] === null) focusSegment(segments[index - 1]);\n      else commit({ ...draft, [segment]: null });\n    } else if (/^\\d$/.test(key) && segment !== \"period\") {\n      event.preventDefault();\n      typeDigit(segment, Number(key));\n    } else if (segment === \"period\" && /^[ap]$/i.test(key)) {\n      event.preventDefault();\n      togglePeriod(key.toLowerCase() === \"p\");\n    } else if (segment === \"period\" && (key === \" \" || key === \"Enter\")) {\n      event.preventDefault();\n      togglePeriod();\n    } else if (key === \":\" || key === \".\" || key === \"/\") {\n      event.preventDefault();\n      focusSegment(segments[index + 1]);\n    }\n  }\n\n  const periodLabels = useMemo(() => {\n    try {\n      const format = new Intl.DateTimeFormat(locale, { hour: \"numeric\", hourCycle: \"h12\" });\n      const label = (hour: number) => format.formatToParts(new Date(2026, 0, 1, hour)).find((part) => part.type === \"dayPeriod\")?.value;\n      return { am: label(9) ?? \"AM\", pm: label(21) ?? \"PM\" };\n    } catch {\n      return { am: \"AM\", pm: \"PM\" };\n    }\n  }, [locale]);\n\n  function display(segment: Segment) {\n    if (segment === \"period\") return isPm ? periodLabels.pm : periodLabels.am;\n    const value = draft[segment];\n    if (value === null) return \"--\";\n    if (segment === \"hours\" && hourCycle === 12) return pad(value % 12 || 12);\n    return pad(value);\n  }\n\n  const labels: Record<Segment, string> = { hours: \"Hours\", minutes: \"Minutes\", seconds: \"Seconds\", period: \"AM/PM\" };\n\n  return (\n    <div\n      id={id}\n      role=\"group\"\n      aria-label={aria[\"aria-label\"]}\n      aria-labelledby={aria[\"aria-labelledby\"]}\n      aria-disabled={disabled || undefined}\n      aria-invalid={invalid || undefined}\n      data-slot=\"time-picker\"\n      className={cx(\n        \"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)]\",\n        \"dark:bg-black dark:text-white dark:shadow-none\",\n        \"transition-[border-color] duration-150 ease-out motion-reduce:transition-none\",\n        invalid\n          ? \"border-red-500/50 dark:border-red-500/50\"\n          : \"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\",\n        slotInterval ? \"pe-1\" : \"pe-2\",\n        disabled && \"pointer-events-none opacity-45\",\n        className,\n      )}\n    >\n      <ClockGlyph className=\"me-1 size-4 shrink-0 text-zinc-500\" />\n      {segments.map((segment, index) => {\n        const value = segment === \"period\" ? (isPm ? 1 : 0) : draft[segment];\n        const empty = segment !== \"period\" && value === null;\n        const twelve = segment === \"hours\" && hourCycle === 12;\n        return (\n          <span key={segment} className=\"contents\">\n            {index > 0 && segment !== \"period\" ? (\n              <span aria-hidden=\"true\" className=\"text-zinc-400 dark:text-zinc-600\">\n                :\n              </span>\n            ) : null}\n            <span\n              ref={(node) => {\n                refs.current[segment] = node;\n              }}\n              role=\"spinbutton\"\n              tabIndex={disabled ? -1 : 0}\n              aria-label={labels[segment]}\n              aria-valuemin={segment === \"period\" ? 0 : twelve ? 1 : 0}\n              aria-valuemax={segment === \"period\" ? 1 : segment === \"hours\" ? (twelve ? 12 : 23) : 59}\n              aria-valuenow={empty ? undefined : segment === \"hours\" && twelve ? (draft.hours! % 12 || 12) : (value as number)}\n              aria-valuetext={empty ? \"Empty\" : display(segment)}\n              onKeyDown={(event) => onSegmentKeyDown(segment, event)}\n              onBlur={() => {\n                typed.current = { segment: null, text: \"\", at: 0 };\n              }}\n              className={cx(\n                \"rounded-[5px] px-[3px] py-0.5 text-center tabular-nums outline-hidden select-none\",\n                segment === \"period\" ? \"ms-1 min-w-[2.5ch]\" : \"min-w-[2.4ch]\",\n                \"transition-[background-color,color] duration-100 ease-out motion-reduce:transition-none\",\n                \"caret-transparent focus:bg-zinc-950 focus:text-white dark:focus:bg-white dark:focus:text-black\",\n                empty ? \"text-zinc-400 dark:text-zinc-600\" : invalid ? \"text-red-600 dark:text-red-400\" : \"text-zinc-950 dark:text-white\",\n              )}\n            >\n              {display(segment)}\n            </span>\n          </span>\n        );\n      })}\n      {name ? <input type=\"hidden\" name={name} value={current ?? \"\"} /> : null}\n      {slotInterval ? (\n        <SlotMenu\n          interval={slotInterval}\n          value={current}\n          showSeconds={showSeconds}\n          hourCycle={hourCycle}\n          locale={locale}\n          min={min}\n          max={max}\n          blocked={blocked}\n          showNow={showNow}\n          disabled={disabled}\n          onPick={(time) => commit(toDraft(time))}\n        />\n      ) : null}\n    </div>\n  );\n}\n\nconst ROW = 32;\n\nfunction SlotMenu({\n  interval,\n  value,\n  showSeconds,\n  hourCycle,\n  locale,\n  min,\n  max,\n  blocked,\n  showNow,\n  disabled,\n  onPick,\n}: {\n  interval: number;\n  value: string | null;\n  showSeconds: boolean;\n  hourCycle: 12 | 24;\n  locale?: string;\n  min: TimeParts | null;\n  max: TimeParts | null;\n  blocked: (time: string) => boolean;\n  showNow: boolean;\n  disabled: boolean;\n  onPick: (time: string) => void;\n}) {\n  const [open, setOpen] = useState(false);\n  const [active, setActive] = useState(0);\n  const [now, setNow] = useState<number | null>(null);\n  const listRef = useRef<HTMLDivElement | null>(null);\n  // The list mounts a render after `open` flips (it lives in a portal), so the glide waits for it.\n  const [listNode, setListNode] = useState<HTMLDivElement | null>(null);\n  const listId = `time-slots${useId().replace(/:/g, \"\")}`;\n\n  const startMinute = min ? min.hours * 60 + min.minutes : 0;\n  const endMinute = max ? max.hours * 60 + max.minutes : 24 * 60 - 1;\n  const slots = useMemo(() => {\n    const out: { time: string; minute: number }[] = [];\n    const stepBy = Math.max(1, Math.round(interval));\n    for (let minute = startMinute; minute <= endMinute; minute += stepBy) {\n      out.push({ time: toTimeString({ hours: Math.floor(minute / 60), minutes: minute % 60, seconds: 0 }), minute });\n    }\n    return out;\n  }, [interval, startMinute, endMinute]);\n\n  const format = useMemo(\n    () => new Intl.DateTimeFormat(locale, { hour: \"numeric\", minute: \"2-digit\", hourCycle: hourCycle === 12 ? \"h12\" : \"h23\" }),\n    [locale, hourCycle],\n  );\n\n  const selectedIndex = value ? slots.findIndex((slot) => slot.time === value.slice(0, 5)) : -1;\n\n  function nearest(minute: number) {\n    let best = 0;\n    slots.forEach((slot, index) => {\n      if (Math.abs(slot.minute - minute) < Math.abs(slots[best]!.minute - minute)) best = index;\n    });\n    return best;\n  }\n\n  function enabledFrom(index: number, direction: 1 | -1) {\n    for (let i = index; i >= 0 && i < slots.length; i += direction) if (!blocked(slots[i]!.time)) return i;\n    return null;\n  }\n\n  function onOpenChange(next: boolean) {\n    if (next) {\n      const date = new Date();\n      const minute = date.getHours() * 60 + date.getMinutes();\n      setNow(minute);\n      const valueMinute = value ? Number(value.slice(0, 2)) * 60 + Number(value.slice(3, 5)) : null;\n      const start = selectedIndex >= 0 ? selectedIndex : nearest(valueMinute ?? minute);\n      setActive(enabledFrom(start, 1) ?? enabledFrom(start, -1) ?? start);\n    }\n    setOpen(next);\n  }\n\n  // Opening lands a few rows short of the target, then glides the rest of the way so the eye\n  // can follow where it settled. Reduced motion places it at once.\n  useEffect(() => {\n    const list = listNode;\n    if (!open || !list) return;\n    const target = Math.max(0, active * ROW + ROW / 2 - list.clientHeight / 2 + 4);\n    const reduce = window.matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n    if (reduce) {\n      list.scrollTop = target;\n      return;\n    }\n    // A short quint ease-out driven by hand: native smooth scrolling gets cut off when the popup\n    // moves focus into the list.\n    const from = Math.max(0, target - ROW * 3);\n    list.scrollTop = from;\n    const start = performance.now();\n    let frame = 0;\n    const tick = (now: number) => {\n      const t = Math.min(1, (now - start) / 380);\n      list.scrollTop = from + (target - from) * (1 - (1 - t) ** 5);\n      if (t < 1) frame = requestAnimationFrame(tick);\n    };\n    frame = requestAnimationFrame(tick);\n    const stop = () => cancelAnimationFrame(frame);\n    list.addEventListener(\"wheel\", stop, { once: true, passive: true });\n    list.addEventListener(\"pointerdown\", stop, { once: true });\n    return () => {\n      stop();\n      list.removeEventListener(\"wheel\", stop);\n      list.removeEventListener(\"pointerdown\", stop);\n    };\n    // Only on open: keyboard moves scroll the active row into view on their own, without gliding.\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n  }, [open, listNode]);\n\n  function moveTo(index: number) {\n    setActive(index);\n    const list = listRef.current;\n    const row = list?.querySelector<HTMLElement>(`[data-index=\"${index}\"]`);\n    row?.scrollIntoView({ block: \"nearest\" });\n  }\n\n  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    const moves: Record<string, () => number | null> = {\n      ArrowDown: () => enabledFrom(active + 1, 1),\n      ArrowUp: () => enabledFrom(active - 1, -1),\n      PageDown: () => enabledFrom(Math.min(slots.length - 1, active + Math.round(60 / interval)), 1) ?? enabledFrom(slots.length - 1, -1),\n      PageUp: () => enabledFrom(Math.max(0, active - Math.round(60 / interval)), -1) ?? enabledFrom(0, 1),\n      Home: () => enabledFrom(0, 1),\n      End: () => enabledFrom(slots.length - 1, -1),\n    };\n    if (moves[event.key]) {\n      event.preventDefault();\n      const next = moves[event.key]!();\n      if (next !== null) moveTo(next);\n      return;\n    }\n    if (event.key === \"Enter\" || event.key === \" \") {\n      event.preventDefault();\n      const slot = slots[active];\n      if (slot && !blocked(slot.time)) {\n        onPick(showSeconds ? `${slot.time}:00` : slot.time);\n        setOpen(false);\n      }\n    }\n  }\n\n  // The current time as a y offset between rows.\n  const nowOffset =\n    showNow && now !== null && now >= startMinute && now <= endMinute ? ((now - startMinute) / Math.max(1, interval)) * ROW + ROW / 2 : null;\n\n  return (\n    <Popover open={open} onOpenChange={onOpenChange}>\n      <PopoverTrigger\n        disabled={disabled}\n        aria-label=\"Show times\"\n        className={cx(\n          \"ms-auto inline-flex size-7 shrink-0 items-center justify-center rounded-md text-zinc-500\",\n          \"transition-[background-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none\",\n          \"hover:bg-zinc-950/[0.04] hover:text-zinc-950 dark:hover:bg-white/[0.06] dark:hover:text-white\",\n          \"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\",\n          \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-0 focus-visible:outline-sky-500\",\n        )}\n      >\n        <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className=\"size-4\">\n          <path d=\"M4.5 6.5 8 10l3.5-3.5\" />\n        </svg>\n      </PopoverTrigger>\n      <PopoverContent align=\"end\" sideOffset={6} initialFocus={listRef} className=\"w-44 p-0\">\n        <div\n          ref={(node) => {\n            listRef.current = node;\n            setListNode(node);\n          }}\n          id={listId}\n          role=\"listbox\"\n          tabIndex={0}\n          aria-label=\"Times\"\n          aria-activedescendant={`${listId}-${active}`}\n          onKeyDown={onKeyDown}\n          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\"\n        >\n          {/* The rail: a hairline with a tick per slot, longer on the hour. */}\n          <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 }} />\n          {nowOffset !== null ? (\n            <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-x-1 z-[1] flex items-center\" style={{ top: 4 + nowOffset }}>\n              <span className=\"ms-[12px] size-[7px] -translate-y-1/2 rounded-full border-[1.5px] border-white bg-sky-500 dark:border-black\" />\n              <span className=\"h-px flex-1 -translate-y-1/2 bg-sky-500/45\" />\n            </div>\n          ) : null}\n          {slots.map((slot, index) => {\n            const isBlocked = blocked(slot.time);\n            const selected = index === selectedIndex;\n            const onHour = slot.minute % 60 === 0;\n            return (\n              <div\n                key={slot.time}\n                id={`${listId}-${index}`}\n                data-index={index}\n                role=\"option\"\n                aria-selected={selected}\n                aria-disabled={isBlocked || undefined}\n                onPointerMove={() => !isBlocked && active !== index && setActive(index)}\n                onClick={() => {\n                  if (isBlocked) return;\n                  onPick(showSeconds ? `${slot.time}:00` : slot.time);\n                  setOpen(false);\n                }}\n                className={cx(\n                  \"relative flex h-8 items-center gap-3 rounded-md ps-[34px] pe-2 text-sm tabular-nums\",\n                  \"transition-[background-color,color] duration-100 ease-out motion-reduce:transition-none\",\n                  isBlocked\n                    ? \"cursor-not-allowed text-zinc-400 line-through decoration-zinc-950/25 dark:text-zinc-600 dark:decoration-white/25\"\n                    : selected\n                      ? \"cursor-default bg-zinc-950 font-medium text-white dark:bg-white dark:text-black\"\n                      : cx(\n                          \"cursor-default\",\n                          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\",\n                        ),\n                )}\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className={cx(\n                    \"absolute top-1/2 h-px -translate-y-1/2\",\n                    onHour ? \"left-[11px] w-[9px]\" : \"left-[15px] w-[5px]\",\n                    selected ? \"bg-white/50 dark:bg-black/40\" : \"bg-zinc-950/20 dark:bg-white/25\",\n                  )}\n                />\n                {format.format(new Date(2026, 0, 1, Math.floor(slot.minute / 60), slot.minute % 60))}\n                {selected ? (\n                  <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\">\n                    <path d=\"m3.5 8.5 3 3 6-7\" />\n                  </svg>\n                ) : null}\n              </div>\n            );\n          })}\n        </div>\n      </PopoverContent>\n    </Popover>\n  );\n}\n\nfunction ClockGlyph({ className }: { className?: string }) {\n  return (\n    <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" className={className}>\n      <circle cx=\"8\" cy=\"8\" r=\"5.75\" />\n      <path d=\"M8 5v3l2 1.25\" />\n    </svg>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { TimePicker } from \"@/components/shaken/ui/time-picker\";\n\n// Slots already booked by other teams for the shared GPU queue.\nconst booked = [\"10:30\", \"10:45\", \"13:00\", \"13:15\", \"13:30\", \"15:45\"];\n\nexport default function TimePickerExample() {\n  const [slot, setSlot] = useState<string | null>(\"14:00\");\n\n  return (\n    <div className=\"flex flex-wrap items-start justify-center gap-6\">\n      <div className=\"grid gap-1.5\">\n        <span id=\"digest-label\" className=\"text-sm font-medium text-zinc-950 dark:text-white\">\n          Daily digest at\n        </span>\n        <TimePicker aria-labelledby=\"digest-label\" defaultValue=\"08:30\" name=\"digestTime\" />\n      </div>\n      <div className=\"grid gap-1.5\">\n        <span id=\"queue-label\" className=\"text-sm font-medium text-zinc-950 dark:text-white\">\n          Reserve the GPU queue\n        </span>\n        <TimePicker\n          aria-labelledby=\"queue-label\"\n          value={slot}\n          onValueChange={setSlot}\n          slotInterval={15}\n          minTime=\"09:00\"\n          maxTime=\"18:00\"\n          disabledTimes={booked}\n        />\n        <p className=\"text-xs text-zinc-500\">{slot ? `Held for 15 minutes from ${slot}` : \"Pick a 15 minute slot\"}</p>\n      </div>\n    </div>\n  );\n}\n"
  }
}
