import * as React from 'react'; import { ThemedComponentClass, themr } from '@friendsofreactjs/react-css-themr'; import { SWITCHCHECKBOX } from '../ThemeIdentifiers'; import * as baseTheme from './SwitchCheckbox.scss'; import { createUniqueIDFactory } from '@shopify/javascript-utilities/other'; import { classNames } from '@shopify/react-utilities/styles'; import VisuallyHidden from '../VisuallyHidden'; import { Spinner,FlexBox,Icon } from '../../../src/components/'; export type ISwitchType = 'normal' | 'trueFalse' | 'yesNo'; export interface Props { // Set theme for SwitchCheckbox theme?: any; // To apply custom styling. componentStyle?: React.CSSProperties; // Set a custom class componentClass?: string; componentId?: string; children?: React.ReactNode; // component props to handle toggle disabled?: boolean; isOpen?: boolean; handleToggle: (value?: boolean) => void; switchType?: ISwitchType; allowNull?: boolean; loading?: boolean markIfRequired?: boolean errors?: [string] | null; } const getUniqueName = createUniqueIDFactory('SwitchCheckbox'); const getFalseRadioName = createUniqueIDFactory('falseRadio'); const getNullRadioName = createUniqueIDFactory('nullRadio'); const getTrueRadioName = createUniqueIDFactory('trueRadio'); const SwitchCheckbox = (props: Props) => { const [names] = React.useState(() => { const fieldName = getUniqueName(); const falseRadio = getFalseRadioName(); const nullRadio = getNullRadioName(); const trueRadio = getTrueRadioName(); return { fieldName, falseRadio, nullRadio, trueRadio, }; }); const [onHover, SetOnHover] = React.useState(false) const { theme, componentClass, componentStyle, isOpen:propIsOpen, allowNull = true, disabled, loading = false, markIfRequired, errors } = props; const { children, handleToggle, switchType = 'normal' } = props; const isOpen = loading ? !propIsOpen : propIsOpen; let switchTypeClass = theme.switchNormal; switch (switchType) { case 'normal': switchTypeClass = theme.switchNormal; break; case 'trueFalse': switchTypeClass = theme.switchTrueFalse; break; case 'yesNo': switchTypeClass = theme.switchYesNo; break; default: switchTypeClass = theme.switchNormal; break; } const className = classNames( componentClass, theme.switchCheckbox, switchTypeClass, isOpen === false && theme.falseSelect, isOpen === true && theme.trueSelect, typeof isOpen !== 'boolean' && !isOpen && theme.nullSelect, disabled && theme.disableSwitch, loading === true && theme.loadingSelect ); return (
{allowNull !== false && }
{ children && {markIfRequired && } {onHover &&
{errors instanceof Array ? errors.join(', ') : (typeof errors === 'string' ? errors : 'An error occurred.')}
} {errors &&
SetOnHover(true)} onMouseLeave={() => SetOnHover(false)}>
}
}
); }; export default themr(SWITCHCHECKBOX, baseTheme)(SwitchCheckbox) as ThemedComponentClass;