{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "time-slot-picker",
  "type": "registry:ui",
  "title": "Time Slot Picker",
  "description": "The times open on one day, as tiles to pick one from: the second half of a booking page, next to a `Calendar`. Built on Base UI's radio group, so it is one tab stop, the arrows move between times, and a form posts the picked slot's `value` under `name`.…",
  "author": "ofri-peretz <https://github.com/ofri-peretz>",
  "categories": [
    "form",
    "pattern"
  ],
  "dependencies": [
    "@base-ui/react"
  ],
  "registryDependencies": [
    "https://ds.interlace.tools/r/interlace-base.json",
    "https://ds.interlace.tools/r/cn.json",
    "https://ds.interlace.tools/r/motion-token.json",
    "https://ds.interlace.tools/r/radio-group.json",
    "https://ds.interlace.tools/r/use-reduced-motion.json"
  ],
  "files": [
    {
      "path": "registry/interlace-ui/patterns/time-slot-picker.tsx",
      "target": "components/ui/patterns/time-slot-picker.tsx",
      "type": "registry:ui",
      "content": "'use client';\n\nimport * as React from 'react';\n\n// @interlace/time-slot-picker v1.2.2 — Interlace design system.\n// Docs, props and live preview: https://ds.interlace.tools/c/time-slot-picker\n// What changed since: https://ds.interlace.tools/c/time-slot-picker#history\n// Generated banner — keep it, the upgrade diff reads this version.\n\n/**\n * @interlace/ui — TimeSlotPicker\n *\n * The times open on one day, as tiles to pick one from: the second half of\n * a booking page, next to a `Calendar`. Built on Base UI's radio group, so\n * it is one tab stop, the arrows move between times, and a form posts the\n * picked slot's `value` under `name`.\n * Mirrors: https://base-ui.com/react/components/radio\n * Inspiration: Cal.com's column of times, Stripe's quiet tiles.\n *\n * ## Anatomy\n *\n *   TimeSlotPicker                  (div — data-slot=\"time-slot-picker\", @container, data-min-viewport=320)\n *     ├─ label                      (data-slot=\"time-slot-picker-label\", names the group)\n *     ├─ description                (data-slot=\"time-slot-picker-description\", e.g. the time zone)\n *     └─ RadioGroup                 (data-slot=\"time-slot-picker-group\", aria-busy while loading)\n *         ├─ heading per period     (data-slot=\"time-slot-picker-period\", with `groupBy=\"period\"`)\n *         └─ Radio × n              (data-slot=\"time-slot\", data-state, button[role=radio])\n *             ├─ time               (the slot's start, in `locale` and `timeZone`)\n *             └─ note               (data-slot=\"time-slot-note\", e.g. \"2 places left\")\n *\n * ## States\n *\n * | State      | What shows                                                    |\n * | ---------- | ------------------------------------------------------------- |\n * | `loading`  | tile-shaped placeholders, the group `aria-busy`               |\n * | no slots   | `labels.empty` in words, never a blank box                    |\n * | slots      | tiles; a full slot is muted, struck through and says so       |\n *\n * ## Keyboard (owned by Base UI)\n *\n * | Key         | Action                                   |\n * | ----------- | ---------------------------------------- |\n * | Tab         | Into the group, on the picked time       |\n * | ← → ↑ ↓     | Pick the previous / next open time       |\n * | Space       | Pick the focused time                    |\n *\n * ## Motion\n *\n * When the list of times changes (a new day), the tiles fade up into place\n * once (200ms, transform and opacity). The picked tile takes its fill in\n * `--duration-fast`. Under reduced motion both are simply there.\n *\n * ## MIN_VIEWPORT — 320\n *\n * The tiles query the picker's own width: two columns in a phone column,\n * three from 28rem, four from 42rem. A sidebar and a full page both work.\n *\n * | Rule | Concept                   | Where in this file                                          |\n * | ---- | ------------------------- | ----------------------------------------------------------- |\n * | R4   | Extends native el         | `React.ComponentProps<'div'>`                               |\n * | R6   | data-slot per part        | time-slot-picker / -label / -group / -period / time-slot     |\n * | R7   | cn + ...rest              | `cn(…, className)` + `{...props}`                           |\n * | R9   | Controlled + uncontrolled | `value` / `defaultValue` / `onValueChange`                  |\n * | R12  | Reuse over wrap           | Base UI owns roving focus, ARIA and the form value          |\n * | R14  | Declares min viewport     | `data-min-viewport` + exported const                        |\n * | R19  | Tokens only               | `border-input`, `bg-primary`, `text-muted-foreground`        |\n * | R26  | A11y                      | labelled radiogroup; full slots say why in their name       |\n */\n\nimport { Radio } from '@base-ui/react/radio';\n\nimport { cn } from '@/lib/utils';\nimport { useReducedMotion } from '@/hooks/use-reduced-motion';\nimport { motionEase } from '@/lib/motion-token';\nimport { RadioGroup } from '@/components/ui/radio-group';\nimport { type DayPeriod, formatSlot, groupByPeriod } from '@/components/ui/patterns/time-slot-model';\n\nexport const MIN_VIEWPORT = 320 as const;\n\nexport interface TimeSlot {\n  /** What your store keys the slot by: `HH:MM`, an ISO instant, or your own id. */\n  value: string;\n  /** What the tile says. @default the start time, from `value` */\n  label?: React.ReactNode;\n  /** Plain text for the slot's accessible name, when `label` is not a string. */\n  text?: string;\n  /** A short line under the time, e.g. \"2 places left\". */\n  note?: React.ReactNode;\n  /** Full or closed: shown, but cannot be picked. */\n  disabled?: boolean;\n  /** Hour (0 to 23) for `groupBy=\"period\"`, when `value` is your own id. */\n  hour?: number;\n}\n\nexport interface TimeSlotPickerLabels {\n  /** Shown when the day has no times. @default 'No times left on this day. Try another day.' */\n  empty?: string;\n  /** Said after a slot that cannot be picked. @default 'Full' */\n  unavailable?: string;\n  /** Headings for `groupBy=\"period\"`. */\n  periods?: Partial<Record<DayPeriod, string>>;\n  /** Said while loading. @default 'Loading times' */\n  loading?: string;\n}\n\nconst DEFAULT_PERIODS: Record<DayPeriod, string> = {\n  morning: 'Morning',\n  afternoon: 'Afternoon',\n  evening: 'Evening',\n};\n\ntype TimeSlotPickerProps = Omit<React.ComponentProps<'div'>, 'defaultValue' | 'onChange'> & {\n  /** Names the group, e.g. \"Times on Tuesday 24 November\". */\n  label: React.ReactNode;\n  /** A line under the label, e.g. the time zone the times are in. */\n  description?: React.ReactNode;\n  slots: readonly TimeSlot[];\n  /** The picked slot's value, controlled. `null` for none. */\n  value?: string | null;\n  defaultValue?: string | null;\n  onValueChange?: (value: string) => void;\n  /** Form field name; the picked `value` is posted under it. */\n  name?: string;\n  /** A slot must be picked before the form submits. */\n  required?: boolean;\n  /** Placeholders while the day's times load. */\n  loading?: boolean;\n  /** `period` puts headings over morning, afternoon and evening. @default 'none' */\n  groupBy?: 'none' | 'period';\n  /** BCP 47 locale for the times. @default the browser's */\n  locale?: string;\n  /** Zone to show ISO instants in. @default the browser's */\n  timeZone?: string;\n  /** Force a 12-hour (`true`) or 24-hour (`false`) clock. @default the locale's */\n  hour12?: boolean;\n  labels?: TimeSlotPickerLabels;\n};\n\nconst TILE =\n  'relative flex min-h-control-lg w-full min-w-0 flex-col items-center justify-center gap-0.5 rounded-lg border px-3 py-2 text-center text-sm font-medium tabular-nums focus-visible:outline-hidden transition-[color,background-color,border-color,box-shadow,scale] duration-(--duration-fast) ease-enter focus-visible:ring-ring focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst TimeSlotPicker = React.forwardRef<HTMLDivElement, TimeSlotPickerProps>(\n  function TimeSlotPicker(\n    {\n      label,\n      description,\n      slots,\n      value,\n      defaultValue,\n      onValueChange,\n      name,\n      required,\n      loading = false,\n      groupBy = 'none',\n      locale,\n      timeZone,\n      hour12,\n      labels,\n      className,\n      ...props\n    },\n    ref,\n  ) {\n    const labelId = React.useId();\n    const descriptionId = React.useId();\n    const groupRef = React.useRef<HTMLDivElement>(null);\n    const reduced = useReducedMotion();\n    const signature = slots.map((s) => s.value).join('|');\n    const mounted = React.useRef(false);\n\n    React.useLayoutEffect(() => {\n      // The first paint is content, not an entrance: only a new list moves.\n      if (!mounted.current) {\n        mounted.current = true;\n        return;\n      }\n      const group = groupRef.current;\n      if (reduced || loading || !group || typeof group.animate !== 'function') return;\n      group.animate(\n        [\n          { transform: 'translateY(0.25rem)', opacity: 0 },\n          { transform: 'translateY(0)', opacity: 1 },\n        ],\n        { duration: 200, easing: motionEase(group, 'enter') },\n      );\n    }, [signature, reduced, loading]);\n\n    const unavailable = labels?.unavailable ?? 'Full';\n    const periods = { ...DEFAULT_PERIODS, ...labels?.periods };\n    const groups =\n      groupBy === 'period'\n        ? groupByPeriod(slots, timeZone)\n        : [{ period: null as DayPeriod | null, slots: [...slots] }];\n\n    const tiles = (list: readonly TimeSlot[]) => (\n      <div className=\"grid grid-cols-2 gap-2 @md:grid-cols-3 @2xl:grid-cols-4\">\n        {list.map((slot) => {\n          const time = formatSlot(slot.value, { locale, timeZone, hour12 });\n          const text = slot.text ?? (typeof slot.label === 'string' ? slot.label : time);\n          return (\n            <Radio.Root\n              key={slot.value}\n              value={slot.value}\n              disabled={slot.disabled}\n              data-slot=\"time-slot\"\n              aria-label={slot.disabled ? `${text}, ${unavailable}` : undefined}\n              className={cn(\n                TILE,\n                'border-input bg-background text-foreground hover:border-ring hover:bg-accent hover:text-accent-foreground motion-safe:active:scale-[0.97]',\n                'data-[checked]:border-primary data-[checked]:bg-primary data-[checked]:text-primary-foreground',\n                'data-[disabled]:text-muted-foreground data-[disabled]:cursor-not-allowed data-[disabled]:border-dashed data-[disabled]:bg-transparent data-[disabled]:hover:border-input data-[disabled]:hover:bg-transparent data-[disabled]:hover:text-muted-foreground data-[disabled]:active:scale-100',\n              )}\n            >\n              <span\n                dir=\"auto\"\n                className={cn('truncate', slot.disabled && 'line-through decoration-from-font')}\n              >\n                {slot.label ?? time}\n              </span>\n              {slot.note && (\n                <span\n                  dir=\"auto\"\n                  data-slot=\"time-slot-note\"\n                  className=\"truncate text-xs font-normal opacity-90\"\n                >\n                  {slot.note}\n                </span>\n              )}\n            </Radio.Root>\n          );\n        })}\n      </div>\n    );\n\n    return (\n      <div\n        ref={ref}\n        data-slot=\"time-slot-picker\"\n        data-min-viewport={String(MIN_VIEWPORT)}\n        className={cn('@container flex w-full min-w-0 flex-col gap-3', className)}\n        {...props}\n      >\n        <div className=\"flex flex-col gap-0.5\">\n          <div id={labelId} data-slot=\"time-slot-picker-label\" className=\"text-sm font-semibold\">\n            {label}\n          </div>\n          {description && (\n            <div\n              id={descriptionId}\n              data-slot=\"time-slot-picker-description\"\n              className=\"text-muted-foreground text-sm\"\n            >\n              {description}\n            </div>\n          )}\n        </div>\n        {loading ? (\n          <div\n            data-slot=\"time-slot-picker-group\"\n            aria-busy=\"true\"\n            aria-labelledby={labelId}\n            role=\"status\"\n            className=\"grid grid-cols-2 gap-2 @md:grid-cols-3 @2xl:grid-cols-4\"\n          >\n            <span className=\"sr-only\">{labels?.loading ?? 'Loading times'}</span>\n            {Array.from({ length: 6 }, (_, i) => (\n              <div\n                key={i}\n                aria-hidden=\"true\"\n                data-slot=\"time-slot-placeholder\"\n                className=\"bg-muted min-h-control-lg w-full rounded-lg motion-safe:animate-pulse\"\n              />\n            ))}\n          </div>\n        ) : slots.length === 0 ? (\n          <p\n            data-slot=\"time-slot-picker-empty\"\n            role=\"status\"\n            className=\"text-muted-foreground border-border rounded-lg border border-dashed px-4 py-6 text-center text-sm\"\n          >\n            {labels?.empty ?? 'No times left on this day. Try another day.'}\n          </p>\n        ) : (\n          <RadioGroup\n            ref={groupRef}\n            data-slot=\"time-slot-picker-group\"\n            aria-labelledby={labelId}\n            aria-describedby={description ? descriptionId : undefined}\n            value={value === undefined ? undefined : value}\n            defaultValue={defaultValue ?? undefined}\n            onValueChange={(v) => onValueChange?.(v as string)}\n            name={name}\n            required={required}\n            className=\"flex flex-col gap-4\"\n          >\n            {groups.map((g) =>\n              g.period ? (\n                <div key={g.period} className=\"flex flex-col gap-2\">\n                  <div\n                    data-slot=\"time-slot-picker-period\"\n                    className=\"text-muted-foreground text-xs font-medium\"\n                  >\n                    {periods[g.period]}\n                  </div>\n                  {tiles(g.slots)}\n                </div>\n              ) : (\n                <React.Fragment key=\"all\">{tiles(g.slots)}</React.Fragment>\n              ),\n            )}\n          </RadioGroup>\n        )}\n      </div>\n    );\n  },\n);\n\nexport { TimeSlotPicker };\nexport type { TimeSlotPickerProps };\n"
    },
    {
      "path": "registry/interlace-ui/patterns/time-slot-model.ts",
      "target": "components/ui/patterns/time-slot-model.ts",
      "type": "registry:ui",
      "content": "export type DayPeriod = 'morning' | 'afternoon' | 'evening';\n\nexport interface TimeSlotLike {\n  value: string;\n  /** Hour of the day (0 to 23) for grouping, when `value` is neither shape above. */\n  hour?: number;\n}\n\nconst WALL_RE = /^([01]\\d|2[0-3]):([0-5]\\d)$/;\nconst INSTANT_RE = /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:\\d{2})$/;\n\n/** `09:30` as a UTC date on 1 January 1970, for formatting with `timeZone: 'UTC'`. */\nfunction wallDate(value: string): Date | null {\n  const m = WALL_RE.exec(value);\n  return m ? new Date(Date.UTC(1970, 0, 1, Number(m[1]), Number(m[2]))) : null;\n}\n\nfunction instantDate(value: string): Date | null {\n  if (!INSTANT_RE.test(value)) return null;\n  const d = new Date(value);\n  return Number.isNaN(d.getTime()) ? null : d;\n}\n\n/** The hour (0 to 23) a slot starts at, or null when it cannot be read. */\nexport function slotHour(slot: TimeSlotLike, timeZone?: string): number | null {\n  if (slot.hour !== undefined) return slot.hour;\n  const wall = wallDate(slot.value);\n  if (wall) return wall.getUTCHours();\n  const instant = instantDate(slot.value);\n  if (!instant) return null;\n  const hour = new Intl.DateTimeFormat('en-GB', {\n    hour: '2-digit',\n    hourCycle: 'h23',\n    timeZone,\n  }).format(instant);\n  return Number(hour);\n}\n\n/** Morning before noon, afternoon before 17:00, evening after. */\nexport function periodOf(hour: number): DayPeriod {\n  if (hour < 12) return 'morning';\n  if (hour < 17) return 'afternoon';\n  return 'evening';\n}\n\nexport interface FormatSlotOptions {\n  locale?: string;\n  /** Zone to show an ISO instant in. Ignored for `HH:MM`. */\n  timeZone?: string;\n  /** Force a 12-hour (`true`) or 24-hour (`false`) clock. @default the locale's */\n  hour12?: boolean;\n}\n\n/** The slot's start time in words for the locale (\"9:30 AM\", \"09:30\"), or the raw value. */\nexport function formatSlot(value: string, opts: FormatSlotOptions = {}): string {\n  const wall = wallDate(value);\n  const date = wall ?? instantDate(value);\n  if (!date) return value;\n  return formatter(opts.locale, opts.hour12, wall ? 'UTC' : opts.timeZone).format(date);\n}\n\n// Building an Intl.DateTimeFormat is far dearer than using one, and a day\n// of slots asks for the same one every time. The keys are a few locales, zones\n// and clocks, so the map stays small even in a long-lived server.\nconst formatters = new Map<string, Intl.DateTimeFormat>();\n\nfunction formatter(locale?: string, hour12?: boolean, timeZone?: string): Intl.DateTimeFormat {\n  const key = `${locale}|${hour12}|${timeZone}`;\n  let fmt = formatters.get(key);\n  if (!fmt) {\n    fmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit', hour12, timeZone });\n    formatters.set(key, fmt);\n  }\n  return fmt;\n}\n\n/**\n * The slots in groups by part of the day, in the order given, leaving out\n * empty groups. Slots whose hour cannot be read go in the first group.\n */\nexport function groupByPeriod<T extends TimeSlotLike>(\n  slots: readonly T[],\n  timeZone?: string,\n): { period: DayPeriod; slots: T[] }[] {\n  const order: DayPeriod[] = ['morning', 'afternoon', 'evening'];\n  const groups = new Map<DayPeriod, T[]>(order.map((p) => [p, []]));\n  for (const slot of slots) {\n    const hour = slotHour(slot, timeZone);\n    groups.get(hour === null ? 'morning' : periodOf(hour))!.push(slot);\n  }\n  return order\n    .map((period) => ({ period, slots: groups.get(period)! }))\n    .filter((g) => g.slots.length > 0);\n}\n\n/**\n * @interlace/ui — time-slot-model\n *\n * The pure half of `TimeSlotPicker`: what hour a slot starts, which part of\n * the day it falls in, and how to say it in a locale and a time zone.\n *\n * A slot's `value` is whatever your booking store keys it by. Two shapes\n * are read for the hour, so the picker can name and group a slot without a\n * label:\n *\n * | `value`                        | Read as                                   |\n * | ------------------------------ | ----------------------------------------- |\n * | `HH:MM` (e.g. `09:30`)         | a wall-clock time at the venue             |\n * | an ISO instant (`…T09:30:00Z`) | a moment, shown in `timeZone`              |\n *\n * Anything else needs its own `label`, and is grouped by `hour` if given.\n */\n\n/** A part of the day, for grouping a long list of times. */\n"
    }
  ],
  "meta": {
    "tier": "pattern",
    "client": true,
    "minViewport": 320,
    "loading": true,
    "version": "1.2.2",
    "since": "2.0.0"
  },
  "docs": "## @interlace/time-slot-picker\n\nInstalled to `components/ui/patterns/time-slot-picker.tsx`.\n\n```tsx\nimport { /* … */ } from '@/components/ui/patterns/time-slot-picker';\n```\n\nProps, a11y contract, live preview and source: https://ds.interlace.tools/c/time-slot-picker\n\nRequires the `@interlace/interlace-base` CSS baseline (installed automatically as a registry dependency). For the Interlace look, also add `@interlace/theme`."
}
