HextaUI

HextaUIのコマースブロックで作られた完全なストア。1つの共有ストア上で、閲覧、フィルター、バッグ、チェックアウト、注文の追跡に対応します。

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

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

Storefrontは、すべてのコマースブロックで使われているホームグッズブランド Halden のためのオンラインショップ全体を、他のブロックを組み合わせて構成したものです。ヘッダーの検索は Product Search、バッグは Cart、すべてのグリッドとレールは Product Card、コレクションページは Product Filters、商品ページは Product Gallery、Variant Picker、Price、Reviews、Shipping Methods の Delivery Estimate、チェックアウトは Checkout、最後の 2 ページは Order Confirmation と Order Tracking です。Storefront が加えるのはつなぎの部分だけです。ヘッダーとフッター、ルーティング、1 つの共有ストア、小さなページレイアウトです。

ページは 9 つあります。ヒーロー、部屋別のタイル、New arrivals のレール、エディトリアルの帯を持つ Home。広い画面ではサイドバー、スマートフォンではシートにフィルターを置き、並べ替えと表示密度のツールバー、削除可能なチップ、Load more を持つコレクションページ。商品ページ。検索結果。ウィッシュリスト。注文履歴。最小限の専用ヘッダーを持つ全画面のチェックアウト。注文確認。注文追跡です。デモカタログには、Living、Bedding、Kitchen、Lighting にわたる 37 点があり、セール、在庫僅少、予約注文、売り切れの商品を含みます。

すべてが 1 つのストアから読み取るため、状態は買い物客についてきます。カードの Quick add、商品ページの Add to bag、バッグのドロワーはすべて同じカートを変更し、ヘッダーのバッグの件数はどのページでも切り替わるアニメーションで更新されます。カードと商品ページのハートは同じウィッシュリストに追加され、開いた商品は Recently viewed に加わり、確定した注文は追跡情報とともに Your orders に表示されます。バッグには、$150 以上の送料無料まであといくらかが表示されます。

ルーティングはブロック内にあります。ページは #/collections/living?color=Oat&sort=newest のようなハッシュ URL なので、戻る・進むが機能し、リンクは新しいタブで開け、フィルター、並べ替え、Load more のページ、選択したバリアントはリロード後も残ります。戻ると、スクロールしていた位置に戻ります。スクロールするのはページだけです。ヘッダーは固定されたまま、フレームはコンテナいっぱいに広がり、ページは 150 ms でクロスフェードします。視差効果を減らす設定ではフェードしません。

  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/storefront

Next.js App Router のルート

ストアはデフォルトで URL のハッシュでルーティングします。usePathname、useSearchParams、useRouter から作ったルーターを渡すと、各ページに /shop 配下の本物の URL が付き、フィルター、並べ替え、選択したバリアントがクエリ文字列に入ります。

"use client"

import * as React from "react"
import { usePathname, useRouter, useSearchParams } from "next/navigation"

import type { ShopCatalog } from "@/components/blocks/storefront/catalog"
import { routeFromPath, routeToPath, type StorefrontRouter } from "@/components/blocks/storefront/routes"
import { Storefront } from "@/components/blocks/storefront/storefront"
import { createStorefrontStore } from "@/components/blocks/storefront/store"

const base = "/shop"

function useShopRouter(): StorefrontRouter {
  const router = useRouter()
  const pathname = usePathname()
  const params = useSearchParams()
  const search = params.toString()
  const route = React.useMemo(
    () => routeFromPath(`${pathname.slice(base.length)}${search ? `?${search}` : ""}`),
    [pathname, search]
  )

  return React.useMemo(
    () => ({
      route,
      href: (next) => `${base}${routeToPath(next)}`.replace(/\/(\?|$)/, "$1"),
      navigate: (next, options) => {
        const href = `${base}${routeToPath(next)}`.replace(/\/(\?|$)/, "$1")
        if (options?.replace) router.replace(href, { scroll: false })
        else router.push(href, { scroll: false })
      },
    }),
    [route, router]
  )
}

