Compare commits
22 Commits
feature/ap
...
file-save
Author | SHA1 | Date | |
---|---|---|---|
0117e197bb | |||
37ebe41526 | |||
ed367ed27c | |||
9666401625 | |||
22d638a090 | |||
0dd99cbc77 | |||
093a4e9758 | |||
6a60f4d286 | |||
260110724e | |||
ee51ae7a33 | |||
0d0eed34b2 | |||
4e1c5cac27 | |||
0ae89341d2 | |||
1630a5a9cd | |||
ffdcdef56c | |||
6612692d98 | |||
534b148b86 | |||
e384607d24 | |||
e7d9989931 | |||
42305d67b9 | |||
06dadf3a0b | |||
ba7a1dcc2c |
22
README.md
22
README.md
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||

|

|
||||||
|
|
||||||
Sandbox is an open-source cloud-based code editing environment with custom AI code generation, live preview, real-time collaboration and AI chat.
|
Sandbox is an open-source cloud-based code editing environment with custom AI code generation, live preview, real-time collaboration, and AI chat.
|
||||||
|
|
||||||
For the latest updates, join our Discord server: [discord.gitwit.dev](https://discord.gitwit.dev/).
|
For the latest updates, join our Discord server: [discord.gitwit.dev](https://discord.gitwit.dev/).
|
||||||
|
|
||||||
@ -10,11 +10,11 @@ For the latest updates, join our Discord server: [discord.gitwit.dev](https://di
|
|||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
|
|
||||||
- Double check that whatever you change "SUPERDUPERSECRET" to, it's the same in all config files.
|
- Double-check that whatever you change "SUPERDUPERSECRET" to, it's the same in all config files.
|
||||||
|
|
||||||
### 0. Requirements
|
### 0. Requirements
|
||||||
|
|
||||||
The application uses NodeJS for the backend, NextJS for the frontend and Cloudflare workers for additional backend tasks.
|
The application uses NodeJS for the backend, NextJS for the frontend, and Cloudflare workers for additional backend tasks.
|
||||||
|
|
||||||
Needed accounts to set up:
|
Needed accounts to set up:
|
||||||
|
|
||||||
@ -22,6 +22,7 @@ Needed accounts to set up:
|
|||||||
- [Liveblocks](https://liveblocks.io/): Used for collaborative editing.
|
- [Liveblocks](https://liveblocks.io/): Used for collaborative editing.
|
||||||
- [E2B](https://e2b.dev/): Used for the terminals and live preview.
|
- [E2B](https://e2b.dev/): Used for the terminals and live preview.
|
||||||
- [Cloudflare](https://www.cloudflare.com/): Used for relational data storage (D2) and file storage (R2).
|
- [Cloudflare](https://www.cloudflare.com/): Used for relational data storage (D2) and file storage (R2).
|
||||||
|
- [Anthropic](https://anthropic.com/) and [OpenAI](https://openai.com/): API keys for code generation.
|
||||||
|
|
||||||
A quick overview of the tech before we start: The deployment uses a **NextJS** app for the frontend and an **ExpressJS** server on the backend. Presumably that's because NextJS integrates well with Clerk middleware but not with Socket.io.
|
A quick overview of the tech before we start: The deployment uses a **NextJS** app for the frontend and an **ExpressJS** server on the backend. Presumably that's because NextJS integrates well with Clerk middleware but not with Socket.io.
|
||||||
|
|
||||||
@ -41,7 +42,6 @@ Run `npm install` in:
|
|||||||
/backend/database
|
/backend/database
|
||||||
/backend/storage
|
/backend/storage
|
||||||
/backend/server
|
/backend/server
|
||||||
/backend/ai
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### 2. Adding Clerk
|
### 2. Adding Clerk
|
||||||
@ -152,6 +152,7 @@ NEXT_PUBLIC_DATABASE_WORKER_URL='https://database.🍎.workers.dev'
|
|||||||
NEXT_PUBLIC_STORAGE_WORKER_URL='https://storage.🍎.workers.dev'
|
NEXT_PUBLIC_STORAGE_WORKER_URL='https://storage.🍎.workers.dev'
|
||||||
NEXT_PUBLIC_WORKERS_KEY='SUPERDUPERSECRET'
|
NEXT_PUBLIC_WORKERS_KEY='SUPERDUPERSECRET'
|
||||||
ANTHROPIC_API_KEY='🔑'
|
ANTHROPIC_API_KEY='🔑'
|
||||||
|
OPENAI_API_KEY='🔑'
|
||||||
```
|
```
|
||||||
|
|
||||||
### 10. Running the IDE
|
### 10. Running the IDE
|
||||||
@ -173,6 +174,15 @@ Setting up deployments first requires a separate domain (such as gitwit.app, whi
|
|||||||
|
|
||||||
We then deploy Dokku on a separate server, according to this guide: https://dev.to/jamesmurdza/host-your-own-paas-platform-as-a-service-on-amazon-web-services-3f0d
|
We then deploy Dokku on a separate server, according to this guide: https://dev.to/jamesmurdza/host-your-own-paas-platform-as-a-service-on-amazon-web-services-3f0d
|
||||||
|
|
||||||
|
And we install [dokku-daemon](https://github.com/dokku/dokku-daemon) with the following commands:
|
||||||
|
|
||||||
|
```
|
||||||
|
git clone https://github.com/dokku/dokku-daemon
|
||||||
|
cd dokku-daemon
|
||||||
|
sudo make install
|
||||||
|
systemctl start dokku-daemon
|
||||||
|
```
|
||||||
|
|
||||||
The Sandbox platform connects to the Dokku server via SSH, using SSH keys specifically generated for this connection. The SSH key is stored on the Sandbox server, and the following environment variables are set in /backend/server/.env:
|
The Sandbox platform connects to the Dokku server via SSH, using SSH keys specifically generated for this connection. The SSH key is stored on the Sandbox server, and the following environment variables are set in /backend/server/.env:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@ -246,8 +256,7 @@ backend/
|
|||||||
├── database/
|
├── database/
|
||||||
│ ├── src
|
│ ├── src
|
||||||
│ └── drizzle
|
│ └── drizzle
|
||||||
├── storage
|
└── storage
|
||||||
└── ai
|
|
||||||
```
|
```
|
||||||
|
|
||||||
| Path | Description |
|
| Path | Description |
|
||||||
@ -256,7 +265,6 @@ backend/
|
|||||||
| `backend/server` | The Express websocket server. |
|
| `backend/server` | The Express websocket server. |
|
||||||
| `backend/database` | API for interfacing with the D1 database (SQLite). |
|
| `backend/database` | API for interfacing with the D1 database (SQLite). |
|
||||||
| `backend/storage` | API for interfacing with R2 storage. Service-bound to `/backend/database`. |
|
| `backend/storage` | API for interfacing with R2 storage. Service-bound to `/backend/database`. |
|
||||||
| `backend/ai` | API for making requests to Workers AI . |
|
|
||||||
|
|
||||||
### Development
|
### Development
|
||||||
|
|
||||||
|
@ -31,9 +31,30 @@ export class DokkuClient extends SSHSocketClient {
|
|||||||
|
|
||||||
// List all deployed Dokku apps
|
// List all deployed Dokku apps
|
||||||
async listApps(): Promise<string[]> {
|
async listApps(): Promise<string[]> {
|
||||||
const response = await this.sendCommand("apps:list")
|
const response = await this.sendCommand("--quiet apps:list")
|
||||||
// Split the output by newline and remove the header
|
return response.output.split("\n")
|
||||||
return response.output.split("\n").slice(1)
|
}
|
||||||
|
|
||||||
|
// Get the creation timestamp of an app
|
||||||
|
async getAppCreatedAt(appName: string): Promise<number> {
|
||||||
|
const response = await this.sendCommand(
|
||||||
|
`apps:report --app-created-at ${appName}`
|
||||||
|
)
|
||||||
|
const createdAt = parseInt(response.output.trim(), 10)
|
||||||
|
|
||||||
|
if (isNaN(createdAt)) {
|
||||||
|
throw new Error(
|
||||||
|
`Failed to retrieve creation timestamp for app ${appName}`
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
return createdAt
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if an app exists
|
||||||
|
async appExists(appName: string): Promise<boolean> {
|
||||||
|
const response = await this.sendCommand(`apps:exists ${appName}`)
|
||||||
|
return response.output.includes("App") === false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -92,7 +92,11 @@ export class FileManager {
|
|||||||
|
|
||||||
// Convert local file path to remote path
|
// Convert local file path to remote path
|
||||||
private getRemoteFileId(localId: string): string {
|
private getRemoteFileId(localId: string): string {
|
||||||
return `projects/${this.sandboxId}${localId}`
|
return [
|
||||||
|
"projects",
|
||||||
|
this.sandboxId,
|
||||||
|
localId.startsWith("/") ? localId : localId,
|
||||||
|
].join("/")
|
||||||
}
|
}
|
||||||
|
|
||||||
// Convert remote file path to local file path
|
// Convert remote file path to local file path
|
||||||
@ -326,13 +330,15 @@ export class FileManager {
|
|||||||
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
if (Buffer.byteLength(body, "utf-8") > MAX_BODY_SIZE) {
|
||||||
throw new Error("File size too large. Please reduce the file size.")
|
throw new Error("File size too large. Please reduce the file size.")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Save to remote storage
|
||||||
await RemoteFileStorage.saveFile(this.getRemoteFileId(fileId), body)
|
await RemoteFileStorage.saveFile(this.getRemoteFileId(fileId), body)
|
||||||
|
|
||||||
|
// Update local file data cache
|
||||||
let file = this.fileData.find((f) => f.id === fileId)
|
let file = this.fileData.find((f) => f.id === fileId)
|
||||||
if (file) {
|
if (file) {
|
||||||
file.data = body
|
file.data = body
|
||||||
} else {
|
} else {
|
||||||
// If the file wasn't in our cache, add it
|
|
||||||
file = {
|
file = {
|
||||||
id: fileId,
|
id: fileId,
|
||||||
data: body,
|
data: body,
|
||||||
@ -340,7 +346,49 @@ export class FileManager {
|
|||||||
this.fileData.push(file)
|
this.fileData.push(file)
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.sandbox.files.write(path.posix.join(this.dirName, fileId), body)
|
// Save to sandbox filesystem
|
||||||
|
const filePath = path.posix.join(this.dirName, fileId)
|
||||||
|
await this.sandbox.files.write(filePath, body)
|
||||||
|
|
||||||
|
// Instead of updating the entire file structure, just ensure this file exists in it
|
||||||
|
const parts = fileId.split('/').filter(Boolean)
|
||||||
|
let current = this.files
|
||||||
|
let currentPath = ''
|
||||||
|
|
||||||
|
// Navigate/create the path to the file
|
||||||
|
for (let i = 0; i < parts.length - 1; i++) {
|
||||||
|
currentPath += '/' + parts[i]
|
||||||
|
let folder = current.find(
|
||||||
|
(f) => f.type === 'folder' && f.name === parts[i]
|
||||||
|
) as TFolder
|
||||||
|
|
||||||
|
if (!folder) {
|
||||||
|
folder = {
|
||||||
|
id: currentPath,
|
||||||
|
type: 'folder',
|
||||||
|
name: parts[i],
|
||||||
|
children: [],
|
||||||
|
}
|
||||||
|
current.push(folder)
|
||||||
|
}
|
||||||
|
current = folder.children
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add/update the file in the structure if it doesn't exist
|
||||||
|
const fileName = parts[parts.length - 1]
|
||||||
|
const existingFile = current.find(
|
||||||
|
(f) => f.type === 'file' && f.name === fileName
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!existingFile) {
|
||||||
|
current.push({
|
||||||
|
id: fileId,
|
||||||
|
type: 'file',
|
||||||
|
name: fileName,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
this.refreshFileList?.(this.files)
|
||||||
this.fixPermissions()
|
this.fixPermissions()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -13,7 +13,10 @@ export class SSHSocketClient {
|
|||||||
private conn: Client
|
private conn: Client
|
||||||
private config: SSHConfig
|
private config: SSHConfig
|
||||||
private socketPath: string
|
private socketPath: string
|
||||||
private isConnected: boolean = false
|
private _isConnected: boolean = false
|
||||||
|
public get isConnected(): boolean {
|
||||||
|
return this._isConnected
|
||||||
|
}
|
||||||
|
|
||||||
// Constructor initializes the SSH client and sets up configuration
|
// Constructor initializes the SSH client and sets up configuration
|
||||||
constructor(config: SSHConfig, socketPath: string) {
|
constructor(config: SSHConfig, socketPath: string) {
|
||||||
@ -34,7 +37,7 @@ export class SSHSocketClient {
|
|||||||
private closeConnection() {
|
private closeConnection() {
|
||||||
console.log("Closing SSH connection...")
|
console.log("Closing SSH connection...")
|
||||||
this.conn.end()
|
this.conn.end()
|
||||||
this.isConnected = false
|
this._isConnected = false
|
||||||
process.exit(0)
|
process.exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -44,17 +47,17 @@ export class SSHSocketClient {
|
|||||||
this.conn
|
this.conn
|
||||||
.on("ready", () => {
|
.on("ready", () => {
|
||||||
console.log("SSH connection established")
|
console.log("SSH connection established")
|
||||||
this.isConnected = true
|
this._isConnected = true
|
||||||
resolve()
|
resolve()
|
||||||
})
|
})
|
||||||
.on("error", (err) => {
|
.on("error", (err) => {
|
||||||
console.error("SSH connection error:", err)
|
console.error("SSH connection error:", err)
|
||||||
this.isConnected = false
|
this._isConnected = false
|
||||||
reject(err)
|
reject(err)
|
||||||
})
|
})
|
||||||
.on("close", () => {
|
.on("close", () => {
|
||||||
console.log("SSH connection closed")
|
console.log("SSH connection closed")
|
||||||
this.isConnected = false
|
this._isConnected = false
|
||||||
})
|
})
|
||||||
.connect(this.config)
|
.connect(this.config)
|
||||||
})
|
})
|
||||||
@ -86,10 +89,13 @@ export class SSHSocketClient {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
.on("data", (data: Buffer) => {
|
.on("data", (data: Buffer) => {
|
||||||
|
// Netcat remains open until it is closed, so we close the connection once we receive data.
|
||||||
resolve(data.toString())
|
resolve(data.toString())
|
||||||
|
stream.close()
|
||||||
})
|
})
|
||||||
.stderr.on("data", (data: Buffer) => {
|
.stderr.on("data", (data: Buffer) => {
|
||||||
reject(new Error(data.toString()))
|
reject(new Error(data.toString()))
|
||||||
|
stream.close()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
@ -156,6 +156,40 @@ export class Sandbox {
|
|||||||
return { success: true, apps: await this.dokkuClient.listApps() }
|
return { success: true, apps: await this.dokkuClient.listApps() }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Handle getting app creation timestamp
|
||||||
|
const handleGetAppCreatedAt: SocketHandler = async ({ appName }) => {
|
||||||
|
if (!this.dokkuClient)
|
||||||
|
throw new Error(
|
||||||
|
"Failed to retrieve app creation timestamp: No Dokku client"
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
createdAt: await this.dokkuClient.getAppCreatedAt(appName),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle checking if an app exists
|
||||||
|
const handleAppExists: SocketHandler = async ({ appName }) => {
|
||||||
|
if (!this.dokkuClient) {
|
||||||
|
console.log("Failed to check app existence: No Dokku client")
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!this.dokkuClient.isConnected) {
|
||||||
|
console.log(
|
||||||
|
"Failed to check app existence: The Dokku client is not connected"
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
exists: await this.dokkuClient.appExists(appName),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Handle deploying code
|
// Handle deploying code
|
||||||
const handleDeploy: SocketHandler = async (_: any) => {
|
const handleDeploy: SocketHandler = async (_: any) => {
|
||||||
if (!this.gitClient) throw Error("No git client")
|
if (!this.gitClient) throw Error("No git client")
|
||||||
@ -253,7 +287,9 @@ export class Sandbox {
|
|||||||
getFolder: handleGetFolder,
|
getFolder: handleGetFolder,
|
||||||
saveFile: handleSaveFile,
|
saveFile: handleSaveFile,
|
||||||
moveFile: handleMoveFile,
|
moveFile: handleMoveFile,
|
||||||
list: handleListApps,
|
listApps: handleListApps,
|
||||||
|
getAppCreatedAt: handleGetAppCreatedAt,
|
||||||
|
getAppExists: handleAppExists,
|
||||||
deploy: handleDeploy,
|
deploy: handleDeploy,
|
||||||
createFile: handleCreateFile,
|
createFile: handleCreateFile,
|
||||||
createFolder: handleCreateFolder,
|
createFolder: handleCreateFolder,
|
||||||
|
@ -146,6 +146,8 @@ io.on("connection", async (socket) => {
|
|||||||
)
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
|
socket.emit("ready")
|
||||||
|
|
||||||
// Handle disconnection event
|
// Handle disconnection event
|
||||||
socket.on("disconnect", async () => {
|
socket.on("disconnect", async () => {
|
||||||
try {
|
try {
|
||||||
|
@ -387,9 +387,16 @@ export default function CodeEditor({
|
|||||||
(mergedCode: string, originalCode: string) => {
|
(mergedCode: string, originalCode: string) => {
|
||||||
if (!editorRef) return
|
if (!editorRef) return
|
||||||
|
|
||||||
|
const model = editorRef.getModel()
|
||||||
|
if (!model) return // Store original content
|
||||||
|
;(model as any).originalContent = originalCode
|
||||||
|
|
||||||
|
// Calculate the full range of the document
|
||||||
|
const fullRange = model.getFullModelRange()
|
||||||
|
|
||||||
|
// Create decorations before applying the edit
|
||||||
const originalLines = originalCode.split("\n")
|
const originalLines = originalCode.split("\n")
|
||||||
const mergedLines = mergedCode.split("\n")
|
const mergedLines = mergedCode.split("\n")
|
||||||
|
|
||||||
const decorations: monaco.editor.IModelDeltaDecoration[] = []
|
const decorations: monaco.editor.IModelDeltaDecoration[] = []
|
||||||
|
|
||||||
for (
|
for (
|
||||||
@ -410,14 +417,16 @@ export default function CodeEditor({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Store original content in the model
|
// Execute the edit operation
|
||||||
const model = editorRef.getModel()
|
editorRef.executeEdits("apply-code", [
|
||||||
if (model) {
|
{
|
||||||
;(model as any).originalContent = originalCode
|
range: fullRange,
|
||||||
}
|
text: mergedCode,
|
||||||
editorRef.setValue(mergedCode)
|
forceMoveMarkers: true,
|
||||||
|
},
|
||||||
|
])
|
||||||
|
|
||||||
// Apply decorations
|
// Apply decorations after the edit
|
||||||
const newDecorations = editorRef.createDecorationsCollection(decorations)
|
const newDecorations = editorRef.createDecorationsCollection(decorations)
|
||||||
setMergeDecorationsCollection(newDecorations)
|
setMergeDecorationsCollection(newDecorations)
|
||||||
},
|
},
|
||||||
@ -784,31 +793,32 @@ export default function CodeEditor({
|
|||||||
setGenerate((prev) => ({ ...prev, show: false }))
|
setGenerate((prev) => ({ ...prev, show: false }))
|
||||||
|
|
||||||
// Check if the tab already exists in the list of open tabs
|
// Check if the tab already exists in the list of open tabs
|
||||||
const exists = tabs.find((t) => t.id === tab.id)
|
const existingTab = tabs.find((t) => t.id === tab.id)
|
||||||
setTabs((prev) => {
|
|
||||||
if (exists) {
|
|
||||||
// If the tab exists, make it the active tab
|
|
||||||
setActiveFileId(exists.id)
|
|
||||||
return prev
|
|
||||||
}
|
|
||||||
// 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 (existingTab) {
|
||||||
if (fileContents[tab.id]) {
|
// If the tab exists, just make it active
|
||||||
setActiveFileContent(fileContents[tab.id])
|
setActiveFileId(existingTab.id)
|
||||||
|
if (fileContents[existingTab.id]) {
|
||||||
|
setActiveFileContent(fileContents[existingTab.id])
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// Otherwise, fetch the content of the file and cache it
|
// If the tab doesn't exist, add it to the list and make it active
|
||||||
|
setTabs((prev) => [...prev, tab])
|
||||||
|
|
||||||
|
// Fetch content if not cached
|
||||||
|
if (!fileContents[tab.id]) {
|
||||||
debouncedGetFile(tab.id, (response: string) => {
|
debouncedGetFile(tab.id, (response: string) => {
|
||||||
setFileContents((prev) => ({ ...prev, [tab.id]: response }))
|
setFileContents((prev) => ({ ...prev, [tab.id]: response }))
|
||||||
setActiveFileContent(response)
|
setActiveFileContent(response)
|
||||||
})
|
})
|
||||||
|
} else {
|
||||||
|
setActiveFileContent(fileContents[tab.id])
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the editor language based on the file type
|
// Set the editor language based on the file type
|
||||||
setEditorLanguage(processFileType(tab.name))
|
setEditorLanguage(processFileType(tab.name))
|
||||||
// Set the active file ID to the new tab
|
// Set the active file ID
|
||||||
setActiveFileId(tab.id)
|
setActiveFileId(tab.id)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -9,7 +9,7 @@ import {
|
|||||||
import { useTerminal } from "@/context/TerminalContext"
|
import { useTerminal } from "@/context/TerminalContext"
|
||||||
import { Sandbox, User } from "@/lib/types"
|
import { Sandbox, User } from "@/lib/types"
|
||||||
import { Globe } from "lucide-react"
|
import { Globe } from "lucide-react"
|
||||||
import { useState } from "react"
|
import { useEffect, useState } from "react"
|
||||||
|
|
||||||
export default function DeployButtonModal({
|
export default function DeployButtonModal({
|
||||||
userData,
|
userData,
|
||||||
@ -18,8 +18,21 @@ export default function DeployButtonModal({
|
|||||||
userData: User
|
userData: User
|
||||||
data: Sandbox
|
data: Sandbox
|
||||||
}) {
|
}) {
|
||||||
const { deploy } = useTerminal()
|
const { deploy, getAppExists } = useTerminal()
|
||||||
const [isDeploying, setIsDeploying] = useState(false)
|
const [isDeploying, setIsDeploying] = useState(false)
|
||||||
|
const [isDeployed, setIsDeployed] = useState(false)
|
||||||
|
const [deployButtonVisible, setDeployButtonEnabled] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const checkDeployment = async () => {
|
||||||
|
if (getAppExists) {
|
||||||
|
const exists = await getAppExists(data.id)
|
||||||
|
setDeployButtonEnabled(exists.success)
|
||||||
|
setIsDeployed((exists.success && exists.exists) ?? false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkDeployment()
|
||||||
|
}, [data.id, getAppExists])
|
||||||
|
|
||||||
const handleDeploy = () => {
|
const handleDeploy = () => {
|
||||||
if (isDeploying) {
|
if (isDeploying) {
|
||||||
@ -30,6 +43,7 @@ export default function DeployButtonModal({
|
|||||||
setIsDeploying(true)
|
setIsDeploying(true)
|
||||||
deploy(() => {
|
deploy(() => {
|
||||||
setIsDeploying(false)
|
setIsDeploying(false)
|
||||||
|
setIsDeployed(true)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -38,10 +52,12 @@ export default function DeployButtonModal({
|
|||||||
<>
|
<>
|
||||||
<Popover>
|
<Popover>
|
||||||
<PopoverTrigger asChild>
|
<PopoverTrigger asChild>
|
||||||
|
{deployButtonVisible && (
|
||||||
<Button variant="outline">
|
<Button variant="outline">
|
||||||
<Globe className="w-4 h-4 mr-2" />
|
<Globe className="w-4 h-4 mr-2" />
|
||||||
Deploy
|
Deploy
|
||||||
</Button>
|
</Button>
|
||||||
|
)}
|
||||||
</PopoverTrigger>
|
</PopoverTrigger>
|
||||||
<PopoverContent
|
<PopoverContent
|
||||||
className="p-4 w-full max-w-xs sm:max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl rounded-lg shadow-lg"
|
className="p-4 w-full max-w-xs sm:max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl rounded-lg shadow-lg"
|
||||||
@ -52,8 +68,9 @@ export default function DeployButtonModal({
|
|||||||
<DeploymentOption
|
<DeploymentOption
|
||||||
icon={<Globe className="text-gray-500 w-5 h-5" />}
|
icon={<Globe className="text-gray-500 w-5 h-5" />}
|
||||||
domain={`${data.id}.gitwit.app`}
|
domain={`${data.id}.gitwit.app`}
|
||||||
timestamp="Deployed 1h ago"
|
timestamp="Deployed 1m ago"
|
||||||
user={userData.name}
|
user={userData.name}
|
||||||
|
isDeployed={isDeployed}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<Button
|
<Button
|
||||||
@ -61,7 +78,7 @@ export default function DeployButtonModal({
|
|||||||
className="mt-4 w-full bg-[#0a0a0a] text-white hover:bg-[#262626]"
|
className="mt-4 w-full bg-[#0a0a0a] text-white hover:bg-[#262626]"
|
||||||
onClick={handleDeploy}
|
onClick={handleDeploy}
|
||||||
>
|
>
|
||||||
{isDeploying ? "Deploying..." : "Update"}
|
{isDeploying ? "Deploying..." : isDeployed ? "Update" : "Deploy"}
|
||||||
</Button>
|
</Button>
|
||||||
</PopoverContent>
|
</PopoverContent>
|
||||||
</Popover>
|
</Popover>
|
||||||
@ -74,16 +91,19 @@ function DeploymentOption({
|
|||||||
domain,
|
domain,
|
||||||
timestamp,
|
timestamp,
|
||||||
user,
|
user,
|
||||||
|
isDeployed,
|
||||||
}: {
|
}: {
|
||||||
icon: React.ReactNode
|
icon: React.ReactNode
|
||||||
domain: string
|
domain: string
|
||||||
timestamp: string
|
timestamp: string
|
||||||
user: string
|
user: string
|
||||||
|
isDeployed: boolean
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-2 w-full text-left p-2 rounded-md border border-gray-700 bg-gray-900">
|
<div className="flex flex-col gap-2 w-full text-left p-2 rounded-md border border-gray-700 bg-gray-900">
|
||||||
<div className="flex items-start gap-2 relative">
|
<div className="flex items-start gap-2 relative">
|
||||||
<div className="flex-shrink-0">{icon}</div>
|
<div className="flex-shrink-0">{icon}</div>
|
||||||
|
{isDeployed ? (
|
||||||
<a
|
<a
|
||||||
href={`https://${domain}`}
|
href={`https://${domain}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
@ -92,9 +112,12 @@ function DeploymentOption({
|
|||||||
>
|
>
|
||||||
{domain}
|
{domain}
|
||||||
</a>
|
</a>
|
||||||
|
) : (
|
||||||
|
<span className="font-semibold text-gray-300">{domain}</span>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-gray-400 mt-0 ml-7">
|
<p className="text-sm text-gray-400 mt-0 ml-7">
|
||||||
{timestamp} • {user}
|
{isDeployed ? `${timestamp} • ${user}` : "Never deployed"}
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
)
|
)
|
||||||
|
@ -20,6 +20,9 @@ interface TerminalContextType {
|
|||||||
createNewTerminal: (command?: string) => Promise<void>
|
createNewTerminal: (command?: string) => Promise<void>
|
||||||
closeTerminal: (id: string) => void
|
closeTerminal: (id: string) => void
|
||||||
deploy: (callback: () => void) => void
|
deploy: (callback: () => void) => void
|
||||||
|
getAppExists:
|
||||||
|
| ((appName: string) => Promise<{ success: boolean; exists?: boolean }>)
|
||||||
|
| null
|
||||||
}
|
}
|
||||||
|
|
||||||
const TerminalContext = createContext<TerminalContextType | undefined>(
|
const TerminalContext = createContext<TerminalContextType | undefined>(
|
||||||
@ -35,6 +38,19 @@ export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
>([])
|
>([])
|
||||||
const [activeTerminalId, setActiveTerminalId] = useState<string>("")
|
const [activeTerminalId, setActiveTerminalId] = useState<string>("")
|
||||||
const [creatingTerminal, setCreatingTerminal] = useState<boolean>(false)
|
const [creatingTerminal, setCreatingTerminal] = useState<boolean>(false)
|
||||||
|
const [isSocketReady, setIsSocketReady] = useState<boolean>(false)
|
||||||
|
|
||||||
|
// Listen for the "ready" signal from the socket
|
||||||
|
React.useEffect(() => {
|
||||||
|
if (socket) {
|
||||||
|
socket.on("ready", () => {
|
||||||
|
setIsSocketReady(true)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
return () => {
|
||||||
|
if (socket) socket.off("ready")
|
||||||
|
}
|
||||||
|
}, [socket])
|
||||||
|
|
||||||
const createNewTerminal = async (command?: string): Promise<void> => {
|
const createNewTerminal = async (command?: string): Promise<void> => {
|
||||||
if (!socket) return
|
if (!socket) return
|
||||||
@ -78,6 +94,20 @@ export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const getAppExists = async (
|
||||||
|
appName: string
|
||||||
|
): Promise<{ success: boolean; exists?: boolean }> => {
|
||||||
|
console.log("Is there a socket: " + !!socket)
|
||||||
|
if (!socket) {
|
||||||
|
console.error("Couldn't check if app exists: No socket")
|
||||||
|
return { success: false }
|
||||||
|
}
|
||||||
|
const response: { success: boolean; exists?: boolean } = await new Promise(
|
||||||
|
(resolve) => socket.emit("getAppExists", { appName }, resolve)
|
||||||
|
)
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
const value = {
|
const value = {
|
||||||
terminals,
|
terminals,
|
||||||
setTerminals,
|
setTerminals,
|
||||||
@ -88,6 +118,7 @@ export const TerminalProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||||||
createNewTerminal,
|
createNewTerminal,
|
||||||
closeTerminal,
|
closeTerminal,
|
||||||
deploy,
|
deploy,
|
||||||
|
getAppExists: isSocketReady ? getAppExists : null,
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
|
Reference in New Issue
Block a user