# Form

A form that moves focus to its first invalid control after a submit.

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

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

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

interface ClassOption {
  readonly class?: string | undefined
}

/** The `<form>`: a column of fields. After a submit it focuses its first invalid control. */
export const FormRoot = <Msg>(h: Html.H<Msg>, form: FormParts, options: ClassOption = {}) =>
  form.root(h.form.class(cn("flex w-full max-w-90 flex-col gap-4", options.class)))

/** The row for the submit button and a `FormStatus`. */
export const FormActions = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.div.class(cn("flex items-center gap-3 pt-1", options.class))

/** A polite note beside the submit button, such as "Saved". */
export const FormStatus = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.span.class(cn("text-xs text-muted-foreground", options.class)).attr("role", "status")
```

```ts
import { FormRoot, FormActions, FormStatus } from "#ui/form"
```

## Usage

Validated with Validation. Submit it empty: every field shows its error and the first one takes focus.

```ts
import { UiSchema, Validation } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, fieldValidationProps, Form } from "@effect/ui-kit"
import { Option, Redacted, Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { FormActions, FormRoot, FormStatus } from "#ui/form"
import { Input } from "#ui/input"

const SignUpValidation = Validation.make({
  name: { required: "Enter your name" },
  email: {
    required: "Enter your email",
    rules: [Validation.Rule.email("Enter an email address, such as ada@example.com")]
  },
  password: {
    value: Schema.Redacted(Schema.String),
    required: "Choose a password",
    rules: [[
      (password) => Redacted.value(password).length >= 8,
      "Use at least 8 characters"
    ]]
  }
})

const TextFieldName = Schema.Literals(["name", "email"])

const FormSignUpMessage = UiSchema.TaggedEnum({
  UpdatedField: { name: TextFieldName, value: Schema.String },
  UpdatedPassword: { value: Schema.Redacted(Schema.String) },
  SubmittedForm: {}
})

export const FormSignUp = Html.component({
  name: "FormSignUp",
  model: Schema.Struct({
    form: SignUpValidation.State,
    createdFor: Schema.NullOr(Schema.String)
  }),
  message: FormSignUpMessage
}).make({
  init: () => ({
    form: SignUpValidation.init({ name: "", email: "", password: Redacted.make("") }),
    createdFor: null
  }),
  update: {
    UpdatedField: ($, { name, value }) =>
      $.evolve({ form: (form) => SignUpValidation.change(form, name, value), createdFor: null }),
    UpdatedPassword: ($, { value }) =>
      $.evolve({ form: (form) => SignUpValidation.change(form, "password", value), createdFor: null }),
    // A tried submit shows every field. This runs before the render the form
    // reads, so the first field it marks invalid is the one that gets focus.
    SubmittedForm: ($) => {
      const form = SignUpValidation.submit($.model.form)
      return Option.match(SignUpValidation.validate(form).value, {
        onNone: () => ({ form, createdFor: null }),
        onSome: ({ email }) => ({ form, createdFor: email })
      })
    }
  },
  view: (h, model) => {
    const { fields } = SignUpValidation.validate(model.form)

    const text = (name: typeof TextFieldName.Type, label: string, type: string, autocomplete: string) =>
      Field(h, {
        key: name,
        props: fieldValidationProps(fields[name]),
        view: (field) =>
          FieldRoot(h, field).children(
            FieldLabel(h, field).children(label),
            Input(h, {
              element: field.control(h.input),
              props: { value: fields[name].value },
              onUpdate: ({ value }) => FormSignUpMessage.UpdatedField({ name, value })
            }).attrs({ name, type, autocomplete }),
            FieldError(h, field)?.children(
              fields[name]._tag === "Invalid" ? fields[name].errors[0] : null
            )
          )
      })

    return Form(h, {
      onEmit: () => FormSignUpMessage.SubmittedForm(),
      view: (form) =>
        FormRoot(h, form).children(
          text("name", "Name", "text", "name"),
          text("email", "Email", "email", "email"),
          Field(h, {
            key: "password",
            props: { ...fieldValidationProps(fields.password), described: true },
            view: (field) =>
              FieldRoot(h, field).children(
                FieldLabel(h, field).children("Password"),
                // No name: a secret stays out of the form's Submitted event.
                Input(h, {
                  element: field.control(h.input),
                  props: { value: Redacted.value(fields.password.value) },
                  onUpdate: ({ value }) => FormSignUpMessage.UpdatedPassword({ value: Redacted.make(value) })
                }).attrs({ type: "password", autocomplete: "new-password" }),
                FieldDescription(h, field).children("At least 8 characters."),
                FieldError(h, field)?.children(
                  fields.password._tag === "Invalid" ? fields.password.errors[0] : null
                )
              )
          }),
          FormActions(h).children(
            h.button.class(buttonVariants()).attr("type", "submit").children("Create account"),
            model.createdFor === null
              ? null
              : FormStatus(h).children(
                `Account created for ${model.createdFor}`
              )
          )
        )
    })
  }
})
```

## Examples

### Server error

A Command stands in for the server. Its rejection lands on the field with reject, and the field is focused.

```ts
import { Command, UiSchema, Validation } from "@effect/ui"
import { Html, HtmlCommand } from "@effect/ui/html"
import { Field, fieldValidationProps, Form } from "@effect/ui-kit"
import { Effect, Option, Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { FormActions, FormRoot, FormStatus } from "#ui/form"
import { Input } from "#ui/input"

const WorkspaceValidation = Validation.make({
  slug: {
    required: "Pick a workspace URL",
    rules: [
      Validation.Rule.minLength(3),
      Validation.Rule.pattern(/^[a-z0-9-]+$/, "Use lowercase letters, digits and dashes")
    ]
  }
})

const FormServerErrorMessage = UiSchema.TaggedEnum({
  UpdatedSlug: { value: Schema.String },
  SubmittedForm: {},
  SucceededCreateWorkspace: { slug: Schema.String },
  FailedCreateWorkspace: { message: Schema.String }
})

const taken = ["effect", "acme", "admin"]

// Stands in for the server. A real one is a Command.Service whose Layer calls the API.
const CreateWorkspace = Command.make(
  "CreateWorkspace",
  { args: { slug: Schema.String } },
  ({ slug }) =>
    Effect.sleep("700 millis").pipe(
      Effect.as(
        taken.includes(slug)
          ? FormServerErrorMessage.FailedCreateWorkspace({ message: `"${slug}" is already taken` })
          : FormServerErrorMessage.SucceededCreateWorkspace({ slug })
      )
    )
)

const SlugInput = Html.ref("SlugInput", "input")

export const FormServerError = Html.component({
  name: "FormServerError",
  model: Schema.Struct({
    form: WorkspaceValidation.State,
    submitting: Schema.Boolean,
    created: Schema.NullOr(Schema.String)
  }),
  message: FormServerErrorMessage
}).make({
  init: () => ({ form: WorkspaceValidation.init({ slug: "effect" }), submitting: false, created: null }),
  update: {
    UpdatedSlug: ($, { value }) =>
      $.model.submitting
        ? $.model
        : $.evolve({ form: (form) => WorkspaceValidation.change(form, "slug", value), created: null }),
    SubmittedForm: ($) => {
      const form = WorkspaceValidation.submit($.model.form)
      return Option.match(WorkspaceValidation.validate(form).value, {
        onNone: () => $.evolve({ form }),
        onSome: ({ slug }) =>
          $.model.submitting
            ? $.model
            : $.evolve({ form, submitting: true, created: null }).run(CreateWorkspace.make({ slug }))
      })
    },
    SucceededCreateWorkspace: ($, { slug }) => $.evolve({ submitting: false, created: slug }),
    // The form only focuses errors known at the render after a submit, so a
    // server's error is focused here. It stays on the field until the field changes.
    FailedCreateWorkspace: ($, { message }) =>
      $.evolve({
        submitting: false,
        form: (form) => WorkspaceValidation.reject(form, { slug: [message] })
      }).run(HtmlCommand.Focus.make({ ref: SlugInput }).pipe(Command.asNoop))
  },
  view: (h, model) => {
    const { slug } = WorkspaceValidation.validate(model.form).fields
    return Form(h, {
      onEmit: () => FormServerErrorMessage.SubmittedForm(),
      view: (form) =>
        FormRoot(h, form).children(
          Field(h, {
            props: { ...fieldValidationProps(slug), described: true },
            view: (field) =>
              FieldRoot(h, field).children(
                FieldLabel(h, field).children("Workspace URL"),
                Input(h, {
                  element: field.control(h.input),
                  props: { value: slug.value },
                  onUpdate: ({ value }) => FormServerErrorMessage.UpdatedSlug({ value })
                })
                  .ref(SlugInput)
                  .attrs({ name: "slug", readonly: model.submitting ? "" : undefined }),
                FieldDescription(h, field).children(
                  "The server refuses effect, acme and admin."
                ),
                FieldError(h, field)?.children(
                  slug._tag === "Invalid" ? slug.errors[0] : null
                )
              )
          }),
          FormActions(h).children(
            h.button.class(buttonVariants({ class: "aria-disabled:opacity-60" }))
              .attrs({ type: "submit", "aria-disabled": model.submitting ? "true" : undefined })
              .children(model.submitting ? "Creating…" : "Create workspace"),
            model.created === null
              ? null
              : FormStatus(h).children(
                `Created ${model.created}.effect.website`
              )
          )
        )
    })
  }
})
```

### Validate on blur

With mode: "onBlur" a field shows its result once it was left.

```ts
import { UiSchema, Validation } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, fieldValidationProps, Form } from "@effect/ui-kit"
import { Option, Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { FieldDescription, FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { FormActions, FormRoot, FormStatus } from "#ui/form"
import { Input } from "#ui/input"

const ContactValidation = Validation.make({
  email: {
    required: "Enter your email",
    rules: [Validation.Rule.email("Enter an email address, such as ada@example.com")]
  },
  website: {
    rules: [Validation.Rule.url({ message: "Enter a full URL, such as https://effect.website" })]
  }
}, { mode: "onBlur" })

const FieldName = Schema.Literals(["email", "website"])

const fields = [
  { name: "email", label: "Email", type: "email", hint: "Required." },
  { name: "website", label: "Website", type: "url", hint: "Optional, checked only when filled in." }
] as const

const FormOnBlurMessage = UiSchema.TaggedEnum({
  UpdatedField: { name: FieldName, value: Schema.String },
  BlurredField: { name: FieldName },
  SubmittedForm: {}
})

export const FormOnBlur = Html.component({
  name: "FormOnBlur",
  model: Schema.Struct({ form: ContactValidation.State, saved: Schema.Boolean }),
  message: FormOnBlurMessage
}).make({
  init: () => ({ form: ContactValidation.init({ email: "", website: "" }), saved: false }),
  update: {
    UpdatedField: ($, { name, value }) =>
      $.evolve({ form: (form) => ContactValidation.change(form, name, value), saved: false }),
    BlurredField: ($, { name }) => $.evolve({ form: (form) => ContactValidation.blur(form, name) }),
    SubmittedForm: ($) => {
      const form = ContactValidation.submit($.model.form)
      return { form, saved: Option.isSome(ContactValidation.validate(form).value) }
    }
  },
  view: (h, model) => {
    const validated = ContactValidation.validate(model.form)
    return Form(h, {
      onEmit: () => FormOnBlurMessage.SubmittedForm(),
      view: (form) =>
        FormRoot(h, form).children(
          fields.map(({ hint, label, name, type }) => {
            const state = validated.fields[name]
            return Field(h, {
              key: name,
              props: { ...fieldValidationProps(state), described: true },
              view: (field) =>
                FieldRoot(h, field).children(
                  FieldLabel(h, field).children(label),
                  Input(h, {
                    element: field.control(h.input),
                    props: { value: state.value },
                    onUpdate: ({ value }) => FormOnBlurMessage.UpdatedField({ name, value })
                  })
                    .attrs({ name, type })
                    .on("blur", FormOnBlurMessage.BlurredField({ name })),
                  FieldDescription(h, field).children(hint),
                  FieldError(h, field)?.children(
                    state._tag === "Invalid" ? state.errors[0] : null
                  )
                )
            })
          }),
          FormActions(h).children(
            h.button.class(buttonVariants()).attr("type", "submit").children("Save contact"),
            model.saved ? FormStatus(h).children("Saved") : null
          )
        )
    })
  }
})
```

### Password checklist

The rules of a field listed as requirements, and a rule that compares two fields.

```ts
import { UiSchema, Validation } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Field, fieldValidationProps, Form } from "@effect/ui-kit"
import { Equal, Option, Redacted, Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { FieldError, FieldLabel, FieldRoot } from "#ui/field"
import { FormActions, FormRoot, FormStatus } from "#ui/form"
import { Input } from "#ui/input"

const Secret = Schema.Redacted(Schema.String)

const PasswordValidation = Validation.make({
  password: {
    value: Secret,
    required: "Choose a password",
    rules: [
      [(password) => Redacted.value(password).length >= 8, "At least 8 characters"],
      [(password) => /[A-Z]/.test(Redacted.value(password)), "An upper-case letter"],
      [(password) => /\d/.test(Redacted.value(password)), "A digit"]
    ]
  },
  // A rule also gets every value, so it can compare two fields.
  confirm: {
    value: Secret,
    required: "Type the password again",
    rules: [[(confirm, values) => Equal.equals(confirm, values.password), "The passwords don't match"]]
  }
}, { mode: "onChange" })

const FieldName = Schema.Literals(["password", "confirm"])

const FormChecklistMessage = UiSchema.TaggedEnum({
  UpdatedSecret: { name: FieldName, value: Secret },
  SubmittedForm: {}
})

export const FormChecklist = Html.component({
  name: "FormChecklist",
  model: Schema.Struct({ form: PasswordValidation.State, changed: Schema.Boolean }),
  message: FormChecklistMessage
}).make({
  init: () => ({
    form: PasswordValidation.init({ password: Redacted.make(""), confirm: Redacted.make("") }),
    changed: false
  }),
  update: {
    UpdatedSecret: ($, { name, value }) =>
      $.evolve({ form: (form) => PasswordValidation.change(form, name, value), changed: false }),
    SubmittedForm: ($) => {
      const form = PasswordValidation.submit($.model.form)
      return { form, changed: Option.isSome(PasswordValidation.validate(form).value) }
    }
  },
  view: (h, model) => {
    const { fields } = PasswordValidation.validate(model.form)
    return Form(h, {
      onEmit: () => FormChecklistMessage.SubmittedForm(),
      view: (form) =>
        FormRoot(h, form).children(
          Field(h, {
            key: "password",
            props: { ...fieldValidationProps(fields.password), described: true },
            view: (field) =>
              FieldRoot(h, field).children(
                FieldLabel(h, field).children("New password"),
                Input(h, {
                  element: field.control(h.input),
                  props: { value: Redacted.value(fields.password.value) },
                  onUpdate: ({ value }) =>
                    FormChecklistMessage.UpdatedSecret({ name: "password", value: Redacted.make(value) })
                }).attrs({ type: "password", autocomplete: "new-password" }),
                // The checklist ignores the mode, so it shows from the first render.
                field.description(h.ul.class("m-0 flex list-none flex-col gap-1 p-0 text-xs text-muted-foreground")).children(
                  PasswordValidation.checklist(model.form, "password").map(({ message, met }) =>
                    h.li
                      .class(
                        "flex items-center gap-2 before:size-1.5 before:rounded-full before:bg-input data-[met]:text-success data-[met]:before:bg-success"
                      )
                      .attr("data-met", met ? "" : undefined)
                      .children(message)
                  )
                ),
                FieldError(h, field)?.children(
                  fields.password._tag === "Invalid" && fields.password.empty ? fields.password.errors[0] : null
                )
              )
          }),
          Field(h, {
            key: "confirm",
            props: fieldValidationProps(fields.confirm),
            view: (field) =>
              FieldRoot(h, field).children(
                FieldLabel(h, field).children("Confirm password"),
                Input(h, {
                  element: field.control(h.input),
                  props: { value: Redacted.value(fields.confirm.value) },
                  onUpdate: ({ value }) =>
                    FormChecklistMessage.UpdatedSecret({ name: "confirm", value: Redacted.make(value) })
                }).attrs({ type: "password", autocomplete: "new-password" }),
                FieldError(h, field)?.children(
                  fields.confirm._tag === "Invalid" ? fields.confirm.errors[0] : null
                )
              )
          }),
          FormActions(h).children(
            h.button.class(buttonVariants()).attr("type", "submit").children("Change password"),
            model.changed
              ? FormStatus(h).children("Password changed")
              : null
          )
        )
    })
  }
})
```

### Submitted values

Submitted carries every named control, so native inputs can keep their own values.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Form } from "@effect/ui-kit"
import { Schema } from "effect"
import { buttonVariants } from "#ui/button"
import { FormActions, FormRoot } from "#ui/form"
import { inputVariants } from "#ui/input"

const Entries = Schema.Array(Schema.Tuple([Schema.String, Schema.String]))

const FormSubmittedValuesMessage = UiSchema.TaggedEnum({
  SubmittedForm: { entries: Entries }
})

export const FormSubmittedValues = Html.component({
  name: "FormSubmittedValues",
  model: Schema.Struct({ entries: Schema.NullOr(Entries) }),
  message: FormSubmittedValuesMessage
}).make({
  init: () => ({ entries: null }),
  update: {
    SubmittedForm: (_, { entries }) => ({ entries })
  },
  view: (h, model) =>
    // The inputs keep their own values here. Submitted carries every named
    // control: `fields` by name, and `entries` in document order.
    Form(h, {
      onEmit: { Submitted: ({ entries }) => FormSubmittedValuesMessage.SubmittedForm({ entries }) },
      view: (form) =>
        FormRoot(h, form).children(
          h.div.class("flex flex-col gap-1.5").children(
            h.label.class("text-[13px] font-medium").attr("for", "form-values-title").children("Title"),
            h.input.class(inputVariants()).attrs({ id: "form-values-title", name: "title", value: "Quarterly report" })
          ),
          h.div.class("flex flex-col gap-1.5").children(
            h.label.class("text-[13px] font-medium").attr("for", "form-values-visibility").children("Visibility"),
            h.select.class(inputVariants()).attrs({ id: "form-values-visibility", name: "visibility" }).children(
              h.option.attr("value", "private").children("Private"),
              h.option.attr("value", "team").children("Team"),
              h.option.attr("value", "public").children("Public")
            )
          ),
          h.div.class("flex flex-col gap-2").children(
            ["email", "slack"].map((channel) =>
              h.label.class("flex items-center gap-2 text-[13px]").children(
                h.input.class("size-3.5 accent-brand").attrs({ type: "checkbox", name: "notify", value: channel, checked: "" }),
                `Notify by ${channel}`
              )
            )
          ),
          FormActions(h).children(
            h.button.class(buttonVariants()).attr("type", "submit").children("Save")
          ),
          model.entries === null ? null : h.dl.class(
            "m-0 grid grid-cols-[auto_1fr] gap-x-4 gap-y-1 rounded-md border bg-muted px-3 py-2.5 font-mono text-xs [&_dd]:m-0 [&_dt]:text-muted-foreground"
          ).children(
            model.entries.flatMap(([name, value]) => [h.dt.children(name), h.dd.children(value)])
          )
        )
    })
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | The <form>. Writes novalidate, and handles submit on a layer of its own. |

## API reference

### Events

| Event | Description |
| --- | --- |
| `Submitted` | { fields, entries }: every submit, with the named controls. fields holds the first value of each name, entries every name and value in document order. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
- [Field](https://www.effectcn.com/components/field.md): Groups a control with its label, description and error, and reports whether it is invalid, touched or focused on each of them.
- [Input](https://www.effectcn.com/components/input.md): A native text input whose value lives in your Model.
