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
This commit is contained in:
23
thoughts-frontend/app/actions/profile.ts
Normal file
23
thoughts-frontend/app/actions/profile.ts
Normal 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;
|
||||
}
|
||||
28
thoughts-frontend/app/actions/social.ts
Normal file
28
thoughts-frontend/app/actions/social.ts
Normal 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");
|
||||
}
|
||||
30
thoughts-frontend/app/actions/thoughts.ts
Normal file
30
thoughts-frontend/app/actions/thoughts.ts
Normal 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}`);
|
||||
}
|
||||
@@ -5,11 +5,10 @@ import {
|
||||
getFriends,
|
||||
getMe,
|
||||
getTopFriends,
|
||||
getUserProfile,
|
||||
Me,
|
||||
User,
|
||||
} from "@/lib/api";
|
||||
import { PostThoughtForm } from "@/components/post-thought-form";
|
||||
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";
|
||||
@@ -62,17 +61,6 @@ 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 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: [] }))
|
||||
@@ -93,7 +81,7 @@ 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 />
|
||||
@@ -111,14 +99,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
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -44,6 +44,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";
|
||||
@@ -126,9 +127,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"
|
||||
@@ -277,19 +275,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't posted any public thoughts yet.
|
||||
</p>
|
||||
</Card>
|
||||
<EmptyState message="This user hasn't posted any public thoughts yet." />
|
||||
)}
|
||||
</TabsContent>
|
||||
{isOwnProfile && (
|
||||
|
||||
@@ -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}`);
|
||||
}
|
||||
|
||||
12
thoughts-frontend/components/empty-state.tsx
Normal file
12
thoughts-frontend/components/empty-state.tsx
Normal 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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
34
thoughts-frontend/components/loading-skeleton.tsx
Normal file
34
thoughts-frontend/components/loading-skeleton.tsx
Normal file
@@ -0,0 +1,34 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
144
thoughts-frontend/components/remote-user-profile/index.tsx
Normal file
144
thoughts-frontend/components/remote-user-profile/index.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
)}
|
||||
|
||||
142
thoughts-frontend/components/thought-form.tsx
Normal file
142
thoughts-frontend/components/thought-form.tsx
Normal 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>
|
||||
}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
{thoughts.map((thought) => (
|
||||
<ThoughtCard
|
||||
key={thought.id}
|
||||
thought={thought}
|
||||
author={author}
|
||||
currentUser={currentUser}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
|
||||
@@ -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,24 +209,24 @@ 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(
|
||||
@@ -254,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
|
||||
);
|
||||
@@ -266,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(),
|
||||
@@ -297,7 +304,7 @@ export const getActorFollowers = (
|
||||
) =>
|
||||
apiFetch(
|
||||
`/federation/actors/${encodeURIComponent(handle)}/followers-list?page=${page}`,
|
||||
{},
|
||||
{ next: { tags: [`remote-actor:${handle}`] } },
|
||||
ActorConnectionPageSchema,
|
||||
token
|
||||
);
|
||||
@@ -309,7 +316,7 @@ export const getActorFollowing = (
|
||||
) =>
|
||||
apiFetch(
|
||||
`/federation/actors/${encodeURIComponent(handle)}/following-list?page=${page}`,
|
||||
{},
|
||||
{ next: { tags: [`remote-actor:${handle}`] } },
|
||||
ActorConnectionPageSchema,
|
||||
token
|
||||
);
|
||||
@@ -317,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
|
||||
@@ -339,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
|
||||
);
|
||||
@@ -351,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) {
|
||||
@@ -375,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
|
||||
);
|
||||
@@ -383,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))
|
||||
);
|
||||
@@ -391,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);
|
||||
@@ -414,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
|
||||
);
|
||||
@@ -438,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
|
||||
);
|
||||
@@ -446,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
8567
thoughts-frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user