# RangeCalendar

A controlled month grid for picking a start and an end date, with a live preview of the range.

- Page: https://www.effectcn.com/components/range-calendar
- Kind: Headless component with parts
- File: `src/ui/range-calendar.ts`
- Built on: `RangeCalendar` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/range-calendar.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/range-calendar.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { RangeCalendar } from "@effect/ui-kit"
import type { DateTime } from "effect"
import { CalendarGrid, CalendarHeader, CalendarRoot } from "#ui/calendar"

/** What the kit's `RangeCalendar` passes to its `view` closure. */
export type RangeCalendarParts = Component.Headless.Parts<typeof RangeCalendar>

// The cell paints the band of the range, so it has no gaps between days and
// rounds off at each end of a week. The day keeps its own corners.
const cellClass = "p-0 text-center has-data-[in-range]:bg-brand-wash first:rounded-s-sm last:rounded-e-sm " +
  "has-data-[range-start]:rounded-s-sm has-data-[range-end]:rounded-e-sm"

const dayClass = "inline-grid size-8 place-items-center rounded-sm p-0 text-[13px] text-foreground tabular-nums " +
  "transition-colors duration-150 hover:bg-accent focus-visible:relative focus-visible:outline-offset-1 " +
  "not-data-[in-range]:data-[today]:bg-accent data-[today]:font-semibold " +
  "not-data-[in-range]:data-[outside-month]:text-muted-foreground not-data-[in-range]:data-[outside-month]:opacity-55 " +
  "data-[range-start]:bg-brand data-[range-start]:text-brand-foreground data-[range-start]:hover:bg-brand " +
  "data-[range-end]:bg-brand data-[range-end]:text-brand-foreground data-[range-end]:hover:bg-brand " +
  "data-[unavailable]:cursor-not-allowed data-[unavailable]:text-muted-foreground data-[unavailable]:line-through " +
  "data-[unavailable]:hover:bg-transparent " +
  "data-[disabled]:cursor-not-allowed data-[disabled]:text-muted-foreground data-[disabled]:opacity-35! " +
  "data-[disabled]:hover:bg-transparent"

/** The element around the header and the grid. `variant: "ghost"` drops the card. */
export const RangeCalendarRoot = <Msg>(
  h: Html.H<Msg>,
  rangeCalendar: RangeCalendarParts,
  options: { readonly variant?: "card" | "ghost" | undefined; readonly class?: string | undefined } = {}
) => CalendarRoot(h, rangeCalendar, options)

/** Previous, the month and year, next. */
export const RangeCalendarHeader = <Msg>(
  h: Html.H<Msg>,
  rangeCalendar: RangeCalendarParts,
  options: { readonly class?: string | undefined } = {}
) => CalendarHeader(h, rangeCalendar, options)

/**
 * The whole table. The ends of the range are filled with the brand colour and
 * the days between them washed, for the preview as for the committed range.
 */
export const RangeCalendarGrid = <Msg>(
  h: Html.H<Msg>,
  rangeCalendar: RangeCalendarParts,
  options: {
    readonly unavailable?: ((date: DateTime.Utc) => boolean) | undefined
    readonly class?: string | undefined
  } = {}
) => CalendarGrid(h, rangeCalendar, { ...options, cellClass, dayClass })
```

```ts
import { RangeCalendarRoot, RangeCalendarHeader, RangeCalendarGrid } from "#ui/range-calendar"
```

## Usage

The first press sets the anchor, hovering previews the range and the second press commits it.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RangeCalendar } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { RangeCalendarGrid, RangeCalendarHeader, RangeCalendarRoot } from "#ui/range-calendar"

const DateRange = Schema.Struct({ start: Schema.DateTimeUtc, end: Schema.DateTimeUtc })

const RangeCalendarBasicMessage = UiSchema.TaggedEnum({
  PickedCalendarRange: { range: DateRange },
  RequestedCalendarMonth: { month: Schema.DateTimeUtc }
})

const today = DateTime.makeUnsafe("2026-11-26T00:00:00Z")

// The calendar's dates are midnight UTC, so format them in UTC.
const shortDate = new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeZone: "UTC" })

export const RangeCalendarBasic = Html.component({
  name: "RangeCalendarBasic",
  model: Schema.Struct({
    range: Schema.NullOr(DateRange),
    month: Schema.DateTimeUtc
  }),
  message: RangeCalendarBasicMessage
}).make({
  init: () => ({
    range: { start: DateTime.subtract(today, { days: 9 }), end: DateTime.subtract(today, { days: 5 }) },
    month: today
  }),
  update: {
    PickedCalendarRange: ($, { range }) => $.evolve({ range }),
    RequestedCalendarMonth: ($, { month }) => $.evolve({ month })
  },
  view: (h, model) =>
    RangeCalendar(h, {
      props: { value: model.range, month: model.month, today, locale: "en-US" },
      onEmit: {
        Picked: ({ end, start }) => RangeCalendarBasicMessage.PickedCalendarRange({ range: { start, end } }),
        RequestedMonth: ({ month }) => RangeCalendarBasicMessage.RequestedCalendarMonth({ month })
      },
      view: (rangeCalendar) =>
        h.div.class("flex flex-col items-center gap-3.5").children(
          RangeCalendarRoot(h, rangeCalendar).children(
            RangeCalendarHeader(h, rangeCalendar),
            RangeCalendarGrid(h, rangeCalendar)
          ),
          // `anchor` is set between the first press and the second.
          h.p.class("m-0 text-[13px] tabular-nums").children(
            rangeCalendar.anchor !== null
              ? `${DateTime.formatIntl(rangeCalendar.anchor, shortDate)} – pick an end date`
              : model.range === null
              ? "No range picked"
              : shortDate.formatRange(DateTime.toDateUtc(model.range.start), DateTime.toDateUtc(model.range.end))
          )
        )
    })
})
```

