import React, { isValidElement } from 'react'; import { StyleSheet } from 'react-native'; import createStyles from './styles/FlatSelect.style'; import { Option, Group } from './interface'; type StylesType = ReturnType; export const addLabelPosition = ( currentOptions: Option[], styles: StylesType ): Option[] => { return currentOptions?.map?.((option) => { const { labelTextStyle, subLabelTextStyle, contentLabelTextStyle } = option; return { ...option, labelPosition: option.labelPosition || 'left', labelTextStyle: StyleSheet.flatten([styles.label, labelTextStyle]), subLabelTextStyle: StyleSheet.flatten([ styles.subLabel, subLabelTextStyle, ]), contentLabelTextStyle: StyleSheet.flatten([ styles.contenLabel, contentLabelTextStyle, ]), }; }); }; export const isContainStr = ({ data, searchStr, }: { data: React.ReactNode; searchStr: string; }) => { if (!data) return false; if (!isValidElement(data)) { return String(data) .toLocaleLowerCase() .includes(searchStr.toLocaleLowerCase()); } return true; }; export const doFilterOptions = ( optionList: Option[], searchStr: string, filterOption?: (input: string, option: Option) => boolean ): Option[] => { return optionList.filter((option: Option) => { if (filterOption) { return filterOption(searchStr, option); } return ( isContainStr({ data: option?.label, searchStr }) || isContainStr({ data: option?.subLabel, searchStr }) || isContainStr({ data: option?.contentLabel, searchStr }) ); }); }; export const doFilterGroupOptions = ( groupList: Group[], searchStr: string, filterOption?: (input: string, option: Option) => boolean ): Group[] => { const filterGroup: Group[] = []; groupList.forEach((group) => { const optionList = doFilterOptions( group?.children, searchStr, filterOption ); if (optionList.length > 0) { filterGroup.push({ label: group.label, children: optionList, }); } }); return filterGroup; }; export const isGroup = (group: Group[]) => { const firstOpt = group?.[0] as Group; return firstOpt?.children instanceof Array; }; export const countOptions = (list: (Option | Group)[]): number => { if (!Array.isArray(list) || list.length === 0) return 0; const first = list[0] as Group; if (first?.children instanceof Array) { return (list as Group[]).reduce( (sum, group) => sum + (group?.children?.length || 0), 0 ); } return (list as Option[]).length || 0; }; export const groupsToSections = ( groups: Group[] ): Array<{ title: React.ReactNode; data: Option[] }> => { return groups.map((group) => ({ title: group.label, data: group.children })); }; export const groupsToCheckboxSections = ( groups: Group[], styles: StylesType ): Array<{ title: React.ReactNode; data: Option[] }> => { return groups.map((group) => ({ title: group.label, data: addLabelPosition(group.children, styles), })); };