mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 20:34:18 +01:00
feat: add HTML artifact preview for inline and file-based HTML outputs
This commit is contained in:
1 parent
5b85abd627
commit
7f9403ce5e
21 files changed
+1323
-62
No files matched your search
@@ -23,12 +23,103 @@ function getSpecialRoutePathFromRequest(c: Context, routeName: string): string |
|
||||
return match?.[1] ? decodeFilePath(match[1]) : undefined
|
||||
}
|
||||
|
||||
function getPreviewPathFromRequest(c: Context): string | undefined {
|
||||
const path = c.req.path
|
||||
const prefix = '/api/files/preview'
|
||||
|
||||
const queryPath = c.req.query('path')
|
||||
if (queryPath !== undefined) {
|
||||
return queryPath
|
||||
}
|
||||
|
||||
if (path.startsWith(prefix + '/')) {
|
||||
const previewPath = path.slice(prefix.length + 1)
|
||||
return decodeURIComponent(previewPath)
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
const PREVIEWABLE_MIME_TYPES = new Set([
|
||||
'text/html',
|
||||
'text/css',
|
||||
'text/javascript',
|
||||
'application/javascript',
|
||||
'application/json',
|
||||
'application/xml',
|
||||
'image/png',
|
||||
'image/jpeg',
|
||||
'image/gif',
|
||||
'image/svg+xml',
|
||||
])
|
||||
|
||||
function isPreviewableMimeType(mimeType?: string): boolean {
|
||||
return mimeType !== undefined && PREVIEWABLE_MIME_TYPES.has(mimeType)
|
||||
}
|
||||
|
||||
function getPreviewHeaders(result: { name: string; size: number; mimeType?: string }): Record<string, string> {
|
||||
const isHtmlSvg = result.mimeType === 'text/html' || result.mimeType === 'image/svg+xml'
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': result.mimeType || 'application/octet-stream',
|
||||
'Content-Length': result.size.toString(),
|
||||
'Content-Disposition': `inline; filename="${result.name}"`,
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'no-referrer',
|
||||
}
|
||||
|
||||
if (isHtmlSvg) {
|
||||
headers['Content-Security-Policy'] = [
|
||||
'sandbox allow-scripts;',
|
||||
"default-src 'self' http: https: data: blob: 'unsafe-inline' 'unsafe-eval';",
|
||||
"script-src 'self' http: https: 'unsafe-inline' 'unsafe-eval';",
|
||||
"style-src 'self' http: https: 'unsafe-inline';",
|
||||
"img-src 'self' http: https: data: blob:;",
|
||||
"font-src 'self' http: https: data:;",
|
||||
"connect-src 'self' http: https:;",
|
||||
"media-src 'self' http: https: data: blob:;",
|
||||
"object-src 'none';",
|
||||
"base-uri 'none';",
|
||||
"frame-ancestors 'self'",
|
||||
].join(' ')
|
||||
}
|
||||
|
||||
return headers
|
||||
}
|
||||
|
||||
export function createFileRoutes() {
|
||||
const app = new Hono()
|
||||
|
||||
app.get('*', async (c) => {
|
||||
const path = c.req.path
|
||||
|
||||
if (path === '/api/files/preview' || path.startsWith('/api/files/preview/')) {
|
||||
const userPath = getPreviewPathFromRequest(c)
|
||||
|
||||
if (!userPath) {
|
||||
return c.json({ error: 'No path provided' }, 400)
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await fileService.getFile(userPath)
|
||||
|
||||
if (result.isDirectory) {
|
||||
return c.json({ error: 'Cannot preview directories' }, 400)
|
||||
}
|
||||
|
||||
if (!isPreviewableMimeType(result.mimeType)) {
|
||||
return c.json({ error: 'File type cannot be previewed' }, 415)
|
||||
}
|
||||
|
||||
const content = await fileService.getRawFileContent(userPath)
|
||||
const headers = getPreviewHeaders(result)
|
||||
|
||||
return new Response(content, { headers })
|
||||
} catch (error: unknown) {
|
||||
logger.error('Failed to preview file:', error)
|
||||
return c.json({ error: getErrorMessage(error) || 'Failed to preview file' }, getStatusCode(error) as ContentfulStatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
if (path.endsWith('/download-zip')) {
|
||||
const userPath = getSpecialRoutePathFromRequest(c, 'download-zip')
|
||||
|
||||
|
||||
@@ -253,6 +253,7 @@ function getMimeType(filePath: string): AllowedMimeType {
|
||||
const mimeTypes: Record<string, AllowedMimeType> = {
|
||||
'.txt': 'text/plain',
|
||||
'.html': 'text/html',
|
||||
'.htm': 'text/html',
|
||||
'.css': 'text/css',
|
||||
'.js': 'text/javascript',
|
||||
'.ts': 'text/typescript',
|
||||
|
||||
@@ -47,6 +47,7 @@ vi.mock('../../src/services/archive', () => ({
|
||||
}))
|
||||
|
||||
const getFile = fileService.getFile as MockedFunction<typeof fileService.getFile>
|
||||
const getRawFileContent = fileService.getRawFileContent as MockedFunction<typeof fileService.getRawFileContent>
|
||||
const getFileRange = fileService.getFileRange as MockedFunction<typeof fileService.getFileRange>
|
||||
const uploadFile = fileService.uploadFile as MockedFunction<typeof fileService.uploadFile>
|
||||
const createFileOrFolder = fileService.createFileOrFolder as MockedFunction<typeof fileService.createFileOrFolder>
|
||||
@@ -69,6 +70,125 @@ describe('File Routes', () => {
|
||||
app.route('/api/files', filesApp)
|
||||
})
|
||||
|
||||
describe('GET /preview/* - HTML Preview Assets', () => {
|
||||
const htmlFileInfo: FileInfo = {
|
||||
name: 'index.html',
|
||||
path: 'test-repo/index.html',
|
||||
isDirectory: false,
|
||||
size: 31,
|
||||
mimeType: 'text/html',
|
||||
content: '',
|
||||
lastModified: new Date(),
|
||||
}
|
||||
|
||||
it('should serve HTML files with sandbox CSP headers', async () => {
|
||||
getFile.mockResolvedValue(htmlFileInfo)
|
||||
getRawFileContent.mockResolvedValue(Buffer.from('<html><body>Hello</body></html>'))
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/index.html')
|
||||
const body = await response.text()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toBe('<html><body>Hello</body></html>')
|
||||
expect(response.headers.get('Content-Type')).toContain('text/html')
|
||||
expect(response.headers.get('Content-Disposition')).toContain('inline')
|
||||
expect(response.headers.get('X-Content-Type-Options')).toBe('nosniff')
|
||||
expect(response.headers.get('Referrer-Policy')).toBe('no-referrer')
|
||||
expect(response.headers.get('Content-Security-Policy')).toContain('sandbox allow-scripts')
|
||||
expect(response.headers.get('Content-Security-Policy')).toContain('https:')
|
||||
expect(getFile).toHaveBeenCalledWith('test-repo/index.html')
|
||||
expect(getRawFileContent).toHaveBeenCalledWith('test-repo/index.html')
|
||||
})
|
||||
|
||||
it('should serve CSS files with text/css Content-Type', async () => {
|
||||
const cssFileInfo: FileInfo = {
|
||||
name: 'styles.css',
|
||||
path: 'test-repo/styles/app.css',
|
||||
isDirectory: false,
|
||||
size: 50,
|
||||
mimeType: 'text/css',
|
||||
content: '',
|
||||
lastModified: new Date(),
|
||||
}
|
||||
getFile.mockResolvedValue(cssFileInfo)
|
||||
getRawFileContent.mockResolvedValue(Buffer.from('body { color: red }'))
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/styles/app.css')
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get('Content-Type')).toContain('text/css')
|
||||
expect(response.headers.get('Content-Security-Policy')).toBeNull()
|
||||
expect(getFile).toHaveBeenCalledWith('test-repo/styles/app.css')
|
||||
})
|
||||
|
||||
it('should support query-based path parameter', async () => {
|
||||
getFile.mockResolvedValue(htmlFileInfo)
|
||||
getRawFileContent.mockResolvedValue(Buffer.from('<html><body>Hello</body></html>'))
|
||||
|
||||
const response = await app.request('/api/files/preview?path=test-repo/index.html')
|
||||
const body = await response.text()
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toBe('<html><body>Hello</body></html>')
|
||||
expect(getFile).toHaveBeenCalledWith('test-repo/index.html')
|
||||
})
|
||||
|
||||
it('should return 400 for directory results', async () => {
|
||||
const dirInfo: FileInfo = {
|
||||
name: 'test-repo',
|
||||
path: 'test-repo',
|
||||
isDirectory: true,
|
||||
size: 0,
|
||||
lastModified: new Date(),
|
||||
}
|
||||
getFile.mockResolvedValue(dirInfo)
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo')
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('Cannot preview directories')
|
||||
})
|
||||
|
||||
it('should return 415 for non-previewable MIME types', async () => {
|
||||
const pdfFileInfo: FileInfo = {
|
||||
name: 'doc.pdf',
|
||||
path: 'test-repo/doc.pdf',
|
||||
isDirectory: false,
|
||||
size: 100,
|
||||
mimeType: 'application/pdf',
|
||||
content: '',
|
||||
lastModified: new Date(),
|
||||
}
|
||||
getFile.mockResolvedValue(pdfFileInfo)
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/doc.pdf')
|
||||
|
||||
expect(response.status).toBe(415)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('File type cannot be previewed')
|
||||
})
|
||||
|
||||
it('should return 400 when no path is provided', async () => {
|
||||
const response = await app.request('/api/files/preview')
|
||||
|
||||
expect(response.status).toBe(400)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('No path provided')
|
||||
})
|
||||
|
||||
it('should return 403 for path traversal attempts', async () => {
|
||||
const error = { message: 'Path traversal detected', statusCode: 403 }
|
||||
getFile.mockRejectedValue(error)
|
||||
|
||||
const response = await app.request('/api/files/preview/test-repo/../outside')
|
||||
|
||||
expect(response.status).toBe(403)
|
||||
const body = await response.json() as { error: string }
|
||||
expect(body.error).toContain('Path traversal detected')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /*/download-zip - Route Order Regression Test', () => {
|
||||
it('should route to archive service for directory download, not file service', async () => {
|
||||
const mockStream = {
|
||||
@@ -175,6 +295,17 @@ describe('File Routes', () => {
|
||||
expect(response.status).toBe(404)
|
||||
expect(body).toHaveProperty('error')
|
||||
})
|
||||
|
||||
it('should route paths starting with "preview" but not matching /preview/ to generic handler', async () => {
|
||||
getFile.mockResolvedValue(mockFileInfo)
|
||||
|
||||
const response = await app.request('/api/files/previewer')
|
||||
const body = await response.json() as FileInfo
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(body).toHaveProperty('isDirectory', false)
|
||||
expect(getFile).toHaveBeenCalledWith('previewer')
|
||||
})
|
||||
})
|
||||
|
||||
describe('GET /* with ?startLine&endLine - File Range', () => {
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getFileApiUrl } from './files'
|
||||
import { encodePathForRoute, getFilePreviewUrl } from './files'
|
||||
|
||||
describe('getFilePreviewUrl', () => {
|
||||
it('constructs preview URL with encoded path segments', () => {
|
||||
const url = getFilePreviewUrl('repo/dir/index.html')
|
||||
expect(url).toBe('/api/files/preview/repo/dir/index.html')
|
||||
})
|
||||
|
||||
it('encodes spaces per segment', () => {
|
||||
const url = getFilePreviewUrl('my repo/file name.html')
|
||||
expect(url).toBe('/api/files/preview/my%20repo/file%20name.html')
|
||||
})
|
||||
|
||||
it('encodes hash characters per segment', () => {
|
||||
const url = getFilePreviewUrl('repo/file#1.html')
|
||||
expect(url).toBe('/api/files/preview/repo/file%231.html')
|
||||
})
|
||||
})
|
||||
|
||||
describe('encodePathForRoute', () => {
|
||||
it('encodes each path segment separately', () => {
|
||||
const result = encodePathForRoute('repo/dir/index.html')
|
||||
expect(result).toBe('repo/dir/index.html')
|
||||
})
|
||||
|
||||
it('encodes special characters per segment', () => {
|
||||
const result = encodePathForRoute('my dir/file name.html')
|
||||
expect(result).toBe('my%20dir/file%20name.html')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getFileApiUrl - existing behavior unchanged', () => {
|
||||
it('still returns a URL with path query param', () => {
|
||||
const url = getFileApiUrl('repo/dir/index.html')
|
||||
expect(url).toContain('/api/files')
|
||||
expect(url).toContain('path=repo%2Fdir%2Findex.html')
|
||||
})
|
||||
})
|
||||
@@ -77,3 +77,12 @@ export async function applyFilePatches(path: string, patches: PatchOperation[]):
|
||||
body: JSON.stringify({ patches }),
|
||||
})
|
||||
}
|
||||
|
||||
export function encodePathForRoute(path: string): string {
|
||||
return path.split('/').map(encodeURIComponent).join('/')
|
||||
}
|
||||
|
||||
export function getFilePreviewUrl(path: string): string {
|
||||
const encodedPath = encodePathForRoute(path)
|
||||
return `${API_BASE_URL}/api/files/preview/${encodedPath}`
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import '@testing-library/jest-dom'
|
||||
import { FilePreview } from './FilePreview'
|
||||
import type { FileInfo } from '@/types/files'
|
||||
|
||||
vi.mock('@/api/files', () => ({
|
||||
getFileApiUrl: (path: string) => `/api/files?path=${encodeURIComponent(path)}`,
|
||||
getFilePreviewUrl: (path: string) => {
|
||||
const encodedPath = path.split('/').map(encodeURIComponent).join('/')
|
||||
return `/api/files/preview/${encodedPath}`
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/components/ui/virtualized-text-view', () => ({
|
||||
VirtualizedTextView: vi.fn(() => <div data-testid="virtualized-text-view" />),
|
||||
}))
|
||||
|
||||
function htmlFile(content: string, overrides?: Partial<FileInfo>): FileInfo {
|
||||
return {
|
||||
name: 'dashboard.html',
|
||||
path: 'test-repo/dashboard.html',
|
||||
isDirectory: false,
|
||||
size: content.length,
|
||||
mimeType: 'text/html',
|
||||
content: btoa(content),
|
||||
lastModified: new Date(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function textFile(name: string, content: string, mimeType: string): FileInfo {
|
||||
return {
|
||||
name,
|
||||
path: `test-repo/${name}`,
|
||||
isDirectory: false,
|
||||
size: content.length,
|
||||
mimeType,
|
||||
content: btoa(content),
|
||||
lastModified: new Date(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('FilePreview - HTML preview', () => {
|
||||
it('renders HTML preview iframe by default for .html file', () => {
|
||||
render(<FilePreview file={htmlFile('<h1>Dashboard</h1>')} />)
|
||||
|
||||
const iframe = screen.getByTitle('HTML preview: dashboard.html')
|
||||
expect(iframe).toBeInTheDocument()
|
||||
expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
|
||||
expect(iframe.getAttribute('src')).toContain('/api/files/preview/test-repo/dashboard.html')
|
||||
})
|
||||
|
||||
it('toggles to source view when code button is clicked', () => {
|
||||
render(<FilePreview file={htmlFile('<h1>Dashboard</h1>')} />)
|
||||
|
||||
const toggleButton = screen.getByTitle('Show HTML source')
|
||||
expect(toggleButton).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(toggleButton)
|
||||
|
||||
expect(screen.queryByTitle('HTML preview: dashboard.html')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('<h1>Dashboard</h1>')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('toggles back to preview when eye button is clicked from source view', () => {
|
||||
render(<FilePreview file={htmlFile('<h1>Dashboard</h1>')} />)
|
||||
|
||||
const showSourceButton = screen.getByTitle('Show HTML source')
|
||||
fireEvent.click(showSourceButton)
|
||||
expect(screen.queryByTitle('HTML preview: dashboard.html')).not.toBeInTheDocument()
|
||||
|
||||
const showPreviewButton = screen.getByTitle('Preview rendered HTML')
|
||||
expect(showPreviewButton).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(showPreviewButton)
|
||||
|
||||
const iframe = screen.getByTitle('HTML preview: dashboard.html')
|
||||
expect(iframe).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders HTML preview for .htm file', () => {
|
||||
render(<FilePreview file={htmlFile('<p>HTM test</p>', { name: 'test.htm', path: 'test-repo/test.htm', mimeType: 'text/html' })} />)
|
||||
|
||||
const iframe = screen.getByTitle('HTML preview: test.htm')
|
||||
expect(iframe).toBeInTheDocument()
|
||||
expect(iframe.getAttribute('src')).toContain('/api/files/preview/test-repo/test.htm')
|
||||
})
|
||||
|
||||
it('does not show HTML preview toggle for non-HTML text file', () => {
|
||||
render(<FilePreview file={textFile('readme.txt', 'Hello world', 'text/plain')} />)
|
||||
|
||||
expect(screen.queryByTitle('Show HTML source')).not.toBeInTheDocument()
|
||||
expect(screen.queryByTitle('Preview rendered HTML')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('Hello world')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('preserves markdown preview behavior for .md files', () => {
|
||||
render(<FilePreview file={textFile('readme.md', '# Hello', 'text/markdown')} />)
|
||||
|
||||
const toggleButton = screen.getByTitle('Show raw markdown')
|
||||
expect(toggleButton).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -2,9 +2,11 @@ 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 type { FileInfo } from '@/types/files'
|
||||
import { getFileApiUrl } from '@/api/files'
|
||||
import { getFileApiUrl, getFilePreviewUrl } from '@/api/files'
|
||||
import { VirtualizedTextView, type VirtualizedTextViewHandle } from '@/components/ui/virtualized-text-view'
|
||||
import { MarkdownRenderer } from './MarkdownRenderer'
|
||||
import { HtmlPreviewFrame } from '@/components/html-preview/HtmlPreviewFrame'
|
||||
import { isHtmlPath } from '@/lib/htmlArtifacts'
|
||||
|
||||
|
||||
const VIRTUALIZATION_THRESHOLD_BYTES = 50_000
|
||||
@@ -21,6 +23,7 @@ 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 = isHtmlPath(file.name) || file.mimeType === 'text/html'
|
||||
|
||||
const [viewMode, setViewMode] = useState<'preview' | 'edit'>('preview')
|
||||
const [editContent, setEditContent] = useState('')
|
||||
@@ -29,6 +32,7 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
const [highlightedLine, setHighlightedLine] = useState<number | undefined>(initialLineNumber)
|
||||
const [lineWrap, setLineWrap] = useState(true)
|
||||
const [markdownPreview, setMarkdownPreview] = useState(isMarkdownFile)
|
||||
const [htmlPreview, setHtmlPreview] = useState(isHtmlFile)
|
||||
const [isLoadingAllContent, setIsLoadingAllContent] = useState(false)
|
||||
const [fullContentLoaded, setFullContentLoaded] = useState(false)
|
||||
const [fullContent, setFullContent] = useState<string | null>(null)
|
||||
@@ -42,9 +46,10 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
useEffect(() => {
|
||||
setFullContentLoaded(false)
|
||||
setMarkdownPreview(isMarkdownFile)
|
||||
setHtmlPreview(isHtmlFile)
|
||||
setFullContent(null)
|
||||
setLocalMdContent(null)
|
||||
}, [file.path, isMarkdownFile])
|
||||
}, [file.path, isMarkdownFile, isHtmlFile])
|
||||
|
||||
useEffect(() => {
|
||||
if (shouldVirtualize && isMarkdownFile && markdownPreview && !isMarkdownTooLarge && !fullContentLoaded) {
|
||||
@@ -227,8 +232,17 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
}
|
||||
|
||||
if (shouldVirtualize && isTextFile) {
|
||||
const showHtmlPreview = isHtmlFile && htmlPreview && viewMode !== 'edit'
|
||||
const showMarkdownPreview = isMarkdownFile && markdownPreview && viewMode !== 'edit'
|
||||
|
||||
if (showHtmlPreview) {
|
||||
return (
|
||||
<div className="h-[calc(100vh-12rem)] min-h-[480px] rounded border border-border overflow-hidden bg-white">
|
||||
<HtmlPreviewFrame title={`HTML preview: ${file.name}`} src={getFilePreviewUrl(file.path)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className={showMarkdownPreview && fullContentLoaded ? 'hidden' : 'h-full'}>
|
||||
@@ -285,6 +299,14 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
if (isHtmlFile && htmlPreview) {
|
||||
return (
|
||||
<div className="h-[calc(100vh-12rem)] min-h-[480px] rounded border border-border overflow-hidden bg-white">
|
||||
<HtmlPreviewFrame title={`HTML preview: ${file.name}`} src={getFilePreviewUrl(file.path)} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
const textContent = decodeBase64(file.content)
|
||||
@@ -392,8 +414,20 @@ export const FilePreview = memo(function FilePreview({ file, hideHeader = false,
|
||||
{markdownPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isHtmlFile && viewMode !== 'edit' && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={(e) => { e.stopPropagation(); e.preventDefault(); setHtmlPreview(!htmlPreview) }}
|
||||
className={`h-7 w-7 p-0 ${htmlPreview ? 'bg-primary text-primary-foreground' : ''}`}
|
||||
title={htmlPreview ? "Show HTML source" : "Preview rendered HTML"}
|
||||
>
|
||||
{htmlPreview ? <Code className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{isTextFile && !markdownPreview && (
|
||||
{isTextFile && !markdownPreview && !htmlPreview && (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { HtmlArtifactPanel } from './HtmlArtifactPanel'
|
||||
import type { HtmlArtifact } from '@/lib/htmlArtifacts'
|
||||
|
||||
vi.mock('@/api/files', () => ({
|
||||
getFilePreviewUrl: (path: string) => `/api/files/preview/${encodeURIComponent(path)}`,
|
||||
}))
|
||||
|
||||
function createInlineArtifact(overrides?: Partial<HtmlArtifact>): HtmlArtifact {
|
||||
return {
|
||||
id: 'test-1',
|
||||
title: 'Test Preview',
|
||||
source: 'inline',
|
||||
html: '<h1>Hello World</h1>',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
function createFileArtifact(overrides?: Partial<HtmlArtifact>): HtmlArtifact {
|
||||
return {
|
||||
id: 'test-2',
|
||||
title: 'File Preview',
|
||||
source: 'file',
|
||||
path: 'my-repo/dist/index.html',
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('HtmlArtifactPanel', () => {
|
||||
it('renders inline artifact with srcdoc and sandbox attribute', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const iframe = screen.getByTitle('Test Preview')
|
||||
expect(iframe).toBeInTheDocument()
|
||||
expect(iframe).toHaveAttribute('srcdoc', '<h1>Hello World</h1>')
|
||||
expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
|
||||
})
|
||||
|
||||
it('renders file artifact iframe with src pointing to preview API', () => {
|
||||
const artifact = createFileArtifact()
|
||||
render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const iframe = screen.getByTitle('File Preview')
|
||||
expect(iframe).toBeInTheDocument()
|
||||
expect(iframe).toHaveAttribute('src')
|
||||
expect(iframe.getAttribute('src')).toContain('/api/files/preview/')
|
||||
expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
|
||||
})
|
||||
|
||||
it('does not include allow-same-origin in sandbox', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const iframe = screen.getByTitle('Test Preview')
|
||||
const sandbox = iframe.getAttribute('sandbox')
|
||||
expect(sandbox).not.toContain('allow-same-origin')
|
||||
})
|
||||
|
||||
it('calls onClose when close button is clicked', () => {
|
||||
const onClose = vi.fn()
|
||||
const artifact = createInlineArtifact()
|
||||
render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={onClose}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const closeButton = screen.getByLabelText('Close preview')
|
||||
fireEvent.click(closeButton)
|
||||
expect(onClose).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('renders fullscreen toggle button on desktop', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const toggleButton = screen.getByLabelText('Enter fullscreen')
|
||||
expect(toggleButton).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders FullscreenSheet on mobile', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
const { container } = render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={true}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const sheetRoot = container.querySelector('.fixed.inset-0')
|
||||
expect(sheetRoot).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders FullscreenSheet when isFullscreen is true (desktop)', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
const { container } = render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={true}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const sheetRoot = container.querySelector('.fixed.inset-0')
|
||||
expect(sheetRoot).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows source label (File artifact / Inline artifact)', () => {
|
||||
const inlineArtifact = createInlineArtifact()
|
||||
render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={inlineArtifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('(Inline artifact)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('returns null when artifact is null', () => {
|
||||
const { container } = render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={null}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(container.innerHTML).toBe('')
|
||||
})
|
||||
|
||||
it('shows desktop side-panel classes on desktop', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
const { container } = render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const panel = container.querySelector('.hidden.md\\:flex')
|
||||
expect(panel).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show desktop side panel on mobile', () => {
|
||||
const artifact = createInlineArtifact()
|
||||
const { container } = render(
|
||||
<HtmlArtifactPanel
|
||||
artifact={artifact}
|
||||
isFullscreen={false}
|
||||
isMobile={true}
|
||||
onClose={() => {}}
|
||||
onToggleFullscreen={() => {}}
|
||||
/>,
|
||||
)
|
||||
|
||||
const panel = container.querySelector('.hidden.md\\:flex')
|
||||
expect(panel).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,96 @@
|
||||
import { getFilePreviewUrl } from '@/api/files'
|
||||
import {
|
||||
FullscreenSheet,
|
||||
FullscreenSheetHeader,
|
||||
FullscreenSheetContent,
|
||||
} from '@/components/ui/fullscreen-sheet'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { X, Maximize2, Minimize2 } from 'lucide-react'
|
||||
import { HtmlPreviewFrame } from './HtmlPreviewFrame'
|
||||
import type { HtmlArtifact } from '@/lib/htmlArtifacts'
|
||||
|
||||
interface HtmlArtifactPanelProps {
|
||||
artifact: HtmlArtifact | null
|
||||
isFullscreen: boolean
|
||||
isMobile: boolean
|
||||
onClose: () => void
|
||||
onToggleFullscreen: () => void
|
||||
}
|
||||
|
||||
export function HtmlArtifactPanel({
|
||||
artifact,
|
||||
isFullscreen,
|
||||
isMobile,
|
||||
onClose,
|
||||
onToggleFullscreen,
|
||||
}: HtmlArtifactPanelProps) {
|
||||
if (!artifact) return null
|
||||
|
||||
const previewSrc = artifact.source === 'file' && artifact.path
|
||||
? getFilePreviewUrl(artifact.path)
|
||||
: undefined
|
||||
const previewSrcDoc = artifact.source === 'inline' ? artifact.html : undefined
|
||||
const title = artifact.title
|
||||
const sourceLabel = artifact.source === 'file' ? 'File artifact' : 'Inline artifact'
|
||||
|
||||
const header = (
|
||||
<div className="flex items-center justify-between px-4 py-2">
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-sm font-medium truncate">{title}</span>
|
||||
<span className="text-xs text-muted-foreground shrink-0">({sourceLabel})</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
{!isMobile && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onToggleFullscreen}
|
||||
aria-label={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
|
||||
>
|
||||
{isFullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
onClick={onClose}
|
||||
aria-label="Close preview"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const frame = (
|
||||
<HtmlPreviewFrame
|
||||
title={title}
|
||||
src={previewSrc}
|
||||
srcDoc={previewSrcDoc}
|
||||
/>
|
||||
)
|
||||
|
||||
if (isMobile || isFullscreen) {
|
||||
return (
|
||||
<FullscreenSheet>
|
||||
<FullscreenSheetHeader>
|
||||
{header}
|
||||
</FullscreenSheetHeader>
|
||||
<FullscreenSheetContent>
|
||||
{frame}
|
||||
</FullscreenSheetContent>
|
||||
</FullscreenSheet>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="hidden md:flex w-[45%] max-w-[720px] min-w-[360px] border-l border-border bg-background flex-col">
|
||||
<div className="flex-shrink-0 border-b border-border">
|
||||
{header}
|
||||
</div>
|
||||
<div className="flex-1 min-h-0">
|
||||
{frame}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface HtmlPreviewFrameProps {
|
||||
title: string
|
||||
src?: string
|
||||
srcDoc?: string
|
||||
className?: string
|
||||
}
|
||||
|
||||
export function HtmlPreviewFrame({ title, src, srcDoc, className }: HtmlPreviewFrameProps) {
|
||||
return (
|
||||
<iframe
|
||||
title={title}
|
||||
src={src}
|
||||
srcDoc={srcDoc}
|
||||
sandbox="allow-scripts"
|
||||
referrerPolicy="no-referrer"
|
||||
className={cn('h-full w-full border-0 bg-white', className)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { CodePreview } from './CodePreview'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useMobile: vi.fn(() => false),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
useMobile: () => mocks.useMobile(),
|
||||
}))
|
||||
|
||||
describe('CodePreview', () => {
|
||||
beforeEach(() => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('shows artifact button for .html files', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
render(
|
||||
<CodePreview
|
||||
fileName="dist/report.html"
|
||||
content="<h1>Report</h1>"
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByTitle('Preview HTML artifact')
|
||||
expect(button).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onHtmlArtifactOpen with file source when artifact button is clicked', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
render(
|
||||
<CodePreview
|
||||
fileName="dist/report.html"
|
||||
content="<h1>Report</h1>"
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByTitle('Preview HTML artifact')
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(onHtmlArtifactOpen).toHaveBeenCalledWith({
|
||||
source: 'file',
|
||||
path: 'dist/report.html',
|
||||
title: expect.stringContaining('report'),
|
||||
})
|
||||
})
|
||||
|
||||
it('shows artifact button for .htm files', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
render(
|
||||
<CodePreview
|
||||
fileName="page.htm"
|
||||
content="<h1>Hello</h1>"
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByTitle('Preview HTML artifact')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show artifact button for .ts files', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
render(
|
||||
<CodePreview
|
||||
fileName="component.ts"
|
||||
content="const x = 1"
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.queryByTitle('Preview HTML artifact')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows show-more button for large files', () => {
|
||||
const lines = Array.from({ length: 30 }, (_, i) => `line ${i + 1}`)
|
||||
const content = lines.join('\n')
|
||||
|
||||
render(
|
||||
<CodePreview
|
||||
fileName="large.ts"
|
||||
content={content}
|
||||
/>
|
||||
)
|
||||
|
||||
expect(screen.getByText(/10 more lines/)).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('uses inline fallback when fileName is empty', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
render(
|
||||
<CodePreview
|
||||
fileName=""
|
||||
content="<h1>Hello</h1>"
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
/>
|
||||
)
|
||||
|
||||
const button = screen.getByTitle('Preview HTML artifact')
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(onHtmlArtifactOpen).toHaveBeenCalledWith({
|
||||
source: 'inline',
|
||||
html: '<h1>Hello</h1>',
|
||||
title: 'HTML artifact',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -2,10 +2,13 @@ import React from 'react'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { isHtmlPath } from '@/lib/htmlArtifacts'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
|
||||
interface CodePreviewProps {
|
||||
fileName: string
|
||||
content: string
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
}
|
||||
|
||||
const INITIAL_CODE_LINES = 20
|
||||
@@ -57,7 +60,7 @@ function detectLanguage(fileName: string): string {
|
||||
return langMap[ext || ''] || 'plaintext'
|
||||
}
|
||||
|
||||
export function CodePreview({ fileName, content }: CodePreviewProps) {
|
||||
export function CodePreview({ fileName, content, onHtmlArtifactOpen }: CodePreviewProps) {
|
||||
const isMobile = useMobile()
|
||||
const [showMore, setShowMore] = React.useState(false)
|
||||
|
||||
@@ -72,11 +75,33 @@ export function CodePreview({ fileName, content }: CodePreviewProps) {
|
||||
? lines.slice(0, INITIAL_CODE_LINES).join('\n')
|
||||
: content
|
||||
|
||||
const isHtmlFile = fileName ? isHtmlPath(fileName) : true
|
||||
|
||||
const handleHtmlArtifact = () => {
|
||||
if (!onHtmlArtifactOpen) return
|
||||
if (fileName) {
|
||||
onHtmlArtifactOpen({ source: 'file', path: fileName, title: extractFileFromPath(fileName) })
|
||||
} else {
|
||||
onHtmlArtifactOpen({ source: 'inline', html: content, title: 'HTML artifact' })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col bg-background">
|
||||
<div className="px-3 py-2 bg-muted/30 border-b border-border/50 flex items-center justify-between text-xs">
|
||||
<span className="font-medium truncate flex-1">{extractFileFromPath(fileName)}</span>
|
||||
<CopyButton content={content} title="Copy" iconSize="sm" variant="ghost" className="flex-shrink-0" />
|
||||
<div className="flex items-center gap-1 flex-shrink-0">
|
||||
{isHtmlFile && onHtmlArtifactOpen && (
|
||||
<button
|
||||
onClick={handleHtmlArtifact}
|
||||
className="px-2 py-1 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground text-xs"
|
||||
title="Preview HTML artifact"
|
||||
>
|
||||
Preview HTML
|
||||
</button>
|
||||
)}
|
||||
<CopyButton content={content} title="Copy" iconSize="sm" variant="ghost" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={cn('overflow-y-auto', isMobile ? 'max-h-64' : 'max-h-96')}>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { useState } from 'react'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import { DiffStats } from './DiffStats'
|
||||
import { ContentDiffViewer } from './ContentDiffViewer'
|
||||
@@ -60,9 +61,10 @@ interface FileToolRenderProps {
|
||||
content?: string
|
||||
toolName: string
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
}
|
||||
|
||||
export function FileToolRender({ part, filediff, filePath, content, toolName, onFileClick }: FileToolRenderProps) {
|
||||
export function FileToolRender({ part, filediff, filePath, content, toolName, onFileClick, onHtmlArtifactOpen }: FileToolRenderProps) {
|
||||
const { preferences } = useSettings()
|
||||
const isReadTool = toolName === 'Read'
|
||||
const isEditTool = toolName === 'Edit'
|
||||
@@ -119,21 +121,21 @@ export function FileToolRender({ part, filediff, filePath, content, toolName, on
|
||||
{expanded && hasExpandableContent && (
|
||||
<div className="bg-card p-0">
|
||||
{filediff && <ContentDiffViewer before={filediff.before} after={filediff.after} />}
|
||||
{content && !filediff && <CodePreview fileName={filePath || ''} content={content} />}
|
||||
{content && !filediff && <CodePreview fileName={filePath || ''} content={content} onHtmlArtifactOpen={onHtmlArtifactOpen} />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export function getToolSpecificRender(part: ToolPart, onFileClick?: (filePath: string) => void): React.ReactElement | null {
|
||||
export function getToolSpecificRender(part: ToolPart, onFileClick?: (filePath: string) => void, onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void): React.ReactElement | null {
|
||||
if (part.state.status !== 'completed') return null
|
||||
|
||||
if (part.tool === 'edit') {
|
||||
const filediff = part.state.metadata?.filediff
|
||||
const filePath = part.state.input?.filePath as string | undefined
|
||||
if (filediff && isFileDiff(filediff)) {
|
||||
return <FileToolRender part={part} filediff={filediff} filePath={filePath} toolName="Edit" onFileClick={onFileClick} />
|
||||
return <FileToolRender part={part} filediff={filediff} filePath={filePath} toolName="Edit" onFileClick={onFileClick} onHtmlArtifactOpen={onHtmlArtifactOpen} />
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,14 +143,14 @@ export function getToolSpecificRender(part: ToolPart, onFileClick?: (filePath: s
|
||||
const filePath = part.state.input?.filePath as string | undefined
|
||||
const content = part.state.input?.content as string | undefined
|
||||
if (filePath) {
|
||||
return <FileToolRender part={part} filePath={filePath} content={content} toolName="Write" onFileClick={onFileClick} />
|
||||
return <FileToolRender part={part} filePath={filePath} content={content} toolName="Write" onFileClick={onFileClick} onHtmlArtifactOpen={onHtmlArtifactOpen} />
|
||||
}
|
||||
}
|
||||
|
||||
if (part.tool === 'read') {
|
||||
const filePath = part.state.input?.filePath as string | undefined
|
||||
if (filePath) {
|
||||
return <FileToolRender part={part} filePath={filePath} toolName="Read" onFileClick={onFileClick} />
|
||||
return <FileToolRender part={part} filePath={filePath} toolName="Read" onFileClick={onFileClick} onHtmlArtifactOpen={onHtmlArtifactOpen} />
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,8 @@ type RetryPartType = components['schemas']['RetryPart']
|
||||
|
||||
type Part = components['schemas']['Part']
|
||||
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
|
||||
interface MessagePartProps {
|
||||
part: Part
|
||||
role?: string
|
||||
@@ -21,6 +23,7 @@ interface MessagePartProps {
|
||||
partIndex?: number
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onChildSessionClick?: (sessionId: string) => void
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
messageTextContent?: string
|
||||
}
|
||||
|
||||
@@ -102,7 +105,7 @@ function TTSButton({ messageId, content, className = "" }: TTSButtonProps) {
|
||||
)
|
||||
}
|
||||
|
||||
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick, onChildSessionClick, messageTextContent }: MessagePartProps) {
|
||||
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick, onChildSessionClick, onHtmlArtifactOpen, messageTextContent }: MessagePartProps) {
|
||||
const { preferences } = useSettings()
|
||||
const simpleChatMode = preferences?.simpleChatMode ?? false
|
||||
const showReasoning = preferences?.showReasoning ?? false
|
||||
@@ -118,13 +121,13 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
|
||||
return null
|
||||
}
|
||||
}
|
||||
return <TextPart part={part} />
|
||||
return <TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />
|
||||
case 'patch':
|
||||
if (simpleChatMode) return null
|
||||
return <PatchPart part={part} onFileClick={onFileClick} />
|
||||
case 'tool':
|
||||
if (simpleChatMode && part.tool !== 'task') return null
|
||||
return <ToolCallPart part={part} onFileClick={onFileClick} onChildSessionClick={onChildSessionClick} />
|
||||
return <ToolCallPart part={part} onFileClick={onFileClick} onChildSessionClick={onChildSessionClick} onHtmlArtifactOpen={onHtmlArtifactOpen} />
|
||||
case 'reasoning':
|
||||
if (simpleChatMode || !showReasoning) return null
|
||||
return (
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { Message, Part, MessageWithParts } from '@/api/types'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { useSessionTodos } from '@/stores/sessionTodosStore'
|
||||
import { useSettings } from '@/hooks/useSettings'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import type { Todo } from '@/components/message/SessionTodoDisplay'
|
||||
import type { OpenCodeError } from '@/lib/opencode-errors'
|
||||
@@ -27,6 +28,7 @@ interface MessageThreadProps {
|
||||
messages?: MessageWithParts[]
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onChildSessionClick?: (sessionId: string) => void
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
onUndoMessage?: (restoredPrompt: string) => void
|
||||
model?: string
|
||||
}
|
||||
@@ -147,6 +149,7 @@ interface MessageRowProps {
|
||||
directory?: string
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onChildSessionClick?: (sessionId: string) => void
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
handleStartEditUserMessage: (userMessageId: string, assistantMessageId: string) => void
|
||||
handleCancelEdit: () => void
|
||||
model?: string
|
||||
@@ -168,6 +171,7 @@ const MessageRow = memo(function MessageRow({
|
||||
directory,
|
||||
onFileClick,
|
||||
onChildSessionClick,
|
||||
onHtmlArtifactOpen,
|
||||
handleStartEditUserMessage,
|
||||
handleCancelEdit,
|
||||
model,
|
||||
@@ -212,6 +216,7 @@ const MessageRow = memo(function MessageRow({
|
||||
partIndex={partIndex}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
messageTextContent={messageTextContent}
|
||||
/>
|
||||
</div>
|
||||
@@ -308,6 +313,7 @@ const MessageRow = memo(function MessageRow({
|
||||
partIndex={partIndex}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
messageTextContent={msg.role === 'assistant' ? messageTextContent : undefined}
|
||||
/>
|
||||
</div>
|
||||
@@ -329,6 +335,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
messages,
|
||||
onFileClick,
|
||||
onChildSessionClick,
|
||||
onHtmlArtifactOpen,
|
||||
onUndoMessage,
|
||||
model
|
||||
}: MessageThreadProps) {
|
||||
@@ -442,6 +449,7 @@ export const MessageThread = memo(function MessageThread({
|
||||
directory={directory}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onHtmlArtifactOpen={onHtmlArtifactOpen}
|
||||
handleStartEditUserMessage={handleStartEditUserMessage}
|
||||
handleCancelEdit={handleCancelEdit}
|
||||
model={model}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent } from '@testing-library/react'
|
||||
import { TextPart } from './TextPart'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useTheme: vi.fn(() => 'dark'),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useTheme', () => ({
|
||||
useTheme: () => mocks.useTheme(),
|
||||
}))
|
||||
|
||||
vi.mock('mermaid', () => ({
|
||||
default: {
|
||||
initialize: vi.fn(),
|
||||
render: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
const createTextPart = (text: string) => ({
|
||||
type: 'text' as const,
|
||||
text,
|
||||
sessionID: 'test-session',
|
||||
id: 'part-1',
|
||||
})
|
||||
|
||||
describe('TextPart', () => {
|
||||
beforeEach(() => {
|
||||
mocks.useTheme.mockReturnValue('dark')
|
||||
})
|
||||
|
||||
it('renders HTML fenced code block with artifact button', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
const markdown = 'Here is a page:\n\n```html\n<html><body><h1>Hello artifact</h1></body></html>\n```'
|
||||
const part = createTextPart(markdown)
|
||||
|
||||
render(<TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />)
|
||||
|
||||
const button = screen.getByTitle('Preview HTML artifact')
|
||||
expect(button).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('calls onHtmlArtifactOpen with correct data when artifact button is clicked', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
const markdown = 'Here is a page:\n\n```html\n<html><body><h1>Hello artifact</h1></body></html>\n```'
|
||||
const part = createTextPart(markdown)
|
||||
|
||||
render(<TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />)
|
||||
|
||||
const button = screen.getByTitle('Preview HTML artifact')
|
||||
fireEvent.click(button)
|
||||
|
||||
expect(onHtmlArtifactOpen).toHaveBeenCalledWith({
|
||||
source: 'inline',
|
||||
html: '<html><body><h1>Hello artifact</h1></body></html>',
|
||||
title: 'HTML artifact',
|
||||
})
|
||||
})
|
||||
|
||||
it('does not show artifact button for non-HTML code blocks', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
const markdown = '```ts\nconst x = 1\n```'
|
||||
const part = createTextPart(markdown)
|
||||
|
||||
render(<TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />)
|
||||
|
||||
expect(screen.queryByTitle('Preview HTML artifact')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('still shows copy button for code blocks', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
const markdown = '```html\n<p>test</p>\n```'
|
||||
const part = createTextPart(markdown)
|
||||
|
||||
render(<TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />)
|
||||
|
||||
expect(screen.getByTitle('Copy code')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('preserves leading/trailing whitespace when copying code content', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
const markdown = '```\n const x = 1\n \n```'
|
||||
const part = createTextPart(markdown)
|
||||
|
||||
render(<TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />)
|
||||
|
||||
const copyButton = screen.getByTitle('Copy code')
|
||||
expect(copyButton).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('does not show artifact button for mermaid code blocks', () => {
|
||||
const onHtmlArtifactOpen = vi.fn()
|
||||
const markdown = '```mermaid\ngraph TD;\nA-->B;\n```'
|
||||
const part = createTextPart(markdown)
|
||||
|
||||
render(<TextPart part={part} onHtmlArtifactOpen={onHtmlArtifactOpen} />)
|
||||
|
||||
expect(screen.queryByTitle('Preview HTML artifact')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,7 @@ import mermaid from 'mermaid'
|
||||
import { Maximize2, X, AlertCircle } from 'lucide-react'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import type { components } from '@/api/opencode-types'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import { useTheme } from '@/hooks/useTheme'
|
||||
import 'highlight.js/styles/github-dark.css'
|
||||
|
||||
@@ -14,6 +15,7 @@ type TextPart = components['schemas']['TextPart']
|
||||
|
||||
interface TextPartProps {
|
||||
part: TextPart
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
}
|
||||
|
||||
interface MermaidBlockProps {
|
||||
@@ -146,10 +148,11 @@ function MermaidBlock({ code }: MermaidBlockProps) {
|
||||
interface CodeBlockProps {
|
||||
children?: React.ReactNode
|
||||
className?: string
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
function CodeBlock({ children, className, ...props }: CodeBlockProps) {
|
||||
function CodeBlock({ children, className, onHtmlArtifactOpen, ...props }: CodeBlockProps) {
|
||||
const extractTextContent = (node: React.ReactNode): string => {
|
||||
if (typeof node === 'string') return node
|
||||
if (typeof node === 'number') return node.toString()
|
||||
@@ -163,14 +166,31 @@ function CodeBlock({ children, className, ...props }: CodeBlockProps) {
|
||||
return ''
|
||||
}
|
||||
|
||||
const codeContent = extractTextContent(children)
|
||||
const rawCodeContent = extractTextContent(children)
|
||||
const codeContent = rawCodeContent.trim()
|
||||
|
||||
const childArray = React.Children.toArray(children)
|
||||
const codeElement = childArray.find((child): child is React.ReactElement => React.isValidElement(child))
|
||||
const codeClassName = codeElement?.props?.className
|
||||
const isHtmlCode = typeof codeClassName === 'string' && (codeClassName.includes('language-html') || codeClassName.includes('language-htm'))
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<pre className={`bg-accent p-1 rounded-lg overflow-x-auto whitespace-pre-wrap break-words border border-border my-4 ${className || ''}`} {...props}>
|
||||
{children}
|
||||
</pre>
|
||||
<CopyButton content={codeContent} title="Copy code" className="absolute top-2 right-2" />
|
||||
<div className="absolute top-2 right-2 flex gap-1">
|
||||
{isHtmlCode && onHtmlArtifactOpen && (
|
||||
<button
|
||||
onClick={() => onHtmlArtifactOpen({ source: 'inline', html: codeContent, title: 'HTML artifact' })}
|
||||
className="p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground text-xs"
|
||||
title="Preview HTML artifact"
|
||||
>
|
||||
Preview HTML
|
||||
</button>
|
||||
)}
|
||||
<CopyButton content={rawCodeContent} title="Copy code" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -184,7 +204,7 @@ function isMermaidBlockComplete(text: string): boolean {
|
||||
return false
|
||||
}
|
||||
|
||||
export function TextPart({ part }: TextPartProps) {
|
||||
export function TextPart({ part, onHtmlArtifactOpen }: TextPartProps) {
|
||||
const mermaidComplete = React.useMemo(() => {
|
||||
return part.text ? isMermaidBlockComplete(part.text) : false
|
||||
}, [part.text])
|
||||
@@ -234,7 +254,7 @@ export function TextPart({ part }: TextPartProps) {
|
||||
},
|
||||
pre({ children }) {
|
||||
return (
|
||||
<CodeBlock>
|
||||
<CodeBlock onHtmlArtifactOpen={onHtmlArtifactOpen}>
|
||||
{children}
|
||||
</CodeBlock>
|
||||
)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useUserBash } from '@/stores/userBashStore'
|
||||
import { useSessionStatusForSession } from '@/stores/sessionStatusStore'
|
||||
import { usePermissions, useQuestions } from '@/contexts/EventContext'
|
||||
import { detectFileReferences } from '@/lib/fileReferences'
|
||||
import type { OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
import { CopyButton } from '@/components/ui/copy-button'
|
||||
import { getToolSpecificRender } from './FileToolRender'
|
||||
@@ -15,6 +16,7 @@ interface ToolCallPartProps {
|
||||
part: ToolPart
|
||||
onFileClick?: (filePath: string, lineNumber?: number) => void
|
||||
onChildSessionClick?: (sessionId: string) => void
|
||||
onHtmlArtifactOpen?: (input: OpenHtmlArtifactInput) => void
|
||||
simpleChatMode?: boolean
|
||||
}
|
||||
|
||||
@@ -26,7 +28,7 @@ function getTaskSessionId(part: ToolPart): string | undefined {
|
||||
return sessionId
|
||||
}
|
||||
|
||||
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
|
||||
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string, lineNumber?: number) => void }) {
|
||||
const jsonString = JSON.stringify(json, null, 2)
|
||||
const references = detectFileReferences(jsonString)
|
||||
|
||||
@@ -47,7 +49,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
|
||||
key={`ref-${index}`}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
onFileClick?.(ref.filePath)
|
||||
onFileClick?.(ref.filePath, ref.lineNumber)
|
||||
}}
|
||||
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 cursor-pointer underline decoration-dotted"
|
||||
title={`Click to open ${ref.filePath}`}
|
||||
@@ -66,7 +68,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
|
||||
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">{parts}</pre>
|
||||
}
|
||||
|
||||
export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCallPartProps) {
|
||||
export function ToolCallPart({ part, onFileClick, onChildSessionClick, onHtmlArtifactOpen }: ToolCallPartProps) {
|
||||
const { preferences } = useSettings()
|
||||
const { userBashCommands } = useUserBash()
|
||||
const taskSessionId = part.tool === 'task' ? getTaskSessionId(part) : undefined
|
||||
@@ -219,7 +221,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
|
||||
return null
|
||||
}
|
||||
|
||||
const toolSpecificRender = getToolSpecificRender(part, onFileClick)
|
||||
const toolSpecificRender = getToolSpecificRender(part, onFileClick, onHtmlArtifactOpen)
|
||||
if (toolSpecificRender) {
|
||||
return toolSpecificRender
|
||||
}
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
isHtmlPath,
|
||||
normalizeWorkspaceFilePath,
|
||||
createHtmlArtifact,
|
||||
getArtifactTitle,
|
||||
} from './htmlArtifacts'
|
||||
|
||||
describe('isHtmlPath', () => {
|
||||
it('returns true for .html paths', () => {
|
||||
expect(isHtmlPath('repo/report.html')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns true for .HTM paths (case-insensitive)', () => {
|
||||
expect(isHtmlPath('page.HTM')).toBe(true)
|
||||
expect(isHtmlPath('page.Htm')).toBe(true)
|
||||
})
|
||||
|
||||
it('returns false for .tsx paths', () => {
|
||||
expect(isHtmlPath('component.tsx')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for .md paths', () => {
|
||||
expect(isHtmlPath('readme.md')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false for missing path', () => {
|
||||
expect(isHtmlPath(undefined)).toBe(false)
|
||||
expect(isHtmlPath('')).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores query strings and hash fragments', () => {
|
||||
expect(isHtmlPath('index.html?raw=true')).toBe(true)
|
||||
expect(isHtmlPath('index.html#section')).toBe(true)
|
||||
expect(isHtmlPath('page.htm?query=1#hash')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('normalizeWorkspaceFilePath', () => {
|
||||
it('strips workspace repos path prefix', () => {
|
||||
const result = normalizeWorkspaceFilePath(
|
||||
'/workspace/repos/my-repo/dist/index.html',
|
||||
'/workspace/repos/my-repo',
|
||||
)
|
||||
expect(result).toBe('my-repo/dist/index.html')
|
||||
})
|
||||
|
||||
it('returns non-matching absolute paths unchanged', () => {
|
||||
const result = normalizeWorkspaceFilePath(
|
||||
'/some/other/path/file.html',
|
||||
'/workspace/repos/my-repo',
|
||||
)
|
||||
expect(result).toBe('/some/other/path/file.html')
|
||||
})
|
||||
|
||||
it('returns relative paths unchanged', () => {
|
||||
const result = normalizeWorkspaceFilePath('relative/path.html', '/workspace/repos/my-repo')
|
||||
expect(result).toBe('relative/path.html')
|
||||
})
|
||||
|
||||
it('returns path unchanged when repoFullPath is missing', () => {
|
||||
const result = normalizeWorkspaceFilePath('/workspace/repos/my-repo/file.html')
|
||||
expect(result).toBe('/workspace/repos/my-repo/file.html')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createHtmlArtifact', () => {
|
||||
it('creates an inline artifact with required html', () => {
|
||||
const artifact = createHtmlArtifact({ source: 'inline', html: '<h1>Hello</h1>' })
|
||||
expect(artifact.source).toBe('inline')
|
||||
expect(artifact.html).toBe('<h1>Hello</h1>')
|
||||
expect(artifact.id).toBeTruthy()
|
||||
expect(artifact.title).toBe('Untitled Artifact')
|
||||
})
|
||||
|
||||
it('creates a file artifact with required path', () => {
|
||||
const artifact = createHtmlArtifact({ source: 'file', path: 'my-repo/dist/index.html' })
|
||||
expect(artifact.source).toBe('file')
|
||||
expect(artifact.path).toBe('my-repo/dist/index.html')
|
||||
expect(artifact.id).toBeTruthy()
|
||||
expect(artifact.title).toBe('index')
|
||||
})
|
||||
|
||||
it('uses provided title', () => {
|
||||
const artifact = createHtmlArtifact({
|
||||
source: 'inline',
|
||||
html: '<h1>Hello</h1>',
|
||||
title: 'My Artifact',
|
||||
})
|
||||
expect(artifact.title).toBe('My Artifact')
|
||||
})
|
||||
|
||||
it('throws when path is missing for file artifact', () => {
|
||||
expect(() => createHtmlArtifact({ source: 'file' })).toThrow('path is required')
|
||||
})
|
||||
|
||||
it('throws when html is missing for inline artifact', () => {
|
||||
expect(() => createHtmlArtifact({ source: 'inline' })).toThrow('html is required')
|
||||
})
|
||||
})
|
||||
|
||||
describe('handleFileClick path detection (normalize + isHtml combo)', () => {
|
||||
it('classifies normalized .html path as artifact', () => {
|
||||
const path = normalizeWorkspaceFilePath(
|
||||
'/workspace/repos/my-repo/dist/index.html',
|
||||
'/workspace/repos/my-repo',
|
||||
)
|
||||
expect(path).toBe('my-repo/dist/index.html')
|
||||
expect(isHtmlPath(path)).toBe(true)
|
||||
})
|
||||
|
||||
it('classifies normalized .htm path as artifact', () => {
|
||||
const path = normalizeWorkspaceFilePath(
|
||||
'/workspace/repos/my-repo/public/page.htm',
|
||||
'/workspace/repos/my-repo',
|
||||
)
|
||||
expect(path).toBe('my-repo/public/page.htm')
|
||||
expect(isHtmlPath(path)).toBe(true)
|
||||
})
|
||||
|
||||
it('does not classify non-HTML path as artifact', () => {
|
||||
const path = normalizeWorkspaceFilePath(
|
||||
'/workspace/repos/my-repo/src/app.tsx',
|
||||
'/workspace/repos/my-repo',
|
||||
)
|
||||
expect(path).toBe('my-repo/src/app.tsx')
|
||||
expect(isHtmlPath(path)).toBe(false)
|
||||
})
|
||||
|
||||
it('does not classify relative non-HTML path as artifact', () => {
|
||||
expect(isHtmlPath(normalizeWorkspaceFilePath('src/utils.ts'))).toBe(false)
|
||||
})
|
||||
|
||||
it('classifies .html path without repo prefix as artifact', () => {
|
||||
const path = normalizeWorkspaceFilePath('some-folder/index.html')
|
||||
expect(isHtmlPath(path)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getArtifactTitle', () => {
|
||||
it('returns file name without extension for .html paths', () => {
|
||||
expect(getArtifactTitle('my-repo/dist/index.html')).toBe('index')
|
||||
})
|
||||
|
||||
it('returns file name without extension for .htm paths', () => {
|
||||
expect(getArtifactTitle('page.htm')).toBe('page')
|
||||
})
|
||||
|
||||
it('returns last segment for non-HTML paths', () => {
|
||||
expect(getArtifactTitle('some/path/file.txt')).toBe('file.txt')
|
||||
})
|
||||
|
||||
it('returns Untitled Artifact for undefined', () => {
|
||||
expect(getArtifactTitle(undefined)).toBe('Untitled Artifact')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,52 @@
|
||||
export interface HtmlArtifact {
|
||||
id: string
|
||||
title: string
|
||||
source: 'inline' | 'file'
|
||||
html?: string
|
||||
path?: string
|
||||
}
|
||||
|
||||
export interface OpenHtmlArtifactInput {
|
||||
title?: string
|
||||
source: 'inline' | 'file'
|
||||
html?: string
|
||||
path?: string
|
||||
}
|
||||
|
||||
const HTML_EXTENSIONS = new Set(['.html', '.htm'])
|
||||
|
||||
export function isHtmlPath(path: string | undefined): boolean {
|
||||
if (!path) return false
|
||||
const clean = path.split(/[?#]/)[0].toLowerCase()
|
||||
return HTML_EXTENSIONS.has(clean.slice(clean.lastIndexOf('.')))
|
||||
}
|
||||
|
||||
export function getArtifactTitle(pathOrTitle: string | undefined): string {
|
||||
if (!pathOrTitle) return 'Untitled Artifact'
|
||||
const lastSegment = pathOrTitle.split('/').pop() || pathOrTitle
|
||||
if (isHtmlPath(lastSegment)) {
|
||||
return lastSegment.slice(0, lastSegment.lastIndexOf('.'))
|
||||
}
|
||||
return lastSegment
|
||||
}
|
||||
|
||||
export function createHtmlArtifact(input: OpenHtmlArtifactInput): HtmlArtifact {
|
||||
if (input.source === 'file' && !input.path) {
|
||||
throw new Error('path is required for file artifacts')
|
||||
}
|
||||
if (input.source === 'inline' && !input.html) {
|
||||
throw new Error('html is required for inline artifacts')
|
||||
}
|
||||
const id = `${Date.now()}-${Math.random().toString(36).slice(2)}`
|
||||
const title = input.title ?? getArtifactTitle(input.source === 'file' ? input.path : undefined)
|
||||
return { id, title, source: input.source, html: input.html, path: input.path }
|
||||
}
|
||||
|
||||
export function normalizeWorkspaceFilePath(filePath: string, repoFullPath?: string): string {
|
||||
if (!filePath.startsWith('/') || !repoFullPath) return filePath
|
||||
const workspaceReposPath = repoFullPath.substring(0, repoFullPath.lastIndexOf('/'))
|
||||
if (filePath.startsWith(`${workspaceReposPath}/`)) {
|
||||
return filePath.substring(workspaceReposPath.length + 1)
|
||||
}
|
||||
return filePath
|
||||
}
|
||||
@@ -52,6 +52,9 @@ import { SessionTodoDisplay } from "@/components/message/SessionTodoDisplay";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
import { useSidebarAction } from "@/hooks/useSidebarAction";
|
||||
import { SessionMoreButton } from "@/components/navigation/SessionMoreButton";
|
||||
import { HtmlArtifactPanel } from "@/components/html-preview/HtmlArtifactPanel";
|
||||
import type { HtmlArtifact, OpenHtmlArtifactInput } from '@/lib/htmlArtifacts'
|
||||
import { createHtmlArtifact, isHtmlPath, normalizeWorkspaceFilePath } from '@/lib/htmlArtifacts'
|
||||
|
||||
const compareMessageIds = (id1: string, id2: string): number => {
|
||||
const num1 = parseInt(id1, 10)
|
||||
@@ -84,6 +87,8 @@ export function SessionDetail() {
|
||||
const [showScrollButton, setShowScrollButton] = useState(false);
|
||||
const [hasPromptContent, setHasPromptContent] = useState(false);
|
||||
const [minimizedQuestion, setMinimizedQuestion] = useState<QuestionRequest | null>(null);
|
||||
const [htmlArtifact, setHtmlArtifact] = useState<HtmlArtifact | null>(null);
|
||||
const [htmlArtifactFullscreen, setHtmlArtifactFullscreen] = useState(false);
|
||||
|
||||
const isMobile = useMobile();
|
||||
const { keyboardHeight } = useVisualViewport();
|
||||
@@ -202,6 +207,28 @@ export function SessionDetail() {
|
||||
setMinimizedQuestion(null)
|
||||
}, [])
|
||||
|
||||
const handleHtmlArtifactOpen = useCallback((input: OpenHtmlArtifactInput) => {
|
||||
try {
|
||||
const normalizedPath = input.source === 'file' && input.path
|
||||
? normalizeWorkspaceFilePath(input.path, repo?.fullPath)
|
||||
: input.path
|
||||
const artifact = createHtmlArtifact({ ...input, path: normalizedPath })
|
||||
setHtmlArtifact(artifact)
|
||||
setHtmlArtifactFullscreen(isMobile)
|
||||
} catch {
|
||||
showToast.error('Failed to create artifact')
|
||||
}
|
||||
}, [isMobile, repo?.fullPath])
|
||||
|
||||
const handleHtmlArtifactClose = useCallback(() => {
|
||||
setHtmlArtifact(null)
|
||||
setHtmlArtifactFullscreen(false)
|
||||
}, [])
|
||||
|
||||
const handleHtmlArtifactFullscreenToggle = useCallback(() => {
|
||||
setHtmlArtifactFullscreen(v => !v)
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (minimizedQuestion && minimizedQuestion.sessionID !== sessionId) {
|
||||
setMinimizedQuestion(null)
|
||||
@@ -336,22 +363,21 @@ export function SessionDetail() {
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
|
||||
const handleFileClick = useCallback((filePath: string) => {
|
||||
let pathToOpen = filePath
|
||||
|
||||
if (filePath.startsWith('/') && repo?.fullPath) {
|
||||
const workspaceReposPath = repo.fullPath.substring(0, repo.fullPath.lastIndexOf('/'))
|
||||
|
||||
if (filePath.startsWith(workspaceReposPath + '/')) {
|
||||
pathToOpen = filePath.substring(workspaceReposPath.length + 1)
|
||||
}
|
||||
const pathToOpen = normalizeWorkspaceFilePath(filePath, repo?.fullPath)
|
||||
|
||||
if (isHtmlPath(pathToOpen)) {
|
||||
handleHtmlArtifactOpen({
|
||||
source: 'file',
|
||||
path: pathToOpen,
|
||||
title: pathToOpen.split('/').pop() || 'HTML artifact',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
setSelectedFilePath(pathToOpen)
|
||||
setFileBrowserOpen(true)
|
||||
}, [repo?.fullPath, setFileBrowserOpen]);
|
||||
}, [repo?.fullPath, handleHtmlArtifactOpen, setFileBrowserOpen]);
|
||||
|
||||
const handleSessionTitleUpdate = useCallback((newTitle: string) => {
|
||||
if (sessionId) {
|
||||
@@ -400,10 +426,6 @@ export function SessionDetail() {
|
||||
promptInputRef.current?.clearPrompt()
|
||||
}, []);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if (!sessionId) {
|
||||
return <Navigate to="/" replace />;
|
||||
}
|
||||
@@ -480,29 +502,31 @@ export function SessionDetail() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="relative flex-1 overflow-hidden flex flex-col">
|
||||
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + PROMPT_OVERLAY_CLEARANCE_PX }}>
|
||||
{repoLoading || sessionLoading || messagesLoading ? (
|
||||
<MessageSkeleton />
|
||||
) : opcodeUrl && repoDirectory ? (
|
||||
<MessageThread
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionID={sessionId}
|
||||
directory={repoDirectory}
|
||||
messages={messages}
|
||||
onFileClick={handleFileClick}
|
||||
onChildSessionClick={handleChildSessionClick}
|
||||
onUndoMessage={handleUndoMessage}
|
||||
model={modelString || undefined}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{opcodeUrl && repoDirectory && !isEditingMessage && (
|
||||
<div
|
||||
ref={promptOverlayRef}
|
||||
className="absolute left-0 right-0 flex justify-center"
|
||||
style={{ bottom: inputBottomOffset }}
|
||||
>
|
||||
<div className="relative flex-1 overflow-hidden flex flex-row">
|
||||
<div className="relative flex-1 min-w-0 overflow-hidden flex flex-col">
|
||||
<div key={sessionId} ref={messageContainerRef} className="flex-1 overflow-y-auto overflow-x-hidden overscroll-contain [mask-image:linear-gradient(to_bottom,transparent,black_16px,black)]" style={{ paddingBottom: promptOverlayHeight + inputBottomOffset + PROMPT_OVERLAY_CLEARANCE_PX }}>
|
||||
{repoLoading || sessionLoading || messagesLoading ? (
|
||||
<MessageSkeleton />
|
||||
) : opcodeUrl && repoDirectory ? (
|
||||
<MessageThread
|
||||
opcodeUrl={opcodeUrl}
|
||||
sessionID={sessionId}
|
||||
directory={repoDirectory}
|
||||
messages={messages}
|
||||
onFileClick={handleFileClick}
|
||||
onChildSessionClick={handleChildSessionClick}
|
||||
onUndoMessage={handleUndoMessage}
|
||||
onHtmlArtifactOpen={handleHtmlArtifactOpen}
|
||||
model={modelString || undefined}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
{opcodeUrl && repoDirectory && !isEditingMessage && (
|
||||
<div
|
||||
ref={promptOverlayRef}
|
||||
className="absolute left-0 right-0 flex justify-center"
|
||||
style={{ bottom: inputBottomOffset }}
|
||||
>
|
||||
<div className="relative w-[94%] md:max-w-4xl">
|
||||
<div className="absolute -top-9 right-0 z-50 flex flex-col items-end gap-2">
|
||||
{ttsEnabled && !hasPromptContent && !isSessionActive && latestPlayableAssistant && (
|
||||
@@ -567,6 +591,16 @@ export function SessionDetail() {
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{htmlArtifact && !htmlArtifactFullscreen && !isMobile && (
|
||||
<HtmlArtifactPanel
|
||||
artifact={htmlArtifact}
|
||||
isFullscreen={false}
|
||||
isMobile={false}
|
||||
onClose={handleHtmlArtifactClose}
|
||||
onToggleFullscreen={handleHtmlArtifactFullscreenToggle}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Sessions Dialog */}
|
||||
@@ -598,6 +632,16 @@ export function SessionDetail() {
|
||||
initialSelectedFile={selectedFilePath}
|
||||
/>
|
||||
|
||||
{htmlArtifact && (htmlArtifactFullscreen || isMobile) && (
|
||||
<HtmlArtifactPanel
|
||||
artifact={htmlArtifact}
|
||||
isFullscreen={true}
|
||||
isMobile={isMobile}
|
||||
onClose={handleHtmlArtifactClose}
|
||||
onToggleFullscreen={handleHtmlArtifactFullscreenToggle}
|
||||
/>
|
||||
)}
|
||||
|
||||
<RepoLspDialog
|
||||
open={lspDialogOpen}
|
||||
onOpenChange={setLspDialogOpen}
|
||||
|
||||
Reference in new issue
Block a user