mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Add file virtualization and patch editing for large files
This commit is contained in:
1 parent
16767a2a77
commit
12b7ab54b2
9 files changed
+760
-31
No files matched your search
@@ -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)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files'
|
||||
|
||||
const API_BASE = API_BASE_URL
|
||||
|
||||
@@ -20,4 +20,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}/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}/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()
|
||||
}
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useState } from 'react'
|
||||
import { useState, useCallback } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Download, Copy, X, Edit3, Save, X as XIcon } from 'lucide-react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { API_BASE_URL } from '@/config'
|
||||
import { VirtualizedTextView } from '@/components/ui/virtualized-text-view'
|
||||
|
||||
const API_BASE = API_BASE_URL
|
||||
|
||||
const VIRTUALIZATION_THRESHOLD_BYTES = 8_000
|
||||
|
||||
interface FilePreviewProps {
|
||||
file: FileInfo
|
||||
hideHeader?: boolean
|
||||
@@ -17,6 +20,9 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
|
||||
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
|
||||
const [editContent, setEditContent] = useState('')
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [hasVirtualizedChanges, setHasVirtualizedChanges] = useState(false)
|
||||
|
||||
const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/')
|
||||
|
||||
const formatFileSize = (bytes: number) => {
|
||||
if (bytes === 0) return '0 Bytes'
|
||||
@@ -64,6 +70,13 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
|
||||
}
|
||||
|
||||
const handleEdit = () => {
|
||||
if (shouldVirtualize) {
|
||||
setViewMode('edit')
|
||||
const event = new CustomEvent('editModeChange', { detail: { isEditing: true } })
|
||||
window.dispatchEvent(event)
|
||||
return
|
||||
}
|
||||
|
||||
if (file.content) {
|
||||
try {
|
||||
const content = decodeBase64(file.content)
|
||||
@@ -105,16 +118,27 @@ 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)
|
||||
}, [file.path])
|
||||
|
||||
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,6 +151,21 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
|
||||
)
|
||||
}
|
||||
|
||||
if (shouldVirtualize && isTextFile) {
|
||||
return (
|
||||
<VirtualizedTextView
|
||||
filePath={file.path}
|
||||
totalLines={file.totalLines}
|
||||
editable={viewMode === 'edit'}
|
||||
onSaveStateChange={handleVirtualizedSaveStateChange}
|
||||
onSave={handleVirtualizedSave}
|
||||
className="h-full"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (!file.content) return null
|
||||
|
||||
if (isTextFile) {
|
||||
if (viewMode === 'edit') {
|
||||
return (
|
||||
@@ -165,6 +204,9 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
|
||||
)
|
||||
}
|
||||
|
||||
const showSaveButton = viewMode === 'edit' && !shouldVirtualize
|
||||
const showCancelButton = viewMode === 'edit'
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col bg-background">
|
||||
{!hideHeader && (
|
||||
@@ -178,6 +220,12 @@ 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>
|
||||
|
||||
@@ -188,28 +236,29 @@ export function FilePreview({ file, hideHeader = false, isMobileModal = false, o
|
||||
</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={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>
|
||||
)}
|
||||
|
||||
{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={handleCancel} className="border-destructive bg-destructive/10 text-destructive hover:bg-destructive/20 h-7 w-7 p-0">
|
||||
<XIcon className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isTextFile && viewMode !== 'edit' && !shouldVirtualize && (
|
||||
<Button variant="outline" size="sm" onClick={handleCopyContent} className="h-7 w-7 p-0">
|
||||
<Copy className="w-3 h-3" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{viewMode !== 'edit' && (
|
||||
<Button variant="outline" size="sm" onClick={handleDownload} className="h-7 w-7 p-0">
|
||||
<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">
|
||||
@@ -221,8 +270,8 @@ 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 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>
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
import { useRef, useCallback, useEffect, useState, useMemo } 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
|
||||
}
|
||||
|
||||
const LINE_HEIGHT = 20
|
||||
const GUTTER_WIDTH = 60
|
||||
|
||||
export function VirtualizedTextView({
|
||||
filePath,
|
||||
totalLines: initialTotalLines = 0,
|
||||
lineHeight = LINE_HEIGHT,
|
||||
editable = false,
|
||||
onSaveStateChange,
|
||||
onSave,
|
||||
className = '',
|
||||
}: VirtualizedTextViewProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [scrollTop, setScrollTop] = useState(0)
|
||||
const [viewportHeight, setViewportHeight] = useState(600)
|
||||
|
||||
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()
|
||||
}, [])
|
||||
|
||||
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])
|
||||
|
||||
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 overflow-auto font-mono text-sm ${className}`}
|
||||
onScroll={handleScroll}
|
||||
onKeyDown={handleKeyDown}
|
||||
style={{ height: '100%' }}
|
||||
>
|
||||
<div style={{ height: totalHeight, position: 'relative' }}>
|
||||
{visibleLines.map(({ lineNum, content, isEdited }) => (
|
||||
<div
|
||||
key={lineNum}
|
||||
className="absolute flex"
|
||||
style={{
|
||||
top: lineNum * lineHeight,
|
||||
height: lineHeight,
|
||||
left: 0,
|
||||
right: 0,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="flex-shrink-0 text-right pr-3 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' : ''
|
||||
}`}
|
||||
style={{ lineHeight: `${lineHeight}px` }}
|
||||
/>
|
||||
) : (
|
||||
<div
|
||||
className="flex-1 pl-2 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>
|
||||
)
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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),
|
||||
})
|
||||
|
||||
|
||||
@@ -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>
|
||||
|
||||
Reference in new issue
Block a user