Compare commits
13 Commits
fix/max-sa
...
fix-editor
Author | SHA1 | Date | |
---|---|---|---|
44f803ffaf | |||
d9ce147e09 | |||
398139ec36 | |||
bd6284df8f | |||
c262fb2a31 | |||
ed709210e3 | |||
97c8598717 | |||
9ec59bc781 | |||
687416e6e9 | |||
006c5cea66 | |||
869ae6c148 | |||
7353e88567 | |||
a0fb905a04 |
@ -29,7 +29,9 @@ npm run dev
|
|||||||
|
|
||||||
### Backend
|
### Backend
|
||||||
|
|
||||||
The backend consists of a primary Express and Socket.io server, and 3 Cloudflare Workers microservices for the D1 database, R2 storage, and Workers AI. The D1 database also contains a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to the R2 storage worker.
|
The backend consists of a primary Express and Socket.io server, and 3 Cloudflare Workers microservices for the D1 database, R2 storage, and Workers AI. The D1 database also contains a [service binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/service-bindings/) to the R2 storage worker. Each open sandbox instantiates a secure Linux sandboxes on E2B, which is used for the terminal and live preview.
|
||||||
|
|
||||||
|
You will need to make an account on [E2B](https://e2b.dev/) to get an API key.
|
||||||
|
|
||||||
#### Socket.io server
|
#### Socket.io server
|
||||||
|
|
||||||
@ -181,3 +183,4 @@ It should be in the form `category(scope or module): message` in your commit mes
|
|||||||
- [Express](https://expressjs.com/)
|
- [Express](https://expressjs.com/)
|
||||||
- [Socket.io](https://socket.io/)
|
- [Socket.io](https://socket.io/)
|
||||||
- [Drizzle ORM](https://orm.drizzle.team/)
|
- [Drizzle ORM](https://orm.drizzle.team/)
|
||||||
|
- [E2B](https://e2b.dev/)
|
||||||
|
@ -110,8 +110,13 @@ export default {
|
|||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const { type, name, userId, visibility } = initSchema.parse(body)
|
const { type, name, userId, visibility } = initSchema.parse(body)
|
||||||
|
|
||||||
const allSandboxes = await db.select().from(sandbox).all()
|
const userSandboxes = await db
|
||||||
if (allSandboxes.length >= 8) {
|
.select()
|
||||||
|
.from(sandbox)
|
||||||
|
.where(eq(sandbox.userId, userId))
|
||||||
|
.all()
|
||||||
|
|
||||||
|
if (userSandboxes.length >= 8) {
|
||||||
return new Response("You reached the maximum # of sandboxes.", {
|
return new Response("You reached the maximum # of sandboxes.", {
|
||||||
status: 400,
|
status: 400,
|
||||||
})
|
})
|
||||||
|
@ -5,3 +5,4 @@ PORT=4000
|
|||||||
WORKERS_KEY=
|
WORKERS_KEY=
|
||||||
DATABASE_WORKER_URL=
|
DATABASE_WORKER_URL=
|
||||||
STORAGE_WORKER_URL=
|
STORAGE_WORKER_URL=
|
||||||
|
E2B_API_KEY=
|
@ -1,4 +1,3 @@
|
|||||||
import fs from "fs";
|
|
||||||
import os from "os";
|
import os from "os";
|
||||||
import path from "path";
|
import path from "path";
|
||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
@ -19,7 +18,7 @@ import {
|
|||||||
saveFile,
|
saveFile,
|
||||||
} from "./fileoperations";
|
} from "./fileoperations";
|
||||||
import { LockManager } from "./utils";
|
import { LockManager } from "./utils";
|
||||||
import { Sandbox, Terminal } from "e2b";
|
import { Sandbox, Terminal, FilesystemManager } from "e2b";
|
||||||
import {
|
import {
|
||||||
MAX_BODY_SIZE,
|
MAX_BODY_SIZE,
|
||||||
createFileRL,
|
createFileRL,
|
||||||
@ -45,9 +44,20 @@ let inactivityTimeout: NodeJS.Timeout | null = null;
|
|||||||
let isOwnerConnected = false;
|
let isOwnerConnected = false;
|
||||||
|
|
||||||
const containers: Record<string, Sandbox> = {};
|
const containers: Record<string, Sandbox> = {};
|
||||||
|
const connections: Record<string, number> = {};
|
||||||
const terminals: Record<string, Terminal> = {};
|
const terminals: Record<string, Terminal> = {};
|
||||||
|
|
||||||
const dirName = path.join(__dirname, "..");
|
const dirName = "/home/user";
|
||||||
|
|
||||||
|
const moveFile = async (
|
||||||
|
filesystem: FilesystemManager,
|
||||||
|
filePath: string,
|
||||||
|
newFilePath: string
|
||||||
|
) => {
|
||||||
|
const fileContents = await filesystem.readBytes(filePath);
|
||||||
|
await filesystem.writeBytes(newFilePath, fileContents);
|
||||||
|
await filesystem.remove(filePath);
|
||||||
|
};
|
||||||
|
|
||||||
io.use(async (socket, next) => {
|
io.use(async (socket, next) => {
|
||||||
const handshakeSchema = z.object({
|
const handshakeSchema = z.object({
|
||||||
@ -103,376 +113,487 @@ io.use(async (socket, next) => {
|
|||||||
const lockManager = new LockManager();
|
const lockManager = new LockManager();
|
||||||
|
|
||||||
io.on("connection", async (socket) => {
|
io.on("connection", async (socket) => {
|
||||||
if (inactivityTimeout) clearTimeout(inactivityTimeout);
|
try {
|
||||||
|
if (inactivityTimeout) clearTimeout(inactivityTimeout);
|
||||||
|
|
||||||
const data = socket.data as {
|
const data = socket.data as {
|
||||||
userId: string;
|
userId: string;
|
||||||
sandboxId: string;
|
sandboxId: string;
|
||||||
isOwner: boolean;
|
isOwner: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (data.isOwner) {
|
if (data.isOwner) {
|
||||||
isOwnerConnected = true;
|
isOwnerConnected = true;
|
||||||
} else {
|
connections[data.sandboxId] = (connections[data.sandboxId] ?? 0) + 1;
|
||||||
if (!isOwnerConnected) {
|
} else {
|
||||||
socket.emit("disableAccess", "The sandbox owner is not connected.");
|
if (!isOwnerConnected) {
|
||||||
return;
|
socket.emit("disableAccess", "The sandbox owner is not connected.");
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
|
||||||
try {
|
|
||||||
if (!containers[data.sandboxId]) {
|
|
||||||
containers[data.sandboxId] = await Sandbox.create();
|
|
||||||
console.log("Created container ", data.sandboxId);
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error("Error creating container ", data.sandboxId, error);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
sandboxFiles.fileData.forEach((file) => {
|
|
||||||
const filePath = path.join(dirName, file.id);
|
|
||||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
||||||
fs.writeFile(filePath, file.data, function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.emit("loaded", sandboxFiles.files);
|
|
||||||
|
|
||||||
socket.on("getFile", (fileId: string, callback) => {
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
callback(file.data);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("getFolder", async (folderId: string, callback) => {
|
|
||||||
const files = await getFolder(folderId);
|
|
||||||
callback(files);
|
|
||||||
});
|
|
||||||
|
|
||||||
// todo: send diffs + debounce for efficiency
|
|
||||||
socket.on("saveFile", async (fileId: string, body: string) => {
|
|
||||||
try {
|
|
||||||
await saveFileRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
|
||||||
socket.emit(
|
|
||||||
"rateLimit",
|
|
||||||
"Rate limited: file size too large. Please reduce the file size."
|
|
||||||
);
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
file.data = body;
|
|
||||||
|
|
||||||
fs.writeFile(path.join(dirName, file.id), body, function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
await saveFile(fileId, body);
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file saving. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("moveFile", async (fileId: string, folderId: string, callback) => {
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
const parts = fileId.split("/");
|
|
||||||
const newFileId = folderId + "/" + parts.pop();
|
|
||||||
|
|
||||||
fs.rename(
|
|
||||||
path.join(dirName, fileId),
|
|
||||||
path.join(dirName, newFileId),
|
|
||||||
function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
file.id = newFileId;
|
|
||||||
|
|
||||||
await renameFile(fileId, newFileId, file.data);
|
|
||||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
|
|
||||||
callback(newFiles.files);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("createFile", async (name: string, callback) => {
|
|
||||||
try {
|
|
||||||
const size: number = await getProjectSize(data.sandboxId);
|
|
||||||
// limit is 200mb
|
|
||||||
if (size > 200 * 1024 * 1024) {
|
|
||||||
io.emit(
|
|
||||||
"rateLimit",
|
|
||||||
"Rate limited: project size exceeded. Please delete some files."
|
|
||||||
);
|
|
||||||
callback({ success: false });
|
|
||||||
}
|
|
||||||
|
|
||||||
await createFileRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
const id = `projects/${data.sandboxId}/${name}`;
|
|
||||||
|
|
||||||
fs.writeFile(path.join(dirName, id), "", function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
sandboxFiles.files.push({
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
type: "file",
|
|
||||||
});
|
|
||||||
|
|
||||||
sandboxFiles.fileData.push({
|
|
||||||
id,
|
|
||||||
data: "",
|
|
||||||
});
|
|
||||||
|
|
||||||
await createFile(id);
|
|
||||||
|
|
||||||
callback({ success: true });
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file creation. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("createFolder", async (name: string, callback) => {
|
|
||||||
try {
|
|
||||||
await createFolderRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
const id = `projects/${data.sandboxId}/${name}`;
|
|
||||||
|
|
||||||
fs.mkdir(path.join(dirName, id), { recursive: true }, function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
callback();
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: folder creation. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("renameFile", async (fileId: string, newName: string) => {
|
|
||||||
try {
|
|
||||||
await renameFileRL.consume(data.userId, 1);
|
|
||||||
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
file.id = newName;
|
|
||||||
|
|
||||||
const parts = fileId.split("/");
|
|
||||||
const newFileId =
|
|
||||||
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
|
|
||||||
|
|
||||||
fs.rename(
|
|
||||||
path.join(dirName, fileId),
|
|
||||||
path.join(dirName, newFileId),
|
|
||||||
function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
}
|
|
||||||
);
|
|
||||||
await renameFile(fileId, newFileId, file.data);
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file renaming. Please slow down.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("deleteFile", async (fileId: string, callback) => {
|
|
||||||
try {
|
|
||||||
await deleteFileRL.consume(data.userId, 1);
|
|
||||||
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
fs.unlink(path.join(dirName, fileId), function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
|
||||||
(f) => f.id !== fileId
|
|
||||||
);
|
|
||||||
|
|
||||||
await deleteFile(fileId);
|
|
||||||
|
|
||||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
callback(newFiles.files);
|
|
||||||
} catch (e) {
|
|
||||||
io.emit("rateLimit", "Rate limited: file deletion. Please slow down.");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// todo
|
|
||||||
// socket.on("renameFolder", async (folderId: string, newName: string) => {
|
|
||||||
// });
|
|
||||||
|
|
||||||
socket.on("deleteFolder", async (folderId: string, callback) => {
|
|
||||||
const files = await getFolder(folderId);
|
|
||||||
|
|
||||||
await Promise.all(
|
|
||||||
files.map(async (file) => {
|
|
||||||
fs.unlink(path.join(dirName, file), function (err) {
|
|
||||||
if (err) throw err;
|
|
||||||
});
|
|
||||||
|
|
||||||
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
|
||||||
(f) => f.id !== file
|
|
||||||
);
|
|
||||||
|
|
||||||
await deleteFile(file);
|
|
||||||
})
|
|
||||||
);
|
|
||||||
|
|
||||||
const newFiles = await getSandboxFiles(data.sandboxId);
|
|
||||||
|
|
||||||
callback(newFiles.files);
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("createTerminal", async (id: string, callback) => {
|
|
||||||
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
try {
|
try {
|
||||||
terminals[id] = await containers[data.sandboxId].terminal.start({
|
if (!containers[data.sandboxId]) {
|
||||||
onData: (data: string) => {
|
containers[data.sandboxId] = await Sandbox.create();
|
||||||
io.emit("terminalResponse", { id, data });
|
console.log("Created container ", data.sandboxId);
|
||||||
},
|
io.emit(
|
||||||
size: { cols: 80, rows: 20 },
|
"previewURL",
|
||||||
onExit: () => console.log("Terminal exited", id),
|
"https://" + containers[data.sandboxId].getHostname(5173)
|
||||||
});
|
);
|
||||||
await terminals[id].sendData("export PS1='user> '\rclear\r");
|
}
|
||||||
console.log("Created terminal", id);
|
} catch (e: any) {
|
||||||
} catch (error) {
|
console.error(`Error creating container ${data.sandboxId}:`, e);
|
||||||
console.error("Error creating terminal ", id, error);
|
io.emit("error", `Error: container creation. ${e.message ?? e}`);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
callback();
|
// Change the owner of the project directory to user
|
||||||
});
|
const fixPermissions = async () => {
|
||||||
|
await containers[data.sandboxId].process.startAndWait(
|
||||||
|
`sudo chown -R user "${path.join(dirName, "projects", data.sandboxId)}"`
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
socket.on("resizeTerminal", (dimensions: { cols: number; rows: number }) => {
|
const sandboxFiles = await getSandboxFiles(data.sandboxId);
|
||||||
Object.values(terminals).forEach((t) => {
|
sandboxFiles.fileData.forEach(async (file) => {
|
||||||
t.resize(dimensions);
|
const filePath = path.join(dirName, file.id);
|
||||||
|
await containers[data.sandboxId].filesystem.makeDir(
|
||||||
|
path.dirname(filePath)
|
||||||
|
);
|
||||||
|
await containers[data.sandboxId].filesystem.write(filePath, file.data);
|
||||||
});
|
});
|
||||||
});
|
fixPermissions();
|
||||||
|
|
||||||
socket.on("terminalData", (id: string, data: string) => {
|
socket.emit("loaded", sandboxFiles.files);
|
||||||
if (!terminals[id]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
socket.on("getFile", (fileId: string, callback) => {
|
||||||
terminals[id].sendData(data);
|
console.log(fileId);
|
||||||
} catch (e) {
|
try {
|
||||||
console.log("Error writing to terminal", e);
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
}
|
if (!file) return;
|
||||||
});
|
|
||||||
|
|
||||||
socket.on("closeTerminal", async (id: string, callback) => {
|
callback(file.data);
|
||||||
if (!terminals[id]) {
|
} catch (e: any) {
|
||||||
return;
|
console.error("Error getting file:", e);
|
||||||
}
|
io.emit("error", `Error: get file. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
await terminals[id].kill();
|
socket.on("getFolder", async (folderId: string, callback) => {
|
||||||
delete terminals[id];
|
try {
|
||||||
|
const files = await getFolder(folderId);
|
||||||
|
callback(files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error getting folder:", e);
|
||||||
|
io.emit("error", `Error: get folder. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
callback();
|
// todo: send diffs + debounce for efficiency
|
||||||
});
|
socket.on("saveFile", async (fileId: string, body: string) => {
|
||||||
|
try {
|
||||||
socket.on(
|
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
||||||
"generateCode",
|
socket.emit(
|
||||||
async (
|
"error",
|
||||||
fileName: string,
|
"Error: file size too large. Please reduce the file size."
|
||||||
code: string,
|
);
|
||||||
line: number,
|
return;
|
||||||
instructions: string,
|
|
||||||
callback
|
|
||||||
) => {
|
|
||||||
const fetchPromise = fetch(
|
|
||||||
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
|
|
||||||
{
|
|
||||||
method: "POST",
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `${process.env.WORKERS_KEY}`,
|
|
||||||
},
|
|
||||||
body: JSON.stringify({
|
|
||||||
userId: data.userId,
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
);
|
|
||||||
|
|
||||||
// Generate code from cloudflare workers AI
|
|
||||||
const generateCodePromise = fetch(
|
|
||||||
`${process.env.AI_WORKER_URL}/api?fileName=${fileName}&code=${code}&line=${line}&instructions=${instructions}`,
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "application/json",
|
|
||||||
Authorization: `${process.env.CF_AI_KEY}`,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const [fetchResponse, generateCodeResponse] = await Promise.all([
|
|
||||||
fetchPromise,
|
|
||||||
generateCodePromise,
|
|
||||||
]);
|
|
||||||
|
|
||||||
const json = await generateCodeResponse.json();
|
|
||||||
|
|
||||||
callback({ response: json.response, success: true });
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
socket.on("disconnect", async () => {
|
|
||||||
if (data.isOwner) {
|
|
||||||
Object.entries(terminals).forEach((t) => {
|
|
||||||
const terminal = t[1];
|
|
||||||
terminal.kill();
|
|
||||||
delete terminals[t[0]];
|
|
||||||
});
|
|
||||||
|
|
||||||
await lockManager.acquireLock(data.sandboxId, async () => {
|
|
||||||
try {
|
try {
|
||||||
if (containers[data.sandboxId]) {
|
await saveFileRL.consume(data.userId, 1);
|
||||||
await containers[data.sandboxId].close();
|
await saveFile(fileId, body);
|
||||||
delete containers[data.sandboxId];
|
} catch (e) {
|
||||||
console.log("Closed container", data.sandboxId);
|
io.emit("error", "Rate limited: file saving. Please slow down.");
|
||||||
}
|
return;
|
||||||
} catch (error) {
|
|
||||||
console.error("Error closing container ", data.sandboxId, error);
|
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
socket.broadcast.emit(
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
"disableAccess",
|
if (!file) return;
|
||||||
"The sandbox owner has disconnected."
|
file.data = body;
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// const sockets = await io.fetchSockets();
|
await containers[data.sandboxId].filesystem.write(
|
||||||
// if (inactivityTimeout) {
|
path.join(dirName, file.id),
|
||||||
// clearTimeout(inactivityTimeout);
|
body
|
||||||
// }
|
);
|
||||||
// if (sockets.length === 0) {
|
fixPermissions();
|
||||||
// console.log("STARTING TIMER");
|
} catch (e: any) {
|
||||||
// inactivityTimeout = setTimeout(() => {
|
console.error("Error saving file:", e);
|
||||||
// io.fetchSockets().then(async (sockets) => {
|
io.emit("error", `Error: file saving. ${e.message ?? e}`);
|
||||||
// if (sockets.length === 0) {
|
}
|
||||||
// console.log("Server stopped", res);
|
});
|
||||||
// }
|
|
||||||
// });
|
socket.on(
|
||||||
// }, 20000);
|
"moveFile",
|
||||||
// } else {
|
async (fileId: string, folderId: string, callback) => {
|
||||||
// console.log("number of sockets", sockets.length);
|
try {
|
||||||
// }
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
});
|
if (!file) return;
|
||||||
|
|
||||||
|
const parts = fileId.split("/");
|
||||||
|
const newFileId = folderId + "/" + parts.pop();
|
||||||
|
|
||||||
|
await moveFile(
|
||||||
|
containers[data.sandboxId].filesystem,
|
||||||
|
path.join(dirName, fileId),
|
||||||
|
path.join(dirName, newFileId)
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
|
||||||
|
file.id = newFileId;
|
||||||
|
|
||||||
|
await renameFile(fileId, newFileId, file.data);
|
||||||
|
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
callback(newFiles.files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error moving file:", e);
|
||||||
|
io.emit("error", `Error: file moving. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("createFile", async (name: string, callback) => {
|
||||||
|
try {
|
||||||
|
const size: number = await getProjectSize(data.sandboxId);
|
||||||
|
// limit is 200mb
|
||||||
|
if (size > 200 * 1024 * 1024) {
|
||||||
|
io.emit(
|
||||||
|
"error",
|
||||||
|
"Rate limited: project size exceeded. Please delete some files."
|
||||||
|
);
|
||||||
|
callback({ success: false });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await createFileRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file creation. Please slow down.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `projects/${data.sandboxId}/${name}`;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.write(
|
||||||
|
path.join(dirName, id),
|
||||||
|
""
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
|
||||||
|
sandboxFiles.files.push({
|
||||||
|
id,
|
||||||
|
name,
|
||||||
|
type: "file",
|
||||||
|
});
|
||||||
|
|
||||||
|
sandboxFiles.fileData.push({
|
||||||
|
id,
|
||||||
|
data: "",
|
||||||
|
});
|
||||||
|
|
||||||
|
await createFile(id);
|
||||||
|
|
||||||
|
callback({ success: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error creating file:", e);
|
||||||
|
io.emit("error", `Error: file creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("createFolder", async (name: string, callback) => {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
await createFolderRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: folder creation. Please slow down.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = `projects/${data.sandboxId}/${name}`;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.makeDir(
|
||||||
|
path.join(dirName, id)
|
||||||
|
);
|
||||||
|
|
||||||
|
callback();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error creating folder:", e);
|
||||||
|
io.emit("error", `Error: folder creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("renameFile", async (fileId: string, newName: string) => {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
await renameFileRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file renaming. Please slow down.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
file.id = newName;
|
||||||
|
|
||||||
|
const parts = fileId.split("/");
|
||||||
|
const newFileId =
|
||||||
|
parts.slice(0, parts.length - 1).join("/") + "/" + newName;
|
||||||
|
|
||||||
|
await moveFile(
|
||||||
|
containers[data.sandboxId].filesystem,
|
||||||
|
path.join(dirName, fileId),
|
||||||
|
path.join(dirName, newFileId)
|
||||||
|
);
|
||||||
|
fixPermissions();
|
||||||
|
await renameFile(fileId, newFileId, file.data);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error renaming folder:", e);
|
||||||
|
io.emit("error", `Error: folder renaming. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("deleteFile", async (fileId: string, callback) => {
|
||||||
|
try {
|
||||||
|
try {
|
||||||
|
await deleteFileRL.consume(data.userId, 1);
|
||||||
|
} catch (e) {
|
||||||
|
io.emit("error", "Rate limited: file deletion. Please slow down.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const file = sandboxFiles.fileData.find((f) => f.id === fileId);
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
await containers[data.sandboxId].filesystem.remove(
|
||||||
|
path.join(dirName, fileId)
|
||||||
|
);
|
||||||
|
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||||
|
(f) => f.id !== fileId
|
||||||
|
);
|
||||||
|
|
||||||
|
await deleteFile(fileId);
|
||||||
|
|
||||||
|
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
callback(newFiles.files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error deleting file:", e);
|
||||||
|
io.emit("error", `Error: file deletion. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// todo
|
||||||
|
// socket.on("renameFolder", async (folderId: string, newName: string) => {
|
||||||
|
// });
|
||||||
|
|
||||||
|
socket.on("deleteFolder", async (folderId: string, callback) => {
|
||||||
|
try {
|
||||||
|
const files = await getFolder(folderId);
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
files.map(async (file) => {
|
||||||
|
await containers[data.sandboxId].filesystem.remove(
|
||||||
|
path.join(dirName, file)
|
||||||
|
);
|
||||||
|
|
||||||
|
sandboxFiles.fileData = sandboxFiles.fileData.filter(
|
||||||
|
(f) => f.id !== file
|
||||||
|
);
|
||||||
|
|
||||||
|
await deleteFile(file);
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
const newFiles = await getSandboxFiles(data.sandboxId);
|
||||||
|
|
||||||
|
callback(newFiles.files);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error deleting folder:", e);
|
||||||
|
io.emit("error", `Error: folder deletion. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("createTerminal", async (id: string, callback) => {
|
||||||
|
try {
|
||||||
|
if (terminals[id] || Object.keys(terminals).length >= 4) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
|
try {
|
||||||
|
terminals[id] = await containers[data.sandboxId].terminal.start({
|
||||||
|
onData: (data: string) => {
|
||||||
|
io.emit("terminalResponse", { id, data });
|
||||||
|
},
|
||||||
|
size: { cols: 80, rows: 20 },
|
||||||
|
onExit: () => console.log("Terminal exited", id),
|
||||||
|
});
|
||||||
|
await terminals[id].sendData(
|
||||||
|
`cd "${path.join(dirName, "projects", data.sandboxId)}"\r`
|
||||||
|
);
|
||||||
|
await terminals[id].sendData("export PS1='user> '\rclear\r");
|
||||||
|
console.log("Created terminal", id);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(`Error creating terminal ${id}:`, e);
|
||||||
|
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
callback();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error(`Error creating terminal ${id}:`, e);
|
||||||
|
io.emit("error", `Error: terminal creation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on(
|
||||||
|
"resizeTerminal",
|
||||||
|
(dimensions: { cols: number; rows: number }) => {
|
||||||
|
try {
|
||||||
|
Object.values(terminals).forEach((t) => {
|
||||||
|
t.resize(dimensions);
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error resizing terminal:", e);
|
||||||
|
io.emit("error", `Error: terminal resizing. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("terminalData", (id: string, data: string) => {
|
||||||
|
try {
|
||||||
|
if (!terminals[id]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
terminals[id].sendData(data);
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error writing to terminal:", e);
|
||||||
|
io.emit("error", `Error: writing to terminal. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on("closeTerminal", async (id: string, callback) => {
|
||||||
|
try {
|
||||||
|
if (!terminals[id]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
await terminals[id].kill();
|
||||||
|
delete terminals[id];
|
||||||
|
|
||||||
|
callback();
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error closing terminal:", e);
|
||||||
|
io.emit("error", `Error: closing terminal. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.on(
|
||||||
|
"generateCode",
|
||||||
|
async (
|
||||||
|
fileName: string,
|
||||||
|
code: string,
|
||||||
|
line: number,
|
||||||
|
instructions: string,
|
||||||
|
callback
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
const fetchPromise = fetch(
|
||||||
|
`${process.env.DATABASE_WORKER_URL}/api/sandbox/generate`,
|
||||||
|
{
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `${process.env.WORKERS_KEY}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
userId: data.userId,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// Generate code from cloudflare workers AI
|
||||||
|
const generateCodePromise = fetch(
|
||||||
|
`${process.env.AI_WORKER_URL}/api?fileName=${fileName}&code=${code}&line=${line}&instructions=${instructions}`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
Authorization: `${process.env.CF_AI_KEY}`,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
const [fetchResponse, generateCodeResponse] = await Promise.all([
|
||||||
|
fetchPromise,
|
||||||
|
generateCodePromise,
|
||||||
|
]);
|
||||||
|
|
||||||
|
const json = await generateCodeResponse.json();
|
||||||
|
|
||||||
|
callback({ response: json.response, success: true });
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error generating code:", e);
|
||||||
|
io.emit("error", `Error: code generation. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
socket.on("disconnect", async () => {
|
||||||
|
try {
|
||||||
|
if (data.isOwner) {
|
||||||
|
connections[data.sandboxId]--;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.isOwner && connections[data.sandboxId] <= 0) {
|
||||||
|
await Promise.all(
|
||||||
|
Object.entries(terminals).map(async ([key, terminal]) => {
|
||||||
|
await terminal.kill();
|
||||||
|
delete terminals[key];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
await lockManager.acquireLock(data.sandboxId, async () => {
|
||||||
|
try {
|
||||||
|
if (containers[data.sandboxId]) {
|
||||||
|
await containers[data.sandboxId].close();
|
||||||
|
delete containers[data.sandboxId];
|
||||||
|
console.log("Closed container", data.sandboxId);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error closing container ", data.sandboxId, error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
socket.broadcast.emit(
|
||||||
|
"disableAccess",
|
||||||
|
"The sandbox owner has disconnected."
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// const sockets = await io.fetchSockets();
|
||||||
|
// if (inactivityTimeout) {
|
||||||
|
// clearTimeout(inactivityTimeout);
|
||||||
|
// }
|
||||||
|
// if (sockets.length === 0) {
|
||||||
|
// console.log("STARTING TIMER");
|
||||||
|
// inactivityTimeout = setTimeout(() => {
|
||||||
|
// io.fetchSockets().then(async (sockets) => {
|
||||||
|
// if (sockets.length === 0) {
|
||||||
|
// console.log("Server stopped", res);
|
||||||
|
// }
|
||||||
|
// });
|
||||||
|
// }, 20000);
|
||||||
|
// } else {
|
||||||
|
// console.log("number of sockets", sockets.length);
|
||||||
|
// }
|
||||||
|
} catch (e: any) {
|
||||||
|
console.log("Error disconnecting:", e);
|
||||||
|
io.emit("error", `Error: disconnecting. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e: any) {
|
||||||
|
console.error("Error connecting:", e);
|
||||||
|
io.emit("error", `Error: connection. ${e.message ?? e}`);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
httpServer.listen(port, () => {
|
httpServer.listen(port, () => {
|
||||||
|
@ -6,6 +6,7 @@ import { ThemeProvider } from "@/components/layout/themeProvider"
|
|||||||
import { ClerkProvider } from "@clerk/nextjs"
|
import { ClerkProvider } from "@clerk/nextjs"
|
||||||
import { Toaster } from "@/components/ui/sonner"
|
import { Toaster } from "@/components/ui/sonner"
|
||||||
import { Analytics } from "@vercel/analytics/react"
|
import { Analytics } from "@vercel/analytics/react"
|
||||||
|
import { TerminalProvider } from '@/context/TerminalContext';
|
||||||
|
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "Sandbox",
|
title: "Sandbox",
|
||||||
@ -27,7 +28,9 @@ export default function RootLayout({
|
|||||||
forcedTheme="dark"
|
forcedTheme="dark"
|
||||||
disableTransitionOnChange
|
disableTransitionOnChange
|
||||||
>
|
>
|
||||||
|
<TerminalProvider>
|
||||||
{children}
|
{children}
|
||||||
|
</TerminalProvider>
|
||||||
<Analytics />
|
<Analytics />
|
||||||
<Toaster position="bottom-left" richColors />
|
<Toaster position="bottom-left" richColors />
|
||||||
</ThemeProvider>
|
</ThemeProvider>
|
||||||
|
@ -3,7 +3,7 @@
|
|||||||
import { SetStateAction, useCallback, useEffect, useRef, useState } from "react"
|
import { SetStateAction, useCallback, useEffect, useRef, useState } from "react"
|
||||||
import monaco from "monaco-editor"
|
import monaco from "monaco-editor"
|
||||||
import Editor, { BeforeMount, OnMount } from "@monaco-editor/react"
|
import Editor, { BeforeMount, OnMount } from "@monaco-editor/react"
|
||||||
import { io } from "socket.io-client"
|
import { Socket, io } from "socket.io-client"
|
||||||
import { toast } from "sonner"
|
import { toast } from "sonner"
|
||||||
import { useClerk } from "@clerk/nextjs"
|
import { useClerk } from "@clerk/nextjs"
|
||||||
|
|
||||||
@ -41,12 +41,16 @@ export default function CodeEditor({
|
|||||||
sandboxData: Sandbox
|
sandboxData: Sandbox
|
||||||
reactDefinitionFile: string
|
reactDefinitionFile: string
|
||||||
}) {
|
}) {
|
||||||
const socket = io(
|
const socketRef = useRef<Socket | null>(null);
|
||||||
`http://localhost:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
|
||||||
{
|
// Initialize socket connection if it doesn't exist
|
||||||
timeout: 2000,
|
if (!socketRef.current) {
|
||||||
}
|
socketRef.current = io(
|
||||||
)
|
`${window.location.protocol}//${window.location.hostname}:${process.env.NEXT_PUBLIC_SERVER_PORT}?userId=${userData.id}&sandboxId=${sandboxData.id}`,
|
||||||
|
{
|
||||||
|
timeout: 2000,
|
||||||
|
}
|
||||||
|
);}
|
||||||
|
|
||||||
const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true)
|
const [isPreviewCollapsed, setIsPreviewCollapsed] = useState(true)
|
||||||
const [disableAccess, setDisableAccess] = useState({
|
const [disableAccess, setDisableAccess] = useState({
|
||||||
@ -90,6 +94,9 @@ export default function CodeEditor({
|
|||||||
}[]
|
}[]
|
||||||
>([])
|
>([])
|
||||||
|
|
||||||
|
// Preview state
|
||||||
|
const [previewURL, setPreviewURL] = useState<string>("");
|
||||||
|
|
||||||
const isOwner = sandboxData.userId === userData.id
|
const isOwner = sandboxData.userId === userData.id
|
||||||
const clerk = useClerk()
|
const clerk = useClerk()
|
||||||
|
|
||||||
@ -298,9 +305,10 @@ export default function CodeEditor({
|
|||||||
)
|
)
|
||||||
);
|
);
|
||||||
console.log(`Saving file...${activeFileId}`);
|
console.log(`Saving file...${activeFileId}`);
|
||||||
socket.emit("saveFile", activeFileId, value);
|
console.log(`Saving file...${value}`);
|
||||||
|
socketRef.current?.emit("saveFile", activeFileId, value);
|
||||||
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY)||1000),
|
}, Number(process.env.FILE_SAVE_DEBOUNCE_DELAY)||1000),
|
||||||
[socket]
|
[socketRef]
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@ -317,57 +325,97 @@ export default function CodeEditor({
|
|||||||
};
|
};
|
||||||
}, [activeFileId, tabs, debouncedSaveData]);
|
}, [activeFileId, tabs, debouncedSaveData]);
|
||||||
|
|
||||||
// Liveblocks live collaboration setup effect
|
// Liveblocks live collaboration setup effect
|
||||||
|
|
||||||
|
type ProviderData = {
|
||||||
|
provider: LiveblocksProvider<never, never, never, never>;
|
||||||
|
yDoc: Y.Doc;
|
||||||
|
yText: Y.Text;
|
||||||
|
binding?: MonacoBinding;
|
||||||
|
onSync: (isSynced: boolean) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const providersMap = useRef(new Map<string, ProviderData>());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const tab = tabs.find((t) => t.id === activeFileId)
|
const tab = tabs.find((t) => t.id === activeFileId);
|
||||||
const model = editorRef?.getModel()
|
const model = editorRef?.getModel();
|
||||||
|
|
||||||
if (!editorRef || !tab || !model) return
|
if (!editorRef || !tab || !model) return;
|
||||||
|
|
||||||
const yDoc = new Y.Doc()
|
let providerData: ProviderData;
|
||||||
const yText = yDoc.getText(tab.id)
|
|
||||||
const yProvider: any = new LiveblocksProvider(room, yDoc)
|
|
||||||
|
|
||||||
const onSync = (isSynced: boolean) => {
|
if (!providersMap.current.has(tab.id)) {
|
||||||
if (isSynced) {
|
const yDoc = new Y.Doc();
|
||||||
const text = yText.toString()
|
const yText = yDoc.getText(tab.id);
|
||||||
if (text === "") {
|
const yProvider = new LiveblocksProvider(room, yDoc);
|
||||||
if (activeFileContent) {
|
|
||||||
yText.insert(0, activeFileContent)
|
const onSync = (isSynced: boolean) => {
|
||||||
} else {
|
if (isSynced) {
|
||||||
setTimeout(() => {
|
const text = yText.toString()
|
||||||
yText.insert(0, editorRef.getValue())
|
if (text === "") {
|
||||||
}, 0)
|
if (activeFileContent) {
|
||||||
|
yText.insert(0, activeFileContent)
|
||||||
|
} else {
|
||||||
|
setTimeout(() => {
|
||||||
|
yText.insert(0, editorRef.getValue())
|
||||||
|
}, 0)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
yProvider.on("sync", onSync);
|
||||||
|
|
||||||
|
providerData = { provider: yProvider, yDoc, yText, onSync };
|
||||||
|
providersMap.current.set(tab.id, providerData);
|
||||||
|
} else {
|
||||||
|
providerData = providersMap.current.get(tab.id)!;
|
||||||
}
|
}
|
||||||
|
|
||||||
yProvider.on("sync", onSync)
|
|
||||||
|
|
||||||
setProvider(yProvider)
|
|
||||||
|
|
||||||
const binding = new MonacoBinding(
|
const binding = new MonacoBinding(
|
||||||
yText,
|
providerData.yText,
|
||||||
model,
|
model,
|
||||||
new Set([editorRef]),
|
new Set([editorRef]),
|
||||||
yProvider.awareness as Awareness
|
providerData.provider.awareness as unknown as Awareness
|
||||||
)
|
);
|
||||||
|
|
||||||
|
providerData.binding = binding;
|
||||||
|
|
||||||
|
setProvider(providerData.provider);
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
yDoc.destroy()
|
// Cleanup logic
|
||||||
yProvider.destroy()
|
if (binding) {
|
||||||
binding.destroy()
|
binding.destroy();
|
||||||
yProvider.off("sync", onSync)
|
}
|
||||||
}
|
if (providerData.binding) {
|
||||||
}, [editorRef, room, activeFileContent])
|
providerData.binding = undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, [editorRef, room, activeFileContent, activeFileId, tabs]);
|
||||||
|
|
||||||
|
// Added this effect to clean up when the component unmounts
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
// Clean up all providers when the component unmounts
|
||||||
|
providersMap.current.forEach((data) => {
|
||||||
|
if (data.binding) {
|
||||||
|
data.binding.destroy();
|
||||||
|
}
|
||||||
|
data.provider.disconnect();
|
||||||
|
data.yDoc.destroy();
|
||||||
|
});
|
||||||
|
providersMap.current.clear();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
// Connection/disconnection effect
|
// Connection/disconnection effect
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
socket.connect()
|
socketRef.current?.connect()
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
socket.disconnect()
|
socketRef.current?.disconnect()
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
@ -383,7 +431,7 @@ export default function CodeEditor({
|
|||||||
setFiles(files)
|
setFiles(files)
|
||||||
}
|
}
|
||||||
|
|
||||||
const onRateLimit = (message: string) => {
|
const onError = (message: string) => {
|
||||||
toast.error(message)
|
toast.error(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -402,20 +450,22 @@ export default function CodeEditor({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.on("connect", onConnect)
|
socketRef.current?.on("connect", onConnect)
|
||||||
socket.on("disconnect", onDisconnect)
|
socketRef.current?.on("disconnect", onDisconnect)
|
||||||
socket.on("loaded", onLoadedEvent)
|
socketRef.current?.on("loaded", onLoadedEvent)
|
||||||
socket.on("rateLimit", onRateLimit)
|
socketRef.current?.on("error", onError)
|
||||||
socket.on("terminalResponse", onTerminalResponse)
|
socketRef.current?.on("terminalResponse", onTerminalResponse)
|
||||||
socket.on("disableAccess", onDisableAccess)
|
socketRef.current?.on("disableAccess", onDisableAccess)
|
||||||
|
socketRef.current?.on("previewURL", setPreviewURL)
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
socket.off("connect", onConnect)
|
socketRef.current?.off("connect", onConnect)
|
||||||
socket.off("disconnect", onDisconnect)
|
socketRef.current?.off("disconnect", onDisconnect)
|
||||||
socket.off("loaded", onLoadedEvent)
|
socketRef.current?.off("loaded", onLoadedEvent)
|
||||||
socket.off("rateLimit", onRateLimit)
|
socketRef.current?.off("error", onError)
|
||||||
socket.off("terminalResponse", onTerminalResponse)
|
socketRef.current?.off("terminalResponse", onTerminalResponse)
|
||||||
socket.off("disableAccess", onDisableAccess)
|
socketRef.current?.off("disableAccess", onDisableAccess)
|
||||||
|
socketRef.current?.off("previewURL", setPreviewURL)
|
||||||
}
|
}
|
||||||
// }, []);
|
// }, []);
|
||||||
}, [terminals])
|
}, [terminals])
|
||||||
@ -430,7 +480,7 @@ export default function CodeEditor({
|
|||||||
// Debounced function to get file content
|
// Debounced function to get file content
|
||||||
const debouncedGetFile = useCallback(
|
const debouncedGetFile = useCallback(
|
||||||
debounce((tabId, callback) => {
|
debounce((tabId, callback) => {
|
||||||
socket.emit('getFile', tabId, callback);
|
socketRef.current?.emit('getFile', tabId, callback);
|
||||||
}, 300), // 300ms debounce delay, adjust as needed
|
}, 300), // 300ms debounce delay, adjust as needed
|
||||||
[]
|
[]
|
||||||
);
|
);
|
||||||
@ -440,21 +490,26 @@ export default function CodeEditor({
|
|||||||
|
|
||||||
setGenerate((prev) => ({ ...prev, show: false }));
|
setGenerate((prev) => ({ ...prev, show: false }));
|
||||||
|
|
||||||
const exists = tabs.find((t) => t.id === tab.id);
|
//editor windows fix
|
||||||
setTabs((prev) => {
|
function updateTabs(){
|
||||||
if (exists) {
|
const exists = tabs.find((t) => t.id === tab.id);
|
||||||
setActiveFileId(exists.id);
|
setTabs((prev) => {
|
||||||
return prev;
|
if (exists) {
|
||||||
}
|
setActiveFileId(exists.id);
|
||||||
return [...prev, tab];
|
return prev;
|
||||||
});
|
}
|
||||||
|
return [...prev, tab];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
if (fileCache.current.has(tab.id)) {
|
if (fileCache.current.has(tab.id)) {
|
||||||
setActiveFileContent(fileCache.current.get(tab.id));
|
setActiveFileContent(fileCache.current.get(tab.id));
|
||||||
|
updateTabs();
|
||||||
} else {
|
} else {
|
||||||
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
debouncedGetFile(tab.id, (response: SetStateAction<string>) => {
|
||||||
fileCache.current.set(tab.id, response);
|
fileCache.current.set(tab.id, response);
|
||||||
setActiveFileContent(response);
|
setActiveFileContent(response);
|
||||||
|
updateTabs();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -534,7 +589,7 @@ export default function CodeEditor({
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
socket.emit("renameFile", id, newName)
|
socketRef.current?.emit("renameFile", id, newName)
|
||||||
setTabs((prev) =>
|
setTabs((prev) =>
|
||||||
prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab))
|
prev.map((tab) => (tab.id === id ? { ...tab, name: newName } : tab))
|
||||||
)
|
)
|
||||||
@ -543,7 +598,7 @@ export default function CodeEditor({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const handleDeleteFile = (file: TFile) => {
|
const handleDeleteFile = (file: TFile) => {
|
||||||
socket.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
|
socketRef.current?.emit("deleteFile", file.id, (response: (TFolder | TFile)[]) => {
|
||||||
setFiles(response)
|
setFiles(response)
|
||||||
})
|
})
|
||||||
closeTab(file.id)
|
closeTab(file.id)
|
||||||
@ -553,11 +608,11 @@ export default function CodeEditor({
|
|||||||
setDeletingFolderId(folder.id)
|
setDeletingFolderId(folder.id)
|
||||||
console.log("deleting folder", folder.id)
|
console.log("deleting folder", folder.id)
|
||||||
|
|
||||||
socket.emit("getFolder", folder.id, (response: string[]) =>
|
socketRef.current?.emit("getFolder", folder.id, (response: string[]) =>
|
||||||
closeTabs(response)
|
closeTabs(response)
|
||||||
)
|
)
|
||||||
|
|
||||||
socket.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
|
socketRef.current?.emit("deleteFolder", folder.id, (response: (TFolder | TFile)[]) => {
|
||||||
setFiles(response)
|
setFiles(response)
|
||||||
setDeletingFolderId("")
|
setDeletingFolderId("")
|
||||||
})
|
})
|
||||||
@ -584,7 +639,7 @@ export default function CodeEditor({
|
|||||||
{generate.show && ai ? (
|
{generate.show && ai ? (
|
||||||
<GenerateInput
|
<GenerateInput
|
||||||
user={userData}
|
user={userData}
|
||||||
socket={socket}
|
socket={socketRef.current}
|
||||||
width={generate.width - 90}
|
width={generate.width - 90}
|
||||||
data={{
|
data={{
|
||||||
fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "",
|
fileName: tabs.find((t) => t.id === activeFileId)?.name ?? "",
|
||||||
@ -644,7 +699,7 @@ export default function CodeEditor({
|
|||||||
handleRename={handleRename}
|
handleRename={handleRename}
|
||||||
handleDeleteFile={handleDeleteFile}
|
handleDeleteFile={handleDeleteFile}
|
||||||
handleDeleteFolder={handleDeleteFolder}
|
handleDeleteFolder={handleDeleteFolder}
|
||||||
socket={socket}
|
socket={socketRef.current}
|
||||||
setFiles={setFiles}
|
setFiles={setFiles}
|
||||||
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
|
addNew={(name, type) => addNew(name, type, setFiles, sandboxData)}
|
||||||
deletingFolderId={deletingFolderId}
|
deletingFolderId={deletingFolderId}
|
||||||
@ -764,6 +819,7 @@ export default function CodeEditor({
|
|||||||
previewPanelRef.current?.expand()
|
previewPanelRef.current?.expand()
|
||||||
setIsPreviewCollapsed(false)
|
setIsPreviewCollapsed(false)
|
||||||
}}
|
}}
|
||||||
|
src={previewURL}
|
||||||
/>
|
/>
|
||||||
</ResizablePanel>
|
</ResizablePanel>
|
||||||
<ResizableHandle />
|
<ResizableHandle />
|
||||||
@ -773,11 +829,7 @@ export default function CodeEditor({
|
|||||||
className="p-2 flex flex-col"
|
className="p-2 flex flex-col"
|
||||||
>
|
>
|
||||||
{isOwner ? (
|
{isOwner ? (
|
||||||
<Terminals
|
<Terminals/>
|
||||||
terminals={terminals}
|
|
||||||
setTerminals={setTerminals}
|
|
||||||
socket={socket}
|
|
||||||
/>
|
|
||||||
) : (
|
) : (
|
||||||
<div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none">
|
<div className="w-full h-full flex items-center justify-center text-lg font-medium text-muted-foreground/50 select-none">
|
||||||
<TerminalSquare className="w-4 h-4 mr-2" />
|
<TerminalSquare className="w-4 h-4 mr-2" />
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import Image from "next/image";
|
import Image from "next/image";
|
||||||
import Logo from "@/assets/logo.svg";
|
import Logo from "@/assets/logo.svg";
|
||||||
import { Pencil, Users } from "lucide-react";
|
import { Pencil, Users, Play, StopCircle } from "lucide-react";
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { Sandbox, User } from "@/lib/types";
|
import { Sandbox, User } from "@/lib/types";
|
||||||
import UserButton from "@/components/ui/userButton";
|
import UserButton from "@/components/ui/userButton";
|
||||||
@ -11,23 +11,30 @@ import { useState } from "react";
|
|||||||
import EditSandboxModal from "./edit";
|
import EditSandboxModal from "./edit";
|
||||||
import ShareSandboxModal from "./share";
|
import ShareSandboxModal from "./share";
|
||||||
import { Avatars } from "../live/avatars";
|
import { Avatars } from "../live/avatars";
|
||||||
|
import RunButtonModal from "./run";
|
||||||
|
import { Terminal } from "@xterm/xterm";
|
||||||
|
import { Socket } from "socket.io-client";
|
||||||
|
import Terminals from "../terminals";
|
||||||
|
|
||||||
export default function Navbar({
|
export default function Navbar({
|
||||||
userData,
|
userData,
|
||||||
sandboxData,
|
sandboxData,
|
||||||
shared,
|
shared,
|
||||||
|
socket,
|
||||||
}: {
|
}: {
|
||||||
userData: User;
|
userData: User;
|
||||||
sandboxData: Sandbox;
|
sandboxData: Sandbox;
|
||||||
shared: {
|
shared: { id: string; name: string }[];
|
||||||
id: string;
|
socket: Socket;
|
||||||
name: string;
|
|
||||||
}[];
|
|
||||||
}) {
|
}) {
|
||||||
const [isEditOpen, setIsEditOpen] = useState(false);
|
const [isEditOpen, setIsEditOpen] = useState(false);
|
||||||
const [isShareOpen, setIsShareOpen] = useState(false);
|
const [isShareOpen, setIsShareOpen] = useState(false);
|
||||||
|
const [isRunning, setIsRunning] = useState(false);
|
||||||
|
const [terminals, setTerminals] = useState<{ id: string; terminal: Terminal | null }[]>([]);
|
||||||
|
const [activeTerminalId, setActiveTerminalId] = useState("");
|
||||||
|
const [creatingTerminal, setCreatingTerminal] = useState(false);
|
||||||
|
|
||||||
const isOwner = sandboxData.userId === userData.id;
|
const isOwner = sandboxData.userId === userData.id;;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@ -62,6 +69,10 @@ export default function Navbar({
|
|||||||
) : null}
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
<RunButtonModal
|
||||||
|
isRunning={isRunning}
|
||||||
|
setIsRunning={setIsRunning}
|
||||||
|
/>
|
||||||
<div className="flex items-center h-full space-x-4">
|
<div className="flex items-center h-full space-x-4">
|
||||||
<Avatars />
|
<Avatars />
|
||||||
|
|
||||||
|
60
frontend/components/editor/navbar/run.tsx
Normal file
60
frontend/components/editor/navbar/run.tsx
Normal file
@ -0,0 +1,60 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Play, StopCircle } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { useTerminal } from "@/context/TerminalContext";
|
||||||
|
import { closeTerminal } from "@/lib/terminal";
|
||||||
|
|
||||||
|
export default function RunButtonModal({
|
||||||
|
isRunning,
|
||||||
|
setIsRunning,
|
||||||
|
}: {
|
||||||
|
isRunning: boolean;
|
||||||
|
setIsRunning: (running: boolean) => void;
|
||||||
|
}) {
|
||||||
|
const { createNewTerminal, terminals, setTerminals, socket, setActiveTerminalId } = useTerminal();
|
||||||
|
|
||||||
|
const handleRun = () => {
|
||||||
|
if (isRunning) {
|
||||||
|
console.log('Stopping sandbox...');
|
||||||
|
console.log('Closing Terminal');
|
||||||
|
console.log('Closing Preview Window');
|
||||||
|
|
||||||
|
// Close all terminals if needed
|
||||||
|
terminals.forEach(term => {
|
||||||
|
if (term.terminal) {
|
||||||
|
// Assuming you have a closeTerminal function similar to createTerminal
|
||||||
|
closeTerminal({
|
||||||
|
term,
|
||||||
|
terminals,
|
||||||
|
setTerminals,
|
||||||
|
setActiveTerminalId,
|
||||||
|
setClosingTerminal: () => { },
|
||||||
|
socket: socket!,
|
||||||
|
activeTerminalId: term.id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.log('Running sandbox...');
|
||||||
|
console.log('Opening Terminal');
|
||||||
|
console.log('Opening Preview Window');
|
||||||
|
|
||||||
|
if (terminals.length < 4) {
|
||||||
|
createNewTerminal();
|
||||||
|
} else {
|
||||||
|
console.error('Maximum number of terminals reached.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setIsRunning(!isRunning);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Button variant="outline" onClick={handleRun}>
|
||||||
|
{isRunning ? <StopCircle className="w-4 h-4 mr-2" /> : <Play className="w-4 h-4 mr-2" />}
|
||||||
|
{isRunning ? 'Stop' : 'Run'}
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
@ -15,9 +15,11 @@ import { toast } from "sonner"
|
|||||||
export default function PreviewWindow({
|
export default function PreviewWindow({
|
||||||
collapsed,
|
collapsed,
|
||||||
open,
|
open,
|
||||||
|
src
|
||||||
}: {
|
}: {
|
||||||
collapsed: boolean
|
collapsed: boolean
|
||||||
open: () => void
|
open: () => void
|
||||||
|
src: string
|
||||||
}) {
|
}) {
|
||||||
const ref = useRef<HTMLIFrameElement>(null)
|
const ref = useRef<HTMLIFrameElement>(null)
|
||||||
const [iframeKey, setIframeKey] = useState(0)
|
const [iframeKey, setIframeKey] = useState(0)
|
||||||
@ -45,7 +47,7 @@ export default function PreviewWindow({
|
|||||||
|
|
||||||
<PreviewButton
|
<PreviewButton
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
navigator.clipboard.writeText(`http://localhost:5173`)
|
navigator.clipboard.writeText(src)
|
||||||
toast.info("Copied preview link to clipboard")
|
toast.info("Copied preview link to clipboard")
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
@ -73,7 +75,7 @@ export default function PreviewWindow({
|
|||||||
ref={ref}
|
ref={ref}
|
||||||
width={"100%"}
|
width={"100%"}
|
||||||
height={"100%"}
|
height={"100%"}
|
||||||
src={`http://localhost:5173`}
|
src={src}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
@ -2,30 +2,16 @@
|
|||||||
|
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import Tab from "@/components/ui/tab";
|
import Tab from "@/components/ui/tab";
|
||||||
import { closeTerminal, createTerminal } from "@/lib/terminal";
|
import { closeTerminal } from "@/lib/terminal";
|
||||||
import { Terminal } from "@xterm/xterm";
|
import { Terminal } from "@xterm/xterm";
|
||||||
import { Loader2, Plus, SquareTerminal, TerminalSquare } from "lucide-react";
|
import { Loader2, Plus, SquareTerminal, TerminalSquare } from "lucide-react";
|
||||||
import { Socket } from "socket.io-client";
|
|
||||||
import { toast } from "sonner";
|
import { toast } from "sonner";
|
||||||
import EditorTerminal from "./terminal";
|
import EditorTerminal from "./terminal";
|
||||||
import { useState } from "react";
|
import { useState } from "react";
|
||||||
|
import { useTerminal } from "@/context/TerminalContext";
|
||||||
|
|
||||||
export default function Terminals({
|
export default function Terminals() {
|
||||||
terminals,
|
const { terminals, setTerminals, socket, createNewTerminal } = useTerminal();
|
||||||
setTerminals,
|
|
||||||
socket,
|
|
||||||
}: {
|
|
||||||
terminals: { id: string; terminal: Terminal | null }[];
|
|
||||||
setTerminals: React.Dispatch<
|
|
||||||
React.SetStateAction<
|
|
||||||
{
|
|
||||||
id: string;
|
|
||||||
terminal: Terminal | null;
|
|
||||||
}[]
|
|
||||||
>
|
|
||||||
>;
|
|
||||||
socket: Socket;
|
|
||||||
}) {
|
|
||||||
const [activeTerminalId, setActiveTerminalId] = useState("");
|
const [activeTerminalId, setActiveTerminalId] = useState("");
|
||||||
const [creatingTerminal, setCreatingTerminal] = useState(false);
|
const [creatingTerminal, setCreatingTerminal] = useState(false);
|
||||||
const [closingTerminal, setClosingTerminal] = useState("");
|
const [closingTerminal, setClosingTerminal] = useState("");
|
||||||
@ -46,7 +32,7 @@ export default function Terminals({
|
|||||||
setTerminals,
|
setTerminals,
|
||||||
setActiveTerminalId,
|
setActiveTerminalId,
|
||||||
setClosingTerminal,
|
setClosingTerminal,
|
||||||
socket,
|
socket: socket!,
|
||||||
activeTerminalId,
|
activeTerminalId,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@ -64,12 +50,7 @@ export default function Terminals({
|
|||||||
toast.error("You reached the maximum # of terminals.");
|
toast.error("You reached the maximum # of terminals.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
createTerminal({
|
createNewTerminal();
|
||||||
setTerminals,
|
|
||||||
setActiveTerminalId,
|
|
||||||
setCreatingTerminal,
|
|
||||||
socket,
|
|
||||||
});
|
|
||||||
}}
|
}}
|
||||||
size="smIcon"
|
size="smIcon"
|
||||||
variant={"secondary"}
|
variant={"secondary"}
|
||||||
|
99
frontend/context/TerminalContext.tsx
Normal file
99
frontend/context/TerminalContext.tsx
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||||
|
import { io, Socket } from 'socket.io-client';
|
||||||
|
import { Terminal } from '@xterm/xterm';
|
||||||
|
import { createId } from '@paralleldrive/cuid2';
|
||||||
|
import { createTerminal as createTerminalHelper, closeTerminal as closeTerminalHelper } from '@/lib/terminal'; // Adjust the import path as necessary
|
||||||
|
|
||||||
|
interface TerminalContextType {
|
||||||
|
socket: Socket | null;
|
||||||
|
terminals: { id: string; terminal: Terminal | null }[];
|
||||||
|
setTerminals: React.Dispatch<React.SetStateAction<{ id: string; terminal: Terminal | null }[]>>;
|
||||||
|
activeTerminalId: string;
|
||||||
|
setActiveTerminalId: React.Dispatch<React.SetStateAction<string>>;
|
||||||
|
creatingTerminal: boolean;
|
||||||
|
setCreatingTerminal: React.Dispatch<React.SetStateAction<boolean>>;
|
||||||
|
createNewTerminal: () => void;
|
||||||
|
closeTerminal: (id: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TerminalContext = createContext<TerminalContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||||
|
const [socket, setSocket] = useState<Socket | null>(null);
|
||||||
|
const [terminals, setTerminals] = useState<{ id: string; terminal: Terminal | null }[]>([]);
|
||||||
|
const [activeTerminalId, setActiveTerminalId] = useState<string>('');
|
||||||
|
const [creatingTerminal, setCreatingTerminal] = useState<boolean>(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
// Replace with your server URL
|
||||||
|
const socketIo = io(process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3001');
|
||||||
|
setSocket(socketIo);
|
||||||
|
|
||||||
|
// Log socket events
|
||||||
|
socketIo.on('connect', () => {
|
||||||
|
console.log('Socket connected:', socketIo.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
socketIo.on('disconnect', () => {
|
||||||
|
console.log('Socket disconnected');
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
socketIo.disconnect();
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const createNewTerminal = () => {
|
||||||
|
if (socket) {
|
||||||
|
createTerminalHelper({
|
||||||
|
setTerminals,
|
||||||
|
setActiveTerminalId,
|
||||||
|
setCreatingTerminal,
|
||||||
|
socket,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const closeTerminal = (id: string) => {
|
||||||
|
const terminalToClose = terminals.find(term => term.id === id);
|
||||||
|
if (terminalToClose && socket) {
|
||||||
|
closeTerminalHelper({
|
||||||
|
term: terminalToClose,
|
||||||
|
terminals,
|
||||||
|
setTerminals,
|
||||||
|
setActiveTerminalId,
|
||||||
|
setClosingTerminal: () => {}, // Implement if needed
|
||||||
|
socket,
|
||||||
|
activeTerminalId,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const value = {
|
||||||
|
socket,
|
||||||
|
terminals,
|
||||||
|
setTerminals,
|
||||||
|
activeTerminalId,
|
||||||
|
setActiveTerminalId,
|
||||||
|
creatingTerminal,
|
||||||
|
setCreatingTerminal,
|
||||||
|
createNewTerminal,
|
||||||
|
closeTerminal,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TerminalContext.Provider value={value}>
|
||||||
|
{children}
|
||||||
|
</TerminalContext.Provider>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useTerminal = (): TerminalContextType => {
|
||||||
|
const context = useContext(TerminalContext);
|
||||||
|
if (!context) {
|
||||||
|
throw new Error('useTerminal must be used within a TerminalProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
};
|
Reference in New Issue
Block a user