ConceptPortal-public/rsconcept/frontend/src/components/input/checkbox.tsx

78 lines
1.8 KiB
TypeScript
Raw Normal View History

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