## Examples

### With presets

Preset buttons write the range and the shown month straight into the Model.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RangeCalendar } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { Button } from "#ui/button"
import { RangeCalendarGrid, RangeCalendarHeader, RangeCalendarRoot } from "#ui/range-calendar"

const DateRange = Schema.Struct({ start: Schema.DateTimeUtc, end: Schema.DateTimeUtc })
type DateRange = typeof DateRange.Type

const Preset = Schema.Literals(["last-7-days", "last-30-days", "this-month", "last-month"])
type Preset = typeof Preset.Type

const RangeCalendarPresetsMessage = UiSchema.TaggedEnum({
  PickedCalendarRange: { range: DateRange },
  RequestedCalendarMonth: { month: Schema.DateTimeUtc },
  ClickedPreset: { preset: Preset }
})

const today = DateTime.makeUnsafe("2026-11-26T00:00:00Z")
const thisMonth = DateTime.startOf(today, "month")
const lastMonth = DateTime.subtract(thisMonth, { months: 1 })

const presets: ReadonlyArray<{ readonly id: Preset; readonly label: string; readonly range: DateRange }> = [
  { id: "last-7-days", label: "Last 7 days", range: { start: DateTime.subtract(today, { days: 6 }), end: today } },
  { id: "last-30-days", label: "Last 30 days", range: { start: DateTime.subtract(today, { days: 29 }), end: today } },
  {
    id: "this-month",
    label: "This month",
    range: { start: thisMonth, end: DateTime.removeTime(DateTime.endOf(today, "month")) }
  },
  {
    id: "last-month",
    label: "Last month",
    range: { start: lastMonth, end: DateTime.subtract(thisMonth, { days: 1 }) }
  }
]

const sameRange = (a: DateRange | null, b: DateRange) =>
  a !== null &&
  DateTime.toEpochMillis(a.start) === DateTime.toEpochMillis(b.start) &&
  DateTime.toEpochMillis(a.end) === DateTime.toEpochMillis(b.end)

