# GlassInput

> A text field of frosted glass. Type in it and its clear button pinches off its end as a droplet; clear it and the droplet melts back in. A value that fails its check shakes the field, and its message rises in under it.

```tsx
import { Field, FieldLabel } from '@ui-sdk/react/field'
import { HugeiconsIcon } from '@hugeicons/react'
import { Mail01Icon } from '@hugeicons/core-free-icons'
import { useLayoutEffect, useRef, useState } from 'react'

import { GlassButton } from '@/components/liquid-glass/glass-button'
import { GlassInput, GlassInputError } from '@/components/liquid-glass/glass-input'
import { followGlass } from '@/components/liquid-glass/glass-layer'

const COLS = 13
const ROWS = 7

/** 1 around the middle of the grid, falling to 0 at its edge. */
const fade = (col: number, row: number) => {
  const distance = Math.hypot((col - (COLS - 1) / 2) / (COLS / 2), (row - (ROWS - 1) / 2) / (ROWS / 2))
  return Math.min(1, Math.max(0, (1 - distance) / 0.45))
}

// Press Subscribe with the field empty, or with "hollis": the Field shakes and the message rises
// in under it, then goes up and out two seconds later. Type an address: the clear button pinches
// off the field's end as a droplet; press it and the droplet melts back in.
// On a phone the button goes under the field, in the middle and as wide as its word, and moves
// down out of the message's way while it shows (`onShownChange`); the glass is told it moves (`followGlass`).
// Behind it, only the Press demo's fine grid on the page's own colour, centred on the field (it
// stays still while the Field shakes): plain DOM, every cell draws its own top and left line,
// fainter towards the edge.
const Grid = () => (
  <div aria-hidden className="absolute top-1/2 left-1/2 -z-10 grid -translate-x-1/2 -translate-y-1/2 grid-cols-[repeat(13,40px)]">
    {Array.from({ length: COLS * ROWS }, (_, i) => (
      <span key={i} className="relative size-10" style={{ opacity: fade(i % COLS, Math.floor(i / COLS)) }}>
        <span className="absolute inset-x-0 top-0 h-px bg-black/10 dark:bg-white/10" />
        <span className="absolute inset-y-0 left-0 w-px bg-black/10 dark:bg-white/10" />
      </span>
    ))}
  </div>
)

export default function Demo() {
  const [subscribed, setSubscribed] = useState('')
  // Which message's pill is showing: the button makes room while either is.
  const [missing, setMissing] = useState(false)
  const [mismatch, setMismatch] = useState(false)
  const room = missing || mismatch
  const slot = useRef<HTMLDivElement>(null)
  useLayoutEffect(() => {
    if (slot.current) followGlass(slot.current)
  }, [room])
  return (
    <div className="relative isolate flex h-[24rem] w-full max-w-xl items-center justify-center">
      {/* The field and its button on one row, the same height (both `lg`, 48 px) (one under the other on a phone). The
          label above the field and the message below it are placed off its edges, so the row is
          laid out by the two alone. */}
      <form
        className="flex w-full max-w-md flex-col gap-2 sm:flex-row sm:items-center"
        onSubmit={(event) => {
          event.preventDefault()
          setSubscribed(String(new FormData(event.currentTarget).get('email')))
        }}
      >
        <div className="relative min-w-0 sm:flex-1">
          <Grid />
          {/* Relative: the label and the message are placed off the Field, which is what shakes. */}
          <Field name="email" className="relative">
            <FieldLabel className="absolute bottom-full mb-2 px-4 text-sm font-medium text-neutral-900 dark:text-white">Email</FieldLabel>
            <GlassInput
              size="lg"
              type="email"
              required
              autoComplete="email"
              placeholder="you@example.com"
              clearLabel="Clear email"
              start={<HugeiconsIcon icon={Mail01Icon} />}
              onValueChange={() => setSubscribed('')}
              className="w-full"
            />
            <div className="absolute inset-x-0 top-full mt-2">
              <GlassInputError match="valueMissing" onShownChange={setMissing}>
                Enter your email address.
              </GlassInputError>
              <GlassInputError match="typeMismatch" onShownChange={setMismatch}>
                Enter a valid email address.
              </GlassInputError>
            </div>
          </Field>
        </div>
        {/* Moved by a transform, so the field above it stays where it is: down by the message's
            height and its gaps (12 + 32 px) while one shows, on a phone only. */}
        <div
          ref={slot}
          className={`max-sm:self-center transition-transform duration-[250ms] ease-[cubic-bezier(0.2,0.8,0.2,1)] motion-reduce:transition-none ${room ? 'max-sm:translate-y-11' : ''}`}
        >
          <GlassButton type="submit" size="lg">
            {subscribed ? 'Subscribed' : 'Subscribe'}
          </GlassButton>
        </div>
      </form>
    </div>
  )
}
```

**Use it for**

- Short text in a form: a name, an email address, a website, a code.
- A value someone types once and gets right: a username, a coupon, a reference number.
- Text with fixed words around it (`https://`, `.com`, a unit) that are not part of the value.

**Not for**

- Looking in several kinds of things at once, with results: use Search.
- Choosing from a known list: use Select.
- Long text over several lines: a textarea.

```bash
npx shadcn@latest add https://liquidglass.onemorethink.dev/r/input.json
```

