2020-10-25 22:47:50 +00:00
|
|
|
import { useField } from 'formik';
|
2022-11-25 20:25:03 +00:00
|
|
|
import type { ReactNode } from 'react';
|
|
|
|
import { memo, useCallback } from 'react';
|
|
|
|
import isEqual from 'react-fast-compare';
|
2020-10-25 22:47:50 +00:00
|
|
|
import tw from 'twin.macro';
|
2022-11-25 20:25:03 +00:00
|
|
|
|
|
|
|
import TitledGreyBox from '@/components/elements/TitledGreyBox';
|
2020-10-25 22:47:50 +00:00
|
|
|
import Input from '@/components/elements/Input';
|
|
|
|
|
|
|
|
interface Props {
|
2022-11-25 20:25:03 +00:00
|
|
|
children?: ReactNode;
|
|
|
|
className?: string;
|
|
|
|
|
|
|
|
isEditable?: boolean;
|
2020-10-25 22:47:50 +00:00
|
|
|
title: string;
|
|
|
|
permissions: string[];
|
|
|
|
}
|
|
|
|
|
2022-11-25 20:25:03 +00:00
|
|
|
function PermissionTitleBox({ isEditable, title, permissions, className, children }: Props) {
|
2022-06-26 19:13:52 +00:00
|
|
|
const [{ value }, , { setValue }] = useField<string[]>('permissions');
|
2020-10-25 22:47:50 +00:00
|
|
|
|
2022-06-26 19:13:52 +00:00
|
|
|
const onCheckboxClicked = useCallback(
|
|
|
|
(e: React.ChangeEvent<HTMLInputElement>) => {
|
|
|
|
if (e.currentTarget.checked) {
|
2022-11-25 20:25:03 +00:00
|
|
|
setValue([...value, ...permissions.filter(p => !value.includes(p))]);
|
2022-06-26 19:13:52 +00:00
|
|
|
} else {
|
2022-11-25 20:25:03 +00:00
|
|
|
setValue(value.filter(p => !permissions.includes(p)));
|
2022-06-26 19:13:52 +00:00
|
|
|
}
|
|
|
|
},
|
2022-11-25 20:25:03 +00:00
|
|
|
[permissions, value],
|
2022-06-26 19:13:52 +00:00
|
|
|
);
|
2020-10-25 22:47:50 +00:00
|
|
|
|
|
|
|
return (
|
|
|
|
<TitledGreyBox
|
|
|
|
title={
|
|
|
|
<div css={tw`flex items-center`}>
|
|
|
|
<p css={tw`text-sm uppercase flex-1`}>{title}</p>
|
2022-06-26 19:13:52 +00:00
|
|
|
{isEditable && (
|
|
|
|
<Input
|
|
|
|
type={'checkbox'}
|
2022-11-25 20:25:03 +00:00
|
|
|
checked={permissions.every(p => value.includes(p))}
|
2022-06-26 19:13:52 +00:00
|
|
|
onChange={onCheckboxClicked}
|
|
|
|
/>
|
|
|
|
)}
|
2020-10-25 22:47:50 +00:00
|
|
|
</div>
|
|
|
|
}
|
|
|
|
className={className}
|
|
|
|
>
|
|
|
|
{children}
|
|
|
|
</TitledGreyBox>
|
|
|
|
);
|
2022-11-25 20:25:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const MemoizedPermissionTitleBox = memo(PermissionTitleBox, isEqual);
|
2020-10-25 22:47:50 +00:00
|
|
|
|
2022-11-25 20:25:03 +00:00
|
|
|
export default MemoizedPermissionTitleBox;
|