# Time Picker

> A native time field with labeled step buttons for small, predictable adjustments.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/time-picker`
- File: `src/components/haze/ui/time-picker.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/button, @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/time-picker

## Use when
- A schedule form collects one time of day.
- People often change the time by a fixed interval such as 15 minutes.

## Avoid when
- The field describes a duration or a date range.

## Alternatives
- [calendar](https://hazeui.com/ui/calendar.md)
- [date-range-picker](https://hazeui.com/ui/date-range-picker.md)
- [quantity-stepper](https://hazeui.com/ui/quantity-stepper.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique time field ID. |
| name | `string` | id | no | Submitted field name. |
| label | `string` | Start time | no | Visible time field label. |
| value | `string` |  | no | Initial 24-hour value in HH:MM format. |
| min | `string` |  | no | Earliest time in HH:MM format. |
| max | `string` |  | no | Latest time in HH:MM format. |
| stepMinutes | `number` | 15 | no | Whole minutes per step, clamped to 1–60. |
| required | `boolean` |  | no | Requires a time before submitting. |
| disabled | `boolean` |  | no | Disables the field and step buttons. |
| form | `string` |  | no | ID of a form outside the component. |
| class | `string` |  | no | Classes for the field wrapper. |

## Accessibility
- The time input follows the browser locale and preserves native validation.
- Step buttons have names that include the size of each step.
- Key Tab: Move to the time input or step buttons.
- Key Enter / Space: Adjust the time from a focused step button.

## Agent prompts

### Install and use

Install the Haze UI component "Time Picker" with `npx shadcn@latest add @haze/time-picker`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import TimePicker from "@/components/haze/ui/time-picker.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/time-picker.md

### Customize with real content

Adapt the Haze time-picker ui for our product. Replace the demo values of these props with our real content: id, name, label, value, min, max, stepMinutes, required, disabled, form, class. Keep the layout, the heading level rules and these accessibility details: The time input follows the browser locale and preserves native validation. Step buttons have names that include the size of each step. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using time-picker, check it fits: use it when a schedule form collects one time of day.; people often change the time by a fixed interval such as 15 minutes.. Avoid it when the field describes a duration or a date range.. Alternatives: @haze/calendar, @haze/date-range-picker, @haze/quantity-stepper.

## Example requests that should lead here
- Let people adjust a daily stand-up time in fifteen-minute steps.
- Add a required start-time field constrained to business hours.

## Source

```astro
---
import { Clock, Minus, Plus } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Button from "./button.astro";
import Input from "./input.astro";

interface Props {
  id: string;
  name?: string;
  label?: string;
  value?: string;
  min?: string;
  max?: string;
  stepMinutes?: number;
  required?: boolean;
  disabled?: boolean;
  form?: string;
  class?: string;
  [key: string]: unknown;
}

const {
  id,
  name = id,
  label = "Start time",
  value = "09:30",
  min = "00:00",
  max = "23:59",
  stepMinutes = 15,
  required,
  disabled,
  form,
  class: className,
  ...rest
} = Astro.props;

const step = Number.isFinite(stepMinutes) ? Math.max(1, Math.min(60, Math.round(stepMinutes))) : 15;
const toMins = (hhmm: string) => {
  const [h = 0, m = 0] = hhmm.split(":").map(Number);
  return (Number.isFinite(h) ? h : 0) * 60 + (Number.isFinite(m) ? m : 0);
};
const minMins = toMins(min);
const maxMins = toMins(max);
const [selH = "09", selM = "30"] = value.split(":");

const validHours = Array.from({ length: 24 }, (_, h) => h).filter(
  (h) => h * 60 + 59 >= minMins && h * 60 <= maxMins,
);
const validMinutes: number[] = [];
for (let m = 0; m < 60; m += step) validMinutes.push(m);
const panelId = `${id}-time-popover`;
---

<div data-haze-time-picker class={cn("grid min-w-0 gap-2", className)}>
  <label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
  <div class="flex min-w-0 items-center gap-1.5" style={`anchor-name: --${panelId}`}>
    <Input
      {...rest}
      id={id}
      name={name}
      type="time"
      value={value}
      min={min}
      max={max}
      step={step * 60}
      form={form}
      required={required}
      disabled={disabled}
      class="flex-1 tabular-nums [[data-haze-time-picker][data-enhanced]_&]:[&::-webkit-calendar-picker-indicator]:hidden"
    />
    <Button
      variant="outline"
      size="icon"
      disabled={disabled}
      popovertarget={panelId}
      aria-label={`Choose ${label.toLowerCase()}`}
      aria-haspopup="dialog"
      data-time-trigger
      class="hidden shrink-0 [[data-haze-time-picker][data-enhanced]_&]:inline-flex"
    >
      <Clock class="size-4" aria-hidden="true" />
    </Button>
    <div class="hidden shrink-0 items-center gap-1 [[data-haze-time-picker][data-enhanced]_&]:flex">
      <Button variant="outline" size="icon" disabled={disabled} aria-label={`Subtract ${step} minutes`} data-time-step="-1">
        <Minus aria-hidden="true" />
      </Button>
      <Button variant="outline" size="icon" disabled={disabled} aria-label={`Add ${step} minutes`} data-time-step="1">
        <Plus aria-hidden="true" />
      </Button>
    </div>
  </div>

  <!-- Stylized Hour & Minute Popover -->
  <div
    id={panelId}
    popover="auto"
    role="dialog"
    aria-label={label}
    data-time-popover
    style={`position-anchor: --${panelId}`}
    class="m-auto w-64 max-w-[calc(100vw-1rem)] -translate-y-1 scale-[0.97] rounded-xl border border-border bg-popover p-3 text-popover-foreground opacity-0 shadow-float transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:translate-y-0 open:scale-100 open:opacity-100 backdrop:bg-background/60 starting:open:-translate-y-1 starting:open:scale-[0.97] starting:open:opacity-0 supports-[position-area:block-end]:m-0 supports-[position-area:block-end]:my-1.5 supports-[position-area:block-end]:backdrop:bg-transparent supports-[position-area:block-end]:[position-area:block-end_span-inline-end] supports-[position-area:block-end]:[position-try-fallbacks:flip-block,flip-inline]"
  >
    <div class="mb-2 flex items-center justify-between border-b border-border pb-2 text-xs">
      <span class="font-medium text-foreground">Select time</span>
      <span data-tp-readout class="font-mono text-muted-foreground tabular-nums">{value}</span>
    </div>
    <div class="grid grid-cols-2 gap-2">
      <div class="rounded-lg border border-border bg-card p-1">
        <p class="px-1.5 pb-1 text-[0.6875rem] font-medium text-muted-foreground">Hour</p>
        <div role="listbox" aria-label="Hour" class="grid max-h-40 grid-cols-3 gap-0.5 overflow-y-auto">
          {
            validHours.map((h) => {
              const hs = String(h).padStart(2, "0");
              return (
                <button
                  type="button"
                  role="option"
                  aria-selected={hs === selH ? "true" : "false"}
                  data-tp-hour={hs}
                  class="h-7 cursor-pointer rounded-sm font-mono text-xs tabular-nums text-muted-foreground transition-colors duration-75 hover:bg-accent hover:text-foreground aria-selected:bg-primary aria-selected:font-medium aria-selected:text-primary-foreground focus-visible:outline-2 focus-visible:outline-ring"
                >
                  {hs}
                </button>
              );
            })
          }
        </div>
      </div>

      <div class="rounded-lg border border-border bg-card p-1">
        <p class="px-1.5 pb-1 text-[0.6875rem] font-medium text-muted-foreground">Minute</p>
        <div role="listbox" aria-label="Minute" class="grid max-h-40 grid-cols-2 gap-0.5 overflow-y-auto">
          {
            validMinutes.map((m) => {
              const ms = String(m).padStart(2, "0");
              return (
                <button
                  type="button"
                  role="option"
                  aria-selected={ms === selM ? "true" : "false"}
                  data-tp-min={ms}
                  class="h-7 cursor-pointer rounded-sm font-mono text-xs tabular-nums text-muted-foreground transition-colors duration-75 hover:bg-accent hover:text-foreground aria-selected:bg-primary aria-selected:font-medium aria-selected:text-primary-foreground focus-visible:outline-2 focus-visible:outline-ring"
                >
                  {ms}
                </button>
              );
            })
          }
        </div>
      </div>
    </div>

    <div class="mt-2.5 flex items-center justify-between border-t border-border pt-2">
      <button
        type="button"
        data-tp-now
        class="inline-flex h-8 cursor-pointer items-center rounded-md px-2 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
      >
        Now
      </button>
      <button
        type="button"
        data-tp-done
        class="inline-flex h-8 cursor-pointer items-center rounded-md bg-primary px-3 text-xs font-medium text-primary-foreground transition-[opacity,scale] duration-150 hover:opacity-91 active:scale-[0.97] focus-visible:outline-2 focus-visible:outline-ring"
      >
        Done
      </button>
    </div>
  </div>
  <span aria-live="polite" data-time-status class="sr-only"></span>
</div>

<script>
  function enhanceTimePickers() {
    document.querySelectorAll<HTMLElement>("[data-haze-time-picker]:not([data-enhanced])").forEach((root) => {
      const input = root.querySelector<HTMLInputElement>("input[type=time]");
      const status = root.querySelector<HTMLElement>("[data-time-status]");
      const trigger = root.querySelector<HTMLButtonElement>("[data-time-trigger]");
      const popup = root.querySelector<HTMLElement>("[data-time-popover]");
      const readout = root.querySelector<HTMLElement>("[data-tp-readout]");
      const hBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-tp-hour]"));
      const mBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-tp-min]"));
      if (!input || !status || !popup || typeof popup.showPopover !== "function") return;

      const toMins = (v: string) => {
        const [h = 0, m = 0] = v.split(":").map(Number);
        return h * 60 + m;
      };
      const minM = input.min ? toMins(input.min) : 0;
      const maxM = input.max ? toMins(input.max) : 1439;

      const syncUI = () => {
        const [curH = "09", curM = "30"] = (input.value || "09:30").split(":");
        if (readout) readout.textContent = input.value || "09:30";
        hBtns.forEach((b) => b.setAttribute("aria-selected", String(b.dataset.tpHour === curH)));
        mBtns.forEach((b) => {
          const hm = toMins(`${curH}:${b.dataset.tpMin}`);
          b.disabled = hm < minM || hm > maxM;
          b.setAttribute("aria-selected", String(b.dataset.tpMin === curM));
        });
      };

      const setTime = (nextH: string, nextM: string) => {
        let clamped = Math.max(minM, Math.min(maxM, toMins(`${nextH}:${nextM}`)));
        const hStr = String(Math.floor(clamped / 60)).padStart(2, "0");
        const mStr = String(clamped % 60).padStart(2, "0");
        input.value = `${hStr}:${mStr}`;
        status.textContent = input.value;
        syncUI();
        input.dispatchEvent(new Event("input", { bubbles: true }));
        input.dispatchEvent(new Event("change", { bubbles: true }));
      };

      const openCustom = () => {
        if (!popup.matches(":popover-open")) {
          syncUI();
          popup.showPopover();
        }
      };

      let closedAt = -Infinity;
      popup.addEventListener("toggle", (ev) => {
        if ((ev as ToggleEvent).newState === "closed") closedAt = performance.now();
      });

      input.addEventListener("click", (ev) => {
        if (input.disabled || input.readOnly) return;
        ev.preventDefault();
        if (performance.now() - closedAt > 250) openCustom();
      });
      input.addEventListener("keydown", (ev) => {
        if (ev.key === " " || ev.key === "F4" || (ev.altKey && ev.key === "ArrowDown")) {
          ev.preventDefault();
          openCustom();
        }
      });
      if (typeof input.showPicker === "function") input.showPicker = openCustom;

      hBtns.forEach((b) => {
        b.addEventListener("click", () => {
          const [, curM = "00"] = (input.value || "09:00").split(":");
          setTime(b.dataset.tpHour ?? "09", curM);
        });
      });

      mBtns.forEach((b) => {
        b.addEventListener("click", () => {
          const [curH = "09"] = (input.value || "09:00").split(":");
          setTime(curH, b.dataset.tpMin ?? "00");
        });
      });

      root.querySelector<HTMLButtonElement>("[data-tp-now]")?.addEventListener("click", () => {
        const now = new Date();
        setTime(String(now.getHours()).padStart(2, "0"), String(now.getMinutes()).padStart(2, "0"));
      });

      root.querySelector<HTMLButtonElement>("[data-tp-done]")?.addEventListener("click", () => {
        popup.hidePopover();
        trigger?.focus();
      });

      for (const button of root.querySelectorAll<HTMLButtonElement>("[data-time-step]")) {
        button.addEventListener("click", () => {
          if (input.disabled || input.readOnly) return;
          const previous = input.value;
          input.stepUp(Number(button.dataset.timeStep));
          if (input.value === previous) return;
          status.textContent = input.value;
          syncUI();
          input.dispatchEvent(new Event("input", { bubbles: true }));
          input.dispatchEvent(new Event("change", { bubbles: true }));
        });
      }

      input.addEventListener("change", syncUI);
      syncUI();
      root.setAttribute("data-enhanced", "");
    });
  }

  enhanceTimePickers();
  if (!document.documentElement.hasAttribute("data-haze-time-picker-listener")) {
    document.documentElement.setAttribute("data-haze-time-picker-listener", "");
    document.addEventListener("astro:page-load", enhanceTimePickers);
  }
</script>
```
