同步:完善质量分析工作台并更新主题字体
同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。 补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。 统一午夜黑及其他主题的控件细节、中文和业务数字字体。 排除本地业务数据、凭据、预览、发布与验收产物。 验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
+206
-149
@@ -1,14 +1,23 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Modal } from 'antd';
|
||||
import { Alert, Button, Modal } from 'antd';
|
||||
import { DownloadOutlined } from '@ant-design/icons';
|
||||
import { toPng } from 'html-to-image';
|
||||
import { AnalysisLegacyResults } from './AnalysisLegacyResults';
|
||||
import { AnalysisReportNarrative } from './AnalysisReportNarrative';
|
||||
import { parseServerReadingSummary } from './analysisReadingModel';
|
||||
import { buildAnalysisNarrative } from './analysisReportModel';
|
||||
import { integrateNativeReportNarrative } from './nativeReportNarrative';
|
||||
import { integrateNativeReportNarrative, compactNativeReportReading } from './nativeReportNarrative';
|
||||
import narrativeCss from './analysis-narrative.css?inline';
|
||||
import exportCss from './analysis-report-export.css?inline';
|
||||
import './analysis-report-export.css';
|
||||
import { analysisScopeText } from './analysisScope';
|
||||
import { captureReportLongImage } from './analysisReportCapture';
|
||||
import { downloadAuthorizedReport, reportDownloadName } from './analysisReportFiles';
|
||||
import { reportSnapshotIdentity } from './analysisSnapshot';
|
||||
import { analysisDisplayTextRemovalRanges, sanitizeAnalysisDisplayText } from './analysisDisplayText';
|
||||
import { resolveAnalysisReportTitle, stripDuplicateFirstMarkdownH1 } from './analysisReportTitle';
|
||||
import { useReportVisualImages, type ReportVisualImage } from './AnalysisReportVisuals';
|
||||
import { analysisMemberListFullyRead, analysisMemberListPeriod, parseAnalysisMemberList } from './analysisMembersModel';
|
||||
import { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||||
@@ -17,44 +26,56 @@ const escape = (value: string) => value.replaceAll('&', '&').replaceAll('<',
|
||||
|
||||
const reportCss = `
|
||||
${narrativeCss}
|
||||
${exportCss}
|
||||
|
||||
.q-report .ai-markdown-table-wrap{height:auto!important;max-height:none!important;overflow:visible!important;border:0;border-radius:0;background:#fff;margin:10px 0 14px}.q-report .ai-markdown{color:inherit;font:inherit}.q-report .ai-markdown pre{white-space:pre-wrap;overflow-wrap:anywhere}
|
||||
.q-report{--surface:#fff;--blue-soft:#eef1ff;--line:#dfe5ef;--ink:#202b3c;--muted-ink:#738197;box-sizing:border-box;width:900px;padding:52px;background:#fff;color:#202b3c;font:15px/1.85 -apple-system,BlinkMacSystemFont,"PingFang SC","Microsoft YaHei",sans-serif;overflow-wrap:anywhere}
|
||||
.q-report *{box-sizing:border-box}.q-report header{padding-bottom:26px;border-bottom:2px solid #355f9b}.q-report .q-eyebrow{font-size:12px;letter-spacing:2px;color:#53739c}.q-report h1{font-size:27px;line-height:1.5;margin:10px 0}.q-report .q-subtitle{font-size:12px;color:#69778b}.q-report h2{font-size:18px;margin:30px 0 12px}.q-report p{margin:10px 0}.q-report .q-prose{white-space:pre-wrap}.q-report .q-kpis{display:flex;gap:12px;margin:22px 0}.q-report .q-kpi{flex:1;padding:17px 18px;background:#f2f6fb;border-radius:6px}.q-report .q-kpi span{display:block;font-size:12px;color:#66778d}.q-report .q-kpi strong{display:block;font-size:27px;font-variant-numeric:tabular-nums;color:#254f87}.q-report table{width:100%;border:1px solid #dfe5ef;border-collapse:collapse;font-size:13px;table-layout:fixed}.q-report th{background:#f2f6fb;color:#53657c;text-align:center;font-weight:650}.q-report th,.q-report td{padding:10px 12px;border:1px solid #dfe5ef;text-align:center;vertical-align:middle}.q-report tbody tr:nth-child(even){background:#f8fafd}.q-report th:first-child,.q-report td:first-child{width:62px;color:#738197;font-variant-numeric:tabular-nums}.q-report .q-note{font-size:12px;color:#69778b}.q-report footer{margin-top:34px;padding-top:16px;border-top:1px solid #dde5ef;font-size:11px;color:#738197}.q-report .q-partial{color:#996b20}@media print{body{margin:0}.q-report{width:100%;padding:20px}tr{break-inside:avoid}}
|
||||
.q-report .q-member-list td{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}.q-report .q-member-list th:last-child,.q-report .q-member-list td:last-child{width:90px}
|
||||
.q-report .q-source-record-list{margin-top:30px}.q-report .q-source-record-set{margin:22px 0}.q-report .q-source-record-set h3{font-size:15px;margin:18px 0 6px}.q-report .q-source-record-list .q-note{font-size:12px;color:#69778b}.q-report .q-source-record-list table{table-layout:auto}.q-report .q-source-record-list th:first-child,.q-report .q-source-record-list td:first-child{width:48px;min-width:48px;white-space:nowrap;overflow-wrap:normal;word-break:normal;color:inherit;font-variant-numeric:tabular-nums}.q-report .q-source-record-list th:nth-child(2),.q-report .q-source-record-list td:nth-child(2){width:140px}.q-report .q-source-record-list td{white-space:pre-wrap;overflow-wrap:anywhere;word-break:break-word}
|
||||
`;
|
||||
|
||||
function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp: string; visualImages: ReportVisualImage[] }) {
|
||||
export function ReportDocument({ turn, stamp, visualImages }: { turn: Row; stamp: string; visualImages: ReportVisualImage[] }) {
|
||||
const result = Object.keys(record(turn.result)).length ? record(turn.result) : turn;
|
||||
const answer = sanitizeAnalysisDisplayText(text(result.reportMarkdown || turn.reportMarkdown || result.answer || turn.answer));
|
||||
const model = buildAnalysisNarrative(answer, result.visuals || turn.visuals, String(turn.question || ''));
|
||||
const reportMarkdown = String(result.reportMarkdown || turn.reportMarkdown || '');
|
||||
const sourceAnswer = sanitizeAnalysisDisplayText(text(reportMarkdown || result.answer || turn.answer));
|
||||
const model = buildAnalysisNarrative(sourceAnswer, result.visuals || turn.visuals);
|
||||
const scope = analysisScopeText(turn);
|
||||
const title = resolveAnalysisReportTitle(result.reportTitle, turn.reportTitle, reportMarkdown, model.period, scope);
|
||||
const answer = sanitizeAnalysisDisplayText(stripDuplicateFirstMarkdownH1(sourceAnswer, title));
|
||||
const memberList = parseAnalysisMemberList(result.memberList ?? turn.memberList);
|
||||
const recordListValue = result.recordList ?? turn.recordList;
|
||||
const memberListStatus = memberList && analysisMemberListFullyRead(memberList)
|
||||
? `已读取全部 ${memberList.rowsReturned} 条`
|
||||
: memberList ? `${memberList.queryComplete ? '已读取' : '读取未完成'} ${memberList.rowsReturned} / ${memberList.totalCount} 条` : '';
|
||||
return <div className="q-report">
|
||||
<style>{reportCss}</style>
|
||||
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{model.title.length > 90 ? `${model.title.slice(0, 90)}…` : model.title}</h1>
|
||||
<div className="q-subtitle">{[model.period, model.scope, stamp].filter(Boolean).join(' · ')}</div>
|
||||
{String(turn.question || '') !== model.title && <p className="q-report-question">{sanitizeAnalysisDisplayText(String(turn.question || ''))}</p>}
|
||||
<header><div className="q-eyebrow">质量数据分析平台 · 分析报告</div><h1>{title}</h1>
|
||||
<div className="q-subtitle">{stamp}</div>
|
||||
{scope && <p className="q-report-scope">{scope}</p>}
|
||||
</header>
|
||||
{String(turn.status || result.status) === 'PARTIAL' && <p className="q-partial">本次分析部分完成,以下保留已获得的结果。</p>}
|
||||
<AnalysisReportNarrative turn={turn} answer={answer} images={visualImages} />
|
||||
<AnalysisReportNarrative turn={turn} answer={answer} images={visualImages} mode="full" />
|
||||
<AnalysisLegacyResults turn={turn} />
|
||||
<footer>数据来源:质量数据分析平台。指标沿用正式计算口径;数据明细保留在 HTML 附录,现场原因以实际核查为准。</footer>
|
||||
{recordListValue !== undefined && recordListValue !== null && <details className="q-report-appendix"><summary>附录:完整来源记录</summary><AnalysisRecordListReport value={recordListValue} /></details>}
|
||||
{memberList && <details className="q-report-appendix"><summary>附录:完整成员清单</summary><section className="q-member-list">
|
||||
<h2>成员清单</h2>
|
||||
<p className="q-note">{analysisMemberListPeriod(memberList.period)} · {memberListStatus}</p>
|
||||
<table><thead><tr><th>序号</th>{memberList.fields.map(field => <th key={field.key}>{field.label}</th>)}<th>阶段</th></tr></thead>
|
||||
<tbody>{memberList.rows.map((row, index) => <tr key={index}>
|
||||
<td>{index + 1}</td>{memberList.fields.map(field => <td key={field.key}>{text(row.values[field.key])}</td>)}
|
||||
<td>{row.stages.map(stage => stage === 'black' ? '黑片' : '亮片').join('、')}</td>
|
||||
</tr>)}</tbody>
|
||||
</table>
|
||||
</section></details>}
|
||||
{!parseServerReadingSummary(turn) && <footer>数据来源:质量数据分析平台。指标沿用正式计算口径;现场原因以实际核查为准。</footer>}
|
||||
</div>;
|
||||
}
|
||||
|
||||
function download(href: string, name: string) { const link = document.createElement('a'); link.href = href; link.download = name; link.click(); }
|
||||
|
||||
/** 图片无法展开明细,生成前临时展开全部附录。 */
|
||||
async function captureReportImage(node: HTMLElement, options: NonNullable<Parameters<typeof toPng>[1]> = {}) {
|
||||
const details = [...node.querySelectorAll('details')].map(element => ({ element, open: element.open }));
|
||||
details.forEach(({ element }) => { element.open = true; });
|
||||
try {
|
||||
await node.ownerDocument.fonts?.ready;
|
||||
await new Promise<void>(resolve => requestAnimationFrame(() => resolve()));
|
||||
const height = Math.max(node.scrollHeight, node.offsetHeight);
|
||||
if (height > 16000) throw new Error('报告较长,请下载 HTML 查看完整图文与明细。');
|
||||
return await toPng(node, { height, backgroundColor: '#ffffff', ...options });
|
||||
} finally {
|
||||
details.forEach(({ element, open }) => { element.open = open; });
|
||||
}
|
||||
function reportHtmlFromElement(element: HTMLElement): string {
|
||||
const copy = element.cloneNode(true) as HTMLElement;
|
||||
const title = copy.querySelector('.q-report header h1')?.textContent?.trim() || '质量分析报告';
|
||||
return `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"><title>${escape(title)}</title><style>body{margin:0;background:#edf1f5}.q-report{margin:0 auto}</style></head><body>${copy.innerHTML}</body></html>`;
|
||||
}
|
||||
|
||||
function removeDisplayMetadataFromElement(element: Element): void {
|
||||
@@ -87,7 +108,7 @@ function removeDisplayMetadataFromElement(element: Element): void {
|
||||
});
|
||||
}
|
||||
|
||||
function safeNativeHtml(source: string): string {
|
||||
function safeNativeHtml(source: string, title: string): string {
|
||||
const parsed = new DOMParser().parseFromString(source, 'text/html');
|
||||
parsed.querySelectorAll('script,iframe,object,embed,base,form,link,video,audio,source,track').forEach(element => element.remove());
|
||||
parsed.querySelectorAll('meta[http-equiv]').forEach(meta => {
|
||||
@@ -140,7 +161,18 @@ function safeNativeHtml(source: string): string {
|
||||
if (node.nodeType === Node.COMMENT_NODE) node.parentNode?.removeChild(node);
|
||||
else if (node.nodeValue) node.nodeValue = sanitizeAnalysisDisplayText(node.nodeValue);
|
||||
}
|
||||
parsed.title = sanitizeAnalysisDisplayText(parsed.title);
|
||||
parsed.title = title;
|
||||
const headings = [...parsed.body.querySelectorAll('h1')];
|
||||
if (headings.length) {
|
||||
headings[0].textContent = title;
|
||||
for (const heading of headings.slice(1)) {
|
||||
if ((heading.textContent || '').replace(/\s+/g, '').trim() === title.replace(/\s+/g, '').trim()) heading.remove();
|
||||
}
|
||||
} else {
|
||||
const heading = parsed.createElement('h1');
|
||||
heading.textContent = title;
|
||||
parsed.body.prepend(heading);
|
||||
}
|
||||
|
||||
const policy = parsed.createElement('meta');
|
||||
policy.setAttribute('http-equiv', 'Content-Security-Policy');
|
||||
@@ -154,6 +186,8 @@ function safeNativeHtml(source: string): string {
|
||||
}
|
||||
|
||||
function frameContentHeight(doc: Document): number {
|
||||
const children = [...doc.body.children].filter(element => !['STYLE','SCRIPT'].includes(element.tagName));
|
||||
if (children.length) return Math.ceil(Math.max(...children.map(element => element.getBoundingClientRect().bottom - doc.body.getBoundingClientRect().top), 1));
|
||||
return Math.ceil(Math.max(
|
||||
doc.body.scrollHeight,
|
||||
doc.body.offsetHeight,
|
||||
@@ -179,149 +213,172 @@ function frameFontCss(doc: Document): string {
|
||||
return fontRules.join('\n');
|
||||
}
|
||||
|
||||
export function AnalysisReportExport({ turn }: { turn: Row }) {
|
||||
const { message } = App.useApp();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [stamp, setStamp] = useState('');
|
||||
const exportGeneration = useRef(0);
|
||||
useEffect(() => { exportGeneration.current += 1; setExporting(false); return () => { exportGeneration.current += 1; }; }, [open, turn.id]);
|
||||
const node = useRef<HTMLDivElement>(null);
|
||||
const visualReport = useReportVisualImages(turn, open);
|
||||
const title = String(turn.question || '质量分析报告').replace(/[\\/:*?"<>|\n\r]/g, '').slice(0, 60);
|
||||
const saveHtml = async () => {
|
||||
if (!node.current) return;
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current || !node.current) return;
|
||||
const html = `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"><title>${escape(title)}</title><style>body{margin:0;background:#edf1f5}.q-report{margin:0 auto}</style></head><body>${node.current.innerHTML}</body></html>`;
|
||||
const url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' }));
|
||||
download(url, `${title}.html`); setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
message.success(visualReport.failed ? 'HTML 已生成,未能绘制的图表已保留数据表。' : 'HTML 报告已生成');
|
||||
} catch (error) { if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '报告导出失败,请重试。'); }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
const saveImage = async () => {
|
||||
const report = node.current?.querySelector<HTMLElement>('.q-report');
|
||||
if (!report) return;
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
const png = await captureReportImage(report, { pixelRatio: 2, skipFonts: true });
|
||||
if (generation !== exportGeneration.current) return;
|
||||
download(png, `${title}.png`);
|
||||
message.success(visualReport.failed ? '报告图片已生成,未能绘制的图表已保留数据表。' : '报告图片已生成');
|
||||
} catch (error) { if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '图片生成失败,请重试或下载 HTML 报告。'); }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => { setStamp(new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })); setOpen(true); }}>生成报告</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => setOpen(false)} width={980} footer={<><Button disabled={exporting || visualReport.loading || !visualReport.authorized} onClick={() => void saveHtml()}>下载 HTML</Button><Button type="primary" loading={exporting} disabled={visualReport.loading || !visualReport.authorized} onClick={() => void saveImage()}>下载图片</Button></>}>
|
||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
||||
{visualReport.authorizationError && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||
{visualReport.authorized && <div className="analysis-report-preview" ref={node}><ReportDocument turn={turn} stamp={stamp} visualImages={visualReport.images} /></div>}
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
turn: Row;
|
||||
reportMarkdown: string;
|
||||
reportHtml?: string;
|
||||
function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }: {
|
||||
turn: Row; reportMarkdown?: string; reportHtml?: string; native?: boolean;
|
||||
}) {
|
||||
const { message } = App.useApp();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [progress, setProgress] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [stamp, setStamp] = useState('');
|
||||
const [frameHeight, setFrameHeight] = useState(1);
|
||||
const [frameReady, setFrameReady] = useState(false);
|
||||
const [prepared, setPrepared] = useState<{ url: string; name: string } | null>(null);
|
||||
const [preparedHtml, setPreparedHtml] = useState<{ url: string; name: string } | null>(null);
|
||||
const preparedUrl = useRef('');
|
||||
const preparedHtmlUrl = useRef('');
|
||||
const exportGeneration = useRef(0);
|
||||
useEffect(() => { exportGeneration.current += 1; setExporting(false); return () => { exportGeneration.current += 1; }; }, [open, turn.id]);
|
||||
const node = useRef<HTMLDivElement>(null);
|
||||
const iframe = useRef<HTMLIFrameElement>(null);
|
||||
const fallbackNode = useRef<HTMLElement>(null);
|
||||
const frameToggleCleanup = useRef<() => void>(() => undefined);
|
||||
const reportTurn = useMemo(() => reportMarkdown === undefined ? turn : { ...turn, reportMarkdown,
|
||||
result: { ...(Object.keys(record(turn.result)).length ? record(turn.result) : turn), reportMarkdown } }, [turn, reportMarkdown]);
|
||||
const snapshot = reportSnapshotIdentity(turn);
|
||||
const turnId = String(turn.id || turn.turnId || '');
|
||||
const currentExport = useRef({ open, turnId, snapshot, reportHtml, reportMarkdown });
|
||||
currentExport.current = { open, turnId, snapshot, reportHtml, reportMarkdown };
|
||||
const visualReport = useReportVisualImages(turn, open);
|
||||
const safeHtml = useMemo(() => {
|
||||
const html = reportHtml?.trim() ? safeNativeHtml(reportHtml) : '';
|
||||
if (!html) return '';
|
||||
return integrateNativeReportNarrative(html, turn, visualReport.images);
|
||||
}, [reportHtml, turn, visualReport.images]);
|
||||
const title = useMemo(() => {
|
||||
const nativeTitle = safeHtml ? new DOMParser().parseFromString(safeHtml, 'text/html').title : '';
|
||||
const heading = reportMarkdown.match(/^#\s+(.+)$/m)?.[1];
|
||||
return String(nativeTitle || heading || turn.question || '质量分析报告').replace(/[\\/:*?"<>|\n\r]/g, '').slice(0, 60) || '质量分析报告';
|
||||
}, [safeHtml, reportMarkdown, turn.question]);
|
||||
if (parseServerReadingSummary(reportTurn)) return '';
|
||||
if (!reportHtml?.trim()) return '';
|
||||
const result = Object.keys(record(reportTurn.result)).length ? record(reportTurn.result) : reportTurn;
|
||||
const markdown = String(result.reportMarkdown || reportTurn.reportMarkdown || '');
|
||||
const answer = sanitizeAnalysisDisplayText(text(markdown || result.answer || reportTurn.answer));
|
||||
const metadata = buildAnalysisNarrative(answer, result.visuals || reportTurn.visuals);
|
||||
const title = resolveAnalysisReportTitle(result.reportTitle, reportTurn.reportTitle, markdown,
|
||||
metadata.period, analysisScopeText(reportTurn));
|
||||
const withNarrative = integrateNativeReportNarrative(safeNativeHtml(reportHtml, title), reportTurn, visualReport.images);
|
||||
return compactNativeReportReading(appendAnalysisRecordReportHtml(withNarrative, result.recordList ?? reportTurn.recordList), reportTurn);
|
||||
}, [reportHtml, reportTurn, visualReport.images]);
|
||||
const showNative = Boolean(safeHtml);
|
||||
const filename = useMemo(() => {
|
||||
const result = Object.keys(record(reportTurn.result)).length ? record(reportTurn.result) : reportTurn;
|
||||
const period = buildAnalysisNarrative('', result.visuals || reportTurn.visuals).period;
|
||||
return reportDownloadName(period);
|
||||
}, [reportTurn]);
|
||||
useEffect(() => {
|
||||
exportGeneration.current += 1; setExporting(false); setProgress(''); setError(''); setPrepared(null); setPreparedHtml(null);
|
||||
if (preparedUrl.current) { URL.revokeObjectURL(preparedUrl.current); preparedUrl.current = ''; }
|
||||
if (preparedHtmlUrl.current) { URL.revokeObjectURL(preparedHtmlUrl.current); preparedHtmlUrl.current = ''; }
|
||||
return () => { exportGeneration.current += 1; if (preparedUrl.current) { URL.revokeObjectURL(preparedUrl.current); preparedUrl.current = ''; } if (preparedHtmlUrl.current) { URL.revokeObjectURL(preparedHtmlUrl.current); preparedHtmlUrl.current = ''; } };
|
||||
}, [open, turnId, snapshot, reportHtml, reportMarkdown]);
|
||||
useEffect(() => { setFrameReady(false); setFrameHeight(1); }, [safeHtml, showNative]);
|
||||
useEffect(() => () => frameToggleCleanup.current(), [safeHtml, open]);
|
||||
|
||||
const currentHtml = () => {
|
||||
if (showNative) {
|
||||
const doc = new DOMParser().parseFromString(safeHtml, 'text/html');
|
||||
return `<!doctype html>\n${doc.documentElement.outerHTML}`;
|
||||
}
|
||||
if (!node.current) throw new Error('报告尚未准备好,请稍后重试。');
|
||||
return reportHtmlFromElement(node.current);
|
||||
};
|
||||
const saveHtml = async () => {
|
||||
const html = safeHtml || `<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${escape(title)}</title><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:"></head><body>${fallbackNode.current?.innerHTML || ''}</body></html>`;
|
||||
if (!safeHtml && !fallbackNode.current) return;
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
const url = URL.createObjectURL(new Blob([html], { type: 'text/html;charset=utf-8' }));
|
||||
download(url, `${title}.html`);
|
||||
setTimeout(() => URL.revokeObjectURL(url), 10000);
|
||||
message.success(visualReport.failed ? 'HTML 已生成,未能绘制的图表已保留数据表。' : 'HTML 报告已生成');
|
||||
} catch (error) { if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '报告导出失败,请重试。'); }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
|
||||
const handleFrameLoad = () => {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) return;
|
||||
setFrameReady(false);
|
||||
void doc.fonts?.ready.then(() => requestAnimationFrame(() => {
|
||||
const height = frameContentHeight(doc);
|
||||
setFrameHeight(Math.max(height, 1));
|
||||
setFrameReady(true);
|
||||
}));
|
||||
};
|
||||
|
||||
const saveImage = async () => {
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true);
|
||||
setExporting(true); setError('');
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
let png: string;
|
||||
if (safeHtml) {
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) throw new Error('原生报告尚未载入');
|
||||
png = await captureReportImage(doc.body, { width: 900, pixelRatio: 1, fontEmbedCSS: frameFontCss(doc) });
|
||||
} else {
|
||||
const report = fallbackNode.current;
|
||||
if (!report) throw new Error('Markdown 报告尚未载入');
|
||||
png = await captureReportImage(report, { width: 900, pixelRatio: 1, skipFonts: true });
|
||||
}
|
||||
if (generation !== exportGeneration.current) return;
|
||||
download(png, `${title}.png`);
|
||||
message.success(visualReport.failed ? '报告图片已生成,未能绘制的图表已保留数据表。' : '报告图片已生成');
|
||||
} catch (error) {
|
||||
if (generation === exportGeneration.current) message.error(error instanceof Error ? error.message : '图片生成失败,请重试。');
|
||||
} finally {
|
||||
if (generation === exportGeneration.current) setExporting(false);
|
||||
}
|
||||
if (preparedHtmlUrl.current) URL.revokeObjectURL(preparedHtmlUrl.current);
|
||||
preparedHtmlUrl.current = URL.createObjectURL(new Blob([currentHtml()], { type: 'text/html;charset=utf-8' }));
|
||||
setPreparedHtml({ url: preparedHtmlUrl.current, name: `${filename}.html` });
|
||||
setProgress('HTML 已准备好。点击“下载 HTML”保存。');
|
||||
} catch (value) { if (generation === exportGeneration.current) setError(value instanceof Error ? value.message : '报告导出失败,请重试。'); }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
|
||||
const prepareImages = async () => {
|
||||
const generation = ++exportGeneration.current;
|
||||
setExporting(true); setError(''); setProgress('正在准备长图…');
|
||||
try {
|
||||
await visualReport.authorize();
|
||||
if (generation !== exportGeneration.current) return;
|
||||
const doc = showNative ? iframe.current?.contentDocument : null;
|
||||
const report = showNative ? doc?.body : node.current?.querySelector<HTMLElement>('.q-report');
|
||||
if (!report) throw new Error('报告尚未准备好,请稍后重试。');
|
||||
const blob = await captureReportLongImage(report, doc ? { fontEmbedCSS: frameFontCss(doc) } : { skipFonts: true },
|
||||
() => generation !== exportGeneration.current);
|
||||
if (generation !== exportGeneration.current) return;
|
||||
if (preparedUrl.current) URL.revokeObjectURL(preparedUrl.current);
|
||||
preparedUrl.current = URL.createObjectURL(blob);
|
||||
setPrepared({ url: preparedUrl.current, name: `${filename}.png` });
|
||||
setProgress('长图已准备好。点击“下载长图”保存。');
|
||||
} catch (value) { if (generation === exportGeneration.current) { setProgress(''); setError(value instanceof Error ? value.message : '图片生成失败,请重试或下载 HTML。'); } }
|
||||
finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
const downloadPrepared = async (file: { url: string; name: string }, kind: 'html' | 'image') => {
|
||||
const generation = ++exportGeneration.current;
|
||||
const expected = currentExport.current;
|
||||
const isCurrent = () => {
|
||||
const current = currentExport.current;
|
||||
return current.open && generation === exportGeneration.current
|
||||
&& current.turnId === expected.turnId && current.snapshot === expected.snapshot
|
||||
&& current.reportHtml === expected.reportHtml && current.reportMarkdown === expected.reportMarkdown
|
||||
&& (kind === 'html' ? preparedHtmlUrl.current : preparedUrl.current) === file.url;
|
||||
};
|
||||
setExporting(true); setError('');
|
||||
try {
|
||||
await downloadAuthorizedReport({
|
||||
authorize: visualReport.authorize,
|
||||
isCurrent,
|
||||
onDenied: value => {
|
||||
if (preparedUrl.current) URL.revokeObjectURL(preparedUrl.current);
|
||||
if (preparedHtmlUrl.current) URL.revokeObjectURL(preparedHtmlUrl.current);
|
||||
preparedUrl.current = ''; preparedHtmlUrl.current = '';
|
||||
setPrepared(null); setPreparedHtml(null); setProgress('');
|
||||
setError(value instanceof Error ? value.message : '无法验证此报告的访问权限,请重新打开分析。');
|
||||
},
|
||||
download: () => {
|
||||
const link = document.createElement('a');
|
||||
link.href = file.url; link.download = file.name;
|
||||
document.body.appendChild(link); link.click(); link.remove();
|
||||
},
|
||||
});
|
||||
} finally { if (generation === exportGeneration.current) setExporting(false); }
|
||||
};
|
||||
const handleFrameLoad = () => {
|
||||
frameToggleCleanup.current();
|
||||
const doc = iframe.current?.contentDocument;
|
||||
if (!doc?.body) return;
|
||||
const resize = () => requestAnimationFrame(() => { if (iframe.current?.contentDocument === doc) setFrameHeight(Math.max(frameContentHeight(doc), 1)); });
|
||||
doc.addEventListener('toggle', resize, true);
|
||||
frameToggleCleanup.current = () => doc.removeEventListener('toggle', resize, true);
|
||||
setFrameReady(false);
|
||||
void Promise.resolve(doc.fonts?.ready).then(() => requestAnimationFrame(() => {
|
||||
if (iframe.current?.contentDocument !== doc) return;
|
||||
setFrameHeight(Math.max(frameContentHeight(doc), 1)); setFrameReady(true);
|
||||
}));
|
||||
};
|
||||
const disabled = exporting || visualReport.loading || !visualReport.authorized || showNative && !frameReady;
|
||||
return <>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => setOpen(true)}>查看报告</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => setOpen(false)} width={980} footer={<>
|
||||
<Button disabled={exporting || visualReport.loading || !visualReport.authorized} onClick={() => void saveHtml()}>下载 HTML</Button>
|
||||
<Button type="primary" loading={exporting} disabled={visualReport.loading || !visualReport.authorized || Boolean(safeHtml) && !frameReady} onClick={() => void saveImage()}>下载图片</Button>
|
||||
<Button type="text" size="small" icon={<DownloadOutlined />} onClick={() => { setStamp(new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai', hour12: false })); setOpen(true); }}>{native ? '查看报告' : '生成报告'}</Button>
|
||||
<Modal title="分析报告" open={open} onCancel={() => { exportGeneration.current += 1; currentExport.current.open = false; setOpen(false); }} width={980} footer={<>
|
||||
{preparedHtml
|
||||
? <Button disabled={disabled} onClick={() => void downloadPrepared(preparedHtml, 'html')}>下载 HTML</Button>
|
||||
: <Button disabled={disabled} onClick={() => void saveHtml()}>下载 HTML</Button>}
|
||||
{prepared
|
||||
? <Button type="primary" disabled={disabled} onClick={() => void downloadPrepared(prepared, 'image')}>下载长图</Button>
|
||||
: <Button type="primary" loading={exporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||||
</>}>
|
||||
{visualReport.loading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||||
{progress && <p className="analysis-report-export-status" role="status" aria-live="polite">{progress}</p>}
|
||||
{error && <Alert className="analysis-report-export-error" type="error" showIcon title={error} closable onClose={() => setError('')} />}
|
||||
{visualReport.failed && <Alert type="warning" showIcon title="部分图表未生成,报告保留相应数据表。" />}
|
||||
{visualReport.authorizationError && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||
{visualReport.authorizationError && visualReport.authorizationError !== error && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||||
{visualReport.authorized && <div className="analysis-report-preview">
|
||||
{safeHtml
|
||||
? <iframe ref={iframe} className="native-analysis-report-frame" title="原生分析报告预览" sandbox="allow-same-origin" srcDoc={safeHtml} width={900} height={frameHeight} onLoad={handleFrameLoad} />
|
||||
: <article ref={fallbackNode}><ReportDocument turn={{ ...turn, reportMarkdown }} stamp="" visualImages={visualReport.images} /></article>}
|
||||
{showNative
|
||||
? <iframe ref={iframe} className="native-analysis-report-frame" title="分析报告预览" sandbox="allow-same-origin" srcDoc={safeHtml} width={900} height={frameHeight} onLoad={handleFrameLoad} />
|
||||
: <div ref={node}><ReportDocument turn={reportTurn} stamp={stamp} visualImages={visualReport.images} /></div>}
|
||||
</div>}
|
||||
</Modal>
|
||||
</>;
|
||||
}
|
||||
|
||||
export function AnalysisReportExport({ turn }: { turn: Row }) {
|
||||
return <ReportExportDialog turn={turn} />;
|
||||
}
|
||||
|
||||
export function NativeAnalysisReport({ turn, reportMarkdown, reportHtml }: {
|
||||
turn: Row; reportMarkdown: string; reportHtml?: string;
|
||||
}) {
|
||||
return <ReportExportDialog turn={turn} reportMarkdown={reportMarkdown} reportHtml={reportHtml} native />;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user