export function Shop({ catalog }: { catalog: ShopCatalog }) {
  const router = useShopRouter()
  const [store] = React.useState(() => createStorefrontStore())
  return <Storefront className="h-svh" store={store} catalog={catalog} router={router} />
}

独自のカートとウィッシュリストの API

サーバーを呼び出す api 関数を渡してください。各関数は共有ストアが変わる前に実行され、サーバーにカートがあればそれを返し、投げられたエラーは買い物客が操作した場所に表示されます。

"use client"

import * as React from "react"

import type { Cart, CartLine } from "../cart/cart"
import type { ShopCatalog } from "@/components/blocks/storefront/catalog"
import { Storefront } from "@/components/blocks/storefront/storefront"
import { createStorefrontStore, type StorefrontApi } from "@/components/blocks/storefront/store"

async function post<T>(path: string, body: unknown): Promise<T> {
  const response = await fetch(path, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  })
  const json = (await response.json()) as T & { error?: string }
  if (!response.ok) throw new Error(json.error ?? "Something went wrong. Try again.")
  return json
}

const api: Partial<StorefrontApi> = {
  addToCart: (line: CartLine) => post<Cart>("/api/cart/lines", { variantId: line.merchandise.id, quantity: line.quantity }),
  updateLine: (lineId, quantity) => post<Cart>("/api/cart/update", { lineId, quantity }),
  removeLine: (lineId) => post<Cart>("/api/cart/remove", { lineId }),
  restoreLine: (line) => post<Cart>("/api/cart/lines", { variantId: line.merchandise.id, quantity: line.quantity }),
  setWishlisted: async (product, saved) => {
    await post("/api/wishlist", { productId: product.id, saved })
  },
  notifyMe: async (_product, variant, email) => {
    await post("/api/back-in-stock", { variantId: variant.id, email })
  },
  subscribe: async (email) => {
    await post("/api/newsletter", { email })
  },
}

export function Shop({ catalog, cart }: { catalog: ShopCatalog; cart: Cart }) {
  const [store] = React.useState(() => createStorefrontStore({ cart }))
  return <Storefront className="h-svh" store={store} catalog={catalog} api={api} />
}

Shopify Storefront API

addToCart、updateLine、removeLine を cartLinesAdd、cartLinesUpdate、cartLinesRemove に対応付け、返されたカートを一度変換し、userErrors をボタンや明細の下のメッセージにします。

"use client"

import * as React from "react"

import type { Cart } from "../cart/cart"
import { money } from "../price/money"
import type { ShopCatalog } from "@/components/blocks/storefront/catalog"
import { Storefront } from "@/components/blocks/storefront/storefront"
import { createStorefrontStore, type StorefrontApi } from "@/components/blocks/storefront/store"

type ShopifyCartLine = {
  id: string
  quantity: number
  cost: { amountPerQuantity: { amount: string; currencyCode: string } }
  merchandise: {
    id: string
    title: string
    product: { id: string; title: string; handle: string }
    image: { url: string; altText: string | null } | null
  }
}

type ShopifyCart = {
  id: string
  checkoutUrl: string
  lines: { nodes: ShopifyCartLine[] }
  cost: { subtotalAmount: { currencyCode: string } }
}

const cartFields = `id checkoutUrl cost { subtotalAmount { currencyCode } }
  lines(first: 100) { nodes { id quantity cost { amountPerQuantity { amount currencyCode } }
  merchandise { ... on ProductVariant { id title product { id title handle } image { url altText } } } } }`

async function storefront<T>(query: string, variables: Record<string, unknown>): Promise<T> {
  const response = await fetch("/api/shopify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ query, variables }),
  })
  const { data, errors } = (await response.json()) as { data: T; errors?: { message: string }[] }
  if (errors?.length) throw new Error(errors[0].message)
  return data
}

