BasicLayout.tsx
12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import { Layout, Menu, Avatar, Dropdown, Button, Breadcrumb } from 'antd';
import { Suspense, useEffect, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
DashboardOutlined,
ShopOutlined,
UploadOutlined,
LogoutOutlined,
UserOutlined,
TeamOutlined,
AuditOutlined,
AppstoreOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
} from '@ant-design/icons';
import { useAccess, buildMenus, type MenuGroupDef } from '@/access';
import { useAppStore } from '@/store/useAppStore';
import { menu as menuApi } from '@/api';
import { logoutEverything } from '../subapp-lifecycle';
import { Logo } from '@/components/Logo';
import { Skeleton } from '@uj/ui';
import menuJson from '@/config/menu.json';
import { roleLabels } from '@/access';
import type { MenuProps } from 'antd';
const { Header, Sider, Content } = Layout;
/** antd Menu 的单条目类型:MenuProps['items'] 联合里的成员(普通项 / 分组 / 分割线…) */
type MenuItemType = NonNullable<MenuProps['items']>[number];
/* ---------- 菜单数据:以后端 /system/menu/tree/current 为准,menu.json 仅作接口未就绪时的兜底 ---------- */
// 前端专属菜单:后端菜单树不下发「工作台」(它是所有角色的落地页,不该被权限挡),
// 故由前端固定拼在最前。其余菜单的名称/分组/顺序/可见性全部由后端树决定,
// path 与 icon 均由后端下发(icon 为 null 时兜底默认图标),前端不再做映射。
const FRONTEND_ONLY_GROUPS: MenuGroupDef[] = [
{
group: '工作台',
// 无标题组:菜单项平铺到顶层,不挂「工作台」标题
hideTitle: true,
children: [
{ path: '/dashboard', label: '工作台', icon: 'DashboardOutlined', resource: 'dashboard' },
],
},
];
// 不在侧边栏菜单里的页面(由右上角头像下拉等方式进入):不参与菜单高亮,页题在此登记
const EXTRA_TITLES: Record<string, string> = {
'/profile': '个人资料',
};
// 图标注册表:菜单数据只存图标名,渲染时查表(新增图标在这里登记即可)
const iconMap: Record<string, React.ReactNode> = {
DashboardOutlined: <DashboardOutlined />,
ShopOutlined: <ShopOutlined />,
UploadOutlined: <UploadOutlined />,
TeamOutlined: <TeamOutlined />,
AuditOutlined: <AuditOutlined />,
UserOutlined: <UserOutlined />,
};
/** 后端未下发图标(icon 为 null)或图标名未登记时的兜底图标 */
const DEFAULT_MENU_ICON: React.ReactNode = <AppstoreOutlined />;
// 后端下发的 icon 是「antd 图标名字符串」,这里查表换成 React 节点。
// 未登记的图标名会静默回落默认图标 —— 这正是之前「菜单全是同一个图标」排查起来很痛苦的原因,
// 故开发环境对未知图标名告警一次(同名只报一次,避免菜单每项刷屏)。
const warnedIcons = new Set<string>();
function resolveIcon(name: string | null | undefined): React.ReactNode {
const hit = name ? iconMap[name] : undefined;
if (hit) return hit;
if (name && import.meta.env.DEV && !warnedIcons.has(name)) {
warnedIcons.add(name);
console.warn(
`[menu] 图标「${name}」未在 src/layouts/BasicLayout.tsx 的 iconMap 中登记,已回落默认图标。` +
`请在 iconMap 补一行,或让后端改发已支持的值。`,
);
}
return DEFAULT_MENU_ICON;
}
// 兜底菜单:接口失败/尚未返回时使用(与 src/config/menu.json 对应)
const fallbackGroups: MenuGroupDef[] = (() => {
const raw = (menuJson as { menus?: unknown }).menus;
if (!Array.isArray(raw)) {
throw new Error('[menu] menu.json 的 menus 必须是数组');
}
return raw as MenuGroupDef[];
})();
/**
* 权限资源 → 页面 path(来自兜底菜单,即前端真正实现的页面清单)。
* buildMenus 只在后端把多个页面节点配成同一个 route 时才用它兜底;正常数据不参与。
*/
const PATH_BY_RESOURCE = new Map<string, string>();
fallbackGroups.forEach((g) =>
g.children.forEach((m) => {
if (m.resource) PATH_BY_RESOURCE.set(m.resource, m.path);
}),
);
export default function BasicLayout() {
const navigate = useNavigate();
const location = useLocation();
const { can, role, roleCodes, points } = useAccess();
const { collapsed, toggleCollapsed, currentUser, loggedIn } = useAppStore();
// 后端菜单树:登录后拉取;接口失败则回落 menu.json 兜底(remoteGroups 保持 null)
const [remoteGroups, setRemoteGroups] = useState<MenuGroupDef[] | null>(null);
useEffect(() => {
if (!loggedIn) return;
let alive = true;
menuApi
.tree()
.then((tree) => {
if (alive) setRemoteGroups(buildMenus(tree, points, PATH_BY_RESOURCE));
})
.catch(() => {
// 接口未就绪/令牌失效:不阻断,走本地兜底菜单
if (alive) setRemoteGroups(null);
});
return () => {
alive = false;
};
}, [loggedIn, points]);
// 后端树为空(接口未就绪或该账号无任何菜单)时走兜底,避免侧边栏整组消失
const groups: MenuGroupDef[] = remoteGroups?.length
? [...FRONTEND_ONLY_GROUPS, ...remoteGroups]
: fallbackGroups;
// -> antd Menu items(后端树已在 buildMenus 内与 permCodes 取过交集;兜底菜单按权限过滤)
// hideTitle 的分组不生成 type:'group',改由 children 平铺到当前层级——
// 这样是真没有标题节点,而不是用 CSS 把标题藏起来(藏起来会留下一行空白占位)。
const items: MenuItemType[] = groups.flatMap<MenuItemType>((g) => {
const children = g.children
.filter((m) => !m.resource || can(m.resource))
.map((m) => ({
key: m.path,
icon: resolveIcon(m.icon),
label: m.label,
}));
return g.hideTitle ? children : [{ type: 'group' as const, label: g.group, children }];
});
const flat = groups.flatMap((g) => g.children);
// 非菜单页面(如 /profile)不匹配任何菜单项:菜单不高亮,页题走 EXTRA_TITLES。
// 用【最长前缀 + 路径段边界】匹配:精确命中优先,其次取最长的祖先路径。
// 不能只用 startsWith 取首个命中——若将来出现 /store 与 /store/listing 这类互为前缀的路由,会错配到短的那一档。
const selectedKey = (() => {
const p = location.pathname;
let best = '';
for (const m of flat) {
if (p === m.path) return m.path;
if (p.startsWith(`${m.path}/`) && m.path.length > best.length) best = m.path;
}
return best;
})();
const current = flat.find((m) => m.path === selectedKey);
const currentGroup = groups.find((g) => g.children.some((m) => m.path === selectedKey));
// 面包屑:分组 > 当前页;分组名与页题同名(如「工作台」)时只留一级,避免重复。
// 非菜单页(/profile)无分组,只显示 EXTRA_TITLES 登记的页题。
const crumbTitles = [
...(currentGroup && currentGroup.group !== current?.label ? [currentGroup.group] : []),
...(current?.label ? [current.label] : []),
];
const fallbackTitle = EXTRA_TITLES[location.pathname];
const crumbs = crumbTitles.length ? crumbTitles : fallbackTitle ? [fallbackTitle] : [];
const crumbItems = crumbs.map((t, i) => ({
key: String(i),
title:
i === crumbs.length - 1 ? (
<span className="uj-crumb-current">{t}</span>
) : (
<span className="uj-crumb-parent">{t}</span>
),
}));
// wujie:登出必须同时销毁所有子应用实例。只清本地令牌的话,重新登录时
// startApp(同名 + alive) 会复用带着上一个账号数据的 iframe(QueryClient 缓存、
// 权限点、会话派生状态全是旧的)。顺序与广播逻辑收口在 subapp-lifecycle.ts。
const onLogout = () => logoutEverything(navigate);
return (
<Layout style={{ height: '100vh', overflow: 'hidden' }}>
<Sider
collapsed={collapsed}
trigger={null}
width={232}
collapsedWidth={68}
className="uj-sider"
>
{/* 品牌区 */}
<div className={`uj-sider-brand${collapsed ? ' is-collapsed' : ''}`}>
<Logo size={34} />
{!collapsed && (
<div className="uj-sider-brand-text">
<span className="t">优加门店上架</span>
<span className="s">Store Launch Platform</span>
</div>
)}
</div>
{/* 菜单区 */}
<div className="uj-sider-menu">
<Menu
theme="dark"
mode="inline"
className="uj-menu"
selectedKeys={selectedKey ? [selectedKey] : []}
items={items}
onClick={({ key }) => navigate(key)}
/>
</div>
</Sider>
<Layout style={{ minWidth: 0 }}>
<Header className="uj-header">
{/* 左:折叠 + 面包屑(分组 > 当前页) */}
<div className="uj-header-left">
<Button
type="text"
aria-label="切换菜单"
icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
onClick={toggleCollapsed}
className="uj-header-fold"
/>
{crumbItems.length > 0 && <Breadcrumb className="uj-header-crumb" items={crumbItems} />}
</div>
{/* 中:全局搜索 */}
<div className="uj-header-search">
{/* <Input
prefix={<SearchOutlined style={{ color: '#8A94A6' }} />}
placeholder="搜索门店 / 任务…"
variant="borderless"
allowClear
/>
<span className="uj-header-search-kbd">⌘K</span> */}
</div>
{/* 右:通知 / 帮助 / 用户 */}
<div className="uj-header-right">
{/* <Badge dot>
<Button
type="text"
aria-label="通知"
icon={<BellOutlined />}
className="uj-header-icon-btn"
/>
</Badge>
<Tooltip title="帮助中心">
<Button
type="text"
aria-label="帮助"
icon={<QuestionCircleOutlined />}
className="uj-header-icon-btn"
/>
</Tooltip> */}
<span className="uj-header-divider" />
<Dropdown
placement="bottomRight"
menu={{
items: [
{
key: 'profile',
icon: <UserOutlined />,
label: '个人资料',
onClick: () => navigate('/profile'),
},
{ type: 'divider' },
{
key: 'logout',
icon: <LogoutOutlined />,
label: '退出登录',
onClick: onLogout,
},
],
}}
>
<button type="button" className="uj-header-user">
<Avatar
size={32}
style={{ background: 'linear-gradient(135deg,#2B5CE6,#5B8DEF)' }}
icon={<UserOutlined />}
/>
<div className="uj-header-user-text">
<span className="n">{currentUser.name}</span>
<span className="r">
{roleCodes.length ? roleCodes.join(' / ') : roleLabels[role]}
</span>
</div>
</button>
</Dropdown>
</div>
</Header>
{/* 子应用列表页把滚动收在表体里(.uj-page--fill 定高),这里保留 auto
只服务主壳自己的长页面(工作台 / 个人资料);两层滚动不会同时出现。 */}
<Content
style={{
flex: 1,
minHeight: 0,
overflow: 'auto',
background: 'var(--uj-bg)',
padding: 24,
display: 'flex',
flexDirection: 'column',
}}
>
<Suspense fallback={<Skeleton variant="default" />}>
<Outlet />
</Suspense>
</Content>
</Layout>
</Layout>
);
}