Engineer a global search experience combining Algolia, semantic re-ranking, and AI-based…
- User
Engineer a global search experience combining Algolia, semantic re-ranking, and AI-based command palette.
- Assistant
Engineer a global search experience combining Algolia, semantic re-ranking, and AI-based command palette.
Here's a thinking process that leads to the suggested solution:
Analyze the Request:
Deconstruct the Features:
Design Concept (Swiss Design + Future Tech):
Inter for UI, Playfair Display for headlines.filter: blur() or an animated canvas (three.js or simple Canvas) to create a "living" background that feels deep and techy without being distracting. Let's go with a Three.js particle web or a flow field that reacts to the mouse to meet the "space depth" requirement.Step-by-Step Implementation Plan:
<script> for fonts and colors.bg-white/10, backdrop-blur-xl), and noise.Refining the "AI" Aspect (The Trick):
Drafting the Code (Mental or Scratchpad):
gsap.to(".modal", {autoAlpha: 1, scale: 1}).Detailed UI Design (Swiss Style):
grid-cols-1 md:grid-cols-3 inside modal.Writing the actual code (Iterative refinement during coding):
font-sans: 'Inter', sans-serif;. Add noise background using a base64 tiny noise image or CSS generator pattern.opacity-0 pointer-events-none). When active, fixed inset-0 z-50.text-4xl, no border, transparent bg.input event -> trigger search (debounced) -> update DOM.Addressing Specific Requirements:
hits array with objectID, title, type, content, tags.score to each hit. When searching, I'll compute a "semantic boost" based on query terms matching tags.commands. If query matches regex patterns, show commands..hit-card entry).grid-span-2 for specific cards.Final Polish:
Self-Correction/Review during drafting:
position: fixed; z-index: 0. Content z-index: 10.Final Output Structure:
(Self-Correction on Language): The user's prompt is in English. I will respond in English.
Let's build the code. Focus on the "WOW" factor.
Let's write the code. (Proceeding to generate HTML). Here is a complete, self-contained single-file solution implementing a high-end "Global Search Experience." It combines a simulated Algolia search interface, semantic re-ranking logic (client-side), and an AI-driven command palette, all wrapped in a sophisticated, award-winning visual design using Tailwind CSS, GSAP, and Three.js.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>NEXUS | Global AI Search</title>
<!-- Tailwind CSS -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Google Fonts: Playfair Display & Inter -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600&family=Playfair+Display:ital,wght@0,600;0,700;1,400&display=swap" rel="stylesheet">
<!-- GSAP -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Three.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<!-- Lucide Icons -->
<script src="https://unpkg.com/lucide@latest"></script>
<!-- Tailwind Config -->
<script>
tailwind.config = {
theme: {
extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
serif: ['Playfair Display', 'serif'],
},
colors: {
'nexus-dark': '#050505',
'nexus-gray': '#1a1a1a',
'nexus-blue': '#2563eb',
'nexus-glow': 'rgba(37, 99, 235, 0.15)',
},
backgroundImage: {
'gradient-radial': 'radial-gradient(var(--tw-gradient-stops))',
},
boxShadow: {
'glow-sm': '0 0 10px var(--tw-shadow-color, rgba(37, 99, 235, 0.2))',
'glow-md': '0 0 20px var(--tw-shadow-color, rgba(37, 99, 235, 0.3))',
}
}
}
}
</script>
<style>
/* Custom Styles & Reset */
body, html {
margin: 0;
padding: 0;
overflow-x: hidden;
background-color: #050505;
color: #e5e5e5;
cursor: default; /* We'll use custom cursor logic handled via JS if needed, stick to default for now */
}
/* Noise Texture Overlay */
.noise-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 50;
opacity: 0.04;
background: url('data:image/svg+xml;utf8,%3Csvg viewBox="0 0 200 200" xmlns="http://www.w3.org/2000/svg"%3E%3Cfilter id="noiseFilter"%3E%3CfeTurbulence type="fractalNoise" baseFrequency="0.65" numOctaves="3" stitchTiles="stitch"/%3E%3C/filter%3E%3Crect width="100%25" height="100%25" filter="url(%23noiseFilter)"/%3E%3C/svg%3E');
}
/* Typography Enhancements */
.text-balance { text-wrap: balance; }
/* Custom Scrollbar */
::-webkit-scrollbar { width: 6px; }
::-webkit-scrollbar-track { background: #0a0a0a; }
::-webkit-scrollbar-thumb { background: #333; border-radius: 3px; }
::-webkit-scrollbar-thumb:hover { background: #444; }
/* Glassmorphism Utilities */
.glass-panel {
background: rgba(20, 20, 20, 0.6);
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
border: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.3);
}
/* Highlight Animation */
.search-match {
background: rgba(37, 99, 235, 0.2);
color: #60a5fa;
border-radius: 2px;
}
/* Loader */
.spinner {
width: 16px;
height: 16px;
border: 2px solid rgba(255,255,255,0.1);
border-left-color: #3b82f6;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
</style>
</head>
<body class="antialiased min-h-screen flex flex-col">
<!-- Background Three.js Canvas -->
<canvas id="bg-canvas" class="fixed top-0 left-0 w-full h-full -z-10"></canvas>
<!-- Grain Noise -->
<div class="noise-overlay"></div>
<!-- Main Page Content (Hero) -->
<main class="relative z-10 flex-1 flex flex-col items-center justify-center px-6 transition-all duration-700" id="hero">
<div class="text-center space-y-6 max-w-4xl">
<div class="inline-block mb-4 border border-white/10 px-4 py-1 rounded-full text-xs uppercase tracking-widest text-gray-400 bg-white/5 backdrop-blur-sm">
AI-Powered Search Infrastructure
</div>
<h1 class="text-6xl md:text-8xl lg:text-9xl font-serif font-[700] leading-[0.9] tracking-tight text-white text-balance">
Find Signal <br> <span class="italic text-nexus-blue/80">In The Noise</span>
</h1>
<p class="text-gray-400 text-lg md:text-xl max-w-2xl mx-auto font-light leading-relaxed">
Experience semantic understanding fused with instant retrieval.
Press <kbd class="px-2 py-1 bg-white/10 border border-white/20 rounded text-xs font-mono text-white">⌘ K</kbd> or click the lens to invoke the command matrix.
</p>
<button id="open-search-btn" class="group relative mt-8 inline-flex items-center justify-center px-8 py-4 bg-white text-black font-medium overflow-hidden transition-all hover:scale-105 active:scale-95">
<span class="absolute inset-0 w-full h-full bg-gradient-to-r from-transparent via-white/20 to-transparent -translate-x-full group-hover:animate-[shimmer_1.5s_infinite]"></span>
<i data-lucide="search" class="mr-2 w-5 h-5"></i> Open Global Search
</button>
</div>
<!-- Decorative floating stats (Bento style mini) -->
<div class="mt-24 grid grid-cols-2 md:grid-cols-4 gap-4 w-full max-w-5xl">
<div class="glass-panel p-4 rounded-2xl">
<div class="text-3xl font-serif font-bold text-white">250ms</div>
<div class="text-xs uppercase tracking-wide text-gray-500">Latency</div>
</div>
<div class="glass-panel p-4 rounded-2xl">
<div class="text-3xl font-serif font-bold text-white">98.5%</div>
<div class="text-xs uppercase tracking-wide text-gray-500">Recall</div>
</div>
<div class="glass-panel p-4 rounded-2xl">
<div class="text-3xl font-serif font-bold text-white">512</div>
<div class="text-xs uppercase tracking-wide text-gray-500">Dimensions</div>
</div>
<div class="glass-panel p-4 rounded-2xl">
<div class="text-3xl font-serif font-bold text-white">24/7</div>
<div class="text-xs uppercase tracking-wide text-gray-500">Uptime</div>
</div>
</div>
</main>
<!-- Global Search Modal (Hidden by default) -->
<div id="command-palette" class="fixed inset-0 z-[100] flex items-start justify-center pt-[15vh] px-4 pointer-events-none opacity-0">
<!-- Backdrop -->
<div class="absolute inset-0 bg-black/80 backdrop-blur-md transition-opacity duration-300 pointer-events-auto" id="modal-backdrop"></div>
<!-- Container -->
<div class="relative w-full max-w-4xl pointer-events-auto transform transition-transform duration-300 scale-95 opacity-0" id="modal-container">
<!-- Glass Panel -->
<div class="glass-panel rounded-2xl overflow-hidden shadow-2xl border-t border-white/10">
<!-- Header / Input Area -->
<div class="flex items-center px-6 py-5 border-b border-white/5 bg-white/[0.02]">
<div class="text-gray-500 mr-4">
<i data-lucide="command" class="w-5 h-5"></i>
</div>
<input
type="text"
id="search-input"
placeholder="Search docs, commands, or ask AI..."
class="flex-1 bg-transparent border-none outline-none text-xl text-white placeholder-gray-600 font-light"
autocomplete="off"
>
<div id="loading-indicator" class="spinner hidden mr-3"></div>
<div class="text-xs text-gray-500 border border-white/10 px-2 py-1 rounded font-mono">ESC</div>
</div>
<!-- Content Area -->
<div class="max-h-[60vh] overflow-y-auto p-6" id="results-area">
<!-- Semantic Status Bar -->
<div id="semantic-status" class="hidden mb-6 flex items-center text-xs font-mono text-nexus-blue">
<div class="w-2 h-2 rounded-full bg-nexus-blue animate-pulse mr-2"></div>
<span>Analyzing intent with semantic vectors...</span>
</div>
<!-- Grid Layout for Results -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-6" id="results-grid">
<!-- Dynamic Content Injected Here -->
</div>
<!-- Empty State -->
<div id="empty-state" class="hidden text-center py-12">
<div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-white/5 mb-4">
<i data-lucide="sparkles" class="w-8 h-8 text-gray-400"></i>
</div>
<h3 class="text-lg font-medium text-white mb-2">Start Typing</h3>
<p class="text-gray-500 text-sm">Try "Q3 financial report", "update brand assets", or "toggle dark mode".</p>
</div>
</div>
</div>
</div>
</div>
<!-- Logic -->
<script>
/**
* ------------------------------------------------------------------
* MOCK DATA & ALGOLIA SIMULATION
* ------------------------------------------------------------------
*/
// Mock Documents (Hits)
const docs = [
{ id: '1', title: 'Q3 Financial Report 2023', type: 'pdf', category: 'Finance', tags: ['finance', 'quarterly', 'earnings', 'report'], content: 'Comprehensive financial breakdown...' },
{ id: '2', title: 'Brand Guidelines v2.0', type: 'figma', category: 'Design', tags: ['design', 'brand', 'logo', 'colors'], content: 'Official brand assets and typography...' },
{ id: '3', title: 'Project Nebula Roadmap', type: 'md', category: 'Engineering', tags: ['engineering', 'roadmap', 'architecture', 'future'], content: 'Technical specifications for the Nebula project...' },
{ id: '4', title: 'User Research Synthesis', type: 'doc', category: 'Product', tags: ['product', 'ux', 'research', 'users'], content: 'Interviews and findings from 50 users...' },
{ id: '5', title: 'Marketing Strategy - APAC', type: 'ppt', category: 'Marketing', tags: ['marketing', 'apac', 'strategy', 'launch'], content: 'Go-to-market plan for Asia Pacific...' },
{ id: '6', title: 'API Integration Guide', type: 'md', category: 'Engineering', tags: ['engineering', 'api', 'docs', 'integration'], content: 'How to connect Nexus to your backend...' },
{ id: '7', title: 'Team Offline Retrospective', type: 'doc', category: 'HR', tags: ['hr', 'team', 'culture', 'retrospective'], content: 'Notes from the last quarterly offsite...' },
{ id: '8', title: 'Legal Contract - Acme Corp', type: 'pdf', category: 'Legal', tags: ['legal', 'contract', 'acme', 'sign'], content: 'Master services agreement...' },
{ id: '9', title: 'Mobile App UI Kit', type: 'sketch', category: 'Design', tags: ['design', 'mobile', 'ui', 'components'], content: 'React Native component library...' },
{ id: '10', title: 'Server Migration Logs', type: 'txt', category: 'DevOps', tags: ['devops', 'server', 'migration', 'aws'], content: 'Outage and recovery logs from Oct 12...' },
];
// Mock Commands (Command Palette Actions)
const commands = [
{ id: 'cmd-1', name: 'Switch to Dark Mode', action: 'toggle-dark', icon: 'moon', keywords: ['dark', 'night', 'theme', 'mode'] },
{ id: 'cmd-2', name: 'Create New Document', action: 'new-doc', icon: 'file-plus', keywords: ['create', 'new', 'doc', 'file', 'write'] },
{ id: 'cmd-3', name: 'Export All Data', action: 'export-data', icon: 'download', keywords: ['export', 'download', 'csv', 'json', 'data'] },
{ id: 'cmd-4', name: 'Open System Settings', action: 'open-settings', icon: 'settings', keywords: ['settings', 'preferences', 'config'] },
{ id: 'cmd-5', name: 'Invite Team Member', action: 'invite', icon: 'user-plus', keywords: ['invite', 'add', 'user', 'team', 'member'] },
{ id: 'cmd-6', name: 'Log Out', action: 'logout', icon: 'log-out', keywords: ['logout', 'exit', 'leave', 'quit'] },
];
/**
* ------------------------------------------------------------------
* SEMANTIC RE-RANKING ENGINE (Simulation)
* ------------------------------------------------------------------
* In a real environment, this would send queries to a vector DB or
* use Algolia's Semantic Search capabilities.
* Here we simulate "concept boosting" based on a simple weighted map.
*/
const semanticConceptMap = {
'money': ['finance', 'earnings', 'report', 'salary', 'cost'],
'design': ['brand', 'logo', 'colors', 'ui', 'components', 'figma', 'sketch'],
'tech': ['engineering', 'api', 'server', 'architecture', 'devops', 'code'],
'people': ['user', 'team', 'hr', 'retrospective', 'culture'],
'future': ['roadmap', 'plan', 'strategy', 'launch', 'nebula']
};
function calculateSemanticScore(item, query) {
let score = 0;
const queryLower = query.toLowerCase();
// 1. Direct Title Match (Algolia Text Score Simulation)
if (item.title.toLowerCase().includes(queryLower)) score += 10;
if (item.category.toLowerCase() === queryLower) score += 8;
// 2. Tag Matching (Keyword)
item.tags.forEach(tag => {
if (tag.includes(queryLower)) score += 5;
});
// 3. Semantic Boosting (The "AI" part)
// Check if any concept map key matches the query, and if the item has related tags.
for (const [concept, relatedTags] of Object.entries(semanticConceptMap)) {
if (queryLower.includes(concept) || relatedTags.includes(queryLower)) {
const intersection = item.tags.filter(tag => relatedTags.includes(tag));
score += intersection.length * 15; // Heavy semantic boost
}
}
// Add some randomness to simulate confidence float
return score + Math.random() * 2;
}
/**
* ------------------------------------------------------------------
* APPLICATION STATE & DOM ELEMENTS
* ------------------------------------------------------------------
*/
const state = {
isOpen: false,
query: '',
hits: [],
matchedCommands: []
};
const dom = {
hero: document.getElementById('hero'),
btn: document.getElementById('open-search-btn'),
modal: document.getElementById('command-palette'),
backdrop: document.getElementById('modal-backdrop'),
container: document.getElementById('modal-container'),
input: document.getElementById('search-input'),
grid: document.getElementById('results-grid'),
empty: document.getElementById('empty-state'),
status: document.getElementById('semantic-status'),
loader: document.getElementById('loading-indicator')
};
/**
* ------------------------------------------------------------------
* SEARCH LOGIC
* ------------------------------------------------------------------
*/
function performSearch(query) {
if (!query.trim()) {
state.hits = [];
state.matchedCommands = [];
render();
return;
}
// Show loading briefly to simulate network/AI
dom.loader.classList.remove('hidden');
setTimeout(() => {
const q = query.toLowerCase();
// 1. Filter & Score Commands
state.matchedCommands = commands.map(cmd => {
const matched = cmd.keywords.some(k => k.includes(q));
if (matched) return cmd;
}).filter(Boolean);
// 2. Filter & Score Documents
let scoredDocs = docs.map(doc => {
const score = calculateSemanticScore(doc, q);
return { ...doc, score };
// Filter out very low score docs if query exists
}).filter(doc => doc.score > 2 || doc.title.toLowerCase().includes(q));
// Sort by Score Descending
scoredDocs.sort((a, b) => b.score - a.score);
state.hits = scoredDocs;
dom.loader.classList.add('hidden');
render();
}, 150); // Artificial delay
}
/**
* ------------------------------------------------------------------
* RENDERING
* ------------------------------------------------------------------
*/
function highlightText(text, query) {
if (!query) return text;
const regex = new RegExp(`(${query})`, 'gi');
return text.replace(regex, '<span class="search-match">$1</span>');
}
function render() {
const { query, hits, matchedCommands } = state;
dom.grid.innerHTML = '';
// Show Empty State if nothing and not loading
if (hits.length === 0 && matchedCommands.length === 0 && query) {
dom.empty.classList.remove('hidden');
return;
} else {
dom.empty.classList.add('hidden');
}
// Render Commands Section (if any)
if (matchedCommands.length > 0) {
const cmdSection = document.createElement('div');
cmdSection.className = 'col-span-1 md:col-span-2 space-y-3';
cmdSection.innerHTML = `<h4 class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">AI Actions</h4>`;
matchedCommands.forEach(cmd => {
const btn = document.createElement('button');
btn.className = 'flex items-center justify-between p-4 rounded-xl bg-white/5 hover:bg-white/10 border border-transparent hover:border-nexus-blue/30 transition-all group w-full text-left';
btn.innerHTML = `
<div class="flex items-center space-x-3">
<div class="text-gray-400 group-hover:text-nexus-blue transition-colors">
<i data-lucide="${cmd.icon}" class="w-5 h-5"></i>
</div>
<span class="text-white font-medium">${highlightText(cmd.name, query)}</span>
</div>
<div class="text-xs text-gray-600 font-mono opacity-0 group-hover:opacity-100 transition-opacity">→</div>
`;
btn.onclick = () => executeCommand(cmd.action);
cmdSection.appendChild(btn);
// Add GSAP stagger entry effect
gsap.fromTo(btn, { opacity: 0, y: 20 }, { opacity: 1, y: 0, duration: 0.3, delay: Math.random() * 0.2 });
});
dom.grid.appendChild(cmdSection);
}
// Render Document Hits Section
if (hits.length > 0) {
const hitsSection = document.createElement('div');
hitsSection.className = 'col-span-1 md:col-span-2 space-y-3';
hitsSection.innerHTML = `<h4 class="text-xs font-bold text-gray-500 uppercase tracking-wider mb-3">Top Semantic Results</h4>`;
hits.forEach(hit => {
const card = document.createElement('div');
card.className = 'flex items-start p-4 rounded-xl bg-white/[0.02] hover:bg-white/5 border border-white/5 hover:border-nexus-blue/20 transition-all group cursor-pointer';
// Icon based on type/icon
let iconName = 'file-text';
if(hit.type === 'pdf') iconName = 'file';
if(hit.type === 'figma') iconName = 'pen-tool';
if(hit.type === 'ppt') iconName = 'presentation';
// Visualizing Re-ranking: Little confidence bar based on score
const scorePercent = Math.min(100, Math.floor(hit.score * 15)); // Arbitrary scaling
card.innerHTML = `
<div class="mr-4 mt-1 text-gray-500 group-hover:text-nexus-blue transition-colors">
<i data-lucide="${iconName}" class="w-6 h-6"></i>
</div>
<div class="flex-1 min-w-0">
<div class="flex justify-between items-start">
<h3 class="text-white font-medium text-base truncate pr-4">${highlightText(hit.title, query)}</h3>
<span class="text-[10px] font-mono text-nexus-blue bg-nexus-glow px-1.5 py-0.5 rounded border border-nexus-blue/20">${scorePercent}% Match</span>
</div>
<div class="flex items-center space-x-3 mt-1">
<span class="text-xs text-gray-600 uppercase">${hit.category}</span>
<span class="text-gray-800">•</span>
<span class="text-xs text-gray-500 truncate">${hit.type.toUpperCase()}</span>
</div>
<p class="text-sm text-gray-500 mt-2 line-clamp-1">${highlightText(hit.content, query)}</p>
</div>
<!-- Semantic Tag Visualization -->
<div class="hidden lg:flex flex-col items-end space-y-1 ml-4">
${hit.tags.slice(0,3).map(t => `<span class="text-[10px] text-gray-600 border border-gray-800 px-1 rounded">${t}</span>`).join('')}
</div>
`;
card.onclick = () => simulateOpen(hit);
hitsSection.appendChild(card);
gsap.fromTo(card, { opacity: 0, x: -20 }, { opacity: 1, x: 0, duration: 0.3, delay: 0.1 });
});
dom.grid.appendChild(hitsSection);
}
// Re-initialize Lucide icons for new content
lucide.createIcons();
}
function executeCommand(action) {
closeModal();
// Simulate feedback toast
showToast(`Executing: ${action}`);
}
function simulateOpen(item) {
closeModal();
showToast(`Opening document: ${item.title}`);
}
function showToast(message) {
const toast = document.createElement('div');
toast.className = 'fixed bottom-8 left-1/2 -translate-x-1/2 bg-white/10 backdrop-blur border border-white/20 text-white px-6 py-3 rounded-full shadow-lg z-[200] flex items-center space-x-2 text-sm font-medium transition-all duration-300 opacity-0 translate-y-4';
toast.innerHTML = `<i data-lucide="check-circle" class="w-4 h-4 text-green-400"></i> <span>${message}</span>`;
document.body.appendChild(toast);
lucide.createIcons();
gsap.to(toast, { opacity: 1, y: 0, duration: 0.3 });
setTimeout(() => {
gsap.to(toast, { opacity: 0, y: 10, duration: 0.3, onComplete: () => toast.remove() });
}, 3000);
}
/**
* ------------------------------------------------------------------
* MODAL & INPUT HANDLING
* ------------------------------------------------------------------
*/
function openModal() {
state.isOpen = true;
dom.modal.classList.remove('pointer-events-none', 'opacity-0');
dom.container.classList.remove('scale-95', 'opacity-0');
dom.input.focus();
// Disable scroll on body
document.body.style.overflow = 'hidden';
}
function closeModal() {
state.isOpen = false;
dom.modal.classList.add('pointer-events-none', 'opacity-0');
dom.container.classList.add('scale-95', 'opacity-0');
document.body.style.overflow = '';
// Clear state after animation? No, keep for history maybe.
state.query = '';
dom.input.value = '';
setTimeout(() => {
if(!state.isOpen) render(); // Clear UI
}, 300);
}
function handleInput(e) {
const val = e.target.value;
state.query = val;
performsemanticStatus(val);
performSearch(val);
}
function performsemanticStatus(query) {
if (query.length > 2) {
dom.status.classList.remove('hidden');
} else {
dom.status.classList.add('hidden');
}
}
// Event Listeners
dom.btn.addEventListener('click', openModal);
dom.backdrop.addEventListener('click', closeModal);
dom.input.addEventListener('input', handleInput);
document.addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
if (state.isOpen) closeModal(); else openModal();
}
if (e.key === 'Escape' && state.isOpen) {
closeModal();
}
});
/**
* ------------------------------------------------------------------
* THREE.JS BACKGROUND (Nexus Network)
* ------------------------------------------------------------------
* A subtle network of particles and lines to represent data connections.
* Dark aesthetic, reacts slightly to mouse.
*/
const canvas = document.getElementById('bg-canvas');
const scene = new THREE.Scene();
// Fog to fade out distant particles
scene.fog = new THREE.FogExp2(0x050505, 0.002);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer({ canvas: canvas, alpha: true, antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
// Particles
const particleCount = 200;
const geometry = new THREE.BufferGeometry();
const positions = new Float32Array(particleCount * 3);
const velocities = [];
for(let i = 0; i < particleCount * 3; i+=3) {
// Random spread
positions[i] = (Math.random() - 0.5) * 30;
positions[i+1] = (Math.random() - 0.5) * 30;
positions[i+2] = (Math.random() - 0.5) * 30;
velocities.push({
x: (Math.random() - 0.5) * 0.02,
y: (Math.random() - 0.5) * 0.02,
z: (Math.random() - 0.5) * 0.02
});
}
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
const material = new THREE.PointsMaterial({
size: 0.15,
color: 0x3b82f6, // Tailwind Blue-600
transparent: true,
opacity: 0.6
});
const particles = new THREE.Points(geometry, material);
scene.add(particles);
// Lines (connections)
const lineMaterial = new THREE.LineBasicMaterial({
color: 0x3b82f6,
transparent: true,
opacity: 0.08
});
const lineGeometry = new THREE.BufferGeometry();
const lines = new THREE.LineSegments(lineGeometry, lineMaterial);
scene.add(lines);
camera.position.z = 15;
// Interaction
let mouseX = 0;
let mouseY = 0;
document.addEventListener('mousemove', (e) => {
mouseX = (e.clientX - window.innerWidth / 2) * 0.001;
mouseY = (e.clientY - window.innerHeight / 2) * 0.001;
});
// Animation Loop
function animate() {
requestAnimationFrame(animate);
const positions = particles.geometry.attributes.position.array;
// Move particles
for(let i = 0; i < positions.length; i+=3) {
positions[i] += velocities[i/3].x;
positions[i+1] += velocities[i/3].y;
positions[i+2] += velocities[i/3].z;
// Bounce off boundaries (cube)
const limit = 15;
if (Math.abs(positions[i]) > limit) velocities[i/3].x *= -1;
if (Math.abs(positions[i+1]) > limit) velocities[i/3].y *= -1;
if (Math.abs(positions[i+2]) > limit) velocities[i/3].z *= -1;
}
particles.geometry.attributes.position.needsUpdate = true;
// Update Lines (connect particles that are close)
updateLines(positions);
// Rotate entire system slightly based on mouse
particles.rotation.y += 0.001;
particles.rotation.x += (mouseY - particles.rotation.x) * 0.05;
particles.rotation.y += (mouseX - particles.rotation.y) * 0.05;
lines.rotation.copy(particles.rotation);
renderer.render(scene, camera);
}
function updateLines(positions) {
const linePositions = [];
const maxDist = 2.5;
for(let i = 0; i < particleCount; i++) {
// Optimization: only check a subset of neighbors
for(let j = i + 1; j < particleCount; j++) {
const dx = positions[i*3] - positions[j*3];
const dy = positions[i*3+1] - positions[j*3+1];
const dz = positions[i*3+2] - positions[j*3+2];
const dist = Math.sqrt(dx*dx + dy*dy + dz*dz);
if (dist < maxDist) {
linePositions.push(
positions[i*3], positions[i*3+1], positions[i*3+2],
positions[j*3], positions[j*3+1], positions[j*3+2]
);
}
}
}
lines.geometry.setAttribute('position', new THREE.Float32BufferAttribute(linePositions, 3));
}
animate();
// Resize Handler
window.addEventListener('resize', () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
/**
* ------------------------------------------------------------------
* INIT
* ------------------------------------------------------------------
*/
window.addEventListener('load', () => {
// Initial Entrance Animation for Hero using GSAP
gsap.from('h1', { y: 50, opacity: 0, duration: 1, ease: 'power4.out' });
gsap.from('p', { y: 30, opacity: 0, duration: 1, delay: 0.2, ease: 'power4.out' });
gsap.from('#open-search-btn', { scale: 0.8, opacity: 0, duration: 0.8, delay: 0.4, ease: 'back.out(1.7)' });
gsap.from('.glass-panel', { y: 30, opacity: 0, duration: 0.8, stagger: 0.1, delay: 0.6, ease: 'power4.out' });
});
</script>
</body>
</html>