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

+62 -89
View File
@@ -1,138 +1,111 @@
<CascadingValue IsFixed=false Value=this>
@implements IAsyncDisposable
@* The app-wide state, cascaded to every page and component (LocalizableComponentBase.CascadingState): the saved
PublicCacheData with its theme settings, the signed-in user, and whether the app is online, polled every 10 seconds. *@
<CascadingValue IsFixed=false Value=this>
@ChildContent
</CascadingValue>
@code {
[Parameter] public RenderFragment ChildContent { get; set; }
[Inject] IStorage DbStorage { get; set; }
[Inject] ILocalStorageService Storage { get; set; }
[Inject] IJSRuntime JS { get; set; }
// [Inject] DataService DataService { get; set; }
[Inject] public AppStatusService Status { get; set; }
[Inject] ILogger<CascadingState> Logger { get; set; }
[Inject] ILoggingService Logger { get; set; }
[Inject] ToastService Toast { get; set; }
public bool IsOnline { get; set; } = true;
Timer IsOnlineTimer { get; set; }
public PublicCacheData PublicCacheData { get; set; }
public User User { get; set; }
public bool IsOnline { get; private set; } = true;
public bool IsOffline => !IsOnline;
public PublicCacheData PublicCacheData { get; private set; } = new();
/// <summary>The signed-in user; Faker's until the login is wired to PrivaPub.</summary>
public User User { get; private set; } = Faker.CurrentUser;
DotNetObjectReference<CascadingState> cascadingStateReference;
PeriodicTimer onlineTimer;
readonly CancellationTokenSource disposeCancellation = new();
protected override async Task OnInitializedAsync()
{
var cancellationToken = disposeCancellation.Token;
try
{
IsOnlineTimer = new Timer(async _ => await UpdateIsOnline(), new AutoResetEvent(false), 0, 10000);
cascadingStateReference = DotNetObjectReference.Create(this);
await JS.InvokeVoidAsync("cascadingStateInstanceReference", cascadingStateReference);
PublicCacheData = await Storage.GetItemAsync<PublicCacheData>(nameof(PublicCacheData));
if (PublicCacheData == null)
{
PublicCacheData = new();
await UpdatePublicCache(PublicCacheData);
}
else
Status.ApplyTheme(PublicCacheData.PageSettings);
await JS.InvokeVoidAsync("cascadingStateInstanceReference", cancellationToken, cascadingStateReference);
User = new();
var publicCacheData = await Storage.GetItemAsync<PublicCacheData>(nameof(PublicCacheData), cancellationToken);
await UpdatePublicCache(publicCacheData ?? new(), cancellationToken);
IsOnline = await Status.IsOnline(cancellationToken);
onlineTimer = new(TimeSpan.FromSeconds(10));
_ = PollOnline(cancellationToken);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(CascadingState)}.{nameof(OnInitializedAsync)}");
await Logger.ProcessError(ex, $"{nameof(CascadingState)}.{nameof(OnInitializedAsync)}", cancellationToken);
}
}
public async ValueTask UpdatePublicCache(PublicCacheData publicCacheData)
/// <summary>Saves the public cache, applies its theme and re-renders the app.</summary>
public async ValueTask UpdatePublicCache(PublicCacheData publicCacheData, CancellationToken cancellationToken = default)
{
try
{
PublicCacheData = publicCacheData;
await Storage.SetItemAsync(nameof(PublicCacheData), PublicCacheData);
Status.ApplyTheme(PublicCacheData.PageSettings);
StateHasChanged();
}
catch (Exception ex)
{
Console.WriteLine($"{nameof(CascadingState)}.{nameof(UpdatePublicCache)}");
Console.WriteLine(ex.ToString());
}
PublicCacheData = publicCacheData;
await Storage.SetItemAsync(nameof(PublicCacheData), PublicCacheData, cancellationToken);
Status.ApplyTheme(PublicCacheData.PageSettings);
StateHasChanged();
}
/// <summary>Changes the page settings, then saves and applies them like UpdatePublicCache.</summary>
public ValueTask UpdatePageSettings(Action<PageSettings> change)
public ValueTask UpdatePageSettings(Action<PageSettings> change, CancellationToken cancellationToken = default)
{
change(PublicCacheData.PageSettings);
return UpdatePublicCache(PublicCacheData);
return UpdatePublicCache(PublicCacheData, cancellationToken);
}
[JSInvokable]
public async Task LogFromJs(string message, string where)
public async Task LogFromJs(string message, string where) =>
await ProcessError(new(message), where);
async Task PollOnline(CancellationToken cancellationToken)
{
try
{
await ProcessError(new(message), where);
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(CascadingState)}.{nameof(LogFromJs)}");
}
}
async Task UpdateIsOnline()
{
try
{
var latestOnlineState = await Status.IsOnline();
//var latestOnlineState = Random.Shared.Next() % 2 == 0;
if (latestOnlineState != IsOnline)
while (await onlineTimer.WaitForNextTickAsync(cancellationToken))
{
IsOnline = latestOnlineState;
StateHasChanged();
var isOnline = await Status.IsOnline(cancellationToken);
if (isOnline == IsOnline)
continue;
IsOnline = isOnline;
await InvokeAsync(StateHasChanged);
}
// else
// {
// var pingIsOnline = await DataService.Ping();
// if (pingIsOnline != IsOnline)
// {
// IsOnline = pingIsOnline;
// StateHasChanged();
// }
// }
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
Logger.LogError(ex, $"{nameof(CascadingState)}.{nameof(UpdateIsOnline)}");
await Logger.ProcessError(ex, $"{nameof(CascadingState)}.{nameof(PollOnline)}", cancellationToken);
}
}
public async ValueTask ProcessError(Exception ex, string where)
/// <summary>Logs an unexpected failure and tells the user.</summary>
public async ValueTask ProcessError(Exception exception, string where, CancellationToken cancellationToken = default)
{
try
{
await DbStorage.AddLog(ex, where);
Logger.LogError(ex, where);
await Task.Run(() => {
});
}
catch (Exception exception)
{
Logger.LogError(exception, $"{nameof(CascadingState)}.{nameof(ProcessError)}");
}
await Logger.ProcessError(exception, where, cancellationToken);
Toast.AddException(exception);
}
public async ValueTask ProcessWarning(string message, string where)
public async ValueTask ProcessWarning(string message, string where, CancellationToken cancellationToken = default)
{
try
{
await DbStorage.AddLog(message, where);
Logger.LogWarning("{where} - {message}", where, message);
await Task.Run(() => {
});
}
catch (Exception exception)
{
Logger.LogError(exception, $"{nameof(CascadingState)}.{nameof(ProcessWarning)}");
}
await Logger.ProcessWarning(message, where, cancellationToken);
Toast.AddWarning(message);
}
}
public async ValueTask DisposeAsync()
{
await disposeCancellation.CancelAsync();
disposeCancellation.Dispose();
onlineTimer?.Dispose();
cascadingStateReference?.Dispose();
}
}
+100 -3
View File
@@ -1,12 +1,109 @@
using collAnon.Client.Services;
using collAnon.Client.Services;
using decePubClient.Services;
using Microsoft.AspNetCore.Components;
namespace decePubClient.LayerComponents
{
public class LocalizableComponentBase : ComponentBase
/// <summary>
/// Base of every page and app component (b2b.next's WidmannComponentBase). It gives them the cascading state, the
/// localizer, navigation and toasts, the loading flag and the disable rule, and the offline helpers: a page that
/// finds the app offline registers its fetch with WhenOnline, starts StartOnlinePolling and stops loading; the
/// job runs once when the app is back online.
/// </summary>
public class LocalizableComponentBase : ComponentBase, IAsyncDisposable
{
[CascadingParameter] protected CascadingState CascadingState { get; set; }
[Inject] public CoalescingStringLocalizer Localizer { get; set; }
protected List<Func<Task>> AfterRenderAsyncJobs = new();
[Inject] protected NavigationManager Navigation { get; set; }
[Inject] protected ToastService Toast { get; set; }
/// <summary>Work to run once after the next render, e.g. JS interop that needs the rendered DOM.</summary>
protected List<Func<Task>> AfterRenderAsyncJobs = [];
/// <summary>True until the component's first load completes; set it to false at the end of OnInitializedAsync.</summary>
protected bool IsLoading { get; set; } = true;
/// <summary>What every Disabled= binding starts from: loading, or no connection.</summary>
protected bool IsDefaultDisabled => IsLoading || CascadingState.IsOffline;
readonly List<Func<Task>> onOnlineJobs = [];
PeriodicTimer pollingTimer;
CancellationTokenSource pollingCancellation;
bool disposed;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (AfterRenderAsyncJobs.Count == 0)
return;
var jobs = AfterRenderAsyncJobs.ToList();
AfterRenderAsyncJobs.Clear();
foreach (var job in jobs)
await job();
}
/// <summary>Runs the job once, the next time the app is online (needs StartOnlinePolling).</summary>
protected void WhenOnline(Func<Task> job) => onOnlineJobs.Add(job);
/// <summary>Checks every interval (10 seconds by default) whether the app is back online to run the WhenOnline jobs.</summary>
protected void StartOnlinePolling(TimeSpan? interval = null)
{
if (pollingTimer is not null)
return;
pollingCancellation = new();
pollingTimer = new(interval ?? TimeSpan.FromSeconds(10));
_ = PollOnline(pollingCancellation.Token);
}
async Task PollOnline(CancellationToken cancellationToken)
{
try
{
while (await pollingTimer.WaitForNextTickAsync(cancellationToken))
{
if (CascadingState.IsOffline || onOnlineJobs.Count == 0)
continue;
var jobs = onOnlineJobs.ToList();
onOnlineJobs.Clear();
foreach (var job in jobs)
{
try
{
await InvokeAsync(job);
}
catch (Exception ex)
{
await CascadingState.ProcessError(ex, $"{GetType().Name}.{nameof(PollOnline)}", cancellationToken);
}
}
await InvokeAsync(StateHasChanged);
}
}
catch (OperationCanceledException)
{
}
}
public virtual async ValueTask DisposeAsync()
{
if (disposed)
return;
disposed = true;
if (pollingCancellation is not null)
{
await pollingCancellation.CancelAsync();
pollingCancellation.Dispose();
}
pollingTimer?.Dispose();
onOnlineJobs.Clear();
GC.SuppressFinalize(this);
}
}
}