# Form

> A `<form>` that Slab's controls submit, reset, and validate with — just like native ones.

`<slab-form>` · Form · built on `<form>`

## Install

```sh
pnpm add slab-elements lit
```

## Usage

```html
<script type="module">
  import 'slab-elements/form.js';
</script>

<slab-form label="Sign up" action="/sign-up" method="post">
  <slab-text-field label="Email" name="email" type="email" required></slab-text-field>
  <button>Sign up</button>
</slab-form>
```

## Example

Here's a styled version, `<slab-styled-form>`. It's not in the package — it's an example of what you can build with the headless element. Copy it and make it yours at the bottom of this page.

```html
<slab-styled-form label="Schedule a pour">
  <slab-styled-text-field label="Job name" name="job" value="14 Alder Lane foundation" required></slab-styled-text-field>
  <slab-styled-date-field label="Pour date" name="date" required></slab-styled-date-field>
  <slab-styled-number label="Cubic yards" min="1" name="yards" value="38"></slab-styled-number>
  <div>
    <button class="styled-button styled-button--primary">Schedule</button>
  </div>
</slab-styled-form>
```

Swap `slab-styled-` for `slab-` in that markup and you've got the same example as it ships: the headless elements with no CSS at all. That's your starting point.

A plain `<form>` works with Slab's controls too. Reach for Form when you
want what it adds: a label that makes the form a landmark, and a
`checkValidity()` that doesn't show errors, just like a native one.

## Keyboard

| Key   | What it does                                      |
| ----- | ------------------------------------------------- |
| Enter | In a field, submits the form, as in a native one. |

## Behavior

A form with no visual styles, around a native `<form>`, so it's submitted, reset and validated the way one is.

The `<form>` is in the light DOM, not the shadow root. A control's form owner is its nearest `<form>` ancestor in its own tree, and that doesn't cross a shadow boundary: a `<form>` in the shadow root with a `<slot>` inside it would own nothing slotted into it, and every control would submit to no form at all. So Form appends a `<form>` as its only child and moves its other children into it, on connect and whenever one is added. The shadow root holds a single `<slot>`, which the `<form>` is slotted into.

Everything else is the `<form>`'s. Slab's controls are form-associated through `ElementInternals`, so they submit, reset, and report their validity to it the way a native `<input>` does, and nothing here walks them. `checkValidity()`, `reportValidity()`, `requestSubmit()`, `reset()` and `submit()` are the `<form>`'s, and "submit" and "reset" bubble from it through the host.

A native `<form>`'s `checkValidity()` fires "invalid" at each invalid control but shows nothing, and so does this one's: Form marks its own `<form>` while its `checkValidity()` runs, whether it's called on Form or on `form`, and Slab's controls stay out of their error state. Only that `<form>` is marked. `HTMLFormElement.prototype` is left alone, so a consumer's own plain `<form>` gets no such marking, and its `checkValidity()` puts Slab's invalid controls into their error state as `reportValidity()` does.

`label`, when set, names the `<form>`, which is what makes it a form landmark. The `<form>` is reachable as `form` and styled as any light-DOM element is.

## API

### `<slab-form>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `action` | `string` |  |  |
| `autocomplete` | `'on' \| 'off'` |  |  |
| `enctype` | `string` |  |  |
| `label` | `string` |  | Names the form, which makes it a landmark. |
| `method` | `'get' \| 'post' \| 'dialog'` |  |  |
| `name` | `string` |  |  |
| `novalidate` | `boolean` | `false` |  |
| `target` | `string` |  |  |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `elements` (read-only) | `HTMLFormControlsCollection` |  |
| `form` (read-only) | `HTMLFormElement` | The native form, in the light DOM |

#### Methods

| Signature | Description |
| --- | --- |
| `checkValidity(): boolean` |  |
| `reportValidity(): boolean` |  |
| `requestSubmit(submitter?: HTMLElement \| null): void` |  |
| `reset(): void` |  |
| `submit(): void` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `(default)` | `Element \| string` | Moved into the form |

## Copy and own it

