同步:补齐已发布的查询面板与不良构成源码
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart } from 'echarts/charts';
|
||||
import { GridComponent, TooltipComponent } from 'echarts/components';
|
||||
import { SVGRenderer } from 'echarts/renderers';
|
||||
import type { DefectMetric, Stage } from './types';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import './defect-composition.css';
|
||||
|
||||
echarts.use([BarChart, GridComponent, TooltipComponent, SVGRenderer]);
|
||||
const weightText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) : '—';
|
||||
const rateText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]!));
|
||||
|
||||
function categoryColors(color: string, surface: string, count: number): string[] {
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const mix = index === 0 ? 0 : Math.min(.8, .3 + (index - 1) * .25);
|
||||
return `#${[1, 3, 5].map(offset => Math.round(parseInt(color.slice(offset, offset + 2), 16) * (1 - mix) + parseInt(surface.slice(offset, offset + 2), 16) * mix).toString(16).padStart(2, '0')).join('')}`;
|
||||
});
|
||||
}
|
||||
|
||||
export default function DefectComposition({ items, stage, totalWeight, onDetail }: {
|
||||
items: DefectMetric[];
|
||||
stage: Stage;
|
||||
totalWeight?: number | null;
|
||||
onDetail: () => void;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const latest = useRef({ items, stage, totalWeight, onDetail });
|
||||
latest.current = { items, stage, totalWeight, onDetail };
|
||||
const redraw = useRef<() => void>(() => undefined);
|
||||
const [colors, setColors] = useState<string[]>([]);
|
||||
const hasShares = items.some(item => typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate > 0 && item.rate <= 1);
|
||||
|
||||
useEffect(() => {
|
||||
const node = container.current;
|
||||
if (!node) return;
|
||||
let chart: ReturnType<typeof echarts.init> | undefined;
|
||||
redraw.current = () => {
|
||||
if (!node.clientWidth) return;
|
||||
const current = latest.current;
|
||||
const css = getComputedStyle(node);
|
||||
const ink = css.getPropertyValue('--ink').trim() || '#222C3C';
|
||||
const muted = css.getPropertyValue('--muted-ink').trim() || '#637187';
|
||||
const line = css.getPropertyValue('--line').trim() || '#DCE2EC';
|
||||
const surface = css.getPropertyValue('--surface').trim() || '#FFFFFF';
|
||||
const color = css.getPropertyValue(current.stage === 'black' ? '--defect-black' : '--defect-bright').trim() || (current.stage === 'black' ? '#718797' : '#607AE1');
|
||||
const palette = categoryColors(color, surface, current.items.length);
|
||||
if (current.stage === 'black' && document.documentElement.dataset.workspaceTheme !== 'dark') {
|
||||
// Match the selected blue-gray swatches; keep the existing dark-theme contrast treatment.
|
||||
for (const index of [1, 2]) {
|
||||
const tone = css.getPropertyValue(`--defect-black-${index + 1}`).trim();
|
||||
if (tone && index < palette.length) palette[index] = tone;
|
||||
}
|
||||
}
|
||||
setColors(old => old.join() === palette.join() ? old : palette);
|
||||
const fontFamily = css.getPropertyValue('--font-ui').trim() || css.fontFamily;
|
||||
const numericFamily = css.getPropertyValue('--font-numeric').trim() || 'Arial';
|
||||
const stageName = current.stage === 'black' ? '黑片' : '亮片';
|
||||
if (!chart) {
|
||||
chart = echarts.init(node, undefined, { renderer: 'svg' });
|
||||
chart.on('click', () => latest.current.onDetail());
|
||||
}
|
||||
const option: echarts.EChartsCoreOption = {
|
||||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
animationDuration: 420,
|
||||
animationDurationUpdate: 520,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
grid: { top: 8, left: 20, right: 20, bottom: 28 },
|
||||
tooltip: {
|
||||
trigger: 'item', backgroundColor: surface, borderColor: line,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
formatter: (raw: unknown) => {
|
||||
const item = current.items[(raw as { seriesIndex: number }).seriesIndex];
|
||||
return item ? `${stageName} · ${escape(item.name)}<br/>重量:${weightText(item.weight)} kg<br/>占比:${rateText(item.rate)}<br/>废率:${rateText(defectWeightRate(item.weight, current.totalWeight))}` : '';
|
||||
},
|
||||
},
|
||||
xAxis: { type: 'value', min: 0, max: 100, interval: 25, axisLine: { show: true, lineStyle: { color: line } }, axisTick: { show: false }, splitLine: { show: false }, axisLabel: { fontFamily: numericFamily, fontSize: 11, color: muted, formatter: '{value}%' } },
|
||||
yAxis: { type: 'category', data: [''], show: false },
|
||||
series: current.items.map((item, index) => ({
|
||||
id: `composition-${current.stage}-${item.name}`, name: item.name, type: 'bar', stack: 'composition', barWidth: 28,
|
||||
data: [typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate >= 0 && item.rate <= 1 ? item.rate * 100 : null],
|
||||
itemStyle: { color: palette[index] },
|
||||
label: { show: typeof item.rate === 'number' && item.rate >= .15, position: 'inside', formatter: rateText(item.rate), color: index === 0 && document.documentElement.dataset.workspaceTheme !== 'dark' ? '#FFFFFF' : ink, fontFamily: numericFamily, fontSize: 13, fontWeight: 600 },
|
||||
emphasis: { itemStyle: { opacity: .85 } },
|
||||
})),
|
||||
};
|
||||
chart.setOption(option, { replaceMerge: ['series'] });
|
||||
};
|
||||
redraw.current();
|
||||
const resize = new ResizeObserver(() => {
|
||||
const { clientWidth: width, clientHeight: height } = node;
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (chart) chart.resize({ width, height, animation: { duration: 0 } }); else redraw.current();
|
||||
});
|
||||
resize.observe(node);
|
||||
const theme = new MutationObserver(() => redraw.current());
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||||
return () => { resize.disconnect(); theme.disconnect(); chart?.dispose(); redraw.current = () => undefined; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => { redraw.current(); }, [items, stage, totalWeight]);
|
||||
|
||||
return <div className="defect-composition">
|
||||
<div className="defect-composition-unit">占比 / %</div>
|
||||
<div className="defect-composition-plot" ref={container} role="img" aria-label={`${stage === 'black' ? '黑片' : '亮片'}分类报废占比,详细数值见下方表格`} style={{ visibility: hasShares ? undefined : 'hidden' }} />
|
||||
{!hasShares && <div className="defect-composition-empty">暂无可绘制的构成占比</div>}
|
||||
<table className="defect-composition-table"><thead><tr><th scope="col">不良分类</th><th scope="col">重量 / kg</th><th scope="col">占比</th><th scope="col">废率</th></tr></thead><tbody>
|
||||
{items.map((item, index) => <tr key={item.name} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDetail(); }}>
|
||||
<td><button type="button" className="defect-composition-category" aria-label={`查看${stage === 'black' ? '黑片' : '亮片'}${item.name}来源明细`}><i aria-hidden="true" style={{ backgroundColor: colors[index] }} />{item.name}</button></td>
|
||||
<td className="defect-composition-weight">{weightText(item.weight)}</td><td>{rateText(item.rate)}</td><td>{rateText(defectWeightRate(item.weight, totalWeight))}</td>
|
||||
</tr>)}
|
||||
</tbody></table>
|
||||
</div>;
|
||||
}
|
||||
Reference in New Issue
Block a user