同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。 补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。 统一午夜黑及其他主题的控件细节、中文和业务数字字体。 排除本地业务数据、凭据、预览、发布与验收产物。 验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
395 lines
18 KiB
TypeScript
395 lines
18 KiB
TypeScript
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||
import { Button, Dropdown, Modal, Table, Tag } from 'antd';
|
||
import type { ColumnsType } from 'antd/es/table';
|
||
import { DownloadOutlined, MoreOutlined, TableOutlined } from '@ant-design/icons';
|
||
import {
|
||
buildAnalysisVisualOption,
|
||
formatVisualValue,
|
||
isVisualCellInvalid,
|
||
loadAnalysisVisualECharts,
|
||
parseAnalysisVisuals,
|
||
combineStageDefectVisuals,
|
||
renderVisualPng,
|
||
visualCategoryLabel,
|
||
visualPeriodSummary,
|
||
visualScopeSummary,
|
||
visualUnitLabel,
|
||
} from './analysisVisualsModel';
|
||
import type { AnalysisVisual } from './analysisVisualsModel';
|
||
import { analysisVisualCumulativeShares, analysisVisualShares, analysisVisualTypeLabel } from './analysisVisualPresentation';
|
||
import './analysis-visuals.css';
|
||
|
||
export interface AnalysisVisualsProps {
|
||
visuals: unknown;
|
||
visualState?: unknown;
|
||
beforeExport?: () => Promise<void>;
|
||
embedded?: boolean;
|
||
hideEvidence?: boolean;
|
||
combineStages?: boolean;
|
||
}
|
||
|
||
interface VisualTableRow {
|
||
key: string;
|
||
index: number;
|
||
label: string;
|
||
values: Array<number | null>;
|
||
}
|
||
|
||
function documentIsHidden(): boolean {
|
||
return document.visibilityState === 'hidden';
|
||
}
|
||
|
||
function visualTheme() {
|
||
const styles = getComputedStyle(document.documentElement);
|
||
return {
|
||
ink: styles.getPropertyValue('--ink').trim() || '#263c5a',
|
||
mutedInk: styles.getPropertyValue('--muted-ink').trim() || '#728198',
|
||
line: styles.getPropertyValue('--line').trim() || '#dfe5ef',
|
||
surface: styles.getPropertyValue('--surface').trim() || '#ffffff',
|
||
};
|
||
}
|
||
|
||
function visualStateName(value: unknown): string {
|
||
if (typeof value === 'string') return value;
|
||
if (typeof value === 'object' && value !== null) {
|
||
const record = value as Record<string, unknown>;
|
||
if (typeof record.status === 'string') return record.status;
|
||
if (typeof record.state === 'string') return record.state;
|
||
}
|
||
return '';
|
||
}
|
||
|
||
function ChartDataTable({ visual, compact = false }: { visual: AnalysisVisual; compact?: boolean }) {
|
||
const shares = analysisVisualShares(visual);
|
||
const cumulativeShares = analysisVisualCumulativeShares(visual);
|
||
const rows: VisualTableRow[] = visual.categories.map((category, index) => ({
|
||
key: category.key,
|
||
index: index + 1,
|
||
label: visualCategoryLabel(visual, index),
|
||
values: visual.series.map(series => series.values[index] ?? null),
|
||
}));
|
||
const columns: ColumnsType<VisualTableRow> = [
|
||
{ title: '序号', dataIndex: 'index', width: 68, align: 'center', fixed: 'left' },
|
||
{
|
||
title: '对象名称', dataIndex: 'label', width: 240, ellipsis: false, fixed: 'left',
|
||
render: (label: string, row) => <span className="analysis-visual-full-label" title={`${label}(${row.key})`}>{label}</span>,
|
||
},
|
||
...visual.series.map((series, seriesIndex) => ({
|
||
title: series.label,
|
||
key: series.key,
|
||
align: 'center' as const,
|
||
width: 150,
|
||
render: (_value: unknown, row: VisualTableRow) => {
|
||
const value = row.values[seriesIndex];
|
||
return isVisualCellInvalid(visual, seriesIndex, row.index - 1)
|
||
? <Tag color="error">无效值</Tag>
|
||
: <span className="analysis-visual-table-value">{formatVisualValue(value, visual.unit)}</span>;
|
||
},
|
||
})),
|
||
...(shares ? [{ title: visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '占已列类别合计', key: 'compositionShare', align: 'center' as const, width: 160,
|
||
render: (_value: unknown, row: VisualTableRow) => `${(shares[row.index - 1] * 100).toFixed(2)}%` }] : []),
|
||
...(cumulativeShares ? [{ title: visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占已列类别合计', key: 'cumulativeShare', align: 'center' as const, width: 170,
|
||
render: (_value: unknown, row: VisualTableRow) => `${(cumulativeShares[row.index - 1] * 100).toFixed(2)}%` }] : []),
|
||
];
|
||
return <div className={compact ? 'analysis-visual-table is-compact' : 'analysis-visual-table'}>
|
||
<Table<VisualTableRow>
|
||
size="small"
|
||
bordered
|
||
columns={columns}
|
||
dataSource={rows}
|
||
pagination={false}
|
||
rowKey="key"
|
||
scroll={{ x: 'max-content', y: compact ? 290 : 440 }}
|
||
/>
|
||
</div>;
|
||
}
|
||
|
||
function safeFilename(title: string): string {
|
||
const base = title.replace(/[\\/:*?"<>|\u0000-\u001f]/g, '-').replace(/\s+/g, '-').slice(0, 64) || 'analysis-chart';
|
||
return `${base}.png`;
|
||
}
|
||
|
||
function chartSummary(visual: AnalysisVisual): string {
|
||
return `${visual.title}。${visual.subtitle}。期间:${visualPeriodSummary(visual)}。${visual.categories.length} 个对象,${visual.series.map(item => item.label).join('、')}。${visualScopeSummary(visual.scope)}`;
|
||
}
|
||
|
||
export function AnalysisVisualCard({ visual, beforeExport, loadRuntime = loadAnalysisVisualECharts, hideEvidence = false }: {
|
||
visual: AnalysisVisual;
|
||
beforeExport?: () => Promise<void>;
|
||
loadRuntime?: typeof loadAnalysisVisualECharts;
|
||
hideEvidence?: boolean;
|
||
}) {
|
||
const cardRef = useRef<HTMLElement>(null);
|
||
const chartNodeRef = useRef<HTMLDivElement>(null);
|
||
const chartRef = useRef<Awaited<ReturnType<typeof loadAnalysisVisualECharts>> extends never ? never : import('echarts/core').ECharts | null>(null);
|
||
const exportControllerRef = useRef<AbortController | null>(null);
|
||
const [nearViewport, setNearViewport] = useState(false);
|
||
const [chartReady, setChartReady] = useState(false);
|
||
const [chartLoading, setChartLoading] = useState(false);
|
||
const [chartError, setChartError] = useState('');
|
||
const [dataOpen, setDataOpen] = useState(false);
|
||
const [exporting, setExporting] = useState(false);
|
||
const [exportError, setExportError] = useState('');
|
||
const [themeRevision, setThemeRevision] = useState(0);
|
||
const [renderAttempt, setRenderAttempt] = useState(0);
|
||
const [retrying, setRetrying] = useState(false);
|
||
const [accessBlocked, setAccessBlocked] = useState(false);
|
||
const retryGeneration = useRef(0);
|
||
const retryPending = useRef(false);
|
||
const visualIdentity = JSON.stringify(visual);
|
||
const currentIdentity = useRef(visualIdentity);
|
||
currentIdentity.current = visualIdentity;
|
||
|
||
useEffect(() => {
|
||
setAccessBlocked(false); setRetrying(false); retryPending.current = false;
|
||
setExportError(''); setChartError(''); setDataOpen(false);
|
||
exportControllerRef.current?.abort(); exportControllerRef.current = null; setExporting(false);
|
||
retryGeneration.current += 1;
|
||
return () => { retryGeneration.current += 1; retryPending.current = false; };
|
||
}, [visualIdentity]);
|
||
|
||
const retryChart = useCallback(async () => {
|
||
if (retryPending.current) return;
|
||
const generation = ++retryGeneration.current;
|
||
const identity = visualIdentity;
|
||
const current = () => generation === retryGeneration.current && identity === currentIdentity.current;
|
||
retryPending.current = true; setRetrying(true);
|
||
try {
|
||
if (!beforeExport) throw new Error('请重新打开这条分析后再重试图表。');
|
||
await beforeExport();
|
||
if (!current()) return;
|
||
setAccessBlocked(false); setExportError(''); setChartReady(false);
|
||
setRenderAttempt(value => value + 1);
|
||
} catch (error) {
|
||
if (current()) {
|
||
setAccessBlocked(true); setChartReady(false); setDataOpen(false);
|
||
setExportError(error instanceof Error ? error.message : '无法验证此图表的访问权限,请重新打开分析。');
|
||
}
|
||
} finally {
|
||
if (current()) { retryPending.current = false; setRetrying(false); }
|
||
}
|
||
}, [beforeExport, visualIdentity]);
|
||
|
||
useEffect(() => {
|
||
const node = cardRef.current;
|
||
if (!node) return;
|
||
if (typeof IntersectionObserver === 'undefined') { setNearViewport(true); return; }
|
||
const observer = new IntersectionObserver(entries => {
|
||
const entry = entries[0];
|
||
if (entry) setNearViewport(entry.isIntersecting);
|
||
}, { rootMargin: '180px 0px', threshold: 0.01 });
|
||
observer.observe(node);
|
||
return () => observer.disconnect();
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
if (!nearViewport || !visual.chartable || accessBlocked) return;
|
||
let cancelled = false;
|
||
let resizeObserver: ResizeObserver | null = null;
|
||
let instance: (Awaited<ReturnType<typeof loadAnalysisVisualECharts>>['init'] extends (...args: never[]) => infer T ? T : never) | undefined;
|
||
const mount = async () => {
|
||
const node = chartNodeRef.current;
|
||
if (!node || documentIsHidden() || cancelled) return;
|
||
setChartLoading(true);
|
||
setChartReady(false);
|
||
try {
|
||
const echarts = await loadRuntime();
|
||
if (cancelled || !chartNodeRef.current || documentIsHidden()) return;
|
||
instance = echarts.init(chartNodeRef.current, undefined, { renderer: 'svg' });
|
||
chartRef.current = instance;
|
||
// Initializing a cached/offscreen card must draw even when React batches
|
||
// loading=true/false into one commit and no option-effect dependency changes.
|
||
instance.setOption(buildAnalysisVisualOption(visual, visualTheme()), { notMerge: true, lazyUpdate: false });
|
||
const resize = () => {
|
||
const chartNode = chartNodeRef.current;
|
||
if (cancelled || documentIsHidden() || !chartNode) return;
|
||
const bounds = chartNode.getBoundingClientRect();
|
||
if (bounds.width > 0 && bounds.height > 0) instance?.resize();
|
||
};
|
||
resizeObserver = new ResizeObserver(resize);
|
||
resizeObserver.observe(chartNodeRef.current);
|
||
setChartError('');
|
||
setChartReady(true);
|
||
} catch {
|
||
instance?.dispose();
|
||
if (chartRef.current === instance) chartRef.current = null;
|
||
if (!cancelled) { setChartReady(false); setChartError('图表渲染暂不可用,可以继续查看完整数据表。'); }
|
||
} finally {
|
||
if (!cancelled) setChartLoading(false);
|
||
}
|
||
};
|
||
const onVisibility = () => {
|
||
if (!documentIsHidden()) {
|
||
if (!instance) void mount();
|
||
else requestAnimationFrame(() => instance?.resize());
|
||
}
|
||
};
|
||
document.addEventListener('visibilitychange', onVisibility);
|
||
void mount();
|
||
return () => {
|
||
cancelled = true;
|
||
document.removeEventListener('visibilitychange', onVisibility);
|
||
resizeObserver?.disconnect();
|
||
instance?.dispose();
|
||
if (chartRef.current === instance) chartRef.current = null;
|
||
};
|
||
}, [nearViewport, visual.chartable, visual.id, visualIdentity, renderAttempt, accessBlocked, loadRuntime]);
|
||
|
||
useEffect(() => {
|
||
if (!nearViewport || !visual.chartable) return;
|
||
const observer = new MutationObserver(() => setThemeRevision(value => value + 1));
|
||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||
return () => observer.disconnect();
|
||
}, [nearViewport, visual.chartable]);
|
||
|
||
useEffect(() => {
|
||
const chart = chartRef.current;
|
||
const node = chartNodeRef.current;
|
||
if (!chart || !node || !visual.chartable) return;
|
||
try {
|
||
chart.setOption(buildAnalysisVisualOption(visual, visualTheme()), { notMerge: true, lazyUpdate: false });
|
||
setChartReady(true);
|
||
} catch {
|
||
setChartError('图表渲染失败,可以继续查看完整数据表。');
|
||
setChartReady(false);
|
||
}
|
||
}, [visual, themeRevision, chartLoading]);
|
||
|
||
useEffect(() => () => { exportControllerRef.current?.abort(); }, []);
|
||
|
||
const openData = useCallback(async () => {
|
||
try { await beforeExport?.(); setDataOpen(true); setExportError(''); }
|
||
catch (error) { setExportError(error instanceof Error ? error.message : '无法读取当前图表数据。'); }
|
||
}, [beforeExport]);
|
||
const download = useCallback(async () => {
|
||
if (!visual.chartable || exporting) return;
|
||
const controller = new AbortController();
|
||
exportControllerRef.current?.abort();
|
||
exportControllerRef.current = controller;
|
||
setExporting(true);
|
||
setExportError('');
|
||
try {
|
||
await beforeExport?.();
|
||
const image = await renderVisualPng(visual, controller.signal);
|
||
if (controller.signal.aborted) return;
|
||
const link = document.createElement('a');
|
||
link.href = image;
|
||
link.download = safeFilename(visual.title);
|
||
link.click();
|
||
} catch (error) {
|
||
if (!controller.signal.aborted) setExportError(error instanceof Error ? error.message : '图表导出失败');
|
||
} finally {
|
||
if (exportControllerRef.current === controller) exportControllerRef.current = null;
|
||
if (!controller.signal.aborted) setExporting(false);
|
||
}
|
||
}, [beforeExport, exporting, visual]);
|
||
|
||
const period = visualPeriodSummary(visual);
|
||
const scope = visualScopeSummary(visual.scope);
|
||
const coverage = visual.coverage.truncated
|
||
? `本图展示 ${visual.coverage.returnedRows} / 共 ${visual.coverage.totalRows} 项`
|
||
: `共 ${visual.coverage.totalRows} 项`;
|
||
|
||
if (accessBlocked) return <article className="analysis-visual-card" ref={cardRef}>
|
||
<p role="alert">{exportError || '无法验证此图表的访问权限,已隐藏原数据。'}</p>
|
||
<Button size="small" loading={retrying} onClick={() => void retryChart()}>重试图表</Button>
|
||
</article>;
|
||
|
||
return <article className={`analysis-visual-card analysis-visual-type-${visual.type}`} ref={cardRef} aria-label={visual.title}>
|
||
<header className="analysis-visual-heading">
|
||
<div className="analysis-visual-heading-copy">
|
||
<h3>{visual.title}</h3>
|
||
<p>{visual.subtitle}</p>
|
||
<div className="analysis-visual-context">
|
||
<span className="analysis-visual-type-label">{analysisVisualTypeLabel(visual.type)}</span>
|
||
<span>{period}</span>
|
||
{scope && <span>{scope}</span>}
|
||
<span>{coverage}</span>
|
||
{visual.stage && <Tag color={visual.stage === 'black' ? 'blue' : 'cyan'}>{visual.stage === 'black' ? '黑片' : '亮片'}</Tag>}
|
||
</div>
|
||
</div>
|
||
<div className="analysis-visual-actions">
|
||
<Button size="small" icon={<TableOutlined />} onClick={openData}>查看数据</Button>
|
||
<Dropdown
|
||
trigger={['click']}
|
||
menu={{ items: [{ key: 'png', icon: <DownloadOutlined />, label: exporting ? '正在导出…' : '下载 PNG', disabled: !visual.chartable || exporting, onClick: () => { void download(); } }] }}
|
||
>
|
||
<Button size="small" aria-label="更多图表操作" icon={exporting ? <span className="analysis-visual-spinner" aria-hidden="true" /> : <MoreOutlined />} />
|
||
</Dropdown>
|
||
</div>
|
||
</header>
|
||
{visual.note && <p className="analysis-visual-note">{visual.note}</p>}
|
||
{visual.chartable ? <>
|
||
<div
|
||
className="analysis-visual-chart-wrap"
|
||
role={chartError ? 'group' : 'button'}
|
||
tabIndex={chartError ? -1 : 0}
|
||
aria-label={`${chartSummary(visual)}。按 Enter 或空格查看数据。`}
|
||
aria-busy={chartLoading}
|
||
style={visual.sectionKey === 'defect_combined' ? { height: Math.max(320, visual.categories.length * 38 + 48) } : undefined}
|
||
onClick={chartError ? undefined : openData}
|
||
onKeyDown={event => {
|
||
if (chartError) return;
|
||
if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); openData(); }
|
||
}}
|
||
>
|
||
<div className="analysis-visual-chart" ref={chartNodeRef} aria-hidden="true"
|
||
style={visual.type === 'heatmap' ? { minWidth: Math.max(380, visual.categories.length * 62 + 160) }
|
||
: visual.type === 'pareto' ? { minWidth: Math.max(600, visual.categories.length * 90 + 180) } : undefined} />
|
||
{!nearViewport && <div className="analysis-visual-placeholder">图表将在进入视口时加载</div>}
|
||
{nearViewport && chartLoading && <div className="analysis-visual-placeholder" role="status">正在加载图表…</div>}
|
||
{chartError && <div className="analysis-visual-chart-error" role="status">{chartError}
|
||
<Button size="small" loading={retrying || chartLoading} onKeyDown={event => event.stopPropagation()}
|
||
onClick={event => { event.stopPropagation(); void retryChart(); }}>重试图表</Button>
|
||
</div>}
|
||
{!chartLoading && !chartError && !chartReady && nearViewport && <div className="analysis-visual-placeholder">图表准备中…</div>}
|
||
</div>
|
||
{visual.type === 'heatmap' && <p className="analysis-visual-scroll-hint">可横向滑动查看各期,或查看完整数据。</p>}
|
||
{visual.type === 'pareto' && <p className="analysis-visual-scroll-hint">窄屏可横向滑动查看,或查看完整数据。</p>}
|
||
<p className="analysis-visual-summary">{chartSummary(visual)}</p>
|
||
{chartError && <ChartDataTable visual={visual} compact />}
|
||
</> : <>
|
||
<p className="analysis-visual-chart-error" role="status">{visual.chartIssue || '此图表暂以数据表显示'}</p>
|
||
<ChartDataTable visual={visual} compact />
|
||
</>}
|
||
{exportError && <p className="analysis-visual-export-error" role="alert">{exportError}</p>}
|
||
<Modal
|
||
className="analysis-visual-modal"
|
||
open={dataOpen}
|
||
title={visual.title}
|
||
onCancel={() => setDataOpen(false)}
|
||
footer={<Button onClick={() => setDataOpen(false)}>关闭</Button>}
|
||
width={920}
|
||
destroyOnHidden
|
||
>
|
||
<div className="analysis-visual-modal-context">
|
||
<span>{visual.subtitle}</span><span>期间:{period}</span>{scope && <span>范围:{scope}</span>}
|
||
<span>单位:{visualUnitLabel(visual)}</span>
|
||
</div>
|
||
<ChartDataTable visual={visual} />
|
||
{visual.note && <p className="analysis-visual-modal-note">{visual.note}</p>}
|
||
{!hideEvidence && visual.evidenceRefs.length > 0 && <div className="analysis-visual-evidence"><strong>证据引用</strong><ul>{visual.evidenceRefs.map(ref => <li key={ref}>{ref}</li>)}</ul></div>}
|
||
</Modal>
|
||
</article>;
|
||
}
|
||
|
||
/** A bad or old visual payload is confined to this module; it never interrupts the answer text. */
|
||
export function AnalysisVisuals({ visuals, visualState, beforeExport, embedded = false, hideEvidence = false, combineStages = true }: AnalysisVisualsProps) {
|
||
const parsed = useMemo(() => {
|
||
const result = parseAnalysisVisuals(visuals);
|
||
return { ...result, visuals: combineStages ? combineStageDefectVisuals(result.visuals) : result.visuals };
|
||
}, [visuals, combineStages]);
|
||
if (!parsed.visuals.length) {
|
||
const state = visualStateName(visualState);
|
||
if (state === 'building') return <div className="analysis-visual-state" role="status">图表整理中</div>;
|
||
if (state === 'failed' || state === 'unavailable') return <div className="analysis-visual-state" role="status">图表暂不可用,已保留分析结果。</div>;
|
||
return null;
|
||
}
|
||
return <section className={`analysis-visuals${embedded ? ' is-embedded' : ''}`} aria-label="分析图表">
|
||
{parsed.visuals.map(visual => <AnalysisVisualCard key={visual.id} visual={visual} beforeExport={beforeExport} hideEvidence={hideEvidence} />)}
|
||
</section>;
|
||
}
|
||
|
||
export { parseAnalysisVisuals };
|
||
export type { AnalysisVisual };
|