HextaUI

ライブの候補、カテゴリ、商品の結果を備えたストアフロントの検索フィールド。入力ミス、遅いまたは失敗する検索、最近の検索、キーボードだけでの操作に対応します。

カテゴリ
EC
使用コンポーネント
5
ファイル
6
使用例
3
利用
HextaUI Pro(55 ブロック)
ソース更新日
Open in new tab

HextaUI Pro に含まれます, 全 55 ブロック, $79 買い切り, プランを比較

Product Search は、ストアのヘッダーにある検索フィールドです。デスクトップではフィールドの下にドロップダウンを開き、スマートフォンではキーボードを表示した状態で全画面のシートを開きます。何も入力されていないときは、最近の検索、トレンドの検索、人気の商品の行を表示します。

買い物客が入力すると、予測部分を太字にした最大 8 件の検索候補、「linen in Bedding」のような一致するカテゴリ、サムネイルと価格付きのいくつかの商品、そして最後に「Search for」の行を表示します。矢印キーで候補に移動するとその候補がフィールドにコピーされて編集でき、Escape で入力した内容に戻り、Tab で候補を補完します。

onSearch(query, { signal }) は短いデバウンスの後に呼ばれます。古いリクエストは中断され、結果はキャッシュされるためバックスペースは即座に反映され、次の結果が読み込まれる間も前の結果は画面に残ります。スピナーは検索が 150ms より長くかかったときだけ表示されます。失敗した検索は Try again の行付きでエラーメッセージを表示し、結果がない検索では「Did you mean」と人気のカテゴリを提示します。

最近の検索は recentStorageKey のキーで localStorage に保存されるか、recent と onRecentChange で制御されます。SearchResultsHeader は、結果ページ用の対応する見出しで、「Results for “vase” (4)」と Did you mean の行を表示します。search.ts にあるあいまい検索のヘルパー fuzzySearch、completeQuery、correctQuery はデモを動かしており、小規模なカタログではそれだけで機能します。

  1. HextaUI Pro を入手する

    一度の支払いで、今後追加されるものも含めてすべてのブロックが使えます。料金を見る。

  2. Proレジストリをcomponents.jsonに追加する

    components.json
    {
      "registries": {
        "@hextaui-pro": {
          "url": "https://hextaui.com/r/pro/{name}.json",
          "headers": {
            "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
          }
        }
      }
    }
  3. トークンを追加する

    アカウントページでトークンを作成し、.env.local に HEXTAUI_PRO_TOKEN として設定してください。

  4. ブロックを追加する

    pnpm dlx shadcn@latest add @hextaui-pro/product-search

ProductSearch が渡す signal を使って Storefront API の predictiveSearch を呼び出し、queries、collections、products を SearchResults に変換します。価格はすでに Money なので、そのまま渡せます。

"use client"

import { ProductSearch } from "@/components/blocks/product-search/product-search"
import type { SearchFn } from "@/components/blocks/product-search/search"

const endpoint = "https://your-shop.myshopify.com/api/2025-07/graphql.json"

const query = `query Predictive($q: String!) {
  predictiveSearch(query: $q, limit: 6, types: [QUERY, COLLECTION, PRODUCT]) {
    queries { text }
    collections { id title handle }
    products {
      id title handle
      featuredImage { url altText }
      priceRange { minVariantPrice { amount currencyCode } }
      compareAtPriceRange { minVariantPrice { amount currencyCode } }
    }
  }
}`

type Money = { amount: string; currencyCode: string }

type PredictiveSearch = {
  queries: { text: string }[]
  collections: { id: string; title: string; handle: string }[]
  products: {
    id: string
    title: string
    handle: string
    featuredImage: { url: string; altText: string | null } | null
    priceRange: { minVariantPrice: Money }
    compareAtPriceRange: { minVariantPrice: Money }
  }[]
}

const search: SearchFn = async (q, { signal }) => {
  const response = await fetch(endpoint, {
    method: "POST",
    signal,
    headers: {
      "Content-Type": "application/json",
      "X-Shopify-Storefront-Access-Token": process.env.NEXT_PUBLIC_SHOPIFY_TOKEN ?? "",
    },
    body: JSON.stringify({ query, variables: { q } }),
  })
  if (!response.ok) throw new Error("Search is unavailable right now. Try again in a moment.")
  const { data } = (await response.json()) as {
    data: { predictiveSearch: PredictiveSearch }
  }
  const result = data.predictiveSearch
  return {
    suggestions: result.queries.map((item) => item.text),
    collections: result.collections.map((item) => ({
      id: item.id,
      title: item.title,
      href: `/collections/${item.handle}`,
    })),
    products: result.products.map((item) => ({
      id: item.id,
      title: item.title,
      href: `/products/${item.handle}`,
      image: item.featuredImage
        ? { src: `${item.featuredImage.url}&width=160`, alt: item.featuredImage.altText ?? "" }
        : undefined,
      price: item.priceRange.minVariantPrice,
      compareAt: item.compareAtPriceRange.minVariantPrice,
    })),
  }
}

