Skip to content

Commit

Permalink
perf(module:modal): call focus() on the next rendering frame to pre…
Browse files Browse the repository at this point in the history
…vent frame drop (#7293)

Calling `focus()` on the element causes browsers to do re-layouts. This can been seen here:
https://gist.github.com/paulirish/5d52fb081b3570c81e3a#setting-focus
Microtasks are executed asynchronously, but within the current rendering frame. Using `requestAnimationFrame`
except of `Promise.resolve` basically unloads the current frame and calls `focus()` on the next rendering
frame, this prevent frame drops on slower devices when the modal is opened.
  • Loading branch information
arturovt committed Apr 21, 2022
1 parent 54386ef commit 106d346
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 2 deletions.
3 changes: 2 additions & 1 deletion components/modal/modal-container.directive.ts
Expand Up @@ -23,6 +23,7 @@ import { fromEvent, Subject } from 'rxjs';
import { takeUntil } from 'rxjs/operators';

import { NzConfigService } from 'ng-zorro-antd/core/config';
import { reqAnimFrame } from 'ng-zorro-antd/core/polyfill';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { getElementOffset, isNotNil } from 'ng-zorro-antd/core/util';

Expand Down Expand Up @@ -157,7 +158,7 @@ export class BaseModalContainerComponent extends BasePortalOutlet implements OnD
if (this.document) {
this.elementFocusedBeforeModalWasOpened = this.document.activeElement as HTMLElement;
if (this.host.nativeElement.focus) {
this.ngZone.runOutsideAngular(() => Promise.resolve().then(() => this.host.nativeElement.focus()));
this.ngZone.runOutsideAngular(() => reqAnimFrame(() => this.host.nativeElement.focus()));
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion components/modal/modal.spec.ts
Expand Up @@ -1121,7 +1121,7 @@ describe('NzModal', () => {
});

fixture.detectChanges();
flushMicrotasks();
tick(16);

expect(document.activeElement!.tagName).toBe('NZ-MODAL-CONTAINER', 'Expected modal container to be focused.');
}));
Expand Down

0 comments on commit 106d346

Please sign in to comment.