import * as React from 'react'; import { View, Pressable, ViewStyle } from 'react-native'; import Icon from '../icon'; import { withTheme } from '../theme'; import styles from './style'; const prefixCls = 'checkbox'; type CheckboxValue = string | number; export interface CheckboxProps { checked?: boolean; value?: CheckboxValue; style?: ViewStyle; checkboxStyle?: ViewStyle; contentStyle?: ViewStyle; disabled?: boolean; theme: AnnaNative.Theme; onPress?: (e: any) => void; onChange?: (checked: boolean, e?: any, v?: CheckboxValue) => void; } const Checkbox: React.FC & { Group?: React.FC; } = props => { const { theme, checked, value, children, style, checkboxStyle, contentStyle, disabled, onPress, onChange, } = props; const { colors } = theme; const { primary } = colors; const handleChange = (e: any) => { if (disabled) { return; } onChange?.(!checked, e, value); }; let currentIcon: React.ReactNode; if (disabled) { currentIcon = ; } else { currentIcon = checked ? ( ) : ( ); } return ( {currentIcon} {children} ); }; const getCheckboxs = ( children: React.ReactNode, value: CheckboxValue[] = [], onChange?: (v?: CheckboxValue[], e?: any) => void, ) => { const onGroupChange = (_checked: any, e: any, v: CheckboxValue) => { const val: any[] = value || []; const newVal = val?.includes(v) ? val?.filter(i => i !== v) : val?.concat(v); const newValue = !Array.isArray(newVal) || newVal.length === 0 ? undefined : newVal; onChange?.(newValue, e); }; const checkboxs = React.Children.map(children, (checkbox: any) => { const p = checkbox?.props || {}; let checked = p.checked; if ((p.value || p.value === 0) && (value as CheckboxValue[])?.includes?.(p.value)) { checked = !checked; } return { ...checkbox, props: { ...checkbox.props, checked, onChange: onGroupChange, }, }; }); return checkboxs; }; export interface GroupProps { value?: CheckboxValue[]; children?: React.ReactNode; direction?: 'row' | 'column' | 'row-reverse' | 'column-reverse'; onChange?: (v?: CheckboxValue[]) => void; } const Group: React.FC = props => { const { value = [], children, direction = 'row', onChange } = props; const checkboxs = getCheckboxs(children, value, onChange); return {checkboxs}; }; const CheckboxWithTheme = withTheme(Checkbox); CheckboxWithTheme.Group = Group; export default CheckboxWithTheme;