diff --git a/docs.json b/docs.json index d5422916..aa2cb32e 100644 --- a/docs.json +++ b/docs.json @@ -146,10 +146,7 @@ "solutions/monetization-overview", { "group": "Shop", - "pages": [ - "solutions/shop/overview", - "solutions/shop/guide" - ] + "pages": ["solutions/shop/overview", "solutions/shop/guide"] }, { "group": "White-label Marketplace", @@ -308,6 +305,13 @@ ] } ] + }, + { + "group": "Components", + "pages": [ + "sdk/marketplace-sdk/components/Media", + "sdk/marketplace-sdk/components/CollectibleCard" + ] } ] }, diff --git a/es/sdk/marketplace-sdk/components/CollectibleCard.mdx b/es/sdk/marketplace-sdk/components/CollectibleCard.mdx new file mode 100644 index 00000000..4e81585e --- /dev/null +++ b/es/sdk/marketplace-sdk/components/CollectibleCard.mdx @@ -0,0 +1,432 @@ +--- +title: CollectibleCard +description: Un componente de tarjeta versátil para mostrar coleccionables en contextos de marketplace y tienda +sidebarTitle: CollectibleCard +--- + +## Importar + +```tsx +import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; +``` + +## Uso + +### Hooks de datos +El SDK proporciona hooks especializados para obtener y formatear datos para el componente CollectibleCard: + +#### Tarjetas de Marketplace + +```tsx +import { useListMarketCardData } from "@0xsequence/marketplace-sdk/react"; + +const { + collectibleCards, + isLoading, + hasNextPage, + isFetchingNextPage, + fetchNextPage, +} = useListMarketCardData({ + orderbookKind, + collectionType, + filterOptions, + searchText, + showListedOnly, + collectionAddress, + chainId, +}); +``` + +#### Tarjetas de Tienda +Para las tarjetas de tienda, hay dos hooks según el tipo de contrato: + +```tsx +// For ERC721 tokens +import { useList721ShopCardData } from "@0xsequence/marketplace-sdk/react"; + +const { collectibleCards, isLoading } = useList721ShopCardData({ + primarySaleItemsWithMetadata, + chainId, + contractAddress, + salesContractAddress, + enabled: contractType === ContractType.ERC721, +}); + +// For ERC1155 tokens +import { useList1155ShopCardData } from "@0xsequence/marketplace-sdk/react"; + +const { collectibleCards, isLoading } = useList1155ShopCardData({ + chainId, + contractAddress, + salesContractAddress, + enabled: contractType === ContractType.ERC1155, + primarySaleItemsWithMetadata, +}); +``` + +Estos hooks gestionan: +- Obtención y formateo de datos +- Estados de carga +- Paginación (para tarjetas de marketplace) +- Requisitos de datos según el tipo +- Integración con filtros y búsqueda + +### Examples + + + + Ejemplo de uso del componente CollectibleCard en un contexto de marketplace: + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function MarketExample() { + return ( + { + console.log(`Clicked collectible ${tokenId}`); + }} + /> + ); + } + ``` + + + + Ejemplo mostrando CollectibleCard en un contexto de tienda: + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function ShopExample() { + return ( + + ); + } + ``` + + + + Ejemplo que demuestra la funcionalidad de ofertas: + + + ![Tarjeta de coleccionable con ofertas](/images/marketplace/collectible_card_with_offer.png "Tarjeta de coleccionable con ofertas") + + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function OffersExample() { + return ( + { + console.log('Offer clicked', order); + e.preventDefault(); + }} + onCannotPerformAction={(action) => { + console.log(`Cannot perform action: ${action}`); + }} + /> + ); + } + ``` + + + +## Parámetros +El componente acepta diferentes props según el tipo de marketplace: + +### Props Base +Estas propiedades son compartidas por todos los tipos de tarjeta: + +```tsx +interface MarketplaceCardBaseProps { + collectibleId: string; + chainId: number; + collectionAddress: Address; + collectionType?: ContractType; + assetSrcPrefixUrl?: string; + cardLoading?: boolean; + marketplaceType?: MarketplaceType; + isTradable?: boolean; +} +``` + +| Parámetro | Type | Description | +| ------------------- | ----------------- | ---------------------------------------------------------- | +| `collectibleId` | `string` | Identificador único para el coleccionable | +| `chainId` | `number` | El ID de la red blockchain | +| `collectionAddress` | `Address` | La dirección del smart contract de la colección | +| `collectionType` | `ContractType` | Opcional. El tipo de contrato (ERC721 o ERC1155) | +| `assetSrcPrefixUrl` | `string` | Prefijo de URL opcional para las fuentes de los assets | +| `cardLoading` | `boolean` | Indicador opcional para mostrar el estado de carga | +| `marketplaceType` | `MarketplaceType` | Opcional. Tipo de marketplace ('market' o 'shop') | +| `isTradable` | `boolean` | Indicador opcional que señala si el ítem es intercambiable | + +### Props de Tarjeta de Tienda +Propiedades adicionales para tarjetas de tienda (`marketplaceType="shop"`): + +```tsx +interface ShopCardSpecificProps { + salesContractAddress: Address; + tokenMetadata: TokenMetadata; + salePrice?: { + amount: string; + currencyAddress: Address; + }; + saleStartsAt?: string; + saleEndsAt?: string; + quantityDecimals?: number; + quantityInitial?: string; + quantityRemaining?: string; + unlimitedSupply?: boolean; +} +``` + +| Parámetro | Type | Description | +| ---------------------- | --------------- | ----------------------------------------------------------- | +| `salesContractAddress` | `Address` | La dirección del contrato de ventas | +| `tokenMetadata` | `TokenMetadata` | Metadatos del token incluyendo nombre, descripción e imagen | +| `salePrice` | `object` | Opcional. Información de precio incluyendo monto y moneda | +| `saleStartsAt` | `string` | Opcional. Timestamp de inicio de venta | +| `saleEndsAt` | `string` | Opcional. Timestamp de fin de venta | +| `quantityDecimals` | `number` | Opcional. Número de decimales para la cantidad | +| `quantityInitial` | `string` | Opcional. Cantidad inicial de suministro | +| `quantityRemaining` | `string` | Opcional. Cantidad restante de suministro | +| `unlimitedSupply` | `boolean` | Opcional. Indica si el suministro es ilimitado | + +### Props de Tarjeta de Marketplace +Propiedades adicionales para tarjetas de marketplace (`marketplaceType="market"`): + +```tsx +interface MarketCardSpecificProps { + orderbookKind?: OrderbookKind; + collectible?: CollectibleOrder; + onCollectibleClick?: (tokenId: string) => void; + onOfferClick?: (params: { + order?: Order; + e: React.MouseEvent; + }) => void; + balance?: string; + balanceIsLoading: boolean; + onCannotPerformAction?: (action: CollectibleCardAction) => void; + prioritizeOwnerActions?: boolean; +} +``` + +| Parámetro | Type | Description | +| ------------------------ | ------------------ | ------------------------------------------------------------------------------ | +| `orderbookKind` | `OrderbookKind` | Opcional. Tipo de orderbook | +| `collectible` | `CollectibleOrder` | Opcional. Información de la orden del coleccionable | +| `onCollectibleClick` | `function` | Opcional. Manejador para eventos de clic en el coleccionable | +| `onOfferClick` | `function` | Opcional. Manejador para eventos de clic en oferta | +| `balance` | `string` | Opcional. Balance del usuario de este coleccionable | +| `balanceIsLoading` | `boolean` | Indica si el balance se está cargando actualmente | +| `onCannotPerformAction` | `function` | Opcional. Manejador para acciones no autorizadas | +| `prioritizeOwnerActions` | `boolean` | Opcional. Indica si se deben priorizar acciones del propietario en la interfaz | + +## Características + +### Variantes de tarjeta +El componente soporta dos variantes principales: +1. **Tarjeta de Marketplace**: Se usa para mostrar coleccionables en un contexto de marketplace con: + - Precio actual listado + - Indicador de la oferta más alta + - Información de balance/propiedad + - Acciones de compra/oferta + +2. **Tarjeta de Tienda**: Se usa para ventas primarias con: + - Precio de venta + - Información de suministro + - Estado de la venta + - Acciones de compra + +### Detección Automática de Tipo +El componente gestiona automáticamente diferentes estándares de tokens: +- ERC-721 (tokens no fungibles) +- ERC-1155 (tokens semi-fungibles) + +### Estados de Carga +Se incluyen estados de carga integrados: + +```tsx + +``` + +### Formateo de Precios +El componente incluye formateo avanzado de precios con: +- Visualización del símbolo de la moneda +- Indicadores de desbordamiento/subdesbordamiento +- Soporte para varios decimales de tokens +- Indicador de "Gratis" para precios en cero + +## Ejemplos de Integración + +### Integración de Contenido de Marketplace +Aquí un ejemplo completo de integración de CollectibleCard en un contexto de marketplace: + +```tsx +import { + CollectibleCard, + useListMarketCardData, +} from "@0xsequence/marketplace-sdk/react"; + +export function MarketContent({ + collectionAddress, + chainId, + onCollectibleClick, +}) { + const { + collectibleCards, + isLoading, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + } = useListMarketCardData({ + orderbookKind, + collectionType, + filterOptions, + searchText, + showListedOnly, + collectionAddress, + chainId, + }); + + return ( +
+ {collectibleCards.map((card, index) => ( + + ))} +
+ ); +} +``` + +### Integración de Contenido de Tienda +Ejemplo de integración de CollectibleCard en un contexto de tienda con manejo de tipo de contrato: + +```tsx +import { + CollectibleCard, + useList721ShopCardData, + useList1155ShopCardData, +} from "@0xsequence/marketplace-sdk/react"; + +export function ShopContent({ + saleContractAddress, + collectionAddress, + chainId, + onCollectibleClick, +}) { + // Choose hook based on contract type + const { collectibleCards, isLoading } = + contractType === ContractType.ERC721 + ? useList721ShopCardData({ + primarySaleItemsWithMetadata, + chainId, + contractAddress: collectionAddress, + salesContractAddress: saleContractAddress, + enabled: true, + }) + : useList1155ShopCardData({ + chainId, + contractAddress: collectionAddress, + salesContractAddress: saleContractAddress, + enabled: true, + primarySaleItemsWithMetadata, + }); + + return ( +
+ {collectibleCards.map((card, index) => ( + + ))} +
+ ); +} +``` + +## Notas +El componente `MarketplaceCollectibleCard` está diseñado para manejar varios escenarios de marketplace con: +- Diseño responsivo +- Estados de carga +- Formateo de precios +- Seguimiento de suministro +- Manejo de acciones +- Funciones específicas para el propietario +- Gestión de ofertas + +Al usar con tokens ERC-1155, tenga en cuenta que: +- El balance se muestra como formato "Propiedad: X" +- La información de suministro se muestra para ítems de tienda +- Se soporta el seguimiento de cantidades + +### Mejores prácticas + +1. **Obtención de Datos** + - Use el hook de datos adecuado según su contexto (market/shop) y tipo de contrato (ERC721/ERC1155) + - Habilite la obtención condicional usando la prop `enabled` cuando sea necesario + - Gestione los estados de carga apropiadamente + +2. **Manejo de Eventos** + - Implemente manejadores de clic tanto para la tarjeta como para acciones específicas (comprar, ofertar) + - Use el callback `onCannotPerformAction` para manejar acciones no autorizadas + +3. **Visualización** + - Envuelva las tarjetas en botones para hacerlas clickeables + - Use el className adecuado para el diseño y espaciado + - Considere implementar scroll infinito o paginación para colecciones grandes \ No newline at end of file diff --git a/es/sdk/marketplace-sdk/components/Media.mdx b/es/sdk/marketplace-sdk/components/Media.mdx new file mode 100644 index 00000000..874937bb --- /dev/null +++ b/es/sdk/marketplace-sdk/components/Media.mdx @@ -0,0 +1,162 @@ +--- +title: Media +description: Componente para mostrar varios tipos de assets coleccionables +sidebarTitle: Media +--- + +## Importar + +```tsx +import { Media } from "@0xsequence/marketplace-sdk/react"; +``` + +## Uso + +### Examples + + + + Ejemplo básico de uso del componente Media para mostrar una imagen: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function BasicExample() { + return ( + + ); + } + ``` + + + + Ejemplo mostrando cómo manejar múltiples assets con fallback: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function MultipleAssetsExample() { + return ( + + ); + } + ``` + + + + Ejemplo con un componente de fallback personalizado: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function CustomFallbackExample() { + const CustomFallback = () => ( +
+

Asset not available

+
+ ); + + return ( + } + /> + ); + } + ``` +
+
+ +## Parámetros +El componente acepta las siguientes props: + +```tsx +interface MediaProps { + name?: string; + assets: (string | undefined)[]; + assetSrcPrefixUrl?: string; + className?: string; + containerClassName?: string; + mediaClassname?: string; + isLoading?: boolean; + fallbackContent?: React.ReactNode; + shouldListenForLoad?: boolean; +} +``` + +| Parámetro | Type | Description | | +| --------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------- | +| `name` | `string` | Nombre opcional para el coleccionable, usado como texto alternativo para imágenes | | +| `assets` | \`(string | undefined)\[]\` | Arreglo de URLs de assets para intentar cargar. El componente intentará cargar cada asset en orden hasta que uno se cargue correctamente | +| `assetSrcPrefixUrl` | `string` | Prefijo de URL opcional para anteponer a las URLs de los assets | | +| `className` | `string` | Nombre de clase CSS opcional para el contenedor del componente | | +| `containerClassName` | `string` | Nombre de clase CSS opcional para el contenedor externo | | +| `mediaClassname` | `string` | Nombre de clase CSS opcional para el elemento media | | +| `isLoading` | `boolean` | Indicador opcional para mostrar el estado de carga | | +| `fallbackContent` | `React.ReactNode` | Contenido personalizado opcional para mostrar cuando no se pueden cargar assets | | +| `shouldListenForLoad` | `boolean` | Indicador opcional para habilitar/deshabilitar los listeners de eventos de carga (por defecto es true) | | + +## Tipos de Media Soportados +El componente Media detecta y gestiona automáticamente diferentes tipos de contenido: +- **Imágenes**: Renderiza archivos de imagen estándar (PNG, JPG, GIF, etc.) +- **Videos**: Soporta archivos de video con autoplay, loop y controles +- **Modelos 3D**: Renderiza modelos 3D usando el componente ModelViewer +- **HTML**: Muestra contenido HTML en un iframe aislado + +## Características + +### Detección Automática de Tipo de Contenido +El componente detecta automáticamente el tipo de contenido del asset y renderiza el elemento apropiado: + +```tsx + +``` + +### Cadena de Fallback +Si un asset falla al cargar, el componente: +1. Intenta el siguiente asset en el arreglo de assets +2. Si todos los assets fallan, muestra el contenido de fallback personalizado +3. Si no se proporciona contenido de fallback, muestra el patrón de tablero de ajedrez por defecto + +### Estados de Carga +El componente incluye estados de carga integrados: + +```tsx + +``` + +## Notas +El componente `Media` está diseñado para manejar varios tipos de assets coleccionables con: +- Detección automática de tipo de contenido +- Manejo de fallback +- Estados de carga +- Ajustes de compatibilidad con Safari + +Al usar con contenido de video, tenga en cuenta que: +- Los videos se reproducen automáticamente por defecto +- Los videos están silenciados por defecto para compatibilidad con autoplay \ No newline at end of file diff --git a/images/marketplace/collectible_card_with_offer.png b/images/marketplace/collectible_card_with_offer.png new file mode 100644 index 00000000..1eda0022 Binary files /dev/null and b/images/marketplace/collectible_card_with_offer.png differ diff --git a/ja/sdk/marketplace-sdk/components/CollectibleCard.mdx b/ja/sdk/marketplace-sdk/components/CollectibleCard.mdx new file mode 100644 index 00000000..ca66f608 --- /dev/null +++ b/ja/sdk/marketplace-sdk/components/CollectibleCard.mdx @@ -0,0 +1,432 @@ +--- +title: CollectibleCard +description: マーケットプレイスやショップでコレクティブルを表示するための多用途なカードコンポーネントです。 +sidebarTitle: CollectibleCard +--- + +## インポート + +```tsx +import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; +``` + +## 使い方 + +### データフック +SDK には、CollectibleCard コンポーネント用のデータ取得・整形専用フックが用意されています。 + +#### マーケットカード + +```tsx +import { useListMarketCardData } from "@0xsequence/marketplace-sdk/react"; + +const { + collectibleCards, + isLoading, + hasNextPage, + isFetchingNextPage, + fetchNextPage, +} = useListMarketCardData({ + orderbookKind, + collectionType, + filterOptions, + searchText, + showListedOnly, + collectionAddress, + chainId, +}); +``` + +#### ショップカード +ショップカードには、コントラクトタイプに応じて2種類のフックがあります。 + +```tsx +// For ERC721 tokens +import { useList721ShopCardData } from "@0xsequence/marketplace-sdk/react"; + +const { collectibleCards, isLoading } = useList721ShopCardData({ + primarySaleItemsWithMetadata, + chainId, + contractAddress, + salesContractAddress, + enabled: contractType === ContractType.ERC721, +}); + +// For ERC1155 tokens +import { useList1155ShopCardData } from "@0xsequence/marketplace-sdk/react"; + +const { collectibleCards, isLoading } = useList1155ShopCardData({ + chainId, + contractAddress, + salesContractAddress, + enabled: contractType === ContractType.ERC1155, + primarySaleItemsWithMetadata, +}); +``` + +これらのフックは以下を処理します: +- データの取得と整形 +- ローディング状態の管理 +- ページネーション(マーケットカード用) +- タイプごとのデータ要件 +- フィルターや検索との連携 + +### 使用例 + + + + マーケットプレイスで CollectibleCard コンポーネントを使う例: + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function MarketExample() { + return ( + { + console.log(`Clicked collectible ${tokenId}`); + }} + /> + ); + } + ``` + + + + ショップで CollectibleCard を利用する例: + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function ShopExample() { + return ( + + ); + } + ``` + + + + オファー機能を持つ例: + + + ![オファー付きコレクティブルカード](/images/marketplace/collectible_card_with_offer.png "Collectible Card with Offers") + + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function OffersExample() { + return ( + { + console.log('Offer clicked', order); + e.preventDefault(); + }} + onCannotPerformAction={(action) => { + console.log(`Cannot perform action: ${action}`); + }} + /> + ); + } + ``` + + + +## パラメータ +コンポーネントはマーケットプレイスタイプに応じて異なるプロパティを受け取ります。 + +### 基本プロパティ +これらのプロパティはすべてのカードタイプで共通です: + +```tsx +interface MarketplaceCardBaseProps { + collectibleId: string; + chainId: number; + collectionAddress: Address; + collectionType?: ContractType; + assetSrcPrefixUrl?: string; + cardLoading?: boolean; + marketplaceType?: MarketplaceType; + isTradable?: boolean; +} +``` + +| パラメータ | 型 | 説明 | +| ------------------- | ----------------- | --------------------------------------- | +| `collectibleId` | `string` | コレクティブルの一意な識別子 | +| `chainId` | `number` | ブロックチェーンネットワークID | +| `collectionAddress` | `Address` | コレクションのスマートコントラクトアドレス | +| `collectionType` | `ContractType` | オプション。コントラクトタイプ(ERC721 または ERC1155) | +| `assetSrcPrefixUrl` | `string` | オプション。アセットソース用のURLプレフィックス | +| `cardLoading` | `boolean` | オプション。ローディング状態を表示するフラグ | +| `marketplaceType` | `MarketplaceType` | オプション。マーケットプレイスタイプ('market' または 'shop') | +| `isTradable` | `boolean` | オプション。このアイテムが取引可能かどうかを示すフラグ | + +### ショップカード用プロパティ +ショップカード(`marketplaceType="shop"`)用の追加プロパティ: + +```tsx +interface ShopCardSpecificProps { + salesContractAddress: Address; + tokenMetadata: TokenMetadata; + salePrice?: { + amount: string; + currencyAddress: Address; + }; + saleStartsAt?: string; + saleEndsAt?: string; + quantityDecimals?: number; + quantityInitial?: string; + quantityRemaining?: string; + unlimitedSupply?: boolean; +} +``` + +| パラメータ | 型 | 説明 | +| ---------------------- | --------------- | ---------------------- | +| `salesContractAddress` | `Address` | 販売コントラクトのアドレス | +| `tokenMetadata` | `TokenMetadata` | トークンのメタデータ(名前、説明、画像など) | +| `salePrice` | `object` | オプション。金額や通貨を含む価格情報 | +| `saleStartsAt` | `string` | オプション。販売開始のタイムスタンプ | +| `saleEndsAt` | `string` | オプション。販売終了のタイムスタンプ | +| `quantityDecimals` | `number` | オプション。数量の小数点以下の桁数 | +| `quantityInitial` | `string` | オプション。初期供給量 | +| `quantityRemaining` | `string` | オプション。残り供給量 | +| `unlimitedSupply` | `boolean` | オプション。供給が無制限かどうか | + +### マーケットカード用プロパティ +マーケットカード(`marketplaceType="market"`)用の追加プロパティ: + +```tsx +interface MarketCardSpecificProps { + orderbookKind?: OrderbookKind; + collectible?: CollectibleOrder; + onCollectibleClick?: (tokenId: string) => void; + onOfferClick?: (params: { + order?: Order; + e: React.MouseEvent; + }) => void; + balance?: string; + balanceIsLoading: boolean; + onCannotPerformAction?: (action: CollectibleCardAction) => void; + prioritizeOwnerActions?: boolean; +} +``` + +| パラメータ | 型 | 説明 | +| ------------------------ | ------------------ | -------------------------- | +| `orderbookKind` | `OrderbookKind` | オプション。オーダーブックの種類 | +| `collectible` | `CollectibleOrder` | オプション。コレクティブルの注文情報 | +| `onCollectibleClick` | `function` | オプション。コレクティブルクリック時のハンドラー | +| `onOfferClick` | `function` | オプション。オファークリック時のハンドラー | +| `balance` | `string` | オプション。このコレクティブルのユーザー保有数 | +| `balanceIsLoading` | `boolean` | 現在バランスを読み込み中かどうか | +| `onCannotPerformAction` | `function` | オプション。権限がない操作時のハンドラー | +| `prioritizeOwnerActions` | `boolean` | オプション。UI上でオーナーの操作を優先するかどうか | + +## 特徴 + +### カードバリエーション +コンポーネントは主に2つのバリエーションをサポートします: +1. **マーケットカード**:マーケットプレイスでコレクティブルを表示する際に使用し、以下を含みます: + - 現在の出品価格 + - 最高オファーの表示 + - 保有・所有情報 + - 購入・オファーアクション + +2. **ショップカード**:一次販売用で、以下を含みます: + - 販売価格 + - 供給情報 + - 販売状況 + - 購入アクション + +### 自動タイプ判定 +コンポーネントは異なるトークン規格を自動で処理します: +- ERC-721(非代替性トークン) +- ERC-1155(半代替性トークン) + +### ローディング状態 +組み込みのローディング状態が用意されています。 + +```tsx + +``` + +### 価格フォーマット +コンポーネントには高度な価格フォーマット機能が含まれています: +- 通貨記号の表示 +- オーバーフロー/アンダーフローの指標 +- さまざまなトークン小数点への対応 +- 価格がゼロの場合の「無料」表示 + +## 統合例 + +### マーケットコンテンツへの統合 +CollectibleCard をマーケットプレイスで統合する完全な例: + +```tsx +import { + CollectibleCard, + useListMarketCardData, +} from "@0xsequence/marketplace-sdk/react"; + +export function MarketContent({ + collectionAddress, + chainId, + onCollectibleClick, +}) { + const { + collectibleCards, + isLoading, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + } = useListMarketCardData({ + orderbookKind, + collectionType, + filterOptions, + searchText, + showListedOnly, + collectionAddress, + chainId, + }); + + return ( +
+ {collectibleCards.map((card, index) => ( + + ))} +
+ ); +} +``` + +### ショップコンテンツへの統合 +コントラクトタイプの処理を含むショップでの CollectibleCard 統合例: + +```tsx +import { + CollectibleCard, + useList721ShopCardData, + useList1155ShopCardData, +} from "@0xsequence/marketplace-sdk/react"; + +export function ShopContent({ + saleContractAddress, + collectionAddress, + chainId, + onCollectibleClick, +}) { + // Choose hook based on contract type + const { collectibleCards, isLoading } = + contractType === ContractType.ERC721 + ? useList721ShopCardData({ + primarySaleItemsWithMetadata, + chainId, + contractAddress: collectionAddress, + salesContractAddress: saleContractAddress, + enabled: true, + }) + : useList1155ShopCardData({ + chainId, + contractAddress: collectionAddress, + salesContractAddress: saleContractAddress, + enabled: true, + primarySaleItemsWithMetadata, + }); + + return ( +
+ {collectibleCards.map((card, index) => ( + + ))} +
+ ); +} +``` + +## 補足 +`MarketplaceCollectibleCard` コンポーネントは、さまざまなマーケットプレイスのシナリオに対応できるよう設計されています: +- レスポンシブレイアウト +- ローディング状態の管理 +- 価格フォーマット +- 供給量の追跡 +- アクションの処理 +- オーナー向け機能 +- オファー管理 + +ERC-1155 トークンで利用する場合の注意点: +- 保有数は「Owned: X」の形式で表示されます +- ショップアイテムには供給情報が表示されます +- 数量の追跡に対応しています + +### ベストプラクティス + +1. **データ取得** + - 利用する状況(マーケット/ショップ)やコントラクトタイプ(ERC721/ERC1155)に応じて適切なデータフックを使ってください。 + - 必要に応じて `enabled` プロップで条件付き取得を有効化できます。 + - ローディング状態を適切に処理してください。 + +2. **イベント処理** + - カードや特定アクション(購入・オファー)用のクリックハンドラーを実装してください。 + - 権限がない操作時は `onCannotPerformAction` コールバックを利用してください。 + +3. **表示** + - クリック可能にするため、カードをボタンでラップしてください。 + - レイアウトや余白調整には適切な className を使ってください。 + - 大規模コレクションには無限スクロールやページネーションの実装も検討してください。 \ No newline at end of file diff --git a/ja/sdk/marketplace-sdk/components/Media.mdx b/ja/sdk/marketplace-sdk/components/Media.mdx new file mode 100644 index 00000000..959a7884 --- /dev/null +++ b/ja/sdk/marketplace-sdk/components/Media.mdx @@ -0,0 +1,162 @@ +--- +title: Media +description: さまざまな種類のコレクティブルアセットを表示するためのコンポーネントです。 +sidebarTitle: Media +--- + +## インポート + +```tsx +import { Media } from "@0xsequence/marketplace-sdk/react"; +``` + +## 使い方 + +### 使用例 + + + + Media コンポーネントで画像を表示する基本例: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function BasicExample() { + return ( + + ); + } + ``` + + + + 複数アセットをフォールバック付きで扱う例: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function MultipleAssetsExample() { + return ( + + ); + } + ``` + + + + カスタムフォールバックコンポーネントを使った例: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function CustomFallbackExample() { + const CustomFallback = () => ( +
+

Asset not available

+
+ ); + + return ( + } + /> + ); + } + ``` +
+
+ +## パラメータ +コンポーネントは以下のプロパティを受け取ります: + +```tsx +interface MediaProps { + name?: string; + assets: (string | undefined)[]; + assetSrcPrefixUrl?: string; + className?: string; + containerClassName?: string; + mediaClassname?: string; + isLoading?: boolean; + fallbackContent?: React.ReactNode; + shouldListenForLoad?: boolean; +} +``` + +| パラメータ | 型 | 説明 | | +| --------------------- | ----------------- | ---------------------------------------- | ---------------------------------------- | +| `name` | `string` | オプション。画像の alt テキストとして使われるコレクティブル名 | | +| `assets` | \`(string | undefined)\[]\` | 読み込みを試みるアセットURLの配列。順番に読み込み、成功したものを表示します。 | +| `assetSrcPrefixUrl` | `string` | アセットURLの先頭に付加するオプションのURLプレフィックス | | +| `className` | `string` | コンポーネントコンテナ用のオプションCSSクラス名 | | +| `containerClassName` | `string` | 外側コンテナ用のオプションCSSクラス名 | | +| `mediaClassname` | `string` | メディア要素自体のオプションCSSクラス名 | | +| `isLoading` | `boolean` | オプション。ローディング状態を表示するフラグ | | +| `fallbackContent` | `React.ReactNode` | すべてのアセットが読み込めない場合に表示するカスタムコンテンツ(オプション) | | +| `shouldListenForLoad` | `boolean` | 読み込みイベントリスナーの有効/無効を切り替えるフラグ(デフォルトは true) | | + +## 対応メディアタイプ +Media コンポーネントは自動的にさまざまなコンテンツタイプを判別・処理します: +- **画像**:標準的な画像ファイル(PNG、JPG、GIFなど)を表示 +- **動画**:自動再生・ループ・コントロール付きで動画ファイルをサポート +- **3Dモデル**:ModelViewer コンポーネントで 3D モデルを表示 +- **HTML**:サンドボックス化された iframe で HTML コンテンツを表示 + +## 特徴 + +### 自動コンテンツタイプ判定 +コンポーネントはアセットのコンテンツタイプを自動判定し、適切な要素を表示します。 + +```tsx + +``` + +### フォールバックチェーン +アセットの読み込みに失敗した場合、コンポーネントは: +1. assets 配列の次のアセットを試します +2. すべてのアセットが失敗した場合、カスタムフォールバックコンテンツを表示します +3. フォールバックコンテンツが指定されていない場合、デフォルトのチェスタイルパターンを表示します + +### ローディング状態 +コンポーネントには組み込みのローディング状態があります。 + +```tsx + +``` + +## 補足 +`Media` コンポーネントは、コレクティブルアセットのさまざまなタイプに対応し、以下の機能を備えています: +- 自動コンテンツタイプ判定 +- フォールバック処理 +- ローディング状態の管理 +- Safari 互換性への調整 + +動画コンテンツを使用する際の注意点: +- 動画はデフォルトで自動再生されます +- 自動再生互換性のため、動画はデフォルトでミュートされます \ No newline at end of file diff --git a/sdk/marketplace-sdk/components/CollectibleCard.mdx b/sdk/marketplace-sdk/components/CollectibleCard.mdx new file mode 100644 index 00000000..19b06d19 --- /dev/null +++ b/sdk/marketplace-sdk/components/CollectibleCard.mdx @@ -0,0 +1,457 @@ +--- +title: "CollectibleCard" +description: "A versatile card component for displaying collectibles in marketplace and shop contexts" +sidebarTitle: "CollectibleCard" +--- + +## Import + +```tsx +import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; +``` + +## Usage + +### Data Hooks + +The SDK provides specialized hooks to fetch and format data for the CollectibleCard component: + +#### Market Cards + +```tsx +import { useListMarketCardData } from "@0xsequence/marketplace-sdk/react"; + +const { + collectibleCards, + isLoading, + hasNextPage, + isFetchingNextPage, + fetchNextPage, +} = useListMarketCardData({ + orderbookKind, + collectionType, + filterOptions, + searchText, + showListedOnly, + collectionAddress, + chainId, +}); +``` + +#### Shop Cards + +For shop cards, there are two hooks based on the contract type: + +```tsx +// For ERC721 tokens +import { useList721ShopCardData } from "@0xsequence/marketplace-sdk/react"; + +const { collectibleCards, isLoading } = useList721ShopCardData({ + primarySaleItemsWithMetadata, + chainId, + contractAddress, + salesContractAddress, + enabled: contractType === ContractType.ERC721, +}); + +// For ERC1155 tokens +import { useList1155ShopCardData } from "@0xsequence/marketplace-sdk/react"; + +const { collectibleCards, isLoading } = useList1155ShopCardData({ + chainId, + contractAddress, + salesContractAddress, + enabled: contractType === ContractType.ERC1155, + primarySaleItemsWithMetadata, +}); +``` + +These hooks handle: + +- Data fetching and formatting +- Loading states +- Pagination (for market cards) +- Type-specific data requirements +- Integration with filters and search + +### Examples + + + + Example of using the CollectibleCard component in a marketplace context: + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function MarketExample() { + return ( + { + console.log(`Clicked collectible ${tokenId}`); + }} + /> + ); + } + ``` + + + + Example showing the CollectibleCard in a shop context: + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function ShopExample() { + return ( + + ); + } + ``` + + + + Example demonstrating offer functionality: + + + +![Collectible Card with Offers](/images/marketplace/collectible_card_with_offer.png "Collectible Card with Offers") + + + + ```tsx + import { CollectibleCard } from "@0xsequence/marketplace-sdk/react"; + + export default function OffersExample() { + return ( + { + console.log('Offer clicked', order); + e.preventDefault(); + }} + onCannotPerformAction={(action) => { + console.log(`Cannot perform action: ${action}`); + }} + /> + ); + } + ``` + + + + +## Parameters + +The component accepts different props based on the marketplace type: + +### Base Props + +These properties are shared by all card types: + +```tsx +interface MarketplaceCardBaseProps { + collectibleId: string; + chainId: number; + collectionAddress: Address; + collectionType?: ContractType; + assetSrcPrefixUrl?: string; + cardLoading?: boolean; + marketplaceType?: MarketplaceType; + isTradable?: boolean; +} +``` + +| Parameter | Type | Description | +| ------------------- | ----------------- | -------------------------------------------------- | +| `collectibleId` | `string` | Unique identifier for the collectible | +| `chainId` | `number` | The blockchain network ID | +| `collectionAddress` | `Address` | The smart contract address of the collection | +| `collectionType` | `ContractType` | Optional. The type of contract (ERC721 or ERC1155) | +| `assetSrcPrefixUrl` | `string` | Optional URL prefix for asset sources | +| `cardLoading` | `boolean` | Optional flag to show loading state | +| `marketplaceType` | `MarketplaceType` | Optional. Type of marketplace ('market' or 'shop') | +| `isTradable` | `boolean` | Optional flag indicating if the item can be traded | + +### Shop Card Props + +Additional properties for shop cards (`marketplaceType="shop"`): + +```tsx +interface ShopCardSpecificProps { + salesContractAddress: Address; + tokenMetadata: TokenMetadata; + salePrice?: { + amount: string; + currencyAddress: Address; + }; + saleStartsAt?: string; + saleEndsAt?: string; + quantityDecimals?: number; + quantityInitial?: string; + quantityRemaining?: string; + unlimitedSupply?: boolean; +} +``` + +| Parameter | Type | Description | +| ---------------------- | --------------- | --------------------------------------------------------- | +| `salesContractAddress` | `Address` | The address of the sales contract | +| `tokenMetadata` | `TokenMetadata` | Metadata for the token including name, description, image | +| `salePrice` | `object` | Optional. Price information including amount and currency | +| `saleStartsAt` | `string` | Optional. Sale start timestamp | +| `saleEndsAt` | `string` | Optional. Sale end timestamp | +| `quantityDecimals` | `number` | Optional. Number of decimals for quantity | +| `quantityInitial` | `string` | Optional. Initial supply amount | +| `quantityRemaining` | `string` | Optional. Remaining supply amount | +| `unlimitedSupply` | `boolean` | Optional. Whether the supply is unlimited | + +### Market Card Props + +Additional properties for market cards (`marketplaceType="market"`): + +```tsx +interface MarketCardSpecificProps { + orderbookKind?: OrderbookKind; + collectible?: CollectibleOrder; + onCollectibleClick?: (tokenId: string) => void; + onOfferClick?: (params: { + order?: Order; + e: React.MouseEvent; + }) => void; + balance?: string; + balanceIsLoading: boolean; + onCannotPerformAction?: (action: CollectibleCardAction) => void; + prioritizeOwnerActions?: boolean; +} +``` + +| Parameter | Type | Description | +| ------------------------ | ------------------ | --------------------------------------------------- | +| `orderbookKind` | `OrderbookKind` | Optional. Type of orderbook | +| `collectible` | `CollectibleOrder` | Optional. Collectible order information | +| `onCollectibleClick` | `function` | Optional. Handler for collectible click events | +| `onOfferClick` | `function` | Optional. Handler for offer click events | +| `balance` | `string` | Optional. User's balance of this collectible | +| `balanceIsLoading` | `boolean` | Whether the balance is currently loading | +| `onCannotPerformAction` | `function` | Optional. Handler for unauthorized actions | +| `prioritizeOwnerActions` | `boolean` | Optional. Whether to prioritize owner actions in UI | + +## Features + +### Card Variants + +The component supports two main variants: + +1. **Market Card**: Used for displaying collectibles in a marketplace context with: + + - Current listing price + - Highest offer indicator + - Balance/ownership information + - Buy/Offer actions + +2. **Shop Card**: Used for primary sales with: + - Sale price + - Supply information + - Sale status + - Purchase actions + +### Automatic Type Detection + +The component automatically handles different token standards: + +- ERC-721 (Non-fungible tokens) +- ERC-1155 (Semi-fungible tokens) + +### Loading States + +Built-in loading states are provided: + +```tsx + +``` + +### Price Formatting + +The component includes sophisticated price formatting with: + +- Currency symbol display +- Overflow/underflow indicators +- Support for various token decimals +- "Free" indicator for zero prices + +## Integration Examples + +### Market Content Integration + +Here's a complete example of integrating the CollectibleCard in a marketplace context: + +```tsx +import { + CollectibleCard, + useListMarketCardData, +} from "@0xsequence/marketplace-sdk/react"; + +export function MarketContent({ + collectionAddress, + chainId, + onCollectibleClick, +}) { + const { + collectibleCards, + isLoading, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + } = useListMarketCardData({ + orderbookKind, + collectionType, + filterOptions, + searchText, + showListedOnly, + collectionAddress, + chainId, + }); + + return ( +
+ {collectibleCards.map((card, index) => ( + + ))} +
+ ); +} +``` + +### Shop Content Integration + +Example of integrating the CollectibleCard in a shop context with contract type handling: + +```tsx +import { + CollectibleCard, + useList721ShopCardData, + useList1155ShopCardData, +} from "@0xsequence/marketplace-sdk/react"; + +export function ShopContent({ + saleContractAddress, + collectionAddress, + chainId, + onCollectibleClick, +}) { + // Choose hook based on contract type + const { collectibleCards, isLoading } = + contractType === ContractType.ERC721 + ? useList721ShopCardData({ + primarySaleItemsWithMetadata, + chainId, + contractAddress: collectionAddress, + salesContractAddress: saleContractAddress, + enabled: true, + }) + : useList1155ShopCardData({ + chainId, + contractAddress: collectionAddress, + salesContractAddress: saleContractAddress, + enabled: true, + primarySaleItemsWithMetadata, + }); + + return ( +
+ {collectibleCards.map((card, index) => ( + + ))} +
+ ); +} +``` + +## Notes + +The `MarketplaceCollectibleCard` component is designed to handle various marketplace scenarios with: + +- Responsive layout +- Loading states +- Price formatting +- Supply tracking +- Action handling +- Owner-specific features +- Offer management + +When using with ERC-1155 tokens, note that: + +- Balance is displayed as "Owned: X" format +- Supply information is shown for shop items +- Quantity tracking is supported + +### Best Practices + +1. **Data Fetching** + + - Use the appropriate data hook based on your context (market/shop) and contract type (ERC721/ERC1155) + - Enable conditional fetching using the `enabled` prop when necessary + - Handle loading states appropriately + +2. **Event Handling** + + - Implement click handlers for both the card and specific actions (buy, offer) + - Use the `onCannotPerformAction` callback to handle unauthorized actions + +3. **Display** + - Wrap cards in buttons for clickable behavior + - Use appropriate className for layout and spacing + - Consider implementing infinite scroll or pagination for large collections diff --git a/sdk/marketplace-sdk/components/Media.mdx b/sdk/marketplace-sdk/components/Media.mdx new file mode 100644 index 00000000..5ba03a1b --- /dev/null +++ b/sdk/marketplace-sdk/components/Media.mdx @@ -0,0 +1,173 @@ +--- +title: "Media" +description: "Component for displaying various types of collectible assets" +sidebarTitle: "Media" +--- + +## Import + +```tsx +import { Media } from "@0xsequence/marketplace-sdk/react"; +``` + +## Usage + +### Examples + + + + Basic example of using the Media component to display an image: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function BasicExample() { + return ( + + ); + } + ``` + + + + Example showing how to handle multiple assets with fallback: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function MultipleAssetsExample() { + return ( + + ); + } + ``` + + + + Example with a custom fallback component: + + ```tsx + import { Media } from "@0xsequence/marketplace-sdk/react"; + + export default function CustomFallbackExample() { + const CustomFallback = () => ( +
+

Asset not available

+
+ ); + + return ( + } + /> + ); + } + ``` + +
+
+ +## Parameters + +The component accepts the following props: + +```tsx +interface MediaProps { + name?: string; + assets: (string | undefined)[]; + assetSrcPrefixUrl?: string; + className?: string; + containerClassName?: string; + mediaClassname?: string; + isLoading?: boolean; + fallbackContent?: React.ReactNode; + shouldListenForLoad?: boolean; +} +``` + +| Parameter | Type | Description | +| --------------------- | ------------------------- | ------------------------------------------------------------------------------------------------------------- | +| `name` | `string` | Optional name for the collectible, used as alt text for images | +| `assets` | `(string \| undefined)[]` | Array of asset URLs to try loading. The component will attempt to load each asset in order until one succeeds | +| `assetSrcPrefixUrl` | `string` | Optional URL prefix to prepend to asset URLs | +| `className` | `string` | Optional CSS class name for the component container | +| `containerClassName` | `string` | Optional CSS class name for the outer container | +| `mediaClassname` | `string` | Optional CSS class name for the media element itself | +| `isLoading` | `boolean` | Optional flag to show loading state | +| `fallbackContent` | `React.ReactNode` | Optional custom content to display when no assets can be loaded | +| `shouldListenForLoad` | `boolean` | Optional flag to enable/disable load event listeners (defaults to true) | + +## Supported Media Types + +The Media component automatically detects and handles different types of content: + +- **Images**: Renders standard image files (PNG, JPG, GIF, etc.) +- **Videos**: Supports video files with autoplay, loop, and controls +- **3D Models**: Renders 3D models using ModelViewer component +- **HTML**: Displays HTML content in a sandboxed iframe + +## Features + +### Automatic Content Type Detection + +The component automatically detects the content type of the asset and renders the appropriate element: + +```tsx + +``` + +### Fallback Chain + +If an asset fails to load, the component will: + +1. Try the next asset in the assets array +2. If all assets fail, display the custom fallback content +3. If no fallback content is provided, show the default chess tile pattern + +### Loading States + +The component includes built-in loading states: + +```tsx + +``` + +## Notes + +The `Media` component is designed to handle various types of collectible assets with built-in: + +- Automatic content type detection +- Fallback handling +- Loading states +- Safari compatibility adjustments + +When using with video content, note that: + +- Videos autoplay by default +- Videos are muted by default for autoplay compatibility