'use client';
import { Component, useEffect, useRef, useState, type ComponentType, type ReactNode, type RefObject } from 'react';
import { ArrowLeft, Download, ExternalLink, RotateCw, X } from 'lucide-react';
import { Dialog, DialogContent, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { FEISHU_TEMPLATE_DIRECTORY, findDocument, templateDownloadUrl, type DocumentId } from '@/lib/documents';
import { appPath } from '@/lib/base-path';
import type { TemplateDocumentProps } from './template-document';
function PreviewError({ message, onRetry }: { message: string; onRetry: () => void }) {
return
{message}
;
}
class DocumentBoundary extends Component<{ children: ReactNode; onRetry: () => void }, { failed: boolean }> {
state = { failed: false };
static getDerivedStateFromError() { return { failed: true }; }
render() { return this.state.failed ? : this.props.children; }
}
type PreviewContent = { id: DocumentId; text?: string; Body?: ComponentType; error?: string };
export default function TemplatePreview({ documentId, onClose, returnFocus }: { documentId: DocumentId; onClose: () => void; returnFocus: RefObject }) {
const [current, setCurrent] = useState(documentId);
const [history, setHistory] = useState([]);
const [attempt, setAttempt] = useState(0);
const [content, setContent] = useState(null);
const scroll = useRef(null);
const info = findDocument(current)!;
const loading = content?.id !== current;
const Body = content?.Body;
useEffect(() => {
const controller = new AbortController();
const text = fetch(appPath('/api/documents/' + encodeURIComponent(findDocument(current)!.filename) + '?format=json'), { signal: controller.signal, cache: 'no-store' })
.then(async response => {
const result = await response.json() as { content?: string; error?: string };
if (!response.ok || typeof result.content !== 'string') throw new Error(result.error || '模板暂时无法加载,请重试。');
return result.content;
});
// Keep the dialog and form mounted even when a renderer chunk fails. Calling
// import again on retry avoids React.lazy's cached rejected promise.
const renderer = import('./template-document').catch(() => { throw new Error('模板预览未能加载,请重试。已填内容仍然保留。'); });
void Promise.all([text, renderer])
.then(([text, module]) => { if (!controller.signal.aborted) setContent({ id: current, text, Body: module.default }); })
.catch(error => {
if (controller.signal.aborted) return;
setContent({ id: current, error: error instanceof Error ? error.message : '模板加载失败,请重试。' });
controller.abort();
});
return () => controller.abort();
}, [current, attempt]);
function retry() { setContent(null); setAttempt(value => value + 1); }
function openDocument(id: DocumentId) { setHistory(previous => [...previous, current]); setCurrent(id); scroll.current?.scrollTo(0, 0); }
return ;
}