# Search field

A search field with its ⌘K hint at rest, a clear button once there is text, Esc to clear, and Enter that never fires mid-composition.

Tier: free. Type: component. Category: inputs. Tags: keyboard.

## Install

```bash
npx shadcn@latest add https://pixilui.com/r/search-field.json
```

One-time setup: add the registry to `components.json`:

```json
{
  "registries": {
    "@pixilui": "https://pixilui.com/r/{name}.json"
  }
}
```

Files: `components/pixilui/search-field.tsx`.

## Preview

Live preview: https://pixilui.com/components/search-field

Knobs:

- `size`: `none`, `sm`, `md`, `lg`

Signature: At rest it shows ⌘K; type and the hint gives way to a clear button, and Esc empties it without leaving the field.

Styles: `lively` (default), `quiet`, set with `data-style` on <html>. The item reads the style through the foundation; it needs no prop. Standalone files: lively https://pixilui.com/r/standalone/search-field.tsx, quiet https://pixilui.com/r/standalone/search-field.quiet.tsx.

## Code

`components/pixilui/search-field.tsx`

```tsx
"use client";

/*
  The search field, locked 1 Dec 2026 (design/explorations/components/locked/inputs, B8). The frame is the
  Field's (../field/field); the look is foundation.css section 8.

  At rest   the shortcut that reaches it (⌘K) sits at the end. Typing hides it and shows the clear button;
            focusing hides it too.
  Clear     the button or Esc (with a value) empties the field as if typed, so onChange runs, and keeps focus.
  Submit    Enter calls onSubmit, never in the middle of composing (Japanese, Chinese input).
  Typing    native: nothing animates on keys.
*/

import { forwardRef, useImperativeHandle, useRef, useState, type ChangeEvent, type ComponentPropsWithoutRef, type KeyboardEvent, type ReactNode } from "react";
import { Field, FieldControl, FieldHintKey, FieldIconButton, FieldInput, FieldPrefix, FieldSuffix, setFieldValue, type FieldSize } from "./field";

export type SearchFieldProps = Omit<ComponentPropsWithoutRef<"input">, "size" | "prefix" | "onSubmit"> & {
  /** The field's name for screen readers ("Search runs"). Search usually has no visible label. */
  "aria-label": string;
  /** The search icon before the text (the animated search icon). */
  icon?: ReactNode;
  /** The shortcut that focuses it, shown at rest without a value: "⌘K". Wiring the key itself is the page's job. */
  shortcut?: ReactNode;
  /** The clear button's name. */
  clearLabel?: string;
  /** The clear button's icon (a cross). */
  clearIcon: ReactNode;
  /** Runs after the clear button or Esc empties the field. */
  onClear?: () => void;
  /** Runs on Enter with the trimmed text. */
  onSubmit?: (query: string) => void;
  /** The button height of the same name. */
  size?: FieldSize;
  /** Classes for the field. Native attributes and the ref go to the input. */
  className?: string;
};

/** A search field: Esc clears it and keeps your focus, a clear button with a value, its shortcut without one. */
export const SearchField = forwardRef<HTMLInputElement, SearchFieldProps>(function SearchField(
  { icon, shortcut, clearLabel = "Clear", clearIcon, onClear, onSubmit, size, className, value, defaultValue, onChange, onKeyDown, id, ...props },
  ref,
) {
  const input = useRef<HTMLInputElement | null>(null);
  useImperativeHandle(ref, () => input.current!, []);
  const [inner, setInner] = useState(String(defaultValue ?? ""));
  const current = value != null ? String(value) : inner;
  const empty = () => {
    const el = input.current;
    if (!el) return;
    setFieldValue(el, "");
    onClear?.();
  };
  return (
    <Field className={className} kind="search" size={size} filled={current.length > 0} inputId={id}>
      <FieldControl>
        {icon != null ? <FieldPrefix>{icon}</FieldPrefix> : null}
        <FieldInput
          ref={input}
          type="search"
          value={value}
          defaultValue={defaultValue}
          onChange={(event: ChangeEvent<HTMLInputElement>) => {
            if (value == null) setInner(event.target.value);
            onChange?.(event);
          }}
          onKeyDown={(event: KeyboardEvent<HTMLInputElement>) => {
            onKeyDown?.(event);
            if (event.defaultPrevented || event.nativeEvent.isComposing) return;
            if (event.key === "Escape" && event.currentTarget.value) {
              event.preventDefault();
              empty();
            } else if (event.key === "Enter" && onSubmit) {
              event.preventDefault();
              onSubmit(event.currentTarget.value.trim());
            }
          }}
          {...props}
        />
        <FieldSuffix>
          {shortcut != null ? <FieldHintKey>{shortcut}</FieldHintKey> : null}
          <FieldIconButton
            className="pixilui-field-clear"
            aria-label={clearLabel}
            onClick={() => {
              empty();
              input.current?.focus();
            }}
          >
            {clearIcon}
          </FieldIconButton>
        </FieldSuffix>
      </FieldControl>
    </Field>
  );
});
```

