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

+254 -4
View File
@@ -1,12 +1,29 @@
using decePubClient.Models;
using decePubClient.Models.Types;
using Markdig;
namespace decePubClient.Helpers;
/// <summary>
/// Mock data until the app is wired to PrivaPub: the signed-in user, the feed shown while IndexedDB holds no messages,
/// and the thread around an expanded message.
/// </summary>
public static class Faker
{
static IReadOnlyList<MessageUser> Users => new List<MessageUser>
public static User CurrentUser => new()
{
new(),
Id = "45f14fa8-c40f-4121-997c-ef2542196a50",
UserName = "@loosy@letsrulethe.world",
DisplayName = "loosy",
PictureUrl = "https://letsrulethe.world/media/ddd91d51-dc12-4b82-86a2-2a28cc959183/L51ZAL4QEL07",
BackgroundUrl = "https://letsrulethe.world/media/9a3cc6c4-1018-4f41-86c7-f3e63e362bf4/EXM8RUK10B0Z",
ProfileUrl = "https://letsrulethe.world/users/loosy"
};
static IReadOnlyList<MessageUser> Users =>
[
CurrentUser.ToMessageUser(),
new()
{
UserId = "7b5703dc-aee8-46b1-aed2-cd06021a1c0c",
@@ -25,7 +42,7 @@ public static class Faker
BackgroundUrl = "https://wallup.net/wp-content/uploads/2016/01/225560-nature-landscape-fall-path-forest-mist-morning-trees-leaves-sunlight.jpg",
ProfileUrl = "https://mastodon.uno/web/@valenappi@beta.birdsite.live"
}
};
];
public static MessageUser GetRandomUser()
{
@@ -44,4 +61,237 @@ public static class Faker
ProfileUrl = user.ProfileUrl
};
}
}
/// <summary>
/// The seed feed. Two entries share a MessageId on purpose: the second is the first one boosted by someone, which
/// is how the feed shows a boost (a copy of the message with BoostingUser set).
/// </summary>
public static List<Message> SeedMessages()
{
var messages = new List<Message>();
messages.Add(new()
{
RootMessageId = default,
MessageId = "992167EE-8947-4823-B1E2-B4E1019B6974",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test di messaggio normale senza titolo",
Medias = [],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "C5307644-4EA8-4B5F-A240-7CFE4DE34741",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = "sopra la panca la capra canta",
Content = Markdown.ToHtml("test di messaggio con titolo"),
Medias = [],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "E473D562-D210-4453-93DA-157D4B90B0D8",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd test di messaggio con overflow del testo",
Medias = [],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "adf89dc6-0484-430e-a7c9-fcb1179b0c28",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test video",
Medias =
[
new()
{
FileName = "8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
Url = "https://ihatebeinga.live/media/8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
AltText = "https://ihatebeinga.live/media/8252d175e714db88beb8ee0349dbac90405d3d5148e96e0cfd7de3b0876dbb1b.mp4",
ContentType = "video/mp4"
}
],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "96025b43-5235-44e9-a3fa-98df31edfbfb",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test immagine",
Medias =
[
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
}
],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "277ca76b-aaad-4aa6-95fb-25f59e2fddf9",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test audio",
Medias =
[
new()
{
FileName = "09bfb06d0096975f.mp3",
Url = "https://cdn.masto.host/mastodonuno/media_attachments/files/107/798/288/501/917/857/original/09bfb06d0096975f.mp3",
AltText = "09bfb06d0096975f.mp3",
ContentType = "audio/mp3"
}
],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
BoostingUser = GetRandomBoostingUser(),
RootMessageId = default,
MessageId = "de64e520-a7d3-4f31-b5a9-ba236f3b146c",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test immagini",
Medias =
[
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
}
],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0,100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
messages.Add(new()
{
RootMessageId = default,
MessageId = "de64e520-a7d3-4f31-b5a9-ba236f3b146c",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = default,
Content = "test immagini",
Medias =
[
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
},
new()
{
FileName = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
Url = "https://ihatebeinga.live/media/51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
AltText = "51a7cf620f1dd096ac5867d5b78f8c71d57a23972b31c64ec124a8c41e77a618.jpg",
ContentType = "image/jpg"
}
],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0,100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
});
return messages;
}
/// <summary>The messages before and after an expanded one.</summary>
public static (List<Message> Ancestors, List<Message> Descendants) Thread(Message message) =>
(
[
new()
{
RootMessageId = default,
MessageId = "51C698E3-7C28-4C90-9212-48D5C81DE089",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = message.Title,
Content = "<p>esempio di messaggio <b>precedente</b> a quello espanso</p>",
Medias = [],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
}
],
[
new()
{
RootMessageId = default,
MessageId = "0569A1DF-46FC-4485-9F11-F8CDFB794404",
User = GetRandomUser(),
MessageType = (MessageType)Random.Shared.Next(0, 4),
Title = message.Title,
Content = "<p>esempio di messaggio <b>successivo</b> a quello espanso</p>",
Medias = [],
CreatedAt = DateTime.UtcNow.AddMinutes(Random.Shared.Next(-5000, 0)),
IsFavourite = Random.Shared.Next() % 2 == 0,
BoostsCounter = Random.Shared.Next(0, 100),
IsBoostedByCurrentUser = Random.Shared.Next() % 2 == 0,
}
]
);
}
+91 -7
View File
@@ -1,17 +1,101 @@
using System.Net.Mail;
using System.Net;
using System.Net.Http.Json;
using System.Net.Mail;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
using decePubClient.Models;
using decePubClient.Services;
using PrivaPub.ClientModels;
namespace decePubClient.Helpers
{
public static class SUtility
{
public static T IfTrueThen<T>(bool conditionIsTrue, T ifTrue, T ifFalse = default)
public const string dateTimeFormat = "dd/MM/yyyy";
public const string timeFormat = "HH:mm";
public const string dateTimeFormatExt = "dd/MM/yyyy HH:mm";
/// <summary>Marks a response HttpService made up itself (a classified failure), not one the server sent.</summary>
public const string FailureHeader = "X-DecePub-Failure";
/// <summary>The JSON options for every HTTP payload: web defaults, ClientJsonContext first, reflection after.</summary>
public static JsonSerializerOptions DefaultSerializer { get; } = new(JsonSerializerDefaults.Web)
{
if (conditionIsTrue)
return ifTrue;
else
return ifFalse;
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
TypeInfoResolver = JsonTypeInfoResolver.Combine(ClientJsonContext.Default, new DefaultJsonTypeInfoResolver())
};
/// <summary>What a cancelled request turns into: HTTP 410, which AddResponseError ignores.</summary>
public static WebResult DefaultTaskCancelledResult =>
new WebResult().Invalidate("Request cancelled, not an error.", (int)HttpStatusCode.Gone, FailureCodes.Cancelled);
public static HttpResponseMessage DefaultTaskCancelled() =>
ClassifiedFailure(FailureCodes.Cancelled, DefaultTaskCancelledResult.ErrorMessage, HttpStatusCode.Gone);
public static HttpResponseMessage DefaultUnauthorized(string message) =>
ClassifiedFailure(FailureCodes.Unauthorized, message, HttpStatusCode.Unauthorized);
/// <summary>A response carrying an invalid WebResult, tagged with FailureHeader so ReadWebResult reads it as is.</summary>
public static HttpResponseMessage ClassifiedFailure(string failureCode, string message, HttpStatusCode statusCode)
{
var content = JsonContent.Create(new WebResult().Invalidate(message, (int)statusCode, failureCode), options: DefaultSerializer);
content.Headers.Add(FailureHeader, failureCode);
return new(statusCode) { Content = content };
}
/// <summary>The value a cancelled read returns: default for value types, an empty list for list interfaces.</summary>
public static T CancellationDefault<T>()
{
var type = typeof(T);
if (type.IsValueType)
return default;
if (type.IsInterface && type.IsGenericType &&
type.GetGenericTypeDefinition() is var definition &&
(definition == typeof(IEnumerable<>) || definition == typeof(ICollection<>) || definition == typeof(IList<>) ||
definition == typeof(IReadOnlyCollection<>) || definition == typeof(IReadOnlyList<>)))
return (T)Activator.CreateInstance(typeof(List<>).MakeGenericType(type.GetGenericArguments()[0]));
if (type.IsInterface || type.IsAbstract || type.GetConstructor(Type.EmptyTypes) is null)
return default;
return Activator.CreateInstance<T>();
}
#region Toasts
/// <summary>Shows a failed result: connectivity failures as warnings, the rest as errors; cancellations not at all.</summary>
public static void AddResponseError(this ToastService toast, WebResult result)
{
if (result.StatusCode is (int)HttpStatusCode.Gone)
return;
if (FailureCodes.IsConnectivity(result.ErrorCode))
{
toast.Add(ToastSeverity.Warning, result.ErrorMessage);
return;
}
toast.Add(ToastSeverity.Error, $"{result.StatusCode} - {result.ErrorMessage}");
}
public static void AddResponseError(this ToastService toast, string message) =>
toast.Add(ToastSeverity.Error, message);
public static void AddResponseSuccess(this ToastService toast, string message) =>
toast.Add(ToastSeverity.Success, message, TimeSpan.FromSeconds(5));
public static void AddWarning(this ToastService toast, string message) =>
toast.Add(ToastSeverity.Warning, message);
public static void AddException(this ToastService toast, Exception exception) =>
toast.Add(ToastSeverity.Error, exception.Message);
#endregion
public static T IfTrueThen<T>(bool conditionIsTrue, T ifTrue, T ifFalse = default) =>
conditionIsTrue ? ifTrue : ifFalse;
public static bool TimeBetween(this DateTime datetime, TimeSpan start, TimeSpan end)
{
// convert datetime to a TimeSpan
@@ -65,4 +149,4 @@ namespace decePubClient.Helpers
}
}
}
}
}