<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sherlock Product Comparison Hub</title>
<style>
/* Modern, responsive CSS for the comparison hub */
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #f8f9fa; }
.hub-container { max-width: 1200px; margin: 0 auto; }
h1 { text-align: center; color: #333; }
#comparison-table { width: 100%; border-collapse: collapse; margin-top: 20px; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
th, td { padding: 16px; text-align: left; border-bottom: 1px solid #eee; }
th { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; font-weight: 600; }
.feature-list { list-style: none; padding: 0; }
.feature-list li { padding: 4px 0; }
.price { font-size: 1.2em; font-weight: bold; color: #28a745; }
.rating { display: flex; align-items: center; }
.stars { color: #ffc107; margin-right: 8px; }
.image { width: 80px; height: 80px; object-fit: cover; border-radius: 8px; }
.refresh-btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px 24px; border-radius: 8px; cursor: pointer; font-size: 1em; margin: 20px auto; display: block; transition: transform 0.2s; }
.refresh-btn:hover { transform: scale(1.05); }
.refresh-btn:disabled { opacity: 0.6; cursor: not-allowed; transform: none; }
.loading { text-align: center; padding: 40px; font-style: italic; color: #666; }
@media (max-width: 768px) { th, td { padding: 12px 8px; font-size: 0.9em; } .image { width: 60px; height: 60px; } }
</style>
</head>
<body>
<div class="hub-container">
<h1>🕵️♂️ Sherlock Product Comparison Hub</h1>
<p style="text-align: center; color: #666;">Compare products dynamically. Schema-driven, templated, and refreshable.</p>
<button id="refresh-btn" class="refresh-btn">🔄 Refresh Data</button>
<div id="comparison-container">
<div class="loading">Loading products...</div>
</div>
</div>
<script>
// ========================================
// 1. PRODUCT SCHEMA (JSON Schema for validation & structure)
// ========================================
const PRODUCT_SCHEMA = {
type: "object",
properties: {
id: { type: "string", description: "Unique product ID" },
name: { type: "string", description: "Product name" },
category: { type: "string", description: "Product category" },
price: { type: "number", description: "Price in USD" },
currency: { type: "string", default: "USD" },
rating: { type: "number", minimum: 0, maximum: 5, description: "Star rating (0-5)" },
image: { type: "string", description: "Image URL" },
features: {
type: "array",
items: { type: "string" },
description: "List of key features"
},
specs: {
type: "object",
properties: {
screenSize: { type: "string" },
batteryLife: { type: "string" },
storage: { type: "string" }
},
description: "Technical specifications"
},
availability: { type: "boolean", description: "In stock?" },
lastUpdated: { type: "string", format: "date-time", description: "Last data update timestamp" }
},
required: ["id", "name", "price", "features"]
};
// Sample data generator/simulator (in production, fetch from API/DB)
function generateSampleData(numProducts = 4) {
const categories = ['Laptops', 'Smartphones', 'Headphones', 'Smartwatches'];
const products = [];
for (let i = 0; i < numProducts; i++) {
products.push({
id: `prod-${Date.now()}-${i}`,
name: `Sherlock ${categories[i % categories.length]} Pro ${i + 1}`,
category: categories[i % categories.length],
price: (500 + Math.random() * 1500).toFixed(2),
currency: "USD",
rating: (3 + Math.random() * 2).toFixed(1),
image: `https://picsum.photos/200/200?random=${i + 1}`,
features: [
`Feature ${i + 1}a`,
`Feature ${i + 1}b`,
`Ultra-fast processing`,
`Long battery life`
],
specs: {
screenSize: `${14 + i * 0.5}"`,
batteryLife: `${10 + i * 2}h`,
storage: `${512 + i * 256}GB`
},
availability: Math.random() > 0.2,
lastUpdated: new Date().toISOString()
});
}
return products;
}
// ========================================
// 2. TEMPLATES (Handlebars-like vanilla JS templating engine)
// ========================================
function createTemplateEngine() {
const templates = {};
// Compile template function
function compile(templateStr) {
return (data) => templateStr.replace(/\{\{([^}]+)\}\}/g, (_, key) => {
const value = key.split('.').reduce((obj, k) => obj?.[k], data);
return value ?? '';
});
}
// Row template for table body
templates.row = compile(`
<td><img src="{{image}}" alt="{{name}}" class="image" loading="lazy"></td>
<td>
<strong>{{name}}</strong><br>
<small>{{category}}</small>
</td>
<td class="price">${{{price}}} {{currency}}</td>
<td class="rating">
<span class="stars">⭐{{rating}}</span>
({{rating}}/5)
</td>
<td>
<ul class="feature-list">
{{#features}}
<li>✅ {{.}}</li>
{{/features}}
</ul>
</td>
<td>
{{#specs}}
<div><strong>Screen:</strong> {{screenSize}}</div>
<div><strong>Battery:</strong> {{batteryLife}}</div>
<div><strong>Storage:</strong> {{storage}}</div>
{{/specs}}
</td>
<td style="color: {{availability ? '#28a745' : '#dc3545'}};">
{{availability ? '✅ In Stock' : '❌ Out of Stock'}}
</td>
<td><small>{{lastUpdated}}</small></td>
`);
// Full table template
templates.table = (products) => {
if (!products || products.length === 0) return '<div class="loading">No products to compare</div>';
const headers = ['Image', 'Product', 'Price', 'Rating', 'Features', 'Specs', 'Stock', 'Updated'];
let html = '<table id="comparison-table"><thead><tr>';
headers.forEach(h => html += `<th>${h}</th>`);
html += '</tr></thead><tbody>';
products.forEach(p => html += `<tr>${templates.row(p)}</tr>`);
html += '</tbody></table>';
return html;
};
return templates;
}
const templates = createTemplateEngine();
// ========================================
// 3. REFRESH LOGIC (Fetch, validate, render cycle)
// ========================================
let currentProducts = [];
async function refreshData() {
const btn = document.getElementById('refresh-btn');
const container = document.getElementById('comparison-container');
btn.disabled = true;
btn.textContent = '🔄 Refreshing...';
container.innerHTML = '<div class="loading">Fetching latest data...</div>';
try {
// Simulate API fetch (replace with real endpoint like '/api/products')
// await new Promise(resolve => setTimeout(resolve, 1000)); // Simulate delay
currentProducts = generateSampleData(4 + Math.floor(Math.random() * 3)); // Dynamic count for demo
// Optional: Validate against schema (using simple check; use ajv.js for full validation)
currentProducts.forEach(p => {
if (!p.id || !p.name || typeof p.price !== 'number') {
throw new Error(`Invalid product: ${p.name}`);
}
});
// Render
container.innerHTML = templates.table(currentProducts);
} catch (error) {
container.innerHTML = `<div style="color: #dc3545;">Error: ${error.message}</div>`;
} finally {
btn.disabled = false;
btn.textContent = '🔄 Refresh Data';
}
}
// Initial load
refreshData();
// Button event
document.getElementById('refresh-btn').addEventListener('click', refreshData);
// Auto-refresh every 30s (optional)
setInterval(refreshData, 30000);
</script>
</body>
</html>
🚀 Quick Start Guide (Sherlock's Notes)
- Schema: Full JSON Schema defined in
PRODUCT_SCHEMA. Extend for your products (e.g., add reviews, warranty).
- Templates: Vanilla JS templating (no deps). Easy to customize
templates.row or add cards/grid views.
- Refresh: Click button or auto-refreshes. Swap
generateSampleData() with fetch('/api/products'). Handles loading/errors.
- Features:
- Responsive design (mobile-friendly).
- Schema validation stub (add ajv for pro).
- Dynamic data simulation (randomized for demo).
- Extend: For backend, use this schema in MongoDB/Postgres/Node.js. API endpoint:
GET /api/compare?category=laptops.
- Deploy: Save as
index.html – zero server needed!
Need customizations? Just ask, Watson. 🕵️♂️