diff --git a/src/app/components/Navigation/index.canonical.test.tsx b/src/app/components/Navigation/index.canonical.test.tsx index a228c705ed5..cfd4fe81798 100644 --- a/src/app/components/Navigation/index.canonical.test.tsx +++ b/src/app/components/Navigation/index.canonical.test.tsx @@ -55,6 +55,18 @@ describe('Navigation - Canonical', () => { expect(dropdown).toHaveTextContent('Dropdown Items'); }); + it('should close the menu when focus moves away from the menu area', () => { + const { getByRole } = render(navigation); + + const menuButton = getByRole('button', { name: 'menu' }); + fireEvent.click(menuButton); + expect(menuButton).toHaveAttribute('aria-expanded', 'true'); + + fireEvent.focusOut(menuButton, { relatedTarget: document.body }); + + expect(menuButton).toHaveAttribute('aria-expanded', 'false'); + }); + describe('Top Bar OJs', () => { it.each([ [ diff --git a/src/app/components/Navigation/index.canonical.tsx b/src/app/components/Navigation/index.canonical.tsx index 1db20c8dc6d..9e3d4262a3d 100644 --- a/src/app/components/Navigation/index.canonical.tsx +++ b/src/app/components/Navigation/index.canonical.tsx @@ -1,4 +1,4 @@ -import React, { useState, use } from 'react'; +import React, { useState, use, FocusEvent } from 'react'; import Navigation from '#psammead/psammead-navigation/src'; import { ScrollableNavigation } from '#psammead/psammead-navigation/src/ScrollableNavigation'; import { @@ -43,10 +43,25 @@ const CanonicalNavigationContainer: React.FC< } }); + const closeMenuWhenFocusLeaves = ({ + currentTarget, + relatedTarget, + }: FocusEvent) => { + const focusMovedOutsideMenu = !currentTarget.contains( + relatedTarget as HTMLElement, + ); + if (isOpen && relatedTarget && focusMovedOutsideMenu) { + setIsOpen(false); + } + }; + return (
-
+