BusinessAdminShell.tsx 7 KB
import type { ReactElement, ReactNode } from 'react';
import { useEffect, useState } from 'react';
import { MenuFoldIcon, MenuUnfoldIcon } from 'tdesign-icons-react';
import { Avatar, Breadcrumb, Button, Dropdown, Menu } from 'tdesign-react';

export interface BusinessAdminShellMenuItem {
  key: string;
  label: ReactNode;
  icon?: ReactElement;
  disabled?: boolean;
  children?: BusinessAdminShellMenuItem[];
}

export interface BusinessAdminShellBreadcrumbItem {
  key: string;
  label: ReactNode;
  onClick?: () => void;
}

export interface BusinessAdminShellUser {
  name: string;
  avatarUrl?: string;
}

export interface BusinessAdminShellProps {
  systemName: string;
  menuItems: BusinessAdminShellMenuItem[];
  activeMenuKey?: string;
  expandedMenuKeys?: string[];
  breadcrumbItems: BusinessAdminShellBreadcrumbItem[];
  user: BusinessAdminShellUser;
  children: ReactNode;
  hasProfile?: boolean;
  defaultCollapsed?: boolean;
  collapsed?: boolean;
  headerHeight?: number;
  contentPadding?: number;
  onMenuChange: (key: string) => void;
  onCollapsedChange?: (collapsed: boolean) => void;
  onLogout: () => void;
  onProfile?: () => void;
}

function renderMenuItem(item: BusinessAdminShellMenuItem) {
  if (item.children?.length) {
    return (
      <Menu.SubMenu
        key={item.key}
        value={item.key}
        title={item.label}
        icon={item.icon}
        disabled={item.disabled}
      >
        {item.children.map((child) => renderMenuItem(child))}
      </Menu.SubMenu>
    );
  }

  return (
    <Menu.MenuItem key={item.key} value={item.key} icon={item.icon} disabled={item.disabled}>
      {item.label}
    </Menu.MenuItem>
  );
}

function UserAvatar({ user }: { user: BusinessAdminShellUser }) {
  const fallbackText = user.name.slice(0, 1) || '?';

  return (
    <Avatar
      aria-label={`${user.name}头像`}
      image={user.avatarUrl}
      size="32px"
      style={user.avatarUrl ? undefined : { backgroundColor: '#2f76ff', color: '#fff' }}
    >
      {user.avatarUrl ? null : fallbackText}
    </Avatar>
  );
}

export function BusinessAdminShell({
  systemName,
  menuItems,
  activeMenuKey,
  expandedMenuKeys = [],
  breadcrumbItems,
  user,
  children,
  hasProfile = false,
  defaultCollapsed = false,
  collapsed,
  headerHeight = 56,
  contentPadding = 24,
  onMenuChange,
  onCollapsedChange,
  onLogout,
  onProfile,
}: BusinessAdminShellProps) {
  const userAvatar = <UserAvatar user={user} />;
  const [internalCollapsed, setInternalCollapsed] = useState(defaultCollapsed);
  const [internalExpandedMenuKeys, setInternalExpandedMenuKeys] = useState(expandedMenuKeys);
  const isCollapsed = collapsed ?? internalCollapsed;
  const asideWidth = isCollapsed ? 64 : 220;

  useEffect(() => {
    setInternalExpandedMenuKeys((currentKeys) => {
      const nextKeys = new Set(currentKeys);
      expandedMenuKeys.forEach((key) => nextKeys.add(key));
      return Array.from(nextKeys);
    });
  }, [expandedMenuKeys]);

  const toggleCollapsed = () => {
    const nextCollapsed = !isCollapsed;
    setInternalCollapsed(nextCollapsed);
    onCollapsedChange?.(nextCollapsed);
  };

  return (
    <div
      className="grid h-screen min-h-screen bg-[var(--gl-color-bg-page)] text-[var(--gl-color-text-primary)] max-[760px]:grid-cols-1"
      style={{ gridTemplateColumns: `${asideWidth}px 1fr` }}
    >
      <aside
        aria-label="左侧导航"
        className="min-w-0 border-r border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)]"
        style={{ width: asideWidth }}
      >
        <div className="flex h-14 items-center justify-between gap-2 px-3">
          {isCollapsed ? null : (
            <h1 className="m-0 min-w-0 truncate px-2 text-base font-semibold leading-[var(--gl-line-height-lg)] text-[var(--gl-color-text-primary)]">
              {systemName}
            </h1>
          )}
          <button
            aria-label={isCollapsed ? '展开菜单' : '收起菜单'}
            className="grid h-8 w-8 shrink-0 place-items-center rounded border-0 bg-transparent p-0 text-[var(--gl-color-text-secondary)] hover:bg-[var(--gl-color-bg-page)] hover:text-[var(--gl-color-primary)]"
            type="button"
            onClick={toggleCollapsed}
          >
            {isCollapsed ? <MenuUnfoldIcon /> : <MenuFoldIcon />}
          </button>
        </div>
        <Menu
          value={activeMenuKey}
          expanded={internalExpandedMenuKeys}
          collapsed={isCollapsed}
          width={['220px', '64px']}
          onChange={(value) => onMenuChange(String(value))}
          onExpand={(value) => setInternalExpandedMenuKeys(value.map(String))}
        >
          {menuItems.map((item) => renderMenuItem(item))}
        </Menu>
      </aside>
      <div className="grid min-h-0 min-w-0 grid-rows-[auto_1fr]">
        <header
          className="flex items-center justify-between gap-4 border-b border-[var(--gl-color-border-secondary)] bg-[var(--gl-color-bg-container)] px-6 text-sm"
          style={{ height: headerHeight }}
        >
          <Breadcrumb separator=">">
            {breadcrumbItems.map((item, index) => {
              const isLast = index === breadcrumbItems.length - 1;
              return (
                <Breadcrumb.BreadcrumbItem key={item.key}>
                  {item.onClick && !isLast ? (
                    <button
                      className="border-0 bg-transparent p-0 text-sm text-[var(--gl-color-primary)] hover:underline"
                      type="button"
                      onClick={item.onClick}
                    >
                      {item.label}
                    </button>
                  ) : (
                    item.label
                  )}
                </Breadcrumb.BreadcrumbItem>
              );
            })}
          </Breadcrumb>
          <div className="flex shrink-0 items-center gap-3">
            <span className="text-sm text-[var(--gl-color-text-primary)]">{user.name}</span>
            {hasProfile ? (
              <Dropdown
                trigger="click"
                options={[
                  { content: '个人信息', value: 'profile' },
                  { content: '退出登录', value: 'logout' },
                ]}
                onClick={(option) => {
                  if (option.value === 'profile') onProfile?.();
                  if (option.value === 'logout') onLogout();
                }}
              >
                <button
                  aria-label={`${user.name} 用户菜单`}
                  className="grid h-8 w-8 place-items-center border-0 bg-transparent p-0"
                  type="button"
                >
                  {userAvatar}
                </button>
              </Dropdown>
            ) : (
              <>
                {userAvatar}
                <Button variant="outline" onClick={onLogout}>
                  退出登录
                </Button>
              </>
            )}
          </div>
        </header>
        <main className="min-h-0 min-w-0 overflow-auto" style={{ padding: contentPadding }}>
          {children}
        </main>
      </div>
    </div>
  );
}