Merge pull request #4 from chriswritescode-dev/feature-file-edit

Feature file edit - diff view- virt line map
This commit is contained in:
Chris Scott authored and GitHub committed 2025-11-27 14:18:58 -05:00
commit 2e02b63138
27 files changed
+1943 -119

No files matched your search

+21 -4
View File
@@ -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)
}
})
+47 -2
View File
@@ -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
}
+123 -1
View File
@@ -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<string, string> = {
@@ -256,4 +259,123 @@ function getMimeType(filePath: string, content: Uint8Array): string {
}
return mimeTypes[ext] || 'text/plain'
}
async function countFileLines(filePath: string): Promise<number> {
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<string[]> {
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<ChunkedFileInfo> {
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<number> {
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 }
}
+207
View File
@@ -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}`)
}
}
+1 -1
View File
@@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="manifest" href="/manifest.json" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0a0a0a" />
<meta name="description" content="AI-powered coding assistant interface" />
<meta name="apple-mobile-web-app-capable" content="yes" />
+26 -4
View File
@@ -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<FileInfo> {
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<ChunkedFileInfo> {
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()
}
+42
View File
@@ -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<GitStatusResponse> {
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<FileDiffResponse> {
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,
})
}
+11 -13
View File
@@ -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<Repo> {
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<Repo[]> {
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<Repo[]> {
}
export async function getRepo(id: number): Promise<Repo> {
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<Repo> {
}
export async function deleteRepo(id: number): Promise<void> {
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<void> {
}
export async function startServer(id: number, openCodeConfigName?: string): Promise<Repo> {
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<Repo> {
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<Repo> {
}
export async function pullRepo(id: number): Promise<Repo> {
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<Repo> {
}
export async function getServerLogs(id: number): Promise<string> {
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<string> {
}
export async function switchRepoConfig(id: number, configName: string): Promise<Repo> {
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<Repo> {
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<Repo> {
}
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')
@@ -273,8 +273,8 @@ useEffect(() => {
)}
{/* Mobile: Full width file listing, Desktop: Split view */}
<div className="flex-1 flex overflow-hidden min-h-0">
<div className={`${isMobile ? 'w-full' : 'w-1/2'} border-r border-border px-4 flex flex-col min-h-0`}>
<div className="flex-1 flex overflow-hidden min-h-0 h-full">
<div className={`${isMobile ? 'w-full' : 'w-[30%]'} border-r border-border px-4 flex flex-col min-h-0 h-full`}>
<div className="flex items-center gap-2 mb-4 mt-4 flex-shrink-0">
<Input
placeholder="Search"
@@ -320,11 +320,11 @@ useEffect(() => {
{/* Desktop only: Preview panel */}
{!isMobile && (
<div className="flex-1 overflow-y-auto min-h-0 pb-8">
<div className="flex-1 overflow-y-auto min-h-0 h-full">
{selectedFile && !selectedFile.isDirectory ? (
<FilePreview file={selectedFile} />
) : (
<div className="flex items-center justify-center h-64 text-muted-foreground">
<div className="flex items-center justify-center h-full text-muted-foreground">
Select a file to preview
</div>
)}
@@ -65,9 +65,9 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini
return (
<div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-sm">
<div className="absolute inset-0 bg-background">
<div className="absolute inset-0 bg-background flex flex-col">
{/* Header */}
<div className="sticky top-0 z-10 border-b border-border bg-background backdrop-blur-sm px-4 py-1">
<div className="flex-shrink-0 border-b border-border bg-background backdrop-blur-sm px-4 py-1">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
{(displayPath === '/' || !repoName) && (
@@ -91,7 +91,7 @@ export function FileBrowserSheet({ isOpen, onClose, basePath = '', repoName, ini
</div>
{/* File Browser Content */}
<div className="h-[calc(100vh-73px)] overflow-hidden">
<div className="flex-1 overflow-hidden min-h-0">
<FileBrowser
basePath={normalizedBasePath}
embedded={true}
@@ -0,0 +1,228 @@
import { useFileDiff } from '@/api/git'
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'
interface FileDiffViewProps {
repoId: number
filePath: string
onBack?: () => 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<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, 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">
{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'
const lineNumber = line.newLineNumber ?? line.oldLineNumber
const isClickable = onLineClick && lineNumber !== undefined
return (
<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">
{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, 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 (
<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">
{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)}>
{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 pb-32">
{diffLines.map((line, index) => (
<DiffLineComponent
key={index}
line={line}
showLineNumbers={!isMobile}
onLineClick={onOpenFile ? (lineNum) => onOpenFile(filePath, lineNum) : undefined}
/>
))}
</div>
)}
</div>
</div>
)
}
@@ -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<number | undefined>(initialLineNumber)
const [lineWrap, setLineWrap] = useState(true)
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'
@@ -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 (
<div className="flex justify-center p-4">
@@ -127,13 +164,33 @@ 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}
lineWrap={lineWrap}
/>
)
}
if (!file.content) return null
if (isTextFile) {
if (viewMode === 'edit') {
return (
<textarea
value={editContent}
onChange={(e) => setEditContent(e.target.value)}
className="text-[16px] bg-muted text-foreground p-2 rounded whitespace-pre-wrap font-mono break-words w-full resize-none focus:outline-none focus:ring-0 border-none block"
className={`text-[16px] bg-muted text-foreground p-2 rounded font-mono w-full resize-none focus:outline-none focus:ring-0 border-none block ${
lineWrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre overflow-x-auto'
}`}
style={{ minHeight: '95vh' }}
placeholder="Edit file content..."
autoFocus
@@ -144,10 +201,32 @@ 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 ${
lineWrap ? 'overflow-x-hidden' : 'overflow-x-auto'
}`}>
{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 ${
lineWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre'
}`}>
{line || ' '}
</pre>
</div>
)
})}
</div>
)
} catch {
return (
@@ -165,6 +244,20 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
)
}
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 (
<div className="h-full flex flex-col bg-background">
{!hideHeader && (
@@ -178,41 +271,54 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
<span className="bg-muted px-1.5 py-0.5 rounded text-xs truncate max-w-[80px] flex-shrink-0">{file.mimeType || 'Unknown'}</span>
<span className="truncate flex-shrink-0">{formatFileSize(file.size)}</span>
<span className="hidden sm:inline truncate flex-shrink-0">{formatDate(file.lastModified)}</span>
{shouldVirtualize && (
<span className="text-xs text-blue-500 flex-shrink-0">Virtualized</span>
)}
{hasVirtualizedChanges && (
<span className="text-xs text-yellow-500 flex-shrink-0">Unsaved changes</span>
)}
</div>
</div>
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
{isTextFile && (
<Button
variant="outline"
size="sm"
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setLineWrap(!lineWrap) }}
className={`h-7 w-7 p-0 ${lineWrap ? 'bg-primary text-primary-foreground' : ''}`}
title={lineWrap ? "Disable line wrap" : "Enable line wrap"}
>
<WrapText className="w-3 h-3" />
</Button>
)}
{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>
)}
{viewMode === 'edit' && (
<>
<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">
<Save className="w-3 h-3" />
</Button>
<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">
<XIcon className="w-3 h-3" />
</Button>
</>
{showSaveButton && (
<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>
)}
{isTextFile && viewMode !== 'edit' && (
<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">
<Download className="w-3 h-3" />
</Button>
)}
{showCancelButton && (
<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>
)}
{viewMode !== 'edit' && (
<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>
)}
@@ -221,11 +327,14 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
</>
)}
<div className={`flex-1 ${viewMode === 'edit' ? 'overflow-hidden' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}>
<div className="p-2 min-w-0">
<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>
</div>
</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>
)
}
@@ -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,141 @@
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, 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])
const handleFileSelect = (path: string) => {
setSelectedFile(path)
}
const handleBack = () => {
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()
}
}
return (
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
<DialogContent
className="w-screen h-screen max-w-none max-h-none p-0 gap-0 bg-background border-0 flex flex-col"
hideCloseButton
>
<div className="flex items-center justify-between px-4 sm: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}
onOpenFile={handleOpenFile}
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}
onOpenFile={handleOpenFile}
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>
<FilePreviewDialog
isOpen={!!previewFilePath}
onClose={handleClosePreview}
filePath={previewFilePath || ''}
repoBasePath={repoLocalPath}
onFileSaved={handleFileSaved}
initialLineNumber={previewLineNumber}
/>
</DialogContent>
</Dialog>
)
}
@@ -4,6 +4,7 @@ import { useSettings } from '@/hooks/useSettings'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
import { useFileSearch } from '@/hooks/useFileSearch'
import { useStandalone } from '@/hooks/useStandalone'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { FileSuggestions } from './FileSuggestions'
@@ -76,6 +77,8 @@ export function PromptInput({
showFileSuggestions,
directory
)
const isStandalone = useStandalone()
const handleSubmit = () => {
if (!prompt.trim() || disabled) return
@@ -415,7 +418,7 @@ export function PromptInput({
return (
<div className="backdrop-blur-md bg-background/90 border border-border rounded-lg p-3 mx-2 mb-2 md:mx-4 md:mb-4 max-w-4xl md:mx-auto">
<div className={`backdrop-blur-md bg-background/90 border border-border rounded-lg p-1 md:p-3 mx-2 md:mx-4 md:mb-4 max-w-4xl md:mx-auto ${isStandalone ? 'mb-6' : 'mb-1'}`}>
<textarea
@@ -429,7 +432,7 @@ export function PromptInput({
: "Send a message... (Cmd/Ctrl+Enter)"
}
disabled={disabled || hasActiveStream}
className={`w-full bg-background px-3 py-2 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg ${
className={`w-full bg-background px-3 text-[16px] text-foreground placeholder-muted-foreground focus:outline-none resize-none min-h-[36px] max-h-[120px] disabled:opacity-50 disabled:cursor-not-allowed md:text-sm rounded-lg ${
isBashMode
? 'border-purple-500/50 bg-purple-500/5'
: ''
@@ -441,7 +444,7 @@ export function PromptInput({
<div className="flex gap-2 items-center">
<button
onClick={handleModeToggle}
className={`px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
className={`w-16 px-2 py-1 rounded-md text-xs font-medium border ${modeBg} ${modeColor} hover:opacity-80 transition-opacity cursor-pointer`}
>
{currentMode.toUpperCase()}
</button>
@@ -7,21 +7,26 @@ 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;
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();
const { data: gitStatus } = useGitStatus(repoId);
const { data: branches } = useQuery({
queryKey: ["branches", repoId],
@@ -75,6 +80,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 +117,14 @@ export function BranchSwitcher({ repoId, currentBranch, isWorktree, repoUrl }: B
onOpenChange={setAddBranchOpen}
repoUrl={repoUrl}
/>
<GitChangesSheet
isOpen={gitChangesOpen}
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>
@@ -0,0 +1,234 @@
import { useRef, useCallback, useEffect, useState, useMemo, forwardRef, useImperativeHandle } from 'react'
import { useVirtualizedContent } from '@/hooks/useVirtualizedContent'
interface VirtualizedTextViewProps {
filePath: string
totalLines?: number
lineHeight?: number
editable?: boolean
onSaveStateChange?: (hasUnsavedChanges: boolean) => void
onSave?: () => void
className?: string
initialLineNumber?: number
lineWrap?: boolean
}
export interface VirtualizedTextViewHandle {
save: () => Promise<void>
}
const LINE_HEIGHT = 20
const GUTTER_WIDTH = 40
export const VirtualizedTextView = forwardRef<VirtualizedTextViewHandle, VirtualizedTextViewProps>(function VirtualizedTextView({
filePath,
totalLines: initialTotalLines = 0,
lineHeight = LINE_HEIGHT,
editable = false,
onSaveStateChange,
onSave,
className = '',
initialLineNumber,
lineWrap = false,
}, 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,
totalLines,
isLoading,
error,
loadRange,
getVisibleRange,
editedLines,
setLineContent,
saveEdits,
isSaving,
hasUnsavedChanges,
prefetchAdjacent,
} = useVirtualizedContent({
filePath,
chunkSize: 200,
overscan: 50,
enabled: true,
initialTotalLines,
})
useEffect(() => {
onSaveStateChange?.(hasUnsavedChanges)
}, [hasUnsavedChanges, onSaveStateChange])
const visibleRange = useMemo(() => {
return getVisibleRange(scrollTop, viewportHeight, lineHeight)
}, [scrollTop, viewportHeight, lineHeight, getVisibleRange])
useEffect(() => {
const { start, end } = visibleRange
loadRange(start, end)
prefetchAdjacent(start, end)
}, [visibleRange, loadRange, prefetchAdjacent])
useEffect(() => {
const container = containerRef.current
if (!container) return
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
setViewportHeight(entry.contentRect.height)
}
})
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)
}, [])
const handleLineChange = useCallback((lineNum: number, value: string) => {
setLineContent(lineNum, value)
}, [setLineContent])
const handleSave = useCallback(async () => {
try {
await saveEdits()
onSave?.()
} catch (err) {
console.error('Failed to save:', err)
}
}, [saveEdits, onSave])
useImperativeHandle(ref, () => ({
save: handleSave,
}), [handleSave])
const handleKeyDown = useCallback((e: React.KeyboardEvent) => {
if ((e.metaKey || e.ctrlKey) && e.key === 's') {
e.preventDefault()
if (hasUnsavedChanges && !isSaving) {
handleSave()
}
}
}, [hasUnsavedChanges, isSaving, handleSave])
const totalHeight = totalLines * lineHeight
const visibleLines = useMemo(() => {
const result: Array<{ lineNum: number; content: string; isEdited: boolean }> = []
for (let i = visibleRange.start; i < visibleRange.end; i++) {
const editedContent = editedLines.get(i)
const lineData = lines.get(i)
result.push({
lineNum: i,
content: editedContent ?? lineData?.content ?? '',
isEdited: editedContent !== undefined,
})
}
return result
}, [visibleRange, lines, editedLines])
if (error) {
return (
<div className="p-4 text-destructive">
Error loading file: {error.message}
</div>
)
}
return (
<div
ref={containerRef}
className={`relative font-mono text-sm ${className} ${
lineWrap ? 'overflow-x-hidden' : 'overflow-auto'
}`}
onScroll={handleScroll}
onKeyDown={handleKeyDown}
style={{ height: '100%' }}
>
<div style={{ height: totalHeight, position: 'relative' }}>
{visibleLines.map(({ lineNum, content, isEdited }) => {
const isHighlighted = highlightedLine === lineNum + 1
return (
<div
key={lineNum}
className={`absolute flex transition-colors duration-300 ${isHighlighted ? 'bg-yellow-500/30' : ''}`}
style={{
top: lineNum * lineHeight,
height: lineHeight,
left: 0,
right: 0,
}}
>
<div
className="flex-shrink-0 text-center text-muted-foreground select-none bg-muted/50 border-r border-border"
style={{ width: GUTTER_WIDTH }}
>
{lineNum + 1}
</div>
{editable ? (
<input
type="text"
value={content}
onChange={(e) => handleLineChange(lineNum, e.target.value)}
className={`flex-1 bg-transparent outline-none pl-2 ${
isEdited ? 'bg-yellow-500/10' : ''
} ${
lineWrap ? 'whitespace-pre-wrap break-all' : 'whitespace-pre'
}`}
style={{ lineHeight: `${lineHeight}px` }}
/>
) : (
<div
className={`flex-1 pl-2 ${
lineWrap ? 'whitespace-pre-wrap break-words' : 'whitespace-pre overflow-hidden text-ellipsis'
}`}
style={{ lineHeight: `${lineHeight}px` }}
>
{content}
</div>
)}
</div>
)})}
{isLoading && visibleLines.length === 0 && (
<div className="absolute inset-0 flex items-center justify-center text-muted-foreground">
Loading...
</div>
)}
</div>
{hasUnsavedChanges && (
<div className="sticky bottom-2 right-2 flex justify-end pointer-events-none">
<button
onClick={handleSave}
disabled={isSaving}
className="pointer-events-auto px-3 py-1 bg-primary text-primary-foreground rounded text-xs font-medium hover:bg-primary/90 disabled:opacity-50"
>
{isSaving ? 'Saving...' : 'Save Changes (Ctrl+S)'}
</button>
</div>
)}
</div>
)
})
+22
View File
@@ -0,0 +1,22 @@
import { useState, useEffect } from 'react'
export function useStandalone() {
const [isStandalone, setIsStandalone] = useState(false)
useEffect(() => {
const checkStandalone = () => {
const isIOSStandalone = ('standalone' in window.navigator) && (window.navigator as Navigator & { standalone: boolean }).standalone
const isDisplayModeStandalone = window.matchMedia('(display-mode: standalone)').matches
setIsStandalone(isIOSStandalone || isDisplayModeStandalone)
}
checkStandalone()
const mediaQuery = window.matchMedia('(display-mode: standalone)')
mediaQuery.addEventListener('change', checkStandalone)
return () => mediaQuery.removeEventListener('change', checkStandalone)
}, [])
return isStandalone
}
+253
View File
@@ -0,0 +1,253 @@
import { useState, useCallback, useRef, useEffect } from 'react'
import { fetchFileRange, applyFilePatches } from '@/api/files'
import type { PatchOperation } from '@/types/files'
interface UseVirtualizedContentOptions {
filePath: string
chunkSize?: number
overscan?: number
enabled?: boolean
initialTotalLines?: number
}
interface LineData {
content: string
loaded: boolean
}
interface UseVirtualizedContentReturn {
lines: Map<number, LineData>
totalLines: number
isLoading: boolean
error: Error | null
loadRange: (startLine: number, endLine: number) => Promise<void>
getVisibleRange: (scrollTop: number, viewportHeight: number, lineHeight: number) => { start: number; end: number }
editedLines: Map<number, string>
setLineContent: (lineNumber: number, content: string) => void
clearEdits: () => void
getDirtyRanges: () => Array<{ startLine: number; endLine: number; content: string }>
saveEdits: () => Promise<void>
isSaving: boolean
hasUnsavedChanges: boolean
prefetchAdjacent: (visibleStart: number, visibleEnd: number) => void
}
export function useVirtualizedContent({
filePath,
chunkSize = 200,
overscan = 50,
enabled = true,
initialTotalLines = 0,
}: UseVirtualizedContentOptions): UseVirtualizedContentReturn {
const [lines, setLines] = useState<Map<number, LineData>>(new Map())
const [totalLines, setTotalLines] = useState(initialTotalLines)
const [isLoading, setIsLoading] = useState(false)
const [isSaving, setIsSaving] = useState(false)
const [error, setError] = useState<Error | null>(null)
const [editedLines, setEditedLines] = useState<Map<number, string>>(new Map())
const loadingRanges = useRef<Set<string>>(new Set())
const loadedRanges = useRef<Array<{ start: number; end: number }>>([])
const isRangeLoaded = useCallback((start: number, end: number): boolean => {
for (const range of loadedRanges.current) {
if (range.start <= start && range.end >= end) {
return true
}
}
return false
}, [])
const mergeRanges = useCallback(() => {
if (loadedRanges.current.length <= 1) return
loadedRanges.current.sort((a, b) => a.start - b.start)
const merged: Array<{ start: number; end: number }> = []
let current = loadedRanges.current[0]
for (let i = 1; i < loadedRanges.current.length; i++) {
const next = loadedRanges.current[i]
if (next.start <= current.end + 1) {
current = { start: current.start, end: Math.max(current.end, next.end) }
} else {
merged.push(current)
current = next
}
}
merged.push(current)
loadedRanges.current = merged
}, [])
const loadRange = useCallback(async (startLine: number, endLine: number) => {
if (!enabled || !filePath) return
const rangeKey = `${startLine}-${endLine}`
if (loadingRanges.current.has(rangeKey)) return
if (isRangeLoaded(startLine, endLine)) return
loadingRanges.current.add(rangeKey)
setIsLoading(true)
setError(null)
try {
const result = await fetchFileRange(filePath, startLine, endLine)
setTotalLines(result.totalLines)
setLines(prev => {
const next = new Map(prev)
result.lines.forEach((content, idx) => {
const lineNum = result.startLine + idx
next.set(lineNum, { content, loaded: true })
})
return next
})
loadedRanges.current.push({ start: result.startLine, end: result.endLine })
mergeRanges()
} catch (err) {
setError(err instanceof Error ? err : new Error('Failed to load file range'))
} finally {
loadingRanges.current.delete(rangeKey)
setIsLoading(false)
}
}, [enabled, filePath, isRangeLoaded, mergeRanges])
const prefetchAdjacent = useCallback((visibleStart: number, visibleEnd: number) => {
const prefetchBefore = Math.max(0, visibleStart - chunkSize)
const prefetchAfter = Math.min(totalLines, visibleEnd + chunkSize)
if (!isRangeLoaded(prefetchBefore, visibleStart) && prefetchBefore < visibleStart) {
loadRange(prefetchBefore, visibleStart)
}
if (!isRangeLoaded(visibleEnd, prefetchAfter) && prefetchAfter > visibleEnd) {
loadRange(visibleEnd, prefetchAfter)
}
}, [chunkSize, totalLines, isRangeLoaded, loadRange])
const getVisibleRange = useCallback((scrollTop: number, viewportHeight: number, lineHeight: number) => {
const start = Math.max(0, Math.floor(scrollTop / lineHeight) - overscan)
const visibleCount = Math.ceil(viewportHeight / lineHeight)
const end = Math.min(totalLines, start + visibleCount + overscan * 2)
return { start, end }
}, [totalLines, overscan])
const setLineContent = useCallback((lineNumber: number, content: string) => {
setEditedLines(prev => {
const next = new Map(prev)
next.set(lineNumber, content)
return next
})
}, [])
const clearEdits = useCallback(() => {
setEditedLines(new Map())
}, [])
const getDirtyRanges = useCallback((): Array<{ startLine: number; endLine: number; content: string }> => {
if (editedLines.size === 0) return []
const sortedLineNums = Array.from(editedLines.keys()).sort((a, b) => a - b)
const ranges: Array<{ startLine: number; endLine: number; content: string }> = []
let rangeStart = sortedLineNums[0]
let rangeLines: string[] = [editedLines.get(rangeStart)!]
let lastLine = rangeStart
for (let i = 1; i < sortedLineNums.length; i++) {
const lineNum = sortedLineNums[i]
if (lineNum === lastLine + 1) {
rangeLines.push(editedLines.get(lineNum)!)
lastLine = lineNum
} else {
ranges.push({
startLine: rangeStart,
endLine: lastLine + 1,
content: rangeLines.join('\n'),
})
rangeStart = lineNum
rangeLines = [editedLines.get(lineNum)!]
lastLine = lineNum
}
}
ranges.push({
startLine: rangeStart,
endLine: lastLine + 1,
content: rangeLines.join('\n'),
})
return ranges
}, [editedLines])
const saveEdits = useCallback(async () => {
if (editedLines.size === 0) return
setIsSaving(true)
setError(null)
try {
const dirtyRanges = getDirtyRanges()
const patches: PatchOperation[] = dirtyRanges.map(range => ({
type: 'replace' as const,
startLine: range.startLine,
endLine: range.endLine,
content: range.content,
}))
const result = await applyFilePatches(filePath, patches)
if (result.success) {
setTotalLines(result.totalLines)
setLines(prev => {
const next = new Map(prev)
editedLines.forEach((content, lineNum) => {
next.set(lineNum, { content, loaded: true })
})
return next
})
clearEdits()
}
} catch (err) {
setError(err instanceof Error ? err : new Error('Failed to save edits'))
throw err
} finally {
setIsSaving(false)
}
}, [filePath, editedLines, getDirtyRanges, clearEdits])
useEffect(() => {
if (enabled && filePath && totalLines === 0) {
loadRange(0, chunkSize)
}
}, [enabled, filePath, totalLines, chunkSize, loadRange])
useEffect(() => {
setLines(new Map())
setEditedLines(new Map())
setTotalLines(initialTotalLines)
loadedRanges.current = []
loadingRanges.current.clear()
}, [filePath, initialTotalLines])
const hasUnsavedChanges = editedLines.size > 0
return {
lines,
totalLines,
isLoading,
error,
loadRange,
getVisibleRange,
editedLines,
setLineContent,
clearEdits,
getDirtyRanges,
saveEdits,
isSaving,
hasUnsavedChanges,
prefetchAdjacent,
}
}
+12
View File
@@ -40,14 +40,26 @@
--color-accent-foreground: #111827;
}
html {
background-color: #0a0a0a;
}
:root:not(.dark) html {
background-color: #ffffff;
}
body {
background: linear-gradient(to bottom right, #0a0a0a, #0d0d0d, #0a0a0a);
color: var(--color-foreground);
transition: background-color 0.3s ease, color 0.3s ease;
min-height: 100vh;
min-height: 100dvh;
}
:root:not(.dark) body {
background: linear-gradient(to bottom right, #ffffff, #f0f0f0, #ffffff);
min-height: 100vh;
min-height: 100dvh;
}
/* Custom animations */
+22
View File
@@ -8,4 +8,26 @@ export interface FileInfo {
children?: FileInfo[]
lastModified: Date
workspaceRoot?: string
totalLines?: number
}
export interface ChunkedFileInfo {
name: string
path: string
isDirectory: false
size: number
mimeType?: string
lines: string[]
totalLines: number
startLine: number
endLine: number
hasMore: boolean
lastModified: Date
}
export interface PatchOperation {
type: 'replace' | 'insert' | 'delete'
startLine: number
endLine?: number
content?: string
}
+25
View File
@@ -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
}
+32 -27
View File
@@ -1,37 +1,42 @@
import path from "path";
import { defineConfig } from "vite";
import { defineConfig, loadEnv } from "vite";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
export default defineConfig({
envDir: path.resolve(__dirname, ".."),
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
server: {
host: "0.0.0.0",
port: 5173,
proxy: {
"/api": {
target: "http://localhost:5003",
changeOrigin: true,
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, path.resolve(__dirname, ".."), "");
const backendPort = env.PORT || 5001;
return {
envDir: path.resolve(__dirname, ".."),
plugins: [react(), tailwindcss()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
},
build: {
assetsInlineLimit: 4096,
rollupOptions: {
output: {
assetFileNames: (assetInfo) => {
if (assetInfo.name === "manifest.json") {
return "manifest.json";
}
return "assets/[name]-[hash][extname]";
server: {
host: "0.0.0.0",
port: 5173,
proxy: {
"/api": {
target: `http://localhost:${backendPort}`,
changeOrigin: true,
},
},
},
},
build: {
assetsInlineLimit: 4096,
rollupOptions: {
output: {
assetFileNames: (assetInfo) => {
if (assetInfo.name === "manifest.json") {
return "manifest.json";
}
return "assets/[name]-[hash][extname]";
},
},
},
},
};
});
+34
View File
@@ -9,6 +9,7 @@ export const FileInfoSchema: z.ZodType<{
content?: string
children?: Array<any>
lastModified: Date
totalLines?: number
}> = z.object({
name: z.string(),
path: z.string(),
@@ -18,6 +19,7 @@ export const FileInfoSchema: z.ZodType<{
content: z.string().optional(),
children: z.lazy(() => z.array(FileInfoSchema)).optional(),
lastModified: z.date(),
totalLines: z.number().optional(),
})
export const CreateFileRequestSchema = z.object({
@@ -35,3 +37,35 @@ export const FileUploadResponseSchema = z.object({
size: z.number(),
mimeType: z.string(),
})
export const ChunkedFileInfoSchema = z.object({
name: z.string(),
path: z.string(),
isDirectory: z.literal(false),
size: z.number(),
mimeType: z.string().optional(),
lines: z.array(z.string()),
totalLines: z.number(),
startLine: z.number(),
endLine: z.number(),
hasMore: z.boolean(),
lastModified: z.date(),
})
export const FileRangeRequestSchema = z.object({
startLine: z.number().int().min(0),
endLine: z.number().int().min(0),
})
export const PatchOperationSchema = z.object({
type: z.enum(['replace', 'insert', 'delete']),
startLine: z.number().int().min(0),
endLine: z.number().int().min(0).optional(),
content: z.string().optional(),
})
export const FilePatchRequestSchema = z.object({
patches: z.array(PatchOperationSchema),
})
+8
View File
@@ -21,6 +21,10 @@ import {
CreateFileRequestSchema,
RenameFileRequestSchema,
FileUploadResponseSchema,
ChunkedFileInfoSchema,
FileRangeRequestSchema,
PatchOperationSchema,
FilePatchRequestSchema,
} from '../schemas/files'
import {
SessionSchema,
@@ -46,6 +50,10 @@ export type FileInfo = z.infer<typeof FileInfoSchema>
export type CreateFileRequest = z.infer<typeof CreateFileRequestSchema>
export type RenameFileRequest = z.infer<typeof RenameFileRequestSchema>
export type FileUploadResponse = z.infer<typeof FileUploadResponseSchema>
export type ChunkedFileInfo = z.infer<typeof ChunkedFileInfoSchema>
export type FileRangeRequest = z.infer<typeof FileRangeRequestSchema>
export type PatchOperation = z.infer<typeof PatchOperationSchema>
export type FilePatchRequest = z.infer<typeof FilePatchRequestSchema>
export type Session = z.infer<typeof SessionSchema>
export type Message = z.infer<typeof MessageSchema>