HextaUI

スウォッチ、クイック追加、ウィッシュリストのハートを備えた、コレクションのグリッドやレール向けの商品タイル。売り切れのサイズ、価格帯、追加の失敗に対応します。

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

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

Product Cardは、コレクションのグリッド、検索結果、おすすめのレールに置くタイルです。Variant Pickerと同じモデルであるProductを受け取り、色ごとではなく商品ごとに1枚のカードを表示します。カード全体はタイトルに付いた1つのリンクで、ハート、スウォッチ、クイック追加はその上に重なる別々のボタンです。

色は小さなスウォッチの列として表示され、すべてに到達できます。幅の狭いカードでは列が横にスクロールし、最後のスウォッチが途中で切れて端がフェードするため、購入者はまだ続きがあることがわかります。スウォッチにホバーすると、少し間を置いてその色の写真をプレビューし、事前に読み込むため、クロスフェードで空白のフレームが表示されることはありません。クリックするとその色が選ばれ、価格、バッジ、在庫がそれに従い、リンクは?color=を設定した商品ページを開きます。マウスでは、カードにホバーすると2枚目の写真にクロスフェードします。

クイック追加は商品に合わせて変わります。バリエーションが1つの商品には、スピナー、Added、Couldn’t addに変わる間も幅を保つAdd to bagボタンが付きます。サイズのある商品では、ホバーまたはキーボードフォーカスで写真の上にサイズボタンの列がスライドアップし、売り切れのサイズには取り消し線が引かれます。タッチスクリーンでは、代わりに+ボタンがVariant Picker付きのボトムシートを開きます。売り切れの商品ではクイック追加が非表示になり、Sold outバッジとNotify meリンクが表示されます。

バッジはデータから生成されます。Sale −20%、Only 3 left、Pre-order、Sold outに加え、Newのような独自のバッジも追加でき、最大2つまで表示されます。ウィッシュリストのハートは楽観的に保存され、保存時に一度弾むように動き、コールバックがエラーを投げるとメッセージとともに元に戻ります。ProductGridはカードを2、3、4列に配置してその間をアニメーションさせ、ProductCardSkeletonは読み込み状態のためにカードの形とまったく同じ形になります。

  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-card

Shopifyのコレクション

Storefront APIの各商品を一度変換して渡します。onQuickAddは選ばれたバリエーションを受け取るため、カートへの追加は1回のfetchで済みます。ルートがエラーを投げると、そのメッセージは購入者がクリックしたカードに表示されます。

import { fromShopify } from "../variant-picker/shopify"
import { ProductCard, ProductGrid } from "@/components/blocks/product-card/product-card"

type ShopifyProduct = Parameters<typeof fromShopify>[0] & {
  rating: { value: string } | null
  ratingCount: { value: string } | null
}

type Collection = {
  title: string
  products: { nodes: ShopifyProduct[] }
}

async function addToCart(merchandiseId: string) {
  const response = await fetch("/api/cart/lines", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ merchandiseId, quantity: 1 }),
  })
  if (!response.ok) {
    const { message } = await response.json()
    throw new Error(message ?? "Couldn’t add this to your bag. Try again.")
  }
}

export function CollectionGrid({ collection }: { collection: Collection }) {
  return (
    <ProductGrid columns={4} aria-label={collection.title}>
      {collection.products.nodes.map((node, index) => {
        const product = fromShopify(node)
        const count = Number(node.ratingCount?.value ?? 0)
        return (
          <ProductCard
            key={product.id}
            product={product}
            href={`/products/${node.handle}`}
            priority={index < 4}
            rating={count > 0 ? { value: Number(JSON.parse(node.rating?.value ?? "{}").value ?? 0), count } : null}
            onQuickAdd={(variant) => addToCart(variant.id)}
          />
        )
      })}
    </ProductGrid>
  )
}

おすすめのレール

「You may also like」や「Complete the look」のために、コンパクトなカードを横スクロールのリストに並べます。各カードは自身のスウォッチとクイック追加を持つため、レールに追加の状態は必要ありません。

