# DateField

A text input that formats and parses a calendar date for a locale and commits it on blur or Enter.

- Page: https://www.effectcn.com/components/date-field
- Kind: Headless component with parts
- File: `src/ui/date-field.ts`
- Built on: `DateField` 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/date-field.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/date-field.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { DateField } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What the kit's `DateField` passes to its `view` closure. A `DatePicker`'s parts fit too. */
export type DateFieldParts = Pick<Component.Headless.Parts<typeof DateField>, "input" | "pattern">

const base = "h-8.5 w-44 min-w-0 rounded-md border border-input bg-background px-3 text-[13px] text-foreground " +
  "tabular-nums shadow-sm outline-none transition-[border-color,box-shadow] duration-150 " +
  "placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/25 " +
  "data-[invalid]:border-destructive data-[invalid]:focus-visible:ring-destructive/25 " +
  "data-[readonly]:bg-muted data-[readonly]:shadow-none " +
  "data-[disabled]:cursor-not-allowed data-[disabled]:bg-muted data-[disabled]:opacity-60"

const sizes = {
  default: "",
  sm: "h-7 w-36 rounded-sm px-2 text-xs",
  lg: "h-10 w-52 px-3.5 text-sm"
} as const

export type DateFieldSize = keyof typeof sizes

/** The input's classes, for an `<input>` that goes through another part first, such as `field.control`. */
export const dateFieldVariants = (
  options: { readonly size?: DateFieldSize | undefined; readonly class?: string | undefined } = {}
): string => cn(base, sizes[options.size ?? "default"], options.class)

/**
 * The typed date. Its placeholder is the locale's pattern, such as `mm/dd/yyyy`.
 * Inside a `Field`, pass the decorated input as `element`:
 * `DateFieldInput(h, dateField, { element: field.control(h.input) })`.
 */
export const DateFieldInput = <Msg>(
  h: Html.H<Msg>,
  dateField: DateFieldParts,
  options: {
    readonly size?: DateFieldSize | undefined
    readonly class?: string | undefined
    readonly element?: Html.H<Msg>["input"] | undefined
  } = {}
) =>
  dateField.input((options.element ?? h.input).class(dateFieldVariants(options))).attr(
    "placeholder",
    dateField.pattern
  )
```

```ts
import { dateFieldVariants, DateFieldInput } from "#ui/date-field"
```

## Usage

Type a date and press Enter or leave the field. Text that doesn't parse reverts.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { DateField } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { DateFieldInput } from "#ui/date-field"

const DateFieldBasicMessage = UiSchema.TaggedEnum({
  CommittedDateField: { date: Schema.NullOr(Schema.DateTimeUtc) }
})

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

export const DateFieldBasic = Html.component({
  name: "DateFieldBasic",
  model: Schema.Struct({ date: Schema.NullOr(Schema.DateTimeUtc) }),
  message: DateFieldBasicMessage
}).make({
  init: () => ({ date: DateTime.makeUnsafe("2026-11-26T00:00:00Z") }),
  update: {
    CommittedDateField: ($, { date }) => $.evolve({ date })
  },
  view: (h, model) =>
    DateField(h, {
      props: { value: model.date, locale: "en-US" },
      onEmit: {
        Committed: ({ date }) => DateFieldBasicMessage.CommittedDateField({ date })
      },
      view: (dateField) =>
        h.div.class("flex flex-col items-center gap-3").children(
          DateFieldInput(h, dateField).attr("aria-label", "Date"),
          h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(
            model.date === null ? "No date" : DateTime.formatIntl(model.date, longDate)
          )
        )
    })
})
```

## Examples

### ISO format

A locale that writes yyyy-mm-dd, and a hidden input that submits the ISO date under name.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { DateField } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { DateFieldInput } from "#ui/date-field"

const DateFieldIsoMessage = UiSchema.TaggedEnum({
  CommittedDateField: { date: Schema.NullOr(Schema.DateTimeUtc) }
})

