Portal/rsconcept/frontend/src/components/Input/Checkbox.tsx

81 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-06-07 20:17:03 +03:00
import clsx from 'clsx';
2025-02-20 18:10:34 +03:00
import { globalIDs } from '@/utils/constants';
2024-06-07 20:17:03 +03:00
import { CheckboxChecked } from '../Icons';
2025-02-22 14:03:13 +03:00
import { type Button } from '../props';
2025-02-20 20:22:05 +03:00
export interface CheckboxProps extends Omit<Button, 'value' | 'onClick' | 'onChange'> {
/** Label to display next to the checkbox. */
2024-06-07 20:17:03 +03:00
label?: string;
/** Indicates whether the checkbox is disabled. */
2024-06-07 20:17:03 +03:00
disabled?: boolean;
/** Current value - `true` or `false`. */
value?: boolean;
/** Callback to set the `value`. */
onChange?: (newValue: boolean) => void;
2024-06-07 20:17:03 +03:00
}
/**
2024-10-30 21:35:43 +03:00
* Component that allows toggling a boolean value.
*/
2025-02-07 10:53:49 +03:00
export function Checkbox({
2024-06-07 20:17:03 +03:00
disabled,
label,
title,
titleHtml,
hideTitle,
className,
value,
onChange,
2024-06-07 20:17:03 +03:00
...restProps
}: CheckboxProps) {
const cursor = disabled ? 'cursor-arrow' : onChange ? 'cursor-pointer' : '';
2024-06-07 20:17:03 +03:00
2025-02-22 14:03:13 +03:00
function handleClick(event: React.MouseEvent<Element>): void {
2024-06-07 20:17:03 +03:00
event.preventDefault();
event.stopPropagation();
if (disabled || !onChange) {
2024-06-07 20:17:03 +03:00
return;
}
onChange(!value);
2024-06-07 20:17:03 +03:00
}
return (
<button
type='button'
className={clsx(
2025-01-23 19:41:31 +03:00
'flex items-center gap-2', //
2025-02-20 20:22:05 +03:00
'outline-hidden',
2024-06-07 20:17:03 +03:00
'focus-frame',
cursor,
className
)}
disabled={disabled}
onClick={handleClick}
2025-02-20 18:10:34 +03:00
data-tooltip-id={!!title || !!titleHtml ? globalIDs.tooltip : undefined}
2024-06-07 20:17:03 +03:00
data-tooltip-html={titleHtml}
data-tooltip-content={title}
data-tooltip-hidden={hideTitle}
{...restProps}
>
<div
className={clsx(
2025-03-09 21:57:21 +03:00
'w-4 h-4', //
2025-02-20 20:22:05 +03:00
'border rounded-xs',
2024-06-07 20:17:03 +03:00
{
2024-12-17 11:37:42 +03:00
'bg-sec-600 text-sec-0': value !== false,
2024-12-17 10:52:36 +03:00
'bg-prim-100': value === false
2024-06-07 20:17:03 +03:00
}
)}
>
2024-12-20 13:36:31 +03:00
{value ? <CheckboxChecked /> : null}
2024-06-07 20:17:03 +03:00
</div>
{label ? <span className={clsx('text-start text-sm whitespace-nowrap select-text', cursor)}>{label}</span> : null}
</button>
);
}