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
153 lines
5.1 KiB
C#
153 lines
5.1 KiB
C#
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 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)
|
|
{
|
|
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
|
|
var now = datetime.TimeOfDay;
|
|
// see if start comes before end
|
|
if (start < end)
|
|
return start <= now && now <= end;
|
|
// start is after end, so do the inverse comparison
|
|
return !(end < now && now < start);
|
|
}
|
|
|
|
public static string GetFileIcon(string fileName)
|
|
{
|
|
switch (Path.GetExtension(fileName))
|
|
{
|
|
case ".odp":
|
|
case ".pptx":
|
|
return "file-powerpoint";
|
|
|
|
case ".ods":
|
|
case ".xlsx":
|
|
return "file-excel";
|
|
|
|
case ".odt":
|
|
case ".docx":
|
|
return "file-word";
|
|
|
|
case ".pdf":
|
|
return "file-pdf";
|
|
|
|
case ".jpg":
|
|
case ".jpeg":
|
|
case ".png":
|
|
return "file-image";
|
|
|
|
default:
|
|
return "file";
|
|
}
|
|
}
|
|
|
|
public static bool IsValidEmail(string email)
|
|
{
|
|
try
|
|
{
|
|
var addr = new MailAddress(email);
|
|
return addr.Address == email;
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
}
|