BizzPocket

Search with suggestions

A search box that suggests products while the shopper types, with useQuery('productSearch'), full keyboard support, and a plain form underneath.

On this page

Goal: a search box that shows matching products, with picture and price, after the shopper has typed two letters, works with the arrow keys, and is a plain GET /search?q= form before its JavaScript arrives.

Data none: the block has no data(). Suggestions come from the browser.
JavaScript one island, about 2.1 KB gzip
Uses useQuery('productSearch'), f.link(), ctx.blockId

The block has three files.

The island

Create blocks/search-suggest/suggest-box.tsx:

blocks/search-suggest/suggest-box.tsx
'use client';
import { useEffect, useState, type KeyboardEvent } from 'react';
import { useQuery } from '@bizzpocket/theme/client';

type Hit = { id: string; handle: string; title: string; price: { amount: number; currency: string }; image?: { src: string; alt: string } | null };
type Result = { hits: Hit[]; total: number };

const MIN = 2; // letters before suggesting
const WAIT_MS = 200; // pause in typing before asking

function money(amount: number, currency: string): string {
  try {
    return new Intl.NumberFormat('en-IN', { style: 'currency', currency }).format(amount);
  } catch {
    return `${currency} ${amount}`;
  }
}

/** An `https:` or site-relative picture only (store data is not checked for you in an island). */
const isImage = (src: string) => src.startsWith('https://') || (src.startsWith('/') && !src.startsWith('//'));

/** The title with the typed text marked. */
function Marked({ text, term }: { text: string; term: string }) {
  const at = text.toLowerCase().indexOf(term.toLowerCase());
  if (term === '' || at < 0) return <>{text}</>;
  return (
    <>
      {text.slice(0, at)}
      <mark>{text.slice(at, at + term.length)}</mark>
      {text.slice(at + term.length)}
    </>
  );
}

export interface SuggestBoxProps {
  /** Unique on the page (the block passes its own id): the list and options are named after it. */
  id: string;
  action: string;
  placeholder: string;
  limit: number;
}

export function SuggestBox({ id, action, placeholder, limit }: SuggestBoxProps) {
  const [q, setQ] = useState('');
  const [term, setTerm] = useState(''); // `q` once the shopper pauses
  const [open, setOpen] = useState(false);
  const [active, setActive] = useState(-1);

  useEffect(() => {
    const t = setTimeout(() => setTerm(q.trim()), WAIT_MS);
    return () => clearTimeout(t);
  }, [q]);

  const enabled = term.length >= MIN;
  const { data, loading } = useQuery<Result>('productSearch', { q: term, limit }, { enabled });
  const hits = enabled ? (data?.hits ?? []) : [];
  const all = `${action}?q=${encodeURIComponent(q.trim())}`;
  // The options: each product, then "all results".
  const options = [...hits.map((h) => `/products/${encodeURIComponent(h.handle)}`), all];
  const shown = open && q.trim().length >= MIN;

  useEffect(() => setActive(-1), [term]);

  const onKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
    if (!shown) return;
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      e.preventDefault();
      // -1 is the input itself; past either end, the choice wraps through it.
      const last = options.length - 1;
      setActive((i) => (e.key === 'ArrowDown' ? (i >= last ? -1 : i + 1) : i <= -1 ? last : i - 1));
    } else if (e.key === 'Escape') {
      setOpen(false);
    } else if (e.key === 'Enter' && active >= 0 && active < options.length) {
      e.preventDefault();
      window.location.assign(options[active]!);
    }
  };

  return (
    <form
      className="ss"
      action={action}
      method="get"
      role="search"
      onBlur={(e) => {
        if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setOpen(false);
      }}
    >
      <input
        className="ss-input"
        type="search"
        name="q"
        value={q}
        placeholder={placeholder}
        aria-label={placeholder}
        autoComplete="off"
        role="combobox"
        aria-autocomplete="list"
        aria-expanded={shown}
        aria-controls={`${id}-list`}
        aria-activedescendant={shown && active >= 0 ? `${id}-${active}` : undefined}
        onChange={(e) => {
          setQ(e.target.value);
          setOpen(true);
        }}
        onFocus={() => setOpen(true)}
        onKeyDown={onKeyDown}
      />
      {/* mousedown keeps the focus in the input, so the list is still there when the click lands. */}
      <ul
        id={`${id}-list`}
        className="ss-list"
        role="listbox"
        aria-label="Suggestions"
        hidden={!shown}
        onMouseDown={(e) => e.preventDefault()}
      >
        {hits.map((h, i) => (
          <li key={h.id} id={`${id}-${i}`} role="option" aria-selected={i === active} className="ss-option">
            <a href={options[i]} tabIndex={-1}>
              {h.image && isImage(h.image.src) ? <img src={h.image.src} alt="" width={40} height={40} /> : <span className="ss-noimg" />}
              <span className="ss-name">
                <Marked text={h.title} term={term} />
              </span>
              <span className="ss-price">{money(h.price.amount, h.price.currency)}</span>
            </a>
          </li>
        ))}
        <li id={`${id}-${hits.length}`} role="option" aria-selected={active === hits.length} className="ss-option ss-all">
          <a href={all} tabIndex={-1}>
            {loading
              ? 'Searching...'
              : enabled && hits.length === 0
                ? `No suggestions. Search for "${q.trim()}"`
                : `See all results for "${q.trim()}"`}
          </a>
        </li>
      </ul>
    </form>
  );
}

