PermButton.tsx
1.38 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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';