diff --git a/packages/docusaurus-theme-classic/package.json b/packages/docusaurus-theme-classic/package.json index 0eb68a49b41d..6602523d71ef 100644 --- a/packages/docusaurus-theme-classic/package.json +++ b/packages/docusaurus-theme-classic/package.json @@ -27,6 +27,7 @@ "prop-types": "^15.7.2", "react-router-dom": "^5.1.2", "react-toggle": "^4.1.1", + "use-onclickoutside": "^0.3.1", "@docusaurus/utils-validation": "^2.0.0-alpha.61" }, "devDependencies": { diff --git a/packages/docusaurus-theme-classic/src/theme/NavbarItem/DefaultNavbarItem.tsx b/packages/docusaurus-theme-classic/src/theme/NavbarItem/DefaultNavbarItem.tsx index 80659c6d0e3e..e1bbe0e822a1 100644 --- a/packages/docusaurus-theme-classic/src/theme/NavbarItem/DefaultNavbarItem.tsx +++ b/packages/docusaurus-theme-classic/src/theme/NavbarItem/DefaultNavbarItem.tsx @@ -5,10 +5,11 @@ * LICENSE file in the root directory of this source tree. */ -import React, {ComponentProps, ComponentType} from 'react'; +import React, {ComponentProps, ComponentType, useState} from 'react'; import clsx from 'clsx'; import Link from '@docusaurus/Link'; import useBaseUrl from '@docusaurus/useBaseUrl'; +import useOnClickOutside from 'use-onclickoutside'; function NavLink({ activeBasePath, @@ -33,6 +34,7 @@ function NavLink({ const toUrl = useBaseUrl(to); const activeBaseUrl = useBaseUrl(activeBasePath); const normalizedHref = useBaseUrl(href, {forcePrependBaseUrl: true}); + return ( (null); + const dropDownMenuRef = React.useRef(null); + const [showDropDown, setShowDropDown] = useState(false); + useOnClickOutside(dropDownRef, () => toggle(false)); + function toggle(state: boolean) { + if (state) { + const firstNavLinkOfULElement = + dropDownMenuRef?.current?.firstChild?.firstChild; + + if (firstNavLinkOfULElement) { + (firstNavLinkOfULElement as HTMLElement).focus(); + } + } + setShowDropDown(state); + } const navLinkClassNames = (extraClassName, isDropdownItem = false) => clsx( { @@ -76,32 +93,34 @@ function NavItemDesktop({items, position, className, ...props}) { return (
e.preventDefault()} onKeyDown={(e) => { - function toggle() { - ((e.target as HTMLElement) - .parentNode as HTMLElement).classList.toggle('dropdown--show'); - } - if (e.key === 'Enter' && !props.to) { - toggle(); - } - if (e.key === 'Tab') { - toggle(); + if ((e.key === 'Enter' && !props.to) || e.key === 'Tab') { + e.preventDefault(); + toggle(true); } }}> {props.label} -