Back office
Three record forms and a dialog with masks, conditional fields, arrays, undo and a saved draft, built with both libraries.
A back-office workspace with three record forms and an invite dialog, built once with @lunarhue/forms and once with TanStack Form. Schemas, formatters, and markup are shared across both builds so you are comparing form wiring only. Switch builds in the preview below; both behave the same.
Bundle size
| Build | @lunarhue/forms is | @lunarhue/forms 0.2.0 | TanStack Form 1.33.5 |
|---|---|---|---|
| Forms + app | 91 B larger (0.4%) | 22.6 kB | 22.5 kB |
| Total | 278 B larger (0.2%) | 112.4 kB | 112.1 kB |
| App only | 1.2 kB smaller (21%) | 4.5 kB | 5.7 kB |
import { Items, useField, useForm } from "@lunarhue/forms-react";
import { baselineOnSubmit, persist, ruled } from "@lunarhue/forms-react/plugins";
import { type FormEvent, useRef, useState } from "react";
import { Loaded, Page, ServerControls } from "../../shared/ui.tsx";
import { companies, customers, orders, sendInvite } from "../../shared/server.ts";
import { orderTotal } from "../format.ts";
import { Company, Customer, Invite, Order, roles } from "../schemas.ts";
import { Section } from "../ui.tsx";
import { forms } from "./forms.ts";
import { AddressFields, ErrorSummary, SaveBar } from "./parts.tsx";
// Each record form starts from the server's copy and takes what it sent as
// the new baseline after a save.
const customerForm = forms.define(
(saved: Customer) => ({
schema: Customer,
defaultValues: saved,
plugins: [baselineOnSubmit()],
onSubmit: async (value) => {
await customers.save(value);
return "Customer saved.";
},
}),
ruled({ shipping: (customer) => ({ hidden: customer.sameAsBilling }) }),
);
function CustomerForm({ saved }: { readonly saved: Customer }) {
const form = useForm(customerForm, saved);
return (
<form.Form>
{(formProps) => (
<form {...formProps}>
<ErrorSummary />
<form.TextField name="name" label="Name" />
<form.TextField name="email" label="Email" />
<form.PhoneField name="phone" label="Phone" inputMode="tel" />
<AddressFields field={form.root.at("billing")} legend="Billing address" />
<form.Checkbox name="sameAsBilling" label="Ship to the billing address" />
<AddressFields field={form.root.at("shipping")} legend="Shipping address" />
<SaveBar load={customers.get} />
<form.State select={(state) => state.submission}>
{(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
</form.State>
</form>
)}
</form.Form>
);
}
const orderForm = forms.define(
(saved: Order) => ({
schema: Order,
defaultValues: saved,
plugins: [baselineOnSubmit()],
onSubmit: async (value) => {
await orders.save(value);
return "Order saved.";
},
}),
ruled({ giftMessage: (order) => ({ hidden: !order.gift }) }),
);
function OrderForm({ saved }: { readonly saved: Order }) {
const form = useForm(orderForm, saved);
const lines = form.root.at("lines");
const total = useField(lines, (snapshot) => orderTotal(snapshot.value));
const listErrors = useField(lines, (snapshot) => snapshot.shownErrors);
return (
<form.Form>
{(formProps) => (
<form {...formProps}>
<ErrorSummary />
<form.TextField name="reference" label="Reference" />
<fieldset>
<legend>Lines</legend>
<Items handle={lines}>
{(line, index) => (
<div className="line">
<form.TextField handle={line.at("sku")} label={`SKU ${index + 1}`} />
<form.QuantityField handle={line.at("quantity")} label={`Quantity ${index + 1}`} inputMode="numeric" />
<form.MoneyField handle={line.at("price")} label={`Price ${index + 1}`} inputMode="decimal" />
<button type="button" onClick={() => lines.remove(index)}>
Remove line {index + 1}
</button>
</div>
)}
</Items>
<ul className="errors">
{listErrors.map((error) => (
<li key={error.message}>{error.message}</li>
))}
</ul>
<button type="button" onClick={() => lines.push({ sku: "", quantity: "1", price: "" })}>
Add line
</button>
<p>Total: {total}</p>
</fieldset>
<form.Checkbox name="gift" label="This order is a gift" />
<form.TextArea name="giftMessage" label="Gift message" />
<SaveBar load={orders.get} />
<form.State select={(state) => state.submission}>
{(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
</form.State>
</form>
)}
</form.Form>
);
}
const companyForm = forms.define((saved: Company) => ({
schema: Company,
defaultValues: saved,
plugins: [baselineOnSubmit()],
// A refusal goes on the fields, as the submit docs show. That ends the
// submit as invalid, so baselineOnSubmit() leaves the values unsaved.
onSubmit: async (value, { store }) => {
const response = await companies.save(value);
if (!response.ok) {
store.setErrors({ fields: Object.fromEntries(Object.entries(response.errors).map(([name, message]) => [name, { message }])) });
return null;
}
return "Company saved.";
},
}));
function CompanyForm({ saved }: { readonly saved: Company }) {
const form = useForm(companyForm, saved);
return (
<form.Form>
{(formProps) => (
<form {...formProps}>
<ErrorSummary />
<form.TextField name="name" label="Company name" />
<form.PhoneField name="phone" label="Phone" inputMode="tel" />
<form.TaxIdField name="taxId" label="Tax ID" inputMode="numeric" />
<AddressFields field={form.root.at("address")} legend="Registered address" />
<SaveBar load={companies.get} />
<form.State select={(state) => state.submission}>
{(submission) => <p role="status">{submission.status === "succeeded" ? submission.result : null}</p>}
</form.State>
</form>
)}
</form.Form>
);
}
// The draft survives closing the dialog and reloading the page.
const inviteForm = forms.define({
schema: Invite,
defaultValues: { email: "", role: "member", message: "" },
plugins: [persist("backoffice-invite")],
onSubmit: (value) => sendInvite(value),
});
function InviteDialog() {
const form = useForm(inviteForm);
const dialog = useRef<HTMLDialogElement>(null);
const [sent, setSent] = useState("");
// A reset puts the submission back to idle, so the message is kept here.
// The reset also saves the empty form as the draft.
const send = async (event: FormEvent) => {
event.preventDefault();
const submission = await form.submit();
if (submission.status !== "succeeded") return;
setSent(submission.result);
form.store.reset();
};
return (
<>
<button type="button" onClick={() => dialog.current?.showModal()}>
Invite a teammate
</button>
<dialog ref={dialog} aria-labelledby="invite-heading">
<h2 id="invite-heading">Invite a teammate</h2>
<form.Form>
{(formProps) => (
<form {...formProps} onSubmit={(event) => void send(event)}>
<form.TextField name="email" label="Email" />
<form.Select name="role" label="Role" options={roles} />
<form.TextArea name="message" label="Message" />
<p role="status">{sent}</p>
<div className="save-bar">
<button type="button" onClick={() => dialog.current?.close()}>
Close
</button>
<form.State select={(state) => state.submitting}>
{(submitting) => <button type="submit">{submitting ? "Sending..." : "Send invite"}</button>}
</form.State>
</div>
</form>
)}
</form.Form>
</dialog>
</>
);
}
export function App() {
return (
<Page title="Back office" lede="Three record forms and a dialog that share field components, a save bar and an error summary.">
<ServerControls>
<button type="button" onClick={customers.editElsewhere}>
Edit customer
</button>
<button type="button" onClick={orders.editElsewhere}>
Edit order
</button>
<button type="button" onClick={companies.editElsewhere}>
Edit company
</button>
</ServerControls>
<InviteDialog />
<Section title="Customer">
<Loaded load={customers.get}>{(saved) => <CustomerForm saved={saved} />}</Loaded>
</Section>
<Section title="Order">
<Loaded load={orders.get}>{(saved) => <OrderForm saved={saved} />}</Loaded>
</Section>
<Section title="Company settings">
<Loaded load={companies.get}>{(saved) => <CompanyForm saved={saved} />}</Loaded>
</Section>
</Page>
);
}import { type AnyFormApi, getBy, useStore } from "@tanstack/react-form";
import { useEffect, useRef, useState } from "react";
import { z } from "zod";
import { companies, customers, orders, type SaveResponse, sendInvite } from "../../shared/server.ts";
import { ErrorList, Loaded, Page, ServerControls } from "../../shared/ui.tsx";
import { orderTotal } from "../format.ts";
import { type Address, Company, countries, Customer, Invite, Order, roles } from "../schemas.ts";
import { Section } from "../ui.tsx";
import { messageOf, useAppForm, withFieldGroup } from "./form.tsx";
import { undoStackOf } from "./history.ts";
import { rebaseline, same } from "./values.ts";
const blankAddress: Address = { street: "", city: "", region: "", postcode: "", country: "US" };
/** An address anywhere in any form. The state shows only for the US. */
const AddressFields = withFieldGroup({
defaultValues: blankAddress,
props: { legend: "" },
render: function Render({ group, legend }) {
const country = useStore(group.store, (state) => state.values.country);
return (
<fieldset>
<legend>{legend}</legend>
<group.AppField name="street">{(field) => <field.TextField label="Street" />}</group.AppField>
<group.AppField name="city">{(field) => <field.TextField label="City" />}</group.AppField>
{country === "US" ? <group.AppField name="region">{(field) => <field.TextField label="State" />}</group.AppField> : null}
<group.AppField name="postcode">{(field) => <field.TextField label="Postcode" />}</group.AppField>
<group.AppField name="country">{(field) => <field.Select label="Country" options={countries} />}</group.AppField>
</fieldset>
);
},
});
/**
* A form for a record loaded from the server, with Refresh for the save bar.
* `useForm` applies its options again on every render, so defaults moved
* with `form.reset(values)` would snap back to the first ones. They live in
* React state and move with each rebaseline. After a save, what was sent
* becomes the defaults, and a field edited while the save ran keeps the
* newer value and stays changed.
*
* A refusal puts the server's messages on the fields with `setErrorMap` and
* leaves the defaults alone. `onSubmit` returning still counts as a
* successful submit, so the status line is React state, not
* `isSubmitSuccessful`.
*/
function useRecordForm<T>(
initial: T,
schema: z.ZodType<T, T>,
server: { readonly get: () => Promise<T>; readonly save: (value: T) => Promise<SaveResponse> },
savedMessage: string,
) {
const [defaults, setDefaults] = useState(initial);
const [status, setStatus] = useState("");
const form = useAppForm({
defaultValues: defaults,
validators: { onChange: schema },
onSubmitInvalid: () => setStatus(""),
onSubmit: async ({ value, formApi }) => {
setStatus("");
const response = await server.save(value);
if (!response.ok) {
// The server names fields by string, and `T` is generic here, so the
// form is used through TanStack's untyped form type.
const untyped: AnyFormApi = formApi;
untyped.setErrorMap({ onSubmit: { fields: response.errors } });
return;
}
rebaseline(formApi, value, (name, current) => !same(current, getBy(value, name)));
setDefaults(value);
setStatus(savedMessage);
},
});
// Leaves the user hasn't changed take the server's copy. Changed ones keep
// their value and stay changed against the new defaults.
const refresh = async () => {
const fresh = await server.get();
rebaseline(form, fresh, (name, value) => !same(value, getBy(defaults, name)));
setDefaults(fresh);
};
return { form, status, saveBar: { defaults, refresh } };
}
function CustomerForm({ initial }: { readonly initial: Customer }) {
const { form, status, saveBar } = useRecordForm(initial, Customer, customers, "Customer saved.");
return (
<form.AppForm>
<form.RecordForm status={status}>
<form.ErrorSummary />
<form.AppField name="name">{(field) => <field.TextField label="Name" />}</form.AppField>
<form.AppField name="email">{(field) => <field.TextField label="Email" />}</form.AppField>
<form.AppField name="phone">{(field) => <field.PhoneField label="Phone" inputMode="tel" />}</form.AppField>
<AddressFields form={form} fields="billing" legend="Billing address" />
<form.AppField name="sameAsBilling">{(field) => <field.Checkbox label="Ship to the billing address" />}</form.AppField>
<form.Subscribe selector={(state) => state.values.sameAsBilling}>
{(sameAsBilling) => (sameAsBilling ? null : <AddressFields form={form} fields="shipping" legend="Shipping address" />)}
</form.Subscribe>
<form.SaveBar {...saveBar} />
</form.RecordForm>
</form.AppForm>
);
}
const newLine = { sku: "", quantity: "1", price: "" };
function OrderForm({ initial }: { readonly initial: Order }) {
const { form, status, saveBar } = useRecordForm(initial, Order, orders, "Order saved.");
return (
<form.AppForm>
<form.RecordForm status={status}>
<form.ErrorSummary />
<form.AppField name="reference">{(field) => <field.TextField label="Reference" />}</form.AppField>
<form.Field name="lines" mode="array">
{(lines) => (
<fieldset>
<legend>Lines</legend>
{lines.state.value.map((_, index) => (
// TanStack's docs key array rows by index.
// oxlint-disable-next-line react/no-array-index-key
<div className="line" key={index}>
<form.AppField name={`lines[${index}].sku`}>{(field) => <field.TextField label={`SKU ${index + 1}`} />}</form.AppField>
<form.AppField name={`lines[${index}].quantity`}>
{(field) => <field.QuantityField label={`Quantity ${index + 1}`} inputMode="numeric" />}
</form.AppField>
<form.AppField name={`lines[${index}].price`}>
{(field) => <field.MoneyField label={`Price ${index + 1}`} inputMode="decimal" />}
</form.AppField>
<button
type="button"
onClick={() => {
undoStackOf(form).record("lines", lines.state.value);
lines.removeValue(index);
}}
>
Remove line {index + 1}
</button>
</div>
))}
<form.Subscribe selector={(state) => state.submissionAttempts > 0}>
{(submitted) => <ErrorList errors={submitted ? lines.state.meta.errors.map(messageOf) : []} />}
</form.Subscribe>
<button
type="button"
onClick={() => {
undoStackOf(form).record("lines", lines.state.value);
lines.pushValue(newLine);
}}
>
Add line
</button>
{/* The array field re-renders only when rows come or go, so the total subscribes on its own. */}
<form.Subscribe selector={(state) => orderTotal(state.values.lines)}>{(total) => <p>Total: {total}</p>}</form.Subscribe>
</fieldset>
)}
</form.Field>
<form.AppField name="gift">{(field) => <field.Checkbox label="This order is a gift" />}</form.AppField>
<form.Subscribe selector={(state) => state.values.gift}>
{(gift) => (gift ? <form.AppField name="giftMessage">{(field) => <field.TextArea label="Gift message" />}</form.AppField> : null)}
</form.Subscribe>
<form.SaveBar {...saveBar} />
</form.RecordForm>
</form.AppForm>
);
}
function CompanyForm({ initial }: { readonly initial: Company }) {
const { form, status, saveBar } = useRecordForm(initial, Company, companies, "Company saved.");
return (
<form.AppForm>
<form.RecordForm status={status}>
<form.ErrorSummary />
<form.AppField name="name">{(field) => <field.TextField label="Company name" />}</form.AppField>
<form.AppField name="phone">{(field) => <field.PhoneField label="Phone" inputMode="tel" />}</form.AppField>
<form.AppField name="taxId">{(field) => <field.TaxIdField label="Tax ID" inputMode="numeric" />}</form.AppField>
<AddressFields form={form} fields="address" legend="Registered address" />
<form.SaveBar {...saveBar} />
</form.RecordForm>
</form.AppForm>
);
}
const draftKey = "backoffice-invite";
const blankInvite: Invite = { email: "", role: "member", message: "" };
// A draft may hold a half-typed email, so it is checked for shape only.
const Draft = z.object({ email: z.string(), role: z.enum(roles), message: z.string() });
/** The saved draft, or undefined when storage is empty, blocked or holds something else. */
function loadDraft(): Invite | undefined {
try {
const parsed = Draft.safeParse(JSON.parse(localStorage.getItem(draftKey) ?? "null"));
return parsed.success ? parsed.data : undefined;
} catch {
return undefined;
}
}
function InviteDialog() {
const dialog = useRef<HTMLDialogElement>(null);
const [sent, setSent] = useState("");
// In state for the same reason as useRecordForm: a reset to the blank
// invite has to stick past the next render.
const [defaults, setDefaults] = useState(() => loadDraft() ?? blankInvite);
const form = useAppForm({
defaultValues: defaults,
validators: { onChange: Invite },
onSubmit: async ({ value, formApi }) => {
setSent(await sendInvite(value));
formApi.reset(blankInvite);
setDefaults(blankInvite);
},
});
// TanStack has no persistence, so the draft is saved on every change.
const values = useStore(form.store, (state) => state.values);
useEffect(() => {
try {
localStorage.setItem(draftKey, JSON.stringify(values));
} catch {
// Storage is blocked or full. The draft just isn't kept.
}
}, [values]);
return (
<>
<button type="button" onClick={() => dialog.current?.showModal()}>
Invite a teammate
</button>
<dialog ref={dialog} aria-labelledby="invite-heading">
<h2 id="invite-heading">Invite a teammate</h2>
<form.AppForm>
<form
noValidate
onSubmit={(event) => {
event.preventDefault();
void form.handleSubmit();
}}
>
<form.AppField name="email">{(field) => <field.TextField label="Email" />}</form.AppField>
<form.AppField name="role">{(field) => <field.Select label="Role" options={roles} />}</form.AppField>
<form.AppField name="message">{(field) => <field.TextArea label="Message" />}</form.AppField>
<p role="status">{sent}</p>
<div className="save-bar">
<button type="button" onClick={() => dialog.current?.close()}>
Close
</button>
<form.Subscribe selector={(state) => state.isSubmitting}>
{(submitting) => <button type="submit">{submitting ? "Sending..." : "Send invite"}</button>}
</form.Subscribe>
</div>
</form>
</form.AppForm>
</dialog>
</>
);
}
export function App() {
return (
<Page title="Back office" lede="Three record forms and a dialog that share field components, a save bar and an error summary.">
<ServerControls>
<button type="button" onClick={customers.editElsewhere}>
Edit customer
</button>
<button type="button" onClick={orders.editElsewhere}>
Edit order
</button>
<button type="button" onClick={companies.editElsewhere}>
Edit company
</button>
</ServerControls>
<InviteDialog />
<Section title="Customer">
<Loaded load={customers.get}>{(saved) => <CustomerForm initial={saved} />}</Loaded>
</Section>
<Section title="Order">
<Loaded load={orders.get}>{(saved) => <OrderForm initial={saved} />}</Loaded>
</Section>
<Section title="Company settings">
<Loaded load={companies.get}>{(saved) => <CompanyForm initial={saved} />}</Loaded>
</Section>
</Page>
);
}What the workspace does
Each record form loads from the mock server and shares a save bar (with change count, Undo, Discard, and Save) plus an error summary after a failed submit:
- Customer: contact details, billing address, and a conditional shipping address shown only when “Ship to the billing address” is unchecked (whose errors only count while visible).
- Order: dynamic line items (SKU, quantity, price) with a live running total, plus a conditional gift message.
- Company settings: name, phone, tax ID, and registered address. Submitting tax ID
00-0000000triggers a server refusal that stays on the field until edited. - Invite a teammate: a modal dialog whose draft persists across closing the dialog and reloading the page.
Across every address, the State field only appears for US addresses. Phone, tax ID, quantity, and price fields are masked, storing clean digits (or decimals) while displaying formatted text.
Where the two implementations differ
On the @lunarhue/forms side, one createForms installs zod(), dirty(), rebase(), rules(), arrays(), and history(). Masks attach via masked(...) parts on PhoneField and MoneyField (no plugin needed), the US-state rule travels inside AddressFieldset, the save bar and error summary find their form via useFormContext(forms) inside <form.Form>, and the invite dialog persists with a single persist("backoffice-invite") plugin.
On the TanStack Form side, createFormHook provides the shared form components, withFieldGroup handles addresses, and Standard Schema + isDefaultValue + form.reset cover validation and dirty state. The rest is implemented in app code:
- Masks: a custom
MaskedInputcleans values and restores the caret by clean-character count (a real app would usually reach for a dedicated masking library; this minimal one doesn’t step over separators on backspace). - Undo: since TanStack doesn’t ship history, field components and line-item buttons record previous values manually and replay them with
setFieldValue. - Conditional rules: each conditional field wraps itself in
form.SubscribeoruseStoreinside every form. - Change counts and Refresh: reuses the
rebaselinepattern from the profile comparison, walking leaf paths likelines[0].price. - Invite draft: reads
localStorageonce for initial defaults and writes back inside an effect on every change.
A few extra details were needed on the TanStack side to keep behavior identical:
- Defaults are mirrored in React state after every save, refresh, and invite so
useFormdoesn’t snap them back on re-render. - Because the form context’s
optionsdon’t reflectreset(values), the save bar takes current defaults as a prop and undo stacks are keyed byformId. - Input IDs are constructed from
formId+ field name so error summary links can jump to inputs. - Order totals subscribe to
linesdirectly (since array fields only re-render on row add/remove), and rows are keyed by index per TanStack’s docs. - Record forms save inside
onSubmitand attach server refusals viaform.setErrorMap; becauseisSubmitSuccessfulstays set, the “Saved” message lives in React state.
How bundle sizes were measured
scripts/size-compare.ts builds each app for production (minified, JS only) in three slices: Forms + app (excluding React, react-dom, and Zod), Total (everything), and App only (excluding the form libraries too, so our plugins count in Forms + app, while TanStack’s hand-written masks, undo, and draft persistence count in App only).
Measured from built package outputs against TanStack Form 1.33.5 and enforced in CI. Source and shared Playwright specs are in examples/compare.
Last updated