From e18d975907cf94b46e8a46a74f22586d05b0ad32 Mon Sep 17 00:00:00 2001 From: nathanlao Date: Sun, 13 Oct 2024 02:01:58 -0700 Subject: [PATCH] fix: tab to select an active option --- src/OptionList.tsx | 3 ++- tests/OptionList.test.tsx | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/OptionList.tsx b/src/OptionList.tsx index b5ab3da2..fc5682f5 100644 --- a/src/OptionList.tsx +++ b/src/OptionList.tsx @@ -215,7 +215,8 @@ const OptionList: React.ForwardRefRenderFunction = (_, r break; } - // >>> Select + // >>> Select (Tab / Enter) + case KeyCode.TAB: case KeyCode.ENTER: { // value const item = memoFlattenOptions[activeIndex]; diff --git a/tests/OptionList.test.tsx b/tests/OptionList.test.tsx index b3709547..6526778f 100644 --- a/tests/OptionList.test.tsx +++ b/tests/OptionList.test.tsx @@ -202,6 +202,46 @@ describe('OptionList', () => { expect(onSelect).toHaveBeenCalledWith('1', expect.objectContaining({ selected: true })); }); + it('should tab key select an active option', () => { + const onActiveValue = jest.fn(); + const onSelect = jest.fn(); + const toggleOpen = jest.fn(); + const listRef = React.createRef(); + + render( + generateList({ + options: [{ value: '1' }, { value: '2' }], + onActiveValue, + onSelect, + toggleOpen, + ref: listRef, + }), + ); + + act(() => { + toggleOpen(true); + }); + + act(() => { + listRef.current.onKeyDown({ which: KeyCode.DOWN } as any); + }); + + expect(onActiveValue).toHaveBeenCalledWith( + '2', + expect.anything(), + expect.objectContaining({ source: 'keyboard' }), + ); + + act(() => { + listRef.current.onKeyDown({ which: KeyCode.TAB } as any); + }); + + expect(onSelect).toHaveBeenCalledTimes(1); + expect(onSelect).toHaveBeenCalledWith('2', expect.objectContaining({ selected: true })); + + expect(toggleOpen).toHaveBeenCalledWith(false); + }); + // mocked how we detect running platform in test environment it('special key operation on Mac', () => { const onActiveValue = jest.fn();