2022-04-27 12:55:43 +02:00
|
|
|
import { FormControlledComponent } from '../../models/form-component';
|
|
|
|
import { FieldPath } from 'react-hook-form/dist/types/path';
|
|
|
|
import { FieldPathValue, UnpackNestedValue } from 'react-hook-form/dist/types';
|
|
|
|
import { Controller, Path } from 'react-hook-form';
|
|
|
|
import Switch from 'react-switch';
|
|
|
|
import { AbstractFormItem, AbstractFormItemProps } from './abstract-form-item';
|
|
|
|
|
2023-01-25 11:05:16 +01:00
|
|
|
type FormSwitchProps<TFieldValues, TContext extends object> = FormControlledComponent<TFieldValues, TContext> & AbstractFormItemProps<TFieldValues> & {
|
2022-04-27 12:55:43 +02:00
|
|
|
defaultValue?: boolean,
|
2022-04-27 15:36:36 +02:00
|
|
|
onChange?: (value: boolean) => void,
|
2022-04-27 12:55:43 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* This component is a wrapper for react-switch, to use with react-hook-form.
|
|
|
|
*/
|
2022-05-10 15:22:01 +02:00
|
|
|
export const FormSwitch = <TFieldValues, TContext extends object>({ id, label, tooltip, className, error, rules, disabled, control, defaultValue, formState, warning, onChange }: FormSwitchProps<TFieldValues, TContext>) => {
|
2022-04-27 15:36:36 +02:00
|
|
|
/**
|
|
|
|
* The following callback will trigger the onChange callback, if it was passed to this component,
|
|
|
|
* when the selected option changes.
|
|
|
|
*/
|
|
|
|
const onChangeCb = (newValue: boolean): void => {
|
|
|
|
if (typeof onChange === 'function') {
|
|
|
|
onChange(newValue);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2022-04-27 12:55:43 +02:00
|
|
|
return (
|
|
|
|
<AbstractFormItem id={id} formState={formState} label={label}
|
2022-04-27 15:36:36 +02:00
|
|
|
className={`form-switch ${className || ''}`} tooltip={tooltip}
|
2022-05-10 15:22:01 +02:00
|
|
|
disabled={disabled}
|
2022-07-25 15:24:21 +02:00
|
|
|
inLine
|
2022-04-27 12:55:43 +02:00
|
|
|
rules={rules} error={error} warning={warning}>
|
|
|
|
<Controller name={id as FieldPath<TFieldValues>}
|
|
|
|
control={control}
|
|
|
|
defaultValue={defaultValue as UnpackNestedValue<FieldPathValue<TFieldValues, Path<TFieldValues>>>}
|
2022-05-09 12:11:37 +02:00
|
|
|
rules={rules}
|
2022-04-27 12:55:43 +02:00
|
|
|
render={({ field: { onChange, value, ref } }) =>
|
2022-04-27 15:36:36 +02:00
|
|
|
<Switch onChange={val => {
|
|
|
|
onChange(val);
|
|
|
|
onChangeCb(val);
|
|
|
|
}}
|
2022-05-02 15:29:32 +02:00
|
|
|
checked={value as boolean || false}
|
2022-04-27 15:36:36 +02:00
|
|
|
width={40}
|
2022-09-02 18:17:15 +02:00
|
|
|
height={19}
|
|
|
|
uncheckedIcon={false}
|
|
|
|
checkedIcon={false}
|
|
|
|
handleDiameter={15}
|
2022-04-27 15:36:36 +02:00
|
|
|
ref={ref}
|
2022-05-10 15:22:01 +02:00
|
|
|
disabled={typeof disabled === 'function' ? disabled(id) : disabled} />
|
2022-04-27 12:55:43 +02:00
|
|
|
} />
|
|
|
|
</AbstractFormItem>
|
|
|
|
);
|
|
|
|
};
|