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

+10 -5
View File
@@ -65,33 +65,38 @@
</section>
@code {
[CascadingParameter] CascadingState CascadingState { get; set; }
[Parameter] public EventCallback<MessageForm> OnMessageSubmit { get; set; }
[Parameter] public EventCallback<TimelineType> OnTimelineChanged { get; set; }
[Parameter] public EventCallback<TimeSortingType> OnTimeSortingChanged { get; set; }
[Inject] ILocalStorageService LocalStorage { get; set; }
bool isPosting { get; set; } = false;
bool isPosting;
ActionBarFilter Filters { get; set; } = new();
protected override async Task OnInitializedAsync()
{
var filters = await LocalStorage.GetItemAsync<ActionBarFilter>(nameof(ActionBarFilter));
if (filters == default)
await LocalStorage.SetItemAsync(nameof(ActionBarFilter), Filters);
else
IsLoading = false;
if (filters is not null)
{
Filters = filters;
return;
}
await LocalStorage.SetItemAsync(nameof(ActionBarFilter), Filters);
}
void OpenCloseMessageForm()
{
isPosting = !isPosting;
}
async Task OnTimelineChange(TimelineType timelineType)
{
Filters.TimelineType = timelineType;
await LocalStorage.SetItemAsync(nameof(ActionBarFilter), Filters);
await OnTimelineChanged.InvokeAsync(Filters.TimelineType);
}
async Task OnTimeSortChange(TimeSortingType timeSorting)
{
Filters.TimeSortingType = timeSorting;
+16 -26
View File
@@ -3,7 +3,7 @@
<div class="flex gap-3 w-full rounded-xl neo-raised @(Highlighted ? "neo-sm" : "neo-2xs") @CssContainer">
<div class="flex flex-col py-3 pl-3 md:py-4 md:pl-4 flex-none rounded-l-xl bg-cover bg-no-repeat bg-center"
style="background-image:linear-gradient(to left, var(--color-base-100), transparent), url('@(Message.User?.BackgroundUrl)');">
style="background-image:linear-gradient(to left, var(--color-base-100), transparent), url('@(Message.User.BackgroundUrl)');">
<a class="block h-12 w-12 md:h-16 md:w-16" href="@Message.User.ProfileUrl" title="@Message.User.UserName">
<img alt="@Message.User.UserName" class="h-12 w-12 md:h-16 md:w-16 object-cover rounded-full neo-raised neo-2xs" src="@(Message.User.PictureUrl ?? "/imgs/icon-192.png")" />
@@ -32,8 +32,8 @@
</a>
</span>
<span class="flex-none inline-flex gap-1 items-center">
<span title="@Message.CreatedAt.ToLocalTime().ToString("📅dd/MM/yy 🕒HH:mm")">
@Message.CreatedAt.GetPassedTime(Localizer._pLocalizer)
<span title="@Message.CreatedAt.ToLocalTime().ToString(SUtility.dateTimeFormatExt)">
@Message.CreatedAt.GetPassedTime(Localizer)
</span>
<i aria-hidden="true" class="@Message.MessageType.GetMessageTypeIcon() text-base"
title="@Localizer[Message.MessageType.ToString()]">
@@ -104,13 +104,13 @@
<div class="flex gap-3">
@if (OnMessageReply.HasDelegate)
{
<DButton Size="DSize.Sm" Active="isAnswering" OnClick="Reply" title="@Localizer[isAnswering ? "Close" : "Reply"]">
<DButton Size="DSize.Sm" Active="isAnswering" Disabled="IsDefaultDisabled" OnClick="Reply" title="@Localizer[isAnswering ? "Close" : "Reply"]">
<i aria-hidden="true" class="@SUtility.IfTrueThen(isAnswering, "ion-md-close-circle", "ion-md-text") text-lg text-success"></i>
</DButton>
}
@if (OnMessageBoost.HasDelegate)
{
<DButton Size="DSize.Sm" Active="Message.IsBoostedByCurrentUser" OnClick="() => OnMessageBoost.InvokeAsync(Message)"
<DButton Size="DSize.Sm" Active="Message.IsBoostedByCurrentUser" Disabled="IsDefaultDisabled" OnClick="() => OnMessageBoost.InvokeAsync(Message)"
title="@Localizer["Boost"]">
<i aria-hidden="true" class="ion-md-repeat @SUtility.IfTrueThen(Message.BoostsCounter != 0, null, "text-lg") text-info"></i>
@if (Message.BoostsCounter != 0)
@@ -121,7 +121,7 @@
}
@if (OnMessageFavourite.HasDelegate)
{
<DButton Size="DSize.Sm" Active="Message.IsFavourite" OnClick="() => OnMessageFavourite.InvokeAsync(Message)"
<DButton Size="DSize.Sm" Active="Message.IsFavourite" Disabled="IsDefaultDisabled" OnClick="() => OnMessageFavourite.InvokeAsync(Message)"
title="@Localizer["Favourite"]">
<i aria-hidden="true" class="@SUtility.IfTrueThen(Message.IsFavourite, "ion-md-heart-dislike", "ion-md-heart") text-lg text-pink-300"></i>
</DButton>
@@ -138,28 +138,29 @@
<ChildContent>
@if (OnUserDirectMessage.HasDelegate)
{
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" OnClick="() => OnUserDirectMessage.InvokeAsync(Message)">
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled" OnClick="() => OnUserDirectMessage.InvokeAsync(Message)">
<i aria-hidden="true" class="ion-md-paper-plane text-base text-success"></i>
<span>@Localizer["Direct message"]</span>
</DButton>
}
@if (OnUserSilence.HasDelegate)
{
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" OnClick="() => OnUserSilence.InvokeAsync(Message.User)">
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled" OnClick="() => OnUserSilence.InvokeAsync(Message.User)">
<i aria-hidden="true" class="ion-md-eye-off text-base drop-shadow-sm text-warning"></i>
<span>@Localizer["Mute"]</span>
</DButton>
}
@if (OnUserBlock.HasDelegate)
{
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" OnClick="() => OnUserBlock.InvokeAsync(Message.User)">
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled" OnClick="() => OnUserBlock.InvokeAsync(Message.User)">
<i aria-hidden="true" class="ion-md-remove-circle text-base text-error"></i>
<span>@Localizer["Block"]</span>
</DButton>
}
@if (@*Message.User.UserName == CurrentUserName &&*@ OnMessageDelete.HasDelegate)
@* Once signed in for real: only for the author's own messages (Message.User.UserId == CascadingState.User.Id). *@
@if (OnMessageDelete.HasDelegate)
{
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" OnClick="DeleteMessage" title="@Localizer["Delete"]">
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled" OnClick="DeleteMessage" title="@Localizer["Delete"]">
<i aria-hidden="true" class="ion-md-trash text-lg text-error"></i>
<span>@Localizer["Delete"]</span>
</DButton>
@@ -184,8 +185,6 @@
</div>
@code {
[CascadingParameter] Task<AuthenticationState> AuthState { get; set; }
[CascadingParameter] CascadingState CascadingState { get; set; }
[Parameter] public Message Message { get; set; } = new();
[Parameter] public EventCallback<MessageForm> OnMessageReply { get; set; }
[Parameter] public EventCallback<Message> OnMessageBoost { get; set; }
@@ -200,15 +199,9 @@
[Parameter] public bool Highlighted { get; set; }
[Parameter] public bool IncludeExpand { get; set; } = true;
bool isAnswering { get; set; } = false;
bool isAnswering;
string CurrentUserName
{
get
{
return AuthState.Result.User.Identity?.Name;
}
}
protected override void OnInitialized() => IsLoading = false;
async Task DeleteMessage()
{
@@ -222,11 +215,8 @@
await OnMessageReply.InvokeAsync(messageForm);
}
async Task Reply()
void Reply()
{
await Task.Run(() =>
{
});
isAnswering = !isAnswering;
}
}
}
@@ -1,4 +1,4 @@
@inherits DComponentBase
@inherits DComponentBase
@* daisyUI Accordion: https://daisyui.com/components/accordion/ . Instead of daisyUI's radio group, the open item is an
index in C# (@bind-Active, -1 = none). Each DAccordionItem registers itself through the cascading value and renders a
@@ -19,7 +19,7 @@
/// <summary>Join the items into one block (join join-vertical, join-item).</summary>
[Parameter] public bool Joined { get; set; }
readonly List<DAccordionItem> items = new();
readonly List<DAccordionItem> items = [];
string CssClass => Cx(Joined ? "join join-vertical rounded-box neo-raised" : "flex flex-col gap-2", Class);
@@ -18,6 +18,7 @@
@code {
[Parameter] public string Src { get; set; }
// "" on purpose (the documented exception to "no string defaults"): an empty alt marks a decorative image.
[Parameter] public string Alt { get; set; } = "";
/// <summary>Shown in the frame when there is no Src, e.g. initials with Placeholder.</summary>
[Parameter] public RenderFragment ChildContent { get; set; }
+3 -3
View File
@@ -1,5 +1,4 @@
@inherits DComponentBase
@inject NavigationManager NavigationManager
@inherits DComponentBase
@* daisyUI Carousel: https://daisyui.com/components/carousel/ . A scroll-snap strip of DCarouselItem children; the
user scrolls or swipes it. Give each item w-full for one slide at a time. ShowNavigation (previous/next on every
@@ -25,6 +24,7 @@
</CascadingValue>
@code {
[Inject] NavigationManager NavigationManager { get; set; }
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public DCarouselSnap Snap { get; set; }
[Parameter] public DDirection Direction { get; set; }
@@ -36,7 +36,7 @@
[Parameter] public string NextText { get; set; } = "Next slide";
[Parameter] public string SlideText { get; set; } = "Slide";
readonly List<DCarouselItem> items = new();
readonly List<DCarouselItem> items = [];
readonly string uid = "d" + Guid.NewGuid().ToString("N")[..8];
RenderFragment Strip => @<div @attributes="AdditionalAttributes" class="@CssClass">@ChildContent</div>;
@@ -16,6 +16,7 @@
@code {
[Parameter] public IEnumerable<string> Images { get; set; }
// "" on purpose (the documented exception to "no string defaults"): an empty alt marks a decorative image.
[Parameter] public string Alt { get; set; } = "";
[Parameter] public RenderFragment ChildContent { get; set; }
}
+2 -2
View File
@@ -1,4 +1,4 @@
@inherits DComponentBase
@inherits DComponentBase
@* daisyUI Tab: https://daisyui.com/components/tab/ . Each DTab child registers itself through the cascading value;
DTabs renders the tab buttons and the active tab's content. The active tab is an index (@bind-Active). *@
@@ -35,7 +35,7 @@
[Parameter] public bool Bottom { get; set; }
[Parameter] public string ContentClass { get; set; } = "pt-4";
readonly List<DTab> tabs = new();
readonly List<DTab> tabs = [];
string CssClass => Cx("tabs", VariantClass, SizeClass, Bottom ? "tabs-bottom" : null, Class);
+58
View File
@@ -0,0 +1,58 @@
@implements IDisposable
@* In-page errors (b2b.next's WidmannErrorViewer): the validation messages of the cascading EditContext, then
AdditionalError (one message) and AdditionalErrors (a list; never join a list into one string), one <li> each.
Renders nothing when there is nothing to show. Messages are text, not markup: they can contain file names. *@
@if (HasContent)
{
<DAlert Color="@(Severity is ErrorViewerSeverity.Warning ? DAlertColor.Warning : DAlertColor.Error)" Variant="DAlertVariant.Soft"
class="@Cx("text-sm", ContainerClass)">
<ul class="list-inside list-disc">
@foreach (var message in Messages)
{
<li>@message</li>
}
</ul>
</DAlert>
}
@code {
[CascadingParameter] EditContext EditContext { get; set; }
[Parameter] public string ContainerClass { get; set; }
[Parameter] public ErrorViewerSeverity Severity { get; set; }
[Parameter] public string AdditionalError { get; set; }
[Parameter] public IEnumerable<string> AdditionalErrors { get; set; } = [];
EditContext subscribedEditContext;
IEnumerable<string> Messages =>
(EditContext?.GetValidationMessages() ?? [])
.Append(AdditionalError)
.Concat(AdditionalErrors)
.Where(message => !string.IsNullOrEmpty(message));
bool HasContent => Messages.Any();
static string Cx(params string[] classes) => DCx.Join(classes);
protected override void OnParametersSet()
{
if (EditContext == subscribedEditContext)
return;
Unsubscribe();
subscribedEditContext = EditContext;
if (subscribedEditContext is not null)
subscribedEditContext.OnValidationStateChanged += OnValidationStateChanged;
}
void OnValidationStateChanged(object sender, ValidationStateChangedEventArgs e) => _ = InvokeAsync(StateHasChanged);
void Unsubscribe()
{
if (subscribedEditContext is not null)
subscribedEditContext.OnValidationStateChanged -= OnValidationStateChanged;
}
public void Dispose() => Unsubscribe();
}
+7
View File
@@ -0,0 +1,7 @@
namespace decePubClient.Components;
public enum ErrorViewerSeverity
{
Error,
Warning
}
+101 -135
View File
@@ -4,15 +4,15 @@
<DataAnnotationsValidator />
<div class="flex flex-col mb-3">
<DInput TValue="string" class="w-full rounded-t-[1.4rem] rounded-b-lg" maxlength="64"
<DInput TValue="string" class="w-full rounded-t-[1.4rem] rounded-b-lg" maxlength="64" autocomplete="off"
placeholder="@Localizer["Title (optional)"]" Value="@MessageForm.Title"
ValueChanged="(v) => OnTitleChanged(v)"
ValueExpression="() => MessageForm.Title" />
<div class="relative mt-1">
<DTextarea TValue="string" @bind-Value="MessageForm.Content" Immediate="true"
class="w-full rounded-b-[1.4rem] rounded-t-lg" maxlength="5000"
class="w-full rounded-b-[1.4rem] rounded-t-lg" maxlength="@MaxContentLength" autocomplete="off"
placeholder="@Localizer["oh shit... here we go again"]" rows="3" />
<span class="absolute text-xs opacity-50 right-2 bottom-1">@(MessageForm.Content?.Length ?? 0)/5000</span>
<span class="absolute text-xs opacity-50 right-2 bottom-1">@ContentLength/@MaxContentLength</span>
</div>
@if (showPreviewButton && isPreviewOpen && MessageForm.Content is { Length: > 0 })
{
@@ -30,10 +30,6 @@
</div>
</div>
}
<div class="text-error text-sm">
<ValidationMessage For="() => MessageForm.Content" />
@contentError
</div>
</div>
<div class="flex flex-col gap-3 mb-3 @SUtility.IfTrueThen(MessageForm.Media.Count == 0, "hidden")">
@@ -51,14 +47,14 @@
<i class="ion-md-image"></i> <b>@media.FileName</b>
</p>
<p class="text-xs break-all">
<i class="ion-md-code"></i> @media.ContentType <i class="ion-md-fitness"></i> @media.Size.GetFileSize(Localizer._pLocalizer)
<i class="ion-md-code"></i> @media.ContentType <i class="ion-md-fitness"></i> @media.Size.GetFileSize(Localizer)
</p>
</div>
<DButton Size="DSize.Sm" class="self-start" OnClick="() => RemoveFile(media)">
<i class="ion-md-trash text-base text-red-400"></i>
</DButton>
</div>
<DTextarea TValue="string" @bind-Value="media.AltText" Size="DSize.Sm" class="w-full rounded-lg!"
<DTextarea TValue="string" @bind-Value="media.AltText" Size="DSize.Sm" class="w-full rounded-lg!" autocomplete="off"
placeholder="@Localizer["Alternative text"]" rows="1" />
</div>
</div>
@@ -74,7 +70,7 @@
<b>@media.FileName</b>
</p>
<p class="text-xs break-all">
<i class="ion-md-code"></i> @media.ContentType <i class="ion-md-fitness"></i> @media.Size.GetFileSize(Localizer._pLocalizer)
<i class="ion-md-code"></i> @media.ContentType <i class="ion-md-fitness"></i> @media.Size.GetFileSize(Localizer)
</p>
</div>
<DButton Size="DSize.Sm" OnClick="() => RemoveFile(media)">
@@ -92,7 +88,7 @@
<b>@media.FileName</b>
</p>
<p class="text-xs break-all">
<i class="ion-md-code"></i> @media.ContentType <i class="ion-md-fitness"></i> @media.Size.GetFileSize(Localizer._pLocalizer)
<i class="ion-md-code"></i> @media.ContentType <i class="ion-md-fitness"></i> @media.Size.GetFileSize(Localizer)
</p>
<audio controls="controls" class="w-full max-h-8">
<source src="@media.Base64Preview" type="@media.ContentType">
@@ -108,19 +104,14 @@
</div>
@if (fileInputErrorMessage is { Length: > 0 })
{
<div class="text-error text-sm p-1 md:p-2 mb-3 rounded-xl neo-inset neo-2xs">
@((MarkupString)fileInputErrorMessage)
</div>
}
<ErrorViewer ContainerClass="mb-3" AdditionalError="@contentError" AdditionalErrors="fileErrors" />
<div class="flex flex-wrap items-start justify-between gap-3">
<div class="flex flex-wrap items-start gap-3">
<DDropdown @bind-IsOpen="MessageForm.IsScopeOptionsOpen"
TriggerClass="@(MessageForm.IsScopeOptionsOpen ? "btn btn-sm btn-active" : "btn btn-sm")"
ContentClass="mt-2 flex gap-2 p-2 rounded-box"
title="@string.Format(Localizer["Message scope type: {0}"], Localizer[MessageForm.MessageType.ToString()])">
title="@Localizer["Message scope type: {0}", Localizer[MessageForm.MessageType.ToString()]]">
<Trigger>
<i class="@MessageForm.MessageType.GetMessageTypeIcon() text-base"></i>
</Trigger>
@@ -180,9 +171,6 @@
}
</ChildContent>
</DSelect>
<div class="text-error text-sm">
<ValidationMessage For="() => MessageForm.ContentType" />
</div>
</div>
@if (showPreviewButton)
@@ -194,7 +182,7 @@
</div>
<DButton Size="DSize.Sm" Type="submit">
<DButton Size="DSize.Sm" Type="submit" Disabled="IsDefaultDisabled">
<span>@Localizer["Post"]</span>
<i class="ion-md-send"></i>
</DButton>
@@ -204,16 +192,46 @@
</EditForm>
@code {
[CascadingParameter] CascadingState CascadingState { get; set; }
const int MaxContentLength = 5_000;
[Inject] ILoggingService Logger { get; set; }
[Parameter] public Message AnsweringMessage { get; set; }
[Parameter] public EventCallback<MessageForm> OnMessageSubmit { get; set; }
MessageForm MessageForm { get; set; } = new();
int totalCharacters { get; set; } = 0;
string fileInputErrorMessage { get; set; }
string contentError { get; set; }
string acceptedFilesTypes { get; set; } = ".jpg,.jpeg,.png,.gif";
bool showPreviewButton { get; set; } = false;
bool isPreviewOpen { get; set; } = false;
List<string> fileErrors = [];
string contentError;
string acceptedFilesTypes = ".jpg,.jpeg,.png,.gif";
bool showPreviewButton;
bool isPreviewOpen;
// Content is null until the user types: a form starts without text.
int ContentLength => MessageForm.Content?.Length ?? 0;
int MaximumFileCount => MessageForm.MediaType switch
{
MediaType.Images => 5,
MediaType.Video or MediaType.Audio => 1,
MediaType.Documents => 3,
_ => 0
};
long MaximumFileSize => MessageForm.MediaType switch
{
MediaType.Images or MediaType.Documents => 3_145_728,
MediaType.Audio => 5_242_880,
MediaType.Video => 20_971_520,
_ => 0
};
protected override void OnInitialized()
{
IsLoading = false;
if (AnsweringMessage is null)
return;
MessageForm.Title = AnsweringMessage.Title;
MessageForm.RootMessageId = AnsweringMessage.RootMessageId ?? AnsweringMessage.MessageId;
}
void UpdateMessageType(MessageType messageType)
{
@@ -221,114 +239,68 @@
MessageForm.IsScopeOptionsOpen = false;
}
protected override void OnInitialized()
{
if (AnsweringMessage != default)
{
MessageForm.Title = AnsweringMessage.Title;
MessageForm.RootMessageId = AnsweringMessage.RootMessageId ?? AnsweringMessage.MessageId;
}
}
bool ShouldDisableUpload() => MessageForm.Media.Count >= MaximumFileCount;
bool ShouldDisableUpload()
{
switch (MessageForm.MediaType)
{
case MediaType.Images:
return MessageForm.Media.Count == 5;
case MediaType.Video:
case MediaType.Audio:
return MessageForm.Media.Count == 1;
case MediaType.Documents:
return MessageForm.Media.Count == 3;
default:
return true;
}
}
bool ShouldHaveMultipleUpload()
{
return MessageForm.MediaType is MediaType.Images or MediaType.Documents;
}
bool ShouldHaveMultipleUpload() => MessageForm.MediaType is MediaType.Images or MediaType.Documents;
async Task OnFileChange(InputFileChangeEventArgs eventArgs)
{
fileErrors = [];
var maximumFileCount = MaximumFileCount;
if (eventArgs.FileCount + MessageForm.Media.Count > maximumFileCount)
{
fileErrors.Add(Localizer["The maximum number of files accepted is {0}, but {1} were supplied.", maximumFileCount,
MessageForm.Media.Count + eventArgs.FileCount]);
return;
}
var maximumFileSize = MaximumFileSize;
foreach (var file in eventArgs.GetMultipleFiles(maximumFileCount))
{
if (file.Name == default || file.ContentType == default || MessageForm.Media.Any(m => m.FileName == file.Name))
continue;
if (file.Size > maximumFileSize)
{
fileErrors.Add(Localizer["Supplied file \"{0}\" with size {1} exceeds the maximum of {2}.", file.Name,
file.Size.GetFileSize(Localizer), maximumFileSize.GetFileSize(Localizer)]);
continue;
}
var uploadMedia = await ReadFile(file, maximumFileSize);
if (uploadMedia is null)
{
fileErrors.Add(Localizer["The file \"{0}\" could not be read.", file.Name]);
continue;
}
MessageForm.Media.Add(uploadMedia);
}
}
/// <summary>Reads a picked file into memory; null when the browser can't read it (logged).</summary>
async Task<UploadMedia> ReadFile(IBrowserFile file, long maximumFileSize, CancellationToken cancellationToken = default)
{
try
{
fileInputErrorMessage = string.Empty;
var maximumFileCount = MessageForm.MediaType switch
using var memoryStream = new MemoryStream();
await using var fileStream = file.OpenReadStream(maximumFileSize, cancellationToken);
await fileStream.CopyToAsync(memoryStream, cancellationToken);
var uploadMedia = new UploadMedia
{
MediaType.Images => 5,
MediaType.Audio => 1,
MediaType.Video => 1,
MediaType.Documents => 3,
_ => 0
FileName = file.Name,
ContentType = file.ContentType,
Size = file.Size,
Blob = memoryStream.ToArray()
};
if (eventArgs.FileCount > maximumFileCount)
{
fileInputErrorMessage = string.Format(Localizer["The maximum number of files accepted is {0}, but {1} were supplied."], maximumFileCount, eventArgs.FileCount);
return;
}
if (eventArgs.FileCount + MessageForm.Media.Count > maximumFileCount)
{
fileInputErrorMessage = string.Format(Localizer["The maximum number of files accepted is {0}, but {1} were supplied."], maximumFileCount, $"{MessageForm.Media.Count}+{eventArgs.FileCount}");
return;
}
var maxAllowedSize = MessageForm.MediaType switch
{
MediaType.Images => 3_145_728,
MediaType.Audio => 5_242_880,
MediaType.Video => 20_971_520,
MediaType.Documents => 3_145_728,
_ => 0
};
var uploadMedia = default(UploadMedia);
using (var memStream = new MemoryStream())
foreach (var file in eventArgs.GetMultipleFiles(maximumFileCount))
{
if (file.Name == default || file.ContentType == default) continue;
if (MessageForm.Media.Any(m => m.FileName == file.Name)) continue;
if (file.Size > maxAllowedSize)
{
fileInputErrorMessage += string.Format(Localizer["Supplied file \"{0}\" with size {1:N0}MBs exceeds the maximum of {2:N0}MBs."], file.Name, file.Size / 1_048_576, maxAllowedSize / 1_048_576) + "<br/>";
continue;
}
uploadMedia = new()
{
FileName = file.Name,
ContentType = file.ContentType,
Size = file.Size
};
try
{
using (var imgStream = file.OpenReadStream(maxAllowedSize))
{
await imgStream.CopyToAsync(memStream);
memStream.Position = 0;
uploadMedia.Blob = memStream.ToArray();
await memStream.FlushAsync();
}
}
catch (IOException e)
{
fileInputErrorMessage = e.Message;
continue;
}
catch (Exception e)
{
fileInputErrorMessage = e.Message;
continue;
}
if (MessageForm.MediaType is MediaType.Images or MediaType.Audio)
uploadMedia.Base64Preview = $"data:{uploadMedia.ContentType};base64,{Convert.ToBase64String(uploadMedia.Blob)}";
MessageForm.Media.Add(uploadMedia);
}
if (MessageForm.MediaType is MediaType.Images or MediaType.Audio)
uploadMedia.Base64Preview = $"data:{uploadMedia.ContentType};base64,{Convert.ToBase64String(uploadMedia.Blob)}";
return uploadMedia;
}
catch (Exception e)
catch (Exception ex)
{
fileInputErrorMessage = e.Message;
await Logger.ProcessError(ex, $"{nameof(MessageUpsertForm)}.{nameof(ReadFile)}:{file.Name}", cancellationToken);
return default;
}
}
@@ -342,12 +314,6 @@
MessageForm.Title = value;
}
void ContentLengthChanged()
{
totalCharacters = MessageForm.Content?.Length ?? 0;
StateHasChanged();
}
void OnContentTypeChanged(ContentType contentType)
{
MessageForm.ContentType = contentType;
@@ -375,7 +341,7 @@
async Task OnValidSubmit()
{
contentError = default;
if ((MessageForm.Content is { Length: 0 } && MessageForm.Media.Count == 0))
if (string.IsNullOrWhiteSpace(MessageForm.Content) && MessageForm.Media.Count == 0)
{
contentError = Localizer["Missing content, either message or media"];
return;
@@ -383,4 +349,4 @@
await OnMessageSubmit.InvokeAsync(MessageForm);
}
}
}
+28 -28
View File
@@ -11,31 +11,31 @@
<div class="flex flex-wrap items-center gap-2">
@foreach (var color in Enum.GetValues<DColor>())
{
<DInput @bind-Value="text" Color="color" placeholder="@color.ToString()" class="w-36" />
<DInput autocomplete="off" @bind-Value="text" Color="color" placeholder="@color.ToString()" class="w-36" />
}
</div>
<div class="flex flex-wrap items-center gap-2">
<DInput @bind-Value="text" Size="DSize.Xs" placeholder="Xs" class="w-28" />
<DInput @bind-Value="text" Size="DSize.Sm" placeholder="Sm" class="w-28" />
<DInput @bind-Value="text" placeholder="Md" class="w-28" />
<DInput @bind-Value="text" Size="DSize.Lg" placeholder="Lg" class="w-28" />
<DInput @bind-Value="text" Size="DSize.Xl" placeholder="Xl" class="w-28" />
<DInput autocomplete="off" @bind-Value="text" Size="DSize.Xs" placeholder="Xs" class="w-28" />
<DInput autocomplete="off" @bind-Value="text" Size="DSize.Sm" placeholder="Sm" class="w-28" />
<DInput autocomplete="off" @bind-Value="text" placeholder="Md" class="w-28" />
<DInput autocomplete="off" @bind-Value="text" Size="DSize.Lg" placeholder="Lg" class="w-28" />
<DInput autocomplete="off" @bind-Value="text" Size="DSize.Xl" placeholder="Xl" class="w-28" />
</div>
<div class="flex flex-wrap items-center gap-2">
<DInput @bind-Value="text" Ghost="true" placeholder="Ghost" />
<DInput @bind-Value="text" disabled placeholder="Disabled" />
<DInput @bind-Value="search" Immediate="true" placeholder="Search">
<DInput autocomplete="off" @bind-Value="text" Ghost="true" placeholder="Ghost" />
<DInput autocomplete="off" @bind-Value="text" disabled placeholder="Disabled" />
<DInput autocomplete="off" @bind-Value="search" Immediate="true" placeholder="Search">
<Prefix><i class="ion-md-search opacity-50"></i></Prefix>
<Suffix><kbd class="kbd kbd-sm">⌘</kbd><kbd class="kbd kbd-sm">K</kbd></Suffix>
</DInput>
<DInput @bind-Value="site" Color="DColor.Primary">
<DInput autocomplete="off" @bind-Value="site" Color="DColor.Primary">
<Prefix><DLabel>https://</DLabel></Prefix>
<Suffix><DLabel>.com</DLabel></Suffix>
</DInput>
</div>
<p class="text-sm opacity-60">Immediate search: "@search", text: "@text"</p>
<div class="flex flex-col">
<DInput @bind-Value="model.Name" Validator="true" placeholder="Name (required)" class="w-full max-w-xs" />
<DInput autocomplete="off" @bind-Value="model.Name" Validator="true" placeholder="Name (required)" class="w-full max-w-xs" />
<DValidatorHint>Name is required</DValidatorHint>
</div>
</section>
@@ -82,22 +82,22 @@
<div class="grid grid-cols-3 gap-2">
@foreach (var color in Enum.GetValues<DColor>())
{
<DTextarea @bind-Value="bio" Color="color" placeholder="@color.ToString()" class="min-h-0 h-12" />
<DTextarea autocomplete="off" @bind-Value="bio" Color="color" placeholder="@color.ToString()" class="min-h-0 h-12" />
}
</div>
<div class="flex flex-wrap items-start gap-2">
<DTextarea @bind-Value="bio" Size="DSize.Xs" placeholder="Xs" class="w-24" />
<DTextarea @bind-Value="bio" Size="DSize.Sm" placeholder="Sm" class="w-24" />
<DTextarea @bind-Value="bio" placeholder="Md" class="w-24" />
<DTextarea @bind-Value="bio" Size="DSize.Lg" placeholder="Lg" class="w-24" />
<DTextarea @bind-Value="bio" Size="DSize.Xl" placeholder="Xl" class="w-24" />
<DTextarea autocomplete="off" @bind-Value="bio" Size="DSize.Xs" placeholder="Xs" class="w-24" />
<DTextarea autocomplete="off" @bind-Value="bio" Size="DSize.Sm" placeholder="Sm" class="w-24" />
<DTextarea autocomplete="off" @bind-Value="bio" placeholder="Md" class="w-24" />
<DTextarea autocomplete="off" @bind-Value="bio" Size="DSize.Lg" placeholder="Lg" class="w-24" />
<DTextarea autocomplete="off" @bind-Value="bio" Size="DSize.Xl" placeholder="Xl" class="w-24" />
</div>
<div class="flex flex-wrap items-start gap-2">
<DTextarea @bind-Value="bio" Ghost="true" placeholder="Ghost" />
<DTextarea @bind-Value="bio" disabled placeholder="Disabled" />
<DTextarea autocomplete="off" @bind-Value="bio" Ghost="true" placeholder="Ghost" />
<DTextarea autocomplete="off" @bind-Value="bio" disabled placeholder="Disabled" />
</div>
<div class="flex flex-col">
<DTextarea @bind-Value="model.Bio" Immediate="true" Validator="true" placeholder="Bio, 10 to 140 characters" class="w-full" />
<DTextarea autocomplete="off" @bind-Value="model.Bio" Immediate="true" Validator="true" placeholder="Bio, 10 to 140 characters" class="w-full" />
<DValidatorHint>Between 10 and 140 characters</DValidatorHint>
<span class="text-sm opacity-60">@(model.Bio?.Length ?? 0)/140</span>
</div>
@@ -286,21 +286,21 @@
<Legend>Page details</Legend>
<ChildContent>
<DLabel>Title</DLabel>
<DInput @bind-Value="text" placeholder="My awesome page" />
<DInput autocomplete="off" @bind-Value="text" placeholder="My awesome page" />
<DLabel>Slug</DLabel>
<DInput @bind-Value="site" placeholder="my-awesome-page" />
<DInput autocomplete="off" @bind-Value="site" placeholder="my-awesome-page" />
</ChildContent>
<Description>You can edit these later</Description>
</DFieldset>
<DFieldset disabled>
<Legend>Disabled fieldset</Legend>
<ChildContent><DInput @bind-Value="text" placeholder="Can't type here" /></ChildContent>
<ChildContent><DInput autocomplete="off" @bind-Value="text" placeholder="Can't type here" /></ChildContent>
</DFieldset>
<DLabel Floating="true" Text="Your email">
<DInput @bind-Value="email" placeholder="mail@site.com" />
<DInput autocomplete="off" @bind-Value="email" placeholder="mail@site.com" />
</DLabel>
<DLabel Floating="true" Text="Notes">
<DTextarea @bind-Value="bio" placeholder="Notes" />
<DTextarea autocomplete="off" @bind-Value="bio" placeholder="Notes" />
</DLabel>
</section>
@@ -308,11 +308,11 @@
<h3 class="text-lg font-bold">DValidator / DValidatorHint</h3>
<p class="text-sm opacity-60">Native rules, checked by the browser once you've edited the field.</p>
<div class="flex flex-col">
<DInput @bind-Value="email" Type="email" Validator="true" required="true" placeholder="mail@site.com" />
<DInput autocomplete="off" @bind-Value="email" Type="email" Validator="true" required="true" placeholder="mail@site.com" />
<DValidatorHint>Enter a valid email address</DValidatorHint>
</div>
<div class="flex flex-col">
<DInput @bind-Value="username" Validator="true" required="true" pattern="[A-Za-z][A-Za-z0-9\-]*" minlength="3"
<DInput autocomplete="off" @bind-Value="username" Validator="true" required="true" pattern="[A-Za-z][A-Za-z0-9\-]*" minlength="3"
maxlength="30" placeholder="Username" title="Only letters, numbers or dash" />
<DValidatorHint Compact="true">Must be 3 to 30 letters, numbers or dashes (Compact: no space while valid)</DValidatorHint>
</div>
@@ -375,7 +375,7 @@
string framework;
DColor? filterColor;
string otp;
List<string> files = new();
List<string> files = [];
void Submitted(bool valid) => submitResult = valid ? "Valid" : "Invalid: see the messages above";
+1 -1
View File
@@ -216,7 +216,7 @@
record Toast(int Id, DAlertColor Color);
readonly List<Toast> toasts = new();
readonly List<Toast> toasts = [];
DToastHorizontal toastHorizontal;
DToastVertical toastVertical;
int toastCount;
+1 -1
View File
@@ -165,7 +165,7 @@
<DButton class="join-item">from lg</DButton>
</DJoin>
<DJoin>
<input class="input join-item" placeholder="Email" />
<input autocomplete="off" class="input join-item" placeholder="Email" />
<select class="select join-item w-28">
<option>Filter</option>
<option>Sci-fi</option>
+41
View File
@@ -0,0 +1,41 @@
@implements IDisposable
@* Shows ToastService's messages at the bottom end of the screen. Placed once, in MainLayout. *@
@if (Toast.Messages.Count > 0)
{
<DToast class="z-[1000]">
@foreach (var message in Toast.Messages)
{
<DAlert @key="message.Id" Color="ColorOf(message.Severity)" class="max-w-sm">
<ChildContent>
<span class="break-words">@message.Text</span>
</ChildContent>
<Actions>
<DButton Size="DSize.Xs" Shape="DButtonShape.Circle" Variant="DButtonVariant.Ghost" aria-label="@Localizer["Close"]"
OnClick="() => Toast.Close(message.Id)">
<i class="ion-md-close"></i>
</DButton>
</Actions>
</DAlert>
}
</DToast>
}
@code {
[Inject] ToastService Toast { get; set; }
[Inject] CoalescingStringLocalizer Localizer { get; set; }
protected override void OnInitialized() => Toast.Changed += OnChanged;
void OnChanged() => _ = InvokeAsync(StateHasChanged);
static DAlertColor ColorOf(ToastSeverity severity) => severity switch
{
ToastSeverity.Success => DAlertColor.Success,
ToastSeverity.Warning => DAlertColor.Warning,
ToastSeverity.Error => DAlertColor.Error,
_ => DAlertColor.Info
};
public void Dispose() => Toast.Changed -= OnChanged;
}