From d53e517f8b33703b8e8f9fa774fff4502456429e Mon Sep 17 00:00:00 2001 From: Belen Curcio Date: Wed, 6 Jan 2021 11:11:05 -0300 Subject: [PATCH] Retry to focus --- components/common/Layout/Layout.tsx | 6 +----- components/ui/Modal/Modal.tsx | 5 ++--- lib/focus-trap.tsx | 26 ++++++++++++++++++++++---- 3 files changed, 25 insertions(+), 12 deletions(-) diff --git a/components/common/Layout/Layout.tsx b/components/common/Layout/Layout.tsx index 14c07860a..12725d3ed 100644 --- a/components/common/Layout/Layout.tsx +++ b/components/common/Layout/Layout.tsx @@ -8,7 +8,7 @@ import { Navbar, Footer } from '@components/common' import { useAcceptCookies } from '@lib/hooks/useAcceptCookies' import { Sidebar, Button, Modal, LoadingDots } from '@components/ui' import { CartSidebarView } from '@components/cart' - +import LoginView from '@components/auth/LoginView' import { CommerceProvider } from '@bigcommerce/storefront-data-hooks' import type { Page } from '@bigcommerce/storefront-data-hooks/api/operations/get-all-pages' @@ -22,10 +22,6 @@ const dynamicProps = { loading: () => , } -const LoginView = dynamic( - () => import('@components/auth/LoginView'), - dynamicProps -) const SignUpView = dynamic( () => import('@components/auth/SignUpView'), dynamicProps diff --git a/components/ui/Modal/Modal.tsx b/components/ui/Modal/Modal.tsx index 150ddcdf0..760cc3555 100644 --- a/components/ui/Modal/Modal.tsx +++ b/components/ui/Modal/Modal.tsx @@ -43,8 +43,8 @@ const Modal: FC = ({ children, open, onClose, onEnter = null }) => { return ( {open ? ( -
-
+
+
- {children}
diff --git a/lib/focus-trap.tsx b/lib/focus-trap.tsx index 048ba2b9a..b3ab38006 100644 --- a/lib/focus-trap.tsx +++ b/lib/focus-trap.tsx @@ -10,22 +10,40 @@ export default function FocusTrap({ children }: Props) { const anchor: RefObject = React.useRef(document.activeElement) const returnFocus = () => { + // Returns focus to the last focused element prior to trap. if (anchor) { anchor.current.focus() } } const trapFocus = () => { - const focusableElements = tabbable(root.current) + if (root.current) { + root.current.focus() + selectFirstFocusableEl() + } + } - if (focusableElements[0]) { - focusableElements[0].focus() + const selectFirstFocusableEl = () => { + // Try to find focusable elements, if match then focus. + let match = null + let end = 10 // Try to find match at least 10 times. + let i = 0 + + while (!match !== i > end) { + console.log('-----------', i) + match = !!tabbable(root.current).length + if (match) { + tabbable(root.current)[0].focus() + } + i = i + 1 } } useEffect(() => { setTimeout(trapFocus, 20) - return returnFocus + return () => { + returnFocus() + } }, [root, children]) return React.createElement('div', {