Retry to focus

This commit is contained in:
Belen Curcio 2021-01-06 11:11:05 -03:00
parent 885a7ccdc1
commit d53e517f8b
3 changed files with 25 additions and 12 deletions

View File

@ -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: () => <Loading />,
}
const LoginView = dynamic(
() => import('@components/auth/LoginView'),
dynamicProps
)
const SignUpView = dynamic(
() => import('@components/auth/SignUpView'),
dynamicProps

View File

@ -43,8 +43,8 @@ const Modal: FC<Props> = ({ children, open, onClose, onEnter = null }) => {
return (
<Portal>
{open ? (
<div role="dialog" className={s.root} ref={ref}>
<div className={s.modal}>
<div className={s.root}>
<div className={s.modal} role="dialog" ref={ref}>
<button
onClick={() => onClose()}
aria-label="Close panel"
@ -52,7 +52,6 @@ const Modal: FC<Props> = ({ children, open, onClose, onEnter = null }) => {
>
<Cross className="h-6 w-6" />
</button>
<FocusTrap>{children}</FocusTrap>
</div>
</div>

View File

@ -10,22 +10,40 @@ export default function FocusTrap({ children }: Props) {
const anchor: RefObject<any> = 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', {