# Your first plugin

> definePlugin, setup hooks, and how a plugin writes to the form.

Source: https://forms.lunarhue.dev/react/writing-plugins/first-plugin

When no plugin does what your forms need, write one. Say pasted text keeps
arriving with doubled spaces. A plugin can collapse them in every string
field, on every form that installs it. Type two spaces in a row below.

```tsx title="note.tsx"
import { createForms, inputProps, useForm } from "@lunarhue/forms-react";
import { collapseSpaces } from "./collapseSpaces";

const forms = createForms({ plugins: [collapseSpaces()] });

const note = forms.define({
  defaultValues: { title: "", body: "" },
  onSubmit: (value) => value,
});

export default function NoteForm() {
  const form = useForm(note, { id: "note" });
  return (
    <form.Form>
      {(formProps) => (
        <form {...formProps}>
          <form.Field name="title">
            {(field) => (
              <label>
                Title
                <input {...inputProps(field)} />
                <output>Stored: {JSON.stringify(field.value)}</output>
              </label>
            )}
          </form.Field>
          <form.Field name="body">
            {(field) => (
              <label>
                Body
                <input {...inputProps(field)} />
                <output>Stored: {JSON.stringify(field.value)}</output>
              </label>
            )}
          </form.Field>
        </form>
      )}
    </form.Form>
  );
}
```

```ts title="collapseSpaces.ts"
import { definePlugin } from "@lunarhue/forms-react/plugins";

// Every string written to the form loses its doubled spaces.
export const collapseSpaces = () =>
  definePlugin({
    name: "collapseSpaces",
    setup: () => ({
      beforeWrite: (write) => (typeof write.value === "string" ? write.value.replace(/ {2,}/g, " ") : write.value),
    }),
  });
```

## definePlugin

Make a plugin with `definePlugin`, from `@lunarhue/forms-core/plugins` or the
same entry under your adapter. Wrap it in a function so each `createForms`
call gets its own:

```ts
import { definePlugin } from "@lunarhue/forms-core/plugins";

export const collapseSpaces = () =>
  definePlugin({
    name: "collapseSpaces",
    setup: () => ({
      beforeWrite: (write) => (typeof write.value === "string" ? write.value.replace(/ {2,}/g, " ") : write.value),
    }),
  });

const forms = createForms({ plugins: [collapseSpaces()] });
```

`setup` runs once per store and returns hooks that see the whole form. Here
`beforeWrite` gets every value write and returns the value to store. A
plugin can also have an `attach`, which runs once for each field a
[part](https://forms.lunarhue.dev/react/writing-plugins/parts.md) of it is put on and returns hooks for that field. A plugin
can have either or both.

## Setup

Setup runs when the store is made, before anything reads it, on the server
and on the client. What it writes (values, flags and meta) is part of the
store's starting state:

- The server snapshot shows it, so the server HTML and the first client
  render agree, and hydrating renders once. This is how [`rules`](https://forms.lunarhue.dev/react/plugins/rules.md) puts
  `disabled` and `hidden` in the server HTML.
- It makes no write records, so no plugin's `onWrite` sees it and no
  `deferred` or `idle` delivery is scheduled. A store that is made and never
  written to, as on the server, starts no timer.
- It doesn't move the baseline. A value written in setup is dirty against the
  defaults. To start from a value without making the form dirty, use
  [`initial`](https://forms.lunarhue.dev/react/writing-plugins/submit.md#starting-values).

So setup must give the same result on the server and the client. Anything
that reads the browser or the environment, such as storage, goes in
`onActive`, which runs when the store gets its first listener. The server
never listens, so it never runs there. [`persist`](https://forms.lunarhue.dev/react/plugins/persist.md) restores in
`onActive`.

## Writes

`beforeWrite` runs before each value write, in plugin order, and returns the
value to write or `refuse` to stop it. A write of an object comes through
once, at the object's path. Hooks from `setup` see it there. Hooks from
`attach` get it walked down to their path, so `mask` cleans a phone field
when a reset writes the whole form.

A row that `push` or `insert` adds comes through as a write at the row's path,
with `before` undefined. The row is already in the array by then, since the
insert makes its key. Return a replacement row, or `refuse` to take the row
out again. A form with no `beforeWrite` plugin skips all of this.

Writes that aren't user edits rerun the validators that already run on the
paths they change. A plugin that writes many paths in one `ctx.write` reruns
each validator once, after the last write. A form validator over those paths
runs once, and an async one isn't restarted.

A plugin's own writes go through `ctx.write`, which runs after every plugin
in the round has run. Their records have `cause: { plugin: name }`. A plugin that moves the
baseline to a value from outside, as [`rebase`](https://forms.lunarhue.dev/react/plugins/rebase.md) does, can pass
`"rebase"` instead: `ctx.write(fn, "rebase")`. Those are the only two causes a
plugin gets. `"user"` and `"reset"` belong to the form. The host passes every
write to every plugin with its cause, and each plugin decides what to do with
it. `mask`, for one, skips rebases.

## Writes after an `await`

Code after an `await` runs once the hook has returned, so the host can't tell
its writes from the user's. A write made straight to the store there counts as
a user edit: the field is marked edited and `history` makes an undo step from
it. Write through `ctx.write`, and pass `edited: false` when the value isn't
the user's:

```ts
async onSubmit() {
  const token = await fetchToken();
  // Wrong: a user edit, with an undo step.
  ctx.store.root.at("token").setValue(token);
  // Right: a plugin write, not marked edited.
  ctx.write(() => ctx.store.root.at("token").setValue(token, { edited: false }));
}
```
