mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
refactor: improve virtualized text viewer with React Query infinite scroll and simplified buffering (#108)
* Add OAuth authentication support for MCP servers * Improve mobile text sizing with responsive text classes * refactor: improve virtualized text viewer with React Query infinite scroll and simplified buffering
This commit is contained in:
1 parent
c453235839
commit
f570758b74
24 files changed
+930
-471
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { useState, useCallback, useRef, useEffect, useMemo } from 'react'
|
||||
import { useState, useCallback, useMemo } from 'react'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { fetchFileRange, applyFilePatches } from '@/api/files'
|
||||
import type { PatchOperation } from '@/types/files'
|
||||
|
||||
@@ -20,7 +21,7 @@ interface UseVirtualizedContentReturn {
|
||||
totalLines: number
|
||||
isLoading: boolean
|
||||
error: Error | null
|
||||
loadRange: (startLine: number, endLine: number) => Promise<void>
|
||||
loadRange: (startLine: number, endLine: number) => void
|
||||
getVisibleRange: (scrollTop: number, viewportHeight: number, lineHeight: number) => { start: number; end: number }
|
||||
editedLines: Map<number, string>
|
||||
setLineContent: (lineNumber: number, content: string) => void
|
||||
@@ -40,101 +41,67 @@ export function useVirtualizedContent({
|
||||
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
|
||||
const [isSaving, setIsSaving] = useState(false)
|
||||
const [saveError, setSaveError] = useState<Error | null>(null)
|
||||
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
error: queryError,
|
||||
fetchNextPage,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['file-range', filePath],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
const result = await fetchFileRange(filePath, pageParam, pageParam + chunkSize)
|
||||
return result
|
||||
},
|
||||
initialPageParam: 0,
|
||||
getNextPageParam: (lastPage) => {
|
||||
if (!lastPage.hasMore) return undefined
|
||||
return lastPage.endLine
|
||||
},
|
||||
enabled: enabled && !!filePath,
|
||||
staleTime: 30_000,
|
||||
refetchOnWindowFocus: false,
|
||||
})
|
||||
|
||||
const totalLines = data?.pages[0]?.totalLines ?? 0
|
||||
|
||||
const lines = useMemo(() => {
|
||||
const map = new Map<number, LineData>()
|
||||
if (!data?.pages) return map
|
||||
|
||||
for (const page of data.pages) {
|
||||
page.lines.forEach((content, idx) => {
|
||||
map.set(page.startLine + idx, { content, loaded: true })
|
||||
})
|
||||
|
||||
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)
|
||||
return map
|
||||
}, [data?.pages])
|
||||
|
||||
const loadedEndLine = useMemo(() => {
|
||||
if (!data?.pages?.length) return 0
|
||||
return Math.max(...data.pages.map(p => p.endLine))
|
||||
}, [data?.pages])
|
||||
|
||||
const loadRange = useCallback((_startLine: number, endLine: number) => {
|
||||
if (endLine > loadedEndLine && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
|
||||
if (!isRangeLoaded(visibleEnd, prefetchAfter) && prefetchAfter > visibleEnd) {
|
||||
loadRange(visibleEnd, prefetchAfter)
|
||||
}
|
||||
}, [chunkSize, totalLines, isRangeLoaded, loadRange])
|
||||
|
||||
}, [loadedEndLine, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
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)
|
||||
const upperBound = totalLines > 0 ? totalLines : start + visibleCount + overscan * 2
|
||||
const end = Math.min(upperBound, start + visibleCount + overscan * 2)
|
||||
return { start, end }
|
||||
}, [totalLines, overscan])
|
||||
|
||||
|
||||
const setLineContent = useCallback((lineNumber: number, content: string) => {
|
||||
setEditedLines(prev => {
|
||||
const next = new Map(prev)
|
||||
@@ -142,21 +109,21 @@ export function useVirtualizedContent({
|
||||
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) {
|
||||
@@ -173,22 +140,22 @@ export function useVirtualizedContent({
|
||||
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)
|
||||
|
||||
setSaveError(null)
|
||||
|
||||
try {
|
||||
const dirtyRanges = getDirtyRanges()
|
||||
const patches: PatchOperation[] = dirtyRanges.map(range => ({
|
||||
@@ -197,67 +164,62 @@ export function useVirtualizedContent({
|
||||
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
|
||||
const error = err instanceof Error ? err : new Error('Failed to save edits')
|
||||
setSaveError(error)
|
||||
throw error
|
||||
} finally {
|
||||
setIsSaving(false)
|
||||
}
|
||||
}, [filePath, editedLines, getDirtyRanges, clearEdits])
|
||||
|
||||
useEffect(() => {
|
||||
if (enabled && filePath && totalLines === 0) {
|
||||
loadRange(0, chunkSize)
|
||||
|
||||
const prefetchAdjacent = useCallback((_visibleStart: number, visibleEnd: number) => {
|
||||
if (visibleEnd >= loadedEndLine - chunkSize && hasNextPage && !isFetchingNextPage) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [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
|
||||
|
||||
}, [loadedEndLine, chunkSize, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
|
||||
const loadAll = useCallback(async () => {
|
||||
if (!enabled || !filePath || totalLines === 0) return
|
||||
if (isRangeLoaded(0, totalLines)) return
|
||||
await loadRange(0, totalLines)
|
||||
}, [enabled, filePath, totalLines, isRangeLoaded, loadRange])
|
||||
|
||||
if (loadedEndLine >= totalLines) return
|
||||
|
||||
let safety = 0
|
||||
const maxIterations = Math.ceil(totalLines / chunkSize) + 1
|
||||
while (safety < maxIterations) {
|
||||
const result = await fetchNextPage()
|
||||
const pages = result.data?.pages
|
||||
if (!pages?.length) break
|
||||
const lastPage = pages[pages.length - 1]
|
||||
if (!lastPage.hasMore || lastPage.endLine >= totalLines) break
|
||||
safety++
|
||||
}
|
||||
}, [enabled, filePath, totalLines, loadedEndLine, chunkSize, fetchNextPage])
|
||||
|
||||
const isFullyLoaded = useMemo(() => {
|
||||
if (totalLines === 0) return false
|
||||
return isRangeLoaded(0, totalLines)
|
||||
}, [totalLines, isRangeLoaded])
|
||||
|
||||
return loadedEndLine >= totalLines
|
||||
}, [totalLines, loadedEndLine])
|
||||
|
||||
const fullContent = useMemo(() => {
|
||||
if (!isFullyLoaded || totalLines === 0) return null
|
||||
const result: string[] = []
|
||||
for (let i = 0; i < totalLines; i++) {
|
||||
const editedContent = editedLines.get(i)
|
||||
const lineData = lines.get(i)
|
||||
result.push(lineData?.content ?? '')
|
||||
result.push(editedContent ?? lineData?.content ?? '')
|
||||
}
|
||||
return result.join('\n')
|
||||
}, [isFullyLoaded, totalLines, lines])
|
||||
|
||||
}, [isFullyLoaded, totalLines, lines, editedLines])
|
||||
|
||||
const hasUnsavedChanges = editedLines.size > 0
|
||||
const error = queryError ?? saveError
|
||||
|
||||
return {
|
||||
lines,
|
||||
totalLines,
|
||||
|
||||
Reference in new issue
Block a user