@shopify/polaris
Version:
Shopify’s admin product component library
33 lines (30 loc) • 841 B
JavaScript
import { useContext, useId, useMemo, useEffect } from 'react';
import { MissingAppProviderError } from '../errors.js';
import { FocusManagerContext } from './context.js';
function useFocusManager({
trapping
}) {
const focusManager = useContext(FocusManagerContext);
const id = useId();
if (!focusManager) {
throw new MissingAppProviderError('No FocusManager was provided.');
}
const {
trapFocusList,
add: addFocusItem,
remove: removeFocusItem
} = focusManager;
const canSafelyFocus = trapFocusList[0] === id;
const value = useMemo(() => ({
canSafelyFocus
}), [canSafelyFocus]);
useEffect(() => {
if (!trapping) return;
addFocusItem(id);
return () => {
removeFocusItem(id);
};
}, [addFocusItem, id, removeFocusItem, trapping]);
return value;
}
export { useFocusManager };