1+ using System . Text . RegularExpressions ;
2+
13namespace BlazorBootstrap . Demo . RCL . Components . Pages . Home ;
24
35/// <summary>
@@ -13,8 +15,23 @@ public partial class Index : BlazorBootstrapComponentBase
1315
1416 private const string GettingStartedUrl = "/getting-started/blazor-webassembly" ;
1517
18+ // The same shields.io sources as the production NuGet and GitHub badges, in JSON form.
19+ // shields.io caches them for 30 minutes and allows cross-origin requests from the WebAssembly host.
20+ private const string GitHubStarsBadgeUrl = "https://img.shields.io/github/stars/vikramlearning/blazorbootstrap.json" ;
21+
1622 private const string InstallCommand = "dotnet add package Blazor.Bootstrap" ;
1723
24+ private const string NuGetDownloadsBadgeUrl = "https://img.shields.io/nuget/dt/Blazor.Bootstrap.json" ;
25+
26+ private const string NuGetPackageUrl = "https://www.nuget.org/packages/Blazor.Bootstrap/" ;
27+
28+ private static readonly TimeSpan LiveStatsTimeout = TimeSpan . FromSeconds ( 5 ) ;
29+
30+ // A shields.io count such as "2.9M" or "1.2k". Error messages such as "inaccessible" are rejected.
31+ private static readonly Regex ShieldsCountPattern = new ( @"^\d+(\.\d+)?[kMB]?$" , RegexOptions . CultureInvariant ) ;
32+
33+ private readonly CancellationTokenSource disposeCts = new ( ) ;
34+
1835 private string copyStatus = string . Empty ;
1936
2037 private string description = "An Enterprise-class Blazor Bootstrap Component library built on the Blazor and Bootstrap CSS frameworks." ;
@@ -31,7 +48,13 @@ public partial class Index : BlazorBootstrapComponentBase
3148
3249 private string releaseShortDescription = default ! ;
3350
34- private IReadOnlyList < ( string Label , string Value ) > stats = Array . Empty < ( string Label , string Value ) > ( ) ;
51+ private string ? githubStars ;
52+
53+ private string ? githubUrl ;
54+
55+ private string ? nugetDownloads ;
56+
57+ private IReadOnlyList < ( string Label , string Value , string ? Url ) > stats = Array . Empty < ( string Label , string Value , string ? Url ) > ( ) ;
3558
3659 private string title = "Blazor Bootstrap Component Library" ;
3760
@@ -46,27 +69,35 @@ public partial class Index : BlazorBootstrapComponentBase
4669 protected override async ValueTask DisposeAsyncCore ( bool disposing )
4770 {
4871 if ( disposing )
72+ {
73+ // Cancelled but not disposed, so a fetch still in flight can safely observe it.
74+ disposeCts . Cancel ( ) ;
4975 objRef ? . Dispose ( ) ;
76+ }
5077
5178 await base . DisposeAsyncCore ( disposing ) ;
5279 }
5380
81+ protected override async Task OnAfterRenderAsync ( bool firstRender )
82+ {
83+ await base . OnAfterRenderAsync ( firstRender ) ;
84+
85+ // After the first interactive render, so prerendering and first paint never wait on the network.
86+ if ( firstRender )
87+ await RefreshLiveStatsAsync ( ) ;
88+ }
89+
5490 protected override void OnInitialized ( )
5591 {
5692 version = $ "v{ Configuration [ "version" ] } "; // example: v4.0.1
5793 releaseShortDescription = Configuration [ "release:short_description" ] ! ;
58- releaseNotesUrl = $ "{ Configuration [ "urls:github" ] } /releases";
94+ githubUrl = Configuration [ "urls:github" ] ;
95+ releaseNotesUrl = $ "{ githubUrl } /releases";
5996
60- // A stat with no configured value is left out instead of showing an empty box.
61- stats = new ( string Label , string ? Value ) [ ]
62- {
63- ( "NuGet downloads" , Configuration [ "stats:nuget_downloads" ] ) ,
64- ( "GitHub stars" , Configuration [ "stats:github_stars" ] ) ,
65- ( "Components" , Configuration [ "stats:components" ] )
66- }
67- . Where ( stat => ! string . IsNullOrWhiteSpace ( stat . Value ) )
68- . Select ( stat => ( stat . Label , stat . Value ! ) )
69- . ToList ( ) ;
97+ // The configured values show until the live values arrive, and stay if they cannot be fetched.
98+ nugetDownloads = Configuration [ "stats:nuget_downloads" ] ;
99+ githubStars = Configuration [ "stats:github_stars" ] ;
100+ BuildStats ( ) ;
70101
71102 base . OnInitialized ( ) ;
72103 }
@@ -110,12 +141,63 @@ public void ResetCopyStatusJS()
110141
111142 #region Private Methods
112143
144+ private void BuildStats ( )
145+ {
146+ // A stat with no value is left out instead of showing an empty box.
147+ stats = new ( string Label , string ? Value , string ? Url ) [ ]
148+ {
149+ ( "NuGet downloads" , nugetDownloads , NuGetPackageUrl ) ,
150+ ( "GitHub stars" , githubStars , string . IsNullOrWhiteSpace ( githubUrl ) ? null : githubUrl ) ,
151+ ( "Components" , Configuration [ "stats:components" ] , null )
152+ }
153+ . Where ( stat => ! string . IsNullOrWhiteSpace ( stat . Value ) )
154+ . Select ( stat => ( stat . Label , stat . Value ! , stat . Url ) )
155+ . ToList ( ) ;
156+ }
157+
113158 private async Task CopyInstallCommandAsync ( )
114159 {
115160 objRef ??= DotNetObjectReference . Create ( this ) ;
116161 await SafeInvokeVoidAsync ( "copyToClipboard" , InstallCommand , objRef ) ;
117162 }
118163
164+ /// <summary>
165+ /// Gets the count from a shields.io JSON badge, or <see langword="null" /> when it cannot be fetched or is not a count.
166+ /// </summary>
167+ private async Task < string ? > GetShieldsCountAsync ( string url , CancellationToken cancellationToken )
168+ {
169+ try
170+ {
171+ var badge = await HttpClient . GetFromJsonAsync < ShieldsBadge > ( url , cancellationToken ) ;
172+ var value = badge ? . Value ? . Trim ( ) ;
173+
174+ return value is not null && ShieldsCountPattern . IsMatch ( value ) ? value : null ;
175+ }
176+ catch ( Exception ex ) when ( ex is HttpRequestException or OperationCanceledException or System . Text . Json . JsonException or NotSupportedException )
177+ {
178+ return null ;
179+ }
180+ }
181+
182+ private async Task RefreshLiveStatsAsync ( )
183+ {
184+ using var timeoutCts = CancellationTokenSource . CreateLinkedTokenSource ( disposeCts . Token ) ;
185+ timeoutCts . CancelAfter ( LiveStatsTimeout ) ;
186+
187+ var downloadsTask = GetShieldsCountAsync ( NuGetDownloadsBadgeUrl , timeoutCts . Token ) ;
188+ var starsTask = GetShieldsCountAsync ( GitHubStarsBadgeUrl , timeoutCts . Token ) ;
189+ var liveDownloads = await downloadsTask ;
190+ var liveStars = await starsTask ;
191+
192+ if ( disposeCts . IsCancellationRequested || ( liveDownloads is null && liveStars is null ) )
193+ return ;
194+
195+ nugetDownloads = liveDownloads ?? nugetDownloads ;
196+ githubStars = liveStars ?? githubStars ;
197+ BuildStats ( ) ;
198+ StateHasChanged ( ) ;
199+ }
200+
119201 #endregion
120202
121203 #endregion
@@ -124,6 +206,8 @@ private async Task CopyInstallCommandAsync()
124206
125207 [ Inject ] public IConfiguration Configuration { get ; set ; } = default ! ;
126208
209+ [ Inject ] public HttpClient HttpClient { get ; set ; } = default ! ;
210+
127211 private string FilterStatusText
128212 {
129213 get
@@ -161,4 +245,9 @@ private IEnumerable<HomeCatalogCategory> ShownCategories
161245 }
162246
163247 #endregion
248+
249+ /// <summary>
250+ /// The part of a shields.io JSON badge this page reads, such as <c>{"value":"2.9M"}</c>.
251+ /// </summary>
252+ private sealed record ShieldsBadge ( string ? Value ) ;
164253}
0 commit comments