Merge pull request #8 from jamesmurdza/fix/editor-file-cache
Fix buggy editor behavior related to file cache
This commit is contained in:
commit
08fccdd506
@ -79,6 +79,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")
|
||||||
@ -335,6 +337,7 @@ export default function CodeEditor({
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}, [editorRef])
|
}, [editorRef])
|
||||||
|
|
||||||
// Generate widget effect
|
// Generate widget effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (generate.show) {
|
if (generate.show) {
|
||||||
@ -413,6 +416,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
|
||||||
@ -456,11 +460,20 @@ 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.
|
||||||
return
|
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) {
|
if (decorations.instance) {
|
||||||
@ -479,25 +492,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) => {
|
||||||
setTabs((prev) =>
|
if (activeFileId) {
|
||||||
prev.map((tab) =>
|
// Get the current content of the file
|
||||||
tab.id === activeFileId ? { ...tab, saved: true } : tab
|
const content = fileContents[activeFileId];
|
||||||
)
|
|
||||||
)
|
|
||||||
console.log(`Saving file...${activeFileId}`)
|
|
||||||
console.log(`Saving file...${value}`)
|
|
||||||
socket?.emit("saveFile", activeFileId, value)
|
|
||||||
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY) || 1000),
|
|
||||||
[socket]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
// 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(() => {
|
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)
|
||||||
@ -594,7 +615,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([])
|
||||||
@ -664,31 +685,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)) {
|
|
||||||
setActiveFileContent(fileCache.current.get(tab.id))
|
// If the file's content is already cached, set it as the active content
|
||||||
|
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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 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))
|
// Added this effect to update fileContents when the editor content changes
|
||||||
setActiveFileId(tab.id)
|
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) => {
|
||||||
@ -704,8 +740,8 @@ export default function CodeEditor({
|
|||||||
? numTabs === 1
|
? numTabs === 1
|
||||||
? null
|
? null
|
||||||
: index < numTabs - 1
|
: index < numTabs - 1
|
||||||
? tabs[index + 1].id
|
? tabs[index + 1].id
|
||||||
: tabs[index - 1].id
|
: tabs[index - 1].id
|
||||||
: activeFileId
|
: activeFileId
|
||||||
|
|
||||||
setTabs((prev) => prev.filter((t) => t.id !== id))
|
setTabs((prev) => prev.filter((t) => t.id !== id))
|
||||||
@ -798,7 +834,7 @@ export default function CodeEditor({
|
|||||||
<DisableAccessModal
|
<DisableAccessModal
|
||||||
message={disableAccess.message}
|
message={disableAccess.message}
|
||||||
open={disableAccess.isDisabled}
|
open={disableAccess.isDisabled}
|
||||||
setOpen={() => {}}
|
setOpen={() => { }}
|
||||||
/>
|
/>
|
||||||
<Loading />
|
<Loading />
|
||||||
</>
|
</>
|
||||||
@ -837,8 +873,8 @@ export default function CodeEditor({
|
|||||||
code:
|
code:
|
||||||
(isSelected && editorRef?.getSelection()
|
(isSelected && editorRef?.getSelection()
|
||||||
? editorRef
|
? editorRef
|
||||||
?.getModel()
|
?.getModel()
|
||||||
?.getValueInRange(editorRef?.getSelection()!)
|
?.getValueInRange(editorRef?.getSelection()!)
|
||||||
: editorRef?.getValue()) ?? "",
|
: editorRef?.getValue()) ?? "",
|
||||||
line: generate.line,
|
line: generate.line,
|
||||||
}}
|
}}
|
||||||
@ -963,58 +999,62 @@ export default function CodeEditor({
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : // Note clerk.loaded is required here due to a bug: https://github.com/clerk/javascript/issues/1643
|
) : // Note clerk.loaded is required here due to a bug: https://github.com/clerk/javascript/issues/1643
|
||||||
clerk.loaded ? (
|
clerk.loaded ? (
|
||||||
<>
|
<>
|
||||||
{provider && userInfo ? (
|
{provider && userInfo ? (
|
||||||
<Cursors yProvider={provider} userInfo={userInfo} />
|
<Cursors yProvider={provider} userInfo={userInfo} />
|
||||||
) : null}
|
) : null}
|
||||||
<Editor
|
<Editor
|
||||||
height="100%"
|
height="100%"
|
||||||
language={editorLanguage}
|
language={editorLanguage}
|
||||||
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 }
|
setTabs((prev) =>
|
||||||
: tab
|
prev.map((tab) =>
|
||||||
|
tab.id === activeFileId
|
||||||
|
? { ...tab, saved: false }
|
||||||
|
: tab
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
} else {
|
||||||
} else {
|
// If the content matches the cached content, mark the file as saved
|
||||||
setTabs((prev) =>
|
setTabs((prev) =>
|
||||||
prev.map((tab) =>
|
prev.map((tab) =>
|
||||||
tab.id === activeFileId
|
tab.id === activeFileId
|
||||||
? { ...tab, saved: false }
|
? { ...tab, saved: true }
|
||||||
: tab
|
: tab
|
||||||
|
)
|
||||||
)
|
)
|
||||||
)
|
}
|
||||||
}
|
}}
|
||||||
}}
|
options={{
|
||||||
options={{
|
tabSize: 2,
|
||||||
tabSize: 2,
|
minimap: {
|
||||||
minimap: {
|
enabled: false,
|
||||||
enabled: false,
|
},
|
||||||
},
|
padding: {
|
||||||
padding: {
|
bottom: 4,
|
||||||
bottom: 4,
|
top: 4,
|
||||||
top: 4,
|
},
|
||||||
},
|
scrollBeyondLastLine: false,
|
||||||
scrollBeyondLastLine: false,
|
fixedOverflowWidgets: true,
|
||||||
fixedOverflowWidgets: true,
|
fontFamily: "var(--font-geist-mono)",
|
||||||
fontFamily: "var(--font-geist-mono)",
|
}}
|
||||||
}}
|
theme="vs-dark"
|
||||||
theme="vs-dark"
|
value={activeFileContent}
|
||||||
value={activeFileContent}
|
/>
|
||||||
/>
|
</>
|
||||||
</>
|
) : (
|
||||||
) : (
|
<div className="w-full h-full flex items-center justify-center text-xl font-medium text-muted-foreground/50 select-none">
|
||||||
<div className="w-full h-full flex items-center justify-center text-xl font-medium text-muted-foreground/50 select-none">
|
<Loader2 className="animate-spin w-6 h-6 mr-3" />
|
||||||
<Loader2 className="animate-spin w-6 h-6 mr-3" />
|
Waiting for Clerk to load...
|
||||||
Waiting for Clerk to load...
|
</div>
|
||||||
</div>
|
)}
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</ResizablePanel>
|
</ResizablePanel>
|
||||||
<ResizableHandle />
|
<ResizableHandle />
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import React, { useEffect, useRef } from 'react';
|
||||||
import { Play, StopCircle } from "lucide-react";
|
import { Play, StopCircle } from "lucide-react";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { useTerminal } from "@/context/TerminalContext";
|
import { useTerminal } from "@/context/TerminalContext";
|
||||||
@ -16,53 +17,57 @@ export default function RunButtonModal({
|
|||||||
setIsRunning: (running: boolean) => void;
|
setIsRunning: (running: boolean) => void;
|
||||||
sandboxData: Sandbox;
|
sandboxData: Sandbox;
|
||||||
}) {
|
}) {
|
||||||
const { createNewTerminal, terminals, closeTerminal } = useTerminal();
|
const { createNewTerminal, closeTerminal, terminals } = useTerminal();
|
||||||
const { setIsPreviewCollapsed, previewPanelRef } = usePreview();
|
const { setIsPreviewCollapsed, previewPanelRef } = usePreview();
|
||||||
|
// Ref to keep track of the last created terminal's ID
|
||||||
|
const lastCreatedTerminalRef = useRef<string | null>(null);
|
||||||
|
|
||||||
const handleRun = () => {
|
// Effect to update the lastCreatedTerminalRef when a new terminal is added
|
||||||
if (isRunning) {
|
useEffect(() => {
|
||||||
console.log('Stopping sandbox...');
|
if (terminals.length > 0 && !isRunning) {
|
||||||
console.log('Closing Preview Window');
|
const latestTerminal = terminals[terminals.length - 1];
|
||||||
|
if (latestTerminal && latestTerminal.id !== lastCreatedTerminalRef.current) {
|
||||||
terminals.forEach(term => {
|
lastCreatedTerminalRef.current = latestTerminal.id;
|
||||||
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.");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
setIsRunning(!isRunning);
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<Button variant="outline" onClick={handleRun}>
|
||||||
<Button variant="outline" onClick={handleRun}>
|
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
|
||||||
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
|
{isRunning ? 'Stop' : 'Run'}
|
||||||
{isRunning ? 'Stop' : 'Run'}
|
</Button>
|
||||||
</Button>
|
|
||||||
</>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user