1 | 'use client';
|
2 |
|
3 | import _extends from "@babel/runtime/helpers/esm/extends";
|
4 | import * as React from 'react';
|
5 | import { unstable_useControlled as useControlled, unstable_useForkRef as useForkRef, unstable_useIsFocusVisible as useIsFocusVisible } from '@mui/utils';
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 | export function useSwitch(props) {
|
18 | const {
|
19 | checked: checkedProp,
|
20 | defaultChecked,
|
21 | disabled,
|
22 | onBlur,
|
23 | onChange,
|
24 | onFocus,
|
25 | onFocusVisible,
|
26 | readOnly,
|
27 | required
|
28 | } = props;
|
29 | const [checked, setCheckedState] = useControlled({
|
30 | controlled: checkedProp,
|
31 | default: Boolean(defaultChecked),
|
32 | name: 'Switch',
|
33 | state: 'checked'
|
34 | });
|
35 | const createHandleInputChange = otherProps => event => {
|
36 |
|
37 | if (event.nativeEvent.defaultPrevented) {
|
38 | return;
|
39 | }
|
40 | setCheckedState(event.target.checked);
|
41 | onChange?.(event);
|
42 | otherProps.onChange?.(event);
|
43 | };
|
44 | const {
|
45 | isFocusVisibleRef,
|
46 | onBlur: handleBlurVisible,
|
47 | onFocus: handleFocusVisible,
|
48 | ref: focusVisibleRef
|
49 | } = useIsFocusVisible();
|
50 | const [focusVisible, setFocusVisible] = React.useState(false);
|
51 | if (disabled && focusVisible) {
|
52 | setFocusVisible(false);
|
53 | }
|
54 | React.useEffect(() => {
|
55 | isFocusVisibleRef.current = focusVisible;
|
56 | }, [focusVisible, isFocusVisibleRef]);
|
57 | const inputRef = React.useRef(null);
|
58 | const createHandleFocus = otherProps => event => {
|
59 |
|
60 | if (!inputRef.current) {
|
61 | inputRef.current = event.currentTarget;
|
62 | }
|
63 | handleFocusVisible(event);
|
64 | if (isFocusVisibleRef.current === true) {
|
65 | setFocusVisible(true);
|
66 | onFocusVisible?.(event);
|
67 | }
|
68 | onFocus?.(event);
|
69 | otherProps.onFocus?.(event);
|
70 | };
|
71 | const createHandleBlur = otherProps => event => {
|
72 | handleBlurVisible(event);
|
73 | if (isFocusVisibleRef.current === false) {
|
74 | setFocusVisible(false);
|
75 | }
|
76 | onBlur?.(event);
|
77 | otherProps.onBlur?.(event);
|
78 | };
|
79 | const handleInputRef = useForkRef(focusVisibleRef, inputRef);
|
80 | const getInputProps = (otherProps = {}) => _extends({
|
81 | checked: checkedProp,
|
82 | defaultChecked,
|
83 | disabled,
|
84 | readOnly,
|
85 | ref: handleInputRef,
|
86 | required,
|
87 | type: 'checkbox',
|
88 | role: 'switch',
|
89 | 'aria-checked': checkedProp
|
90 | }, otherProps, {
|
91 | onChange: createHandleInputChange(otherProps),
|
92 | onFocus: createHandleFocus(otherProps),
|
93 | onBlur: createHandleBlur(otherProps)
|
94 | });
|
95 | return {
|
96 | checked,
|
97 | disabled: Boolean(disabled),
|
98 | focusVisible,
|
99 | getInputProps,
|
100 | inputRef: handleInputRef,
|
101 | readOnly: Boolean(readOnly)
|
102 | };
|
103 | } |
\ | No newline at end of file |