fix: filecontent update while switching tabs, empty file crash

This commit is contained in:
Akhileshrangani4 2024-09-28 19:25:03 -04:00
parent 6845e1fef9
commit 5817b2ea48
2 changed files with 152 additions and 98 deletions

View File

@ -159,8 +159,9 @@ io.on("connection", async (socket) => {
await lockManager.acquireLock(data.sandboxId, async () => { await lockManager.acquireLock(data.sandboxId, async () => {
try { try {
if (!containers[data.sandboxId]) { // Start a new container if the container doesn't exist or it timed out.
containers[data.sandboxId] = await Sandbox.create({ timeoutMs: 1200000 }); if (!containers[data.sandboxId] || !(await containers[data.sandboxId].isRunning())) {
containers[data.sandboxId] = await Sandbox.create({ timeoutMs: 1200_000 });
console.log("Created container ", data.sandboxId); console.log("Created container ", data.sandboxId);
} }
} catch (e: any) { } catch (e: any) {

View File

@ -70,6 +70,8 @@ export default function CodeEditor({
const [activeFileId, setActiveFileId] = useState<string>("") const [activeFileId, setActiveFileId] = useState<string>("")
const [activeFileContent, setActiveFileContent] = useState("") const [activeFileContent, setActiveFileContent] = useState("")
const [deletingFolderId, setDeletingFolderId] = useState("") const [deletingFolderId, setDeletingFolderId] = useState("")
// Added this state to track the most recent content for each file
const [fileContents, setFileContents] = useState<Record<string, string>>({});
// Editor state // Editor state
const [editorLanguage, setEditorLanguage] = useState("plaintext") const [editorLanguage, setEditorLanguage] = useState("plaintext")
@ -257,6 +259,7 @@ export default function CodeEditor({
} }
}) })
}, [editorRef]) }, [editorRef])
// Generate widget effect // Generate widget effect
useEffect(() => { useEffect(() => {
if (generate.show) { if (generate.show) {
@ -335,6 +338,7 @@ export default function CodeEditor({
}) })
} }
}, [generate.show]) }, [generate.show])
// Suggestion widget effect // Suggestion widget effect
useEffect(() => { useEffect(() => {
if (!suggestionRef.current || !editorRef) return if (!suggestionRef.current || !editorRef) return
@ -378,12 +382,21 @@ export default function CodeEditor({
} }
const model = editorRef?.getModel() const model = editorRef?.getModel()
const line = model?.getLineContent(cursorLine) // added this because it was giving client side exception - Illegal value for lineNumber when opening an empty file
if (model) {
if (line === undefined || line.trim() !== "") { const totalLines = model.getLineCount();
decorations.instance?.clear() // 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 return
} }
}
if (decorations.instance) { if (decorations.instance) {
decorations.instance.set(decorations.options) decorations.instance.set(decorations.options)
@ -401,25 +414,33 @@ export default function CodeEditor({
}, [decorations.options]) }, [decorations.options])
// Save file keybinding logic effect // Save file keybinding logic effect
// Function to save the file content after a debounce period
const debouncedSaveData = useCallback( const debouncedSaveData = useCallback(
debounce((value: string | undefined, activeFileId: string | undefined) => { 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) => setTabs((prev) =>
prev.map((tab) => prev.map((tab) =>
tab.id === activeFileId ? { ...tab, saved: true } : tab tab.id === activeFileId ? { ...tab, saved: true } : tab
) )
) );
console.log(`Saving file...${activeFileId}`) console.log(`Saving file...${activeFileId}`);
console.log(`Saving file...${value}`) console.log(`Saving file...${content}`);
socket?.emit("saveFile", activeFileId, value) socket?.emit("saveFile", activeFileId, content);
}
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000), }, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000),
[socket] [socket, fileContents]
) );
// Keydown event listener to trigger file save on Ctrl+S or Cmd+S
useEffect(() => { useEffect(() => {
const down = (e: KeyboardEvent) => { const down = (e: KeyboardEvent) => {
if (e.key === "s" && (e.metaKey || e.ctrlKey)) { if (e.key === "s" && (e.metaKey || e.ctrlKey)) {
e.preventDefault() e.preventDefault()
debouncedSaveData(editorRef?.getValue(), activeFileId) debouncedSaveData(activeFileId);
} }
} }
document.addEventListener("keydown", down) document.addEventListener("keydown", down)
@ -516,7 +537,7 @@ export default function CodeEditor({
// Socket event listener effect // Socket event listener effect
useEffect(() => { useEffect(() => {
const onConnect = () => {} const onConnect = () => { }
const onDisconnect = () => { const onDisconnect = () => {
setTerminals([]) setTerminals([])
@ -586,31 +607,46 @@ export default function CodeEditor({
} // 300ms debounce delay, adjust as needed } // 300ms debounce delay, adjust as needed
const selectFile = (tab: TTab) => { const selectFile = (tab: TTab) => {
if (tab.id === activeFileId) return if (tab.id === activeFileId) return;
setGenerate((prev) => ({ ...prev, show: false })) setGenerate((prev) => ({ ...prev, show: false }));
const exists = tabs.find((t) => t.id === tab.id) // Check if the tab already exists in the list of open tabs
const exists = tabs.find((t) => t.id === tab.id);
setTabs((prev) => { setTabs((prev) => {
if (exists) { if (exists) {
setActiveFileId(exists.id) // If the tab exists, make it the active tab
return prev setActiveFileId(exists.id);
return prev;
} }
return [...prev, tab] // If the tab doesn't exist, add it to the list of tabs and make it active
}) return [...prev, tab];
});
if (fileCache.current.has(tab.id)) { // If the file's content is already cached, set it as the active content
setActiveFileContent(fileCache.current.get(tab.id)) if (fileContents[tab.id]) {
setActiveFileContent(fileContents[tab.id]);
} else { } else {
debouncedGetFile(tab.id, (response: SetStateAction<string>) => { // Otherwise, fetch the content of the file and cache it
fileCache.current.set(tab.id, response) debouncedGetFile(tab.id, (response: string) => {
setActiveFileContent(response) setFileContents(prev => ({ ...prev, [tab.id]: response }));
}) setActiveFileContent(response);
});
} }
setEditorLanguage(processFileType(tab.name)) // Set the editor language based on the file type
setActiveFileId(tab.id) setEditorLanguage(processFileType(tab.name));
// Set the active file ID to the new tab
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 // Close tab and remove from tabs
const closeTab = (id: string) => { const closeTab = (id: string) => {
@ -720,12 +756,25 @@ export default function CodeEditor({
<DisableAccessModal <DisableAccessModal
message={disableAccess.message} message={disableAccess.message}
open={disableAccess.isDisabled} open={disableAccess.isDisabled}
setOpen={() => {}} setOpen={() => { }}
/> />
<Loading /> <Loading />
</> </>
) )
useEffect(() => {
console.log('Editor mounted');
return () => console.log('Editor unmounted');
}, []);
useEffect(() => {
console.log('activeFileContent changed:');
}, [activeFileContent]);
useEffect(() => {
console.log('activeFileId changed:');
}, [activeFileId]);
return ( return (
<> <>
{/* Copilot DOM elements */} {/* Copilot DOM elements */}
@ -784,11 +833,11 @@ export default function CodeEditor({
const afterLineNumber = isAbove ? line - 1 : line const afterLineNumber = isAbove ? line - 1 : line
id = changeAccessor.addZone({ id = changeAccessor.addZone({
afterLineNumber, afterLineNumber,
heightInLines: isAbove?11: 12, heightInLines: isAbove ? 11 : 12,
domNode: generateRef.current, domNode: generateRef.current,
}) })
const contentWidget= generate.widget const contentWidget = generate.widget
if (contentWidget){ if (contentWidget) {
editorRef?.layoutContentWidget(contentWidget) editorRef?.layoutContentWidget(contentWidget)
} }
} else { } else {
@ -896,15 +945,10 @@ export default function CodeEditor({
beforeMount={handleEditorWillMount} beforeMount={handleEditorWillMount}
onMount={handleEditorMount} onMount={handleEditorMount}
onChange={(value) => { onChange={(value) => {
if (value === activeFileContent) { // If the new content is different from the cached content, update it
setTabs((prev) => if (value !== fileContents[activeFileId]) {
prev.map((tab) => setActiveFileContent(value ?? ""); // Update the active file content
tab.id === activeFileId // Mark the file as unsaved by setting 'saved' to false
? { ...tab, saved: true }
: tab
)
)
} else {
setTabs((prev) => setTabs((prev) =>
prev.map((tab) => prev.map((tab) =>
tab.id === activeFileId tab.id === activeFileId
@ -912,6 +956,15 @@ export default function CodeEditor({
: tab : 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={{ options={{