diff --git a/packages/select/src/components/options-list/Component.tsx b/packages/select/src/components/options-list/Component.tsx index cec0d3721a..eca0220b51 100644 --- a/packages/select/src/components/options-list/Component.tsx +++ b/packages/select/src/components/options-list/Component.tsx @@ -11,14 +11,9 @@ import { GroupShape, OptionShape, OptionsListProps } from '../../typings'; import { isGroup, useVisibleOptions } from '../../utils'; import { Optgroup as DefaultOptgroup } from '../optgroup'; -import styles from './index.module.css'; - -const createCounter = () => { - let count = 0; +import { createCounter, getSelectedItemsInGroup } from './utils'; - // eslint-disable-next-line no-plusplus - return () => count++; -}; +import styles from './index.module.css'; export const OptionsList = forwardRef( ( @@ -85,15 +80,9 @@ export const OptionsList = forwardRef( const scrollbarRef = useRef(null); const counter = createCounter(); const renderGroup = (group: GroupShape) => { - const groupSelectedItems = selectedItems?.filter((item) => - group.options.includes(item), - ); + const groupSelectedItems = getSelectedItemsInGroup(selectedItems, group); const handleSelectedItems = (items: OptionShape[]) => { - setSelectedItems( - (selectedItems?.filter((item) => !group.options.includes(item)) ?? []).concat( - items, - ), - ); + setSelectedItems(getSelectedItemsInGroup(selectedItems, group).concat(items)); }; return ( diff --git a/packages/select/src/components/options-list/utils.ts b/packages/select/src/components/options-list/utils.ts new file mode 100644 index 0000000000..18eb0c25ca --- /dev/null +++ b/packages/select/src/components/options-list/utils.ts @@ -0,0 +1,18 @@ +import { GroupShape, OptionsListProps } from '../../typings'; + +export const getSelectedItemsInGroup = ( + selectedItems: OptionsListProps['selectedItems'], + group: GroupShape, +) => + selectedItems === undefined + ? [] + : selectedItems.filter(({ key: selectedItemKey }) => + group.options.some((option) => option.key === selectedItemKey), + ); + +export const createCounter = () => { + let count = 0; + + // eslint-disable-next-line no-plusplus + return () => count++; +};