feat: suspense boundaries, streaming sidebar, N+1 fix for top-friends
Some checks failed
lint / lint (push) Has been cancelled
test / unit (push) Has been cancelled
test / integration (push) Has been cancelled
lint / lint (pull_request) Failing after 5m3s
test / unit (pull_request) Successful in 16m12s
test / integration (pull_request) Failing after 17m8s

- Backend: top-friends endpoint returns Vec<UserResponse> (JOIN already existed, handler was discarding data)
- Frontend: TopFriends self-contained — fetches own data via cookies, no more N+1 getUserProfile calls
- Frontend: sidebar (TopFriends, PopularTags, UsersCount) wrapped in Suspense — feed renders immediately
- Frontend: TagsSkeleton + CountSkeleton added to loading-skeleton.tsx
- Frontend: loading.tsx skeleton files added for feed, tags, search, and thread pages
This commit is contained in:
2026-05-16 02:18:51 +02:00
11 changed files with 127 additions and 83 deletions

View File

@@ -75,6 +75,12 @@ pub struct NotificationResponse {
pub created_at: DateTime<Utc>, pub created_at: DateTime<Utc>,
} }
#[derive(Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TopFriendsResponse {
pub top_friends: Vec<UserResponse>,
}
#[derive(Serialize, utoipa::ToSchema)] #[derive(Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct ErrorResponse { pub struct ErrorResponse {

View File

@@ -4,6 +4,8 @@ use crate::{
state::AppState, state::AppState,
}; };
use api_types::requests::SetTopFriendsRequest; use api_types::requests::SetTopFriendsRequest;
use api_types::responses::TopFriendsResponse;
use crate::handlers::auth::to_user_response;
use application::use_cases::profile::{get_top_friends, get_user_by_username, set_top_friends}; use application::use_cases::profile::{get_top_friends, get_user_by_username, set_top_friends};
use application::use_cases::social::*; use application::use_cases::social::*;
use axum::{ use axum::{
@@ -155,15 +157,17 @@ pub async fn put_top_friends(
set_top_friends(&*d.top_friends, &uid, ids).await?; set_top_friends(&*d.top_friends, &uid, ids).await?;
Ok(StatusCode::NO_CONTENT) Ok(StatusCode::NO_CONTENT)
} }
#[utoipa::path(get, path = "/users/{username}/top-friends", params(("username" = String, Path, description = "Username")), responses((status = 200, description = "Top friends list")))] #[utoipa::path(get, path = "/users/{username}/top-friends",
params(("username" = String, Path, description = "Username")),
responses((status = 200, description = "Top friends list", body = TopFriendsResponse)))]
pub async fn get_top_friends_handler( pub async fn get_top_friends_handler(
Deps(d): Deps<SocialDeps>, Deps(d): Deps<SocialDeps>,
Path(username): Path<String>, Path(username): Path<String>,
) -> Result<Json<serde_json::Value>, ApiError> { ) -> Result<Json<TopFriendsResponse>, ApiError> {
let user = get_user_by_username(&*d.users, &username).await?; let user = get_user_by_username(&*d.users, &username).await?;
let friends = get_top_friends(&*d.top_friends, &user.id).await?; let friends = get_top_friends(&*d.top_friends, &user.id).await?;
let usernames: Vec<&str> = friends.iter().map(|(_, u)| u.username.as_str()).collect(); let top_friends = friends.iter().map(|(_, u)| to_user_response(u)).collect();
Ok(Json(serde_json::json!({ "topFriends": usernames }))) Ok(Json(TopFriendsResponse { top_friends }))
} }
#[cfg(test)] #[cfg(test)]

View File

