A form from one Effect Schema: errors in plain words on blur and submit, an error summary, async checks, server errors on their fields, and focus on the first field to fix.
import { Command, Component, Query, UiSchema } from "@effect/ui"import { Html } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Effect, Option, Schema } from "effect"import { AsyncResult } from "effect/reactivity"import { Button } from "./ui/uicontext/components/Button.ts"import { FormField, inGroup, Input, InputGroup } from "./ui/uicontext/components/FormControls.ts"import { fieldId, focusField, make } from "./ui/uicontext/components/forms/Form.ts"import { ErrorSummary, FormActions } from "./ui/uicontext/components/forms/FormLayout.ts"import { RadioGroup } from "./ui/uicontext/components/RadioGroup.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, radius, space } from "./ui/uicontext/components/tokens.stylex.ts"// Create a workspace: a name, the URL it lives at, and where its data is kept. The URL follows the// name until it's edited, and a debounced check asks the server whether it's free while you type;// a newer keystroke interrupts the check in flight. The server checks again on submit, and its// answer lands on the field it's about.const Workspace = make( Schema.Struct({ name: Schema.Trim.check( Schema.isNonEmpty({ message: "Name your workspace" }), Schema.isMaxLength(48, { message: "Keep the name to 48 characters" }), ).annotate({ title: "Workspace name" }), slug: Schema.String.check( Schema.isNonEmpty({ message: "Choose a URL for the workspace" }), Schema.isMinLength(3, { message: "Use at least 3 characters" }), Schema.isMaxLength(32, { message: "Keep the URL to 32 characters" }), Schema.isPattern(/^[a-z0-9]+(?:-[a-z0-9]+)*$/u, { message: "Use lowercase letters, numbers and single dashes" }), ).annotate({ title: "Workspace URL" }), region: Schema.Literals(["us", "eu", "ap"]).annotate({ title: "Data region", message: "Choose where your data is kept" }), }),)const regions = [ { value: "us", label: "United States", description: "Virginia. Fastest for the Americas." }, { value: "eu", label: "European Union", description: "Frankfurt. Data stays in the EU." }, { value: "ap", label: "Asia Pacific", description: "Singapore." },]// stands in for the server: some URLs are taken, and one more is taken between the check and the submitconst taken = new Set(["acme", "design", "admin", "support", "northwind", "studio"])const takenOnSubmit = new Set(["acme-design"])class IsSlugTaken extends Query.Service<IsSlugTaken>()("example/IsSlugTaken", { args: { slug: Schema.String }, success: Schema.Boolean, staleTime: "30 seconds",}) { // a slow network: the answer takes most of a second, and a newer keystroke interrupts it static readonly layer = this.toLayer(({ slug }) => Effect.sleep("700 millis").pipe(Effect.as(taken.has(slug))))}const Field = Schema.Literals(["name", "slug", "region"])const Message = UiSchema.TaggedEnum({ UpdatedField: { name: Field, value: Schema.String }, BlurredField: { name: Field }, Submitted: {}, AnsweredSlugCheck: {}, SucceededCreateWorkspace: { slug: Schema.String }, FailedCreateWorkspace: { field: Field, message: Schema.String }, ClickedStartOver: {},})class CreateWorkspace extends Command.Service<CreateWorkspace>()("example/CreateWorkspace", { args: { name: Schema.String, slug: Schema.String, region: Schema.String }, success: Message,}) { static readonly layer = this.toLayer(({ slug, region }) => Effect.sleep("900 millis").pipe( Effect.as( taken.has(slug) || takenOnSubmit.has(slug) ? Message.FailedCreateWorkspace({ field: "slug", message: "Someone took this URL a moment ago. Try another." }) : region === "ap" ? Message.FailedCreateWorkspace({ field: "region", message: "New workspaces can't be created in Asia Pacific this week. Choose another region." }) : Message.SucceededCreateWorkspace({ slug }), ), ))}const slugify = (name: string) => name.normalize("NFKD").replaceAll(/[̀-ͯ]/gu, "").toLowerCase().replaceAll(/[^a-z0-9]+/gu, "-").replaceAll(/^-+|-+$/gu, "").slice(0, 32)const styles = stylex.create({ card: { display: "grid", gap: space.xl, inlineSize: "min(100%, 30rem)", containerType: "inline-size" }, head: { display: "grid", gap: space.xs }, title: { margin: 0, fontSize: font.lg, fontWeight: 600, letterSpacing: "-0.01em" }, lead: { margin: 0, fontSize: font.sm, color: color.muted }, done: { display: "grid", gap: space.md, padding: space.xl, borderWidth: 1, borderStyle: "solid", borderColor: color.line, borderRadius: radius.lg, backgroundColor: color.panel }, url: { fontFamily: font.mono, fontSize: font.sm, overflowWrap: "anywhere" },})const FORM = "create"const DOMAIN = "app.northpeak.dev/"const validated = (form: typeof Workspace.State.Type, check: AsyncResult.AsyncResult<boolean>) => Workspace.validate(form, { slug: AsyncResult.map(check, (isTaken) => (isTaken ? [`${form.values.slug} is taken. Try ${form.values.slug}-team or ${form.values.slug}-hq.`] : [])), })// a submit goes through when every field passes; while the URL check is still out it waits for the// answer; otherwise focus moves to the first field to fixconst attempt = (form: typeof Workspace.State.Type, check: AsyncResult.AsyncResult<boolean>) => { const checked = validated(form, check) if (Option.isSome(checked.value)) return { form, queued: false, submitting: true, command: CreateWorkspace.make(checked.value.value) } if (checked.validating && !checked.invalid) return { form, queued: true, submitting: false, command: undefined } const first = checked.firstError() return { form, queued: false, submitting: false, command: first === undefined ? undefined : focusField(FORM, first) }}const CreateWorkspaceFormNoDeps = Html.component({ name: "CreateWorkspaceForm", model: Schema.Struct({ form: Workspace.State, // the URL follows the name until someone edits it slugEdited: Schema.Boolean, submitting: Schema.Boolean, // submitted while the URL check was still out: it goes through when the answer comes queued: Schema.Boolean, created: Schema.NullOr(Schema.String), }), message: Message, queries: { slugTaken: { query: IsSlugTaken, debounce: "350 millis", args: ({ model }) => (Workspace.passes(model.form, "slug") ? { slug: model.form.values.slug } : undefined), onChange: () => Message.AnsweredSlugCheck(), }, },}).make({ init: () => ({ form: Workspace.init({ name: "", slug: "", region: "" }), slugEdited: false, submitting: false, queued: false, created: null }), update: { UpdatedField: ($, { name, value }) => { if ($.model.submitting) return $.model if (name === "slug") return $.evolve({ queued: false, form: (form) => Workspace.change(form, "slug", value.toLowerCase()), slugEdited: value !== "" }) const form = Workspace.change($.model.form, name, value) return $.evolve({ queued: false, form: name === "name" && !$.model.slugEdited ? Workspace.change(form, "slug", slugify(value)) : form }) }, BlurredField: ($, { name }) => $.evolve({ form: (form) => Workspace.blur(form, name) }), Submitted: ($) => { // a second press while it's being created does nothing if ($.model.submitting) return $.model const { command, ...next } = attempt(Workspace.submit($.model.form), $.queries.slugTaken) return command === undefined ? $.evolve(next) : $.evolve(next).run(command) }, AnsweredSlugCheck: ($) => { if (!$.model.queued || $.model.submitting) return $.model const { command, ...next } = attempt($.model.form, $.queries.slugTaken) return command === undefined ? $.evolve(next) : $.evolve(next).run(command) }, SucceededCreateWorkspace: ($, { slug }) => $.evolve({ submitting: false, created: slug }), FailedCreateWorkspace: ($, { field, message }) => $.evolve({ submitting: false, form: (form) => Workspace.reject(form, { [field]: message }) }).run(focusField(FORM, field)), ClickedStartOver: ($) => $.set({ form: Workspace.init({ name: "", slug: "", region: "" }), slugEdited: false, submitting: false, queued: false, created: null }), }, view: (h, model) => { if (model.created !== null) { return h.div.attrs(sx(styles.card)).children( h.div.attrs({ role: "status", ...sx(styles.done) }).children( h.h3.attrs(sx(styles.title)).children(`${model.form.values.name.trim()} is ready`), h.p.attrs(sx(styles.url)).children(`${DOMAIN}${model.created}`), h.div.children(Button(h, {}).on("click", Message.ClickedStartOver()).children("Create another")), ), ) } const checked = validated(model.form, h.queries.slugTaken) const name = checked.field("name") const slug = checked.field("slug") const region = checked.field("region") const slugStatus = slug.checking ? { tone: "pending" as const, text: "Checking…" } : slug.checked ? { tone: "success" as const, text: `${DOMAIN}${slug.value as string} is free` } : undefined const blur = (field: typeof Field.Type) => Message.BlurredField({ name: field }) return h.form .attrs({ id: FORM, novalidate: "", "aria-labelledby": `${FORM}-title`, "aria-busy": model.submitting ? "true" : undefined, ...sx(styles.card) }) .on("submit", Message.Submitted()) .children( h.div.attrs(sx(styles.head)).children( h.h3.attrs({ id: `${FORM}-title`, ...sx(styles.title) }).children("Create a workspace"), h.p.attrs(sx(styles.lead)).children("Your team's projects, docs and chat live here."), ), ErrorSummary(h, { form: FORM, errors: checked.errors, submits: model.form.submits }), FormField(h, { id: fieldId(FORM, "name"), label: "Workspace name", required: name.required, hint: `${model.form.values.name.length}/48`, hintOver: model.form.values.name.length > 48, ...(name.error === undefined ? {} : { error: name.error }), }, (attrs) => Input(h, { invalid: name.error !== undefined }) .attrs({ ...attrs, autocomplete: "organization", placeholder: "Acme Design", readonly: model.submitting ? "" : undefined }) .value(model.form.values.name) .on("input", ({ value }) => Message.UpdatedField({ name: "name", value })) .on("blur", blur("name"))), FormField(h, { id: fieldId(FORM, "slug"), label: "Workspace URL", required: slug.required, description: "Lowercase letters, numbers and dashes. You can change it later.", ...(slug.error === undefined ? {} : { error: slug.error }), ...(slugStatus === undefined ? {} : { status: slugStatus }), }, (attrs) => InputGroup(h, { start: DOMAIN }, Input(h, { invalid: slug.error !== undefined, style: inGroup }) .attrs({ ...attrs, autocapitalize: "none", autocomplete: "off", spellcheck: "false", placeholder: "acme-design", readonly: model.submitting ? "" : undefined }) .value(model.form.values.slug) .on("input", ({ value }) => Message.UpdatedField({ name: "slug", value })) .on("blur", blur("slug")))), FormField(h, { id: fieldId(FORM, "region"), label: "Data region", required: region.required, group: true, ...(region.error === undefined ? {} : { error: region.error }), }, (field) => RadioGroup(h, { id: fieldId(FORM, "region"), value: model.form.values.region === "" ? null : model.form.values.region, options: regions, field, readOnly: model.submitting, onPick: (value) => Message.UpdatedField({ name: "region", value }), })), FormActions(h, [ Button(h, { tone: "primary", type: "submit" }) .attrs({ "aria-disabled": model.submitting || model.queued ? "true" : undefined }) .children(model.submitting ? "Creating…" : model.queued ? "Checking URL…" : "Create workspace"), ]), ) },})export const CreateWorkspaceForm = CreateWorkspaceFormNoDeps.pipe(Component.provide([IsSlugTaken.layer, CreateWorkspace.layer]))Installation
pnpm dlx shadcn@latest add checkfu/uicontext/formUsage
import { FormField, Input } from "./ui/uicontext/components/FormControls.ts"import { fieldId, make } from "./ui/uicontext/components/forms/Form.ts"export const Profile = make( Schema.Struct({ name: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter your name" })).annotate({ title: "Name" }), email: Schema.String.check(Schema.isPattern(/^[^\s@]+@[^\s@]+$/u, { message: "Enter an email address, like [email protected]" })), team: Schema.optionalKey(Schema.String), }),)// in the Model: `form: Profile.State`; in update: Profile.change, Profile.blur, Profile.submitexport const NameField = <M>(h: Html.H<M>, form: typeof Profile.State.Type, onInput: (value: string) => M, onBlur: M) => { const name = Profile.validate(form).field("name") return FormField(h, { id: fieldId("profile", "name"), label: "Name", required: name.required, ...(name.error === undefined ? {} : { error: name.error }) }, (attrs) => Input(h, { invalid: name.error !== undefined }).attrs(attrs).value(form.values.name) .on("input", ({ value }) => onInput(value)) .on("blur", onBlur))}Examples
Billing address by country
Switch the country: the labels, the required fields, their order and the postal format follow it. Try ZIP 00000 to see the server refuse it.
import { Command, Component, UiSchema } from "@effect/ui"import { Html } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Effect, Option, Schema } from "effect"import { Button } from "./ui/uicontext/components/Button.ts"import { FormField, Input, Select } from "./ui/uicontext/components/FormControls.ts"import { fieldId, focusField, make } from "./ui/uicontext/components/forms/Form.ts"import { ErrorSummary, FieldGrid, FormActions, fullRow } from "./ui/uicontext/components/forms/FormLayout.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, radius, space } from "./ui/uicontext/components/tokens.stylex.ts"import { countries, type Country, countryOf } from "./countries.ts"// A billing address whose fields follow the country: a ZIP code and a state for the United States,// a postcode and an optional county for the United Kingdom, the postal code first for Japan. The// field checks say what's missing; one check on the whole address knows each country's postal// format and lands on the postal code.// "ZIP code" keeps its capitals; "Postcode" doesn'tconst noun = (label: string) => (/^[A-Z]{2}/u.test(label) ? label : label.toLowerCase())const Address = make( Schema.Struct({ name: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter the name on the account" })).annotate({ title: "Full name" }), company: Schema.optionalKey(Schema.String).annotate({ title: "Company" }), country: Schema.String.check(Schema.isNonEmpty({ message: "Choose a country" })).annotate({ title: "Country" }), line1: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter the street address" })).annotate({ title: "Street address" }), line2: Schema.optionalKey(Schema.String), city: Schema.Trim.check(Schema.isNonEmpty({ message: "Enter a city or town" })).annotate({ title: "City" }), region: Schema.optionalKey(Schema.String).annotate({ title: "Region" }), postal: Schema.optionalKey(Schema.String).annotate({ title: "Postal code" }), }).check( Schema.makeFilter((address) => { const country = countryOf(address.country) if (country === undefined) return undefined const issues: Array<{ path: ReadonlyArray<string>; issue: string }> = [] const postal = (address.postal ?? "").trim() if (country.postal !== null) { if (postal === "") issues.push({ path: ["postal"], issue: `Enter a ${noun(country.postal.label)}` }) else if (!country.postal.pattern.test(postal.toUpperCase())) issues.push({ path: ["postal"], issue: `Enter a ${noun(country.postal.label)} like ${country.postal.example}` }) } if (country.region?.required === true && (address.region ?? "").trim() === "") { issues.push({ path: ["region"], issue: `${country.region.options === undefined ? "Enter" : "Choose"} a ${noun(country.region.label)}` }) } return issues }), ),)type Name = (typeof Address.names)[number]const Message = UiSchema.TaggedEnum({ UpdatedField: { name: Schema.String, value: Schema.String }, BlurredField: { name: Schema.String }, Submitted: {}, SucceededSaveAddress: {}, FailedSaveAddress: { field: Schema.String, message: Schema.String },})// stands in for the billing service, which checks a US ZIP code against the cityclass SaveAddress extends Command.Service<SaveAddress>()("example/SaveAddress", { args: { country: Schema.String, postal: Schema.optional(Schema.String) }, success: Message,}) { static readonly layer = this.toLayer(({ country, postal }) => Effect.sleep("800 millis").pipe( Effect.as( country === "US" && postal === "00000" ? Message.FailedSaveAddress({ field: "postal", message: "We couldn't find this ZIP code. Check it and try again." }) : Message.SucceededSaveAddress(), ), ))}const styles = stylex.create({ form: { display: "grid", gap: space.xl, inlineSize: "min(100%, 36rem)", containerType: "inline-size" }, title: { margin: 0, fontSize: font.lg, fontWeight: 600, letterSpacing: "-0.01em" }, saved: { margin: 0, paddingBlock: space.sm, paddingInline: space.md, borderRadius: radius.md, backgroundColor: `color-mix(in srgb, ${color.success} 10%, ${color.panel})`, color: color.success, fontSize: font.sm },})const FORM = "billing"// the summary names the fields as this country doesconst labelsOf = (country: Country) => ({ city: country.cityLabel, ...(country.region === null ? {} : { region: country.region.label }), ...(country.postal === null ? {} : { postal: country.postal.label }),})const empty = { name: "", company: "", country: "US", line1: "", line2: "", city: "", region: "", postal: "" }export const BillingAddressNoDeps = Html.component({ name: "BillingAddress", model: Schema.Struct({ form: Address.State, saving: Schema.Boolean, saved: Schema.Boolean }), message: Message,}).make({ init: () => ({ form: Address.init(empty), saving: false, saved: false }), update: { UpdatedField: ($, { name, value }) => { if ($.model.saving) return $.model const form = Address.change($.model.form, name, value) // a region from another country means nothing here return $.evolve({ saved: false, form: name === "country" ? Address.change(form, "region", "") : form }) }, BlurredField: ($, { name }) => $.evolve({ form: (form) => Address.blur(form, name) }), Submitted: ($) => { if ($.model.saving) return $.model const form = Address.submit($.model.form) const checked = Address.validate(form) return Option.match(checked.value, { onNone: () => { const first = checked.firstError() return first === undefined ? $.evolve({ form }) : $.evolve({ form }).run(focusField(FORM, first)) }, onSome: (address) => $.evolve({ form, saving: true }).run(SaveAddress.make({ country: address.country, ...(address.postal === undefined ? {} : { postal: address.postal.trim() }) })), }) }, SucceededSaveAddress: ($) => $.evolve({ saving: false, saved: true, form: (form) => Address.saved(form) }), FailedSaveAddress: ($, { field, message }) => $.evolve({ saving: false, form: (form) => Address.reject(form, { [field]: message }) }).run(focusField(FORM, field)), }, view: (h, model) => { const country: Country = countryOf(model.form.values.country) ?? countries[0]! const checked = Address.validate(model.form, {}, labelsOf(country)) const values = model.form.values const text = (name: Name, label: string, autocomplete: string, options: { readonly required?: boolean; readonly optional?: boolean; readonly style?: stylex.StyleXStyles; readonly inputMode?: string } = {}) => { const field = checked.field(name) return FormField(h, { id: fieldId(FORM, name), label, ...(options.required === true ? { required: true } : {}), ...(options.optional === true ? { optional: true } : {}), ...(field.error === undefined ? {} : { error: field.error }), ...(options.style === undefined ? {} : { style: options.style }), }, (attrs) => Input(h, { invalid: field.error !== undefined }) .attrs({ ...attrs, autocomplete, inputmode: options.inputMode, readonly: model.saving ? "" : undefined }) .value(values[name]) .on("input", ({ value }) => Message.UpdatedField({ name, value })) .on("blur", Message.BlurredField({ name }))) } const region = country.region === null ? null : country.region.options === undefined ? text("region", country.region.label, "address-level1", country.region.required ? { required: true } : { optional: true }) : FormField(h, { id: fieldId(FORM, "region"), label: country.region.label, ...(country.region.required ? { required: true } : { optional: true }), ...(checked.field("region").error === undefined ? {} : { error: checked.field("region").error! }), }, (attrs) => Select(h, { invalid: checked.field("region").error !== undefined }) .attrs({ ...attrs, autocomplete: "address-level1", disabled: model.saving ? "" : undefined }) .value(values.region) .on("change", ({ value }) => Message.UpdatedField({ name: "region", value })) .on("blur", Message.BlurredField({ name: "region" })) .children( h.option.attrs({ value: "" }).children(`Choose a ${country.region!.label.toLowerCase()}`), country.region!.options!.map((option) => h.option.attrs({ value: option }).children(option)), )) const postal = country.postal === null ? null : text("postal", country.postal.label, "postal-code", { required: true, inputMode: country.postal.numeric ? "numeric" : "text" }) const city = text("city", country.cityLabel, "address-level2", { required: true }) return h.form .attrs({ id: FORM, novalidate: "", "aria-labelledby": `${FORM}-title`, ...sx(styles.form) }) .on("submit", Message.Submitted()) .children( h.h3.attrs({ id: `${FORM}-title`, ...sx(styles.title) }).children("Billing address"), ErrorSummary(h, { form: FORM, errors: checked.errors, submits: model.form.submits }), FieldGrid(h, [ text("name", "Full name", "name", { required: true }), text("company", "Company", "organization", { optional: true }), FormField(h, { id: fieldId(FORM, "country"), label: "Country", required: true, style: fullRow }, (attrs) => Select(h).attrs({ ...attrs, autocomplete: "country", disabled: model.saving ? "" : undefined }) .value(values.country) .on("change", ({ value }) => Message.UpdatedField({ name: "country", value })) .children(countries.map((c) => h.option.attrs({ value: c.code }).children(c.name)))), // in Japan the postal code comes first, and finds the rest country.postalFirst ? postal : null, text("line1", "Street address", "address-line1", { required: true, style: fullRow }), text("line2", country.line2Label, "address-line2", { optional: true, style: fullRow }), ]), FieldGrid(h, country.postalFirst ? [region, city] : [city, region, postal], { columns: country.region === null || country.postal === null || country.postalFirst ? 2 : 3 }), model.saved ? h.p.attrs({ role: "status", ...sx(styles.saved) }).children("Address saved. It'll appear on your next invoice.") : null, FormActions(h, [ Button(h, { tone: "primary", type: "submit" }) .attrs({ "aria-disabled": model.saving ? "true" : undefined }) .children(model.saving ? "Saving…" : "Save address"), ]), ) },})export const BillingAddress = BillingAddressNoDeps.pipe(Component.provide(SaveAddress.layer))API reference
FormView function
Options
| Name | Type | Default | Description |
|---|---|---|---|
mode | "onBlur" | "onChange" | "onSubmit" | onBlur | When a field starts showing its errors; onBlur by default |
FormSectionView function
Options
| Name | Type | Description |
|---|---|---|
titlerequired | string | — |
description | string | A sentence on what the fields are for |
childrenrequired | View.Children | — |
style | Style | — |
ErrorSummaryView function
Options
| Name | Type | Description |
|---|---|---|
formrequired | string | The form's id, which the fields' ids start with |
errorsrequired | FormError[] | — |
submitsrequired | number | Submits tried: the summary shows after the first, and is read out again on each |
formError | string | The server's error about the whole form |
title | (count: number) => string | "Fix 2 fields to continue" by default |
SaveBarView function
Options
| Name | Type | Description |
|---|---|---|
staterequired | "dirty" | "saving" | "saved" | "failed" | "clean" | Where the changes stand; nothing shows while there are none |
changes | number | How many fields changed: "3 unsaved changes" |
error | string | Why the save failed, and what to do |
onDiscardrequired | Message | — |
saveLabel | string | "Save changes" by default |
LeaveGuardView function
Options
| Name | Type | Default | Description |
|---|---|---|---|
whenrequired | boolean | — | — |
onLeaverequired | (href: string) => Message | — | — |
scope | "document" | "parent" | document | Guard links in the whole document, or only in the guard's parent element; document by default |
LeaveDialogView function
Options
| Name | Type | Description |
|---|---|---|
openrequired | boolean | — |
subject | string | What's being edited: "workspace settings" |
onStayrequired | Message | — |
onLeaverequired | Message | — |