2022-04-24 10:39:11 +02:00
|
|
|
import { ChangeEvent, FC, PropsWithChildren } from 'react';
|
2020-07-14 16:12:14 +02:00
|
|
|
import classNames from 'classnames';
|
2020-08-22 19:03:25 +02:00
|
|
|
import { identity } from 'ramda';
|
2022-04-03 10:10:10 +02:00
|
|
|
import { useDomId } from './helpers/hooks';
|
2020-07-14 16:12:14 +02:00
|
|
|
|
2022-04-24 10:39:11 +02:00
|
|
|
export type BooleanControlProps = PropsWithChildren<{
|
2020-08-22 19:03:25 +02:00
|
|
|
checked?: boolean;
|
|
|
|
onChange?: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void;
|
|
|
|
className?: string;
|
2020-11-28 09:34:41 +01:00
|
|
|
inline?: boolean;
|
2022-04-24 10:39:11 +02:00
|
|
|
}>;
|
2020-07-14 16:12:14 +02:00
|
|
|
|
2020-08-22 19:03:25 +02:00
|
|
|
interface BooleanControlWithTypeProps extends BooleanControlProps {
|
|
|
|
type: 'switch' | 'checkbox';
|
|
|
|
}
|
2020-07-14 16:12:14 +02:00
|
|
|
|
2022-05-28 11:16:59 +02:00
|
|
|
export const BooleanControl: FC<BooleanControlWithTypeProps> = (
|
2020-11-28 09:34:41 +01:00
|
|
|
{ checked = false, onChange = identity, className, children, type, inline = false },
|
2020-08-22 19:03:25 +02:00
|
|
|
) => {
|
2022-04-03 10:10:10 +02:00
|
|
|
const id = useDomId();
|
2020-08-22 19:03:25 +02:00
|
|
|
const onChecked = (e: ChangeEvent<HTMLInputElement>) => onChange(e.target.checked, e);
|
2020-07-14 16:12:14 +02:00
|
|
|
const typeClasses = {
|
2022-03-05 14:04:01 +01:00
|
|
|
'form-switch': type === 'switch',
|
|
|
|
'form-checkbox': type === 'checkbox',
|
2020-07-14 16:12:14 +02:00
|
|
|
};
|
2020-11-28 09:34:41 +01:00
|
|
|
const style = inline ? { display: 'inline-block' } : {};
|
2020-07-14 16:12:14 +02:00
|
|
|
|
|
|
|
return (
|
2022-03-05 14:04:01 +01:00
|
|
|
<span className={classNames('form-check', typeClasses, className)} style={style}>
|
|
|
|
<input type="checkbox" className="form-check-input" id={id} checked={checked} onChange={onChecked} />
|
|
|
|
<label className="form-check-label" htmlFor={id}>{children}</label>
|
2020-07-14 16:12:14 +02:00
|
|
|
</span>
|
|
|
|
);
|
|
|
|
};
|