| 1 |
import { createFocusTrap, FocusTrap as FocusTrapInstance, Options as FocusTrapOptions } from 'focus-trap'; |
| 2 |
import { ComponentPropsWithRef, forwardRef, useEffect, useImperativeHandle, useRef } from 'react'; |
| 3 |
import { useUnmountEffect } from '../useUnmountEffect'; |
| 4 |
|
| 5 |
export interface FocusTrapProps extends ComponentPropsWithRef<'div'> { |
| 6 |
active?: boolean; |
| 7 |
paused?: boolean; |
| 8 |
focusTrapOptions?: FocusTrapOptions; |
| 9 |
/** Prevent from scrolling to the previously focused element on deactivation */ |
| 10 |
preventScrollOnDeactivate?: boolean; |
| 11 |
/** Unique id that can optionally be applied to focus trap */ |
| 12 |
id?: string; |
| 13 |
} |
| 14 |
|
| 15 |
export const FocusTrap = forwardRef<HTMLDivElement, FocusTrapProps>(function FocusTrap( |
| 16 |
{ active = true, paused = false, focusTrapOptions = {}, preventScrollOnDeactivate = false, ...props }, |
| 17 |
forwardedRef |
| 18 |
) { |
| 19 |
// Fall back to internal ref if no forwarded ref is provided. |
| 20 |
const ref = useRef<HTMLDivElement>(null); |
| 21 |
useImperativeHandle(forwardedRef, () => ref.current!); |
| 22 |
|
| 23 |
// Create focus trap instance after rendering DOM. |
| 24 |
const focusTrapRef = useRef<FocusTrapInstance | null>(null); |
| 25 |
useEffect(() => { |
| 26 |
const focusTrap = createFocusTrap(ref.current!, { |
| 27 |
...focusTrapOptions, |
| 28 |
returnFocusOnDeactivate: false |
| 29 |
}); |
| 30 |
focusTrapRef.current = focusTrap; |
| 31 |
|
| 32 |
// Deactivate focus trap on cleanup. |
| 33 |
return () => { |
| 34 |
focusTrap.deactivate(); |
| 35 |
}; |
| 36 |
}, []); |
| 37 |
|
| 38 |
// Handle activation status based on 'active' prop. |
| 39 |
useEffect(() => { |
| 40 |
const focusTrap = focusTrapRef.current; |
| 41 |
active ? focusTrap?.activate() : focusTrap?.deactivate(); |
| 42 |
}, [active]); |
| 43 |
|
| 44 |
// Handle pause status based on 'pause' prop. |
| 45 |
useEffect(() => { |
| 46 |
const focusTrap = focusTrapRef.current; |
| 47 |
paused ? focusTrap?.pause() : focusTrap?.unpause(); |
| 48 |
}, [paused]); |
| 49 |
|
| 50 |
// Store the currently active element to restore focus to later. |
| 51 |
const previousElementRef = useRef(typeof document !== 'undefined' ? document.activeElement : null); |
| 52 |
|
| 53 |
// Restore focus to the previously active element on unmount. |
| 54 |
useUnmountEffect(() => { |
| 55 |
if (focusTrapOptions.returnFocusOnDeactivate !== false && previousElementRef.current instanceof HTMLElement) { |
| 56 |
previousElementRef.current.focus({ |
| 57 |
preventScroll: preventScrollOnDeactivate |
| 58 |
}); |
| 59 |
} |
| 60 |
}); |
| 61 |
|
| 62 |
return <div ref={ref} {...props} />; |
| 63 |
}); |
| 64 |
|
| 65 |
FocusTrap.displayName = 'FocusTrap'; |