aura-glass
Version:
A comprehensive glassmorphism design system for React applications with 142+ production-ready components
298 lines (295 loc) • 9.96 kB
JavaScript
'use client';
import { jsx } from 'react/jsx-runtime';
import { useState, useRef, useEffect, useCallback, createContext } from 'react';
// Default user behavior
const DEFAULT_USER_BEHAVIOR = {
preferredIntensity: 0.6,
preferredContrast: 0.5,
readingTime: 5,
deviceType: 'desktop',
accessibilityNeeds: {
highContrast: false,
reducedMotion: false,
largerText: false
},
engagementLevel: 0.5,
returnRate: 0.5
};
// Create context
const AIGlassThemeContext = /*#__PURE__*/createContext(undefined);
function AIGlassThemeProvider({
children,
initialConfig = {},
storageKey = 'ai-glass-theme-data',
enableAnalytics = true
}) {
// Core state
const [currentTheme, setCurrentTheme] = useState(null);
const [isGenerating, setIsGenerating] = useState(false);
const [generationError, setGenerationError] = useState(null);
// Configuration state
const [aiConfig, setAIConfig] = useState({
adaptToSentiment: true,
adaptToContext: true,
adaptToTime: true,
adaptToSeason: true,
adaptToBehavior: true,
enableABTesting: false,
accessibilityFirst: true,
performanceMode: false,
...initialConfig
});
// User behavior state
const [userBehavior, setUserBehavior] = useState(DEFAULT_USER_BEHAVIOR);
// Theme management state
const [themeHistory, setThemeHistory] = useState([]);
const [favoriteThemes, setFavoriteThemes] = useState([]);
// Performance state
const [performanceMode, setPerformanceMode] = useState(false);
const [accessibilityMode, setAccessibilityMode] = useState(false);
// Refs for performance tracking
const generationStartTime = useRef(0);
const sentimentUsage = useRef(new Map());
const engagementHistory = useRef([]);
// Initialize on mount
useEffect(() => {
const initializeAI = async () => {
try {
// Load persisted data
const saved = localStorage.getItem(storageKey);
if (saved) {
const data = JSON.parse(saved);
if (data.userBehavior) {
setUserBehavior({
...DEFAULT_USER_BEHAVIOR,
...data.userBehavior
});
}
if (data.themeHistory) {
setThemeHistory(data.themeHistory);
}
if (data.favoriteThemes) {
setFavoriteThemes(data.favoriteThemes);
}
if (data.aiConfig) {
setAIConfig({
...aiConfig,
...data.aiConfig
});
}
}
console.log('AI Glass Theme Provider initialized');
} catch (error) {
console.error('Failed to initialize AI Glass Theme Provider:', error);
setGenerationError('Failed to initialize AI theme system');
}
};
initializeAI();
}, []);
// Persist data when state changes
useEffect(() => {
const dataToSave = {
userBehavior,
themeHistory: themeHistory.slice(-50),
// Keep last 50 themes
favoriteThemes,
aiConfig,
timestamp: new Date().toISOString()
};
try {
localStorage.setItem(storageKey, JSON.stringify(dataToSave));
} catch (error) {
console.warn('Failed to save AI theme data:', error);
}
}, [userBehavior, themeHistory, favoriteThemes, aiConfig, storageKey]);
// Update AI config
const updateAIConfig = useCallback(config => {
setAIConfig(prev => {
const newConfig = {
...prev,
...config
};
return newConfig;
});
}, []);
// Generate theme from content (simplified implementation)
const generateTheme = useCallback(async (content, context = {}) => {
setIsGenerating(true);
setGenerationError(null);
generationStartTime.current = performance.now();
try {
// Simulate AI processing delay
await new Promise(resolve => setTimeout(resolve, 500));
// Simple theme generation based on content analysis
const contentLength = content.length;
const hasKeywords = ['urgent', 'important', 'breaking'].some(word => content.toLowerCase().includes(word));
// Generate colors based on content analysis
const baseHue = hasKeywords ? 0 : Math.random() * 360; // Red for urgent, random for others
const saturation = 0.7;
const lightness = 0.6;
const theme = {
id: `theme-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
name: `Generated Theme ${themeHistory.length + 1}`,
colors: {
primary: `hsl(${baseHue}, ${saturation * 100}%, ${lightness * 100}%)`,
secondary: `hsl(${(baseHue + 60) % 360}, ${saturation * 100}%, ${(lightness + 0.1) * 100}%)`,
accent: `hsl(${(baseHue + 120) % 360}, ${saturation * 100}%, ${(lightness - 0.1) * 100}%)`,
background: `hsl(${baseHue}, ${saturation * 50}%, ${lightness * 20}%)`,
surface: `hsl(${baseHue}, ${saturation * 30}%, ${lightness * 40}%)`,
text: `hsl(${baseHue}, ${saturation * 20}%, ${lightness * 90}%)`
},
glass: {
blur: Math.max(8, Math.min(20, contentLength / 100)),
opacity: hasKeywords ? 0.9 : 0.7,
borderRadius: hasKeywords ? '8px' : '16px'
},
animations: {
duration: performanceMode ? 0.1 : 0.5,
easing: 'ease-out'
},
metadata: {
sentiment: hasKeywords ? 'urgent' : 'neutral',
context: context.type || 'general',
created: new Date()
}
};
// Update theme history
setThemeHistory(prev => [theme, ...prev.slice(0, 49)]);
setCurrentTheme(theme);
return theme;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Theme generation failed';
setGenerationError(errorMessage);
console.error('Theme generation error:', error);
throw error;
} finally {
setIsGenerating(false);
}
}, [themeHistory.length, performanceMode]);
// Generate theme from sentiment
const generateThemeFromSentiment = useCallback(async (sentiment, context = {}) => {
// Track sentiment usage
const currentCount = sentimentUsage.current.get(sentiment.sentiment) || 0;
sentimentUsage.current.set(sentiment.sentiment, currentCount + 1);
// Create mock content based on sentiment
const mockContent = `This is ${sentiment.sentiment} content with ${sentiment.intensity} intensity`;
return generateTheme(mockContent, context);
}, [generateTheme]);
// Update user behavior
const updateUserBehavior = useCallback(behavior => {
setUserBehavior(prev => ({
...prev,
...behavior
}));
}, []);
// Track user interaction with theme
const trackInteraction = useCallback((themeId, engagement, satisfaction) => {
if (!enableAnalytics) return;
// Record engagement
engagementHistory.current.push({
timestamp: new Date(),
engagement
});
// Keep only last 100 engagement records
if (engagementHistory.current.length > 100) {
engagementHistory.current = engagementHistory.current.slice(-100);
}
// Update user behavior based on interaction
const currentEngagement = userBehavior.engagementLevel;
const newEngagement = (currentEngagement + engagement) / 2;
updateUserBehavior({
engagementLevel: newEngagement,
returnRate: satisfaction > 0.7 ? Math.min(1, userBehavior.returnRate + 0.1) : userBehavior.returnRate
});
}, [enableAnalytics, userBehavior, updateUserBehavior]);
// Favorites management
const addToFavorites = useCallback(theme => {
setFavoriteThemes(prev => {
if (prev.find(t => t.id === theme.id)) return prev;
return [theme, ...prev];
});
}, []);
const removeFromFavorites = useCallback(themeId => {
setFavoriteThemes(prev => prev.filter(t => t.id !== themeId));
}, []);
// Cache and data management
const clearCache = useCallback(() => {
setThemeHistory([]);
sentimentUsage.current.clear();
engagementHistory.current = [];
try {
localStorage.removeItem(storageKey);
} catch (error) {
console.warn('Failed to clear cache:', error);
}
}, [storageKey]);
const exportAIData = useCallback(() => {
const exportData = {
version: '1.0.0',
timestamp: new Date().toISOString(),
aiConfig,
userBehavior,
themeHistory,
favoriteThemes
};
return JSON.stringify(exportData, null, 2);
}, [aiConfig, userBehavior, themeHistory, favoriteThemes]);
const importAIData = useCallback(data => {
try {
const importData = JSON.parse(data);
if (importData.aiConfig) {
updateAIConfig(importData.aiConfig);
}
if (importData.userBehavior) {
updateUserBehavior(importData.userBehavior);
}
if (importData.themeHistory) {
setThemeHistory(importData.themeHistory);
}
if (importData.favoriteThemes) {
setFavoriteThemes(importData.favoriteThemes);
}
return true;
} catch (error) {
console.error('Failed to import AI data:', error);
return false;
}
}, [updateAIConfig, updateUserBehavior]);
// Context value
const contextValue = {
// Current state
currentTheme,
isGenerating,
generationError,
// Configuration
aiConfig,
updateAIConfig,
// Theme generation
generateTheme,
generateThemeFromSentiment,
// Theme management
themeHistory,
favoriteThemes,
addToFavorites,
removeFromFavorites,
// User behavior
userBehavior,
updateUserBehavior,
trackInteraction,
// Performance and accessibility
performanceMode,
setPerformanceMode,
accessibilityMode,
setAccessibilityMode,
// Data management
clearCache,
exportAIData,
importAIData
};
return jsx(AIGlassThemeContext.Provider, {
value: contextValue,
children: children
});
}
export { AIGlassThemeProvider, AIGlassThemeProvider as default };
//# sourceMappingURL=AIGlassThemeProvider.js.map