import { useEffect, useMemo, useState } from 'react' import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom' import { clearToken } from '../api' import '../pages/wechat.css' type NavLeaf = { kind?: 'link'; to: string; end?: boolean; ico: string; label: string } type NavBranch = { kind: 'branch' id: string ico: string label: string /** 任一前缀命中则父级高亮并保持展开 */ match: string[] children: NavLeaf[] } type NavEntry = NavLeaf | NavBranch type NavGroup = { label: string; items: NavEntry[] } const NAV_GROUPS: NavGroup[] = [ { label: '总览', items: [{ to: '/wechat', end: true, ico: '◈', label: '运营概览' }], }, { label: '内容', items: [ { to: '/wechat/nav', ico: '🧭', label: '导航' }, { to: '/wechat/books/default', ico: '📕', label: '小册与试读%' }, { kind: 'branch', id: 'vip', ico: '👑', label: 'VIP', match: ['/wechat/vip', '/wechat/shop', '/wechat/memo'], children: [ { to: '/wechat/vip', end: true, ico: '⚙', label: '运营配置' }, { to: '/wechat/vip/ebooks', ico: '📖', label: '电子书' }, { to: '/wechat/vip/course', ico: '🎬', label: '视频课程' }, { to: '/wechat/shop', ico: '🛒', label: '电商' }, { to: '/wechat/memo', ico: '🏕️', label: '知识社群' }, ], }, ], }, { label: '运营', items: [ { to: '/wechat/users', ico: '👥', label: '读者' }, { to: '/wechat/orders', ico: '🧾', label: '订单' }, ], }, { label: '数据与发布', items: [ { to: '/wechat/events', ico: '📊', label: '埋点事件' }, { to: '/wechat/checklist', ico: '✓', label: '部署检查清单' }, ], }, ] function flattenLeaves(groups: NavGroup[]): NavLeaf[] { const out: NavLeaf[] = [] for (const g of groups) { for (const item of g.items) { if (item.kind === 'branch') out.push(...item.children) else out.push(item) } } return out } const FLAT_NAV = flattenLeaves(NAV_GROUPS) function titleFromPath(pathname: string) { const sorted = [...FLAT_NAV].sort((a, b) => b.to.length - a.to.length) const hit = sorted.find((n) => (n.end ? pathname === n.to : pathname.startsWith(n.to))) return hit?.label || '微信后台' } function isBranchActive(branch: NavBranch, pathname: string) { return branch.match.some( (m) => pathname === m || pathname.startsWith(`${m}/`), ) } /** 微信小程序后台壳层 — 仅 /wechat/*;VIP 二级菜单;移动端抽屉 */ export default function Layout() { const nav = useNavigate() const { pathname } = useLocation() const [drawerOpen, setDrawerOpen] = useState(false) const vipActive = useMemo( () => pathname === '/wechat/vip' || pathname.startsWith('/wechat/vip/') || pathname.startsWith('/wechat/shop') || pathname.startsWith('/wechat/memo'), [pathname], ) const [vipOpen, setVipOpen] = useState(() => vipActive) useEffect(() => { setDrawerOpen(false) }, [pathname]) useEffect(() => { if (vipActive) setVipOpen(true) }, [vipActive]) useEffect(() => { document.body.style.overflow = drawerOpen ? 'hidden' : '' return () => { document.body.style.overflow = '' } }, [drawerOpen]) function logout() { clearToken() nav('/login') } function renderEntry(item: NavEntry) { if (item.kind === 'branch') { const open = item.id === 'vip' ? vipOpen : false const active = isBranchActive(item, pathname) return (