MOBILE-3814 chore: Create a wait to be visible function

main
Pau Ferrer Ocaña 2022-03-16 11:56:25 +01:00
parent 8b3a07d224
commit 1819c743a6
2 changed files with 40 additions and 5 deletions

View File

@ -27,7 +27,7 @@ export class CoreOnAppearDirective implements OnInit, OnDestroy {
@Output() onAppear = new EventEmitter();
private element: HTMLElement;
protected domPromise?: CoreCancellablePromise<void>;
protected visiblePromise?: CoreCancellablePromise<void>;
constructor(element: ElementRef) {
this.element = element.nativeElement;
@ -37,9 +37,9 @@ export class CoreOnAppearDirective implements OnInit, OnDestroy {
* @inheritdoc
*/
async ngOnInit(): Promise<void> {
this.domPromise = CoreDomUtils.waitToBeInDOM(this.element);
this.visiblePromise = CoreDomUtils.waitToBeVisible(this.element);
await this.domPromise;
await this.visiblePromise;
this.onAppear.emit();
}
@ -48,7 +48,7 @@ export class CoreOnAppearDirective implements OnInit, OnDestroy {
* @inheritdoc
*/
ngOnDestroy(): void {
this.domPromise?.cancel();
this.visiblePromise?.cancel();
}
}

View File

@ -100,7 +100,7 @@ export class CoreDomUtilsProvider {
* @param timeout If defined, timeout to wait before rejecting the promise.
* @return Cancellable promise.
*/
waitToBeInDOM(element: Element, timeout?: number): CoreCancellablePromise<void> {
waitToBeInDOM(element: HTMLElement, timeout?: number): CoreCancellablePromise<void> {
const root = element.getRootNode({ composed: true });
if (root === document) {
@ -140,6 +140,41 @@ export class CoreDomUtilsProvider {
);
}
/**
* Wait an element to be in dom and visible.
*
* @param element Element to wait.
* @return Cancellable promise.
*/
waitToBeVisible(element: HTMLElement): CoreCancellablePromise<void> {
const domPromise = CoreDomUtils.waitToBeInDOM(element);
let interval: number | undefined;
return new CoreCancellablePromise<void>(
async (resolve) => {
await domPromise;
if (CoreDomUtils.isElementVisible(element)) {
return resolve();
}
interval = window.setInterval(() => {
if (!CoreDomUtils.isElementVisible(element)) {
return;
}
resolve();
window.clearInterval(interval);
}, 50);
},
() => {
domPromise.cancel();
window.clearInterval(interval);
},
);
}
/**
* Window resize is widely checked and may have many performance issues, debouce usage is needed to avoid calling it too much.
* This function helps setting up the debounce feature and remove listener easily.