mirror of
https://github.com/vercel/commerce.git
synced 2025-07-22 20:26:49 +00:00
.vscode
assets
components
config
docs
framework
lib
click-outside
hooks
colors.ts
defaults.ts
focus-trap.tsx
get-slug.ts
range-map.ts
search.tsx
to-pixels.ts
usage-warns.ts
pages
public
.editorconfig
.env.template
.gitignore
.prettierignore
.prettierrc
README.md
codegen.json
commerce.config.json
global.d.ts
license.md
next-env.d.ts
next.config.js
package.json
postcss.config.js
tailwind.config.js
tsconfig.json
yarn.lock
* Focus trap and Modal Functionality * Changes * Changes * Update components/ui/Modal/Modal.tsx Co-authored-by: Luis Alvarez D. <luis@vercel.com> * changes Co-authored-by: Luis Alvarez D. <luis@vercel.com>
65 lines
1.5 KiB
TypeScript
65 lines
1.5 KiB
TypeScript
import React, { useEffect, RefObject } from 'react'
|
|
import { tabbable } from 'tabbable'
|
|
|
|
interface Props {
|
|
children: React.ReactNode | any
|
|
focusFirst?: boolean
|
|
}
|
|
|
|
export default function FocusTrap({ children, focusFirst = false }: Props) {
|
|
const root: RefObject<any> = React.useRef()
|
|
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 = () => {
|
|
// Focus the container element
|
|
if (root.current) {
|
|
root.current.focus()
|
|
if (focusFirst) {
|
|
selectFirstFocusableEl()
|
|
}
|
|
}
|
|
}
|
|
|
|
const selectFirstFocusableEl = () => {
|
|
// Try to find focusable elements, if match then focus
|
|
// Up to 6 seconds of load time threshold
|
|
let match = false
|
|
let end = 60 // Try to find match at least n times
|
|
let i = 0
|
|
const timer = setInterval(() => {
|
|
if (!match !== i > end) {
|
|
match = !!tabbable(root.current).length
|
|
if (match) {
|
|
// Attempt to focus the first el
|
|
tabbable(root.current)[0].focus()
|
|
}
|
|
i = i + 1
|
|
} else {
|
|
// Clear interval after n attempts
|
|
clearInterval(timer)
|
|
}
|
|
}, 100)
|
|
}
|
|
|
|
useEffect(() => {
|
|
setTimeout(trapFocus, 20)
|
|
return () => {
|
|
returnFocus()
|
|
}
|
|
}, [root, children])
|
|
|
|
return React.createElement('div', {
|
|
ref: root,
|
|
children,
|
|
className: 'outline-none focus-trap',
|
|
tabIndex: -1,
|
|
})
|
|
}
|