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

+93 -147
View File
@@ -27,7 +27,7 @@
{
<Content Message="message"
OnMessageBoost="async (m) => await OnMessageBoost(m)" OnMessageDelete="async (m) => await OnMessageDelete(m)"
OnMessageFavourite="async (m) => await OnMessageFavourite(m)" OnMessageReply="async (m) => await OnMessageReply(m)"
OnMessageFavourite="async (m) => await OnMessageFavourite(m)" OnMessageReply="async (m) => await OnMessageSubmit(m)"
OnMessageMediaDownload="async (m) => await OnMessageMediaDownload(m)"
OnUserBlock="async (u) => await OnUserBlock(u)" OnUserDirectMessage="async (u) => await OnUserDirectMessage(u)" OnUserSilence="async (u) => await OnUserSilence(u)" />
}
@@ -58,55 +58,39 @@
</div>
@code {
[CascadingParameter] Task<AuthenticationState> AuthState { get; set; }
[CascadingParameter] CascadingState CascadingState { get; set; }
[Inject] IBlazorDownloadFileService BlazorDownloadFileService { get; set; }
[Inject] IStorage Storage { get; set; }
[Inject] ILocalStorageService LocalStorage { get; set; }
[Inject] HttpClient Http { get; set; }
[Inject] MessagesService MessagesService { get; set; }
TimelineType TimelineType { get; set; } = TimelineType.Home;
TimeSortingType TimeSortingType { get; set; } = TimeSortingType.Ascending;
IReadOnlyList<Claim> userClaim
{
get
{
var auth = AuthState.Result;
if (auth.User.Identity?.IsAuthenticated ?? false)
return auth.User.Claims.ToList();
return new List<Claim>();
}
}
List<Message> IncomingMessages { get; set; } = new();
List<Message> Messages { get; set; } = new();
string Response { get; set; }
List<Message> Messages { get; set; } = [];
protected override async Task OnInitializedAsync()
{
var filters = await LocalStorage.GetItemAsync<ActionBarFilter>(nameof(ActionBarFilter));
if (filters == default)
await LocalStorage.SetItemAsync(nameof(ActionBarFilter), new ActionBarFilter());
else
var filters = await LocalStorage.GetItemAsync<ActionBarFilter>(nameof(ActionBarFilter)) ?? new();
TimelineType = filters.TimelineType;
TimeSortingType = filters.TimeSortingType;
if (CascadingState.IsOffline)
{
TimelineType = filters.TimelineType;
TimeSortingType = filters.TimeSortingType;
WhenOnline(LoadData);
StartOnlinePolling();
IsLoading = false;
return;
}
Messages = await Storage.GetMessages();
//try
//{
// var response = await Http.GetAsync("api/test");
// Response = await response.Content.ReadAsStringAsync();
//}
//catch
//{
//}
await LoadData();
IsLoading = false;
}
// The feed: the mock one in IndexedDB until the app reads PrivaPub's timeline.
async Task LoadData()
{
Messages = await Storage.GetMessages();
}
void OnTimelineChanged(TimelineType timelineType)
{
TimelineType = timelineType;
@@ -117,143 +101,105 @@
TimeSortingType = timeSortingType;
}
// Covers replies too: the form carries the RootMessageId.
async Task OnMessageSubmit(MessageForm messageForm)
{
await Task.Run(() =>
var result = await MessagesService.SubmitMessage(messageForm, CascadingState.User);
if (result.IsInvalid)
{
});
var submitMessage = await MessagesService.SubmitMessage(messageForm);
Messages.Insert(0, new()
{
MessageId = Guid.NewGuid().ToString(),
Content = messageForm.Content?.ParseContent(messageForm.ContentType),
CreatedAt = DateTime.UtcNow,
MessageType = messageForm.MessageType,
Medias = messageForm.Media.Select(m => new Media
{
FileName = m.FileName,
AltText = m.AltText,
ContentType = m.ContentType,
Url = m.Base64Preview,
Blob = m.Blob
}).ToList(),
Title = messageForm.Title,
User = new MessageUser
{
UserId = CascadingState.User.Id,
UserName = CascadingState.User.UserName,
DisplayName = CascadingState.User.DisplayName,
PictureUrl = CascadingState.User.PictureUrl,
ProfileUrl = CascadingState.User.ProfileUrl,
BackgroundUrl = CascadingState.User.BackgroundUrl
},
});
}
async Task OnMessageReply(MessageForm messageForm)
{
await Task.Run(() =>
{
});
var replyMessage = await MessagesService.SubmitMessage(messageForm);
Messages.Insert(0, new()
{
RootMessageId = messageForm.RootMessageId,
MessageId = Guid.NewGuid().ToString(),
Content = messageForm.Content?.ParseContent(messageForm.ContentType),
CreatedAt = DateTime.UtcNow,
MessageType = messageForm.MessageType,
Medias = messageForm.Media.Select(m => new Media
{
FileName = m.FileName,
AltText = m.AltText,
ContentType = m.ContentType,
Url = m.Base64Preview,
Blob = m.Blob
}).ToList(),
Title = messageForm.Title,
User = new MessageUser
{
UserId = CascadingState.User.Id,
UserName = CascadingState.User.UserName,
DisplayName = CascadingState.User.DisplayName,
PictureUrl = CascadingState.User.PictureUrl,
ProfileUrl = CascadingState.User.ProfileUrl,
BackgroundUrl = CascadingState.User.BackgroundUrl
}
});
}
async ValueTask OnMessageBoost(Message message)
{
var boostedMessageTemp = await MessagesService.BoostUnboostMessage(message);
message.BoostsCounter = message.IsBoostedByCurrentUser ? message.BoostsCounter - 1 : message.BoostsCounter + 1;
message.IsBoostedByCurrentUser = !message.IsBoostedByCurrentUser;
if (message.IsBoostedByCurrentUser)
{
var boostedMessage = new Message
{
BoostingUser = new()
{
UserId = CascadingState.User.Id,
DisplayName = CascadingState.User.DisplayName,
PictureUrl = CascadingState.User.PictureUrl,
ProfileUrl = CascadingState.User.ProfileUrl,
UserName = CascadingState.User.UserName
},
BoostsCounter = message.BoostsCounter,
Content = message.Content,
CreatedAt = message.CreatedAt,
IsBoostedByCurrentUser = true,
IsFavourite = message.IsFavourite,
Medias = message.Medias,
MessageId = message.MessageId,
MessageType = message.MessageType,
RootMessageId = message.RootMessageId,
Title = message.Title,
User = message.User
};
Messages.Insert(0, boostedMessage);
Toast.AddResponseError(result);
return;
}
else
Messages.Insert(0, result.Data as Message);
}
async Task OnMessageBoost(Message message)
{
var result = await MessagesService.BoostUnboostMessage(message);
if (result.IsInvalid)
{
Messages.RemoveAll(m => m.MessageId == message.MessageId && m.BoostingUser != null && m.BoostingUser.UserId == CascadingState.User.Id);
Toast.AddResponseError(result);
return;
}
if (!message.IsBoostedByCurrentUser)
{
Messages.RemoveAll(m => m.MessageId == message.MessageId && m.BoostingUser?.UserId == CascadingState.User.Id);
return;
}
// The feed shows a boost as a copy of the message carrying the booster.
Messages.Insert(0, new()
{
BoostingUser = CascadingState.User.ToBoostingUser(),
BoostsCounter = message.BoostsCounter,
Content = message.Content,
CreatedAt = message.CreatedAt,
IsBoostedByCurrentUser = true,
IsFavourite = message.IsFavourite,
Medias = message.Medias,
MessageId = message.MessageId,
MessageType = message.MessageType,
RootMessageId = message.RootMessageId,
Title = message.Title,
User = message.User
});
}
async ValueTask OnMessageFavourite(Message message)
async Task OnMessageFavourite(Message message)
{
message.IsFavourite = !message.IsFavourite;
var favouriteMessage = await MessagesService.FavouriteUnfavouriteMessage(message);
var result = await MessagesService.FavouriteUnfavouriteMessage(message);
if (result.IsInvalid)
Toast.AddResponseError(result);
}
async ValueTask OnMessageDelete(Message message)
async Task OnMessageDelete(Message message)
{
var result = await MessagesService.DeleteMessage(message);
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
Messages.Remove(message);
var deleteResult = await MessagesService.DeleteMessage(message);
Toast.AddResponseSuccess(Localizer["Message deleted."]);
}
async ValueTask OnMessageMediaDownload(Media media)
async Task OnMessageMediaDownload(Media media)
{
await Task.Run(() =>
{
});
await BlazorDownloadFileService.DownloadFileAsync(media.FileName, media.Blob, media.ContentType);
}
async ValueTask OnUserBlock(MessageUser messageUser)
async Task OnUserBlock(MessageUser messageUser)
{
var blockResult = await MessagesService.BlockUserFromMessage(messageUser);
var result = await MessagesService.BlockUserFromMessage(messageUser);
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
Toast.AddResponseSuccess(Localizer["{0} blocked.", messageUser.DisplayName]);
}
async ValueTask OnUserDirectMessage(Message message)
async Task OnUserDirectMessage(Message message)
{
var directMessage = await MessagesService.ReplyMessage(message, MessageType.Direct);
var result = await MessagesService.ReplyMessage(message, MessageType.Direct);
if (result.IsInvalid)
Toast.AddResponseError(result);
}
async ValueTask OnUserSilence(MessageUser messageUser)
async Task OnUserSilence(MessageUser messageUser)
{
var silenceResult = await MessagesService.SilenceUserFromMessage(messageUser);
}
var result = await MessagesService.SilenceUserFromMessage(messageUser);
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
}
Toast.AddResponseSuccess(Localizer["{0} muted.", messageUser.DisplayName]);
}
}