Compare commits

...

23 Commits

Author SHA1 Message Date
78ee7b9388 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
2026-05-16 02:18:51 +02:00
f135e4d583 feat(frontend): loading.tsx skeletons for feed, tags, search, and thread pages 2026-05-16 02:16:45 +02:00
42baf3fe3c perf(frontend): stream sidebar via Suspense — feed renders immediately; sidebar loads async 2026-05-16 02:14:36 +02:00
e86f07ef34 refactor(frontend): TopFriends self-contained — fetches own data, no N+1 2026-05-16 02:11:05 +02:00
98d3fdb832 feat(frontend): TagsSkeleton and CountSkeleton for sidebar Suspense fallbacks 2026-05-16 02:10:55 +02:00
2c3e7934b8 fix(frontend): getTopFriends schema returns UserSchema[] not string[] 2026-05-16 02:10:37 +02:00
29e4af26d8 fix(api): top-friends endpoint returns full UserResponse — eliminates frontend N+1 2026-05-16 02:08:22 +02:00
57b1bfc447 feat(api-types): TopFriendsResponse with Vec<UserResponse> 2026-05-16 02:06:06 +02:00
28521cc9ed docs: suspense + streaming implementation plan 2026-05-16 02:03:52 +02:00
7f10349c76 docs: suspense + streaming design spec 2026-05-16 01:59:16 +02:00
e2210ba0f0 feat(frontend): performance + DRY + composition overhaul
- Tagged fetch cache: all GET fetches have next.tags for targeted invalidation
- Server Actions (thoughts, social, profile) replace scattered router.refresh()
- Eliminated author profile waterfall — use thought.author directly
- useOptimistic on FollowButton for instant feedback
- ThoughtForm unifies PostThoughtForm and ReplyForm
- EmptyState and LoadingSkeleton shared primitives
- RemoteUserProfile split into ProfileCard + Connections
2026-05-15 23:21:51 +02:00
448cd506eb fix(frontend): remove dead activeTab state; guard URL hostname parse 2026-05-15 20:21:05 +02:00
c1c9539978 refactor(frontend): split RemoteUserProfile into ProfileCard + Connections 2026-05-15 20:16:39 +02:00
688e7b0018 refactor(frontend): FollowButton useOptimistic + Server Action; edit-profile-form Server Action 2026-05-15 20:08:49 +02:00
71233f069e fix(frontend): ThoughtForm — safe onSuccess?.() on cancel, dedupe reply textarea classes 2026-05-15 20:07:27 +02:00
d450a1d8d8 refactor(frontend): EmptyState + LoadingSkeleton primitives; unified ThoughtForm replaces PostThoughtForm and ReplyForm 2026-05-15 20:01:00 +02:00
dadfe04934 perf(frontend): eliminate author profile waterfall — use thought.author directly 2026-05-15 19:47:06 +02:00
9ecbde019d feat(frontend): Server Actions for thought, social, and profile mutations 2026-05-15 19:43:10 +02:00
ed789c6170 fix(frontend): tag remaining GET fetches for cache invalidation 2026-05-15 19:41:50 +02:00
091c3a4706 feat(frontend): add next.tags cache support to apiFetch; tag all GET fetches 2026-05-15 19:38:24 +02:00
fe610c8b6f fix(frontend): tag getTopFriends fetch 2026-05-15 19:30:17 +02:00
4f92c16c0f docs: frontend overhaul implementation plan 2026-05-15 19:24:28 +02:00
896d2d86c9 docs: frontend overhaul design spec 2026-05-15 19:17:31 +02:00
35 changed files with 11852 additions and 820 deletions

View File