function toCart(cart: ShopifyCart): Cart {
  return {
    id: cart.id,
    currencyCode: cart.cost.subtotalAmount.currencyCode,
    lines: cart.lines.nodes.map((line) => ({
      id: line.id,
      quantity: line.quantity,
      price: money(line.cost.amountPerQuantity.amount, line.cost.amountPerQuantity.currencyCode),
      merchandise: {
        id: line.merchandise.id,
        productId: line.merchandise.product.id,
        productTitle: line.merchandise.product.title,
        variantTitle: line.merchandise.title === "Default Title" ? undefined : line.merchandise.title,
        image: line.merchandise.image
          ? { id: line.merchandise.image.url, src: line.merchandise.image.url, alt: line.merchandise.image.altText ?? "" }
          : undefined,
      },
    })),
  }
}

type Result = { cart: ShopifyCart; userErrors: { message: string }[] }

async function mutate(name: string, query: string, variables: Record<string, unknown>) {
  const data = await storefront<Record<string, Result>>(query, variables)
  const result = data[name]
  if (result.userErrors.length) throw new Error(result.userErrors[0].message)
  return toCart(result.cart)
}

const api: Partial<StorefrontApi> = {
  addToCart: (line, cart) =>
    mutate(
      "cartLinesAdd",
      `mutation($cartId: ID!, $lines: [CartLineInput!]!) { cartLinesAdd(cartId: $cartId, lines: $lines) { cart { ${cartFields} } userErrors { message } } }`,
      { cartId: cart.id, lines: [{ merchandiseId: line.merchandise.id, quantity: line.quantity }] }
    ),
  updateLine: (lineId, quantity, cart) =>
    mutate(
      "cartLinesUpdate",
      `mutation($cartId: ID!, $lines: [CartLineUpdateInput!]!) { cartLinesUpdate(cartId: $cartId, lines: $lines) { cart { ${cartFields} } userErrors { message } } }`,
      { cartId: cart.id, lines: [{ id: lineId, quantity }] }
    ),
  removeLine: (lineId, cart) =>
    mutate(
      "cartLinesRemove",
      `mutation($cartId: ID!, $lineIds: [ID!]!) { cartLinesRemove(cartId: $cartId, lineIds: $lineIds) { cart { ${cartFields} } userErrors { message } } }`,
      { cartId: cart.id, lineIds: [lineId] }
    ),
}

export function ShopifyStorefront({ catalog, cart }: { catalog: ShopCatalog; cart: ShopifyCart }) {
  const [store] = React.useState(() => createStorefrontStore({ cart: toCart(cart) }))
  return <Storefront className="h-svh" store={store} catalog={catalog} api={api} />
}

構造

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

パーツ説明
Storefrontアプリシェル。お知らせバー、ナビゲーション・検索・アカウント・ウィッシュリスト・バッグを持つヘッダー、ページ領域、ニュースレターの入力欄付きフッター、ルーティング。
createStorefrontStore, useStorefrontStoreカート、ウィッシュリスト、最近見た商品、確定済みの注文を保持する小さな外部ストア。useSyncExternalStore で読み取ります。
simulatedApiデフォルトの api。本物のサーバーのように待機し、カートの明細をまとめ、手持ちの在庫を超える数量を拒否し、Checkout のデモ用ヘルパーで注文を確定します。
useHashRouter, routeFromPath, routeToPath組み込みのハッシュルーターと、独自のアダプターを作るためのヘルパー。
ShopCatalog商品(variant-picker の Product に、collection、category、material、colors、description、reviews を加えたもの)と、ナビゲーションに表示するコレクション。
shopFacets, shopAccessors, sortProducts, runSearch件数付きのファセットを作り、一覧を並べ替え、入力ミスを許容してカタログを検索する純粋なヘルパー。

ストアフロント

ルート要素用に div のプロップも受け付けます。h-svh のように高さを指定すると、その高さいっぱいに広がります。

