ArtifactPreview Component
The ArtifactPreview component provides secure, sandboxed preview functionality for code artifacts including React components, JavaScript, and HTML with extensive library support.
Overview
This component renders interactive previews of code artifacts in a secure iframe environment. It supports React JSX/TSX components, vanilla JavaScript, and HTML with automatic library loading and security features.
Location
src/components/ArtifactPreview.tsx
Features
Supported Artifact Types
- React Components: JSX/TSX with full React 18 support
- JavaScript: Browser-compatible JavaScript with library access
- HTML: Direct HTML rendering with styling support
- TypeScript: TSX components with Babel transpilation
Auto-Preview Logic
- React/JSX/TSX: Automatically enables preview mode
- JavaScript: Auto-preview for browser-compatible code
- Server-side Detection: Identifies Node.js/Express code and shows appropriate messaging
- Manual Control: Users can toggle preview on/off
Extensive Library Support
Core Libraries (All Artifact Types)
- Charts: Recharts (LineChart, BarChart, PieChart, etc.)
- Date/Time: dayjs, date-fns for date manipulation
- Utilities: lodash, uuid, classNames
- Styling: Tailwind CSS with custom theme colors
React-Specific Libraries
- Animation: Framer Motion (motion components, AnimatePresence)
- Forms: React Hook Form (useForm, Controller)
- Drag & Drop: React Beautiful DnD
- Charts: Full Recharts component set
Security Features
- Domain Allowlist: Restricts external data fetching to approved domains
- Secure Fetch: Custom
secureFetch()function with domain validation - Content Security Policy: CSP-safe SVG and image handling
- Sandboxed Execution: Iframe isolation with controlled permissions
Props Interface
interface ArtifactPreviewProps {
content: string; // The code content to preview
type: string; // Artifact type (react, jsx, tsx, js, html)
title: string; // Display title for the preview
}
Usage Example
import { ArtifactPreview } from '@/components/ArtifactPreview';
function CodeDisplay({ artifact }) {
return (
<div className="artifact-container">
<ArtifactPreview
content={artifact.code}
type={artifact.type}
title={artifact.title}
/>
</div>
);
}
Secure Data Fetching
Approved Domains
The component includes an extensive allowlist of trusted domains:
const ALLOWED_DOMAINS = [
// Government & Official Data
'data.gov', 'api.census.gov', 'opendata.gov.uk',
// Financial & Economic
'api.worldbank.org', 'query1.finance.yahoo.com',
// Development APIs
'api.github.com', 'jsonplaceholder.typicode.com',
// CDN & Static Files
'cdn.jsdelivr.net', 'unpkg.com',
// Academic & Research
'api.crossref.org', 'export.arxiv.org'
];
Data Fetching Functions
// Secure fetch with domain validation
window.secureFetch = async function(url, options = {})
// Convenience methods
window.fetchJSON = async function(url) // JSON data
window.fetchCSV = async function(url) // CSV with parsing
window.fetchXML = async function(url) // XML documents
window.fetchText = async function(url) // Plain text
React Artifact Example
function App() {
const [count, setCount] = React.useState(0);
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-4">Counter Example</h1>
<p className="mb-4">Count: {count}</p>
<button
onClick={() => setCount(count + 1)}
className="bg-blue-500 text-white px-4 py-2 rounded"
>
Increment
</button>
</div>
);
}
Chart Integration Example
function ChartDemo() {
const data = [
{ name: 'Jan', sales: 1000 },
{ name: 'Feb', sales: 1200 },
{ name: 'Mar', sales: 900 }
];
return (
<Chart.ResponsiveContainer width="100%" height={300}>
<Chart.BarChart data={data}>
<Chart.XAxis dataKey="name" />
<Chart.YAxis />
<Chart.Bar dataKey="sales" fill="#8884d8" />
</Chart.BarChart>
</Chart.ResponsiveContainer>
);
}
Implementation Details
Browser Detection
const isBrowserJavaScript = type.toLowerCase() === 'javascript' &&
!content.includes('require(') &&
!content.includes('module.exports') &&
!content.includes('app.listen(');
Error Handling
- JavaScript Errors: Captured and displayed in preview
- React Compilation: Babel transpilation with error reporting
- Network Errors: Graceful handling of failed library loads
- Domain Violations: Clear security error messages
Performance Optimizations
- Library Caching: CDN resources cached by browser
- Lazy Loading: Libraries loaded only when needed
- Iframe Isolation: Prevents performance impact on main app
Preview Controls
Available Actions
- Run/Hide Preview: Toggle preview mode
- Refresh: Reload the preview iframe
- Open in New Tab: Launch preview in separate window
- Info Tooltip: Shows library and feature information
Auto-Detection Messages
- Server-side Code: Displays instructions for Node.js/Express code
- Compatibility Warnings: Alerts for unsupported features
- Library Status: Shows loading state for external dependencies
Dependencies
- React 18 (for React artifacts)
- Babel Standalone (JSX transpilation)
- Tailwind CSS (styling)
- Various CDN libraries (Recharts, Framer Motion, etc.)
Browser Compatibility
- Modern Browsers: Chrome 66+, Firefox 63+, Safari 13.1+
- Iframe Sandbox: All modern browsers
- ES6 Features: Transpiled for wider compatibility
- CSP Compliance: Works with Content Security Policies
Security Considerations
Sandboxing
- Iframe with
sandbox="allow-scripts allow-same-origin" - No access to parent window or DOM
- Isolated execution context
Data Access Control
- Domain allowlist prevents unauthorized external requests
- No file system access
- No sensitive environment variable exposure
Code Execution
- Client-side only execution
- No server-side code evaluation
- Safe library loading from trusted CDNs
Related Components
ArtifactDisplay- Main artifact rendering componentArtifactPanel- Artifact management interface- Code editor components for artifact creation