PermButton.tsx 1.38 KB
import { forwardRef } from 'react';
import { UButton, UTooltip, type UButtonProps } from '@uj/ui';
import { useAccess } from '../runtime/AccessProvider';

interface PermButtonProps extends UButtonProps {
  /** 所需权限点,如 'store:approve:pass';无该权限时按 fallback 处理 */
  permission: string;
  /** 无权限时的表现:'hide' 不渲染(默认)| 'disabled' 渲染禁用态 */
  fallback?: 'hide' | 'disabled';
  /** fallback='disabled' 时,禁用态悬浮提示文案 */
  unauthorizedTip?: string;
}

/**
 * 权限按钮:根据后端返回的权限点自动决定显示/隐藏(或禁用)。
 * 用法:<PermButton permission={P.STORE_APPROVE_AUDIT} type="link">审核</PermButton>
 */
export const PermButton = forwardRef<HTMLButtonElement, PermButtonProps>(
  ({ permission, fallback = 'hide', unauthorizedTip, ...rest }, ref) => {
    const { canPoint } = useAccess();
    const ok = canPoint(permission);

    if (!ok && fallback === 'hide') return null;

    const btn = (
      <UButton
        ref={ref}
        {...rest}
        disabled={!ok || rest.disabled}
        style={rest.type === 'text' ? { ...rest.style, paddingInline: 0 } : rest.style}
      />
    );

    if (!ok && fallback === 'disabled' && unauthorizedTip) {
      return <UTooltip title={unauthorizedTip}>{btn}</UTooltip>;
    }
    return btn;
  },
);

PermButton.displayName = 'PermButton';