github.com/web-platform-tests/wpt.fyi@v0.0.0-20240530210107-70cf978996f1/webapp/components/loading-state.js (about) 1 /** 2 * Copyright 2018 The WPT Dashboard Project. All rights reserved. 3 * Use of this source code is governed by a BSD-style license that can be 4 * found in the LICENSE file. 5 */ 6 7 /* 8 LoadingState is a behaviour component for indicating when information is 9 still being loaded (generally, fetched). 10 */ 11 12 // eslint-disable-next-line no-unused-vars 13 const LoadingState = (superClass) => class extends superClass { 14 static get properties() { 15 return { 16 loadingCount: { 17 type: Number, 18 value: 0, 19 observer: 'loadingCountChanged', 20 }, 21 isLoading: { 22 type: Boolean, 23 computed: 'computeIsLoading(loadingCount)', 24 notify: true, 25 }, 26 onLoadingComplete: Function, 27 }; 28 } 29 30 computeIsLoading(loadingCount) { 31 return !!loadingCount; 32 } 33 34 loadingCountChanged(now, then) { 35 if (now === 0 && then > 0 && this.onLoadingComplete) { 36 this.onLoadingComplete(); 37 } 38 } 39 40 async load(promise, opt_errHandler) { 41 this.loadingCount++; 42 try { 43 return await promise; 44 } catch (e) { 45 // eslint-disable-next-line no-console 46 console.log(`Failed to load: ${e}`); 47 if (opt_errHandler) { 48 opt_errHandler(e); 49 } 50 } finally { 51 this.loadingCount--; 52 } 53 } 54 55 retry(f, shouldRetry, num, wait) { 56 let count = 0; 57 const retry = () => { 58 count++; 59 return f().catch(err => { 60 if (count >= num || !shouldRetry(err)) { 61 throw err; 62 } 63 return new Promise((resolve, reject) => window.setTimeout( 64 () => retry().then(resolve, reject), 65 wait 66 )); 67 }); 68 }; 69 return retry(); 70 } 71 }; 72 73 export { LoadingState };