import { useEffect, useRef } from 'react'; import ReplayButton from './ReplayButton'; import GifDownloadButton from './GifDownloadButton'; import { loadingSketch } from '../sketches'; export default function SketchRenderer({ generatedCode, isGenerating, error, showCodePanel, onReplay, onGifCapture, isCapturingGif, isInitialSketch }) { const sketchContainer = useRef(null); const currentSketch = useRef(null); useEffect(() => { // Add message listener for GIF capture completion const handleGifComplete = (event) => { if (event.data.type === 'gifCaptureComplete') { onGifCapture(false); // Signal completion } }; window.addEventListener('message', handleGifComplete); return () => { window.removeEventListener('message', handleGifComplete); }; }, [onGifCapture]); useEffect(() => { if (generatedCode && window.p5 && sketchContainer.current) { // Cleanup previous sketch if it exists const cleanup = () => { if (currentSketch.current) { currentSketch.current.remove(); currentSketch.current = null; } }; cleanup(); try { const formattedCodeResponse = ` p5.js Sketch `; const iframe = document.createElement('iframe'); iframe.srcdoc = formattedCodeResponse; iframe.style.width = '100%'; iframe.style.height = '100%'; iframe.style.border = 'none'; iframe.id = 'sketch-iframe'; iframe.onload = () => { iframe.contentWindow.addEventListener('error', (e) => { if (e.message.includes('Receiving end does not exist') || e.message.includes('p5.js seems to have been imported multiple times')) { e.preventDefault(); } }); }; sketchContainer.current.innerHTML = ''; sketchContainer.current.appendChild(iframe); } catch (error) { console.error('Error running p5.js sketch:', error); setError('Error running the animation: ' + error.message); } } return () => { if (sketchContainer.current) { sketchContainer.current.innerHTML = ''; } }; }, [generatedCode, isGenerating]); return (
{isInitialSketch && !error && !isGenerating && (
Type a word below to get started
)} {error && (
{error}
)} {showCodePanel && !error && ( <> onGifCapture(true)} title="Download as GIF" isCapturing={isCapturingGif} /> )}
); }