1/* 2 * Copyright 2022 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17import { Injectable } from '@angular/core'; 18 19/** 20 * Tracks activity that should show a progress bar. 21 */ 22@Injectable() 23export class ProgressTracker extends EventTarget { 24 private progressCount = 0; 25 26 get isActive() { 27 return this.progressCount > 0; 28 } 29 30 trackPromise<T>(promise: Promise<T>): Promise<T> { 31 queueMicrotask(() => { 32 this.beginProgress(); 33 promise.finally(() => this.endProgress()); 34 }); 35 return promise; 36 } 37 38 /** 39 * Marks the beginning of the progress. 40 * 41 * Must be followed by exactly one endProgress` call. 42 */ 43 beginProgress() { 44 this.progressCount++; 45 if (this.progressCount == 1) { 46 this.dispatchEvent(new Event('progress-started')); 47 } 48 } 49 50 /** 51 * Ends a previously started progress. 52 */ 53 endProgress() { 54 console.assert(this.progressCount > 0); 55 this.progressCount--; 56 if (this.progressCount == 0) { 57 this.dispatchEvent(new Event('progress-ended')); 58 } 59 } 60} 61