export const DateFieldIso = Html.component({
  name: "DateFieldIso",
  model: Schema.Struct({ date: Schema.NullOr(Schema.DateTimeUtc) }),
  message: DateFieldIsoMessage
}).make({
  init: () => ({ date: DateTime.makeUnsafe("2026-11-26T00:00:00Z") }),
  update: {
    CommittedDateField: ($, { date }) => $.evolve({ date })
  },
  view: (h, model) =>
    DateField(h, {
      // Swedish dates are written yyyy-mm-dd. With `name`, a hidden input submits the ISO date.
      props: { value: model.date, locale: "sv-SE", name: "published" },
      onEmit: {
        Committed: ({ date }) => DateFieldIsoMessage.CommittedDateField({ date })
      },
      view: (dateField) =>
        h.div.class("flex flex-col items-center gap-3").children(
          DateFieldInput(h, dateField, { class: "font-mono" }).attr("aria-label", "Published"),
          h.p.class("m-0 font-mono text-xs text-muted-foreground tabular-nums").children(
            `published=${model.date === null ? "" : DateTime.formatIsoDateUtc(model.date)}`
          )
        )
    })
})
```

### Locale formats

One date, four locales. Each field parses its own order, and ISO everywhere.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { DateField } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { DateFieldInput } from "#ui/date-field"

const DateFieldLocalesMessage = UiSchema.TaggedEnum({
  CommittedDateField: { date: Schema.NullOr(Schema.DateTimeUtc) }
})

const locales = [
  { locale: "en-US", label: "English (US)" },
  { locale: "en-GB", label: "English (UK)" },
  { locale: "de-DE", label: "German" },
  { locale: "ja-JP", label: "Japanese" }
]

export const DateFieldLocales = Html.component({
  name: "DateFieldLocales",
  model: Schema.Struct({ date: Schema.NullOr(Schema.DateTimeUtc) }),
  message: DateFieldLocalesMessage
}).make({
  init: () => ({ date: DateTime.makeUnsafe("2026-03-04T00:00:00Z") }),
  update: {
    CommittedDateField: ($, { date }) => $.evolve({ date })
  },
  view: (h, model) =>
    h.div.class("grid grid-cols-2 gap-x-4 gap-y-5").children(
      ...locales.map(({ label, locale }) =>
        DateField(h, {
          key: locale,
          props: { value: model.date, locale },
          onEmit: {
            Committed: ({ date }) => DateFieldLocalesMessage.CommittedDateField({ date })
          },
          view: (dateField) =>
            h.label.class("flex flex-col items-start gap-1.5").children(
              h.span.class("text-[13px] font-medium").children(label),
              DateFieldInput(h, dateField),
              h.span.class("text-xs text-muted-foreground").children(dateField.pattern)
            )
        })
      )
    )
})
```

### Label, description and error

Inside a Field, which names the input and shows the consumer's validation.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { DateField, Field } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { DateFieldInput } from "#ui/date-field"

const DateFieldLabelledMessage = UiSchema.TaggedEnum({
  CommittedDateField: { date: Schema.NullOr(Schema.DateTimeUtc) }
})

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

const errorOf = (date: DateTime.Utc | null): string | null =>
  date === null
    ? "Enter a due date."
    : DateTime.isLessThan(date, today)
    ? "The due date can't be in the past."
    : null

