Spaces:
Running
Running
| import { useState, useEffect, useRef } from "react"; | |
| import Editor from "@monaco-editor/react"; | |
| import { askAgent } from "./agent/assistant"; | |
| import { runCode } from "./agent/runner"; | |
| import { | |
| loadTree, | |
| saveTree, | |
| addFile, | |
| addFolder, | |
| renameNode, | |
| deleteNode, | |
| getNodeByPath, | |
| updateFileContent, | |
| searchTree, | |
| } from "./fileStore"; | |
| import { downloadProjectZip } from "./zipExport"; | |
| import { parseProblems } from "./problemParser"; | |
| import "./App.css"; | |
| // =================== SUPPORTED LANGUAGES =================== | |
| const LANGUAGE_OPTIONS = [ | |
| { id: "python", ext: ".py", icon: "π", monaco: "python" }, | |
| { id: "javascript", ext: ".js", icon: "π¨", monaco: "javascript" }, | |
| { id: "typescript", ext: ".ts", icon: "π¦", monaco: "typescript" }, | |
| { id: "cpp", ext: ".cpp", icon: "π ", monaco: "cpp" }, | |
| { id: "c", ext: ".c", icon: "π·", monaco: "c" }, | |
| { id: "java", ext: ".java", icon: "β", monaco: "java" }, | |
| { id: "html", ext: ".html", icon: "π", monaco: "html" }, | |
| { id: "css", ext: ".css", icon: "π¨", monaco: "css" }, | |
| { id: "json", ext: ".json", icon: "π§Ύ", monaco: "json" }, | |
| ]; | |
| const RUNNABLE_LANGS = ["python", "javascript", "java"]; | |
| // =================== APP =================== | |
| function App() { | |
| const [tree, setTree] = useState(loadTree()); | |
| const [activePath, setActivePath] = useState("main.py"); // selected file or folder path | |
| const [output, setOutput] = useState(""); | |
| const [prompt, setPrompt] = useState(""); | |
| const [explanation, setExplanation] = useState(""); | |
| const [stdin, setStdin] = useState(""); | |
| const [problems, setProblems] = useState([]); | |
| const [theme, setTheme] = useState("vs-dark"); | |
| const [searchOpen, setSearchOpen] = useState(false); | |
| const [searchQuery, setSearchQuery] = useState(""); | |
| const [aiSuggestions, setAiSuggestions] = useState([]); | |
| const [contextMenu, setContextMenu] = useState(null); // {x,y,file} | |
| const editorRef = useRef(null); | |
| const fileInputRef = useRef(null); | |
| // NEW: loading states | |
| const [isRunning, setIsRunning] = useState(false); | |
| const [isFixing, setIsFixing] = useState(false); | |
| const [isExplaining, setIsExplaining] = useState(false); | |
| // Always persist tree on change | |
| useEffect(() => { | |
| saveTree(tree); | |
| }, [tree]); | |
| // helpers | |
| const currentNode = getNodeByPath(tree, activePath); | |
| const langMeta = | |
| LANGUAGE_OPTIONS.find((l) => currentNode?.name?.endsWith(l.ext)) || | |
| LANGUAGE_OPTIONS[0]; | |
| // ---------- Tree utilities ---------- | |
| const collectFolderPaths = (node, acc = []) => { | |
| if (!node) return acc; | |
| if (node.type === "folder") acc.push(node.path || ""); | |
| node.children?.forEach((c) => collectFolderPaths(c, acc)); | |
| return acc; | |
| }; | |
| // ---------- File / Folder actions ---------- | |
| const handleNewFile = () => { | |
| const filename = window.prompt("Filename (with extension):", "untitled.js"); | |
| if (!filename) return; | |
| // Determine default parent | |
| const selected = getNodeByPath(tree, activePath); | |
| let parentPath = ""; | |
| if (selected?.type === "folder") parentPath = selected.path; | |
| else if (selected?.type === "file") { | |
| const parts = selected.path.split("/").slice(0, -1); | |
| parentPath = parts.join("/"); | |
| } | |
| const folders = collectFolderPaths(tree); | |
| const suggestion = parentPath || folders[0] || ""; | |
| const chosen = window.prompt( | |
| `Parent folder (enter path). Available:\n${folders.join("\n")}\n\nLeave empty for root.`, | |
| suggestion | |
| ); | |
| const targetParent = chosen == null ? parentPath : (chosen.trim() || ""); | |
| const updated = addFile(tree, filename, targetParent); | |
| setTree(updated); | |
| const newPath = (targetParent ? targetParent + "/" : "") + filename; | |
| setActivePath(newPath); | |
| }; | |
| const handleNewFolder = () => { | |
| const name = window.prompt("Folder name:", "new_folder"); | |
| if (!name) return; | |
| const selected = getNodeByPath(tree, activePath); | |
| const parentPath = selected && selected.type === "folder" ? selected.path : ""; | |
| const updated = addFolder(tree, name, parentPath); | |
| setTree(updated); | |
| }; | |
| const handleRename = () => { | |
| if (!activePath) return; | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node) return; | |
| const newName = window.prompt("New name:", node.name); | |
| if (!newName || newName === node.name) return; | |
| const updated = renameNode(tree, activePath, newName); | |
| setTree(updated); | |
| const parts = activePath.split("/"); | |
| parts.pop(); | |
| const parent = parts.join("/"); | |
| const newPath = (parent ? parent + "/" : "") + newName; | |
| setActivePath(newPath); | |
| }; | |
| const handleDelete = () => { | |
| if (!activePath) return; | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node) return; | |
| if (node.type === "folder" && node.children?.length > 0) { | |
| const ok = window.confirm(`Folder "${node.name}" has ${node.children.length} items. Delete anyway?`); | |
| if (!ok) return; | |
| } else { | |
| const ok = window.confirm(`Delete "${node.name}"?`); | |
| if (!ok) return; | |
| } | |
| const updated = deleteNode(tree, activePath); | |
| setTree(updated); | |
| setActivePath(""); | |
| }; | |
| const downloadFile = () => { | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node || node.type !== "file") return; | |
| const blob = new Blob([node.content || ""], { type: "text/plain;charset=utf-8" }); | |
| const a = document.createElement("a"); | |
| a.href = URL.createObjectURL(blob); | |
| a.download = node.name; | |
| a.click(); | |
| }; | |
| // Import file from user's machine into selected folder | |
| const handleImportFileClick = () => fileInputRef.current?.click(); | |
| const handleFileInputChange = async (e) => { | |
| const f = e.target.files?.[0]; | |
| if (!f) return; | |
| const text = await f.text(); | |
| const selected = getNodeByPath(tree, activePath); | |
| let parentPath = ""; | |
| if (selected?.type === "folder") parentPath = selected.path; | |
| else if (selected?.type === "file") parentPath = selected.path.split("/").slice(0, -1).join(""); | |
| const updated = addFile(tree, f.name, parentPath); | |
| const newPath = (parentPath ? parentPath + "/" : "") + f.name; | |
| const finalTree = updateFileContent(updated, newPath, text); | |
| setTree(finalTree); | |
| setActivePath(newPath); | |
| e.target.value = ""; | |
| }; | |
| // ---------- Run & Agent (with progress flags) ---------- | |
| const handleRun = async () => { | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node || node.type !== "file") { | |
| setOutput("Select a file to run."); | |
| return; | |
| } | |
| const selectedLang = LANGUAGE_OPTIONS.find((l) => node.name.endsWith(l.ext))?.id; | |
| if (!selectedLang || !RUNNABLE_LANGS.includes(selectedLang)) { | |
| setOutput(`β οΈ Run not supported for this file type.`); | |
| return; | |
| } | |
| setIsRunning(true); | |
| setOutput(""); // clear previous | |
| setProblems([]); | |
| try { | |
| const res = await runCode(node.content, selectedLang, stdin); | |
| setOutput(res.output || ""); | |
| setProblems(res.error ? parseProblems(res.output) : []); | |
| } catch (err) { | |
| setOutput(String(err)); | |
| } finally { | |
| setIsRunning(false); | |
| } | |
| }; | |
| const handleAskFix = async () => { | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node || node.type !== "file") { | |
| setOutput("Select a file to apply fix."); | |
| return; | |
| } | |
| setIsFixing(true); | |
| try { | |
| const userHint = prompt.trim() ? `User request: ${prompt}` : ""; | |
| const reply = await askAgent( | |
| `Improve, debug, or refactor this ${LANGUAGE_OPTIONS.find((l) => node.name.endsWith(l.ext))?.id || "file"} file.\n${userHint}\nReturn ONLY updated code, no explanation.\n\nCODE:\n${node.content}` | |
| ); | |
| const updatedTree = updateFileContent(tree, node.path, reply); | |
| setTree(updatedTree); | |
| } catch (err) { | |
| setOutput(String(err)); | |
| } finally { | |
| setIsFixing(false); | |
| } | |
| }; | |
| const handleExplainSelection = async () => { | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node || node.type !== "file") { | |
| setExplanation("Select a file to explain."); | |
| return; | |
| } | |
| setIsExplaining(true); | |
| try { | |
| const editor = editorRef.current; | |
| let selectedCode = ""; | |
| try { | |
| selectedCode = editor?.getModel()?.getValueInRange(editor.getSelection()) || ""; | |
| } catch {} | |
| const code = selectedCode.trim() || node.content; | |
| const userHint = prompt.trim() ? `Focus on: ${prompt}` : "Give a clear and simple explanation."; | |
| const reply = await askAgent( | |
| `Explain what this code does, any risks, and improvements.\n${userHint}\n\nCODE:\n${code}` | |
| ); | |
| setExplanation(reply); | |
| } catch (err) { | |
| setExplanation(String(err)); | |
| } finally { | |
| setIsExplaining(false); | |
| } | |
| }; | |
| // AI suggestions for continuation (simple) | |
| const fetchAiSuggestions = async (code) => { | |
| if (!code?.trim()) return; | |
| try { | |
| const reply = await askAgent(`Suggest possible next lines for continuation. Return 3 short snippets.\n${code}`); | |
| setAiSuggestions(reply.split("\n").filter((l) => l.trim())); | |
| } catch { | |
| // ignore suggestion errors | |
| } | |
| }; | |
| // ---------- Search ---------- | |
| const handleSearchToggle = () => setSearchOpen(!searchOpen); | |
| const handleSearchNow = () => { | |
| if (!searchQuery) return; | |
| const results = searchTree(tree, searchQuery); | |
| alert(`Found ${results.length} results:\n` + JSON.stringify(results, null, 2)); | |
| }; | |
| // ---------- Editor change ---------- | |
| const updateActiveFileContent = (value) => { | |
| const node = getNodeByPath(tree, activePath); | |
| if (!node) return; | |
| const updated = updateFileContent(tree, activePath, value ?? ""); | |
| setTree(updated); | |
| }; | |
| // ---------- Render Tree (inside component) ---------- | |
| const renderTree = (node, depth = 0) => { | |
| const isActive = node.path === activePath; | |
| return ( | |
| <div key={node.path || node.name} style={{ paddingLeft: depth * 10 }}> | |
| <div | |
| className={`tree-item ${node.type} ${isActive ? "ide-file-item-active" : ""}`} | |
| onClick={() => setActivePath(node.path)} | |
| onContextMenu={(e) => { | |
| e.preventDefault(); | |
| setActivePath(node.path); | |
| setContextMenu({ x: e.pageX, y: e.pageY, file: node.path }); | |
| }} | |
| style={{ display: "flex", alignItems: "center", gap: 8 }} | |
| > | |
| <span style={{ width: 18 }}>{node.type === "folder" ? "π" : "π"}</span> | |
| <span className="ide-file-name">{node.name}</span> | |
| </div> | |
| {node.children && node.children.map((c) => renderTree(c, depth + 1))} | |
| </div> | |
| ); | |
| }; | |
| // any loading? | |
| const anyLoading = isRunning || isFixing || isExplaining; | |
| // ---------- JSX UI ---------- | |
| return ( | |
| <div className={`ide-root ${theme === "vs-dark" ? "ide-dark" : "ide-light"}`}> | |
| {/* Hidden file input for import */} | |
| <input ref={fileInputRef} id="file-import-input" type="file" style={{ display: "none" }} onChange={handleFileInputChange} /> | |
| {/* Top menu */} | |
| <div className="ide-menubar"> | |
| <div className="ide-menubar-left"> | |
| <span className="ide-logo">βοΈ DevMate IDE</span> | |
| <button onClick={handleNewFile} disabled={anyLoading}>π New File</button> | |
| <button onClick={handleNewFolder} disabled={anyLoading}>π New Folder</button> | |
| <button onClick={handleRename} disabled={anyLoading}>βοΈ Rename</button> | |
| <button onClick={handleDelete} disabled={anyLoading}>π Delete</button> | |
| <button onClick={downloadFile} disabled={anyLoading}>π₯ Download</button> | |
| <button onClick={() => downloadProjectZip()} disabled={anyLoading}>π¦ ZIP</button> | |
| <button onClick={handleImportFileClick} disabled={anyLoading}>π€ Import File</button> | |
| </div> | |
| <div className="ide-menubar-right"> | |
| <button onClick={handleSearchToggle} disabled={anyLoading}>π Search</button> | |
| <button onClick={handleRun} disabled={isRunning || anyLoading}> | |
| {isRunning ? "β³ Running..." : "βΆ Run"} | |
| </button> | |
| <button onClick={handleAskFix} disabled={isFixing || anyLoading}> | |
| {isFixing ? "β³ Fixing..." : "π€ Fix"} | |
| </button> | |
| <button onClick={handleExplainSelection} disabled={isExplaining || anyLoading}> | |
| {isExplaining ? "β³ Explaining..." : "π Explain"} | |
| </button> | |
| <button onClick={() => setTheme((t) => (t === "vs-dark" ? "light" : "vs-dark"))} disabled={anyLoading}> | |
| {theme === "vs-dark" ? "βοΈ" : "π"} | |
| </button> | |
| </div> | |
| </div> | |
| {/* Indeterminate progress bar under menubar when busy */} | |
| {anyLoading && ( | |
| <div className="ide-progress-wrap"> | |
| <div className="ide-progress" /> | |
| </div> | |
| )} | |
| {/* Body */} | |
| <div className="ide-body"> | |
| {/* Sidebar */} | |
| <div className="ide-sidebar"> | |
| <div className="ide-sidebar-header"> | |
| <span>EXPLORER</span> | |
| <button className="ide-icon-button" onClick={handleNewFile} title="New File" disabled={anyLoading}>οΌ</button> | |
| </div> | |
| <div className="ide-file-list" style={{ padding: 6 }}>{renderTree(tree)}</div> | |
| </div> | |
| {/* Main (editor + bottom panels) */} | |
| <div className="ide-main"> | |
| <div className="ide-editor-wrapper"> | |
| <Editor | |
| height="100%" | |
| theme={theme} | |
| language={langMeta.monaco} | |
| value={currentNode?.content || ""} | |
| onChange={updateActiveFileContent} | |
| onMount={(editor) => (editorRef.current = editor)} | |
| onBlur={() => fetchAiSuggestions(currentNode?.content)} | |
| options={{ | |
| minimap: { enabled: true }, | |
| fontSize: 14, | |
| scrollBeyondLastLine: false, | |
| }} | |
| /> | |
| </div> | |
| {/* AI inline suggestions popup */} | |
| {aiSuggestions.length > 0 && ( | |
| <div className="ai-popup"> | |
| {aiSuggestions.map((s, i) => ( | |
| <div key={i} className="ai-suggest" onClick={() => updateActiveFileContent((currentNode?.content || "") + "\n" + s)}>{s}</div> | |
| ))} | |
| </div> | |
| )} | |
| {/* Bottom panels */} | |
| <div className="ide-panels"> | |
| <pre className="ide-output">{output}</pre> | |
| <input className="ide-input-box" placeholder="Program input..." value={stdin} onChange={(e) => setStdin(e.target.value)} /> | |
| {problems.length > 0 && ( | |
| <div className="ide-problems-panel"> | |
| <div>π¨ Problems ({problems.length})</div> | |
| {problems.map((p, i) => ( | |
| <div key={i}> | |
| {p.path}:{p.line} β {p.message} | |
| </div> | |
| ))} | |
| </div> | |
| )} | |
| </div> | |
| </div> | |
| {/* Right AI panel */} | |
| <div className="ide-right-panel"> | |
| <div className="ide-ai-header">π€ AI Assistant</div> | |
| <div className="ide-ai-section"> | |
| <label className="ide-ai-label">Instruction</label> | |
| <textarea className="ide-agent-textarea" placeholder="Ask the AI (optimize, add tests, convert, etc.)" value={prompt} onChange={(e) => setPrompt(e.target.value)} /> | |
| </div> | |
| <div className="ide-ai-buttons"> | |
| <button onClick={handleAskFix} disabled={isFixing || anyLoading}>{isFixing ? "β³ Apply Fix" : "π‘ Apply Fix"}</button> | |
| <button onClick={handleExplainSelection} disabled={isExplaining || anyLoading}>{isExplaining ? "β³ Explaining" : "π Explain Code"}</button> | |
| </div> | |
| {explanation && ( | |
| <div className="ide-ai-section"> | |
| <label className="ide-ai-label">Explanation</label> | |
| <div className="ide-explain">{explanation}</div> | |
| </div> | |
| )} | |
| </div> | |
| </div> | |
| {/* Search dialog */} | |
| {searchOpen && ( | |
| <div className="search-dialog"> | |
| <input placeholder="Search text..." onChange={(e) => setSearchQuery(e.target.value)} /> | |
| <button onClick={handleSearchNow}>Search</button> | |
| </div> | |
| )} | |
| {/* Context menu */} | |
| {contextMenu && ( | |
| <div className="ide-context-menu" style={{ top: contextMenu.y, left: contextMenu.x }} onMouseLeave={() => setContextMenu(null)}> | |
| <div onClick={() => { setContextMenu(null); handleRename(); }}>βοΈ Rename</div> | |
| <div onClick={() => { setContextMenu(null); handleDelete(); }}>π Delete</div> | |
| <div onClick={() => { setContextMenu(null); downloadFile(); }}>π₯ Download</div> | |
| </div> | |
| )} | |
| </div> | |
| ); | |
| } | |
| export default App; | |