feat: enhance HTML artifact preview with mobile support and test cleanup

This commit is contained in:
Chris Scott committed 2026-06-20 23:20:39 -04:00
1 parent 7c8a4fe64c
commit 8a12731a2c
8 files changed
+219 -57

No files matched your search

@@ -12,6 +12,9 @@ import { FolderOpen, Upload, RefreshCw, X } from 'lucide-react'
import type { FileInfo } from '@/types/files'
import { useMobile } from '@/hooks/useMobile'
import { getFileApiUrl, useFile } from '@/api/files'
import { HtmlArtifactPanel } from '@/components/html-preview/HtmlArtifactPanel'
import type { HtmlArtifact } from '@/lib/htmlArtifacts'
import { createHtmlArtifact, isHtmlPath } from '@/lib/htmlArtifacts'
export interface FileBrowserHandle {
goBack: () => void
@@ -51,6 +54,10 @@ const encodeBase64 = (content: string) => {
return btoa(binary)
}
const isHtmlFileInfo = (file: FileInfo): boolean => (
isHtmlPath(file.path) || isHtmlPath(file.name) || file.mimeType === 'text/html'
)
async function readFileEntry(entry: FileSystemFileEntry): Promise<File> {
return new Promise((resolve, reject) => {
entry.file(resolve, reject)
@@ -135,6 +142,7 @@ export const FileBrowser = forwardRef<FileBrowserHandle, FileBrowserProps>(funct
const [currentPath, setCurrentPath] = useState(basePath)
const [files, setFiles] = useState<FileInfo | null>(null)
const [selectedFile, setSelectedFile] = useState<FileInfo | null>(null)
const [htmlArtifact, setHtmlArtifact] = useState<HtmlArtifact | null>(null)
const [searchQuery, setSearchQuery] = useState('')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
@@ -152,7 +160,17 @@ useEffect(() => {
if (initialFileData) {
setSelectedFile(initialFileData)
if (isMobile) {
setIsPreviewModalOpen(true)
if (isHtmlFileInfo(initialFileData)) {
setHtmlArtifact(createHtmlArtifact({
source: 'file',
path: initialFileData.path,
title: initialFileData.name,
}))
setIsPreviewModalOpen(false)
} else {
setHtmlArtifact(null)
setIsPreviewModalOpen(true)
}
onPreviewStateChange?.(true)
}
}
@@ -262,7 +280,17 @@ useEffect(() => {
// On mobile, open preview in modal
if (isMobile) {
setIsPreviewModalOpen(true)
if (isHtmlFileInfo(fullFileData)) {
setHtmlArtifact(createHtmlArtifact({
source: 'file',
path: fullFileData.path,
title: fullFileData.name,
}))
setIsPreviewModalOpen(false)
} else {
setHtmlArtifact(null)
setIsPreviewModalOpen(true)
}
onPreviewStateChange?.(true)
}
} catch (err) {
@@ -275,10 +303,19 @@ useEffect(() => {
const handleCloseModal = useCallback(() => {
setIsPreviewModalOpen(false)
setHtmlArtifact(null)
setSelectedFile(null)
onPreviewStateChange?.(false)
}, [onPreviewStateChange])
const handleCloseHtmlArtifact = useCallback(() => {
setHtmlArtifact(null)
setSelectedFile(null)
onPreviewStateChange?.(false)
}, [onPreviewStateChange])
const handleToggleHtmlArtifactFullscreen = useCallback(() => {}, [])
const handleDirectoryClick = (path: string) => {
loadFiles(path)
}
@@ -645,6 +682,16 @@ useEffect(() => {
file={selectedFile}
showFilePreviewHeader={true}
/>
{isMobile && htmlArtifact && (
<HtmlArtifactPanel
artifact={htmlArtifact}
isFullscreen={true}
isMobile={true}
onClose={handleCloseHtmlArtifact}
onToggleFullscreen={handleToggleHtmlArtifactFullscreen}
/>
)}
</div>
)
}
@@ -746,6 +793,16 @@ useEffect(() => {
onClose={handleCloseModal}
file={selectedFile}
/>
{isMobile && htmlArtifact && (
<HtmlArtifactPanel
artifact={htmlArtifact}
isFullscreen={true}
isMobile={true}
onClose={handleCloseHtmlArtifact}
onToggleFullscreen={handleToggleHtmlArtifactFullscreen}
/>
)}
{uploadDialog}
</div>
@@ -7,6 +7,15 @@ import { FileBrowser } from './FileBrowser'
import type { FileBrowserHandle } from './FileBrowser'
import * as useMobile from '../../hooks/useMobile'
vi.mock('@/components/html-preview/HtmlArtifactPanel', () => ({
HtmlArtifactPanel: ({ artifact, onClose }: { artifact: { path?: string } | null; onClose: () => void }) => (
<div data-testid="html-artifact-panel">
<span>{artifact?.path}</span>
<button aria-label="Close preview" onClick={onClose}>Close</button>
</div>
),
}))
function createQueryClient() {
return new QueryClient({
defaultOptions: {
@@ -87,6 +96,60 @@ describe('FileBrowserSheet', () => {
})
describe('FileBrowser navigation', () => {
it('opens mobile HTML files with the shared HTML artifact panel', async () => {
const mobileSpy = vi.spyOn(useMobile, 'useMobile').mockReturnValue(true)
const originalFetch = globalThis.fetch
const htmlFile = {
name: 'dashboard.html',
path: 'test-repo/dashboard.html',
isDirectory: false,
size: 24,
mimeType: 'text/html',
content: btoa('<h1>Dashboard</h1>'),
lastModified: new Date(),
}
globalThis.fetch = vi.fn(async (input: RequestInfo | URL) => {
const url = new URL(String(input), 'http://localhost')
const path = url.searchParams.get('path')
if (path === htmlFile.path) {
return {
ok: true,
json: async () => htmlFile,
} as Response
}
return {
ok: true,
json: async () => ({
name: 'test-repo',
path: 'test-repo',
isDirectory: true,
children: [htmlFile],
}),
} as Response
})
try {
render(
<FileBrowser
basePath="test-repo"
embedded={true}
/>,
{ wrapper: createWrapper() }
)
fireEvent.click(await screen.findByText('dashboard.html'))
expect(await screen.findByTestId('html-artifact-panel')).toHaveTextContent('test-repo/dashboard.html')
expect(screen.queryByTitle('HTML preview: dashboard.html')).not.toBeInTheDocument()
} finally {
globalThis.fetch = originalFetch
mobileSpy.mockRestore()
}
})
it('exposes imperative handle with goBack, canGoBack, and getCurrentPath', () => {
const ref = { current: null as unknown as FileBrowserHandle }
@@ -1091,5 +1154,3 @@ describe('FileBrowserSheet swipe decision integration', () => {
mockUseSwipeBack.mockRestore()
})
})
@@ -1,9 +1,11 @@
import { memo, useCallback, useState, useEffect, useRef } from "react";
import { FilePreview } from "./FilePreview";
import { FullscreenSheet } from "@/components/ui/fullscreen-sheet";
import { Button } from "@/components/ui/button";
import type { FileInfo } from "@/types/files";
import { GPU_ACCELERATED_STYLE, MODAL_TRANSITION_MS } from "@/lib/utils";
import { useSwipeBack } from "@/hooks/useMobile";
import { X } from "lucide-react";
interface MobileFilePreviewModalProps {
isOpen: boolean;
@@ -69,13 +71,24 @@ export const MobileFilePreviewModal = memo(function MobileFilePreviewModal({
return (
<div ref={containerRef} style={{ isolation: 'isolate' }}>
<FullscreenSheet style={{ ...GPU_ACCELERATED_STYLE, ...swipeStyles }}>
<div className={`h-full overflow-hidden bg-background pt-safe ${showFilePreviewHeader ? "" : "pb-8"}`}>
<FullscreenSheet className="h-dvh max-h-dvh w-screen max-w-screen overflow-hidden" style={{ ...GPU_ACCELERATED_STYLE, ...swipeStyles }}>
<div className="flex h-full min-h-0 flex-1 flex-col overflow-hidden bg-background pt-safe">
{!showFilePreviewHeader && (
<Button
variant="ghost"
size="icon-sm"
onClick={handleClose}
aria-label="Close preview"
className="absolute right-2 top-2 z-10"
>
<X className="size-4" />
</Button>
)}
<FilePreview
key={localFile.path}
file={localFile}
hideHeader={!showFilePreviewHeader}
isMobileModal={showFilePreviewHeader}
isMobileModal
onCloseModal={handleClose}
/>
</div>
@@ -42,7 +42,8 @@ describe('HtmlArtifactPanel', () => {
const iframe = screen.getByTitle('Test Preview')
expect(iframe).toBeInTheDocument()
expect(iframe).toHaveAttribute('srcdoc', '<h1>Hello World</h1>')
expect(iframe.getAttribute('srcdoc')).toContain('<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">')
expect(iframe.getAttribute('srcdoc')).toContain('<h1>Hello World</h1>')
expect(iframe).toHaveAttribute('sandbox', 'allow-scripts')
})
@@ -148,21 +149,6 @@ describe('HtmlArtifactPanel', () => {
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
@@ -1,7 +1,6 @@
import { getFilePreviewUrl } from '@/api/files'
import {
FullscreenSheet,
FullscreenSheetHeader,
FullscreenSheetContent,
} from '@/components/ui/fullscreen-sheet'
import { Button } from '@/components/ui/button'
@@ -31,34 +30,27 @@ export function HtmlArtifactPanel({
: 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>
)}
const headerButtons = (
<div className="flex items-center gap-1">
{!isMobile && (
<Button
variant="ghost"
size="icon-sm"
onClick={onClose}
aria-label="Close preview"
onClick={onToggleFullscreen}
aria-label={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
>
<X className="size-4" />
{isFullscreen ? <Minimize2 className="size-4" /> : <Maximize2 className="size-4" />}
</Button>
</div>
)}
<Button
variant="ghost"
size="icon-sm"
onClick={onClose}
aria-label="Close preview"
>
<X className="size-4" />
</Button>
</div>
)
@@ -72,11 +64,11 @@ export function HtmlArtifactPanel({
if (isMobile || isFullscreen) {
return (
<FullscreenSheet>
<FullscreenSheetHeader>
{header}
</FullscreenSheetHeader>
<FullscreenSheetContent>
<FullscreenSheet className="h-dvh max-h-dvh w-screen max-w-screen overflow-hidden">
<FullscreenSheetContent className="relative h-full max-h-full w-full max-w-full">
<div className="absolute top-2 right-2 z-10">
{headerButtons}
</div>
{frame}
</FullscreenSheetContent>
</FullscreenSheet>
@@ -84,13 +76,13 @@ export function HtmlArtifactPanel({
}
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="hidden md:flex w-[45%] max-w-[720px] min-w-[360px] border-l border-border bg-background flex-col relative">
<div className="flex-1 min-h-0">
{frame}
</div>
<div className="absolute top-2 right-2 z-10">
{headerButtons}
</div>
</div>
)
}
@@ -1,4 +1,5 @@
import { cn } from '@/lib/utils'
import { normalizeHtmlPreviewDocument } from '@/lib/htmlArtifacts'
interface HtmlPreviewFrameProps {
title: string
@@ -9,14 +10,16 @@ interface HtmlPreviewFrameProps {
export function HtmlPreviewFrame({ title, src, srcDoc, className }: HtmlPreviewFrameProps) {
const sandbox = src ? 'allow-scripts allow-same-origin' : 'allow-scripts'
const normalizedSrcDoc = srcDoc ? normalizeHtmlPreviewDocument(srcDoc) : undefined
return (
<iframe
title={title}
src={src}
srcDoc={srcDoc}
srcDoc={normalizedSrcDoc}
sandbox={sandbox}
referrerPolicy="no-referrer"
className={cn('h-full w-full border-0 bg-white', className)}
scrolling="yes"
className={cn('block h-full max-h-full min-h-0 w-full max-w-full border-0 bg-white', className)}
/>
)
}
+26
View File
@@ -4,6 +4,7 @@ import {
normalizeWorkspaceFilePath,
createHtmlArtifact,
getArtifactTitle,
normalizeHtmlPreviewDocument,
} from './htmlArtifacts'
describe('isHtmlPath', () => {
@@ -154,3 +155,28 @@ describe('getArtifactTitle', () => {
expect(getArtifactTitle(undefined)).toBe('Untitled Artifact')
})
})
describe('normalizeHtmlPreviewDocument', () => {
it('adds viewport meta and sizing style to html fragments', () => {
const result = normalizeHtmlPreviewDocument('<h1>Hello</h1>')
expect(result).toContain('name="viewport"')
expect(result).toContain('opencode-html-preview-sizing')
expect(result).toContain('overflow-y:auto!important')
expect(result).toContain('<h1>Hello</h1>')
})
it('does not duplicate an existing viewport meta tag', () => {
const result = normalizeHtmlPreviewDocument('<head><meta name="viewport" content="width=device-width"></head>')
expect(result.match(/name="viewport"/g)).toHaveLength(1)
expect(result).toContain('opencode-html-preview-sizing')
})
it('inserts preview sizing before an existing closing head tag', () => {
const result = normalizeHtmlPreviewDocument('<html><head><title>Demo</title></head><body>Demo</body></html>')
expect(result).toContain('<title>Demo</title><meta name="viewport"')
expect(result).toContain('opencode-html-preview-sizing')
})
})
+24
View File
@@ -14,6 +14,12 @@ export interface OpenHtmlArtifactInput {
}
const HTML_EXTENSIONS = new Set(['.html', '.htm'])
const HTML_PREVIEW_STYLE_ID = 'opencode-html-preview-sizing'
const HTML_PREVIEW_VIEWPORT_META = '<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">'
const HTML_PREVIEW_SIZING_STYLE = `<style id="${HTML_PREVIEW_STYLE_ID}">html,body{width:100%;max-width:100%;min-width:0;min-height:100%;height:auto!important;margin:0;overflow-x:hidden!important;overflow-y:auto!important;}#root,#__next{min-height:100%;height:auto!important;max-width:100%;overflow-x:hidden;}*,*::before,*::after{box-sizing:border-box;}img,svg,video,canvas{max-width:100%;}</style>`
const VIEWPORT_META_PATTERN = /<meta\s+[^>]*name=["']viewport["'][^>]*>/i
const HEAD_OPEN_PATTERN = /<head([^>]*)>/i
const HEAD_CLOSE_PATTERN = /<\/head>/i
export function isHtmlPath(path: string | undefined): boolean {
if (!path) return false
@@ -42,6 +48,24 @@ export function createHtmlArtifact(input: OpenHtmlArtifactInput): HtmlArtifact {
return { id, title, source: input.source, html: input.html, path: input.path }
}
export function normalizeHtmlPreviewDocument(html: string): string {
const viewportMeta = VIEWPORT_META_PATTERN.test(html) ? '' : HTML_PREVIEW_VIEWPORT_META
const sizingStyle = html.includes(HTML_PREVIEW_STYLE_ID) ? '' : HTML_PREVIEW_SIZING_STYLE
const headContent = `${viewportMeta}${sizingStyle}`
if (!headContent) return html
if (HEAD_CLOSE_PATTERN.test(html)) {
return html.replace(HEAD_CLOSE_PATTERN, `${headContent}</head>`)
}
if (HEAD_OPEN_PATTERN.test(html)) {
return html.replace(HEAD_OPEN_PATTERN, `<head$1>${headContent}`)
}
return `<head>${headContent}</head>${html}`
}
export function normalizeWorkspaceFilePath(filePath: string, repoFullPath?: string): string {
if (!filePath.startsWith('/') || !repoFullPath) return filePath
const workspaceReposPath = repoFullPath.substring(0, repoFullPath.lastIndexOf('/'))