import omit from 'lodash/omit'; import React, { memo, ReactElement } from 'react'; import { ScrollView } from 'react-native'; import { useControllableValue } from 'ahooks'; import Space from '../space'; import Checkbox from './checkbox'; import type { CheckboxGroupProps } from './interface'; function CheckboxGroup({ options, multiple, highlight, labelAlign, editable = true, scrollable = false, checkboxComponent: PropsCheckboxComponent, checkboxComponentStyle, renderIcon, defaultValue, disabled, onDisabledPress, ...restProps }: CheckboxGroupProps) { const [value, onChange] = useControllableValue( restProps, { defaultValue: multiple ? defaultValue ?? [] : defaultValue, } ); const CheckboxComponent = PropsCheckboxComponent || Checkbox; const contentJSX = ( {options.map((item) => { const selected = multiple ? ((value ?? []) as T[])?.indexOf?.(item.value) > -1 : value === item.value; return ( { if (!editable) { return; } const isReset = _value !== item.value; if (multiple) { const oldValue = (value ?? []) as T[]; const newValue = isReset ? oldValue.filter((v) => v !== item.value) : [item.value, ...oldValue]; const newOptions = newValue.map((v) => { const optionIndex = options.findIndex((o) => o.value === v); return { ...options[optionIndex], }; }); onChange(newValue, newOptions); } else { const newValue = isReset ? undefined : _value; const newOptions = isReset ? undefined : options.filter((o) => o.value === _value); onChange(newValue, newOptions); } }} onDisabledPress={() => onDisabledPress?.(item)} /> ); })} ); if (scrollable && restProps.direction === 'horizontal' && !restProps.wrap) { return ( {contentJSX} ); } return contentJSX; } export default memo(CheckboxGroup) as ( p: CheckboxGroupProps ) => ReactElement;