MorphUI is a full-stack adaptive UI application that uses AI to dynamically transform its interface based on user behavior and mood.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β User Interaction Layer β
β (Clicks, Scrolls, Navigation) β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β React Frontend (Port 5173) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Components: β
β β’ Dashboard - Main UI container β
β β’ FeatureCard - Individual feature modules β
β β’ AdaptationIndicator - Loading state β
β β’ DemoControls - Manual controls β
β β
β State Management (Zustand): β
β β’ Current theme, layout, features β
β β’ Mood analysis results β
β β’ Adaptation state β
β β
β Theme Engine: β
β β’ 5 themes (minimal-dark, minimal-light, vibrant, β
β gamified, productivity) β
β β’ 3 spacing modes (compact, normal, spacious) β
β β’ 3 animation levels (minimal, normal, playful) β
β β
β Behavior Tracking: β
β β’ Click tracking with coordinates β
β β’ Scroll depth monitoring β
β β’ Navigation pattern detection β
β β’ Feature usage analytics β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β REST API / WebSocket (Future)
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β Node.js Backend (Port 3000) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β API Routes: β
β β’ /api/analytics - Behavior tracking endpoints β
β β’ /api/adaptation - UI adaptation endpoints β
β β
β Services: β
β β’ BehaviorAnalyzer - Session management & metrics β
β β’ OllamaService - Local AI-powered analysis β
β β
β Behavior Analysis: β
β β’ Click frequency calculation β
β β’ Error rate detection β
β β’ Dwell time analysis β
β β’ Navigation pattern recognition β
β β’ Feature engagement scoring β
βββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β Local HTTP (localhost:11434)
βββββββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β Ollama Local AI β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Capabilities: β
β β’ Mood inference from behavioral metrics β
β β’ UI adaptation recommendations β
β β’ Reasoning explanation generation β
β β’ π Privacy-first: All processing on your machine β
β β
β Models Supported: β
β β’ gemma3:270m (Default - ultra-compact, very fast) β
β β’ gemma2:2b (Lightweight) β
β β’ gemma2:9b (More accurate) β
β β’ llama3.2:3b (Alternative) β
β β’ phi3:mini (Compact) β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
User clicks button
β
BehaviorTracking Hook captures event
β
POST /api/analytics/interaction {
sessionId: "session-123",
interaction: {
type: "click",
target: "dashboard",
coordinates: { x: 100, y: 200 },
timestamp: 1234567890
}
}
β
Backend stores in session memoryFrontend requests metrics
β
GET /api/analytics/metrics/session-123
β
Backend calculates:
- avgClickFrequency: 8.5 clicks/min
- errorRate: 0.05
- avgDwellTime: 5.2 seconds
- navigationPattern: "exploratory"
β
Returns BehaviorMetrics objectAdaptation cycle triggered (every 30s or manual)
β
POST /api/adaptation/recommend {
sessionId: "session-123",
currentState: {
theme: "minimal-light",
layout: "grid",
features: [...]
}
}
β
Backend:
1. Gets behavior metrics
2. Calls Gemini AI for mood analysis
3. Calls Gemini AI for UI recommendations
β
Gemini analyzes:
Mood: "relaxed" (confidence: 0.85)
Recommendation: {
theme: "vibrant",
layout: "cards",
features: [...],
reasoning: "User is exploring comfortably"
}
β
Frontend applies adaptation
β
UI morphs with smooth transitionsApp.tsx (Root)
βββ ThemeProvider (styled-components)
β βββ GlobalStyles
β βββ Dashboard
β β βββ Header
β β βββ MoodBadge
β β βββ AdaptationInfo
β β βββ FeaturesGrid
β β βββ FeatureCard (x15)
β βββ AdaptationIndicator (Fixed position)
β βββ DemoControls (Fixed position)
β βββ ToggleButton
β βββ Panel
β βββ Mode Selection
β βββ Action Buttons
index.ts (Express Server)
βββ Routes
β βββ /api/analytics
β β βββ POST /session
β β βββ POST /interaction
β β βββ POST /pageview
β β βββ GET /metrics/:sessionId
β β βββ GET /session/:sessionId
β βββ /api/adaptation
β βββ POST /recommend
β βββ POST /mood
β βββ POST /feedback
βββ Services
βββ BehaviorAnalyzer
β βββ Session Management
β βββ Interaction Tracking
β βββ Metrics Calculation
β βββ Cleanup Timer
βββ OllamaService
βββ Mood Analysis
βββ UI Adaptation
βββ Fallback Logic
AppStore {
// UI Configuration
theme: ThemeType
layout: LayoutType
visibleFeatures: string[]
animations: 'minimal' | 'normal' | 'playful'
spacing: 'compact' | 'normal' | 'spacious'
complexity: 'simple' | 'moderate' | 'advanced'
// AI State
currentMood: MoodAnalysis | null
adaptationReasoning: string
isAdapting: boolean
// Demo
demoMode: 'auto' | 'stress' | 'focus' | 'explorer' | 'relax' | null
// Actions
applyAdaptation(adaptation, mood)
setDemoMode(mode)
setIsAdapting(isAdapting)
resetToDefault()
}- Creation: User visits β
sessionIdgenerated β Stored insessionStorage - Tracking: All interactions associated with
sessionId - Analysis: Metrics calculated on-demand from session data
- Expiration: Sessions auto-expire after 30 minutes of inactivity
- Cleanup: Expired sessions removed every 10 minutes
{
sessionId: "session-1234567890-abc123",
userId: "user-456" (optional),
startTime: 1234567890000,
lastActivity: 1234567890000,
interactions: [
{ type: "click", timestamp: ..., target: "dashboard" },
{ type: "scroll", timestamp: ..., metadata: {...} }
],
pageViews: ["/", "/analytics", "/settings"],
featureUsage: {
"dashboard": 12,
"analytics": 5,
"settings": 2
}
}Analyze the following user behavior metrics and determine their current mood state.
Metrics:
- Average click frequency: 8.5 clicks/minute
- Error rate: 5.0%
- Average dwell time: 5.2 seconds
- Navigation pattern: exploratory
- Interaction speed: normal
- Scroll depth: 70%
Determine the user's mood from: stressed, focused, relaxed, exploratory, frustrated
Respond ONLY with a JSON object: {...}
Generate an optimal UI adaptation based on user behavior and mood.
Current UI State:
- Theme: minimal-light
- Layout: grid
- Visible Features: dashboard, analytics, calendar, tasks, settings
User Mood: relaxed (confidence: 0.85)
Behavior Metrics: {...}
Respond ONLY with a JSON object: {...}
If Gemini API fails:
-
Rule-based mood detection:
- High error rate + rapid clicks β stressed
- Low click frequency + long dwell time β relaxed
- Exploratory navigation + deep scrolling β exploratory
-
Predefined adaptations:
- Each mood has a default UI configuration
- Guaranteed consistent user experience
Theme {
name: string
colors: {
primary, secondary, background, surface,
text, textSecondary, border,
success, warning, error, accent
}
spacing: { xs, sm, md, lg, xl }
borderRadius: string
shadows: { sm, md, lg }
transitions: { fast, normal, slow }
}getTheme(themeName, spacing, animations) β Theme
// Example: Generate "vibrant" theme with "spacious" spacing and "playful" animations
getTheme('vibrant', 'spacious', 'playful') β {
name: 'Vibrant',
colors: { ... }, // Vibrant color palette
spacing: { xs: '12px', sm: '24px', ... }, // Spacious
transitions: {
fast: 'all 0.2s cubic-bezier(...)', // Playful
normal: 'all 0.4s cubic-bezier(...)',
slow: 'all 0.6s cubic-bezier(...)'
}
}- Debounced tracking: Scroll/hover events debounced to 300ms
- Interaction limit: Only last 100 interactions stored per session
- Animation optimization: Framer Motion for GPU-accelerated animations
- Code splitting: Dynamic imports for large components (future)
- In-memory sessions: Fast access, auto-cleanup
- Rate limiting: 100 requests per 15 minutes per IP
- Gemini API: Cached responses for identical queries (future)
- Metrics calculation: On-demand, not stored
- CORS: Configured for specific frontend URL
- Helmet: Security headers enabled
- Rate Limiting: Prevents abuse
- Input Validation: All endpoints validate inputs
- No sensitive data: No passwords or PII stored
- API keys: Never committed to git
- Separate configs: Dev vs. production keys
- Secure transmission: HTTPS in production
- In-memory sessions: Won't scale across multiple servers
- No persistence: Sessions lost on server restart
- Single server: Not load-balanced
- Redis: Distributed session storage
- PostgreSQL: User profiles, adaptation history
- Load balancing: Multiple backend instances
- WebSocket: Real-time bidirectional communication
- CDN: Static asset delivery
- Service logic (BehaviorAnalyzer, GeminiService)
- Utility functions
- State management
- API endpoints
- Service interactions
- Database operations (future)
- User flows
- Adaptation cycles
- Cross-browser compatibility
- Load testing (k6, Artillery)
- Memory profiling
- API response times
cd packages/frontend
npm run build
# Deploy dist/ foldercd packages/backend
npm run build
# Deploy with Procfile or railway.json# Frontend
VITE_API_URL=https://api.morphui.com/api
# Backend
GEMINI_API_KEY=your_key_here
NODE_ENV=production
FRONTEND_URL=https://morphui.comThis architecture enables MorphUI to:
β
Track user behavior in real-time
β
Analyze mood using AI
β
Adapt UI dynamically
β
Provide smooth, delightful transitions
β
Scale to production workloads