| 1 |
import { ChangeEvent, FocusEvent } from 'react'; |
| 2 |
import { |
| 3 |
ariaDescribedByIds, |
| 4 |
descriptionId, |
| 5 |
getTemplate, |
| 6 |
schemaRequiresTrueValue, |
| 7 |
FormContextType, |
| 8 |
RJSFSchema, |
| 9 |
StrictRJSFSchema, |
| 10 |
WidgetProps, |
| 11 |
} from '@rjsf/utils'; |
| 12 |
import { Checkbox } from '@fluentui/react-components'; |
| 13 |
|
| 14 |
/** The `CheckBoxWidget` is a widget for rendering boolean properties. |
| 15 |
* It is typically used to represent a boolean. |
| 16 |
* |
| 17 |
* @param props - The `WidgetProps` for this component |
| 18 |
*/ |
| 19 |
export default function CheckboxWidget< |
| 20 |
T = any, |
| 21 |
S extends StrictRJSFSchema = RJSFSchema, |
| 22 |
F extends FormContextType = any |
| 23 |
>(props: WidgetProps<T, S, F>) { |
| 24 |
const { |
| 25 |
schema, |
| 26 |
id, |
| 27 |
value, |
| 28 |
disabled, |
| 29 |
readonly, |
| 30 |
label = '', |
| 31 |
hideLabel, |
| 32 |
autofocus, |
| 33 |
onChange, |
| 34 |
onBlur, |
| 35 |
onFocus, |
| 36 |
registry, |
| 37 |
options, |
| 38 |
uiSchema, |
| 39 |
} = props; |
| 40 |
const DescriptionFieldTemplate = getTemplate<'DescriptionFieldTemplate', T, S, F>( |
| 41 |
'DescriptionFieldTemplate', |
| 42 |
registry, |
| 43 |
options |
| 44 |
); |
| 45 |
// Because an unchecked checkbox will cause html5 validation to fail, only add |
| 46 |
// the "required" attribute if the field value must be "true", due to the |
| 47 |
// "const" or "enum" keywords |
| 48 |
const required = schemaRequiresTrueValue<S>(schema); |
| 49 |
|
| 50 |
const _onChange = ({ target: { checked } }: ChangeEvent<HTMLInputElement>) => onChange(checked); |
| 51 |
const _onBlur = ({ target: { value } }: FocusEvent<HTMLInputElement>) => onBlur(id, value); |
| 52 |
const _onFocus = ({ target: { value } }: FocusEvent<HTMLInputElement>) => onFocus(id, value); |
| 53 |
const description = options.description ?? schema.description; |
| 54 |
|
| 55 |
return ( |
| 56 |
<> |
| 57 |
{!hideLabel && !!description && ( |
| 58 |
<DescriptionFieldTemplate |
| 59 |
id={descriptionId<T>(id)} |
| 60 |
description={description} |
| 61 |
schema={schema} |
| 62 |
uiSchema={uiSchema} |
| 63 |
registry={registry} |
| 64 |
/> |
| 65 |
)} |
| 66 |
<Checkbox |
| 67 |
id={id} |
| 68 |
name={id} |
| 69 |
label={label} |
| 70 |
checked={typeof value === 'undefined' ? false : Boolean(value)} |
| 71 |
required={required} |
| 72 |
disabled={disabled || readonly} |
| 73 |
autoFocus={autofocus} |
| 74 |
onChange={_onChange} |
| 75 |
onBlur={_onBlur} |
| 76 |
onFocus={_onFocus} |
| 77 |
aria-describedby={ariaDescribedByIds<T>(id)} |
| 78 |
/> |
| 79 |
</> |
| 80 |
); |
| 81 |
} |