79 lines
2.4 KiB
TypeScript
Raw Normal View History

2024-10-21 13:57:45 -06:00
"use client"
2024-07-23 17:30:35 -04:00
2024-10-21 13:57:45 -06:00
import { Button } from "@/components/ui/button"
import { usePreview } from "@/context/PreviewContext"
import { useTerminal } from "@/context/TerminalContext"
import { Sandbox } from "@/lib/types"
import { Play, StopCircle } from "lucide-react"
import { useEffect, useRef } from "react"
import { toast } from "sonner"
2024-07-23 17:30:35 -04:00
export default function RunButtonModal({
isRunning,
setIsRunning,
sandboxData,
2024-07-23 17:30:35 -04:00
}: {
2024-10-21 13:57:45 -06:00
isRunning: boolean
setIsRunning: (running: boolean) => void
sandboxData: Sandbox
2024-07-23 17:30:35 -04:00
}) {
2024-10-21 13:57:45 -06:00
const { createNewTerminal, closeTerminal, terminals } = useTerminal()
const { setIsPreviewCollapsed, previewPanelRef } = usePreview()
// Ref to keep track of the last created terminal's ID
2024-10-21 13:57:45 -06:00
const lastCreatedTerminalRef = useRef<string | null>(null)
2024-07-23 17:30:35 -04:00
// Effect to update the lastCreatedTerminalRef when a new terminal is added
useEffect(() => {
if (terminals.length > 0 && !isRunning) {
2024-10-21 13:57:45 -06:00
const latestTerminal = terminals[terminals.length - 1]
if (
latestTerminal &&
latestTerminal.id !== lastCreatedTerminalRef.current
) {
lastCreatedTerminalRef.current = latestTerminal.id
2024-07-23 17:30:35 -04:00
}
}
2024-10-21 13:57:45 -06:00
}, [terminals, isRunning])
2024-07-23 17:30:35 -04:00
const handleRun = async () => {
2024-10-21 13:57:45 -06:00
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"
? "./venv/bin/streamlit run main.py --server.runOnSave true"
: "npm run dev"
2024-10-21 13:57:45 -06:00
try {
// Create a new terminal with the appropriate command
2024-10-21 13:57:45 -06:00
await createNewTerminal(command)
setIsPreviewCollapsed(false)
previewPanelRef.current?.expand()
} catch (error) {
2024-10-21 13:57:45 -06:00
toast.error("Failed to create new terminal.")
console.error("Error creating new terminal:", error)
return
}
} else if (!isRunning) {
2024-10-21 13:57:45 -06:00
toast.error("You've reached the maximum number of terminals.")
return
2024-07-23 17:30:35 -04:00
}
2024-10-21 13:57:45 -06:00
setIsRunning(!isRunning)
}
2024-07-23 17:30:35 -04:00
return (
<Button variant="outline" onClick={handleRun}>
2024-10-21 13:57:45 -06:00
{isRunning ? (
<StopCircle className="w-4 h-4 mr-2" />
) : (
<Play className="w-4 h-4 mr-2" />
)}
{isRunning ? "Stop" : "Run"}
</Button>
2024-10-21 13:57:45 -06:00
)
}