UNPKG

@datalayer/core

Version:

[![Datalayer](https://assets.datalayer.tech/datalayer-25.svg)](https://datalayer.io)

50 lines (49 loc) 2.03 kB
/* * Copyright (c) 2023-2025 Datalayer, Inc. * Distributed under the terms of the Modified BSD License. */ import React from 'react'; import { focusTrap } from '@primer/behaviors'; /** * Hook used to trap focus inside a container. Returns a ref that can be added to the container * that should trap focus. * @param settings {FocusTrapHookSettings} */ export function useFocusTrap(settings, dependencies = []) { const containerRef = settings?.containerRef; const initialFocusRef = settings?.initialFocusRef; const disabled = settings?.disabled; const abortController = React.useRef(); const previousFocusedElement = React.useRef(null); // If we are enabling a focus trap and haven't already stored the previously focused element // go ahead an do that so we can restore later when the trap is disabled. if (!previousFocusedElement.current && !settings?.disabled) { previousFocusedElement.current = document.activeElement; } // This function removes the event listeners that enable the focus trap and restores focus // to the previously-focused element (if necessary). function disableTrap() { abortController.current?.abort(); if (settings?.restoreFocusOnCleanUp && previousFocusedElement.current instanceof HTMLElement) { previousFocusedElement.current.focus(); previousFocusedElement.current = null; } } React.useEffect(() => { if (containerRef?.current instanceof HTMLElement) { if (!disabled) { abortController.current = focusTrap(containerRef.current, initialFocusRef?.current ?? undefined); return () => { disableTrap(); }; } else { disableTrap(); } } }, // eslint-disable-next-line react-hooks/exhaustive-deps [containerRef, initialFocusRef, disabled, ...dependencies]); return { containerRef, initialFocusRef }; }