BizzPocket

Predictive search (typeahead)

usePredictiveSearch from @bizzpocket/theme/client gives an island a correct combobox: products and categories for the text typed so far. It needs no extra endpoint: it calls the public browser queries productSearch and categoryTree (the category tree is fetched once; categories match the term without regard to case or accents). There are no query suggestions: the platform stores no searches.

tsx
'use client';
import { usePredictiveSearch } from '@bizzpocket/theme/client';

export function SearchBox() {
  const ps = usePredictiveSearch({ minChars: 2, debounceMs: 150 });
  return (
    <form action="/search">
      <input name="q" type="search" {...ps.inputProps} />
      <ul {...ps.listboxProps}>
        {ps.items.map((item, i) => (
          <li key={item.id} {...ps.getOptionProps(i)}>
            {item.title}
          </li>
        ))}
      </ul>
      <p role="status" aria-live="polite" className="sr-only">{ps.liveMessage}</p>
    </form>
  );
}
  • The option is the interactive element, once: getOptionProps gives it role="option" and a click handler that navigates (or calls onSelect). Do not put an <a> inside it: a link is not valid inside role="option", and a click would navigate twice. Show the product image, price or category label as plain content of the <li>.
  • The three prop groups are typed with React's own handler types, so they spread onto an <input>, the listbox element and each option element with no cast and no as unknown as. If tsc reports a clash, the prop is on the wrong element (getOptionProps(i) goes on the option, listboxProps on the list).
  • Pass inputProps as a whole: it includes onCompositionStart and onCompositionEnd. While an IME (Japanese, Chinese, Korean) is composing, the typed text is shown but not searched, and Enter commits the candidate instead of opening an option.
  • If the category tree fails to load, results for that term show products only and are not cached, so the next keystroke tries again.
  • status is idle | loading | ready | empty | error. An error clears on the next keystroke.
  • Keys: Up and Down move (and open the list); Home and End move only while the list is open, otherwise they move the text caret; Enter opens the active option (no active option: the form submits); Escape closes, then clears.
  • Options: debounceMs (150), minChars (2), productLimit (5), categoryLimit (3), cacheSize (30), messages (English defaults, translate them), onSelect.
  • The term is trimmed and cut to 200 characters. A newer keystroke aborts the older request; a late answer is dropped.