@@ -0,0 +1,20 @@
import { ThoughtSkeleton } from "@/components/loading-skeleton";
export default function FeedLoading() {
return (
<div className="container mx-auto max-w-6xl p-4 sm:p-6">
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
<aside className="hidden lg:block lg:col-span-1" />
<main className="col-span-1 lg:col-span-2 space-y-6">
<div className="h-10 w-32 bg-muted rounded animate-pulse mb-6" />
<div className="space-y-4">
<ThoughtSkeleton />
<ThoughtSkeleton />
<ThoughtSkeleton />
</div>
</main>
<aside className="hidden lg:block lg:col-span-1" />
</div>
</div>
);
}

View File

@@ -1,12 +1,6 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { import { getFeed, getMe, Me } from "@/lib/api";
getFeed,
getFriends,
getMe,
getTopFriends,
Me,
} from "@/lib/api";
import { ThoughtForm } from "@/components/thought-form"; import { ThoughtForm } from "@/components/thought-form";
import { EmptyState } from "@/components/empty-state"; import { EmptyState } from "@/components/empty-state";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -16,9 +10,10 @@ import { ThoughtThread } from "@/components/thought-thread";
import { buildThoughtThreads } from "@/lib/utils"; import { buildThoughtThreads } from "@/lib/utils";
import { TopFriends } from "@/components/top-friends"; import { TopFriends } from "@/components/top-friends";
import { UsersCount } from "@/components/users-count"; import { UsersCount } from "@/components/users-count";
import { PaginationNav } from "@/components/pagination-nav"; import { PaginationNav } from "@/components/pagination-nav";
import { redirect } from "next/navigation"; import { redirect } from "next/navigation";
import { Suspense } from "react";
import { ProfileSkeleton, TagsSkeleton, CountSkeleton } from "@/components/loading-skeleton";
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Home", title: "Home",
@@ -61,18 +56,26 @@ async function FeedPage({
const { items: allThoughts, totalPages } = feedData!; const { items: allThoughts, totalPages } = feedData!;
const thoughtThreads = buildThoughtThreads(allThoughts); const thoughtThreads = buildThoughtThreads(allThoughts);
const friends = (await getFriends(token)).users.map((user) => user.username); const sidebar = (
const topFriendsData = me <>
? await getTopFriends(me.username, token).catch(() => ({ topFriends: [] })) <Suspense fallback={<ProfileSkeleton />}>
: { topFriends: [] }; <TopFriends username={me.username} />
const shouldDisplayTopFriends = topFriendsData.topFriends.length > 0; </Suspense>
<Suspense fallback={<TagsSkeleton />}>
<PopularTags />
</Suspense>
<Suspense fallback={<CountSkeleton />}>
<UsersCount />
</Suspense>
</>
);
return ( return (
<div className="container mx-auto max-w-6xl p-4 sm:p-6"> <div className="container mx-auto max-w-6xl p-4 sm:p-6">
<div className="grid grid-cols-1 lg:grid-cols-4 gap-8"> <div className="grid grid-cols-1 lg:grid-cols-4 gap-8">
<aside className="hidden lg:block lg:col-span-1"> <aside className="hidden lg:block lg:col-span-1">
<div className="sticky top-20 space-y-6 glass-effect glossy-effect bottom rounded-md p-4"> <div className="sticky top-20 space-y-6 glass-effect glossy-effect bottom rounded-md p-4">
<h2 className="text-lg font-semibold">Filters & Sorting</h2> <h2 className="text-lg font-semibold">Filters &amp; Sorting</h2>
<p className="text-sm text-muted-foreground">Coming soon...</p> <p className="text-sm text-muted-foreground">Coming soon...</p>
</div> </div>
</aside> </aside>
@@ -84,14 +87,7 @@ async function FeedPage({
<ThoughtForm /> <ThoughtForm />
<div className="block lg:hidden space-y-6"> <div className="block lg:hidden space-y-6">
<PopularTags /> {sidebar}
{shouldDisplayTopFriends && (
<TopFriends mode="top-friends" usernames={topFriendsData.topFriends} />
)}
{!shouldDisplayTopFriends && token && friends.length > 0 && (
<TopFriends mode="friends" usernames={friends || []} />
)}
<UsersCount />
</div> </div>
<div className="space-y-6"> <div className="space-y-6">
@@ -115,14 +111,7 @@ async function FeedPage({
<aside className="hidden lg:block lg:col-span-1"> <aside className="hidden lg:block lg:col-span-1">
<div className="sticky top-20 space-y-6"> <div className="sticky top-20 space-y-6">
<PopularTags /> {sidebar}
{shouldDisplayTopFriends && (
<TopFriends mode="top-friends" usernames={topFriendsData.topFriends} />
)}
{!shouldDisplayTopFriends && token && friends.length > 0 && (
<TopFriends mode="friends" usernames={friends || []} />
)}
<UsersCount />
</div> </div>
</aside> </aside>
</div> </div>

View File

@@ -0,0 +1,12 @@
import { ThoughtSkeleton } from "@/components/loading-skeleton";
export default function SearchLoading() {
return (
<div className="container mx-auto max-w-2xl p-4 sm:p-6 space-y-4">
<div className="h-8 w-48 bg-muted rounded animate-pulse" />
<ThoughtSkeleton />
<ThoughtSkeleton />
<ThoughtSkeleton />
</div>
);
}

View File

@@ -0,0 +1,12 @@
import { ThoughtSkeleton } from "@/components/loading-skeleton";
export default function TagLoading() {
return (
<div className="container mx-auto max-w-2xl p-4 sm:p-6 space-y-4">
<div className="h-8 w-40 bg-muted rounded animate-pulse" />
<ThoughtSkeleton />
<ThoughtSkeleton />
<ThoughtSkeleton />
</div>
);
}

View File

@@ -0,0 +1,13 @@
import { ThoughtSkeleton } from "@/components/loading-skeleton";
export default function ThoughtLoading() {
return (
<div className="container mx-auto max-w-2xl p-4 sm:p-6 space-y-4">
<ThoughtSkeleton />
<div className="pl-6 border-l-2 border-primary border-dashed space-y-4">
<ThoughtSkeleton />
<ThoughtSkeleton />
</div>
</div>
);
}

View File

@@ -5,7 +5,6 @@ import {
getMe, getMe,
getRemoteFollowers, getRemoteFollowers,
getRemoteFollowing, getRemoteFollowing,
getTopFriends,
getUserProfile, getUserProfile,
getUserThoughts, getUserThoughts,
Me, Me,
@@ -52,6 +51,8 @@ import { notFound } from "next/navigation";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
import { FollowButton } from "@/components/follow-button"; import { FollowButton } from "@/components/follow-button";
import { TopFriends } from "@/components/top-friends"; import { TopFriends } from "@/components/top-friends";
import { Suspense } from "react";
import { ProfileSkeleton } from "@/components/loading-skeleton";
import { buildThoughtThreads } from "@/lib/utils"; import { buildThoughtThreads } from "@/lib/utils";
import { ThoughtThread } from "@/components/thought-thread"; import { ThoughtThread } from "@/components/thought-thread";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
@@ -127,15 +128,6 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
const fediverseHandle = const fediverseHandle =
user.local && apiDomain ? `@${user.username}@${apiDomain}` : null; user.local && apiDomain ? `@${user.username}@${apiDomain}` : null;
// Show who the profile owner follows (uses the already-fetched followingResult).
const friends =
followingResult.status === "fulfilled"
? followingResult.value.items.map((u) => u.username)
: [];
const topFriendsData = await getTopFriends(username, token).catch(() => ({ topFriends: [] }));
const shouldDisplayTopFriends = topFriendsData.topFriends.length > 0;
return ( return (
<div id={`profile-page-${user.username}`}> <div id={`profile-page-${user.username}`}>
{user.customCss && ( {user.customCss && (
@@ -252,10 +244,9 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
</div> </div>
</Card> </Card>
{shouldDisplayTopFriends && ( <Suspense fallback={<ProfileSkeleton />}>
<TopFriends mode="top-friends" usernames={topFriendsData.topFriends} /> <TopFriends username={user.username} />
)} </Suspense>
{token && <TopFriends mode="friends" usernames={friends || []} />}
</div> </div>
</aside> </aside>

View File

@@ -32,3 +32,26 @@ export function ProfileSkeleton() {
</Card> </Card>
) )
} }
export function TagsSkeleton() {
return (
<Card>
<CardContent className="pt-4 space-y-2">
<Skeleton className="h-4 w-24 mb-3" />
{[...Array(5)].map((_, i) => (
<Skeleton key={i} className="h-6 w-full rounded-full" />
))}
</CardContent>
</Card>
)
}
export function CountSkeleton() {
return (
<Card>
<CardContent className="pt-4 pb-4">
<Skeleton className="h-6 w-32" />
</CardContent>
</Card>
)
}

View File

@@ -1,51 +1,25 @@
import Link from "next/link"; import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"; import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { UserAvatar } from "./user-avatar"; import { UserAvatar } from "./user-avatar";
import { getUserProfile, User } from "@/lib/api"; import { getTopFriends } from "@/lib/api";
import { cookies } from "next/headers"; import { cookies } from "next/headers";
interface TopFriendsProps { interface TopFriendsProps {
mode: "friends" | "top-friends"; username: string;
usernames: string[];
} }
export async function TopFriends({ export async function TopFriends({ username }: TopFriendsProps) {
mode = "top-friends",
usernames,
}: TopFriendsProps) {
const token = (await cookies()).get("auth_token")?.value ?? null; const token = (await cookies()).get("auth_token")?.value ?? null;
const data = await getTopFriends(username, token).catch(() => ({ topFriends: [] }));
const friends = data.topFriends;
if (usernames.length === 0) { if (friends.length === 0) return null;
return (
<Card className="p-4">
<CardHeader className="p-0 pb-2">
<CardTitle className="text-lg text-shadow-md">Top Friends</CardTitle>
</CardHeader>
<CardContent className="p-0">
<p className="text-sm text-muted-foreground">
No top friends to display.
</p>
</CardContent>
</Card>
);
}
const friendsResults = await Promise.allSettled(
usernames.map((username) => getUserProfile(username, token))
);
const friends = friendsResults
.filter(
(result): result is PromiseFulfilledResult<User> =>
result.status === "fulfilled"
)
.map((result) => result.value);
return ( return (
<Card id="top-friends" className="p-4"> <Card id="top-friends" className="p-4">
<CardHeader id="top-friends__header" className="p-0 pb-2"> <CardHeader id="top-friends__header" className="p-0 pb-2">
<CardTitle id="top-friends__title" className="text-lg text-shadow-md"> <CardTitle id="top-friends__title" className="text-lg text-shadow-md">
{mode === "top-friends" ? "Top Friends" : "Friends"} Top Friends
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent id="top-friends__content" className="p-0"> <CardContent id="top-friends__content" className="p-0">
@@ -59,7 +33,7 @@ export async function TopFriends({
<UserAvatar src={friend.avatarUrl} alt={friend.username} /> <UserAvatar src={friend.avatarUrl} alt={friend.username} />
<span <span
id={`top-friends__name-${friend.id}`} id={`top-friends__name-${friend.id}`}
className="text-xs truncate w-full group-hover:underline font-medium text-shadow-sm" className="text-xs truncate w-full font-medium text-shadow-sm"
> >
{friend.displayName || friend.username} {friend.displayName || friend.username}
</span> </span>

View File

@@ -232,7 +232,7 @@ export const getTopFriends = (username: string, token: string | null) =>
apiFetch( apiFetch(
`/users/${username}/top-friends`, `/users/${username}/top-friends`,
{ next: { tags: [`profile:${username}`] } }, { next: { tags: [`profile:${username}`] } },
z.object({ topFriends: z.array(z.string()) }), z.object({ topFriends: z.array(UserSchema) }),
token token
); );