import type { Product, ProductVariant } from "../variant-picker/product"
import { ProductCard } from "@/components/blocks/product-card/product-card"

type RecommendationsProps = {
  title: string
  products: Product[]
  addToBag: (variantId: string) => Promise<void>
}

export function Recommendations({ title, products, addToBag }: RecommendationsProps) {
  if (products.length === 0) return null
  return (
    <section aria-labelledby="recommendations" className="flex flex-col gap-4">
      <h2 id="recommendations" className="text-lg font-medium">
        {title}
      </h2>
      <ul
        role="list"
        className="-mx-4 flex snap-x snap-mandatory gap-3 overflow-x-auto px-4 pb-2"
      >
        {products.map((product) => (
          <li key={product.id} className="w-44 shrink-0 snap-start sm:w-56">
            <ProductCard
              product={product}
              size="sm"
              headingLevel={3}
              onQuickAdd={(variant: ProductVariant) => addToBag(variant.id)}
            />
          </li>
        ))}
      </ul>
    </section>
  )
}

APIに保存するウィッシュリスト

ハートはすぐに塗りつぶされ、リクエストが失敗すると元に戻ります。サインインしていない購入者はlocalStorageに保存するため、保存にアカウントは不要で、サインイン済みの購入者はAPIに保存します。

"use client"

import * as React from "react"

import type { Product } from "../variant-picker/product"
import { ProductCard, ProductGrid } from "@/components/blocks/product-card/product-card"

const storageKey = "wishlist"

function readLocal(): string[] {
  try {
    return JSON.parse(localStorage.getItem(storageKey) ?? "[]")
  } catch {
    return []
  }
}

export function WishlistGrid({
  products,
  signedIn,
}: {
  products: Product[]
  signedIn: boolean
}) {
  const [saved, setSaved] = React.useState<string[]>([])

  React.useEffect(() => {
    if (!signedIn) {
      setSaved(readLocal())
      return
    }
    fetch("/api/wishlist")
      .then((response) => response.json())
      .then((data: { productIds: string[] }) => setSaved(data.productIds))
  }, [signedIn])

  const change = async (next: boolean, product: Product) => {
    const ids = next
      ? [...saved, product.id]
      : saved.filter((id) => id !== product.id)
    if (signedIn) {
      const response = await fetch(`/api/wishlist/${encodeURIComponent(product.id)}`, {
        method: next ? "PUT" : "DELETE",
      })
      if (!response.ok) throw new Error("Couldn’t update your wishlist. Try again.")
    } else {
      localStorage.setItem(storageKey, JSON.stringify(ids))
    }
    setSaved(ids)
  }

  return (
    <ProductGrid columns={3}>
      {products.map((product) => (
        <ProductCard
          key={product.id}
          product={product}
          wishlisted={saved.includes(product.id)}
          onWishlistChange={change}
        />
      ))}
    </ProductGrid>
  )
}

構造

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

パーツ説明
ProductCard写真、バッジ、ウィッシュリストのハート、クイック追加、スウォッチ、販売元、タイトル、価格、評価。
ProductGrid2、3、4列のレスポンシブなカードのリストで、読み込み状態にも対応します。
ProductCardSkeletonカードとまったく同じ形状の読み込みプレースホルダー。
getAutoBadges, getCardPrice, getQuickAddMode, getSizeChipsカードの背後にある純粋なヘルパー。サーバーでも使えます。

ProductCard

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

