# AI search bar

> Search card with instant filtering and a sample AI answer whose citations jump to the matching results.

- Kind: block · Category: AI · Interactivity: script
- Install: `npx shadcn@latest add @haze/ai-search-bar`
- File: `src/components/haze/blocks/ai-search-bar.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/blocks/ai-search-bar

## Use when
- Prototyping a search experience with an example of how an AI summary can cite matching results
- Replacing a plain search modal with a unified Docs, Customers and Issues search card

## Avoid when
- You only need a simple navigation command palette without AI synthesis; use command-menu

## Alternatives
- [command-menu](https://hazeui.com/ui/command-menu.md)
- [ai-answer](https://hazeui.com/blocks/ai-answer.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` | "haze-ai-search-bar" | no | Unique prefix for search input and result anchors. |
| placeholder | `string` | "Search" | no | Search input placeholder. |
| hits | `SearchHit[]` | 4 grouped hits | no | Search results with an optional href. Supplying custom hits hides the sample answer. |
| class | `string` |  | no | Extra classes on the outer section. |

## Accessibility
- Numbered citations inside the AI answer move focus directly to the matching search hit below.
- Citations can reveal a result excluded by the current filter without clearing the search.
- Live match counts and revealed citations are announced in a polite role="status" line.
- Key Tab: Move from the search field to the sample answer button, citations, and available result links
- Key Enter: Follow a citation or result link
- Key Enter / Space: Toggle the sample answer

## Agent prompts

### Install and use

Install the Haze UI block "AI search bar" with `npx shadcn@latest add @haze/ai-search-bar`. 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 AiSearchBar from "@/components/haze/blocks/ai-search-bar.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/blocks/ai-search-bar.md

### Customize with real content

Adapt the Haze ai-search-bar block for our product. Replace the demo values of these props with our real content: id, placeholder, hits, class. Keep the layout, the heading level rules and these accessibility details: Numbered citations inside the AI answer move focus directly to the matching search hit below. Citations can reveal a result excluded by the current filter without clearing the search. Live match counts and revealed citations are announced in a polite role="status" line. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using ai-search-bar, check it fits: use it when prototyping a search experience with an example of how an ai summary can cite matching results; replacing a plain search modal with a unified docs, customers and issues search card. Avoid it when you only need a simple navigation command palette without ai synthesis; use command-menu. Alternatives: @haze/command-menu, @haze/ai-answer.

## Example requests that should lead here
- Build a workspace search bar with instant filtering and a sample answer that links to cited results

## Source