プロパティ型デフォルト
storecreateStorefrontStore({ cart, wishlist, recent, orders }) で作る共有の状態。
StorefrontStore–
catalog{ products, collections, colors?, currencyCode }。products は、すべてのグリッド、ファセット、検索結果、おすすめの元になります。
ShopCatalog–
nameヘッダー、フッター、チェックアウトに表示するワードマーク。
ReactNode"Halden"
navヘッダーのナビゲーションに並べるコレクションの id(表示順)。
string[]every collection
heroホームページのヒーロー。cta は、ルートを持つ { label, to } です。
{ image, eyebrow?, title, description?, cta? }–
editorialホームページの控えめな帯。
{ image, eyebrow?, title, description, cta? }–
announcementヘッダーの上にある細いバー。null にすると非表示にします。
ReactNode | nullfree shipping and returns line
apiサーバー呼び出し。addToCart、updateLine、removeLine、restoreLine、setWishlisted、notifyMe、estimateDelivery、subscribe、getRates、estimateTax、applyCode、removeCode、placeOrder、express です。指定しないものはシミュレートされます。サーバーのカートを使うならそれを返し、メッセージを表示するならエラーを投げてください。
Partial<StorefrontApi>simulatedApi()
router{ route, navigate, href }。組み込みのハッシュルーターを置き換えます。
StorefrontRouteruseHashRouter()
searchAlgolia や Shopify の predictive search など、ヘッダーの入力欄に使う独自の検索。
SearchFnsearches the catalog
trending検索欄が空のときに表示する人気の検索。
string[][]
customerチェックアウト用のサインイン中の買い物客。保存済みの住所とカードを含みます。
CheckoutCustomer | null–
onSignIn, onSignOutチェックアウトに Sign in と Sign out を表示します。
() => void–
checkoutCheckout に渡す expressMethods、paymentMethods、addressForm、payment、footer、defaultCountry、labels。
Pick<CheckoutProps, …>–
freeShippingThresholdバッグの送料無料バーと、商品ページの無料配送の表示を制御します。null にすると両方を非表示にします。
Money | null$150
pageSizeコレクションページで Load more を 1 回押すごとに読み込む商品数。
number12
locale金額、数値、日付に使うロケール。
string"en-US"

StorefrontRoute

ルーターが受け渡すもの。

プロパティ型デフォルト
pageページ。
"home" | "collection" | "product" | "search" | "wishlist" | "account" | "checkout" | "order" | "tracking"–
idコレクションの id、商品の handle、または注文の id。
string–
searchクエリパラメーター。コレクションではフィルターと並べ替え、検索では q、商品では glaze=Sand のようなオプションの値です。
string–

createStorefrontStore

setCart、clearCart、setWishlisted、viewProduct、clearRecent、addOrder を持つ StorefrontStore を返します。

プロパティ型デフォルト
cartサーバーまたは cookie から得る初期カート。
Cartan empty USD cart
wishlist保存された商品の id。
string[][]
recent最近見た商品の id(新しい順)。12 件まで保持します。
string[][]
ordersYour orders に表示する注文。
Order[][]
キーアクション
⌘Kどのページからでも検索を開きます。/ でも開けます。
Tabヘッダー、続いてページ内を移動します。ページが切り替わると、フォーカスは新しいページの先頭から始まります。
Enterリンクを開く、バッグに追加する、または入力したテキストで検索します。
←→バリアントピッカーで色やサイズを選び、ギャラリーの画像間を移動します。
Escバッグ、メニュー、フィルターシート、検索ドロップダウンを閉じます。
  • 各ページは、それを描画するブロックのアクセシビリティを保っています。バッグは変更を polite に通知し、Add to bag は追加した内容を伝え、フィルターは結果件数を通知し、バリアントピッカーは本物のラジオグループで、売り切れのサイズも Notify me のためにフォーカス可能なままです。
  • リンクは本物の href を持つ本物のリンクなので、中クリックや新しいタブでも機能します。ページが切り替わると新しいページが通知され、フォーカスがその先頭に移ります。戻る操作ではスクロール位置が復元されます。
  • 重要な情報が色や動きだけで示されることはありません。売り切れ、在庫僅少、セールは言葉で表示され、ヘッダーのボタンはバッグとウィッシュリストのアイテム数を伝え、ページのフェード、レール、ヒーローのボタンは視差効果を減らす設定を尊重します。

使用技術

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

コード

11 個のファイルを components/blocks/storefront に追加しました。