2020-12-06 15:07:44 +03:00
|
|
|
import { ChangeEvent, FC, useRef } from 'react';
|
2020-07-14 17:12:14 +03:00
|
|
|
import classNames from 'classnames';
|
|
|
|
import { v4 as uuid } from 'uuid';
|
2020-08-22 20:03:25 +03:00
|
|
|
import { identity } from 'ramda';
|
2020-07-14 17:12:14 +03:00
|
|
|
|
2020-08-22 20:03:25 +03:00
|
|
|
export interface BooleanControlProps {
|
|
|
|
checked?: boolean;
|
|
|
|
onChange?: (checked: boolean, e: ChangeEvent<HTMLInputElement>) => void;
|
|
|
|
className?: string;
|
2020-11-28 11:34:41 +03:00
|
|
|
inline?: boolean;
|
2020-08-22 20:03:25 +03:00
|
|
|
}
|
2020-07-14 17:12:14 +03:00
|
|
|
|
2020-08-22 20:03:25 +03:00
|
|
|
interface BooleanControlWithTypeProps extends BooleanControlProps {
|
|
|
|
type: 'switch' | 'checkbox';
|
|
|
|
}
|
2020-07-14 17:12:14 +03:00
|
|
|
|
2020-08-22 20:03:25 +03:00
|
|
|
const BooleanControl: FC<BooleanControlWithTypeProps> = (
|
2020-11-28 11:34:41 +03:00
|
|
|
{ checked = false, onChange = identity, className, children, type, inline = false },
|
2020-08-22 20:03:25 +03:00
|
|
|
) => {
|
2020-12-06 15:07:44 +03:00
|
|
|
const { current: id } = useRef(uuid());
|
2020-08-22 20:03:25 +03:00
|
|
|
const onChecked = (e: ChangeEvent<HTMLInputElement>) => onChange(e.target.checked, e);
|
2020-07-14 17:12:14 +03:00
|
|
|
const typeClasses = {
|
|
|
|
'custom-switch': type === 'switch',
|
|
|
|
'custom-checkbox': type === 'checkbox',
|
|
|
|
};
|
2020-11-28 11:34:41 +03:00
|
|
|
const style = inline ? { display: 'inline-block' } : {};
|
2020-07-14 17:12:14 +03:00
|
|
|
|
|
|
|
return (
|
2020-11-28 11:34:41 +03:00
|
|
|
<span className={classNames('custom-control', typeClasses, className)} style={style}>
|
2020-07-14 17:12:14 +03:00
|
|
|
<input type="checkbox" className="custom-control-input" id={id} checked={checked} onChange={onChecked} />
|
|
|
|
<label className="custom-control-label" htmlFor={id}>{children}</label>
|
|
|
|
</span>
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default BooleanControl;
|