# Pin Input

> A PIN or one-time code field: a row of native inputs, one per character, that submits as one value.

`<slab-pin-input>` · Form · built on `<input>`

## Install

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

## Usage

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

<slab-pin-input label="Verification code" name="code" autocomplete="one-time-code" required></slab-pin-input>
```

## Example

Here's a styled version, `<slab-styled-pin-input>`. 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-pin-input label="Site access code" length="6" autocomplete="one-time-code" required>
  <span slot="description">Sent to the foreman's phone. Try pasting "482-913".</span>
</slab-styled-pin-input>
```

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.

The inputs fill from the start, without gaps, and the row is one tab stop. A pasted or autofilled code is spread across them from the input it lands in, keeping only the characters `type` accepts, so "123-456" fills six. Listen for "complete" to verify a code as soon as the last character is in.

The group is named by `label`, and each input by `inputLabel`, "Character 1 of 6" and so on unless you set it. Lay the inputs out with `::part(inputs)`, and style an input with a character in it with `::part(filled)`.

## Keyboard

| Key            | What it does                                                                         |
| -------------- | ------------------------------------------------------------------------------------ |
| A character    | Fills the focused input and moves to the next.                                       |
| Backspace      | Deletes the focused input's character, or the one before it when the input is empty. |
| Delete         | Deletes the focused input's character.                                               |
| Left, Right    | Moves to the previous or next input, up to the first empty one.                      |
| Home, End      | Moves to the first input, or to where typing continues.                              |
| Enter          | Submits the form.                                                                    |
| Tab, Shift+Tab | Moves out of the field.                                                              |

## Behavior

A PIN or one-time code field with no visual styles: a row of native inputs, one per character, that reads and submits as one value.

Typing a character moves to the next input, and Backspace moves back. A pasted or autofilled code is spread across the inputs from the one it lands in, with anything that isn't a digit, or a letter or digit for `type="alphanumeric"`, left out. So "123-456" fills six inputs. Set `autocomplete="one-time-code"` for a code sent by text or email, and the browser offers it above the keyboard.

The inputs fill from the start, without gaps. Focusing one past the first empty input focuses that empty one instead, and deleting a character moves the ones after it back. The row is one tab stop, and the arrow keys, Home and End move between inputs.

The inputs are a `[role=group]` named by `label`, and each is named by `inputLabel`, "Character 1 of 6" and so on unless you set it.

`required` makes an empty value invalid, as `valueMissing`. A value that's started but has fewer than `length` characters is always invalid, as `tooShort`, whether or not the field is required.

Style it through its parts and through `:state(complete)`, `:state(disabled)`, `:state(error)`, `:state(readonly)` and `:state(required)`.

## API

### `<slab-pin-input>`

#### Attributes

| Name | Type | Default | Description |
| --- | --- | --- | --- |
| `label` (required) | `string` |  |  |
| `autocomplete` | `HTMLInputElement['autocomplete']` |  | Set on the first input. "one-time-code" for a code sent by text or email. |
| `disabled` | `boolean` | `false` |  |
| `hide-label` | `boolean` | `false` |  |
| `length` | `number` | `6` | How many characters, and so how many inputs. |
| `mask` | `boolean` | `false` | Hides each character as it's typed, as a password input does. |
| `name` | `string` | `''` |  |
| `placeholder` | `string` |  | Shown in each empty input. |
| `readonly` | `boolean` | `false` |  |
| `required` | `boolean` | `false` |  |
| `type` | `'numeric' \| 'alphanumeric'` | `'numeric'` | "numeric" accepts digits and brings up a number pad. "alphanumeric" accepts letters and digits. |
| `value` | `string` | `''` | Like a native input, the attribute is the default value and the property is the current one, so the attribute doesn't change as the field is typed into. |
| `version` | `string` |  |  |

#### Properties

| Name | Type | Description |
| --- | --- | --- |
| `inputLabel` | `(position: number, length: number) => string` | Names each input from its position, starting at 1, and `length`. "Character 1 of 6" and so on when unset. |
| `form` (read-only) | `HTMLFormElement \| null` |  |
| `validity` (read-only) | `ValidityState` |  |

#### Methods

| Signature | Description |
| --- | --- |
| `checkValidity(): boolean` |  |
| `focus(options?: FocusOptions): void` |  |
| `reportValidity(): boolean` |  |
| `resetValidityFeedback(): void` | Clears the validity feedback without changing `validity`. |
| `setCustomValidity(message: string): void` |  |
| `setValidity(flags?: ValidityStateFlags, message?: string): void` |  |