The block

Create blocks/search-suggest/search-suggest.tsx:

blocks/search-suggest/search-suggest.tsx
import { block, f } from '@bizzpocket/theme';
import { SuggestBox } from './suggest-box';
import './search-suggest.css';

export default block({
  name: 'Search with suggestions',
  category: 'utility',
  // Shoppers reach for search first: make it work as soon as the page loads.
  hydrate: 'load',
  fields: {
    placeholder: f.text({ default: 'Search products' }),
    limit: f.number({ default: 6, min: 3, max: 10, integer: true, label: 'Suggestions shown' }),
    action: f.link({ default: '/search', label: 'Search results page' }),
  },
  render: ({ placeholder, limit, action }, ctx) => (
    <div className="ss-wrap">
      <SuggestBox id={`ss-${ctx.blockId}`} action={action ?? '/search'} placeholder={placeholder} limit={limit} />
    </div>
  ),
});

The CSS

Create blocks/search-suggest/search-suggest.css:

blocks/search-suggest/search-suggest.css
.ss-wrap { padding: 1rem; max-width: 36rem; margin: 0 auto; }
.ss { position: relative; }
.ss-input { width: 100%; padding: 0.7rem 1rem; border: 1px solid #ccc; border-radius: 999px; font: inherit; }
.ss-list {
  position: absolute; z-index: 40; left: 0; right: 0; top: calc(100% + 0.25rem);
  margin: 0; padding: 0.25rem; list-style: none;
  background: #fff; border: 1px solid #e5e5e5; border-radius: 0.75rem; box-shadow: 0 12px 24px rgb(0 0 0 / 0.1);
}
.ss-option a { display: flex; align-items: center; gap: 0.75rem; padding: 0.5rem; border-radius: 0.5rem; color: inherit; text-decoration: none; }
.ss-option img, .ss-noimg { width: 2.5rem; height: 2.5rem; flex: none; object-fit: cover; border-radius: 0.375rem; background: #f3f3f3; }
.ss-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ss-name mark { background: none; font-weight: 700; color: inherit; }
.ss-price { font-size: 0.875rem; opacity: 0.75; }
/* The keyboard's current choice (aria-selected) and the pointer's look the same. */
.ss-option[aria-selected='true'] a, .ss-option a:hover { background: #f3f3f3; }
.ss-all a { justify-content: center; font-weight: 600; }

Add it to a page with bunx bizzpocket add-to-layout search-suggest, or put SuggestBox in your header in place of the sir.search form of the header recipe. In bizzpocket dev --mock, a search returns the sample products whose title has every word typed: try "train" (3 products) or "wooden".

How it works

  • The server renders a real form. <form action="/search" method="get"> with an input named q. Before the island wakes, or without JavaScript, Enter opens the search page as usual. The island adds the suggestions on top.
  • Typing waits for a pause. term follows q 200 ms after the last keystroke, so fast typing makes one request, not one per letter. enabled: term.length >= 2 keeps useQuery idle for one letter.
  • useQuery('productSearch', { q, limit }) calls GET /_bp/q/productSearch?v=.... The answer is { hits, total, facets }; each hit is a Product (id, handle, title, price, image...). A new term cancels the request still running. Every answer is kept for the visit, so backspacing to an earlier word shows its suggestions at once.
  • Keyboard, the combobox way. The input is role="combobox" and controls a role="listbox". The arrow keys move aria-activedescendant through the options and back to the input, Enter opens the active option (or submits the form when none is active), and Escape closes the list. Focus never leaves the input, so the shopper can keep typing.
  • The ids come from the block. ctx.blockId makes the list and option ids unique on the page. Each island renders as its own React root, so useId() would give two search boxes on one page the same ids.
  • Store data is checked. An island cannot use the server's checks, so picture URLs are accepted only when they are https: or site paths. Product links are built from the handle, never taken from the data.

JS cost

block           server B  client gz  css gz  data
--------------  --------  ---------  ------  ----
search-suggest       721       2143     491  none

About 2.1 KB gzip for the island, useQuery included. hydrate: 'load' wakes it with the page; in a footer or further down, the default 'visible' would cost nothing until the shopper scrolls there. On the Bun host, the first island on a page also loads the shared React runtime, once for every island on the page.