`<slab-styled-form>` isn't in the package. It's an example — copy it into your project and change whatever you want. Under the hood, it's just the headless element, subclassed, with `styles` set. That's it. Keyboard, focus, ARIA, forms, and events all come from the headless element, and the styles only reach in through `::part()` and `:state()`, same as yours would.

To use it, copy these files, swap the tag in `@customElement()` for one of your own, and import it. `tokens.styles.ts` holds the colors and fonts every styled example shares, so you only need it once.

### TypeScript

These files are TypeScript, and `@customElement()` is one of Lit's decorators (TypeScript's experimental flavor). You'll need two options in your tsconfig, per [Lit's docs](https://lit.dev/docs/components/decorators/#decorators-typescript): `experimentalDecorators` to compile them, and `useDefineForClassFields` turned off so class fields don't stomp on the accessors Lit sets up.

```json
{
  "compilerOptions": {
    "experimentalDecorators": true,
    "useDefineForClassFields": false
  }
}
```

Using plain JavaScript? Drop the types and register the class with `customElements.define()` instead of the decorator.

### form.ts

```ts
import { customElement } from 'lit/decorators.js';
import Form from 'slab-elements/form.js';
import styles from './form.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-form': StyledForm;
  }
}

/**
 * Form, styled: its fields stacked, with room between them.
 */
@customElement('slab-styled-form')
export default class StyledForm extends Form {
  static override styles = [tokens, styles];
}
```

### form.styles.ts

```ts
import { css } from 'lit';

/*
  Form moves its children into a "<form>" of its own, in the light DOM, and
  slots that in. So the form is what's laid out.
*/
export default css`
  ::slotted(form) {
    display: grid;
    gap: 1.5rem;
  }
`;
```

### tokens.styles.ts

```ts
import { css } from 'lit';

/*
  The styled components' palette and type, taken from the logo: ink for the
  courses, ember for the base, paper behind them.

  Each is a short alias for a "--slab-styled-*" property, with the default as
  its fallback. Retheming is "--slab-styled-ember" and the rest on ":root",
  which every shadow root inherits. Were the defaults declared under those
  names here instead, each host's own declaration would shadow the page's.

  Each default is "light-dark()", so the components follow the page's
  "color-scheme": "dark" for dark, "light" for light, and "light dark" to
  follow the operating system. Ink and paper trade places in the dark, so
  ink is always the text and paper always what's behind it. Contrast is given
  as light, then dark.
*/
export default css`
  :host {
    /* Secondary text. 6.8:1 and 6.9:1 on paper. */
    --ash: var(--slab-styled-ash, light-dark(#5e5a55, #a8a19a));
    --border: 2px solid var(--ink);

    /* Behind disabled and read-only controls, and hovered rows. */
    --chalk: var(--slab-styled-chalk, light-dark(#f4f1ec, #2b2926));

    /*
      The logo's orange, brighter in the dark. 4.25:1 and 5.2:1 on paper is
      enough for borders, fills and large text, but not always for small text,
      which takes "--ember-deep".
    */
    --ember: var(--slab-styled-ember, light-dark(#d9492a, #ec5f3b));

    /*
      Orange for small text on paper, and for paper text on it. 5.7:1 and
      7.4:1.
    */
    --ember-deep: var(--slab-styled-ember-deep, light-dark(#b3381a, #ff8566));
    --font-body: var(
      --slab-styled-font-body,
      'IBM Plex Sans',
      system-ui,
      sans-serif
    );
    --font-display: var(
      --slab-styled-font-display,
      'Zilla Slab',
      rockwell,
      'Roboto Slab',
      serif
    );
    --font-mono: var(
      --slab-styled-font-mono,
      'IBM Plex Mono',
      ui-monospace,
      monospace
    );
    --ink: var(--slab-styled-ink, light-dark(#1c1c1c, #f4f1ec));
    --paper: var(--slab-styled-paper, light-dark(#fff, #1a1918));

    /* The hard, offset shadow a raised surface casts. */
    --shadow: 4px 4px 0 var(--ink);
  }
`;
```
