import React, { memo, isValidElement, ReactElement } from 'react'; import { View, TouchableOpacity, TouchableWithoutFeedback, StyleSheet, } from 'react-native'; import { isString, isNil } from 'lodash'; import { useControllableValue } from 'ahooks'; import Theme from '../theme'; import CheckboxIcon from './checkbox-icon'; import type { CheckboxProps } from './interface'; import { varCreator, styleCreator } from './style'; import ShouldRender from '../../components/ShouldRender'; import { useTheme } from '../../components/Theme/Theme'; import { renderHighLightTextLikeJSX } from '../helpers'; import Image from '../../components/Image'; const isValidString = (v: React.ReactNode) => isString(v) && v !== ''; function Checkbox({ textStyle, labelTextStyle, subLabelTextStyle, iconStyle, activeValue = true as unknown as ActiveValueT, inactiveValue = false as unknown as InactiveValueT, label, labelProps, subLabel, subLabelProps, labelDisabled = false, labelPosition = 'right', iconSize = 20, renderIcon, disabled, activeColor, style, children, prefixIcon, highlight, testID, onDisabledPress, contentLabel, contentLabelProps, contenStyle, contentLabelTextStyle, ...restProps }: CheckboxProps) { if (disabled) { labelDisabled = disabled; } const token = useTheme(); const [value, onChange] = useControllableValue( restProps, { defaultValue: inactiveValue, } ); const TOKENS = Theme.useThemeTokens(); const CV = Theme.createVar(TOKENS, varCreator); // @ts-ignore const STYLES = Theme.createStyle(CV, styleCreator); const active = value === activeValue; const onChangeValue = () => { if (labelDisabled) return; const newValue = active ? inactiveValue : activeValue; onChange(newValue); }; const prefixRender = ( <> {prefixIcon} ); const labelJSX = !isNil(label) ? ( {prefixRender} {renderHighLightTextLikeJSX( label, StyleSheet.flatten([ STYLES.label, labelTextStyle, disabled ? STYLES.label_disabled : null, ]), highlight, labelProps )} {renderHighLightTextLikeJSX( subLabel, StyleSheet.flatten([ STYLES.subLabel, subLabelTextStyle, disabled ? STYLES.label_disabled : null, ]), highlight, subLabelProps )} {renderHighLightTextLikeJSX( contentLabel, StyleSheet.flatten([ STYLES.contentLabel, contentLabelTextStyle, disabled ? STYLES.label_disabled : null, ]), highlight, contentLabelProps )} ) : ( children ); const iconProps = { style: iconStyle, active, activeColor, disabled, size: iconSize, onPress: onChangeValue, }; const iconJSX = renderIcon ? ( renderIcon(iconProps) ) : ( ); return ( {labelPosition === 'left' ? labelJSX : null} {iconJSX} {labelPosition === 'right' ? labelJSX : null} ); } export default memo(Checkbox) as < ActiveValueT = boolean, InactiveValueT = boolean >( p: CheckboxProps ) => ReactElement;