Wire the client to PrivaPub: one sign-in, real feeds, a globe, nerd stats

One sign-in for both of PrivaPub's APIs: the root logs in on /clientapi,
picks a persona, and each persona gets its own Mastodon token in
exchange for the JWT (PersonaExchange). HttpService picks credentials
and JSON by route (JWT and camelCase for /clientapi, the persona token
and snake_case for /api, nothing for /oauth), retries a refused persona
token once, and records every request for the nerd stats.

The feed page is three columns: navigation with a persona switcher, the
feed with a tab per kind (home, local, federated, nearby, communities
and circles, direct, notifications, favourites, bookmarks, hashtags),
and a 3D globe that looks at the spherical mean of the posts in view
and draws a pulse and an arc to a hovered one. Posts sit at their own
place, their event's venue, the reader (located posts) or their
author's server as PrivaPub publishes it. Cards favourite, boost,
bookmark, reply, mute, block and delete; the composer posts with a
content warning, visibility, media and alt text, or as a located post.
Older pages load as the end nears; newer ones are polled while visible.
Nerd stats in tooltips: provenance, author and server, place, media,
counts, paging, the globe's camera and frame rate.

The mock (Faker, MessagesService, the Message models and store) and the
OIDC template leftovers are gone. Strings in English and Italian.

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-04 11:03:14 +02:00
1 parent f41ebf2160
commit 827ecb770e
56 files changed
+5367 -832

No files matched your search

