import { useState, useEffect, useCallback, useRef } from 'react'; import { useParams } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { type Project } from '@/lib/ProjectsManager'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane'; import { PreviewPane } from '@/components/Shakespeare/PreviewPane'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { ProjectDetailsDialog } from '@/components/ProjectDetailsDialog'; import { DeleteProjectDialog } from '@/components/DeleteProjectDialog'; import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { ArrowLeft, MessageSquare, Eye, Code, Menu, Loader2 } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; import { useIsMobile } from '@/hooks/useIsMobile'; import { ProjectTitleMenu } from '@/components/ProjectTitleMenu'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { GitSyncButton } from '@/components/git-sync'; import { DeployButton } from '@/components/deploy/DeployButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; import { useConsoleError } from '@/hooks/useConsoleError'; import { useAutoBuild } from '@/hooks/useAutoBuild'; import { useToast } from '@/hooks/useToast'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useGitFetch } from '@/hooks/useGitFetch'; import { useQueryClient } from '@tanstack/react-query'; import { cn } from '@/lib/utils'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); const { t } = useTranslation(); const [project, setProject] = useState(null); const [isLoading, setIsLoading] = useState(true); const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview'); const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const [isAILoading, setIsAILoading] = useState(false); const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false); const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false); const [deleteDialogOpen, setDeleteDialogOpen] = useState(false); const [isDeleting, setIsDeleting] = useState(false); // Use console error state from provider const { consoleError, dismissConsoleError, clearErrors } = useConsoleError(); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); const navigate = useNavigate(); const isMobile = useIsMobile(); const { toast } = useToast(); const { projectsPath } = useFSPaths(); const queryClient = useQueryClient(); const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile); const build = useBuildProject(projectId!); const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!); const { hasRunningSessions } = useProjectSessionStatus(projectId || ''); // Automatically fetch from remote to keep git status updated useGitFetch(projectId ? `${projectsPath}/${projectId}` : undefined); // Enable auto-build for previewable projects useAutoBuild({ projectId: projectId!, enabled: isPreviewable, debounceMs: 2000, }); const loadProject = useCallback(async () => { if (!projectId) return; try { const projectData = await projectsManager.getProject(projectId); setProject(projectData); // Clear console messages and error state when switching projects clearErrors(); } catch (error) { console.error('Failed to load project:', error); } finally { setIsLoading(false); } }, [projectId, projectsManager, clearErrors]); useEffect(() => { loadProject(); }, [loadProject]); // Reset view state when projectId changes useEffect(() => { if (projectId) { // Reset to preview tab if the new project is previewable, otherwise code setActiveTab(isPreviewable ? 'preview' : 'code'); // Reset mobile view to chat when switching projects setMobileView('chat'); } }, [projectId, isPreviewable]); // Switch away from preview mode if project is not previewable useEffect(() => { if (mobileView === 'preview' && !isPreviewable) { setMobileView('code'); } if (activeTab === 'preview' && !isPreviewable) { setActiveTab('code'); } }, [isPreviewable, mobileView, activeTab]); const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { setMobileView('chat'); } // Call the ChatPane's startNewSession function if (chatPaneRef.current) { chatPaneRef.current.startNewSession(); } }; const handleAILoadingChange = (loading: boolean) => { setIsAILoading(loading); }; // Handle first user interaction to enable audio context const handleFirstInteraction = () => { // This will be handled automatically by the useKeepAlive hook // when isAILoading becomes true after user interaction }; const handleDismissConsoleError = () => { dismissConsoleError(); }; const handleProjectDeleted = async () => { setProject(null); navigate('/'); }; const handleDeleteProject = async () => { if (!project) return; setIsDeleting(true); try { await projectsManager.deleteProject(project.id); // Invalidate the projects query to update the sidebar await queryClient.invalidateQueries({ queryKey: ['projects'] }); toast({ title: "Project deleted", description: `"${project.name}" has been permanently deleted.`, }); // Close the dialog first setDeleteDialogOpen(false); // Navigate back to home and notify parent navigate('/'); handleProjectDeleted(); } catch (error) { toast({ title: "Failed to delete project", description: error instanceof Error ? error.message : "An unexpected error occurred", variant: "destructive", }); } finally { setIsDeleting(false); } }; const isAnyLoading = isAILoading || build.isPending; if (!project && !isLoading) { return (

Project Not Found

); } if (isMobile) { return (
{project ? ( setGitHistoryOpen(true)} onDuplicate={() => setDuplicateDialogOpen(true)} onDelete={() => setDeleteDialogOpen(true)} onProjectDetails={() => setIsProjectDetailsOpen(true)} isAILoading={isAILoading} isAnyLoading={isAnyLoading || isDeleting} className="text-base" /> ) : ( )}
{project ? ( <> ) : ( <> )}
{/* Mobile Sidebar Overlay */} {isSidebarVisible && (
{/* Backdrop - only covers the area not occupied by the sidebar */}
setIsSidebarVisible(false)} /> {/* Sidebar - positioned above the backdrop */}
{ setProject(selectedProject); setIsSidebarVisible(false); // Always collapse sidebar on mobile navigation if (selectedProject) { setMobileView('chat'); // Switch to chat view when selecting a project navigate(`/project/${selectedProject.id}`); } else { navigate('/'); } }} onClose={() => setIsSidebarVisible(false)} />
)}
{mobileView === 'chat' && ( project ? ( ) : (
) )} {(mobileView === 'preview' || mobileView === 'code') && ( project ? ( ) : (
) )}
{isPreviewable && ( )}
{/* Dialogs */} {project && ( <> )}
); } return (
{/* Fixed Sidebar */}
{ setProject(selectedProject); if (selectedProject) { navigate(`/project/${selectedProject.id}`); } else { navigate('/'); } }} onToggleSidebar={() => setIsSidebarVisible(!isSidebarVisible)} className="h-full" />
{/* Main Content Area */}
{/* Chat Panel */}
{/* Chat Header */}
{/* Left side - Sidebar toggle (when collapsed) */}
{!isSidebarVisible && ( )} {/* Project title */}
{project ? ( setGitHistoryOpen(true)} onDuplicate={() => setDuplicateDialogOpen(true)} onDelete={() => setDeleteDialogOpen(true)} onProjectDetails={() => setIsProjectDetailsOpen(true)} isAILoading={isAILoading} isAnyLoading={isAnyLoading || isDeleting} className="text-lg" /> ) : ( )}
{/* Right side - Deploy and Sync buttons */}
{project ? ( <> ) : ( <> )}
{/* Chat Content */}
{project ? ( ) : (
)}
{/* Resizable Handle */} {/* Preview/Code Panel */}
{project ? ( setActiveTab(activeTab === 'preview' ? 'code' : 'preview') : undefined} isPreviewable={isPreviewable} /> ) : (
)}
{/* Dialogs */} {project && ( <> )}
); }