mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Add git changes viewer with diff display
- Add backend git-operations service for git status and file diffs - Add git/status and git/diff API routes to repos - Add GitChangesPanel component to list changed files with status - Add FileDiffView component with unified diff rendering - Add GitChangesSheet as full-screen dialog wrapper - Integrate View Changes option into BranchSwitcher dropdown - Support both mobile (stacked) and desktop (split) layouts
This commit is contained in:
1 parent
12b7ab54b2
commit
ed82b99236
8 files changed
+815
-3
No files matched your search
@@ -2,12 +2,14 @@ import { Hono } from 'hono'
|
||||
import type { Database } from 'bun:sqlite'
|
||||
import * as db from '../db/queries'
|
||||
import * as repoService from '../services/repo'
|
||||
import * as gitOperations from '../services/git-operations'
|
||||
import { SettingsService } from '../services/settings'
|
||||
import { writeFileContent } from '../services/file-operations'
|
||||
import { opencodeServerManager } from '../services/opencode-single-server'
|
||||
import { logger } from '../utils/logger'
|
||||
import { withTransactionAsync } from '../db/transactions'
|
||||
import { getOpenCodeConfigFilePath } from '@opencode-webui/shared'
|
||||
import { getOpenCodeConfigFilePath, getReposPath } from '@opencode-webui/shared'
|
||||
import path from 'path'
|
||||
|
||||
export function createRepoRoutes(database: Database) {
|
||||
const app = new Hono()
|
||||
@@ -146,7 +148,6 @@ export function createRepoRoutes(database: Database) {
|
||||
logger.info(`Switched config for repo ${id} to '${configName}'`)
|
||||
logger.info(`Updated OpenCode config: ${openCodeConfigPath}`)
|
||||
|
||||
// Restart OpenCode server to pick up new workspace config
|
||||
logger.info('Restarting OpenCode server due to workspace config change')
|
||||
await opencodeServerManager.stop()
|
||||
await opencodeServerManager.start()
|
||||
@@ -204,6 +205,50 @@ export function createRepoRoutes(database: Database) {
|
||||
return c.json({ error: error.message }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/status', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const status = await gitOperations.getGitStatus(repoPath)
|
||||
|
||||
return c.json(status)
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get git status:', error)
|
||||
return c.json({ error: error.message }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
app.get('/:id/git/diff', async (c) => {
|
||||
try {
|
||||
const id = parseInt(c.req.param('id'))
|
||||
const filePath = c.req.query('path')
|
||||
|
||||
if (!filePath) {
|
||||
return c.json({ error: 'path query parameter is required' }, 400)
|
||||
}
|
||||
|
||||
const repo = db.getRepoById(database, id)
|
||||
|
||||
if (!repo) {
|
||||
return c.json({ error: 'Repo not found' }, 404)
|
||||
}
|
||||
|
||||
const repoPath = path.resolve(getReposPath(), repo.localPath)
|
||||
const diff = await gitOperations.getFileDiff(repoPath, filePath)
|
||||
|
||||
return c.json(diff)
|
||||
} catch (error: any) {
|
||||
logger.error('Failed to get file diff:', error)
|
||||
return c.json({ error: error.message }, 500)
|
||||
}
|
||||
})
|
||||
|
||||
return app
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { executeCommand } from '../utils/process'
|
||||
import { logger } from '../utils/logger'
|
||||
import path from 'path'
|
||||
|
||||
export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied'
|
||||
|
||||
export interface GitFileStatus {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
staged: boolean
|
||||
oldPath?: string
|
||||
}
|
||||
|
||||
export interface GitStatusResponse {
|
||||
branch: string
|
||||
ahead: number
|
||||
behind: number
|
||||
files: GitFileStatus[]
|
||||
hasChanges: boolean
|
||||
}
|
||||
|
||||
export interface FileDiffResponse {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
diff: string | null
|
||||
additions: number
|
||||
deletions: number
|
||||
isBinary: boolean
|
||||
}
|
||||
|
||||
function parseStatusCode(code: string): GitFileStatusType {
|
||||
switch (code) {
|
||||
case 'M': return 'modified'
|
||||
case 'A': return 'added'
|
||||
case 'D': return 'deleted'
|
||||
case 'R': return 'renamed'
|
||||
case 'C': return 'copied'
|
||||
case '?': return 'untracked'
|
||||
default: return 'modified'
|
||||
}
|
||||
}
|
||||
|
||||
function parsePorcelainV2(output: string): { branch: string; ahead: number; behind: number; files: GitFileStatus[] } {
|
||||
const lines = output.split('\n').filter(line => line.trim())
|
||||
let branch = 'HEAD'
|
||||
let ahead = 0
|
||||
let behind = 0
|
||||
const files: GitFileStatus[] = []
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('# branch.head ')) {
|
||||
branch = line.replace('# branch.head ', '')
|
||||
} else if (line.startsWith('# branch.ab ')) {
|
||||
const match = line.match(/# branch\.ab \+(\d+) -(\d+)/)
|
||||
if (match && match[1] && match[2]) {
|
||||
ahead = parseInt(match[1], 10)
|
||||
behind = parseInt(match[2], 10)
|
||||
}
|
||||
} else if (line.startsWith('1 ') || line.startsWith('2 ')) {
|
||||
const parts = line.split(' ')
|
||||
const xy = parts[1]
|
||||
if (!xy || xy.length < 2) continue
|
||||
const stagedStatus = xy[0] as string
|
||||
const unstagedStatus = xy[1] as string
|
||||
|
||||
if (line.startsWith('2 ')) {
|
||||
const pathParts = parts.slice(8).join(' ').split('\t')
|
||||
const filePath = pathParts[1] || pathParts[0] || ''
|
||||
const oldPath = pathParts[0] || ''
|
||||
|
||||
if (stagedStatus !== '.') {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: parseStatusCode(stagedStatus),
|
||||
staged: true,
|
||||
oldPath: stagedStatus === 'R' || stagedStatus === 'C' ? oldPath : undefined
|
||||
})
|
||||
}
|
||||
if (unstagedStatus !== '.') {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: parseStatusCode(unstagedStatus),
|
||||
staged: false
|
||||
})
|
||||
}
|
||||
} else {
|
||||
const filePath = parts.slice(8).join(' ') || ''
|
||||
|
||||
if (stagedStatus !== '.') {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: parseStatusCode(stagedStatus),
|
||||
staged: true
|
||||
})
|
||||
}
|
||||
if (unstagedStatus !== '.') {
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: parseStatusCode(unstagedStatus),
|
||||
staged: false
|
||||
})
|
||||
}
|
||||
}
|
||||
} else if (line.startsWith('? ')) {
|
||||
const filePath = line.substring(2)
|
||||
files.push({
|
||||
path: filePath,
|
||||
status: 'untracked',
|
||||
staged: false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return { branch, ahead, behind, files }
|
||||
}
|
||||
|
||||
export async function getGitStatus(repoPath: string): Promise<GitStatusResponse> {
|
||||
try {
|
||||
const fullPath = path.resolve(repoPath)
|
||||
const output = await executeCommand(['git', '-C', fullPath, 'status', '--porcelain=v2', '--branch'])
|
||||
const { branch, ahead, behind, files } = parsePorcelainV2(output)
|
||||
|
||||
return {
|
||||
branch,
|
||||
ahead,
|
||||
behind,
|
||||
files,
|
||||
hasChanges: files.length > 0
|
||||
}
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to get git status for ${repoPath}:`, error)
|
||||
throw new Error(`Failed to get git status: ${error.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getFileDiff(repoPath: string, filePath: string): Promise<FileDiffResponse> {
|
||||
try {
|
||||
const fullRepoPath = path.resolve(repoPath)
|
||||
const status = await getGitStatus(repoPath)
|
||||
const fileStatus = status.files.find(f => f.path === filePath)
|
||||
|
||||
if (!fileStatus) {
|
||||
return {
|
||||
path: filePath,
|
||||
status: 'modified',
|
||||
diff: null,
|
||||
additions: 0,
|
||||
deletions: 0,
|
||||
isBinary: false
|
||||
}
|
||||
}
|
||||
|
||||
let diff: string | null = null
|
||||
let additions = 0
|
||||
let deletions = 0
|
||||
let isBinary = false
|
||||
|
||||
if (fileStatus.status === 'untracked') {
|
||||
try {
|
||||
const content = await executeCommand(['git', '-C', fullRepoPath, 'diff', '--no-index', '--', '/dev/null', filePath])
|
||||
diff = content
|
||||
} catch (error: any) {
|
||||
if (error.message?.includes('exit code 1') || error.message?.includes('Command failed with code 1')) {
|
||||
const output = error.message || ''
|
||||
const diffMatch = output.match(/diff --git[\s\S]*/)
|
||||
diff = diffMatch ? diffMatch[0] : `New file: ${filePath}`
|
||||
} else {
|
||||
diff = `New file: ${filePath}`
|
||||
}
|
||||
}
|
||||
} else {
|
||||
try {
|
||||
diff = await executeCommand(['git', '-C', fullRepoPath, 'diff', 'HEAD', '--', filePath])
|
||||
} catch (error: any) {
|
||||
logger.warn(`Failed to get diff for ${filePath}:`, error.message)
|
||||
diff = null
|
||||
}
|
||||
}
|
||||
|
||||
if (diff) {
|
||||
if (diff.includes('Binary files') || diff.includes('GIT binary patch')) {
|
||||
isBinary = true
|
||||
} else {
|
||||
const lines = diff.split('\n')
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('+') && !line.startsWith('+++')) {
|
||||
additions++
|
||||
} else if (line.startsWith('-') && !line.startsWith('---')) {
|
||||
deletions++
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
path: filePath,
|
||||
status: fileStatus.status,
|
||||
diff,
|
||||
additions,
|
||||
deletions,
|
||||
isBinary
|
||||
}
|
||||
} catch (error: any) {
|
||||
logger.error(`Failed to get file diff for ${filePath}:`, error)
|
||||
throw new Error(`Failed to get file diff: ${error.message}`)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { GitStatusResponse, FileDiffResponse } from '@/types/git'
|
||||
|
||||
const API_BASE = API_BASE_URL
|
||||
|
||||
export async function fetchGitStatus(repoId: number): Promise<GitStatusResponse> {
|
||||
const response = await fetch(`${API_BASE}/api/repos/${repoId}/git/status`)
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Failed to fetch git status' }))
|
||||
throw new Error(error.error || 'Failed to fetch git status')
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export async function fetchFileDiff(repoId: number, path: string): Promise<FileDiffResponse> {
|
||||
const response = await fetch(`${API_BASE}/api/repos/${repoId}/git/diff?path=${encodeURIComponent(path)}`)
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ error: 'Failed to fetch file diff' }))
|
||||
throw new Error(error.error || 'Failed to fetch file diff')
|
||||
}
|
||||
|
||||
return response.json()
|
||||
}
|
||||
|
||||
export function useGitStatus(repoId: number | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['gitStatus', repoId],
|
||||
queryFn: () => repoId ? fetchGitStatus(repoId) : Promise.reject(new Error('No repo ID')),
|
||||
enabled: !!repoId,
|
||||
refetchInterval: 10000,
|
||||
})
|
||||
}
|
||||
|
||||
export function useFileDiff(repoId: number | undefined, path: string | undefined) {
|
||||
return useQuery({
|
||||
queryKey: ['fileDiff', repoId, path],
|
||||
queryFn: () => (repoId && path) ? fetchFileDiff(repoId, path) : Promise.reject(new Error('Missing params')),
|
||||
enabled: !!repoId && !!path,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
import { useFileDiff } from '@/api/git'
|
||||
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, Plus, Minus, ArrowLeft } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { GitFileStatusType } from '@/types/git'
|
||||
|
||||
interface FileDiffViewProps {
|
||||
repoId: number
|
||||
filePath: string
|
||||
onBack?: () => void
|
||||
isMobile?: boolean
|
||||
}
|
||||
|
||||
interface DiffLine {
|
||||
type: 'add' | 'remove' | 'context' | 'header' | 'hunk'
|
||||
content: string
|
||||
oldLineNumber?: number
|
||||
newLineNumber?: number
|
||||
}
|
||||
|
||||
function parseDiff(diff: string): DiffLine[] {
|
||||
const lines = diff.split('\n')
|
||||
const result: DiffLine[] = []
|
||||
let oldLine = 0
|
||||
let newLine = 0
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('diff --git') || line.startsWith('index ') || line.startsWith('---') || line.startsWith('+++')) {
|
||||
result.push({ type: 'header', content: line })
|
||||
} else if (line.startsWith('@@')) {
|
||||
const match = line.match(/@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/)
|
||||
if (match) {
|
||||
oldLine = parseInt(match[1], 10)
|
||||
newLine = parseInt(match[2], 10)
|
||||
}
|
||||
result.push({ type: 'hunk', content: line })
|
||||
} else if (line.startsWith('+')) {
|
||||
result.push({ type: 'add', content: line.substring(1), newLineNumber: newLine })
|
||||
newLine++
|
||||
} else if (line.startsWith('-')) {
|
||||
result.push({ type: 'remove', content: line.substring(1), oldLineNumber: oldLine })
|
||||
oldLine++
|
||||
} else if (line.startsWith(' ') || line === '') {
|
||||
result.push({ type: 'context', content: line.substring(1) || '', oldLineNumber: oldLine, newLineNumber: newLine })
|
||||
oldLine++
|
||||
newLine++
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: string; bgColor: string; label: string }> = {
|
||||
modified: { icon: FileEdit, color: 'text-yellow-500', bgColor: 'bg-yellow-500/10', label: 'Modified' },
|
||||
added: { icon: FilePlus, color: 'text-green-500', bgColor: 'bg-green-500/10', label: 'Added' },
|
||||
deleted: { icon: FileX, color: 'text-red-500', bgColor: 'bg-red-500/10', label: 'Deleted' },
|
||||
renamed: { icon: FileText, color: 'text-blue-500', bgColor: 'bg-blue-500/10', label: 'Renamed' },
|
||||
untracked: { icon: File, color: 'text-gray-400', bgColor: 'bg-gray-500/10', label: 'Untracked' },
|
||||
copied: { icon: FileText, color: 'text-purple-500', bgColor: 'bg-purple-500/10', label: 'Copied' },
|
||||
}
|
||||
|
||||
function DiffLineComponent({ line, showLineNumbers }: { line: DiffLine; showLineNumbers: boolean }) {
|
||||
if (line.type === 'header') {
|
||||
return (
|
||||
<div className="px-4 py-1 bg-muted/50 text-muted-foreground text-xs font-mono truncate">
|
||||
{line.content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (line.type === 'hunk') {
|
||||
return (
|
||||
<div className="px-4 py-1 bg-blue-500/10 text-blue-400 text-xs font-mono">
|
||||
{line.content}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const bgClass = line.type === 'add'
|
||||
? 'bg-green-500/10'
|
||||
: line.type === 'remove'
|
||||
? 'bg-red-500/10'
|
||||
: ''
|
||||
|
||||
const textClass = line.type === 'add'
|
||||
? 'text-green-400'
|
||||
: line.type === 'remove'
|
||||
? 'text-red-400'
|
||||
: 'text-foreground'
|
||||
|
||||
return (
|
||||
<div className={cn('flex font-mono text-sm', bgClass)}>
|
||||
{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">
|
||||
{line.oldLineNumber || ''}
|
||||
</span>
|
||||
<span className="w-10 px-2 text-right border-r border-border/50">
|
||||
{line.newLineNumber || ''}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<div className="w-6 flex-shrink-0 flex items-center justify-center">
|
||||
{line.type === 'add' && <Plus className="w-3 h-3 text-green-500" />}
|
||||
{line.type === 'remove' && <Minus className="w-3 h-3 text-red-500" />}
|
||||
</div>
|
||||
<pre className={cn('flex-1 px-2 py-0.5 whitespace-pre-wrap break-all', textClass)}>
|
||||
{line.content || ' '}
|
||||
</pre>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function FileDiffView({ repoId, filePath, onBack, isMobile = false }: FileDiffViewProps) {
|
||||
const { data: diffData, isLoading, error } = useFileDiff(repoId, filePath)
|
||||
|
||||
const fileName = filePath.split('/').pop() || filePath
|
||||
const dirPath = filePath.includes('/') ? filePath.substring(0, filePath.lastIndexOf('/')) : ''
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-full py-8">
|
||||
<Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex flex-col items-center justify-center h-full py-8 text-muted-foreground">
|
||||
<FileText className="w-8 h-8 mb-2 opacity-50" />
|
||||
<p className="text-sm">Failed to load diff</p>
|
||||
<p className="text-xs mt-1">{error.message}</p>
|
||||
{onBack && (
|
||||
<Button variant="ghost" size="sm" onClick={onBack} className="mt-4">
|
||||
<ArrowLeft className="w-4 h-4 mr-2" />
|
||||
Back
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!diffData) {
|
||||
return null
|
||||
}
|
||||
|
||||
const config = statusConfig[diffData.status]
|
||||
const Icon = config.icon
|
||||
const diffLines = diffData.diff ? parseDiff(diffData.diff) : []
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full bg-background">
|
||||
<div className={cn('flex items-center gap-2 px-3 py-2 border-b border-border flex-shrink-0', config.bgColor)}>
|
||||
{onBack && (
|
||||
<Button variant="ghost" size="sm" onClick={onBack} className="h-7 w-7 p-0 mr-1">
|
||||
<ArrowLeft className="w-4 h-4" />
|
||||
</Button>
|
||||
)}
|
||||
<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>}
|
||||
</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)}>
|
||||
{config.label}
|
||||
</span>
|
||||
{!diffData.isBinary && (
|
||||
<>
|
||||
<span className="text-green-500">+{diffData.additions}</span>
|
||||
<span className="text-red-500">-{diffData.deletions}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto min-h-0">
|
||||
{diffData.isBinary ? (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
<p className="text-sm">Binary file - cannot display diff</p>
|
||||
</div>
|
||||
) : !diffData.diff ? (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
<p className="text-sm">No changes to display</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="divide-y divide-border/30">
|
||||
{diffLines.map((line, index) => (
|
||||
<DiffLineComponent
|
||||
key={index}
|
||||
line={line}
|
||||
showLineNumbers={!isMobile}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import { useState } from 'react'
|
||||
import { useGitStatus } from '@/api/git'
|
||||
import { Loader2, FileText, FilePlus, FileX, FileEdit, File, ChevronRight, ArrowUp, ArrowDown } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import type { GitFileStatus, GitFileStatusType } from '@/types/git'
|
||||
|
||||
interface GitChangesPanelProps {
|
||||
repoId: number
|
||||
onFileSelect: (path: string) => void
|
||||
selectedFile?: string
|
||||
}
|
||||
|
||||
const statusConfig: Record<GitFileStatusType, { icon: typeof FileText; color: string; label: string }> = {
|
||||
modified: { icon: FileEdit, color: 'text-yellow-500', label: 'Modified' },
|
||||
added: { icon: FilePlus, color: 'text-green-500', label: 'Added' },
|
||||
deleted: { icon: FileX, color: 'text-red-500', label: 'Deleted' },
|
||||
renamed: { icon: FileText, color: 'text-blue-500', label: 'Renamed' },
|
||||
untracked: { icon: File, color: 'text-gray-400', label: 'Untracked' },
|
||||
copied: { icon: FileText, color: 'text-purple-500', label: 'Copied' },
|
||||
}
|
||||
|
||||
function FileStatusItem({ file, isSelected, onClick }: { file: GitFileStatus; isSelected: boolean; onClick: () => void }) {
|
||||
const config = statusConfig[file.status]
|
||||
const Icon = config.icon
|
||||
const fileName = file.path.split('/').pop() || file.path
|
||||
const dirPath = file.path.includes('/') ? file.path.substring(0, file.path.lastIndexOf('/')) : ''
|
||||
|
||||
return (
|
||||
<button
|
||||
onClick={onClick}
|
||||
className={cn(
|
||||
'w-full flex items-center gap-2 px-3 py-2 text-left hover:bg-accent/50 transition-colors rounded-md',
|
||||
isSelected && 'bg-accent'
|
||||
)}
|
||||
>
|
||||
<Icon className={cn('w-4 h-4 flex-shrink-0', config.color)} />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-sm text-foreground truncate">{fileName}</span>
|
||||
{file.staged && (
|
||||
<span className="text-[10px] px-1 py-0.5 bg-green-500/20 text-green-500 rounded">staged</span>
|
||||
)}
|
||||
</div>
|
||||
{dirPath && (
|
||||
<span className="text-xs text-muted-foreground truncate block">{dirPath}</span>
|
||||
)}
|
||||
{file.oldPath && (
|
||||
<span className="text-xs text-muted-foreground truncate block">← {file.oldPath}</span>
|
||||
)}
|
||||
</div>
|
||||
<ChevronRight className="w-4 h-4 text-muted-foreground flex-shrink-0" />
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export function GitChangesPanel({ repoId, onFileSelect, selectedFile }: GitChangesPanelProps) {
|
||||
const { data: status, isLoading, error } = useGitStatus(repoId)
|
||||
const [filter, setFilter] = useState<GitFileStatusType | 'all'>('all')
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<p className="text-sm">Failed to load git status</p>
|
||||
<p className="text-xs mt-1">{error.message}</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!status || !status.hasChanges) {
|
||||
return (
|
||||
<div className="text-center py-8 text-muted-foreground">
|
||||
<FileText className="w-8 h-8 mx-auto mb-2 opacity-50" />
|
||||
<p className="text-sm">No uncommitted changes</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const filteredFiles = filter === 'all'
|
||||
? status.files
|
||||
: status.files.filter(f => f.status === filter)
|
||||
|
||||
const statusCounts = status.files.reduce((acc, file) => {
|
||||
acc[file.status] = (acc[file.status] || 0) + 1
|
||||
return acc
|
||||
}, {} as Record<string, number>)
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="px-3 py-2 border-b border-border flex-shrink-0">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="text-sm font-medium text-foreground">{status.branch}</span>
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
{status.ahead > 0 && (
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowUp className="w-3 h-3" />
|
||||
{status.ahead}
|
||||
</span>
|
||||
)}
|
||||
{status.behind > 0 && (
|
||||
<span className="flex items-center gap-0.5">
|
||||
<ArrowDown className="w-3 h-3" />
|
||||
{status.behind}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1">
|
||||
<button
|
||||
onClick={() => setFilter('all')}
|
||||
className={cn(
|
||||
'text-xs px-2 py-0.5 rounded transition-colors',
|
||||
filter === 'all' ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/50'
|
||||
)}
|
||||
>
|
||||
All ({status.files.length})
|
||||
</button>
|
||||
{Object.entries(statusCounts).map(([statusKey, count]) => {
|
||||
const config = statusConfig[statusKey as GitFileStatusType]
|
||||
return (
|
||||
<button
|
||||
key={statusKey}
|
||||
onClick={() => setFilter(statusKey as GitFileStatusType)}
|
||||
className={cn(
|
||||
'text-xs px-2 py-0.5 rounded transition-colors',
|
||||
filter === statusKey ? 'bg-accent text-foreground' : 'text-muted-foreground hover:bg-accent/50'
|
||||
)}
|
||||
>
|
||||
<span className={config.color}>{config.label}</span> ({count})
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto p-2">
|
||||
<div className="space-y-1">
|
||||
{filteredFiles.map((file) => (
|
||||
<FileStatusItem
|
||||
key={`${file.path}-${file.staged}`}
|
||||
file={file}
|
||||
isSelected={selectedFile === file.path}
|
||||
onClick={() => onFileSelect(file.path)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Dialog, DialogContent } from '@/components/ui/dialog'
|
||||
import { GitChangesPanel } from './GitChangesPanel'
|
||||
import { FileDiffView } from './FileDiffView'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { X, GitBranch } from 'lucide-react'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
|
||||
interface GitChangesSheetProps {
|
||||
isOpen: boolean
|
||||
onClose: () => void
|
||||
repoId: number
|
||||
currentBranch: string
|
||||
}
|
||||
|
||||
export function GitChangesSheet({ isOpen, onClose, repoId, currentBranch }: GitChangesSheetProps) {
|
||||
const [selectedFile, setSelectedFile] = useState<string | undefined>()
|
||||
const isMobile = useMobile()
|
||||
|
||||
useEffect(() => {
|
||||
if (!isOpen) {
|
||||
setSelectedFile(undefined)
|
||||
}
|
||||
}, [isOpen])
|
||||
|
||||
const handleFileSelect = (path: string) => {
|
||||
setSelectedFile(path)
|
||||
}
|
||||
|
||||
const handleBack = () => {
|
||||
setSelectedFile(undefined)
|
||||
}
|
||||
|
||||
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 items-center justify-between px-4 py-3 border-b border-border flex-shrink-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="w-4 h-4 text-blue-400" />
|
||||
<h2 className="text-sm font-semibold text-foreground">
|
||||
{selectedFile ? 'File Changes' : 'Git Changes'}
|
||||
</h2>
|
||||
<span className="text-xs text-muted-foreground">({currentBranch})</span>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onClose}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-muted transition-all duration-200 h-8 w-8"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-hidden min-h-0">
|
||||
{isMobile ? (
|
||||
selectedFile ? (
|
||||
<FileDiffView
|
||||
repoId={repoId}
|
||||
filePath={selectedFile}
|
||||
onBack={handleBack}
|
||||
isMobile={true}
|
||||
/>
|
||||
) : (
|
||||
<GitChangesPanel
|
||||
repoId={repoId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
)
|
||||
) : (
|
||||
<div className="flex h-full">
|
||||
<div className="w-[280px] border-r border-border overflow-hidden flex-shrink-0">
|
||||
<GitChangesPanel
|
||||
repoId={repoId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1 overflow-hidden min-w-0">
|
||||
{selectedFile ? (
|
||||
<FileDiffView
|
||||
repoId={repoId}
|
||||
filePath={selectedFile}
|
||||
isMobile={false}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full text-muted-foreground">
|
||||
<p className="text-sm">Select a file to view changes</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -7,10 +7,12 @@ import {
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { GitBranch, Check, Plus } from "lucide-react";
|
||||
import { GitBranch, Check, Plus, GitCommit } from "lucide-react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { listBranches, switchBranch } from "@/api/repos";
|
||||
import { useGitStatus } from "@/api/git";
|
||||
import { AddBranchWorkspaceDialog } from "@/components/repo/AddBranchWorkspaceDialog";
|
||||
import { GitChangesSheet } from "@/components/file-browser/GitChangesSheet";
|
||||
|
||||
interface BranchSwitcherProps {
|
||||
repoId: number;
|
||||
@@ -21,7 +23,9 @@ interface BranchSwitcherProps {
|
||||
|
||||
export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: BranchSwitcherProps) {
|
||||
const [addBranchOpen, setAddBranchOpen] = useState(false);
|
||||
const [gitChangesOpen, setGitChangesOpen] = useState(false);
|
||||
const queryClient = useQueryClient();
|
||||
const { data: gitStatus } = useGitStatus(repoId);
|
||||
|
||||
const { data: branches } = useQuery({
|
||||
queryKey: ["branches", repoId],
|
||||
@@ -75,6 +79,21 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: B
|
||||
Loading branches...
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitChangesOpen(true)}
|
||||
className="text-muted-foreground hover:text-foreground hover:bg-accent cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<GitCommit className="w-3 h-3" />
|
||||
<span className="flex-1">View Changes</span>
|
||||
{gitStatus?.hasChanges && (
|
||||
<span className="text-xs text-yellow-500">
|
||||
{gitStatus.files.length}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
{!isWorktree && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
@@ -97,6 +116,13 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: B
|
||||
onOpenChange={setAddBranchOpen}
|
||||
repoUrl={repoUrl}
|
||||
/>
|
||||
|
||||
<GitChangesSheet
|
||||
isOpen={gitChangesOpen}
|
||||
onClose={() => setGitChangesOpen(false)}
|
||||
repoId={repoId}
|
||||
currentBranch={currentBranch}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
export type GitFileStatusType = 'modified' | 'added' | 'deleted' | 'renamed' | 'untracked' | 'copied'
|
||||
|
||||
export interface GitFileStatus {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
staged: boolean
|
||||
oldPath?: string
|
||||
}
|
||||
|
||||
export interface GitStatusResponse {
|
||||
branch: string
|
||||
ahead: number
|
||||
behind: number
|
||||
files: GitFileStatus[]
|
||||
hasChanges: boolean
|
||||
}
|
||||
|
||||
export interface FileDiffResponse {
|
||||
path: string
|
||||
status: GitFileStatusType
|
||||
diff: string | null
|
||||
additions: number
|
||||
deletions: number
|
||||
isBinary: boolean
|
||||
}
|
||||
Reference in new issue
Block a user