Files
shakespeare/src/components/Shakespeare/PreviewPane.tsx
T

503 lines
17 KiB
TypeScript

import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
interface PreviewPaneProps {
projectId: string;
activeTab: 'preview' | 'code';
}
interface JSONRPCRequest {
jsonrpc: '2.0';
method: string;
params: {
request: {
url: string;
method: string;
headers: Record<string, string>;
body: string | null;
}
};
id: number;
}
interface JSONRPCResponse {
jsonrpc: '2.0';
result?: {
status: number;
statusText: string;
headers: Record<string, string>;
body: string | null;
};
error?: {
code: number;
message: string;
data?: Record<string, unknown>;
};
id: number;
}
export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer');
const isMobile = useIsMobile();
const [hasBuiltProject, setHasBuiltProject] = useState(false);
const [currentPath, setCurrentPath] = useState('/');
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
const [historyIndex, setHistoryIndex] = useState(0);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const projectsManager = useProjectsManager();
const loadFileContent = useCallback(async (filePath: string) => {
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<string, string> = {
'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]);
const refreshIframe = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
const currentSrc = iframeRef.current.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 = currentSrc;
}
}, 10);
}
}, []);
const navigateToPath = useCallback((path: string) => {
if (iframeRef.current) {
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
setCurrentPath(path);
// Update navigation history
const newHistory = navigationHistory.slice(0, historyIndex + 1);
newHistory.push(path);
setNavigationHistory(newHistory);
setHistoryIndex(newHistory.length - 1);
}
}, [projectId, navigationHistory, historyIndex]);
const goBack = useCallback(() => {
if (historyIndex > 0) {
const newIndex = historyIndex - 1;
const path = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
}
}, [historyIndex, navigationHistory, projectId]);
const goForward = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
const newIndex = historyIndex + 1;
const path = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.local-shakespeare.dev`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
}
}, [historyIndex, navigationHistory, projectId]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.local-shakespeare.dev`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
console.log(`Preview iframe requesting: ${fetchRequest.url}`);
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
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;
// 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 {
// File not found, try SPA fallback to index.html
console.log(`File not found: ${filePath}, trying index.html fallback`);
}
// SPA fallback: serve index.html for non-file requests
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
console.log(`No files found, returning 404 for: ${path}`);
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]);
// Setup messaging protocol for iframe communication
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.local-shakespeare.dev`;
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);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, projectId]);
useEffect(() => {
if (selectedFile) {
loadFileContent(selectedFile);
}
}, [selectedFile, loadFileContent]);
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();
refreshIframe();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframe]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
if (isMobile) {
setMobileCodeView('editor');
}
};
const handleFileSave = async (content: string) => {
if (!selectedFile) return;
try {
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
setFileContent(content);
} catch (error) {
console.error('Failed to save file:', error);
}
};
return (
<div className="h-full">
<Tabs value={activeTab} className="h-full">
<TabsContent value="preview" className="h-full mt-0">
{hasBuiltProject ? (
<div className="h-full w-full flex flex-col">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={navigateToPath}
onRefresh={refreshIframe}
onBack={goBack}
onForward={goForward}
canGoBack={historyIndex > 0}
canGoForward={historyIndex < navigationHistory.length - 1}
/>
<iframe
ref={iframeRef}
src={`https://${projectId}.local-shakespeare.dev${currentPath}`}
className="w-full flex-1 border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
</div>
) : (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">Project Preview</h3>
<p className="text-muted-foreground mb-4">
Build your project to see the preview here
</p>
</div>
</div>
)}
</TabsContent>
<TabsContent value="code" className="h-full mt-0">
{isMobile ? (
<div className="h-full flex flex-col">
{mobileCodeView === 'explorer' ? (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
</>
) : (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
<Button
variant="ghost"
size="sm"
onClick={() => setMobileCodeView('explorer')}
className="p-1"
>
<ArrowLeft className="h-4 w-4" />
</Button>
<h3 className="font-semibold flex-1 truncate bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{selectedFile ? selectedFile.split('/').pop() : 'File Editor'}
</h3>
<GitStatusIndicator projectId={projectId} />
</div>
<div className="flex-1">
{selectedFile ? (
<FileEditor
filePath={selectedFile}
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<FolderOpen className="h-12 w-12 mx-auto text-muted-foreground mb-4" />
<p className="text-muted-foreground">
Select a file from the explorer to edit
</p>
<Button
variant="outline"
size="sm"
onClick={() => setMobileCodeView('explorer')}
className="mt-4"
>
Open File Explorer
</Button>
</div>
</div>
)}
</div>
</>
)}
</div>
) : (
<div className="h-full flex">
<div className="w-1/3 border-r">
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
<div className="flex items-center justify-between">
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">File Explorer</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</div>
<ScrollArea className="h-[calc(100%-60px)]">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
</div>
<div className="flex-1">
{selectedFile ? (
<FileEditor
filePath={selectedFile}
content={fileContent}
onSave={handleFileSave}
isLoading={isLoading}
projectId={projectId}
/>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<p className="text-muted-foreground">
Select a file from the explorer to edit
</p>
</div>
</div>
)}
</div>
</div>
)}
</TabsContent>
</Tabs>
</div>
);
}