# Field

Groups a control with its label, description and error, and reports whether it is invalid, touched or focused on each of them.

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

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

/** What the kit's `Field` hands its `view` closure. */
export type FieldParts = Component.Headless.Parts<typeof Field>

interface ClassOption {
  readonly class?: string | undefined
}

const orientations = {
  vertical: "flex-col gap-1.5",
  horizontal: "flex-row items-center justify-between gap-4"
} as const

export type FieldOrientation = keyof typeof orientations

/**
 * The field's root. `vertical` stacks the label, the control and the text
 * under it. `horizontal` puts a `FieldContent` on the left and a small
 * control, such as a switch, on the right.
 */
export const FieldRoot = <Msg>(
  h: Html.H<Msg>,
  field: FieldParts,
  options: ClassOption & { readonly orientation?: FieldOrientation | undefined } = {}
) => field.root(h.div.class(cn("flex w-full min-w-0", orientations[options.orientation ?? "vertical"], options.class)))

/** The column of label and description in a horizontal field. */
export const FieldContent = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("flex min-w-0 flex-col gap-0.5", options.class))

export const FieldLabel = <Msg>(h: Html.H<Msg>, field: FieldParts, options: ClassOption = {}) =>
  field.label(
    h.label.class(cn(
      "text-[13px] leading-snug font-medium data-[disabled]:opacity-50 data-[invalid]:text-destructive",
      options.class
    ))
  )

/** The name of a field drawn with `field.group`, such as a range slider or a one-time code. */
export const FieldLegend = <Msg>(h: Html.H<Msg>, field: FieldParts, options: ClassOption = {}) =>
  field.legend(
    h.div.class(cn(
      "text-[13px] leading-snug font-medium data-[disabled]:opacity-50 data-[invalid]:text-destructive",
      options.class
    ))
  )

/** Needs `described: true` in the field's props, so the control points at it. */
export const FieldDescription = <Msg>(h: Html.H<Msg>, field: FieldParts, options: ClassOption = {}) =>
  field.description(
    h.p.class(cn("m-0 text-xs leading-normal text-muted-foreground data-[disabled]:opacity-50", options.class))
  )

/** `undefined` unless the field is invalid and enabled: `FieldError(h, field)?.children(message)`. */
export const FieldError = <Msg>(h: Html.H<Msg>, field: FieldParts, options: ClassOption = {}) =>
  field.error(h.div.class(cn("text-xs leading-normal text-destructive", options.class)))
```

```ts
import { FieldRoot, FieldContent, FieldLabel, FieldLegend, FieldDescription, FieldError } from "#ui/field"
```

## Usage

The label names the input and the input points at the description, with no id written.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldDescription, FieldLabel, FieldRoot } from "#ui/field"
import { Input } from "#ui/input"

const FieldBasicMessage = UiSchema.TaggedEnum({ UpdatedName: { value: Schema.String } })

export const FieldBasic = Html.component({
  name: "FieldBasic",
  model: Schema.Struct({ name: Schema.String }),
  message: FieldBasicMessage
}).make({
  init: () => ({ name: "" }),
  update: {
    UpdatedName: ($, { value }) => $.evolve({ name: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Field(h, {
        props: { described: true, filled: model.name !== "" },
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children("Display name"),
            Input(h, {
              element: field.control(h.input),
              props: { value: model.name },
              onUpdate: ({ value }) => FieldBasicMessage.UpdatedName({ value })
            }).attrs({ name: "name", placeholder: "Ada Lovelace" }),
            FieldDescription(h, field).children(
              "Shown next to your comments and commits."
            )
          )
      })
    )
})
```

## Examples

### Validation

Rules from Validation, mapped to the field with fieldValidationProps, with the error shown as you type.

