Skip to content

Commit

Permalink
fix: filterSort don't work on group item (#1068)
Browse files Browse the repository at this point in the history
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: afc163 <afc163@gmail.com>
  • Loading branch information
3 people authored Sep 3, 2024
1 parent e55d4a1 commit d97b770
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
19 changes: 15 additions & 4 deletions src/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -431,15 +431,26 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
mergedSearchValue,
mergedFieldNames,
]);

const sorter = (inputOptions: DefaultOptionType[]) => {
const sortedOptions = [...inputOptions].sort((a, b) =>
filterSort(a, b, { searchValue: mergedSearchValue }),
);
return sortedOptions.map((item) => {
if (Array.isArray(item.options)) {
return {
...item,
options: item.options.length > 0 ? sorter(item.options) : item.options,
};
}
return item;
});
};
const orderedFilteredOptions = React.useMemo(() => {
if (!filterSort) {
return filledSearchOptions;
}

return [...filledSearchOptions].sort((a, b) =>
filterSort(a, b, { searchValue: mergedSearchValue }),
);
return sorter(filledSearchOptions);
}, [filledSearchOptions, filterSort, mergedSearchValue]);

const displayOptions = React.useMemo(
Expand Down
36 changes: 36 additions & 0 deletions tests/Select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1948,6 +1948,42 @@ describe('Select.Basic', () => {
);
});

it('filterSort should work with search value when grouping', () => {
const { container } = render(
<Select
open
showSearch
searchValue="entry"
style={{ width: 100 }}
placeholder="Search to Select"
optionFilterProp="label"
filterSort={(optionA, optionB, info) => {
if (!info.searchValue) return 0;
const labelA = (optionA?.label ?? '').toLowerCase();
const labelB = (optionB?.label ?? '').toLowerCase();
const matchA = labelA.startsWith(info.searchValue);
const matchB = labelB.startsWith(info.searchValue);
if (matchA && !matchB) return -1;
if (!matchA && matchB) return 1;
return labelA.localeCompare(labelB);
}}
options={[
{
value: 'group1',
label: 'group1',
options: [
{ label: 'Entry1', value: 'Entry1' },
{ label: 'Entry2', value: 'Entry2' },
{ label: 'Entry3', value: 'Entry3' },
{ label: 'Entry', value: 'Entry' },
],
},
]}
/>,
);
expect(container.querySelector('.rc-select-item-option-grouped').textContent).toBe('Entry');
});

it('correctly handles the `tabIndex` prop', () => {
const { container } = render(<Select tabIndex={0} />);
expect(container.querySelector('.rc-select').getAttribute('tabindex')).toBeFalsy();
Expand Down

0 comments on commit d97b770

Please sign in to comment.