Skip to content

Commit 106d346

Browse files
authored
perf(module:modal): call focus() on the next rendering frame to prevent 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.
1 parent 54386ef commit 106d346

2 files changed

Lines changed: 3 additions & 2 deletions

File tree

components/modal/modal-container.directive.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import { fromEvent, Subject } from 'rxjs';
2323
import { takeUntil } from 'rxjs/operators';
2424

2525
import { NzConfigService } from 'ng-zorro-antd/core/config';
26+
import { reqAnimFrame } from 'ng-zorro-antd/core/polyfill';
2627
import { NzSafeAny } from 'ng-zorro-antd/core/types';
2728
import { getElementOffset, isNotNil } from 'ng-zorro-antd/core/util';
2829

@@ -157,7 +158,7 @@ export class BaseModalContainerComponent extends BasePortalOutlet implements OnD
157158
if (this.document) {
158159
this.elementFocusedBeforeModalWasOpened = this.document.activeElement as HTMLElement;
159160
if (this.host.nativeElement.focus) {
160-
this.ngZone.runOutsideAngular(() => Promise.resolve().then(() => this.host.nativeElement.focus()));
161+
this.ngZone.runOutsideAngular(() => reqAnimFrame(() => this.host.nativeElement.focus()));
161162
}
162163
}
163164
}

components/modal/modal.spec.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1121,7 +1121,7 @@ describe('NzModal', () => {
11211121
});
11221122

11231123
fixture.detectChanges();
1124-
flushMicrotasks();
1124+
tick(16);
11251125

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

0 commit comments

Comments
 (0)