From 8ae166fef418997549ff7d4acaba64c3112b358e Mon Sep 17 00:00:00 2001 From: Akhileshrangani4 Date: Sun, 22 Sep 2024 00:23:12 -0400 Subject: [PATCH 1/3] fix: close the terminal opened with run button --- frontend/components/editor/navbar/run.tsx | 85 ++++++++++++----------- 1 file changed, 45 insertions(+), 40 deletions(-) diff --git a/frontend/components/editor/navbar/run.tsx b/frontend/components/editor/navbar/run.tsx index 82f69c9..26e8bbd 100644 --- a/frontend/components/editor/navbar/run.tsx +++ b/frontend/components/editor/navbar/run.tsx @@ -1,5 +1,6 @@ "use client"; +import React, { useEffect, useRef } from 'react'; import { Play, StopCircle } from "lucide-react"; import { Button } from "@/components/ui/button"; import { useTerminal } from "@/context/TerminalContext"; @@ -16,53 +17,57 @@ export default function RunButtonModal({ setIsRunning: (running: boolean) => void; sandboxData: Sandbox; }) { - const { createNewTerminal, terminals, closeTerminal } = useTerminal(); + const { createNewTerminal, closeTerminal, terminals } = useTerminal(); const { setIsPreviewCollapsed, previewPanelRef } = usePreview(); + // Ref to keep track of the last created terminal's ID + const lastCreatedTerminalRef = useRef(null); - const handleRun = () => { - if (isRunning) { - console.log('Stopping sandbox...'); - console.log('Closing Preview Window'); - - terminals.forEach(term => { - if (term.terminal) { - closeTerminal(term.id); - console.log('Closing Terminal', term.id); - } - }); - - setIsPreviewCollapsed(true); - previewPanelRef.current?.collapse(); - } else { - console.log('Running sandbox...'); - console.log('Opening Terminal'); - console.log('Opening Preview Window'); - - if (terminals.length < 4) { - if (sandboxData.type === "streamlit") { - createNewTerminal( - "pip install -r requirements.txt && streamlit run main.py --server.runOnSave true" - ); - } else { - createNewTerminal("yarn install && yarn dev"); - } - } else { - toast.error("You reached the maximum # of terminals."); - console.error("Maximum number of terminals reached."); + // Effect to update the lastCreatedTerminalRef when a new terminal is added + useEffect(() => { + if (terminals.length > 0 && !isRunning) { + const latestTerminal = terminals[terminals.length - 1]; + if (latestTerminal && latestTerminal.id !== lastCreatedTerminalRef.current) { + lastCreatedTerminalRef.current = latestTerminal.id; } - - setIsPreviewCollapsed(false); - previewPanelRef.current?.expand(); } + }, [terminals, isRunning]); + + const handleRun = async () => { + if (isRunning && lastCreatedTerminalRef.current) + { + await closeTerminal(lastCreatedTerminalRef.current); + lastCreatedTerminalRef.current = null; + setIsPreviewCollapsed(true); + previewPanelRef.current?.collapse(); + } + else if (!isRunning && terminals.length < 4) + { + const command = sandboxData.type === "streamlit" + ? "pip install -r requirements.txt && streamlit run main.py --server.runOnSave true" + : "yarn install && yarn dev"; + + try { + // Create a new terminal with the appropriate command + await createNewTerminal(command); + setIsPreviewCollapsed(false); + previewPanelRef.current?.expand(); + } catch (error) { + toast.error("Failed to create new terminal."); + console.error("Error creating new terminal:", error); + return; + } + } else if (!isRunning) { + toast.error("You've reached the maximum number of terminals."); + return; + } + setIsRunning(!isRunning); }; return ( - <> - - + ); } \ No newline at end of file From 229b489c1e778d4489d5b08c49c3d035e81e6537 Mon Sep 17 00:00:00 2001 From: Akhileshrangani4 Date: Sat, 28 Sep 2024 19:25:03 -0400 Subject: [PATCH 2/3] fix: filecontent update while switching tabs, empty file crash # Conflicts: # backend/server/src/index.ts --- frontend/components/editor/index.tsx | 239 ++++++++++++++++----------- 1 file changed, 146 insertions(+), 93 deletions(-) diff --git a/frontend/components/editor/index.tsx b/frontend/components/editor/index.tsx index ab497ad..991579b 100644 --- a/frontend/components/editor/index.tsx +++ b/frontend/components/editor/index.tsx @@ -79,6 +79,8 @@ export default function CodeEditor({ const [activeFileId, setActiveFileId] = useState("") const [activeFileContent, setActiveFileContent] = useState("") const [deletingFolderId, setDeletingFolderId] = useState("") + // Added this state to track the most recent content for each file + const [fileContents, setFileContents] = useState>({}); // Editor state const [editorLanguage, setEditorLanguage] = useState("plaintext") @@ -335,6 +337,7 @@ export default function CodeEditor({ } }) }, [editorRef]) + // Generate widget effect useEffect(() => { if (generate.show) { @@ -413,6 +416,7 @@ export default function CodeEditor({ }) } }, [generate.show]) + // Suggestion widget effect useEffect(() => { if (!suggestionRef.current || !editorRef) return @@ -456,11 +460,20 @@ export default function CodeEditor({ } const model = editorRef?.getModel() - const line = model?.getLineContent(cursorLine) - - if (line === undefined || line.trim() !== "") { - decorations.instance?.clear() - return + // added this because it was giving client side exception - Illegal value for lineNumber when opening an empty file + if (model) { + const totalLines = model.getLineCount(); + // Check if the cursorLine is a valid number, If cursorLine is out of bounds, we fall back to 1 (the first line) as a default safe value. + const lineNumber = cursorLine > 0 && cursorLine <= totalLines ? cursorLine : 1; // fallback to a valid line number + // If for some reason the content doesn't exist, we use an empty string as a fallback. + const line = model.getLineContent(lineNumber) ?? ""; + // Check if the line is not empty or only whitespace (i.e., `.trim()` removes spaces). + // If the line has content, we clear any decorations using the instance of the `decorations` object. + // Decorations refer to editor highlights, underlines, or markers, so this clears those if conditions are met. + if (line.trim() !== "") { + decorations.instance?.clear(); + return + } } if (decorations.instance) { @@ -479,25 +492,33 @@ export default function CodeEditor({ }, [decorations.options]) // Save file keybinding logic effect + // Function to save the file content after a debounce period const debouncedSaveData = useCallback( - debounce((value: string | undefined, activeFileId: string | undefined) => { - setTabs((prev) => - prev.map((tab) => - tab.id === activeFileId ? { ...tab, saved: true } : tab - ) - ) - console.log(`Saving file...${activeFileId}`) - console.log(`Saving file...${value}`) - socket?.emit("saveFile", activeFileId, value) - }, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000), - [socket] - ) + debounce((activeFileId: string | undefined) => { + if (activeFileId) { + // Get the current content of the file + const content = fileContents[activeFileId]; + // Mark the file as saved in the tabs + setTabs((prev) => + prev.map((tab) => + tab.id === activeFileId ? { ...tab, saved: true } : tab + ) + ); + console.log(`Saving file...${activeFileId}`); + console.log(`Saving file...${content}`); + socket?.emit("saveFile", activeFileId, content); + } + }, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000), + [socket, fileContents] + ); + + // Keydown event listener to trigger file save on Ctrl+S or Cmd+S useEffect(() => { const down = (e: KeyboardEvent) => { if (e.key === "s" && (e.metaKey || e.ctrlKey)) { e.preventDefault() - debouncedSaveData(editorRef?.getValue(), activeFileId) + debouncedSaveData(activeFileId); } } document.addEventListener("keydown", down) @@ -594,7 +615,7 @@ export default function CodeEditor({ // Socket event listener effect useEffect(() => { - const onConnect = () => {} + const onConnect = () => { } const onDisconnect = () => { setTerminals([]) @@ -664,31 +685,46 @@ export default function CodeEditor({ } // 300ms debounce delay, adjust as needed const selectFile = (tab: TTab) => { - if (tab.id === activeFileId) return - - setGenerate((prev) => ({ ...prev, show: false })) - - const exists = tabs.find((t) => t.id === tab.id) + if (tab.id === activeFileId) return; + + setGenerate((prev) => ({ ...prev, show: false })); + + // Check if the tab already exists in the list of open tabs + const exists = tabs.find((t) => t.id === tab.id); setTabs((prev) => { if (exists) { - setActiveFileId(exists.id) - return prev + // If the tab exists, make it the active tab + setActiveFileId(exists.id); + return prev; } - return [...prev, tab] - }) - - if (fileCache.current.has(tab.id)) { - setActiveFileContent(fileCache.current.get(tab.id)) + // If the tab doesn't exist, add it to the list of tabs and make it active + return [...prev, tab]; + }); + + // If the file's content is already cached, set it as the active content + if (fileContents[tab.id]) { + setActiveFileContent(fileContents[tab.id]); } else { - debouncedGetFile(tab.id, (response: SetStateAction) => { - fileCache.current.set(tab.id, response) - setActiveFileContent(response) - }) + // Otherwise, fetch the content of the file and cache it + debouncedGetFile(tab.id, (response: string) => { + setFileContents(prev => ({ ...prev, [tab.id]: response })); + setActiveFileContent(response); + }); } + + // Set the editor language based on the file type + setEditorLanguage(processFileType(tab.name)); + // Set the active file ID to the new tab + setActiveFileId(tab.id); + }; - setEditorLanguage(processFileType(tab.name)) - setActiveFileId(tab.id) - } + // Added this effect to update fileContents when the editor content changes + useEffect(() => { + if (activeFileId) { + // Cache the current active file content using the file ID as the key + setFileContents(prev => ({ ...prev, [activeFileId]: activeFileContent })); + } + }, [activeFileContent, activeFileId]); // Close tab and remove from tabs const closeTab = (id: string) => { @@ -704,8 +740,8 @@ export default function CodeEditor({ ? numTabs === 1 ? null : index < numTabs - 1 - ? tabs[index + 1].id - : tabs[index - 1].id + ? tabs[index + 1].id + : tabs[index - 1].id : activeFileId setTabs((prev) => prev.filter((t) => t.id !== id)) @@ -798,12 +834,25 @@ export default function CodeEditor({ {}} + setOpen={() => { }} /> ) + useEffect(() => { + console.log('Editor mounted'); + return () => console.log('Editor unmounted'); + }, []); + + useEffect(() => { + console.log('activeFileContent changed:'); + }, [activeFileContent]); + + useEffect(() => { + console.log('activeFileId changed:'); + }, [activeFileId]); + return ( <> {/* Copilot DOM elements */} @@ -837,8 +886,8 @@ export default function CodeEditor({ code: (isSelected && editorRef?.getSelection() ? editorRef - ?.getModel() - ?.getValueInRange(editorRef?.getSelection()!) + ?.getModel() + ?.getValueInRange(editorRef?.getSelection()!) : editorRef?.getValue()) ?? "", line: generate.line, }} @@ -963,58 +1012,62 @@ export default function CodeEditor({ ) : // Note clerk.loaded is required here due to a bug: https://github.com/clerk/javascript/issues/1643 - clerk.loaded ? ( - <> - {provider && userInfo ? ( - - ) : null} - { - if (value === activeFileContent) { - setTabs((prev) => - prev.map((tab) => - tab.id === activeFileId - ? { ...tab, saved: true } - : tab + clerk.loaded ? ( + <> + {provider && userInfo ? ( + + ) : null} + { + // If the new content is different from the cached content, update it + if (value !== fileContents[activeFileId]) { + setActiveFileContent(value ?? ""); // Update the active file content + // Mark the file as unsaved by setting 'saved' to false + setTabs((prev) => + prev.map((tab) => + tab.id === activeFileId + ? { ...tab, saved: false } + : tab + ) ) - ) - } else { - setTabs((prev) => - prev.map((tab) => - tab.id === activeFileId - ? { ...tab, saved: false } - : tab + } else { + // If the content matches the cached content, mark the file as saved + setTabs((prev) => + prev.map((tab) => + tab.id === activeFileId + ? { ...tab, saved: true } + : tab + ) ) - ) - } - }} - options={{ - tabSize: 2, - minimap: { - enabled: false, - }, - padding: { - bottom: 4, - top: 4, - }, - scrollBeyondLastLine: false, - fixedOverflowWidgets: true, - fontFamily: "var(--font-geist-mono)", - }} - theme="vs-dark" - value={activeFileContent} - /> - - ) : ( -
- - Waiting for Clerk to load... -
- )} + } + }} + options={{ + tabSize: 2, + minimap: { + enabled: false, + }, + padding: { + bottom: 4, + top: 4, + }, + scrollBeyondLastLine: false, + fixedOverflowWidgets: true, + fontFamily: "var(--font-geist-mono)", + }} + theme="vs-dark" + value={activeFileContent} + /> + + ) : ( +
+ + Waiting for Clerk to load... +
+ )} From cf6888e3d3f373973e2710fb6986e2cb605ffc75 Mon Sep 17 00:00:00 2001 From: Akhileshrangani4 Date: Wed, 2 Oct 2024 18:29:09 -0400 Subject: [PATCH 3/3] chore: remove unnecessary code --- frontend/components/editor/index.tsx | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/frontend/components/editor/index.tsx b/frontend/components/editor/index.tsx index 991579b..415b552 100644 --- a/frontend/components/editor/index.tsx +++ b/frontend/components/editor/index.tsx @@ -840,19 +840,6 @@ export default function CodeEditor({ ) - useEffect(() => { - console.log('Editor mounted'); - return () => console.log('Editor unmounted'); - }, []); - - useEffect(() => { - console.log('activeFileContent changed:'); - }, [activeFileContent]); - - useEffect(() => { - console.log('activeFileId changed:'); - }, [activeFileId]); - return ( <> {/* Copilot DOM elements */}