```astro
---
import { FileText, Search, Sparkles, Tag, Users } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface SearchHit {
  id: number;
  group: "Docs" | "Customers" | "Issues";
  title: string;
  meta: string;
  href?: string;
}

interface Props {
  id?: string;
  placeholder?: string;
  hits?: SearchHit[];
  class?: string;
}

const demoHits: SearchHit[] = [
  { id: 1, group: "Docs", title: "Webhook signature verification", meta: "Security · Updated 2d ago" },
  { id: 2, group: "Docs", title: "Retrying failed delivery attempts", meta: "API reference · 4 min read" },
  { id: 3, group: "Customers", title: "Tidewell Logistics", meta: "Enterprise · 120 seats · EU-West" },
  { id: 4, group: "Issues", title: "ENG-482: Webhook timeout on burst imports", meta: "In progress · Assigned to Marco" },
];

const {
  id = "haze-ai-search-bar",
  placeholder = "Search",
  hits = demoHits,
  class: className,
} = Astro.props;
const showExample = hits === demoHits;
---

<section aria-labelledby={`${id}-title`} data-haze-ai-search class={cn("bg-background px-4 py-10 sm:px-6 sm:py-14", className)}>
  <div class="mx-auto max-w-2xl overflow-hidden rounded-2xl border border-border bg-card shadow-float">
    <h2 id={`${id}-title`} class="sr-only">Hybrid workspace search</h2>

    <div class="flex flex-wrap items-center gap-2.5 border-b border-border px-4 py-3">
      <div class="flex w-40 min-w-0 flex-auto items-center gap-2.5">
        <Search class="size-4 shrink-0 text-muted-foreground" aria-hidden="true" />
        <label for={`${id}-q`} class="sr-only">Search workspace</label>
        <input
          id={`${id}-q`}
          data-asb-input
          type="search"
          placeholder={placeholder}
          class="-mx-px border border-frame-input h-8 min-w-0 flex-1 rounded-sm bg-transparent px-1 text-sm text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden"
        />
      </div>
      {showExample && <button type="button" hidden data-asb-ask aria-expanded="true" aria-controls={`${id}-answer`} class="inline-flex h-8 shrink-0 cursor-pointer items-center gap-1.5 rounded-lg border border-frame bg-muted px-2.5 text-xs font-medium text-foreground hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring transition-[background-color,border-color,color,opacity,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-75">
        <Sparkles class="size-3.5" aria-hidden="true" />
        <span>Sample answer</span>
      </button>}
    </div>

    {showExample && <div id={`${id}-answer`} data-asb-answer class="border-b border-border bg-muted/40 px-4 py-3.5">
      <p class="inline-flex items-center gap-1.5 text-xs font-medium text-foreground">
        <Sparkles class="size-3.5" aria-hidden="true" />
        Sample AI answer
      </p>
      <p class="mt-1.5 text-sm/6 text-pretty text-foreground">
        Webhooks verify HMAC-SHA256 signatures before retrying up to 5 times with exponential backoff
        <a href={`#${id}-hit-1`} data-asb-cite="1" aria-label="1, jump to result 1" class="mx-1 inline-flex size-6 cursor-pointer items-center justify-center rounded-sm border border-frame bg-muted font-mono text-[0.6875rem] font-semibold text-foreground focus-visible:outline-2 focus-visible:outline-ring">1</a>
        <a href={`#${id}-hit-2`} data-asb-cite="2" aria-label="2, jump to result 2" class="mr-1 inline-flex size-6 cursor-pointer items-center justify-center rounded-sm border border-frame bg-muted font-mono text-[0.6875rem] font-semibold text-foreground focus-visible:outline-2 focus-visible:outline-ring">2</a>.
        Active burst-import timeouts are tracked under ENG-482
        <a href={`#${id}-hit-4`} data-asb-cite="4" aria-label="4, jump to result 4" class="mx-1 inline-flex size-6 cursor-pointer items-center justify-center rounded-sm border border-frame bg-muted font-mono text-[0.6875rem] font-semibold text-foreground focus-visible:outline-2 focus-visible:outline-ring">4</a>.
      </p>
    </div>}

    <div class="p-3">
      <ul role="list" class="grid gap-1">
        {
          hits.map((hit) => {
            const Result = hit.href ? "a" : "div";
            return (
              <li
                id={`${id}-hit-${hit.id}`}
                tabindex="-1"
                data-asb-hit={String(hit.id)}
                data-search={`${hit.group} ${hit.title} ${hit.meta}`.toLowerCase()}
                class="rounded-xl border border-transparent focus-visible:outline-2 focus-visible:outline-ring target:border-foreground target:bg-accent"
              >
                <Result
                  href={hit.href}
                  class={cn("flex items-center justify-between gap-3 rounded-xl px-3 py-2", hit.href && "transition-colors duration-150 hover:bg-accent focus-visible:outline-2 focus-visible:outline-ring")}
                >
                  <span class="flex min-w-0 items-center gap-2.5">
                    <span class="hidden size-7 shrink-0 place-items-center rounded-lg border border-frame bg-muted/40 text-muted-foreground sm:grid" aria-hidden="true">
                      {hit.group === "Docs" ? <FileText class="size-3.5" /> : hit.group === "Customers" ? <Users class="size-3.5" /> : <Tag class="size-3.5" />}
                    </span>
                    <span class="min-w-0">
                      <span class="block wrap-anywhere text-sm/5 font-medium text-foreground sm:truncate">{hit.title}</span>
                      <span class="block wrap-anywhere text-xs/4 text-muted-foreground sm:truncate">{hit.meta}</span>
                    </span>
                  </span>
                  <span class="flex shrink-0 items-center gap-1.5">
                    <span class="font-mono text-[0.6875rem] text-foreground">[{hit.id}]</span>
                    <span class="rounded-md border border-border bg-muted/40 px-1.5 py-0.5 text-[0.6875rem] text-muted-foreground">{hit.group}</span>
                  </span>
                </Result>
              </li>
            );
          })
        }
      </ul>
      <p data-asb-status role="status" class="mt-2 px-2 text-xs/4 text-muted-foreground">
        {hits.length ? `Showing ${hits.length} workspace ${hits.length === 1 ? "match" : "matches"}` : "No workspace matches"}
      </p>
    </div>
  </div>
</section>

<script>
  function initAiSearchBars() {
    document.querySelectorAll<HTMLElement>("[data-haze-ai-search]").forEach((root) => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");
      const input = root.querySelector<HTMLInputElement>("[data-asb-input]");
      const answer = root.querySelector<HTMLElement>("[data-asb-answer]");
      const ask = root.querySelector<HTMLButtonElement>("[data-asb-ask]");
      const status = root.querySelector<HTMLElement>("[data-asb-status]");
      const results = Array.from(root.querySelectorAll<HTMLElement>("[data-asb-hit]"));
      let revealed: HTMLElement | undefined;

      input?.addEventListener("input", () => {
        const q = input.value.trim().toLowerCase();
        revealed = undefined;
        const shown = results.filter((result) => {
          result.hidden = !(result.dataset.search ?? "").includes(q);
          return !result.hidden;
        }).length;
        if (status) status.textContent = shown ? `Showing ${shown} workspace ${shown === 1 ? "match" : "matches"}` : "No workspace matches";
      });

      if (ask && answer) {
        ask.hidden = false;
        ask.addEventListener("click", () => {
          answer.hidden = !answer.hidden;
          ask.setAttribute("aria-expanded", String(!answer.hidden));
        });
      }

      root.querySelectorAll<HTMLAnchorElement>("[data-asb-cite]").forEach((link) => {
        link.addEventListener("click", (event) => {
          if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
          const result = results.find((row) => row.dataset.asbHit === link.dataset.asbCite);
          if (!result) return;
          if (revealed && revealed !== result) revealed.hidden = true;
          revealed = result.hidden || revealed === result ? result : undefined;
          result.hidden = false;
          result.focus({ preventScroll: true });
          if (status) status.textContent = revealed
            ? `Showing cited result [${link.dataset.asbCite}] outside the filter.`
            : `Focused cited result [${link.dataset.asbCite}].`;
        });
      });
    });
  }
  initAiSearchBars();
  document.addEventListener("astro:page-load", initAiSearchBars);
</script>
```
