180 lines
12 KiB
TypeScript
180 lines
12 KiB
TypeScript
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, 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 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; 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));
|
|
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 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; 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('');
|
|
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 = (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;
|
|
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;
|
|
}
|
|
})();
|
|
validation.current = request;
|
|
void request.finally(() => { if (validation.current === request) validation.current = null; });
|
|
return request;
|
|
};
|
|
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 = (next: PageKey, search: string, force = false, pop = false) => {
|
|
remember(!pop);
|
|
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)!;
|
|
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(() => {
|
|
if (!pop) history.pushState({}, '', `${location.pathname}${entry.search}`);
|
|
current.current = next; onPageChange(next); render(value => value + 1);
|
|
});
|
|
window.scrollTo(0, entry.scroll);
|
|
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) => {
|
|
if (next === 'imports') next = 'sources';
|
|
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);
|
|
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;
|
|
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);
|
|
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(() => {
|
|
if (!ready) return;
|
|
const frame = requestAnimationFrame(() => window.scrollTo(0, entries.current.get(page)?.scroll || 0));
|
|
return () => cancelAnimationFrame(frame);
|
|
}, [page, ready, activeEntryKey]);
|
|
const connectionNotice = error && <Alert type="warning" showIcon message="页面状态暂未更新" description={error} action={<Button onClick={() => { void validate(); }}>重新连接</Button>} />;
|
|
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} inert={active && navigationBusy} style={!active ? { display: 'none' } : undefined}>
|
|
<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>
|
|
</PageCacheContext.Provider>
|
|
</div>;
|
|
})}</>;
|
|
});
|