diff --git a/web/src/DefectComposition.tsx b/web/src/DefectComposition.tsx new file mode 100644 index 0000000..971da3e --- /dev/null +++ b/web/src/DefectComposition.tsx @@ -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(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))}
+
; +} diff --git a/web/src/QualityWorkspace.tsx b/web/src/QualityWorkspace.tsx index 217485e..5197b2b 100644 --- a/web/src/QualityWorkspace.tsx +++ b/web/src/QualityWorkspace.tsx @@ -17,7 +17,6 @@ import { CheckOutlined, DatabaseOutlined, DownOutlined, - DeploymentUnitOutlined, KeyOutlined, LineChartOutlined, LoadingOutlined, @@ -67,7 +66,6 @@ const navGroups = [ items: [ ['overall', '总体合格率', AppstoreOutlined], ['department', '产业部', ApartmentOutlined], - ['group', '产业部-业务分组', DeploymentUnitOutlined], ['product', '产品汇总', DatabaseOutlined], ['blackProduct', '黑片汇总', DatabaseOutlined], ['brightProduct', '亮片汇总', DatabaseOutlined], diff --git a/web/src/QueryPage.tsx b/web/src/QueryPage.tsx index fbbee76..14756ec 100644 --- a/web/src/QueryPage.tsx +++ b/web/src/QueryPage.tsx @@ -47,6 +47,9 @@ import { readableSelectPopup } from './readableSelectPopup'; import { isInternalDataField, readableMetricFormula } from './publicDataDisplay'; import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults'; import { defectWeightRate } from './trendMetrics'; +import DefectComposition from './DefectComposition'; +import { QueryTrendPanel, QueryTablePanel } from './QueryPanels'; +import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection'; import './query-motion.css'; import { ExtraQueryFilters } from './ExtraQueryFilters'; import { freezeSourceRecordsQuery } from './sourceRecordsContext'; @@ -299,10 +302,10 @@ export default function QueryPage({ page, onUnauthorized }: { const [options, setOptions] = useState(null); const [optionsError, setOptionsError] = useState(''); const [optionsLoading, setOptionsLoading] = useState(true); - const automaticPeriod = useRef(!initialQuery.year && !initialQuery.month && !initialQuery.quarter); + const automaticPeriod = useRef(page !== 'overall' && !initialQuery.year && !initialQuery.month && !initialQuery.quarter); const defaultMonth = previousCompleteMonth(); const defaultQuarter = previousCompleteQuarter(); - const [period, setPeriod] = useState(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year ? 'year' : 'month'); + const [period, setPeriod] = useState(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year || page === 'overall' ? 'year' : 'month'); const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear())); const [month, setMonth] = useState(initialQuery.month || defaultMonth.month); const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter); @@ -599,35 +602,9 @@ export default function QueryPage({ page, onUnauthorized }: { }, []); const selectTrendPeriod = useCallback((value: number | string) => { automaticPeriod.current = false; - const raw = String(value); - const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/); - const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/); - const yearMatch = raw.match(/^(\d{4})$/); - if (quarterMatch) { - if (period === 'quarter' && year === Number(quarterMatch[1]) && quarter === Number(quarterMatch[2])) { - captureTrendAnchor(); setPeriod('year'); return; - } - if (period !== 'quarter' || year !== Number(quarterMatch[1]) || quarter !== Number(quarterMatch[2])) captureTrendAnchor(); - setYear(Number(quarterMatch[1])); setQuarter(Number(quarterMatch[2])); setPeriod('quarter'); - } else if (yearMonth) { - if (period === 'month' && year === Number(yearMonth[1]) && month === Number(yearMonth[2])) { - captureTrendAnchor(); setPeriod('year'); return; - } - if (period !== 'month' || year !== Number(yearMonth[1]) || month !== Number(yearMonth[2])) captureTrendAnchor(); - setYear(Number(yearMonth[1])); setMonth(Number(yearMonth[2])); setPeriod('month'); - } else if (yearMatch) { - if (period !== 'year' || year !== Number(yearMatch[1])) captureTrendAnchor(); - setYear(Number(yearMatch[1])); setPeriod('year'); - } else { - const selected = monthNumber(value); - if (selected) { - if (period === 'month' && month === selected) { - captureTrendAnchor(); setPeriod('year'); return; - } - if (period !== 'month' || month !== selected) captureTrendAnchor(); - setPeriod('month'); setMonth(selected); - } - } + const next = nextTrendPeriod(value, { period, year, month, quarter }); + if (next.period !== period || next.year !== year || next.month !== month || next.quarter !== quarter) captureTrendAnchor(); + setYear(next.year); setMonth(next.month); setQuarter(next.quarter); setPeriod(next.period); }, [period, year, month, quarter, captureTrendAnchor]); useLayoutEffect(() => { @@ -770,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: {
{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'} - +
{organizationSummary.length > 0 &&
组织路径 @@ -794,18 +771,11 @@ export default function QueryPage({ page, onUnauthorized }: { <>
-
-
- - setTrendMode(value as typeof trendMode)} aria-label="趋势视图" /> -
-
- {trendMode==='data'&&setDefectDisplay(value as typeof defectDisplay)} aria-label="趋势不良显示方式"/>} - - {trendMode !== 'data' && setTrendStage(value as Stage)} aria-label="趋势阶段" />} -
+ setTrendStage(value as Stage)} aria-label="趋势阶段" />}> {currentTrendError && setQueryRevision(value => value + 1)}>重试} />}
{trendMode === 'data' @@ -813,29 +783,22 @@ export default function QueryPage({ page, onUnauthorized }: { : } {trendRefreshing && 正在更新趋势}
-
+ -
-
- -
- {(queryBusy || !tableReady) && 正在更新} - } placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} /> - - setFullFields(value === 'full')} aria-label="字段显示" /> - setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" /> - {!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && } - {drilledProduct && } - } + {drilledProduct && }} + exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} + onExport={async () => { setSummaryExporting(true); try { await summaryExport.current?.exportExcel(); } catch (error) { message.error(`导出失败:${chooseError(error)}`); } finally { setSummaryExporting(false); } - }}>Excel导出 -
-
-
横向滑动查看完整指标
+ }}> -
+
@@ -937,23 +900,15 @@ export function MetricCard({ primary, label, value, note, stage, onClick }: { pr ; } -export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) { - return
-
不良分类
- {items.map(item => )} -
; +export function DefectBreakdown({ items, stage, totalWeight, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) { + return ; } export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage, refreshKey = 0, pending = false }: { releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage; refreshKey?: number; pending?: boolean; }) { + const { active } = usePageCache(); const container = useRef(null); const chart = useRef | null>(null); const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse; externalScrapWeight?: number | null } | null>(null); @@ -1005,13 +960,18 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna useEffect(() => { const node = container.current; - if (!node) return; - const instance = echarts.init(node, undefined, { renderer: 'svg' }); + if (!node || !active) return; + const instance = echarts.init(node, undefined, { renderer: 'svg', width: node.clientWidth, height: node.clientHeight }); chart.current = instance; - const observer = new ResizeObserver(() => instance.resize()); + const observer = new ResizeObserver(() => { + const { clientWidth: width, clientHeight: height } = node; + if (width > 0 && height > 0 && (width !== instance.getWidth() || height !== instance.getHeight())) { + instance.resize({ width, height, animation: { duration: 0 } }); + } + }); observer.observe(node); return () => { observer.disconnect(); instance.dispose(); if (chart.current === instance) chart.current = null; }; - }, []); + }, [active]); const items = useMemo(() => { if (!responses) return []; @@ -1039,8 +999,8 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna const styles = getComputedStyle(container.current); const ink = styles.getPropertyValue('--ink').trim() || '#222222'; const line = styles.getPropertyValue('--line').trim() || '#dfe5ef'; - const blue = styles.getPropertyValue('--blue').trim() || '#607ae1'; - const teal = styles.getPropertyValue('--teal').trim() || '#008f7d'; + const black = styles.getPropertyValue('--defect-black').trim() || '#718797'; + const bright = styles.getPropertyValue('--defect-bright').trim() || '#607AE1'; const surface = styles.getPropertyValue('--surface').trim() || '#ffffff'; let accumulated = 0; const cumulative = items.map(item => { @@ -1081,12 +1041,12 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna { type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize }, axisLabel: { color: ink, fontFamily: numericFamily, fontSize, formatter: '{value}%' }, splitLine: { show: false } }, ], series: [ - { id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) }, + { id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, itemStyle: { color: onlyStage === 'black' ? black : bright }, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? black : bright } })) }, { id: 'pareto-cumulative', name: '累计占比', type: 'line', z: 10, yAxisIndex: 1, symbol: 'circle', symbolSize: 5, lineStyle: { width: 2, color: '#d58c35' }, itemStyle: { color: '#d58c35', borderColor: surface, borderWidth: 1 }, data: cumulative.map((value, index) => ({ id: items[index].key, name: items[index].label, value })) }, ], }; instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false }); - }, [items, totalWeight, themeRevision]); + }, [items, totalWeight, themeRevision, active]); return
{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}{loading && 正在更新}
@@ -1219,6 +1179,7 @@ function trendBarWidth(chartWidth: number, count: number): number { } export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) { + const { active } = usePageCache(); const container = useRef(null); const chart = useRef | null>(null); const onMonthRef = useRef(onMonth); @@ -1267,10 +1228,12 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP }, []); useEffect(() => { - if (!container.current || !hasRows) return; - const instance = echarts.init(container.current, undefined, { renderer: 'svg' }); + if (!container.current || !hasRows || !active) return; + const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight }); chart.current = instance; graphicIds.current.clear(); + selectionReady.current = false; + setBarMasks([]); instance.on('click', params => { if (params.componentType !== 'series' && params.componentType !== 'xAxis') return; const currentRows = rowsRef.current; @@ -1285,8 +1248,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP const observer = new ResizeObserver(() => { if (!container.current) return; const { clientWidth, clientHeight } = container.current; + if (clientWidth <= 0 || clientHeight <= 0) return; if (clientWidth !== instance.getWidth() || clientHeight !== instance.getHeight()) { - instance.resize(); + instance.resize({ width: clientWidth, height: clientHeight, animation: { duration: 0 } }); if (modeRef.current === 'production') { const barWidth = trendBarWidth(instance.getWidth(), rowsRef.current.length); instance.setOption({ series: [{ id: 'qualified-weight', barWidth }, { id: 'scrap-weight', barWidth }] }); @@ -1296,7 +1260,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP }); observer.observe(container.current); return () => { observer.disconnect(); instance.dispose(); chart.current = null; }; - }, [hasRows, refreshBarMasks]); + }, [hasRows, refreshBarMasks, active]); useEffect(() => { const instance = chart.current; @@ -1308,6 +1272,8 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP const bars = trendBarPalette(getWorkspaceTheme(document.documentElement.dataset.workspaceTheme).id); const barColor = bars.qualified; const teal = css.getPropertyValue('--teal').trim() || '#008f7d'; + const blackLine = css.getPropertyValue('--defect-black').trim() || '#718797'; + const brightLine = css.getPropertyValue('--defect-bright').trim() || blue; const line = css.getPropertyValue('--line').trim() || '#dfe5ef'; const surface = css.getPropertyValue('--surface').trim() || '#ffffff'; const labels = rows.map(row => row.periodLabel || String(row.month)); @@ -1329,7 +1295,8 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP }; const base: echarts.EChartsCoreOption = { animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches, - animationDuration: 0, + animationDuration: 520, + animationEasing: 'cubicOut', animationDurationUpdate: 520, animationEasingUpdate: 'cubicOut', textStyle: { fontFamily, color: ink, fontSize }, @@ -1346,6 +1313,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP const maxRate = rates.length ? Math.max(100, Math.ceil(Math.max(...rates) + 1)) : 100; const stageName = stage === 'black' ? '黑片' : '亮片'; const barWidth = trendBarWidth(instance.getWidth(), rows.length); + const ratePoints = { ...pointStyle, symbol: 'emptyCircle', symbolSize: 6 }; const targetLine = targetRate == null ? {} : { markLine: { silent: true, symbol: 'none', @@ -1362,9 +1330,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP series: [ { id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: bars.hoverQualified } }, data: barData('qualifiedWeight') }, { id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: bars.scrap }, emphasis: { itemStyle: { color: bars.hoverScrap } }, data: barData('scrapWeight') }, - { id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...pointStyle, ...targetLine, lineStyle: { width: 2.5, color: blue }, itemStyle: { color: blue, borderColor: surface, borderWidth: 1.5 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) }, - { id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: '#9278bf' }, itemStyle: { color: '#9278bf', borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) }, - { id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: teal }, itemStyle: { color: teal, borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) }, + { id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...ratePoints, ...targetLine, symbolSize: 7, emphasis: { ...pointStyle.emphasis, scale: 1.15 }, lineStyle: { width: 3.2, color: teal, cap: 'round', join: 'round' }, itemStyle: { color: teal, borderColor: teal, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) }, + { id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: blackLine, cap: 'round', join: 'round' }, itemStyle: { color: blackLine, borderColor: blackLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) }, + { id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: brightLine, cap: 'round', join: 'round' }, itemStyle: { color: brightLine, borderColor: brightLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) }, ], }; } else { @@ -1382,7 +1350,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP } instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false }); refreshBarMasks(); - }, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod]); + }, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active]); const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod; @@ -1426,7 +1394,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
; } -function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight' }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate' }) { +export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage }) { const compact = useCompactTable(); const columns: ColumnsType = [ { title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => }, @@ -1440,7 +1408,8 @@ function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight' }: { ro { title: rateBasisTitle('亮片合格率', rateBasis, 'bright'), dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: rateBasis === 'original' ? 180 : 194, className: 'rate-cell bright', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) }, { title: rateBasisTitle('综合合格率', rateBasis, 'composite'), dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 120, fixed: compact ? undefined : 'right', className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) }, ]; - return rows.length ?
String(row.month)} pagination={false} scroll={{ x: columns.reduce((total, column) => total + Number(column.width || 0), 0) }} /> + const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns; + return rows.length ?
String(row.month)} pagination={false} scroll={{ x: visibleColumns.reduce((total, column) => total + Number(column.width || 0), 0) }} /> : ; } diff --git a/web/src/QueryPanels.tsx b/web/src/QueryPanels.tsx new file mode 100644 index 0000000..549d21f --- /dev/null +++ b/web/src/QueryPanels.tsx @@ -0,0 +1,55 @@ +import type { ReactNode, Ref } from 'react'; +import { Button, Input, Segmented, Select, Spin } from 'antd'; +import { DownloadOutlined, SearchOutlined } from '@ant-design/icons'; +import { readableSelectPopup } from './readableSelectPopup'; + +type Granularity = 'month' | 'quarter' | 'year'; +type TrendMode = 'production' | 'defects' | 'data'; +type DefectDisplay = 'weight' | 'rate'; + +export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGranularity, defectDisplay, onDefectDisplay, object, onObject, objects, scopeName, stageSwitch, children }: { + panelRef?: Ref; id?: string; mode: TrendMode; onMode: (value: TrendMode) => void; + granularity: Granularity; onGranularity: (value: Granularity) => void; + defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void; + object?: string; onObject: (value?: string) => void; objects: Array<{ label: string; value: string }>; + scopeName: string; stageSwitch?: ReactNode; children: ReactNode; +}) { + const periodName = granularity === 'month' ? '月度' : granularity === 'quarter' ? '季度' : '年度'; + return
+
+

{periodName}变化趋势

+ +
+
+ {mode === 'data' && } + + {mode !== 'data' && stageSwitch} +
+ {children} +
; +} + +export function QueryTablePanel({ heading, busy, search, onSearchChange, onSearch, productView = true, searchPlaceholder, searchDisabled = false, searchUnavailable = false, fullFields, onFullFields, defectDisplay, onDefectDisplay, returnControls, exporting, exportDisabled, onExport, children }: { + heading: ReactNode; busy?: boolean; search: string; onSearchChange: (value: string) => void; onSearch: () => void; + productView?: boolean; searchPlaceholder?: string; searchDisabled?: boolean; searchUnavailable?: boolean; + fullFields: boolean; onFullFields: (value: boolean) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void; + returnControls?: ReactNode; exporting: boolean; exportDisabled: boolean; onExport: () => void; children: ReactNode; +}) { + return
+
+ {heading} +
+ {busy && 正在更新} + } placeholder={searchPlaceholder || (productView ? '输入关键词或完整产品名称' : '搜索汇总对象')} value={search} onChange={event => onSearchChange(event.target.value)} onPressEnter={onSearch} aria-label={productView ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} /> + + onFullFields(value === 'full')} aria-label="字段显示" /> + + {returnControls} + +
+
+
横向滑动查看完整指标
+ {children} +
; +} diff --git a/web/src/StageProductPage.tsx b/web/src/StageProductPage.tsx index b78b99d..aaa71f4 100644 --- a/web/src/StageProductPage.tsx +++ b/web/src/StageProductPage.tsx @@ -1,10 +1,10 @@ import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion'; import { queryScrapWeight } from './queryMetricValues'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; -import { Alert, App, Button, Empty, Input, Modal, Segmented, Select, Spin } from 'antd'; -import { DownOutlined, DownloadOutlined, UpOutlined } from '@ant-design/icons'; +import { Alert, App, Button, Empty, Modal, Segmented, Select, Spin } from 'antd'; +import { ArrowLeftOutlined, DownOutlined, UpOutlined } from '@ant-design/icons'; import { api, decodeQueryValueList, encodeQueryValueList } from './api'; -import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage'; +import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, TrendTable, fullYearTrend, queryFromLocation } from './QueryPage'; import { StageSourceFilters } from './StageSourceFilters'; import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery'; import { usePageCache } from './pageCache'; @@ -12,6 +12,8 @@ import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } fro import { readableSelectPopup } from './readableSelectPopup'; import { readableMetricFormula } from './publicDataDisplay'; import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types'; +import { QueryTrendPanel, QueryTablePanel } from './QueryPanels'; +import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection'; import './stage-product.css'; const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—'; @@ -29,6 +31,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU const [applied,setApplied]=useState(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null); const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight'); const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production'); + const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef(''); const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month'); const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false); const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise}>(null);const [exporting,setExporting]=useState(false); @@ -41,7 +44,10 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU },[onUnauthorized]); useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]); const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]); - const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(product),projectGroup:encodeQueryValueList(projectGroup),productSearch:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,product,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]); + const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]); + const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]); + useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters]); + const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]); // Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit. useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]); const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:''; @@ -59,20 +65,27 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU const selectedTrendPeriod=trendGranularity==='month'&&applied?.month ? `${applied.year}-${String(applied.month).padStart(2,'0')}` : trendGranularity==='quarter'&&applied?.quarter ? `${applied.year}-Q${applied.quarter}` : undefined; - const selectTrendPeriod=(value:number|string)=>{if(!applied)return;automaticPeriod.current=false;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);}; + const selectTrendPeriod=(value:number|string)=>{automaticPeriod.current=false;const next=nextTrendPeriod(value,{period,year,month,quarter});setYear(next.year);setMonth(next.month);setQuarter(next.quarter);setPeriod(next.period);}; const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied); const queryBusy=supportLoading||loading||(!error&&!supportError&&(dirty||!current)); const queryFailed=!!(error||supportError); - const submit=()=>{automaticPeriod.current=false;const value=search.trim();setAppliedSearch(value);setApplied(stageProductQuery({...draft,productSearch:value||undefined},stage,sourceFilters));setRevision(v=>v+1);}; - const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);}; + const submit=()=>{automaticPeriod.current=false;setAppliedSearch(search.trim());setDrilledProduct('');setRevision(v=>v+1);}; + const setTrendObject=(value?:string)=>{const selected=value||'';setDrilledProduct('');setSearch(selected);setAppliedSearch(selected);}; + const returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);setTrendMode('production');}; + const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);}; const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||'')); const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[]; + const trendOptions=useMemo(()=>[...products.map(value=>({label:value,value})),...(drilledProduct==='__UNASSIGNED__'?[{label:'未分类',value:drilledProduct}]:[])],[products,drilledProduct]); + const trendObject=drilledProduct||exactProductSearch; + const drilledLabel=drilledProduct==='__UNASSIGNED__'?'未分类':drilledProduct; const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void,extra=false)=>{trendError&&}
{trendMode==='data'?setBasisOpen(true)} onDrilldown={()=>{}}/>:}{trendLoading&&正在更新趋势}
{trendMode!=='data'&&
指标由来源分量汇总,使用当前生效公式。
} -
setSearch(e.target.value)} onPressEnter={submit}/>setFullFields(v==='full')}/>setDefectDisplay(v as typeof defectDisplay)}/>
- setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setAppliedSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/> -
+
+ + {trendError&&setRevision(v=>v+1)}>重试}/>} +
+ {trendMode==='data' + ? + : } + {trendRefreshing&&正在更新趋势} +
+
+ } + busy={queryBusy||!tableReady} search={drilledLabel||search} onSearchChange={setSearch} onSearch={submit} searchDisabled={!!drilledProduct} searchUnavailable={!catalog||!!supportError} + fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} + returnControls={drilledProduct&&} + exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}> + + setBasisOpen(true)} + emptyText={queryBusy?'正在更新数据…':error?'查询失败,暂无可展示结果':'当前条件下暂无数据'} + onDrilldown={row=>{if(drilledProduct)return;const selected=row.product||'__UNASSIGNED__';drillParentSearch.current=appliedSearch;setDrilledProduct(selected);setTrendGranularity('month');setTrendMode('production');}}/> + +
-
+
+

