Add virtual terminal to Code tab

This commit is contained in:
Alex Gleason committed 2025-09-26 17:39:12 -05:00
1 parent ca334d7585
commit dc50d41928
2 files changed
+357 -40

No files matched your search

+98 -40
View File
@@ -8,7 +8,7 @@ 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, CloudUpload, X } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -27,6 +27,7 @@ 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';
// Get iframe domain from environment variable
@@ -76,7 +77,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
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 [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('/');
@@ -455,6 +457,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
setSelectedFile(null);
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
// Reset navigation history and state
setCurrentPath('/');
@@ -731,16 +734,47 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{isMobile ? (
<div className="h-full flex flex-col">
{mobileCodeView === 'explorer' ? (
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
<div className="flex-1 relative">
<ScrollArea className="h-full">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
{/* Floating Terminal Button */}
<Button
variant="outline"
size="sm"
onClick={() => setMobileCodeView('terminal')}
className="absolute bottom-4 right-4 h-10 w-10 p-0 rounded-full shadow-lg bg-background border-2"
>
<Terminal className="h-4 w-4" />
</Button>
</div>
) : mobileCodeView === 'terminal' ? (
<>
<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 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Terminal
</h3>
<GitStatusIndicator projectId={projectId} />
</div>
</ScrollArea>
<div className="flex-1">
<TerminalComponent projectId={projectId} />
</div>
</>
) : (
<>
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
@@ -803,6 +837,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{t('backToPreview')}
</Button>
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
)}
@@ -810,43 +852,59 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{!isMobile && !isPreviewable && (
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
<div className="flex-1" />
<Button
variant="ghost"
size="sm"
onClick={() => setDesktopCodeView(desktopCodeView === 'terminal' ? 'files' : 'terminal')}
className="gap-2 text-muted-foreground hover:text-foreground"
>
<Terminal className="h-4 w-4" />
</Button>
<GitStatusIndicator projectId={projectId} />
</div>
)}
<div className="flex-1 flex min-h-0">
<div className="w-1/3 border-r flex flex-col">
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
{desktopCodeView === 'terminal' ? (
<div className="flex-1">
<TerminalComponent projectId={projectId} />
</div>
) : (
<>
<div className="w-1/3 border-r flex flex-col">
<ScrollArea className="flex-1">
<ScrollBar orientation="horizontal" />
<div className="min-w-max">
<FileTree
projectId={projectId}
onFileSelect={handleFileSelect}
selectedFile={selectedFile}
/>
</div>
</ScrollArea>
</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">
{t('selectFileFromExplorer')}
</p>
</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">
{t('selectFileFromExplorer')}
</p>
</div>
</div>
)}
</div>
)}
</div>
</>
)}
</div>
</div>
)}
+259
View File
@@ -0,0 +1,259 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { ScrollArea } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { X, Copy, Trash2 } from 'lucide-react';
import { cn } from '@/lib/utils';
import { ShellTool } from '@/lib/tools/ShellTool';
import { useFS } from '@/hooks/useFS';
import { useGit } from '@/hooks/useGit';
interface TerminalProps {
projectId: string;
onClose?: () => void;
className?: string;
}
interface TerminalLine {
id: string;
type: 'input' | 'output' | 'error';
content: string;
timestamp: Date;
}
export function Terminal({ projectId, onClose, className }: TerminalProps) {
const [lines, setLines] = useState<TerminalLine[]>([]);
const [currentInput, setCurrentInput] = useState('');
const [isExecuting, setIsExecuting] = useState(false);
const [commandHistory, setCommandHistory] = useState<string[]>([]);
const [historyIndex, setHistoryIndex] = useState(-1);
const [currentWorkingDirectory, setCurrentWorkingDirectory] = useState(`/projects/${projectId}`);
const inputRef = useRef<HTMLInputElement>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const shellToolRef = useRef<ShellTool | null>(null);
const { fs } = useFS();
const { git } = useGit();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git);
// Add welcome message
setLines([{
id: Date.now().toString(),
type: 'output',
content: `Welcome to Shakespeare Terminal\nProject: ${projectId}\nType 'help' to see available commands.`,
timestamp: new Date()
}]);
}, [projectId, fs, git]);
// Auto-scroll to bottom when new lines are added
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [lines]);
// Focus input when component mounts
useEffect(() => {
if (inputRef.current) {
inputRef.current.focus();
}
}, []);
const addLine = useCallback((type: TerminalLine['type'], content: string) => {
const newLine: TerminalLine = {
id: Date.now().toString() + Math.random(),
type,
content,
timestamp: new Date()
};
setLines(prev => [...prev, newLine]);
}, []);
const executeCommand = useCallback(async (command: string) => {
if (!shellToolRef.current || !command.trim()) return;
// Add command to history
if (command.trim() && !commandHistory.includes(command.trim())) {
setCommandHistory(prev => [...prev, command.trim()]);
}
setHistoryIndex(-1);
// Add input line
addLine('input', `$ ${command}`);
setIsExecuting(true);
try {
// Handle special help command
if (command.trim().toLowerCase() === 'help') {
const availableCommands = shellToolRef.current.getAvailableCommands();
const helpText = `Available commands:\n\n${availableCommands.map(cmd =>
`${cmd.name.padEnd(12)} - ${cmd.description}`
).join('\n')}\n\nUse 'which <command>' for more details about a specific command.`;
addLine('output', helpText);
} else {
const result = await shellToolRef.current.execute({ command });
// Update current working directory
const newCwd = shellToolRef.current.getCurrentWorkingDirectory();
setCurrentWorkingDirectory(newCwd);
// Add output
if (result && result.trim()) {
addLine('output', result);
}
}
} catch (error) {
addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`);
} finally {
setIsExecuting(false);
}
}, [addLine, commandHistory]);
const handleSubmit = useCallback((e: React.FormEvent) => {
e.preventDefault();
if (currentInput.trim() && !isExecuting) {
executeCommand(currentInput);
setCurrentInput('');
}
}, [currentInput, isExecuting, executeCommand]);
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if (e.key === 'ArrowUp') {
e.preventDefault();
if (commandHistory.length > 0) {
const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1);
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (historyIndex >= 0) {
const newIndex = historyIndex + 1;
if (newIndex >= commandHistory.length) {
setHistoryIndex(-1);
setCurrentInput('');
} else {
setHistoryIndex(newIndex);
setCurrentInput(commandHistory[newIndex]);
}
}
} else if (e.key === 'Tab') {
e.preventDefault();
// Basic tab completion could be added here
}
}, [commandHistory, historyIndex]);
const copyToClipboard = useCallback(async (content: string) => {
try {
await navigator.clipboard.writeText(content);
} catch (error) {
console.error('Failed to copy to clipboard:', error);
}
}, []);
const clearTerminal = useCallback(() => {
setLines([]);
}, []);
const getPrompt = () => {
const relativePath = currentWorkingDirectory.replace(`/projects/${projectId}`, '') || '/';
return `${projectId}:${relativePath}$`;
};
return (
<div className={cn("h-full flex flex-col bg-black text-green-400 font-mono text-sm", className)}>
{/* Terminal Header */}
<div className="flex items-center justify-between p-2 bg-gray-900 border-b border-gray-700">
<div className="flex items-center gap-2">
<div className="flex gap-1">
<div className="w-3 h-3 rounded-full bg-red-500"></div>
<div className="w-3 h-3 rounded-full bg-yellow-500"></div>
<div className="w-3 h-3 rounded-full bg-green-500"></div>
</div>
<span className="text-gray-300 text-xs">Terminal - {projectId}</span>
</div>
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
onClick={clearTerminal}
className="h-6 w-6 p-0 text-gray-400 hover:text-white hover:bg-gray-700"
>
<Trash2 className="h-3 w-3" />
</Button>
{onClose && (
<Button
variant="ghost"
size="sm"
onClick={onClose}
className="h-6 w-6 p-0 text-gray-400 hover:text-white hover:bg-gray-700"
>
<X className="h-3 w-3" />
</Button>
)}
</div>
</div>
{/* Terminal Content */}
<div className="flex-1 flex flex-col min-h-0">
<ScrollArea className="flex-1" ref={scrollRef}>
<div className="p-2 space-y-1">
{lines.map((line) => (
<div
key={line.id}
className={cn(
"group relative",
line.type === 'input' && "text-blue-400",
line.type === 'error' && "text-red-400",
line.type === 'output' && "text-green-400"
)}
>
<pre className="whitespace-pre-wrap break-words font-mono text-xs leading-relaxed">
{line.content}
</pre>
<Button
variant="ghost"
size="sm"
onClick={() => copyToClipboard(line.content)}
className="absolute right-0 top-0 h-4 w-4 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-gray-500 hover:text-white hover:bg-gray-700"
>
<Copy className="h-2 w-2" />
</Button>
</div>
))}
{isExecuting && (
<div className="text-yellow-400 text-xs">
<span className="animate-pulse">Executing...</span>
</div>
)}
</div>
</ScrollArea>
{/* Command Input */}
<div className="border-t border-gray-700 p-2">
<form onSubmit={handleSubmit} className="flex items-center gap-2">
<span className="text-blue-400 text-xs font-mono whitespace-nowrap">
{getPrompt()}
</span>
<input
ref={inputRef}
type="text"
value={currentInput}
onChange={(e) => setCurrentInput(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isExecuting}
className="flex-1 bg-transparent border-none outline-none text-green-400 font-mono text-xs placeholder-gray-500"
placeholder="Enter command..."
autoComplete="off"
spellCheck="false"
/>
</form>
</div>
</div>
</div>
);
}