CodeIDE / src /App.js
FrederickSundeep's picture
commit initial 09-12-2025 016
5b4b486
raw
history blame
16.5 kB
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);
// 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 ----------
// Create a new file inside selected folder (or root)
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("/");
}
// Offer user to choose another parent folder
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);
// Set active to newly created file
const newPath = (targetParent ? targetParent + "/" : "") + filename;
setActivePath(newPath);
};
// Create a folder under selected folder or root
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);
};
// Rename selected node (file or folder)
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);
// compute new activePath (preserve parent)
const parts = activePath.split("/");
parts.pop();
const parent = parts.join("/");
const newPath = (parent ? parent + "/" : "") + newName;
setActivePath(newPath);
};
// Delete selected node (confirm if folder not empty)
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(""); // deselect / fallback
};
// Download single file
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();
// decide parent folder
const selected = getNodeByPath(tree, activePath);
let parentPath = "";
if (selected?.type === "folder") parentPath = selected.path; // fallback
// (above line intentionally split to maintain code clarity)
// compute parent path correctly:
if (selected?.type === "folder") parentPath = selected.path;
else if (selected?.type === "file") parentPath = selected.path.split("/").slice(0, -1).join("");
// create file under parent and write content
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 ----------
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;
}
const res = await runCode(node.content, selectedLang, stdin);
setOutput(res.output || "");
setProblems(res.error ? parseProblems(res.output) : []);
};
const handleAskFix = async () => {
const node = getNodeByPath(tree, activePath);
if (!node || node.type !== "file") {
setOutput("Select a file to apply fix.");
return;
}
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);
};
const handleExplainSelection = async () => {
const node = getNodeByPath(tree, activePath);
if (!node || node.type !== "file") {
setExplanation("Select a file to explain.");
return;
}
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);
};
// AI suggestions for continuation (simple)
const fetchAiSuggestions = async (code) => {
if (!code?.trim()) return;
const reply = await askAgent(`Suggest possible next lines for continuation. Return 3 short snippets.\n${code}`);
setAiSuggestions(reply.split("\n").filter((l) => l.trim()));
};
// ---------- 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 (moved inside component so it sees activePath) ----------
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>
);
};
// ---------- 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}>πŸ“„ New File</button>
<button onClick={handleNewFolder}>πŸ“ New Folder</button>
<button onClick={handleRename}>✏️ Rename</button>
<button onClick={handleDelete}>πŸ—‘ Delete</button>
<button onClick={downloadFile}>πŸ“₯ Download</button>
<button onClick={() => downloadProjectZip()}>πŸ“¦ ZIP</button>
<button onClick={handleImportFileClick}>πŸ“€ Import File</button>
</div>
<div className="ide-menubar-right">
<button onClick={handleSearchToggle}>πŸ” Search</button>
<button onClick={handleRun}>β–Ά Run</button>
<button onClick={handleAskFix}>πŸ€– Fix</button>
<button onClick={handleExplainSelection}>πŸ“– Explain</button>
<button onClick={() => setTheme((t) => (t === "vs-dark" ? "light" : "vs-dark"))}>
{theme === "vs-dark" ? "β˜€οΈ" : "πŸŒ™"}
</button>
</div>
</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">οΌ‹</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}>πŸ’‘ Apply Fix</button>
<button onClick={handleExplainSelection}>πŸ“– 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;