统一全系统资源加载、轻量趋势与缓存恢复
This commit is contained in:
@@ -1,19 +1,29 @@
|
||||
import { readQueryLocation } from './queryLoadingScope';
|
||||
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';
|
||||
import { api, configureRequestScope, resetRequestScope } from './api';
|
||||
import { pageUsesResources } from './resourceInvalidation';
|
||||
import type { AuthUser, QueryParams } from './types';
|
||||
import type { PageKey } from './QualityWorkspace';
|
||||
import { PageCacheContext, WORKSPACE_INVALIDATED } from './pageCache';
|
||||
|
||||
const QueryPage = lazy(() => import('./QueryPage'));
|
||||
const StageProductPage = lazy(() => import('./StageProductPage'));
|
||||
const ManagementPages = lazy(() => import('./ManagementPages'));
|
||||
const loadQueryPage = () => import('./QueryPage');
|
||||
const loadStageProductPage = () => import('./StageProductPage');
|
||||
const loadManagementPages = () => import('./ManagementPages');
|
||||
const QueryPage = lazy(loadQueryPage);
|
||||
const StageProductPage = lazy(loadStageProductPage);
|
||||
const ManagementPages = lazy(loadManagementPages);
|
||||
|
||||
export function preloadWorkspacePage(page: PageKey): Promise<unknown> {
|
||||
return page === 'blackProduct' || page === 'brightProduct' ? loadStageProductPage()
|
||||
: QUERY_PAGES.includes(page) ? loadQueryPage() : loadManagementPages();
|
||||
}
|
||||
const QUERY_PAGES: PageKey[] = ['overall', 'department', 'group', 'product', 'blackProduct', 'brightProduct'];
|
||||
const retained = (_page: PageKey) => true;
|
||||
type ResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number };
|
||||
type Entry = { initialSearch: string; search: string; key: number; scroll: number; revision?: 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));
|
||||
@@ -23,10 +33,12 @@ function encode(value: unknown) {
|
||||
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 userRef = useRef(user);
|
||||
userRef.current = user;
|
||||
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 revisions = useRef<{ authRevision: string; dataRevision: string; currentReleaseId: string | null } | 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('');
|
||||
@@ -38,28 +50,47 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
() => window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
busy => { if (alive.current) setNavigationBusy(busy); },
|
||||
);
|
||||
const validate = () => {
|
||||
const validate = (warmVisibleOptions = false) => {
|
||||
if (validation.current) return validation.current;
|
||||
const epoch = generation.current;
|
||||
const request = (async () => {
|
||||
try {
|
||||
const state = await api.workspaceState();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
if (revisions.current && state.authRevision !== revisions.current.authRevision) {
|
||||
configureRequestScope({ userId: userRef.current.id, ...state });
|
||||
if ((revisions.current && state.authRevision !== revisions.current.authRevision) || entries.current.size === 0) {
|
||||
// 已知授权变化时立即撤下旧结果,不能等待身份读取成功才清除。
|
||||
setReady(false);
|
||||
entries.current.clear();
|
||||
render(value => value + 1);
|
||||
const latest = await api.me();
|
||||
if (!alive.current || generation.current !== epoch) return false;
|
||||
// 权限改变时清除全部旧缓存,重建此刻正在查看的页面;校验不负责切换路由。
|
||||
transitions.current?.cancel(); requested.current = current.current;
|
||||
userRef.current = latest;
|
||||
configureRequestScope({ userId: latest.id, ...state });
|
||||
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);
|
||||
}
|
||||
if (revisions.current && state.dataRevision !== revisions.current.dataRevision) setRefreshKey(value => value + 1);
|
||||
revisions.current = state;
|
||||
render(value => value + 1);
|
||||
setError('');
|
||||
// The visible query needs these options; start their shared read before its code mounts.
|
||||
if (warmVisibleOptions && QUERY_PAGES.includes(requested.current)) {
|
||||
void api.options().catch(() => {});
|
||||
if (requested.current === 'blackProduct' || requested.current === 'brightProduct') {
|
||||
const explicitRelease = readQueryLocation(entries.current.get(requested.current)?.initialSearch || '').releaseId;
|
||||
void api.sourceColumnCatalog(explicitRelease || state.currentReleaseId || undefined).catch(() => {});
|
||||
}
|
||||
}
|
||||
setReady(true);
|
||||
return true;
|
||||
} catch (value) {
|
||||
if (alive.current && generation.current === epoch && value && typeof value === 'object' && 'status' in value && value.status === 403) {
|
||||
setReady(false); entries.current.clear(); resetRequestScope();
|
||||
}
|
||||
if (alive.current && generation.current === epoch && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '页面状态校验失败,请重试');
|
||||
return false;
|
||||
}
|
||||
@@ -79,6 +110,11 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
const entry = entries.current.get(next)!;
|
||||
requested.current = next;
|
||||
transitions.current!.run(async signal => {
|
||||
// 先核实权限与版本,再让已保留页面重新订阅,避免旧版本内容先闪出。
|
||||
if (!await validate(true) || signal.aborted) {
|
||||
if (!signal.aborted && requested.current === next) requested.current = current.current;
|
||||
return;
|
||||
}
|
||||
if (!alive.current || entries.current.get(next) !== entry) return;
|
||||
// 与浏览器快照同步提交页面及滚动位置,避免转场结束后再补一次定位。
|
||||
flushSync(() => {
|
||||
@@ -86,8 +122,8 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
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);
|
||||
if (!signal.aborted && current.current === next && entries.current.get(next) === entry) window.scrollTo(0, entry.scroll);
|
||||
});
|
||||
};
|
||||
const navigate = (next: PageKey, query?: QueryParams, resultRef?: ResultRef) => {
|
||||
@@ -105,10 +141,22 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
} }));
|
||||
useEffect(() => {
|
||||
alive.current = true;
|
||||
void validate();
|
||||
const invalidate = () => setRefreshKey(value => value + 1);
|
||||
configureRequestScope({ userId: userRef.current.id, authRevision: null, dataRevision: null, currentReleaseId: null });
|
||||
void validate(true);
|
||||
const invalidate = (event: Event) => {
|
||||
const resources = (event as CustomEvent<{ resources?: string[] }>).detail?.resources;
|
||||
for (const [name, entry] of entries.current) {
|
||||
if (pageUsesResources(name, resources)) entry.revision = (entry.revision || 0) + 1;
|
||||
}
|
||||
render(value => value + 1);
|
||||
void validate();
|
||||
};
|
||||
const foreground = () => { if (document.visibilityState === 'visible') void validate(); };
|
||||
window.addEventListener(WORKSPACE_INVALIDATED, invalidate);
|
||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); };
|
||||
window.addEventListener('quality-permission-recheck', foreground);
|
||||
window.addEventListener('focus', foreground);
|
||||
document.addEventListener('visibilitychange', foreground);
|
||||
return () => { alive.current = false; transitions.current?.cancel(); generation.current++; validation.current = null; resetRequestScope(); window.removeEventListener(WORKSPACE_INVALIDATED, invalidate); window.removeEventListener('quality-permission-recheck', foreground); window.removeEventListener('focus', foreground); document.removeEventListener('visibilitychange', foreground); };
|
||||
}, []);
|
||||
const activeEntryKey = entries.current.get(page)?.key;
|
||||
useLayoutEffect(() => {
|
||||
@@ -121,7 +169,7 @@ export const CachedWorkspacePages = forwardRef<WorkspaceNavigation, {
|
||||
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} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey, onLocationChange: search => { entry.search = search; } }}>
|
||||
<PageCacheContext.Provider value={{ active, initialSearch: entry.initialSearch, refreshKey: refreshKey + (entry.revision || 0), currentReleaseId: revisions.current?.currentReleaseId, authRevision: revisions.current?.authRevision, dataRevision: revisions.current?.dataRevision, 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} />}
|
||||
</Suspense>
|
||||
|
||||
Reference in New Issue
Block a user