#### Events

| Name | Type | Description |
| --- | --- | --- |
| `input` | `Event` |  |
| `complete` | `Event` |  |
| `change` | `Event` |  |

#### Slots

| Name | Type | Description |
| --- | --- | --- |
| `description` | `Element \| string` |  |

#### CSS parts

| Name | Description |
| --- | --- |
| `description` | Text about the field, and its validity message when it has one |
| `filled` | An input with a character in it |
| `input` | Each input |
| `inputs` | The inputs' container |
| `label` | The label |
| `validity-message` |  |

## Copy and own it

`<slab-styled-pin-input>` 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.

### pin-input.ts

```ts
import { customElement } from 'lit/decorators.js';
import PinInput from 'slab-elements/pin-input.js';
import styles from './pin-input.styles.js';
import textInput from './text-input.styles.js';
import tokens from './tokens.styles.js';

declare global {
  interface HTMLElementTagNameMap {
    'slab-styled-pin-input': StyledPinInput;
  }
}

/**
 * Pin Input, styled: Text Field's look, cut into a row of square inputs in
 * a mono face, each filled one set on an ember base.
 */
@customElement('slab-styled-pin-input')
export default class StyledPinInput extends PinInput {
  static override styles = [tokens, textInput, styles];
}
```

### pin-input.styles.ts

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

export default css`
  [part~='inputs'] {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
  }

  [part~='input'] {
    font-family: var(--font-mono);
    font-size: 1.25rem;
    font-weight: 600;
    inline-size: 3rem;
    padding: 0;
    text-align: center;

    /* The selection would cover the one character, so it's only a caret. */
    &::selection {
      background-color: transparent;
    }
  }

  [part~='filled'] {
    border-block-end-color: var(--ember);
    border-block-end-width: 4px;
  }
`;
```

### text-input.styles.ts

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

/*
  The look shared by everything typed into: Text Field, Textarea, Number, Date
  Field, Time Field and Combobox, whose fields are "::part(input)", or
  "::part(textarea)" for Textarea. File Drop starts from it too, for its label
  and description.
*/
export default css`
  :host {
    color: var(--ink);
    display: grid;
    font-family: var(--font-body);
  }

  [part~='label'] {
    font-family: var(--font-display);
    font-size: 1.0625rem;
    font-weight: 600;
    margin-block-end: 0.375rem;
  }

  :host(:state(required)) [part~='label']::after {
    color: var(--ember-deep);
    content: ' *' / '';
  }

  [part~='input'],
  [part~='textarea'] {
    background-color: var(--paper);
    block-size: 3rem;
    border: var(--border);
    border-radius: 0;
    box-sizing: border-box;
    color: inherit;
    font: inherit;

    /* A fixed height, shared with Select, so fields line up in a row. */
    padding: 0 0.75rem;
    transition:
      background-color 100ms,
      border-color 100ms,
      box-shadow 100ms,
      translate 100ms;

    &::placeholder {
      color: var(--ash);
    }

    /*
      The outline is transparent rather than gone, so it still shows in forced
      colors, where box shadows don't.
    */
    &:focus-visible {
      box-shadow: 4px 4px 0 var(--ember);
      outline: 2px solid transparent;
      translate: -2px -2px;
    }

    &:disabled {
      background-color: var(--chalk);
      border-style: dashed;
      color: var(--ash);
      cursor: not-allowed;
    }
  }

  [part~='textarea'] {
    block-size: auto;
    min-block-size: 7rem;
    padding: 0.625rem 0.75rem;
    resize: vertical;
  }

  :host(:state(readonly)) [part~='input'],
  :host(:state(readonly)) [part~='textarea'] {
    background-color: var(--chalk);
  }

  :host(:state(error)) [part~='input'],
  :host(:state(error)) [part~='textarea'] {
    border-color: var(--ember-deep);
  }

  /*
    Spaced by what's in it rather than by a gap, so a description with
    nothing in it takes no room, and a control beside the field lines up
    with its bottom edge.
  */
  [part~='description'] {
    color: var(--ash);
    display: grid;
    font-size: 0.875rem;
  }

  ::slotted([slot='description']) {
    margin-block-start: 0.375rem;
  }

  [part~='validity-message'] {
    color: var(--ember-deep);
    font-weight: 600;
    margin-block-start: 0.375rem;

    &::before {
      content: '■ ' / '';
    }
  }

  @media (prefers-reduced-motion: reduce) {
    [part~='input'],
    [part~='textarea'] {
      transition: none;
    }
  }
`;
```

### 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);
  }
`;
```
