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(null); const latest = useRef({ items, stage, totalWeight, onDetail }); latest.current = { items, stage, totalWeight, onDetail }; const redraw = useRef<() => void>(() => undefined); const [colors, setColors] = useState([]); 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 | 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)}
重量:${weightText(item.weight)} kg
占比:${rateText(item.rate)}
废率:${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
占比 / %
{!hasShares &&
暂无可绘制的构成占比
} {items.map((item, index) => { if (window.getSelection()?.isCollapsed !== false) onDetail(); }}> )}
不良分类重量 / kg占比废率
{weightText(item.weight)}{rateText(item.rate)}{rateText(defectWeightRate(item.weight, totalWeight))}
; }