export function StoreSearch() {
  return (
    <ProductSearch
      onSearch={search}
      onSubmit={(q) => window.location.assign(`/search?q=${encodeURIComponent(q)}`)}
      recentStorageKey="store:recent-searches"
      trending={["linen bedding", "ring vase"]}
    />
  )
}

Algolia

1 回のマルチクエリのリクエストで、検索候補と商品をまとめて取得します。Algolia の入力ミスの許容とファセットの件数が、候補、「in Bedding」の行、結果の件数を埋めます。

"use client"

import { money } from "../price/money"
import { ProductSearch } from "@/components/blocks/product-search/product-search"
import type { SearchFn } from "@/components/blocks/product-search/search"

const appId = "YOUR_APP_ID"
const searchKey = "YOUR_SEARCH_ONLY_KEY"

type ProductHit = {
  objectID: string
  title: string
  handle: string
  image: string
  price: number
  collection: string
}

type SuggestionHit = { query: string }

type Response = {
  results: [
    { hits: SuggestionHit[] },
    { hits: ProductHit[]; nbHits: number; facets?: { collection?: Record<string, number> } },
  ]
}

const search: SearchFn = async (query, { signal }) => {
  const response = await fetch(`https://${appId}-dsn.algolia.net/1/indexes/*/queries`, {
    method: "POST",
    signal,
    headers: {
      "X-Algolia-Application-Id": appId,
      "X-Algolia-API-Key": searchKey,
    },
    body: JSON.stringify({
      requests: [
        { indexName: "products_query_suggestions", query, hitsPerPage: 8 },
        { indexName: "products", query, hitsPerPage: 4, facets: ["collection"], typoTolerance: true },
      ],
    }),
  })
  if (!response.ok) throw new Error("Search is unavailable right now. Try again in a moment.")
  const { results } = (await response.json()) as Response
  const [suggestions, products] = results
  return {
    suggestions: suggestions.hits.map((hit) => hit.query),
    collections: Object.entries(products.facets?.collection ?? {})
      .slice(0, 2)
      .map(([title, count]) => ({ id: title, title, count })),
    products: products.hits.map((hit) => ({
      id: hit.objectID,
      title: hit.title,
      href: `/products/${hit.handle}`,
      image: { src: hit.image },
      price: money(hit.price, "USD"),
    })),
    total: products.nbHits,
  }
}

export function AlgoliaSearch() {
  return <ProductSearch onSearch={search} recentStorageKey="recent-searches" />
}

Next.js の検索ページ

router を使って Enter を /search?q= に送り、URL からフィールドに初期値を入れて、結果ページに検索語が反映されるようにします。商品とカテゴリはそれぞれのルートを開きます。

"use client"

import { useRouter, useSearchParams } from "next/navigation"

import { ProductSearch } from "@/components/blocks/product-search/product-search"
import type { SearchFn } from "@/components/blocks/product-search/search"

const search: SearchFn = async (query, { signal }) => {
  const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal })
  if (!response.ok) throw new Error("Search is unavailable right now. Try again in a moment.")
  return response.json()
}

export function HeaderSearch() {
  const router = useRouter()
  const params = useSearchParams()

  return (
    <ProductSearch
      key={params.get("q") ?? ""}
      defaultValue={params.get("q") ?? ""}
      onSearch={search}
      onSubmit={(query) => router.push(`/search?q=${encodeURIComponent(query)}`)}
      onSelectProduct={(product) => product.href && router.push(product.href)}
      onSelectCollection={(collection, query) =>
        router.push(`${collection.href}?q=${encodeURIComponent(query)}`)
      }
      recentStorageKey="recent-searches"
    />
  )
}

構造

外側から内側へ組み合わせるパーツ。

パーツ説明
ProductSearchフィールド、⌘K のヒント、そしてドロップダウンまたは全画面のシート。
SearchResultsHeader件数とスペルの提案を含む、結果ページの見出し。
fuzzySearch, completeQuery, correctQuery小規模なカタログ向けの、入力ミスを許容する一致、検索語の補完、スペルの修正。
splitCompletion, addRecent, removeRecent候補を入力済みの部分と予測部分に分け、最近の検索の一覧を編集します。

ProductSearch

divのプロップも受け付けます。

