mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 12:54:20 +01:00
fix(files): resolve workspace paths and add sandboxed HTML preview (#367)
* fix(files): resolve workspace paths and add sandboxed HTML preview Accept workspace-absolute paths in the file service and return repo-relative paths for file reads and directory listings. Serve raw content under a CSP sandbox and preview HTML files in a sandboxed iframe with a raw toggle. Resolve file-click paths from the session directory and repo local path, detect absolute and html/htm file references while ignoring URLs, accept the legacy filePath input key and filediff metadata, fix the file browser navigating into an initially selected directory, and use focus-visible rings across shared UI primitives. * fix(files): address review feedback on navigation and path fallback Key initial directory navigation to the initial selection so viewport changes do not reset it, and open the mobile preview from a separate effect. Fall back to the legacy filePath input when path is empty, and cover both with regression tests.
This commit is contained in:
1 parent
5bd688de4b
commit
68b13c8e35
19 files changed
+307
-58
No files matched your search
@@ -144,20 +144,11 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct
|
||||
|
||||
const dropZoneRef = useRef<HTMLDivElement>(null)
|
||||
const uploadCancelledRef = useRef(false)
|
||||
const loadRequestRef = useRef(0)
|
||||
const isMobile = useMobile()
|
||||
|
||||
const { data: initialFileData, error: initialFileError } = useFile(initialSelectedFile)
|
||||
|
||||
useEffect(() => {
|
||||
if (initialFileData) {
|
||||
setSelectedFile(initialFileData)
|
||||
if (isMobile) {
|
||||
setIsPreviewModalOpen(true)
|
||||
onPreviewStateChange?.(true)
|
||||
}
|
||||
}
|
||||
}, [initialFileData, isMobile, onPreviewStateChange])
|
||||
|
||||
useEffect(() => {
|
||||
if (initialFileError) {
|
||||
setError(initialFileError.message)
|
||||
@@ -165,6 +156,7 @@ useEffect(() => {
|
||||
}, [initialFileError])
|
||||
|
||||
const loadFiles = useCallback(async (path: string) => {
|
||||
const request = ++loadRequestRef.current
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
|
||||
@@ -175,13 +167,15 @@ useEffect(() => {
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
if (request !== loadRequestRef.current) return
|
||||
setFiles(data)
|
||||
setCurrentPath(path)
|
||||
onDirectoryLoad?.({ workspaceRoot: data.workspaceRoot, currentPath: path })
|
||||
} catch (err) {
|
||||
if (request !== loadRequestRef.current) return
|
||||
setError(err instanceof Error ? err.message : 'Failed to load files')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
if (request === loadRequestRef.current) setLoading(false)
|
||||
}
|
||||
}, [onDirectoryLoad])
|
||||
|
||||
@@ -448,6 +442,23 @@ useEffect(() => {
|
||||
loadFiles(basePath)
|
||||
}, [basePath, loadFiles])
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialFileData) return
|
||||
setError(null)
|
||||
if (initialFileData.isDirectory) {
|
||||
setSelectedFile(null)
|
||||
void loadFiles(initialFileData.path)
|
||||
return
|
||||
}
|
||||
setSelectedFile(initialFileData)
|
||||
}, [initialFileData, loadFiles])
|
||||
|
||||
useEffect(() => {
|
||||
if (!initialFileData || initialFileData.isDirectory || !isMobile) return
|
||||
setIsPreviewModalOpen(true)
|
||||
onPreviewStateChange?.(true)
|
||||
}, [initialFileData, isMobile, onPreviewStateChange])
|
||||
|
||||
useEffect(() => {
|
||||
const handleFileSaved = (event: CustomEvent<{ path: string; content?: string }>) => {
|
||||
if (selectedFile && selectedFile.path === event.detail.path) {
|
||||
|
||||
@@ -86,6 +86,88 @@ describe('FileBrowserSheet', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileBrowser initial selection', () => {
|
||||
it('navigates into an initially selected directory even when the base listing resolves later', async () => {
|
||||
const directory = (path: string, children: string[]) => ({
|
||||
name: path.split('/').pop(),
|
||||
path,
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
lastModified: new Date().toISOString(),
|
||||
children: children.map((name) => ({ name, path: `${path}/${name}`, isDirectory: true, size: 0, lastModified: new Date().toISOString() })),
|
||||
})
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = new URL(String(input), 'http://localhost').searchParams.get('path')
|
||||
if (path === 'repo') {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
return new Response(JSON.stringify(directory('repo', ['frontend'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
}
|
||||
return new Response(JSON.stringify(directory('repo/frontend', ['src'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const ref = { current: null as unknown as FileBrowserHandle }
|
||||
|
||||
try {
|
||||
render(
|
||||
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />,
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
expect(await screen.findByText('src')).toBeInTheDocument()
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
expect(ref.current.getCurrentPath()).toBe('repo/frontend')
|
||||
expect(screen.queryByText('frontend')).not.toBeInTheDocument()
|
||||
} finally {
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
|
||||
it('does not reload the initial directory when the viewport changes', async () => {
|
||||
const directory = (path: string, children: string[]) => ({
|
||||
name: path.split('/').pop(),
|
||||
path,
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
lastModified: new Date().toISOString(),
|
||||
children: children.map((name) => ({ name, path: `${path}/${name}`, isDirectory: true, size: 0, lastModified: new Date().toISOString() })),
|
||||
})
|
||||
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = new URL(String(input), 'http://localhost').searchParams.get('path')
|
||||
if (path === 'repo') {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50))
|
||||
return new Response(JSON.stringify(directory('repo', ['frontend'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
}
|
||||
return new Response(JSON.stringify(directory('repo/frontend', ['src'])), { status: 200, headers: { 'Content-Type': 'application/json' } })
|
||||
})
|
||||
vi.stubGlobal('fetch', fetchMock)
|
||||
const mobileSpy = vi.spyOn(useMobile, 'useMobile').mockReturnValue(false)
|
||||
const ref = { current: null as unknown as FileBrowserHandle }
|
||||
|
||||
try {
|
||||
const { rerender } = render(
|
||||
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />,
|
||||
{ wrapper: createWrapper() }
|
||||
)
|
||||
|
||||
expect(await screen.findByText('src')).toBeInTheDocument()
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
const callsBefore = fetchMock.mock.calls.length
|
||||
|
||||
mobileSpy.mockReturnValue(true)
|
||||
rerender(
|
||||
<FileBrowser ref={ref as never} basePath="repo" embedded={true} initialSelectedFile="repo/frontend" />
|
||||
)
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 100))
|
||||
expect(fetchMock.mock.calls.length).toBe(callsBefore)
|
||||
expect(ref.current.getCurrentPath()).toBe('repo/frontend')
|
||||
} finally {
|
||||
mobileSpy.mockRestore()
|
||||
vi.unstubAllGlobals()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('FileBrowser navigation', () => {
|
||||
it('exposes imperative handle with goBack, canGoBack, and getCurrentPath', () => {
|
||||
const ref = { current: null as unknown as FileBrowserHandle }
|
||||
|
||||
@@ -40,6 +40,21 @@ describe('FilePreview header buttons', () => {
|
||||
expect(active.className).not.toMatch(OUTLINE_DARK_OVERRIDE)
|
||||
})
|
||||
|
||||
it('renders HTML files in a sandboxed iframe with a raw toggle', () => {
|
||||
render(<FilePreview file={textFile('report.html', 'text/html')} />)
|
||||
|
||||
const frame = screen.getByTitle('report.html')
|
||||
expect(frame.tagName).toBe('IFRAME')
|
||||
expect(frame).toHaveAttribute('sandbox', 'allow-scripts')
|
||||
expect(frame.getAttribute('src')).toContain('raw=true')
|
||||
expect(screen.getByTitle('Open HTML in new tab')).toHaveAttribute('target', '_blank')
|
||||
|
||||
fireEvent.click(screen.getByTitle('Show raw HTML'))
|
||||
|
||||
expect(screen.queryByTitle('report.html')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('# heading')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the success and destructive tints on the edit actions in dark mode', () => {
|
||||
render(<FilePreview file={textFile('Dockerfile', 'text/plain')} />)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState, useCallback, useRef, useEffect, memo } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code } from 'lucide-react'
|
||||
import { Download, X, Edit3, Save, X as XIcon, WrapText, Eye, Code, ExternalLink } from 'lucide-react'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { saveFileFromUrl } from '@/lib/download'
|
||||
@@ -24,6 +24,9 @@ interface FilePreviewProps {
|
||||
|
||||
export const FilePreview = memo(function FilePreview({ file, hideHeader = false, isMobileModal = false, onCloseModal, onFileSaved, initialLineNumber }: FilePreviewProps) {
|
||||
const isMarkdownFile = file.name.toLowerCase().endsWith('.md') || file.name.toLowerCase().endsWith('.mdx') || file.mimeType === 'text/markdown'
|
||||
const isHtmlFile = /\.html?$/i.test(file.name) || file.mimeType === 'text/html'
|
||||
const hasRenderedPreview = isMarkdownFile || isHtmlFile
|
||||
const previewLabel = isHtmlFile ? 'HTML' : 'markdown'
|
||||
|
||||
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
|
||||
const [editContent, setEditContent] = useState('')
|
||||
@@ -31,7 +34,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
const [hasVirtualizedChanges, setHasVirtualizedChanges] = useState(false)
|
||||
const [highlightedLine, setHighlightedLine] = useState<number | undefined>(initialLineNumber)
|
||||
const [lineWrap, setLineWrap] = useState(true)
|
||||
const [markdownPreview, setMarkdownPreview] = useState(isMarkdownFile)
|
||||
const [renderedPreview, setRenderedPreview] = useState(hasRenderedPreview)
|
||||
const [isLoadingAllContent, setIsLoadingAllContent] = useState(false)
|
||||
const [fullContentLoaded, setFullContentLoaded] = useState(false)
|
||||
const [fullContent, setFullContent] = useState<string | null>(null)
|
||||
@@ -41,16 +44,18 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
|
||||
const shouldVirtualize = file.size > VIRTUALIZATION_THRESHOLD_BYTES && !file.mimeType?.startsWith('image/')
|
||||
const isMarkdownTooLarge = file.size > MARKDOWN_PREVIEW_SIZE_LIMIT
|
||||
const showHtmlPreview = isHtmlFile && renderedPreview && viewMode !== 'edit'
|
||||
const rawFileUrl = getFileApiUrl(file.path, { params: { raw: true } })
|
||||
|
||||
useEffect(() => {
|
||||
setFullContentLoaded(false)
|
||||
setMarkdownPreview(isMarkdownFile)
|
||||
setRenderedPreview(hasRenderedPreview)
|
||||
setFullContent(null)
|
||||
setLocalMdContent(null)
|
||||
}, [file.path, isMarkdownFile])
|
||||
}, [file.path, hasRenderedPreview])
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualize && isMarkdownFile && markdownPreview && !isMarkdownTooLarge && !fullContentLoaded) {
|
||||
if (shouldVirtualize && isMarkdownFile && renderedPreview && !isMarkdownTooLarge && !fullContentLoaded) {
|
||||
const loadContent = async () => {
|
||||
if (!virtualizedRef.current) return
|
||||
setIsLoadingAllContent(true)
|
||||
@@ -66,7 +71,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
const timer = setTimeout(loadContent, 0)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
}, [shouldVirtualize, isMarkdownFile, markdownPreview, isMarkdownTooLarge, fullContentLoaded])
|
||||
}, [shouldVirtualize, isMarkdownFile, renderedPreview, isMarkdownTooLarge, fullContentLoaded])
|
||||
|
||||
|
||||
|
||||
@@ -216,7 +221,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
return (
|
||||
<div className="flex justify-center p-4">
|
||||
<img
|
||||
src={getFileApiUrl(file.path, { params: { raw: true } })}
|
||||
src={rawFileUrl}
|
||||
alt={file.name}
|
||||
className="max-w-full h-auto object-contain rounded"
|
||||
/>
|
||||
@@ -224,8 +229,19 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
)
|
||||
}
|
||||
|
||||
if (showHtmlPreview) {
|
||||
return (
|
||||
<iframe
|
||||
src={rawFileUrl}
|
||||
title={file.name}
|
||||
sandbox="allow-scripts"
|
||||
className="w-full h-full border-0 bg-white"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (shouldVirtualize && isTextFile) {
|
||||
const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit'
|
||||
const showMarkdownPreview = isMarkdownFile && renderedPreview && viewMode !== 'edit'
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -248,7 +264,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
{isMarkdownTooLarge ? (
|
||||
<div className="flex flex-col items-center justify-center h-32 gap-2 text-muted-foreground">
|
||||
<span>File too large for markdown preview (max 1MB)</span>
|
||||
<Button variant="outline" size="sm" onClick={() => setMarkdownPreview(false)}>
|
||||
<Button variant="outline" size="sm" onClick={() => setRenderedPreview(false)}>
|
||||
View raw
|
||||
</Button>
|
||||
</div>
|
||||
@@ -295,7 +311,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
)
|
||||
}
|
||||
|
||||
if (isMarkdownFile && markdownPreview) {
|
||||
if (isMarkdownFile && renderedPreview) {
|
||||
return <MarkdownRenderer content={displayContent} onContentChange={handleLocalMarkdownContentChange} />
|
||||
}
|
||||
|
||||
@@ -379,19 +395,27 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1 flex-shrink-0 mt-1">
|
||||
{isMarkdownFile && viewMode !== 'edit' && (
|
||||
{hasRenderedPreview && viewMode !== 'edit' && (
|
||||
<Button
|
||||
variant={markdownPreview ? 'default' : 'outline'}
|
||||
variant={renderedPreview ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setMarkdownPreview(!markdownPreview) }}
|
||||
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setRenderedPreview(!renderedPreview) }}
|
||||
className="h-7 w-7 p-0"
|
||||
title={markdownPreview ? "Show raw markdown" : "Preview rendered markdown"}
|
||||
title={renderedPreview ? `Show raw ${previewLabel}` : `Preview rendered ${previewLabel}`}
|
||||
>
|
||||
{markdownPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
{renderedPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isHtmlFile && viewMode !== 'edit' && (
|
||||
<Button variant="outline" size="sm" asChild className="h-7 w-7 p-0">
|
||||
<a href={rawFileUrl} target="_blank" rel="noopener noreferrer" title="Open HTML in new tab" onClick={(e) => e.stopPropagation()}>
|
||||
<ExternalLink className="w-3 h-3" />
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isTextFile && !markdownPreview && (
|
||||
{isTextFile && !renderedPreview && (
|
||||
<Button
|
||||
variant={lineWrap ? 'default' : 'outline'}
|
||||
size="sm"
|
||||
@@ -439,9 +463,9 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
|
||||
<div
|
||||
ref={contentRef}
|
||||
className={`flex-1 ${viewMode === 'edit' && !shouldVirtualize ? 'overflow-hidden' : shouldVirtualize ? '' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}
|
||||
className={`flex-1 ${viewMode === 'edit' && !shouldVirtualize ? 'overflow-hidden' : shouldVirtualize || showHtmlPreview ? '' : 'overflow-y-auto overscroll-contain'} min-h-0 overflow-x-hidden`}
|
||||
>
|
||||
<div className={`${shouldVirtualize ? 'h-full' : 'p-2'} min-w-0`}>
|
||||
<div className={`${shouldVirtualize || showHtmlPreview ? 'h-full' : 'p-2'} min-w-0`}>
|
||||
{renderContent()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user