export const DateFieldLabelled = Html.component({
  name: "DateFieldLabelled",
  model: Schema.Struct({ date: Schema.NullOr(Schema.DateTimeUtc) }),
  message: DateFieldLabelledMessage
}).make({
  init: () => ({ date: DateTime.makeUnsafe("2026-11-20T00:00:00Z") }),
  update: {
    CommittedDateField: ($, { date }) => $.evolve({ date })
  },
  view: (h, model) => {
    const error = errorOf(model.date)
    return Field(h, {
      props: { invalid: error !== null, described: true },
      view: (field) =>
        DateField(h, {
          props: { value: model.date, locale: "en-US", name: "due", required: true, disabled: field.disabled },
          onEmit: {
            Committed: ({ date }) => DateFieldLabelledMessage.CommittedDateField({ date })
          },
          view: (dateField) =>
            field.root(h.div.class("flex flex-col items-start gap-1.5")).children(
              field.label(h.label.class("text-[13px] font-medium")).children("Due date"),
              DateFieldInput(h, dateField, { element: field.control(h.input), class: "w-56" }),
              field.description(h.p.class("m-0 text-xs text-muted-foreground")).children("Invoices are due at the end of this day."),
              field.error(h.div.class("text-xs text-destructive"))?.children(error ?? "")
            )
        })
    })
  }
})
```

### Sizes

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { DateField } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { DateFieldInput } from "#ui/date-field"

const DateFieldSizesMessage = UiSchema.TaggedEnum({
  CommittedDateField: { date: Schema.NullOr(Schema.DateTimeUtc) }
})

const sizes = ["sm", "default", "lg"] as const

export const DateFieldSizes = Html.component({
  name: "DateFieldSizes",
  model: Schema.Struct({ date: Schema.NullOr(Schema.DateTimeUtc) }),
  message: DateFieldSizesMessage
}).make({
  init: () => ({ date: DateTime.makeUnsafe("2026-11-26T00:00:00Z") }),
  update: {
    CommittedDateField: ($, { date }) => $.evolve({ date })
  },
  view: (h, model) =>
    h.div.class("flex flex-wrap items-center justify-center gap-3").children(
      ...sizes.map((size) =>
        DateField(h, {
          key: size,
          props: { value: model.date, locale: "en-US" },
          onEmit: {
            Committed: ({ date }) => DateFieldSizesMessage.CommittedDateField({ date })
          },
          view: (dateField) => DateFieldInput(h, dateField, { size }).attr("aria-label", `Date, ${size}`)
        })
      )
    )
})
```

### Disabled and read-only

Disabled submits nothing; read-only stays focusable and selectable but commits nothing.

```ts
import { Html } from "@effect/ui/html"
import { DateField } from "@effect/ui-kit"
import { DateTime, Schema } from "effect"
import { DateFieldInput } from "#ui/date-field"

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

export const DateFieldDisabled = Html.component({
  name: "DateFieldDisabled",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    h.div.class("flex flex-wrap justify-center gap-4").children(
      // Neither field commits, so there is no `onEmit`.
      DateField(h, {
        key: "disabled",
        props: { value: created, locale: "en-US", disabled: true },
        view: (dateField) =>
          h.label.class("flex flex-col items-start gap-1.5").children(
            h.span.class("text-[13px] font-medium text-muted-foreground").children("Disabled"),
            DateFieldInput(h, dateField)
          )
      }),
      DateField(h, {
        key: "read-only",
        props: { value: created, locale: "en-US", readOnly: true },
        view: (dateField) =>
          h.label.class("flex flex-col items-start gap-1.5").children(
            h.span.class("text-[13px] font-medium").children("Read-only"),
            DateFieldInput(h, dateField)
          )
      })
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `input` | The <input>. The kit wraps it in a display: contents span that also holds the hidden form input. |
| `pattern` | Value: the locale's pattern, such as dd/mm/yyyy, for a placeholder or hint. |
| `value, inputValue` | Values: the normalized date and the text the input shows. |
| `disabled, readOnly, required` | Values: the props, as booleans. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `DateTime \| null` | The date, or null for an empty field. |
| `locale` | `string \| string[]` | Formats, parses and derives pattern. |
| `name` | `string` | Adds a hidden input that submits the date as YYYY-MM-DD. |
| `form` | `string` | The id of the form that submits it, when outside one. |
| `disabled` | `boolean` | Disables both inputs and commits nothing. |
| `readOnly` | `boolean` | Focusable and selectable, but commits nothing. |
| `required` | `boolean` | Sets the native required attribute. |

### Events

| Event | Description |
| --- | --- |
| `Committed` | { date }: blur or Enter with a parsed date that differs from value. Empty text commits null. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-disabled` | On input: the field is disabled. |
| `data-readonly` | On input: the field is read-only. |
| `data-required` | On input: the field is required. |
| `data-invalid` | On input, from an enclosing Field whose invalid is true. |
