SideNav.tsx 12.6 KB
import { useCallback, useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { createPortal } from 'react-dom';
import {
  DashboardOutlined,
  ShopOutlined,
  UploadOutlined,
  TeamOutlined,
  AuditOutlined,
  AppstoreOutlined,
  FolderOutlined,
  GiftOutlined,
  FileSyncOutlined,
  FundOutlined,
  TransactionOutlined,
  SolutionOutlined,
  HomeOutlined,
  SettingOutlined,
  CarOutlined,
  FundProjectionScreenOutlined,
  AimOutlined,
  ExperimentOutlined,
  ControlOutlined,
  ToolOutlined,
  SendOutlined,
  ReconciliationOutlined,
  UserSwitchOutlined,
  FileTextOutlined,
  SafetyCertificateOutlined,
  WechatOutlined,
  PayCircleOutlined,
  WalletOutlined,
  RightOutlined,
} from '@ant-design/icons';
import type { MenuGroupDef } from '@/access';

/**
 * 侧栏导航(自绘,不走 antd Menu)。
 *
 * 为什么自绘:重设计后一级是「章节头」——四列网格(图标 / 标题槽 / 子项数 / 展开指示),
 * 二级是导轨下的纯文字项,且章节头与子项高度不同。antd Menu 的 SubMenu 把两者共用
 * itemHeight,标题内容包在 .ant-menu-title-content 里由内容撑宽;要让标题槽 flex:1、
 * 右端对齐到同一条线,只能覆盖组件内部盒模型 —— design.css 旧注释自己就写过
 * 「折叠态居中尤其敏感,任何 width / padding-inline 覆盖都会算歪」。
 * 用 type:'group' 自定义 label 也不行:group 标题在 inline 模式下点不动,会把
 * BasicLayout 里「原先 group 标题永远展开才换成 SubMenu」的修复回退掉。
 *
 * 因此只换渲染层:数据仍是后端菜单树经 buildMenus 得到的 MenuGroupDef[],
 * 空组剔除 / selectedKey 最长前缀 / openKeys 受控校准 / 切页时的
 * PAGE_LEAVE_EVENT + cancelRequests + navigate 全部留在 BasicLayout,本组件不碰。
 * 菜单显隐以 /system/menu/tree/current 为准,本组件不做任何权限判断。
 *
 * 二级菜单刻意不渲染 m.icon:12 个不同线性图标在 34px 行里会形成锯齿边,
 * 且 iconMap 是白名单,后端新增页面漏登记就会静默回落。二级改用导轨上的统一节点,
 * 选中信号也由该节点承担(半透明点 → 品牌蓝实心 + 亮环)。后端 sys_menu.icon
 * 字段不动,一级分组与工作台单入口仍按 icon 渲染。
 */
interface SideNavProps {
  /** 权限过滤后的分组(空组已剔除),由 BasicLayout 生成 */
  groups: MenuGroupDef[];
  selectedKey: string;
  /** 当前页所属分组名;null 表示当前页是平铺单入口或非菜单页 */
  activeGroupName: string | null;
  isGroupOpen: (name: string) => boolean;
  onToggleGroup: (name: string) => void;
  collapsed: boolean;
  onToggleCollapsed: () => void;
  onNavigate: (path: string) => void;
  /** 底部信息条:当前登录角色,取自登录态而非写死 */
  roleLabel: string;
}

/** 图标注册表:只登记用到的字面量,避免 `import * as antdIcons` 把 894 个图标打进首屏。
 *  现在只有一级分组与工作台单入口会查表;二级不查,故后端给二级配的图标名无需登记。 */
const iconMap: Record<string, ReactNode> = {
  DashboardOutlined: <DashboardOutlined />,
  ShopOutlined: <ShopOutlined />,
  UploadOutlined: <UploadOutlined />,
  TeamOutlined: <TeamOutlined />,
  AuditOutlined: <AuditOutlined />,
  GiftOutlined: <GiftOutlined />,
  FileSyncOutlined: <FileSyncOutlined />,
  FundOutlined: <FundOutlined />,
  TransactionOutlined: <TransactionOutlined />,
  SolutionOutlined: <SolutionOutlined />,
  HomeOutlined: <HomeOutlined />,
  SettingOutlined: <SettingOutlined />,
  CarOutlined: <CarOutlined />,
  FundProjectionScreenOutlined: <FundProjectionScreenOutlined />,
  AimOutlined: <AimOutlined />,
  ExperimentOutlined: <ExperimentOutlined />,
  ControlOutlined: <ControlOutlined />,
  ToolOutlined: <ToolOutlined />,
  SendOutlined: <SendOutlined />,
  ReconciliationOutlined: <ReconciliationOutlined />,
  UserSwitchOutlined: <UserSwitchOutlined />,
  FileTextOutlined: <FileTextOutlined />,
  SafetyCertificateOutlined: <SafetyCertificateOutlined />,
  WechatOutlined: <WechatOutlined />,
  PayCircleOutlined: <PayCircleOutlined />,
  // 财务管理(finance)一级目录,见 scripts/finance-menu-migration.sql
  WalletOutlined: <WalletOutlined />,
};
const DEFAULT_MENU_ICON: ReactNode = <AppstoreOutlined />;
const GROUP_DEFAULT_ICON: ReactNode = <FolderOutlined />;

const warnedIcons = new Set<string>();
function resolveIcon(
  name: string | null | undefined,
  fallback: ReactNode = DEFAULT_MENU_ICON,
): 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}」未在 SideNav.tsx 的 iconMap 中登记,已回落兜底图标。` +
        `请在 iconMap 补一行,或让后端改发已支持的值。`,
    );
  }
  return fallback;
}

/**
 * 折叠控制线稿:与 docs/sider-redesign.html 的 fold / unfold 路径逐条一致。
 * 不用 antd MenuFoldOutlined / MenuUnfoldOutlined —— 那两个是「带方框 + 三条横线」的
 * 汉堡图标,和侧栏的极简线稿语言不符,是原型与实现最直观的一处不一致。
 */
const FOLD_PATHS: Record<'fold' | 'unfold', string[]> = {
  fold: ['M14 5l-7 7 7 7', 'M20 5v14'],
  unfold: ['M10 5l7 7-7 7', 'M4 5v14'],
};
function FoldGlyph({ collapsed }: { collapsed: boolean }) {
  return (
    <svg
      width="15"
      height="15"
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="1.7"
      strokeLinecap="round"
      strokeLinejoin="round"
      aria-hidden="true"
    >
      {FOLD_PATHS[collapsed ? 'unfold' : 'fold'].map((d) => (
        <path key={d} d={d} />
      ))}
    </svg>
  );
}

interface PopoverState {
  group: MenuGroupDef;
  top: number;
}

export default function SideNav({
  groups,
  selectedKey,
  activeGroupName,
  isGroupOpen,
  onToggleGroup,
  collapsed,
  onToggleCollapsed,
  onNavigate,
  roleLabel,
}: SideNavProps) {
  const navRef = useRef<HTMLElement>(null);
  const [fade, setFade] = useState({ top: false, bottom: false });
  const [popover, setPopover] = useState<PopoverState | null>(null);

  const solo = groups.filter((g) => g.hideTitle).flatMap((g) => g.children);
  const chapters = groups.filter((g) => !g.hideTitle);

  /** 长菜单的上下渐隐:只在真的还有内容时出现,静默提示可滚动。 */
  const syncFade = useCallback(() => {
    const el = navRef.current;
    if (!el) return;
    const more = el.scrollHeight - el.clientHeight;
    const top = el.scrollTop > 4;
    const bottom = more > 4 && el.scrollTop < more - 4;
    setFade((prev) => (prev.top === top && prev.bottom === bottom ? prev : { top, bottom }));
  }, []);

  useEffect(() => {
    syncFade();
    window.addEventListener('resize', syncFade);
    return () => window.removeEventListener('resize', syncFade);
  }, [syncFade, groups, collapsed, popover]);

  /** 折叠态浮层:点外部或 Esc 关闭。浮层 portal 到 body,避开 .ant-layout-sider 的 overflow:hidden。 */
  useEffect(() => {
    if (!popover) return;
    const onDocClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement | null;
      if (!target?.closest('.uj-nav-popover') && !target?.closest('.uj-chap-head')) {
        setPopover(null);
      }
    };
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') setPopover(null);
    };
    document.addEventListener('click', onDocClick);
    document.addEventListener('keydown', onKey);
    return () => {
      document.removeEventListener('click', onDocClick);
      document.removeEventListener('keydown', onKey);
    };
  }, [popover]);

  // 展开侧栏时浮层失去意义,立即收掉,避免展开后出现一块悬空面板。
  useEffect(() => {
    if (!collapsed) setPopover(null);
  }, [collapsed]);

  const handleChapterClick = (group: MenuGroupDef, anchorTop: number) => {
    if (collapsed) {
      // 浮层跟随锚点,但按真实子项数估高后夹回视口内:
      // 二手车管理 12 项在矮窗口里不夹会整块溢出屏幕底部。
      const estimated = 44 + group.children.length * 32;
      const top = Math.max(12, Math.min(anchorTop, window.innerHeight - estimated - 12));
      setPopover((prev) => (prev?.group.group === group.group ? null : { group, top }));
      return;
    }
    onToggleGroup(group.group);
  };

  return (
    <>
      <nav className="uj-nav" ref={navRef} onScroll={syncFade} aria-label="主导航">
        <div className="uj-zone-label">工作区</div>
        {solo.map((m) => {
          const active = selectedKey === m.path;
          return (
            <button
              key={m.path}
              type="button"
              className={`uj-solo${active ? ' is-active' : ''}`}
              title={m.label}
              aria-current={active ? 'page' : undefined}
              onClick={() => onNavigate(m.path)}
            >
              <span className="uj-solo-ico">{resolveIcon(m.icon)}</span>
              <span className="uj-solo-txt">{m.label}</span>
            </button>
          );
        })}

        <div className="uj-zone-sep" />
        <div className="uj-zone-label">业务域</div>

        {chapters.map((g) => {
          const open = isGroupOpen(g.group);
          const current = activeGroupName === g.group;
          return (
            <div
              key={g.group}
              className={`uj-chapter${open ? ' is-open' : ''}${current ? ' is-current' : ''}`}
            >
              <button
                type="button"
                className="uj-chap-head"
                title={g.group}
                aria-expanded={collapsed ? undefined : open}
                onClick={(e) => handleChapterClick(g, e.currentTarget.getBoundingClientRect().top)}
              >
                <span className="uj-chap-ico">
                  {resolveIcon(
                    g.icon,
                    g.children[0] ? resolveIcon(g.children[0].icon) : GROUP_DEFAULT_ICON,
                  )}
                </span>
                <span className="uj-chap-label">{g.group}</span>
                <span className="uj-chap-count">{g.children.length}</span>
                <span className="uj-chap-chev">
                  <RightOutlined />
                </span>
              </button>
              {!collapsed && open && (
                <div className="uj-chap-body">
                  {g.children.map((m) => {
                    const active = selectedKey === m.path;
                    return (
                      <button
                        key={m.path}
                        type="button"
                        className={`uj-leaf${active ? ' is-active' : ''}`}
                        title={m.label}
                        aria-current={active ? 'page' : undefined}
                        onClick={() => onNavigate(m.path)}
                      >
                        <span className="uj-leaf-node" aria-hidden="true" />
                        <span className="uj-leaf-txt">{m.label}</span>
                      </button>
                    );
                  })}
                </div>
              )}
            </div>
          );
        })}
      </nav>

      <div className={`uj-nav-fade is-top${fade.top ? ' is-on' : ''}`} aria-hidden="true" />
      <div className={`uj-nav-fade is-bottom${fade.bottom ? ' is-on' : ''}`} aria-hidden="true" />

      <div className="uj-sider-foot">
        <button
          type="button"
          className="uj-fold-btn"
          onClick={onToggleCollapsed}
          aria-label={collapsed ? '展开导航' : '收起导航'}
          title={collapsed ? '展开导航' : '收起导航'}
        >
          <FoldGlyph collapsed={collapsed} />
        </button>
        {!collapsed && (
          <div className="uj-foot-meta">
            <span className="n">{roleLabel}</span>
            <span className="e">当前登录角色</span>
          </div>
        )}
      </div>

      {popover &&
        createPortal(
          <div className="uj-nav-popover" role="menu" style={{ top: popover.top }}>
            <div className="uj-pop-title">{popover.group.group}</div>
            {popover.group.children.map((m) => (
              <button
                key={m.path}
                type="button"
                role="menuitem"
                className={`uj-pop-item${selectedKey === m.path ? ' is-active' : ''}`}
                onClick={() => {
                  onNavigate(m.path);
                  setPopover(null);
                }}
              >
                {m.label}
              </button>
            ))}
          </div>,
          document.body,
        )}
    </>
  );
}