import { encodeBase64 } from '@std/encoding/base64'; import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; import { useFSPaths } from '@/hooks/useFSPaths'; import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages'; import { useConsoleError } from '@/hooks/useConsoleError'; import { useBuildProject } from '@/hooks/useBuildProject'; import { Tabs, TabsContent } from '@/components/ui/tabs'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { Button } from '@/components/ui/button'; import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { Popover, PopoverContent, PopoverTrigger, } from '@/components/ui/popover'; import { cn } from '@/lib/utils'; import { FileTree } from './FileTree'; import { FileEditor } from './FileEditor'; import { DeployDialog } from '@/components/DeployDialog'; import { Terminal as TerminalComponent } from '@/components/Terminal'; import { useSearchParams } from 'react-router-dom'; import { useAppContext } from '@/hooks/useAppContext'; import { isMediaFile } from '@/lib/fileUtils'; interface PreviewPaneProps { projectId: string; activeTab: 'preview' | 'code'; onToggleView?: () => void; projectName?: string; onFirstInteraction?: () => void; isPreviewable?: boolean; } interface JSONRPCRequest { jsonrpc: '2.0'; method: string; params: { request: { url: string; method: string; headers: Record; body: string | null; } }; id: number; } interface JSONRPCResponse { jsonrpc: '2.0'; result?: { status: number; statusText: string; headers: Record; body: string | null; } error?: { code: number; message: string; data?: Record; }; id: number; } export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction: _onFirstInteraction, isPreviewable = true }: PreviewPaneProps) { const { t } = useTranslation(); const { config } = useAppContext(); const { previewDomain } = config; const [selectedFile, setSelectedFile] = useState(null); const [fileContent, setFileContent] = useState(''); const [isLoading, setIsLoading] = useState(false); const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer'); const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files'); const isMobile = useIsMobile(); const [hasBuiltProject, setHasBuiltProject] = useState(false); const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); const [deployDialogOpen, setDeployDialogOpen] = useState(false); const iframeRef = useRef(null); const { fs } = useFS(); const { projectsPath } = useFSPaths(); const projectsManager = useProjectsManager(); // Use console error state from provider const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError(); const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId); const [searchParams, setSearchParams] = useSearchParams(); const [shouldBuild, setShouldBuild] = useState(false); const handleBuildProject = useCallback(() => { buildProject(undefined, { onError: (error) => { console.error('Build failed:', error); } }); }, [buildProject]); // Handle "build" URL parameter on initial load useEffect(() => { if (searchParams.has('build')) { setShouldBuild(true); // Remove the build parameter from URL const newSearchParams = new URLSearchParams(searchParams); newSearchParams.delete('build'); setSearchParams(newSearchParams, { replace: true }); } }, [searchParams, setSearchParams]); // Build automatically if "build" parameter was present useEffect(() => { if (shouldBuild && isPreviewable && !isBuildLoading) { setShouldBuild(false); handleBuildProject(); } }, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]); const loadFileContent = useCallback(async (filePath: string) => { // Skip loading media files - they can't be edited as text if (isMediaFile(filePath)) { setFileContent(''); setIsLoading(false); return; } setIsLoading(true); try { const content = await projectsManager.readFile(projectId, filePath); setFileContent(content); } catch (_error) { console.error('Failed to load file:', _error); setFileContent(''); } finally { setIsLoading(false); } }, [projectId, projectsManager]); const getContentType = (filename: string): string => { const ext = filename.split('.').pop()?.toLowerCase(); const mimeTypes: Record = { 'html': 'text/html', 'js': 'application/javascript', 'mjs': 'application/javascript', 'css': 'text/css', 'json': 'application/json', 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif', 'svg': 'image/svg+xml', 'ico': 'image/x-icon', 'woff': 'font/woff', 'woff2': 'font/woff2', 'ttf': 'font/ttf', 'eot': 'application/vnd.ms-fontobject', 'txt': 'text/plain', 'xml': 'application/xml', 'pdf': 'application/pdf', 'zip': 'application/zip', }; return mimeTypes[ext || ''] || 'application/octet-stream'; }; const checkForBuiltProject = useCallback(async () => { try { const exists = await projectsManager.fileExists(projectId, 'dist/index.html'); setHasBuiltProject(exists); } catch (error) { console.error('Failed to check for built project:', error); setHasBuiltProject(false); } }, [projectId, projectsManager]); // Legacy refresh function for build completion events const refreshIframeLegacy = useCallback(() => { if (iframeRef.current) { // Force reload the iframe by updating its src iframeRef.current.src = '/'; // Use a small timeout to ensure the src is cleared before setting it back setTimeout(() => { if (iframeRef.current) { iframeRef.current.src = `https://${projectId}.${previewDomain}/`; } }, 10); } }, [projectId, previewDomain]); const sendResponse = useCallback((message: JSONRPCResponse) => { if (iframeRef.current?.contentWindow) { const targetOrigin = `https://${projectId}.${previewDomain}`; iframeRef.current.contentWindow.postMessage(message, targetOrigin); } }, [projectId, previewDomain]); const sendError = useCallback((message: JSONRPCResponse) => { if (iframeRef.current?.contentWindow) { const targetOrigin = `https://${projectId}.${previewDomain}`; iframeRef.current.contentWindow.postMessage(message, targetOrigin); } }, [projectId, previewDomain]); const handleConsoleMessage = useCallback((message: { jsonrpc: '2.0'; method: 'console'; params: { level: 'log' | 'warn' | 'error' | 'info' | 'debug'; message: string; }; }) => { const { params } = message; // Normalize level to ensure it's one of our supported types let normalizedLevel: ConsoleMessage['level'] = 'log'; if (['log', 'warn', 'error', 'info', 'debug'].includes(params.level)) { normalizedLevel = params.level as ConsoleMessage['level']; } // Add to console messages addConsoleMessage(normalizedLevel, params.message); // Log to parent console for debugging with appropriate level console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); }, []); const handleUpdateNavigationState = useCallback((message: { jsonrpc: '2.0'; method: 'updateNavigationState'; params: { currentUrl: string; canGoBack: boolean; canGoForward: boolean; }; }) => { const { params } = message; try { // params.currentUrl is now just a semantic path (e.g., "/about", "/contact?param=value#section") const path = params.currentUrl; setCurrentPath(path); // Update navigation history if this is a new navigation // But only if it's different from current path (avoid duplicates) if (path !== navigationHistory[historyIndex]) { const newHistory = navigationHistory.slice(0, historyIndex + 1); newHistory.push(path); setNavigationHistory(newHistory); setHistoryIndex(newHistory.length - 1); } } catch (error) { console.error('Failed to handle navigation state:', params.currentUrl, error); } }, [historyIndex, navigationHistory]); const sendNavigationCommand = useCallback((method: string, params?: Record) => { if (iframeRef.current?.contentWindow) { const message = { jsonrpc: '2.0', method, params: params || {}, id: Date.now() }; const targetOrigin = `https://${projectId}.${previewDomain}`; iframeRef.current.contentWindow.postMessage(message, targetOrigin); } }, [projectId, previewDomain]); const navigateIframe = useCallback((url: string) => { // Send semantic path directly (e.g., "/about", "/contact") // The iframe's NavigationHandler will handle this as semantic navigation sendNavigationCommand('navigate', { url }); }, [sendNavigationCommand]); const refreshIframe = useCallback(() => { sendNavigationCommand('refresh'); }, [sendNavigationCommand]); const goBackIframe = useCallback(() => { if (historyIndex > 0) { // Move back in history const newIndex = historyIndex - 1; const targetPath = navigationHistory[newIndex]; setHistoryIndex(newIndex); setCurrentPath(targetPath); // Tell iframe to navigate to this path sendNavigationCommand('navigate', { url: targetPath }); } }, [historyIndex, navigationHistory, sendNavigationCommand]); const goForwardIframe = useCallback(() => { if (historyIndex < navigationHistory.length - 1) { // Move forward in history const newIndex = historyIndex + 1; const targetPath = navigationHistory[newIndex]; setHistoryIndex(newIndex); setCurrentPath(targetPath); // Tell iframe to navigate to this path sendNavigationCommand('navigate', { url: targetPath }); } }, [historyIndex, navigationHistory, sendNavigationCommand]); const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; const { request: fetchRequest } = params; try { // Parse the URL and validate origin const url = new URL(fetchRequest.url); const expectedOrigin = `https://${projectId}.${previewDomain}`; if (url.origin !== expectedOrigin) { console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`); sendError({ jsonrpc: '2.0', error: { code: -32003, message: 'Invalid URL - origin mismatch', data: { url: fetchRequest.url, expectedOrigin } }, id }); return; } const path = url.pathname; const filePath = path; // Skip SPA fallback for static assets (files with extensions) const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path); // SPA routing: try to serve the exact file first try { const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath); console.log(`Serving file: ${filePath}`); sendResponse({ jsonrpc: '2.0', result: { status: 200, statusText: 'OK', headers: { 'Content-Type': getContentType(filePath), 'Cache-Control': 'no-cache', }, body: encodeBase64(bytes), }, id }); return; } catch { // For static assets, return 404 immediately if (isStaticAsset) { sendResponse({ jsonrpc: '2.0', result: { status: 404, statusText: 'Not Found', headers: { 'Content-Type': 'text/plain', }, body: encodeBase64(`Static asset not found: ${path}`), }, id }); return; } } // SPA fallback: serve index.html for non-file requests (SPA routing) try { const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html'); console.log(`Serving index.html fallback for: ${path}`); sendResponse({ jsonrpc: '2.0', result: { status: 200, statusText: 'OK', headers: { 'Content-Type': 'text/html', 'Cache-Control': 'no-cache', }, body: encodeBase64(bytes), }, id }); } catch { // Even index.html doesn't exist sendResponse({ jsonrpc: '2.0', result: { status: 404, statusText: 'Not Found', headers: { 'Content-Type': 'text/plain', }, body: encodeBase64(`File not found: ${path}`), }, id }); } } catch (error) { console.error('Error processing fetch request:', error); sendError({ jsonrpc: '2.0', error: { code: -32002, message: 'Request processing error', data: { url: fetchRequest.url, error: String(error) } }, id }); } }, [projectId, projectsManager, sendResponse, sendError, previewDomain]); // Setup messaging protocol for iframe communication useEffect(() => { const handleMessage = (event: MessageEvent) => { // Verify origin for security const expectedOrigin = `https://${projectId}.${previewDomain}`; if (event.origin !== expectedOrigin) { console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`); return; } const message = event.data; console.log('Received message from iframe:', message); if (message.jsonrpc === '2.0' && message.method === 'fetch') { handleFetch(message); } else if (message.jsonrpc === '2.0' && message.method === 'console') { handleConsoleMessage(message); } else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') { handleUpdateNavigationState(message); } }; window.addEventListener('message', handleMessage); return () => window.removeEventListener('message', handleMessage); }, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]); useEffect(() => { if (selectedFile) { loadFileContent(selectedFile); } }, [selectedFile, loadFileContent]); // Reset selected file and navigation history when projectId changes const prevProjectIdRef = useRef(); useEffect(() => { setSelectedFile(null); setFileContent(''); setMobileCodeView('explorer'); setDesktopCodeView('files'); // Reset navigation history and state setCurrentPath('/'); setNavigationHistory(['/']); setHistoryIndex(0); // Only clear console messages when projectId actually changes (not on initial mount) if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) { clearErrors(); } prevProjectIdRef.current = projectId; }, [projectId, clearErrors]); useEffect(() => { checkForBuiltProject(); }, [checkForBuiltProject]); // Listen for build completion events to refresh the iframe useEffect(() => { const handleBuildComplete = (event: CustomEvent) => { if (event.detail?.projectId === projectId) { console.log('Build completed for project, refreshing preview'); // Check for built project and refresh iframe checkForBuiltProject(); refreshIframeLegacy(); } }; window.addEventListener('buildComplete', handleBuildComplete as EventListener); return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener); }, [projectId, checkForBuiltProject, refreshIframeLegacy]); const handleFileSelect = (filePath: string) => { setSelectedFile(filePath); if (isMobile) { setMobileCodeView('editor'); } }; const handleFileSave = async (content: string) => { if (!selectedFile) return; try { await fs.writeFile(`${projectsPath}/${projectId}/${selectedFile}`, content); setFileContent(content); // Automatically trigger a rebuild after saving a file if (isPreviewable) { console.log('File saved, triggering rebuild...'); handleBuildProject(); } } catch (error) { console.error('Failed to save file:', error); } }; const ConsoleDropdown = () => { const [isOpen, setIsOpen] = useState(false); const [copiedMessageIndex, setCopiedMessageIndex] = useState(null); const messages = isOpen ? getConsoleMessages() : []; const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => { try { await navigator.clipboard.writeText(msg.message); setCopiedMessageIndex(index); setTimeout(() => setCopiedMessageIndex(null), 2000); } catch (error) { console.error('Failed to copy message to clipboard:', error); } }; const messageCount = messages.length; return ( {/* Messages */}
{messageCount === 0 ? (

No console messages

Messages from your project will appear here

) : ( messages.map((msg, index) => (
{ e.stopPropagation(); copyMessageToClipboard(msg, index); }} >
{msg.message}
)) )}
{/* Close button */}
); }; const Menu = () => { const isAnyLoading = isBuildLoading; return ( {isBuildLoading ? ( ) : ( )} {isBuildLoading ? 'Building...' : 'Build'} setDeployDialogOpen(true)} disabled={isAnyLoading} className="gap-2" > Deploy ); }; return (
{isPreviewable && (
{/* Always show browser address bar */}
0} canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1} extraContent={(
{(!isMobile && onToggleView && isPreviewable) && ( )}
)} />
{/* Content area */}
{hasBuiltProject ? (