{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "time-picker",
  "type": "registry:ui",
  "title": "Time Picker",
  "description": "A time field made of an hour and a minute that are each stepped with the arrow keys or typed, with an AM/PM part where the locale uses a 12-hour clock. The value is a 24-hour \"HH:mm\" string.",
  "categories": [
    "ui"
  ],
  "dependencies": [],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/direction",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/time-picker.tsx",
      "type": "registry:ui",
      "target": "components/ui/time-picker.tsx",
      "content": "\"use client\";\n/**\n * @name time-picker\n * @category ui\n * @description A time field made of an hour and a minute that are each stepped with the arrow keys or typed, with an AM/PM part where the locale uses a 12-hour clock. The value is a 24-hour \"HH:mm\" string.\n * @when Any time of the person's own choosing: an opening hour, a reminder, an arrival. When the times on offer are a fixed list use slot-picker. Never the browser's native time input. Name it with `aria-label` or `aria-labelledby`.\n * @example\n * <p id=\"opens-label\">Opens at</p>\n * <TimePicker aria-labelledby=\"opens-label\" defaultValue=\"09:30\" minuteStep={5} name=\"opens\" locale=\"en-GB\" />\n *\n * // Controlled, limited, 12-hour whatever the locale, with translated names\n * <TimePicker\n *   value={time}\n *   onValueChange={setTime}\n *   min=\"08:00\"\n *   max=\"18:00\"\n *   hourCycle={12}\n *   aria-label=\"Pick-up time\"\n *   labels={{ hour: \"Hour\", minute: \"Minute\", period: \"Morning or afternoon\", empty: \"Not set\" }}\n * />\n */\nimport { createContext, use, useMemo, useRef, useState, type ChangeEvent, type ComponentProps, type KeyboardEvent, type ReactNode } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { inlineStep } from \"@/lib/direction\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\n\nexport type TimePickerLabels = {\n  hour: string;\n  minute: string;\n  /** The name of the AM/PM part. */\n  period: string;\n  /** What a part says while no time is set. */\n  empty: string;\n};\n\nconst LABELS: TimePickerLabels = { hour: \"Hour\", minute: \"Minute\", period: \"AM or PM\", empty: \"Empty\" };\n\nconst pad = (value: number): string => String(value).padStart(2, \"0\");\n\ntype TimeContextValue = {\n  hour: number | null;\n  minute: number | null;\n  cycle: 12 | 24;\n  /** The locale's words for before and after noon. */\n  periods: readonly [string, string];\n  minuteStep: number;\n  disabled: boolean;\n  labels: TimePickerLabels;\n  /** Sets the time, kept within `min` and `max`. */\n  set: (hour: number, minute: number) => void;\n  clear: () => void;\n  /** Where the arrows start from while nothing is set. */\n  start: { hour: number; minute: number };\n};\n\nconst TimeContext = createContext<TimeContextValue | null>(null);\n\nfunction useTime(part: string): TimeContextValue {\n  const context = use(TimeContext);\n  if (!context) throw new Error(`<${part}> must be used inside <TimePicker>.`);\n  return context;\n}\n\nexport type TimePickerProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  /** The time as \"HH:mm\" on the 24-hour clock, or null for none. Controlled. */\n  value?: string | null;\n  defaultValue?: string | null;\n  onValueChange?: (value: string | null) => void;\n  /** What one arrow key adds to or takes from the minutes. Default 1. Typed minutes are kept as typed. */\n  minuteStep?: number;\n  /** The earliest and the latest time, as \"HH:mm\". A time outside them becomes the nearest one inside. */\n  min?: string;\n  max?: string;\n  /** The language tag: it decides between the 12-hour and the 24-hour clock and names AM and PM. Default \"en\". */\n  locale?: string;\n  /** 12 or 24, when the locale's own clock is not wanted. */\n  hourCycle?: 12 | 24;\n  /** The field's name in a form: the \"HH:mm\" value is submitted with it (\"\" when none). */\n  name?: string;\n  disabled?: boolean;\n  /** The names of the parts. Translate them with the interface. */\n  labels?: Partial<TimePickerLabels>;\n  /** The parts, when the default (hour, separator, minute, and AM/PM on a 12-hour clock) is not what is wanted. */\n  children?: ReactNode;\n};\n\nfunction parse(value: string | null | undefined): { hour: number; minute: number } | null {\n  const match = value ? /^([01]\\d|2[0-3]):([0-5]\\d)$/.exec(value) : null;\n  return match ? { hour: Number(match[1]), minute: Number(match[2]) } : null;\n}\n\n/**\n * Each part is a spin button: Up and Down change it (the minutes by `minuteStep`), Home and End go to its\n * limits, typing digits sets it and moves on to the next part, Left and Right move between parts, and\n * Backspace or Delete empties the field. The first change to an empty field sets the other part too, so the\n * value is always a whole time or nothing.\n *\n * The parts sit in a `dir=\"ltr\"` wrapper: a time of day is written hour first, left to right, in\n * right-to-left languages as well (as a telephone number is), so Left and Right keep their plain meaning here.\n */\nexport function TimePicker({\n  className,\n  value,\n  defaultValue = null,\n  onValueChange,\n  minuteStep = 1,\n  min,\n  max,\n  locale = \"en\",\n  hourCycle,\n  name,\n  disabled = false,\n  labels,\n  children,\n  ...props\n}: TimePickerProps) {\n  const [current, setCurrent] = useControllableState<string | null>({ value, defaultValue, onChange: onValueChange });\n  const time = parse(current);\n\n  const clock = useMemo(() => {\n    const formatter = new Intl.DateTimeFormat(locale, { hour: \"numeric\", hour12: true, timeZone: \"UTC\" });\n    const period = (hour: number, fallback: string): string => formatter.formatToParts(Date.UTC(1970, 0, 1, hour)).find((part) => part.type === \"dayPeriod\")?.value ?? fallback;\n    const resolved = new Intl.DateTimeFormat(locale, { hour: \"numeric\" }).resolvedOptions().hourCycle;\n    return { cycle: resolved === \"h11\" || resolved === \"h12\" ? (12 as const) : (24 as const), periods: [period(9, \"AM\"), period(15, \"PM\")] as const };\n  }, [locale]);\n  const cycle = hourCycle ?? clock.cycle;\n\n  const set = (hour: number, minute: number): void => {\n    const next = `${pad(hour)}:${pad(minute)}`;\n    setCurrent(min !== undefined && next < min ? min : max !== undefined && next > max ? max : next);\n  };\n\n  return (\n    <TimeContext\n      value={{\n        hour: time?.hour ?? null,\n        minute: time?.minute ?? null,\n        cycle,\n        periods: clock.periods,\n        minuteStep: Math.max(1, Math.round(minuteStep)),\n        disabled,\n        labels: { ...LABELS, ...labels },\n        set,\n        clear: () => setCurrent(null),\n        start: parse(min) ?? { hour: 0, minute: 0 },\n      }}\n    >\n      <div\n        role=\"group\"\n        data-slot=\"time-picker\"\n        data-disabled={disabled ? \"\" : undefined}\n        className={cn(\"inline-flex h-control w-fit shrink-0 items-center rounded-control border border-input bg-background px-2.5 text-sm text-foreground data-[disabled]:opacity-50\", className)}\n        {...props}\n      >\n        <div dir=\"ltr\" className=\"flex items-center gap-0.5 tabular-nums\">\n          {children ?? (\n            <>\n              <TimePickerHour />\n              <TimePickerSeparator />\n              <TimePickerMinute />\n              {cycle === 12 ? <TimePickerPeriod /> : null}\n            </>\n          )}\n        </div>\n        {name ? <input type=\"hidden\" name={name} value={current ?? \"\"} disabled={disabled} /> : null}\n      </div>\n    </TimeContext>\n  );\n}\n\nconst SEGMENT = \"[data-slot=time-picker] input[role=spinbutton]\";\n\n/** Moves focus to the part before or after this one, if there is one. */\nfunction focusSibling(from: HTMLElement, step: -1 | 1): void {\n  const parts = [...(from.closest(\"[data-slot=time-picker]\")?.querySelectorAll<HTMLElement>(SEGMENT) ?? [])];\n  parts[parts.indexOf(from) + step]?.focus();\n}\n\nconst segmentClass =\n  \"box-content h-7 w-[2ch] shrink-0 cursor-default rounded-sm bg-transparent px-1 text-center caret-transparent selection:bg-transparent focus:bg-highlight-soft disabled:pointer-events-none pointer-coarse:h-9\";\n\ntype SegmentProps = Omit<ComponentProps<\"input\">, \"value\" | \"defaultValue\" | \"type\" | \"onChange\">;\n\ntype SegmentBehaviour = {\n  slot: string;\n  text: string;\n  /** Up (+1) and Down (-1). */\n  onStep: (direction: -1 | 1) => void;\n  /** Home (-1) and End (+1). */\n  onLimit: (end: -1 | 1) => void;\n  /** For a part that takes digits: the smallest and the largest number it can hold, and what to do with a finished one. */\n  range?: readonly [number, number];\n  onNumber?: (value: number) => void;\n  /** A typed letter (the AM/PM part). */\n  onLetter?: (letter: string) => void;\n};\n\nfunction Segment({ slot, text, onStep, onLimit, range, onNumber, onLetter, className, onKeyDown, onBlur, ...props }: SegmentProps & SegmentBehaviour) {\n  const time = useTime(\"TimePicker part\");\n  /**\n   * A first digit that may be followed by a second (\"1\" before \"14\"). It is shown but is not yet the value,\n   * so that a half-typed number is never pulled to the earliest or the latest time allowed.\n   */\n  const [typed, setTypedState] = useState(\"\");\n  // The same digit for the handlers: leaving the part (which a finished number does) must not read a stale one.\n  const waiting = useRef(\"\");\n  const setTyped = (digit: string): void => {\n    waiting.current = digit;\n    setTypedState(digit);\n  };\n\n  const type = (character: string, target: HTMLElement): void => {\n    if (/^\\d$/.test(character) && range && onNumber) {\n      const digit = Number(character);\n      const [least, most] = range;\n      const joined = waiting.current === \"\" ? Number.NaN : Number(waiting.current) * 10 + digit;\n      if (joined >= least && joined <= most) {\n        onNumber(joined);\n      } else if (digit * 10 <= most) {\n        // It can still become a two-digit number: wait for the next digit.\n        setTyped(character);\n        return;\n      } else if (digit >= least) {\n        onNumber(digit);\n      }\n      setTyped(\"\");\n      focusSibling(target, 1);\n    } else if (onLetter) {\n      onLetter(character.toLowerCase());\n    }\n  };\n\n  const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {\n    onKeyDown?.(event);\n    if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return;\n    const sideways = inlineStep(event.key, event.currentTarget);\n    if (sideways !== 0) {\n      event.preventDefault();\n      focusSibling(event.currentTarget, sideways);\n    } else if (event.key === \"ArrowUp\" || event.key === \"ArrowDown\") {\n      event.preventDefault();\n      setTyped(\"\");\n      onStep(event.key === \"ArrowUp\" ? 1 : -1);\n    } else if (event.key === \"Home\" || event.key === \"End\") {\n      event.preventDefault();\n      setTyped(\"\");\n      onLimit(event.key === \"Home\" ? -1 : 1);\n    } else if (event.key === \"Backspace\" || event.key === \"Delete\") {\n      event.preventDefault();\n      setTyped(\"\");\n      time.clear();\n    } else if (event.key.length === 1 && event.key !== \" \") {\n      event.preventDefault();\n      type(event.key, event.currentTarget);\n    }\n  };\n\n  // On-screen keyboards do not always send key events: what they typed arrives here instead.\n  const handleChange = (event: ChangeEvent<HTMLInputElement>): void => {\n    const shown = typed === \"\" ? text : typed;\n    const character = event.target.value.replace(shown, \"\").slice(-1) || event.target.value.slice(-1);\n    if (character) type(character, event.currentTarget);\n  };\n\n  return (\n    <input\n      data-slot={slot}\n      role=\"spinbutton\"\n      type=\"text\"\n      autoComplete=\"off\"\n      disabled={time.disabled}\n      value={typed === \"\" ? text : typed}\n      onChange={handleChange}\n      onKeyDown={handleKeyDown}\n      onBlur={(event) => {\n        // A single digit left waiting is the number.\n        if (waiting.current !== \"\" && range && Number(waiting.current) >= range[0]) onNumber?.(Number(waiting.current));\n        setTyped(\"\");\n        onBlur?.(event);\n      }}\n      className={cn(segmentClass, className)}\n      {...props}\n    />\n  );\n}\n\nconst EMPTY = \"––\";\n\nexport type TimePickerPartProps = Omit<ComponentProps<\"input\">, \"value\" | \"defaultValue\" | \"type\" | \"onChange\">;\n\n/** The hour: 0 to 23, or 1 to 12 beside an AM/PM part (stepping then stays within the morning or the afternoon). */\nexport function TimePickerHour(props: TimePickerPartProps) {\n  const time = useTime(\"TimePickerHour\");\n  const { hour, cycle, periods } = time;\n  const minute = time.minute ?? time.start.minute;\n  const half = hour !== null && hour >= 12 ? 1 : 0;\n  const shown = hour === null ? null : cycle === 24 ? hour : hour % 12 || 12;\n\n  /** An hour as written on this clock, to the 24-hour value in the current half of the day. */\n  const from = (written: number): number => (cycle === 24 ? written : (written % 12) + half * 12);\n\n  return (\n    <Segment\n      slot=\"time-picker-hour\"\n      inputMode=\"numeric\"\n      aria-label={time.labels.hour}\n      aria-valuenow={shown ?? undefined}\n      aria-valuemin={cycle === 24 ? 0 : 1}\n      aria-valuemax={cycle === 24 ? 23 : 12}\n      aria-valuetext={shown === null ? time.labels.empty : cycle === 24 ? pad(shown) : `${shown} ${periods[half]}`}\n      text={shown === null ? EMPTY : cycle === 24 ? pad(shown) : String(shown)}\n      onStep={(direction) => {\n        if (hour === null) time.set(time.start.hour, time.start.minute);\n        else if (cycle === 24) time.set((hour + direction + 24) % 24, minute);\n        else time.set(half * 12 + (((hour % 12) + direction + 12) % 12), minute);\n      }}\n      onLimit={(end) => time.set(cycle === 24 ? (end === -1 ? 0 : 23) : half * 12 + (end === -1 ? 0 : 11), minute)}\n      range={cycle === 24 ? [0, 23] : [1, 12]}\n      onNumber={(written) => time.set(from(written), minute)}\n      {...props}\n    />\n  );\n}\n\n/** The minute: 00 to 59. Up and Down move to the next or the previous multiple of `minuteStep`. */\nexport function TimePickerMinute(props: TimePickerPartProps) {\n  const time = useTime(\"TimePickerMinute\");\n  const { minute, minuteStep } = time;\n  const hour = time.hour ?? time.start.hour;\n  return (\n    <Segment\n      slot=\"time-picker-minute\"\n      inputMode=\"numeric\"\n      aria-label={time.labels.minute}\n      aria-valuenow={minute ?? undefined}\n      aria-valuemin={0}\n      aria-valuemax={59}\n      aria-valuetext={minute === null ? time.labels.empty : pad(minute)}\n      text={minute === null ? EMPTY : pad(minute)}\n      onStep={(direction) => {\n        if (minute === null) return time.set(time.start.hour, time.start.minute);\n        const next = direction === 1 ? Math.floor(minute / minuteStep) * minuteStep + minuteStep : Math.ceil(minute / minuteStep) * minuteStep - minuteStep;\n        const last = Math.floor(59 / minuteStep) * minuteStep;\n        time.set(hour, next > 59 ? 0 : next < 0 ? last : next);\n      }}\n      onLimit={(end) => time.set(hour, end === -1 ? 0 : Math.floor(59 / minuteStep) * minuteStep)}\n      range={[0, 59]}\n      onNumber={(typed) => time.set(hour, typed)}\n      {...props}\n    />\n  );\n}\n\n/** Before or after noon, in the locale's words. Up, Down or a press switches it; typing the first letter of either sets it. */\nexport function TimePickerPeriod({ className, onClick, ...props }: TimePickerPartProps) {\n  const time = useTime(\"TimePickerPeriod\");\n  const { hour, periods } = time;\n  const minute = time.minute ?? time.start.minute;\n  const half = hour !== null && hour >= 12 ? 1 : 0;\n  const to = (next: number): void => time.set(((hour ?? time.start.hour) % 12) + next * 12, minute);\n  const length = Math.max(periods[0].length, periods[1].length);\n  return (\n    <Segment\n      slot=\"time-picker-period\"\n      inputMode=\"none\"\n      // As wide as the longer of the two words.\n      style={{ width: `${length + 0.5}ch` }}\n      aria-label={time.labels.period}\n      aria-valuenow={hour === null ? undefined : half}\n      aria-valuemin={0}\n      aria-valuemax={1}\n      aria-valuetext={hour === null ? time.labels.empty : periods[half]}\n      text={hour === null ? EMPTY : periods[half]}\n      onStep={() => to(hour === null ? half : 1 - half)}\n      onLimit={(end) => to(end === -1 ? 0 : 1)}\n      onLetter={(letter) => {\n        const first = periods.findIndex((period) => period.toLowerCase().startsWith(letter));\n        if (first !== -1) to(first);\n      }}\n      onClick={(event) => {\n        onClick?.(event);\n        if (!event.defaultPrevented) to(hour === null ? half : 1 - half);\n      }}\n      className={cn(\"ms-1 cursor-pointer\", className)}\n      {...props}\n    />\n  );\n}\n\n/** The mark between the hour and the minute. Decoration: screen readers hear the parts' own names. */\nexport function TimePickerSeparator({ className, children, ...props }: ComponentProps<\"span\">) {\n  return (\n    <span aria-hidden=\"true\" data-slot=\"time-picker-separator\" className={cn(\"text-muted-foreground\", className)} {...props}>\n      {children ?? \":\"}\n    </span>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Any time of the person's own choosing: an opening hour, a reminder, an arrival. When the times on offer are a fixed list use slot-picker. Never the browser's native time input. Name it with `aria-label` or `aria-labelledby`.",
    "example": "<p id=\"opens-label\">Opens at</p>\n<TimePicker aria-labelledby=\"opens-label\" defaultValue=\"09:30\" minuteStep={5} name=\"opens\" locale=\"en-GB\" />\n\n// Controlled, limited, 12-hour whatever the locale, with translated names\n<TimePicker\n  value={time}\n  onValueChange={setTime}\n  min=\"08:00\"\n  max=\"18:00\"\n  hourCycle={12}\n  aria-label=\"Pick-up time\"\n  labels={{ hour: \"Hour\", minute: \"Minute\", period: \"Morning or afternoon\", empty: \"Not set\" }}\n/>",
    "client": true
  }
}
