Adopt b2b.next's client patterns: services, page state, feedback
Ported from the owner's b2b.next and adapted from MudBlazor to the daisyUI
components:
- LocalizableComponentBase provides CascadingState, Navigation, Toast,
IsLoading/IsDefaultDisabled, WhenOnline/StartOnlinePolling, and after-render
jobs that actually run.
- CascadingState starts with initialised state and polls the online status
with a PeriodicTimer. It reports errors through ILoggingService plus a toast,
and disposes what it holds.
- New pieces:
- ToastService + ToastHost, the snackbar, with AddResponseError/Success/
Warning/Exception in SUtility;
- ErrorViewer, which shows the validation messages plus AdditionalError(s);
- LoggingService, which writes to the console and the IndexedDB client log.
- HttpService is rebuilt and registered:
- auth levels Get/Post/Delete, *Anon and *TotallyAnon;
- retry with backoff;
- classified failures (FailureCodes) instead of exceptions;
- HTTP 410 on cancel;
- the "default" client.
ReadWebResult and DefaultReadFromJsonAsync read its responses.
- ClientJsonContext is source-generated, and SUtility.DefaultSerializer and
Blazored.LocalStorage use it.
- WebResult gains a C# 14 IsInvalid extension property.
The code follows the imported rules:
- Every service and async helper takes a CancellationToken last.
- Primary constructors replace constructor-plus-fields.
- MessagesService and IStorage return Task<WebResult> / Task<List<T>>.
MessagesService is still mock, building its results in memory; the seed
feed and thread moved to Faker.
- Index and ExpandMessage follow the page pattern: an offline guard with
WhenOnline, LoadData, and early returns with toasts on the results they used
to ignore. ExpandMessage reloads on route change and shows "not found"
instead of a null message.
- Model and state collections are [], and the fake identity defaults moved
out of the models.
- Components:
- no ?. chains over initialised state;
- [Inject] instead of @inject;
- IsDefaultDisabled on the actions;
- autocomplete on every text input;
- Localizer[key, args] instead of string.Format;
- the localizer no longer leaks its inner _pLocalizer.
- Settings → General gains a language picker (English/Italiano), and
SetDefaultCulture limits the culture to those two.
Bugs fixed along the way:
- A compose with untouched (null) content passed the empty check.
- File errors were joined with <br/> and rendered as markup.
- ClientLogs.ErrorMessage() threw on warnings.
- CoalescingStringLocalizer[key, args] showed a raw "{0}" for missing keys.
- AppStatusService exposed a call to a JS function that doesn't exist.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LsXgEaXee4GCU1hwYgPJXw
This commit is contained in:
1 parent
ca060f25fb
commit
95428430c0
55 files changed
+1844
-1337
No files matched your search
@@ -2,6 +2,7 @@
|
||||
|
||||
using collAnon.Client.Services;
|
||||
|
||||
using decePubClient.Helpers;
|
||||
using decePubClient.Models;
|
||||
using decePubClient.Services;
|
||||
|
||||
@@ -16,6 +17,8 @@ using PrivaPub.ClientModels;
|
||||
using System.Collections.Specialized;
|
||||
using System.ComponentModel;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http.Json;
|
||||
using System.Text.Json;
|
||||
using System.Web;
|
||||
|
||||
@@ -34,53 +37,47 @@ namespace decePubClient.Extensions
|
||||
public static T QueryString<T>(this NavigationManager navigationManager, string key)
|
||||
{
|
||||
var value = navigationManager.QueryString()[key];
|
||||
var converter = TypeDescriptor.GetConverter(typeof(T));
|
||||
if (converter.IsValid(value))
|
||||
return (T)Convert.ChangeType(value, typeof(T));
|
||||
else
|
||||
if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
|
||||
return default;
|
||||
return (T)Convert.ChangeType(value, typeof(T));
|
||||
}
|
||||
|
||||
#endregion Navigation Manager
|
||||
|
||||
#region Setups
|
||||
|
||||
public static async Task SetDefaultCulture(this WebAssemblyHost host)
|
||||
/// <summary>The languages with resources (Resources/AllStrings.*.resx); any other browser language gets English.</summary>
|
||||
public static readonly string[] SupportedLanguages = ["en", "it"];
|
||||
|
||||
public static async Task SetDefaultCulture(this WebAssemblyHost host, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var culture = default(CultureInfo);
|
||||
var culture = ToCulture(default);
|
||||
try
|
||||
{
|
||||
var storage = host.Services.GetRequiredService<ILocalStorageService>();
|
||||
var publicCache = await storage.GetItemAsync<PublicCacheData>(nameof(PublicCacheData));
|
||||
var publicCache = await storage.GetItemAsync<PublicCacheData>(nameof(PublicCacheData), cancellationToken);
|
||||
if (publicCache is null)
|
||||
{
|
||||
var browserLanguage = host.Services.GetRequiredService<AppStatusService>().Language();
|
||||
publicCache = new();
|
||||
var status = host.Services.GetRequiredService<AppStatusService>();
|
||||
var browserLanguage = status.Language();
|
||||
if (browserLanguage.Contains("en"))
|
||||
browserLanguage = "en-GB";
|
||||
var appConfig = host.Services.GetRequiredService<AppConfiguration>();
|
||||
if (!string.IsNullOrEmpty(publicCache.PageSettings.CurrentLanguageCode) &&
|
||||
publicCache.PageSettings.CurrentLanguageCode.Contains("en"))
|
||||
publicCache.PageSettings.CurrentLanguageCode = "en-GB";
|
||||
culture = new(publicCache.PageSettings.CurrentLanguageCode ?? browserLanguage);
|
||||
publicCache.PageSettings.CurrentLanguageCode = culture.TwoLetterISOLanguageName;
|
||||
await storage.SetItemAsync(nameof(PublicCacheData), publicCache);
|
||||
publicCache.PageSettings.CurrentLanguageCode =
|
||||
SupportedLanguages.FirstOrDefault(language => browserLanguage?.StartsWith(language) ?? false) ?? "en";
|
||||
await storage.SetItemAsync(nameof(PublicCacheData), publicCache, cancellationToken);
|
||||
}
|
||||
|
||||
culture ??= new(publicCache.PageSettings.CurrentLanguageCode == "en" ? "en-GB" : publicCache.PageSettings.CurrentLanguageCode);
|
||||
CultureInfo.DefaultThreadCurrentCulture = culture;
|
||||
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
||||
culture = ToCulture(publicCache.PageSettings.CurrentLanguageCode);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine(ex);
|
||||
culture = new("en-GB");
|
||||
CultureInfo.DefaultThreadCurrentCulture = culture;
|
||||
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
||||
}
|
||||
|
||||
CultureInfo.DefaultThreadCurrentCulture = culture;
|
||||
CultureInfo.DefaultThreadCurrentUICulture = culture;
|
||||
}
|
||||
|
||||
static CultureInfo ToCulture(string languageCode) => languageCode is "it" ? new("it-IT") : new("en-GB");
|
||||
|
||||
#endregion Setups
|
||||
|
||||
public static string GetLogLevelClass(this string logType) => logType switch
|
||||
@@ -112,6 +109,64 @@ namespace decePubClient.Extensions
|
||||
public static string ToString(this WebResult webResult, CoalescingStringLocalizer localizer) =>
|
||||
localizer["{0} - {1}", webResult.StatusCode, webResult.ErrorMessage];
|
||||
|
||||
/// <summary>
|
||||
/// Reads a failed response as a WebResult: a failure HttpService made up (FailureHeader) as is, 401/403 and 5xx
|
||||
/// as a generic message, validation ProblemDetails as their errors, anything else as the server's WebResult.
|
||||
/// A cancelled request (410) becomes SUtility.DefaultTaskCancelledResult.
|
||||
/// </summary>
|
||||
public static async Task<WebResult> ReadWebResult(this HttpContent content, HttpStatusCode statusCode,
|
||||
CoalescingStringLocalizer localizer, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (statusCode is HttpStatusCode.Gone)
|
||||
return SUtility.DefaultTaskCancelledResult;
|
||||
|
||||
var result = new WebResult();
|
||||
try
|
||||
{
|
||||
var json = await content.ReadAsStringAsync(cancellationToken);
|
||||
if (content.Headers.Contains(SUtility.FailureHeader))
|
||||
return JsonSerializer.Deserialize<WebResult>(json, SUtility.DefaultSerializer);
|
||||
|
||||
if (statusCode is HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden)
|
||||
return result.Invalidate(localizer["You are not authorized to do this."], (int)statusCode, FailureCodes.Unauthorized);
|
||||
|
||||
if ((int)statusCode > 499)
|
||||
return result.Invalidate(localizer["The server reported an internal error (HTTP {0}).", (int)statusCode], (int)statusCode,
|
||||
FailureCodes.ServerError);
|
||||
|
||||
if (json.Contains("\"title\""))
|
||||
{
|
||||
var validationErrors = JsonSerializer.Deserialize<ValidationErrors>(json, SUtility.DefaultSerializer);
|
||||
var lines = validationErrors.Errors.Select(error => $"{error.Key}: {string.Join(", ", error.Value)}").Prepend(validationErrors.Title);
|
||||
return result.Invalidate(string.Join('\n', lines), validationErrors.Status);
|
||||
}
|
||||
|
||||
return JsonSerializer.Deserialize<WebResult>(json, SUtility.DefaultSerializer) ??
|
||||
result.Invalidate(localizer["The server sent an invalid response."], (int)statusCode);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return SUtility.DefaultTaskCancelledResult;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return result.Invalidate(localizer["The server sent an invalid response."], (int)HttpStatusCode.BadRequest, exception: ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads a successful response body; a cancelled read returns SUtility.CancellationDefault.</summary>
|
||||
public static async Task<T> DefaultReadFromJsonAsync<T>(this HttpResponseMessage response, CancellationToken cancellationToken = default)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await response.Content.ReadFromJsonAsync<T>(SUtility.DefaultSerializer, cancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
return SUtility.CancellationDefault<T>();
|
||||
}
|
||||
}
|
||||
|
||||
public static string Timeframe(this DateTime creationDate, CoalescingStringLocalizer localizer)
|
||||
{
|
||||
var timeframe = DateTime.Now - creationDate.ToLocalTime();
|
||||
@@ -133,19 +188,19 @@ namespace decePubClient.Extensions
|
||||
|
||||
public static AuthorizationPolicy IsAdminPolicy() =>
|
||||
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
||||
.RequireClaim(Policies.IsAdmin, true.ToString().ToLower())
|
||||
.RequireClaim(Policies.IsUser, true.ToString().ToLower())
|
||||
.RequireClaim(Policies.IsModerator, true.ToString().ToLower())
|
||||
.RequireClaim(Policies.IsAdmin, "true")
|
||||
.RequireClaim(Policies.IsUser, "true")
|
||||
.RequireClaim(Policies.IsModerator, "true")
|
||||
.Build();
|
||||
|
||||
public static AuthorizationPolicy IsUserPolicy() =>
|
||||
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
||||
.RequireClaim(Policies.IsUser, true.ToString().ToLower())
|
||||
.RequireClaim(Policies.IsUser, "true")
|
||||
.Build();
|
||||
|
||||
public static AuthorizationPolicy IsUserModeratorPolicy() =>
|
||||
new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
||||
.RequireClaim(Policies.IsModerator, true.ToString().ToLower())
|
||||
.RequireClaim(Policies.IsModerator, "true")
|
||||
.Build();
|
||||
|
||||
#endregion
|
||||
|
||||
Reference in new issue
Block a user