Files
SupplierSystem/src/components/Layout.tsx
T
Ubuntu deb3e72750
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s
chore: 以 AI 生鲜配送系统 当前版本作为 SupplierSystem 起点
来源仓库:jxc/ai-fresh-delivery
来源提交:f0b1a180e2deb7e4673b9d1c8542619f7bc0f73d
快照树:  09f679334ff38f0ff25e907961c94a8223bcaedd(与来源 HEAD 工作树逐字节一致,3801 个文件)

按约定本仓库不带任何历史提交:来源仓库的历史中含真实凭据
(生产 SSH 私钥 deploy/id_rsa_tencent、server/.env、.env.tencent/.env.production/.env.gitea、
deploy/小程序AppSecret.txt,其中 MP_APPSECRET / S3 AccessKey 经哈希比对与线上同值),
整包推送会把这些凭据永久带入本仓库,故只取「当前版本」的单提交快照。
供应商系统后续开发自本提交开始。
2026-10-08 17:35:43 +08:00

462 lines
20 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { Outlet, NavLink, useLocation } from 'react-router-dom';
import {
PanelLeftOpen,
Package,
ChevronRight,
Menu,
} from 'lucide-react';
import { useAuth } from '../hooks/useAuth';
import { useOperatingBranch } from '../hooks/useOperatingBranch';
import { useMenuLayout } from '../hooks/useMenuLayout';
import { supabase } from '../supabase/client';
import { NotificationBell } from './NotificationBell';
import { OrderEntryIntakeFab } from './OrderEntryIntakeFab';
import { UserAccountMenu } from './UserAccountMenu';
import { MenuNavIcon } from './MenuNavIcon';
import { ThemeSwitcher } from './ThemeSwitcher';
import { notify } from '../utils/notify';
import type { RuntimeMenuItem } from '../utils/menuLayout';
import { filterRuntimeMenuByAccess } from '../utils/menuAccessFilter';
import { useRoleLabels } from '../hooks/useRoleLabels';
import { isPlatformBranchCode, resolveOperatingBranchCode } from '../utils/platformBranch';
import {
collectMenuLeafPaths,
findActiveMenuChild,
isActiveInMenuGroup,
isMenuChildActive,
isStandaloneMenuActive,
shouldExpandMenuGroup,
} from '../utils/sidebarMenuMatch';
import { useI18n } from '../i18n/I18nProvider';
import { formatHeaderDate, formatHeaderTime } from '../i18n/format';
import { translateRuntimeMenuTree } from '../i18n/translateMenu';
/** 侧栏二级菜单展开高度(含间距),避免固定 500px 截断长列表 */
function getSubmenuMaxHeight(childCount: number, expanded: boolean): string {
if (!expanded || childCount <= 0) return '0px';
const rowHeight = 38;
return `${childCount * rowHeight + 12}px`;
}
const COLLAPSED_GROUPS_STORAGE_KEY = 'sidebar-collapsed-menu-groups';
function readCollapsedMenuGroups(): Set<string> {
if (typeof window === 'undefined') return new Set();
try {
const raw = sessionStorage.getItem(COLLAPSED_GROUPS_STORAGE_KEY);
if (!raw) return new Set();
const parsed = JSON.parse(raw);
return new Set(Array.isArray(parsed) ? parsed.filter((v) => typeof v === 'string') : []);
} catch {
return new Set();
}
}
function writeCollapsedMenuGroups(groups: Set<string>) {
if (typeof window === 'undefined') return;
sessionStorage.setItem(COLLAPSED_GROUPS_STORAGE_KEY, JSON.stringify([...groups]));
}
export const Layout: React.FC = () => {
const { profile, hasPermission, hasRole } = useAuth();
const { t, locale } = useI18n();
// 角色标签统一口径(含自建角色),与账号菜单/操作日志/角色权限页一致
const { roleLabel: resolveRoleLabel } = useRoleLabels();
const { operatingBranchCode, setOperatingBranch } = useOperatingBranch();
const { menuItems, loading: menuLoading } = useMenuLayout();
const [sidebarOpen, setSidebarOpen] = useState(true);
/** 小屏抽屉式侧栏开关(lg 以下生效) */
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [expandedMenus, setExpandedMenus] = useState<string[]>([]);
/** 用户手动折叠的菜单组(点击分组标题收起),跨路由保持 */
const [userCollapsedGroups, setUserCollapsedGroups] = useState<Set<string>>(
() => readCollapsedMenuGroups()
);
const [branchOptions, setBranchOptions] = useState<Array<{ branch_code: string; branch_name: string }>>([]);
const [currentTime, setCurrentTime] = useState(() => new Date());
const location = useLocation();
const isSuperAdmin = hasRole('super_admin');
const outletKey = isSuperAdmin
? (operatingBranchCode || profile?.branch_code || 'no-branch')
: (profile?.branch_code || 'default');
useEffect(() => {
const timer = window.setInterval(() => setCurrentTime(new Date()), 30_000);
return () => window.clearInterval(timer);
}, []);
const persistCollapsedGroups = useCallback((groups: Set<string>) => {
writeCollapsedMenuGroups(groups);
}, []);
const markGroupCollapsed = useCallback((path: string) => {
setUserCollapsedGroups((prev) => {
if (prev.has(path)) return prev;
const next = new Set(prev).add(path);
persistCollapsedGroups(next);
return next;
});
}, [persistCollapsedGroups]);
const markGroupExpanded = useCallback((path: string) => {
setUserCollapsedGroups((prev) => {
if (!prev.has(path)) return prev;
const next = new Set(prev);
next.delete(path);
persistCollapsedGroups(next);
return next;
});
}, [persistCollapsedGroups]);
const toggleMenu = (path: string, currentlyOpen: boolean) => {
if (currentlyOpen) {
setExpandedMenus((prev) => prev.filter((p) => p !== path));
markGroupCollapsed(path);
return;
}
setExpandedMenus((prev) => (prev.includes(path) ? prev : [...prev, path]));
markGroupExpanded(path);
};
const isMenuExpanded = (path: string) => expandedMenus.includes(path);
const filterMenuItems = useCallback(
(items: RuntimeMenuItem[]) => filterRuntimeMenuByAccess(items, hasPermission, hasRole),
[hasPermission, hasRole]
);
const visibleMenuItems = useMemo(
() => translateRuntimeMenuTree(filterMenuItems(menuItems), t, locale),
[menuItems, filterMenuItems, t, locale]
);
const allMenuLeafPaths = useMemo(
() => collectMenuLeafPaths(visibleMenuItems),
[visibleMenuItems]
);
useEffect(() => {
setMobileSidebarOpen(false);
}, [location.pathname]);
const prevPathnameRef = useRef(location.pathname);
const isInitialNavEffectRef = useRef(true);
useEffect(() => {
if (menuLoading) return;
const shouldResetCollapsed =
isInitialNavEffectRef.current || prevPathnameRef.current !== location.pathname;
isInitialNavEffectRef.current = false;
prevPathnameRef.current = location.pathname;
if (!shouldResetCollapsed) return;
const activeGroupPaths = visibleMenuItems
.filter(
(item) =>
Boolean(item.children?.length) &&
findActiveMenuChild(location.pathname, item.children!, allMenuLeafPaths)
)
.map((item) => item.path);
setUserCollapsedGroups((prev) => {
let next: Set<string> | null = null;
for (const path of activeGroupPaths) {
if (!prev.has(path)) continue;
next = next ?? new Set(prev);
next.delete(path);
}
if (!next) return prev;
persistCollapsedGroups(next);
return next;
});
setExpandedMenus(activeGroupPaths);
}, [location.pathname, menuLoading, visibleMenuItems, allMenuLeafPaths, persistCollapsedGroups]);
useEffect(() => {
if (!profile?.must_change_password || !profile.id) return;
const key = `password-change-tip:${profile.id}`;
if (sessionStorage.getItem(key)) return;
sessionStorage.setItem(key, '1');
notify.warning('当前账号仍在使用初始密码或重置密码,建议尽快在右上角账号菜单中修改密码。');
}, [profile?.id, profile?.must_change_password]);
useEffect(() => {
if (!isSuperAdmin) return;
let active = true;
void (async () => {
const { data, error } = await supabase
.from('branches')
.select('branch_code, branch_name')
.eq('status', 1)
.order('branch_code');
if (!active || error) return;
const rows = data || [];
setBranchOptions(rows);
// 仅首次加载时自动选择业务分公司,后续尊重用户手动选择(含基础平台)
if (!operatingBranchCode) {
const resolved = resolveOperatingBranchCode(operatingBranchCode, rows);
if (resolved) {
setOperatingBranch(resolved);
}
}
})();
return () => {
active = false;
};
}, [isSuperAdmin, operatingBranchCode, setOperatingBranch]);
const operatingBranchName =
branchOptions.find((b) => b.branch_code === operatingBranchCode)?.branch_name || operatingBranchCode;
const primaryRole = profile?.roles?.[0];
const roleLabel = primaryRole ? resolveRoleLabel(primaryRole) : t('layout.unknownRole');
return (
<div className="app-shell app-foreground min-h-screen flex">
{/* Mobile drawer backdrop */}
{mobileSidebarOpen && (
<div
className="fixed inset-0 bg-black/40 z-40 lg:hidden"
onClick={() => setMobileSidebarOpen(false)}
aria-hidden="true"
/>
)}
{/* Sidebar */}
<aside
className={`app-sidebar fixed left-0 top-0 h-full backdrop-blur-xl border-r transition-all duration-300 z-50 flex flex-col ${
sidebarOpen || mobileSidebarOpen ? 'w-[260px]' : 'sidebar-collapsed-new'
} ${mobileSidebarOpen ? 'max-lg:translate-x-0' : 'max-lg:-translate-x-full'}`}
style={{ background: 'var(--app-sidebar-bg)' }}
>
{/* Logo Area */}
<div className="h-16 flex items-center gap-3 px-5 border-b shrink-0" style={{ borderColor: 'var(--app-sidebar-border)' }}>
<div className="app-logo w-[38px] h-[38px] flex items-center justify-center shrink-0">
<Package className="w-[22px] h-[22px] text-white" />
</div>
<div className="sidebar-hide-collapsed overflow-hidden whitespace-nowrap transition-all duration-250">
<span className="app-foreground block text-[15px] font-semibold leading-tight tracking-tight">
{t('login.brandTitle')}
</span>
<span className="app-foreground-muted -mt-0.5 block text-[11px] tracking-wide">{t('login.brandSubtitle')}</span>
</div>
</div>
{/* Navigation */}
<nav className="flex-1 overflow-y-auto overflow-x-hidden py-3 px-2.5 scrollbar-thin" style={{ scrollbarWidth: 'thin', scrollbarColor: 'rgba(148,163,184,0.3) transparent' }}>
{menuLoading ? (
<div className="px-1 py-1 space-y-2" aria-busy="true" aria-label={t('common.loading')}>
{Array.from({ length: 6 }).map((_, index) => (
<div
key={index}
className="app-table-head h-9 animate-pulse rounded-lg"
/>
))}
</div>
) : (
visibleMenuItems.map((item) => {
const hasChildren = item.children && item.children.length > 0;
const activeChild = hasChildren
? findActiveMenuChild(location.pathname, item.children!, allMenuLeafPaths)
: undefined;
const userCollapsed = userCollapsedGroups.has(item.path);
const submenuOpen = shouldExpandMenuGroup({
hasActiveChild: Boolean(activeChild),
userCollapsed,
userExpanded: isMenuExpanded(item.path),
});
const visibleChildren = submenuOpen ? item.children : [];
const isActive = hasChildren
? isActiveInMenuGroup(location.pathname, item.children!, allMenuLeafPaths)
: isStandaloneMenuActive(location.pathname, item.path);
return (
<div key={`${item.path}:${item.label}`} className="nav-group-container">
{hasChildren ? (
<>
<button
type="button"
onClick={() => toggleMenu(item.path, submenuOpen)}
aria-expanded={submenuOpen}
aria-controls={`submenu-${item.path.replace(/[^a-zA-Z0-9_-]/g, '-')}`}
title={item.label}
className={`nav-group-label w-full flex items-center gap-2 rounded-lg cursor-pointer ${
isActive ? 'app-foreground' : ''
}`}
>
<MenuNavIcon icon={item.icon} iconSvg={item.iconSvg} className="nav-group-icon" />
<span className="flex-1 text-left truncate">{item.label}</span>
<ChevronRight
className="group-chevron-icon shrink-0"
style={{
transform: submenuOpen ? 'rotate(90deg)' : 'rotate(0deg)',
transition: 'transform 0.25s cubic-bezier(0.4, 0, 0.2, 1)',
}}
/>
</button>
<div
id={`submenu-${item.path.replace(/[^a-zA-Z0-9_-]/g, '-')}`}
className={`nav-items-list ${!submenuOpen ? 'collapsed-parent' : ''}`}
style={{
maxHeight: getSubmenuMaxHeight(visibleChildren?.length ?? 0, submenuOpen),
opacity: submenuOpen ? 1 : 0,
paddingTop: submenuOpen ? undefined : '0',
paddingBottom: submenuOpen ? undefined : '0',
pointerEvents: submenuOpen ? 'auto' : 'none',
}}
>
{visibleChildren?.map((child) => (
<NavLink
key={child.path}
to={child.path}
end
className={() =>
`subnav-item ${
isMenuChildActive(
location.pathname,
child.path,
item.children!,
allMenuLeafPaths
)
? 'active'
: ''
}`
}
>
<span>{child.label}</span>
</NavLink>
))}
</div>
</>
) : (
<NavLink
to={item.path}
end
className={({ isActive: navActive }) =>
`nav-item ${navActive ? 'active' : ''}`
}
>
{(item.icon || item.iconSvg) && (
<MenuNavIcon icon={item.icon} iconSvg={item.iconSvg} className="nav-icon" />
)}
<span className="nav-item-text sidebar-hide-collapsed">{item.label}</span>
</NavLink>
)}
</div>
);
})
)}
</nav>
{/* Sidebar Footer - Collapse Button */}
<div className="sidebar-footer">
<button
type="button"
onClick={() => setSidebarOpen(!sidebarOpen)}
className="sidebar-collapse-btn"
>
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ transition: 'transform 0.3s ease', transform: sidebarOpen ? 'rotate(0deg)' : 'rotate(180deg)' }}>
<polyline points="11 17 6 12 11 7"/><polyline points="18 17 13 12 18 7"/>
</svg>
<span className="sidebar-hide-collapsed">{sidebarOpen ? '收起侧栏' : ''}</span>
</button>
</div>
</aside>
{/* Main Content:min-w-0 避免宽表把 flex 主栏撑出整页横滚 */}
<div className={`flex-1 min-w-0 transition-all duration-300 ml-0 ${sidebarOpen ? 'lg:ml-[260px]' : 'lg:ml-[72px]'}`}>
{/* Header */}
<header className="app-header h-14 backdrop-blur-xl border-b flex items-center justify-between px-4 sm:px-7 sticky top-0 z-40" style={{ background: 'var(--app-header-bg)', borderColor: 'var(--app-header-border)' }}>
<div className="flex items-center gap-4">
<button
type="button"
onClick={() => setMobileSidebarOpen(true)}
title="打开导航"
aria-label="打开导航"
className="app-nav-idle lg:hidden p-2 rounded-xl transition-colors duration-150"
>
<Menu className="app-foreground-muted w-4 h-4" />
</button>
{!sidebarOpen && (
<button
type="button"
onClick={() => setSidebarOpen(true)}
title="展开导航"
aria-label="展开导航"
className="app-nav-idle hidden lg:block p-2 rounded-xl transition-colors duration-150"
>
<PanelLeftOpen className="app-foreground-muted w-4 h-4" />
</button>
)}
<div className="flex items-center gap-2">
<span className="app-foreground-muted text-xs">当前角色</span>
<span className="command-role-chip px-2.5 py-1 text-xs font-medium rounded-md border">
{roleLabel}
</span>
{profile?.branch_name && !isSuperAdmin && (
<span className="command-role-chip px-2.5 py-1 text-xs font-medium rounded-md border">
{profile.branch_name}
</span>
)}
{isSuperAdmin && (
<label className="app-foreground-muted flex items-center gap-2 text-xs">
<span>{t('layout.operatingBranch')}</span>
<select
value={operatingBranchCode || ''}
onChange={(e) => setOperatingBranch(e.target.value || null)}
className="app-status-warning app-focus-ring rounded-full border px-2.5 py-1 text-xs font-medium outline-none focus:ring-2"
aria-label={t('layout.pickBranch')}
>
{!operatingBranchCode && <option value="">{t('layout.pleaseSelect')}</option>}
{branchOptions.map((branch) => (
<option key={branch.branch_code} value={branch.branch_code}>
{branch.branch_name}
{isPlatformBranchCode(branch.branch_code) ? t('layout.platformConfig') : ''}
</option>
))}
</select>
</label>
)}
{isSuperAdmin && operatingBranchCode && !branchOptions.length && (
<span className="app-status-warning rounded-full border px-2.5 py-1 text-xs font-medium">
{operatingBranchName}
</span>
)}
</div>
</div>
<div className="flex items-center gap-3">
<div className="hidden xl:flex flex-col items-end border-r pr-3" style={{ borderColor: 'var(--app-header-border)' }}>
<span className="font-mono text-sm font-semibold tracking-[0.12em] command-accent">
{formatHeaderTime(currentTime, locale)}
</span>
<span className="app-foreground-muted text-[10px]">
{formatHeaderDate(currentTime, locale)}
</span>
</div>
<ThemeSwitcher />
<NotificationBell />
<UserAccountMenu />
</div>
</header>
{/* Page Content */}
<main className="p-4 sm:p-7 min-h-[calc(100vh-56px)] min-w-0 overflow-x-hidden">
{isSuperAdmin && !operatingBranchCode ? (
<div className="app-foreground-muted flex min-h-[40vh] items-center justify-center text-sm">
{t('layout.initBranch')}
</div>
) : (
<Outlet key={outletKey} />
)}
</main>
</div>
<OrderEntryIntakeFab />
</div>
);
};