Skip to content

Commit

Permalink
fix(Tearsheet): properly focus specified element with new hook (#5264)
Browse files Browse the repository at this point in the history
* fix(Tearsheet): properly focus specified element with new hook

* chore: update comment
  • Loading branch information
matthewgallo authored May 21, 2024
1 parent 705f403 commit 1dc2407
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
13 changes: 11 additions & 2 deletions packages/ibm-products/src/components/Tearsheet/TearsheetShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<HTMLDivElement>)
.current;

Expand Down Expand Up @@ -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);
}
Expand Down
9 changes: 7 additions & 2 deletions packages/ibm-products/src/global/js/hooks/useFocus.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -83,6 +87,7 @@ export const useFocus = (modalRef) => {
firstElement: getFocusable().first,
lastElement: getFocusable().last,
allElements: getFocusable().all,
specifiedElement: getFocusable().specified,
keyDownListener: handleKeyDown,
getFocusable: getFocusable,
};
Expand Down

0 comments on commit 1dc2407

Please sign in to comment.