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:
thepraandClaude Opus 5.5 committed 2026-10-03 15:26:21 +02:00
1 parent ca060f25fb
commit 95428430c0
55 files changed
+1844 -1337

No files matched your search

+20 -33
View File
@@ -1,4 +1,5 @@
using Blazored.LocalStorage;
using decePubClient.Helpers;
using decePubClient.Models;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
@@ -6,22 +7,9 @@ using System.Text.Json;
namespace decePubClient.Services
{
public class TokenAuthStateProvider : AuthenticationStateProvider
public class TokenAuthStateProvider(ILocalStorageService storage, IStorage dbStorage, ILogger<TokenAuthStateProvider> logger)
: AuthenticationStateProvider
{
readonly ILocalStorageService Storage;
readonly IStorage DbStorage;
readonly ILogger<TokenAuthStateProvider> Logger;
AuthData AuthData { get; set; }
public TokenAuthStateProvider(ILocalStorageService storage,
IStorage dbStorage,
ILogger<TokenAuthStateProvider> logger)
{
Storage = storage;
DbStorage = dbStorage;
Logger = logger;
}
public void SetToken(/*string token, long expirationTicks = default*/)
{
//AuthData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
@@ -41,41 +29,40 @@ namespace decePubClient.Services
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public async ValueTask<bool> IsAuthenticatedAsync()
/// <summary>The stored token while it is still valid, otherwise null.</summary>
public async Task<string> GetToken(CancellationToken cancellationToken = default)
{
AuthData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
if (AuthData is null)
{
AuthData = new();
await Storage.SetItemAsync(nameof(AuthData), AuthData);
}
return AuthData.Token != null &&
AuthData.TokenExpiration.HasValue &&
AuthData.TokenExpiration.Value > DateTime.UtcNow.Ticks;
var authData = await storage.GetItemAsync<AuthData>(nameof(AuthData), cancellationToken);
if (string.IsNullOrEmpty(authData?.Token) || authData.TokenExpiration is not { } expiration || expiration <= DateTime.UtcNow.Ticks)
return null;
return authData.Token;
}
public async Task LogoutAsync(bool deleteDb = false)
public async Task<bool> IsAuthenticatedAsync(CancellationToken cancellationToken = default) =>
await GetToken(cancellationToken) is not null;
public async Task LogoutAsync(bool deleteDb = false, CancellationToken cancellationToken = default)
{
Logger.LogInformation($"set null({nameof(LogoutAsync)})");
logger.LogInformation($"set null({nameof(LogoutAsync)})");
//await Storage.RemoveItemAsync(nameof(PrivateCacheData));
await Storage.RemoveItemAsync(nameof(AuthData));
await storage.RemoveItemAsync(nameof(AuthData), cancellationToken);
if (deleteDb)
await DbStorage.RemoveAll(includeClientLogs: true);
await dbStorage.RemoveAll(includeClientLogs: true, cancellationToken: cancellationToken);
NotifyAuthenticationStateChanged(GetAuthenticationStateAsync());
}
public override async Task<AuthenticationState> GetAuthenticationStateAsync()
{
AuthData = await Storage.GetItemAsync<AuthData>(nameof(AuthData));
if (string.IsNullOrEmpty(AuthData?.Token))
var authData = await storage.GetItemAsync<AuthData>(nameof(AuthData));
if (string.IsNullOrEmpty(authData?.Token))
{
Logger.LogInformation($"set null({nameof(GetAuthenticationStateAsync)})");
logger.LogInformation($"set null({nameof(GetAuthenticationStateAsync)})");
return new(new());
}
var claims = new List<Claim>
{
new(ClaimTypes.UserData, JsonSerializer.Serialize(AuthData.User))
new(ClaimTypes.UserData, JsonSerializer.Serialize(authData.User, SUtility.DefaultSerializer))
};
//claims.Add(new(Policies.IsUser, (AuthData.User.Policies.Contains(Policies.IsUser)).ToString().ToLower()));