接入 DSH 专用运行时和对话界面,保留模型原始回答,支持会话分页、连续追问与显式报告。 补齐组合筛选、各维度 Top100、分组查询到排名图的转换,图表故障静默省略并基于保存数据自动恢复。 优化报告风格、图表顺序和表格换行,更新接入说明及构建输入。 验证:独立目录前后端构建通过;118 项 Java、102 项前端、102 项图表、14 项 DSH 应用和 13 项组合筛选检查通过。 仅提交相关源码、锁定依赖与测试;不包含凭据、会话、业务数据或本地产物。
379 lines
26 KiB
TypeScript
379 lines
26 KiB
TypeScript
import { useEffect, useMemo, useRef, useState } from 'react';
|
||
import { AnalysisMemberListReport } from './AnalysisMemberListReport';
|
||
import { Alert, Button, Modal } from 'antd';
|
||
import { DownloadOutlined } from '@ant-design/icons';
|
||
import { AnalysisLegacyResults } from './AnalysisLegacyResults';
|
||
import { AnalysisReportNarrative } from './AnalysisReportNarrative';
|
||
import { parseServerReadingSummary } from './analysisReadingModel';
|
||
import { buildAnalysisNarrative } from './analysisReportModel';
|
||
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 { AnalysisRecordListReport, appendAnalysisRecordReportHtml } from './AnalysisRecordList';
|
||
import { useDelayedIndicator } from './useDelayedBusy';
|
||
import { alignReportTableText } from './tableTextAlignment';
|
||
|
||
type Row = Record<string, unknown>;
|
||
const record = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||
const text = (value: unknown) => value === null || value === undefined || value === '' ? '—' : String(value);
|
||
const escape = (value: string) => value.replaceAll('&', '&').replaceAll('<', '<').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;max-width:100%;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}
|
||
@media screen and (max-width:600px){.q-report{padding:24px 18px}.q-report h1{font-size:22px}.q-report .ai-markdown-table-wrap,.q-report .analysis-focus-table-wrap{max-width:100%;overflow-x:auto!important;overflow-y:visible!important}.q-report .ai-markdown-table-wrap table,.q-report .analysis-focus-table-wrap table{min-width:796px}.q-report .q-kpis{flex-wrap:wrap}.q-report .q-kpi{min-width:140px}}
|
||
`;
|
||
|
||
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 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,
|
||
model.sections?.flatMap(section => section.visuals ?? [])[0]?.title);
|
||
const answer = sanitizeAnalysisDisplayText(stripDuplicateFirstMarkdownH1(sourceAnswer, title));
|
||
const recordListValue = result.recordList ?? turn.recordList;
|
||
return <div className="q-report">
|
||
<style>{reportCss}</style>
|
||
<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} mode="full" />
|
||
<AnalysisLegacyResults turn={turn} />
|
||
{recordListValue !== undefined && recordListValue !== null && <details className="q-report-appendix"><summary>附录:完整来源记录</summary><AnalysisRecordListReport value={recordListValue} /></details>}
|
||
<AnalysisMemberListReport value={result.memberList ?? turn.memberList} />
|
||
{!parseServerReadingSummary(turn) && <footer>数据来源:质量数据分析平台。指标沿用正式计算口径;现场原因以实际核查为准。</footer>}
|
||
</div>;
|
||
}
|
||
|
||
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 {
|
||
const walker = element.ownerDocument.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
||
const textNodes: Array<{ node: Text; start: number; end: number }> = [];
|
||
let node: Node | null;
|
||
let offset = 0;
|
||
while ((node = walker.nextNode())) {
|
||
const textNode = node as Text;
|
||
const start = offset;
|
||
offset += textNode.data.length;
|
||
textNodes.push({ node: textNode, start, end: offset });
|
||
}
|
||
|
||
const ranges = analysisDisplayTextRemovalRanges(textNodes.map(item => item.node.data).join(''));
|
||
for (const range of [...ranges].reverse()) {
|
||
for (const item of [...textNodes].reverse()) {
|
||
const overlapStart = Math.max(range.start, item.start);
|
||
const overlapEnd = Math.min(range.end, item.end);
|
||
if (overlapStart >= overlapEnd) continue;
|
||
const localStart = overlapStart - item.start;
|
||
const localEnd = overlapEnd - item.start;
|
||
item.node.data = item.node.data.slice(0, localStart) + item.node.data.slice(localEnd);
|
||
}
|
||
}
|
||
|
||
// Inline labels whose values were removed can otherwise leave empty bold/code wrappers.
|
||
element.querySelectorAll('strong,b,em,i,code,span').forEach(child => {
|
||
if (!child.textContent?.trim() && !child.querySelector('img,svg')) child.remove();
|
||
});
|
||
}
|
||
|
||
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 => {
|
||
const directive = (meta.getAttribute('http-equiv') || '').trim().toLowerCase();
|
||
if (directive === 'content-security-policy' || directive === 'refresh') meta.remove();
|
||
});
|
||
|
||
const safeRasterData = (value: string) => /^data:image\/(?:png|jpe?g|gif|webp);base64,/i.test(value.trim());
|
||
const safeFontData = (value: string) => /^data:(?:font\/(?:woff2?|ttf|otf)|application\/(?:font-woff|vnd\.ms-fontobject|x-font-(?:ttf|otf)));base64,/i.test(value.trim());
|
||
const safeCss = (value: string) => value
|
||
.replace(/@import\s+(?:url\([^)]*\)|[^;]+);?/gi, '')
|
||
.replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (whole, _quote: string, raw: string) => {
|
||
const url = String(raw).trim();
|
||
return url.startsWith('#') || safeRasterData(url) || safeFontData(url) ? whole : 'none';
|
||
});
|
||
|
||
parsed.querySelectorAll('*').forEach(element => {
|
||
for (const attribute of [...element.attributes]) {
|
||
const name = attribute.name.toLowerCase();
|
||
const value = sanitizeAnalysisDisplayText(attribute.value.trim());
|
||
const tagName = element.tagName.toLowerCase();
|
||
if (/^(?:data-)?(?:release[-_]?id|story[-_]?(?:id|slug|version)|version[-_]?(?:id|no|number))$/i.test(name)) {
|
||
element.removeAttribute(attribute.name);
|
||
continue;
|
||
}
|
||
const autoResource = ['src', 'srcset', 'poster'].includes(name)
|
||
|| (['href', 'xlink:href'].includes(name) && ['image', 'use', 'feimage'].includes(tagName));
|
||
const safeReference = value.startsWith('#') || (['src', 'href', 'xlink:href'].includes(name) && safeRasterData(value));
|
||
if (name.startsWith('on') || name === 'srcdoc' || /^(?:javascript\s*:|data\s*:\s*text\/html)/i.test(value) || (autoResource && !safeReference)) {
|
||
element.removeAttribute(attribute.name);
|
||
} else if (name === 'style') {
|
||
element.setAttribute(attribute.name, safeCss(value));
|
||
} else if (value !== attribute.value) {
|
||
element.setAttribute(attribute.name, value);
|
||
}
|
||
}
|
||
});
|
||
parsed.querySelectorAll('style').forEach(style => { style.textContent = safeCss(style.textContent || ''); });
|
||
parsed.querySelectorAll('meta[name],meta[property]').forEach(meta => {
|
||
const key = `${meta.getAttribute('name') || ''} ${meta.getAttribute('property') || ''}`;
|
||
if (/release|story|version/i.test(key)) meta.remove();
|
||
});
|
||
parsed.querySelectorAll('blockquote').forEach(element => {
|
||
if (/^v\d+(?:\.\d+)*\s*复核说明\s*[::]?/i.test(element.textContent?.trim() || '')) element.remove();
|
||
});
|
||
parsed.querySelectorAll('p,h1,h2,h3,h4,h5,h6,li,td,th,caption,figcaption,title').forEach(removeDisplayMetadataFromElement);
|
||
const walker = parsed.createTreeWalker(parsed.body, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT);
|
||
let node: Node | null;
|
||
while ((node = walker.nextNode())) {
|
||
if (node.nodeType === Node.COMMENT_NODE) node.parentNode?.removeChild(node);
|
||
else if (node.nodeValue) node.nodeValue = sanitizeAnalysisDisplayText(node.nodeValue);
|
||
}
|
||
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');
|
||
policy.setAttribute('content', "default-src 'none'; script-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; media-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'");
|
||
parsed.head.prepend(policy);
|
||
const exportStyle = parsed.createElement('style');
|
||
exportStyle.setAttribute('data-report-export-layout', '');
|
||
exportStyle.textContent = 'html,body{box-sizing:border-box;width:900px!important;min-width:900px!important;max-width:900px!important;margin:0!important;overflow-wrap:anywhere}*,*:before,*:after{box-sizing:border-box}';
|
||
parsed.head.append(exportStyle);
|
||
alignReportTableText(parsed);
|
||
return `<!doctype html>\n${parsed.documentElement.outerHTML}`;
|
||
}
|
||
|
||
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,
|
||
doc.body.getBoundingClientRect().height,
|
||
doc.documentElement.scrollHeight,
|
||
doc.documentElement.offsetHeight,
|
||
doc.documentElement.getBoundingClientRect().height,
|
||
));
|
||
}
|
||
|
||
function frameFontCss(doc: Document): string {
|
||
const fontRules: string[] = [];
|
||
const collect = (rules: CSSRuleList) => {
|
||
for (const rule of Array.from(rules)) {
|
||
if (rule.type === CSSRule.FONT_FACE_RULE) fontRules.push(rule.cssText);
|
||
const nested = (rule as CSSGroupingRule).cssRules;
|
||
if (nested) collect(nested);
|
||
}
|
||
};
|
||
for (const sheet of Array.from(doc.styleSheets)) {
|
||
try { collect(sheet.cssRules); } catch { /* External style sheets are removed before rendering. */ }
|
||
}
|
||
return fontRules.join('\n');
|
||
}
|
||
|
||
function ReportExportDialog({ turn, reportMarkdown, reportHtml, native = false }: {
|
||
turn: Row; reportMarkdown?: string; reportHtml?: string; native?: boolean;
|
||
}) {
|
||
const [open, setOpen] = useState(false);
|
||
const [exporting, setExporting] = useState(false);
|
||
const showExporting = useDelayedIndicator(exporting, 150);
|
||
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);
|
||
const node = useRef<HTMLDivElement>(null);
|
||
const iframe = useRef<HTMLIFrameElement>(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 showVisualLoading = useDelayedIndicator(visualReport.loading, 150);
|
||
const safeHtml = useMemo(() => {
|
||
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), metadata.sections?.flatMap(section => section.visuals ?? [])[0]?.title);
|
||
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 generation = ++exportGeneration.current;
|
||
setExporting(true); setError('');
|
||
try {
|
||
await visualReport.authorize();
|
||
if (generation !== exportGeneration.current) return;
|
||
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={() => { 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={showExporting} disabled={disabled} onClick={() => void prepareImages()}>下载长图</Button>}
|
||
</>}>
|
||
{showVisualLoading && <p role="status">{visualReport.progress || '正在准备报告图表…'}</p>}
|
||
{progress && (!exporting || showExporting) && <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 && visualReport.authorizationError !== error && <Alert type="error" showIcon title={visualReport.authorizationError} />}
|
||
{visualReport.authorized && <div className="analysis-report-preview">
|
||
{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 />;
|
||
}
|