aura-glass
Version:
A comprehensive glassmorphism design system for React applications with 142+ production-ready components
886 lines (883 loc) • 34.3 kB
JavaScript
'use client';
import { jsx, jsxs } from 'react/jsx-runtime';
import { useReducedMotion } from '../../hooks/useReducedMotion.js';
import { useRef, useState, useEffect, useCallback, useContext, createContext } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '../../lib/utilsComprehensive.js';
// Advanced quantum-inspired optimization algorithm
class QuantumOptimizer {
constructor() {
this.quantumStates = new Map();
this.entanglementMatrix = [];
this.observationHistory = [];
}
createQuantumState(systemId, dimensions) {
// Initialize quantum state as probability amplitudes
const state = Array.from({
length: dimensions
}, () => Math.random() - 0.5);
const norm = Math.sqrt(state.reduce((sum, val) => sum + val * val, 0));
this.quantumStates.set(systemId, state.map(val => val / norm));
}
entangleSystems(system1, system2, strength) {
const state1 = this.quantumStates.get(system1);
const state2 = this.quantumStates.get(system2);
if (state1 && state2) {
// Simulate quantum entanglement through correlated state updates
for (let i = 0; i < Math.min(state1.length, state2.length); i++) {
const correlation = strength * (Math.random() - 0.5);
state1[i] += correlation * state2[i];
state2[i] += correlation * state1[i];
}
}
}
observe(systemId) {
const state = this.quantumStates.get(systemId);
if (!state) return 0;
// Collapse quantum state to measured value
const probabilities = state.map(amplitude => amplitude * amplitude);
const random = Math.random();
let cumulative = 0;
for (let i = 0; i < probabilities.length; i++) {
cumulative += probabilities[i];
if (random < cumulative) {
this.observationHistory.push({
state: systemId,
outcome: i / probabilities.length
});
return i / probabilities.length;
}
}
return 0;
}
evolveStates() {
// Quantum evolution based on Schrödinger equation simulation
this.quantumStates.forEach((state, systemId) => {
const evolutionMatrix = this.generateEvolutionMatrix(state.length);
const newState = this.applyMatrix(evolutionMatrix, state);
this.quantumStates.set(systemId, newState);
});
}
generateEvolutionMatrix(size) {
const matrix = Array.from({
length: size
}, () => Array(size).fill(0));
for (let i = 0; i < size; i++) {
for (let j = 0; j < size; j++) {
matrix[i][j] = Math.cos(0.1 * (i - j)) * Math.exp(-0.01 * (i - j) * (i - j));
}
}
return matrix;
}
applyMatrix(matrix, state) {
return matrix.map(row => row.reduce((sum, val, idx) => sum + val * state[idx], 0));
}
}
// Self-healing neural network for system optimization
class SelfHealingNetwork {
constructor(topology) {
this.topology = topology;
this.weights = [];
this.biases = [];
this.healthScores = [];
this.redundantNodes = new Map();
this.initializeNetwork();
}
initializeNetwork() {
for (let i = 0; i < this.topology.length - 1; i++) {
const layerWeights = Array.from({
length: this.topology[i + 1]
}, () => Array.from({
length: this.topology[i]
}, () => Math.random() * 2 - 1));
this.weights.push(layerWeights);
const layerBiases = Array.from({
length: this.topology[i + 1]
}, () => Math.random() * 2 - 1);
this.biases.push(layerBiases);
this.healthScores.push(...Array(this.topology[i + 1]).fill(1.0));
}
}
forward(input) {
let activation = input;
for (let layer = 0; layer < this.weights.length; layer++) {
const newActivation = [];
for (let node = 0; node < this.weights[layer].length; node++) {
let sum = this.biases[layer][node];
for (let prevNode = 0; prevNode < activation.length; prevNode++) {
sum += this.weights[layer][node][prevNode] * activation[prevNode];
}
// Apply health-adjusted activation
const healthFactor = this.healthScores[layer * this.topology[layer] + node] || 1.0;
newActivation.push(this.relu(sum) * healthFactor);
}
activation = newActivation;
}
return activation;
}
relu(x) {
return Math.max(0, x);
}
diagnoseHealth() {
// Monitor for degraded nodes
this.healthScores = this.healthScores.map((health, index) => {
const degradation = Math.random() * 0.01; // Simulate gradual degradation
return Math.max(0.1, health - degradation);
});
}
healNetwork() {
// Replace unhealthy nodes with redundant ones
this.healthScores.forEach((health, index) => {
if (health < 0.5) {
this.regenerateNode(index);
}
});
}
regenerateNode(nodeIndex) {
const layerIndex = Math.floor(nodeIndex / this.topology.reduce((sum, size) => sum + size, 0));
const nodeInLayer = nodeIndex % this.topology[layerIndex];
// Reinitialize weights and biases for the damaged node
if (this.weights[layerIndex] && this.weights[layerIndex][nodeInLayer]) {
this.weights[layerIndex][nodeInLayer] = this.weights[layerIndex][nodeInLayer].map(() => Math.random() * 2 - 1);
}
if (this.biases[layerIndex] && this.biases[layerIndex][nodeInLayer] !== undefined) {
this.biases[layerIndex][nodeInLayer] = Math.random() * 2 - 1;
}
this.healthScores[nodeIndex] = 1.0;
}
}
// Main meta-engine class
class GlassMetaEngineCore {
constructor() {
this.systemMetrics = new Map();
this.optimizations = [];
this.evolutions = [];
this.systemHealth = new Map();
this.quantumOptimizer = new QuantumOptimizer();
this.selfHealingNetwork = new SelfHealingNetwork([20, 40, 20, 10]);
this.evolutionStage = 0;
this.learningRate = 0.001;
this.initializeEvolution();
this.startEvolutionCycle();
}
initializeEvolution() {
// Initialize quantum states for known glass systems
const glassSystems = ["GlassPhysicsEngine", "GlassMorphingEngine", "Glass3DEngine", "OrganicAnimationEngine", "EmotionalIntelligenceEngine", "SpatialComputingEngine", "AIPersonalizationEngine"];
glassSystems.forEach(system => {
this.quantumOptimizer.createQuantumState(system, 8);
this.systemHealth.set(system, {
systemId: system,
healthScore: 1.0,
issues: [],
recommendations: [],
trend: "stable"
});
});
// Create quantum entanglements between related systems
this.quantumOptimizer.entangleSystems("GlassPhysicsEngine", "Glass3DEngine", 0.7);
this.quantumOptimizer.entangleSystems("EmotionalIntelligenceEngine", "OrganicAnimationEngine", 0.8);
this.quantumOptimizer.entangleSystems("SpatialComputingEngine", "Glass3DEngine", 0.6);
}
startEvolutionCycle() {
// Continuous evolution cycle
setInterval(() => {
this.evolveSystem();
}, 5000); // Every 5 seconds
// Health monitoring cycle
setInterval(() => {
this.monitorSystemHealth();
}, 10000); // Every 10 seconds
// Neural network healing
setInterval(() => {
this.selfHealingNetwork.diagnoseHealth();
this.selfHealingNetwork.healNetwork();
}, 30000); // Every 30 seconds
}
recordSystemUsage(metric) {
if (!this.systemMetrics.has(metric.systemId)) {
this.systemMetrics.set(metric.systemId, []);
}
const systemMetrics = this.systemMetrics.get(metric.systemId);
systemMetrics.push(metric);
// Keep only recent metrics (last 1000)
if (systemMetrics.length > 1000) {
systemMetrics.splice(0, systemMetrics.length - 1000);
}
this.analyzeMetrics(metric.systemId);
this.generateOptimizations(metric.systemId);
}
analyzeMetrics(systemId) {
const metrics = this.systemMetrics.get(systemId);
if (!metrics || metrics.length < 10) return;
const recent = metrics.slice(-50);
const avgPerformance = recent.reduce((sum, m) => sum + m.performanceMetrics.renderTime, 0) / recent.length;
const avgMemory = recent.reduce((sum, m) => sum + m.performanceMetrics.memoryUsage, 0) / recent.length;
const avgSatisfaction = recent.reduce((sum, m) => sum + m.userSatisfactionScore, 0) / recent.length;
// Update system health
const health = this.systemHealth.get(systemId);
if (health) {
const newHealthScore = this.calculateHealthScore(avgPerformance, avgMemory, avgSatisfaction);
health.healthScore = newHealthScore;
health.trend = newHealthScore > health.healthScore ? "improving" : newHealthScore < health.healthScore ? "declining" : "stable";
// Identify issues
if (avgPerformance > 100) {
health.issues.push({
type: "performance",
severity: avgPerformance > 200 ? "high" : "medium",
description: `Average render time is ${avgPerformance.toFixed(1)}ms`,
autoFixable: true
});
}
if (avgMemory > 50) {
health.issues.push({
type: "memory-leak",
severity: avgMemory > 100 ? "critical" : "medium",
description: `High memory usage detected: ${avgMemory.toFixed(1)}MB`,
autoFixable: false
});
}
if (avgSatisfaction < 0.7) {
health.issues.push({
type: "user-friction",
severity: avgSatisfaction < 0.5 ? "high" : "medium",
description: `User satisfaction below threshold: ${(avgSatisfaction * 100).toFixed(1)}%`,
autoFixable: true
});
}
}
}
calculateHealthScore(performance, memory, satisfaction) {
const perfScore = Math.max(0, 1 - performance / 200);
const memScore = Math.max(0, 1 - memory / 100);
const satScore = satisfaction;
return perfScore * 0.3 + memScore * 0.2 + satScore * 0.5;
}
generateOptimizations(systemId) {
const health = this.systemHealth.get(systemId);
if (!health || health.healthScore > 0.8) return;
// Generate optimization based on identified issues
health.issues.forEach(issue => {
const optimization = this.createOptimization(systemId, issue);
if (optimization) {
this.optimizations.push(optimization);
}
});
// Use neural network to predict optimal configurations
const metrics = this.systemMetrics.get(systemId);
if (metrics && metrics.length > 20) {
const input = this.metricsToVector(metrics.slice(-10));
const neuralOutput = this.selfHealingNetwork.forward(input);
const aiOptimization = this.interpretNeuralOutput(systemId, neuralOutput);
if (aiOptimization) {
this.optimizations.push(aiOptimization);
}
}
}
createOptimization(systemId, issue) {
const optimizationId = `opt_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
switch (issue.type) {
case "performance":
return {
id: optimizationId,
targetSystem: systemId,
optimizationType: "performance",
description: "Implement render optimization and frame batching",
impact: 0.8,
confidence: 0.9,
implementation: 'enableFrameBatching: true, renderOptimization: "aggressive"',
estimatedGain: {
performance: "40-60% faster rendering",
userExperience: "Smoother animations"
},
priority: "high",
autoApplyable: true
};
case "memory-leak":
return {
id: optimizationId,
targetSystem: systemId,
optimizationType: "memory",
description: "Enable garbage collection optimization and memory pooling",
impact: 0.7,
confidence: 0.8,
implementation: 'memoryPooling: true, gcOptimization: "aggressive"',
estimatedGain: {
memory: "30-50% reduction in memory usage",
performance: "Reduced GC pauses"
},
priority: "medium",
autoApplyable: false
};
case "user-friction":
return {
id: optimizationId,
targetSystem: systemId,
optimizationType: "user-experience",
description: "Adaptive UI optimization based on user behavior patterns",
impact: 0.6,
confidence: 0.75,
implementation: 'adaptiveUI: true, behaviorLearning: "enhanced"',
estimatedGain: {
userExperience: "Improved interaction flow",
performance: "Predictive loading"
},
priority: "medium",
autoApplyable: true
};
}
return null;
}
interpretNeuralOutput(systemId, output) {
const maxIndex = output.indexOf(Math.max(...output));
const confidence = output[maxIndex];
if (confidence < 0.6) return null;
const optimizationTypes = ["performance", "memory", "battery", "network", "accessibility"];
const type = optimizationTypes[maxIndex % optimizationTypes.length];
return {
id: `neural_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
targetSystem: systemId,
optimizationType: type,
description: `AI-suggested ${type} optimization`,
impact: confidence,
confidence,
implementation: `neuralOptimization: {type: "${type}", strength: ${confidence.toFixed(2)}}`,
estimatedGain: {
[type]: `${(confidence * 50).toFixed(0)}% improvement expected`
},
priority: confidence > 0.8 ? "high" : "medium",
autoApplyable: confidence > 0.9
};
}
metricsToVector(metrics) {
const vector = new Array(20).fill(0);
metrics.forEach((metric, index) => {
if (index < 5) {
vector[index * 4] = metric.performanceMetrics.renderTime / 200;
vector[index * 4 + 1] = metric.performanceMetrics.memoryUsage / 100;
vector[index * 4 + 2] = metric.performanceMetrics.interactionLatency / 50;
vector[index * 4 + 3] = metric.userSatisfactionScore;
}
});
return vector;
}
evolveSystem() {
this.evolutionStage++;
// Quantum evolution
this.quantumOptimizer.evolveStates();
// Analyze system correlations for emergent behaviors
this.detectEmergentBehaviors();
// Apply successful optimizations
this.applyOptimizations();
// Generate system evolutions
this.generateEvolutions();
}
detectEmergentBehaviors() {
const systems = Array.from(this.systemMetrics.keys());
for (let i = 0; i < systems.length; i++) {
for (let j = i + 1; j < systems.length; j++) {
const correlation = this.calculateSystemCorrelation(systems[i], systems[j]);
if (correlation > 0.8) {
const evolution = {
id: `emergence_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
evolutionType: "emergent-behavior",
description: `Strong correlation detected between ${systems[i]} and ${systems[j]}`,
affectedSystems: [systems[i], systems[j]],
evolutionStage: "detected",
confidence: correlation,
potentialImpact: 0.7
};
this.evolutions.push(evolution);
}
}
}
}
calculateSystemCorrelation(system1, system2) {
const metrics1 = this.systemMetrics.get(system1)?.slice(-20);
const metrics2 = this.systemMetrics.get(system2)?.slice(-20);
if (!metrics1 || !metrics2 || metrics1.length < 10 || metrics2.length < 10) return 0;
// Simple correlation calculation
const perf1 = metrics1.map(m => m.performanceMetrics.renderTime);
const perf2 = metrics2.map(m => m.performanceMetrics.renderTime);
const mean1 = perf1.reduce((sum, val) => sum + val, 0) / perf1.length;
const mean2 = perf2.reduce((sum, val) => sum + val, 0) / perf2.length;
let numerator = 0;
let denom1 = 0;
let denom2 = 0;
for (let i = 0; i < Math.min(perf1.length, perf2.length); i++) {
const diff1 = perf1[i] - mean1;
const diff2 = perf2[i] - mean2;
numerator += diff1 * diff2;
denom1 += diff1 * diff1;
denom2 += diff2 * diff2;
}
const correlation = numerator / Math.sqrt(denom1 * denom2);
return Math.abs(correlation);
}
applyOptimizations() {
const autoApplyable = this.optimizations.filter(opt => opt.autoApplyable && opt.confidence > 0.8);
autoApplyable.forEach(optimization => {
// Simulate applying optimization
console.log(`Auto-applying optimization: ${optimization.description} for ${optimization.targetSystem}`);
// Update system health after optimization
const health = this.systemHealth.get(optimization.targetSystem);
if (health) {
health.healthScore = Math.min(1.0, health.healthScore + optimization.impact * 0.1);
health.issues = health.issues.filter(issue => issue.type !== optimization.optimizationType || !issue.autoFixable);
}
});
// Remove applied optimizations
this.optimizations = this.optimizations.filter(opt => !autoApplyable.includes(opt));
}
generateEvolutions() {
if (this.evolutionStage % 10 === 0) {
// Every 10 evolution cycles
const evolution = {
id: `evo_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
evolutionType: "adaptive-learning",
description: "Enhanced learning algorithm deployment",
affectedSystems: Array.from(this.systemMetrics.keys()),
evolutionStage: "detected",
confidence: 0.75 + Math.random() * 0.2,
potentialImpact: 0.6 + Math.random() * 0.3
};
this.evolutions.push(evolution);
}
}
monitorSystemHealth() {
this.systemHealth.forEach((health, systemId) => {
// Auto-heal critical issues
const criticalIssues = health.issues.filter(issue => issue.severity === "critical");
if (criticalIssues.length > 0) {
criticalIssues.forEach(issue => {
if (issue.autoFixable) {
// Apply emergency healing
console.log(`Emergency healing applied to ${systemId} for ${issue.type}`);
health.healthScore = Math.max(health.healthScore, 0.5);
}
});
}
});
}
// Public API
getSystemMetrics() {
return new Map(this.systemMetrics);
}
getOptimizations() {
return [...this.optimizations];
}
getEvolutions() {
return [...this.evolutions];
}
getSystemHealth() {
return new Map(this.systemHealth);
}
getQuantumStates() {
return Array.from(this.systemHealth.keys()).map(system => ({
system,
coherence: this.quantumOptimizer.observe(system)
}));
}
}
// React Context for the meta-engine
const GlassMetaEngineContext = /*#__PURE__*/createContext({
engine: null,
recordUsage: () => {},
optimizations: [],
evolutions: [],
systemHealth: new Map()
});
// Provider component
function GlassMetaEngineProvider({
children,
onEvolution,
onOptimization
}) {
useReducedMotion();
const engineRef = useRef();
const [optimizations, setOptimizations] = useState([]);
const [evolutions, setEvolutions] = useState([]);
const [systemHealth, setSystemHealth] = useState(new Map());
// Initialize engine
useEffect(() => {
engineRef.current = new GlassMetaEngineCore();
// Update state periodically
const updateInterval = setInterval(() => {
if (engineRef.current) {
const newOptimizations = engineRef.current.getOptimizations();
const newEvolutions = engineRef.current.getEvolutions();
const newHealth = engineRef.current.getSystemHealth();
setOptimizations(newOptimizations);
setEvolutions(newEvolutions);
setSystemHealth(newHealth);
// Trigger callbacks
newOptimizations.forEach(opt => onOptimization?.(opt));
newEvolutions.forEach(evo => onEvolution?.(evo));
}
}, 1000);
return () => clearInterval(updateInterval);
}, [onEvolution, onOptimization]);
const recordUsage = useCallback(metric => {
engineRef.current?.recordSystemUsage(metric);
}, []);
const value = {
engine: engineRef.current || null,
recordUsage,
optimizations,
evolutions,
systemHealth
};
return jsx(GlassMetaEngineContext.Provider, {
value: value,
children: children
});
}
// Hook to use the meta-engine
function useGlassMetaEngine() {
const context = useContext(GlassMetaEngineContext);
if (!context) {
throw new Error("useGlassMetaEngine must be used within GlassMetaEngineProvider");
}
return context;
}
// Meta-engine dashboard component
function GlassMetaDashboard({
className,
showQuantumStates = true,
showEvolutions = true,
maxOptimizations = 10
}) {
const prefersReducedMotion = useReducedMotion();
const {
optimizations,
evolutions,
systemHealth,
engine
} = useGlassMetaEngine();
const [showDashboard, setShowDashboard] = useState(false);
const [quantumStates, setQuantumStates] = useState([]);
// Update quantum states
useEffect(() => {
if (engine && showQuantumStates) {
const updateStates = () => {
setQuantumStates(engine.getQuantumStates());
};
updateStates();
const interval = setInterval(updateStates, 2000);
return () => clearInterval(interval);
}
}, [engine, showQuantumStates]);
const topOptimizations = optimizations.slice(0, maxOptimizations);
const criticalEvolutions = evolutions.filter(evo => evo.confidence > 0.8);
return jsxs("div", {
className: cn("fixed bottom-4 right-4 z-50", className),
children: [jsxs(motion.button, {
className: cn("w-14 h-14 glass-radius-full glass-surface-primary glass-elev-4", "flex items-center justify-center glass-text-primary", "transition-all duration-300 hover:scale-105", "relative overflow-hidden"),
onClick: () => setShowDashboard(!showDashboard),
whileHover: {
scale: 1.05
},
whileTap: {
scale: 0.95
},
children: [jsx("div", {
className: 'absolute inset-0 opacity-20',
children: quantumStates.map((state, index) => jsx(motion.div, {
className: 'absolute w-1 h-1 glass-surface-blue glass-radius-full',
animate: prefersReducedMotion ? {} : {
x: Math.cos(index * 0.8) * 20 + 20,
y: Math.sin(index * 0.8) * 20 + 20,
opacity: state.coherence
},
transition: prefersReducedMotion ? {
duration: 0
} : {
duration: 2,
repeat: Infinity,
ease: "linear"
}
}, state.system))
}), jsxs("div", {
className: 'relative z-10',
children: ["\uD83E\uDDEC", optimizations.length > 0 && jsx(motion.div, {
className: 'absolute -glass-top-2 -right-2 w-4 h-4 glass-surface-green glass-radius-full glass-text-xs text-primary glass-flex glass-items-center glass-justify-center',
initial: {
scale: 0
},
animate: prefersReducedMotion ? {} : {
scale: 1
},
transition: prefersReducedMotion ? {
duration: 0
} : {
duration: 0.3
},
children: optimizations.length
})]
})]
}), jsx(AnimatePresence, {
children: showDashboard && jsxs(motion.div, {
className: cn("absolute bottom-16 right-0 w-96 max-h-[80vh] overflow-y-auto", "glass-surface-primary glass-elev-5 glass-radius-lg glass-p-6 glass-gap-4"),
initial: {
opacity: 0,
y: 10,
scale: 0.95
},
animate: prefersReducedMotion ? {} : {
opacity: 1,
y: 0,
scale: 1
},
exit: {
opacity: 0,
y: 10,
scale: 0.95
},
transition: prefersReducedMotion ? {
duration: 0
} : {
duration: 0.3
},
children: [jsxs("div", {
className: "glass-flex glass-items-center glass-justify-between",
children: [jsx("h3", {
className: 'glass-text-lg font-semibold text-primary',
children: "Meta-Engine Dashboard"
}), jsx("button", {
onClick: () => setShowDashboard(false),
className: 'glass-text-sm glass-text-secondary hover:text-primary glass-focus glass-touch-target glass-contrast-guard',
children: "\u2715"
})]
}), jsxs("div", {
className: "glass-gap-2",
children: [jsx("h4", {
className: 'glass-text-sm font-medium glass-text-secondary uppercase tracking-wide',
children: "System Health"
}), jsx("div", {
className: "glass-grid glass-grid-cols-1 glass-gap-2",
children: Array.from(systemHealth.entries()).map(([systemId, health]) => jsxs(motion.div, {
className: "glass-p-3 glass-surface-secondary glass-radius-md",
initial: {
opacity: 0,
x: -10
},
animate: prefersReducedMotion ? {} : {
opacity: 1,
x: 0
},
children: [jsxs("div", {
className: "glass-flex glass-items-center glass-justify-between",
children: [jsx("span", {
className: 'glass-text-sm text-primary font-medium',
children: systemId.replace("Glass", "")
}), jsxs("div", {
className: "glass-flex glass-items-center glass-gap-2",
children: [jsx("div", {
className: 'w-3 h-3 glass-radius-full',
style: {
backgroundColor: health.healthScore > 0.8 ? "var(--glass-color-success)" : health.healthScore > 0.6 ? "var(--glass-color-warning)" : "var(--glass-color-danger)"
}
}), jsxs("span", {
className: "glass-text-xs glass-text-secondary",
children: [(health.healthScore * 100).toFixed(0), "%"]
})]
})]
}), health.issues.length > 0 && jsxs("div", {
className: "glass-mt-1 glass-text-xs glass-text-tertiary",
children: [health.issues.length, " issue", health.issues.length !== 1 ? "s" : "", " detected"]
})]
}, systemId))
})]
}), showQuantumStates && quantumStates.length > 0 && jsxs("div", {
className: "glass-gap-2",
children: [jsx("h4", {
className: 'glass-text-sm font-medium glass-text-secondary uppercase tracking-wide',
children: "Quantum Coherence"
}), jsx("div", {
className: "glass-grid glass-grid-cols-2 glass-gap-2",
children: quantumStates.map(state => jsxs("div", {
className: "glass-p-2 glass-surface-secondary glass-radius-sm",
children: [jsx("div", {
className: 'glass-text-xs text-primary font-medium',
children: state.system.replace("Glass", "")
}), jsxs("div", {
className: "glass-mt-1 glass-flex glass-items-center glass-gap-2",
children: [jsx("div", {
className: 'glass-flex-1 glass-surface-subtle glass-radius-full h-2',
children: jsx(motion.div, {
className: 'h-2 glass-surface-blue glass-radius-full',
initial: {
width: 0
},
animate: {
width: `${state.coherence * 100}%`
},
transition: prefersReducedMotion ? {
duration: 0
} : {
duration: 0.5
}
})
}), jsxs("span", {
className: "glass-text-xs glass-text-secondary",
children: [(state.coherence * 100).toFixed(0), "%"]
})]
})]
}, state.system))
})]
}), topOptimizations.length > 0 && jsxs("div", {
className: "glass-gap-2",
children: [jsx("h4", {
className: 'glass-text-sm font-medium glass-text-secondary uppercase tracking-wide',
children: "Active Optimizations"
}), topOptimizations.map(optimization => jsxs(motion.div, {
className: "glass-p-3 glass-surface-secondary glass-radius-md",
initial: {
opacity: 0,
x: -10
},
animate: prefersReducedMotion ? {} : {
opacity: 1,
x: 0
},
children: [jsxs("div", {
className: "glass-flex glass-items-center glass-justify-between",
children: [jsx("span", {
className: 'glass-text-sm text-primary font-medium',
children: optimization.targetSystem.replace("Glass", "")
}), jsxs("div", {
className: "glass-flex glass-items-center glass-gap-1",
children: [jsx("div", {
className: 'w-2 h-2 glass-radius-full',
style: {
backgroundColor: optimization.priority === "critical" ? "var(--glass-color-danger-dark)" : optimization.priority === "high" ? "var(--glass-color-warning)" : optimization.priority === "medium" ? "var(--glass-color-success)" : "var(--glass-gray-500)"
}
}), jsx("span", {
className: 'glass-text-xs glass-text-secondary capitalize',
children: optimization.priority
})]
})]
}), jsx("div", {
className: "glass-mt-1 glass-text-xs glass-text-tertiary",
children: optimization.description
}), jsxs("div", {
className: "glass-mt-2 glass-flex glass-items-center glass-justify-between",
children: [jsx("span", {
className: 'glass-text-xs glass-text-secondary capitalize',
children: optimization.optimizationType
}), jsxs("span", {
className: "glass-text-xs glass-text-secondary",
children: ["Impact: ", (optimization.impact * 100).toFixed(0), "%"]
})]
})]
}, optimization.id))]
}), showEvolutions && criticalEvolutions.length > 0 && jsxs("div", {
className: "glass-gap-2",
children: [jsx("h4", {
className: 'glass-text-sm font-medium glass-text-secondary uppercase tracking-wide',
children: "System Evolutions"
}), criticalEvolutions.slice(0, 3).map(evolution => jsxs(motion.div, {
className: "glass-p-3 glass-surface-secondary glass-radius-md",
initial: {
opacity: 0,
x: -10
},
animate: prefersReducedMotion ? {} : {
opacity: 1,
x: 0
},
children: [jsx("div", {
className: 'glass-text-sm text-primary font-medium',
children: evolution.evolutionType.replace("-", " ")
}), jsx("div", {
className: "glass-mt-1 glass-text-xs glass-text-tertiary",
children: evolution.description
}), jsxs("div", {
className: "glass-mt-2 glass-flex glass-items-center glass-justify-between",
children: [jsx("span", {
className: 'glass-text-xs glass-text-secondary capitalize',
children: evolution.evolutionStage
}), jsxs("span", {
className: "glass-text-xs glass-text-secondary",
children: [(evolution.confidence * 100).toFixed(0), "% confidence"]
})]
})]
}, evolution.id))]
}), optimizations.length === 0 && evolutions.length === 0 && jsxs("div", {
className: 'text-center glass-text-sm glass-text-secondary glass-py-8',
children: ["System operating at optimal parameters", jsx("div", {
className: "glass-mt-1 glass-text-xs glass-text-tertiary",
children: "Meta-engine monitoring all systems..."
})]
})]
})
})]
});
}
// Hook to automatically record system usage
function useMetaEngineRecorder(systemId, componentType) {
const {
recordUsage
} = useGlassMetaEngine();
const startTimeRef = useRef(Date.now());
const recordMetric = useCallback((userSatisfactionScore = 1.0) => {
const endTime = Date.now();
const renderTime = endTime - startTimeRef.current;
recordUsage({
systemId,
componentType,
usageCount: 1,
performanceMetrics: {
renderTime,
memoryUsage: performance.memory?.usedJSHeapSize / 1024 / 1024 || 0,
interactionLatency: 0,
errorRate: 0
},
userSatisfactionScore,
timestamp: Date.now(),
context: {
deviceType: window.innerWidth < 768 ? "mobile" : window.innerWidth < 1024 ? "tablet" : "desktop",
browserEngine: navigator.userAgent.includes("Chrome") ? "Chromium" : navigator.userAgent.includes("Firefox") ? "Gecko" : navigator.userAgent.includes("Safari") ? "WebKit" : "Unknown",
networkConnection: navigator.connection?.effectiveType || "unknown",
batteryLevel: navigator.getBattery?.().then(battery => battery.level)
}
});
startTimeRef.current = Date.now();
}, [recordUsage, systemId, componentType]);
// Auto-record on component mount/unmount
useEffect(() => {
recordMetric();
return () => recordMetric();
}, [recordMetric]);
return {
recordMetric
};
}
// Presets for different meta-engine configurations
const metaEnginePresets = {
conservative: {
evolutionRate: 0.1,
optimizationThreshold: 0.8,
quantumCoherence: 0.5,
selfHealingEnabled: false
},
balanced: {
evolutionRate: 0.5,
optimizationThreshold: 0.6,
quantumCoherence: 0.7,
selfHealingEnabled: true
},
aggressive: {
evolutionRate: 0.9,
optimizationThreshold: 0.4,
quantumCoherence: 0.9,
selfHealingEnabled: true
},
experimental: {
evolutionRate: 1.0,
optimizationThreshold: 0.2,
quantumCoherence: 1.0,
selfHealingEnabled: true
}
};
export { GlassMetaDashboard, GlassMetaEngineProvider, metaEnginePresets, useGlassMetaEngine, useMetaEngineRecorder };
//# sourceMappingURL=GlassMetaEngine.js.map