# Input

> Labeled text field with helper and error text, an optional prefix or suffix, a password field that can show what you typed, and a search field you can clear.

Docs: https://plumbago.ochotzas.com/components/input

## Installation

```sh
npx plumbago add input
```

This copies `components/ui/input.tsx` into your project, along with `cn`, `field`, and installs `@base-ui/react`.

## Usage

```tsx
import { TextField } from "@/components/ui/input"

<TextField label="Dish name" placeholder="Slow-roasted lamb shoulder" />
```

## Examples

### Preview

```tsx
import { TextField } from "@/components/ui/input"

export default function InputDemo() {
  return (
    <div className="w-full max-w-80">
      <TextField label="Dish name" placeholder="Slow-roasted lamb shoulder" />
    </div>
  )
}
```

### With description

```tsx
import { TextField } from "@/components/ui/input"

export default function InputWithDescription() {
  return (
    <div className="w-full max-w-80">
      <TextField label="Dish name" defaultValue="Smoked aubergine" description="Shown on the menu and on printed tickets." />
    </div>
  )
}
```

### Prefix and suffix

```tsx
import { TextField } from "@/components/ui/input"

export default function InputPrefixAndSuffix() {
  return (
    <div className="flex w-full max-w-80 flex-col gap-4">
      <TextField label="Price" prefix="€" inputMode="decimal" defaultValue="14.50" />
      <TextField label="Prep time" suffix="min" inputMode="numeric" defaultValue="25" />
    </div>
  )
}
```

### Error

```tsx
import { Button } from "@/components/ui/button"
import { TextField } from "@/components/ui/input"
import { useState } from "react"

export default function InputError() {
  const [price, setPrice] = useState("")
  const [error, setError] = useState<string>()
  const [rejections, setRejections] = useState(0)

  return (
    <form
      noValidate
      className="flex w-full max-w-80 flex-col gap-4"
      onSubmit={(event) => {
        event.preventDefault()
        if (/^\d+(\.\d{1,2})?$/.test(price)) {
          setError(undefined)
          return
        }
        setError("Enter a price, like 14.50.")
        setRejections((count) => count + 1)
      }}
    >
      <TextField
        label="Price"
        placeholder="14.50"
        prefix="€"
        inputMode="decimal"
        value={price}
        error={error}
        shakeKey={rejections}
        onChange={(event) => {
          setPrice(event.target.value)
          setError(undefined)
        }}
      />
      <Button type="submit">Save price</Button>
    </form>
  )
}
```

### With a button

```tsx
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { useState } from "react"

export default function InputWithAButton() {
  const [dish, setDish] = useState("")
  const [added, setAdded] = useState<string[]>([])

  return (
    <form
      className="flex w-full max-w-80 flex-col gap-3"
      onSubmit={(event) => {
        event.preventDefault()
        if (dish.trim() === "") return
        setAdded((list) => [dish.trim(), ...list])
        setDish("")
      }}
    >
      <div className="flex gap-2">
        <Input aria-label="Dish name" placeholder="Add a dish" value={dish} onChange={(event) => setDish(event.target.value)} />
        <Button type="submit" variant="secondary" disabled={dish.trim() === ""}>
          Add
        </Button>
      </div>
      {added.length > 0 && (
        <p
          key={added[0]}
          className="ml-1 text-footnote text-ink-2 transition-[opacity,filter] duration-spring ease-spring starting:opacity-0 motion-safe:starting:blur-[4px]"
        >
          Added {added[0]} to Specials.
        </p>
      )}
    </form>
  )
}
```

### Password

```tsx
import { FieldDescription, FieldLabel, FieldRoot, PasswordInput } from "@/components/ui/input"

export default function InputPassword() {
  return (
    <FieldRoot className="max-w-80">
      <FieldLabel>Staff PIN</FieldLabel>
      <PasswordInput inputMode="numeric" defaultValue="4821" />
      <FieldDescription>Used to open the till and void orders.</FieldDescription>
    </FieldRoot>
  )
}
```

### Search

```tsx
import { SearchInput } from "@/components/ui/input"

export default function InputSearch() {
  return (
    <div className="w-full max-w-80">
      <SearchInput placeholder="Search dishes" aria-label="Search dishes" defaultValue="risotto" />
    </div>
  )
}
```

