import { useState } from "react"; import { SandpackLayout, SandpackFileExplorer, } from "@codesandbox/sandpack-react"; import { ChevronRight, ChevronLeft } from "lucide-react"; import { useParams } from "next/navigation"; import { useQueryClient } from "@tanstack/react-query"; import { format } from "date-fns"; import { useUpdateEffect } from "react-use"; import { AppEditorMonacoEditor } from "./monaco-editor"; import { Button } from "@/components/ui/button"; import { cn } from "@/lib/utils"; import Loading from "../loading"; import { ProjectWithCommits } from "@/actions/projects"; export function AppEditorCode() { const queryClient = useQueryClient(); const { repoId } = useParams<{ repoId: string }>(); const [isFileExplorerCollapsed, setIsFileExplorerCollapsed] = useState(true); const [isSavingChanges, setIsSavingChanges] = useState(false); const [isSavingChangesSuccess, setIsSavingChangesSuccess] = useState(false); const [isSavingChangesError, setIsSavingChangesError] = useState(false); const [isClosing, setIsClosing] = useState(false); const [showSaveChanges, setShowSaveChanges] = useState(false); const handleSaveChanges = async () => { if (repoId === "new") return; setIsSavingChanges(true); const manuallyUpdatedFiles = queryClient.getQueryData(["manuallyUpdatedFiles"]) ?? []; const response = await fetch(`/api/projects/${repoId}`, { method: "PUT", body: JSON.stringify({ files: manuallyUpdatedFiles, prompt: `✍️ ${format(new Date(), "dd/MM")} - ${format( new Date(), "HH:mm" )} - Manual changes.`, isManualChanges: true, }), }).then(async (response) => { if (response.ok) { const data = await response.json(); return data; } throw new Error("Failed to save changes"); }); if (response.success) { setIsSavingChangesSuccess(true); queryClient.invalidateQueries({ queryKey: ["manuallyUpdatedFiles"] }); queryClient.setQueryData( ["project"], (oldProject: ProjectWithCommits) => ({ ...oldProject, commits: [response.commit, ...(oldProject?.commits ?? [])], }) ); } else { setIsSavingChangesError(true); } setIsSavingChanges(false); setShowSaveChanges(false); }; const undoChanges = () => { queryClient.setQueryData(["manuallyUpdatedFiles"], []); setShowSaveChanges(false); }; useUpdateEffect(() => { if (isSavingChangesSuccess) { setTimeout(() => setIsSavingChangesSuccess(false), 3000); } }, [isSavingChangesSuccess]); useUpdateEffect(() => { if (isClosing) { setTimeout(() => { setIsSavingChangesSuccess(false); setIsSavingChangesError(false); setIsClosing(false); }, 300); } }, [isClosing]); return (
{repoId && (

{isSavingChangesSuccess ? "Changes saved" : isSavingChangesError ? "Failed to save changes" : "Save Changes"}

{isSavingChangesSuccess ? "Changes saved successfully" : isSavingChangesError ? "Something went wrong, please try again." : "You have unsaved manual changes. Click the button to save your changes."}

{!isSavingChangesSuccess && !isSavingChanges && ( )} {isSavingChangesSuccess || isSavingChangesError ? ( ) : ( )}
)}
); }