This commit is contained in:
@@ -10,29 +10,20 @@ export interface ModuleConfig {
|
||||
component: ComponentType;
|
||||
}
|
||||
|
||||
/** path 到模块 id 的映射 */
|
||||
const PATH_MAP: Record<string, string> = {
|
||||
'/vehicle': 'assets',
|
||||
'/assets': 'assets',
|
||||
'/mileage': 'mileage',
|
||||
'/scheduling': 'scheduling',
|
||||
'/energy': 'energy',
|
||||
};
|
||||
/** hash 一级段(`#<id>` 或 `#<id>/<sub>` 都只取 id) */
|
||||
function getHashHead(): string {
|
||||
return window.location.hash.slice(1).split('/')[0];
|
||||
}
|
||||
|
||||
function getInitialModule(modules: ModuleConfig[]): string {
|
||||
// 优先看 hash
|
||||
const hash = window.location.hash.slice(1);
|
||||
if (modules.some((m) => m.id === hash)) return hash;
|
||||
// 再看 pathname
|
||||
const pathModule = PATH_MAP[window.location.pathname];
|
||||
if (pathModule && modules.some((m) => m.id === pathModule)) return pathModule;
|
||||
// 默认第一个
|
||||
const head = getHashHead();
|
||||
if (modules.some((m) => m.id === head)) return head;
|
||||
return modules[0]?.id ?? '';
|
||||
}
|
||||
|
||||
function getHashModule(modules: ModuleConfig[]): string {
|
||||
const hash = window.location.hash.slice(1);
|
||||
return modules.some((m) => m.id === hash) ? hash : '';
|
||||
const head = getHashHead();
|
||||
return modules.some((m) => m.id === head) ? head : '';
|
||||
}
|
||||
|
||||
export function Shell({ modules }: { modules: ModuleConfig[] }) {
|
||||
@@ -48,16 +39,17 @@ export function Shell({ modules }: { modules: ModuleConfig[] }) {
|
||||
}, [modules]);
|
||||
|
||||
useEffect(() => {
|
||||
// 同步 hash 到当前模块:使用 replaceState 避免产生多余的 history 记录,
|
||||
// 否则在小程序/webview 环境下首次进入需要点两次返回才能退出
|
||||
if (window.location.hash.slice(1) !== activeModule) {
|
||||
// 同步 hash 一段到当前模块:使用 replaceState 避免产生多余的 history 记录,
|
||||
// 否则在小程序/webview 环境下首次进入需要点两次返回才能退出。
|
||||
// 注意只比对一级段,避免把子模块写入的 `#<id>/<sub>` 二级段抹掉。
|
||||
if (getHashHead() !== activeModule) {
|
||||
const { pathname, search } = window.location;
|
||||
window.history.replaceState(null, '', `${pathname}${search}#${activeModule}`);
|
||||
}
|
||||
}, [activeModule]);
|
||||
|
||||
const switchModule = (id: string) => {
|
||||
if (window.location.hash.slice(1) === id) return;
|
||||
if (getHashHead() === id) return;
|
||||
const { pathname, search } = window.location;
|
||||
window.history.replaceState(null, '', `${pathname}${search}#${id}`);
|
||||
setActiveModule(id);
|
||||
|
||||
Reference in New Issue
Block a user