# Back office

> Three record forms and a dialog with masks, conditional fields, arrays, undo and a saved draft, built with both libraries.

Source: https://forms.lunarhue.dev/react/compared/backoffice

A back-office workspace with three record forms and an invite dialog, built once with `@lunarhue/forms` and once with [TanStack Form](https://tanstack.com/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.

| Build (gzip) | @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 |

```tsx title="lunarhue/App.tsx"
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>
  );
}
```

```tsx title="lunarhue/fields.tsx"
import { checkboxProps, type Choice, type FieldApi, type FormError, inputProps, selectProps, textareaProps } from "@lunarhue/forms-react";
import type { dirty } from "@lunarhue/forms-react/plugins";
import { rules } from "@lunarhue/forms-react/plugins";
import type { HTMLAttributes } from "react";
import { CheckShell, FieldShell } from "../../shared/ui.tsx";

// Each component reads `field.dirty`, so it fits only forms with dirty().
type DirtyField<V> = FieldApi<V, typeof dirty>;

const messages = (field: { readonly shownErrors: readonly FormError[] }) => field.shownErrors.map((error) => error.message);

interface TextProps {
  readonly field: DirtyField<string>;
  readonly label: string;
}

// A rule can hide the text fields, so they read the rules meta. A field
// no rule names reads `{ hidden: false }`.
export function TextField({ field, label }: TextProps) {
  if (rules.meta(field).hidden) return null;
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <input {...inputProps(field)} />
    </FieldShell>
  );
}

export function TextArea({ field, label }: TextProps) {
  if (rules.meta(field).hidden) return null;
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <textarea rows={3} {...textareaProps(field)} />
    </FieldShell>
  );
}

/**
 * The input behind every masked field type in forms.ts. The `masked` part
 * on the type cleans the value and gives the display text, so this stays a
 * plain input.
 */
export function MaskedInput({ field, label, inputMode }: TextProps & { readonly inputMode: HTMLAttributes<HTMLInputElement>["inputMode"] }) {
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <input {...inputProps(field)} inputMode={inputMode} />
    </FieldShell>
  );
}

interface SelectProps {
  readonly field: DirtyField<Choice>;
  readonly label: string;
  readonly options: readonly Choice[];
}

export function Select({ field, label, options }: SelectProps) {
  return (
    <FieldShell id={field.id} errorId={field.errorId} label={label} errors={messages(field)} changed={field.dirty}>
      <select {...selectProps(field)}>
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    </FieldShell>
  );
}

export function Checkbox({ field, label }: { readonly field: DirtyField<boolean>; readonly label: string }) {
  return (
    <CheckShell errorId={field.errorId} errors={messages(field)} changed={field.dirty}>
      <input {...checkboxProps(field)} />
      {label}
    </CheckShell>
  );
}
```

```ts title="lunarhue/forms.ts"
// One `createForms` for the whole back office. Every form gets the same
// plugins and field types, and the save bar and error summary work on any
// of them through `useFormContext(forms)`.
import { createForms, defineField } from "@lunarhue/forms-react";
import { arrays, dirty, history, rebase, ruled, rules } from "@lunarhue/forms-react/plugins";
import { masked } from "@lunarhue/forms-react/text";
import { zod } from "@lunarhue/forms-schema/zod";
import { cleanMoney, digitsOnly, formatMoney, formatPhone, formatTaxId } from "../format.ts";
import { Address } from "../schemas.ts";
import { Checkbox, MaskedInput, Select, TextArea, TextField } from "./fields.tsx";

// Each masked type stores the clean value and shows it formatted.
const PhoneField = defineField(MaskedInput, masked({ clean: digitsOnly(10), display: formatPhone }));
const TaxIdField = defineField(MaskedInput, masked({ clean: digitsOnly(9), display: formatTaxId }));
const MoneyField = defineField(MaskedInput, masked({ clean: cleanMoney, display: formatMoney }));
const QuantityField = defineField(MaskedInput, masked({ clean: digitsOnly(4) }));

export const forms = createForms({
  plugins: [zod(), dirty(), rebase(), rules(), arrays(), history()],
  fields: { TextField, TextArea, Select, Checkbox, PhoneField, TaxIdField, MoneyField, QuantityField },
});

// Every address, wherever it sits, shows the region only for the US.
export const AddressFieldset = forms.fieldset(Address, ruled({ region: (address) => ({ hidden: address.country !== "US" }) }));
```

```tsx title="lunarhue/parts.tsx"
// The pieces every back office form shares. Each finds its form with
// `useFormContext(forms)`, so they need no props to reach it.
import { type HandleOf, useField, useFormContext, useFormState, useInvalidFields } from "@lunarhue/forms-react";
import { history, rules } from "@lunarhue/forms-react/plugins";
import { countries } from "../schemas.ts";
import { ErrorSummaryView, SaveBarView } from "../ui.tsx";
import { AddressFieldset, forms } from "./forms.ts";

/** The change count, undo, refresh, discard and save. `load` fetches the server's copy for Refresh. */
export function SaveBar({ load }: { readonly load: () => Promise<unknown> }) {
  const form = useFormContext(forms);
  const canUndo = useFormState(form, (state) => history.formMeta(state).canUndo);
  const submitting = useFormState(form, (state) => state.submitting);
  // `changes()` is a read, not a subscription, so it runs whenever the root
  // field changes.
  const count = useField(form.root, () => form.store.changes().length);

  // Fields the user hasn't changed take the server's copy. Changed ones keep
  // their text and stay dirty against the new baseline.
  const refresh = async () => {
    const fresh = await load();
    form.plugins.rebase(form.root, fresh, (leaf) => (Object.is(leaf.value, leaf.baseline) ? "take" : "keep"));
  };

  return (
    <SaveBarView
      count={count}
      canUndo={canUndo}
      submitting={submitting}
      onUndo={() => form.plugins.history.undo()}
      onRefresh={() => void refresh()}
      onDiscard={() => form.root.reset()}
    />
  );
}

/** Every field with errors, once the user has tried to save. */
export function ErrorSummary() {
  const form = useFormContext(forms);
  const tried = useFormState(form, (state) => state.submitCount > 0);
  const invalid = useInvalidFields(form);
  const problems = invalid.map((entry) => ({ id: entry.field.id, name: entry.name, messages: entry.errors.map((error) => error.message) }));
  return <ErrorSummaryView problems={tried ? problems : []} />;
}

/** An address anywhere in any form. A rule on the handle above it can hide it whole. */
export function AddressFields({ field, legend }: { readonly field: HandleOf<typeof AddressFieldset>; readonly legend: string }) {
  const hidden = useField(field, (snapshot) => rules.meta(snapshot).hidden);
  const scope = AddressFieldset.scope(field);
  if (hidden) return null;
  return (
    <fieldset>
      <legend>{legend}</legend>
      <scope.TextField name="street" label="Street" />
      <scope.TextField name="city" label="City" />
      <scope.TextField name="region" label="State" />
      <scope.TextField name="postcode" label="Postcode" />
      <scope.Select name="country" label="Country" options={countries} />
    </fieldset>
  );
}
```

```tsx title="tanstack/App.tsx"
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>
  );
}
```

```tsx title="tanstack/form.tsx"
// The back office's form hook: field components, the masked inputs, and the
// save bar and error summary as form components, so every form gets them.
import { type AnyFormApi, createFormHook, createFormHookContexts, useStore } from "@tanstack/react-form";
import { type HTMLAttributes, type ReactNode, useLayoutEffect, useRef } from "react";
import { CheckShell, FieldShell } from "../../shared/ui.tsx";
import { cleanMoney, digitsOnly, formatMoney, formatPhone, formatTaxId } from "../format.ts";
import { ErrorSummaryView, SaveBarView } from "../ui.tsx";
import { undoStackOf, useCanUndo } from "./history.ts";
import { changedNames } from "./values.ts";

const { fieldContext, formContext, useFieldContext, useFormContext } = createFormHookContexts();

/**
 * The input id for a field. The error summary links to inputs by name, so
 * the id comes from the form's id and the field's name, not from `useId`.
 */
export const fieldId = (form: AnyFormApi, name: string): string => `${form.formId}-${name}`;

/** Schema issues arrive as objects, function validators' errors as strings. */
export function messageOf(error: unknown): string {
  if (typeof error === "string") return error;
  if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") return error.message;
  return String(error);
}

/**
 * What every field component needs: ids, the errors to show, the changed
 * mark, and a change handler that records the old value for Undo. Errors
 * wait for a blur or a submit.
 */
function useFieldView<V>() {
  const field = useFieldContext<V>();
  const id = fieldId(field.form, field.name);
  const submitted = useStore(field.form.store, (state) => state.submissionAttempts > 0);
  const { isBlurred, errors, isDefaultValue } = field.state.meta;
  const shown = isBlurred || submitted ? [...new Set(errors.map(messageOf))] : [];
  return {
    field,
    id,
    errorId: `${id}-errors`,
    errors: shown,
    changed: !isDefaultValue,
    change: (value: V) => {
      undoStackOf(field.form).record(field.name, field.state.value);
      field.handleChange(value);
    },
    aria: {
      "aria-invalid": shown.length > 0 ? true : undefined,
      "aria-describedby": shown.length > 0 ? `${id}-errors` : undefined,
    },
  };
}

function TextField({ label }: { readonly label: string }) {
  const view = useFieldView<string>();
  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <input
        id={view.id}
        name={view.field.name}
        value={view.field.state.value}
        onChange={(event) => view.change(event.target.value)}
        onBlur={view.field.handleBlur}
        {...view.aria}
      />
    </FieldShell>
  );
}

function TextArea({ label }: { readonly label: string }) {
  const view = useFieldView<string>();
  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <textarea
        id={view.id}
        rows={3}
        name={view.field.name}
        value={view.field.state.value}
        onChange={(event) => view.change(event.target.value)}
        onBlur={view.field.handleBlur}
        {...view.aria}
      />
    </FieldShell>
  );
}

/** A select over the field's options. The field context can't type them, so they are strings. */
function Select({ label, options }: { readonly label: string; readonly options: readonly string[] }) {
  const view = useFieldView<string>();
  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <select
        id={view.id}
        name={view.field.name}
        value={view.field.state.value}
        onChange={(event) => view.change(event.target.value)}
        onBlur={view.field.handleBlur}
        {...view.aria}
      >
        {options.map((option) => (
          <option key={option} value={option}>
            {option}
          </option>
        ))}
      </select>
    </FieldShell>
  );
}

function Checkbox({ label }: { readonly label: string }) {
  const view = useFieldView<boolean>();
  return (
    <CheckShell errorId={view.errorId} errors={view.errors} changed={view.changed}>
      <input
        id={view.id}
        type="checkbox"
        name={view.field.name}
        checked={view.field.state.value}
        onChange={(event) => view.change(event.target.checked)}
        onBlur={view.field.handleBlur}
        {...view.aria}
      />
      {label}
    </CheckShell>
  );
}

/** Where the caret goes in `text` so that `count` clean characters sit before it. */
function caretAfter(text: string, clean: (text: string) => string, count: number): number {
  for (let index = 0; index <= text.length; index++) {
    if (clean(text.slice(0, index)).length >= count) return index;
  }
  return text.length;
}

interface MaskProps {
  readonly label: string;
  readonly inputMode: HTMLAttributes<HTMLInputElement>["inputMode"];
}

/**
 * An input that stores `clean(text)` and shows `display(value)`. React puts
 * the caret at the end when the shown text changes length, so the caret is
 * put back after the same number of clean characters as before the edit.
 */
function MaskedInput({ label, inputMode, clean, display }: MaskProps & { readonly clean: (text: string) => string; readonly display: (value: string) => string }) {
  const view = useFieldView<string>();
  const input = useRef<HTMLInputElement>(null);
  const caret = useRef<number | null>(null);
  const text = display(view.field.state.value);

  useLayoutEffect(() => {
    if (caret.current === null || input.current === null) return;
    const position = caretAfter(text, clean, caret.current);
    caret.current = null;
    input.current.setSelectionRange(position, position);
  });

  return (
    <FieldShell id={view.id} errorId={view.errorId} label={label} errors={view.errors} changed={view.changed}>
      <input
        ref={input}
        id={view.id}
        inputMode={inputMode}
        name={view.field.name}
        value={text}
        onChange={(event) => {
          const typed = event.target.value;
          caret.current = clean(typed.slice(0, event.target.selectionStart ?? typed.length)).length;
          view.change(clean(typed));
        }}
        onBlur={view.field.handleBlur}
        {...view.aria}
      />
    </FieldShell>
  );
}

const cleanPhone = digitsOnly(10);
const cleanTaxId = digitsOnly(9);
const cleanQuantity = digitsOnly(4);
const shownAsIs = (value: string) => value;

const PhoneField = (props: MaskProps) => <MaskedInput {...props} clean={cleanPhone} display={formatPhone} />;
const TaxIdField = (props: MaskProps) => <MaskedInput {...props} clean={cleanTaxId} display={formatTaxId} />;
const MoneyField = (props: MaskProps) => <MaskedInput {...props} clean={cleanMoney} display={formatMoney} />;
const QuantityField = (props: MaskProps) => <MaskedInput {...props} clean={cleanQuantity} display={shownAsIs} />;

interface SaveBarProps {
  /** The form's current default values, the copy the count compares against. */
  readonly defaults: unknown;
  /** Fetches the server's copy and makes it the defaults. */
  readonly refresh: () => Promise<void>;
}

/**
 * The change count, undo, refresh, discard and save. The form context hands
 * out a copy of the form whose `options` don't follow `reset(values)`, so
 * the defaults come in as a prop.
 */
function SaveBar({ defaults, refresh }: SaveBarProps) {
  const form = useFormContext();
  const count = useStore(form.store, (state) => changedNames(state.values, defaults).length);
  const submitting = useStore(form.store, (state) => state.isSubmitting);
  const canUndo = useCanUndo(form);
  return (
    <SaveBarView
      count={count}
      canUndo={canUndo}
      submitting={submitting}
      onUndo={() => undoStackOf(form).undo(form)}
      onRefresh={() => void refresh()}
      onDiscard={() => {
        form.reset();
        undoStackOf(form).clear();
      }}
    />
  );
}

/** The form element, wired to submit, with the status line under it. */
function RecordForm({ status, children }: { readonly status: string; readonly children: ReactNode }) {
  const form = useFormContext();
  return (
    <form
      noValidate
      onSubmit={(event) => {
        event.preventDefault();
        void form.handleSubmit();
      }}
    >
      {children}
      <p role="status">{status}</p>
    </form>
  );
}

/** Every field with errors, once the user has tried to save. */
function ErrorSummary() {
  const form = useFormContext();
  const problems = useStore(form.store, (state) =>
    state.submissionAttempts === 0
      ? []
      : Object.entries(state.fieldMeta).flatMap(([name, meta]) => {
          // The context's form is untyped, so its meta is too.
          const errors: readonly unknown[] = typeof meta === "object" && meta !== null && "errors" in meta && Array.isArray(meta.errors) ? meta.errors : [];
          return errors.length === 0 ? [] : [{ id: fieldId(form, name), name, messages: [...new Set(errors.map(messageOf))] }];
        }),
  );
  return <ErrorSummaryView problems={problems} />;
}

export const { useAppForm, withForm, withFieldGroup } = createFormHook({
  fieldContext,
  formContext,
  fieldComponents: { TextField, TextArea, Select, Checkbox, PhoneField, TaxIdField, MoneyField, QuantityField },
  formComponents: { RecordForm, SaveBar, ErrorSummary },
});
```

```ts title="tanstack/history.ts"
// Undo for a TanStack form, which has none. The field components and the
// line buttons record the old value before each user change. Undo writes it
// back. One stack per form, found by its id: field components see the core
// form object, while the form context hands out a copy of it.
import type { AnyFormApi } from "@tanstack/react-form";
import { useSyncExternalStore } from "react";

interface Step {
  readonly name: string;
  readonly value: unknown;
}

const limit = 100;

class UndoStack {
  #steps: Step[] = [];
  readonly #listeners = new Set<() => void>();

  get canUndo(): boolean {
    return this.#steps.length > 0;
  }

  /** Call before a user change, with the field's value before it. */
  record(name: string, value: unknown): void {
    this.#steps = [...this.#steps, { name, value }].slice(-limit);
    this.#notify();
  }

  undo(form: AnyFormApi): void {
    const step = this.#steps.at(-1);
    if (step === undefined) return;
    this.#steps = this.#steps.slice(0, -1);
    form.setFieldValue(step.name, step.value);
    this.#notify();
  }

  clear(): void {
    if (this.#steps.length === 0) return;
    this.#steps = [];
    this.#notify();
  }

  subscribe = (listener: () => void): (() => void) => {
    this.#listeners.add(listener);
    return () => this.#listeners.delete(listener);
  };

  #notify(): void {
    for (const listener of this.#listeners) listener();
  }
}

const stacks = new Map<string, UndoStack>();

/** The form's undo stack. */
export function undoStackOf(form: AnyFormApi): UndoStack {
  let stack = stacks.get(form.formId);
  if (stack === undefined) {
    stack = new UndoStack();
    stacks.set(form.formId, stack);
  }
  return stack;
}

/** True while the form has a change to undo. */
export function useCanUndo(form: AnyFormApi): boolean {
  const stack = undoStackOf(form);
  return useSyncExternalStore(stack.subscribe, () => stack.canUndo);
}
```

```ts title="tanstack/values.ts"
// Dirty tracking over plain values. TanStack keeps `isDefaultValue` per
// mounted field, but has no list of a form's leaves, no count of changed
// ones, and no way to move the defaults while keeping some values. These
// helpers walk the values instead.
import { type AnyFormApi, getBy } from "@tanstack/react-form";

const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
  typeof value === "object" && value !== null && !Array.isArray(value);

/** Deep equality for JSON-like values. */
export function same(a: unknown, b: unknown): boolean {
  if (Object.is(a, b)) return true;
  if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((item, index) => same(item, b[index]));
  if (isRecord(a) && isRecord(b)) {
    const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
    return [...keys].every((key) => same(a[key], b[key]));
  }
  return false;
}

/**
 * The field names of every leaf in `a` and `b`, in TanStack's syntax:
 * `billing.city`, `lines[0].price`. Objects are walked key by key, and
 * arrays item by item while both have the same length. An array whose
 * length changed is one leaf.
 */
export function leafNames(a: unknown, b: unknown, prefix = ""): string[] {
  if (isRecord(a) && isRecord(b)) {
    const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
    return [...keys].flatMap((key) => leafNames(a[key], b[key], prefix === "" ? key : `${prefix}.${key}`));
  }
  if (Array.isArray(a) && Array.isArray(b) && a.length === b.length) {
    return a.flatMap((item: unknown, index) => leafNames(item, b[index], `${prefix}[${index}]`));
  }
  return [prefix];
}

/** The leaves whose value differs from the defaults. */
export function changedNames(values: unknown, defaults: unknown): string[] {
  return leafNames(values, defaults).filter((name) => !same(getBy(values, name), getBy(defaults, name)));
}

/**
 * Makes `baseline` the form's default values. Leaves `keep` picks keep their
 * current value and stay changed. `form.reset(values)` moves the defaults
 * but also writes every value, so the kept ones are written back after it.
 */
export function rebaseline(form: AnyFormApi, baseline: unknown, keep: (name: string, value: unknown) => boolean): void {
  const values: unknown = form.state.values;
  const kept = leafNames(values, baseline).flatMap((name) => {
    const value: unknown = getBy(values, name);
    return keep(name, value) ? [{ name, value }] : [];
  });
  form.reset(baseline);
  for (const { name, value } of kept) form.setFieldValue(name, value);
}
```

## 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-0000000` triggers 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 `MaskedInput` cleans 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.Subscribe` or `useStore` inside every form.
- **Change counts and Refresh:** reuses the `rebaseline` pattern from the [profile comparison](https://forms.lunarhue.dev/react/compared/profile.md), walking leaf paths like `lines[0].price`.
- **Invite draft:** reads `localStorage` once 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 `useForm` doesn't snap them back on re-render.
- Because the form context's `options` don't reflect `reset(values)`, the save bar takes current defaults as a prop and undo stacks are keyed by `formId`.
- Input IDs are constructed from `formId` + field name so error summary links can jump to inputs.
- Order totals subscribe to `lines` directly (since array fields only re-render on row add/remove), and rows are keyed by index per TanStack's docs.
- Record forms save inside `onSubmit` and attach server refusals via `form.setErrorMap`; because `isSubmitSuccessful` stays set, the "Saved" message lives in React state.

## How bundle sizes were measured

[`scripts/size-compare.ts`](https://github.com/LunarHUE/forms/blob/main/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`](https://github.com/LunarHUE/forms/tree/main/examples/compare).