プロパティ型デフォルト
onSearch結果を取得します。signal が発火したら中断します。投げられたエラーのメッセージはドロップダウンに表示されます。
(query, { signal }) => Promise<SearchResults>–
onSubmit買い物客がテキストで検索したとき、または候補、最近の検索、トレンドの検索を選んだときに呼ばれます。
(query: string) => void–
onSelectProduct商品が選ばれたときに呼ばれます。ない場合は、商品の href が開きます。
(product, query) => void–
onSelectCollectionカテゴリが選ばれたときに呼ばれます。ない場合は、カテゴリの href が開きます。
(collection, query) => void–
value制御する場合の検索語。
string–
defaultValue初期の検索語。
string""
onValueChange買い物客の入力に合わせて呼ばれます。
(query: string) => void–
open制御する場合の、ドロップダウンまたはシートが開いているかどうか。
boolean–
onOpenChange開閉したときに呼ばれます。
(open: boolean) => void–
recentStorageKey最近の検索を、このキーで localStorage に保存します。
string–
recent制御する場合の最近の検索。
string[]–
defaultRecent何も保存されていないときに表示する最近の検索。
string[][]
onRecentChange検索が追加、削除、またはクリアされたときに呼ばれます。
(recent: string[]) => void–
maxRecent保持する最近の検索の数。
number5
trending空の状態に表示するトレンドの検索。
string[][]
popularProducts空の状態に表示する商品。4 件、スマートフォンでは 3 件を表示します。
SearchProduct[][]
popularCollections何も一致しないときに提示するカテゴリ。
SearchCollection[][]
maxSuggestions表示する検索候補。
number8, or 5 on a phone
maxProducts表示する商品の結果。
number4, or 3 on a phone
debounce入力後、検索するまで待つミリ秒数。
number120
shortcut⌘K、Ctrl+K、/ で開きます。
booleantrue
alignドロップダウンをフィールドに揃えます。
"start" | "center" | "end""start"
locale価格と件数のロケール。
Intl.LocalesArgument"en-US"
labels見出し、行、ヒント、アナウンスの文言。
Partial<ProductSearchLabels>–
プロパティ型デフォルト
suggestions検索語の補完候補。最適なものから順に並べます。結果がある検索語だけを提案します。
string[]–
collections一致するカテゴリ。「query in Bedding」のように表示されます。
{ id; title; href?; count? }[]–
products商品の結果。price は Money または { min, max } です。
{ id; title; href?; image?; price?; compareAt?; subtitle? }[]–
totalライブのアナウンスに使う結果の総件数。デフォルトは products.length です。
number–
correction入力ミスに一致させたときの修正後の検索語。「Showing results for」として表示され、何も一致しなかった場合は「Did you mean」として表示されます。
string–

SearchResultsHeader

divのプロップも受け付けます。

プロパティ型デフォルト
query見出しに表示される検索語。
string–
count結果の件数。null の間は非表示です。
number | null–
suggestion「Did you mean」として表示されるスペルの提案。
string | null–
correctedFrom結果が修正後の検索語に対するものであるときの、元の検索語。「Search instead for」として表示されます。
string | null–
onSuggestionSelectいずれかのリンクがクリックされたときに呼ばれます。
(query: string) => void–
headingLevel見出しのレベル。
1 | 2 | 31
キーアクション
Meta+KControl+Kフィールドにフォーカスし、検索を開きます。
/ほかのフィールドで入力中でなければ、検索を開きます。
ArrowDownArrowUpすべての行を移動します。移動するにつれて候補がフィールドにコピーされます。
Enterハイライトされた行を開くか、入力した内容で検索します。
Tabハイライトされた候補または最上位の候補を補完し、入力を続けます。
Shift+Deleteハイライトされた最近の検索を削除します。
Escape入力した内容に戻し、次に閉じ、次にフィールドをクリアします。
  • フィールドは、グループ化された選択肢の listbox を持つ combobox です。aria-activedescendant がハイライトされた行に追従するため、フォーカスがフィールドから離れることはありません。
  • 「6 results」のような結果の件数は、キー入力ごとではなく、各検索が落ち着いた時点で一度だけ読み上げられます。失敗した検索は alert として読み上げられます。
  • スマートフォンのシートを閉じると、フォーカスは検索ボタンに戻ります。iOS でズームされないよう、タッチスクリーンではフィールドに 16px のテキストを使います。
  • 強制カラーモードでは、ハイライトされた行にアウトラインが付きます。視差効果を減らす設定では、スピナー、フェード、矢印の小さな動きが抑えられるか取り除かれます。

使用技術

Product Search を構成する無料のHextaUIコンポーネントです。それぞれ単独でインストールできます。

コード

6 個のファイルを components/blocks/product-search に追加しました。