# Masks

> Clean what a field stores, and choose what its input shows.

Source: https://forms.lunarhue.dev/react/plugins/masks

A phone number should be stored as digits but read as `(555) 123-4567`.
`mask()` cleans what a field stores and chooses what its input shows. Type a
phone number, then type in the middle of it.

```tsx title="contact.tsx"
import { createForms, defineField, useForm } from "@lunarhue/forms-react";
import { digits, mask, masked } from "@lunarhue/forms-react/plugins";
import { PhoneInput } from "./PhoneInput";

// "5551234567" shows as "(555) 123-4567".
function formatPhone(value: string) {
  const area = value.slice(0, 3);
  const prefix = value.slice(3, 6);
  const line = value.slice(6, 10);
  if (value.length > 6) return `(${area}) ${prefix}-${line}`;
  if (value.length > 3) return `(${area}) ${prefix}`;
  return area;
}

// Every PhoneField stores digits and shows them formatted. The store only
// ever holds digits, so `onSubmit` gets digits.
const PhoneField = defineField(PhoneInput, masked({ clean: digits, display: formatPhone }));

const forms = createForms({ plugins: [mask()], fields: { PhoneField } });

const contact = forms.define({
  defaultValues: { phone: "" },
  onSubmit: (value) => value.phone,
});

export default function ContactForm() {
  const form = useForm(contact, { id: "contact" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.PhoneField name="phone" label="Phone" />
          <button type="submit">Save</button>
        </form>
      )}
    </form.Form>
  );
}
```

```tsx title="PhoneInput.tsx"
import { type FieldApi, inputProps } from "@lunarhue/forms-react";

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

// A plain input. The mask part on `PhoneField` gives the field its display
// text, so `inputProps` shows the formatted number and keeps the caret where
// the user is typing.
export function PhoneInput({ field, label }: PhoneInputProps) {
  return (
    <label>
      {label}
      <input {...inputProps(field, { type: "tel" })} />
    </label>
  );
}
```

A mask cleans a field's value before the store takes it. Put `mask()` in the
form's plugins, and a `masked(...)` part on the field type it cleans:

```ts
const PhoneField = defineField(PhoneInput, masked({ clean: digits, display: formatPhone }));

const forms = createForms({ plugins: [mask()], fields: { PhoneField } });
```

Every field `<form.PhoneField>` renders gets the mask, and only those. Every
value that reaches the field goes through `clean` first, whether the user
typed it, a reset wrote it or another plugin did. `digits` and `upper` are
ready-made cleaners, and any function from string to string works.

`masked` fits string fields only, so `defineField(NumberInput, masked(...))` is a
type error. So is a form that renders `PhoneField` without `mask()` in its
plugins: the error reads `Add mask() to this form's plugins: PhoneField uses
it`.

A field type's parts attach the first time it renders a field. To attach
one earlier, pin it on the definition. See
[Parts on field components](https://forms.lunarhue.dev/react/plugin-composition/field-parts.md).

## Display text

A cleaner changes what the store holds, not what the input shows. Give the
part a `display` to show the value formatted. With `formatPhone` above, the
input shows `(555) 123-4567` and the store, `field.value` and `onSubmit` get
`5551234567`.

`display` gets the clean value and returns the text to show. A value that
isn't a string reaches it as `""`. Keep it a pure function of the value, since
the server and the browser both call it. Text inputs and textareas show the
display text, on the server too, so the page hydrates with it. Number,
checkbox, radio and select inputs ignore it.

Everything except the input reads the stored value: `field.value`, the
schema, `onSubmit`, `dirty`, history and persistence. The display text lives
only in `field.text`, which `inputProps(field)` uses too. An input bound to
`field.value` instead shows the stored value. To keep the caret in place,
write with `field.setText(text, event)`. See
[Binding an element](https://forms.lunarhue.dev/react/basics/fields.md#binding-an-element).

A plugin of your own can give a field display text too. See
[Writing a plugin](https://forms.lunarhue.dev/react/writing-plugins/meta.md#display-text-from-a-plugin).

## Caret

The caret stays where the user is typing. After typing or pasting it steps
over the characters the display adds, so typing carries on past a `-`. After a
backspace it doesn't, so the next backspace deletes a digit. A character
`clean` drops leaves the text and the caret as they were.

A field with only a cleaner shows the clean value. When the cleaner changes
the text, as `upper` does, React or Solid may move the caret to the end when
it rewrites the input. `{ clean: upper, display: (value) => value }` keeps it
in place.

## Two masks on one field

A field type can carry more than one `masked` part. Each cleans in turn, in
the order listed. If both give a display, the first one wins: the input shows
its text and keeps the caret with its `clean`.

## What gets cleaned

- A write above a field, such as `setValue` on `address`, a root replace from
  `bind`, or a row that `push` or `insert` adds, is cleaned at each masked
  field below it.
- The field's value is cleaned when the part attaches, and so is its baseline
  while the field isn't dirty, so the form doesn't start dirty and a reset
  leaves it clean.
- User edits, resets and other plugins' writes are cleaned. A value `persist`
  restores comes out clean.
- Rebases aren't. The incoming value is the server's copy, and the baseline
  moves to it as it came. Cleaning it would make the form dirty against its
  own baseline.
