import React, { useEffect, useCallback, useState, useMemo } from 'react'; import { CodeAnnotation } from '@plannotator/ui/types'; import type { AvailableBranches, CompareTargetConfig, DiffOption, JjEvoLogEntry, RecentCommit, WorktreeInfo } from '@plannotator/shared/types'; import { buildFileTree, getAncestorPaths, getAllFolderPaths, getVisualFileOrder } from '../utils/buildFileTree'; import { FileTreeNodeItem } from './FileTreeNode'; import { BaseBranchPicker } from './BaseBranchPicker'; import { EvoLogPicker } from './EvoLogPicker'; import { DiffTypePicker } from './DiffTypePicker'; import { WorktreePicker } from './WorktreePicker'; import { getReviewSearchSideLabel, type ReviewSearchFileGroup, type ReviewSearchMatch } from '../utils/reviewSearch'; import type { DiffFile } from '../types'; import { OverlayScrollArea } from '@plannotator/ui/components/OverlayScrollArea'; interface FileTreeProps { files: DiffFile[]; activeFileIndex: number; onSelectFile: (index: number) => void; onDoubleClickFile?: (index: number) => void; annotations: CodeAnnotation[]; viewedFiles: Set; onToggleViewed?: (filePath: string) => void; hideViewedFiles?: boolean; onToggleHideViewed?: () => void; enableKeyboardNav?: boolean; diffOptions?: DiffOption[]; activeDiffType?: string; onSelectDiff?: (diffType: string) => void; isLoadingDiff?: boolean; width?: number; worktrees?: WorktreeInfo[]; activeWorktreePath?: string | null; onSelectWorktree?: (path: string | null) => void; currentBranch?: string; /** Compare target picker — base branch for Git, bookmark/revision for jj. */ availableBranches?: AvailableBranches; selectedBase?: string; detectedBase?: string; onSelectBase?: (branch: string) => void; compareTarget?: CompareTargetConfig; /** HEAD ancestry for the commit-baseline picker (git only, #709). */ recentCommits?: RecentCommit[]; /** Evolution log entries for the current jj change (jj-evolog mode only). */ jjEvologs?: JjEvoLogEntry[]; /** Default evolog commit ID to compare against (second evolog entry). */ detectedEvoBase?: string; stagedFiles?: Set; onCopyRawDiff?: () => void; canCopyRawDiff?: boolean; copyRawDiffStatus?: 'idle' | 'success' | 'error'; searchQuery?: string; isSearchOpen?: boolean; isSearchPending?: boolean; searchInputRef?: React.RefObject; onOpenSearch?: () => void; onSearchChange?: (value: string) => void; onSearchClear?: () => void; onSearchClose?: () => void; searchGroups?: ReviewSearchFileGroup[]; searchMatches?: ReviewSearchMatch[]; activeSearchMatchId?: string | null; onSelectSearchMatch?: (matchId: string) => void; onStepSearchMatch?: (direction: 1 | -1) => void; onSelectAllFiles?: () => void; isAllFilesActive?: boolean; scrollHighlightIndex?: number; /** Absolute repo root for the "Copy full path" context menu item. Null/undefined hides the option (e.g. PR review mode). */ repoRoot?: string | null; } export const FileTree: React.FC = ({ files, activeFileIndex, onSelectFile, onDoubleClickFile, annotations, viewedFiles, onToggleViewed, hideViewedFiles = false, onToggleHideViewed, enableKeyboardNav = true, diffOptions, activeDiffType, onSelectDiff, isLoadingDiff, width, worktrees, activeWorktreePath, onSelectWorktree, currentBranch, availableBranches, selectedBase, detectedBase, onSelectBase, compareTarget, recentCommits, jjEvologs, detectedEvoBase, stagedFiles, onCopyRawDiff, canCopyRawDiff = false, copyRawDiffStatus = 'idle', searchQuery = '', isSearchOpen = false, isSearchPending, searchInputRef, onOpenSearch, onSearchChange, onSearchClear, onSearchClose, searchGroups = [], searchMatches = [], activeSearchMatchId, onSelectSearchMatch, onStepSearchMatch, onSelectAllFiles, isAllFilesActive = false, scrollHighlightIndex, repoRoot, }) => { const isSearchVisible = !!onSearchChange && (isSearchOpen || !!searchQuery.trim()); const tree = useMemo(() => buildFileTree(files), [files]); const allFolderPaths = useMemo(() => getAllFolderPaths(tree), [tree]); const visualOrder = useMemo(() => getVisualFileOrder(tree), [tree]); // Keyboard navigation: j/k or arrow keys const handleKeyDown = useCallback((e: KeyboardEvent) => { if (!enableKeyboardNav) return; // Don't interfere with input fields if (e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement) { return; } // Yield keyboard nav when a floating overlay owns the focus — Radix // DropdownMenu / Popover / Dialog handle arrow keys themselves, and the // old native onSearchChange(e.target.value)} onKeyDown={(e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'f') { e.preventDefault(); return; } if (e.key === 'Enter' && searchMatches.length > 0 && !isSearchPending) { e.preventDefault(); onStepSearchMatch?.(e.shiftKey ? -1 : 1); } if (e.key === 'Escape') { e.preventDefault(); if (searchQuery) { onSearchClear?.(); } else { onSearchClose?.(); (e.target as HTMLInputElement).blur(); } } }} placeholder="Search diff..." className="w-full pl-7 py-1.5 pr-7 bg-muted rounded text-xs text-foreground placeholder:text-muted-foreground/50 focus:outline-none focus:ring-1 focus:ring-primary/50" />
{searchQuery.trim() && !isSearchPending && ( {searchMatches.length} )}
)} {/* Worktree + diff selectors — combined row when both present */} {((worktrees && worktrees.length > 0 && onSelectWorktree) || (diffOptions && diffOptions.length > 0 && onSelectDiff)) && (
{worktrees && worktrees.length > 0 && onSelectWorktree && (
)} {diffOptions && diffOptions.length > 0 && onSelectDiff && (
)}
)} {/* Evolog picker — only shown when jj-evolog diff type is active */} {activeDiffType === 'jj-evolog' && onSelectBase && selectedBase && jjEvologs && jjEvologs.length >= 2 && detectedEvoBase && (
from evolution
)} {/* Compare target picker — only relevant for base-dependent diff types (not evolog) */} {activeDiffType !== 'jj-evolog' && onSelectBase && selectedBase && detectedBase && availableBranches && activeDiffType && compareTarget?.diffTypes.includes(activeDiffType) && (
{compareTarget.picker.rowLabel}
)} {/* File tree or search results */}
{searchQuery.trim() ? ( isSearchPending ? (
Searching…
) : searchGroups.length > 0 ? ( searchGroups.map((group) => ( )) ) : (
No matches found
) ) : ( <> {onSelectAllFiles && ( )} {tree.map(node => ( ))} )}
{/* Footer */}
{onCopyRawDiff ? ( ) : ( )} +{files.reduce((sum, f) => sum + f.additions, 0)} -{files.reduce((sum, f) => sum + f.deletions, 0)}
); }; // --- Search result components --- function highlightQuery(text: string, query: string) { const trimmed = query.trim(); if (!trimmed) return text; const regex = new RegExp(`(${trimmed.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi'); const parts = text.split(regex); // split with a capturing group puts matches at odd indices (1, 3, 5...) return parts.map((part, i) => i % 2 === 1 ? {part} : part ); } const SearchFileGroup: React.FC<{ group: ReviewSearchFileGroup; searchQuery: string; activeSearchMatchId: string | null; onSelectMatch?: (matchId: string) => void; }> = ({ group, searchQuery, activeSearchMatchId, onSelectMatch }) => { const [collapsed, setCollapsed] = useState(false); const fileName = group.filePath.split('/').pop() || group.filePath; const dirPath = group.filePath.includes('/') ? group.filePath.slice(0, group.filePath.lastIndexOf('/')) : ''; return (
{/* File header */} {/* Match rows */} {!collapsed && (
{group.matches.map((match) => ( { onSelectMatch?.(match.id); }} /> ))}
)}
); }; const SearchMatchRow: React.FC<{ match: ReviewSearchMatch; searchQuery: string; isActive: boolean; onSelect: () => void; }> = ({ match, searchQuery, isActive, onSelect }) => { const sideLabel = getReviewSearchSideLabel(match.side); const sideColor = match.side === 'addition' ? 'text-success' : match.side === 'deletion' ? 'text-destructive' : 'text-muted-foreground/60'; return ( ); };