From ccfc77749653eeb539580701d2216997719b2e36 Mon Sep 17 00:00:00 2001 From: Anuradha Wickramarachchi Date: Mon, 9 Dec 2024 22:53:29 +0000 Subject: [PATCH] DEV: add debounce to component spinner --- .../component-spinner.component.html | 2 +- .../component-spinner.component.ts | 47 ++++++++++++++++++- 2 files changed, 46 insertions(+), 3 deletions(-) diff --git a/webgui/webapp/src/app/components/component-spinner/component-spinner.component.html b/webgui/webapp/src/app/components/component-spinner/component-spinner.component.html index 39901fb..62c46a4 100644 --- a/webgui/webapp/src/app/components/component-spinner/component-spinner.component.html +++ b/webgui/webapp/src/app/components/component-spinner/component-spinner.component.html @@ -1,4 +1,4 @@ -@if (loading) { +@if (localLoading | async) {
diff --git a/webgui/webapp/src/app/components/component-spinner/component-spinner.component.ts b/webgui/webapp/src/app/components/component-spinner/component-spinner.component.ts index c19d232..4f0a15b 100644 --- a/webgui/webapp/src/app/components/component-spinner/component-spinner.component.ts +++ b/webgui/webapp/src/app/components/component-spinner/component-spinner.component.ts @@ -1,12 +1,55 @@ -import { Component, Input } from '@angular/core'; +import { AsyncPipe } from '@angular/common'; +import { Component, Input, OnDestroy, OnInit } from '@angular/core'; +import { OnChanges, SimpleChanges } from '@angular/core'; +import { + debounce, + distinctUntilChanged, + map, + Observable, + pairwise, + startWith, + Subject, + timer, +} from 'rxjs'; @Component({ selector: 'app-component-spinner', templateUrl: './component-spinner.component.html', styleUrls: ['./component-spinner.component.scss'], + imports: [AsyncPipe], standalone: true, }) -export class ComponentSpinnerComponent { +export class ComponentSpinnerComponent implements OnChanges, OnInit, OnDestroy { @Input() loading: boolean = false; + localLoading: Observable = new Observable(); + private loadingSubject = new Subject(); + + ngOnChanges(changes: SimpleChanges): void { + if (changes['loading']) { + this.loadingSubject.next(this.loading); + } + } + + /** + * Lifecycle hook that is called after data-bound properties of a directive are initialized. + * Initializes the localLoading observable by subscribing to the loadingSubject observable. + * + * The localLoading observable: + * - Starts with a value of false. + * - Emits values only when they change. + * - Emits a value after a debounce period, which is 1000ms if the previous value was true, otherwise 0ms. + * - Maps the emitted pair to the current value. + */ + ngOnInit(): void { + this.localLoading = this.loadingSubject.pipe( + startWith(false), + distinctUntilChanged(), + pairwise(), + debounce(([prev, _]) => (!!prev ? timer(1000) : timer(0))), + map(([_, curr]) => curr), + ); + } + + ngOnDestroy(): void {} }