RoleDetailDrawer.tsx 10.5 KB
import { useMemo, useState } from 'react';
import { CheckOutlined, DownOutlined, MinusOutlined, RightOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import { UAlert, UButton, UDescriptions, UDrawer, UText } from '@uj/ui';
import { menu, role, type MenuNode } from '@/api';
import { getDataScopeLabel } from '@/constants/dataScope';

export interface RoleDetailDrawerProps {
  open: boolean;
  roleId?: number;
  onClose: () => void;
}

export function RoleDetailDrawer({ open, roleId, onClose }: RoleDetailDrawerProps) {
  const [collapsedNodeIds, setCollapsedNodeIds] = useState<Set<number>>(new Set());
  const detailQuery = useQuery({
    queryKey: ['role-detail', roleId],
    queryFn: () => role.detail(roleId as number),
    enabled: open && Boolean(roleId),
  });
  const menuQuery = useQuery({
    queryKey: ['role-permission-menu-tree'],
    queryFn: () => menu.allTree(),
    enabled: open,
  });
  const grantedIds = useMemo(() => new Set(detailQuery.data?.menuIds ?? []), [detailQuery.data]);
  const isLoading = detailQuery.isLoading || menuQuery.isLoading;
  const error = detailQuery.error ?? menuQuery.error;
  const detail = detailQuery.data;

  return (
    <UDrawer
      open={open}
      placement="right"
      size={760}
      title={detail ? `角色详情 · ${detail.roleName}` : '角色详情'}
      onClose={onClose}
      footer={
        <UButton type="default" style={{ float: 'right' }} onClick={onClose}>
          关闭
        </UButton>
      }
    >
      {error ? <UAlert type="error" showIcon message="角色详情加载失败,请关闭后重试" /> : null}
      {detail ? (
        <>
          <div style={summaryStyle}>
            <span>
              角色编码 <strong>{detail.roleCode}</strong>
            </span>
            <span>
              默认数据域{' '}
              {detail.defaultDataScopeLabel ?? getDataScopeLabel(detail.defaultDataScope)}
            </span>
            <span>
              关联账号 <strong>{detail.userCount} 名</strong>
            </span>
            <span>类型 {detail.isBuiltin === 1 ? '内置' : '自定义'}</span>
          </div>
          <SectionTitle>角色基本信息</SectionTitle>
          <UDescriptions
            size="small"
            column={1}
            items={[
              { key: 'name', label: '角色名称', children: detail.roleName },
              { key: 'code', label: '角色编码', children: detail.roleCode },
              {
                key: 'scope',
                label: '默认数据域',
                children:
                  detail.defaultDataScopeLabel ?? getDataScopeLabel(detail.defaultDataScope),
              },
              { key: 'count', label: '关联账号', children: `${detail.userCount} 名` },
              { key: 'description', label: '角色描述', children: detail.description || '—' },
            ]}
          />
          <SectionTitle>菜单可见范围(权限矩阵)</SectionTitle>
          <div style={matrixStyle}>
            {isLoading ? <UText type="secondary">权限加载中…</UText> : null}
            {!isLoading ? (
              <PermissionTree
                nodes={menuQuery.data ?? []}
                grantedIds={grantedIds}
                collapsedNodeIds={collapsedNodeIds}
                onToggle={(id) => {
                  setCollapsedNodeIds((previous) => {
                    const next = new Set(previous);
                    if (next.has(id)) next.delete(id);
                    else next.add(id);
                    return next;
                  });
                }}
              />
            ) : null}
          </div>
          <div style={legendStyle}>
            <PermissionLegend state="checked" label="已授权" />
            <PermissionLegend state="partial" label="部分授权(父节点)" />
            <PermissionLegend state="empty" label="未授权" />
          </div>
        </>
      ) : null}
    </UDrawer>
  );
}

function SectionTitle({ children }: { children: string }) {
  return (
    <h3 style={sectionTitleStyle}>
      <span style={sectionMarkerStyle} />
      {children}
    </h3>
  );
}

function PermissionMark({ state }: { state: 'checked' | 'partial' | 'empty' | 'na' }) {
  const label = {
    checked: '已授权',
    partial: '部分授权',
    empty: '未授权',
    na: '不适用',
  }[state];
  return (
    <span aria-label={label} style={{ ...permissionMarkStyle, ...permissionStateStyle[state] }}>
      {state === 'checked' ? <CheckOutlined /> : null}
      {state === 'partial' ? <MinusOutlined /> : null}
      {state === 'na' ? '—' : null}
    </span>
  );
}

function PermissionLegend({
  state,
  label,
}: {
  state: 'checked' | 'partial' | 'empty' | 'na';
  label: string;
}) {
  return (
    <span style={legendItemStyle}>
      <PermissionMark state={state} />
      {label}
    </span>
  );
}

function PermissionTree({
  nodes,
  grantedIds,
  collapsedNodeIds,
  onToggle,
}: {
  nodes: MenuNode[];
  grantedIds: Set<number>;
  collapsedNodeIds: Set<number>;
  onToggle: (id: number) => void;
}) {
  return (
    <div role="tree" style={treeStyle}>
      {nodes.map((node) => (
        <PermissionTreeNode
          key={node.id}
          node={node}
          grantedIds={grantedIds}
          depth={0}
          collapsedNodeIds={collapsedNodeIds}
          onToggle={onToggle}
        />
      ))}
    </div>
  );
}

function PermissionTreeNode({
  node,
  grantedIds,
  depth,
  collapsedNodeIds,
  onToggle,
}: {
  node: MenuNode;
  grantedIds: Set<number>;
  depth: number;
  collapsedNodeIds: Set<number>;
  onToggle: (id: number) => void;
}) {
  if (node.nodeType === 3)
    return <PermissionButton node={node} grantedIds={grantedIds} depth={depth} />;
  const buttons = (node.children ?? []).filter((child) => child.nodeType === 3);
  const menus = (node.children ?? []).filter((child) => child.nodeType !== 3);
  const hasChildren = buttons.length > 0 || menus.length > 0;
  const expanded = !collapsedNodeIds.has(node.id);
  return (
    <div
      role="treeitem"
      aria-level={depth + 1}
      aria-expanded={hasChildren ? expanded : undefined}
      style={treeNodeStyle}
    >
      <div style={{ ...treeLabelStyle, paddingLeft: depth * 22 }}>
        {hasChildren ? (
          <UButton
            type="text"
            size="small"
            aria-label={`${expanded ? '收起' : '展开'}${node.label}`}
            icon={expanded ? <DownOutlined /> : <RightOutlined />}
            style={treeToggleStyle}
            onClick={() => onToggle(node.id)}
          />
        ) : (
          <span style={treeBranchStyle}>•</span>
        )}
        <PermissionMark state={nodePermissionState(node, grantedIds)} />
        <UText strong={node.nodeType === 1}>{node.label}</UText>
      </div>
      {expanded && buttons.length ? (
        <div style={{ ...buttonListStyle, marginLeft: (depth + 1) * 22 + 18 }} role="group">
          {buttons.map((button) => (
            <PermissionButton
              key={button.id}
              node={button}
              grantedIds={grantedIds}
              depth={depth + 1}
            />
          ))}
        </div>
      ) : null}
      {expanded &&
        menus.map((child) => (
          <PermissionTreeNode
            key={child.id}
            node={child}
            grantedIds={grantedIds}
            depth={depth + 1}
            collapsedNodeIds={collapsedNodeIds}
            onToggle={onToggle}
          />
        ))}
    </div>
  );
}

function PermissionButton({
  node,
  grantedIds,
  depth,
}: {
  node: MenuNode;
  grantedIds: Set<number>;
  depth: number;
}) {
  return (
    <span
      role="treeitem"
      aria-level={depth + 1}
      style={permissionButtonStyle}
      title={node.permCode ?? undefined}
    >
      <PermissionMark state={grantedIds.has(node.id) ? 'checked' : 'empty'} />
      {node.label}
    </span>
  );
}

function nodePermissionState(
  node: MenuNode,
  grantedIds: Set<number>,
): 'checked' | 'partial' | 'empty' {
  const nodes = [node, ...descendantsOf(node)];
  const grantedCount = nodes.filter((item) => grantedIds.has(item.id)).length;
  if (grantedCount === nodes.length) return 'checked';
  return grantedCount > 0 ? 'partial' : 'empty';
}

function descendantsOf(node: MenuNode): MenuNode[] {
  return (node.children ?? []).flatMap((child) => [child, ...descendantsOf(child)]);
}

const summaryStyle = {
  color: 'var(--uj-text-3)',
  display: 'flex',
  flexWrap: 'wrap' as const,
  fontSize: 13,
  gap: '8px 16px',
  marginBottom: 'var(--uj-space-module, 10px)',
};
const sectionTitleStyle = {
  alignItems: 'center',
  borderBottom: '1px solid var(--uj-divider)',
  display: 'flex',
  fontSize: 14,
  gap: 6,
  lineHeight: '16px',
  margin: '20px 0 12px',
  padding: '0 0 8px',
};
const sectionMarkerStyle = {
  backgroundColor: 'var(--uj-primary)',
  borderRadius: 2,
  height: 10,
  width: 3,
};
const matrixStyle = {
  border: '1px solid var(--uj-border)',
  borderRadius: 10,
  minHeight: 80,
  padding: 12,
};
const treeStyle = { display: 'flex', flexDirection: 'column' as const, gap: 8 };
const treeNodeStyle = { display: 'flex', flexDirection: 'column' as const, gap: 8 };
const treeLabelStyle = { alignItems: 'center', display: 'flex', gap: 8, minHeight: 24 };
const treeBranchStyle = {
  color: 'var(--uj-text-3)',
  display: 'inline-block',
  textAlign: 'center' as const,
  width: 12,
};
const treeToggleStyle = {
  color: 'var(--uj-text-3)',
  height: 20,
  margin: 0,
  minWidth: 20,
  padding: 0,
  width: 20,
};
const buttonListStyle = { display: 'flex', flexDirection: 'column' as const, gap: 4 };
const permissionButtonStyle = {
  alignItems: 'center',
  color: 'var(--uj-text-2)',
  display: 'flex',
  fontSize: 12,
  gap: 6,
  minHeight: 24,
  padding: 0,
};
const permissionMarkStyle = {
  alignItems: 'center',
  border: '1px solid var(--uj-border)',
  borderRadius: 3,
  boxSizing: 'border-box' as const,
  color: 'var(--uj-on-primary)',
  display: 'inline-flex',
  fontSize: 10,
  height: 15,
  justifyContent: 'center',
  lineHeight: 1,
  verticalAlign: 'middle',
  width: 15,
};
const permissionStateStyle = {
  checked: { backgroundColor: 'var(--uj-primary)', borderColor: 'var(--uj-primary)' },
  partial: { backgroundColor: 'var(--uj-primary)', borderColor: 'var(--uj-primary)' },
  empty: { backgroundColor: 'var(--uj-surface)' },
  na: { backgroundColor: 'var(--uj-surface-2)', color: 'var(--uj-text-3)' },
};
const legendStyle = {
  color: 'var(--uj-text-3)',
  display: 'flex',
  flexWrap: 'wrap' as const,
  fontSize: 12,
  gap: 10,
  marginTop: 12,
};
const legendItemStyle = { alignItems: 'center', display: 'inline-flex', gap: 6 };