{label}

{displayed?.data.defects[stage]?.length ? item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : }
{displayed&&item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>} +
setBasisOpen(false)} footer={}>

{readableMetricFormula((current?.context.metricFormulaDescriptions as Record|undefined)?.[formulaKey])}

{records&&{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>} diff --git a/web/src/defect-composition.css b/web/src/defect-composition.css new file mode 100644 index 0000000..acf41a5 --- /dev/null +++ b/web/src/defect-composition.css @@ -0,0 +1,20 @@ +.query-page { --defect-black: #718797; --defect-black-2: #A9BAC5; --defect-black-3: #D5E0E6; --defect-bright: var(--query-bright,var(--blue)); } +:root[data-workspace-theme='dark'] .query-page { --defect-black: #B9BEC8; } +.query-page .defect-stage-title.black { color: var(--defect-black); } +.query-page .defect-stage-title.bright { color: var(--defect-bright); } +.query-page .defect-stage-title.black i,.query-page .defect-stage-title.bright i { background: currentColor; } +.defect-composition { position: relative; min-width: 0; padding-top: 2px; } +.defect-composition-unit { font-size: var(--font-note); line-height: 18px; color: var(--muted-ink); } +.defect-composition-plot { width: 100%; min-width: 0; height: 94px; } +.defect-composition-empty { position: absolute; inset: 23px 0 auto; height: 65px; display: flex; align-items: center; justify-content: center; color: var(--muted-ink); font-size: var(--font-control); } +.defect-composition-table { width: 100%; table-layout: fixed; border-collapse: collapse; margin: 8px 0 0; font-size: var(--font-table); } +.defect-composition-table th { width: 25%; padding: 0 4px; text-align: center; height: 30px; font-size: var(--font-note); font-weight: 500; color: var(--ink); } +.defect-composition-table td { height: 37px; padding: 0 4px; text-align: center; border-top: 1px solid color-mix(in srgb,var(--line) 65%,transparent); color: var(--muted-ink); font-family: var(--font-numeric); font-variant-numeric: tabular-nums; cursor: pointer; } +.defect-composition-table td.defect-composition-weight { color: var(--ink); font-weight: 600; } +.defect-composition-table tr:hover td { background: var(--hover); } +.defect-composition-category { display: inline-grid; grid-template-columns: 9px minmax(0,1fr); align-items: center; gap: 9px; width: calc(3em + 18px); max-width: 100%; padding: 5px 0; text-align: center; color: var(--ink); font: var(--font-table) var(--font-ui); background: transparent; border: 0; cursor: pointer; } +.defect-composition-category i { flex: 0 0 9px; height: 9px; background: var(--blue); } +.defect-composition-category:focus-visible { outline: 2px solid var(--blue); outline-offset: 3px; } +.defect-stage-grid:has(.defect-composition) > .defect-stage-column { padding: 0 16px 14px; } +.defect-stage-grid:has(.defect-composition) .defect-stage-title { padding: 14px 1px 10px; } +@media(max-width:760px) { :is(.defect-stage-grid,.stage-defect-comparison):has(.defect-composition) > .defect-stage-column { padding: 0 12px 12px; } } diff --git a/web/src/stage-product.css b/web/src/stage-product.css index 5534c6b..d315bcb 100644 --- a/web/src/stage-product.css +++ b/web/src/stage-product.css @@ -11,4 +11,12 @@ .stage-metric-strip { grid-template-columns: repeat(2,minmax(0,1fr)); } } -.stage-product-page .defects-panel > .defect-stage-column { padding: 14px; } +.stage-defect-comparison { display: grid; grid-template-columns: minmax(300px,1fr) minmax(0,2fr); border-top: 1px solid var(--line); } +.stage-defect-comparison > .defect-stage-column { padding: 0 16px 14px; } +.stage-defect-comparison .defect-stage-title { min-height: 40px; padding: 10px 0; } +.stage-defect-comparison > .defect-pareto-section { min-width: 0; border-top: 0; border-left: 1px solid var(--line); padding: 0 12px 10px; } +.stage-defect-comparison .defect-pareto-chart { height: 360px; } +@media(max-width:1000px) { + .stage-defect-comparison { grid-template-columns: 1fr; } + .stage-defect-comparison > .defect-pareto-section { border-left: 0; border-top: 1px solid var(--line); } +} diff --git a/web/src/trendPeriodSelection.ts b/web/src/trendPeriodSelection.ts new file mode 100644 index 0000000..c90bd55 --- /dev/null +++ b/web/src/trendPeriodSelection.ts @@ -0,0 +1,23 @@ +import type { PeriodKind } from './types'; + +type PeriodSelection = { period: PeriodKind; year: number; month: number; quarter: number }; + +export function selectTrendPeriod(value: number | string, current: PeriodSelection): PeriodSelection { + const raw = String(value); + const quarterly = raw.match(/^(\d{4})-Q([1-4])$/); + const monthly = raw.match(/^(\d{4})-(\d{1,2})$/); + if (quarterly) { + const year = Number(quarterly[1]), quarter = Number(quarterly[2]); + return { ...current, year, quarter, period: current.period === 'quarter' && current.year === year && current.quarter === quarter ? 'year' : 'quarter' }; + } + if (monthly) { + const year = Number(monthly[1]), month = Number(monthly[2]); + if (month < 1 || month > 12) return current; + return { ...current, year, month, period: current.period === 'month' && current.year === year && current.month === month ? 'year' : 'month' }; + } + if (/^\d{4}$/.test(raw)) return { ...current, year: Number(raw), period: 'year' }; + const month = Number(raw.match(/\d{1,2}/)?.[0]); + return Number.isInteger(month) && month >= 1 && month <= 12 + ? { ...current, month, period: current.period === 'month' && current.month === month ? 'year' : 'month' } + : current; +} diff --git a/web/verification/chart_entry_motion.test.mjs b/web/verification/chart_entry_motion.test.mjs new file mode 100644 index 0000000..bf2eed8 --- /dev/null +++ b/web/verification/chart_entry_motion.test.mjs @@ -0,0 +1,39 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import ts from 'typescript'; +import React from 'react'; +function fixture() { + const source=fs.readFileSync(process.env.QUERY_CHART_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8'); + const end=source.includes('export function TrendTable(')?source.indexOf('export function TrendTable('):source.indexOf('function TrendTable('); + const code=source.slice(source.indexOf('export function TrendChart('),end).replace('export function','function'); + const slots=new Map(),effects=new Map(),observers=[],charts=[];let cursor=0,dirty=false,queued=[],active=true; + const node={clientWidth:900,clientHeight:380}; + const hooks={useRef(initial){const i=cursor++;if(!slots.has(i))slots.set(i,{current:initial});return slots.get(i);},useState(initial){const i=cursor++;if(!slots.has(i))slots.set(i,initial);return [slots.get(i),v=>{const next=typeof v==='function'?v(slots.get(i)):v;if(!Object.is(next,slots.get(i))){slots.set(i,next);dirty=true;}}];},useCallback(fn,deps){const i=cursor++;const old=slots.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))slots.set(i,{fn,deps});return slots.get(i).fn;},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((d,j)=>!Object.is(d,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}}; + hooks.useLayoutEffect=hooks.useEffect; + const ec={init(_node,_theme,opts){const c={opts,options:[],resizes:[],disposed:false,getWidth:()=>c.opts.width??100,getHeight:()=>c.opts.height??380,on(){},resize(o){c.resizes.push(o);},setOption(o){c.options.push(o);},convertToPixel:()=>0,dispose(){c.disposed=true;}};charts.push(c);return c;}}; + const prelude=`const {useRef,useState,useEffect,useLayoutEffect,useCallback}=hooks; + const usePageCache=()=>({active:getActive()}); + const Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'}); + const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{constructor(fn){this.fn=fn;observers.push(this)}observe(){}disconnect(){this.disconnected=true}}; + const document={documentElement:{dataset:{}}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})}; + const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12}); + const getComputedStyle=()=>({getPropertyValue:()=>''}),getWorkspaceTheme=()=>({id:'light'}),trendBarPalette=()=>({qualified:'#607ae1',scrap:'#d58c35'}); + const trendBarWidth=()=>32,hasStageRows=()=>true,stageValue=(r,s,f)=>r[s][f],visibleCompositeRate=()=>.95,visibleStageRate=()=>.97,rateNumber=v=>v*100,numberText=String,escapeTooltipText=String,defectWeightRate=()=>0; + `; + const compiled=ts.transpileModule(prelude+code+'\nreturn TrendChart;',{fileName:'motion.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText; + const Component=new Function('React','hooks','echarts','getActive','observers',compiled)(React,hooks,ec,()=>active,observers); + const stage={qualifiedWeight:90,scrapWeight:10,totalWeight:100,defects:[]};const props={rows:[{month:1,black:stage,bright:stage}],mode:'production',stage:'bright',rateBasis:'original',targetRate:null,onMonth(){}}; + function attach(t){if(!t||typeof t!=='object')return;if(t.props?.ref)t.props.ref.current=node;React.Children.forEach(t.props?.children,attach);} + function render(){let n=0;do{cursor=0;dirty=false;queued=[];attach(Component(props));queued.forEach(f=>f());assert.ok(++n<10);}while(dirty);} + return {charts,node,render,setActive(v){active=v;render();},resize(){for(const o of observers)if(!o.disconnected)o.fn();},unmount(){effects.forEach(e=>e.cleanup?.());}}; +} +test('visible entry uses the actual chart size and enables native vertical bar growth',()=>{ + const f=fixture();f.render();const c=f.charts[0];assert.equal(c.opts.width,900);assert.equal(c.opts.height,380); + const o=c.options.find(o=>o.series);assert.ok(o.animationDuration>0);assert.equal(o.xAxis.type,'category');assert.equal(o.yAxis[0].type,'value');assert.ok(o.series.filter(s=>s.type==='bar').every(s=>s.yAxisIndex===0));f.unmount(); +}); +test('cached page reentry creates a fresh vertical reveal and never resizes a hidden chart to zero',()=>{ + const f=fixture();f.render();f.node.clientWidth=0;f.resize();assert.equal(f.charts[0].resizes.length,0); + f.setActive(false);assert.equal(f.charts[0].disposed,true);assert.equal(f.charts.length,1); + f.node.clientWidth=900;f.setActive(true);assert.equal(f.charts.length,2);assert.equal(f.charts[1].opts.width,900);assert.ok(f.charts[1].options.find(o=>o.series).animationDuration>0);f.unmount(); +}); diff --git a/web/verification/defect_smooth_refresh.test.mjs b/web/verification/defect_smooth_refresh.test.mjs index 9a2f15c..237c7c2 100644 --- a/web/verification/defect_smooth_refresh.test.mjs +++ b/web/verification/defect_smooth_refresh.test.mjs @@ -19,6 +19,7 @@ function fixture(){ const Spin='Spin',Alert='Alert',Empty=Object.assign('Empty',{PRESENTED_IMAGE_SIMPLE:'simple'}); const MutationObserver=class{observe(){}disconnect(){}},ResizeObserver=class{observe(){}disconnect(){}}; const document={documentElement:{}},window={matchMedia:()=>({matches:false,addEventListener(){},removeEventListener(){}})}; + const usePageCache=()=>({active:true}); const queryChartTypography=()=>({fontFamily:'sans',numericFamily:'sans',fontSize:12,tooltipFontSize:12}); const getComputedStyle=()=>({getPropertyValue:()=>''}),escapeTooltipText=v=>v,numberText=v=>String(v),chooseError=e=>e.message; class ApiError extends Error{}; diff --git a/web/verification/trend_period_selection.test.mjs b/web/verification/trend_period_selection.test.mjs new file mode 100644 index 0000000..e1e6c82 --- /dev/null +++ b/web/verification/trend_period_selection.test.mjs @@ -0,0 +1,18 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { selectTrendPeriod } from '../src/trendPeriodSelection.ts'; +const current={year:2026,month:9,quarter:3,period:'month'}; +test('clicking the selected month returns to annual scope; another month selects that month',()=>{ + assert.deepEqual(selectTrendPeriod('2026-09',current),{...current,period:'year'}); + assert.deepEqual(selectTrendPeriod('2026-08',current),{...current,month:8}); + assert.deepEqual(selectTrendPeriod('08月',current),{...current,month:8}); +}); +test('quarter selection and toggling preserve the selected year',()=>{ + assert.deepEqual(selectTrendPeriod('2025-Q4',current),{...current,year:2025,quarter:4,period:'quarter'}); + assert.deepEqual(selectTrendPeriod('2026-Q3',{...current,period:'quarter'}),{...current,period:'year'}); +}); +test('annual selection and invalid values cannot produce an invalid month',()=>{ + assert.deepEqual(selectTrendPeriod('2025',current),{...current,year:2025,period:'year'}); + assert.equal(selectTrendPeriod('2026-13',current),current); + assert.equal(selectTrendPeriod('invalid',current),current); +});