import { useMemo, useState } from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { listBranches, switchBranch, GitAuthError, getRepo } from '@/api/repos' import { fetchGitStatus } from '@/api/git' import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Checkbox } from '@/components/ui/checkbox' import { ConfirmDestructiveDialog } from '@/components/ui/confirm-destructive-dialog' import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu' import { Loader2, GitBranch, GitBranchPlus, GitMerge, Check, Plus, AlertCircle, Globe, MoreHorizontal, Pencil, Trash2 } from 'lucide-react' import { cn } from '@/lib/utils' import { showToast } from '@/lib/toast' import { useGit } from '@/hooks/useGit' import { GIT_UI_COLORS } from '@/lib/git-status-styles' import { CreateWorktreeDialog } from '@/components/repo/CreateWorktreeDialog' import { IntegrateBranchDialog } from '@/components/source-control/IntegrateBranchDialog' import { invalidateRepoGitCaches, setRepoGitStatusCaches } from '@/lib/queryInvalidation' interface BranchesTabProps { repoId: number currentBranch: string } interface BranchTarget { name: string upstream?: string } export function BranchesTab({ repoId, currentBranch }: BranchesTabProps) { const queryClient = useQueryClient() const [newBranchName, setNewBranchName] = useState('') const [searchQuery, setSearchQuery] = useState('') const [isCreating, setIsCreating] = useState(false) const [worktreeDialogOpen, setWorktreeDialogOpen] = useState(false) const [integrateDialogOpen, setIntegrateDialogOpen] = useState(false) const [renamingBranch, setRenamingBranch] = useState(null) const [renameValue, setRenameValue] = useState('') const [branchToDelete, setBranchToDelete] = useState(null) const [forceDelete, setForceDelete] = useState(false) const [deleteRemote, setDeleteRemote] = useState(false) const git = useGit(repoId) const { data: branches, isLoading, error, refetch } = useQuery({ queryKey: ['branches', repoId], queryFn: () => listBranches(repoId), staleTime: 30000, }) const { data: repo } = useQuery({ queryKey: ['repo', repoId], queryFn: () => getRepo(repoId), staleTime: 30000, }) const repoUrl = repo?.repoUrl ?? null const isRepoWorktree = repo?.isWorktree ?? false const filteredBranches = useMemo(() => { const allBranches = branches?.branches ?? [] if (!searchQuery.trim()) return allBranches const query = searchQuery.toLowerCase() return allBranches.filter((branch) => branch.name.toLowerCase().includes(query)) }, [branches, searchQuery]) const switchBranchMutation = useMutation({ mutationFn: async (branch: string) => { const updatedRepo = await switchBranch(repoId, branch) const status = await fetchGitStatus(repoId) return { updatedRepo, status } }, onSuccess: ({ updatedRepo, status }) => { queryClient.setQueryData(['repo', repoId], updatedRepo) setRepoGitStatusCaches(queryClient, repoId, status) invalidateRepoGitCaches(queryClient, repoId, { invalidateStatus: false }) refetch() showToast.success(`Switched to branch: ${updatedRepo.currentBranch}`) }, onError: (error) => { if (error instanceof GitAuthError) { showToast.error('Authentication failed. Please update your Git token in Settings.') } else { showToast.error(error.message || 'Failed to switch branch') } }, }) const handleCreateBranch = async () => { if (!newBranchName.trim()) return try { await git.createBranch.mutateAsync(newBranchName.trim()) setNewBranchName('') setIsCreating(false) refetch() } catch { // Error handled by mutation } } const startRename = (branch: BranchTarget) => { setRenamingBranch(branch.name) setRenameValue(branch.name) } const cancelRename = () => { setRenamingBranch(null) setRenameValue('') } const handleRename = async () => { const nextName = renameValue.trim() if (!renamingBranch || !nextName || nextName === renamingBranch) { cancelRename() return } try { await git.renameBranch.mutateAsync({ from: renamingBranch, to: nextName }) cancelRename() } catch { // Error handled by mutation } } const startDelete = (branch: BranchTarget) => { setBranchToDelete({ name: branch.name, upstream: branch.upstream }) setForceDelete(false) setDeleteRemote(false) } const closeDelete = () => { setBranchToDelete(null) setForceDelete(false) setDeleteRemote(false) } const handleDelete = async () => { if (!branchToDelete) return try { await git.deleteBranch.mutateAsync({ name: branchToDelete.name, force: forceDelete, deleteRemote: branchToDelete.upstream ? deleteRemote : false, }) closeDelete() } catch { // Error handled by mutation } } if (isLoading) { return (
) } if (error) { return (

Failed to load branches

{error.message}

) } const activeBranch = branches?.branches?.find(b => b.current)?.name || currentBranch const hasBranches = (branches?.branches?.length ?? 0) > 0 return (
{isCreating ? (
setNewBranchName(e.target.value)} className="h-10 md:h-8 md:text-sm" autoFocus onKeyDown={(e) => { if (e.key === 'Enter') handleCreateBranch() if (e.key === 'Escape') { setIsCreating(false) setNewBranchName('') } }} />
) : (
{hasBranches && ( setSearchQuery(e.target.value)} className="h-10 md:h-8 md:text-sm flex-1 min-w-0" /> )} {repoUrl && ( )} {isRepoWorktree && ( )}
)}
{switchBranchMutation.isPending && (
)} {filteredBranches.length > 0 ? (
{filteredBranches.map((branch) => { const isCurrent = branch.name === activeBranch || branch.name === `remotes/${activeBranch}` const isRemote = branch.type === 'remote' const checkoutName = isRemote ? branch.name.replace(/^remotes\/[^/]+\//, '') : branch.name const isCheckedOutElsewhere = branch.isWorktree && !isCurrent const handleClick = () => { if (isCurrent || isCheckedOutElsewhere) return switchBranchMutation.mutate(checkoutName) } if (renamingBranch === branch.name) { return (
setRenameValue(e.target.value)} className="h-10 md:h-8 md:text-sm flex-1 min-w-0" aria-label={`New name for branch ${renamingBranch}`} autoFocus onKeyDown={(e) => { if (e.key === 'Enter') handleRename() if (e.key === 'Escape') cancelRename() }} />
) } return (
{!isRemote && ( startRename(branch)} disabled={isCheckedOutElsewhere}> Rename startDelete(branch)} disabled={isCurrent || !!branch.isWorktree} > Delete )}
) })}
) : (
{searchQuery.trim() ? (

No branches match "{searchQuery.trim()}"

) : (

No branches found

)}
)}
{ if (!open) closeDelete() }} onConfirm={handleDelete} onCancel={closeDelete} title={`Delete branch "${branchToDelete?.name ?? ''}"?`} description="This removes the local branch. This action cannot be undone." confirmLabel="Delete" pendingLabel="Deleting..." isPending={git.deleteBranch.isPending} >
{branchToDelete?.upstream && ( )}
) }