Files
decePubClient/Extensions/GenericExtensions.cs
T
thepraandClaude Opus 5.5 95428430c0 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
2026-10-03 15:26:21 +02:00

155 lines
3.9 KiB
C#

using collAnon.Client.Services;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Web;
using Blazored.LocalStorage;
using decePubClient.Models;
using decePubClient.Models.Types;
using decePubClient.Resources;
using decePubClient.Services;
using DnetIndexedDb;
using DnetIndexedDb.Fluent;
using DnetIndexedDb.Models;
using Markdig;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Localization;
namespace decePubClient.Extensions;
public static class GenericExtensions
{
public static IServiceCollection AddIndexedDb(this IServiceCollection services)
{
return services.AddIndexedDbDatabase<IndexedDb>(options =>
{
var model = new IndexedDbDatabaseModel()
.WithName("data")
.WithVersion(2)
.WithModelId(1);
model.AddStore(nameof(Message))
.WithKey(nameof(Message.MessageId))
.AddUniqueIndex(nameof(Message.MessageId))
.AddIndex(nameof(Message.RootMessageId))
.AddIndex(nameof(Message.User))
.AddIndex(nameof(Message.MessageType))
.AddIndex(nameof(Message.Title))
.AddIndex(nameof(Message.Content))
.AddIndex(nameof(Message.CreatedAt))
.AddIndex(nameof(Message.Medias));
// IStorage.AddLog numbers entries itself (max key + 1), so the key is Id rather than generated. Version 2
// added this store; before it, every log write failed inside AddLog's try/catch.
model.AddStore(nameof(ClientLogs))
.WithKey(nameof(ClientLogs.Id))
.AddUniqueIndex(nameof(ClientLogs.Id))
.AddIndex(nameof(ClientLogs.TimeStamp));
options.UseDatabase(model);
});
}
public static string GetPassedTime(this DateTime dateTime, CoalescingStringLocalizer localizer)
{
var timeframe = DateTime.Now - dateTime.ToLocalTime();
return (int)timeframe.TotalHours switch
{
>= 24 => localizer["{0}d", (int)timeframe.TotalDays],
>= 1 => localizer["{0}h", (int)timeframe.TotalHours],
_ => localizer["{0}m", (int)timeframe.TotalMinutes]
};
}
public static string GetFileSize(this long size, CoalescingStringLocalizer localizer) => size switch
{
>= 1_048_576 => localizer["{0}MB", size / 1_048_576],
_ => localizer["{0}KB", size / 1_024]
};
public static string ParseContent(this string content, ContentType contentType)
{
switch (contentType)
{
case ContentType.PlainText:
return content;
case ContentType.HTML:
return ((MarkupString)content).Value;
case ContentType.Markdown:
return Markdown.ToHtml(content);
default:
return default;
}
}
public static string GetMessageTypeIcon(this MessageType messageType)
{
switch (messageType)
{
case MessageType.Public:
return "ion-md-globe";
case MessageType.Unlisted:
return "ion-md-unlock";
case MessageType.FollowersOnly:
return "ion-md-lock";
case MessageType.Direct:
return "ion-md-paper-plane";
default:
return default;
}
}
public static string GetTimelineTypeIcon(this TimelineType timelineType)
{
switch (timelineType)
{
case TimelineType.Home:
return "ion-md-home";
case TimelineType.Local:
return "ion-md-people";
case TimelineType.Federation:
return "ion-md-globe";
default:
return default;
}
}
public static string GetContentTypeIcon(this ContentType contentType)
{
switch (contentType)
{
case ContentType.PlainText:
return "ion-md-quote";
case ContentType.HTML:
return "ion-logo-html5";
case ContentType.Markdown:
return "ion-logo-markdown";
default:
return default;
}
}
public static string GetMediaTypeIcon(this MediaType mediaType)
{
switch (mediaType)
{
case MediaType.Images:
return "ion-md-images";
case MediaType.Video:
return "ion-md-videocam";
case MediaType.Documents:
return "ion-md-document";
case MediaType.Audio:
return "ion-md-volume-high";
default:
return default;
}
}
}