'use client'; import { memo, useMemo, useState, useCallback, useEffect } from 'react'; import { PanelRoot, PanelBody, PanelHeaderBarSplit } from './panel-primitives'; import { IconArrowBackUp, IconPlus, IconMinus, IconCheck, IconGitCommit, IconGitPullRequest, IconLoader2, IconPencil, IconCloudDownload, IconCloudUpload, IconEye, IconChevronDown, IconGitBranch, IconGitCherryPick, IconGitMerge, IconArrowRight, } from '@tabler/icons-react'; import { Button } from '@kandev/ui/button'; import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip'; import { HoverCard, HoverCardContent, HoverCardTrigger } from '@kandev/ui/hover-card'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter, DialogClose, } from '@kandev/ui/dialog'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from '@kandev/ui/dropdown-menu'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from '@kandev/ui/alert-dialog'; import { Checkbox } from '@kandev/ui/checkbox'; import { Label } from '@kandev/ui/label'; import { Textarea } from '@kandev/ui/textarea'; import { LineStat } from '@/components/diff-stat'; import { cn } from '@/lib/utils'; import { useAppStore } from '@/components/state-provider'; import { useSessionGitStatus } from '@/hooks/domains/session/use-session-git-status'; import { useSessionCommits } from '@/hooks/domains/session/use-session-commits'; import { useGitOperations } from '@/hooks/use-git-operations'; import { useSessionFileReviews } from '@/hooks/use-session-file-reviews'; import { useCumulativeDiff } from '@/hooks/domains/session/use-cumulative-diff'; import { hashDiff, normalizeDiffContent } from '@/components/review/types'; import type { FileInfo } from '@/lib/state/store'; import { useToast } from '@/components/toast-provider'; import { useIsTaskArchived, ArchivedPanelPlaceholder } from './task-archived-context'; import { FileStatusIcon } from './file-status-icon'; const splitPath = (path: string) => { const lastSlash = path.lastIndexOf('/'); if (lastSlash === -1) return { folder: '', file: path }; return { folder: path.slice(0, lastSlash), file: path.slice(lastSlash + 1), }; }; type ChangedFile = { path: string; status: FileInfo['status']; staged: boolean; plus: number | undefined; minus: number | undefined; oldPath: string | undefined; }; type ChangesPanelProps = { onOpenFile: (path: string) => void; onOpenCommitDetail?: (sha: string) => void; onOpenDiffAll?: () => void; onOpenReview?: () => void; }; // --- Timeline section dot colors --- const DOT_COLORS = { unstaged: 'bg-yellow-500', staged: 'bg-emerald-500', commits: 'bg-blue-500', action: 'bg-muted-foreground/25', } as const; // --- Timeline visual components --- function TimelineDot({ color }: { color: string }) { return (
); } function TimelineSection({ dotColor, label, count, action, isLast, children, }: { dotColor: string; label?: string; count?: number; action?: React.ReactNode; isLast?: boolean; children?: React.ReactNode; }) { return (
{/* Vertical line + dot */}
{!isLast && (
)}
{/* Content */}
{/* Header */} {label && (
{label} {typeof count === 'number' && count > 0 && ( ({count}) )} {action}
)} {/* Children (file list, buttons, etc.) */} {children}
); } // --- File row --- function FileRow({ file, isPending, onOpenFile, onStage, onUnstage, onDiscard, onEditFile, }: { file: ChangedFile; isPending: boolean; onOpenFile: (path: string) => void; onStage: (path: string) => void; onUnstage: (path: string) => void; onDiscard: (path: string) => void; onEditFile: (path: string) => void; }) { const { folder, file: name } = splitPath(file.path); return (
  • onOpenFile(file.path)} >
    {isPending ? (
    ) : file.staged ? ( ) : ( )}
    Discard changes Edit
  • ); } // --- Main component --- const ChangesPanel = memo(function ChangesPanel({ onOpenFile, onOpenCommitDetail, onOpenDiffAll, onOpenReview }: ChangesPanelProps) { const isArchived = useIsTaskArchived(); const [showDiscardDialog, setShowDiscardDialog] = useState(false); const [fileToDiscard, setFileToDiscard] = useState(null); const [pendingStageFiles, setPendingStageFiles] = useState>(new Set()); // Commit dialog state const [commitDialogOpen, setCommitDialogOpen] = useState(false); const [commitMessage, setCommitMessage] = useState(''); // PR dialog state const [prDialogOpen, setPrDialogOpen] = useState(false); const [prTitle, setPrTitle] = useState(''); const [prBody, setPrBody] = useState(''); const [prDraft, setPrDraft] = useState(true); const activeSessionId = useAppStore((state) => state.tasks.activeSessionId); const taskTitle = useAppStore((state) => { if (!state.tasks.activeTaskId) return undefined; return state.kanban.tasks.find((t: { id: string }) => t.id === state.tasks.activeTaskId)?.title; }); const baseBranch = useAppStore((state) => { if (!activeSessionId) return undefined; return state.taskSessions.items[activeSessionId]?.base_branch; }); const displayBranch = useAppStore((state) => { if (!activeSessionId) return null; const gs = state.gitStatus.bySessionId[activeSessionId]; return gs?.branch ?? null; }); const gitStatus = useSessionGitStatus(activeSessionId); const { commits } = useSessionCommits(activeSessionId ?? null); const gitOps = useGitOperations(activeSessionId ?? null); const { toast } = useToast(); const { reviews } = useSessionFileReviews(activeSessionId); const { diff: cumulativeDiff } = useCumulativeDiff(activeSessionId); const aheadCount = gitStatus?.ahead ?? 0; const behindCount = gitStatus?.behind ?? 0; // Clean base branch name for display const baseBranchDisplay = useMemo(() => { if (!baseBranch) return 'main'; return baseBranch.replace(/^origin\//, ''); }, [baseBranch]); // Convert git status files to array const changedFiles = useMemo(() => { if (!gitStatus?.files || Object.keys(gitStatus.files).length === 0) { return []; } return (Object.values(gitStatus.files) as FileInfo[]).map((file: FileInfo) => ({ path: file.path, status: file.status, staged: file.staged, plus: file.additions, minus: file.deletions, oldPath: file.old_path, })); }, [gitStatus]); // Split into unstaged and staged const unstagedFiles = useMemo(() => changedFiles.filter((f) => !f.staged), [changedFiles]); const stagedFiles = useMemo(() => changedFiles.filter((f) => f.staged), [changedFiles]); // Review progress const { reviewedCount, totalFileCount } = useMemo(() => { const paths = new Set(); if (gitStatus?.files) { for (const [path, file] of Object.entries(gitStatus.files)) { const diff = file.diff ? normalizeDiffContent(file.diff) : ''; if (diff) paths.add(path); } } if (cumulativeDiff?.files) { for (const [path, file] of Object.entries(cumulativeDiff.files)) { if (paths.has(path)) continue; const diff = file.diff ? normalizeDiffContent(file.diff) : ''; if (diff) paths.add(path); } } let reviewed = 0; for (const path of paths) { const state = reviews.get(path); if (!state?.reviewed) continue; let diffContent = ''; const uncommittedFile = gitStatus?.files?.[path]; if (uncommittedFile?.diff) { diffContent = normalizeDiffContent(uncommittedFile.diff); } else if (cumulativeDiff?.files?.[path]?.diff) { diffContent = normalizeDiffContent(cumulativeDiff.files[path].diff!); } if (diffContent && state.diffHash && state.diffHash !== hashDiff(diffContent)) { continue; } reviewed++; } return { reviewedCount: reviewed, totalFileCount: paths.size }; }, [gitStatus, cumulativeDiff, reviews]); const reviewProgressPercent = totalFileCount > 0 ? (reviewedCount / totalFileCount) * 100 : 0; // Clear pending spinners when git status updates useEffect(() => { if (pendingStageFiles.size > 0) { setPendingStageFiles(new Set()); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [changedFiles]); // --- Handlers --- const handleGitOperation = useCallback( async ( operation: () => Promise<{ success: boolean; output: string; error?: string }>, operationName: string, ) => { try { const result = await operation(); if (result.success) { toast({ title: `${operationName} successful`, description: result.output.slice(0, 200) || `${operationName} completed`, variant: 'success', }); } else { toast({ title: `${operationName} failed`, description: result.error || 'An error occurred', variant: 'error', }); } } catch (e) { toast({ title: `${operationName} failed`, description: e instanceof Error ? e.message : 'An unexpected error occurred', variant: 'error', }); } }, [toast], ); const handlePull = useCallback(() => { handleGitOperation(() => gitOps.pull(), 'Pull'); }, [handleGitOperation, gitOps]); const handleRebase = useCallback(() => { const targetBranch = baseBranch?.replace(/^origin\//, '') || 'main'; handleGitOperation(() => gitOps.rebase(targetBranch), 'Rebase'); }, [handleGitOperation, gitOps, baseBranch]); const handlePush = useCallback(() => { handleGitOperation(() => gitOps.push(), 'Push'); }, [handleGitOperation, gitOps]); const handleStageAll = useCallback(async () => { try { await gitOps.stage(); } catch { // Toast handled by gitOps } }, [gitOps]); const handleStage = useCallback(async (path: string) => { setPendingStageFiles((prev) => new Set(prev).add(path)); try { await gitOps.stage([path]); } catch { setPendingStageFiles((prev) => { const next = new Set(prev); next.delete(path); return next; }); } }, [gitOps]); const handleUnstage = useCallback(async (path: string) => { setPendingStageFiles((prev) => new Set(prev).add(path)); try { await gitOps.unstage([path]); } catch { setPendingStageFiles((prev) => { const next = new Set(prev); next.delete(path); return next; }); } }, [gitOps]); const handleDiscardClick = useCallback((filePath: string) => { setFileToDiscard(filePath); setShowDiscardDialog(true); }, []); const handleDiscardConfirm = useCallback(async () => { if (!fileToDiscard) return; try { const result = await gitOps.discard([fileToDiscard]); if (!result.success) { toast({ title: 'Failed to discard changes', description: result.error || 'An unknown error occurred', variant: 'error', }); } } catch (error) { toast({ title: 'Failed to discard changes', description: error instanceof Error ? error.message : 'An unknown error occurred', variant: 'error', }); } finally { setShowDiscardDialog(false); setFileToDiscard(null); } }, [fileToDiscard, gitOps, toast]); // Commit dialog const handleOpenCommitDialog = useCallback(() => { setCommitMessage(''); setCommitDialogOpen(true); }, []); const handleCommit = useCallback(async () => { if (!commitMessage.trim()) return; setCommitDialogOpen(false); await handleGitOperation( () => gitOps.commit(commitMessage.trim(), false), 'Commit', ); setCommitMessage(''); }, [commitMessage, handleGitOperation, gitOps]); // PR dialog const handleOpenPRDialog = useCallback(() => { setPrTitle(taskTitle || ''); setPrBody(''); setPrDialogOpen(true); }, [taskTitle]); const handleCreatePR = useCallback(async () => { if (!prTitle.trim()) return; setPrDialogOpen(false); try { const result = await gitOps.createPR(prTitle.trim(), prBody.trim(), baseBranch, prDraft); if (result.success) { toast({ title: prDraft ? 'Draft PR created' : 'PR created', description: result.pr_url || 'PR created successfully', variant: 'success', }); if (result.pr_url) window.open(result.pr_url, '_blank'); } else { toast({ title: 'Create PR failed', description: result.error || 'An error occurred', variant: 'error', }); } } catch (e) { toast({ title: 'Create PR failed', description: e instanceof Error ? e.message : 'An error occurred', variant: 'error', }); } setPrTitle(''); setPrBody(''); }, [prTitle, prBody, baseBranch, prDraft, gitOps, toast]); // Determine which sections to show const hasUnstaged = unstagedFiles.length > 0; const hasStaged = stagedFiles.length > 0; const hasCommits = commits.length > 0; const hasChanges = changedFiles.length > 0; const hasAnything = hasUnstaged || hasStaged || hasCommits; // Compute stats for commit dialog const { stagedFileCount, stagedAdditions, stagedDeletions } = useMemo(() => { let additions = 0; let deletions = 0; const count = stagedFiles.length; if (gitStatus?.files && count > 0) { for (const file of Object.values(gitStatus.files) as FileInfo[]) { if (file.staged) { additions += file.additions || 0; deletions += file.deletions || 0; } } } return { stagedFileCount: count, stagedAdditions: additions, stagedDeletions: deletions }; }, [gitStatus, stagedFiles]); // Determine how many timeline sections exist after commits for "isLast" logic const showActionButtons = hasCommits; const lastTimelineSection = hasCommits ? 'action' : hasStaged ? 'staged' : 'unstaged'; if (isArchived) return ; return ( {/* Toolbar header */} ) : undefined } right={ <> {displayBranch && (
    Your code lives in: and will be merged into:
    {displayBranch}
    {baseBranchDisplay}
    )} Pull {behindCount > 0 && ( {behindCount} behind )} Rebase {behindCount > 0 && ( {behindCount} behind )} } /> {/* Scrollable content */}
    {/* Empty state */} {!hasAnything && (
    Your changed files will appear here
    )} {/* Timeline */} {hasAnything && (
    {/* UNSTAGED section */} {hasUnstaged && ( Stage all } >
      {unstagedFiles.map((file) => ( ))}
    )} {/* STAGED section — only show when there are staged files */} {hasStaged && ( Commit } >
      {stagedFiles.map((file) => ( ))}
    )} {/* COMMITS section */} {hasCommits && (
      {commits.map((commit) => (
    • onOpenCommitDetail?.(commit.commit_sha)} > {commit.commit_sha.slice(0, 7)} {commit.commit_message} +{commit.insertions} {' '} -{commit.deletions}
    • ))}
    )} {/* Action buttons (Create PR / Push) — connected to timeline */} {showActionButtons && (
    )}
    )}
    {/* Review progress — pinned to bottom */} {totalFileCount > 0 && (
    {reviewedCount}/{totalFileCount} reviewed
    {reviewedCount} of {totalFileCount} files reviewed )} {/* Discard confirmation dialog */} Discard changes? This will permanently discard all changes to{' '} {fileToDiscard}. This action cannot be undone. Cancel Discard {/* Commit Dialog */} Commit Changes
    {stagedFileCount > 0 ? ( {stagedFileCount}{' '} staged file{stagedFileCount !== 1 ? 's' : ''} {(stagedAdditions > 0 || stagedDeletions > 0) && ( (+{stagedAdditions} {' / '} -{stagedDeletions}) )} ) : ( No staged files to commit )}