Files
Agent-Workbench/src/client/HtmlFilePreview.tsx
T

25 lines
2.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, useState } from 'react';
import { ExternalLink, LoaderCircle, RotateCw } from 'lucide-react';
import { api } from './api';
import { desktop } from './desktop';
import './LocalFiles.css';
type Preview = { id: string; url: string; projectId: string; path: string };
export function HtmlFilePreview({ projectId, path }: { projectId: string; path: string }) {
const [preview, setPreview] = useState<Preview | null>(null), [error, setError] = useState(''), [attempt, setAttempt] = useState(0), [loaded, setLoaded] = useState(false);
useEffect(() => {
let current = true, owned: Preview | null = null;
const close = (value: Preview) => api('/projects/' + projectId + '/file-previews/' + value.id, {}, 'DELETE').catch(() => {});
setPreview(null); setError(''); setLoaded(false);
void api<Preview>('/projects/' + projectId + '/file-previews', { path }).then(value => {
if (current) { owned = value; setPreview(value); } else void close(value);
}).catch(cause => { if (current) setError(cause instanceof Error ? cause.message : '无法打开 HTML 预览。'); });
return () => { current = false; if (owned) void close(owned); };
}, [projectId, path, attempt]);
return <div className="html-file-preview">
<div className="html-preview-toolbar"><span>HTML 文件预览</span><button type="button" className="button secondary" onClick={() => setAttempt(value => value + 1)}><RotateCw size={14} />刷新预览</button>{preview && (desktop?.openFilePreview ? <button type="button" className="button secondary" onClick={() => void desktop!.openFilePreview!({ projectId, url: preview.url }).catch(cause => setError(cause.message))}><ExternalLink size={14} />在浏览器打开</button> : <a className="button secondary" href={preview.url} target="_blank" rel="noopener noreferrer"><ExternalLink size={14} />独立页面</a>)}</div>
{error ? <div className="html-preview-message" role="alert"><p>{error}</p><button className="button secondary" onClick={() => setAttempt(value => value + 1)}>重试预览</button></div> : <>{!loaded && <div className="html-preview-message" role="status"><LoaderCircle size={17} className="spin" />正在打开 HTML 页面…</div>}{preview && <iframe key={preview.id} title={'HTML 预览:' + path} src={preview.url} sandbox="allow-scripts" referrerPolicy="no-referrer" onLoad={() => setLoaded(true)} onError={() => setError('页面加载失败,请刷新预览后重试。')} />}</>}
<p className="html-preview-note">直接读取已保存文件,支持页面脚本与相对资源。需要后端或构建的应用请启动项目预览。</p>
</div>;
}