Skip to content

Commit

Permalink
bugfix: fixes #2
Browse files Browse the repository at this point in the history
  • Loading branch information
cluk3 committed Mar 6, 2020
1 parent 24b102a commit 233a013
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
46 changes: 46 additions & 0 deletions src/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,49 @@ test("useContextMenu hides the menu on ENTER key press", () => {

expect(result.current[3].isVisible).toEqual(false);
});

test("useContextMenu index of item selected by keyboard gets reset when closing the menu", () => {
let selectedEl = 0;
const { result } = renderHook(() =>
useContextMenu({
handleElementSelect: _selectedEl => (selectedEl = _selectedEl)
})
);

result.current[0].ref.current = {
getBoundingClientRect: jest.fn(() => ({ height: 100, width: 100 })),
contains: () => false
};

result.current[1].ref(1);
result.current[1].ref(2);
result.current[1].ref(3);

act(() => {
result.current[3].setVisible(true);
});

act(() => {
const event = new KeyboardEvent("keydown", { keyCode: 40 });

document.dispatchEvent(event);
});

act(() => {
const event = new MouseEvent("touchstart");

document.dispatchEvent(event);
});

act(() => {
result.current[3].setVisible(true);
});

act(() => {
const event = new KeyboardEvent("keydown", { keyCode: 40 });

document.dispatchEvent(event);
});

expect(selectedEl).toEqual(1);
});
5 changes: 4 additions & 1 deletion src/useContextMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,10 @@ const useContextMenu = ({ rtl, handleElementSelect = focusElement } = {}) => {

useEffect(() => {
const handleOutsideClick = e => {
!menuRef.current.contains(e.target) && hideMenu();
if (!menuRef.current.contains(e.target)) {
setSelectedIndex(-1);
hideMenu();
}
};
const handleKeyNavigation = e => {
switch (e.keyCode) {
Expand Down

0 comments on commit 233a013

Please sign in to comment.