2023-09-07 16:30:43 +03:00
|
|
|
import { useMemo } from 'react';
|
2023-08-02 18:24:17 +03:00
|
|
|
|
2023-09-07 16:30:43 +03:00
|
|
|
import { CheckboxChecked } from '../Icons';
|
2023-07-15 17:46:19 +03:00
|
|
|
import Label from './Label';
|
|
|
|
|
2023-07-20 17:11:03 +03:00
|
|
|
export interface CheckboxProps {
|
|
|
|
id?: string
|
|
|
|
label?: string
|
2023-07-15 17:46:19 +03:00
|
|
|
required?: boolean
|
|
|
|
disabled?: boolean
|
|
|
|
widthClass?: string
|
2023-07-31 22:38:58 +03:00
|
|
|
tooltip?: string
|
2023-07-15 17:46:19 +03:00
|
|
|
|
2023-09-07 16:30:43 +03:00
|
|
|
value: boolean
|
|
|
|
setValue?: (newValue: boolean) => void
|
|
|
|
}
|
2023-08-02 18:24:17 +03:00
|
|
|
|
2023-09-07 16:30:43 +03:00
|
|
|
function Checkbox({ id, required, disabled, tooltip, label, widthClass = 'w-fit', value, setValue }: CheckboxProps) {
|
|
|
|
const cursor = useMemo(
|
|
|
|
() => {
|
|
|
|
if (disabled) {
|
|
|
|
return 'cursor-not-allowed';
|
|
|
|
} else if (setValue) {
|
|
|
|
return 'cursor-pointer';
|
|
|
|
} else {
|
|
|
|
return ''
|
|
|
|
}
|
|
|
|
}, [disabled, setValue]);
|
|
|
|
const bgColor = useMemo(
|
|
|
|
() => {
|
|
|
|
return value !== false ? 'clr-primary' : 'clr-app'
|
|
|
|
}, [value]);
|
2023-08-02 18:24:17 +03:00
|
|
|
|
2023-08-29 15:17:16 +03:00
|
|
|
function handleClick(event: React.MouseEvent<HTMLButtonElement, MouseEvent>): void {
|
2023-08-02 18:24:17 +03:00
|
|
|
event.preventDefault();
|
2023-09-07 16:30:43 +03:00
|
|
|
if (disabled || !setValue) {
|
|
|
|
return;
|
2023-08-02 18:24:17 +03:00
|
|
|
}
|
2023-09-07 16:30:43 +03:00
|
|
|
setValue(!value);
|
2023-09-04 20:37:55 +03:00
|
|
|
}
|
2023-08-02 18:24:17 +03:00
|
|
|
|
2023-07-15 17:46:19 +03:00
|
|
|
return (
|
2023-08-29 15:17:16 +03:00
|
|
|
<button
|
2023-09-07 16:30:43 +03:00
|
|
|
id={id}
|
|
|
|
className={`flex items-center [&:not(:first-child)]:mt-3 clr-outline focus:outline-dotted focus:outline-1 ${widthClass}`}
|
2023-08-29 15:17:16 +03:00
|
|
|
title={tooltip}
|
|
|
|
disabled={disabled}
|
|
|
|
onClick={handleClick}
|
|
|
|
>
|
2023-09-07 16:30:43 +03:00
|
|
|
<div className={`relative peer w-4 h-4 shrink-0 mt-0.5 border rounded-sm appearance-none ${bgColor} ${cursor}`} />
|
2023-08-02 18:24:17 +03:00
|
|
|
{ label &&
|
|
|
|
<Label
|
2023-09-07 16:30:43 +03:00
|
|
|
className={`${cursor} px-2 text-start`}
|
2023-07-15 17:46:19 +03:00
|
|
|
text={label}
|
|
|
|
required={required}
|
|
|
|
htmlFor={id}
|
2023-07-20 17:11:03 +03:00
|
|
|
/>}
|
2023-09-07 16:30:43 +03:00
|
|
|
{value && <CheckboxChecked />}
|
2023-08-29 15:17:16 +03:00
|
|
|
</button>
|
2023-07-15 17:46:19 +03:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2023-07-25 20:27:29 +03:00
|
|
|
export default Checkbox;
|