+300
View File
@@ -0,0 +1,300 @@
@inherits LocalizableComponentBase
@* A new post or a reply, as the current persona. Through the Mastodon API it is plain text with a content warning, a
visibility and media (each uploaded first, with its alt text). A located post is text only, kept within its range of
this device's position and never federated; a group post goes to the group. Both of those go through /clientapi. *@
<EditForm Model="form" OnValidSubmit="Publish" class="flex flex-col gap-3">
<DataAnnotationsValidator />
@if (form.HasContentWarning)
{
<DInput TValue="string" class="w-full rounded-t-[1.4rem] rounded-b-lg" maxlength="500" autocomplete="off"
placeholder="@Localizer["Content warning"]" @bind-Value="form.SpoilerText">
<Prefix><i class="ion-md-warning text-warning"></i></Prefix>
</DInput>
}
<div class="relative">
<DTextarea TValue="string" @bind-Value="form.Content" Immediate="true"
class="@(form.HasContentWarning ? "w-full rounded-b-[1.4rem] rounded-t-lg" : "w-full rounded-[1.4rem]")" maxlength="@ComposeForm.MaxContentLength" autocomplete="off"
placeholder="@(InReplyTo is null ? Localizer["What's happening?"] : Localizer["Reply to {0}", "@" + InReplyTo.Account?.Acct])" rows="3" />
<span class="absolute text-xs opacity-50 right-3 bottom-2">@ContentLength/@ComposeForm.MaxContentLength</span>
</div>
@if (form.Media.Count > 0)
{
<div class="flex flex-col gap-2">
@foreach (var media in form.Media)
{
<div class="flex w-full items-center gap-3 rounded-xl p-2 md:p-3 neo-raised neo-2xs">
@if (media.Base64Preview is { Length: > 0 } preview && media.ContentType.StartsWith("image"))
{
<img alt="@media.AltText" class="object-cover rounded-lg max-h-20 max-w-24 flex-none" src="@preview" />
}
else
{
<i class="text-2xl @form.MediaType.GetMediaTypeIcon()"></i>
}
<div class="flex flex-col flex-1 min-w-0 gap-1">
<p class="text-xs break-all"><b>@media.FileName</b> · @media.ContentType · @media.Size.GetFileSize(Localizer)</p>
<DTextarea TValue="string" @bind-Value="media.AltText" Size="DSize.Sm" class="w-full rounded-lg!" autocomplete="off" maxlength="1500"
placeholder="@Localizer["Alternative text"]" rows="1" />
</div>
<DButton Size="DSize.Sm" class="self-start" OnClick="() => form.Media.Remove(media)" title="@Localizer["Delete"]">
<i class="ion-md-trash text-base text-error"></i>
</DButton>
</div>
}
</div>
}
@if (form.IsLocated)
{
<div class="flex flex-col gap-1 rounded-xl p-3 neo-inset neo-2xs text-xs">
<span class="inline-flex gap-2 items-center">
<i class="ion-md-locate text-primary"></i>
@if (form.Latitude is null)
{
<span>@Localizer["Asking this device for its position…"]</span>
}
else
{
<span>@Localizer["Shown only to people within {0} km of here, never sent to other servers.", form.RangeKm.ToString("0")]</span>
}
</span>
<DRange TValue="double" Size="DSize.Xs" Min="1" Max="50" Step="1" @bind-Value="form.RangeKm" />
</div>
}
<ErrorViewer AdditionalError="@error" AdditionalErrors="fileErrors" />
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="flex flex-wrap items-center gap-2">
@if (!form.IsLocated && GroupId is null)
{
<DDropdown @bind-IsOpen="form.IsScopeOptionsOpen" TriggerClass="@(form.IsScopeOptionsOpen ? "btn btn-sm btn-active" : "btn btn-sm")"
ContentClass="mt-2 flex gap-2 p-2 rounded-box" title="@Localizer["Message scope type: {0}", Localizer[form.MessageType.ToString()]]">
<Trigger>
<i class="@form.MessageType.GetMessageTypeIcon() text-base"></i>
</Trigger>
<ChildContent>
@foreach (var messageType in Enum.GetValues<MessageType>())
{
<DButton Size="DSize.Sm" Active="form.MessageType == messageType" OnClick="() => SetMessageType(messageType)" title="@Localizer[messageType.ToString()]">
<i class="@messageType.GetMessageTypeIcon() text-base"></i>
</DButton>
}
</ChildContent>
</DDropdown>
}
<DButton Size="DSize.Sm" Active="form.HasContentWarning" OnClick="() => form.HasContentWarning = !form.HasContentWarning" title="@Localizer["Content warning"]">
<i class="ion-md-warning text-base"></i>
</DButton>
@if (!form.IsLocated && GroupId is null)
{
@* A label styled as a button opens the hidden file input. *@
<label class="btn btn-sm @(form.Media.Count >= MaximumFileCount ? "btn-disabled" : null)" title="@Localizer["Attach"]">
<InputFile accept="@AcceptedFileTypes" class="hidden" multiple="@(form.MediaType is MediaType.Images)" OnChange="OnFileChange"
disabled="@(form.Media.Count >= MaximumFileCount)" />
<i class="ion-md-attach text-base"></i>
@if (form.Media.Count != 0)
{
<span>+@form.Media.Count</span>
}
</label>
<DSelect TValue="MediaType" Size="DSize.Sm" class="w-auto" Value="form.MediaType" ValueChanged="v => form.MediaType = v"
ValueExpression="() => form.MediaType" disabled="@(form.Media.Count > 0)">
<Prefix><i class="@form.MediaType.GetMediaTypeIcon()"></i></Prefix>
<ChildContent>
@foreach (var mediaType in new[] { MediaType.Images, MediaType.Video, MediaType.Audio })
{
<option value="@mediaType">@Localizer[mediaType.ToString()]</option>
}
</ChildContent>
</DSelect>
}
@if (InReplyTo is null && GroupId is null)
{
<DButton Size="DSize.Sm" Active="form.IsLocated" OnClick="ToggleLocated" title="@Localizer["Located post"]">
<i class="ion-md-locate text-base"></i>
</DButton>
}
</div>
<DButton Size="DSize.Sm" Type="submit" Color="DColor.Primary" Disabled="IsDefaultDisabled || isPublishing || (form.IsLocated && form.Latitude is null)">
@if (isPublishing)
{
<DLoading Size="DSize.Xs" LabelText="@Localizer["loading"]" />
}
<span>@Localizer[InReplyTo is null ? "Post" : "Reply"]</span>
<i class="ion-md-send"></i>
</DButton>
</div>
</EditForm>
@code {
[Inject] StatusService StatusService { get; set; }
[Inject] ILoggingService Logger { get; set; }
[Inject] IJSRuntime JS { get; set; }
/// <summary>The status this answers; the reply starts with its visibility (never wider) and content warning.</summary>
[Parameter] public Status InReplyTo { get; set; }
/// <summary>The community or circle the post is for.</summary>
[Parameter] public string GroupId { get; set; }
/// <summary>The published post, to show it; a located or group post comes back as null (it is not on the Mastodon API).</summary>
[Parameter] public EventCallback<FeedPost> OnPublished { get; set; }
ComposeForm form = new();
List<string> fileErrors = [];
string error;
bool isPublishing;
int ContentLength => form.Content?.Length ?? 0;
int MaximumFileCount => form.MediaType is MediaType.Images ? 4 : 1;
long MaximumFileSize => form.MediaType switch
{
MediaType.Images => 16_777_216,
MediaType.Audio => 41_943_040,
_ => 99_614_720
};
string AcceptedFileTypes => form.MediaType switch
{
MediaType.Images => ".jpg,.jpeg,.png,.gif,.webp,.avif",
MediaType.Video => ".mp4,.m4v,.webm,.mov",
MediaType.Audio => ".mp3,.ogg,.oga,.opus,.wav,.flac,.m4a",
_ => default
};
protected override void OnInitialized()
{
IsLoading = false;
form.GroupId = GroupId;
if (InReplyTo is null)
return;
form.InReplyToId = InReplyTo.Id;
form.MessageType = InReplyTo.Visibility switch
{
"direct" => MessageType.Direct,
"private" => MessageType.FollowersOnly,
"unlisted" => MessageType.Unlisted,
_ => MessageType.Public
};
form.HasContentWarning = InReplyTo.SpoilerText is { Length: > 0 };
form.SpoilerText = InReplyTo.SpoilerText;
var mentions = InReplyTo.Mentions.Select(m => m.Acct).Prepend(InReplyTo.Account?.Acct)
.Where(acct => acct is not null && acct != CascadingState.Persona?.Acct).Distinct().Select(acct => "@" + acct);
form.Content = string.Join(' ', mentions) is { Length: > 0 } prefix ? prefix + " " : null;
}
void SetMessageType(MessageType messageType)
{
form.MessageType = messageType;
form.IsScopeOptionsOpen = false;
}
async Task ToggleLocated()
{
form.IsLocated = !form.IsLocated;
if (!form.IsLocated || form.Latitude is not null)
return;
var position = await JS.InvokeAsync<GeoPosition>("feedPosition");
if (position?.Error is { Length: > 0 } positionError)
{
form.IsLocated = false;
error = Localizer["This device did not give its position: {0}", positionError];
return;
}
form.Latitude = position?.Latitude;
form.Longitude = position?.Longitude;
}
async Task OnFileChange(InputFileChangeEventArgs eventArgs)
{
fileErrors = [];
if (eventArgs.FileCount + form.Media.Count > MaximumFileCount)
{
fileErrors.Add(Localizer["The maximum number of files accepted is {0}, but {1} were supplied.", MaximumFileCount, form.Media.Count + eventArgs.FileCount]);
return;
}
foreach (var file in eventArgs.GetMultipleFiles(MaximumFileCount))
{
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;
}
if (await ReadFile(file) is { } media)
form.Media.Add(media);
else
fileErrors.Add(Localizer["The file \"{0}\" could not be read.", file.Name]);
}
}
/// <summary>Reads a picked file into memory; null when the browser can't read it (logged).</summary>
async Task<UploadMedia> ReadFile(IBrowserFile file, CancellationToken cancellationToken = default)
{
try
{
using var memoryStream = new MemoryStream();
await using var fileStream = file.OpenReadStream(MaximumFileSize, cancellationToken);
await fileStream.CopyToAsync(memoryStream, cancellationToken);
var media = new UploadMedia { FileName = file.Name, ContentType = file.ContentType, Size = file.Size, Blob = memoryStream.ToArray() };
if (file.ContentType.StartsWith("image"))
media.Base64Preview = $"data:{media.ContentType};base64,{Convert.ToBase64String(media.Blob)}";
return media;
}
catch (Exception ex)
{
await Logger.ProcessError(ex, $"{nameof(Composer)}.{nameof(ReadFile)}:{file.Name}", cancellationToken);
return default;
}
}
async Task Publish()
{
error = default;
if (string.IsNullOrWhiteSpace(form.Content) && form.Media.Count == 0)
{
error = Localizer["Missing content, either message or media"];
return;
}
if (CascadingState.PersonaId is null)
{
error = Localizer["Choose a persona first."];
return;
}
isPublishing = true;
var result = await StatusService.Publish(form, CascadingState.PersonaId);
isPublishing = false;
if (result.IsInvalid)
{
error = result.ErrorMessage;
return;
}
Toast.AddResponseSuccess(form.IsLocated ? Localizer["Located post published."] : Localizer["Published."]);
var published = result.Data as FeedPost;
form = new() { GroupId = GroupId };
await OnPublished.InvokeAsync(published);
}
sealed class GeoPosition
{
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public double? Accuracy { get; set; }
public string Error { get; set; }
}
}
+567 -188
View File
@@ -1,222 +1,601 @@
@inherits LocalizableComponentBase
<div class="flex gap-3 w-full rounded-xl neo-raised @(Highlighted ? "neo-sm" : "neo-2xs") @CssContainer">
@* One feed item: a post (a boost shows the original and its booster), a notification, or a conversation's last post.
The card does its own Mastodon actions (favourite, boost, bookmark, reply, mute, block, delete) and tells the page
about replies and deletions. data-post-* attributes tell the globe where the post is (wwwroot/js/globe.js); a
quoted post (Compact) has none, since it is not an item of the feed. Located
posts have no actions: PrivaPub keeps them off the Mastodon API. Nerd stats are on the time, the author, the place,
the media and the counts. *@
<article class="flex gap-3 w-full rounded-xl neo-raised @(Highlighted ? "neo-sm" : "neo-2xs") @CssContainer"
data-post-id="@(Compact ? null : Post.Key)" data-lat="@(Compact ? null : Coordinate(Post.Location?.Latitude))"
data-lng="@(Compact ? null : Coordinate(Post.Location?.Longitude))" data-src="@(Compact ? null : Post.Location?.Source.ToString().ToLowerInvariant())"
data-label="@(Compact ? null : Post.Location?.Label)" data-host="@(Compact ? null : Post.Host)"
data-range="@(Post.Located && !Compact ? Coordinate(Post.RangeKm) : null)">
<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)');">
@if (Author is { } author)
{
<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="@HeaderBackground(author)">
<a class="block h-12 w-12 md:h-14 md:w-14" href="@author.Url" target="_blank" rel="noopener noreferrer" title="@author.Acct">
@* alt="": the author's name is next to it. *@
<img alt="" loading="lazy" class="h-12 w-12 md:h-14 md:w-14 object-cover rounded-full neo-raised neo-2xs bg-base-100"
src="@(author.Avatar ?? "imgs/icon-192.png")" />
</a>
</div>
}
<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")" />
</a>
<div class="flex flex-col gap-2 flex-1 py-3 pr-3 md:py-4 md:pr-4 min-w-0">
</div>
@if (Post.Notification is { } notification)
{
<p class="inline-flex flex-wrap items-center gap-2 min-w-0 text-xs">
<i aria-hidden="true" class="@NotificationIcon(notification.Type)"></i>
<span>@NotificationText(notification)</span>
<span class="opacity-60" title="@NerdRow.Time(notification.CreatedAt)">@notification.CreatedAt.GetPassedTime(Localizer)</span>
</p>
}
else if (Post.BoostedBy is { } booster)
{
<p class="inline-flex flex-1 items-center gap-2 min-w-0 text-xs">
<i class="ion-md-repeat text-info" aria-hidden="true"></i>
<a class="font-bold truncate" href="@booster.Url" target="_blank" rel="noopener noreferrer" title="@booster.Acct">@booster.Name</a>
<span>@Localizer["boosted"]</span>
</p>
}
else if (Post.Conversation is { } conversation)
{
<p class="inline-flex flex-wrap items-center gap-2 min-w-0 text-xs">
<i class="ion-md-mail @(conversation.Unread ? "text-primary" : null)" aria-hidden="true"></i>
<span class="truncate">@string.Join(", ", conversation.Accounts.Select(a => "@" + a.Acct))</span>
</p>
}
<div class="flex flex-col gap-3 flex-1 py-3 pr-3 md:py-4 md:pr-4 min-w-0">
@if (Status is { } status)
{
<header class="flex flex-wrap items-baseline gap-x-2 gap-y-1 min-w-0 justify-between text-xs md:text-sm">
<NerdTip Heading="@Localizer["Author"]" Rows="AuthorRows()" Align="DTooltipAlign.Start" Class="min-w-0 flex-1">
<span class="inline-flex gap-2 min-w-0 max-w-full">
<b class="shrink truncate" title="@status.Account?.Name">@status.Account?.Name</b>
<span class="flex-1 min-w-6 opacity-50 truncate self-center text-xs">@("@" + status.Account?.Acct)</span>
</span>
</NerdTip>
<span class="flex-none inline-flex gap-2 items-center">
@if (Post.Location is { } location)
{
<NerdTip Heading="@Localizer["Place"]" Rows="LocationRows()" Placement="DTooltipPlacement.Bottom" Align="DTooltipAlign.End">
<span class="badge badge-ghost badge-sm gap-1 max-w-40">
<i class="@LocationIcon(location.Source)" aria-hidden="true"></i>
<span class="truncate">@(location.Label ?? Localizer["Near you"])</span>
</span>
</NerdTip>
}
else if (ServerGeo?.Cdn is { Length: > 0 } cdn)
{
<span class="badge badge-ghost badge-sm gap-1" title="@Localizer["The server is behind {0}, so its place is unknown.", cdn]">
<i class="ion-md-cloud" aria-hidden="true"></i>
<span>@cdn</span>
</span>
}
<NerdTip Heading="@Localizer["Post"]" Rows="PostRows()" Pending="isReadingProvenance" OnOpen="ReadProvenance"
Placement="DTooltipPlacement.Bottom" Align="DTooltipAlign.End">
<time datetime="@NerdRow.Time(status.CreatedAt)" class="opacity-80">@status.CreatedAt.GetPassedTime(Localizer)</time>
@if (status.EditedAt is not null)
{
<span class="opacity-60">*</span>
}
</NerdTip>
<i aria-hidden="true" class="@VisibilityIcon(status.Visibility) text-base" title="@VisibilityText(status.Visibility)"></i>
</span>
</header>
<div class="flex flex-col gap-1 flex-1 min-w-0">
@if (Message.BoostingUser != null)
@if (status.Privapub?.Title is { Length: > 0 } title)
{
<p class="inline-flex flex-1 gap-2 min-w-0 text-xs">
<a class="font-bold" href="@Message.BoostingUser.ProfileUrl" title="@Message.BoostingUser.UserName">@Message.BoostingUser.DisplayName</a>
<i class="ion-md-repeat text-info" aria-hidden="true"></i>
<span>@Localizer["boosted"]</span>
<p class="text-sm md:text-base font-bold break-words">@title</p>
}
@if (status.SpoilerText is { Length: > 0 } spoiler)
{
<DCollapse @bind-IsOpen="isSpoilerOpen" Icon="DCollapseIcon.Arrow" class="rounded-lg neo-xs" HeaderClass="text-sm py-2 min-h-0"
ContentClass="text-sm">
<Header>
<span class="inline-flex gap-2 items-center"><i class="ion-md-warning text-warning"></i>@spoiler</span>
</Header>
<ChildContent>
@Body(status)
</ChildContent>
</DCollapse>
}
else
{
@Body(status)
}
@if (Post.Located)
{
<p class="inline-flex gap-2 items-center text-xs opacity-70">
<i class="ion-md-locate"></i>
<span>@Localizer["{0} km from you, shown within {1} km", Number(Post.DistanceKm), Number(Post.RangeKm)]</span>
</p>
}
<p class="inline-flex flex-1 gap-2 min-w-0 justify-between text-xs md:text-sm">
<span class="inline-flex gap-2 min-w-0">
<b class="shrink truncate max-w-[80%]" title="@Message.User.DisplayName">
@Message.User.DisplayName
</b>
<a class="underline flex-1 min-w-6 opacity-50 truncate self-center text-xs" href="@Message.User.ProfileUrl" title="@Message.User.UserName">
@Message.User.UserName
</a>
</span>
<span class="flex-none inline-flex gap-1 items-center">
<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()]">
</i>
</span>
</p>
@if (Message.Title is { Length: > 0 })
@if (!Post.Located && !Compact)
{
<p class="text-sm md:text-base font-bold break-all">@Message.Title</p>
<footer class="flex gap-2 mt-1 justify-between">
<div class="flex gap-2">
<DButton Size="DSize.Sm" Active="isReplying" Disabled="IsDefaultDisabled" OnClick="ToggleReply" title="@Localizer[isReplying ? "Close" : "Reply"]">
<i aria-hidden="true" class="@(isReplying ? "ion-md-close-circle" : "ion-md-text") text-lg text-success"></i>
@if (status.RepliesCount > 0)
{
<span>@status.RepliesCount</span>
}
</DButton>
<DButton Size="DSize.Sm" Active="status.Reblogged" Disabled="IsDefaultDisabled || isActing || !CanBoost(status)"
OnClick="() => Act(status.Reblogged ? StatusAction.Unreblog : StatusAction.Reblog)" title="@Localizer["Boost"]">
<i aria-hidden="true" class="ion-md-repeat text-lg text-info"></i>
@if (status.ReblogsCount > 0)
{
<span>@status.ReblogsCount</span>
}
</DButton>
<DButton Size="DSize.Sm" Active="status.Favourited" Disabled="IsDefaultDisabled || isActing"
OnClick="() => Act(status.Favourited ? StatusAction.Unfavourite : StatusAction.Favourite)" title="@Localizer["Favourite"]">
<i aria-hidden="true" class="@(status.Favourited ? "ion-md-heart" : "ion-md-heart-empty") text-lg text-pink-400"></i>
@if (status.FavouritesCount > 0)
{
<span>@status.FavouritesCount</span>
}
</DButton>
<DButton Size="DSize.Sm" Active="status.Bookmarked" Disabled="IsDefaultDisabled || isActing"
OnClick="() => Act(status.Bookmarked ? StatusAction.Unbookmark : StatusAction.Bookmark)" title="@Localizer["Bookmark"]">
<i aria-hidden="true" class="ion-md-bookmark text-lg @(status.Bookmarked ? "text-warning" : null)"></i>
</DButton>
<NerdTip Heading="@Localizer["Counts"]" Rows="CountRows(status)" Class="self-center">
<i class="ion-md-stats opacity-40" aria-label="@Localizer["Counts"]"></i>
</NerdTip>
</div>
<div class="flex gap-2">
<DDropdown @bind-IsOpen="isOptionsOpen" Align="DDropdownAlign.End" CloseOnContentClick="true" Placement="DDropdownPlacement.Top"
TriggerClass="@(isOptionsOpen ? "btn btn-sm btn-active" : "btn btn-sm")"
ContentClass="mb-2 flex flex-col gap-2 p-2 rounded-box" title="@Localizer["Other"]">
<Trigger>
<i aria-hidden="true" class="ion-md-more text-lg"></i>
</Trigger>
<ChildContent>
@if (status.Url is { Length: > 0 } url)
{
<a class="btn btn-sm justify-start whitespace-nowrap" href="@url" target="_blank" rel="noopener noreferrer">
<i aria-hidden="true" class="ion-md-open text-base"></i>
<span>@Localizer["Open original"]</span>
</a>
}
@if (!IsOwn)
{
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled || isActing" OnClick="@(() => AccountAction("mute"))">
<i aria-hidden="true" class="ion-md-eye-off text-base text-warning"></i>
<span>@Localizer["Mute"]</span>
</DButton>
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled || isActing" OnClick="@(() => AccountAction("block"))">
<i aria-hidden="true" class="ion-md-remove-circle text-base text-error"></i>
<span>@Localizer["Block"]</span>
</DButton>
}
else
{
<DButton Size="DSize.Sm" class="justify-start whitespace-nowrap" Disabled="IsDefaultDisabled || isActing" OnClick="Delete">
<i aria-hidden="true" class="ion-md-trash text-base text-error"></i>
<span>@Localizer["Delete"]</span>
</DButton>
}
</ChildContent>
</DDropdown>
@if (IncludeExpand)
{
<NavLink class="btn btn-sm" href="@($"expand/{Uri.EscapeDataString(status.Id)}")" title="@Localizer["Expand"]">
<i aria-hidden="true" class="ion-md-expand text-lg"></i>
</NavLink>
}
</div>
</footer>
@if (isReplying)
{
<Composer InReplyTo="status" OnPublished="Replied" />
}
}
@if (Message.Content is { Length: > 0 })
{
<div class="text-sm md:text-base break-all">
@((MarkupString)Message.Content)
</div>
}
@if (Message.Medias.Count != 0)
{
<div class="grid gap-4 auto-cols-auto grid-rows-1 grid-flow-col-dense">
@foreach (var media in Message.Medias)
{
if (media.ContentType.StartsWith("image"))
{
<a class="w-auto" href="@media.Url">
<img alt="@media.AltText" class="w-full rounded-lg @SUtility.IfTrueThen(Message.Medias.Count > 1, "max-h-[30vh]")" src="@media.Url" title="@media.AltText">
</a>
}
else if (media.ContentType.StartsWith("video"))
{
<video class="w-full max-h-[50vh] aspect-video rounded-lg mx-auto neo-inset neo-2xs" controls="controls" playsinline="playsinline" preload="metadata" title="@media.FileName">
<source src="@media.Url" type="@media.ContentType" />
</video>
}
else if (media.ContentType.StartsWith("audio"))
{
<audio class="w-full max-h-8" controls="controls" preload="metadata" title="@media.FileName">
<source src="@media.Url" type="@media.ContentType" />
</audio>
}
else
{
<div class="flex items-center gap-3 rounded-lg p-3 md:p-4 neo-raised neo-2xs">
<span>
<i class="text-2xl ion-md-document"></i>
</span>
<div class="flex flex-col w-full gap-1">
<p class="text-xs md:text-sm break-all">
<b>@media.FileName</b>
</p>
<p class="text-xs break-all">
<i class="ion-md-code"></i> @media.ContentType
</p>
</div>
<DButton Size="DSize.Sm" OnClick="async () => await OnMessageMediaDownload.InvokeAsync(media)">
<i class="ion-md-download text-base"></i>
</DButton>
</div>
}
}
</div>
}
</div>
<div class="flex gap-3 mt-3 justify-between">
<div class="flex gap-3">
@if (OnMessageReply.HasDelegate)
{
<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" 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)
{
<span>@Message.BoostsCounter</span>
}
</DButton>
}
@if (OnMessageFavourite.HasDelegate)
{
<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>
}
</div>
<div class="flex gap-3">
<DDropdown @bind-IsOpen="Message.IsOptionsOpen" Align="DDropdownAlign.End" CloseOnContentClick="true"
TriggerClass="@(Message.IsOptionsOpen ? "btn btn-sm btn-active" : "btn btn-sm")"
ContentClass="mt-2 flex flex-col gap-2 p-2 rounded-box" title="@Localizer["Other"]">
<Trigger>
<i aria-hidden="true" class="ion-md-more text-lg"></i>
</Trigger>
<ChildContent>
@if (OnUserDirectMessage.HasDelegate)
{
<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" 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" 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>
}
@* 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" 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>
}
</ChildContent>
</DDropdown>
@if (IncludeExpand)
{
<NavLink class="btn btn-sm" href="@($"expand/{Message.MessageId}")" title="@Localizer["Expand"]">
<i aria-hidden="true" class="ion-md-expand text-lg"></i>
</NavLink>
}
</div>
</div>
@if (isAnswering)
}
else if (Post.Notification?.Account is { } follower)
{
<MessageUpsertForm AnsweringMessage="Message" OnMessageSubmit="SubmitReply"></MessageUpsertForm>
<p class="text-sm">
<b>@follower.Name</b> <span class="opacity-60">@("@" + follower.Acct)</span>
</p>
}
</div>
</div>
</article>
@code {
[Parameter] public Message Message { get; set; } = new();
[Parameter] public EventCallback<MessageForm> OnMessageReply { get; set; }
[Parameter] public EventCallback<Message> OnMessageBoost { get; set; }
[Parameter] public EventCallback<Message> OnMessageFavourite { get; set; }
[Parameter] public EventCallback<Message> OnMessageDelete { get; set; }
[Parameter] public EventCallback<Message> OnUserDirectMessage { get; set; }
[Parameter] public EventCallback<Media> OnMessageMediaDownload { get; set; }
[Parameter] public EventCallback<MessageUser> OnUserBlock { get; set; }
[Parameter] public EventCallback<MessageUser> OnUserSilence { get; set; }
[Inject] StatusService StatusService { get; set; }
[Inject] InstanceService InstanceService { get; set; }
[Inject] ProvenanceService ProvenanceService { get; set; }
[Parameter, EditorRequired] public FeedPost Post { get; set; }
[Parameter] public EventCallback<FeedPost> OnDeleted { get; set; }
[Parameter] public EventCallback<FeedPost> OnReplied { get; set; }
[Parameter] public EventCallback<string> OnTag { get; set; }
[Parameter] public string CssContainer { get; set; }
/// <summary>Deeper shadow, for the message a thread page is about.</summary>
/// <summary>Deeper shadow, for the post a thread page is about.</summary>
[Parameter] public bool Highlighted { get; set; }
[Parameter] public bool IncludeExpand { get; set; } = true;
/// <summary>Without actions, e.g. a quoted post.</summary>
[Parameter] public bool Compact { get; set; }
bool isAnswering;
bool isReplying;
bool isActing;
bool isOptionsOpen;
bool isSpoilerOpen;
bool isReadingProvenance;
readonly HashSet<string> revealedMedia = [];
Status Status => Post.Status;
Account Author => Post.Status?.Account ?? Post.Notification?.Account;
ServerInfo Server => InstanceService.Known(Post.Host);
InstanceLocation ServerGeo => Server?.Geo;
bool IsOwn => Post.IsOwnedBy(CascadingState.PersonaId);
protected override void OnInitialized() => IsLoading = false;
async Task DeleteMessage()
RenderFragment Body(Status status) => @<div class="flex flex-col gap-3">
@if (status.Content is { Length: > 0 } content)
{
<div class="post-content text-sm md:text-base break-words">@((MarkupString)content)</div>
}
@if (status.MediaAttachments.Count > 0)
{
<div class="grid gap-2 @(status.MediaAttachments.Count > 1 ? "grid-cols-2" : "grid-cols-1")">
@foreach (var media in status.MediaAttachments)
{
<NerdTip Heading="@Localizer["Media"]" Rows="MediaRows(media)" Class="block w-full">
@if (status.Sensitive && !revealedMedia.Contains(media.Id))
{
<button type="button" class="flex items-center justify-center w-full aspect-video rounded-lg neo-inset neo-2xs text-sm"
@onclick="() => revealedMedia.Add(media.Id)">
<i class="ion-md-eye-off mr-2"></i>@Localizer["Sensitive media, show"]
</button>
}
else
{
@Media(media, status.MediaAttachments.Count > 1)
}
</NerdTip>
}
</div>
}
@if (status.Card is { } card && status.MediaAttachments.Count == 0)
{
<a class="flex gap-3 rounded-lg p-2 neo-inset neo-2xs min-w-0" href="@card.Url" target="_blank" rel="noopener noreferrer">
@if (card.Image is { Length: > 0 } image)
{
<img alt="@card.ImageDescription" loading="lazy" class="h-16 w-24 flex-none object-cover rounded-md" src="@image" />
}
<span class="flex flex-col min-w-0 text-xs">
<b class="truncate">@card.Title</b>
<span class="line-clamp-2 opacity-70">@card.Description</span>
<span class="truncate opacity-50">@(card.ProviderName ?? CardHost(card.Url))</span>
</span>
</a>
}
@if (status.Poll is { } poll)
{
<div class="flex flex-col gap-1 text-xs">
@foreach (var option in poll.Options)
{
var share = poll.VotesCount > 0 && option.VotesCount is { } votes ? votes * 100d / poll.VotesCount : 0;
<div class="relative rounded-md overflow-hidden neo-inset neo-2xs px-2 py-1">
<div class="absolute inset-y-0 left-0 bg-primary/20" style="width:@(share.ToString("0.#", System.Globalization.CultureInfo.InvariantCulture))%"></div>
<span class="relative flex justify-between gap-2"><span>@option.Title</span><span>@share.ToString("0")%</span></span>
</div>
}
<span class="opacity-60">@Localizer["{0} votes", poll.VotesCount] · @(poll.Expired ? Localizer["closed"] : Localizer["open"])</span>
</div>
}
@if (status.Privapub?.Event is { } happening)
{
<div class="flex flex-col gap-1 text-xs rounded-lg p-2 neo-inset neo-2xs">
<span class="inline-flex gap-2 items-center"><i class="ion-md-calendar"></i>@EventTime(happening)</span>
@foreach (var venue in happening.Places)
{
<span class="inline-flex gap-2 items-center"><i class="ion-md-pin"></i>@(venue.Name ?? venue.Address ?? venue.Url)</span>
}
</div>
}
@if (status.Quote?.QuotedStatus is { } quoted)
{
<Content Post="FeedPost.Of(quoted)" Compact="true" IncludeExpand="false" CssContainer="neo-inset! shadow-none" />
}
@if (status.Tags.Count > 0)
{
<div class="flex flex-wrap gap-1">
@foreach (var tag in status.Tags)
{
<button type="button" class="badge badge-soft badge-sm" @onclick="() => OnTag.InvokeAsync(tag.Name)">#@tag.Name</button>
}
</div>
}
</div>;
RenderFragment Media(MediaAttachment media, bool several) => media.Type switch
{
isAnswering = false;
await OnMessageDelete.InvokeAsync(Message);
"image" => @<a class="block w-full" href="@media.Url" target="_blank" rel="noopener noreferrer">
<img alt="@media.Description" title="@media.Description" loading="lazy" class="w-full rounded-lg object-cover @(several ? "aspect-square" : "max-h-[60vh]")"
src="@(media.PreviewUrl ?? media.Url)" />
</a>,
"gifv" => @<video class="w-full rounded-lg" autoplay muted loop playsinline title="@media.Description" src="@media.Url"></video>,
"video" => @<video class="w-full max-h-[50vh] aspect-video rounded-lg neo-inset neo-2xs" controls playsinline preload="metadata"
poster="@media.PreviewUrl" title="@media.Description" src="@media.Url"></video>,
"audio" => @<audio class="w-full" controls preload="metadata" title="@media.Description" src="@media.Url"></audio>,
_ => @<a class="btn btn-sm justify-start" href="@media.Url" target="_blank" rel="noopener noreferrer">
<i class="ion-md-document"></i><span class="truncate">@(media.Description ?? media.Url)</span>
</a>
};
async Task Act(StatusAction action)
{
isActing = true;
var result = await StatusService.Act(Status.Id, action);
isActing = false;
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
// Unreblog answers with the original; reblog with the boost wrapper.
var updated = (Status)result.Data;
Post.Status = updated.Reblog ?? updated;
}
async Task SubmitReply(MessageForm messageForm)
async Task Delete()
{
isAnswering = false;
await OnMessageReply.InvokeAsync(messageForm);
isActing = true;
var result = await StatusService.Delete(Status.Id);
isActing = false;
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
Toast.AddResponseSuccess(Localizer["Message deleted."]);
await OnDeleted.InvokeAsync(Post);
}
void Reply()
async Task AccountAction(string action)
{
isAnswering = !isAnswering;
isActing = true;
var result = await StatusService.AccountAction(Status.Account.Id, action);
isActing = false;
if (result.IsInvalid)
{
Toast.AddResponseError(result);
return;
}
Toast.AddResponseSuccess(action == "block" ? Localizer["{0} blocked.", Status.Account.Name] : Localizer["{0} muted.", Status.Account.Name]);
}
void ToggleReply() => isReplying = !isReplying;
async Task Replied(FeedPost reply)
{
isReplying = false;
Status.RepliesCount++;
await OnReplied.InvokeAsync(reply);
}
async Task ReadProvenance()
{
if (Status is null || Post.Located)
return;
isReadingProvenance = true;
await ProvenanceService.Get(Status.Id);
isReadingProvenance = false;
}
static bool CanBoost(Status status) => status.Visibility is "public" or "unlisted";
static string Coordinate(double? value) => value?.ToString("0.####", System.Globalization.CultureInfo.InvariantCulture);
static string Number(double? value) => value?.ToString("0.#", System.Globalization.CultureInfo.CurrentCulture) ?? "?";
static string CardHost(string url) => Uri.TryCreate(url, UriKind.Absolute, out var uri) ? uri.Host : url;
// PrivaPub (like Mastodon) answers a placeholder for a missing header: /media/missing-header.png.
static string HeaderBackground(Account account) => account.Header is { Length: > 0 } header && !header.Contains("/missing-")
? $"background-image:linear-gradient(to left, var(--color-base-100), transparent), url('{header}');"
: null;
string EventTime(PrivaPubEvent happening) => happening.Start is { } start
? happening.End is { } end
? $"{start.ToLocalTime():g} – {end.ToLocalTime():t}"
: start.ToLocalTime().ToString("g")
: Localizer["Event"];
string VisibilityText(string visibility) => visibility switch
{
"public" => Localizer[MessageType.Public.ToString()],
"unlisted" => Localizer[MessageType.Unlisted.ToString()],
"private" => Localizer[MessageType.FollowersOnly.ToString()],
"direct" => Localizer[MessageType.Direct.ToString()],
_ => Localizer["Located"]
};
static string VisibilityIcon(string visibility) => visibility switch
{
"public" => "ion-md-globe",
"unlisted" => "ion-md-unlock",
"private" => "ion-md-lock",
"direct" => "ion-md-paper-plane",
_ => "ion-md-locate"
};
static string LocationIcon(LocationSource source) => source switch
{
LocationSource.Place or LocationSource.Event => "ion-md-pin",
LocationSource.NearYou => "ion-md-locate",
LocationSource.Country => "ion-md-flag",
_ => "ion-md-planet"
};
static string NotificationIcon(string type) => type switch
{
"favourite" => "ion-md-heart text-pink-400",
"reblog" => "ion-md-repeat text-info",
"mention" => "ion-md-at text-success",
"follow" or "follow_request" => "ion-md-person-add text-primary",
"poll" => "ion-md-podium",
"update" or "quoted_update" => "ion-md-create",
"quote" => "ion-md-quote",
_ => "ion-md-notifications"
};
string NotificationText(Notification notification)
{
var name = notification.Account?.Name;
return notification.Type switch
{
"favourite" => Localizer["{0} favourited your post", name],
"reblog" => Localizer["{0} boosted your post", name],
"mention" => Localizer["{0} mentioned you", name],
"follow" => Localizer["{0} followed you", name],
"follow_request" => Localizer["{0} asked to follow you", name],
"status" => Localizer["{0} posted", name],
"poll" => Localizer["A poll you took part in has ended"],
"update" => Localizer["{0} edited a post", name],
"quote" => Localizer["{0} quoted your post", name],
"pleroma:emoji_reaction" => Localizer["{0} reacted {1}", name, notification.Emoji],
_ => Localizer["{0}: {1}", name, notification.Type]
};
}
#region Nerd stats
IEnumerable<NerdRow> PostRows()
{
var status = Status;
yield return NerdRow.Of("id", status.Id);
yield return NerdRow.Of("created_at", status.CreatedAt);
yield return NerdRow.Of("edited_at", status.EditedAt);
yield return NerdRow.Of("uri", status.Uri);
yield return NerdRow.Of("language", status.Language);
yield return NerdRow.Of("visibility", status.Visibility);
yield return NerdRow.Of("type", status.Privapub?.ObjectType);
yield return NerdRow.Of("source", status.Privapub?.Source?.MediaType);
yield return NerdRow.Of("client", status.Application?.Name);
if (ProvenanceService.Known(status.Id) is not { } provenance)
yield break;
yield return NerdRow.Of("path", provenance.Path);
yield return NerdRow.Of("activity", provenance.Activity is { } activity ? $"{activity.Type} {activity.Id}" : null);
yield return NerdRow.Of("inbox", provenance.Inbox);
yield return NerdRow.Of("fetched_by", provenance.FetchedBy);
yield return NerdRow.Of("published", provenance.Published);
yield return NerdRow.Of("received_at", provenance.ReceivedAt);
if (provenance.ReceivedAt is { } received && provenance.Published is { } published)
yield return new(Localizer["delivery latency"], NerdRow.Duration(received - published));
yield return NerdRow.Of("signature", provenance.Signature is { } signature
? $"{signature.Scheme} {signature.Algorithm} ({string.Join(' ', signature.Headers)})"
: null);
yield return NerdRow.Of("key_id", provenance.Signature?.KeyId);
yield return NerdRow.Of("raw", provenance.RawBytes > 0 ? NerdRow.Bytes(provenance.RawBytes) + (provenance.RawTruncated ? " (truncated)" : null) : null);
yield return NerdRow.Of("sha256", provenance.RawHash is { Length: > 16 } hash ? hash[..16] + "…" : provenance.RawHash);
yield return NerdRow.Of("revisions", provenance.Revisions.Count > 0 ? provenance.Revisions.Count : null);
yield return NerdRow.Of("refetched", provenance.Refetched ? true : null);
yield return NerdRow.Of("extensions", provenance.Extensions.Count > 0 ? string.Join(", ", provenance.Extensions) : null);
yield return NerdRow.Of("@context", provenance.ContextNamespaces.Count > 0 ? string.Join(", ", provenance.ContextNamespaces) : null);
}
IEnumerable<NerdRow> AuthorRows()
{
var account = Status?.Account;
if (account is null)
yield break;
yield return NerdRow.Of("acct", account.Acct);
yield return NerdRow.Of("uri", account.Uri);
yield return NerdRow.Of("created_at", account.CreatedAt);
yield return NerdRow.Of(Localizer["followers"], account.FollowersCount);
yield return NerdRow.Of(Localizer["following"], account.FollowingCount);
yield return NerdRow.Of(Localizer["posts"], account.StatusesCount);
yield return NerdRow.Of("bot", account.Bot ? true : null);
yield return NerdRow.Of("locked", account.Locked ? true : null);
if (Server is not { } server)
yield break;
yield return NerdRow.Of(Localizer["server"], server.NodeName is { Length: > 0 } name && name != server.Host ? $"{server.Host} ({name})" : server.Host);
yield return NerdRow.Of(Localizer["software"], $"{server.Software} {server.Version}".Trim());
yield return NerdRow.Of(Localizer["Users"], server.Users is { } users
? server.ActiveMonth is { } active ? $"{users:N0} ({active:N0} {Localizer["active this month"]})" : users.ToString("N0")
: null);
yield return NerdRow.Of(Localizer["local posts"], server.LocalPosts);
yield return NerdRow.Of(Localizer["registrations"], server.OpenRegistrations is { } open ? open ? Localizer["open"] : Localizer["closed"] : null);
yield return NerdRow.Of(Localizer["last delivery"], server.LastSuccessAt);
yield return NerdRow.Of(Localizer["failures in a row"], server.ConsecutiveFailures > 0 ? server.ConsecutiveFailures : null);
yield return NerdRow.Of(Localizer["described"], server.DescribedAt);
}
IEnumerable<NerdRow> LocationRows()
{
var location = Post.Location;
yield return new(Localizer["source"], location.Source switch
{
LocationSource.Place => Localizer["the post's own place"],
LocationSource.Event => Localizer["the event's venue"],
LocationSource.Server => Localizer["the author's server"],
LocationSource.Country => Localizer["the author's server's country"],
_ => Localizer["Near you"]
});
yield return NerdRow.Of("lat, lng", $"{Coordinate(location.Latitude)}, {Coordinate(location.Longitude)}");
yield return NerdRow.Of(Localizer["precision"], $"±{location.PrecisionKm:0} km");
if (location.Source is LocationSource.Server or LocationSource.Country && ServerGeo is { } geo)
{
yield return NerdRow.Of(Localizer["network"], geo.Network);
yield return NerdRow.Of(Localizer["located by"], geo.Source);
yield return NerdRow.Of(Localizer["located at"], geo.LocatedAt);
}
if (InstanceService.Known(InstanceService.SelfHost)?.Geo is { Latitude: { } selfLatitude, Longitude: { } selfLongitude } && location.Source is not LocationSource.NearYou)
yield return new(Localizer["from PrivaPub"], $"{NerdRow.Kilometres(selfLatitude, selfLongitude, location.Latitude, location.Longitude):N0} km");
}
static IEnumerable<NerdRow> MediaRows(MediaAttachment media)
{
yield return NerdRow.Of("type", media.Type);
yield return NerdRow.Of("size", media.Meta?.Original?.Size);
yield return NerdRow.Of("aspect", media.Meta?.Original?.Aspect);
yield return NerdRow.Of("length", media.Meta?.Length);
yield return NerdRow.Of("focus", media.Meta?.Focus is { } focus ? $"{focus.X:0.##}, {focus.Y:0.##}" : null);
yield return NerdRow.Of("blurhash", media.Blurhash);
yield return NerdRow.Of("served by", Uri.TryCreate(media.Url, UriKind.Absolute, out var served) ? served.Host : null);
yield return NerdRow.Of("origin", Uri.TryCreate(media.RemoteUrl, UriKind.Absolute, out var origin) ? origin.Host : null);
yield return NerdRow.Of("alt", media.Description is { Length: > 0 } alt ? $"{alt.Length} chars" : "none");
}
IEnumerable<NerdRow> CountRows(Status status)
{
yield return NerdRow.Of(Localizer["replies"], status.RepliesCount);
yield return NerdRow.Of(Localizer["boosts"], status.ReblogsCount);
yield return NerdRow.Of(Localizer["Favourites"], status.FavouritesCount);
yield return NerdRow.Of(Localizer["quotes"], status.QuotesCount > 0 ? status.QuotesCount : null);
yield return NerdRow.Of(Localizer["votes"], status.Privapub?.Votes is { } votes && votes.Up + votes.Down > 0 ? $"+{votes.Up} −{votes.Down}" : null);
if (status.FavouritesCount > 0)
yield return NerdRow.Of(Localizer["boosts per favourite"], Math.Round((double)status.ReblogsCount / status.FavouritesCount, 2));
}
#endregion
}
+107
View File
@@ -0,0 +1,107 @@
@inherits LocalizableComponentBase
@* The feed page's tabs, one per kind of feed, scrolling sideways on narrow screens. Groups adds a choice of the
persona's communities and circles, Tag the hashtag being followed. The stats icon shows how the current feed was
read; the buttons on the right open the composer and, on narrow screens, the globe. *@
<div class="flex flex-col gap-2">
<div class="flex items-center gap-2 min-w-0">
<div class="flex-1 min-w-0 overflow-x-auto">
<DTabs Active="ActiveIndex" ActiveChanged="Select" Variant="DTabsVariant.Box" Size="DSize.Sm" ContentClass="hidden" class="flex-nowrap w-max">
@foreach (var type in Types)
{
<DTab Class="gap-1 whitespace-nowrap">
<Header>
<i class="@type.GetTimelineTypeIcon()" aria-hidden="true"></i>
<span class="@(type == Filter.TimelineType ? null : "hidden xl:inline")">@TabName(type)</span>
</Header>
</DTab>
}
</DTabs>
</div>
<NerdTip Heading="@Localizer["Feed"]" Rows="Stats" Placement="DTooltipPlacement.Bottom" Align="DTooltipAlign.End">
<i class="ion-md-stats opacity-50" aria-label="@Localizer["Feed"]"></i>
</NerdTip>
<DButton Size="DSize.Sm" class="lg:hidden" Active="Filter.ShowGlobe" OnClick="ToggleGlobe" title="@Localizer["Globe"]">
<i class="ion-md-planet text-base"></i>
</DButton>
<DButton Size="DSize.Sm" Active="IsComposing" OnClick="() => OnCompose.InvokeAsync()" title="@Localizer["Post"]">
<i class="ion-md-create text-base"></i>
<span class="hidden sm:inline">@Localizer["Post"]</span>
</DButton>
</div>
@if (Filter.TimelineType is TimelineType.Groups)
{
@if (Groups.Count == 0)
{
<p class="text-xs opacity-70">@Localizer["This persona is in no community or circle yet."]</p>
}
else
{
<DSelect TValue="string" Size="DSize.Sm" class="w-full sm:w-auto" Value="Filter.GroupId" ValueChanged="SelectGroup" ValueExpression="() => Filter.GroupId">
<Prefix><i class="@(SelectedGroup?.IsCommunity == false ? "ion-md-lock" : "ion-md-contacts")"></i></Prefix>
<ChildContent>
@foreach (var group in Groups)
{
<option value="@group.Id">@(group.IsCommunity ? "◎" : "◉") @(group.Name ?? group.UserName)</option>
}
</ChildContent>
</DSelect>
}
}
else if (Filter.TimelineType is TimelineType.Tag)
{
<p class="text-sm inline-flex items-center gap-2"><i class="ion-md-pricetag"></i><b>#@Filter.Tag</b></p>
}
</div>
@code {
[Parameter, EditorRequired] public FeedFilter Filter { get; set; }
[Parameter] public List<ViewGroup> Groups { get; set; } = [];
[Parameter] public IEnumerable<NerdRow> Stats { get; set; } = [];
[Parameter] public bool IsComposing { get; set; }
[Parameter] public EventCallback OnCompose { get; set; }
/// <summary>Raised after Filter changed (tab, group or globe).</summary>
[Parameter] public EventCallback<FeedFilter> OnChanged { get; set; }
static readonly TimelineType[] Always =
[
TimelineType.Home, TimelineType.Local, TimelineType.Federation, TimelineType.Nearby, TimelineType.Groups, TimelineType.Direct,
TimelineType.Notifications, TimelineType.Favourites, TimelineType.Bookmarks
];
List<TimelineType> Types => Filter.Tag is { Length: > 0 } ? [.. Always, TimelineType.Tag] : [.. Always];
int ActiveIndex => Types.IndexOf(Filter.TimelineType);
ViewGroup SelectedGroup => Groups.FirstOrDefault(g => g.Id == Filter.GroupId);
protected override void OnInitialized() => IsLoading = false;
string TabName(TimelineType type) => type switch
{
TimelineType.Federation => Localizer["Federated"],
TimelineType.Tag => "#" + Filter.Tag,
_ => Localizer[type.ToString()]
};
async Task Select(int index)
{
Filter.TimelineType = Types[index];
if (Filter.TimelineType is TimelineType.Groups && SelectedGroup is null)
Filter.GroupId = Groups.FirstOrDefault()?.Id;
await OnChanged.InvokeAsync(Filter);
}
async Task SelectGroup(string groupId)
{
Filter.GroupId = groupId;
await OnChanged.InvokeAsync(Filter);
}
async Task ToggleGlobe()
{
Filter.ShowGlobe = !Filter.ShowGlobe;
await OnChanged.InvokeAsync(Filter);
}
}
+184
View File
@@ -0,0 +1,184 @@
@inherits LocalizableComponentBase
@* The feed's 3D globe (wwwroot/js/globe.js on the vendored globe.gl): it looks at the average place of the posts in
view and shows where a hovered post is. The posts' places go to the module in one call whenever they change; the
corner shows the camera and the frame rate, its tooltip the rest of the globe's numbers. *@
<div class="relative w-full h-full">
<div @ref="element" class="absolute inset-0" aria-label="@Localizer["Globe of the posts in view"]" role="img"></div>
<div class="absolute left-2 bottom-2 flex items-center gap-2 text-[10px] font-mono opacity-70 pointer-events-auto">
<NerdTip Heading="@Localizer["Globe"]" Rows="StatsRows()" Placement="DTooltipPlacement.Top" Align="DTooltipAlign.Start">
<span class="badge badge-ghost badge-xs gap-1">
<i class="ion-md-planet"></i>
@if (stats is { Error: null } live)
{
<span>@Fixed(live.Latitude), @Fixed(live.Longitude) · @Fixed(live.Altitude) · @live.Fps fps</span>
}
else if (stats?.Error is { Length: > 0 })
{
<span>@Localizer["The globe could not start."]</span>
}
else
{
<span>@Localizer["loading"]…</span>
}
</span>
</NerdTip>
</div>
</div>
@code {
[Inject] IJSRuntime JS { get; set; }
[Inject] InstanceService InstanceService { get; set; }
/// <summary>The id of the element that scrolls the feed's cards.</summary>
[Parameter, EditorRequired] public string ScrollContainerId { get; set; }
[Parameter] public List<FeedPost> Posts { get; set; } = [];
ElementReference element;
IJSObjectReference module;
PeriodicTimer statsTimer;
readonly CancellationTokenSource cancellation = new();
string sentFingerprint;
GlobeStats stats;
protected override void OnInitialized() => IsLoading = false;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
try
{
if (firstRender)
{
module = await JS.InvokeAsync<IJSObjectReference>("import", "./js/globe.js");
await module.InvokeVoidAsync("create", element, ScrollContainerId);
statsTimer = new(TimeSpan.FromSeconds(1));
_ = ReadStats(cancellation.Token);
}
await SendPosts();
}
catch (JSDisconnectedException)
{
}
catch (Exception ex) when (ex is JSException or InvalidOperationException)
{
await CascadingState.ProcessError(ex, $"{nameof(GlobePanel)}.{nameof(OnAfterRenderAsync)}");
}
}
/// <summary>Sends the located posts when they changed since the last call.</summary>
async Task SendPosts()
{
if (module is null)
return;
var located = Posts.Where(p => p.Location is not null).ToList();
var self = InstanceService.Known(InstanceService.SelfHost);
var fingerprint = string.Join('|', located.Select(p => $"{p.Key}:{p.Location.Latitude}:{p.Location.Longitude}")) + $"#{self?.Geo?.Latitude}";
if (fingerprint == sentFingerprint)
return;
sentFingerprint = fingerprint;
var points = located.Select(p =>
{
var server = InstanceService.Known(p.Host)?.Geo;
return new GlobePoint(p.Key, p.Location.Latitude, p.Location.Longitude, p.Location.Source.ToString().ToLowerInvariant(), p.Location.Label, p.Host,
server?.Latitude, server?.Longitude, p.Located ? p.RangeKm : null);
}).ToList();
await module.InvokeVoidAsync("setPosts", points, SelfPoint(self));
}
static GlobeSelf SelfPoint(ServerInfo self)
{
if (self?.Geo is { Latitude: { } latitude, Longitude: { } longitude } geo)
return new(latitude, longitude, $"PrivaPub · {geo.City ?? self.Host}", self.Host);
return CountryPoints.Of(self?.Geo?.Country) is { } country
? new(country.Latitude, country.Longitude, $"PrivaPub · {InstanceService.CountryName(self.Geo.Country)}", self.Host)
: null;
}
async Task ReadStats(CancellationToken cancellationToken)
{
try
{
while (await statsTimer.WaitForNextTickAsync(cancellationToken))
{
stats = await module.InvokeAsync<GlobeStats>("stats", cancellationToken);
await InvokeAsync(StateHasChanged);
}
}
catch (OperationCanceledException)
{
}
catch (JSDisconnectedException)
{
}
}
IEnumerable<NerdRow> StatsRows()
{
if (stats is null)
yield break;
yield return NerdRow.Of(Localizer["camera"], $"{Fixed(stats.Latitude)}, {Fixed(stats.Longitude)} @ {Fixed(stats.Altitude)}");
yield return NerdRow.Of(Localizer["in view"], $"{stats.VisibleLocated}/{stats.Visible} {Localizer["placed"]}");
yield return NerdRow.Of(Localizer["centre of view"], stats.CentroidLatitude is { } latitude ? $"{Fixed(latitude)}, {Fixed(stats.CentroidLongitude)}" : null);
yield return NerdRow.Of(Localizer["spread"], stats.SpreadKm > 0 ? $"{stats.SpreadKm:N0} km" : null);
yield return NerdRow.Of(Localizer["points"], $"{stats.Points} ({stats.Posts} {Localizer["posts"]}, {stats.Servers} {Localizer["servers"]})");
yield return NerdRow.Of(Localizer["hovered"], stats.Hovered is { } hovered ? $"{hovered} ({stats.Arcs} {Localizer["arcs"]}, {stats.Rings} {Localizer["rings"]})" : null);
yield return NerdRow.Of("fps", stats.Paused ? Localizer["paused"] : stats.Fps.ToString());
yield return NerdRow.Of(Localizer["auto-rotate"], stats.AutoRotate);
yield return NerdRow.Of(Localizer["texture"], stats.Texture is { } texture ? $"{texture} 4096×2048" : null);
yield return NerdRow.Of("WebGL", stats.Renderer);
yield return NerdRow.Of(Localizer["error"], stats.Error);
}
static string Fixed(double? value) => value?.ToString("0.##", System.Globalization.CultureInfo.InvariantCulture) ?? "–";
public override async ValueTask DisposeAsync()
{
await cancellation.CancelAsync();
cancellation.Dispose();
statsTimer?.Dispose();
try
{
if (module is not null)
{
await module.InvokeVoidAsync("dispose");
await module.DisposeAsync();
}
}
catch (JSDisconnectedException)
{
}
await base.DisposeAsync();
}
sealed record GlobePoint(string Key, double Lat, double Lng, string Src, string Label, string Host, double? ServerLat, double? ServerLng, double? Range);
sealed record GlobeSelf(double Lat, double Lng, string Label, string Host);
sealed class GlobeStats
{
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public double? Altitude { get; set; }
public int Visible { get; set; }
public int VisibleLocated { get; set; }
public double? CentroidLatitude { get; set; }
public double? CentroidLongitude { get; set; }
public double SpreadKm { get; set; }
public int Points { get; set; }
public int Posts { get; set; }
public int Servers { get; set; }
public int Fps { get; set; }
public string Renderer { get; set; }
public string Texture { get; set; }
public bool AutoRotate { get; set; }
public bool Paused { get; set; }
public string Hovered { get; set; }
public int Arcs { get; set; }
public int Rings { get; set; }
public string Error { get; set; }
}
}
+57
View File
@@ -0,0 +1,57 @@
using System.Globalization;
namespace decePubClient.Components.Nerd;
/// <summary>One line of a NerdTip; a row without a value is not shown.</summary>
public sealed record NerdRow(string Label, string Value)
{
public static NerdRow Of(string label, object value) => new(label, value switch
{
null => null,
DateTime time => Time(time),
double number => number.ToString("0.###", CultureInfo.InvariantCulture),
bool flag => flag ? "yes" : "no",
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
_ => value.ToString()
});
/// <summary>A UTC time to the millisecond, as PrivaPub records it.</summary>
public static string Time(DateTime time) =>
DateTime.SpecifyKind(time, time.Kind == DateTimeKind.Unspecified ? DateTimeKind.Utc : time.Kind).ToUniversalTime()
.ToString("yyyy-MM-dd HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
/// <summary>A duration the way a person reads it: 850 ms, 12.4 s, 3 min 5 s, 2 h 10 min, 4 d 3 h.</summary>
public static string Duration(TimeSpan span)
{
var sign = span < TimeSpan.Zero ? "-" : string.Empty;
span = span.Duration();
return sign + (span.TotalSeconds switch
{
< 1 => $"{span.TotalMilliseconds:0} ms",
< 60 => $"{span.TotalSeconds.ToString("0.0", CultureInfo.InvariantCulture)} s",
< 3600 => $"{span.Minutes} min {span.Seconds} s",
< 86400 => $"{(int)span.TotalHours} h {span.Minutes} min",
_ => $"{(int)span.TotalDays} d {span.Hours} h"
});
}
/// <summary>A byte count: 912 B, 14.2 KiB, 3.1 MiB.</summary>
public static string Bytes(long? bytes) => bytes switch
{
null => null,
< 1024 => $"{bytes} B",
< 1024 * 1024 => $"{(bytes.Value / 1024d).ToString("0.0", CultureInfo.InvariantCulture)} KiB",
_ => $"{(bytes.Value / 1048576d).ToString("0.0", CultureInfo.InvariantCulture)} MiB"
};
/// <summary>The great-circle distance between two points in kilometres (haversine, Earth radius 6371 km).</summary>
public static double Kilometres(double latitude1, double longitude1, double latitude2, double longitude2)
{
const double radius = 6371;
double Radians(double degrees) => degrees * Math.PI / 180;
var dLatitude = Radians(latitude2 - latitude1);
var dLongitude = Radians(longitude2 - longitude1);
var a = Math.Pow(Math.Sin(dLatitude / 2), 2) + Math.Cos(Radians(latitude1)) * Math.Cos(Radians(latitude2)) * Math.Pow(Math.Sin(dLongitude / 2), 2);
return 2 * radius * Math.Asin(Math.Min(1, Math.Sqrt(a)));
}
}
+49
View File
@@ -0,0 +1,49 @@
@inherits LocalizableComponentBase
@* Nerd stats on hover or focus: a DTooltip whose content is a monospace list of label/value rows. OnOpen runs on the
first hover or focus, for stats read on demand (a post's provenance); rows with no value are left out. *@
<DTooltip Placement="Placement" Align="Align" class="@Class" TipContent="Body" @onmouseenter="Open" @onfocusin="Open">
@ChildContent
</DTooltip>
@code {
[Parameter] public RenderFragment ChildContent { get; set; }
[Parameter] public string Heading { get; set; }
[Parameter] public IEnumerable<NerdRow> Rows { get; set; } = [];
/// <summary>Shown under the rows while OnOpen's work runs.</summary>
[Parameter] public bool Pending { get; set; }
[Parameter] public EventCallback OnOpen { get; set; }
[Parameter] public DTooltipPlacement Placement { get; set; }
[Parameter] public DTooltipAlign Align { get; set; }
[Parameter] public string Class { get; set; }
bool opened;
protected override void OnInitialized() => IsLoading = false;
async Task Open()
{
if (opened || !OnOpen.HasDelegate)
return;
opened = true;
await OnOpen.InvokeAsync();
}
RenderFragment Body => @<div class="nerd-stats flex flex-col gap-1 text-left font-mono text-[11px] leading-tight max-w-80">
@if (Heading is { Length: > 0 })
{
<p class="font-bold opacity-80">@Heading</p>
}
<dl class="grid grid-cols-[auto_minmax(0,1fr)] gap-x-2 gap-y-0.5">
@foreach (var row in Rows.Where(row => !string.IsNullOrEmpty(row.Value)))
{
<dt class="opacity-60 whitespace-nowrap">@row.Label</dt>
<dd class="break-all">@row.Value</dd>
}
</dl>
@if (Pending)
{
<p class="opacity-60">@Localizer["loading"]…</p>
}
</div>;
}