From 1c54a889cee6c57257652eb477c41cd84dbeb1d4 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 28 Dec 2025 17:51:37 -0600 Subject: [PATCH] Add git branch switcher --- src/components/BranchSwitcher.test.tsx | 210 +++++++++++++++++++ src/components/BranchSwitcher.tsx | 274 +++++++++++++++++++++++++ src/pages/ProjectView.tsx | 10 +- 3 files changed, 493 insertions(+), 1 deletion(-) create mode 100644 src/components/BranchSwitcher.test.tsx create mode 100644 src/components/BranchSwitcher.tsx diff --git a/src/components/BranchSwitcher.test.tsx b/src/components/BranchSwitcher.test.tsx new file mode 100644 index 00000000..6e4f2e15 --- /dev/null +++ b/src/components/BranchSwitcher.test.tsx @@ -0,0 +1,210 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { BranchSwitcher } from './BranchSwitcher'; +import { TestApp } from '@/test/TestApp'; + +// Mock hooks +vi.mock('@/hooks/useGitStatus', () => ({ + useGitStatus: vi.fn(), +})); + +vi.mock('@/hooks/useGit', () => ({ + useGit: vi.fn(), +})); + +vi.mock('@/hooks/useFSPaths', () => ({ + useFSPaths: vi.fn(() => ({ + projectsPath: '/projects', + })), +})); + +vi.mock('@/hooks/useToast', () => ({ + useToast: vi.fn(() => ({ + toast: vi.fn(), + })), +})); + +import { useGitStatus } from '@/hooks/useGitStatus'; +import { useGit } from '@/hooks/useGit'; + +describe('BranchSwitcher', () => { + const mockGit = { + checkout: vi.fn(), + branch: vi.fn(), + }; + + beforeEach(() => { + vi.clearAllMocks(); + (useGit as ReturnType).mockReturnValue({ git: mockGit }); + }); + + it('should not render when not in a git repository', () => { + (useGitStatus as ReturnType).mockReturnValue({ + data: { + isGitRepo: false, + currentBranch: null, + branches: [], + }, + }); + + const { container } = render( + + + + ); + + expect(container.firstChild).toBeNull(); + }); + + it('should render branch switcher button when in a git repository', () => { + (useGitStatus as ReturnType).mockReturnValue({ + data: { + isGitRepo: true, + currentBranch: 'main', + branches: ['main', 'develop'], + hasUncommittedChanges: false, + }, + }); + + render( + + + + ); + + expect(screen.getByRole('button')).toBeInTheDocument(); + expect(screen.getByText('main')).toBeInTheDocument(); + }); + + it('should show dropdown menu when clicked', async () => { + const user = userEvent.setup(); + (useGitStatus as ReturnType).mockReturnValue({ + data: { + isGitRepo: true, + currentBranch: 'main', + branches: ['main', 'develop', 'feature/test'], + hasUncommittedChanges: false, + }, + }); + + render( + + + + ); + + const button = screen.getByRole('button'); + await user.click(button); + + await waitFor(() => { + expect(screen.getByText('Switch Branch')).toBeInTheDocument(); + expect(screen.getByText('develop')).toBeInTheDocument(); + expect(screen.getByText('feature/test')).toBeInTheDocument(); + expect(screen.getByText('Create new branch')).toBeInTheDocument(); + }); + }); + + it('should show current branch with checkmark', async () => { + const user = userEvent.setup(); + (useGitStatus as ReturnType).mockReturnValue({ + data: { + isGitRepo: true, + currentBranch: 'main', + branches: ['main', 'develop'], + hasUncommittedChanges: false, + }, + }); + + render( + + + + ); + + const button = screen.getByRole('button'); + await user.click(button); + + await waitFor(() => { + expect(screen.getByText('Switch Branch')).toBeInTheDocument(); + expect(screen.getByText('develop')).toBeInTheDocument(); + }); + }); + + it('should open create branch dialog when clicking create new branch', async () => { + const user = userEvent.setup(); + (useGitStatus as ReturnType).mockReturnValue({ + data: { + isGitRepo: true, + currentBranch: 'main', + branches: ['main'], + hasUncommittedChanges: false, + }, + }); + + render( + + + + ); + + const button = screen.getByRole('button'); + await user.click(button); + + const createButton = await screen.findByText('Create new branch'); + await user.click(createButton); + + await waitFor(() => { + expect(screen.getByText('Create New Branch')).toBeInTheDocument(); + expect(screen.getByPlaceholderText('feature/my-new-feature')).toBeInTheDocument(); + }); + }); + + it('should handle branch creation', async () => { + const user = userEvent.setup(); + (useGitStatus as ReturnType).mockReturnValue({ + data: { + isGitRepo: true, + currentBranch: 'main', + branches: ['main'], + hasUncommittedChanges: false, + }, + }); + + mockGit.branch.mockResolvedValue(undefined); + mockGit.checkout.mockResolvedValue(undefined); + + render( + + + + ); + + // Open dropdown + const button = screen.getByRole('button'); + await user.click(button); + + // Click create new branch + const createButton = await screen.findByText('Create new branch'); + await user.click(createButton); + + // Enter branch name + const input = await screen.findByPlaceholderText('feature/my-new-feature'); + await user.type(input, 'feature/new-branch'); + + // Click create button + const createBranchButton = screen.getByRole('button', { name: /Create Branch/i }); + await user.click(createBranchButton); + + await waitFor(() => { + expect(mockGit.branch).toHaveBeenCalledWith({ + dir: '/projects/test-project', + ref: 'feature/new-branch', + }); + expect(mockGit.checkout).toHaveBeenCalledWith({ + dir: '/projects/test-project', + ref: 'feature/new-branch', + }); + }); + }); +}); diff --git a/src/components/BranchSwitcher.tsx b/src/components/BranchSwitcher.tsx new file mode 100644 index 00000000..a6871c55 --- /dev/null +++ b/src/components/BranchSwitcher.tsx @@ -0,0 +1,274 @@ +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { GitBranch, Check, Plus, Loader2 } from 'lucide-react'; +import { useGitStatus } from '@/hooks/useGitStatus'; +import { useGit } from '@/hooks/useGit'; +import { useFSPaths } from '@/hooks/useFSPaths'; +import { useToast } from '@/hooks/useToast'; +import { useQueryClient } from '@tanstack/react-query'; +import { cn } from '@/lib/utils'; + +interface BranchSwitcherProps { + projectId: string; + className?: string; +} + +export function BranchSwitcher({ projectId, className }: BranchSwitcherProps) { + const [isCreatingBranch, setIsCreatingBranch] = useState(false); + const [newBranchName, setNewBranchName] = useState(''); + const [isSwitching, setIsSwitching] = useState(false); + const [isCreating, setIsCreating] = useState(false); + + const { data: gitStatus } = useGitStatus(projectId); + const { git } = useGit(); + const { projectsPath } = useFSPaths(); + const { toast } = useToast(); + const queryClient = useQueryClient(); + + const handleSwitchBranch = async (branchName: string) => { + if (!gitStatus?.currentBranch || branchName === gitStatus.currentBranch) { + return; + } + + // Check for uncommitted changes + if (gitStatus.hasUncommittedChanges) { + toast({ + title: "Uncommitted changes", + description: "Please commit or discard your changes before switching branches.", + variant: "destructive", + }); + return; + } + + setIsSwitching(true); + + try { + const projectPath = `${projectsPath}/${projectId}`; + + await git.checkout({ + dir: projectPath, + ref: branchName, + }); + + toast({ + title: "Branch switched", + description: `Switched to branch "${branchName}"`, + }); + + // Invalidate git status to refresh the UI + await queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); + } catch (error) { + console.error('Failed to switch branch:', error); + toast({ + title: "Failed to switch branch", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } finally { + setIsSwitching(false); + } + }; + + const handleCreateBranch = async () => { + if (!newBranchName.trim()) { + toast({ + title: "Invalid branch name", + description: "Branch name cannot be empty", + variant: "destructive", + }); + return; + } + + // Validate branch name (basic validation) + if (!/^[a-zA-Z0-9_\-/.]+$/.test(newBranchName)) { + toast({ + title: "Invalid branch name", + description: "Branch name can only contain letters, numbers, hyphens, underscores, slashes, and dots", + variant: "destructive", + }); + return; + } + + // Check if branch already exists + if (gitStatus?.branches.includes(newBranchName)) { + toast({ + title: "Branch already exists", + description: `A branch named "${newBranchName}" already exists`, + variant: "destructive", + }); + return; + } + + setIsCreating(true); + + try { + const projectPath = `${projectsPath}/${projectId}`; + + // Create new branch + await git.branch({ + dir: projectPath, + ref: newBranchName, + }); + + // Switch to the new branch + await git.checkout({ + dir: projectPath, + ref: newBranchName, + }); + + toast({ + title: "Branch created", + description: `Created and switched to branch "${newBranchName}"`, + }); + + // Close dialog and reset state + setIsCreatingBranch(false); + setNewBranchName(''); + + // Invalidate git status to refresh the UI + await queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); + } catch (error) { + console.error('Failed to create branch:', error); + toast({ + title: "Failed to create branch", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } finally { + setIsCreating(false); + } + }; + + // Don't show if not a git repo + if (!gitStatus?.isGitRepo) { + return null; + } + + const currentBranch = gitStatus.currentBranch || 'main'; + const branches = gitStatus.branches || []; + + return ( + <> + + + + + + Switch Branch + + {branches.length > 0 ? ( + branches.map((branch) => ( + handleSwitchBranch(branch)} + disabled={branch === currentBranch || isSwitching} + className="cursor-pointer" + > +
+ {branch} + {branch === currentBranch && ( + + )} +
+
+ )) + ) : ( + No branches found + )} + + setIsCreatingBranch(true)} + disabled={isSwitching} + className="cursor-pointer" + > + + Create new branch + +
+
+ + + + + Create New Branch + + Create a new branch from the current branch "{currentBranch}". + + +
+
+ + setNewBranchName(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + handleCreateBranch(); + } + }} + autoFocus + /> +
+
+ + + + +
+
+ + ); +} diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 7340ccd4..efe12c87 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -20,6 +20,7 @@ import { DuplicateProjectDialog } from '@/components/DuplicateProjectDialog'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { GitSyncButton } from '@/components/git-sync'; import { DeployButton } from '@/components/deploy/DeployButton'; +import { BranchSwitcher } from '@/components/BranchSwitcher'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; import { useConsoleError } from '@/hooks/useConsoleError'; @@ -226,6 +227,10 @@ export function ProjectView() {
{project ? ( <> + + )}
@@ -453,10 +459,11 @@ export function ProjectView() { - {/* Right side - Deploy and Sync buttons */} + {/* Right side - Branch, Deploy and Sync buttons */}
{project ? ( <> + + )}