( props: AriaToggleProps, state: ToggleState, ref: RefObject<HTMLInputElement | null> )
| 75 | * Handles interactions for toggle elements, e.g. Checkboxes and Switches. |
| 76 | */ |
| 77 | export function useToggle( |
| 78 | props: AriaToggleProps, |
| 79 | state: ToggleState, |
| 80 | ref: RefObject<HTMLInputElement | null> |
| 81 | ): ToggleAria { |
| 82 | let { |
| 83 | isDisabled = false, |
| 84 | isReadOnly = false, |
| 85 | value, |
| 86 | name, |
| 87 | form, |
| 88 | children, |
| 89 | isRequired, |
| 90 | validationBehavior = 'aria', |
| 91 | 'aria-label': ariaLabel, |
| 92 | 'aria-labelledby': ariaLabelledby, |
| 93 | 'aria-describedby': ariaDescribedby, |
| 94 | onPressStart, |
| 95 | onPressEnd, |
| 96 | onPressChange, |
| 97 | onPress, |
| 98 | onPressUp, |
| 99 | onClick |
| 100 | } = props; |
| 101 | |
| 102 | // Create validation state here because it doesn't make sense to add to general useToggleState. |
| 103 | let validationState = useFormValidationState({...props, value: state.isSelected}); |
| 104 | let {isInvalid, validationErrors, validationDetails} = validationState.displayValidation; |
| 105 | |
| 106 | useFormValidation(props, validationState, ref); |
| 107 | |
| 108 | let onChange: ChangeEventHandler<HTMLInputElement> = e => { |
| 109 | // since we spread props on label, onChange will end up there as well as in here. |
| 110 | // so we have to stop propagation at the lowest level that we care about |
| 111 | e.stopPropagation(); |
| 112 | state.setSelected(getEventTarget(e).checked); |
| 113 | }; |
| 114 | |
| 115 | let hasChildren = children != null; |
| 116 | let hasAriaLabel = ariaLabel != null || ariaLabelledby != null; |
| 117 | if (!hasChildren && !hasAriaLabel && process.env.NODE_ENV !== 'production') { |
| 118 | console.warn( |
| 119 | 'If you do not provide children, you must specify an aria-label for accessibility' |
| 120 | ); |
| 121 | } |
| 122 | |
| 123 | // Handle press state for keyboard interactions and cases where labelProps is not used. |
| 124 | let {pressProps, isPressed} = usePress({ |
| 125 | onPressStart, |
| 126 | onPressEnd, |
| 127 | onPressChange, |
| 128 | onPress, |
| 129 | onPressUp, |
| 130 | onClick, |
| 131 | isDisabled |
| 132 | }); |
| 133 | |
| 134 | // Handle press state on the label. |
no test coverage detected