Debian Codegraph @

packages/mui/src/CheckboxWidget/CheckboxWidget.tsx

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