Skip to content

Commit

Permalink
Switch popup focus to useEffect, add setTimeout for React 16 (microso…
Browse files Browse the repository at this point in the history
  • Loading branch information
smhigley authored and miroslavstastny committed May 5, 2021
1 parent 2b03aba commit 276616a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "switch popup focus to useEffect, add setTimeout for React 16",
"packageName": "@fluentui/react",
"email": "sarah.higley@microsoft.com",
"dependentChangeType": "patch"
}
18 changes: 10 additions & 8 deletions packages/react/src/components/Popup/Popup.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ function defaultFocusRestorer(options: IPopupRestoreFocusParams) {
// Make sure that the focus method actually exists
// In some cases the object might exist but not be a real element.
// This is primarily for IE 11 and should be removed once IE 11 is no longer in use.
originalElement.focus?.();
// This is wrapped in a setTimeout because of a React 16 bug that is resolved in 17.
// Once we move to 17, the setTimeout should be removed (ref: https://github.com/facebook/react/issues/17894#issuecomment-656094405)
setTimeout(() => {
originalElement.focus?.();
}, 0);
}
}

Expand All @@ -65,9 +69,13 @@ function useRestoreFocus(props: IPopupProps, root: React.RefObject<HTMLDivElemen
const originalFocusedElement = React.useRef<HTMLElement>();
const containsFocus = React.useRef(false);

React.useLayoutEffect(() => {
React.useEffect(() => {
originalFocusedElement.current = getDocument()!.activeElement as HTMLElement;

if (doesElementContainFocus(root.current!)) {
containsFocus.current = true;
}

return () => {
onRestoreFocus?.({
originalElement: originalFocusedElement.current,
Expand All @@ -78,13 +86,7 @@ function useRestoreFocus(props: IPopupProps, root: React.RefObject<HTMLDivElemen
// De-reference DOM Node to avoid retainment via transpiled closure of _onKeyDown
originalFocusedElement.current = undefined;
};
// eslint-disable-next-line react-hooks/exhaustive-deps -- should only run on first render
}, []);

React.useEffect(() => {
if (doesElementContainFocus(root.current!)) {
containsFocus.current = true;
}
// eslint-disable-next-line react-hooks/exhaustive-deps -- should only run on first render
}, []);

Expand Down

0 comments on commit 276616a

Please sign in to comment.