ConceptPortal-public/rsconcept/frontend/src/components/ui/CheckboxTristate.tsx

93 lines
2.2 KiB
TypeScript
Raw Normal View History

import clsx from 'clsx';
2023-09-07 16:30:43 +03:00
import { globals } from '@/utils/constants';
2023-12-21 00:12:24 +03:00
import { CheckboxChecked, CheckboxNull } from '../Icons';
import { CProps } from '../props';
2023-09-07 16:30:43 +03:00
import { CheckboxProps } from './Checkbox';
export interface CheckboxTristateProps extends Omit<CheckboxProps, 'value' | 'setValue'> {
/** Current value - `null`, `true` or `false`. */
2023-12-28 14:04:44 +03:00
value: boolean | null;
/** Callback to set the `value`. */
2023-12-28 14:04:44 +03:00
setValue?: (newValue: boolean | null) => void;
2023-09-07 16:30:43 +03:00
}
/**
2024-10-30 21:35:55 +03:00
* Component that allows toggling among three states: `true`, `false`, and `null`.
*/
function CheckboxTristate({
disabled,
label,
title,
titleHtml,
2024-03-09 16:40:10 +03:00
hideTitle,
className,
value,
setValue,
...restProps
}: CheckboxTristateProps) {
const cursor = disabled ? 'cursor-arrow' : setValue ? 'cursor-pointer' : '';
function handleClick(event: CProps.EventMouse): void {
2023-09-07 16:30:43 +03:00
event.preventDefault();
2024-05-23 13:36:16 +03:00
event.stopPropagation();
2023-09-07 16:30:43 +03:00
if (disabled || !setValue) {
return;
}
if (value === false) {
2023-12-28 14:04:44 +03:00
setValue(null);
} else if (value === null) {
setValue(true);
2023-09-07 16:30:43 +03:00
} else {
setValue(false);
2023-09-07 16:30:43 +03:00
}
}
return (
2023-12-28 14:04:44 +03:00
<button
type='button'
className={clsx(
2024-03-17 19:24:12 +03:00
'flex items-center gap-2', // prettier: split lines
'outline-none',
2024-05-12 13:58:28 +03:00
'focus-frame',
cursor,
className
)}
2023-12-28 14:04:44 +03:00
disabled={disabled}
onClick={handleClick}
data-tooltip-id={!!title || !!titleHtml ? globals.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(
'w-4 h-4', // prettier: split lines
'border rounded-sm',
{
'clr-primary': value !== false,
'clr-app': value === false
}
)}
2023-12-28 14:04:44 +03:00
>
{value ? (
<div className='mt-[1px] ml-[1px]'>
<CheckboxChecked />
2023-12-28 14:04:44 +03:00
</div>
) : null}
{value == null ? (
<div className='mt-[1px] ml-[1px]'>
<CheckboxNull />
2023-12-28 14:04:44 +03:00
</div>
) : null}
</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-09-07 16:30:43 +03:00
}
export default CheckboxTristate;