Skip to content

Commit

Permalink
fix: focusAsync still works even if past animationFrame fails to run (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
smhigley authored Sep 28, 2023
1 parent e7c0c14 commit d701af3
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 12 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "fix: focusAsync still works even if past animationFrame fails to run",
"packageName": "@fluentui/utilities",
"email": "sarah.higley@microsoft.com",
"dependentChangeType": "patch"
}
21 changes: 9 additions & 12 deletions packages/utilities/src/focus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,7 +477,7 @@ export function shouldWrapFocus(
return elementContainsAttribute(element, noWrapDataAttribute) === 'true' ? false : true;
}

let targetToFocusOnNextRepaint: HTMLElement | { focus: () => void } | null | undefined = undefined;
let animationId: number | undefined = undefined;

/**
* Sets focus to an element asynchronously. The focus will be set at the next browser repaint,
Expand All @@ -487,23 +487,20 @@ let targetToFocusOnNextRepaint: HTMLElement | { focus: () => void } | null | und
*/
export function focusAsync(element: HTMLElement | { focus: () => void } | undefined | null): void {
if (element) {
// An element was already queued to be focused, so replace that one with the new element
if (targetToFocusOnNextRepaint) {
targetToFocusOnNextRepaint = element;
return;
}

targetToFocusOnNextRepaint = element;

const win = getWindow(element as Element);

if (win) {
// cancel any previous focus queues
if (animationId !== undefined) {
win.cancelAnimationFrame(animationId);
}

// element.focus() is a no-op if the element is no longer in the DOM, meaning this is always safe
win.requestAnimationFrame(() => {
targetToFocusOnNextRepaint && targetToFocusOnNextRepaint.focus();
animationId = win.requestAnimationFrame(() => {
element && element.focus();

// We are done focusing for this frame, so reset the queued focus element
targetToFocusOnNextRepaint = undefined;
animationId = undefined;
});
}
}
Expand Down

0 comments on commit d701af3

Please sign in to comment.