import * as React from 'react'; import classNames from 'classnames'; import { classNameModifier, classNameModifierByFlag } from '../shared/utils'; import { ComponentClassNames } from '../shared/constants'; import { Flex } from '../Flex'; import { FieldErrorMessage } from '../Field'; import { Input } from '../Input'; import { Label } from '../Label'; import { ForwardRefPrimitive, Primitive, BaseSwitchFieldProps, SwitchFieldProps, } from '../types'; import { useStableId } from '../utils/useStableId'; import { useSwitch } from './useSwitch'; import { View } from '../View'; import { VisuallyHidden } from '../VisuallyHidden'; const SwitchFieldPrimitive: Primitive = ( { className, defaultChecked, id, isChecked, isDisabled, isLabelHidden, label, labelPosition, name, onChange, size, thumbColor, trackCheckedColor, trackColor, value, hasError, errorMessage, ...rest }, ref ) => { const { isOn, changeHandler, isFocused, setIsFocused } = useSwitch({ onChange, isChecked, defaultChecked, isDisabled, }); const fieldId = useStableId(id); const LabelType = isLabelHidden ? VisuallyHidden : View; const wrapperClasses = classNames( ComponentClassNames.SwitchTrack, classNameModifierByFlag(ComponentClassNames.SwitchTrack, 'checked', isOn), classNameModifierByFlag( ComponentClassNames.SwitchTrack, 'disabled', isDisabled ), classNameModifierByFlag( ComponentClassNames.SwitchTrack, 'focused', isFocused ), classNameModifierByFlag(ComponentClassNames.SwitchTrack, 'error', hasError) ); const componentClasses = classNames( ComponentClassNames.SwitchThumb, classNameModifierByFlag(ComponentClassNames.SwitchThumb, 'checked', isOn), classNameModifierByFlag( ComponentClassNames.SwitchThumb, 'disabled', isDisabled ) ); return ( { setIsFocused(true); }} onBlur={() => { setIsFocused(false); }} /> ); }; /** * [📖 Docs](https://ui.docs.amplify.aws/react/components/switchfield) */ export const SwitchField: ForwardRefPrimitive = React.forwardRef(SwitchFieldPrimitive); SwitchField.displayName = 'SwitchField';