Skip to content

Commit

Permalink
Fix #6718: FocusTrap better handling of autoFocus property (#6721)
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware authored Jul 2, 2024
1 parent 0e0d064 commit f5005c0
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
1 change: 1 addition & 0 deletions components/lib/button/Button.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ export const Button = React.memo(
{
ref: elementRef,
'aria-label': defaultAriaLabel,
'data-pc-autofocus': props.autoFocus,
className: classNames(props.className, cx('root', { size, disabled })),
disabled: disabled
},
Expand Down
12 changes: 11 additions & 1 deletion components/lib/focustrap/FocusTrap.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,20 @@ export const FocusTrap = React.memo(
return firstFocusableElementRef.current && firstFocusableElementRef.current.parentElement;
};

/**
* This method sets the auto focus on the first focusable element within the target element.
* It first tries to find a focusable element using the autoFocusSelector. If no such element is found,
* it then tries to find a focusable element using the firstFocusableSelector.
* If the autoFocus prop is set to true and a focusable element is found, it sets the focus on that element.
*
* @param {HTMLElement} target - The target element within which to find a focusable element.
*/
const setAutoFocus = (target) => {
const { autoFocusSelector = '', firstFocusableSelector = '', autoFocus = false } = props || {};
const defaultAutoFocusSelector = `${getComputedSelector(autoFocusSelector)}`;
const computedAutoFocusSelector = `[autofocus]${defaultAutoFocusSelector}, [data-pc-autofocus='true']${defaultAutoFocusSelector}`;

let focusableElement = DomHandler.getFirstFocusableElement(target, `[autofocus]${getComputedSelector(autoFocusSelector)}`);
let focusableElement = DomHandler.getFirstFocusableElement(target, computedAutoFocusSelector);

autoFocus && !focusableElement && (focusableElement = DomHandler.getFirstFocusableElement(target, getComputedSelector(firstFocusableSelector)));

Expand Down

0 comments on commit f5005c0

Please sign in to comment.