プロパティ型デフォルト
productオプション、バリエーション、画像を含む商品。
Product–
hrefカードのリンク先。文字列の場合、購入者が色を選ぶと?color=が追加されます。
string | (color) => string"/products/{handle}"
linkRenderタイトルのリンクを、<Link prefetch />のようなルーターのLinkで描画します。
ReactElement<a>–
selectedColor制御時に選ばれているスウォッチの値。スウォッチのオプションは、スウォッチを持つオプションです。
string–
defaultSelectedColorスウォッチの初期値。デフォルトは在庫のある最初の色です。
string–
onSelectedColorChange購入者が色を選んだときに呼ばれます。
(color: string) => void–
badges自動のバッジの後に表示される独自のバッジ。
(string | { id; label; tone? })[]–
autoBadgesデータからSale、Low stock、Pre-order、Sold outを表示します。
booleantrue
maxBadges一度に表示されるバッジの最大数。
number2
rating星を「4.8 (126)」とともに表示します。countが0のときは非表示になります。
{ value: number; count: number } | null–
wishlisted制御時に、商品が保存されているかどうか。
boolean–
defaultWishlisted非制御時の保存状態の初期値。
booleanfalse
onWishlistChangeハートを表示します。ハートはすぐに切り替わり、これがエラーを投げるかrejectされると元に戻ります。
(wishlisted, product) => void | Promise<void>–
onQuickAddクイック追加を表示します。カードは返されたPromiseから、保留中、追加済み、エラーの状態を表示します。
(variant, product) => void | Promise<void>–
notifyHref売り切れの商品でNotify meがリンクする先。デフォルトは?notify=1付きの商品リンクです。
string–
sizeカードの密度。ProductGridの内側では列数に従います。
"sm" | "default"–
priorityファーストビュー内のカード向けに、写真を高い優先度で即座に読み込みます。
booleanfalse
imageSizes写真のsizes属性。
string–
headingLevelタイトルの見出しレベル。
2 | 3 | 43
locale価格と件数のロケール。
Intl.LocalesArgument"en-US"
trailingZeros$48ではなく$48.00と表示します。
booleanfalse
labelsボタン、バッジ、スウォッチ名、読み上げに使う文言。
Partial<ProductCardLabels>–

ProductGrid

ulのプロップも受け付けます。各子要素はリスト項目で囲まれます。

プロパティ型デフォルト
columns広い画面での列数。スマートフォンでは、2の場合は1列、それ以外は2列で表示されます。
2 | 3 | 43
sizeカードの密度。4列のときのデフォルトはsmです。
"sm" | "default"–
loadingスケルトンを表示し、aria-busyを設定します。
booleanfalse
skeletonCount読み込み中に表示するスケルトンの数。
number8
skeleton読み込み中の各セル用のカスタムスケルトン。
ReactNode–

ProductCardSkeleton

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

プロパティ型デフォルト
sizeカードの密度に合わせます。
"sm" | "default"–
swatchesスウォッチの列を含めます。
booleantrue
rating評価の行を含めます。
booleanfalse
キーアクション
Tab商品リンクからハート、クイック追加のボタン、各スウォッチへと移動します。カードにフォーカスするとサイズの列が表示されます。
Enterリンクから商品ページを開くか、フォーカスされたサイズを追加します。
Spaceハートを切り替えるか、フォーカスされたスウォッチを選ぶか、フォーカスされたサイズを追加します。
Escapeクイック追加のシートを閉じ、フォーカスを+ボタンに戻します。
  • カードは見出しの中にある、商品タイトルで名前が付けられた1つのリンクです。ハート、スウォッチ、クイック追加はその上に重なる別々のボタンで、リンクの中に入れ子になることはありません。
  • スウォッチには「Sage, 3 of 5」のような名前が付き、色が売り切れの場合はそれを伝えます。選ばれたスウォッチにはaria-pressedが付きます。売り切れのサイズはaria-disabled付きでフォーカス可能なままで、「Twin, sold out」という名前が付きます。
  • ハートはaria-pressedと「Save Ring Vase to wishlist」というラベルを使います。politeなライブリージョンが「Added Washed Linen Duvet Cover, White / King, to your bag」のように保存、削除、追加を通知し、失敗はアラートとして通知されます。
  • ホバー専用の効果はマウスポインターに限られ、サイズの列はキーボードフォーカスでも開きます。モーションはtransformとopacityのみで、視差効果を減らす設定では短いフェードだけが残ります。

使用技術

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

コード

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