优化:查询页面平滑切换与默认月份高亮
This commit is contained in:
@@ -1,3 +1,5 @@
|
||||
import { flushSync } from 'react-dom';
|
||||
import { createWorkspaceTransition, waitForWorkspaceContent } from './workspaceTransition';
|
||||
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { Alert, Button, Spin } from 'antd';
|
||||
import { api } from './api';
|
||||
@@ -22,12 +24,20 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
page: PageKey; user: AuthUser; onPageChange: (page: PageKey) => void; onUserChange: (user: AuthUser) => void; onUnauthorized: (error: unknown) => boolean;
|
||||
}>(function CachedWorkspacePages({ page, user, onPageChange, onUserChange, onUnauthorized }, ref) {
|
||||
const entries = useRef(new Map<PageKey, Entry>([[page, { initialSearch: location.search, search: location.search, key: 0, scroll: 0 }]]));
|
||||
const requested = useRef(page);
|
||||
const current = useRef(page), generation = useRef(0), key = useRef(0);
|
||||
const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null);
|
||||
const validation = useRef<Promise<boolean> | null>(null);
|
||||
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
|
||||
const [ready, setReady] = useState(false), [error, setError] = useState('');
|
||||
const [navigationBusy, setNavigationBusy] = useState(false);
|
||||
const alive = useRef(true);
|
||||
const transitions = useRef<ReturnType<typeof createWorkspaceTransition> | null>(null);
|
||||
if (!transitions.current) transitions.current = createWorkspaceTransition(
|
||||
typeof document.startViewTransition === 'function' ? document.startViewTransition.bind(document) : undefined,
|
||||
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
busy => { if (alive.current) setNavigationBusy(busy); },
|
||||
);
|
||||
const validate = () => {
|
||||
if (validation.current) return validation.current;
|
||||
const epoch = generation.current;
|
||||
@@ -39,6 +49,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
const latest = await api.me();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
|
||||
transitions.current?.cancel(); requested.current = current.current;
|
||||
onUserChange(latest); entries.current.clear();
|
||||
entries.current.set(current.current, { initialSearch: location.search, search: location.search, key: ++key.current, scroll: 0 });
|
||||
render(value => value + 1);
|
||||
@@ -66,14 +77,22 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
const previous = entries.current.get(next);
|
||||
if (!previous || force) entries.current.set(next, { initialSearch: search, search, key: ++key.current, scroll: 0 });
|
||||
const entry = entries.current.get(next)!;
|
||||
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`);
|
||||
current.current = next; onPageChange(next); render(value => value + 1);
|
||||
// 本地页面先响应点击,网络校验在后台进行;连续切换共享尚未结束的请求。
|
||||
void validate();
|
||||
requested.current = next;
|
||||
transitions.current!.run(async signal => {
|
||||
if (!alive.current || entries.current.get(next) !== entry) return;
|
||||
// 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
|
||||
flushSync(() => {
|
||||
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`);
|
||||
current.current = next; onPageChange(next); render(value => value + 1);
|
||||
});
|
||||
window.scrollTo(0, entry.scroll);
|
||||
void validate();
|
||||
await waitForWorkspaceContent(() => document.querySelector(`.page-view[data-page="${next}"]`), signal);
|
||||
});
|
||||
};
|
||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
|
||||
if (next === 'imports') next = 'sources';
|
||||
if (next === current.current && !query && !resultRef) return;
|
||||
if (next === requested.current && !query && !resultRef) return;
|
||||
const params = new URLSearchParams({ page: next });
|
||||
if (query) params.set('context', encode({ query, ...(resultRef ? { resultRef } : {}) }));
|
||||
const cached = entries.current.get(next);
|
||||
@@ -89,7 +108,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
void validate();
|
||||
const invalidate = () => setRefreshKey(value => value + 1);
|
||||
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
||||
return () => { alive.current = false; generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
||||
}, []);
|
||||
const activeEntryKey = entries.current.get(page)?.key;
|
||||
useLayoutEffect(() => {
|
||||
@@ -101,7 +120,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
if (!ready) return connectionNotice || <div className="loading-panel"><Spin />正在打开工作台…</div>;
|
||||
return <>{connectionNotice}{Array.from(entries.current.entries()).filter(([name]) => retained(name) || name === page).map(([name, entry]) => {
|
||||
const active = name === page;
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} style={!active ? { display: 'none' } : undefined}>
|
||||
return <div key={`${name}-${entry.key}`} className="page-view" data-page={name} hidden={!active} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
|
||||
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
|
||||
{name === 'blackProduct' || name === 'brightProduct' ? <StageProductPage stage={name === 'blackProduct' ? 'black' : 'bright'} onUnauthorized={onUnauthorized} /> : QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
|
||||
|
||||
+104
-99
@@ -1,3 +1,4 @@
|
||||
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
|
||||
import { trendBarPalette } from './trendBarPalette';
|
||||
import { getWorkspaceTheme } from './ui-themes';
|
||||
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
|
||||
@@ -44,7 +45,7 @@ import type {
|
||||
import type { PageKey } from './QualityWorkspace';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
|
||||
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import './query-motion.css';
|
||||
import { ExtraQueryFilters } from './ExtraQueryFilters';
|
||||
@@ -299,9 +300,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [optionsError, setOptionsError] = useState('');
|
||||
const [optionsLoading, setOptionsLoading] = useState(true);
|
||||
const automaticPeriod = useRef(!initialQuery.year && !initialQuery.month && !initialQuery.quarter);
|
||||
const defaultMonth = previousCompleteMonth();
|
||||
const defaultQuarter = previousCompleteQuarter();
|
||||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : page === 'overall' ? 'year' : 'month');
|
||||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year ? '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);
|
||||
@@ -342,7 +344,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [recordQuerySnapshot, setRecordQuerySnapshot] = useState<QueryParams | null>(null);
|
||||
const [basisOpen, setBasisOpen] = useState(false);
|
||||
const trendAnchorTop = useRef<number | null>(null);
|
||||
const tableContent = useRef<HTMLDivElement>(null);
|
||||
const summaryExport = useRef<{ exportExcel: () => Promise<void> }>(null);
|
||||
const [summaryExporting, setSummaryExporting] = useState(false);
|
||||
const trendSection = useRef<HTMLElement>(null);
|
||||
@@ -353,7 +354,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (active && refreshSeen.current !== refreshKey) { refreshSeen.current = refreshKey; setQueryRevision(value => value + 1); }
|
||||
if (!active) { setRecordsOpen(false); setBasisOpen(false); }
|
||||
}, [active, refreshKey]);
|
||||
const tableHeight = useRef(525);
|
||||
|
||||
|
||||
|
||||
@@ -362,8 +362,11 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
api.options().then(result => {
|
||||
if (!alive) return;
|
||||
setOptions(result);
|
||||
const yearOptions = (result.years || []).map(value => Number(String(value).match(/\d{4}/)?.[0])).filter(Number.isFinite);
|
||||
if (yearOptions.length && !yearOptions.includes(year)) setYear(Math.max(...yearOptions));
|
||||
if (automaticPeriod.current) {
|
||||
const available = defaultQueryMonth(result);
|
||||
setYear(available.year); setMonth(available.month);
|
||||
automaticPeriod.current = false;
|
||||
}
|
||||
setOptionsError('');
|
||||
}).catch(errorValue => {
|
||||
if (onUnauthorized(errorValue)) return;
|
||||
@@ -413,10 +416,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const queryPending = !currentMetricsData && !currentMetricsError;
|
||||
const queryBusy = loading || queryPending;
|
||||
const metricKeyRef = useRef(metricKey);
|
||||
useLayoutEffect(() => {
|
||||
// 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';
|
||||
const trendParams = useMemo<QueryParams>(() => {
|
||||
@@ -446,6 +445,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}, [queryKey, active]);
|
||||
|
||||
useEffect(() => {
|
||||
if (optionsLoading) return;
|
||||
const controller = new AbortController();
|
||||
setLoading(true);
|
||||
setError('');
|
||||
@@ -467,7 +467,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
setErrorKey(metricKey);
|
||||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [metricKey, queryRevision, onUnauthorized]);
|
||||
}, [metricKey, queryRevision, onUnauthorized, optionsLoading]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!trendObject || defectQueryKey === queryKey) {
|
||||
@@ -491,6 +491,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}, [trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
||||
|
||||
useEffect(() => {
|
||||
if (optionsLoading) return;
|
||||
if (useSummaryTrend) {
|
||||
setTrendLoading(false);
|
||||
return;
|
||||
@@ -506,7 +507,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(`趋势加载失败:${chooseError(errorValue)}`);
|
||||
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
||||
return () => controller.abort();
|
||||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message]);
|
||||
}, [trendKey, useSummaryTrend, queryRevision, onUnauthorized, message, optionsLoading]);
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
@@ -568,6 +569,21 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
return orderedRows.filter(row => [row.label, row.department, row.group, row.product, row.projectGroup].filter(Boolean).join(' ').toLocaleLowerCase().includes(term));
|
||||
}, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]);
|
||||
|
||||
const tableReady = drilledProduct ? trendDataKey === trendKey && !trendLoading : !!currentMetricsData;
|
||||
const retainedTable = useRetainedResult(tableReady ? {
|
||||
rows: drilledProduct ? drilledTrendData : visibleRows,
|
||||
view: drilledProduct ? 'overall' as const : view,
|
||||
layoutView: drilledProduct ? 'product' as const : view,
|
||||
period: drilledProduct ? 'year' as const : period,
|
||||
year, month, quarter, drilledProduct,
|
||||
} : null);
|
||||
const tableRows = retainedTable?.rows || [];
|
||||
const tablePeriod = retainedTable?.period || period;
|
||||
const tableView = retainedTable?.view || view;
|
||||
const tableMonth = retainedTable?.month || month;
|
||||
const tableQuarter = retainedTable?.quarter || quarter;
|
||||
const tableProduct = retainedTable?.drilledProduct || '';
|
||||
|
||||
const captureTrendAnchor = useCallback(() => {
|
||||
trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null;
|
||||
// Keep enough document height while the downstream charts are replaced by
|
||||
@@ -575,6 +591,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
defectsHeight.current = defectsSection.current?.offsetHeight ?? 0;
|
||||
}, []);
|
||||
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})$/);
|
||||
@@ -662,7 +679,8 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}, [summaryMetricsData, drilledProduct, defectQueryParams, queryParams, view, message]);
|
||||
const summaryMetricsError = drilledProduct ? trendObjectMetricsError : currentMetricsError;
|
||||
const summaryBusy = drilledProduct ? trendObjectMetricsLoading || !summaryMetricsData && !summaryMetricsError : queryBusy;
|
||||
const rowForSummary = summaryMetricsData?.summary;
|
||||
const displayedSummaryData = useRetainedResult(summaryMetricsData);
|
||||
const rowForSummary = displayedSummaryData?.summary;
|
||||
const rawFormulaDescriptions = summaryMetricsData?.context.metricFormulaDescriptions;
|
||||
const formulaDescriptions = rawFormulaDescriptions && typeof rawFormulaDescriptions === 'object' && !Array.isArray(rawFormulaDescriptions) ? rawFormulaDescriptions as Record<string, unknown> : {};
|
||||
const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap'];
|
||||
@@ -719,11 +737,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
value={period}
|
||||
options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]}
|
||||
onChange={value => {
|
||||
automaticPeriod.current = false;
|
||||
const nextPeriod = value as PeriodKind;
|
||||
setPeriod(nextPeriod);
|
||||
setTrendGranularity(nextPeriod === 'quarter' ? 'quarter' : 'month');
|
||||
if (nextPeriod === 'month') {
|
||||
const previous = previousCompleteMonth();
|
||||
const previous = defaultQueryMonth(options);
|
||||
setYear(previous.year);
|
||||
setMonth(previous.month);
|
||||
} else if (nextPeriod === 'quarter') {
|
||||
@@ -734,9 +753,9 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}}
|
||||
aria-label="统计周期"
|
||||
/>
|
||||
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={setYear} loading={optionsLoading} /></label>
|
||||
{period === 'month' && <label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={setMonth} /></label>}
|
||||
{period === 'quarter' && <label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={setQuarter} /></label>}
|
||||
<label className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={value => { automaticPeriod.current = false; setYear(value); }} loading={optionsLoading} /></label>
|
||||
{period === 'month' && <label className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={value => { automaticPeriod.current = false; setMonth(value); }} /></label>}
|
||||
{period === 'quarter' && <label className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={value => { automaticPeriod.current = false; setQuarter(value); }} /></label>}
|
||||
{filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })}
|
||||
{filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)}
|
||||
{filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)}
|
||||
@@ -744,7 +763,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<ExtraQueryFilters key={queryRevision} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
|
||||
<div className="query-toolbar-tail">
|
||||
<span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
|
||||
<Button type="default" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
|
||||
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('month'); setTrendGranularity('month'); }}>重置</Button>
|
||||
</div>
|
||||
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
|
||||
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
|
||||
@@ -754,12 +773,12 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
<section className={`metric-strip ${!summaryMetricsData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
|
||||
<section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
|
||||
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
|
||||
<MetricCard primary label="综合合格率" value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
|
||||
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
|
||||
<MetricCard label="亮片合格率" value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
|
||||
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText(queryTotalScrapWeight(rowForSummary, rateBasis))} kg` : '—'} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(queryScrapWeight(rowForSummary?.bright, 'bright', rateBasis))} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
|
||||
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
|
||||
<MetricCard label="亮片合格率" value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
|
||||
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText(queryTotalScrapWeight(rowForSummary, rateBasis))} kg` : '—'} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(queryScrapWeight(rowForSummary?.bright, 'bright', rateBasis))} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
|
||||
</section>
|
||||
|
||||
{['department', 'group', 'product'].includes(page) && <>
|
||||
@@ -767,77 +786,6 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
</>}
|
||||
|
||||
<>
|
||||
<section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
<SectionHeading title={drilledProduct ? '产品月度质量数据' : page === 'overall' ? `${period === 'year' ? '年度月度' : period === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={drilledProduct ? `${year} 年 · ${drilledProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
|
||||
<div className="table-tools">
|
||||
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
|
||||
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
|
||||
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
|
||||
<Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
|
||||
setSummaryExporting(true);
|
||||
try { await summaryExport.current?.exportExcel(); }
|
||||
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
|
||||
finally { setSummaryExporting(false); }
|
||||
}}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
<Spin spinning={queryBusy}><div ref={tableContent} className="query-table-content" style={{ minHeight: queryBusy ? tableHeight.current : undefined }} aria-busy={queryBusy} inert={!currentMetricsData}>
|
||||
{drilledProduct ? (
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||
rows={drilledTrendData}
|
||||
view="overall"
|
||||
layoutView="product"
|
||||
pageSizeOverride={12}
|
||||
period="year"
|
||||
month={month}
|
||||
quarter={quarter}
|
||||
fullFields={fullFields}
|
||||
defectDisplay={defectDisplay}
|
||||
rateBasis={rateBasis}
|
||||
onDetail={openRecords}
|
||||
onBasis={() => setBasisOpen(true)}
|
||||
onDrilldown={() => undefined}
|
||||
/>
|
||||
) : (
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||
rows={visibleRows}
|
||||
view={view}
|
||||
period={period}
|
||||
month={month}
|
||||
quarter={quarter}
|
||||
fullFields={fullFields}
|
||||
defectDisplay={defectDisplay}
|
||||
rateBasis={rateBasis}
|
||||
onDetail={openRecords}
|
||||
onBasis={() => setBasisOpen(true)}
|
||||
emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'}
|
||||
onDrilldown={row => {
|
||||
if (view === 'overall') setViewOverride('department');
|
||||
else if (view === 'department' && row.department) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setGroup([]); setProduct([]); setDepartment([row.department]); setViewOverride('group'); }
|
||||
else if (view === 'group' && row.group) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setProduct([]); setGroup([row.group]); setViewOverride('product'); }
|
||||
else if (view === 'product') {
|
||||
const selectedProduct = row.product || row.label;
|
||||
if (!selectedProduct) return;
|
||||
setDrilledProduct(selectedProduct);
|
||||
setTrendObject(selectedProduct);
|
||||
setTrendGranularity('month');
|
||||
setTrendMode('production');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div></Spin>
|
||||
</section>
|
||||
|
||||
<div className="analysis-stack">
|
||||
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
@@ -860,6 +808,62 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div>
|
||||
</section>
|
||||
|
||||
|
||||
<section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
|
||||
<div className="table-tools">
|
||||
{(queryBusy || !tableReady) && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||||
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
|
||||
{!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
|
||||
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
|
||||
<Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
|
||||
setSummaryExporting(true);
|
||||
try { await summaryExport.current?.exportExcel(); }
|
||||
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
|
||||
finally { setSummaryExporting(false); }
|
||||
}}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||||
rows={tableRows}
|
||||
view={tableView}
|
||||
layoutView={retainedTable?.layoutView || view}
|
||||
pageSizeOverride={tableProduct ? 12 : undefined}
|
||||
period={tablePeriod}
|
||||
month={tableMonth}
|
||||
quarter={tableQuarter}
|
||||
fullFields={fullFields}
|
||||
defectDisplay={defectDisplay}
|
||||
rateBasis={rateBasis}
|
||||
onDetail={openRecords}
|
||||
onBasis={() => setBasisOpen(true)}
|
||||
emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'}
|
||||
onDrilldown={row => {
|
||||
if (drilledProduct) return;
|
||||
if (view === 'overall') setViewOverride('department');
|
||||
else if (view === 'department' && row.department) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setGroup([]); setProduct([]); setDepartment([row.department]); setViewOverride('group'); }
|
||||
else if (view === 'group' && row.group) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setProduct([]); setGroup([row.group]); setViewOverride('product'); }
|
||||
else if (view === 'product') {
|
||||
const selectedProduct = row.product || row.label;
|
||||
if (!selectedProduct) return;
|
||||
setDrilledProduct(selectedProduct);
|
||||
setTrendObject(selectedProduct);
|
||||
setTrendGranularity('month');
|
||||
setTrendMode('production');
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</SmoothTableFrame>
|
||||
</section>
|
||||
|
||||
<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="不良具体构成" />
|
||||
@@ -917,10 +921,11 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}
|
||||
|
||||
export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: React.ReactNode; value: string; note?: string; stage?: Stage; onClick: () => void }) {
|
||||
const parts = value.match(/^(.*?)(%| kg)$/);
|
||||
const displayedValue = useAnimatedMetricText(value);
|
||||
const parts = displayedValue.match(/^(.*?)(%| kg)$/);
|
||||
return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}>
|
||||
<span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span>
|
||||
<strong className="metric-value">{parts ? <>{parts[1]}<span className="metric-unit">{parts[2]}</span></> : value}</strong>
|
||||
<strong className="metric-value">{parts ? <>{parts[1]}<span className="metric-unit">{parts[2]}</span></> : displayedValue}</strong>
|
||||
{note && <small>{note}</small>}
|
||||
</button>;
|
||||
}
|
||||
@@ -1133,7 +1138,7 @@ export function MetricTable({
|
||||
align: 'center' as const,
|
||||
width: field === 'rate' ? (stage === 'bright' && rateBasis !== 'original' ? 164 : fullFields ? 96 : 116) : (fullFields ? 112 : 145),
|
||||
className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`,
|
||||
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field, rateBasis),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field, rateBasis))}</Button>,
|
||||
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field, rateBasis),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field, rateBasis))} /></Button>,
|
||||
});
|
||||
const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({
|
||||
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`,
|
||||
@@ -1143,7 +1148,7 @@ export function MetricTable({
|
||||
width: fullFields ? 100 : 130,
|
||||
render: (_: unknown, row: MetricRow) => {
|
||||
const value = defectList(row, stage).find(item => item.name === name);
|
||||
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)}</Button>;
|
||||
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)} /></Button>;
|
||||
},
|
||||
}));
|
||||
const brightDetailColumns: ColumnsType<MetricRow> = defectColumns('bright', brightDefects);
|
||||
@@ -1155,8 +1160,8 @@ export function MetricTable({
|
||||
const allColumns: ColumnsType<MetricRow> = [
|
||||
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
|
||||
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('总重量', 'black', 'totalWeight'), numeric('合格重量', 'black', 'qualifiedWeight'), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
|
||||
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] },
|
||||
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleCompositeRate(row, rateBasis))}</button> },
|
||||
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }] },
|
||||
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> },
|
||||
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
|
||||
];
|
||||
const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns;
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
import { useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
|
||||
export function useRetainedResult<T>(current: T | null | undefined): T | null {
|
||||
const previous = useRef<T | null>(null);
|
||||
useLayoutEffect(() => { if (current != null) previous.current = current; }, [current]);
|
||||
return current ?? previous.current;
|
||||
}
|
||||
|
||||
function numericText(text: string) {
|
||||
const match = text.match(/^(-?[\d,]+(?:\.\d+)?)(%| kg)?$/);
|
||||
if (!match) return null;
|
||||
const value = Number(match[1].replaceAll(',', ''));
|
||||
return Number.isFinite(value) ? { value, decimals: match[1].split('.')[1]?.length || 0, unit: match[2] || '' } : null;
|
||||
}
|
||||
|
||||
export function interpolateMetricText(from: string, to: string, progress: number): string {
|
||||
const start = numericText(from), target = numericText(to);
|
||||
if (!start || !target || start.unit !== target.unit || progress >= 1) return to;
|
||||
const value = start.value + (target.value - start.value) * Math.max(0, progress);
|
||||
return value.toLocaleString('en-US', { minimumFractionDigits: target.decimals, maximumFractionDigits: target.decimals }) + target.unit;
|
||||
}
|
||||
|
||||
export function useAnimatedMetricText(value: string): string {
|
||||
const [display, setDisplay] = useState(value);
|
||||
const shown = useRef(value);
|
||||
useLayoutEffect(() => {
|
||||
const from = shown.current;
|
||||
const commit = (text: string) => { shown.current = text; setDisplay(text); };
|
||||
if (from === value) return;
|
||||
const startValue = numericText(from), targetValue = numericText(value);
|
||||
if (!startValue || !targetValue || startValue.unit !== targetValue.unit || window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
|
||||
commit(value); return;
|
||||
}
|
||||
const start = performance.now();
|
||||
let frame = 0;
|
||||
const update = (now: number) => {
|
||||
const progress = Math.min(1, (now - start) / 520);
|
||||
commit(interpolateMetricText(from, value, 1 - (1 - progress) ** 3));
|
||||
if (progress < 1) frame = requestAnimationFrame(update);
|
||||
};
|
||||
frame = requestAnimationFrame(update);
|
||||
// 连续点击时从此刻的显示值继续,不回到上一次请求的起点。
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [value]);
|
||||
return display;
|
||||
}
|
||||
|
||||
export function AnimatedMetricText({ value }: { value: string }) {
|
||||
return <span className="animated-metric-text">{useAnimatedMetricText(value)}</span>;
|
||||
}
|
||||
|
||||
export function SmoothTableFrame({ children, busy, blocked }: { children: ReactNode; busy: boolean; blocked: boolean }) {
|
||||
const content = useRef<HTMLDivElement>(null);
|
||||
const [height, setHeight] = useState<number>();
|
||||
useLayoutEffect(() => {
|
||||
const node = content.current;
|
||||
if (!node) return;
|
||||
const measure = () => setHeight(node.offsetHeight);
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(node);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
useLayoutEffect(() => { if (content.current) setHeight(content.current.offsetHeight); }, [children]);
|
||||
return <div className="smooth-table-frame" style={{ height }}>
|
||||
<div ref={content} className="query-table-content" aria-busy={busy} inert={blocked}>{children}</div>
|
||||
</div>;
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
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';
|
||||
@@ -7,7 +8,7 @@ import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHea
|
||||
import { StageSourceFilters } from './StageSourceFilters';
|
||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { readableMetricFormula } from './publicDataDisplay';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
@@ -18,6 +19,7 @@ const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}
|
||||
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
|
||||
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
|
||||
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
|
||||
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
|
||||
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
|
||||
const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
|
||||
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
|
||||
@@ -32,7 +34,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const label=stage==='black'?'黑片':'亮片';
|
||||
const loadSupport=useCallback(async()=>{
|
||||
setSupportLoading(true);setSupportError('');
|
||||
try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);setOptions(choices);setCatalog(source);}
|
||||
try{const [choices,source]=await Promise.all([api.options(),api.sourceColumnCatalog()]);if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);}
|
||||
catch(error){if(!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
|
||||
finally{setSupportLoading(false);}
|
||||
},[onUnauthorized]);
|
||||
@@ -52,23 +54,29 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const trendKey=JSON.stringify({query:trendQuery,revision});
|
||||
useEffect(()=>{if(!active||!current||!trendQuery)return;const controller=new AbortController();setTrendLoading(true);setTrendError('');void api.metrics(trendQuery,controller.signal).then(value=>{if(!controller.signal.aborted)setTrendResponse({key:trendKey,value});}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setTrendError(error instanceof Error?error.message:'趋势读取失败');}).finally(()=>{if(!controller.signal.aborted)setTrendLoading(false);});return()=>controller.abort();},[active,trendKey,!!current,onUnauthorized]);
|
||||
const visibleTrend=useMemo(()=>fullYearTrend(trendResponse?.key===trendKey?trendResponse.value.trend:[],applied?.year||year,trendGranularity),[trendResponse,trendKey,applied?.year,year,trendGranularity]);
|
||||
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;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 dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{setApplied(draft);setRevision(v=>v+1);};
|
||||
const displayedTrend=useRetainedResult(trendResponse?.key===trendKey?visibleTrend:null)||visibleTrend;
|
||||
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 dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);const submit=()=>{automaticPeriod.current=false;setApplied(draft);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 select=(name:string,value:string[],choices:string[],change:(v:string[])=>void)=><label className="query-field query-primary-field"><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(current?.rows||[],stage),[current,stage]);
|
||||
const summary=current?.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
|
||||
const displayedQuery = displayed?.query || applied;
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
|
||||
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
|
||||
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
|
||||
return <div className="query-page stage-product-page">
|
||||
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
|
||||
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}>
|
||||
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>setPeriod(v as PeriodKind)}/>
|
||||
<label className="query-field query-period-field"><span>年份</span><Select aria-label="年份" value={year} onChange={setYear} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={setMonth} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={setQuarter} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>{automaticPeriod.current=false;setPeriod(v as PeriodKind);}}/>
|
||||
<label className="query-field query-period-field"><span>年份</span><Select aria-label="年份" value={year} onChange={v=>{automaticPeriod.current=false;setYear(v);}} options={(options?.years?.length?options.years:[year]).map(v=>({label:`${v}年`,value:v}))}/></label>
|
||||
{period==='month'&&<label className="query-field query-period-field"><span>月份</span><Select aria-label="月份" value={month} onChange={v=>{automaticPeriod.current=false;setMonth(v);}} options={Array.from({length:12},(_,i)=>({label:`${i+1}月`,value:i+1}))}/></label>}
|
||||
{period==='quarter'&&<label className="query-field query-period-field"><span>季度</span><Select aria-label="季度" value={quarter} onChange={v=>{automaticPeriod.current=false;setQuarter(v);}} options={[1,2,3,4].map(v=>({label:`第${v}季度`,value:v}))}/></label>}
|
||||
{select('产业部',department,options?.departments||[],values=>{setDepartment(values);setGroup([]);setProduct([]);})}
|
||||
{select('业务分组',group,groups,values=>{setGroup(values);setProduct([]);})}
|
||||
{select('产品',product,products,setProduct)}
|
||||
@@ -86,18 +94,17 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
<MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
</section>
|
||||
<div className="query-quality-summary"><span>{current?`来源覆盖 ${current.coverage.sourceMonths.filter(m=>(stage==='black'?m.blackRows:m.brightRows)>0).length} 个月 · 参与计算 ${current.coverage.includedRows.toLocaleString()} 行`:loading?'正在查询…':'暂无统计结果'}</span><Button type="link" disabled={!current} onClick={()=>setBasisOpen(true)}>计算口径</Button></div>
|
||||
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={displayedTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}{trendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}</div><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
|
||||
<section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div>
|
||||
<Spin spinning={loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={period} month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></Spin>
|
||||
<SmoothTableFrame busy={loading||!current} blocked={!current||loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={displayedQuery?.month?'month':displayedQuery?.quarter?'quarter':'year'} month={displayedQuery?.month||month} quarter={displayedQuery?.quarter||quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></SmoothTableFrame>
|
||||
</section>
|
||||
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<Spin spinning={trendLoading}><div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={visibleTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={visibleTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} onMonth={selectTrendPeriod}/>}</div></Spin><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
|
||||
<section className="panel section-panel defects-panel">
|
||||
<section className="panel section-panel defects-panel" aria-busy={loading||!current}>
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
|
||||
<section className="defect-stage-column" aria-label={`${label}不良构成`}>
|
||||
<section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}>
|
||||
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
|
||||
{current?.defects[stage]?.length ? <DefectBreakdown items={current.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...current.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
{displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
</section>
|
||||
{current&&applied&&<DefectParetoPanel releaseId={current.release?.id} query={applied} onlyStage={stage} externalScrapWeight={stage==='black'?current.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
{displayed&&<DefectParetoPanel releaseId={displayed.data.release?.id} query={displayed.query} pending={!current||loading} refreshKey={revision} onlyStage={stage} externalScrapWeight={stage==='black'?displayed.data.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
</section></div>
|
||||
<Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal>
|
||||
{records&&<RecordsDrawer key={JSON.stringify(records)} open={recordVisible} row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>}
|
||||
|
||||
@@ -3,6 +3,18 @@ export function previousCompleteMonth(reference = new Date()): { year: number; m
|
||||
return { year: previous.getFullYear(), month: previous.getMonth() + 1 };
|
||||
}
|
||||
|
||||
export function defaultQueryMonth(options?: { periods?: string[]; latestDataPeriod?: { year?: number; month?: number } } | null, reference = new Date()): { year: number; month: number } {
|
||||
const previous = previousCompleteMonth(reference);
|
||||
const key = `${previous.year}-${String(previous.month).padStart(2, '0')}`;
|
||||
const latest = options?.latestDataPeriod;
|
||||
const latestKey = latest?.year && latest.month && latest.month >= 1 && latest.month <= 12
|
||||
? `${latest.year}-${String(latest.month).padStart(2, '0')}` : undefined;
|
||||
const previousMissing = Array.isArray(options?.periods)
|
||||
? !options.periods.includes(key) : latestKey != null && latestKey < key;
|
||||
// 只按已发布月份判断;筛选结果为空不会改动用户选定的月份。
|
||||
return previousMissing ? previousCompleteMonth(new Date(previous.year, previous.month - 1, 1)) : previous;
|
||||
}
|
||||
|
||||
export function previousCompleteQuarter(reference = new Date()): { year: number; quarter: number } {
|
||||
const firstMonthOfCurrentQuarter = Math.floor(reference.getMonth() / 3) * 3;
|
||||
const previousQuarterEnd = new Date(reference.getFullYear(), firstMonthOfCurrentQuarter, 0);
|
||||
|
||||
@@ -51,3 +51,6 @@
|
||||
.record-query-tools { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.record-query-tools > .ant-segmented { grid-column: 2; }
|
||||
}
|
||||
.smooth-table-frame { min-width: 0; overflow: clip; transition: height 520ms cubic-bezier(.22,.61,.36,1); }
|
||||
.animated-metric-text { font-variant-numeric: tabular-nums lining-nums; }
|
||||
@media (prefers-reduced-motion: reduce) { .smooth-table-frame { transition: none; } }
|
||||
|
||||
@@ -633,3 +633,24 @@ body { background: var(--background); }
|
||||
}
|
||||
|
||||
.query-quality-summary { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 14px; color: var(--muted-ink); font-size: var(--font-control); margin: 0 0 14px; }
|
||||
|
||||
/* 浏览器保留前后两帧连续交接;顶部与侧栏独立固定,不进行整页位移或缩放。 */
|
||||
:root { view-transition-name: root; }
|
||||
.sidebar { view-transition-name: workspace-sidebar; }
|
||||
.topbar { view-transition-name: workspace-header; }
|
||||
::view-transition { pointer-events: none; }
|
||||
::view-transition-group(root),
|
||||
::view-transition-group(workspace-sidebar),
|
||||
::view-transition-group(workspace-header) { animation: none; }
|
||||
::view-transition-old(root) { animation: workspace-page-out 280ms cubic-bezier(.22,.61,.36,1) both; }
|
||||
::view-transition-new(root) { animation: workspace-page-in 280ms cubic-bezier(.22,.61,.36,1) both; }
|
||||
::view-transition-old(root), ::view-transition-new(root) { mix-blend-mode: plus-lighter; }
|
||||
::view-transition-old(workspace-sidebar), ::view-transition-old(workspace-header) { display: none; }
|
||||
::view-transition-new(workspace-sidebar), ::view-transition-new(workspace-header) { animation: none; }
|
||||
@keyframes workspace-page-out { to { opacity: 0; } }
|
||||
@keyframes workspace-page-in { from { opacity: 0; } }
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
::view-transition-group(*) { animation: none !important; }
|
||||
::view-transition-old(root) { display: none; }
|
||||
::view-transition-new(root) { animation: none; }
|
||||
}
|
||||
|
||||
@@ -125,6 +125,8 @@ export interface ReleaseOption {
|
||||
|
||||
export interface OptionsResponse {
|
||||
years: (number | string)[];
|
||||
periods?: string[];
|
||||
latestDataPeriod?: { year?: number; month?: number };
|
||||
departments: string[];
|
||||
groups: string[];
|
||||
groupDepartments?: Record<string, string | null>;
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
type Transition = Pick<ViewTransition, 'ready' | 'finished' | 'skipTransition'>;
|
||||
type StartTransition = (update: () => Promise<void>) => Transition;
|
||||
|
||||
/** 每次导航都可打断;跳过旧动画时,旧回调也不能覆盖最后一次选择。 */
|
||||
export function createWorkspaceTransition(start?: StartTransition, reducedMotion: () => boolean = () => false, onBusy: (busy: boolean) => void = () => {}) {
|
||||
let sequence = 0;
|
||||
let running: Transition | undefined;
|
||||
let controller: AbortController | undefined;
|
||||
const cancel = () => {
|
||||
sequence++;
|
||||
controller?.abort();
|
||||
running?.skipTransition();
|
||||
running = undefined;
|
||||
onBusy(false);
|
||||
};
|
||||
return {
|
||||
cancel,
|
||||
run(update: (signal: AbortSignal) => void | Promise<void>) {
|
||||
cancel();
|
||||
const epoch = sequence;
|
||||
const request = new AbortController();
|
||||
controller = request;
|
||||
let committed = false;
|
||||
const apply = async () => {
|
||||
if (epoch !== sequence || request.signal.aborted) return;
|
||||
committed = true;
|
||||
await update(request.signal);
|
||||
};
|
||||
if (!start || reducedMotion()) { void apply(); return; }
|
||||
onBusy(true);
|
||||
try {
|
||||
const transition = start(apply);
|
||||
running = transition;
|
||||
// 重复点击、缩放及不支持的快照状态都可以正常跳过动画。
|
||||
void transition.ready.catch(() => {});
|
||||
const finish = () => { if (running === transition) { running = undefined; onBusy(false); } };
|
||||
void transition.finished.then(finish, finish);
|
||||
} catch {
|
||||
onBusy(false);
|
||||
if (!committed) void apply();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** 首次打开先准备目标内容;网络慢时有明确上限,连续导航会立即解除等待。 */
|
||||
export function waitForWorkspaceContent(getPage: () => Element | null, signal: AbortSignal, timeout = 900): Promise<void> {
|
||||
return new Promise(resolve => {
|
||||
let settled = false;
|
||||
let settleTimer: number | undefined;
|
||||
const finish = () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
observer.disconnect();
|
||||
window.clearTimeout(timer);
|
||||
window.clearTimeout(settleTimer);
|
||||
signal.removeEventListener('abort', finish);
|
||||
resolve();
|
||||
};
|
||||
const isReady = () => {
|
||||
const page = getPage();
|
||||
return page && !page.querySelector('.loading-panel, .query-table-content[aria-busy="true"], .metric-strip[aria-busy="true"], .trend-chart-shell[aria-busy="true"], .defect-pareto-section[aria-busy="true"]');
|
||||
};
|
||||
const check = () => {
|
||||
if (settled) return;
|
||||
if (signal.aborted) { finish(); return; }
|
||||
if (isReady()) {
|
||||
// 留出一次提交的时间,让图表初始化及后续查询状态先就位。
|
||||
if (settleTimer == null) settleTimer = window.setTimeout(() => {
|
||||
settleTimer = undefined;
|
||||
if (isReady()) finish();
|
||||
}, 32);
|
||||
} else {
|
||||
window.clearTimeout(settleTimer);
|
||||
settleTimer = undefined;
|
||||
}
|
||||
};
|
||||
const observer = new MutationObserver(check);
|
||||
const timer = window.setTimeout(finish, timeout);
|
||||
observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['aria-busy', 'hidden'] });
|
||||
signal.addEventListener('abort', finish, { once: true });
|
||||
check();
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user