## Usage

When to use:

- Searching runs, agents and people in a panel or a header.

When not to use:

- A command palette: use the command menu.
- Filtering by known groups: use Chip group.

```tsx
import { useState } from "react";
import { IconSearch } from "@/components/pixilui/icons/search";
import { SearchField } from "@/components/pixilui/search-field";
import type { FieldSize } from "@/components/pixilui/field";

// The first option of each knob is the demo's default; the docs preview starts there.
export const knobs = {
  size: ["none", "sm", "md", "lg"],
} as const;

/** The static Hugeicons cancel-01 (MIT): the clear button's cross, which has no animated icon. */
function IconCross() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M18 6L6 18m12 0L6 6" />
    </svg>
  );
}

/** Search over runs: Enter searches, Esc clears. */
export default function SearchFieldDemo({ size = "none" }: KnobValues<typeof knobs>) {
  const [last, setLast] = useState<string | null>(null);
  return (
    <div className="flex w-full max-w-sm flex-col gap-3">
      <SearchField aria-label="Search runs" icon={<IconSearch />} shortcut="⌘K" placeholder="Search runs, agents and people" clearIcon={<IconCross />} onSubmit={setLast} size={size === "none" ? undefined : (size as FieldSize)} />
      <p className="type-caption text-muted">{last === null ? "No search yet" : last ? `Searched for "${last}"` : "Searched for everything"}</p>
    </div>
  );
}
```

## Examples

None.

## API

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `className` | `string` |  | Classes for the field. Native attributes and the ref go to the input. |
| `aria-label` (required) | `string` |  | The field's name for screen readers ("Search runs"). Search usually has no visible label. |
| `icon` | `ReactNode` |  | The search icon before the text (the animated search icon). |
| `shortcut` | `ReactNode` |  | The shortcut that focuses it, shown at rest without a value: "⌘K". Wiring the key itself is the page's job. |
| `clearLabel` | `string` | `"Clear"` | The clear button's name. |
| `clearIcon` (required) | `ReactNode` |  | The clear button's icon (a cross). |
| `onClear` | `() => void` |  | Runs after the clear button or Esc empties the field. |
| `onSubmit` | `(query: string) => void` |  | Runs on Enter with the trimmed text. |
| `size` | `FieldSize` |  | The button height of the same name. |

Also accepts every native `<input>` attribute except `size`, `prefix`, `onSubmit`, and a ref to it.

## Keyboard

- `Escape`: Clears the text when there is some.
- `Enter`: Runs onSubmit with the text, never in the middle of composing.

## Accessibility

- Named by its aria-label; the clear button is a labelled button.

## Motion

- The shortcut hint and the clear button swap as text arrives and leaves; nothing animates on keys.

## Responsive

- Fills its container's width; the label row and the message wrap.

## Performance

- Native typing: nothing renders per key beyond the value; the look is CSS in the foundation (section 8).

## Notes for AI

- <SearchField aria-label="Search runs" icon={<IconSearch />} shortcut="⌘K" clearIcon={...} onSubmit={run} />.
- onClear runs after the clear button or Esc empties it.

## Related

- [Input](https://pixilui.com/components/input/markdown): A text field with its label, help and error, a unit or icon on either side, and a rule that checks on blur and Enter and says what's wrong in plain words.
- [Chip group](https://pixilui.com/components/chip-group/markdown): A row of filter chips with counts: press one and it fills with the accent tint, and the total beside it rolls only the digits that changed.
