diff --git a/README.md b/README.md index 4677b96..0bc15ff 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,6 @@ The purpose of Chaos Coder is to accelerate the development process by providing - Real-time code preview for each variation - Interactive interface with theme toggling - Voice input support for hands-free prompting -- Performance metrics for generation times - Keyboard shortcuts for quick access to tools ## Tech Stack diff --git a/nextjs-web-app/BACKGROUND_OPTIMIZATION.md b/nextjs-web-app/BACKGROUND_OPTIMIZATION.md new file mode 100644 index 0000000..fe29ee4 --- /dev/null +++ b/nextjs-web-app/BACKGROUND_OPTIMIZATION.md @@ -0,0 +1,107 @@ +# Background Animation Optimization + +## Overview +Replaced the GPU-intensive Continuous Aurora Background Animation with a more efficient, lightweight background system to improve performance and reduce GPU usage. + +## Changes Made + +### 1. Aurora Background Component (`src/components/ui/aurora-background.tsx`) +**Before:** +- Heavy blur effects (blur-[100px], blur-[120px], blur-[90px]) +- Continuous 60-second linear animations with `animate-aurora` +- Complex gradient animations with background-position changes +- Multiple layered animated elements with pseudo-elements +- GPU-intensive transform3d and will-change properties + +**After:** +- Static gradient base with subtle color transitions +- Minimal animated overlay with gentle movement +- Optional subtle particle effects using CSS-only animations +- Significantly reduced GPU usage +- Maintained visual appeal with better performance + +### 2. CSS Animations (`src/app/globals.css`) +**Removed:** +- `@keyframes aurora` - Complex background-position animation +- `.animate-aurora` - GPU-intensive animation class + +**Added:** +- `@keyframes gentle-shift` - Subtle gradient movement (20s duration) +- `@keyframes float-slow` - Gentle particle floating (15s duration) +- `@keyframes float-delayed` - Delayed particle animation (18s duration) +- `@keyframes float-gentle` - Rotating particle animation (22s duration) + +### 3. Tailwind Configuration (`tailwind.config.js`) +**Removed:** +- `aurora` keyframe definition +- `aurora` animation class + +**Added:** +- `gentle-shift` keyframe and animation +- `float-slow` keyframe and animation +- `float-delayed` keyframe and animation +- `float-gentle` keyframe and animation + +## Performance Benefits + +### GPU Usage Reduction +- **Before:** Continuous GPU layer creation with transform3d and will-change +- **After:** Minimal GPU usage with simple transform and opacity changes + +### Animation Efficiency +- **Before:** Complex background-position animations running every frame +- **After:** Simple transform and opacity animations with longer durations + +### Visual Quality +- **Before:** Heavy blur effects causing rendering overhead +- **After:** Clean gradients with subtle movement maintaining visual appeal + +### Battery Life +- **Before:** High GPU usage leading to increased power consumption +- **After:** Minimal resource usage improving battery life on mobile devices + +## Technical Details + +### New Animation Properties +- **Duration:** Longer animation cycles (15-22 seconds) vs. previous 60-second continuous loop +- **Easing:** `ease-in-out` for smoother, more natural movement +- **Delays:** Staggered animation starts to create organic movement patterns +- **Opacity:** Low opacity values (0.1-0.5) for subtle visual effects + +### Browser Compatibility +- Uses standard CSS transforms and opacity changes +- Compatible with all modern browsers +- Respects `prefers-reduced-motion` settings for accessibility + +### Reduced Motion Support +The existing reduced motion support in `globals.css` continues to work: +```css +@media (prefers-reduced-motion: reduce) { + .animate-aurora { + animation: none; + } + * { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} +``` + +## Testing Results +- ✅ Homepage loads with new efficient background +- ✅ Results page displays correctly with new background +- ✅ Visual appeal maintained while reducing GPU usage +- ✅ Animations are smooth and subtle +- ✅ No performance degradation observed + +## Migration Notes +- No breaking changes to component API +- Existing `AuroraBackground` component usage remains the same +- All pages using the component automatically benefit from the optimization +- No additional configuration required + +## Future Improvements +- Consider adding user preference for animation intensity +- Implement performance monitoring to track GPU usage improvements +- Add option to completely disable animations for maximum performance diff --git a/nextjs-web-app/PERFORMANCE_OPTIMIZATIONS.md b/nextjs-web-app/PERFORMANCE_OPTIMIZATIONS.md deleted file mode 100644 index 295df76..0000000 --- a/nextjs-web-app/PERFORMANCE_OPTIMIZATIONS.md +++ /dev/null @@ -1,109 +0,0 @@ -# Performance Optimizations - -This document outlines the performance optimizations implemented to reduce resource usage and improve the application's efficiency. - -## Issues Identified and Fixed - -### 1. Memory Leaks -- **RateLimiter**: Fixed `setInterval` that was never cleared, causing memory accumulation -- **VoiceInput**: Added proper cleanup for speech recognition and timeouts -- **AnimatedHero**: Ensured timeout cleanup in useEffect - -### 2. Excessive Re-renders -- **CodePreviewPanel**: Added `React.memo` and `useCallback` to prevent unnecessary re-renders -- **AppTile**: Memoized component and callbacks -- **PerformanceMetrics**: Added memoization for expensive calculations -- **Results Page**: Optimized state updates and API calls with throttling - -### 3. Resource-Intensive Operations -- **API Calls**: Added throttling between requests (100ms delay) to prevent overwhelming the system -- **Monaco Editor**: Lazy loaded to reduce initial bundle size -- **Bundle Optimization**: Configured webpack to split chunks for better caching - -### 4. CSS Animations -- **Aurora Background**: Added hardware acceleration with `transform3d` and `will-change` -- **Reduced Motion**: Added support for users who prefer reduced motion -- **Performance**: Optimized animation properties for better GPU utilization - -## New Features Added - -### 1. Debouncing (`src/hooks/useDebounce.ts`) -- Custom hooks for debouncing values and callbacks -- Prevents excessive API calls and function executions - -### 2. Lazy Loading (`src/components/LazyLoad.tsx`) -- Intersection Observer-based lazy loading -- Reduces initial render load -- Configurable thresholds and margins - -### 3. Bundle Optimization (`next.config.ts`) -- Code splitting for vendor libraries -- Separate chunks for heavy dependencies (Monaco Editor, Framer Motion) -- Image optimization with WebP/AVIF formats -- Response compression - -## Performance Improvements - -### Before Optimizations -- Multiple simultaneous API calls causing system overload -- Memory leaks from uncleaned timers and event listeners -- Large initial bundle size with Monaco Editor -- Continuous animations consuming CPU/GPU resources -- Unnecessary re-renders causing UI lag - -### After Optimizations -- Throttled API calls with 100ms delays -- Proper cleanup of all timers and event listeners -- Lazy-loaded Monaco Editor reducing initial bundle by ~2MB -- Hardware-accelerated animations with reduced motion support -- Memoized components preventing unnecessary re-renders - -## Usage Examples - -### Debouncing Usage -```typescript -import { useDebounce, useDebouncedCallback } from '@/hooks/useDebounce'; - -// Debounce a value -const debouncedValue = useDebounce(inputValue, 300); - -// Debounce a callback -const debouncedCallback = useDebouncedCallback(handleSearch, 300); -``` - -### Lazy Loading Usage -```typescript -import LazyLoad from '@/components/LazyLoad'; - -}> - - -``` - -## Browser DevTools Recommendations - -1. **Performance Tab**: Monitor for long tasks (>50ms) -2. **Memory Tab**: Check for memory leaks and heap growth -3. **Network Tab**: Verify bundle sizes and loading times -4. **Lighthouse**: Run regular performance audits - -## Best Practices Implemented - -1. **Component Memoization**: Use `React.memo` for expensive components -2. **Callback Optimization**: Use `useCallback` for event handlers -3. **Lazy Loading**: Load heavy components only when needed -4. **Bundle Splitting**: Separate vendor and feature code -5. **Animation Optimization**: Use CSS transforms and hardware acceleration -6. **Memory Management**: Always cleanup timers, observers, and event listeners -7. **API Throttling**: Prevent overwhelming backend services -8. **Accessibility**: Support for reduced motion preferences - - - -## Future Optimizations - -1. **Service Worker**: Cache API responses and static assets -2. **Virtual Scrolling**: For large lists of generated apps -3. **Image Optimization**: Implement next/image for better loading -4. **CDN**: Serve static assets from CDN -5. **Database Optimization**: Implement proper caching strategies diff --git a/nextjs-web-app/next.config.ts b/nextjs-web-app/next.config.ts index 17245c5..5e91004 100644 --- a/nextjs-web-app/next.config.ts +++ b/nextjs-web-app/next.config.ts @@ -12,44 +12,11 @@ const nextConfig: NextConfig = { // !! WARN !! ignoreBuildErrors: true, }, - // Performance optimizations - experimental: { - optimizePackageImports: ['framer-motion', 'react-icons'], - }, - // Bundle optimization - webpack: (config, { dev, isServer }) => { - // Optimize bundle size in production - if (!dev && !isServer) { - config.optimization.splitChunks = { - chunks: 'all', - cacheGroups: { - vendor: { - test: /[\\/]node_modules[\\/]/, - name: 'vendors', - chunks: 'all', - }, - framerMotion: { - test: /[\\/]node_modules[\\/]framer-motion[\\/]/, - name: 'framer-motion', - chunks: 'all', - }, - monaco: { - test: /[\\/]node_modules[\\/]@monaco-editor[\\/]/, - name: 'monaco-editor', - chunks: 'all', - }, - }, - }; - } - return config; - }, - // Compress responses - compress: true, - // Enable static optimization - trailingSlash: false, - // Optimize images images: { - formats: ['image/webp', 'image/avif'], + domains: [ + 'lh3.googleusercontent.com', // Google user avatars + 'avatars.githubusercontent.com', // GitHub avatars (in case you add GitHub auth) + ], }, }; diff --git a/nextjs-web-app/src/app/api/generate/route.ts b/nextjs-web-app/src/app/api/generate/route.ts index efedf91..fd87e88 100644 --- a/nextjs-web-app/src/app/api/generate/route.ts +++ b/nextjs-web-app/src/app/api/generate/route.ts @@ -19,38 +19,8 @@ const frameworkPrompts = { }; export async function POST(req: NextRequest) { - // Get client IP address - const ip = req.ip || req.headers.get("x-forwarded-for") || "127.0.0.1"; - - // Check rate limit (5 requests per IP) - const count = submissionCounts.get(ip) || 0; - // For debugging only - console.log(`Rate limit check: IP ${ip} has used ${count} requests`); - - // if (count >= 25) { - // console.log("Rate limit exceeded for IP:", ip); - // return new Response( - // JSON.stringify({ - // error: "rate_limit_exceeded", - // message: "Free limit exceeded. Please create an account to continue.", - // }), - // { - // status: 429, - // headers: { - // "Content-Type": "application/json", - // }, - // } - // ); - // } - - // Parse the request body - const body = await req.json(); - - // Only increment count for real generations, not rate limit checks - if (body && body.variation !== "rate-limit-check") { - submissionCounts.set(ip, count + 1); - } try { + const body = await req.json(); const { prompt, variation, framework } = body; const portkeyApiKey = process.env.PORTKEY_API_KEY; @@ -135,12 +105,31 @@ Additional Notes: Format the code with proper indentation and spacing for readability.`; } else { - fullPrompt = `Create a well-structured, modern web application: - -Instructions: -1. Base functionality: ${prompt} -2. Variation: ${variation} -3. Framework: ${frameworkInstructions} + fullPrompt = `Create a well-structured, modern web application based on the specific requirements below: + +CORE FUNCTIONALITY REQUEST: +${prompt} + +IMPORTANT: Interpret the request literally and specifically. Do not default to generic patterns like to-do lists unless explicitly requested. Be creative and think about what the user actually wants. + +VARIATION INSTRUCTIONS: +${variation} + +FRAMEWORK REQUIREMENTS: +${frameworkInstructions} + +CREATIVE INTERPRETATION GUIDELINES: +- If the request mentions "organize" or "productivity", consider alternatives to to-do lists such as: + * Calendar/scheduling apps + * Dashboard with widgets + * Time tracking applications + * Habit tracking systems + * Note-taking or journaling apps + * Project management boards + * Goal setting interfaces +- Focus on the specific domain or context mentioned in the request +- Add unique features that make the application interesting and functional +- Think about what would genuinely solve the user's stated problem Technical Requirements: - Create a single HTML file with clean, indented code structure diff --git a/nextjs-web-app/src/app/globals.css b/nextjs-web-app/src/app/globals.css index 6cd6551..aa34816 100644 --- a/nextjs-web-app/src/app/globals.css +++ b/nextjs-web-app/src/app/globals.css @@ -31,22 +31,69 @@ } } -/* Aurora animation - optimized for performance */ -@keyframes aurora { - from { - background-position: 50% 50%, 50% 50%; +/* Efficient background animations - minimal GPU usage */ +@keyframes gentle-shift { + 0%, 100% { + transform: translateX(0) translateY(0); + opacity: 0.3; } - to { - background-position: 350% 50%, 350% 50%; + 50% { + transform: translateX(10px) translateY(-5px); + opacity: 0.5; } } -.animate-aurora { - animation: aurora 60s linear infinite; - /* Use will-change to optimize for animation */ - will-change: background-position; - /* Use transform3d to enable hardware acceleration */ - transform: translate3d(0, 0, 0); +@keyframes float-slow { + 0%, 100% { + transform: translateY(0px) scale(1); + opacity: 0.2; + } + 50% { + transform: translateY(-20px) scale(1.1); + opacity: 0.4; + } +} + +@keyframes float-delayed { + 0%, 100% { + transform: translateY(0px) translateX(0px); + opacity: 0.1; + } + 33% { + transform: translateY(-15px) translateX(5px); + opacity: 0.3; + } + 66% { + transform: translateY(-10px) translateX(-3px); + opacity: 0.2; + } +} + +@keyframes float-gentle { + 0%, 100% { + transform: translateY(0px) rotate(0deg); + opacity: 0.15; + } + 50% { + transform: translateY(-12px) rotate(180deg); + opacity: 0.35; + } +} + +.animate-gentle-shift { + animation: gentle-shift 20s ease-in-out infinite; +} + +.animate-float-slow { + animation: float-slow 15s ease-in-out infinite; +} + +.animate-float-delayed { + animation: float-delayed 18s ease-in-out infinite 3s; +} + +.animate-float-gentle { + animation: float-gentle 22s ease-in-out infinite 6s; } /* Reduce motion for users who prefer it */ diff --git a/nextjs-web-app/src/app/layout.tsx b/nextjs-web-app/src/app/layout.tsx index f467c19..2211a8e 100644 --- a/nextjs-web-app/src/app/layout.tsx +++ b/nextjs-web-app/src/app/layout.tsx @@ -17,11 +17,12 @@ export const metadata: Metadata = { icons: { icon: "/favicon.ico", }, - viewport: { - width: "device-width", - initialScale: 1, - maximumScale: 1, - }, +}; + +export const viewport = { + width: "device-width", + initialScale: 1, + maximumScale: 1, }; export default function RootLayout({ diff --git a/nextjs-web-app/src/app/page.tsx b/nextjs-web-app/src/app/page.tsx index 4fc98ae..685d585 100644 --- a/nextjs-web-app/src/app/page.tsx +++ b/nextjs-web-app/src/app/page.tsx @@ -14,6 +14,8 @@ import { FaStore, FaRobot, FaQuestionCircle, + FaMinus, + FaPlus, } from "react-icons/fa"; // Signup Modal Component @@ -81,9 +83,15 @@ export function SignupModal({ isOpen, onClose }: { isOpen: boolean; onClose: () ); } +// Constants for number of generations +const MIN_NUM_GENERATIONS = 1; +const MAX_NUM_GENERATIONS = 6; + export default function Home() { const [prompt, setPrompt] = useState(""); const [error, setError] = useState(null); + const [numGenerations, setNumGenerations] = useState(3); + const [showSignupModal, setShowSignupModal] = useState(false); const router = useRouter(); const examples = [ { @@ -125,7 +133,25 @@ export default function Home() { ]; const [isLoading, setIsLoading] = useState(false); - const [showSignupModal, setShowSignupModal] = useState(false); + // Functions for incrementing/decrementing generations + const incrementGenerations = () => { + if (numGenerations < MAX_NUM_GENERATIONS) { + setNumGenerations(numGenerations + 1); + } + }; + + const decrementGenerations = () => { + if (numGenerations > MIN_NUM_GENERATIONS) { + setNumGenerations(numGenerations - 1); + } + }; + + // Gradient style for the number display + const gradientStyle = { + background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', + WebkitBackgroundClip: 'text', + WebkitTextFillColor: 'transparent', + }; const handleSubmit = async () => { if (!prompt) { @@ -137,37 +163,10 @@ export default function Home() { setIsLoading(true); try { - // Make a test request to check rate limit before redirecting - const response = await fetch("/api/generate", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - prompt: prompt.substring(0, 50), // Just send a small part of the prompt for the check - variation: "rate-limit-check", - framework: "none", - }), - }); - - if (response.status === 429) { - // Rate limit exceeded - setShowSignupModal(true); - setIsLoading(false); - return; - } - - const data = await response.json(); - if (data.error === "rate_limit_exceeded") { - setShowSignupModal(true); - setIsLoading(false); - return; - } - - // If no rate limit issues, proceed to results page - router.push(`/results?prompt=${encodeURIComponent(prompt)}`); + // Navigate directly to results page + router.push(`/results?prompt=${encodeURIComponent(prompt)}&numGenerations=${numGenerations}`); } catch (error) { - console.error("Error checking rate limit:", error); - // Still try to navigate even if there was an error checking rate limit - router.push(`/results?prompt=${encodeURIComponent(prompt)}`); + console.error("Error navigating to results:", error); } finally { setIsLoading(false); } @@ -182,20 +181,75 @@ export default function Home() { /> )}
- -
+ +
-