-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathCheckbox.tsx
More file actions
88 lines (77 loc) · 2.43 KB
/
Copy pathCheckbox.tsx
File metadata and controls
88 lines (77 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { Checkbox, Form } from "antd";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
type EnsembleAction,
unwrapWidget,
useRegisterBindings,
} from "@ensembleui/react-framework";
import { cloneDeep, isString } from "lodash-es";
import type { EnsembleWidgetProps } from "../../shared/types";
import { EnsembleRuntime } from "../../runtime";
import { WidgetRegistry } from "../../registry";
import { useEnsembleAction } from "../../runtime/hooks";
import type { FormInputProps } from "./types";
import { EnsembleFormItem } from "./FormItem";
const widgetName = "Checkbox";
export type CheckBoxProps = {
trailingText?: string | { [key: string]: unknown };
leadingText?: string;
onChange?: EnsembleAction;
} & EnsembleWidgetProps &
FormInputProps<boolean>;
export const CheckboxWidget: React.FC<CheckBoxProps> = (props) => {
const [checked, setChecked] = useState<boolean>();
const { rootRef, values } = useRegisterBindings(
{ ...props, initialValue: props.value, value: checked, widgetName },
props.id,
{
setValue: setChecked,
},
);
const action = useEnsembleAction(props.onChange);
const trailingContent = useMemo(() => {
if (values?.trailingText) {
if (isString(values.trailingText)) {
return values.trailingText;
}
return EnsembleRuntime.render([
unwrapWidget(cloneDeep(values.trailingText)),
]);
}
}, [values?.trailingText]);
const handleChange = useCallback(
(newValue: boolean) => {
setChecked(newValue);
action?.callback({ value: newValue });
},
[action?.callback],
);
const formInstance = Form.useFormInstance();
useEffect(() => {
setChecked(Boolean(values?.initialValue));
}, [values?.initialValue]);
useEffect(() => {
if (formInstance) {
formInstance.setFieldsValue({
[values?.id ?? values?.label ?? ""]: checked,
});
}
}, [checked, formInstance]);
return (
<EnsembleFormItem valuePropName="checked" values={values}>
<Checkbox
checked={Boolean(values?.value)}
disabled={values?.enabled === false}
onChange={(event): void => handleChange(event.target.checked)}
ref={rootRef}
style={{
marginLeft: `${props.leadingText ? "4px" : "0px"}`,
...values?.styles,
}}
>
{trailingContent}
</Checkbox>
</EnsembleFormItem>
);
};
WidgetRegistry.register(widgetName, CheckboxWidget);