@@ -75,6 +75,12 @@ pub struct NotificationResponse {
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)]
#[serde(rename_all = "camelCase")]
pub struct ErrorResponse {

View File

@@ -4,6 +4,8 @@ use crate::{
state::AppState,
};
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::social::*;
use axum::{
@@ -155,15 +157,17 @@ pub async fn put_top_friends(
set_top_friends(&*d.top_friends, &uid, ids).await?;
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(
Deps(d): Deps<SocialDeps>,
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 friends = get_top_friends(&*d.top_friends, &user.id).await?;
let usernames: Vec<&str> = friends.iter().map(|(_, u)| u.username.as_str()).collect();
Ok(Json(serde_json::json!({ "topFriends": usernames })))
let top_friends = friends.iter().map(|(_, u)| to_user_response(u)).collect();
Ok(Json(TopFriendsResponse { top_friends }))
}
#[cfg(test)]

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,579 @@
# Suspense Boundaries & Streaming Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Stream the feed page immediately while sidebar widgets load independently, and fix the N+1 top-friends profile fetch by having the backend return full user objects in one query.
**Architecture:** The `TopFriendRepository::list_for_user` already JOINs users — the backend just discards the user data and returns only usernames. We fix the handler to return `Vec<UserResponse>`. Frontend: `TopFriends` becomes self-contained (fetches its own data via cookies, no props from page), wrapped in `<Suspense>`. `app/page.tsx` drops all sidebar awaits, reducing critical-path work to two parallel calls.
**Tech Stack:** Rust/Axum (backend), Next.js 15 App Router, React 19 Suspense, Tailwind CSS, shadcn/ui
---
## Key Facts
- `TopFriendRepository::list_for_user` already returns `Vec<(TopFriend, User)>` — the JOIN with the users table is done. The handler just discards the `User` data.
- `to_user_response(u: &User) -> UserResponse` lives in `crates/presentation/src/handlers/auth.rs` as `pub fn` — import it where needed.
- Auth token in frontend server components: `(await cookies()).get("auth_token")?.value ?? null` via `next/headers`.
- Baseline test suite: `cargo test` (148 tests) in the backend; `npx tsc --noEmit` in `thoughts-frontend/`.
---
## File Map
| File | Change |
|---|---|
| `crates/api-types/src/responses.rs` | Add `TopFriendsResponse { top_friends: Vec<UserResponse> }` |
| `crates/presentation/src/handlers/social.rs` | Return `TopFriendsResponse` instead of `{ topFriends: usernames }` |
| `thoughts-frontend/lib/api.ts` | Update `getTopFriends` schema to `z.array(UserSchema)` |
| `thoughts-frontend/components/loading-skeleton.tsx` | Add `TagsSkeleton`, `CountSkeleton` |
| `thoughts-frontend/components/top-friends.tsx` | Self-contained: fetches own data, no `usernames` prop |
| `thoughts-frontend/app/page.tsx` | Strip `getFriends`/`getTopFriends`/`shouldDisplayTopFriends`; add Suspense |
| `thoughts-frontend/app/loading.tsx` | New — feed page skeleton |
| `thoughts-frontend/app/tags/[tagName]/loading.tsx` | New |
| `thoughts-frontend/app/search/loading.tsx` | New |
| `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx` | New |
---
## Task 1: Add `TopFriendsResponse` to api-types
**Files:**
- Modify: `crates/api-types/src/responses.rs`
- [ ] **Step 1: Add the response struct**
In `crates/api-types/src/responses.rs`, after the `NotificationResponse` block, add:
```rust
#[derive(Serialize, utoipa::ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct TopFriendsResponse {
pub top_friends: Vec<UserResponse>,
}
```
- [ ] **Step 2: Verify it compiles**
```bash
cargo build -p api-types
```
Expected: Compiles with no errors.
- [ ] **Step 3: Commit**
```bash
git add crates/api-types/src/responses.rs
git commit -m "feat(api-types): TopFriendsResponse with Vec<UserResponse>"
```
---
## Task 2: Update `get_top_friends_handler` to return full user objects
**Files:**
- Modify: `crates/presentation/src/handlers/social.rs`
- [ ] **Step 1: Read the current handler**
Current code (around line 159167 in `social.rs`):
```rust
pub async fn get_top_friends_handler(
Deps(d): Deps<SocialDeps>,
Path(username): Path<String>,
) -> Result<Json<serde_json::Value>, ApiError> {
let user = get_user_by_username(&*d.users, &username).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();
Ok(Json(serde_json::json!({ "topFriends": usernames })))
}
```
`friends` is already `Vec<(TopFriend, User)>` — the user data is there.
- [ ] **Step 2: Add import and update the handler**
Add to the imports at the top of `social.rs`:
```rust
use api_types::responses::TopFriendsResponse;
use crate::handlers::auth::to_user_response;
```
Replace the handler body:
```rust
#[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(
Deps(d): Deps<SocialDeps>,
Path(username): Path<String>,
) -> Result<Json<TopFriendsResponse>, ApiError> {
let user = get_user_by_username(&*d.users, &username).await?;
let friends = get_top_friends(&*d.top_friends, &user.id).await?;
let top_friends = friends.iter().map(|(_, u)| to_user_response(u)).collect();
Ok(Json(TopFriendsResponse { top_friends }))
}
```
- [ ] **Step 3: Run backend tests**
```bash
cargo test
```
Expected: 148 tests pass (same as before — no test exercises the response shape directly).
- [ ] **Step 4: Smoke-test the endpoint manually (optional)**
```bash
curl -s -H "Authorization: Bearer <your_token>" http://localhost:3001/users/me/top-friends | python3 -m json.tool
```
Expected: `{ "topFriends": [ { "id": "...", "username": "...", "avatarUrl": "...", ... } ] }`
- [ ] **Step 5: Commit**
```bash
git add crates/presentation/src/handlers/social.rs
git commit -m "fix(api): top-friends endpoint returns full UserResponse — eliminates frontend N+1"
```
---
## Task 3: Update frontend `getTopFriends` Zod schema
**Files:**
- Modify: `thoughts-frontend/lib/api.ts`
- [ ] **Step 1: Find and update `getTopFriends`**
In `lib/api.ts`, find `getTopFriends` (around line 232). Current:
```ts
export const getTopFriends = (username: string, token: string | null) =>
apiFetch(
`/users/${username}/top-friends`,
{ next: { tags: [`profile:${username}`] } },
z.object({ topFriends: z.array(z.string()) }),
token
);
```
Replace with:
```ts
export const getTopFriends = (username: string, token: string | null) =>
apiFetch(
`/users/${username}/top-friends`,
{ next: { tags: [`profile:${username}`] } },
z.object({ topFriends: z.array(UserSchema) }),
token
);
```
`UserSchema` is already defined in the same file — no new import needed.
- [ ] **Step 2: Type-check**
```bash
cd thoughts-frontend && npx tsc --noEmit
```
Expected: 0 errors. (TypeScript will flag call sites that use `getTopFriends` and expect `string[]` — these are fixed in Task 4.)
If errors: note them, they'll be resolved in Task 4.
- [ ] **Step 3: Commit**
```bash
git add thoughts-frontend/lib/api.ts
git commit -m "fix(frontend): getTopFriends schema returns UserSchema[] not string[]"
```
---
## Task 4: Add `TagsSkeleton` and `CountSkeleton` to loading-skeleton.tsx
**Files:**
- Modify: `thoughts-frontend/components/loading-skeleton.tsx`
- [ ] **Step 1: Add the two new exports**
In `thoughts-frontend/components/loading-skeleton.tsx`, append after the existing exports:
```tsx
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>
)
}
```
`Card`, `CardContent`, and `Skeleton` are already imported in the file.
- [ ] **Step 2: Type-check**
```bash
cd thoughts-frontend && npx tsc --noEmit
```
Expected: 0 errors.
- [ ] **Step 3: Commit**
```bash
git add thoughts-frontend/components/loading-skeleton.tsx
git commit -m "feat(frontend): TagsSkeleton and CountSkeleton for sidebar Suspense fallbacks"
```
---
## Task 5: Rewrite `TopFriends` to be self-contained
**Files:**
- Modify: `thoughts-frontend/components/top-friends.tsx`
- [ ] **Step 1: Replace the component**
Replace the entire file with:
```tsx
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { UserAvatar } from "./user-avatar";
import { getTopFriends } from "@/lib/api";
import { cookies } from "next/headers";
interface TopFriendsProps {
username: string;
}
export async function TopFriends({ username }: TopFriendsProps) {
const token = (await cookies()).get("auth_token")?.value ?? null;
const data = await getTopFriends(username, token).catch(() => ({ topFriends: [] }));
const friends = data.topFriends;
if (friends.length === 0) return null;
return (
<Card id="top-friends" className="p-4">
<CardHeader id="top-friends__header" className="p-0 pb-2">
<CardTitle id="top-friends__title" className="text-lg text-shadow-md">
Top Friends
</CardTitle>
</CardHeader>
<CardContent id="top-friends__content" className="p-0">
{friends.map((friend) => (
<Link
id={`top-friends__link-${friend.id}`}
href={`/users/${friend.username}`}
key={friend.id}
className="flex items-center gap-3 py-2 px-2 -mx-2 rounded-lg hover:bg-accent/50 transition-colors"
>
<UserAvatar src={friend.avatarUrl} alt={friend.username} />
<span
id={`top-friends__name-${friend.id}`}
className="text-xs truncate w-full font-medium text-shadow-sm"
>
{friend.displayName || friend.username}
</span>
</Link>
))}
</CardContent>
</Card>
);
}
```
Changes from old component:
- Props: was `{ mode, usernames: string[] }`, now `{ username: string }` — fetches its own data
- No more N+1 `getUserProfile` calls — renders `data.topFriends` (already `User[]`) directly
- `mode` prop removed — always shows "Top Friends" title (the "friends fallback" mode is dropped)
- Returns `null` if no top friends (sidebar just hides the widget)
- [ ] **Step 2: Type-check**
```bash
cd thoughts-frontend && npx tsc --noEmit
```
Expected: Errors at `app/page.tsx` call sites (still pass old props) — will be fixed in Task 6.
- [ ] **Step 3: Commit (even with type errors from call sites)**
```bash
git add thoughts-frontend/components/top-friends.tsx
git commit -m "refactor(frontend): TopFriends self-contained — fetches own data, no N+1"
```
---
## Task 6: Update `app/page.tsx` — strip blocking awaits + add Suspense
**Files:**
- Modify: `thoughts-frontend/app/page.tsx`
- [ ] **Step 1: Update imports**
Replace the current import block at the top of `app/page.tsx`:
```ts
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { getFeed, getMe, Me } from "@/lib/api";
import { ThoughtForm } from "@/components/thought-form";
import { EmptyState } from "@/components/empty-state";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { PopularTags } from "@/components/popular-tags";
import { ThoughtThread } from "@/components/thought-thread";
import { buildThoughtThreads } from "@/lib/utils";
import { TopFriends } from "@/components/top-friends";
import { UsersCount } from "@/components/users-count";
import { PaginationNav } from "@/components/pagination-nav";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { ProfileSkeleton, TagsSkeleton, CountSkeleton } from "@/components/loading-skeleton";
```
(Removed: `getFriends`, `getTopFriends`, `User`)
- [ ] **Step 2: Replace `FeedPage` function**
```tsx
async function FeedPage({
token,
searchParams,
}: {
token: string;
searchParams: { page?: string };
}) {
const page = parseInt(searchParams.page ?? "1", 10);
const [feedData, me] = await Promise.all([
getFeed(token, page).catch(() => null),
getMe(token).catch(() => null) as Promise<Me | null>,
]);
if (!feedData || !me) {
redirect("/login");
}
const { items: allThoughts, totalPages } = feedData!;
const thoughtThreads = buildThoughtThreads(allThoughts);
const sidebar = (
<>
<Suspense fallback={<ProfileSkeleton />}>
<TopFriends username={me.username} />
</Suspense>
<Suspense fallback={<TagsSkeleton />}>
<PopularTags />
</Suspense>
<Suspense fallback={<CountSkeleton />}>
<UsersCount />
</Suspense>
</>
);
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">
<div className="sticky top-20 space-y-6 glass-effect glossy-effect bottom rounded-md p-4">
<h2 className="text-lg font-semibold">Filters &amp; Sorting</h2>
<p className="text-sm text-muted-foreground">Coming soon...</p>
</div>
</aside>
<main className="col-span-1 lg:col-span-2 space-y-6">
<header className="mb-6">
<h1 className="text-3xl font-bold text-shadow-sm">Your Feed</h1>
</header>
<ThoughtForm />
<div className="block lg:hidden space-y-6">
{sidebar}
</div>
<div className="space-y-6">
{thoughtThreads.map((thought) => (
<ThoughtThread
key={thought.id}
thought={thought}
currentUser={me}
/>
))}
{thoughtThreads.length === 0 && (
<EmptyState message="Your feed is empty. Follow some users to see their thoughts!" />
)}
</div>
<PaginationNav
page={page}
totalPages={totalPages}
buildHref={(p) => `/?page=${p}`}
/>
</main>
<aside className="hidden lg:block lg:col-span-1">
<div className="sticky top-20 space-y-6">
{sidebar}
</div>
</aside>
</div>
</div>
);
}
```
- [ ] **Step 3: Type-check**
```bash
cd thoughts-frontend && npx tsc --noEmit
```
Expected: 0 errors.
- [ ] **Step 4: Commit**
```bash
git add thoughts-frontend/app/page.tsx
git commit -m "perf(frontend): stream sidebar via Suspense — feed renders immediately, sidebar loads async"
```
---
## Task 7: Add `loading.tsx` files for pages missing them
**Files:**
- Create: `thoughts-frontend/app/loading.tsx`
- Create: `thoughts-frontend/app/tags/[tagName]/loading.tsx`
- Create: `thoughts-frontend/app/search/loading.tsx`
- Create: `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx`
- [ ] **Step 1: Create `thoughts-frontend/app/loading.tsx`**
This matches the feed page layout (3-column grid with feed column visible):
```tsx
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>
);
}
```
- [ ] **Step 2: Create `thoughts-frontend/app/tags/[tagName]/loading.tsx`**
```tsx
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>
);
}
```
- [ ] **Step 3: Create `thoughts-frontend/app/search/loading.tsx`**
```tsx
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>
);
}
```
- [ ] **Step 4: Create `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx`**
```tsx
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>
);
}
```
- [ ] **Step 5: Type-check**
```bash
cd thoughts-frontend && npx tsc --noEmit
```
Expected: 0 errors.
- [ ] **Step 6: Commit**
```bash
git add thoughts-frontend/app/loading.tsx \
thoughts-frontend/app/tags \
thoughts-frontend/app/search/loading.tsx \
thoughts-frontend/app/thoughts
git commit -m "feat(frontend): loading.tsx skeletons for feed, tags, search, and thread pages"
```
---
## Final Verification
- [ ] `cargo test` — 148 tests pass
- [ ] `cd thoughts-frontend && npx tsc --noEmit` — 0 errors
- [ ] `grep -r "usernames" thoughts-frontend/components/top-friends.tsx` — 0 results (old prop gone)
- [ ] `grep -r "getFriends\|getTopFriends\|shouldDisplayTopFriends" thoughts-frontend/app/page.tsx` — 0 results
- [ ] `grep -r "Suspense" thoughts-frontend/app/page.tsx` — 3+ results (one per sidebar widget)

View File

@@ -0,0 +1,304 @@
# Frontend Overhaul Design
**Date:** 2026-05-15
**Status:** Approved
## Problem
The backend `/feed` endpoint responds in ~10ms, but the frontend renders the page noticeably later. Three root causes:
1. **Author profile waterfall** — every page that displays thoughts fetches N separate `getUserProfile` calls after the main feed query, sequentially. 4+ pages duplicate this pattern verbatim.
2. **Scattered cache invalidation** — 5 isolated `router.refresh()` calls with no shared abstraction. Full page re-render on every mutation regardless of what actually changed.
3. **Broken composition**`authorDetails: Map<string, {...}>` prop-drilled 4+ levels. Three components over 200 lines. Empty/loading states copy-pasted 4+ times each. `PostThoughtForm` and `ReplyForm` are near-identical duplicates.
## Approach
**Server Actions + `revalidateTag`** — idiomatic Next.js 15 + React 19 solution.
- Backend embeds author data in all response types → waterfall eliminated at the source
- Fetch cache tagged by data domain → mutations revalidate exactly what changed, not the whole page
- Server Actions replace client-side fetch + `router.refresh()` → one invalidation point per mutation
- `useOptimistic` (React 19) → instant UI feedback for toggle interactions
- Component splits and shared primitives → composition fixed
No new dependencies added.
---
## Section 1: Backend — Embed Author Data Everywhere
### New type in `crates/api-types/`
```rust
pub struct AuthorResponse {
pub id: Uuid,
pub username: String,
pub display_name: Option<String>,
pub avatar_url: Option<String>,
}
```
### Response types updated
| Response type | Change |
|---|---|
| `ThoughtResponse` | Add `author: AuthorResponse` |
| `NotificationResponse` | Add `actor: AuthorResponse` |
| `BoostResponse` / `LikeResponse` | Add `actor: AuthorResponse` if referencing a user |
### Architecture constraints
- Business logic stays in application use cases, not handlers.
- **Feed/list queries:** `PgFeedRepository` already joins the users table. `row_to_entry` populates author fields from the existing join — no extra queries.
- **Individual thought lookups:** Use cases that return a single thought compose `ThoughtRepository + UserReader` to produce a `ThoughtWithAuthor` output struct. The use case already takes both ports.
- **Handlers** only map: `ThoughtWithAuthor → ThoughtResponse { author: AuthorResponse }`. No DB access.
### Frontend impact
`lib/api.ts` Zod schemas updated to match. The `authorDetails: Map<string, {...}>` pattern, all `getUserProfile` calls inside page components, and all `Promise.all([...getUserProfile])` waterfalls are deleted.
---
## Section 2: Frontend — Tagged Fetch Cache
Replace bare `fetch()` calls with tagged Next.js fetch so `revalidateTag` can target them precisely.
### `apiFetch` signature addition
```ts
apiFetch(path, token, options?: RequestInit & { next?: NextFetchRequestConfig })
```
The `next` field passes through to `fetch()`. No new dependencies.
### Tag taxonomy
| Tag | Invalidated when |
|---|---|
| `feed` | thought posted, deleted, edited, boosted |
| `profile:{username}` | profile edited, follow/unfollow of that user |
| `thoughts:{id}` | thought edited, deleted, replied to |
| `tags:{name}` | new thought containing that tag |
| `notifications` | any interaction received |
### Usage
```ts
// lib/api.ts
const feed = await apiFetch('/feed', token, { next: { tags: ['feed'] } })
const profile = await apiFetch(`/users/${username}`, token, {
next: { tags: [`profile:${username}`] }
})
```
---
## Section 3: Mutation Layer — Server Actions
All mutations become Server Actions in `app/actions/`. Each action calls the backend, then revalidates exactly the affected tags.
### File layout
```
app/actions/
thoughts.ts — createThought, deleteThought, editThought
social.ts — followUser, unfollowUser, likeThought, boostThought
profile.ts — updateProfile
```
### Examples
```ts
// app/actions/thoughts.ts
'use server'
import { revalidateTag } from 'next/cache'
export async function createThought(formData: FormData) {
const token = await getToken()
await apiFetch('/thoughts', token, { method: 'POST', body: parseFormData(formData) })
revalidateTag('feed')
}
export async function deleteThought(thoughtId: string, authorUsername: string) {
const token = await getToken()
await apiFetch(`/thoughts/${thoughtId}`, token, { method: 'DELETE' })
revalidateTag('feed')
revalidateTag(`thoughts:${thoughtId}`)
revalidateTag(`profile:${authorUsername}`)
}
```
```ts
// app/actions/social.ts
'use server'
export async function followUser(username: string) {
const token = await getToken()
await apiFetch(`/users/${username}/follow`, token, { method: 'POST' })
revalidateTag(`profile:${username}`)
revalidateTag('feed')
}
export async function likeThought(thoughtId: string) {
const token = await getToken()
await apiFetch(`/thoughts/${thoughtId}/like`, token, { method: 'POST' })
revalidateTag(`thoughts:${thoughtId}`)
revalidateTag('feed')
}
```
### Migration
Components drop `router.refresh()` and the `useRouter` import entirely. They call the Server Action directly (or pass it as a prop). The `router` dependency disappears from all mutation components.
---
## Section 4: Optimistic Updates — `useOptimistic`
React 19's `useOptimistic` used for toggle interactions where latency is most noticeable: like, boost, follow.
### Like/boost (in `ThoughtCardActions`)
```tsx
'use client'
export function ThoughtActions({ thought }: { thought: ThoughtResponse }) {
const [optimisticLiked, addOptimisticLike] = useOptimistic(thought.liked_by_viewer)
const [optimisticLikes, addOptimisticCount] = useOptimistic(thought.likes_count)
async function handleLike() {
addOptimisticLike(!optimisticLiked)
addOptimisticCount(optimisticLiked ? optimisticLikes - 1 : optimisticLikes + 1)
await likeThought(thought.id)
}
return (
<button onClick={handleLike}>
{optimisticLiked ? '♥' : '♡'} {optimisticLikes}
</button>
)
}
```
### Follow button
```tsx
'use client'
export function FollowButton({ username, initialFollowing }: Props) {
const [optimisticFollowing, addOptimistic] = useOptimistic(initialFollowing)
async function handleFollow() {
addOptimistic(!optimisticFollowing)
await (optimisticFollowing ? unfollowUser(username) : followUser(username))
}
return <button onClick={handleFollow}>{optimisticFollowing ? 'Unfollow' : 'Follow'}</button>
}
```
**Scope:** optimistic updates for like, boost, follow only. `createThought` and `deleteThought` do not get optimistic treatment — tagged cache revalidation is fast enough.
---
## Section 5: Composition
### `ThoughtCard` split
```
components/thought-card/
index.tsx — assembles sub-components, no logic
header.tsx — avatar, username, display name, timestamp
body.tsx — content, hashtag links, content warning toggle
actions.tsx — like, boost, reply, delete; owns useOptimistic (client component)
```
Author data comes from `ThoughtResponse.author` directly. No `authorDetails` map, no prop drilling.
### Unified `ThoughtForm`
Replaces `PostThoughtForm` and `ReplyForm` (near-identical duplicates).
```tsx
// components/thought-form.tsx
type Props = {
action: (formData: FormData) => Promise<void> // Server Action passed in
placeholder?: string
replyTo?: string
}
```
Call sites:
```tsx
<ThoughtForm action={createThought} placeholder="What's on your mind?" />
<ThoughtForm action={replyToThought.bind(null, thoughtId)} replyTo={author} />
```
`PostThoughtForm` and `ReplyForm` files are deleted.
### Shared primitives
```tsx
// components/empty-state.tsx
export function EmptyState({ message }: { message: string }) { ... }
// components/loading-skeleton.tsx
export function ThoughtSkeleton() { ... }
export function ProfileSkeleton() { ... }
```
4 copy-pasted empty state blocks replaced by `<EmptyState message="No thoughts yet." />`. Repeated loading card JSX replaced by `<ThoughtSkeleton />`.
### `RemoteUserProfile` split
```
components/remote-user-profile/
index.tsx — tab state only (client)
profile-card.tsx — avatar, bio, stats (server)
connections.tsx — followers/following lists with Suspense boundary (client)
```
---
## Files Changed
### Backend (`crates/`)
| File | Change |
|---|---|
| `crates/api-types/src/responses.rs` | Add `AuthorResponse`; embed in `ThoughtResponse`, `NotificationResponse` |
| `crates/adapters/postgres/src/feed.rs` | Enrich `row_to_entry` with author columns from existing join |
| `crates/application/src/use_cases/thoughts.rs` | Return `ThoughtWithAuthor` from relevant use cases |
| `crates/presentation/src/handlers/thoughts.rs` | Map `ThoughtWithAuthor → ThoughtResponse`; remove secondary user fetches |
| `crates/presentation/src/handlers/feed.rs` | Same mapping update |
| `crates/presentation/src/handlers/notifications.rs` | Embed actor in notification responses |
### Frontend (`thoughts-frontend/`)
| File | Change |
|---|---|
| `lib/api.ts` | Add `next` option to `apiFetch`; update Zod schemas with `AuthorResponse` |
| `app/actions/thoughts.ts` | New — Server Actions for thought mutations |
| `app/actions/social.ts` | New — Server Actions for social interactions |
| `app/actions/profile.ts` | New — Server Actions for profile mutations |
| `app/page.tsx` | Remove author fetch waterfall; use tagged fetch |
| `app/users/[username]/page.tsx` | Same |
| `app/thoughts/[thoughtId]/page.tsx` | Same |
| `app/tags/[tagName]/page.tsx` | Same |
| `app/search/page.tsx` | Same |
| `components/thought-card/` | Split into header/body/actions |
| `components/thought-form.tsx` | New unified form |
| `components/post-thought-form.tsx` | Deleted |
| `components/reply-form.tsx` | Deleted |
| `components/empty-state.tsx` | New shared primitive |
| `components/loading-skeleton.tsx` | New shared primitive |
| `components/follow-button.tsx` | Remove `router.refresh()`; use Server Action + `useOptimistic` |
| `components/remote-user-profile/` | Split into profile-card/connections |
---
## What This Does Not Cover
- Streaming / Suspense boundaries between sidebar widgets (future, lower priority once waterfall is gone)
- Search result caching (search is user-input-driven; less predictable tag invalidation)
- Pagination beyond the current page-based approach

View File

@@ -0,0 +1,173 @@
# Suspense Boundaries & Streaming Design
**Date:** 2026-05-16
**Status:** Approved
## Problem
The home feed page (`app/page.tsx`) blocks rendering until all data is ready:
- `getFeed` + `getMe` — critical path, fine
- `getFriends` + `getTopFriends` — sidebar data, runs **after** the feed fetch, adds 150500ms before any HTML ships
- `PopularTags`, `TopFriends`, `UsersCount` are async server components that all resolve before the page renders
Additionally, `TopFriends` has an N+1 problem: it fetches a list of usernames then makes N separate `getUserProfile` calls in parallel (~500ms2s+ for 510 friends).
No React Suspense boundaries exist anywhere in the app. `ThoughtSkeleton` and `ProfileSkeleton` are available from the previous overhaul.
## Solution
1. **Backend:** enrich `/users/{username}/top-friends` to return full `UserResponse` objects — eliminating the N+1
2. **Frontend:** move sidebar fetches into the sidebar components themselves, wrap each in `<Suspense>`, strip secondary fetches from `app/page.tsx`
---
## Section 1: Backend — Enrich top-friends endpoint
### Response type change
```rust
// crates/api-types/src/responses.rs
pub struct TopFriendsResponse {
pub top_friends: Vec<UserResponse>,
}
```
Replaces the existing `{ topFriends: string[] }` shape. Same URL: `GET /users/{username}/top-friends`.
### Use case change
The existing use case calls `TopFriendRepository::get_top_friends(username)` returning `Vec<UserId>`. Add a `UserRepository::find_many(&[UserId])` call (or a single JOIN query) to resolve the full user objects in one extra query. No N+1.
### Files changed
| File | Change |
|---|---|
| `crates/api-types/src/responses.rs` | Add `TopFriendsResponse { top_friends: Vec<UserResponse> }` |
| `crates/domain/src/ports.rs` | Add `find_many(ids: &[UserId])` to `UserRepository` (or equivalent) |
| `crates/adapters/postgres/src/user.rs` | Implement `find_many` with `WHERE id = ANY($1)` |
| `crates/application/src/use_cases/users.rs` | Update top-friends use case to return `Vec<User>` |
| `crates/presentation/src/handlers/users.rs` | Map `Vec<User>``TopFriendsResponse` |
---
## Section 2: Frontend — Suspense boundaries + self-contained sidebars
### Strip `app/page.tsx`
Remove `getFriends`, `getTopFriends`, `shouldDisplayTopFriends`, and the conditional sidebar rendering logic. Page-level critical path becomes:
```ts
const [feedData, me] = await Promise.all([
getFeed(token, page).catch(() => null),
getMe(token).catch(() => null),
])
```
Pass `me.username` and `token` as props to `TopFriends`.
### Self-contained `TopFriends`
`TopFriends` receives `username: string` and `token: string` as props and fetches `getTopFriends(username, token)` internally. The response is now `{ topFriends: UserResponse[] }` — render directly, no secondary fetches.
### Suspense wrapping (both desktop and mobile sidebars)
```tsx
<Suspense fallback={<ProfileSkeleton />}>
<TopFriends username={me.username} token={token} />
</Suspense>
<Suspense fallback={<TagsSkeleton />}>
<PopularTags />
</Suspense>
<Suspense fallback={<CountSkeleton />}>
<UsersCount />
</Suspense>
```
Each widget streams in independently. Feed renders as soon as `getFeed` resolves.
### New skeleton variants
Add to `components/loading-skeleton.tsx`:
```tsx
export function TagsSkeleton() {
return (
<Card>
<CardContent className="pt-4 space-y-2">
<Skeleton className="h-4 w-24" />
{[...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">
<Skeleton className="h-6 w-32" />
</CardContent>
</Card>
)
}
```
### `loading.tsx` files for pages missing them
Currently only `/users/[username]/loading.tsx` exists. Add:
| Page | Skeleton content |
|---|---|
| `app/loading.tsx` | `ThoughtSkeleton` × 3 |
| `app/tags/[tagName]/loading.tsx` | `ThoughtSkeleton` × 3 |
| `app/search/loading.tsx` | `ThoughtSkeleton` × 3 |
| `app/thoughts/[thoughtId]/loading.tsx` | `ThoughtSkeleton` × 2 |
### Update `lib/api.ts`
```ts
// Before
export const getTopFriends = (username: string, token: string | null) =>
apiFetch(..., z.object({ topFriends: z.array(z.string()) }), token)
// After
export const getTopFriends = (username: string, token: string | null) =>
apiFetch(..., z.object({ topFriends: z.array(UserSchema) }), token)
```
---
## Files Changed
### Backend
| File | Change |
|---|---|
| `crates/api-types/src/responses.rs` | `TopFriendsResponse { top_friends: Vec<UserResponse> }` |
| `crates/domain/src/ports.rs` | `UserRepository::find_many` |
| `crates/adapters/postgres/src/user.rs` | `find_many` impl |
| `crates/application/src/use_cases/users.rs` | Return `Vec<User>` from top-friends use case |
| `crates/presentation/src/handlers/users.rs` | Map to `TopFriendsResponse` |
### Frontend
| File | Change |
|---|---|
| `thoughts-frontend/lib/api.ts` | Update `getTopFriends` schema |
| `thoughts-frontend/app/page.tsx` | Strip sidebar fetches; pass `username`+`token` to TopFriends |
| `thoughts-frontend/components/top-friends.tsx` | Self-contained fetch; use `UserResponse[]` |
| `thoughts-frontend/components/loading-skeleton.tsx` | Add `TagsSkeleton`, `CountSkeleton` |
| `thoughts-frontend/app/loading.tsx` | New — feed skeleton |
| `thoughts-frontend/app/tags/[tagName]/loading.tsx` | New |
| `thoughts-frontend/app/search/loading.tsx` | New |
| `thoughts-frontend/app/thoughts/[thoughtId]/loading.tsx` | New |
---
## What This Does Not Cover
- Suspense on the feed content itself (feed is already the critical path — streaming it would show partial thought lists, which is awkward UX)
- Left sidebar "Filters & Sorting" placeholder (still empty)
- Streaming on other pages beyond loading.tsx coverage

View File

@@ -0,0 +1,23 @@
"use server";
import { revalidateTag } from "next/cache";
import { cookies } from "next/headers";
import { updateProfile as apiUpdateProfile, UpdateProfileSchema } from "@/lib/api";
import { z } from "zod";
async function getToken(): Promise<string> {
const token = (await cookies()).get("auth_token")?.value;
if (!token) throw new Error("Not authenticated");
return token;
}
export async function updateProfile(
username: string,
data: z.infer<typeof UpdateProfileSchema>
) {
const token = await getToken();
const updated = await apiUpdateProfile(data, token);
revalidateTag(`profile:${username}`);
revalidateTag("me");
return updated;
}

View File

@@ -0,0 +1,28 @@
"use server";
import { revalidateTag } from "next/cache";
import { cookies } from "next/headers";
import {
followUser as apiFollowUser,
unfollowUser as apiUnfollowUser,
} from "@/lib/api";
async function getToken(): Promise<string> {
const token = (await cookies()).get("auth_token")?.value;
if (!token) throw new Error("Not authenticated");
return token;
}
export async function followUser(username: string) {
const token = await getToken();
await apiFollowUser(username, token);
revalidateTag(`profile:${username}`);
revalidateTag("feed");
}
export async function unfollowUser(username: string) {
const token = await getToken();
await apiUnfollowUser(username, token);
revalidateTag(`profile:${username}`);
revalidateTag("feed");
}

View File

@@ -0,0 +1,30 @@
"use server";
import { revalidateTag } from "next/cache";
import { cookies } from "next/headers";
import {
createThought as apiCreateThought,
deleteThought as apiDeleteThought,
CreateThoughtSchema,
} from "@/lib/api";
import { z } from "zod";
async function getToken(): Promise<string> {
const token = (await cookies()).get("auth_token")?.value;
if (!token) throw new Error("Not authenticated");
return token;
}
export async function createThought(data: z.infer<typeof CreateThoughtSchema>) {
const token = await getToken();
const thought = await apiCreateThought(data, token);
revalidateTag("feed");
return thought;
}
export async function deleteThought(thoughtId: string) {
const token = await getToken();
await apiDeleteThought(thoughtId, token);
revalidateTag("feed");
revalidateTag(`thought:${thoughtId}`);
}

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,15 +1,8 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import {
getFeed,
getFriends,
getMe,
getTopFriends,
getUserProfile,
Me,
User,
} from "@/lib/api";
import { PostThoughtForm } from "@/components/post-thought-form";
import { getFeed, getMe, Me } from "@/lib/api";
import { ThoughtForm } from "@/components/thought-form";
import { EmptyState } from "@/components/empty-state";
import { Button } from "@/components/ui/button";
import Link from "next/link";
import { PopularTags } from "@/components/popular-tags";
@@ -17,9 +10,10 @@ import { ThoughtThread } from "@/components/thought-thread";
import { buildThoughtThreads } from "@/lib/utils";
import { TopFriends } from "@/components/top-friends";
import { UsersCount } from "@/components/users-count";
import { PaginationNav } from "@/components/pagination-nav";
import { redirect } from "next/navigation";
import { Suspense } from "react";
import { ProfileSkeleton, TagsSkeleton, CountSkeleton } from "@/components/loading-skeleton";
export const metadata: Metadata = {
title: "Home",
@@ -62,29 +56,26 @@ async function FeedPage({
const { items: allThoughts, totalPages } = feedData!;
const thoughtThreads = buildThoughtThreads(allThoughts);
const authors = [...new Set(allThoughts.map((t) => t.author.username))];
const userProfiles = await Promise.all(
authors.map((username) => getUserProfile(username, token).catch(() => null))
const sidebar = (
<>
<Suspense fallback={<ProfileSkeleton />}>
<TopFriends username={me.username} />
</Suspense>
<Suspense fallback={<TagsSkeleton />}>
<PopularTags />
</Suspense>
<Suspense fallback={<CountSkeleton />}>
<UsersCount />
</Suspense>
</>
);
const authorDetails = new Map<string, { avatarUrl?: string | null }>(
userProfiles
.filter((u): u is User => !!u)
.map((user) => [user.username, { avatarUrl: user.avatarUrl }])
);
const friends = (await getFriends(token)).users.map((user) => user.username);
const topFriendsData = me
? await getTopFriends(me.username, token).catch(() => ({ topFriends: [] }))
: { topFriends: [] };
const shouldDisplayTopFriends = topFriendsData.topFriends.length > 0;
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">
<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>
</div>
</aside>
@@ -93,17 +84,10 @@ async function FeedPage({
<header className="mb-6">
<h1 className="text-3xl font-bold text-shadow-sm">Your Feed</h1>
</header>
<PostThoughtForm />
<ThoughtForm />
<div className="block lg:hidden space-y-6">
<PopularTags />
{shouldDisplayTopFriends && (
<TopFriends mode="top-friends" usernames={topFriendsData.topFriends} />
)}
{!shouldDisplayTopFriends && token && friends.length > 0 && (
<TopFriends mode="friends" usernames={friends || []} />
)}
<UsersCount />
{sidebar}
</div>
<div className="space-y-6">
@@ -111,14 +95,11 @@ async function FeedPage({
<ThoughtThread
key={thought.id}
thought={thought}
authorDetails={authorDetails}
currentUser={me}
/>
))}
{thoughtThreads.length === 0 && (
<p className="text-center text-muted-foreground pt-8">
Your feed is empty. Follow some users to see their thoughts!
</p>
<EmptyState message="Your feed is empty. Follow some users to see their thoughts!" />
)}
</div>
<PaginationNav
@@ -130,14 +111,7 @@ async function FeedPage({
<aside className="hidden lg:block lg:col-span-1">
<div className="sticky top-20 space-y-6">
<PopularTags />
{shouldDisplayTopFriends && (
<TopFriends mode="top-friends" usernames={topFriendsData.topFriends} />
)}
{!shouldDisplayTopFriends && token && friends.length > 0 && (
<TopFriends mode="friends" usernames={friends || []} />
)}
<UsersCount />
{sidebar}
</div>
</aside>
</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

@@ -1,6 +1,6 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { getMe, search, lookupRemoteActor, User } from "@/lib/api";
import { getMe, search, lookupRemoteActor } from "@/lib/api";
export async function generateMetadata({
searchParams,
@@ -16,6 +16,7 @@ export async function generateMetadata({
: "Search for people and thoughts on Thoughts",
};
}
import { EmptyState } from "@/components/empty-state";
import { UserListCard } from "@/components/user-list-card";
import { RemoteUserCard } from "@/components/remote-user-card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
@@ -51,13 +52,6 @@ export default async function SearchPage({ searchParams }: SearchPageProps) {
token ? getMe(token).catch(() => null) : null,
]);
const authorDetails = new Map<string, { avatarUrl?: string | null }>();
if (results) {
results.users.forEach((user: User) => {
authorDetails.set(user.username, { avatarUrl: user.avatarUrl });
});
}
return (
<div className="container mx-auto max-w-2xl p-4 sm:p-6">
<header className="my-6">
@@ -74,9 +68,7 @@ export default async function SearchPage({ searchParams }: SearchPageProps) {
<RemoteUserCard actor={remoteActor} />
</div>
) : (
<p className="text-center text-muted-foreground pt-8">
No user found at {query}
</p>
<EmptyState message={`No user found at ${query}`} />
)
) : results ? (
<Tabs defaultValue="thoughts" className="w-full">
@@ -91,7 +83,6 @@ export default async function SearchPage({ searchParams }: SearchPageProps) {
<TabsContent value="thoughts">
<ThoughtList
thoughts={results.thoughts}
authorDetails={authorDetails}
currentUser={me}
/>
</TabsContent>
@@ -100,9 +91,7 @@ export default async function SearchPage({ searchParams }: SearchPageProps) {
</TabsContent>
</Tabs>
) : (
<p className="text-center text-muted-foreground pt-8">
No results found or an error occurred.
</p>
<EmptyState message="No results found or an error occurred." />
)}
</main>
</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

@@ -1,7 +1,7 @@
// app/tags/[tagName]/page.tsx
import type { Metadata } from "next";
import { cookies } from "next/headers";
import { getThoughtsByTag, getUserProfile, getMe, Me, User } from "@/lib/api";
import { getThoughtsByTag, getMe, Me } from "@/lib/api";
export async function generateMetadata({
params,
@@ -23,6 +23,7 @@ export async function generateMetadata({
},
};
}
import { EmptyState } from "@/components/empty-state";
import { buildThoughtThreads } from "@/lib/utils";
import { ThoughtThread } from "@/components/thought-thread";
import { notFound } from "next/navigation";
@@ -49,16 +50,6 @@ export default async function TagPage({ params }: TagPageProps) {
const thoughtThreads = buildThoughtThreads(allThoughts);
const me = meResult.status === "fulfilled" ? (meResult.value as Me) : null;
const authors = [...new Set(allThoughts.map((t) => t.author.username))];
const userProfiles = await Promise.all(
authors.map((username) => getUserProfile(username, token).catch(() => null))
);
const authorDetails = new Map<string, { avatarUrl?: string | null }>(
userProfiles
.filter((u): u is User => !!u)
.map((user) => [user.username, { avatarUrl: user.avatarUrl }])
);
return (
<div className="container mx-auto max-w-2xl p-4 sm:p-6">
<header className="my-6">
@@ -72,14 +63,11 @@ export default async function TagPage({ params }: TagPageProps) {
<ThoughtThread
key={thought.id}
thought={thought}
authorDetails={authorDetails}
currentUser={me}
/>
))}
{thoughtThreads.length === 0 && (
<p className="text-center text-muted-foreground pt-8">
No thoughts found for this tag.
</p>
<EmptyState message="No thoughts found for this tag." />
)}
</main>
</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

@@ -3,10 +3,8 @@ import { cookies } from "next/headers";
import {
getThoughtById,
getThoughtThread,
getUserProfile,
getMe,
Me,
User,
ThoughtThread as ThoughtThreadType,
} from "@/lib/api";
import { ThoughtThread } from "@/components/thought-thread";
@@ -52,14 +50,6 @@ export async function generateMetadata({
};
}
function collectAuthors(thread: ThoughtThreadType): string[] {
const authors = new Set<string>([thread.author.username]);
for (const reply of thread.replies) {
collectAuthors(reply).forEach((author) => authors.add(author));
}
return Array.from(authors);
}
export default async function ThoughtPage({ params }: ThoughtPageProps) {
const { thoughtId } = await params;
const token = (await cookies()).get("auth_token")?.value ?? null;
@@ -76,20 +66,6 @@ export default async function ThoughtPage({ params }: ThoughtPageProps) {
const thread = threadResult.value;
const me = meResult.status === "fulfilled" ? (meResult.value as Me) : null;
// Fetch details for all authors in the thread efficiently
const authorUsernames = collectAuthors(thread);
const userProfiles = await Promise.all(
authorUsernames.map((username) =>
getUserProfile(username, token).catch(() => null)
)
);
const authorDetails = new Map<string, { avatarUrl?: string | null }>(
userProfiles
.filter((u): u is User => !!u)
.map((user) => [user.username, { avatarUrl: user.avatarUrl }])
);
return (
<div className="container mx-auto max-w-2xl p-4 sm:p-6">
<header className="my-6">
@@ -98,7 +74,6 @@ export default async function ThoughtPage({ params }: ThoughtPageProps) {
<main>
<ThoughtThread
thought={thread}
authorDetails={authorDetails}
currentUser={me}
/>
</main>

View File

@@ -5,7 +5,6 @@ import {
getMe,
getRemoteFollowers,
getRemoteFollowing,
getTopFriends,
getUserProfile,
getUserThoughts,
Me,
@@ -44,6 +43,7 @@ export async function generateMetadata({
},
};
}
import { EmptyState } from "@/components/empty-state";
import { UserAvatar } from "@/components/user-avatar";
import { Calendar, Settings } from "lucide-react";
import { Card } from "@/components/ui/card";
@@ -51,6 +51,8 @@ import { notFound } from "next/navigation";
import { cookies } from "next/headers";
import { FollowButton } from "@/components/follow-button";
import { TopFriends } from "@/components/top-friends";
import { Suspense } from "react";
import { ProfileSkeleton } from "@/components/loading-skeleton";
import { buildThoughtThreads } from "@/lib/utils";
import { ThoughtThread } from "@/components/thought-thread";
import { Button } from "@/components/ui/button";
@@ -126,18 +128,6 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
const fediverseHandle =
user.local && apiDomain ? `@${user.username}@${apiDomain}` : null;
const authorDetails = new Map<string, { avatarUrl?: string | null }>();
authorDetails.set(user.username, { avatarUrl: user.avatarUrl });
// 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 (
<div id={`profile-page-${user.username}`}>
{user.customCss && (
@@ -254,10 +244,9 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
</div>
</Card>
{shouldDisplayTopFriends && (
<TopFriends mode="top-friends" usernames={topFriendsData.topFriends} />
)}
{token && <TopFriends mode="friends" usernames={friends || []} />}
<Suspense fallback={<ProfileSkeleton />}>
<TopFriends username={user.username} />
</Suspense>
</div>
</aside>
@@ -277,19 +266,11 @@ export default async function ProfilePage({ params }: ProfilePageProps) {
<ThoughtThread
key={thought.id}
thought={thought}
authorDetails={authorDetails}
currentUser={me}
/>
))}
{thoughtThreads.length === 0 && (
<Card
id="profile-card__no-thoughts"
className="flex items-center justify-center h-48"
>
<p className="text-center text-muted-foreground">
This user hasn&apos;t posted any public thoughts yet.
</p>
</Card>
<EmptyState message="This user hasn't posted any public thoughts yet." />
)}
</TabsContent>
{isOwnProfile && (

View File

@@ -3,9 +3,8 @@
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/use-auth";
import { Me, UpdateProfileSchema, updateProfile } from "@/lib/api";
import { Me, UpdateProfileSchema } from "@/lib/api";
import { updateProfile } from "@/app/actions/profile";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
@@ -25,8 +24,6 @@ interface EditProfileFormProps {
}
export function EditProfileForm({ currentUser }: EditProfileFormProps) {
const router = useRouter();
const { token } = useAuth();
const form = useForm<z.infer<typeof UpdateProfileSchema>>({
resolver: zodResolver(UpdateProfileSchema),
@@ -40,13 +37,10 @@ export function EditProfileForm({ currentUser }: EditProfileFormProps) {
});
async function onSubmit(values: z.infer<typeof UpdateProfileSchema>) {
if (!token) return;
toast.info("Updating your profile...");
try {
await updateProfile(values, token);
await updateProfile(currentUser.username, values);
toast.success("Profile updated successfully!");
router.push(`/users/${currentUser.username}`);
router.refresh();
} catch (err) {
toast.error(`Failed to update profile. ${err}`);
}

View File

@@ -0,0 +1,12 @@
interface EmptyStateProps {
message: string
className?: string
}
export function EmptyState({ message, className }: EmptyStateProps) {
return (
<p className={`text-center text-muted-foreground pt-8 ${className ?? ""}`}>
{message}
</p>
)
}

View File

@@ -1,66 +1,41 @@
"use client";
"use client"
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/hooks/use-auth";
import { followUser, unfollowUser } from "@/lib/api";
import { Button } from "@/components/ui/button";
import { toast } from "sonner";
import { UserPlus, UserMinus } from "lucide-react";
import { useOptimistic } from "react"
import { followUser, unfollowUser } from "@/app/actions/social"
import { Button } from "@/components/ui/button"
import { toast } from "sonner"
import { UserPlus, UserMinus } from "lucide-react"
interface FollowButtonProps {
username: string;
isInitiallyFollowing: boolean;
username: string
isInitiallyFollowing: boolean
}
export function FollowButton({
username,
isInitiallyFollowing,
}: FollowButtonProps) {
const [isFollowing, setIsFollowing] = useState(isInitiallyFollowing);
const [isLoading, setIsLoading] = useState(false);
const { token } = useAuth();
const router = useRouter();
const handleClick = async () => {
if (!token) {
toast.error("You must be logged in to follow users.");
return;
}
setIsLoading(true);
const action = isFollowing ? unfollowUser : followUser;
export function FollowButton({ username, isInitiallyFollowing }: FollowButtonProps) {
const [optimisticFollowing, setOptimisticFollowing] = useOptimistic(isInitiallyFollowing)
async function handleClick() {
const next = !optimisticFollowing
setOptimisticFollowing(next)
try {
// Optimistic update
setIsFollowing(!isFollowing);
await action(username, token);
router.refresh(); // Re-fetch server component data to get the latest follower count etc.
await (next ? followUser(username) : unfollowUser(username))
} catch {
// Revert on error
setIsFollowing(isFollowing);
toast.error(`Failed to ${isFollowing ? "unfollow" : "follow"} user.`);
} finally {
setIsLoading(false);
setOptimisticFollowing(!next) // revert
toast.error(`Failed to ${next ? "follow" : "unfollow"} user.`)
}
};
}
return (
<Button
onClick={handleClick}
disabled={isLoading}
variant={isFollowing ? "secondary" : "default"}
data-following={isFollowing}
variant={optimisticFollowing ? "secondary" : "default"}
data-following={optimisticFollowing}
>
{isFollowing ? (
<>
<UserMinus className="mr-2 h-4 w-4" /> Unfollow
</>
{optimisticFollowing ? (
<><UserMinus className="mr-2 h-4 w-4" /> Unfollow</>
) : (
<>
<UserPlus className="mr-2 h-4 w-4" /> Follow
</>
<><UserPlus className="mr-2 h-4 w-4" /> Follow</>
)}
</Button>
);
)
}

View File

@@ -0,0 +1,57 @@
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { Skeleton } from "@/components/ui/skeleton"
export function ThoughtSkeleton() {
return (
<Card>
<CardHeader className="flex flex-row items-center gap-4">
<Skeleton className="h-10 w-10 rounded-full" />
<div className="space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-20" />
</div>
</CardHeader>
<CardContent className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</CardContent>
</Card>
)
}
export function ProfileSkeleton() {
return (
<Card>
<CardContent className="pt-6 flex items-center gap-4">
<Skeleton className="h-16 w-16 rounded-full" />
<div className="space-y-2">
<Skeleton className="h-5 w-40" />
<Skeleton className="h-4 w-24" />
</div>
</CardContent>
</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,130 +0,0 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import {
Form,
FormField,
FormItem,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { CreateThoughtSchema, createThought } from "@/lib/api";
import { useAuth } from "@/hooks/use-auth";
import { toast } from "sonner";
import { Globe, Lock, Users } from "lucide-react";
import { useState } from "react";
import { Confetti } from "./confetti";
export function PostThoughtForm() {
const router = useRouter();
const { token } = useAuth();
const [showConfetti, setShowConfetti] = useState(false);
const form = useForm<z.infer<typeof CreateThoughtSchema>>({
resolver: zodResolver(CreateThoughtSchema),
defaultValues: { content: "", visibility: "public" },
});
async function onSubmit(values: z.infer<typeof CreateThoughtSchema>) {
if (!token) {
toast.error("You must be logged in to post.");
return;
}
try {
await createThought(values, token);
toast.success("Your thought has been posted!");
setShowConfetti(true);
form.reset();
router.refresh(); // This is the key to updating the feed
} catch {
toast.error("Failed to post thought. Please try again.");
}
}
return (
<>
<Confetti fire={showConfetti} onComplete={() => setShowConfetti(false)} />
<Card>
<CardContent className="p-4">
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder="What's on your mind?"
className="resize-none"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-between items-center">
<FormField
control={form.control}
name="visibility"
render={({ field }) => (
<Select
onValueChange={field.onChange}
defaultValue={field.value}
>
<FormControl>
<SelectTrigger className="w-[150px]">
<SelectValue placeholder="Visibility" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="public">
<div className="flex items-center gap-2">
<Globe className="h-4 w-4" /> Public
</div>
</SelectItem>
<SelectItem value="followers">
<div className="flex items-center gap-2">
<Users className="h-4 w-4" /> Followers
</div>
</SelectItem>
<SelectItem value="unlisted">
<div className="flex items-center gap-2">
<Lock className="h-4 w-4" /> Unlisted
</div>
</SelectItem>
<SelectItem value="direct">
<div className="flex items-center gap-2">
<Lock className="h-4 w-4" /> Direct
</div>
</SelectItem>
</SelectContent>
</Select>
)}
/>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? "Posting..." : "Post Thought"}
</Button>
</div>
</form>
</Form>
</CardContent>
</Card>
</>
);
}

View File

@@ -1,295 +0,0 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { UserAvatar } from "@/components/user-avatar";
import { ThoughtList } from "@/components/thought-list";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { ExternalLink, UserPlus, UserMinus } from "lucide-react";
import { followUser, unfollowUser, RemoteActor, Thought, Me, getActorFollowers, getActorFollowing, ActorConnection } from "@/lib/api";
import { RemoteUserCard } from "@/components/remote-user-card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { toast } from "sonner";
import { useAuth } from "@/hooks/use-auth";
interface RemoteUserProfileProps {
actor: RemoteActor;
initialPosts: Thought[];
me: Me | null;
initialFollowed?: boolean;
}
export function RemoteUserProfile({
actor,
initialPosts,
me,
initialFollowed = false,
}: RemoteUserProfileProps) {
const [followed, setFollowed] = useState(initialFollowed);
const [loading, setLoading] = useState(false);
const { token } = useAuth();
type ConnectionTab = "posts" | "followers" | "following";
const [activeTab, setActiveTab] = useState<ConnectionTab>("posts");
const [followers, setFollowers] = useState<ActorConnection[]>([]);
const [following, setFollowing] = useState<ActorConnection[]>([]);
const [followersPage, setFollowersPage] = useState(1);
const [followingPage, setFollowingPage] = useState(1);
const [followersHasMore, setFollowersHasMore] = useState(false);
const [followingHasMore, setFollowingHasMore] = useState(false);
const [followersLoaded, setFollowersLoaded] = useState(false);
const [followingLoaded, setFollowingLoaded] = useState(false);
const handleFollow = async () => {
if (!token) {
toast.error("You must be logged in to follow users.");
return;
}
setLoading(true);
try {
if (followed) {
await unfollowUser(actor.handle, token);
setFollowed(false);
} else {
await followUser(actor.handle, token);
setFollowed(true);
toast.success(`Follow request sent to ${actor.handle}`);
}
} catch {
toast.error(
followed ? "Failed to unfollow." : "Failed to send follow request.",
);
} finally {
setLoading(false);
}
};
const loadFollowers = async (page: number) => {
const result = await getActorFollowers(actor.handle, page, token).catch(() => null);
if (!result) return;
setFollowers((prev) => (page === 1 ? result.items : [...prev, ...result.items]));
setFollowersHasMore(result.hasMore);
setFollowersLoaded(true);
setFollowersPage(page);
};
const loadFollowing = async (page: number) => {
const result = await getActorFollowing(actor.handle, page, token).catch(() => null);
if (!result) return;
setFollowing((prev) => (page === 1 ? result.items : [...prev, ...result.items]));
setFollowingHasMore(result.hasMore);
setFollowingLoaded(true);
setFollowingPage(page);
};
const handleTabChange = (tab: string) => {
setActiveTab(tab as ConnectionTab);
if (tab === "followers" && !followersLoaded) loadFollowers(1);
if (tab === "following" && !followingLoaded) loadFollowing(1);
};
const isOwnProfile = me?.username === actor.handle;
const authorDetails = new Map<string, { avatarUrl?: string | null }>();
initialPosts.forEach((t) => {
authorDetails.set(t.author.username, { avatarUrl: actor.avatarUrl });
});
return (
<div>
<div
className="h-48 bg-muted bg-cover bg-center"
style={{
backgroundImage: actor.bannerUrl ? `url(${actor.bannerUrl})` : "none",
}}
/>
<main className="container mx-auto max-w-6xl p-4 -mt-16 grid grid-cols-1 lg:grid-cols-4 gap-8">
<aside className="col-span-1 space-y-6">
<div className="sticky top-20 space-y-6">
<Card className="p-6 bg-card/80 backdrop-blur-lg">
<div className="flex justify-between items-start">
<div className="w-24 h-24 rounded-full border-4 border-background shrink-0">
<UserAvatar
src={actor.avatarUrl}
alt={actor.displayName}
className="w-full h-full"
/>
</div>
{!isOwnProfile && token && (
<Button
onClick={handleFollow}
disabled={loading}
variant={followed ? "secondary" : "default"}
size="sm"
>
{followed ? (
<>
<UserMinus className="mr-2 h-4 w-4" /> Unfollow
</>
) : (
<>
<UserPlus className="mr-2 h-4 w-4" /> Follow
</>
)}
</Button>
)}
</div>
<div className="mt-4 min-w-0">
<h1 className="text-2xl font-bold truncate">
{actor.displayName ?? actor.handle}
</h1>
<p className="text-sm text-muted-foreground truncate">
{actor.handle}
</p>
</div>
{actor.bio && (
<div
className="mt-4 text-sm [&_a]:underline [&_a]:text-primary [&_p]:mb-2"
dangerouslySetInnerHTML={{ __html: actor.bio }}
/>
)}
<Button
asChild
variant="outline"
size="sm"
className="mt-4 w-full"
>
<Link
href={actor.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center overflow-hidden"
>
<ExternalLink className="mr-2 h-4 w-4 shrink-0" />
<span className="truncate">
{new URL(actor.url).hostname}
</span>
</Link>
</Button>
{actor.alsoKnownAs && (
<p className="mt-2 text-xs text-muted-foreground">
Also known as:{" "}
<Link
href={actor.alsoKnownAs}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{actor.alsoKnownAs}
</Link>
</p>
)}
{actor.attachment.length > 0 && (
<div className="mt-4 space-y-0 text-sm">
{actor.attachment.map((field) => (
<div
key={field.name}
className="grid grid-cols-[minmax(0,5rem)_1fr] gap-2 border-t py-1"
>
<span className="font-medium text-muted-foreground truncate" title={field.name}>
{field.name}
</span>
<span
className="break-all min-w-0 [&_a]:underline [&_a]:text-primary"
dangerouslySetInnerHTML={{ __html: field.value }}
/>
</div>
))}
</div>
)}
</Card>
</div>
</aside>
<div className="col-span-1 lg:col-span-3">
<Tabs defaultValue="posts" onValueChange={handleTabChange}>
<TabsList>
<TabsTrigger value="posts">Posts</TabsTrigger>
<TabsTrigger value="followers">Followers</TabsTrigger>
<TabsTrigger value="following">Following</TabsTrigger>
</TabsList>
<TabsContent value="posts" className="space-y-4 mt-4">
{initialPosts.length > 0 ? (
<ThoughtList
thoughts={initialPosts}
authorDetails={authorDetails}
currentUser={me}
/>
) : (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">
Posts are being fetched check back soon.
</p>
</Card>
)}
</TabsContent>
<TabsContent value="followers" className="mt-4">
{!followersLoaded ? (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">Loading followers</p>
</Card>
) : followers.length === 0 ? (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">
No followers cached yet check back soon.
</p>
</Card>
) : (
<div className="space-y-2">
{followers.map((f) => (
<RemoteUserCard key={f.url} actor={f} />
))}
{followersHasMore && (
<button
onClick={() => loadFollowers(followersPage + 1)}
className="w-full text-sm text-muted-foreground hover:text-foreground py-2"
>
Load more
</button>
)}
</div>
)}
</TabsContent>
<TabsContent value="following" className="mt-4">
{!followingLoaded ? (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">Loading following</p>
</Card>
) : following.length === 0 ? (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">
No following cached yet check back soon.
</p>
</Card>
) : (
<div className="space-y-2">
{following.map((f) => (
<RemoteUserCard key={f.url} actor={f} />
))}
{followingHasMore && (
<button
onClick={() => loadFollowing(followingPage + 1)}
className="w-full text-sm text-muted-foreground hover:text-foreground py-2"
>
Load more
</button>
)}
</div>
)}
</TabsContent>
</Tabs>
</div>
</main>
</div>
);
}

View File

@@ -0,0 +1,75 @@
"use client";
import { useState, useEffect } from "react";
import { ActorConnection, getActorFollowers, getActorFollowing } from "@/lib/api";
import { Card } from "@/components/ui/card";
import { RemoteUserCard } from "@/components/remote-user-card";
interface ConnectionsProps {
handle: string;
token: string | null;
type: "followers" | "following";
/** Parent sets this to true when the tab becomes active for the first time. */
active: boolean;
}
export function Connections({ handle, token, type, active }: ConnectionsProps) {
const [items, setItems] = useState<ActorConnection[]>([]);
const [page, setPage] = useState(1);
const [hasMore, setHasMore] = useState(false);
const [loaded, setLoaded] = useState(false);
const load = async (p: number) => {
const fetchFn = type === "followers" ? getActorFollowers : getActorFollowing;
const result = await fetchFn(handle, p, token).catch(() => null);
if (!result) return;
setItems((prev) => (p === 1 ? result.items : [...prev, ...result.items]));
setHasMore(result.hasMore);
setLoaded(true);
setPage(p);
};
useEffect(() => {
if (active && !loaded) {
load(1);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
const emptyMessage =
type === "followers"
? "No followers cached yet — check back soon."
: "No following cached yet — check back soon.";
if (!loaded) {
return (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">Loading {type}</p>
</Card>
);
}
if (items.length === 0) {
return (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">{emptyMessage}</p>
</Card>
);
}
return (
<div className="space-y-2">
{items.map((f) => (
<RemoteUserCard key={f.url} actor={f} />
))}
{hasMore && (
<button
onClick={() => load(page + 1)}
className="w-full text-sm text-muted-foreground hover:text-foreground py-2"
>
Load more
</button>
)}
</div>
);
}

View File

@@ -0,0 +1,144 @@
"use client";
import { useState } from "react";
import { UserMinus, UserPlus } from "lucide-react";
import { followUser, unfollowUser, RemoteActor, Thought, Me } from "@/lib/api";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { ThoughtList } from "@/components/thought-list";
import { toast } from "sonner";
import { useAuth } from "@/hooks/use-auth";
import { ProfileCard } from "./profile-card";
import { Connections } from "./connections";
interface RemoteUserProfileProps {
actor: RemoteActor;
initialPosts: Thought[];
me: Me | null;
initialFollowed?: boolean;
}
export function RemoteUserProfile({
actor,
initialPosts,
me,
initialFollowed = false,
}: RemoteUserProfileProps) {
const [followed, setFollowed] = useState(initialFollowed);
const [followLoading, setFollowLoading] = useState(false);
const { token } = useAuth();
const [followersActive, setFollowersActive] = useState(false);
const [followingActive, setFollowingActive] = useState(false);
const handleFollow = async () => {
if (!token) {
toast.error("You must be logged in to follow users.");
return;
}
setFollowLoading(true);
try {
if (followed) {
await unfollowUser(actor.handle, token);
setFollowed(false);
} else {
await followUser(actor.handle, token);
setFollowed(true);
toast.success(`Follow request sent to ${actor.handle}`);
}
} catch {
toast.error(followed ? "Failed to unfollow." : "Failed to send follow request.");
} finally {
setFollowLoading(false);
}
};
const handleTabChange = (tab: string) => {
if (tab === "followers") setFollowersActive(true);
if (tab === "following") setFollowingActive(true);
};
const isOwnProfile = me?.username === actor.handle;
const followButton =
!isOwnProfile && token ? (
<Button
onClick={handleFollow}
disabled={followLoading}
variant={followed ? "secondary" : "default"}
size="sm"
>
{followed ? (
<>
<UserMinus className="mr-2 h-4 w-4" /> Unfollow
</>
) : (
<>
<UserPlus className="mr-2 h-4 w-4" /> Follow
</>
)}
</Button>
) : undefined;
return (
<div>
<div
className="h-48 bg-muted bg-cover bg-center"
style={{
backgroundImage: actor.bannerUrl ? `url(${actor.bannerUrl})` : "none",
}}
/>
<main className="container mx-auto max-w-6xl p-4 -mt-16 grid grid-cols-1 lg:grid-cols-4 gap-8">
<aside className="col-span-1 space-y-6">
<div className="sticky top-20 space-y-6">
<Card className="p-6 bg-card/80 backdrop-blur-lg">
<ProfileCard actor={actor} action={followButton} />
</Card>
</div>
</aside>
<div className="col-span-1 lg:col-span-3">
<Tabs defaultValue="posts" onValueChange={handleTabChange}>
<TabsList>
<TabsTrigger value="posts">Posts</TabsTrigger>
<TabsTrigger value="followers">Followers</TabsTrigger>
<TabsTrigger value="following">Following</TabsTrigger>
</TabsList>
<TabsContent value="posts" className="space-y-4 mt-4">
{initialPosts.length > 0 ? (
<ThoughtList thoughts={initialPosts} currentUser={me} />
) : (
<Card className="flex items-center justify-center h-48">
<p className="text-center text-muted-foreground">
Posts are being fetched check back soon.
</p>
</Card>
)}
</TabsContent>
<TabsContent value="followers" className="mt-4">
<Connections
handle={actor.handle}
token={token}
type="followers"
active={followersActive}
/>
</TabsContent>
<TabsContent value="following" className="mt-4">
<Connections
handle={actor.handle}
token={token}
type="following"
active={followingActive}
/>
</TabsContent>
</Tabs>
</div>
</main>
</div>
);
}

View File

@@ -0,0 +1,98 @@
import Link from "next/link";
import { ExternalLink } from "lucide-react";
import { ReactNode } from "react";
import { RemoteActor } from "@/lib/api";
import { UserAvatar } from "@/components/user-avatar";
import { Button } from "@/components/ui/button";
interface ProfileCardProps {
actor: RemoteActor;
/** Slot rendered next to the avatar (e.g. follow/unfollow button). */
action?: ReactNode;
}
export function ProfileCard({ actor, action }: ProfileCardProps) {
let hostname: string | null = null;
try {
if (actor.url) hostname = new URL(actor.url).hostname;
} catch {
hostname = actor.url;
}
return (
<>
<div className="flex justify-between items-start">
<div className="w-24 h-24 rounded-full border-4 border-background shrink-0">
<UserAvatar
src={actor.avatarUrl}
alt={actor.displayName}
className="w-full h-full"
/>
</div>
{action}
</div>
<div className="mt-4 min-w-0">
<h1 className="text-2xl font-bold truncate">
{actor.displayName ?? actor.handle}
</h1>
<p className="text-sm text-muted-foreground truncate">{actor.handle}</p>
</div>
{actor.bio && (
<div
className="mt-4 text-sm [&_a]:underline [&_a]:text-primary [&_p]:mb-2"
dangerouslySetInnerHTML={{ __html: actor.bio }}
/>
)}
<Button asChild variant="outline" size="sm" className="mt-4 w-full">
<Link
href={actor.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center overflow-hidden"
>
<ExternalLink className="mr-2 h-4 w-4 shrink-0" />
<span className="truncate">{hostname}</span>
</Link>
</Button>
{actor.alsoKnownAs && (
<p className="mt-2 text-xs text-muted-foreground">
Also known as:{" "}
<Link
href={actor.alsoKnownAs}
target="_blank"
rel="noopener noreferrer"
className="underline"
>
{actor.alsoKnownAs}
</Link>
</p>
)}
{actor.attachment.length > 0 && (
<div className="mt-4 space-y-0 text-sm">
{actor.attachment.map((field) => (
<div
key={field.name}
className="grid grid-cols-[minmax(0,5rem)_1fr] gap-2 border-t py-1"
>
<span
className="font-medium text-muted-foreground truncate"
title={field.name}
>
{field.name}
</span>
<span
className="break-all min-w-0 [&_a]:underline [&_a]:text-primary"
dangerouslySetInnerHTML={{ __html: field.value }}
/>
</div>
))}
</div>
)}
</>
);
}

View File

@@ -1,97 +0,0 @@
"use client";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import {
Form,
FormField,
FormItem,
FormControl,
FormMessage,
} from "@/components/ui/form";
import { Textarea } from "@/components/ui/textarea";
import { CreateThoughtSchema, createThought } from "@/lib/api";
import { useAuth } from "@/hooks/use-auth";
import { toast } from "sonner";
import { useState } from "react";
import { Confetti } from "./confetti";
interface ReplyFormProps {
parentThoughtId: string;
onReplySuccess: () => void; // A callback to close the form after success
}
export function ReplyForm({ parentThoughtId, onReplySuccess }: ReplyFormProps) {
const router = useRouter();
const { token } = useAuth();
const [showConfetti, setShowConfetti] = useState(false);
const form = useForm<z.infer<typeof CreateThoughtSchema>>({
resolver: zodResolver(CreateThoughtSchema),
defaultValues: {
content: "",
inReplyToId: parentThoughtId,
visibility: "public",
},
});
async function onSubmit(values: z.infer<typeof CreateThoughtSchema>) {
if (!token) {
toast.error("You must be logged in to reply.");
return;
}
try {
await createThought(values, token);
toast.success("Your reply has been posted!");
form.reset();
setShowConfetti(true);
console.log("Showing confetti");
onReplySuccess();
router.refresh();
} catch {
toast.error("Failed to post reply. Please try again.");
}
}
return (
<>
<Confetti fire={showConfetti} onComplete={() => setShowConfetti(false)} />
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-2 p-4">
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder="Post your reply..."
className="resize-none bg-white glass-effect glossy-efect bottom shadow-fa-sm"
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className="flex justify-end gap-2">
<Button
type="button"
variant="ghost"
onClick={onReplySuccess} // Close button
>
Cancel
</Button>
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting ? "Replying..." : "Reply"}
</Button>
</div>
</form>
</Form>
</>
);
}

View File

@@ -7,11 +7,11 @@ import {
CardHeader,
} from "@/components/ui/card";
import { UserAvatar } from "./user-avatar";
import { deleteThought, Me, Thought } from "@/lib/api";
import { Me, Thought } from "@/lib/api";
import { deleteThought } from "@/app/actions/thoughts";
import { format, formatDistanceToNow } from "date-fns";
import { useAuth } from "@/hooks/use-auth";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import {
DropdownMenu,
@@ -36,31 +36,25 @@ import {
MoreHorizontal,
Trash2,
} from "lucide-react";
import { ReplyForm } from "@/components/reply-form";
import { ThoughtForm } from "@/components/thought-form";
import Link from "next/link";
import { cn } from "@/lib/utils";
interface ThoughtCardProps {
thought: Thought;
author: {
username: string;
displayName?: string | null;
avatarUrl?: string | null;
};
currentUser: Me | null;
isReply?: boolean;
}
export function ThoughtCard({
thought,
author,
currentUser,
isReply = false,
}: ThoughtCardProps) {
const { author } = thought;
const [isAlertOpen, setIsAlertOpen] = useState(false);
const [isReplyOpen, setIsReplyOpen] = useState(false);
const { token } = useAuth();
const router = useRouter();
const timeAgo = formatDistanceToNow(new Date(thought.createdAt), {
addSuffix: true,
});
@@ -68,11 +62,9 @@ export function ThoughtCard({
const isAuthor = currentUser?.username === thought.author.username;
const handleDelete = async () => {
if (!token) return;
try {
await deleteThought(thought.id, token);
await deleteThought(thought.id);
toast.success("Thought deleted successfully.");
router.refresh();
} catch (error) {
console.error("Failed to delete thought:", error);
toast.error("Failed to delete thought.");
@@ -203,9 +195,9 @@ export function ThoughtCard({
{isReplyOpen && (
<div className="border-t m-4 rounded-2xl border-border/50 bg-secondary/20 ">
<ReplyForm
parentThoughtId={thought.id}
onReplySuccess={() => setIsReplyOpen(false)}
<ThoughtForm
replyToId={thought.id}
onSuccess={() => setIsReplyOpen(false)}
/>
</div>
)}

View File

@@ -0,0 +1,142 @@
"use client"
import { useForm } from "react-hook-form"
import { zodResolver } from "@hookform/resolvers/zod"
import { z } from "zod"
import { Button } from "@/components/ui/button"
import { Card, CardContent } from "@/components/ui/card"
import {
Form,
FormField,
FormItem,
FormControl,
FormMessage,
} from "@/components/ui/form"
import { Textarea } from "@/components/ui/textarea"
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { CreateThoughtSchema } from "@/lib/api"
import { useAuth } from "@/hooks/use-auth"
import { toast } from "sonner"
import { Globe, Lock, Users } from "lucide-react"
import { useState } from "react"
import { Confetti } from "./confetti"
import { createThought } from "@/app/actions/thoughts"
interface ThoughtFormProps {
/** Set to the parent thought ID when composing a reply. */
replyToId?: string
/** Called after successful submit (e.g. close the reply panel). */
onSuccess?: () => void
/** Whether to wrap in a Card. Defaults to true when no replyToId. */
card?: boolean
}
export function ThoughtForm({ replyToId, onSuccess, card = !replyToId }: ThoughtFormProps) {
const { token } = useAuth()
const [showConfetti, setShowConfetti] = useState(false)
const form = useForm<z.infer<typeof CreateThoughtSchema>>({
resolver: zodResolver(CreateThoughtSchema),
defaultValues: {
content: "",
visibility: "public",
...(replyToId ? { inReplyToId: replyToId } : {}),
},
})
async function onSubmit(values: z.infer<typeof CreateThoughtSchema>) {
if (!token) {
toast.error("You must be logged in.")
return
}
try {
await createThought(values)
toast.success(replyToId ? "Reply posted!" : "Thought posted!")
setShowConfetti(true)
form.reset()
onSuccess?.()
} catch {
toast.error(replyToId ? "Failed to post reply." : "Failed to post thought.")
}
}
const inner = (
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
<FormField
control={form.control}
name="content"
render={({ field }) => (
<FormItem>
<FormControl>
<Textarea
placeholder={replyToId ? "Post your reply..." : "What's on your mind?"}
className={`resize-none ${replyToId ? "bg-white shadow-fa-sm" : ""}`}
{...field}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<div className={`flex ${replyToId ? "justify-end gap-2" : "justify-between items-center"}`}>
{!replyToId && (
<FormField
control={form.control}
name="visibility"
render={({ field }) => (
<Select onValueChange={field.onChange} defaultValue={field.value}>
<FormControl>
<SelectTrigger className="w-[150px]">
<SelectValue placeholder="Visibility" />
</SelectTrigger>
</FormControl>
<SelectContent>
<SelectItem value="public">
<div className="flex items-center gap-2"><Globe className="h-4 w-4" /> Public</div>
</SelectItem>
<SelectItem value="followers">
<div className="flex items-center gap-2"><Users className="h-4 w-4" /> Followers</div>
</SelectItem>
<SelectItem value="unlisted">
<div className="flex items-center gap-2"><Lock className="h-4 w-4" /> Unlisted</div>
</SelectItem>
<SelectItem value="direct">
<div className="flex items-center gap-2"><Lock className="h-4 w-4" /> Direct</div>
</SelectItem>
</SelectContent>
</Select>
)}
/>
)}
{replyToId && (
<Button type="button" variant="ghost" onClick={() => onSuccess?.()}>
Cancel
</Button>
)}
<Button type="submit" disabled={form.formState.isSubmitting}>
{form.formState.isSubmitting
? (replyToId ? "Replying..." : "Posting...")
: (replyToId ? "Reply" : "Post Thought")}
</Button>
</div>
</form>
</Form>
)
return (
<>
<Confetti fire={showConfetti} onComplete={() => setShowConfetti(false)} />
{card
? <Card><CardContent className="p-4">{inner}</CardContent></Card>
: <div className="space-y-2 p-4">{inner}</div>
}
</>
)
}

View File

@@ -4,15 +4,10 @@ import { Card, CardContent } from "./ui/card";
interface ThoughtListProps {
thoughts: Thought[];
authorDetails: Map<string, { avatarUrl?: string | null }>;
currentUser: Me | null;
}
export function ThoughtList({
thoughts,
authorDetails,
currentUser,
}: ThoughtListProps) {
export function ThoughtList({ thoughts, currentUser }: ThoughtListProps) {
if (thoughts.length === 0) {
return (
<p className="text-center text-muted-foreground pt-8">
@@ -25,21 +20,13 @@ export function ThoughtList({
<Card>
<CardContent className="divide-y p-0">
<div className="space-y-6 p-4">
{thoughts.map((thought) => {
const author = {
username: thought.author.username,
displayName: thought.author.displayName,
...authorDetails.get(thought.author.username),
};
return (
<ThoughtCard
key={thought.id}
thought={thought}
author={author}
currentUser={currentUser}
/>
);
})}
{thoughts.map((thought) => (
<ThoughtCard
key={thought.id}
thought={thought}
currentUser={currentUser}
/>
))}
</div>
</CardContent>
</Card>

View File

@@ -3,29 +3,19 @@ import { ThoughtCard } from "./thought-card";
interface ThoughtThreadProps {
thought: ThoughtThreadType;
authorDetails: Map<string, { avatarUrl?: string | null }>;
currentUser: Me | null;
isReply?: boolean;
}
export function ThoughtThread({
thought,
authorDetails,
currentUser,
isReply = false,
}: ThoughtThreadProps) {
const author = {
username: thought.author.username,
displayName: thought.author.displayName,
avatarUrl: thought.author.avatarUrl, // API-provided avatar (from DB COALESCE)
...authorDetails.get(thought.author.username), // override for local users
};
return (
<div id={`thought-thread-${thought.id}`} className="flex flex-col gap-0">
<ThoughtCard
thought={thought}
author={author}
currentUser={currentUser}
isReply={isReply}
/>
@@ -39,7 +29,6 @@ export function ThoughtThread({
<ThoughtThread
key={reply.id}
thought={reply}
authorDetails={authorDetails}
currentUser={currentUser}
isReply={true}
/>

View File

@@ -1,51 +1,25 @@
import Link from "next/link";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { UserAvatar } from "./user-avatar";
import { getUserProfile, User } from "@/lib/api";
import { getTopFriends } from "@/lib/api";
import { cookies } from "next/headers";
interface TopFriendsProps {
mode: "friends" | "top-friends";
usernames: string[];
username: string;
}
export async function TopFriends({
mode = "top-friends",
usernames,
}: TopFriendsProps) {
export async function TopFriends({ username }: TopFriendsProps) {
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) {
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);
if (friends.length === 0) return null;
return (
<Card id="top-friends" className="p-4">
<CardHeader id="top-friends__header" className="p-0 pb-2">
<CardTitle id="top-friends__title" className="text-lg text-shadow-md">
{mode === "top-friends" ? "Top Friends" : "Friends"}
Top Friends
</CardTitle>
</CardHeader>
<CardContent id="top-friends__content" className="p-0">
@@ -59,7 +33,7 @@ export async function TopFriends({
<UserAvatar src={friend.avatarUrl} alt={friend.username} />
<span
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}
</span>

View File

@@ -151,9 +151,13 @@ const API_BASE_URL =
? process.env.NEXT_PUBLIC_SERVER_SIDE_API_URL
: process.env.NEXT_PUBLIC_API_URL;
type ApiFetchOptions = Omit<RequestInit, 'next'> & {
next?: { tags?: string[]; revalidate?: number | false }
}
async function apiFetch<T>(
endpoint: string,
options: RequestInit = {},
options: ApiFetchOptions = {},
schema: z.ZodType<T>,
token?: string | null
): Promise<T> {
@@ -161,9 +165,11 @@ async function apiFetch<T>(
throw new Error("API_BASE_URL is not defined");
}
const { next, ...restOptions } = options;
const headers: Record<string, string> = {
"Content-Type": "application/json",
...(options.headers as Record<string, string>),
...(restOptions.headers as Record<string, string>),
};
if (token) {
@@ -171,8 +177,9 @@ async function apiFetch<T>(
}
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
...options,
...restOptions,
headers,
...(next ? { next } : {}),
});
if (!response.ok) {
@@ -202,27 +209,32 @@ export const loginUser = (data: z.infer<typeof LoginSchema>) =>
// ── Current user ──────────────────────────────────────────────────────────
export const getMe = (token: string) =>
apiFetch("/users/me", {}, MeSchema, token);
apiFetch("/users/me", { next: { tags: ['me'] } }, MeSchema, token);
export const updateProfile = (data: z.infer<typeof UpdateProfileSchema>, token: string) =>
apiFetch("/users/me", { method: "PATCH", body: JSON.stringify(data) }, UserSchema, token);
export const getMeFollowingList = (token: string) =>
apiFetch("/users/me/following", {}, z.object({ total: z.number(), items: z.array(UserSchema) }), token);
apiFetch("/users/me/following", { next: { tags: ['me'] } }, z.object({ total: z.number(), items: z.array(UserSchema) }), token);
// ── Users ─────────────────────────────────────────────────────────────────
export const getUserProfile = (username: string, token: string | null) =>
apiFetch(`/users/${username}`, {}, UserSchema, token);
apiFetch(`/users/${username}`, { next: { tags: [`profile:${username}`] } }, UserSchema, token);
export const getFollowersList = (username: string, token: string | null) =>
apiFetch(`/users/${username}/followers`, {}, z.object({ total: z.number(), items: z.array(UserSchema) }), token);
apiFetch(`/users/${username}/followers`, { next: { tags: [`profile:${username}`] } }, z.object({ total: z.number(), items: z.array(UserSchema) }), token);
export const getFollowingList = (username: string, token: string | null) =>
apiFetch(`/users/${username}/following`, {}, z.object({ total: z.number(), items: z.array(UserSchema) }), token);
apiFetch(`/users/${username}/following`, { next: { tags: [`profile:${username}`] } }, z.object({ total: z.number(), items: z.array(UserSchema) }), token);
export const getTopFriends = (username: string, token: string | null) =>
apiFetch(`/users/${username}/top-friends`, {}, z.object({ topFriends: z.array(z.string()) }), token);
apiFetch(
`/users/${username}/top-friends`,
{ next: { tags: [`profile:${username}`] } },
z.object({ topFriends: z.array(UserSchema) }),
token
);
export const followUser = (username: string, token: string) =>
apiFetch(`/users/${username}/follow`, { method: "POST" }, z.null(), token);
@@ -249,7 +261,7 @@ export const markAllNotificationsRead = (token: string) =>
export const lookupRemoteActor = (handle: string, token: string | null) =>
apiFetch(
`/users/lookup?handle=${encodeURIComponent(handle)}`,
{},
{ next: { tags: [`remote-actor:${handle}`] } },
RemoteActorSchema,
token
);
@@ -261,7 +273,7 @@ export const getRemoteActorPosts = (
) =>
apiFetch(
`/federation/actors/${encodeURIComponent(handle)}/posts?page=${page}&per_page=20`,
{},
{ next: { tags: [`remote-actor:${handle}`] } },
z.object({
total: z.number(),
page: z.number(),
@@ -292,7 +304,7 @@ export const getActorFollowers = (
) =>
apiFetch(
`/federation/actors/${encodeURIComponent(handle)}/followers-list?page=${page}`,
{},
{ next: { tags: [`remote-actor:${handle}`] } },
ActorConnectionPageSchema,
token
);
@@ -304,7 +316,7 @@ export const getActorFollowing = (
) =>
apiFetch(
`/federation/actors/${encodeURIComponent(handle)}/following-list?page=${page}`,
{},
{ next: { tags: [`remote-actor:${handle}`] } },
ActorConnectionPageSchema,
token
);
@@ -312,20 +324,20 @@ export const getActorFollowing = (
export const getAllUsers = (page: number = 1, pageSize: number = 20) =>
apiFetch(
`/users?page=${page}&per_page=${pageSize}`,
{},
{ next: { tags: ['users'] } },
z.object({ items: z.array(UserSchema), total: z.number(), page: z.number(), per_page: z.number() })
.transform((d) => ({ ...d, totalPages: Math.ceil(d.total / d.per_page) }))
);
export const getAllUsersCount = () =>
apiFetch("/users/count", {}, z.object({ count: z.number() }));
apiFetch("/users/count", { next: { tags: ['users'] } }, z.object({ count: z.number() }));
// ── Thoughts ──────────────────────────────────────────────────────────────
export const getFeed = (token: string, page: number = 1, pageSize: number = 20) =>
apiFetch(
`/feed?page=${page}&per_page=${pageSize}`,
{},
{ next: { tags: ['feed'] } },
z.object({ items: z.array(ThoughtSchema), total: z.number(), page: z.number(), per_page: z.number() })
.transform((d) => ({ ...d, totalPages: Math.ceil(d.total / d.per_page) })),
token
@@ -334,7 +346,7 @@ export const getFeed = (token: string, page: number = 1, pageSize: number = 20)
export const getUserThoughts = (username: string, token: string | null) =>
apiFetch(
`/users/${username}/thoughts`,
{},
{ next: { tags: [`profile:${username}`] } },
z.object({ items: z.array(ThoughtSchema), total: z.number(), page: z.number(), per_page: z.number() }),
token
);
@@ -346,10 +358,10 @@ export const deleteThought = (thoughtId: string, token: string) =>
apiFetch(`/thoughts/${thoughtId}`, { method: "DELETE" }, z.null(), token);
export const getThoughtById = (thoughtId: string, token: string | null) =>
apiFetch(`/thoughts/${thoughtId}`, {}, ThoughtSchema, token);
apiFetch(`/thoughts/${thoughtId}`, { next: { tags: [`thought:${thoughtId}`] } }, ThoughtSchema, token);
export const getThoughtThread = async (thoughtId: string, token: string | null): Promise<ThoughtThread> => {
const thoughts = await apiFetch(`/thoughts/${thoughtId}/thread`, {}, z.array(ThoughtSchema), token);
const thoughts = await apiFetch(`/thoughts/${thoughtId}/thread`, { next: { tags: [`thought:${thoughtId}`] } }, z.array(ThoughtSchema), token);
type T = z.infer<typeof ThoughtSchema>;
const repliesMap: Record<string, T[]> = {};
for (const t of thoughts) {
@@ -370,7 +382,7 @@ export const getThoughtThread = async (thoughtId: string, token: string | null):
export const getThoughtsByTag = (tagName: string, token: string | null) =>
apiFetch(
`/tags/${tagName}`,
{},
{ next: { tags: [`tag:${tagName}`, 'feed'] } },
z.object({ tag: z.string(), items: z.array(ThoughtSchema), total: z.number(), page: z.number(), per_page: z.number() }),
token
);
@@ -378,7 +390,7 @@ export const getThoughtsByTag = (tagName: string, token: string | null) =>
export const getPopularTags = () =>
apiFetch(
"/tags/popular",
{},
{ next: { tags: ['tags:popular'] } },
z.object({ tags: z.array(z.object({ name: z.string(), thought_count: z.number() })) })
.transform((d) => d.tags.map((t) => t.name))
);
@@ -386,12 +398,12 @@ export const getPopularTags = () =>
// ── Search ────────────────────────────────────────────────────────────────
export const search = (query: string, token: string | null) =>
apiFetch(`/search?q=${encodeURIComponent(query)}`, {}, SearchResultsSchema, token);
apiFetch(`/search?q=${encodeURIComponent(query)}`, { next: { tags: ['search'] } }, SearchResultsSchema, token);
// ── API Keys ──────────────────────────────────────────────────────────────
export const getApiKeys = (token: string) =>
apiFetch("/api-keys", {}, z.object({ keys: z.array(ApiKeySchema) }), token);
apiFetch("/api-keys", { next: { tags: ['api-keys'] } }, z.object({ keys: z.array(ApiKeySchema) }), token);
export const createApiKey = (data: z.infer<typeof CreateApiKeySchema>, token: string) =>
apiFetch("/api-keys", { method: "POST", body: JSON.stringify(data) }, ApiKeyResponseSchema, token);
@@ -409,7 +421,7 @@ export const getFriends = (token: string) =>
export const getPendingFollowRequests = (token: string) =>
apiFetch(
"/federation/me/followers/pending",
{},
{ next: { tags: ['federation:pending'] } },
z.array(RemoteActorSchema),
token
);
@@ -433,7 +445,7 @@ export const rejectFollowRequest = (actorUrl: string, token: string) =>
export const getRemoteFollowers = (token: string) =>
apiFetch(
"/federation/me/followers",
{},
{ next: { tags: ['federation:followers'] } },
z.array(RemoteActorSchema),
token
);
@@ -441,7 +453,7 @@ export const getRemoteFollowers = (token: string) =>
export const getRemoteFollowing = (token: string) =>
apiFetch(
"/federation/me/following",
{},
{ next: { tags: ['federation:following'] } },
z.array(RemoteActorSchema),
token
);

8567
thoughts-frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff