import { Box, ButtonProps, Checkbox, Flex, Menu, MenuButton, MenuItem, MenuItemProps, MenuList, useDisclosure } from '@chakra-ui/react'; import React, { useMemo, useRef } from 'react'; import MyTag from '../Tag/index'; import MyIcon from '../Icon'; import MyAvatar from '../Avatar'; import { useTranslation } from 'next-i18next'; import { useScrollPagination } from '../../../hooks/useScrollPagination'; export type SelectProps = { value: T[]; placeholder?: string; list: { icon?: string; label: string | React.ReactNode; value: T; }[]; maxH?: number; itemWrap?: boolean; onSelect: (val: T[]) => void; closeable?: boolean; showCheckedIcon?: boolean; ScrollData?: ReturnType['ScrollData']; isSelectAll?: boolean; setIsSelectAll?: React.Dispatch>; } & Omit; const MultipleSelect = ({ value = [], placeholder, list = [], maxH = 400, onSelect, closeable = false, showCheckedIcon = true, itemWrap = true, ScrollData, isSelectAll, setIsSelectAll, ...props }: SelectProps) => { const ref = useRef(null); const { t } = useTranslation(); const { isOpen, onOpen, onClose } = useDisclosure(); const menuItemStyles: MenuItemProps = { borderRadius: 'sm', py: 2, display: 'flex', alignItems: 'center', _hover: { backgroundColor: 'myGray.100' }, _notLast: { mb: 2 } }; const onclickItem = (val: T) => { if (value.includes(val)) { onSelect(value.filter((i) => i !== val)); } else { onSelect([...value, val]); } }; const onSelectAll = () => { if (!setIsSelectAll) { onSelect(value.length === list.length ? [] : list.map((item) => item.value)); return; } if (isSelectAll) { onSelect([]); } setIsSelectAll((state) => !state); }; const ListRender = useMemo(() => { return ( <> {list.map((item, i) => ( { e.stopPropagation(); e.preventDefault(); onclickItem(item.value); }} whiteSpace={'pre-wrap'} fontSize={'sm'} gap={2} > {!showCheckedIcon && ( )} {item.icon && } {item.label} {showCheckedIcon && ( {(isSelectAll && !value.includes(item.value)) || (!isSelectAll && value.includes(item.value) && ( ))} )} ))} ); }, [value, list, isSelectAll]); const isAllSelected = useMemo( () => (isSelectAll && value.length === 0) || (!isSelectAll && value.length === list.length), [isSelectAll, value, list] ); return ( {value.length === 0 && placeholder ? ( {placeholder} ) : ( {isAllSelected ? ( {t('common:common.All')} ) : ( (isSelectAll ? list.filter((item) => !value.includes(item.value)) : list.filter((item) => value.includes(item.value)) ).map((item, i) => ( {item.label} {closeable && ( { e.stopPropagation(); onclickItem(item.value); }} /> )} )) )} )} { e.stopPropagation(); e.preventDefault(); onSelectAll(); }} whiteSpace={'pre-wrap'} fontSize={'sm'} gap={2} mb={1} > {!showCheckedIcon && } {t('common:common.All')} {showCheckedIcon && ( {isAllSelected && } )} {ScrollData ? {ListRender} : ListRender} ); }; export default MultipleSelect;