export const RangeCalendarPresets = Html.component({
  name: "RangeCalendarPresets",
  model: Schema.Struct({
    range: Schema.NullOr(DateRange),
    month: Schema.DateTimeUtc
  }),
  message: RangeCalendarPresetsMessage
}).make({
  init: () => ({ range: presets[0]!.range, month: thisMonth }),
  update: {
    PickedCalendarRange: ($, { range }) => $.evolve({ range }),
    RequestedCalendarMonth: ($, { month }) => $.evolve({ month }),
    ClickedPreset: ($, { preset }) => {
      const range = presets.find(({ id }) => id === preset)!.range
      return $.evolve({ range, month: DateTime.startOf(range.end, "month") })
    }
  },
  view: (h, model) =>
    h.div.class("flex w-fit rounded-lg border bg-card shadow-sm").children(
      h.div.class("flex min-w-32 flex-col gap-0.5 border-e p-2").children(
        ...presets.map(({ id, label, range }) =>
          Button(h, {
            size: "sm",
            variant: sameRange(model.range, range) ? "secondary" : "ghost",
            class: "justify-start",
            onPress: RangeCalendarPresetsMessage.ClickedPreset({ preset: id })
          }).attr("aria-pressed", String(sameRange(model.range, range))).children(label)
        )
      ),
      RangeCalendar(h, {
        props: { value: model.range, month: model.month, today, max: today, locale: "en-US" },
        onEmit: {
          Picked: ({ end, start }) => RangeCalendarPresetsMessage.PickedCalendarRange({ range: { start, end } }),
          RequestedMonth: ({ month }) => RangeCalendarPresetsMessage.RequestedCalendarMonth({ month })
        },
        view: (rangeCalendar) =>
          RangeCalendarRoot(h, rangeCalendar, { variant: "ghost", class: "p-3" }).children(
            RangeCalendarHeader(h, rangeCalendar),
            RangeCalendarGrid(h, rangeCalendar)
          )
      })
    )
})
```

### Bounded

min and max limit both ends of the range.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RangeCalendar } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { RangeCalendarGrid, RangeCalendarHeader, RangeCalendarRoot } from "#ui/range-calendar"

const DateRange = Schema.Struct({ start: Schema.DateTimeUtc, end: Schema.DateTimeUtc })

const RangeCalendarBoundedMessage = UiSchema.TaggedEnum({
  PickedCalendarRange: { range: DateRange },
  RequestedCalendarMonth: { month: Schema.DateTimeUtc }
})

const today = DateTime.makeUnsafe("2026-11-26T00:00:00Z")
const lastDay = DateTime.add(today, { days: 60 })

const nightsBetween = (start: DateTime.Utc, end: DateTime.Utc) =>
  Math.round((DateTime.toEpochMillis(end) - DateTime.toEpochMillis(start)) / 86_400_000)

export const RangeCalendarBounded = Html.component({
  name: "RangeCalendarBounded",
  model: Schema.Struct({
    stay: Schema.NullOr(DateRange),
    month: Schema.DateTimeUtc
  }),
  message: RangeCalendarBoundedMessage
}).make({
  init: () => ({ stay: null, month: today }),
  update: {
    PickedCalendarRange: ($, { range }) => $.evolve({ stay: range }),
    RequestedCalendarMonth: ($, { month }) => $.evolve({ month })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      RangeCalendar(h, {
        props: { value: model.stay, month: model.month, today, min: today, max: lastDay, locale: "en-US" },
        onEmit: {
          Picked: ({ end, start }) => RangeCalendarBoundedMessage.PickedCalendarRange({ range: { start, end } }),
          RequestedMonth: ({ month }) => RangeCalendarBoundedMessage.RequestedCalendarMonth({ month })
        },
        view: (rangeCalendar) =>
          RangeCalendarRoot(h, rangeCalendar).children(
            RangeCalendarHeader(h, rangeCalendar),
            RangeCalendarGrid(h, rangeCalendar)
          )
      }),
      model.stay === null
        ? h.p.class("m-0 text-[13px] tabular-nums text-muted-foreground").children("Check in from today, up to 60 days ahead.")
        : h.p.class("m-0 text-[13px] tabular-nums").children(
          `${nightsBetween(model.stay.start, model.stay.end)} nights, from ${
            DateTime.formatIsoDateUtc(model.stay.start)
          } to ${DateTime.formatIsoDateUtc(model.stay.end)}`
        )
    )
})
```

### Unavailable days

A range may span unavailable days, so the consumer validates it in update.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RangeCalendar } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { RangeCalendarGrid, RangeCalendarHeader, RangeCalendarRoot } from "#ui/range-calendar"

const DateRange = Schema.Struct({ start: Schema.DateTimeUtc, end: Schema.DateTimeUtc })

const RangeCalendarUnavailableMessage = UiSchema.TaggedEnum({
  PickedCalendarRange: { range: DateRange },
  RequestedCalendarMonth: { month: Schema.DateTimeUtc }
})

const today = DateTime.makeUnsafe("2026-11-26T00:00:00Z")

const booked = new Set(["2026-12-05", "2026-12-06", "2026-12-07", "2026-12-18", "2026-12-19"])

const isBooked = (date: DateTime.Utc) => booked.has(DateTime.formatIsoDateUtc(date))

const spansBooked = (start: DateTime.Utc, end: DateTime.Utc) => {
  for (let day = start; DateTime.isLessThanOrEqualTo(day, end); day = DateTime.add(day, { days: 1 })) {
    if (isBooked(day)) return true
  }
  return false
}

