diff --git a/src/OptionList.tsx b/src/OptionList.tsx index 87b9094a..8740a4e9 100644 --- a/src/OptionList.tsx +++ b/src/OptionList.tsx @@ -8,6 +8,7 @@ import SelectContext from './SelectContext'; import TransBtn from './TransBtn'; import useBaseProps from './hooks/useBaseProps'; import type { FlattenOptionData } from './interface'; +import { getNextActiveIndex } from './utils/keyUtil'; import { isPlatformMac } from './utils/platformUtil'; import { isValidCount } from './utils/valueUtil'; @@ -211,7 +212,10 @@ const OptionList: React.ForwardRefRenderFunction = (_, r } if (offset !== 0) { - const nextActiveIndex = getEnabledActiveIndex(activeIndex + offset, offset); + const nextActiveIndex = getEnabledActiveIndex( + getNextActiveIndex(activeIndex, offset), + offset, + ); scrollIntoView(nextActiveIndex); setActive(nextActiveIndex, true); } diff --git a/src/utils/keyUtil.ts b/src/utils/keyUtil.ts index e6325374..ffa8e16c 100644 --- a/src/utils/keyUtil.ts +++ b/src/utils/keyUtil.ts @@ -1,5 +1,9 @@ import { KeyCode } from '@rc-component/util'; +export function getNextActiveIndex(activeIndex: number, offset: number): number { + return activeIndex === -1 && offset < 0 ? -1 : activeIndex + offset; +} + /** keyCode Judgment function */ export function isValidateOpenKey(currentKeyCode: number): boolean { return ( diff --git a/tests/keyUtil.test.ts b/tests/keyUtil.test.ts new file mode 100644 index 00000000..5bdfa77c --- /dev/null +++ b/tests/keyUtil.test.ts @@ -0,0 +1,16 @@ +import { getNextActiveIndex } from '../src/utils/keyUtil'; + +describe('getNextActiveIndex', () => { + it.each([ + [-1, -1, -1], + [-1, 1, 0], + [0, -1, -1], + [0, 1, 1], + [1, -1, 0], + [1, 1, 2], + [2, -1, 1], + [2, 1, 3], + ])('starts scanning from %i with offset %i at %i', (activeIndex, offset, expected) => { + expect(getNextActiveIndex(activeIndex, offset)).toBe(expected); + }); +});