Files
gofly-platform-services/zlt-web/react-web-next/src/layouts/BasicLayout.tsx
T

232 lines
8.0 KiB
TypeScript
Raw Normal View History

import React, { useEffect, useMemo, useState } from 'react';
import { Space, message, Avatar, Dropdown } from 'antd';
import {
LogoutOutlined,
UserOutlined,
SettingOutlined,
DashboardOutlined,
AppstoreOutlined,
FileTextOutlined,
TeamOutlined,
CloudServerOutlined,
BugOutlined,
SearchOutlined,
MessageOutlined,
FolderOutlined,
} from '@ant-design/icons';
import { Link, useLocation, history } from 'umi';
import ProLayout, { MenuDataItem } from '@ant-design/pro-layout';
import { fetchMenuData, outLogin } from '@/services/login';
2025-10-01 03:51:53 +08:00
import { clearTenantCache } from '@/utils/tenantCache';
import { useTheme } from '@/theme';
import { ThemeSwitch } from '@/components/ui';
type MenuNode = {
id?: number | string;
name?: string;
url?: string;
path?: string;
css?: string;
children?: MenuNode[];
subMenus?: MenuNode[];
};
const BasicLayout: React.FC = (props: any) => {
const location = useLocation();
const { mode, toggle } = useTheme();
const [menus, setMenus] = useState<MenuNode[]>([]);
const [loaded, setLoaded] = useState(false);
useEffect(() => {
let mounted = true;
(async () => {
try {
const list = await fetchMenuData();
if (mounted) {
setMenus(Array.isArray(list) ? (list as MenuNode[]) : []);
setLoaded(true);
}
} catch {
if (mounted) setLoaded(true);
}
})();
return () => { mounted = false; };
}, []);
const menuDataRender = useMemo(() => {
2025-09-26 18:42:41 +08:00
const mapPath = (m: MenuNode, childrenLen: number): string | undefined => {
const cand = (m.path || m.url || '').trim();
if (!cand) return undefined;
const lower = cand.toLowerCase();
2025-10-01 03:51:53 +08:00
if (lower.startsWith('http')) return cand; // 澶栭摼
if (lower.endsWith('.html')) return cand.startsWith('/') ? cand : `/${cand}`; // 闈欐€佽矾鐢? if (lower === '/welcome' || lower === 'welcome') return '/welcome';
// 鍏煎鍚庣鑿滃崟鏈甫 .html 鐨勫彾瀛愯矾鐢憋紝渚嬪 /system/tenant => /system/tenant.html
2025-09-26 18:42:41 +08:00
const ensureSlash = cand.startsWith('/') ? cand : `/${cand}`;
const parts = ensureSlash.split('/').filter(Boolean);
if (childrenLen === 0 && parts.length >= 2) {
return `${ensureSlash}.html`;
}
2025-10-01 03:51:53 +08:00
return undefined; // 浣滀负鍒嗙粍
};
const getIcon = (p?: string) => {
const s = (p || '').toLowerCase();
if (s.includes('system')) return <SettingOutlined />;
if (s.includes('order')) return <AppstoreOutlined />;
if (s.includes('device')) return <CloudServerOutlined />;
if (s.includes('log')) return <BugOutlined />;
if (s.includes('search')) return <SearchOutlined />;
if (s.includes('message')) return <MessageOutlined />;
if (s.includes('file')) return <FolderOutlined />;
if (s.includes('user')) return <TeamOutlined />;
if (s.includes('welcome')) return <DashboardOutlined />;
return <FileTextOutlined />;
};
const normalize = (menu: MenuNode, index: number, parentKey = ''): MenuDataItem => {
const stableKey =
menu.id ||
(menu.url && menu.url !== 'javascript:;' ? menu.url : '') ||
(menu.path && menu.path !== 'javascript:;' ? menu.path : '') ||
`${parentKey}-${menu.name}-${index}`;
const keyStr = String(stableKey);
const childrenList: MenuNode[] = (menu.children && menu.children.length ? menu.children : (menu.subMenus || [])) || [];
2025-09-26 18:42:41 +08:00
const path = mapPath(menu, childrenList.length);
const item: MenuDataItem = {
key: keyStr,
2025-10-01 03:51:53 +08:00
name: menu.name || `鑿滃崟${index + 1}`,
path,
icon: getIcon(path),
children: childrenList.map((child: MenuNode, i: number) => normalize(child, i, keyStr)),
};
return item;
};
if (!loaded) return [];
2025-10-01 03:51:53 +08:00
const list = menus && menus.length ? menus : [{ name: '首页', url: '/welcome', id: 'welcome-default' }];
const rendered = list.map((m, i) => normalize(m, i));
const hasHome = rendered.some((r) => r.path === '/welcome');
if (!hasHome) {
rendered.unshift({ key: 'welcome-fixed', name: '首页', path: '/welcome', icon: <DashboardOutlined /> });
}
return rendered;
}, [menus, mode, loaded]);
const rightContentRender = () => (
<Space size="middle">
{/*<Link to="/welcome" style={{ color: 'var(--text-primary)' }}>首页</Link>*/}
<ThemeSwitch mode={mode} onToggle={toggle} />
<Dropdown
menu={{
items: [
{ key: 'profile', icon: <UserOutlined />, label: '个人中心' },
2025-10-01 03:51:53 +08:00
{ key: 'settings', icon: <SettingOutlined />, label: '设置' },
{ type: 'divider' as any },
{
key: 'logout',
icon: <LogoutOutlined />,
label: '退出登录',
onClick: async () => {
try { await outLogin(); } catch {}
try {
sessionStorage.removeItem('access_token');
sessionStorage.removeItem('current_user');
2025-10-01 03:51:53 +08:00
clearTenantCache();
} catch {}
message.success('已退出登录');
history.push('/user/login');
},
},
],
}}
placement="bottomRight"
>
<div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
<Avatar size="small" icon={<UserOutlined />} />
<span style={{ color: 'var(--text-primary)' }}>管理员</span>
</div>
</Dropdown>
</Space>
);
return (
<div className="page-enter">
<ProLayout
key="go-fly-pro-layout"
title="Go-Fly Admin"
logo={false}
location={location}
route={{ routes: menuDataRender }}
navTheme={mode === 'dark' ? 'realDark' : 'light'}
colorPrimary="var(--primary-color)"
layout="mix"
contentWidth="Fluid"
fixedHeader
fixSiderbar
splitMenus={false}
siderWidth={256}
rightContentRender={rightContentRender}
menuDataRender={() => menuDataRender}
menuItemRender={(menuItemProps, defaultDom) => {
if (menuItemProps.isUrl || !menuItemProps.path) return defaultDom;
const path = String(menuItemProps.path);
if (path === 'javascript:;' || path === '#' || path.startsWith('menu-item-')) {
return <span className="menu-enter">{defaultDom}</span>;
}
return (
<Link to={path} className="menu-enter">
{defaultDom}
</Link>
);
}}
headerTitleRender={(logo, title) => (
2025-10-01 03:51:53 +08:00
<Link to="/welcome" style={{ textDecoration: 'none' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, fontWeight: 600 }}>
<div
style={{
width: 32,
height: 32,
background: 'var(--tech-gradient)',
borderRadius: '8px',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: 'var(--logo-initial-color, #0f5132)',
}}
>
G
</div>
<span style={{ fontSize: 18, color: 'var(--text-primary)', fontWeight: 700 }}>{title}</span>
</div>
2025-10-01 03:51:53 +08:00
</Link>
)}
token={{
sider: {
colorMenuBackground: 'var(--sider-bg)',
colorBgMenuItemSelected: 'var(--primary-color)',
colorTextMenuSelected: '#ffffff',
colorTextMenu: 'var(--text-secondary)',
colorBgMenuItemHover: 'var(--bg-glass)',
},
header: {
colorBgHeader: 'var(--header-bg)',
colorHeaderTitle: 'var(--text-primary)',
colorTextRightActionsItem: 'var(--text-secondary)',
},
}}
>
<div className="layout-content-wrapper" style={{ margin: 0, borderRadius: 0, minHeight: '100%' }}>
{props.children}
</div>
</ProLayout>
</div>
);
};
export default BasicLayout;
2025-10-01 03:51:53 +08:00