# Fieldsets and scopes

> Type a component that renders one part of a form, and use it on every form with that part.

Source: https://forms.lunarhue.dev/solid/composition/fieldsets

One component renders both addresses below. It takes a handle, and its names
are relative to it.

```tsx title="order.tsx"
import { createForm } from "@lunarhue/forms-solid";
import { AddressFields } from "./AddressFields";
import { forms, Order } from "./forms";

const order = forms.define({
  schema: Order,
  defaultValues: {
    name: "",
    shipping: { street: "", city: "" },
    billing: { street: "", city: "" },
  },
  onSubmit: (value) => value,
});

export default function OrderForm() {
  const form = createForm(order, { id: "order" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.TextField name="name" label="Name" />
          <AddressFields field={form.root.at("shipping")} legend="Shipping" />
          <AddressFields field={form.root.at("billing")} legend="Billing" />
          <button type="submit">Save</button>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="AddressFields.tsx"
import type { HandleOf } from "@lunarhue/forms-solid";
import { Address, forms } from "./forms";

// A token for the address shape. It types the handle this component takes.
const AddressFieldset = forms.fieldset(Address);

interface AddressFieldsProps {
  readonly field: HandleOf<typeof AddressFieldset>;
  readonly legend: string;
}

// Any handle to an address fits, so the same component renders both. Names
// in the scope are relative: `name="city"` here is `shipping.city` or
// `billing.city`.
export function AddressFields(props: AddressFieldsProps) {
  const scope = AddressFieldset.scope(props.field);
  return (
    <fieldset>
      <legend>{props.legend}</legend>
      <scope.TextField name="street" label="Street" />
      <scope.TextField name="city" label="City" />
    </fieldset>
  );
}
```

```ts title="forms.ts"
import { createForms } from "@lunarhue/forms-solid";
import { z } from "zod";
import { TextField } from "./TextField";

// No plugins: the schemas below validate through Standard Schema.
export const forms = createForms({ fields: { TextField } });

export const Address = z.object({
  street: z.string().min(1, "Enter a street."),
  city: z.string().min(1, "Enter a city."),
});

export const Order = z.object({
  name: z.string().min(1, "Enter your name."),
  shipping: Address,
  billing: Address,
});
```

```tsx title="TextField.tsx"
import { type FieldApi, inputProps } from "@lunarhue/forms-solid";
import { For } from "solid-js";

interface TextFieldProps {
  readonly field: FieldApi<string>;
  readonly label: string;
}

export function TextField(props: TextFieldProps) {
  return (
    <div>
      <label for={props.field.id}>{props.label}</label>
      <input {...inputProps(props.field)} />
      <ul id={props.field.errorId}>
        <For each={props.field.shownErrors}>{(error) => <li>{error.message}</li>}</For>
      </ul>
    </div>
  );
}
```

## Typing the handle

A component that renders part of a form takes a handle prop. To type it,
make a fieldset from the part's schema and use `HandleOf`:

```tsx
import type { HandleOf } from "@lunarhue/forms-solid";

const AddressFieldset = forms.fieldset(Address);

function AddressFields(props: { field: HandleOf<typeof AddressFieldset> }) {
  const scope = AddressFieldset.scope(props.field);
  return (
    <fieldset>
      <scope.TextField name="street" label="Street" />
      <scope.TextField name="city" label="City" />
    </fieldset>
  );
}

<AddressFields field={form.root.at("shipping")} />;
```

## Scopes

`scope(handle)` returns the same members a form has, `Field`, `Items` and
your registered components, with names relative to the handle. It is a cached
lookup, not a hook, so call it anywhere.

The fieldset's schema only types the shape. The form's own schema does the
validating. Without a schema, write the type: `forms.fieldset<Address>()`.

## Which handles fit

A handle fits when its value has exactly the shape: an array row, or a field
of another form from the same `createForms`. A handle of an object with more
keys doesn't. The component could replace the whole value and drop the keys
it doesn't know, so handles are strict in their value type. A handle of a
form with more plugins still fits one that asks for fewer.

## Generic fieldsets

To take objects with more keys, make the component generic in the value and
pass it as the second argument of `HandleOf`:

```tsx
function AddressFields<A extends Address>(props: { field: HandleOf<typeof AddressFieldset, A> }) {
  const scope = AddressFieldset.scope(props.field);
  return (
    <fieldset>
      <scope.TextField name="street" label="Street" />
      <scope.TextField handle={props.field.at("city")} label="City" />
    </fieldset>
  );
}

// `office` has a `phone` too.
<AddressFields field={form.root.at("office")} />;
```

A child that `Address` names, such as `field.at("city")`, reads as its type
in `Address`, so it fits a `FieldApi<string>` component. A child that is an
object itself stays generic and needs a generic component of its own. A
merge write such as `field.setValue({ city: "Oslo" })` doesn't type-check on
a generic handle. Write the child instead: `field.at("city").setValue("Oslo")`.

`createInputProps` reads the value type from the handle's own type, so type
the child first: `const city: FieldHandle<string> = props.field.at("city")`.
