# Calendar

> An inline month grid for choosing one date, backed by a native date input with limits and form validation.

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

## Use when
- The weeks around a date matter, such as when scheduling a release.
- People should be able to type the date or choose it from a month grid.

## Avoid when
- The user must choose both ends of a date range.

## Alternatives
- [date-picker](https://hazeui.com/ui/date-picker.md)
- [date-range-picker](https://hazeui.com/ui/date-range-picker.md)
- [time-picker](https://hazeui.com/ui/time-picker.md)
- [input](https://hazeui.com/ui/input.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique identifier for the date field. |
| name | `string` | id | no | Submitted field name. |
| label | `string` | Date | no | Visible label for the date field. |
| value | `string` |  | no | Initial date in YYYY-MM-DD format. |
| min | `string` |  | no | Earliest allowed date in YYYY-MM-DD format. |
| max | `string` |  | no | Latest allowed date in YYYY-MM-DD format. |
| required | `boolean` |  | no | Requires the user to enter a date. |
| disabled | `boolean` |  | no | Disables the native field. |
| form | `string` |  | no | ID of a form outside the component. |
| locale | `string` | en | no | BCP 47 locale for the calendar labels. |
| weekStart | `0 \| 1` | 1 | no | First day of the week, Sunday or Monday. |
| presentation | `inline \| popover` | inline | no | Renders the grid inline or opens it from a calendar button. |
| openLabel | `string` | Open calendar | no | Accessible name of the popover and its trigger. |
| class | `string` |  | no | Classes for the date field wrapper. |

## Accessibility
- The native input preserves typing, form validation, and reset.
- Once the script runs, the browser's own date popup is replaced by this grid, so two pickers never open at once.
- The grid announces the month and full date of each day.
- Key Arrow keys: Move by a day or week while focused in the grid.
- Key Home / End: Move to the start or end of the week.
- Key Page Up / Page Down: Go back or forward one month. Add Shift to move a year.
- Key Enter / Space: Select the focused date.
- Key Space, F4 or Alt + Down in the field: Open the calendar (popover) or move focus to the grid (inline).

## Agent prompts

### Install and use

Install the Haze UI component "Calendar" with `npx shadcn@latest add @haze/calendar`. 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 Calendar from "@/components/haze/ui/calendar.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/calendar.md

### Customize with real content

Adapt the Haze calendar ui for our product. Replace the demo values of these props with our real content: id, name, label, value, min, max, required, disabled, form, locale, weekStart, presentation, openLabel, class. Keep the layout, the heading level rules and these accessibility details: The native input preserves typing, form validation, and reset. Once the script runs, the browser's own date popup is replaced by this grid, so two pickers never open at once. The grid announces the month and full date of each day. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using calendar, check it fits: use it when the weeks around a date matter, such as when scheduling a release.; people should be able to type the date or choose it from a month grid.. Avoid it when the user must choose both ends of a date range.. Alternatives: @haze/date-picker, @haze/date-range-picker, @haze/time-picker, @haze/input.

## Example requests that should lead here
- Add an inline calendar for selecting a release date.
- Let contributors pick a date from a schedule constrained to this quarter.

## Source

```astro
---
import { CalendarDays, ChevronLeft, ChevronRight } 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;
  required?: boolean;
  disabled?: boolean;
  form?: string;
  locale?: string;
  weekStart?: 0 | 1;
  presentation?: "inline" | "popover";
  openLabel?: string;
  class?: string;
  [key: string]: unknown;
}

const { id, name = id, label = "Date", value, min, max, required, disabled, form,
  locale = "en", weekStart = 1, presentation = "inline", openLabel = "Open calendar", class: className, ...rest } = Astro.props;
const popover = presentation === "popover";
const panelId = `${id}-calendar`;
---

<div data-haze-calendar data-locale={locale} data-week-start={weekStart} class={cn("grid min-w-0 gap-2", className)}>
  <label for={id} class="text-[0.8125rem]/5 font-medium">{label}</label>
  <div class="group flex min-w-0 items-start gap-2" style={popover ? `anchor-name: --${panelId}` : undefined}>
    <Input {...rest} id={id} name={name} type="date" value={value} min={min} max={max} required={required} disabled={disabled} form={form}
      class="[[data-haze-calendar][data-enhanced]_&]:[&::-webkit-calendar-picker-indicator]:hidden" />
    {popover && (
      <Button variant="outline" size="icon" popovertarget={panelId} aria-label={openLabel} aria-haspopup="dialog"
        data-calendar-trigger class="hidden [[data-haze-calendar][data-enhanced]_&]:inline-flex group-has-[input:disabled]:hidden! group-has-[input[readonly]]:hidden!">
        <CalendarDays aria-hidden="true" />
      </Button>
    )}
  </div>
  <div id={popover ? panelId : undefined} popover={popover ? "auto" : undefined}
    role={popover ? "dialog" : undefined} aria-label={popover ? openLabel : undefined}
    data-calendar-popover={popover || undefined}
    style={popover ? `position-anchor: --${panelId}` : undefined}
    class={cn("hidden rounded-xl p-3", popover
      ? "m-auto max-h-[calc(100dvh-1rem)] w-68 max-w-[calc(100vw-1rem)] -translate-y-1 scale-[0.97] overflow-y-auto border border-border bg-popover text-popover-foreground opacity-0 shadow-float transition-[opacity,scale,translate,overlay,display] transition-discrete duration-150 ease-snappy open:block 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]: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,flip-block_flip-inline]"
      : "w-68 max-w-full border border-frame bg-card text-card-foreground [[data-haze-calendar][data-enhanced]_&]:block")}>
    <div class="mb-3 grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1">
      <Button variant="ghost" size="icon" class="size-8" aria-label="Previous month" data-calendar-prev><ChevronLeft aria-hidden="true" class="rtl:rotate-180" /></Button>
      <p id={`${id}-month`} data-calendar-month aria-live="polite" class="text-center text-[0.9375rem]/5 font-medium tracking-[-0.01em] wrap-anywhere"></p>
      <Button variant="ghost" size="icon" class="size-8" aria-label="Next month" data-calendar-next><ChevronRight aria-hidden="true" class="rtl:rotate-180" /></Button>
    </div>
    <table role="grid" aria-labelledby={`${id}-month`} class="w-full table-fixed border-separate border-spacing-x-0 border-spacing-y-1 text-center text-[0.8125rem]/5">
      <thead><tr data-calendar-weekdays></tr></thead>
      <tbody data-calendar-days></tbody>
    </table>
    <template data-calendar-day>
      <button type="button" tabindex="-1" class="mx-auto grid size-8 max-w-full place-items-center rounded-full tabular-nums transition-[color,background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:z-10 focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100 disabled:text-muted-foreground/60 disabled:hover:bg-transparent aria-[current=date]:font-medium aria-[current=date]:underline aria-[current=date]:underline-offset-4 data-[selected]:bg-primary data-[selected]:hover:bg-primary data-[selected]:font-medium data-[selected]:text-primary-foreground"></button>
    </template>
  </div>
</div>

<script>
  const day = 86_400_000;
  const toDate = (value: string) => Date.parse(`${value}T00:00:00Z`);
  const monthOf = (stamp: number) => {
    const date = new Date(stamp);
    date.setUTCDate(1);
    return date.getTime();
  };
  const shiftMonth = (stamp: number, offset: number) => {
    const date = new Date(monthOf(stamp));
    date.setUTCMonth(date.getUTCMonth() + offset);
    return date.getTime();
  };

  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input[type=date]");
    const month = root.querySelector<HTMLElement>("[data-calendar-month]");
    const weekdays = root.querySelector<HTMLTableRowElement>("[data-calendar-weekdays]");
    const days = root.querySelector<HTMLTableSectionElement>("[data-calendar-days]");
    const template = root.querySelector<HTMLTemplateElement>("[data-calendar-day]");
    const prev = root.querySelector<HTMLButtonElement>("[data-calendar-prev]");
    const next = root.querySelector<HTMLButtonElement>("[data-calendar-next]");
    const popup = root.querySelector<HTMLElement>("[data-calendar-popover]");
    const trigger = root.querySelector<HTMLButtonElement>("[data-calendar-trigger]");
    const dayButton = template?.content.querySelector("button");
    if (!input || !month || !weekdays || !days || !dayButton || !prev || !next || input.matches(":disabled, [readonly]")) return;
    if (popup && typeof popup.hidePopover !== "function") return;

    const today = new Date();
    const todayStamp = Date.UTC(today.getFullYear(), today.getMonth(), today.getDate());
    const bound = (value: string, fallback: string) => Number.isFinite(toDate(value)) ? toDate(value) : toDate(fallback);
    const min = bound(input.min, "0001-01-01");
    const max = bound(input.max, "9999-12-31");
    if (min > max) return;
    const weekStart = Number(root.dataset.weekStart);
    const locale = root.dataset.locale;
    const dateFormat = (options: Intl.DateTimeFormatOptions) => new Intl.DateTimeFormat(locale, { ...options, calendar: "gregory", timeZone: "UTC" });
    const heading = dateFormat({ month: "long", year: "numeric" });
    const weekday = dateFormat({ weekday: "narrow" });
    const weekdayName = dateFormat({ weekday: "long" });
    const dayName = dateFormat({ dateStyle: "full" });
    const dayNumber = new Intl.NumberFormat(locale, { useGrouping: false });
    const clamp = (stamp: number) => Math.max(min, Math.min(max, stamp));
    const selectedDate = () => Number.isFinite(input.valueAsNumber) ? input.valueAsNumber : todayStamp;
    const columnOf = (stamp: number) => (new Date(stamp).getUTCDay() + 7 - weekStart) % 7;
    let active = clamp(selectedDate());

    for (let index = 0; index < 7; index += 1) {
      const stamp = Date.UTC(2026, 0, 4 + weekStart + index);
      const cell = document.createElement("th");
      cell.scope = "col";
      cell.className = "h-6 text-xs font-medium text-muted-foreground";
      cell.textContent = weekday.format(stamp);
      cell.setAttribute("aria-label", weekdayName.format(stamp));
      weekdays.append(cell);
    }

    const render = (focus = false) => {
      const first = monthOf(active);
      const nextMonth = shiftMonth(first, 1);
      const selected = toDate(input.value);
      if (month.textContent !== heading.format(first)) month.textContent = heading.format(first);
      prev.disabled = first <= min;
      next.disabled = nextMonth > max;
      days.replaceChildren();
      let activeButton: HTMLButtonElement | undefined;
      for (let rowStart = first - columnOf(first) * day; rowStart < nextMonth; rowStart += day * 7) {
        const row = days.insertRow();
        for (let offset = 0; offset < 7; offset += 1) {
          const cell = row.insertCell();
          const stamp = rowStart + offset * day;
          if (stamp < first || stamp >= nextMonth) continue;
          const button = dayButton.cloneNode(true) as HTMLButtonElement;
          button.dataset.calendarStamp = String(stamp);
          button.textContent = dayNumber.format(new Date(stamp).getUTCDate());
          button.setAttribute("aria-label", dayName.format(stamp));
          if (stamp === todayStamp) button.setAttribute("aria-current", "date");
          button.disabled = stamp < min || stamp > max;
          cell.setAttribute("aria-selected", String(stamp === selected));
          button.toggleAttribute("data-selected", stamp === selected);
          if (stamp === active) {
            button.tabIndex = 0;
            activeButton = button;
          }
          cell.append(button);
        }
      }
      if (focus) activeButton?.focus();
    };

    const navigateMonth = (offset: number, focus: boolean) => {
      const target = shiftMonth(active, offset);
      const dayIndex = new Date(active).getUTCDate() - 1;
      active = clamp(Math.min(target + dayIndex * day, shiftMonth(target, 1) - day));
      render(focus);
    };
    days.addEventListener("click", (event) => {
      const button = (event.target as Element).closest<HTMLButtonElement>("[data-calendar-stamp]");
      if (!button || button.disabled || input.matches(":disabled, [readonly]")) return;
      active = Number(button.dataset.calendarStamp);
      input.value = new Date(active).toISOString().slice(0, 10);
      input.dispatchEvent(new Event("input", { bubbles: true }));
      input.dispatchEvent(new Event("change", { bubbles: true }));
      if (popup?.matches(":popover-open")) {
        popup.hidePopover();
        trigger?.focus();
      } else {
        render(true);
      }
    });
    days.addEventListener("keydown", (event) => {
      if (event.altKey || event.ctrlKey || event.metaKey) return;
      const direction = getComputedStyle(root).direction === "rtl" ? -1 : 1;
      const offsets: Record<string, number | undefined> = {
        ArrowLeft: -direction, ArrowRight: direction, ArrowUp: -7, ArrowDown: 7,
        Home: -columnOf(active), End: 6 - columnOf(active),
      };
      const offset = offsets[event.key];
      if (offset !== undefined) {
        event.preventDefault();
        active = clamp(active + offset * day);
        render(true);
      } else if (event.key === "PageUp" || event.key === "PageDown") {
        event.preventDefault();
        navigateMonth((event.key === "PageUp" ? -1 : 1) * (event.shiftKey ? 12 : 1), true);
      }
    });
    prev.addEventListener("click", () => {
      navigateMonth(-1, false);
      if (prev.disabled) next.focus();
    });
    next.addEventListener("click", () => {
      navigateMonth(1, false);
      if (next.disabled) prev.focus();
    });
    const sync = (focus = false) => {
      active = clamp(selectedDate());
      render(focus);
    };
    input.addEventListener("change", () => sync());
    // Once enhanced, the custom calendar is the only picker: the browser's own date popup would open on top of it.
    // Clicking the field opens the popover (inline: the calendar is already on screen); the picker keys move to the grid.
    const openCustom = () => {
      if (popup) {
        if (!popup.matches(":popover-open")) popup.showPopover();
      } else {
        sync(true);
      }
    };
    // A click on the field while the popover is open light-dismisses it first; don't reopen it straight away.
    let closedAt = -Infinity;
    let pointerOpen = false;
    popup?.addEventListener("toggle", (event) => {
      if ((event as ToggleEvent).newState === "closed") closedAt = performance.now();
    });
    input.addEventListener("click", (event) => {
      if (input.matches(":disabled, [readonly]")) return;
      event.preventDefault();
      // A pointer open leaves focus in the field, so a click on a segment can still be followed by typing.
      if (popup && performance.now() - closedAt > 300) { pointerOpen = true; openCustom(); }
    });
    input.addEventListener("keydown", (event) => {
      if (input.matches(":disabled, [readonly]")) return;
      if (event.key === " " || event.key === "F4" || (event.altKey && event.key === "ArrowDown")) {
        event.preventDefault();
        openCustom();
      }
    });
    if (typeof input.showPicker === "function") input.showPicker = openCustom;
    input.form?.addEventListener("reset", () => queueMicrotask(() => sync()));
    popup?.addEventListener("toggle", () => {
      if (popup.matches(":popover-open")) sync(!pointerOpen);
      pointerOpen = false;
    });
    render();
    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-calendar]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-calendar-listener")) {
    document.documentElement.setAttribute("data-haze-calendar-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
