Add file preview dialog and line navigation in git diff viewer

This commit is contained in:
Chris Scott committed 2025-11-27 10:52:05 -05:00
1 parent ed82b99236
commit dcf2dd68e7
7 files changed
+272 -57

No files matched your search

@@ -1,5 +1,5 @@
import { useFileDiff } from '@/api/git'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, Plus, Minus, ArrowLeft } from 'lucide-react'
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, Plus, Minus, ArrowLeft, ExternalLink } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { cn } from '@/lib/utils'
import type { GitFileStatusType } from '@/types/git'
@@ -8,6 +8,7 @@ interface FileDiffViewProps {
repoId: number
filePath: string
onBack?: () => void
onOpenFile?: (path: string, lineNumber?: number) => void
isMobile?: boolean
}
@@ -59,7 +60,7 @@ const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: st
copied: { icon: FileText, color: 'text-purple-500', bgColor: 'bg-purple-500/10', label: 'Copied' },
}
function DiffLineComponent({ line, showLineNumbers }: { line: DiffLine; showLineNumbers: boolean }) {
function DiffLineComponent({ line, showLineNumbers, onLineClick }: { line: DiffLine; showLineNumbers: boolean; onLineClick?: (lineNumber: number) => void }) {
if (line.type === 'header') {
return (
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate">
@@ -88,8 +89,18 @@ function DiffLineComponent({ line, showLineNumbers }: { line: DiffLine; showLine
? 'text-red-400'
: 'text-foreground'
const lineNumber = line.newLineNumber ?? line.oldLineNumber
const isClickable = onLineClick && lineNumber !== undefined
return (
<div className={cn('flex font-mono text-sm', bgClass)}>
<div
className={cn(
'flex font-mono text-sm',
bgClass,
isClickable && 'cursor-pointer hover:bg-accent/50 transition-colors'
)}
onClick={() => isClickable && lineNumber !== undefined && onLineClick(lineNumber)}
>
{showLineNumbers && (
<div className="flex-shrink-0 w-20 flex text-xs text-muted-foreground select-none">
<span className="w-10 px-2 text-right border-r border-border/50">
@@ -111,7 +122,7 @@ function DiffLineComponent({ line, showLineNumbers }: { line: DiffLine; showLine
)
}
export function FileDiffView({ repoId, filePath, onBack, isMobile = false }: FileDiffViewProps) {
export function FileDiffView({ repoId, filePath, onBack, onOpenFile, isMobile = false }: FileDiffViewProps) {
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath)
const fileName = filePath.split('/').pop() || filePath
@@ -159,8 +170,23 @@ export function FileDiffView({ repoId, filePath, onBack, isMobile = false }: Fil
)}
<Icon className={cn('w-4 h-4 flex-shrink-0', config.color)} />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium text-foreground truncate">{fileName}</div>
{dirPath && <div className="text-xs text-muted-foreground truncate">{dirPath}</div>}
{onOpenFile ? (
<button
onClick={() => onOpenFile(filePath)}
className="text-left group"
>
<div className="text-sm font-medium text-foreground truncate group-hover:text-primary group-hover:underline flex items-center gap-1">
{fileName}
<ExternalLink className="w-3 h-3 opacity-0 group-hover:opacity-100 transition-opacity" />
</div>
{dirPath && <div className="text-xs text-muted-foreground truncate">{dirPath}</div>}
</button>
) : (
<>
<div className="text-sm font-medium text-foreground truncate">{fileName}</div>
{dirPath && <div className="text-xs text-muted-foreground truncate">{dirPath}</div>}
</>
)}
</div>
<div className="flex items-center gap-2 text-xs flex-shrink-0">
<span className={cn('px-1.5 py-0.5 rounded', config.bgColor, config.color)}>
@@ -191,6 +217,7 @@ export function FileDiffView({ repoId, filePath, onBack, isMobile = false }: Fil
key={index}
line={line}
showLineNumbers={!isMobile}
onLineClick={onOpenFile ? (lineNum) => onOpenFile(filePath, lineNum) : undefined}
/>
))}
</div>
@@ -1,9 +1,9 @@
import { useState, useCallback } from 'react'
import { useState, useCallback, useRef, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Download, Copy, X, Edit3, Save, X as XIcon } from 'lucide-react'
import { Download, X, Edit3, Save, X as XIcon } from 'lucide-react'
import type { FileInfo } from '@/types/files'
import { API_BASE_URL } from '@/config'
import { VirtualizedTextView } from '@/components/ui/virtualized-text-view'
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
const API_BASE = API_BASE_URL
@@ -14,15 +14,34 @@ interface FilePreviewProps {
hideHeader?: boolean
isMobileModal?: boolean
onCloseModal?: () => void
onFileSaved?: () => void
initialLineNumber?: number
}
export function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal }: FilePreviewProps) {
export function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) {
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
const [editContent, setEditContent] = useState('')
const [isSaving, setIsSaving] = useState(false)
const [hasVirtualizedChanges, setHasVirtualizedChanges] = useState(false)
const [highlightedLine, setHighlightedLine] = useState<number | undefined>(initialLineNumber)
const virtualizedRef = useRef<VirtualizedTextViewHandle>(null)
const contentRef = useRef<HTMLDivElement>(null)
const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/')
useEffect(() => {
if (initialLineNumber && contentRef.current && !shouldVirtualize) {
const lineHeight = 20
const scrollPosition = (initialLineNumber - 1) * lineHeight
setHighlightedLine(initialLineNumber)
setTimeout(() => {
contentRef.current?.scrollTo({ top: scrollPosition, behavior: 'smooth' })
}, 100)
setTimeout(() => {
setHighlightedLine(undefined)
}, 3000)
}
}, [initialLineNumber, shouldVirtualize, file.content])
const formatFileSize = (bytes: number) => {
if (bytes === 0) return '0 Bytes'
@@ -58,17 +77,6 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
}
}
const handleCopyContent = async () => {
if (file.content) {
try {
const content = decodeBase64(file.content)
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
}
const handleEdit = () => {
if (shouldVirtualize) {
setViewMode('edit')
@@ -77,16 +85,14 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
return
}
if (file.content) {
try {
const content = decodeBase64(file.content)
setEditContent(content)
setViewMode('edit')
const event = new CustomEvent('editModeChange', { detail: { isEditing: true } })
window.dispatchEvent(event)
} catch (err) {
console.error('Failed to load content for editing:', err)
}
try {
const content = file.content ? decodeBase64(file.content) : ''
setEditContent(content)
setViewMode('edit')
const event = new CustomEvent('editModeChange', { detail: { isEditing: true } })
window.dispatchEvent(event)
} catch (err) {
console.error('Failed to load content for editing:', err)
}
}
@@ -108,6 +114,7 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
window.dispatchEvent(editEvent)
const event = new CustomEvent('fileSaved', { detail: { path: file.path, content: editContent } })
window.dispatchEvent(event)
onFileSaved?.()
} catch (err) {
console.error('Failed to save file:', err)
} finally {
@@ -133,7 +140,8 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
window.dispatchEvent(editEvent)
const event = new CustomEvent('fileSaved', { detail: { path: file.path } })
window.dispatchEvent(event)
}, [file.path])
onFileSaved?.()
}, [file.path, onFileSaved])
const isTextFile = file.mimeType?.startsWith('text/') ||
['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '')
@@ -154,12 +162,14 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
if (shouldVirtualize && isTextFile) {
return (
<VirtualizedTextView
ref={virtualizedRef}
filePath={file.path}
totalLines={file.totalLines}
editable={viewMode === 'edit'}
onSaveStateChange={handleVirtualizedSaveStateChange}
onSave={handleVirtualizedSave}
className="h-full"
initialLineNumber={initialLineNumber}
/>
)
}
@@ -183,10 +193,28 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
try {
const textContent = decodeBase64(file.content)
const lines = textContent.split('\n')
return (
<pre className="pb-[200px] text-sm bg-muted text-foreground rounded whitespace-pre-wrap font-mono break-words overflow-x-hidden">
<code>{textContent}</code>
</pre>
<div className="pb-[200px] text-sm bg-muted text-foreground rounded font-mono overflow-x-hidden">
{lines.map((line, index) => {
const lineNum = index + 1
const isHighlighted = highlightedLine === lineNum
return (
<div
key={index}
className={`flex transition-colors duration-300 ${isHighlighted ? 'bg-yellow-500/30' : ''}`}
style={{ minHeight: '20px', lineHeight: '20px' }}
>
<span className="w-12 flex-shrink-0 text-right pr-3 text-muted-foreground select-none border-r border-border/50 text-xs">
{lineNum}
</span>
<pre className="flex-1 pl-3 whitespace-pre-wrap break-all">
{line || ' '}
</pre>
</div>
)
})}
</div>
)
} catch {
return (
@@ -204,7 +232,18 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
)
}
const showSaveButton = viewMode === 'edit' && !shouldVirtualize
const handleVirtualizedSaveClick = async () => {
if (virtualizedRef.current) {
setIsSaving(true)
try {
await virtualizedRef.current.save()
} finally {
setIsSaving(false)
}
}
}
const showSaveButton = viewMode === 'edit'
const showCancelButton = viewMode === 'edit'
return (
@@ -231,37 +270,31 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
{isTextFile && viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleEdit} className="h-7 w-7 p-0">
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleEdit() }} className="h-7 w-7 p-0">
<Edit3 className="w-3 h-3" />
</Button>
)}
{showSaveButton && (
<Button variant="outline" size="sm" onClick={handleSave} disabled={isSaving} className="border-green-600 bg-green-600/10 text-green-600 hover:bg-green-600/20 h-7 w-7 p-0">
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); shouldVirtualize ? handleVirtualizedSaveClick() : handleSave() }} disabled={isSaving || (shouldVirtualize && !hasVirtualizedChanges)} className="border-green-600 bg-green-600/10 text-green-600 hover:bg-green-600/20 h-7 w-7 p-0">
<Save className="w-3 h-3" />
</Button>
)}
{showCancelButton && (
<Button variant="outline" size="sm" onClick={handleCancel} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleCancel() }} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<XIcon className="w-3 h-3" />
</Button>
)}
{isTextFile && viewMode !== 'edit' && !shouldVirtualize && (
<Button variant="outline" size="sm" onClick={handleCopyContent} className="h-7 w-7 p-0">
<Copy className="w-3 h-3" />
</Button>
)}
{viewMode !== 'edit' && (
<Button variant="outline" size="sm" onClick={handleDownload} className="h-7 w-7 p-0">
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); handleDownload() }} className="h-7 w-7 p-0">
<Download className="w-3 h-3" />
</Button>
)}
{viewMode !== 'edit' && isMobileModal && onCloseModal && (
<Button variant="outline" size="sm" onClick={onCloseModal} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<Button variant="outline" size="sm" onClick={(e) => { e.stopPropagation(); e.preventDefault(); onCloseModal() }} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
<X className="w-3 h-3" />
</Button>
)}
@@ -270,7 +303,10 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
</>
)}
<div className={`flex-1 ${viewMode === 'edit' && !shouldVirtualize ? 'overflow-hidden' : shouldVirtualize ? '' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}>
<div
ref={contentRef}
className={`flex-1 ${viewMode === 'edit' && !shouldVirtualize ? 'overflow-hidden' : shouldVirtualize ? '' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}
>
<div className={`${shouldVirtualize ? 'h-full' : 'p-2'} min-w-0`}>
{renderContent()}
</div>
@@ -0,0 +1,90 @@
import { useState, useEffect } from 'react'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { FilePreview } from './FilePreview'
import { Loader2, FileText } from 'lucide-react'
import { API_BASE_URL } from '@/config'
import type { FileInfo } from '@/types/files'
interface FilePreviewDialogProps {
isOpen: boolean
onClose: () => void
filePath: string
repoBasePath?: string
onFileSaved?: () => void
initialLineNumber?: number
}
export function FilePreviewDialog({ isOpen, onClose, filePath, repoBasePath, onFileSaved, initialLineNumber }: FilePreviewDialogProps) {
const [file, setFile] = useState<FileInfo | null>(null)
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
useEffect(() => {
if (!isOpen || !filePath) {
setFile(null)
setError(null)
return
}
const fetchFile = async () => {
setIsLoading(true)
setError(null)
try {
const fullPath = repoBasePath ? `${repoBasePath}/${filePath}` : filePath
const response = await fetch(`${API_BASE_URL}/api/files/${fullPath}`)
if (!response.ok) {
throw new Error(`Failed to load file: ${response.statusText}`)
}
const data = await response.json()
setFile(data)
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load file')
} finally {
setIsLoading(false)
}
}
fetchFile()
}, [isOpen, filePath, repoBasePath])
const handleOpenChange = (open: boolean) => {
if (!open) {
onClose()
}
}
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 bg-background border-0 flex flex-col"
hideCloseButton
>
<div className="flex-1 overflow-hidden min-h-0">
{isLoading ? (
<div className="flex items-center justify-center h-full">
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
</div>
) : error ? (
<div className="flex flex-col items-center justify-center h-full text-muted-foreground">
<FileText className="w-8 h-8 mb-2 opacity-50" />
<p className="text-sm">Failed to load file</p>
<p className="text-xs mt-1">{error}</p>
</div>
) : file ? (
<FilePreview
file={file}
hideHeader={false}
isMobileModal={true}
onCloseModal={onClose}
onFileSaved={onFileSaved}
initialLineNumber={initialLineNumber}
/>
) : null}
</div>
</DialogContent>
</Dialog>
)
}
@@ -2,24 +2,31 @@ import { useState, useEffect } from 'react'
import { Dialog, DialogContent } from '@/components/ui/dialog'
import { GitChangesPanel } from './GitChangesPanel'
import { FileDiffView } from './FileDiffView'
import { FilePreviewDialog } from './FilePreviewDialog'
import { Button } from '@/components/ui/button'
import { X, GitBranch } from 'lucide-react'
import { useMobile } from '@/hooks/useMobile'
import { useQueryClient } from '@tanstack/react-query'
interface GitChangesSheetProps {
isOpen: boolean
onClose: () => void
repoId: number
currentBranch: string
repoLocalPath?: string
}
export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch }: GitChangesSheetProps) {
export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch, repoLocalPath }: GitChangesSheetProps) {
const [selectedFile, setSelectedFile] = useState<string | undefined>()
const [previewFilePath, setPreviewFilePath] = useState<string | null>(null)
const [previewLineNumber, setPreviewLineNumber] = useState<number | undefined>()
const isMobile = useMobile()
const queryClient = useQueryClient()
useEffect(() => {
if (!isOpen) {
setSelectedFile(undefined)
setPreviewFilePath(null)
}
}, [isOpen])
@@ -31,6 +38,21 @@ export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch }: GitC
setSelectedFile(undefined)
}
const handleOpenFile = (path: string, lineNumber?: number) => {
setPreviewFilePath(path)
setPreviewLineNumber(lineNumber)
}
const handleClosePreview = () => {
setPreviewFilePath(null)
setPreviewLineNumber(undefined)
}
const handleFileSaved = () => {
queryClient.invalidateQueries({ queryKey: ['gitStatus'] })
queryClient.invalidateQueries({ queryKey: ['fileDiff'] })
}
const handleOpenChange = (open: boolean) => {
if (!open) {
onClose()
@@ -68,6 +90,7 @@ export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch }: GitC
repoId={repoId}
filePath={selectedFile}
onBack={handleBack}
onOpenFile={handleOpenFile}
isMobile={true}
/>
) : (
@@ -91,6 +114,7 @@ export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch }: GitC
<FileDiffView
repoId={repoId}
filePath={selectedFile}
onOpenFile={handleOpenFile}
isMobile={false}
/>
) : (
@@ -102,6 +126,15 @@ export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch }: GitC
</div>
)}
</div>
<FilePreviewDialog
isOpen={!!previewFilePath}
onClose={handleClosePreview}
filePath={previewFilePath || ''}
repoBasePath={repoLocalPath}
onFileSaved={handleFileSaved}
initialLineNumber={previewLineNumber}
/>
</DialogContent>
</Dialog>
)
@@ -19,9 +19,10 @@ interface BranchSwitcherProps {
currentBranch: string;
isWorktree?: boolean;
repoUrl: string;
repoLocalPath?: string;
}
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: BranchSwitcherProps) {
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl, repoLocalPath }: BranchSwitcherProps) {
const [addBranchOpen, setAddBranchOpen] = useState(false);
const [gitChangesOpen, setGitChangesOpen] = useState(false);
const queryClient = useQueryClient();
@@ -122,6 +123,7 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: B
onClose={() => setGitChangesOpen(false)}
repoId={repoId}
currentBranch={currentBranch}
repoLocalPath={repoLocalPath}
/>
</>
);
@@ -123,6 +123,7 @@ export function SessionDetailHeader({
currentBranch={currentBranch}
isWorktree={repo.isWorktree}
repoUrl={repo.repoUrl}
repoLocalPath={repo.localPath}
/>
</div>
</div>
@@ -1,4 +1,4 @@
import { useRef, useCallback, useEffect, useState, useMemo } from 'react'
import { useRef, useCallback, useEffect, useState, useMemo, forwardRef, useImperativeHandle } from 'react'
import { useVirtualizedContent } from '@/hooks/useVirtualizedContent'
interface VirtualizedTextViewProps {
@@ -9,12 +9,17 @@ interface VirtualizedTextViewProps {
onSaveStateChange?: (hasUnsavedChanges: boolean) => void
onSave?: () => void
className?: string
initialLineNumber?: number
}
export interface VirtualizedTextViewHandle {
save: () => Promise<void>
}
const LINE_HEIGHT = 20
const GUTTER_WIDTH = 60
export function VirtualizedTextView({
export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, VirtualizedTextViewProps>(function VirtualizedTextView({
filePath,
totalLines: initialTotalLines = 0,
lineHeight = LINE_HEIGHT,
@@ -22,10 +27,12 @@ export function VirtualizedTextView({
onSaveStateChange,
onSave,
className = '',
}: VirtualizedTextViewProps) {
initialLineNumber,
}, ref) {
const containerRef = useRef<HTMLDivElement>(null)
const [scrollTop, setScrollTop] = useState(0)
const [viewportHeight, setViewportHeight] = useState(600)
const [highlightedLine, setHighlightedLine] = useState<number | undefined>(initialLineNumber)
const {
lines,
@@ -75,6 +82,19 @@ export function VirtualizedTextView({
resizeObserver.observe(container)
return () => resizeObserver.disconnect()
}, [])
useEffect(() => {
if (initialLineNumber && containerRef.current) {
const scrollPosition = (initialLineNumber - 1) * lineHeight
setHighlightedLine(initialLineNumber)
setTimeout(() => {
containerRef.current?.scrollTo({ top: scrollPosition, behavior: 'smooth' })
}, 100)
setTimeout(() => {
setHighlightedLine(undefined)
}, 3000)
}
}, [initialLineNumber, lineHeight])
const handleScroll = useCallback((e: React.UIEvent<HTMLDivElement>) => {
setScrollTop(e.currentTarget.scrollTop)
@@ -93,6 +113,10 @@ export function VirtualizedTextView({
}
}, [saveEdits, onSave])
useImperativeHandle(ref, () => ({
save: handleSave,
}), [handleSave])
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
@@ -138,10 +162,12 @@ export function VirtualizedTextView({
style={{ height: '100%' }}
>
<div style={{ height: totalHeight, position: 'relative' }}>
{visibleLines.map(({ lineNum, content, isEdited }) => (
{visibleLines.map(({ lineNum, content, isEdited }) => {
const isHighlighted = highlightedLine === lineNum + 1
return (
<div
key={lineNum}
className="absolute flex"
className={`absolute flex transition-colors duration-300 ${isHighlighted ? 'bg-yellow-500/30' : ''}`}
style={{
top: lineNum * lineHeight,
height: lineHeight,
@@ -175,7 +201,7 @@ export function VirtualizedTextView({
</div>
)}
</div>
))}
)})}
{isLoading && visibleLines.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center text-muted-foreground">
@@ -197,4 +223,4 @@ export function VirtualizedTextView({
)}
</div>
)
}
})