-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathuseSwitch.ts
59 lines (55 loc) · 1.57 KB
/
useSwitch.ts
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
import type { InputHTMLAttributes } from 'react';
// import { CheckboxGroupContext } from '../Checkbox/CheckboxGroup';
import type { FormField } from '../useFormField';
import { useFormField } from '../useFormField';
import type { SwitchProps } from './Switch';
type UseCheckbox = (props: SwitchProps) => FormField & {
inputProps?: Pick<
InputHTMLAttributes<HTMLInputElement>,
| 'readOnly'
| 'type'
| 'name'
| 'required'
| 'defaultChecked'
| 'checked'
| 'onClick'
| 'onChange'
>;
};
/** Handles props for `Switch` in context with `Checkbox.Group` (and `Fieldset`) */
export const useSwitch: UseCheckbox = (props) => {
// const checkboxGroup = useContext(CheckboxGroupContext);
const { inputProps, readOnly, ...rest } = useFormField(props, 'switch');
const propsValue = props.value || '';
return {
...rest,
readOnly,
inputProps: {
...inputProps,
readOnly,
type: 'checkbox',
role: 'switch',
// defaultChecked: checkboxGroup?.defaultValue
// ? checkboxGroup?.defaultValue.includes(propsValue)
// : props.defaultChecked,
// checked: checkboxGroup?.value
// ? checkboxGroup?.value.includes(propsValue)
// : props.checked,
onClick: (e) => {
if (readOnly) {
e.preventDefault();
return;
}
props?.onClick?.(e);
},
onChange: (e) => {
if (readOnly) {
e.preventDefault();
return;
}
props?.onChange?.(e);
// checkboxGroup?.toggleValue(propsValue);
},
},
};
};