# Expanding search

> A compact search trigger expands into a GET form with optional filterable page links.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/expanding-search`
- File: `src/components/haze/ui/expanding-search.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/input, @haze/utils
- Docs page: https://hazeui.com/ui/expanding-search

## Use when
- Search should stay compact until someone opens it.
- A small local list can guide visitors to known pages.

## Avoid when
- Use Combobox to choose a value rather than following a link.

## Alternatives
- [search-field](https://hazeui.com/ui/search-field.md)
- [command-menu](https://hazeui.com/ui/command-menu.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique search field ID. |
| label | `string` |  | no | Accessible label for the search. |
| name | `string` |  | no | Query parameter sent by the form. |
| placeholder | `string` |  | no | Field hint. |
| action | `string` |  | no | Destination for the GET form. |
| results | `Result[]` |  | no | Optional links to filter as the visitor types. |
| emptyMessage | `string` |  | no | Message when no link matches the query. |
| class | `string` |  | no | Classes for the disclosure surface. |

## Accessibility
- A native disclosure opens the search form without JavaScript.
- Filtering keeps results as regular links.
- Key Keyboard: Enter or Space opens search. Arrow Down focuses the first matching result. Escape closes and returns focus.

## Agent prompts

### Install and use

Install the Haze UI component "Expanding search" with `npx shadcn@latest add @haze/expanding-search`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ExpandingSearch from "@/components/haze/ui/expanding-search.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/expanding-search.md

### Customize with real content

Adapt the Haze expanding-search ui for our product. Replace the demo values of these props with our real content: id, label, name, placeholder, action, results, emptyMessage, class. Keep the layout, the heading level rules and these accessibility details: A native disclosure opens the search form without JavaScript. Filtering keeps results as regular links. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using expanding-search, check it fits: use it when search should stay compact until someone opens it.; a small local list can guide visitors to known pages.. Avoid it when use combobox to choose a value rather than following a link.. Alternatives: @haze/search-field, @haze/command-menu.

## Example requests that should lead here
- Make a search icon expand to a field with matching documentation links below.

## Source

```astro
---
import { Search, X } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
import Input from "./input.astro";

interface Result {
  label: string;
  href: string;
  detail?: string;
}
interface Props {
  id: string;
  label?: string;
  placeholder?: string;
  name?: string;
  action?: string;
  results?: Result[];
  emptyMessage?: string;
  class?: string;
}
const { id, label = "Search", placeholder = "Find a page", name = "q", action = "/browse", results = [],
  emptyMessage = "No matching pages.", class: className } = Astro.props;
---
<details data-haze-expanding-search class={cn("group/search relative h-10 w-10 min-w-0 max-w-full rounded-lg border border-frame-input bg-field hover:border-frame-foreground open:w-full open:border-frame-strong has-[input:focus-visible]:border-ring has-[input:focus-visible]:ring-3 has-[input:focus-visible]:ring-ring/24 motion-safe:transition-[width,border-color] motion-safe:duration-300 motion-safe:ease-snappy", className)}>
  <summary class="absolute inset-s-0 top-0 z-10 grid size-9.5 cursor-pointer list-none place-items-center rounded-lg text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring [&::-webkit-details-marker]:hidden">
    <Search class="size-4" aria-hidden="true" />
    <span class="sr-only group-open/search:hidden">Open {label}</span>
    <span class="hidden group-open/search:sr-only group-open/search:block">Close {label}</span>
  </summary>
  <div class="min-w-0">
    <form method="get" action={action} role="search" aria-label={label} class="min-w-0 overflow-hidden rounded-lg ps-10 pe-10">
      <label for={id} class="sr-only">{label}</label>
      <Input id={id} type="search" name={name} placeholder={placeholder} autocomplete="off" class="h-9.5 rounded-none border-0 bg-transparent px-1 text-sm focus-visible:ring-0 focus-visible:outline-hidden [&::-webkit-search-cancel-button]:appearance-none" />
      <button type="submit" class="sr-only">{label}</button>
    </form>
    <button type="button" data-search-close aria-label="Clear search and close" class="absolute inset-e-1 top-0.75 z-10 grid size-8 cursor-pointer place-items-center rounded-lg text-muted-foreground transition-[color,background-color,scale] duration-150 ease-snappy active:scale-90 active:duration-100 hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring">
      <X class="size-4" aria-hidden="true" />
    </button>
    {results.length > 0 && (
      <div class="absolute inset-x-0 top-full z-20 mt-1.5 grid max-h-[min(20rem,calc(100dvh-6rem))] min-w-0 origin-top overflow-y-auto rounded-xl border border-border bg-popover p-1.5 text-popover-foreground shadow-float motion-safe:animate-rise">
        <ul aria-label="Suggested pages" class="grid min-w-0 gap-0.5">
          {results.map(({ label: title, href, detail }) => (
            <li data-search-result class="min-w-0 [&[hidden]]:hidden">
              <a href={href} class="grid min-h-9 min-w-0 content-center gap-0.5 rounded-lg px-2.5 py-1 text-[0.8125rem]/5 wrap-anywhere hover:bg-accent focus-visible:bg-accent focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring">
                {title}
                {detail && <span class="text-xs/4 text-muted-foreground">{detail}</span>}
              </a>
            </li>
          ))}
        </ul>
        <p data-search-empty hidden class="p-2.5 text-xs/5 text-muted-foreground [&[hidden]]:hidden">{emptyMessage}</p>
      </div>
    )}
  </div>
</details>

<script>
  function enhance(root: HTMLDetailsElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const input = root.querySelector<HTMLInputElement>("input[type=search]");
    const trigger = root.querySelector("summary");
    if (!input || !trigger) return;
    const items = [...root.querySelectorAll<HTMLElement>("[data-search-result]")];
    const empty = root.querySelector<HTMLElement>("[data-search-empty]");
    const options = items.map(item => ({ item, label: (item.textContent ?? "").trim().toLocaleLowerCase() }));
    input.addEventListener("input", () => {
      const value = input.value.trim().toLocaleLowerCase();
      for (const { item, label } of options) item.hidden = !label.includes(value);
      if (empty) empty.hidden = items.some(item => !item.hidden);
    });
    root.querySelector("[data-search-close]")?.addEventListener("click", () => {
      input.value = "";
      input.dispatchEvent(new Event("input", { bubbles: true }));
      root.open = false;
      trigger.focus();
    });
    trigger.addEventListener("click", () => {
      requestAnimationFrame(() => {
        if (root.open && document.activeElement === trigger) input.focus();
      });
    });
    root.addEventListener("keydown", event => {
      if (event.key === "Escape" && root.open) {
        event.preventDefault();
        root.open = false;
        trigger.focus();
      } else if (event.key === "ArrowDown" && document.activeElement === input) {
        const first = root.querySelector<HTMLElement>("[data-search-result]:not([hidden]) a");
        if (first) { event.preventDefault(); first.focus(); }
      }
    });
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLDetailsElement>("[data-haze-expanding-search]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-expanding-search-listener")) {
    document.documentElement.setAttribute("data-haze-expanding-search-listener", "");
    document.addEventListener("astro:page-load", init);
    document.addEventListener("pointerdown", event => {
      document.querySelectorAll<HTMLDetailsElement>("[data-haze-expanding-search][open]").forEach(root => {
        if (!root.contains(event.target as Node)) root.open = false;
      });
    });
  }
</script>
```