```ts
import { UiSchema, Validation } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, fieldValidationProps } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { Input } from "#ui/input"

const EmailValidation = Validation.make({
  email: {
    required: "Email is required",
    rules: [
      Validation.Rule.email("Enter an email address, such as ada@example.com"),
      Validation.Rule.endsWith("@example.com", "Use your @example.com address")
    ]
  }
}, { mode: "onChange" })

const FieldValidationMessage = UiSchema.TaggedEnum({ UpdatedEmail: { value: Schema.String } })

export const FieldValidation = Html.component({
  name: "FieldValidation",
  model: Schema.Struct({ form: EmailValidation.State }),
  message: FieldValidationMessage
}).make({
  init: () => ({ form: EmailValidation.init({ email: "" }) }),
  update: {
    UpdatedEmail: ($, { value }) =>
      $.evolve({ form: (form) => EmailValidation.change(form, "email", value) })
  },
  view: (h, model) => {
    const { email } = EmailValidation.validate(model.form).fields
    return h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Field(h, {
        props: { ...fieldValidationProps(email), described: true },
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children("Work email"),
            Input(h, {
              element: field.control(h.input),
              props: { value: email.value },
              onUpdate: ({ value }) => FieldValidationMessage.UpdatedEmail({ value })
            }).attrs({ type: "email", name: "email", placeholder: "ada@example.com" }),
            FieldDescription(h, field).children(
              field.valid ? "This address can receive invoices." : "The result shows once you start typing."
            ),
            // `error` is undefined unless the field is invalid and enabled.
            FieldError(h, field)?.children(
              email._tag === "Invalid" ? email.errors[0] : null
            )
          )
      })
    )
  }
})
```

### Required

A required field that is checked when it loses focus.

```ts
import { UiSchema, Validation } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, fieldValidationProps } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { Input } from "#ui/input"

const ProjectValidation = Validation.make({
  name: {
    required: "A project needs a name",
    rules: [Validation.Rule.minLength(3), Validation.Rule.maxLength(24)]
  }
}, { mode: "onBlur" })

const FieldRequiredMessage = UiSchema.TaggedEnum({
  UpdatedName: { value: Schema.String },
  BlurredName: {}
})

export const FieldRequired = Html.component({
  name: "FieldRequired",
  model: Schema.Struct({ form: ProjectValidation.State }),
  message: FieldRequiredMessage
}).make({
  init: () => ({ form: ProjectValidation.init({ name: "" }) }),
  update: {
    UpdatedName: ($, { value }) =>
      $.evolve({ form: (form) => ProjectValidation.change(form, "name", value) }),
    BlurredName: ($) => $.evolve({ form: (form) => ProjectValidation.blur(form, "name") })
  },
  view: (h, model) => {
    const { name } = ProjectValidation.validate(model.form).fields
    return h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Field(h, {
        props: { ...fieldValidationProps(name), described: true },
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children(
              "Project name",
              name.required ? h.span.class("ml-0.5 text-destructive").attr("aria-hidden", "true").children("*") : null
            ),
            // The field handles blur on a layer of its own, so this handler runs as well.
            Input(h, {
              element: field.control(h.input),
              props: { value: name.value },
              onUpdate: ({ value }) => FieldRequiredMessage.UpdatedName({ value })
            })
              .attrs({ name: "project", "aria-required": "true" })
              .on("blur", FieldRequiredMessage.BlurredName()),
            FieldDescription(h, field).children(
              "3 to 24 characters. Checked when you leave the field."
            ),
            FieldError(h, field)?.children(
              name._tag === "Invalid" ? name.errors[0] : null
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children("Click into the field and Tab away to see the error.")
    )
  }
})
```

### With a switch

A horizontal field whose control is a Switch's root.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, Switch } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldContent, FieldDescription, FieldLabel, FieldRoot } from "#ui/field"

const settings = [
  { name: "mentions", label: "Mentions", description: "Email me when someone mentions me." },
  { name: "digest", label: "Weekly digest", description: "A summary of activity every Monday." }
] as const

const FieldSwitchMessage = UiSchema.TaggedEnum({
  ToggledSwitch: { name: Schema.Literals(["mentions", "digest"]), checked: Schema.Boolean }
})

