优化:缓存查询与智能分析页面,修复组织下钻和草稿保留

This commit is contained in:
2026-10-23 16:06:59 +08:00
parent 6394e057bf
commit f14400bd60
9 changed files with 261 additions and 50 deletions
+97
View File
@@ -0,0 +1,97 @@
import { forwardRef, lazy, Suspense, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from 'react';
import { Alert, Button, Spin } from 'antd';
import { api } from './api';
import type { AuthUser, QueryParams } from './types';
import type { PageKey } from './QualityWorkspace';
import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache';
const QueryPage = lazy(() => import('./QueryPage'));
const ManagementPages = lazy(() => import('./ManagementPages'));
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product'];
const retained = (page: PageKey) => QUERY_PAGES.includes(page) || page === 'analysis';
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
type Entry = { initialSearch: string; search: string; key: number; scroll: number };
export type WorkspaceNavigation = { navigate: (page: PageKey, query?: QueryParams, resultRef?: ResultRef) => void; syncLocation: () => void };
function encode(value: unknown) {
const bytes = new TextEncoder().encode(JSON.stringify(value));
return btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join('')).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}
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 current = useRef(page), generation = useRef(0), key = useRef(0);
const revisions = useRef<{ authRevision: string; dataRevision: string } | null>(null);
const [refreshKey, setRefreshKey] = useState(0), [, render] = useState(0);
const [ready, setReady] = useState(false), [error, setError] = useState('');
const alive = useRef(true);
const validate = async (currentSelection = () => true) => {
const state = await api.workspaceState();
if (!alive.current || !currentSelection()) return false;
if (revisions.current && state.authRevision !== revisions.current.authRevision) {
// 权限改变后销毁旧缓存,服务端随后按最新身份重新查询。
const latest = await api.me();
if (!alive.current || !currentSelection()) return false;
onUserChange(latest); entries.current.clear();
}
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
revisions.current = state;
return true;
};
const remember = (updateSearch = true) => {
const entry = entries.current.get(current.current);
if (entry) { if (updateSearch) entry.search = location.search; entry.scroll = window.scrollY; }
};
const enter = async (next: PageKey, search: string, force = false, pop = false) => {
remember(!pop);
const selection = ++generation.current;
try {
if (!await validate(() => generation.current === selection) || generation.current !== selection) return;
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; setError(''); onPageChange(next); render(value => value + 1);
} catch (value) {
if (alive.current && generation.current === selection && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
}
};
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
if (next === 'imports') next = 'sources';
if (next === current.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);
void enter(next, query || resultRef || !cached ? `?${params}` : cached.search, Boolean(query || resultRef) || !retained(next));
};
useImperativeHandle(ref, () => ({ navigate, syncLocation: () => {
const next = new URLSearchParams(location.search).get('page') as PageKey || 'overall';
const entry = entries.current.get(next);
void enter(next, location.search, !entry || entry.search !== location.search, true);
} }));
useEffect(() => {
alive.current = true;
void validate().then(ok => { if (ok) setReady(true); }).catch(value => { if (alive.current && !onUnauthorized(value)) setError(String(value)); });
const invalidate = () => setRefreshKey(value => value + 1);
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
return () => { alive.current = false; generation.current++; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
}, []);
useLayoutEffect(() => {
if (!ready) return;
const frame = requestAnimationFrame(() => window.scrollTo(0, entries.current.get(page)?.scroll || 0));
return () => cancelAnimationFrame(frame);
}, [page, ready]);
if (error) return <Alert type="error" showIcon message="页面暂不可用" description={error} action={<Button onClick={() => location.reload()}>重新连接</Button>} />;
if (!ready) return <div className="loading-panel"><Spin />正在打开工作台…</div>;
return <>{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}>
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
<Suspense fallback={<div className="loading-panel"><Spin />正在打开页面…</div>}>
{QUERY_PAGES.includes(name) ? <QueryPage page={name} onUnauthorized={onUnauthorized} onNavigate={navigate} /> : <ManagementPages page={name} user={user} onUnauthorized={onUnauthorized} onNavigate={navigate} />}
</Suspense>
</PageCacheContext.Provider>
</div>;
})}</>;
});