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
npm install admesh-ui-sdk




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
- 🎭 Interactive Storybook: https://storybook.useadmesh.com/ - Explore all components and ad formats
- 📚 Complete Documentation: https://docs.useadmesh.com/ - Full SDK documentation and guides
- 🚀 AdMesh Dashboard: https://useadmesh.com - Get your API keys and manage campaigns
- 📦 npm Package: 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.
- 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
``bash`
npm install admesh-ui-sdk
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)
- 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
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.
Step 1: Install the SDK
`bash`
npm install admesh-ui-sdk
Step 2: Add a container element
`html`
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 ID on your platform
const sessionId = AdMeshSDK.createSession();
// Fetch and render recommendations automatically
await admesh.showRecommendations({
query: userQuery,
containerId: 'admesh-recommendations',
session_id: sessionId
});
`
`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);
`
The SDK is stateless regarding session management. Your platform is responsible for:
- Creating Sessions: Use AdMeshSDK.createSession() to generate a session IDAdMeshSDK.createMessageId(sessionId)
- Creating Message IDs: Use to generate message IDssession_id
- Storing Sessions: Store session IDs in your platform's storage (localStorage, database, etc.)
- Passing IDs to SDK: Provide 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
});
`
`typescript`
const admesh = new AdMeshSDK({
apiKey: 'your-api-key', // Required
theme: { // Optional: customize appearance
mode: 'light',
primaryColor: '#3b82f6',
borderRadius: '8px'
}
});
- ✅ API authentication with your API key
- ✅ Recommendation fetching from /aip/context endpoint (auction-based)
- ✅ 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
The /aip/context endpoint returns a recommendation object with:creative_input
- Full with all format fields (weave, tail, product_card)
- Complete billing information (CPX, CPC, CPA values)
- Tracking URLs (exposure_url, click_url, admesh_link)
- Format metadata (allowed_formats, preferred_format, fallback_formats)
- ✅ Session creation and storage (use AdMeshSDK.createSession())
- ✅ Session persistence across page reloads
- ✅ Session lifecycle management (when to create new sessions)
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'
}
}
});
When working directly with WeaveResponseProcessor you now receive richer context for exposure tracking. The optional onExposurePixel callback passed to scanAndProcessLinks() is invoked with { exposureUrl, adId, linkElement }, enabling you to plug the DOM node into your own IntersectionObserver logic (or the SDK’s helper).
`typescript
import {
WeaveResponseProcessor,
createInlineExposureTracker
} from 'admesh-ui-sdk';
const processor = new WeaveResponseProcessor();
const inlineTracker = createInlineExposureTracker();
processor.scanAndProcessLinks(container, recommendations, ({ exposureUrl, adId, linkElement }) => {
inlineTracker.startTracking({
exposureUrl,
adId,
linkElement,
sessionId: currentSessionId,
logPrefix: '[CustomInlineTracking]'
});
});
`
This guarantees inline/weave ads also respect the MRC requirement (50 % visible for 1 s) before firing pixels, and keeps exposure deduplication tied to your sessionId.
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.
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 (
My AI Application
{/ AdMesh layout - auto-detects best format /}
recommendations={recommendations}
layout="auto"
maxItems={6}
onRecommendationClick={(adId, admeshLink) => {
window.open(admeshLink, '_blank');
}}
/>
);
}
`$3
`tsx
// Citation layout for AI conversations
recommendations={recommendations}
conversationText="Based on your startup needs, I recommend HubSpot CRM for its excellent free tier..."
layout="citation"
/>// Ecommerce layout for product grids
ecommerceProducts={products}
layout="ecommerce"
title="Featured Products"
/>
// Grid layout for recommendation cards
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
$3
- 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
recommendations={recommendations}
ecommerceProducts={products}
conversationText="Based on your needs..."
layout="auto"
// maxItems defaults: 1 for layout, 3 for ecommerce
/>
// Specific layouts with custom maxItems
`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 typesKey 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.
$3
#### AdMeshProductCard
Individual product recommendation card with rich information display.
`tsx
// Default clean minimal design (recommended)
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
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
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
$3
#### AdMeshSummaryUnit
Display recommendations with summary text and follow-up suggestions.
`tsx
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
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
$3
#### AdMeshProductCard - Simple Variation
Simple, clean ad format for minimal integration.
`tsx
recommendation={recommendation}
variation="simple" // Creates inline ad format
onClick={(adId, admeshLink) => window.open(admeshLink)}
/>
`$3
#### AdMeshBadge
Reusable badge component for highlighting features.
#### AdMeshLinkTracker
Wrapper for tracking any clickable element with built-in analytics.
`tsx
adId={recommendation.ad_id}
admeshLink={recommendation.admesh_link}
productId={recommendation.product_id}
onClick={() => handleClick()}
trackingData={{ title: recommendation.title }}
>
`🎨 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.
$3
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
$3
`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
}
});
recommendations={recommendations}
theme={customTheme}
/>
`$3
`tsx
// Use built-in presets
`$3
`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.
$3
`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
}
`$3
`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;
}
`$3
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 => )}
`🎯 Layout-Based Integration
The AdMeshLayout component automatically adapts to different contexts and use cases.
$3
`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 (
response={{
layout_type: 'auto',
recommendations: recommendations
}}
/>
);
}
`$3
#### Auto Layout
Automatically selects the best layout based on content and context:
`tsx
recommendations={recommendations}
layout="auto"
/>
`#### Grid Layout
Displays recommendations in a responsive grid format:
`tsx
recommendations={recommendations}
layout="grid"
/>
`#### List Layout
Displays recommendations in a vertical list format:
`tsx
recommendations={recommendations}
layout="list"
/>
`#### Citation Layout
Displays recommendations as inline citations within text:
`tsx
recommendations={recommendations}
layout="citation"
/>
`$3
#### AdMeshBadge
Reusable badge component for highlighting features and trust indicators:
`tsx
import { AdMeshBadge } from 'admesh-ui-sdk'; 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'; adId={recommendation.meta.ad_id}
admeshLink={recommendation.admesh_link}
productId={recommendation.product_id}
onClick={() => handleClick()}
trackingData={{ title: recommendation.title }}
>
`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.
$3
`tsx
import { createAdMeshTheme } from 'admesh-ui-sdk';const customTheme = createAdMeshTheme({
mode: 'light', // 'light' | 'dark'
accentColor: '#2563eb',
borderRadius: '8px',
fontFamily: 'Inter, sans-serif'
});
recommendations={recommendations}
theme={customTheme}
/>
`$3
`tsx
import { createDarkTheme } from 'admesh-ui-sdk';const darkTheme = createDarkTheme({
accentColor: '#3b82f6'
});
recommendations={recommendations}
theme={darkTheme}
/>
`$3
All components support custom styling through className and style props:
`tsx
recommendations={recommendations}
className="my-custom-recommendations"
style={{
backgroundColor: '#f8f9fa',
borderRadius: '12px',
padding: '16px'
}}
/>
`
`$3
#### 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 (
{messages.map((msg, i) => (
message ${msg.role}}>
{msg.content} {/ Show recommendations after assistant messages /}
{msg.role === 'assistant' && recommendations.length > 0 && (
recommendations={recommendations}
layout="list"
maxItems={2}
/>
)}
))}
);
}
`💬 Chat Components
Perfect for websites and applications that want to provide AI-powered recommendations through chat interfaces.
$3
`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 (
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)}
/>
);
}
`$3
- 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
$3
`tsx
// Embedded chat with message limit
config={{
maxMessages: 20,
enableTypingIndicator: true,
placeholder: "What can I help you find today?"
}}
/>
`🤖 Auto-Recommendations (AI Integration)
$3
#### 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);
}
};
`$3
- 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 via exposure URLs and click URLs provided in recommendations.
$3
Tracking is handled automatically by the SDK components:
- Exposure Tracking:
AdMeshViewabilityTracker fires exposure URLs when ads become viewable (MRC-compliant: 50% visible for 1 second)
- Click Tracking: AdMeshLinkTracker navigates to click URLs which automatically track clicks and redirect to merchant URLs
- Conversion Tracking: Handled via conversion pixels embedded in click URLs`tsx
// All components automatically track interactions via exposure/click URLs
brand={recommendation}
// Exposure tracking handled by AdMeshViewabilityTracker (fires exposure_url)
// Click tracking handled by AdMeshLinkTracker (uses click_url/admesh_link)
/>
`$3
1. Exposure URLs (
/exposure) - Fired automatically when ads meet MRC viewability standards
- Handled by AdMeshViewabilityTracker component
- Used for billing and attribution2. Click URLs (
/click) - Used when users click on recommendations
- Handled by AdMeshLinkTracker component
- Automatically tracks clicks and redirects to merchant3. Conversion Pixels (
/conversion/pixel) - Fired when conversions occur
- Embedded in click URLs via UTM parameters
- Tracked automatically by merchant sites$3
Use
AdMeshLinkTracker to wrap custom components for click tracking:`tsx
import { AdMeshLinkTracker } from 'admesh-ui-sdk'; recommendationId="rec_123"
admeshLink="https://api.useadmesh.com/click/rec_123?..."
productId="product-456"
>
`Note: The
admeshLink prop should be the click URL from the recommendation, which already includes all tracking parameters.🔗 Integration Examples
$3
`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 (
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 (
{messages.map((msg, i) => (
message ${msg.role}}>
{msg.content} {/ Show recommendations after assistant messages /}
{msg.role === 'assistant' && recommendations.length > 0 && (
recommendations={recommendations}
layout="list"
maxItems={3}
onRecommendationClick={(adId, link) => window.open(link)}
/>
)}
))}
);
}
`$3
`tsx
// Display the same recommendations in different formats
function MultiFormatDemo({ recommendations }: { recommendations: AdMeshRecommendation[] }) {
return (
{/ Main layout /}
recommendations={recommendations}
autoLayout={true}
/> {/ Citation format /}
recommendations={recommendations}
layout="citation"
/>
{/ Ecommerce cards /}
{recommendations.length > 0 && (
recommendations={recommendations}
showPricing={true}
/>
)}
);
}
`📚 API Reference
$3
`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
$3
🌐 Hosted Storybook: 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!
$3
📚 Full Documentation: 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:
$3
`jsx
// Light theme (default)
// Dark theme with proper contrast ratios
// Custom accent color
// Dynamic theme switching
const [isDarkMode, setIsDarkMode] = useState(false);
`$3
- ✅ 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
$3
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);
}
`$3
All AdMesh components automatically respect the theme prop:
`jsx
// All components support the same theme interface
`📱 Responsive Design & Accessibility
$3
All AdMesh components are built with mobile-first responsive design:
`tsx
// Components automatically adapt to screen sizes
recommendations={recommendations}
// Automatically shows:
// - Grid layout on desktop
// - Single column on mobile
// - Optimized touch targets
// - Readable typography scaling
/>`$3
- 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
recommendations={recommendations}
layout="list"
// Automatically includes:
// - aria-labels for recommendations
// - keyboard navigation
// - screen reader announcements
// - focus management
/>
`$3
`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
$3
#### Components Not Displaying
`tsx
// ❌ Missing recommendations data
// ✅ Always provide valid recommendations array
`#### 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-domEnsure 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
// ✅ Use responsive containers
`$3
`tsx
// ✅ Limit recommendations for better performance
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 installStart Storybook for development
npm run storybook # Storybook at :6006Build library for NPM
npm run buildBuild Storybook for deployment
npm run build-storybookRun linting
npm run lintRun tests
npm run testType checking
npm run type-check
`🚀 Deployment
$3
1. Go to 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 mainNo environment variables needed - Vercel's GitHub integration handles everything automatically!
$3
`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:
$3
- 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$3
1. Install:
npm install admesh-ui-sdk
2. Import: import { AdMeshProductCard } from 'admesh-ui-sdk';
3. Use: 📋 New in v0.13.0: Unified Schema Guide - 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
}
`$3
`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
}
}
``Ready to get started? Check out our Interactive Storybook or Complete Documentation!
---
MIT License
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 for detailed instructions.