export const RangeCalendarUnavailable = Html.component({
  name: "RangeCalendarUnavailable",
  model: Schema.Struct({
    stay: Schema.NullOr(DateRange),
    month: Schema.DateTimeUtc,
    rejected: Schema.Boolean
  }),
  message: RangeCalendarUnavailableMessage
}).make({
  init: () => ({ stay: null, month: DateTime.makeUnsafe("2026-12-01T00:00:00Z"), rejected: false }),
  update: {
    // A booked day can't start or end a range, but a range can still span one.
    PickedCalendarRange: ($, { range }) =>
      spansBooked(range.start, range.end)
        ? $.evolve({ rejected: true })
        : $.evolve({ stay: range, rejected: false }),
    RequestedCalendarMonth: ($, { month }) => $.evolve({ month })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      RangeCalendar(h, {
        props: { value: model.stay, month: model.month, today, min: today, locale: "en-US" },
        onEmit: {
          Picked: ({ end, start }) => RangeCalendarUnavailableMessage.PickedCalendarRange({ range: { start, end } }),
          RequestedMonth: ({ month }) => RangeCalendarUnavailableMessage.RequestedCalendarMonth({ month })
        },
        view: (rangeCalendar) =>
          RangeCalendarRoot(h, rangeCalendar).children(
            RangeCalendarHeader(h, rangeCalendar),
            RangeCalendarGrid(h, rangeCalendar, { unavailable: isBooked })
          )
      }),
      model.rejected
        ? h.p.class("m-0 text-[13px] tabular-nums text-destructive").attr("role", "alert").children(
          "Those dates include nights that are already booked."
        )
        : h.p.class("m-0 text-[13px] tabular-nums text-muted-foreground").children(
          model.stay === null
            ? "Struck-through nights are booked."
            : `Booked ${DateTime.formatIsoDateUtc(model.stay.start)} to ${DateTime.formatIsoDateUtc(model.stay.end)}`
        )
    )
})
```

### Read-only

Shows a fixed range that can be browsed but not changed.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { RangeCalendar } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { RangeCalendarGrid, RangeCalendarHeader, RangeCalendarRoot } from "#ui/range-calendar"

const RangeCalendarReadOnlyMessage = UiSchema.TaggedEnum({
  RequestedCalendarMonth: { month: Schema.DateTimeUtc }
})

const today = DateTime.makeUnsafe("2026-11-26T00:00:00Z")

const sprint = {
  start: DateTime.makeUnsafe("2026-11-16T00:00:00Z"),
  end: DateTime.makeUnsafe("2026-11-27T00:00:00Z")
}

export const RangeCalendarReadOnly = Html.component({
  name: "RangeCalendarReadOnly",
  model: Schema.Struct({ month: Schema.DateTimeUtc }),
  message: RangeCalendarReadOnlyMessage
}).make({
  init: () => ({ month: today }),
  update: {
    RequestedCalendarMonth: ($, { month }) => $.evolve({ month })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-3.5").children(
      RangeCalendar(h, {
        // Read-only still browses months and takes focus; it sets no anchor.
        props: { value: sprint, month: model.month, today, readOnly: true, locale: "en-US" },
        onEmit: {
          Picked: () => undefined,
          RequestedMonth: ({ month }) => RangeCalendarReadOnlyMessage.RequestedCalendarMonth({ month })
        },
        view: (rangeCalendar) =>
          RangeCalendarRoot(h, rangeCalendar).children(
            RangeCalendarHeader(h, rangeCalendar),
            RangeCalendarGrid(h, rangeCalendar)
          )
      }),
      h.p.class("m-0 text-[13px] tabular-nums text-muted-foreground").children("Sprint 48 is locked.")
    )
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `root` | Any element around the header and the grid. |
| `heading` | Any element showing rangeCalendar.title. |
| `previous / next` | The <button>s that ask for the neighbouring month. |
| `grid` | The <table>, with aria-multiselectable. |
| `weekday` | A <th> of the header row: weekday({ element, index }). |
| `cell` | A <td> of the body: cell({ element, date }). |
| `day` | The <button> in each cell: day({ element, date, unavailable? }). |
| `anchor` | Value: the first day of a range in progress, or null. |
| `weeks, weekdays, month, title` | Values, as Calendar exposes them. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `{ start: DateTime, end: DateTime } \| null` | The committed range. |
| `month` | `DateTime` | Any date in the month to show. Controlled. |
| `today` | `DateTime` | The current day. |
| `min / max` | `DateTime` | Inclusive bounds for both ends. |
| `firstDayOfWeek` | `0 \| 1 \| ... \| 6` | Defaults to the locale's first day. |
| `locale` | `string \| string[]` | BCP 47 tag for titles and names. |
| `disabled` | `boolean` | Disables every button; no anchor, no preview. |
| `readOnly` | `boolean` | Browsable, but sets no anchor and shows no preview. |

### Events

| Event | Description |
| --- | --- |
| `Picked` | { start, end }: the second press of a range, with the two days in order. |
| `RequestedMonth` | { month }: an arrow or the keyboard asked for another month. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-selected` | On day: the day is in value, the committed range. |
| `data-in-range` | On day: the day is in the range shown, preview or value. |
| `data-range-start` | On day: the first day of the range shown. |
| `data-range-end` | On day: the last day of the range shown. |
| `data-today` | On day: the day is today. |
| `data-outside-month` | On day: the day belongs to a neighbouring month. |
| `data-unavailable` | On day: drawn with unavailable: true. |
| `data-disabled` | On day, previous, next, root, heading and grid. |
| `data-readonly` | On root, heading and grid. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
- [Calendar](https://www.effectcn.com/components/calendar.md): A controlled month grid for picking one date, with full keyboard navigation.
