Skip to content

Commit 9b60445

Browse files
765477020liuqiang
andauthored
fix: Select with maxCount limit does not allow removal of selected opt… (#1148)
Co-authored-by: liuqiang <[email protected]>
1 parent 80a3bc3 commit 9b60445

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

src/OptionList.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -228,7 +228,11 @@ const OptionList: React.ForwardRefRenderFunction<RefOptionListProps, {}> = (_, r
228228
case KeyCode.ENTER: {
229229
// value
230230
const item = memoFlattenOptions[activeIndex];
231-
if (item && !item?.data?.disabled && !overMaxCount) {
231+
if (!item || item.data.disabled) {
232+
return onSelectValue(undefined);
233+
}
234+
235+
if (!overMaxCount || rawValues.has(item.value)) {
232236
onSelectValue(item.value);
233237
} else {
234238
onSelectValue(undefined);

tests/OptionList.test.tsx

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -462,6 +462,54 @@ describe('OptionList', () => {
462462
expect(onActiveValue).not.toHaveBeenCalledWith('3', expect.anything(), expect.anything());
463463
});
464464

465+
it('should deselect a selected option when Enter is pressed and maxCount is reached', () => {
466+
const onSelect = jest.fn();
467+
const toggleOpen = jest.fn();
468+
const listRef = React.createRef<RefOptionListProps>();
469+
470+
// Initial selected values: '1' and '2'
471+
const initialValues = new Set(['1', '2']);
472+
473+
render(
474+
generateList({
475+
multiple: true,
476+
maxCount: 2,
477+
options: [
478+
{ value: '1', label: '1' },
479+
{ value: '2', label: '2' },
480+
{ value: '3', label: '3' },
481+
],
482+
values: initialValues,
483+
onSelect,
484+
toggleOpen,
485+
ref: listRef,
486+
}),
487+
);
488+
489+
// Verify initial selection state
490+
expect(initialValues.has('1')).toBe(true); // 1 is selected
491+
expect(initialValues.has('2')).toBe(true); // 2 is selected
492+
expect(initialValues.has('3')).toBe(false); // 3 is not selected
493+
494+
act(() => {
495+
toggleOpen(true);
496+
});
497+
498+
act(() => {
499+
listRef.current.onKeyDown({ which: KeyCode.ENTER } as any);
500+
});
501+
502+
// Verify that onSelect was called to deselect '1'
503+
expect(onSelect).toHaveBeenCalledWith('1', expect.objectContaining({ selected: false }));
504+
505+
// Verify that onSelect was NOT called for '2' or '3'
506+
expect(onSelect).not.toHaveBeenCalledWith('2', expect.anything());
507+
expect(onSelect).not.toHaveBeenCalledWith('3', expect.anything());
508+
509+
// Verify only one call was made (for deselecting '1')
510+
expect(onSelect).toHaveBeenCalledTimes(1);
511+
});
512+
465513
describe('List.ScrollBar', () => {
466514
let mockElement;
467515
let boundingRect = {

0 commit comments

Comments
 (0)