At least 8 characters.

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/form.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")
    
  3. Import it

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

Usage

Sign up.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.

The server refuses effect, acme and admin.

Validate on blur

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

Required.

Optional, checked only when filled in.

Password checklist

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

  • At least 8 characters
  • An upper-case letter
  • A digit

Submitted values

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

Anatomy

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

PartDescription
rootThe <form>. Writes novalidate, and handles submit on a layer of its own.

API reference

Events

EventDescription
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.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.
  • Field: Groups a control with its label, description and error, and reports whether it is invalid, touched or focused on each of them.
  • Input: A native text input whose value lives in your Model.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.