Skip to content

Commit b04e0a3

Browse files
authored
feat(demo): Show live NuGet downloads and GitHub stars on the home page (#1398)
Fetch the counts from the same shields.io sources as the production badges after the first interactive render, keeping the configured values as the prerender and failure fallback. Link the NuGet downloads box to the NuGet package page and the GitHub stars box to the repository. QF-26112004
1 parent 1179774 commit b04e0a3

3 files changed

Lines changed: 118 additions & 14 deletions

File tree

‎BlazorBootstrap.Demo.RCL/Components/Pages/Home/Index.razor‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,18 @@
3838
<dl class="bd-home-stats d-flex flex-wrap justify-content-center gap-3 mt-4 mb-0">
3939
@foreach (var stat in stats)
4040
{
41-
<div class="d-flex flex-column-reverse px-3 py-2 rounded-3">
42-
<dt class="small fw-normal text-body-secondary">@stat.Label</dt>
41+
<div class="position-relative d-flex flex-column-reverse px-3 py-2 rounded-3">
42+
<dt class="small fw-normal text-body-secondary">
43+
@if (stat.Url is null)
44+
{
45+
@stat.Label
46+
}
47+
else
48+
{
49+
@* The stretched link makes the whole box clickable; its name stays the stat label. *@
50+
<a class="stretched-link text-reset" href="@stat.Url">@stat.Label</a>
51+
}
52+
</dt>
4353
<dd class="fs-4 fw-semibold mb-0">@stat.Value</dd>
4454
</div>
4555
}

‎BlazorBootstrap.Demo.RCL/Components/Pages/Home/Index.razor.cs‎

Lines changed: 101 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
using System.Text.RegularExpressions;
2+
13
namespace 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
}

‎BlazorBootstrap.Demo.RCL/wwwroot/css/blazorbootstrap.demo.rcl.css‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,6 +225,11 @@ h1:focus-visible {
225225
border: var(--bs-border-width) solid var(--bs-border-color);
226226
}
227227

228+
.bd-home-stats > div:has(a:hover),
229+
.bd-home-stats > div:has(a:focus-visible) {
230+
border-color: var(--bs-primary);
231+
}
232+
228233
/*
229234
* Reserve the Carbon cover ad's space so the content below does not move when it loads.
230235
* Carbon's cover format is up to 400px wide. At 360px and wider it lays out side by side

0 commit comments

Comments
 (0)