diff --git a/packages/ibm-products/src/components/Tearsheet/TearsheetShell.tsx b/packages/ibm-products/src/components/Tearsheet/TearsheetShell.tsx index 771aa0b819..ea97b473a7 100644 --- a/packages/ibm-products/src/components/Tearsheet/TearsheetShell.tsx +++ b/packages/ibm-products/src/components/Tearsheet/TearsheetShell.tsx @@ -242,7 +242,10 @@ export const TearsheetShell = React.forwardRef( const modalBodyRef = useRef(null); const modalRef = ref || localRef; const { width } = useResizeObserver(resizer); - const { firstElement, keyDownListener } = useFocus(modalRef); + const { firstElement, keyDownListener, specifiedElement } = useFocus( + modalRef, + selectorPrimaryFocus + ); const modalRefValue = (modalRef as MutableRefObject) .current; @@ -283,13 +286,19 @@ export const TearsheetShell = React.forwardRef( // Callback to give the tearsheet the opportunity to claim focus handleStackChange.claimFocus = function () { + if (selectorPrimaryFocus) { + return specifiedElement?.focus(); + } firstElement?.focus(); }; useEffect(() => { if (open) { - // Focusing the first element + // Focusing the first element or selectorPrimaryFocus element setTimeout(() => { + if (selectorPrimaryFocus) { + return specifiedElement?.focus(); + } firstElement?.focus(); }, 0); } diff --git a/packages/ibm-products/src/global/js/hooks/useFocus.js b/packages/ibm-products/src/global/js/hooks/useFocus.js index cb28fa2cf0..5d1a6dcbf3 100644 --- a/packages/ibm-products/src/global/js/hooks/useFocus.js +++ b/packages/ibm-products/src/global/js/hooks/useFocus.js @@ -9,7 +9,7 @@ import { usePrefix } from '@carbon/react'; import { pkg } from '../../../settings'; import { useCallback, useEffect } from 'react'; -export const useFocus = (modalRef) => { +export const useFocus = (modalRef, selectorPrimaryFocus) => { const carbonPrefix = usePrefix(); const tearsheetBaseClass = `${pkg.prefix}--tearsheet`; // Querying focusable element in the modal @@ -40,13 +40,17 @@ export const useFocus = (modalRef) => { const first = focusableElements?.[0]; const last = focusableElements?.[focusableElements?.length - 1]; const all = focusableElements; + const specifiedElement = selectorPrimaryFocus + ? modalEl?.querySelector(selectorPrimaryFocus) + : null; return { first, last, all, + specifiedElement, }; - }, [modalEl, query]); + }, [modalEl, query, selectorPrimaryFocus]); useEffect(() => { getFocusable(); @@ -83,6 +87,7 @@ export const useFocus = (modalRef) => { firstElement: getFocusable().first, lastElement: getFocusable().last, allElements: getFocusable().all, + specifiedElement: getFocusable().specified, keyDownListener: handleKeyDown, getFocusable: getFocusable, };