import { useState, useEffect, useCallback } from 'react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger, } from '@/components/ui/dialog'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@/components/ui/alert-dialog'; import { Badge } from '@/components/ui/badge'; import { GitBranch, Plus, Trash2, Check, Loader2, ArrowUpRight, } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; import { useFSPaths } from '@/hooks/useFSPaths'; import { useToast } from '@/hooks/useToast'; import { cn } from '@/lib/utils'; interface BranchInfo { name: string; isCurrent: boolean; isRemote: boolean; remoteName?: string; commitId?: string; ahead?: number; behind?: number; } interface BranchManagerProps { projectId: string; currentBranch: string | null; onBranchChange?: () => void; } export function BranchManager({ projectId, currentBranch, onBranchChange }: BranchManagerProps) { const [branches, setBranches] = useState([]); const [isLoading, setIsLoading] = useState(true); const [newBranchName, setNewBranchName] = useState(''); const [isCreating, setIsCreating] = useState(false); const [isCreateDialogOpen, setIsCreateDialogOpen] = useState(false); const [deletingBranch, setDeletingBranch] = useState(null); const [switchingToBranch, setSwitchingToBranch] = useState(null); const { git } = useGit(); const { projectsPath } = useFSPaths(); const { toast } = useToast(); const projectPath = `${projectsPath}/${projectId}`; const loadBranches = useCallback(async () => { setIsLoading(true); try { // Get local branches const localBranches = await git.listBranches({ dir: projectPath, }); // Get remote branches let remoteBranches: string[] = []; try { remoteBranches = await git.listBranches({ dir: projectPath, remote: 'origin', }); } catch { // No remote or error fetching remote branches } // Get current branch const current = await git.currentBranch({ dir: projectPath }).catch(() => null); // Build branch info const branchInfos: BranchInfo[] = []; // Add local branches for (const branch of localBranches) { const isCurrent = branch === current; let commitId: string | undefined; try { commitId = await git.resolveRef({ dir: projectPath, ref: `refs/heads/${branch}`, }); } catch { // Skip branches we can't resolve } branchInfos.push({ name: branch, isCurrent, isRemote: false, commitId, }); } // Add remote branches for (const branch of remoteBranches) { // Skip if we already have this as a local branch if (localBranches.includes(branch)) continue; let commitId: string | undefined; try { commitId = await git.resolveRef({ dir: projectPath, ref: `refs/remotes/origin/${branch}`, }); } catch { // Skip branches we can't resolve } branchInfos.push({ name: branch, isCurrent: false, isRemote: true, remoteName: 'origin', commitId, }); } setBranches(branchInfos); } catch (error) { console.error('Failed to load branches:', error); toast({ title: 'Failed to load branches', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setIsLoading(false); } }, [git, projectPath, toast]); useEffect(() => { loadBranches(); }, [projectId, currentBranch, loadBranches]); const handleCreateBranch = async () => { if (!newBranchName.trim()) { toast({ title: 'Invalid branch name', description: 'Please enter a branch name', variant: 'destructive', }); return; } // Validate branch name const invalidChars = /[~^: \\?*[\]]/; if (invalidChars.test(newBranchName)) { toast({ title: 'Invalid branch name', description: 'Branch name contains invalid characters', variant: 'destructive', }); return; } setIsCreating(true); try { // Get current HEAD to base the new branch on const currentRef = await git.resolveRef({ dir: projectPath, ref: 'HEAD', }); // Create the new branch await git.branch({ dir: projectPath, ref: newBranchName.trim(), object: currentRef, }); toast({ title: 'Branch created', description: `Created branch "${newBranchName}"`, }); setNewBranchName(''); setIsCreateDialogOpen(false); await loadBranches(); onBranchChange?.(); } catch (error) { toast({ title: 'Failed to create branch', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setIsCreating(false); } }; const handleSwitchBranch = async (branchName: string) => { setSwitchingToBranch(branchName); try { await git.checkout({ dir: projectPath, ref: branchName, force: true, }); toast({ title: 'Branch switched', description: `Switched to branch "${branchName}"`, }); await loadBranches(); onBranchChange?.(); } catch (error) { toast({ title: 'Failed to switch branch', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setSwitchingToBranch(null); } }; const handleDeleteBranch = async (branchName: string) => { setDeletingBranch(branchName); try { await git.deleteBranch({ dir: projectPath, ref: branchName, }); toast({ title: 'Branch deleted', description: `Deleted branch "${branchName}"`, }); await loadBranches(); onBranchChange?.(); } catch (error) { toast({ title: 'Failed to delete branch', description: error instanceof Error ? error.message : 'Unknown error', variant: 'destructive', }); } finally { setDeletingBranch(null); } }; const localBranches = branches.filter(b => !b.isRemote); const remoteBranches = branches.filter(b => b.isRemote); return (
{/* Header with create button */}

Branches

Create New Branch Create a new branch from the current HEAD
setNewBranchName(e.target.value)} onKeyDown={(e) => { if (e.key === 'Enter' && !isCreating) { handleCreateBranch(); } }} autoFocus />
{currentBranch && (
Creating from: {currentBranch}
)}
{isLoading ? (
) : (
{/* Local Branches */} {localBranches.length > 0 && (
Local Branches
{localBranches.map((branch) => ( ))}
)} {/* Remote Branches */} {remoteBranches.length > 0 && (
Remote Branches
{remoteBranches.map((branch) => ( ))}
)} {/* Empty state */} {localBranches.length === 0 && remoteBranches.length === 0 && (

No branches found

)}
)}
); } interface BranchItemProps { branch: BranchInfo; onSwitch: (name: string) => void; onDelete: (name: string) => void; isSwitching: boolean; isDeleting: boolean; } function BranchItem({ branch, onSwitch, onDelete, isSwitching, isDeleting }: BranchItemProps) { const [showDeleteDialog, setShowDeleteDialog] = useState(false); return ( <>
{/* Branch icon and name */}
{branch.isCurrent ? ( ) : ( )}
{branch.name} {branch.isRemote && ( )}
{branch.commitId && (
{branch.commitId.substring(0, 7)}
)}
{/* Current badge */} {branch.isCurrent && ( Current )} {/* Actions */} {!branch.isCurrent && !branch.isRemote && (
)}
{/* Delete confirmation dialog */} Delete Branch Are you sure you want to delete the branch {branch.name}? This action cannot be undone. Cancel { onDelete(branch.name); setShowDeleteDialog(false); }} className="bg-destructive text-destructive-foreground hover:bg-destructive/90" > Delete Branch ); }