Skip to content

Commit

Permalink
解决分组时排序失效问题
Browse files Browse the repository at this point in the history
  • Loading branch information
Zyf665 committed Jul 25, 2024
1 parent bbe6b41 commit 457562b
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 6 deletions.
21 changes: 16 additions & 5 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 = (options: DefaultOptionType[]) => {
const sortedOptions = [...options].sort((a, b) =>
filterSort(a, b, { searchValue: mergedSearchValue }),
);
const sortedOptionsWithNested = sortedOptions.map((item) => {
if (Array.isArray(item.options)) {
return {
...item,
options: sorter(item.options),
};
}
return item;
});
return sortedOptionsWithNested;
};
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
39 changes: 38 additions & 1 deletion tests/Select.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1947,7 +1947,44 @@ describe('Select.Basic', () => {
'Communicated',
);
});

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',
);
})

Check notice

Code scanning / CodeQL

Semicolon insertion Note test

Avoid automated semicolon insertion (99% of all statements in
the enclosing function
have an explicit semicolon).
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 457562b

Please sign in to comment.