Files
opencode-manager/frontend/src/api/files.ts
T
Chris Scott 31755c23f8 refactor: improve file browser path resolution and navigation (#193)
- Add query parameter support for file paths to handle special characters
- Enable navigation above base path with proper validation
- Centralize URL encoding logic for file API calls
- Update path validation to use workspace base instead of repos base
- Add normalizePath utility for consistent path handling
2026-04-23 17:06:49 -04:00

67 lines
2.3 KiB
TypeScript

import { useQuery } from '@tanstack/react-query'
import { fetchWrapper, fetchWrapperBlob } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { FileInfo, ChunkedFileInfo, PatchOperation } from '@/types/files'
function getFileApiUrl(path: string): string {
if (path.includes('..')) {
return `${API_BASE_URL}/api/files/?path=${encodeURIComponent(path)}`
}
return `${API_BASE_URL}/api/files/${path.split('/').map(encodeURIComponent).join('/')}`
}
async function fetchFile(path: string): Promise<FileInfo> {
return fetchWrapper(getFileApiUrl(path))
}
export function useFile(path: string | undefined) {
return useQuery({
queryKey: ['file', path],
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> {
return fetchWrapper(getFileApiUrl(path), {
params: { startLine, endLine },
})
}
export async function applyFilePatches(path: string, patches: PatchOperation[]): Promise<{ success: boolean; totalLines: number }> {
return fetchWrapper(getFileApiUrl(path), {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ patches }),
})
}
export async function getIgnoredPaths(path: string): Promise<{ ignoredPaths: string[] }> {
return fetchWrapper(`${API_BASE_URL}/api/files/${path}/ignored-paths`)
}
export interface DownloadOptions {
includeGit?: boolean
includePaths?: string[]
}
export async function downloadDirectoryAsZip(path: string, options?: DownloadOptions): Promise<void> {
const params = new URLSearchParams()
if (options?.includeGit) params.append('includeGit', 'true')
if (options?.includePaths?.length) params.append('includePaths', options.includePaths.join(','))
const url = `${API_BASE_URL}/api/files/${path}/download-zip${params.toString() ? '?' + params.toString() : ''}`
const blob = await fetchWrapperBlob(url)
const urlObj = window.URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = urlObj
const dirName = path.split('/').pop() || 'download'
a.download = `${dirName}.zip`
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
window.URL.revokeObjectURL(urlObj)
}