> The behaviour (the native field, the form it is in, UI SDK's Field and its label and errors, and the reason each change is made) comes from UI SDK's Input, so Input needs `@ui-sdk/core` and `@ui-sdk/react`. The install command adds them at the exact version this was built on: UI SDK is in beta and its API may still change.

## Usage

```tsx
import { Field, FieldLabel } from '@ui-sdk/react/field'
import { GlassInput, GlassInputError } from '@/components/liquid-glass/glass-input'

<form onSubmit={subscribe}>
  <Field name="email">
    <FieldLabel>Email</FieldLabel>
    <GlassInput type="email" required autoComplete="email" placeholder="you@example.com" clearLabel="Clear email" />
    <GlassInputError match="valueMissing">Enter your email address.</GlassInputError>
    <GlassInputError match="typeMismatch">Enter a valid email address.</GlassInputError>
  </Field>
  <GlassButton type="submit">Subscribe</GlassButton>
</form>
```

Empty, the field is one body of glass. Type, and its clear button pinches off the field's end as a droplet, the body pulling back to make room, and its cross comes in out of a blur once the droplet is out. Press it and the text goes, the caret stays in the field, and the droplet melts back in. The field is a surface: it holds still under the pointer, a press lights it where it lands, and placing the caret melts nothing. Its glass is Button's: clear and as full of light as a GlassButton beside it, so a field and its button are one material. It is clear, so it needs something behind it to bend.

## Validation

Submit a form with a value that fails its check (`required`, `type="email"`, `pattern`…) and the field shakes from side to side, two pixels each way in 200 ms (inside a Field the whole Field does, its label with it), while its message rises in under it as a pill: from a little below, a little small and blurred, on a spring that just passes its place. Two seconds later the pill goes up, grows and blurs away; submit again and a new one comes in as the old one leaves. The field also shakes when your code marks it invalid (the Field's `invalid`). `GlassInputError` is UI SDK's FieldError: put it right after the GlassInput inside the Field, one per message, with the same `match`. It takes no room of its own (the pill floats over what is below it), and the message stays for screen readers after the pill has gone; `hideAfter={0}` keeps the pill too. The shake and the pill are Lué Studio's contact form (lue.studio/contact), taken from its code and checked frame by frame against a recording of it.

## API reference

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `size` | `'sm' \| 'md' \| 'lg'` | `'md'` | 32, 40 or 48 px tall. |
| `start` | `ReactNode` | — | Inside the glass, before the text: an icon, or text such as `https://`. Not part of the value. |
| `end` | `ReactNode` | — | Inside the glass, after the text and before the droplet. |
| `clearable` | `boolean` | `true` | A clear button that pinches off the field's end as a droplet while there is text. |
| `clearLabel` | `string` | `'Clear'` | The clear button's accessible name. Write it in the page's language. |
| `shake` | `boolean` | `true` | Shake from side to side when the value fails its check: on a submit, and when the Field marks it invalid. Inside a Field the whole Field shakes, its label and its message too. |
| `value / defaultValue / onValueChange` | `UI SDK Input` | — | As on UI SDK's Input: the value, for a controlled field, or the one it starts with; and the change, with its reason (`input-change`, `clear-press`, `reset`, `imperative`). `details.cancel()` keeps the text as it was. |
| `controller` | `InputController` | — | From `createInputController()` of `@ui-sdk/react/input`: reads, writes, clears and focuses the field from anywhere. |
| `material` | `'clear' \| 'tinted'` | `'clear'` | Clear glass frosts and bends what is behind; tinted takes the colour of your own `bg-*` class. |
| `tint` | `number` | `0.6` | Clear glass: how much tint covers the backdrop (0–1), as on Button. |
| `blur` | `number` | `0` | Clear glass: how much the backdrop is frosted, in px; 0 leaves it clear, as on Button. |
| `className` | `string` | — | On the glass: its width (18rem by default) and, for tinted glass, its `bg-*`. |
| `inputClassName` | `string` | — | On the native input inside. |
| `GlassInputError match` | `ValidityKey \| boolean` | — | When the message shows, as on UI SDK's FieldError: a validity flag (`'valueMissing'`, `'typeMismatch'`…), `true` for an error of your own, or left out for any problem. |
| `GlassInputError hideAfter` | `number` | `2000` | How long the pill stays before it goes up and out (ms); `0` keeps it while the value is wrong. The message stays for screen readers either way. |
| `GlassInputError onShownChange` | `(shown: boolean) => void` | `—` | Called with `true` as the pill comes in and `false` as it starts to go, on the same frame. The pill takes no room, so this is how what is below makes room for it: the example moves its button down on a phone. |
| `…` | `input props` | — | Every native input prop goes to the input: `type`, `name`, `placeholder`, `autoComplete`, `required`, `pattern`, `disabled`, `readOnly`… |

## Accessibility

- A native `<input>`: text editing, selection, autocomplete and the form behave as they always do. Name it with a Field's label or `aria-label`.
- The clear button is a button named by `clearLabel`. It is in the tab order only while there is text; pressing it empties the field, reports `clear-press` and puts the caret back.
- Inside a Field, an invalid value marks the input `aria-invalid` and the Field's errors describe it.
- A failed check marks the input `aria-invalid`, describes it with the message (UI SDK's FieldError) and moves the focus to it. The pill is a picture of that message, hidden from screen readers, and the message stays after the pill has gone.
- With reduced motion the cross and the pill fade in and out, and the field does not shake; the droplet's own motion is the engine's, which reduced motion stills.
- Without WebGL2 it is a plain frosted field with a clear button at its end.

Source: https://liquidglass.onemorethink.dev/docs/input
