修复:查询切换时保持滚动位置并平滑更新底部图表

This commit is contained in:
2026-11-01 13:38:21 +08:00
parent 2230500a96
commit d89bd2e451
4 changed files with 91 additions and 29 deletions
+38 -28
View File
@@ -346,6 +346,8 @@ export default function QueryPage({ page, onUnauthorized }: {
const summaryExport = useRef<{ exportExcel: () => Promise<void> }>(null);
const [summaryExporting, setSummaryExporting] = useState(false);
const trendSection = useRef<HTMLElement>(null);
const defectsSection = useRef<HTMLElement>(null);
const defectsHeight = useRef(0);
const refreshSeen = useRef(refreshKey);
useEffect(() => {
if (active && refreshSeen.current !== refreshKey) { refreshSeen.current = refreshKey; setQueryRevision(value => value + 1); }
@@ -412,7 +414,8 @@ export default function QueryPage({ page, onUnauthorized }: {
const queryBusy = loading || queryPending;
const metricKeyRef = useRef(metricKey);
useLayoutEffect(() => {
if (currentMetricsData && tableContent.current) tableHeight.current = tableContent.current.getBoundingClientRect().height;
// CSS min-height uses layout pixels; DOM rectangles include workspace zoom.
if (currentMetricsData && tableContent.current) tableHeight.current = tableContent.current.offsetHeight;
}, [currentMetricsData, fullFields, drilledProduct]);
metricKeyRef.current = metricKey;
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
@@ -567,6 +570,9 @@ export default function QueryPage({ page, onUnauthorized }: {
const captureTrendAnchor = useCallback(() => {
trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null;
// Keep enough document height while the downstream charts are replaced by
// loading content, otherwise the browser clamps scrollY before anchoring.
defectsHeight.current = defectsSection.current?.offsetHeight ?? 0;
}, []);
const selectTrendPeriod = useCallback((value: number | string) => {
const raw = String(value);
@@ -639,6 +645,13 @@ export default function QueryPage({ page, onUnauthorized }: {
const activeDefectData = trendObject
? defectQueryKey === queryKey ? currentMetricsData : trendObjectMetrics?.key === defectQueryKey ? trendObjectMetrics.data : null
: currentMetricsData;
const previousDefectSnapshot = useRef<{ data: MetricsResponse; query: QueryParams } | null>(null);
useLayoutEffect(() => {
if (activeDefectData) previousDefectSnapshot.current = { data: activeDefectData, query: defectQueryParams };
}, [activeDefectData, defectQueryKey]);
const displayedDefectData = activeDefectData || previousDefectSnapshot.current?.data;
const displayedDefectQuery = activeDefectData ? defectQueryParams : previousDefectSnapshot.current?.query || defectQueryParams;
const defectsRefreshing = !activeDefectData && (queryBusy || trendObjectMetricsLoading);
// 产品月度下钻复用当前对象的服务端指标,汇总表仍保留父层结果供返回。
const summaryMetricsData = drilledProduct ? activeDefectData : currentMetricsData;
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number, sourceQuery?: QueryParams, sourceData?: MetricsResponse | null) => {
@@ -655,8 +668,8 @@ export default function QueryPage({ page, onUnauthorized }: {
const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap'];
const brightFormula = formulaDescriptions[rateBasis === 'original' ? 'brightRate' : 'brightRateWithoutHeadquartersScrap'];
const formulaText = readableMetricFormula;
const blackDefectItems = activeDefectData?.defects?.black || [];
const brightDefectItems = activeDefectData?.defects?.bright || [];
const blackDefectItems = displayedDefectData?.defects?.black || [];
const brightDefectItems = displayedDefectData?.defects?.bright || [];
const organizationPaths = options?.organizationPaths || [];
const organizationPathOptions = useMemo(() => {
const departments = new Set(department);
@@ -847,26 +860,24 @@ export default function QueryPage({ page, onUnauthorized }: {
<div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div>
</section>
<section className="panel section-panel defects-panel">
<section className="panel section-panel defects-panel" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
<div className="section-heading-row">
<SectionHeading title="不良具体构成" />
{defectsRefreshing && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
</div>
{trendObjectMetricsLoading && <div className="defect-pareto-status"><Spin size="small" />正在更新当前趋势对象的不良数据</div>}
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
<div className="defect-stage-grid">
<div className="defect-stage-grid" inert={!activeDefectData}>
{(['black', 'bright'] as const).map(stage => {
const items = stage === 'black' ? blackDefectItems : brightDefectItems;
return <section className="defect-stage-column" key={stage} aria-label={`${stage === 'black' ? '黑片' : '亮片'}不良构成`}>
<h3 className={`defect-stage-title ${stage}`}><i />{stage === 'black' ? '黑片' : '亮片'}</h3>
{trendObjectMetricsLoading || trendObjectMetricsError
? null
: items.length
? <DefectBreakdown items={items} stage={stage} totalWeight={activeDefectData?.summary?.[stage]?.totalWeight} maximum={Math.max(0, ...items.map(item => item.weight ?? 0))} onDetail={() => openRecords(null, stage, undefined, defectQueryParams, activeDefectData)} />
: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件下暂无不良分类数据" />}
{items.length
? <DefectBreakdown items={items} stage={stage} totalWeight={displayedDefectData?.summary?.[stage]?.totalWeight} maximum={Math.max(0, ...items.map(item => item.weight ?? 0))} onDetail={() => openRecords(null, stage, undefined, defectQueryParams, activeDefectData)} />
: !defectsRefreshing && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件下暂无不良分类数据" />}
</section>;
})}
</div>
{currentMetricsData ? <DefectParetoPanel key={`${currentMetricsData.release?.id}:${defectQueryKey}:${queryRevision}`} releaseId={currentMetricsData.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : <div className="defect-pareto-status">{queryBusy ? '正在更新不良数据…' : '不良数据暂不可用'}</div>}
{displayedDefectData ? <DefectParetoPanel releaseId={displayedDefectData.release?.id} query={displayedDefectQuery} refreshKey={queryRevision} pending={defectsRefreshing} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : !defectsRefreshing && <div className="defect-pareto-status">不良数据暂不可用</div>}
</section>
</div>
</>
@@ -928,12 +939,12 @@ export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }
}
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage }: {
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage;
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 container = useRef<HTMLDivElement>(null);
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse } | null>(null);
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse; externalScrapWeight?: number | null } | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [themeRevision, setThemeRevision] = useState(0);
@@ -956,13 +967,12 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
const controller = new AbortController();
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
setResponses(null);
setLoading(true);
setError('');
Promise.all([
onlyStage === 'bright' ? Promise.resolve({kind:'fine_defect_top' as const,releaseId,sourceRows:0,rows:[]}) : api.fineDefectTop({ ...base, stage: 'black' }, controller.signal),
onlyStage === 'black' ? Promise.resolve({kind:'fine_defect_top' as const,releaseId,sourceRows:0,rows:[]}) : api.fineDefectTop({ ...base, stage: 'bright' }, controller.signal),
]).then(([black, bright]) => { if (!controller.signal.aborted) setResponses({ black, bright }); })
]).then(([black, bright]) => { if (!controller.signal.aborted) setResponses({ black, bright, externalScrapWeight }); })
.catch(value => {
if (controller.signal.aborted) return;
if (onUnauthorized(value)) return;
@@ -970,7 +980,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
})
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
return () => controller.abort();
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage]);
}, [releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
useEffect(() => {
const refresh = () => setThemeRevision(value => value + 1);
@@ -1000,12 +1010,12 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
weight: row.weight,
kind: 'source' as const,
})));
if (onlyStage !== 'bright' && typeof externalScrapWeight === 'number' && Number.isFinite(externalScrapWeight) && externalScrapWeight > 0) {
raw.push({ key: 'black:externalScrap', label: '黑片·外废', category: '外废', weight: externalScrapWeight, kind: 'category' });
if (onlyStage !== 'bright' && typeof responses.externalScrapWeight === 'number' && Number.isFinite(responses.externalScrapWeight) && responses.externalScrapWeight > 0) {
raw.push({ key: 'black:externalScrap', label: '黑片·外废', category: '外废', weight: responses.externalScrapWeight, kind: 'category' });
}
return raw.filter(item => typeof item.weight === 'number' && Number.isFinite(item.weight) && item.weight > 0)
.sort((left, right) => right.weight! - left.weight! || left.label.localeCompare(right.label, 'zh-CN'));
}, [responses, externalScrapWeight, onlyStage]);
}, [responses, onlyStage]);
const totalWeight = items.reduce((total, item) => total + (item.weight || 0), 0);
useEffect(() => {
@@ -1027,6 +1037,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
});
const option: echarts.EChartsCoreOption = {
textStyle: { color: ink, fontFamily, fontSize },
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
animationDuration: 420,
animationDurationUpdate: 520,
grid: { left: 32, right: 24, top: 48, bottom: 12, containLabel: true },
@@ -1058,20 +1069,19 @@ 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: [
{ name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
{ 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 },
{ 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-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, { notMerge: true, lazyUpdate: false });
instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false });
}, [items, totalWeight, themeRevision]);
return <section className="defect-pareto-section" aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong></div>
{loading && <div className="defect-pareto-status"><Spin size="small" />正在汇总细分报废重量</div>}
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
<div className="defect-pareto-chart" ref={container} style={{ display: !releaseId || error || (responses && !items.length) ? 'none' : undefined }} aria-label="按报废重量降序排列,折线表示累计占比" />
<div className="defect-pareto-chart" ref={container} inert={loading || pending || !!error} style={{ display: !releaseId || (responses && !items.length) ? 'none' : undefined }} aria-label="按报废重量降序排列,折线表示累计占比" />
</section>;
}
+5
View File
@@ -4,6 +4,11 @@
.query-awaiting-data .metric-value { opacity: .5; }
.query-table-content { min-width: 0; }
.query-table-content[aria-busy="true"] { pointer-events: none; }
.defect-refresh-indicator { display: inline-flex; align-items: center; gap: 6px; margin-left: auto; color: var(--ink); font-size: var(--font-note); }
.defect-pareto-heading { align-items: center; }
.defect-track > i { transition: width 520ms cubic-bezier(.22,.61,.36,1); }
.defect-pareto-chart[inert] { pointer-events: none; }
@media (prefers-reduced-motion: reduce) { .defect-track > i { transition: none; } }
.source-records-drawer .ant-drawer-content,
.source-records-drawer .ant-drawer-header,
.source-records-drawer .ant-drawer-body { background: var(--surface, #fff); }
+1 -1
View File
@@ -77,7 +77,7 @@ button { color: inherit; }
.mobile-brand { display: none; }
.page-content { width: 100%; min-width: 0; margin: 0; padding: 15px 20px 20px; }
.panel { background: var(--surface); border: 1px solid var(--line); border-radius: var(--panel-radius, 5px) !important; }
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; }
.query-page { display: flex; min-width: 0; flex-direction: column; gap: 11px; overflow-anchor: none; }
.query-toolbar { position: sticky; top: 53px; z-index: 35; display: flex; min-height: 48px; flex-wrap: wrap; align-items: center; gap: 10px 13px; padding: 7px 11px; }
.query-toolbar::before { content: ''; position: absolute; right: -20px; bottom: 100%; left: -20px; height: 18px; background: var(--background); pointer-events: none; }
.query-field { display: inline-flex; min-width: 0; align-items: center; gap: 7px; }
@@ -0,0 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import ts from 'typescript';
import React from 'react';
const deferred=()=>{let resolve,reject;const promise=new Promise((r,j)=>{resolve=r;reject=j;});return {promise,resolve,reject};};
const tick=()=>new Promise(r=>setImmediate(r));
function find(tree,predicate){if(!tree||typeof tree!=='object')return; if(predicate(tree))return tree;for(const child of React.Children.toArray(tree.props?.children)){const result=find(child,predicate);if(result)return result;}}
function fixture(){
const source=fs.readFileSync(process.env.QUERY_PARETO_SOURCE || new URL('../src/QueryPage.tsx',import.meta.url),'utf8');
const component=source.slice(source.indexOf('export function DefectParetoPanel('),source.indexOf('export function SectionHeading(')).replace('export function','function');
const requests=[],options=[],effects=new Map(),states=new Map(),refs=new Map();let cursor=0,dirty=false,queued=[],tree,creates=0,clears=0;
const node={clientWidth:900,clientHeight:470};
const hooks={useState(initial){const i=cursor++;if(!states.has(i))states.set(i,initial);return [states.get(i),v=>{states.set(i,typeof v==='function'?v(states.get(i)):v);dirty=true;}];},useRef(initial){const i=cursor++;if(!refs.has(i))refs.set(i,{current:initial});return refs.get(i);},useMemo(fn){cursor++;return fn();},useEffect(fn,deps){const i=cursor++,old=effects.get(i);if(!old||deps.some((x,j)=>!Object.is(x,old.deps[j])))queued.push(()=>{old?.cleanup?.();effects.set(i,{deps,cleanup:fn()});});}};
const api={fineDefectTop(params,signal){const d=deferred();requests.push({...d,params,signal});return d.promise;}};
const chart={setOption:(value,config)=>options.push({value,config}),clear(){clears++;},resize(){},dispose(){}};
const echarts={init(){creates++;return chart;}};
const prelude=`const {useState,useRef,useMemo,useEffect}=hooks;
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 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{};
`;
const js=ts.transpileModule(prelude+component+'\nreturn DefectParetoPanel;',{fileName:'fixture.tsx',compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
const renderComponent=new Function('React','hooks','api','echarts',js)(React,hooks,api,echarts);
const props={releaseId:'release-A',query:{year:2026,month:1},onUnauthorized:()=>false};
const render=()=>{let attempts=0;do{cursor=0;dirty=false;queued=[];tree=renderComponent(props);find(tree,e=>{if(e.props?.ref)e.props.ref.current=node;return false;});queued.forEach(fn=>fn());assert.ok(++attempts<10);}while(dirty);return tree;};
const result=weight=>({kind:'fine_defect_top',releaseId:'release-A',sourceRows:1,rows:[{key:'chip',label:'缺角',category:'责废',weight}]});
const resolvePair=(index,weight)=>{requests[index].resolve(result(weight));requests[index+1].resolve(result(weight/2));};
return {props,requests,options,render,resolvePair,get creates(){return creates;},get clears(){return clears;},get tree(){return tree;},unmount(){effects.forEach(x=>x.cleanup?.());}};
}
test('actual Pareto keeps the old chart while fetching and updates the same instance with stable series/data ids',async()=>{
const ui=fixture();ui.render();ui.resolvePair(0,100);await tick();ui.render();const clears=ui.clears;
assert.equal(ui.options.at(-1).value.series[0].data[0].value,100);
ui.props.query={year:2026,month:2};ui.render();assert.equal(ui.tree.props['aria-busy'],true);assert.equal(ui.clears,clears);assert.equal(ui.creates,1);assert.equal(ui.options.at(-1).value.series[0].data[0].value,100);
ui.resolvePair(2,50);await tick();ui.render();const update=ui.options.at(-1);
assert.equal(update.value.series[0].data[0].value,50);assert.equal(update.config.notMerge,undefined);assert.deepEqual(update.config.replaceMerge,['series']);assert.equal(update.value.series[0].id,'pareto-weight');assert.equal(update.value.series[0].data[0].id,'black:chip');assert.equal(ui.creates,1);ui.unmount();
});
test('late responses cannot overwrite a newer selection or mix its external scrap into older data',async()=>{
const ui=fixture();ui.props.externalScrapWeight=3;ui.render();ui.resolvePair(0,100);await tick();ui.render();ui.props.query={year:2026,month:2};ui.props.externalScrapWeight=7;ui.render();ui.props.query={year:2026,month:3};ui.props.externalScrapWeight=11;ui.render();assert.equal(ui.requests[2].signal.aborted,true);
ui.resolvePair(4,70);await tick();ui.render();ui.resolvePair(2,999);await tick();ui.render();const data=ui.options.at(-1).value.series[0].data;assert.equal(data[0].value,70);assert.equal(data.find(x=>x.id==='black:externalScrap').value,11);ui.unmount();
});
test('a failed refresh retains the last chart with an error and disables its old tooltips',async()=>{
const ui=fixture();ui.render();ui.resolvePair(0,100);await tick();ui.render();const clears=ui.clears;ui.props.query={year:2026,month:2};ui.render();ui.requests[2].reject(Error('offline'));await tick();ui.render();assert.equal(ui.clears,clears);assert.equal(ui.options.at(-1).value.series[0].data[0].value,100);assert.equal(find(ui.tree,n=>n.type==='Alert').props.description,'offline');assert.equal(find(ui.tree,n=>n.props?.className==='defect-pareto-chart').props.inert,true);ui.unmount();
});