export const FieldSwitch = Html.component({
  name: "FieldSwitch",
  model: Schema.Struct({ mentions: Schema.Boolean, digest: Schema.Boolean }),
  message: FieldSwitchMessage
}).make({
  init: () => ({ mentions: true, digest: false }),
  update: {
    ToggledSwitch: ($, { checked, name }) => $.evolve({ [name]: checked })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      settings.map(({ description, label, name }) =>
        Field(h, {
          key: name,
          props: { described: true },
          view: (field) =>
            FieldRoot(h, field, { orientation: "horizontal" }).children(
              FieldContent(h).children(
                FieldLabel(h, field).children(label),
                FieldDescription(h, field).children(description)
              ),
              Switch(h, {
                props: { checked: model[name], name, disabled: field.disabled },
                onToggle: ({ checked }) => FieldSwitchMessage.ToggledSwitch({ name, checked }),
                view: (parts) =>
                  parts.root(
                    field.control(
                      h.button.class(
                        "inline-flex h-5 w-9 shrink-0 items-center rounded-full bg-input p-0.5 transition-colors duration-150 data-[checked]:bg-brand"
                      )
                    )
                  ).children(
                    parts.thumb(
                      h.span.class(
                        "size-4 rounded-full bg-background shadow-sm transition-transform duration-150 data-[checked]:translate-x-4"
                      )
                    )
                  )
              })
            )
        })
      )
    )
})
```

### With a slider

The field's control is the thumb's range input.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, Slider } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldDescription, FieldLabel, FieldRoot } from "#ui/field"
import {
  SliderControl,
  SliderHeader,
  SliderIndicator,
  SliderRoot,
  SliderThumb,
  SliderTrack,
  SliderValue
} from "#ui/slider"

const FieldSliderMessage = UiSchema.TaggedEnum({ MovedSlider: { value: Schema.Number } })

export const FieldSlider = Html.component({
  name: "FieldSlider",
  model: Schema.Struct({ quality: Schema.Number }),
  message: FieldSliderMessage
}).make({
  init: () => ({ quality: 80 }),
  update: {
    MovedSlider: ($, { value }) => $.evolve({ quality: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Field(h, {
        props: { described: true },
        view: (field) =>
          FieldRoot(h, field).children(
            Slider(h, {
              props: { value: model.quality, min: 10, step: 5, disabled: field.disabled },
              onEmit: {
                Moved: ({ value }) =>
                  typeof value === "number" ? FieldSliderMessage.MovedSlider({ value }) : undefined,
                Committed: () => undefined
              },
              view: (slider) =>
                SliderRoot(h, slider).children(
                  SliderHeader(h, slider).children(
                    FieldLabel(h, field).children("Image quality"),
                    SliderValue(h, slider).children(`${model.quality}%`)
                  ),
                  SliderControl(h, slider).children(
                    SliderTrack(h, slider).children(
                      SliderIndicator(h, slider),
                      // The field's control is the thumb's range input, so the label names it.
                      SliderThumb(h, slider, { input: field.control(h.input).attr("name", "quality") })
                    )
                  )
                )
            }),
            FieldDescription(h, field).children(
              model.quality < 50 ? "Small files with visible artefacts." : "Larger files that stay sharp."
            )
          )
      })
    )
})
```

### Textarea and select

Any native control takes field.control.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field } from "@effect/ui-kit"
import { Schema } from "effect"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { inputVariants } from "#ui/input"

const roles = ["Viewer", "Editor", "Owner"] as const

const FieldControlsMessage = UiSchema.TaggedEnum({
  UpdatedBio: { value: Schema.String },
  ChoseRole: { value: Schema.String }
})

const limit = 120

