2022-11-25 13:25:03 -07:00
|
|
|
import type { ReactNode } from 'react';
|
|
|
|
import { memo } from 'react';
|
2020-08-25 21:25:31 -07:00
|
|
|
import isEqual from 'react-fast-compare';
|
2022-11-25 13:25:03 -07:00
|
|
|
import { usePermissions } from '@/plugins/usePermissions';
|
2020-03-28 17:25:04 -07:00
|
|
|
|
|
|
|
interface Props {
|
|
|
|
action: string | string[];
|
2020-03-29 21:52:18 -07:00
|
|
|
matchAny?: boolean;
|
2022-11-25 13:25:03 -07:00
|
|
|
renderOnError?: ReactNode | null;
|
|
|
|
children: ReactNode;
|
2020-03-28 17:25:04 -07:00
|
|
|
}
|
|
|
|
|
2022-11-25 13:25:03 -07:00
|
|
|
function Can({ action, matchAny = false, renderOnError, children }: Props) {
|
2020-03-29 14:19:17 -07:00
|
|
|
const can = usePermissions(action);
|
2020-03-28 17:25:04 -07:00
|
|
|
|
|
|
|
return (
|
|
|
|
<>
|
2022-11-25 13:25:03 -07:00
|
|
|
{(matchAny && can.filter(p => p).length > 0) || (!matchAny && can.every(p => p)) ? children : renderOnError}
|
2020-03-28 17:25:04 -07:00
|
|
|
</>
|
|
|
|
);
|
2022-11-25 13:25:03 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
const MemoizedCan = memo(Can, isEqual);
|
2020-03-28 17:25:04 -07:00
|
|
|
|
2022-11-25 13:25:03 -07:00
|
|
|
export default MemoizedCan;
|