Rows of fields to add, remove and reorder by drag or keyboard, with a minimum and a maximum: invites, line items.
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 { formatCount } from "./ui/uicontext/components/domain/Format.ts"import { FormField, Input, Select } from "./ui/uicontext/components/FormControls.ts"import { addRow, fieldId, focusField, make, moveRow, removeRow } from "./ui/uicontext/components/forms/Form.ts"import { ErrorSummary, FormActions } from "./ui/uicontext/components/forms/FormLayout.ts"import { RepeatingFields, rowLabel } from "./ui/uicontext/components/forms/RepeatingFields.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, radius, space } from "./ui/uicontext/components/tokens.stylex.ts"// Invite teammates: an email and a role for each, up to ten at a time. Rows are added, removed and// reordered; an address that's in the list twice is caught before sending, and one that's already// in the workspace comes back from the server onto its row.const Invite = Schema.Struct({ id: Schema.String, email: Schema.Trim.check( Schema.isNonEmpty({ message: "Enter an email address" }), Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/u, { message: "Enter an email address, like [email protected]" }), ).annotate({ title: "Email" }), role: Schema.Literals(["member", "admin", "guest"]).annotate({ title: "Role" }),})const Invites = make( Schema.Struct({ invites: Schema.Array(Invite).check( Schema.isMinLength(1, { message: "Add someone to invite" }), Schema.makeFilter((rows) => { const seen = new Set<string>() return rows.flatMap((row, index) => { const email = row.email.toLowerCase() if (seen.has(email)) return [{ path: [index, "email"], issue: "This address is already in the list" }] seen.add(email) return [] }) }), ), }),)const MAX = 10const roles = [ ["member", "Member"], ["admin", "Admin"], ["guest", "Guest"],] as constconst Message = UiSchema.TaggedEnum({ UpdatedEmail: { id: Schema.String, value: Schema.String }, PickedRole: { id: Schema.String, value: Schema.String }, BlurredEmail: { id: Schema.String }, ClickedAdd: {}, ClickedRemove: { id: Schema.String }, MovedInvite: { id: Schema.String, to: Schema.Number }, Submitted: {}, SucceededSendInvites: { count: Schema.Number }, FailedSendInvites: { errors: Schema.Record(Schema.String, Schema.String) },})const members = new Set(["[email protected]", "[email protected]"])class SendInvites extends Command.Service<SendInvites>()("example/SendInvites", { args: { invites: Schema.Array(Schema.Struct({ id: Schema.String, email: Schema.String, role: Schema.String })) }, success: Message,}) { // the server knows who's a member already, and says so per row static readonly layer = this.toLayer(({ invites }) => Effect.sleep("900 millis").pipe( Effect.as( invites.some((i) => members.has(i.email.toLowerCase())) ? Message.FailedSendInvites({ errors: Object.fromEntries( invites.filter((i) => members.has(i.email.toLowerCase())).map((i) => [`invites.${i.id}.email`, `${i.email} is already in Northwind`]), ), }) : Message.SucceededSendInvites({ count: invites.length }), ), ))}const styles = stylex.create({ form: { display: "grid", gap: space.xl, inlineSize: "min(100%, 40rem)" }, title: { margin: 0, fontSize: font.lg, fontWeight: 600, letterSpacing: "-0.01em" }, lead: { margin: 0, marginBlockStart: space.xs, fontSize: font.sm, color: color.muted }, sent: { 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 = "invite"const blank = (id: string) => ({ id, email: "", role: "member" as const })export const InviteTeammatesNoDeps = Html.component({ name: "InviteTeammates", model: Schema.Struct({ form: Invites.State, nextId: Schema.Number, sending: Schema.Boolean, sent: Schema.Number }), message: Message,}).make({ init: () => ({ form: Invites.init({ invites: [{ id: "r1", email: "[email protected]", role: "admin" }, blank("r2")] }), nextId: 3, sending: false, sent: 0, }), update: { UpdatedEmail: ($, { id, value }) => ($.model.sending ? $.model : $.evolve({ form: (form) => Invites.change(form, `invites.${id}.email`, value), sent: 0 })), PickedRole: ($, { id, value }) => ($.model.sending ? $.model : $.evolve({ form: (form) => Invites.change(form, `invites.${id}.role`, value) })), BlurredEmail: ($, { id }) => $.evolve({ form: (form) => Invites.blur(form, `invites.${id}.email`) }), ClickedAdd: ($) => $.model.sending || $.model.form.values.invites.length >= MAX ? $.model : $.evolve({ form: (form) => addRow(form, "invites", blank(`r${$.model.nextId}`)), nextId: (n) => n + 1 }), ClickedRemove: ($, { id }) => ($.model.sending || $.model.form.values.invites.length <= 1 ? $.model : $.evolve({ form: (form) => removeRow(form, "invites", id) })), MovedInvite: ($, { id, to }) => $.evolve({ form: (form) => moveRow(form, "invites", id, to) }), Submitted: ($) => { if ($.model.sending) return $.model const form = Invites.submit($.model.form) const checked = Invites.validate(form) return Option.match(checked.value, { onNone: () => { const first = checked.firstError() return first === undefined ? $.evolve({ form }) : $.evolve({ form }).run(focusField(FORM, first)) }, onSome: ({ invites }) => $.evolve({ form, sending: true }).run(SendInvites.make({ invites })), }) }, SucceededSendInvites: ($, { count }) => $.evolve({ sending: false, sent: count, form: Invites.init({ invites: [blank(`r${$.model.nextId}`)] }), nextId: (n) => n + 1 }), FailedSendInvites: ($, { errors }) => { const first = Object.keys(errors)[0] const next = $.evolve({ sending: false, form: (form) => Invites.reject(form, errors) }) return first === undefined ? next : next.run(focusField(FORM, first)) }, }, view: (h, model) => { const checked = Invites.validate(model.form) const rows = model.form.values.invites const list = checked.field("invites") return h.form .attrs({ id: FORM, novalidate: "", "aria-labelledby": `${FORM}-title`, ...sx(styles.form) }) .on("submit", Message.Submitted()) .children( h.div.children( h.h3.attrs({ id: `${FORM}-title`, ...sx(styles.title) }).children("Invite teammates"), h.p.attrs(sx(styles.lead)).children("They'll get an email with a link to join Northwind."), ), ErrorSummary(h, { form: FORM, errors: checked.errors, submits: model.form.submits }), RepeatingFields(h, { id: `${FORM}-rows`, legend: "People to invite", rows, noun: "teammate", min: 1, max: MAX, columns: "minmax(0, 1fr) 9rem", headings: ["Email", "Role"], disabled: model.sending, onAdd: Message.ClickedAdd(), onRemove: (id) => Message.ClickedRemove({ id }), onMove: (id, to) => Message.MovedInvite({ id, to }), row: (row, index) => { const email = checked.field(`invites.${row.id}.email`) return [ FormField(h, { id: fieldId(FORM, `invites.${row.id}.email`), label: "Email", labelStyle: rowLabel, ...(email.error === undefined ? {} : { error: email.error }) }, (attrs) => Input(h, { invalid: email.error !== undefined }) .attrs({ ...attrs, type: "email", autocomplete: "off", placeholder: "[email protected]", "aria-label": `Email, teammate ${index + 1}` }) .value(row.email) .on("input", ({ value }) => Message.UpdatedEmail({ id: row.id, value })) .on("blur", Message.BlurredEmail({ id: row.id }))), FormField(h, { id: fieldId(FORM, `invites.${row.id}.role`), label: "Role", labelStyle: rowLabel }, (attrs) => Select(h) .attrs({ ...attrs, "aria-label": `Role, teammate ${index + 1}` }) .value(row.role) .on("change", ({ value }) => Message.PickedRole({ id: row.id, value })) .children(roles.map(([value, label]) => h.option.key(value).attrs({ value }).children(label)))), ] }, }), list.error === undefined ? null : h.p.attrs({ role: "alert", ...sx(styles.lead) }).children(list.error), model.sent > 0 ? h.p.attrs({ role: "status", ...sx(styles.sent) }).children(`Sent ${formatCount(model.sent, "invite")}.`) : null, FormActions(h, [ Button(h, { tone: "primary", type: "submit" }) .attrs({ "aria-disabled": model.sending ? "true" : undefined }) .children(model.sending ? "Sending…" : `Send ${formatCount(rows.length, "invite")}`), ]), ) },})export const InviteTeammates = InviteTeammatesNoDeps.pipe(Component.provide(SendInvites.layer))Installation
pnpm dlx shadcn@latest add checkfu/uicontext/repeating-fieldsUsage
import { RepeatingFields } from "./ui/uicontext/components/forms/RepeatingFields.ts"export const Links = <M, C extends View.Children<M>>( h: Html.H<M>, rows: ReadonlyArray<{ readonly id: string; readonly url: string }>, field: (row: { readonly id: string; readonly url: string }, index: number) => C, on: { readonly add: M; readonly remove: (id: string) => M; readonly move: (id: string, to: number) => M },) => RepeatingFields(h, { id: "links", legend: "Links", noun: "link", rows, max: 5, columns: "minmax(0, 1fr)", row: field, onAdd: on.add, onRemove: on.remove, onMove: on.move, })Examples
Invoice line items
Amounts and totals follow each keystroke. Type “ten” as a quantity, or leave a price empty and save.
import { UiSchema } from "@effect/ui"import { Html } from "@effect/ui/html"import * as stylex from "@stylexjs/stylex"import { Option, Schema } from "effect"import { Button } from "./ui/uicontext/components/Button.ts"import { FormField, Input } from "./ui/uicontext/components/FormControls.ts"import { addRow, fieldId, focusField, make, moveRow, removeRow } from "./ui/uicontext/components/forms/Form.ts"import { FormActions } from "./ui/uicontext/components/forms/FormLayout.ts"import { RepeatingFields, rowLabel } from "./ui/uicontext/components/forms/RepeatingFields.ts"import { sx } from "./ui/uicontext/components/Sx.ts"import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"// An invoice's line items: a description, a quantity and a unit price each, with the amount per line// and the totals worked out as you type. Quantities and prices are typed as text and decoded to// numbers by the Schema, so "1,5" or "ten" get a plain sentence instead of NaN.const Line = Schema.Struct({ id: Schema.String, description: Schema.Trim.check(Schema.isNonEmpty({ message: "Describe the item" })).annotate({ title: "Description" }), quantity: Schema.FiniteFromString.check( Schema.isInt({ message: "Enter a whole number" }), Schema.isBetween({ minimum: 1, maximum: 9999 }, { message: "Enter 1 to 9,999" }), ).annotate({ title: "Quantity" }), price: Schema.FiniteFromString.check(Schema.isGreaterThanOrEqualTo(0, { message: "Enter a price of 0 or more" })) .annotate({ title: "Unit price" }) // an empty price would decode as 0; the key says what to do instead .annotateKey({ messageMissingKey: "Enter a price" }),})const Invoice = make(Schema.Struct({ lines: Schema.Array(Line).check(Schema.isMaxLength(25)) }))const TAX = 0.08875const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })const percent = new Intl.NumberFormat("en-US", { style: "percent", maximumFractionDigits: 3 })/** What a line comes to, while its numbers read as numbers. */const amountOf = (line: { readonly quantity: string; readonly price: string }) => { const quantity = Number(line.quantity) const price = Number(line.price.replaceAll(",", "")) return line.quantity.trim() === "" || line.price.trim() === "" || !Number.isFinite(quantity) || !Number.isFinite(price) ? null : quantity * price}const Message = UiSchema.TaggedEnum({ UpdatedLine: { id: Schema.String, field: Schema.Literals(["description", "quantity", "price"]), value: Schema.String }, BlurredLine: { id: Schema.String, field: Schema.String }, ClickedAdd: {}, ClickedRemove: { id: Schema.String }, MovedLine: { id: Schema.String, to: Schema.Number }, Submitted: {},})const styles = stylex.create({ form: { display: "grid", gap: space.xl, inlineSize: "min(100%, 44rem)" }, head: { display: "flex", flexWrap: "wrap", alignItems: "baseline", justifyContent: "space-between", gap: space.md }, title: { margin: 0, fontSize: font.lg, fontWeight: 600, letterSpacing: "-0.01em" }, meta: { margin: 0, fontSize: font.sm, color: color.muted, fontVariantNumeric: "tabular-nums" }, // on a narrow card the amount reads as one line under the fields: "Amount $4,800.00" amount: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: space.sm, minInlineSize: 0 }, amountLabel: { fontSize: font.sm, fontWeight: 500, color: color.fg }, amountValue: { display: "flex", alignItems: "center", justifyContent: "flex-end", marginInlineStart: "auto", minBlockSize: { default: 36, "@media (pointer: coarse)": 40 }, fontVariantNumeric: "tabular-nums", fontSize: font.base, color: color.fg, whiteSpace: "nowrap", }, pending: { color: color.faint }, numeric: { textAlign: "end", fontVariantNumeric: "tabular-nums" }, totals: { display: "grid", gridTemplateColumns: "auto auto", justifyContent: "end", columnGap: space.xxl, rowGap: space.xs, margin: 0, fontVariantNumeric: "tabular-nums" }, term: { fontSize: font.sm, color: color.muted, textAlign: "end" }, value: { margin: 0, fontSize: font.sm, color: color.fg, textAlign: "end" }, total: { fontSize: font.base, fontWeight: 600, color: color.fg }, saved: { margin: 0, fontSize: font.sm, color: color.success },})const FORM = "invoice"const blank = (id: string) => ({ id, description: "", quantity: "1", price: "" })export const InvoiceLines = Html.component({ name: "InvoiceLines", model: Schema.Struct({ form: Invoice.State, nextId: Schema.Number, saved: Schema.Boolean }), message: Message,}).make({ init: () => ({ form: Invoice.init({ lines: [ { id: "l1", description: "Brand workshop, two days", quantity: "1", price: "4800" }, { id: "l2", description: "Logo and type system", quantity: "1", price: "6500" }, { id: "l3", description: "Illustration, per piece", quantity: "12", price: "180" }, ], }), nextId: 4, saved: false, }), update: { UpdatedLine: ($, { id, field, value }) => $.evolve({ form: (form) => Invoice.change(form, `lines.${id}.${field}`, value), saved: false }), BlurredLine: ($, { id, field }) => $.evolve({ form: (form) => Invoice.blur(form, `lines.${id}.${field}`) }), ClickedAdd: ($) => $.evolve({ form: (form) => addRow(form, "lines", blank(`l${$.model.nextId}`)), nextId: (n) => n + 1, saved: false }), ClickedRemove: ($, { id }) => $.evolve({ form: (form) => removeRow(form, "lines", id), saved: false }), MovedLine: ($, { id, to }) => $.evolve({ form: (form) => moveRow(form, "lines", id, to), saved: false }), Submitted: ($) => { const form = Invoice.submit($.model.form) const checked = Invoice.validate(form) return Option.match(checked.value, { onNone: () => { const first = checked.firstError() return first === undefined ? $.evolve({ form }) : $.evolve({ form }).run(focusField(FORM, first)) }, onSome: () => $.evolve({ form: Invoice.saved(form), saved: true }), }) }, }, view: (h, model) => { const checked = Invoice.validate(model.form) const lines = model.form.values.lines const subtotal = lines.reduce((sum, line) => sum + (amountOf(line) ?? 0), 0) const tax = Math.round(subtotal * TAX * 100) / 100 const field = (id: string, index: number, name: "description" | "quantity" | "price", label: string, extra: { readonly inputMode?: string; readonly numeric?: boolean } = {}) => { const state = checked.field(`lines.${id}.${name}`) const line = lines[index]! return FormField(h, { id: fieldId(FORM, `lines.${id}.${name}`), label, labelStyle: rowLabel, ...(state.error === undefined ? {} : { error: state.error }) }, (attrs) => Input(h, { invalid: state.error !== undefined, ...(extra.numeric === true ? { style: styles.numeric } : {}) }) .attrs({ ...attrs, inputmode: extra.inputMode, autocomplete: "off", "aria-label": `${label}, line ${index + 1}` }) .value(line[name]) .on("input", ({ value }) => Message.UpdatedLine({ id, field: name, value })) .on("blur", Message.BlurredLine({ id, field: name }))) } return h.form .attrs({ id: FORM, novalidate: "", "aria-labelledby": `${FORM}-title`, ...sx(styles.form) }) .on("submit", Message.Submitted()) .children( h.div.attrs(sx(styles.head)).children( h.h3.attrs({ id: `${FORM}-title`, ...sx(styles.title) }).children("Invoice INV-2048"), h.p.attrs(sx(styles.meta)).children("Harbor & Pine Studio · due Jan 4, 2027"), ), RepeatingFields(h, { id: `${FORM}-lines`, legend: "Line items", rows: lines, noun: "line", min: 1, max: 25, columns: "minmax(0, 1fr) 5rem 7rem 7rem", headings: ["Description", "Qty", "Unit price", "Amount"], onAdd: Message.ClickedAdd(), onRemove: (id) => Message.ClickedRemove({ id }), onMove: (id, to) => Message.MovedLine({ id, to }), row: (line, index) => { const amount = amountOf(line) return [ field(line.id, index, "description", "Description"), field(line.id, index, "quantity", "Qty", { inputMode: "numeric", numeric: true }), field(line.id, index, "price", "Unit price", { inputMode: "decimal", numeric: true }), h.div.attrs(sx(styles.amount)).children( h.span.attrs({ "aria-hidden": "true", ...sx(styles.amountLabel, rowLabel) }).children("Amount"), h.output.attrs({ "aria-label": `Amount, line ${index + 1}`, ...sx(styles.amountValue, amount === null && styles.pending) }).children(amount === null ? "—" : money.format(amount)), ), ] }, }), h.dl.attrs(sx(styles.totals)).children( h.dt.attrs(sx(styles.term)).children("Subtotal"), h.dd.attrs(sx(styles.value)).children(money.format(subtotal)), h.dt.attrs(sx(styles.term)).children(`Sales tax (${percent.format(TAX)})`), h.dd.attrs(sx(styles.value)).children(money.format(tax)), h.dt.attrs(sx(styles.term, styles.total)).children("Total"), h.dd.attrs(sx(styles.value, styles.total)).children(money.format(subtotal + tax)), ), FormActions(h, [ model.saved ? h.p.attrs({ role: "status", ...sx(styles.saved) }).children("Saved as a draft") : null, Button(h, { tone: "primary", type: "submit" }).children("Save draft"), ]), ) },})API reference
Options
| Name | Type | Default | Description |
|---|---|---|---|
idrequired | string | — | The group's id, for its legend and live region |
legendrequired | string | — | Names the group: "Teammates", "Line items" |
description | string | — | A sentence under the legend |
rowsrequired | ReadonlyArray<{ readonly id: string }> | — | — |
nounrequired | string | — | What one row is, for Add and for what's read out: "teammate", "line item" |
min | number | 0 | Fewer rows than this can't be removed down to; 0 by default |
max | number | — | No more rows can be added past this |
columnsrequired | string | — | The column widths of a row's fields in a wide group, as a grid template |
headings | string[] | — | The field labels, once as column headings in a wide group |
rowrequired | (row: { readonly id: string }, index: number) => View.Children | — | A row's fields, in the order of columns |
onAddrequired | Message | — | — |
onRemoverequired | (id: string) => Message | — | — |
onMove | (id: string, to: number) => Message | — | Report a move: reordering shows only with it |
footer | View.Content | — | After the rows, beside Add: totals, or a note |
disabled | boolean | — | — |
style | Style | — | — |