export const FieldControls = Html.component({
  name: "FieldControls",
  model: Schema.Struct({ bio: Schema.String, role: Schema.String }),
  message: FieldControlsMessage
}).make({
  init: () => ({ bio: "", role: "Editor" }),
  update: {
    UpdatedBio: ($, { value }) => $.evolve({ bio: value }),
    ChoseRole: ($, { value }) => $.evolve({ role: value })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Field(h, {
        key: "bio",
        props: { described: true, invalid: model.bio.length > limit, filled: model.bio !== "" },
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children("Bio"),
            field.control(h.textarea.class(inputVariants({ class: "h-auto min-h-19 resize-y py-2" })))
              .attrs({ name: "bio", rows: "3", placeholder: "A sentence about you" })
              .value(model.bio)
              .on("input", ({ value }) => FieldControlsMessage.UpdatedBio({ value })),
            FieldDescription(h, field).children(
              `${model.bio.length} of ${limit} characters`
            ),
            FieldError(h, field)?.children(
              `Remove ${model.bio.length - limit} characters`
            )
          )
      }),
      Field(h, {
        key: "role",
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children("Role"),
            field.control(h.select.class(inputVariants()))
              .attr("name", "role")
              .value(model.role)
              .on("change", ({ value }) => FieldControlsMessage.ChoseRole({ value }))
              .children(roles.map((role) => h.option.attr("value", role).children(role)))
          )
      })
    )
})
```

### Disabled

A disabled field disables its control, marks every part and hides its error.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { Input } from "#ui/input"

const FieldDisabledMessage = UiSchema.TaggedEnum({
  UpdatedDomain: { value: Schema.String },
  PressedLock: {}
})

export const FieldDisabled = Html.component({
  name: "FieldDisabled",
  model: Schema.Struct({ domain: Schema.String, locked: Schema.Boolean }),
  message: FieldDisabledMessage
}).make({
  init: () => ({ domain: "effect.website", locked: true }),
  update: {
    UpdatedDomain: ($, { value }) => $.evolve({ domain: value }),
    PressedLock: ($) => $.evolve({ locked: (locked) => !locked })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-90 flex-col gap-3.5").children(
      Field(h, {
        props: { disabled: model.locked, described: true, invalid: model.domain === "" },
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children("Custom domain"),
            Input(h, {
              element: field.control(h.input),
              props: { value: model.domain },
              onUpdate: ({ value }) => FieldDisabledMessage.UpdatedDomain({ value })
            }).attr("name", "domain"),
            FieldDescription(h, field).children(
              field.disabled ? "Managed by your organisation." : "Point a CNAME record at this domain."
            ),
            FieldError(h, field)?.children("Enter a domain")
          )
      }),
      h.div.children(
        Button(h, { variant: "outline", size: "sm", onPress: FieldDisabledMessage.PressedLock() })
          .children(model.locked ? "Unlock field" : "Lock field")
      )
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | Any element around the field, usually a <div>. |
| `label` | A <label>, pointed at the control's id. |
| `control` | An <input>, <textarea>, <select> or <button>. Its result is another kit call's element. |
| `description` | Any element. Needs the described prop, so the control points at it. |
| `error` | Any element with role="alert". Returns undefined unless the field is invalid and enabled. |
| `group / legend / member` | For a control made of several focusable elements, such as a range slider or an OTP field. |
| `focusWithin` | Around a trigger and its popup, for a select or a combobox. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `invalid` | `boolean` | true marks the field invalid and shows the error, false marks it valid, left out it is neither. |
| `disabled` | `boolean` | Disables the control, sets data-disabled on every part and hides the error. |
| `described` | `boolean` | The field draws a description, so the control gets aria-describedby. |
| `filled` | `boolean` | Sets data-filled. You hold the value, so you say whether there is one. |
| `dirty` | `boolean` | Sets data-dirty. You know the value the field started with. |
| `id` | `string` | The control's id and the label's for. Generated when left out. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-invalid / data-valid` | On every part. Neither while invalid is left out. |
| `data-touched` | The control has lost focus at least once. |
| `data-focused` | The control has focus. |
| `data-filled` | From the filled prop. |
| `data-dirty` | From the dirty prop. |
| `data-disabled` | The field, or a Fieldset around it, is disabled. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
- [Input](https://www.effectcn.com/components/input.md): A native text input whose value lives in your Model.
- [Slider](https://www.effectcn.com/components/slider.md): A controlled slider with one thumb or several, dragged or moved with the keyboard.