### Disabled

```tsx
import { TextField } from "@/components/ui/input"

export default function InputDisabled() {
  return (
    <div className="w-full max-w-80">
      <TextField label="Kitchen station" defaultValue="Grill" disabled />
    </div>
  )
}
```

### Inside an island

```tsx
import { TextField } from "@/components/ui/input"
import { Island } from "@/components/ui/island"

export default function InputInsideAnIsland() {
  return (
    <Island className="flex w-full max-w-md flex-col gap-4">
      <TextField label="Table name" placeholder="Window 4" />
      <TextField label="Seats" type="number" defaultValue="12" error="This table seats 8 at most." />
    </Island>
  )
}
```

## Built on Base UI

Input wraps these Base UI parts and keeps their props:

- [Input](https://base-ui.com/react/components/input)

## Source

```tsx
import { Input as BaseInput } from "@base-ui/react/input"
import { cn } from "@/lib/cn"
import { FieldDescription, FieldError, FieldLabel, FieldRoot, fieldControlStyle } from "@/components/ui/field"
import { type ComponentProps, type ReactNode, useRef, useState } from "react"

export { FieldDescription, FieldError, FieldLabel, FieldRoot }

type BaseInputProps = Omit<ComponentProps<typeof BaseInput>, "className" | "prefix">

export type InputProps = BaseInputProps & {
  prefix?: ReactNode
  suffix?: ReactNode
  className?: string
}

const groupStyle = cn(
  "relative flex h-11 w-full items-center gap-2 rounded-md bg-fill-field px-4 text-body text-ink",
  "transition-shadow duration-fast ease-out focus-within:ring-2 focus-within:ring-accent",
  "has-data-invalid:animate-shake has-data-invalid:ring-2 has-data-invalid:ring-danger motion-reduce:has-data-invalid:animate-none",
  "has-disabled:cursor-default has-disabled:opacity-40",
)

const groupedInputStyle = "h-full min-w-0 flex-1 border-0 bg-transparent p-0 text-body text-ink outline-none placeholder:text-ink-3 disabled:cursor-default"

const adornmentStyle = "flex shrink-0 items-center text-ink-2 select-none [&_svg]:size-[18px]"

export function Input({ prefix, suffix, className, ...props }: InputProps) {
  if (prefix === undefined && suffix === undefined) {
    return <BaseInput data-slot="input" className={cn(fieldControlStyle, "h-11 px-4", className)} {...props} />
  }
  return (
    <InputGroup className={className}>
      {prefix !== undefined && <span className={adornmentStyle}>{prefix}</span>}
      <BaseInput data-slot="input" className={groupedInputStyle} {...props} />
      {suffix !== undefined && <span className={adornmentStyle}>{suffix}</span>}
    </InputGroup>
  )
}

function InputGroup({ className, children }: { className?: string; children: ReactNode }) {
  return (
    <div data-slot="input-group" className={cn(groupStyle, className)}>
      {children}
    </div>
  )
}

export type TextFieldProps = InputProps & {
  label: ReactNode
  description?: ReactNode
  error?: ReactNode
  shakeKey?: number
}

export function TextField({ label, description, error, shakeKey, className, ...inputProps }: TextFieldProps) {
  return (
    <FieldRoot shakeKey={shakeKey} invalid={error ? true : undefined} disabled={inputProps.disabled} className={className}>
      <FieldLabel>{label}</FieldLabel>
      <Input {...inputProps} />
      {error ? <FieldError match>{error}</FieldError> : description && <FieldDescription>{description}</FieldDescription>}
    </FieldRoot>
  )
}

const swapIn = "transition-[opacity,scale,filter] duration-spring ease-spring"
const swapOut = "scale-80 opacity-0 motion-safe:blur-[2px]"

export type PasswordInputProps = Omit<InputProps, "type" | "suffix">

export function PasswordInput({ disabled, ...props }: PasswordInputProps) {
  const [shown, setShown] = useState(false)
  return (
    <Input
      type={shown ? "text" : "password"}
      autoComplete="current-password"
      disabled={disabled}
      {...props}
      suffix={
        <button
          type="button"
          data-slot="password-toggle"
          aria-label={shown ? "Hide password" : "Show password"}
          aria-pressed={shown}
          disabled={disabled}
          onClick={() => setShown((value) => !value)}
          className="relative -mr-1.5 grid size-8 cursor-pointer place-items-center rounded-full text-ink-2 outline-none after:absolute after:-inset-1.5 hover:text-ink focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-default [-webkit-tap-highlight-color:transparent]"
        >
          <EyeIcon className={cn("col-start-1 row-start-1", swapIn, shown && swapOut)} />
          <EyeOffIcon className={cn("col-start-1 row-start-1", swapIn, !shown && swapOut)} />
        </button>
      }
    />
  )
}

export type SearchInputProps = Omit<InputProps, "type" | "prefix" | "suffix"> & {
  clearLabel?: string
}

export function SearchInput({ clearLabel = "Clear search", value, defaultValue, onChange, disabled, ...props }: SearchInputProps) {
  const inputRef = useRef<HTMLInputElement | null>(null)
  const [uncontrolledFilled, setUncontrolledFilled] = useState(String(defaultValue ?? "") !== "")
  const filled = value !== undefined ? String(value) !== "" : uncontrolledFilled

  function clear() {
    const input = inputRef.current
    if (!input) return
    Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "")
    input.dispatchEvent(new Event("input", { bubbles: true }))
    input.focus()
  }

  return (
    <InputGroup className="pr-1.5 pl-3.5 [&_[type=search]::-webkit-search-cancel-button]:appearance-none">
      <svg viewBox="0 0 24 24" aria-hidden="true" className="size-[18px] shrink-0 fill-none stroke-ink-3" strokeWidth="2" strokeLinecap="round">
        <circle cx="11" cy="11" r="6.5" />
        <path d="m16 16 4 4" />
      </svg>
      <BaseInput
        ref={inputRef}
        type="search"
        data-slot="search-input"
        value={value}
        defaultValue={defaultValue}
        disabled={disabled}
        onChange={(event) => {
          setUncontrolledFilled(event.currentTarget.value !== "")
          onChange?.(event)
        }}
        className={groupedInputStyle}
        {...props}
      />
      <button
        type="button"
        data-slot="search-input-clear"
        aria-label={clearLabel}
        aria-hidden={filled ? undefined : true}
        tabIndex={filled && !disabled ? 0 : -1}
        onClick={clear}
        className={cn(
          "relative grid size-8 shrink-0 cursor-pointer place-items-center rounded-full text-ink-3 outline-none after:absolute after:-inset-1.5 hover:text-ink-2 focus-visible:ring-2 focus-visible:ring-accent [-webkit-tap-highlight-color:transparent]",
          swapIn,
          filled && !disabled ? "pointer-events-auto" : cn("pointer-events-none", swapOut),
        )}
      >
        <ClearIcon />
      </button>
    </InputGroup>
  )
}

function EyeIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      className={cn("size-5 fill-none stroke-current", className)}
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M2.5 12s3.5-6.5 9.5-6.5 9.5 6.5 9.5 6.5-3.5 6.5-9.5 6.5S2.5 12 2.5 12Z" />
      <circle cx="12" cy="12" r="3" />
    </svg>
  )
}

function EyeOffIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      aria-hidden="true"
      className={cn("size-5 fill-none stroke-current", className)}
      strokeWidth="1.75"
      strokeLinecap="round"
      strokeLinejoin="round"
    >
      <path d="M10.6 5.6A9.7 9.7 0 0 1 12 5.5c6 0 9.5 6.5 9.5 6.5a17 17 0 0 1-2.4 3.2M6.3 6.9C3.9 8.6 2.5 12 2.5 12s3.5 6.5 9.5 6.5c1.6 0 3-.4 4.2-1M9.9 9.9a3 3 0 0 0 4.2 4.2M3.5 3.5l17 17" />
    </svg>
  )
}

function ClearIcon() {
  return (
    <svg viewBox="0 0 20 20" aria-hidden="true" className="size-[18px]">
      <circle cx="10" cy="10" r="8.5" className="fill-current" />
      <path d="m7.25 7.25 5.5 5.5m0-5.5-5.5 5.5" className="stroke-surface" strokeWidth="1.6" strokeLinecap="round" />
    </svg>
  )
}
```
