diff --git a/backend/src/routes/files.ts b/backend/src/routes/files.ts index 2a3ee55c..a61acef1 100644 --- a/backend/src/routes/files.ts +++ b/backend/src/routes/files.ts @@ -1,11 +1,9 @@ import { Hono } from 'hono' -import { serveStatic } from '@hono/node-server/serve-static' -import * as db from '../db/queries' import * as fileService from '../services/files' import type { Database } from 'bun:sqlite' import { logger } from '../utils/logger' -export function createFileRoutes(database: Database) { +export function createFileRoutes(_database: Database) { const app = new Hono() app.get('/*', async (c) => { @@ -13,6 +11,20 @@ export function createFileRoutes(database: Database) { const userPath = c.req.path.replace(/^\/api\/files\//, '') || '' const download = c.req.query('download') === 'true' const raw = c.req.query('raw') === 'true' + const startLineParam = c.req.query('startLine') + const endLineParam = c.req.query('endLine') + + if (startLineParam !== undefined && endLineParam !== undefined) { + const startLine = parseInt(startLineParam, 10) + const endLine = parseInt(endLineParam, 10) + + if (isNaN(startLine) || isNaN(endLine) || startLine < 0 || endLine < startLine) { + return c.json({ error: 'Invalid line range parameters' }, 400) + } + + const result = await fileService.getFileRange(userPath, startLine, endLine) + return c.json(result) + } const result = await fileService.getFile(userPath) @@ -92,10 +104,15 @@ export function createFileRoutes(database: Database) { const path = c.req.path.replace(/^\/api\/files\//, '') || '' const body = await c.req.json() + if (body.patches && Array.isArray(body.patches)) { + const result = await fileService.applyFilePatches(path, body.patches) + return c.json(result) + } + const result = await fileService.renameOrMoveFile(path, body) return c.json(result) } catch (error: any) { - logger.error('Failed to rename/move file:', error) + logger.error('Failed to patch file:', error) return c.json({ error: error.message }, error.statusCode || 500) } }) diff --git a/backend/src/routes/repos.ts b/backend/src/routes/repos.ts index 28347490..e6b81108 100644 --- a/backend/src/routes/repos.ts +++ b/backend/src/routes/repos.ts @@ -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 } diff --git a/backend/src/services/files.ts b/backend/src/services/files.ts index 83f3281e..3b3e4b5a 100644 --- a/backend/src/services/files.ts +++ b/backend/src/services/files.ts @@ -1,5 +1,7 @@ import fs from 'fs/promises' import path from 'path' +import { createReadStream } from 'fs' +import { createInterface } from 'readline' import { logger } from '../utils/logger' import { @@ -12,6 +14,7 @@ import { listDirectory } from './file-operations' import { FILE_LIMITS, ALLOWED_MIME_TYPES, getReposPath } from '@opencode-webui/shared' +import type { ChunkedFileInfo, PatchOperation } from '@opencode-webui/shared' const SHARED_WORKSPACE_BASE = getReposPath() @@ -233,7 +236,7 @@ function validatePath(userPath: string): string { return resolved } -function getMimeType(filePath: string, content: Uint8Array): string { +function getMimeType(filePath: string, _content: Uint8Array): string { const ext = path.extname(filePath).toLowerCase() const mimeTypes: Record = { @@ -256,4 +259,123 @@ function getMimeType(filePath: string, content: Uint8Array): string { } return mimeTypes[ext] || 'text/plain' +} + +async function countFileLines(filePath: string): Promise { + return new Promise((resolve, reject) => { + let lineCount = 0 + const stream = createReadStream(filePath, { encoding: 'utf8' }) + const rl = createInterface({ input: stream, crlfDelay: Infinity }) + + rl.on('line', () => { lineCount++ }) + rl.on('close', () => resolve(lineCount)) + rl.on('error', reject) + }) +} + +async function readFileLines(filePath: string, startLine: number, endLine: number): Promise { + return new Promise((resolve, reject) => { + const lines: string[] = [] + let currentLine = 0 + const stream = createReadStream(filePath, { encoding: 'utf8' }) + const rl = createInterface({ input: stream, crlfDelay: Infinity }) + + rl.on('line', (line) => { + if (currentLine >= startLine && currentLine < endLine) { + lines.push(line) + } + currentLine++ + if (currentLine >= endLine) { + rl.close() + stream.destroy() + } + }) + rl.on('close', () => resolve(lines)) + rl.on('error', reject) + }) +} + +export async function getFileRange(userPath: string, startLine: number, endLine: number): Promise { + const validatedPath = validatePath(userPath) + logger.info(`Getting file range for path: ${userPath} lines ${startLine}-${endLine}`) + + const exists = await fileExists(validatedPath) + if (!exists) { + throw { message: 'File does not exist', statusCode: 404 } + } + + const stats = await getFileStats(validatedPath) + if (stats.isDirectory) { + throw { message: 'Path is a directory', statusCode: 400 } + } + + const totalLines = await countFileLines(validatedPath) + const clampedEnd = Math.min(endLine, totalLines) + const lines = await readFileLines(validatedPath, startLine, clampedEnd) + const mimeType = getMimeType(validatedPath, new Uint8Array()) + + return { + name: path.basename(validatedPath), + path: userPath, + isDirectory: false as const, + size: stats.size, + mimeType, + lines, + totalLines, + startLine, + endLine: clampedEnd, + hasMore: clampedEnd < totalLines, + lastModified: stats.lastModified, + } +} + +export async function getFileTotalLines(userPath: string): Promise { + const validatedPath = validatePath(userPath) + const exists = await fileExists(validatedPath) + if (!exists) { + throw { message: 'File does not exist', statusCode: 404 } + } + return countFileLines(validatedPath) +} + +export async function applyFilePatches(userPath: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> { + const validatedPath = validatePath(userPath) + logger.info(`Applying ${patches.length} patches to: ${userPath}`) + + const exists = await fileExists(validatedPath) + if (!exists) { + throw { message: 'File does not exist', statusCode: 404 } + } + + const content = await fs.readFile(validatedPath, 'utf8') + const lines = content.split('\n') + + const sortedPatches = [...patches].sort((a, b) => b.startLine - a.startLine) + + for (const patch of sortedPatches) { + const { type, startLine, endLine, content: patchContent } = patch + + switch (type) { + case 'replace': { + const end = endLine ?? startLine + 1 + const newLines = patchContent?.split('\n') ?? [] + lines.splice(startLine, end - startLine, ...newLines) + break + } + case 'insert': { + const newLines = patchContent?.split('\n') ?? [] + lines.splice(startLine, 0, ...newLines) + break + } + case 'delete': { + const end = endLine ?? startLine + 1 + lines.splice(startLine, end - startLine) + break + } + } + } + + await fs.writeFile(validatedPath, lines.join('\n'), 'utf8') + + return { success: true, totalLines: lines.length } } \ No newline at end of file diff --git a/backend/src/services/git-operations.ts b/backend/src/services/git-operations.ts new file mode 100644 index 00000000..04fb89a9 --- /dev/null +++ b/backend/src/services/git-operations.ts @@ -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 { + 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 { + 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}`) + } +} diff --git a/frontend/index.html b/frontend/index.html index 606e64f0..3f7e6447 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -4,7 +4,7 @@ - + diff --git a/frontend/src/api/files.ts b/frontend/src/api/files.ts index 4550a2b6..bfe859b1 100644 --- a/frontend/src/api/files.ts +++ b/frontend/src/api/files.ts @@ -1,11 +1,9 @@ import { useQuery } from '@tanstack/react-query' import { API_BASE_URL } from '@/config' -import type { FileInfo } from '@/types/files' - -const API_BASE = API_BASE_URL +import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files' async function fetchFile(path: string): Promise { - const response = await fetch(`${API_BASE}/api/files/${path}`) + const response = await fetch(`${API_BASE_URL}/api/files/${path}`) if (!response.ok) { throw new Error(`Failed to load file: ${response.statusText}`) @@ -20,4 +18,28 @@ export function useFile(path: string | undefined) { queryFn: () => path ? fetchFile(path) : Promise.reject(new Error('No file path provided')), enabled: !!path, }) +} + +export async function fetchFileRange(path: string, startLine: number, endLine: number): Promise { + const response = await fetch(`${API_BASE_URL}/api/files/${path}?startLine=${startLine}&endLine=${endLine}`) + + if (!response.ok) { + throw new Error(`Failed to load file range: ${response.statusText}`) + } + + return response.json() +} + +export async function applyFilePatches(path: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> { + const response = await fetch(`${API_BASE_URL}/api/files/${path}`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ patches }), + }) + + if (!response.ok) { + throw new Error(`Failed to apply patches: ${response.statusText}`) + } + + return response.json() } \ No newline at end of file diff --git a/frontend/src/api/git.ts b/frontend/src/api/git.ts new file mode 100644 index 00000000..968a4dab --- /dev/null +++ b/frontend/src/api/git.ts @@ -0,0 +1,42 @@ +import { useQuery } from '@tanstack/react-query' +import { API_BASE_URL } from '@/config' +import type { GitStatusResponse, FileDiffResponse } from '@/types/git' + +export async function fetchGitStatus(repoId: number): Promise { + const response = await fetch(`${API_BASE_URL}/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 { + const response = await fetch(`${API_BASE_URL}/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, + }) +} diff --git a/frontend/src/api/repos.ts b/frontend/src/api/repos.ts index ceba0a7b..9b0b6b7e 100644 --- a/frontend/src/api/repos.ts +++ b/frontend/src/api/repos.ts @@ -1,15 +1,13 @@ import type { Repo } from './types' import { API_BASE_URL } from '@/config' -const API_BASE = API_BASE_URL - export async function createRepo( repoUrl: string, branch?: string, openCodeConfigName?: string, useWorktree?: boolean ): Promise { - const response = await fetch(`${API_BASE}/api/repos`, { + const response = await fetch(`${API_BASE_URL}/api/repos`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ repoUrl, branch, openCodeConfigName, useWorktree }), @@ -24,7 +22,7 @@ export async function createRepo( } export async function listRepos(): Promise { - const response = await fetch(`${API_BASE}/api/repos`) + const response = await fetch(`${API_BASE_URL}/api/repos`) if (!response.ok) { throw new Error('Failed to list repos') @@ -34,7 +32,7 @@ export async function listRepos(): Promise { } export async function getRepo(id: number): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}`) + const response = await fetch(`${API_BASE_URL}/api/repos/${id}`) if (!response.ok) { throw new Error('Failed to get repo') @@ -44,7 +42,7 @@ export async function getRepo(id: number): Promise { } export async function deleteRepo(id: number): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}`, { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}`, { method: 'DELETE', }) @@ -54,7 +52,7 @@ export async function deleteRepo(id: number): Promise { } export async function startServer(id: number, openCodeConfigName?: string): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}/server/start`, { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/server/start`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ openCodeConfigName }), @@ -68,7 +66,7 @@ export async function startServer(id: number, openCodeConfigName?: string): Prom } export async function stopServer(id: number): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}/server/stop`, { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/server/stop`, { method: 'POST', }) @@ -80,7 +78,7 @@ export async function stopServer(id: number): Promise { } export async function pullRepo(id: number): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}/pull`, { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/pull`, { method: 'POST', }) @@ -92,7 +90,7 @@ export async function pullRepo(id: number): Promise { } export async function getServerLogs(id: number): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}/server/logs`) + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/server/logs`) if (!response.ok) { throw new Error('Failed to get server logs') @@ -102,7 +100,7 @@ export async function getServerLogs(id: number): Promise { } export async function switchRepoConfig(id: number, configName: string): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}/config/switch`, { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/config/switch`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ configName }), @@ -117,7 +115,7 @@ export async function switchRepoConfig(id: number, configName: string): Promise< } export async function switchBranch(id: number, branch: string): Promise { - const response = await fetch(`${API_BASE}/api/repos/${id}/branch/switch`, { + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branch/switch`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ branch }), @@ -132,7 +130,7 @@ export async function switchBranch(id: number, branch: string): Promise { } export async function listBranches(id: number): Promise<{ local: string[], remote: string[], current: string | null }> { - const response = await fetch(`${API_BASE}/api/repos/${id}/branches`) + const response = await fetch(`${API_BASE_URL}/api/repos/${id}/branches`) if (!response.ok) { throw new Error('Failed to list branches') diff --git a/frontend/src/components/file-browser/FileBrowser.tsx b/frontend/src/components/file-browser/FileBrowser.tsx index f25aa26f..30f3176d 100644 --- a/frontend/src/components/file-browser/FileBrowser.tsx +++ b/frontend/src/components/file-browser/FileBrowser.tsx @@ -273,8 +273,8 @@ useEffect(() => { )} {/* Mobile: Full width file listing, Desktop: Split view */} -
-
+
+
{ {/* Desktop only: Preview panel */} {!isMobile && ( -
+
{selectedFile && !selectedFile.isDirectory ? ( ) : ( -
+
Select a file to preview
)} diff --git a/frontend/src/components/file-browser/FileBrowserSheet.tsx b/frontend/src/components/file-browser/FileBrowserSheet.tsx index afcdc4d1..bd81fedb 100644 --- a/frontend/src/components/file-browser/FileBrowserSheet.tsx +++ b/frontend/src/components/file-browser/FileBrowserSheet.tsx @@ -65,9 +65,9 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini return (
-
+
{/* Header */} -
+
{(displayPath === '/' || !repoName) && ( @@ -91,7 +91,7 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini
{/* File Browser Content */} -
+
void + onOpenFile?: (path: string, lineNumber?: number) => 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 = { + 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, onLineClick }: { line: DiffLine; showLineNumbers: boolean; onLineClick?: (lineNumber: number) => void }) { + if (line.type === 'header') { + return ( +
+ {line.content} +
+ ) + } + + if (line.type === 'hunk') { + return ( +
+ {line.content} +
+ ) + } + + 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' + + const lineNumber = line.newLineNumber ?? line.oldLineNumber + const isClickable = onLineClick && lineNumber !== undefined + + return ( +
isClickable && lineNumber !== undefined && onLineClick(lineNumber)} + > + {showLineNumbers && ( +
+ + {line.oldLineNumber || ''} + + + {line.newLineNumber || ''} + +
+ )} +
+ {line.type === 'add' && } + {line.type === 'remove' && } +
+
+        {line.content || ' '}
+      
+
+ ) +} + +export function FileDiffView({ repoId, filePath, onBack, onOpenFile, 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 ( +
+ +
+ ) + } + + if (error) { + return ( +
+ +

Failed to load diff

+

{error.message}

+ {onBack && ( + + )} +
+ ) + } + + if (!diffData) { + return null + } + + const config = statusConfig[diffData.status] + const Icon = config.icon + const diffLines = diffData.diff ? parseDiff(diffData.diff) : [] + + return ( +
+
+ {onBack && ( + + )} + +
+ {onOpenFile ? ( + + ) : ( + <> +
{fileName}
+ {dirPath &&
{dirPath}
} + + )} +
+
+ + {config.label} + + {!diffData.isBinary && ( + <> + +{diffData.additions} + -{diffData.deletions} + + )} +
+
+ +
+ {diffData.isBinary ? ( +
+

Binary file - cannot display diff

+
+ ) : !diffData.diff ? ( +
+

No changes to display

+
+ ) : ( +
+ {diffLines.map((line, index) => ( + onOpenFile(filePath, lineNum) : undefined} + /> + ))} +
+ )} +
+
+ ) +} diff --git a/frontend/src/components/file-browser/FilePreview.tsx b/frontend/src/components/file-browser/FilePreview.tsx index fa5d5606..f69d2f24 100644 --- a/frontend/src/components/file-browser/FilePreview.tsx +++ b/frontend/src/components/file-browser/FilePreview.tsx @@ -1,22 +1,52 @@ -import { useState } from 'react' +import { useState, useCallback, useRef, useEffect, memo } 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, WrapText } from 'lucide-react' import type { FileInfo } from '@/types/files' import { API_BASE_URL } from '@/config' +import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view' + const API_BASE = API_BASE_URL +const VIRTUALIZATION_THRESHOLD_BYTES = 8_000 + interface FilePreviewProps { file: FileInfo hideHeader?: boolean isMobileModal?: boolean onCloseModal?: () => void + onFileSaved?: () => void + initialLineNumber?: number } -export function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal }: FilePreviewProps) { +export const FilePreview = memo(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(initialLineNumber) + const [lineWrap, setLineWrap] = useState(true) + const virtualizedRef = useRef(null) + const contentRef = useRef(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' @@ -52,28 +82,22 @@ 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 (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) - } + if (shouldVirtualize) { + setViewMode('edit') + const event = new CustomEvent('editModeChange', { detail: { isEditing: true } }) + window.dispatchEvent(event) + return + } + + 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) } } @@ -95,6 +119,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 { @@ -105,16 +130,28 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o const handleCancel = () => { setEditContent('') setViewMode('preview') + setHasVirtualizedChanges(false) const event = new CustomEvent('editModeChange', { detail: { isEditing: false } }) window.dispatchEvent(event) } + const handleVirtualizedSaveStateChange = useCallback((hasChanges: boolean) => { + setHasVirtualizedChanges(hasChanges) + }, []) + + const handleVirtualizedSave = useCallback(() => { + setViewMode('preview') + const editEvent = new CustomEvent('editModeChange', { detail: { isEditing: false } }) + window.dispatchEvent(editEvent) + const event = new CustomEvent('fileSaved', { detail: { path: file.path } }) + window.dispatchEvent(event) + onFileSaved?.() + }, [file.path, onFileSaved]) + const isTextFile = file.mimeType?.startsWith('text/') || ['application/json', 'application/xml', 'text/javascript', 'text/typescript'].includes(file.mimeType || '') const renderContent = () => { - if (!file.content) return null - if (file.mimeType?.startsWith('image/')) { return (
@@ -127,13 +164,33 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o ) } + if (shouldVirtualize && isTextFile) { + return ( + + ) + } + + if (!file.content) return null + if (isTextFile) { if (viewMode === 'edit') { return (