UNPKG

admesh-ui-sdk

Version:

Beautiful, modern React components for displaying AI-powered product recommendations with citation-based conversation ads, auto-triggered widgets, floating chat, conversational interfaces, persistent sidebar, and built-in tracking. Includes zero-code SDK

1,702 lines (1,386 loc) 50.2 kB
# AdMesh UI SDK [![npm version](https://badge.fury.io/js/admesh-ui-sdk.svg)](https://www.npmjs.com/package/admesh-ui-sdk) [![npm downloads](https://img.shields.io/npm/dm/admesh-ui-sdk.svg)](https://www.npmjs.com/package/admesh-ui-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) [![TypeScript](https://img.shields.io/badge/TypeScript-5.8-blue.svg)](https://www.typescriptlang.org/) [![React](https://img.shields.io/badge/React-18%2B%20%7C%2019%2B-blue.svg)](https://react.dev/) A comprehensive React + TypeScript component library for displaying AdMesh product recommendations across all ad unit formats with built-in tracking, theming, and accessibility support. **📦 Install from npm**: `npm install admesh-ui-sdk` ## 🌐 Live Sites - **🎭 Interactive Storybook**: [https://storybook.useadmesh.com/](https://storybook.useadmesh.com/) - Explore all components and ad formats - **📚 Complete Documentation**: [https://docs.useadmesh.com/](https://docs.useadmesh.com/) - Full SDK documentation and guides - **🚀 AdMesh Dashboard**: [https://useadmesh.com](https://useadmesh.com) - Get your API keys and manage campaigns - **📦 npm Package**: [https://www.npmjs.com/package/admesh-ui-sdk](https://www.npmjs.com/package/admesh-ui-sdk) - Install from npm registry > **🎨 Component Showcase**: This repository contains the UI SDK components with an interactive Storybook for exploring all ad formats and components. ## 🚀 Features - **Complete Ad Unit Library** - All AdMesh ad formats in one unified SDK - **Citation-Based Conversation Ads** - Display recommendations as numbered references within text - **Conversational Ad Units** - Perfect for chat interfaces, AI assistants, and conversational experiences - **Floating & Auto Widgets** - Non-intrusive recommendation displays - **Expandable Units** - Rich, interactive product showcases - **Built-in Tracking** - Automatic click, view, and conversion tracking - **Intelligent Layouts** - Auto-selects optimal layout based on intent and data - **Advanced Customization** - Complete freedom over colors, icons, fonts, and styling - **Theme System** - Enhanced theming with presets, dark mode, and component overrides - **TypeScript First** - Full type safety and IntelliSense support - **Framework Agnostic** - React core, but designed for easy embedding - **Responsive Design** - Mobile-first responsive components - **Accessibility** - WCAG 2.1 AA compliant - **Weave Mode** - Automatic link detection and enhancement for organic LLM responses - **Performance Optimized** - 97% faster link detection with CSS selector optimization - **Multi-Domain Support** - Works with `api.useadmesh.com` and `*.useadmesh.com` domains ## 📦 Installation ```bash npm install admesh-ui-sdk ``` ### Supported Domains The SDK automatically detects and enhances links from: - **`api.useadmesh.com/click/*`** - Standard AdMesh domain - **`*.useadmesh.com/click/*`** - Any subdomain (e.g., `tracking.useadmesh.com`, `custom.useadmesh.com`) ### Requirements - **Node.js**: 16.0.0 or higher - **npm**: 8.0.0 or higher - **React**: 18.0.0 or 19.0.0 - **React DOM**: 18.0.0 or 19.0.0 ## 🚀 Zero-Code Integration (Recommended for Platforms) The AdMesh SDK provides a **zero-code integration experience** that handles everything automatically. Perfect for platforms that want to add monetized recommendations without writing custom code. ### 3-Step Integration **Step 1: Install the SDK** ```bash npm install admesh-ui-sdk ``` **Step 2: Add a container element** ```html <!-- Place this div where you want recommendations to appear --> <div id="admesh-recommendations"></div> ``` **Step 3: Initialize and fetch recommendations** ```typescript import { AdMeshSDK } from 'admesh-ui-sdk'; // Initialize once with your API key const admesh = new AdMeshSDK({ apiKey: 'your-api-key-here' }); // Generate session and message IDs on your platform const sessionId = AdMeshSDK.createSession(); const messageId = AdMeshSDK.createMessageId(sessionId); // Fetch and render recommendations automatically await admesh.showRecommendations({ query: userQuery, containerId: 'admesh-recommendations', format: 'auto', // optional: auto-detects best format session_id: sessionId, message_id: messageId }); ``` ### Complete Example ```typescript import { AdMeshSDK } from 'admesh-ui-sdk'; const admesh = new AdMeshSDK({ apiKey: 'admesh_prod_your_key_here' }); // When user searches or asks a question async function handleUserQuery(query: string, sessionId: string, messageId: string) { try { await admesh.showRecommendations({ query: query, containerId: 'admesh-recommendations', format: 'auto', session_id: sessionId, message_id: messageId }); } catch (error) { console.error('Failed to fetch recommendations:', error); } } // Initialize session when conversation starts const sessionId = AdMeshSDK.createSession(); // Generate message ID for each query const messageId = AdMeshSDK.createMessageId(sessionId); // Handle user query await handleUserQuery('best CRM for small business', sessionId, messageId); ``` ### Session Management The SDK is **stateless** regarding session management. Your platform is responsible for: - **Creating Sessions**: Use `AdMeshSDK.createSession()` to generate a session ID - **Creating Message IDs**: Use `AdMeshSDK.createMessageId(sessionId)` to generate message IDs - **Storing Sessions**: Store session IDs in your platform's storage (localStorage, database, etc.) - **Passing IDs to SDK**: Provide `session_id` and `message_id` when calling `showRecommendations()` ```typescript // Generate IDs on your platform const sessionId = AdMeshSDK.createSession(); const messageId = AdMeshSDK.createMessageId(sessionId); // Store in your platform's storage localStorage.setItem('admesh_session_id', sessionId); // Pass to SDK when fetching recommendations await admesh.showRecommendations({ query: userQuery, containerId: 'admesh-recommendations', session_id: sessionId, message_id: messageId }); ``` ### Configuration Options ```typescript const admesh = new AdMeshSDK({ apiKey: 'your-api-key', // Required theme: { // Optional: customize appearance mode: 'light', primaryColor: '#3b82f6', borderRadius: '8px' } }); ``` ### What the SDK Handles Automatically - ✅ API authentication with your API key - ✅ Recommendation fetching from `/agent/recommend` endpoint - ✅ Automatic rendering with appropriate UI components - ✅ Exposure tracking (when recommendations are shown) - ✅ Click tracking (when users click recommendations) - ✅ Conversion tracking (when users complete actions) - ✅ Error handling and logging - ✅ Responsive design and theming ### What Your Platform Handles - ✅ Session creation and storage (use `AdMeshSDK.createSession()`) - ✅ Message ID generation (use `AdMeshSDK.createMessageId(sessionId)`) - ✅ Session persistence across page reloads - ✅ Session lifecycle management (when to create new sessions) ### Advanced: Custom Styling For custom styling needs, use the `showRecommendations()` method with the `theme` option: ```typescript await admesh.showRecommendations({ query: 'best CRM for small business', containerId: 'recommendations', format: 'product', session_id: sessionId, message_id: messageId, theme: { mode: 'dark', colors: { primary: '#007bff', secondary: '#6c757d' } } }); ``` ## ✨ Self-Contained Design **Zero configuration required!** The AdMesh UI SDK is completely self-contained and works like Google Ads or any professional SDK: - ✅ **No Tailwind CSS setup needed** - All styles are automatically injected - ✅ **No external CSS imports required** - Works out of the box in any React app - ✅ **No build configuration changes** - Just install and use - ✅ **Platform independent** - Consistent appearance across all applications - ✅ **Zero dependencies** - Only requires React and ReactDOM as peer dependencies The SDK automatically injects all necessary styles when components are rendered, ensuring consistent appearance regardless of your application's CSS framework, Tailwind configuration, or styling approach. ## 🎯 Quick Start ### AdMeshLayout Component (Recommended) ```tsx import React from 'react'; import { AdMeshLayout } from 'admesh-ui-sdk'; // No CSS import needed! Styles are auto-injected ✨ const recommendations = [ { title: "HubSpot CRM", reason: "Perfect for remote teams with excellent collaboration features", intent_match_score: 0.92, admesh_link: "https://useadmesh.com/track?ad_id=hubspot-123", ad_id: "hubspot-123", product_id: "hubspot-crm", has_free_tier: true, trial_days: 14, keywords: ["CRM", "Sales", "Marketing"] } ]; function App() { return ( <div> <h1>My AI Application</h1> {/* AdMesh layout - auto-detects best format */} <AdMeshLayout recommendations={recommendations} layout="auto" maxItems={6} onRecommendationClick={(adId, admeshLink) => { window.open(admeshLink, '_blank'); }} /> </div> ); } ``` ### Specific Layout Examples ```tsx // Citation layout for AI conversations <AdMeshLayout recommendations={recommendations} conversationText="Based on your startup needs, I recommend HubSpot CRM for its excellent free tier..." layout="citation" /> // Ecommerce layout for product grids <AdMeshLayout ecommerceProducts={products} layout="ecommerce" title="Featured Products" /> // Grid layout for recommendation cards <AdMeshLayout recommendations={recommendations} layout="grid" columns={3} spacing="lg" title="Recommended Solutions" /> ``` ## 📋 Component Comparison Choose the right component for your use case: | Component | Best For | Display Style | Integration Complexity | Mobile Optimized | |-----------|----------|---------------|----------------------|------------------| | **AdMeshLayout** | All use cases | Auto-adaptive | ⭐ Easy | ✅ Yes | | **AdMeshProductCard** | Individual products | Single card | ⭐ Easy | ✅ Yes | | **AdMeshEcommerceCards** | Product carousels | Horizontal scroll | ⭐ Easy | ✅ Yes | ## 🎯 AdMeshLayout **AdMeshLayout** is the recommended component that automatically combines and optimizes all other components: - **Auto-Detection**: Automatically chooses the best layout based on your content - **Multiple Layouts**: Citation, ecommerce, grid, list, and mixed layouts - **Single API**: One component handles all recommendation types - **Smart Optimization**: Automatically limits items and optimizes for mobile - **Customizable**: Full control over layout, spacing, and component behavior - **FTC Compliance**: Includes proper "Sponsored", "Sponsored", and "" disclosures ### Default Configuration - **Default numberOfItems**: 1 for layout components, 3 for ecommerce - **Single Item Layout**: When numberOfItems is 1, card displays at 100% width - **Disclosure Handling**: Only AdMeshLayout shows disclosures - individual components are disclosure-free The **AdMeshLayout** component is the recommended way to display AdMesh recommendations. It automatically detects the best layout based on your content and provides a single API for all recommendation types. ```tsx import { AdMeshLayout } from 'admesh-ui-sdk'; // Auto-detection (recommended) - defaults to 1 item for layout, 3 for ecommerce <AdMeshLayout recommendations={recommendations} ecommerceProducts={products} conversationText="Based on your needs..." layout="auto" // maxItems defaults: 1 for layout, 3 for ecommerce /> // Specific layouts with custom maxItems <AdMeshLayout layout="citation" recommendations={recs} conversationText="..." /> <AdMeshLayout layout="ecommerce" ecommerceProducts={products} maxItems={3} /> <AdMeshLayout layout="grid" recommendations={recs} maxItems={1} columns={1} /> <AdMeshLayout layout="list" recommendations={recs} maxItems={1} /> <AdMeshLayout layout="mixed" recommendations={recs} ecommerceProducts={products} /> ``` **Layout Types:** - **`auto`**: Automatically detects best layout based on content - **`citation`**: Direct links within conversation text - **`ecommerce`**: Horizontal scrolling product grid - **`grid`**: Responsive grid of recommendation cards - **`list`**: Vertical list of simplified cards - **`mixed`**: Combines multiple component types **Key Features:** - **Smart Auto-Detection**: Chooses optimal layout automatically - **Responsive Design**: Adapts to all screen sizes - **Customizable**: Control columns, spacing, titles, and behavior - **Component Props**: Pass props to underlying components - **Event Handling**: Unified click and hover handlers ## 📋 Individual Components > **Note**: Individual components no longer display disclosure elements (Match Score, "Sponsored", ""). Only AdMeshLayout includes FTC-compliant disclosures. Use AdMeshLayout for platform integration. ### Core Components #### AdMeshProductCard Individual product recommendation card with rich information display. ```tsx // Default clean minimal design (recommended) <AdMeshProductCard recommendation={recommendation} showMatchScore={false} // Deprecated - Match Score removed from UI showBadges={true} showFeatures={false} // Default: clean minimal design onClick={(adId, admeshLink) => window.open(admeshLink)} /> // With features for detailed showcases <AdMeshProductCard recommendation={recommendation} showFeatures={true} // Show key features section onClick={(adId, admeshLink) => window.open(admeshLink)} /> ``` **Props:** - `showFeatures` (boolean, default: false) - Whether to display the key features section. Default is clean minimal design. - `showBadges` (boolean, default: true) - Whether to show product badges - `showMatchScore` (boolean, default: false) - Deprecated, match score removed from UI #### AdMeshEcommerceCards Horizontal scrolling product cards for ecommerce recommendations, similar to Google product search results. ```tsx <AdMeshEcommerceCards products={ecommerceProducts} title="Recommended Laptops" showPricing={true} showRatings={true} showBrand={true} cardWidth="md" maxCards={10} onProductClick={(product) => window.open(product.admesh_link || product.url)} /> ``` **Perfect for:** - Product search results - Ecommerce recommendations - Mixed AdMesh + Walmart/Amazon products - Google-style product carousels - Shopping comparison displays ### Summary Components #### AdMeshSummaryUnit Display recommendations with summary text and follow-up suggestions. ```tsx <AdMeshSummaryUnit recommendations={recommendations} summary="Here are the best CRM tools for your needs" followupSuggestions={[ { label: "Compare pricing", query: "CRM pricing comparison" }, { label: "Free trials", query: "CRM free trial options" } ]} onRecommendationClick={(adId, link) => window.open(link)} onFollowupClick={(query) => console.log('Follow-up:', query)} /> ``` #### AdMeshSummaryLayout Layout component for displaying summary-style recommendations. ```tsx <AdMeshSummaryLayout recommendations={recommendations} summary="Based on your requirements, here are the top recommendations" layout="grid" // 'grid' | 'list' showFollowups={true} /> ``` **Perfect for:** - AI assistant responses - Conversation summaries - Follow-up suggestions - End-of-conversation recommendations #### AdMeshInlineCard Compact inline recommendation component perfect for chat interfaces. ```tsx <AdMeshInlineCard recommendation={recommendation} compact={true} showReason={true} onClick={(adId, link) => window.open(link)} /> ``` ### Additional Components #### AdMeshProductCard - Simple Variation Simple, clean ad format for minimal integration. ```tsx <AdMeshProductCard recommendation={recommendation} variation="simple" // Creates inline ad format onClick={(adId, admeshLink) => window.open(admeshLink)} /> ``` ### 🔧 Utility Components #### AdMeshBadge Reusable badge component for highlighting features. #### AdMeshLinkTracker Wrapper for tracking any clickable element with built-in analytics. ```tsx <AdMeshLinkTracker adId={recommendation.ad_id} admeshLink={recommendation.admesh_link} productId={recommendation.product_id} onClick={() => handleClick()} trackingData={{ title: recommendation.title }} > <YourCustomComponent /> </AdMeshLinkTracker> ``` ## 🎨 Advanced Customization & Theming The AdMesh UI SDK provides **complete freedom** for AI platforms to customize colors, icons, fonts, and styling to match their brand perfectly. ### Consistent Design System The AdMesh UI SDK ensures consistent styling across all components: - **🎨 Unified Colors & Themes**: All components share the same color palette and theme system - **📝 Consistent Fonts**: All components use the same font family for visual consistency - **📐 Standardized Width**: 100% width for all components except ecommerce cards (which maintain horizontal scrolling) - **📱 Responsive Design**: Mobile-friendly and adaptive across all screen sizes - **🌙 Dark Mode Support**: Seamless light/dark mode transitions with consistent styling ### Enhanced Theme System ```tsx import { createAdMeshTheme, themePresets } from 'admesh-ui-sdk'; // Custom brand colors with automatic consistency const customTheme = createAdMeshTheme({ mode: 'light', primaryColor: '#ff6b6b', // Your brand color secondaryColor: '#4ecdc4', // Secondary brand color accentColor: '#45b7d1', // Accent color borderRadius: '16px', // Custom border radius fontFamily: '"Poppins", sans-serif', // Applied consistently across all components // Custom icons (emoji or React components) icons: { starIcon: '🌟', expandIcon: '▼', collapseIcon: '▲' }, // Component-specific overrides (width settings are automatically applied) components: { button: { backgroundColor: '#custom-color', borderRadius: '12px' } // Width settings are automatically applied: // - productCard: { width: '100%' } // - citationUnit: { width: '100%' } // - inlineRecommendation: { width: '100%' } // - ecommerce cards maintain auto width for horizontal scrolling } }); <AdMeshProductCard recommendations={recommendations} theme={customTheme} /> ``` ### Preset Themes ```tsx // Use built-in presets <AdMeshProductCard theme={themePresets.minimal} /> <AdMeshProductCard theme={themePresets.vibrant} /> <AdMeshProductCard theme={themePresets.corporate} /> ``` ### Dark Mode ```tsx import { createDarkTheme } from 'admesh-ui-sdk'; const darkTheme = createDarkTheme({ primaryColor: '#a78bfa', secondaryColor: '#34d399' }); ``` ## 📊 Unified Recommendation JSON Response All AdMesh ad units use the same unified recommendation response structure. This ensures consistency across all components and makes integration seamless. ### Complete Recommendation Object ```typescript interface AdMeshRecommendation { // Core required fields title: string; // Product/service title reason: string; // Why this is recommended intent_match_score: number; // 0-1 normalized match score admesh_link: string; // Tracking URL for clicks ad_id: string; // Unique ad identifier product_id: string; // Unique product identifier // Core product/offer fields url?: string; // Direct product URL redirect_url?: string; // Alternative redirect URL description?: string; // Product description pricing?: string; // Pricing information reward_note?: string | null; // Special offers/rewards keywords?: string[]; // Product keywords categories?: string[]; // Product categories features?: string[]; // Key features list integrations?: string[]; // Integration capabilities has_free_tier?: boolean; // Free tier availability trial_days?: number; // Trial period length audience_segment?: string; // Target audience is_ai_powered?: boolean; // AI-powered product flag is_open_source?: boolean; // Open source flag offer_trust_score?: number; // Offer trust rating (0-1) brand_trust_score?: number; // Brand trust rating (0-1) // Marketing content fields (for rich ad units) recommendation_title?: string; // Marketing-optimized title recommendation_description?: string; // Marketing-optimized description offer_images?: Array<{ // Promotional images url: string; storage_path: string; filename: string; content_type: string; dimensions: { width: number; height: number; }; }>; product_logo?: { // Product logo url: string; storage_path: string; filename: string; content_type: string; dimensions: { width: number; height: number; }; }; feature_sections?: Array<{ // Feature sections for expandable units title: string; description: string; icon: string; }>; // Extended compatibility fields reviews_summary?: string; // User reviews summary security?: string[]; // Security features support?: string[]; // Support options badges?: string[]; // Display badges } ``` ### API Response Structure ```typescript interface AgentRecommendationResponse { session_id: string; intent: { goal: string; intent_group: string; purchase_intent: string; intent_type: string; layout_type: string; categories: string[]; }; response: { summary: string; recommendations: AdMeshRecommendation[]; followup_suggestions: Array<{ label: string; query: string; }>; layout_type: string; }; tokens_used: number; model_used: string; } ``` ### Usage Across All Ad Units The same recommendation object works seamlessly across all ad unit types: ```tsx // Same recommendations for all components const recommendations: AdMeshRecommendation[] = [ { title: "HubSpot CRM", reason: "Perfect for remote teams with excellent collaboration features", intent_match_score: 0.92, admesh_link: "https://useadmesh.com/track?ad_id=hubspot-123", ad_id: "hubspot-123", product_id: "hubspot-crm", has_free_tier: true, trial_days: 14, keywords: ["CRM", "Sales", "Marketing"], pricing: "Free tier available, paid plans from $45/month", // ... additional fields as needed } ]; // Use with any ad unit {recommendations.map(rec => <AdMeshProductCard key={rec.ad_id} recommendation={rec} />)} <AdMeshLayout recommendations={recommendations} layout="auto" /> <AdMeshEcommerceCards recommendations={recommendations} /> ``` ## 🎯 Layout-Based Integration The AdMeshLayout component automatically adapts to different contexts and use cases. ### Quick Start - Layout Component ```tsx import React from 'react'; import { AdMeshLayout } from 'admesh-ui-sdk'; const recommendations = [ { product_id: "hubspot-crm", title: "HubSpot CRM", recommendation_description: "Perfect for remote teams with excellent collaboration features", admesh_link: "https://useadmesh.com/track?ad_id=hubspot-123", categories: ["CRM", "Sales", "Marketing"], trust_score: 95.0, meta: { ad_id: "hubspot-123", intent_match_score: 92.0, reason: "Perfect for remote teams with excellent collaboration features" } } ]; function RecommendationDisplay() { return ( <div className="recommendations-container"> <AdMeshLayout response={{ layout_type: 'auto', recommendations: recommendations }} /> </div> ); } ``` ### Layout Types #### Auto Layout Automatically selects the best layout based on content and context: ```tsx <AdMeshLayout recommendations={recommendations} layout="auto" /> ``` #### Grid Layout Displays recommendations in a responsive grid format: ```tsx <AdMeshLayout recommendations={recommendations} layout="grid" /> ``` #### List Layout Displays recommendations in a vertical list format: ```tsx <AdMeshLayout recommendations={recommendations} layout="list" /> ``` #### Citation Layout Displays recommendations as inline citations within text: ```tsx <AdMeshLayout recommendations={recommendations} layout="citation" /> ``` ### Individual Components #### AdMeshInlineCard Compact inline recommendations for chat interfaces: ```tsx import { AdMeshInlineCard } from 'admesh-ui-sdk'; <AdMeshInlineCard recommendation={recommendation} compact={true} showReason={true} onClick={(adId, link) => window.open(link)} /> ``` #### AdMeshBadge Reusable badge component for highlighting features and trust indicators: ```tsx import { AdMeshBadge } from 'admesh-ui-sdk'; <AdMeshBadge type="trust" // 'trust' | 'feature' | 'promotion' variant="primary" // 'primary' | 'secondary' | 'success' size="small" // 'small' | 'medium' | 'large' text="Highly Trusted" /> ``` #### AdMeshLinkTracker Wrapper component for tracking clicks on any element: ```tsx import { AdMeshLinkTracker } from 'admesh-ui-sdk'; <AdMeshLinkTracker adId={recommendation.meta.ad_id} admeshLink={recommendation.admesh_link} productId={recommendation.product_id} onClick={() => handleClick()} trackingData={{ title: recommendation.title }} > <YourCustomComponent /> </AdMeshLinkTracker> ``` **Key Features:** - **Automatic Tracking**: Built-in click and view tracking - **Custom Elements**: Wrap any component for tracking - **Analytics Integration**: Seamless data collection - **Performance Optimized**: Minimal overhead ## 🎨 Theming and Customization The AdMesh UI SDK provides comprehensive theming capabilities for all components. ### Theme Configuration ```tsx import { createAdMeshTheme } from 'admesh-ui-sdk'; const customTheme = createAdMeshTheme({ mode: 'light', // 'light' | 'dark' accentColor: '#2563eb', borderRadius: '8px', fontFamily: 'Inter, sans-serif' }); <AdMeshLayout recommendations={recommendations} theme={customTheme} /> ``` ### Dark Mode Support ```tsx import { createDarkTheme } from 'admesh-ui-sdk'; const darkTheme = createDarkTheme({ accentColor: '#3b82f6' }); <AdMeshLayout recommendations={recommendations} theme={darkTheme} /> ``` ### Component Customization All components support custom styling through className and style props: ```tsx <AdMeshLayout recommendations={recommendations} className="my-custom-recommendations" style={{ backgroundColor: '#f8f9fa', borderRadius: '12px', padding: '16px' }} /> ``` ``` ### Integration Examples #### Chat Application ```tsx function ChatApp() { const [messages, setMessages] = useState([]); const [recommendations, setRecommendations] = useState([]); const handleUserMessage = async (message) => { // Add user message setMessages(prev => [...prev, { role: 'user', content: message }]); // Get AI response and recommendations const response = await getAIResponse(message); setMessages(prev => [...prev, { role: 'assistant', content: response.text }]); // Show recommendations if available if (response.recommendations) { setRecommendations(response.recommendations); } }; return ( <div className="chat-container"> {messages.map((msg, i) => ( <div key={i} className={`message ${msg.role}`}> {msg.content} {/* Show recommendations after assistant messages */} {msg.role === 'assistant' && recommendations.length > 0 && ( <AdMeshLayout recommendations={recommendations} layout="list" maxItems={2} /> )} </div> ))} </div> ); } <AdMeshProductCard theme={theme} recommendations={recommendations} /> ``` ## 💬 Chat Components Perfect for websites and applications that want to provide AI-powered recommendations through chat interfaces. ### Embedded Chat Interface ```tsx import React, { useState } from 'react'; import { AdMeshChatInterface } from 'admesh-ui-sdk'; function ChatPage() { const [messages, setMessages] = useState([]); const [isLoading, setIsLoading] = useState(false); const handleSendMessage = async (messageContent) => { // Add user message const userMessage = { id: `user-${Date.now()}`, role: 'user', content: messageContent, timestamp: new Date(), }; setMessages(prev => [...prev, userMessage]); setIsLoading(true); // Get AI response const response = await getAIResponse(messageContent); setMessages(prev => [...prev, response]); setIsLoading(false); }; return ( <div className="h-screen"> <AdMeshChatInterface messages={messages} config={{ placeholder: "Ask me about products...", enableTypingIndicator: true, maxMessages: 50 }} theme={{ mode: 'light' }} isLoading={isLoading} onSendMessage={handleSendMessage} onRecommendationClick={(adId, link) => window.open(link)} /> </div> ); } ``` ### Chat Features - **Embedded Interface**: Full chat interface for web applications - **Message History**: Persistent conversation state - **Typing Indicators**: Visual feedback during AI response generation - **Recommendation Display**: Inline product recommendations with tracking - **Theme Support**: Light/dark modes with custom branding ### Configuration Examples ```tsx // Embedded chat with message limit <AdMeshChatInterface config={{ maxMessages: 20, enableTypingIndicator: true, placeholder: "What can I help you find today?" }} /> ``` ## 🤖 Auto-Recommendations (AI Integration) ### Integration with AI Applications #### ChatGPT Plugin Integration ```tsx // When ChatGPT detects software-related queries const handleChatGPTResponse = (userQuery, gptResponse) => { if (containsSoftwareQuery(userQuery)) { const recommendations = await getAdMeshRecommendations(userQuery); showAutoRecommendations(recommendations, userQuery); } }; ``` #### Claude Integration ```tsx // When Claude processes business queries const handleClaudeQuery = async (query) => { const intent = await detectIntent(query); if (intent.category === 'software' || intent.category === 'tools') { const recommendations = await fetchRecommendations(intent); triggerAutoWidget(recommendations, query); } }; ``` ### Auto-Recommendation Features - **Zero User Input**: Automatically appears based on AI detection - **Contextual Triggers**: Shows why recommendations appeared - **Smart Positioning**: Non-intrusive placement options ## 📊 Tracking & Analytics All AdMesh UI components include comprehensive built-in tracking for views, clicks, and conversions. ### Automatic Tracking Every component automatically tracks: - **Views**: When recommendations are displayed - **Clicks**: When users click on recommendations - **Conversions**: When users complete desired actions ```tsx // All components automatically track interactions <AdMeshProductCard recommendations={recommendations} onProductClick={(adId, admeshLink) => { // This click is automatically tracked window.open(admeshLink, '_blank'); }} onTrackView={(data) => { // Optional: Custom view tracking console.log('Recommendation viewed:', data); }} /> ``` ### Global Tracking Configuration ```tsx import { setAdMeshTrackerConfig } from 'admesh-ui-sdk'; setAdMeshTrackerConfig({ enabled: true }); ``` ### Custom Tracking Use the `AdMeshLinkTracker` component for custom tracking: ```tsx import { AdMeshLinkTracker } from 'admesh-ui-sdk'; <AdMeshLinkTracker adId="custom-ad-123" admeshLink="https://useadmesh.com/track?ad_id=custom-ad-123" productId="product-456" trackingData={{ customField: 'value', source: 'custom-component' }} onClick={() => { // Your custom click handler console.log('Custom click tracked'); }} > <YourCustomComponent /> </AdMeshLinkTracker> ``` ### Tracking Events ```tsx import { useAdMeshTracker } from 'admesh-ui-sdk'; function CustomComponent() { const { trackClick, trackView, trackConversion } = useAdMeshTracker(); const handleCustomEvent = async () => { await trackClick({ adId: 'ad-123', admeshLink: 'https://useadmesh.com/track?ad_id=ad-123', productId: 'product-456', metadata: { source: 'custom-button' } }); }; return <button onClick={handleCustomEvent}>Track Custom Event</button>; } ``` ## 🔗 Integration Examples ### Complete Integration with AdMesh Backend SDKs ```tsx import { AdMesh } from '@admesh/typescript-sdk'; import { AdMeshProductCard, AdMeshLayout } from 'admesh-ui-sdk'; const client = new AdMesh({ apiKey: 'your-api-key' }); // Basic recommendation display async function getRecommendations(query: string) { const response = await client.recommend.getRecommendations({ query, format: 'auto' }); return ( <AdMeshProductCard recommendation={response.response?.recommendations?.[0]} autoLayout={true} /> ); } // Chat interface integration function ChatApp() { const [messages, setMessages] = useState([]); const [recommendations, setRecommendations] = useState([]); const handleUserMessage = async (message: string) => { // Add user message setMessages(prev => [...prev, { role: 'user', content: message }]); // Get AI response with recommendations const response = await client.recommend.getRecommendations({ query: message, format: 'conversational' }); // Add assistant response setMessages(prev => [...prev, { role: 'assistant', content: response.response?.summary || 'Here are some recommendations...' }]); // Show recommendations if (response.response?.recommendations) { setRecommendations(response.response.recommendations); } }; return ( <div className="chat-container"> {messages.map((msg, i) => ( <div key={i} className={`message ${msg.role}`}> {msg.content} {/* Show recommendations after assistant messages */} {msg.role === 'assistant' && recommendations.length > 0 && ( <AdMeshLayout recommendations={recommendations} layout="list" maxItems={3} onRecommendationClick={(adId, link) => window.open(link)} /> )} </div> ))} </div> ); } ``` ### Multi-Format Display ```tsx // Display the same recommendations in different formats function MultiFormatDemo({ recommendations }: { recommendations: AdMeshRecommendation[] }) { return ( <div className="space-y-8"> {/* Main layout */} <AdMeshProductCard recommendations={recommendations} autoLayout={true} /> {/* Citation format */} <AdMeshLayout recommendations={recommendations} layout="citation" /> {/* Ecommerce cards */} {recommendations.length > 0 && ( <AdMeshEcommerceCards recommendations={recommendations} showPricing={true} /> )} </div> ); } ``` ## 📚 API Reference ### Core Types ```tsx // Complete recommendation interface (see Unified JSON Response section above) interface AdMeshRecommendation { // Core required fields title: string; reason: string; intent_match_score: number; // 0-1 normalized score admesh_link: string; ad_id: string; product_id: string; // All optional fields for different ad unit needs url?: string; description?: string; pricing?: string; features?: string[]; keywords?: string[]; categories?: string[]; has_free_tier?: boolean; trial_days?: number; // ... see complete interface above } // Intent types for layout selection type IntentType = | 'compare_products' | 'best_for_use_case' | 'trial_demo' | 'budget_conscious'; // Theme configuration interface AdMeshTheme { mode: 'light' | 'dark'; accentColor?: string; borderRadius?: string; fontFamily?: string; } // Conversational ad configuration interface ConversationalAdConfig { displayMode: 'inline' | 'summary' | 'floating' | 'minimal' | 'citation'; context: 'chat' | 'assistant' | 'agent' | 'support'; maxRecommendations?: number; showPoweredBy?: boolean; autoShow?: boolean; delayMs?: number; position?: 'top' | 'bottom' | 'inline'; } // Chat configuration interface AdMeshChatConfig { position: 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'; size: 'sm' | 'md' | 'lg' | 'xl'; displayMode: 'widget' | 'fullscreen' | 'embedded'; autoOpen?: boolean; showWelcomeMessage?: boolean; welcomeMessage?: string; placeholder?: string; maxMessages?: number; enableTypingIndicator?: boolean; } ``` ## 🎭 Live Examples & Documentation ### Interactive Storybook **🌐 Hosted Storybook**: [https://storybook.useadmesh.com/](https://storybook.useadmesh.com/) Explore interactive examples and component variations: - **📝 Citation Components** - Different citation styles (numbered, bracketed, superscript) - **💬 Conversational Ads** - Chat interface integration examples - **🎯 Layout Components** - Unified layout with multiple display options - **🎨 Theme Variations** - Light/dark mode examples - **📱 Responsive Design** - Mobile and desktop layout adaptations - **🔧 Configuration Options** - All component props and configurations **No installation required** - view all ad formats directly in your browser! ### Complete Documentation **📚 Full Documentation**: [https://docs.useadmesh.com/](https://docs.useadmesh.com/) - **Getting Started Guides** - Step-by-step integration tutorials - **API Reference** - Complete component and prop documentation - **Integration Examples** - Real-world implementation patterns - **Best Practices** - Optimization and performance tips - **Troubleshooting** - Common issues and solutions ## 🎨 Theming & Dark Mode The AdMesh UI SDK provides comprehensive theming support with full dark mode compliance: ### Theme Configuration ```jsx // Light theme (default) <AdMeshProductCard theme={{ mode: "light" }} /> // Dark theme with proper contrast ratios <AdMeshProductCard theme={{ mode: "dark" }} /> // Custom accent color <AdMeshProductCard theme={{ mode: "light", accentColor: "#3b82f6" }} /> // Dynamic theme switching const [isDarkMode, setIsDarkMode] = useState(false); <AdMeshProductCard theme={{ mode: isDarkMode ? "dark" : "light" }} /> ``` ### Dark Mode Features - ✅ **Full Dark Mode Support**: All components automatically adapt to dark theme - ✅ **WCAG Accessibility**: Proper contrast ratios meet accessibility guidelines - ✅ **Consistent Branding**: "" remains visible in both themes - ✅ **Smooth Transitions**: Components transition smoothly between light and dark modes - ✅ **CSS Variables**: Uses CSS custom properties for consistent theming - ✅ **No Ambiguous Elements**: Clean, focused interface without confusing UI elements ### CSS Custom Properties The SDK uses CSS custom properties that automatically adjust based on the theme: ```css /* Light theme variables */ .admesh-component[data-admesh-theme="light"] { --admesh-background: #ffffff; --admesh-text: #111827; --admesh-border: #e5e7eb; --admesh-surface: #f9fafb; } /* Dark theme variables */ .admesh-component[data-admesh-theme="dark"] { --admesh-background: #111827; --admesh-text: #f9fafb; --admesh-border: #374151; --admesh-surface: #1f2937; --admesh-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.3); } ``` ### Theme Integration All AdMesh components automatically respect the theme prop: ```jsx // All components support the same theme interface <AdMeshProductCard theme={{ mode: "dark" }} /> <AdMeshChatInterface theme={{ mode: "dark" }} /> ``` ## 📱 Responsive Design & Accessibility ### Mobile-First Design All AdMesh components are built with mobile-first responsive design: ```tsx // Components automatically adapt to screen sizes <AdMeshProductCard recommendations={recommendations} // Automatically shows: // - Grid layout on desktop // - Single column on mobile // - Optimized touch targets // - Readable typography scaling /> ``` ### Accessibility Features - **WCAG 2.1 AA Compliant**: All components meet accessibility standards - **Keyboard Navigation**: Full keyboard support for all interactive elements - **Screen Reader Support**: Proper ARIA labels and semantic HTML - **Focus Management**: Visible focus indicators and logical tab order - **Color Contrast**: Meets contrast requirements in both light and dark modes - **Reduced Motion**: Respects user's motion preferences ```tsx // Accessibility is built-in, no additional configuration needed <AdMeshLayout recommendations={recommendations} layout="list" // Automatically includes: // - aria-labels for recommendations // - keyboard navigation // - screen reader announcements // - focus management /> ``` ### Responsive Breakpoints ```css /* Built-in responsive breakpoints */ .admesh-component { /* Mobile: 0-640px */ /* Tablet: 641-1024px */ /* Desktop: 1025px+ */ } /* Components automatically adjust: - Typography scales appropriately - Touch targets are 44px minimum - Layouts stack on mobile - Sidebars become overlays - Chat widgets resize appropriately */ ``` ## 🔧 Troubleshooting ### Common Issues & Solutions #### Components Not Displaying ```tsx // ❌ Missing recommendations data <AdMeshProductCard recommendations={undefined} /> // ✅ Always provide valid recommendations array <AdMeshProductCard recommendations={recommendations || []} /> ``` #### Styling Issues ```tsx // ❌ CSS not loading (if using manual import) import { AdMeshProductCard } from 'admesh-ui-sdk'; // ✅ Styles are auto-injected, no import needed import { AdMeshProductCard } from 'admesh-ui-sdk'; // Styles automatically included ✨ ``` #### TypeScript Errors ```bash # Install required peer dependencies npm install --save-dev @types/react @types/react-dom # Ensure React 16.8+ for hooks support npm install react@^16.8.0 react-dom@^16.8.0 ``` #### Tracking Not Working ```tsx // ❌ Missing admesh_link in recommendations const recommendations = [{ title: "Product", // Missing admesh_link }]; // ✅ Include proper tracking URLs const recommendations = [{ title: "Product", admesh_link: "https://useadmesh.com/track?ad_id=123", ad_id: "123", product_id: "product-123" }]; ``` #### Mobile Layout Issues ```tsx // ❌ Fixed widths that don't scale <div style={{ width: '800px' }}> <AdMeshProductCard recommendations={recommendations} /> </div> // ✅ Use responsive containers <div className="w-full max-w-4xl mx-auto"> <AdMeshProductCard recommendations={recommendations} /> </div> ``` ### Performance Optimization ```tsx // ✅ Limit recommendations for better performance <AdMeshProductCard recommendations={recommendations} maxDisplayed={6} // Limit to 6 items /> // ✅ Use React.memo for static recommendations const MemoizedAdMeshProductCard = React.memo(AdMeshProductCard); // ✅ Lazy load components const AdMeshEcommerceCards = React.lazy(() => import('admesh-ui-sdk').then(module => ({ default: module.AdMeshEcommerceCards })) ); ``` ## 🛠 Development ```bash # Install dependencies npm install # Start Storybook for development npm run storybook # Storybook at :6006 # Build library for NPM npm run build # Build Storybook for deployment npm run build-storybook # Run linting npm run lint # Run tests npm run test # Type checking npm run type-check ``` ## 🚀 Deployment ### Automatic Vercel Deployment 1. Go to [vercel.com](https://vercel.com) and import your GitHub repository 2. Configure build settings: - **Build Command**: `npm run build-storybook` - **Output Directory**: `storybook-static` 3. Deploy automatically on every push to main **No environment variables needed** - Vercel's GitHub integration handles everything automatically! ### Manual Deployment ```bash npm run build-storybook npx serve storybook-static ``` --- ## 🎯 Summary The AdMesh UI SDK provides a complete solution for displaying product recommendations across all ad unit formats: ### ✅ What You Get - **10+ Ad Unit Types** - From simple cards to complex conversational interfaces - **Unified JSON Schema** - Same recommendation structure works across all components and sources (Walmart, AdMesh, etc.) - **Built-in Tracking** - Automatic analytics for views, clicks, and conversions - **Full Responsive Design** - Mobile-first with accessibility compliance - **TypeScript Support** - Complete type safety and IntelliSense - **Theme System** - Light/dark mode with custom branding - **Zero Configuration** - Works out of the box with sensible defaults ### 🚀 Get Started in 3 Steps 1. **Install**: `npm install admesh-ui-sdk` 2. **Import**: `import { AdMeshProductCard } from 'admesh-ui-sdk';` 3. **Use**: `<AdMeshProductCard recommendations={recommendations} />` 📋 **New in v0.13.0**: [Unified Schema Guide](./UNIFIED_SCHEMA_GUIDE.md) - Learn about the new unified JSON schema that works across all recommendation sources. ## 📋 Unified JSON Schema The AdMesh UI SDK uses a unified JSON schema that works across all recommendation sources (Walmart, AdMesh, Amazon, etc.). This ensures consistent data structure regardless of the source: ```typescript interface AdMeshRecommendation { // Required core fields (new format) product_id: string; title: string; recommendation_description: string; admesh_link: string; categories: string[]; integrations: string[]; trust_score: number; reward_note: string; meta: { ad_id: string; offer_trust_score: number; brand_trust_score: number; intent_match_score: number; reason: string; description: string; keywords: string[]; url: string; redirect_url: string; }; // Legacy fields for backward compatibility ad_id?: string; // Use meta.ad_id instead brand?: string; source?: string; // ... other legacy fields } ``` ### Example Unified Response ```json { "ad_id": "walmart_249887530", "admesh_link": "https://goto.walmart.com/c/None/568844/9383?veh=aff&sourceid=imp_000011112222333344&u=https%3A%2F%2Fwww.walmart.com%2Fip%2F249887530", "audience_segment": "", "availability": "in_stock", "brand": "ZENY", "brand_trust_score": 0.5, "categories": ["All Walmart Restored Large Appliances"], "description": "The smallest and lightest twin tub portable washing machine available...", "discount_percentage": 34.9, "external_id": "249887530", "features": ["Free 2-3 day shipping"], "image_url": "https://i5.walmartimages.com/asr/7505138e-bbfa-4a43-9de4-2ab8c71eed99.6810f971aaffdca38d18e9928b3e4450.jpeg?odnHeight=450&odnWidth=450&odnBg=ffffff", "intent_match_score": 0.72, "is_fallback": false, "keywords": [], "offer_trust_score": 1, "original_price": 152.9, "price": 99.48, "pricing": "$99.48", "product_id": "walmart_249887530", "rating": 4, "reason": "Perfect match for 'best washing machine to buy' - from trusted brand ZENY, highly rated (4.0/5)", "recommendation_description": "The smallest and lightest twin tub portable washing machine available...", "recommendation_title": "ZENY Portable Washing Machine Mini Twin Tub Washing Machine with Washer & Spinner, Gravity Drain ...", "redirect_url": "https://www.walmart.com/ip/249887530", "review_count": 384, "reward_note": "", "source": "walmart", "title": "ZENY Portable Washing Machine Mini Twin Tub Washing Machine with Washer & Spinner, Gravity Drain ...", "trial_days": 0, "url": "https://www.walmart.com/ip/249887530", "shipping_info": { "free_shipping_over_35": false, "standard_rate": 0, "two_day_rate": 0, "ship_to_store": false, "free_ship_to_store": false } } ``` ### 🌟 Perfect For - **AI Applications** - Citation-based conversation ads - **Chat Interfaces** - Inline and floating recommendation units - **E-commerce Sites** - Product comparison and showcase components - **SaaS Platforms** - Unified layout components with smart detection - **Content Sites** - Expandable and simple ad formats Ready to get started? Check out our [Interactive Storybook](https://storybook.useadmesh.com/) or [Complete Documentation](https://docs.useadmesh.com/)! --- ## 📄 License MIT License ## 🤝 Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests and stories 5. Submit a pull request See our [Contributing Guide](CONTRIBUTING.md) for detailed instructions. ## 📞 Support & Community ### Documentation & Resources - **📚 Complete Documentation**: [https://docs.useadmesh.com](https://docs.useadmesh.com) - **🎭 Interactive Storybook**: [https://storybook.useadmesh.com](https://storybook.useadmesh.com) - **🚀 AdMesh Dashboard**: [https://useadmesh.com](https://useadmesh.com) ### Get Help - **GitHub Issues**: [Report bugs or request features](https://github.com/GouniManikumar12/admesh-ui-sdk/issues) - **Email Support**: [mani@useadmesh.com](mailto:mani@useadmesh.com) - **Discord Community**: [Join our Discord](https://discord.gg/admesh) (coming soon) ### Quick Links - **API Keys**: Get your API keys at [useadmesh.com](https://useadmesh.com) - **TypeScript SDK**: [@admesh/typescript-sdk](https://www.npmjs.com/package/@admesh/typescript-sdk) - **Python SDK**: [admesh-python](https://pypi.org/project/admesh/) - **Status Page**: [status.useadmesh.com](https://status.useadmesh.com) ### Contributing We welcome contributions! See our [Contributing Guide](CONTRIBUTING.md) for details on: - Setting up the development environment - Code style and standards - Submitting pull requests - Reporting issues