seem good
This commit is contained in:
439
frontend/app/auth/page.tsx
Normal file
439
frontend/app/auth/page.tsx
Normal file
@@ -0,0 +1,439 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, Suspense } from "react";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import { useAuth } from "@/lib/auth";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Eye, EyeOff, Loader2, LogIn, UserPlus, KeyRound, Mail } from "lucide-react";
|
||||
import { API_URL } from "@/lib/api";
|
||||
import { UserRole } from "@/lib/types";
|
||||
|
||||
// Default export wraps the inner component in Suspense (required by Next.js
|
||||
// when useSearchParams() is used inside a "use client" page).
|
||||
export default function AuthPage() {
|
||||
return (
|
||||
<Suspense>
|
||||
<AuthPageInner />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function AuthPageInner() {
|
||||
const { currentUser, login, register, refresh } = useAuth();
|
||||
const router = useRouter();
|
||||
const searchParams = useSearchParams();
|
||||
const resetToken = searchParams.get("token") || "";
|
||||
const initialTab = resetToken ? "reset" : "signin";
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [showPwd, setShowPwd] = useState(false);
|
||||
|
||||
// Redirect if already logged in
|
||||
useEffect(() => {
|
||||
if (currentUser) router.replace("/dashboard");
|
||||
}, [currentUser, router]);
|
||||
|
||||
// ── Sign In ───────────────────────────────────────────────────────────────
|
||||
const handleSignIn = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const email = fd.get("email") as string;
|
||||
const password = fd.get("password") as string;
|
||||
setLoading(true);
|
||||
try {
|
||||
await login(email, password);
|
||||
toast.success("Welcome back!");
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Login failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Sign Up ───────────────────────────────────────────────────────────────
|
||||
const handleSignUp = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const name = fd.get("name") as string;
|
||||
const email = fd.get("email") as string;
|
||||
const password = fd.get("password") as string;
|
||||
setLoading(true);
|
||||
try {
|
||||
await register(name, email, password);
|
||||
toast.success("Account created! Welcome!");
|
||||
router.push("/dashboard");
|
||||
router.refresh();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Registration failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Magic Link ────────────────────────────────────────────────────────────
|
||||
const handleMagicLink = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const email = fd.get("email") as string;
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch("/auth/magic-link", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
toast.success("Magic link sent! Check your email.");
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to send magic link");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Password Reset Request ────────────────────────────────────────────────
|
||||
const handleResetRequest = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const email = fd.get("email") as string;
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch("/auth/password-reset/request", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ email }),
|
||||
});
|
||||
toast.success("Reset link sent! Check your email.");
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// ── Password Reset Confirm ────────────────────────────────────────────────
|
||||
const handleResetConfirm = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const token = fd.get("token") as string;
|
||||
const password = fd.get("password") as string;
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch("/auth/password-reset/confirm", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ token, password }),
|
||||
});
|
||||
toast.success("Password updated! You can now sign in.");
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to reset password");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-lg space-y-5">
|
||||
<Tabs defaultValue={initialTab}>
|
||||
<TabsList className="grid w-full grid-cols-3">
|
||||
<TabsTrigger value="signin">Sign In</TabsTrigger>
|
||||
<TabsTrigger value="signup">Sign Up</TabsTrigger>
|
||||
<TabsTrigger value="reset">Reset</TabsTrigger>
|
||||
</TabsList>
|
||||
|
||||
{/* ── Sign In Tab ─────────────────────────────────────────────────── */}
|
||||
<TabsContent value="signin">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<LogIn className="h-5 w-5" /> Sign In
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Sign in to your account to access the dashboard.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<form onSubmit={handleSignIn} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="signin-email">Email</Label>
|
||||
<Input
|
||||
id="signin-email"
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
required
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="signin-password">Password</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="signin-password"
|
||||
name="password"
|
||||
type={showPwd ? "text" : "password"}
|
||||
placeholder="Enter your password"
|
||||
required
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setShowPwd((v) => !v)}
|
||||
>
|
||||
{showPwd ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Sign In
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<Separator />
|
||||
|
||||
<form onSubmit={handleMagicLink} className="space-y-2">
|
||||
<Input
|
||||
id="magic-email"
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="Magic link: enter your email"
|
||||
/>
|
||||
<Button
|
||||
type="submit"
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
disabled={loading}
|
||||
>
|
||||
<Mail className="mr-2 h-4 w-4" />
|
||||
Send magic link
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
<Button
|
||||
variant="outline"
|
||||
className="w-full"
|
||||
onClick={() =>
|
||||
(window.location.href = `${API_URL}/auth/google`)
|
||||
}
|
||||
>
|
||||
<svg className="mr-2 h-4 w-4" viewBox="0 0 24 24">
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"
|
||||
/>
|
||||
<path
|
||||
fill="currentColor"
|
||||
d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"
|
||||
/>
|
||||
</svg>
|
||||
Continue with Google
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* ── Sign Up Tab ─────────────────────────────────────────────────── */}
|
||||
<TabsContent value="signup">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<UserPlus className="h-5 w-5" /> Create Account
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
New sign-ups are assigned the default MEMBER role.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSignUp} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="signup-name">Full Name</Label>
|
||||
<Input
|
||||
id="signup-name"
|
||||
name="name"
|
||||
placeholder="Your full name"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="signup-email">Email</Label>
|
||||
<Input
|
||||
id="signup-email"
|
||||
name="email"
|
||||
type="email"
|
||||
placeholder="you@example.com"
|
||||
required
|
||||
autoComplete="email"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="signup-password">Password</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
id="signup-password"
|
||||
name="password"
|
||||
type={showPwd ? "text" : "password"}
|
||||
placeholder="Create a password"
|
||||
required
|
||||
autoComplete="new-password"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setShowPwd((v) => !v)}
|
||||
>
|
||||
{showPwd ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Create Account
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* ── Reset Password Tab ──────────────────────────────────────────── */}
|
||||
<TabsContent value="reset">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<KeyRound className="h-5 w-5" /> Reset Password
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* Step 1: Request */}
|
||||
<form onSubmit={handleResetRequest} className="space-y-3">
|
||||
<Label>Request reset link</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input name="email" type="email" placeholder="your@email.com" />
|
||||
<Button type="submit" variant="outline" disabled={loading}>
|
||||
{loading && (
|
||||
<Loader2 className="mr-1 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Send
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Step 2: Confirm */}
|
||||
<form onSubmit={handleResetConfirm} className="space-y-3">
|
||||
<Label>Confirm new password</Label>
|
||||
<Input
|
||||
name="token"
|
||||
placeholder="Reset token from email"
|
||||
defaultValue={resetToken}
|
||||
required
|
||||
/>
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
name="password"
|
||||
type={showPwd ? "text" : "password"}
|
||||
placeholder="New password"
|
||||
required
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={() => setShowPwd((v) => !v)}
|
||||
>
|
||||
{showPwd ? (
|
||||
<EyeOff className="h-4 w-4" />
|
||||
) : (
|
||||
<Eye className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<Button type="submit" className="w-full" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Update Password
|
||||
</Button>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* ── Demo credentials card ─────────────────────────────────────────── */}
|
||||
<Card className="border-dashed">
|
||||
<CardContent className="pt-5 space-y-3">
|
||||
<div className="rounded-lg bg-muted p-4 space-y-1">
|
||||
<p className="font-semibold">Demo Admin Account</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Email: <strong>admin@gmail.com</strong>
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Password: <strong>Whatever123$</strong>
|
||||
</p>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
className="mt-2"
|
||||
onClick={() => {
|
||||
const emailInput = document.getElementById(
|
||||
"signin-email"
|
||||
) as HTMLInputElement | null;
|
||||
const pwdInput = document.getElementById(
|
||||
"signin-password"
|
||||
) as HTMLInputElement | null;
|
||||
if (emailInput) emailInput.value = "admin@gmail.com";
|
||||
if (pwdInput) pwdInput.value = "Whatever123$";
|
||||
document.querySelector<HTMLButtonElement>('[value="signin"]')?.click();
|
||||
}}
|
||||
>
|
||||
Use these credentials
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2 text-sm">
|
||||
<p className="font-semibold">Role Permissions</p>
|
||||
<div className="space-y-1 text-muted-foreground">
|
||||
<p>
|
||||
<span className="font-medium text-blue-600">MEMBER</span> — View
|
||||
blog posts only
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium text-amber-600">MANAGER</span> —
|
||||
View all + create (draft only)
|
||||
</p>
|
||||
<p>
|
||||
<span className="font-medium text-red-600">ADMIN</span> — Full
|
||||
CRUD access + user management
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
308
frontend/app/blog/[slug]/page.tsx
Normal file
308
frontend/app/blog/[slug]/page.tsx
Normal file
@@ -0,0 +1,308 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { marked } from "marked";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { BlogPost, PaginatedResult, TagCloudItem } from "@/lib/types";
|
||||
import { ViewTracker } from "./view-tracker";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Eye, TrendingUp, ArrowLeft, Calendar } from "lucide-react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
interface Props {
|
||||
params: Promise<{ slug: string }>;
|
||||
}
|
||||
|
||||
export async function generateMetadata({ params }: Props) {
|
||||
const { slug } = await params;
|
||||
try {
|
||||
const { post } = await apiFetch<{ post: BlogPost }>(
|
||||
`/blog-posts/public/${slug}`
|
||||
);
|
||||
return {
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
openGraph: {
|
||||
title: post.title,
|
||||
description: post.excerpt,
|
||||
images: post.featuredImageUrl ? [post.featuredImageUrl] : [],
|
||||
},
|
||||
};
|
||||
} catch {
|
||||
return { title: "Post not found" };
|
||||
}
|
||||
}
|
||||
|
||||
async function getPost(slug: string): Promise<BlogPost | null> {
|
||||
try {
|
||||
const data = await apiFetch<{ success: boolean; post: BlogPost }>(
|
||||
`/blog-posts/public/${slug}`
|
||||
);
|
||||
return data.post;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getRelatedPosts(post: BlogPost): Promise<BlogPost[]> {
|
||||
try {
|
||||
// Get posts with shared category
|
||||
const cat = post.categories[0];
|
||||
if (cat) {
|
||||
const result = await apiFetch<PaginatedResult<BlogPost>>(
|
||||
`/blog-posts/public?category=${encodeURIComponent(cat)}&pageSize=4`
|
||||
);
|
||||
const filtered = result.items.filter((p) => p.id !== post.id);
|
||||
if (filtered.length > 0) return filtered.slice(0, 4);
|
||||
}
|
||||
// Fallback: latest
|
||||
const result = await apiFetch<PaginatedResult<BlogPost>>(
|
||||
"/blog-posts/public?pageSize=4"
|
||||
);
|
||||
return result.items.filter((p) => p.id !== post.id).slice(0, 4);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function getPopularPosts(excludeId: string): Promise<BlogPost[]> {
|
||||
try {
|
||||
const result = await apiFetch<PaginatedResult<BlogPost>>(
|
||||
"/blog-posts/public?sort=most_viewed&pageSize=6"
|
||||
);
|
||||
return result.items.filter((p) => p.id !== excludeId).slice(0, 5);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function getTopTags(): Promise<TagCloudItem[]> {
|
||||
try {
|
||||
const result = await apiFetch<PaginatedResult<BlogPost>>(
|
||||
"/blog-posts/public?pageSize=100"
|
||||
);
|
||||
const counts: Record<string, number> = {};
|
||||
for (const post of result.items) {
|
||||
for (const tag of post.tags || []) {
|
||||
const t = tag.trim();
|
||||
if (t) counts[t] = (counts[t] || 0) + 1;
|
||||
}
|
||||
}
|
||||
return Object.entries(counts)
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 20);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export default async function BlogDetailPage({ params }: Props) {
|
||||
const { slug } = await params;
|
||||
const post = await getPost(slug);
|
||||
|
||||
if (!post) return notFound();
|
||||
|
||||
const [relatedPosts, popularPosts, topTags] = await Promise.all([
|
||||
getRelatedPosts(post),
|
||||
getPopularPosts(post.id),
|
||||
getTopTags(),
|
||||
]);
|
||||
|
||||
const contentHtml =
|
||||
post.contentFormat === "markdown"
|
||||
? await marked(post.content)
|
||||
: post.content;
|
||||
|
||||
const publishedDate = new Date(post.createdAt).toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
<ViewTracker slug={slug} />
|
||||
|
||||
{/* ── Back button ────────────────────────────────────────────────────── */}
|
||||
<Button asChild variant="ghost" size="sm" className="-ml-2">
|
||||
<Link href="/">
|
||||
<ArrowLeft className="h-4 w-4 mr-1" /> Back to Blog
|
||||
</Link>
|
||||
</Button>
|
||||
|
||||
{/* ── Article ────────────────────────────────────────────────────────── */}
|
||||
<article className="rounded-2xl border bg-card p-5 shadow-sm">
|
||||
{/* Categories */}
|
||||
{post.categories.length > 0 && (
|
||||
<div className="mb-3 flex flex-wrap gap-2">
|
||||
{post.categories.map((cat) => (
|
||||
<Badge key={cat} variant="secondary" className="uppercase tracking-wide text-xs">
|
||||
{cat}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<h1 className="text-3xl font-bold leading-tight">{post.title}</h1>
|
||||
|
||||
{post.excerpt && (
|
||||
<p className="mt-3 text-lg text-muted-foreground">{post.excerpt}</p>
|
||||
)}
|
||||
|
||||
{/* Meta */}
|
||||
<div className="mt-3 flex flex-wrap gap-3 text-sm text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Calendar className="h-3 w-3" /> {publishedDate}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Eye className="h-3 w-3" /> {post.views.toLocaleString()} views
|
||||
</span>
|
||||
{post.author && (
|
||||
<span>by {post.author.name || post.author.email}</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Featured image */}
|
||||
{post.featuredImageUrl && (
|
||||
<div className="mt-5 relative h-64 md:h-96 w-full overflow-hidden rounded-xl">
|
||||
<Image
|
||||
src={post.featuredImageUrl}
|
||||
alt={post.featuredImageAlt || post.title}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 768px) 100vw, 800px"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tags */}
|
||||
{post.tags.length > 0 && (
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{post.tags.map((tag) => (
|
||||
<Link key={tag} href={`/?tags=${encodeURIComponent(tag)}`}>
|
||||
<Badge variant="outline" className="cursor-pointer hover:bg-muted">
|
||||
#{tag}
|
||||
</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<Separator className="my-6" />
|
||||
|
||||
{/* Content */}
|
||||
<div
|
||||
className="prose prose-zinc dark:prose-invert max-w-none
|
||||
prose-headings:font-bold prose-headings:tracking-tight
|
||||
prose-h1:text-3xl prose-h2:text-2xl prose-h3:text-xl
|
||||
prose-a:text-primary prose-a:no-underline hover:prose-a:underline
|
||||
prose-code:bg-muted prose-code:px-1 prose-code:py-0.5 prose-code:rounded
|
||||
prose-pre:bg-muted prose-pre:border prose-pre:rounded-lg
|
||||
prose-blockquote:border-l-4 prose-blockquote:border-muted-foreground/30
|
||||
prose-img:rounded-xl prose-img:border"
|
||||
dangerouslySetInnerHTML={{ __html: contentHtml }}
|
||||
/>
|
||||
</article>
|
||||
|
||||
{/* ── Related + Sidebar ──────────────────────────────────────────────── */}
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_20rem]">
|
||||
{/* Related posts */}
|
||||
<section className="rounded-2xl border bg-card p-5">
|
||||
<h2 className="mb-4 text-xl font-bold">More from the blog</h2>
|
||||
{relatedPosts.length > 0 ? (
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{relatedPosts.map((related) => (
|
||||
<article
|
||||
key={related.id}
|
||||
className="rounded-xl border bg-muted/30 p-4"
|
||||
>
|
||||
{related.categories.length > 0 && (
|
||||
<div className="mb-2 flex flex-wrap gap-1">
|
||||
{related.categories.slice(0, 2).map((cat) => (
|
||||
<Badge
|
||||
key={cat}
|
||||
variant="secondary"
|
||||
className="text-xs uppercase"
|
||||
>
|
||||
{cat}
|
||||
</Badge>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<Link href={`/blog/${related.slug}`} className="group">
|
||||
<h3 className="font-semibold leading-tight group-hover:text-primary transition-colors line-clamp-2">
|
||||
{related.title}
|
||||
</h3>
|
||||
</Link>
|
||||
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
|
||||
{related.excerpt}
|
||||
</p>
|
||||
<p className="mt-1 text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Eye className="h-3 w-3" /> {related.views.toLocaleString()}
|
||||
</p>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No related posts yet.
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
|
||||
{/* Sidebar */}
|
||||
<aside className="space-y-4">
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4" /> Popular Posts
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{popularPosts.map((p) => (
|
||||
<Link
|
||||
key={p.slug}
|
||||
href={`/blog/${p.slug}`}
|
||||
className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm font-medium hover:bg-muted transition-colors"
|
||||
>
|
||||
<span className="line-clamp-1 mr-2">{p.title}</span>
|
||||
<span className="text-muted-foreground shrink-0 flex items-center gap-1">
|
||||
<Eye className="h-3 w-3" />
|
||||
{p.views.toLocaleString()}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base">Tags</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{topTags.map((tag) => (
|
||||
<Link
|
||||
key={tag.name}
|
||||
href={`/?tags=${encodeURIComponent(tag.name)}`}
|
||||
>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="cursor-pointer hover:bg-muted transition-colors"
|
||||
>
|
||||
#{tag.name}
|
||||
</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
13
frontend/app/blog/[slug]/view-tracker.tsx
Normal file
13
frontend/app/blog/[slug]/view-tracker.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
|
||||
export function ViewTracker({ slug }: { slug: string }) {
|
||||
useEffect(() => {
|
||||
clientFetch(`/blog-posts/public/${slug}/view`, { method: "POST" }).catch(
|
||||
() => {}
|
||||
);
|
||||
}, [slug]);
|
||||
return null;
|
||||
}
|
||||
200
frontend/app/dashboard/components/create-post-form.tsx
Normal file
200
frontend/app/dashboard/components/create-post-form.tsx
Normal file
@@ -0,0 +1,200 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Loader2, PlusCircle } from "lucide-react";
|
||||
import { PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||
|
||||
interface Props {
|
||||
userRole: UserRole;
|
||||
onCreated: () => void;
|
||||
}
|
||||
|
||||
export function CreatePostForm({ userRole, onCreated }: Props) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [status, setStatus] = useState<PostStatus>(PostStatus.DRAFT);
|
||||
const [contentFormat, setContentFormat] = useState<ContentFormat>(
|
||||
ContentFormat.MARKDOWN
|
||||
);
|
||||
const [isFeatured, setIsFeatured] = useState("false");
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const body = {
|
||||
title: fd.get("title"),
|
||||
slug: fd.get("slug") || undefined,
|
||||
excerpt: fd.get("excerpt") || undefined,
|
||||
content: fd.get("content"),
|
||||
contentFormat,
|
||||
status: userRole === UserRole.ADMIN ? status : PostStatus.DRAFT,
|
||||
isFeatured: isFeatured === "true",
|
||||
categories: fd.get("categories") || undefined,
|
||||
tags: fd.get("tags") || undefined,
|
||||
featuredImageUrl: fd.get("featuredImageUrl") || undefined,
|
||||
featuredImageAlt: fd.get("featuredImageAlt") || undefined,
|
||||
};
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch("/blog-posts", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post created!");
|
||||
(e.target as HTMLFormElement).reset();
|
||||
onCreated();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Failed to create post");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="space-y-4 rounded-xl border bg-muted/30 p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold flex items-center gap-2">
|
||||
<PlusCircle className="h-4 w-4" /> Create New Post
|
||||
</h3>
|
||||
{userRole !== UserRole.ADMIN && (
|
||||
<span className="text-xs text-muted-foreground border rounded-full px-2 py-0.5">
|
||||
Status forced to Draft (Manager)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-title">Title *</Label>
|
||||
<Input id="cp-title" name="title" placeholder="Post title" required />
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-slug">Slug (optional)</Label>
|
||||
<Input id="cp-slug" name="slug" placeholder="custom-slug" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-excerpt">Excerpt</Label>
|
||||
<Textarea
|
||||
id="cp-excerpt"
|
||||
name="excerpt"
|
||||
placeholder="Short description…"
|
||||
rows={2}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-content">Content *</Label>
|
||||
<Textarea
|
||||
id="cp-content"
|
||||
name="content"
|
||||
placeholder="Write your post content…"
|
||||
rows={8}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<div className="space-y-1">
|
||||
<Label>Format</Label>
|
||||
<Select
|
||||
value={contentFormat}
|
||||
onValueChange={(v) => setContentFormat(v as ContentFormat)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
|
||||
<SelectItem value={ContentFormat.HTML}>HTML</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
{userRole === UserRole.ADMIN && (
|
||||
<>
|
||||
<div className="space-y-1">
|
||||
<Label>Status</Label>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(v) => setStatus(v as PostStatus)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PostStatus.DRAFT}>Draft</SelectItem>
|
||||
<SelectItem value={PostStatus.PUBLISHED}>Published</SelectItem>
|
||||
<SelectItem value={PostStatus.ARCHIVED}>Archived</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label>Featured</Label>
|
||||
<Select value={isFeatured} onValueChange={setIsFeatured}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="false">Not featured</SelectItem>
|
||||
<SelectItem value="true">Featured</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-categories">Categories (comma separated)</Label>
|
||||
<Input
|
||||
id="cp-categories"
|
||||
name="categories"
|
||||
placeholder="backend,api"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-tags">Tags (comma separated)</Label>
|
||||
<Input id="cp-tags" name="tags" placeholder="rest,pagination" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-imgurl">Featured Image URL</Label>
|
||||
<Input
|
||||
id="cp-imgurl"
|
||||
name="featuredImageUrl"
|
||||
placeholder="https://…"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<Label htmlFor="cp-imgalt">Image Alt Text</Label>
|
||||
<Input id="cp-imgalt" name="featuredImageAlt" placeholder="Alt text" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Create Post
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
293
frontend/app/dashboard/components/posts-table.tsx
Normal file
293
frontend/app/dashboard/components/posts-table.tsx
Normal file
@@ -0,0 +1,293 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useCallback } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { BlogPost, PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||
import { CreatePostForm } from "./create-post-form";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Eye, Loader2, Pencil, Trash2, X, Check, ExternalLink } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
interface Props {
|
||||
initialPosts: BlogPost[];
|
||||
userRole: UserRole;
|
||||
}
|
||||
|
||||
export function PostsTable({ initialPosts, userRole }: Props) {
|
||||
const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const refreshPosts = useCallback(async () => {
|
||||
try {
|
||||
const data = await clientFetch<{ posts: BlogPost[]; total: number }>(
|
||||
"/blog-posts?pageSize=50"
|
||||
);
|
||||
setPosts(data.posts);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch(`/blog-posts/${id}`, { method: "DELETE" });
|
||||
toast.success("Post deleted.");
|
||||
setPosts((prev) => prev.filter((p) => p.id !== id));
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Delete failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleUpdate = async (
|
||||
e: React.FormEvent<HTMLFormElement>,
|
||||
id: string
|
||||
) => {
|
||||
e.preventDefault();
|
||||
const fd = new FormData(e.currentTarget);
|
||||
const body: Record<string, unknown> = {
|
||||
title: fd.get("title"),
|
||||
slug: fd.get("slug") || undefined,
|
||||
excerpt: fd.get("excerpt") || undefined,
|
||||
content: fd.get("content"),
|
||||
contentFormat: fd.get("contentFormat"),
|
||||
status: fd.get("status"),
|
||||
isFeatured: fd.get("isFeatured") === "true",
|
||||
categories: fd.get("categories") || undefined,
|
||||
tags: fd.get("tags") || undefined,
|
||||
featuredImageUrl: fd.get("featuredImageUrl") || undefined,
|
||||
featuredImageAlt: fd.get("featuredImageAlt") || undefined,
|
||||
};
|
||||
setLoading(true);
|
||||
try {
|
||||
await clientFetch(`/blog-posts/${id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post updated!");
|
||||
setEditingId(null);
|
||||
await refreshPosts();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Update failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const statusColor: Record<PostStatus, string> = {
|
||||
[PostStatus.PUBLISHED]: "bg-emerald-100 text-emerald-800 border-emerald-200",
|
||||
[PostStatus.DRAFT]: "bg-zinc-100 text-zinc-700 border-zinc-200",
|
||||
[PostStatus.ARCHIVED]: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Create form for ADMIN/MANAGER */}
|
||||
{(userRole === UserRole.ADMIN || userRole === UserRole.MANAGER) && (
|
||||
<CreatePostForm userRole={userRole} onCreated={refreshPosts} />
|
||||
)}
|
||||
|
||||
{/* Posts list */}
|
||||
{posts.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
|
||||
No posts yet.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{posts.map((post) => (
|
||||
<article
|
||||
key={post.id}
|
||||
className="rounded-xl border bg-card p-4 shadow-sm"
|
||||
>
|
||||
{editingId === post.id && userRole === UserRole.ADMIN ? (
|
||||
/* ── Edit form ─────────────────────────────────────────── */
|
||||
<form
|
||||
onSubmit={(e) => handleUpdate(e, post.id)}
|
||||
className="space-y-3"
|
||||
>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="font-semibold text-sm">Editing post</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setEditingId(null)}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Input name="title" defaultValue={post.title} required placeholder="Title" />
|
||||
<Input name="slug" defaultValue={post.slug} placeholder="Slug" />
|
||||
</div>
|
||||
<Textarea name="excerpt" defaultValue={post.excerpt} placeholder="Excerpt" rows={2} />
|
||||
<Textarea name="content" defaultValue={post.content} placeholder="Content" rows={6} required />
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-3">
|
||||
<Select name="contentFormat" defaultValue={post.contentFormat}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
|
||||
<SelectItem value={ContentFormat.HTML}>HTML</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select name="status" defaultValue={post.status}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PostStatus.DRAFT}>Draft</SelectItem>
|
||||
<SelectItem value={PostStatus.PUBLISHED}>Published</SelectItem>
|
||||
<SelectItem value={PostStatus.ARCHIVED}>Archived</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Select name="isFeatured" defaultValue={String(post.isFeatured)}>
|
||||
<SelectTrigger><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="false">Not featured</SelectItem>
|
||||
<SelectItem value="true">Featured</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Input name="categories" defaultValue={post.categories.join(",")} placeholder="Categories" />
|
||||
<Input name="tags" defaultValue={post.tags.join(",")} placeholder="Tags" />
|
||||
</div>
|
||||
<div className="grid gap-2 sm:grid-cols-2">
|
||||
<Input name="featuredImageUrl" defaultValue={post.featuredImageUrl || ""} placeholder="Image URL" />
|
||||
<Input name="featuredImageAlt" defaultValue={post.featuredImageAlt || ""} placeholder="Image Alt" />
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 justify-end">
|
||||
<Button type="button" variant="ghost" onClick={() => setEditingId(null)}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
<Check className="mr-1 h-4 w-4" /> Save
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
) : (
|
||||
/* ── Post card view ─────────────────────────────────────── */
|
||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||
<div className="space-y-1 min-w-0">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<Link
|
||||
href={`/blog/${post.slug}`}
|
||||
className="font-semibold hover:text-primary transition-colors"
|
||||
target="_blank"
|
||||
>
|
||||
{post.title}
|
||||
<ExternalLink className="inline-block ml-1 h-3 w-3" />
|
||||
</Link>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
/{post.slug}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-1.5 pt-1">
|
||||
<span className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${statusColor[post.status]}`}>
|
||||
{post.status}
|
||||
</span>
|
||||
<span className="inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs text-muted-foreground">
|
||||
<Eye className="h-3 w-3" /> {post.views.toLocaleString()}
|
||||
</span>
|
||||
{post.isFeatured && (
|
||||
<Badge variant="secondary" className="text-xs">⭐ featured</Badge>
|
||||
)}
|
||||
{post.author && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
by {post.author.name || post.author.email}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{post.excerpt && (
|
||||
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
|
||||
{post.excerpt}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex flex-wrap gap-1 mt-1">
|
||||
{post.categories.map((c) => (
|
||||
<Badge key={c} variant="secondary" className="text-xs">{c}</Badge>
|
||||
))}
|
||||
{post.tags.map((t) => (
|
||||
<Badge key={t} variant="outline" className="text-xs">#{t}</Badge>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<div className="flex gap-2 shrink-0">
|
||||
{userRole === UserRole.ADMIN && (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setEditingId(post.id)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button variant="outline" size="sm" className="text-destructive border-destructive/30 hover:bg-destructive/5">
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete post?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{post.title}" will be permanently deleted.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => handleDelete(post.id)}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
191
frontend/app/dashboard/components/users-table.tsx
Normal file
191
frontend/app/dashboard/components/users-table.tsx
Normal file
@@ -0,0 +1,191 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { User, UserRole } from "@/lib/types";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Loader2, Pencil, X, Check } from "lucide-react";
|
||||
|
||||
interface Props {
|
||||
initialUsers: User[];
|
||||
}
|
||||
|
||||
const roleColor: Record<UserRole, string> = {
|
||||
[UserRole.ADMIN]: "bg-red-100 text-red-800 border-red-200",
|
||||
[UserRole.MANAGER]: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
[UserRole.MEMBER]: "bg-blue-100 text-blue-700 border-blue-200",
|
||||
};
|
||||
|
||||
export function UsersTable({ initialUsers }: Props) {
|
||||
const [users, setUsers] = useState<User[]>(initialUsers);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [editName, setEditName] = useState("");
|
||||
const [editRole, setEditRole] = useState<UserRole>(UserRole.MEMBER);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const startEdit = (user: User) => {
|
||||
setEditingId(user.id);
|
||||
setEditName(user.name || "");
|
||||
setEditRole(user.role);
|
||||
};
|
||||
|
||||
const cancelEdit = () => {
|
||||
setEditingId(null);
|
||||
};
|
||||
|
||||
const handleUpdate = async (user: User) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
// Update name if changed
|
||||
let updated = user;
|
||||
if (editName !== (user.name || "")) {
|
||||
const res = await clientFetch<{ success: boolean; user: User }>(
|
||||
`/users/${user.id}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ name: editName || undefined }),
|
||||
}
|
||||
);
|
||||
updated = res.user;
|
||||
}
|
||||
|
||||
// Update role if changed
|
||||
if (editRole !== user.role) {
|
||||
const res = await clientFetch<{ success: boolean; user: User }>(
|
||||
`/users/${user.id}/role`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ role: editRole }),
|
||||
}
|
||||
);
|
||||
updated = res.user;
|
||||
}
|
||||
|
||||
toast.success("User updated.");
|
||||
setUsers((prev) => prev.map((u) => (u.id === user.id ? updated : u)));
|
||||
setEditingId(null);
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Update failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
{users.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-8 text-center text-sm text-muted-foreground">
|
||||
No users found.
|
||||
</div>
|
||||
) : (
|
||||
users.map((user) => (
|
||||
<div
|
||||
key={user.id}
|
||||
className="rounded-xl border bg-card p-4 shadow-sm flex flex-wrap items-center gap-3"
|
||||
>
|
||||
{editingId === user.id ? (
|
||||
/* ── Edit row ─────────────────────────────────────────────── */
|
||||
<div className="flex flex-1 flex-wrap items-center gap-2">
|
||||
<Input
|
||||
className="h-8 w-40"
|
||||
placeholder="Name"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
/>
|
||||
<Select
|
||||
value={editRole}
|
||||
onValueChange={(v) => setEditRole(v as UserRole)}
|
||||
>
|
||||
<SelectTrigger className="h-8 w-32">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={UserRole.MEMBER}>MEMBER</SelectItem>
|
||||
<SelectItem value={UserRole.MANAGER}>MANAGER</SelectItem>
|
||||
<SelectItem value={UserRole.ADMIN}>ADMIN</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div className="flex gap-1">
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleUpdate(user)}
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Check className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={cancelEdit}>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
/* ── View row ─────────────────────────────────────────────── */
|
||||
<>
|
||||
<div className="flex flex-1 flex-wrap items-center gap-3 min-w-0">
|
||||
{/* Avatar placeholder */}
|
||||
<div className="h-8 w-8 shrink-0 rounded-full bg-muted flex items-center justify-center text-xs font-semibold uppercase">
|
||||
{(user.name || user.email).charAt(0)}
|
||||
</div>
|
||||
<div className="min-w-0 flex-1">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{user.name ?? (
|
||||
<span className="italic text-muted-foreground">
|
||||
No name
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{user.email}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${roleColor[user.role]}`}
|
||||
>
|
||||
{user.role}
|
||||
</span>
|
||||
|
||||
{!user.isActive && (
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="text-xs text-muted-foreground"
|
||||
>
|
||||
Inactive
|
||||
</Badge>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground shrink-0">
|
||||
Joined {new Date(user.createdAt).toLocaleDateString()}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Actions */}
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => startEdit(user)}
|
||||
>
|
||||
<Pencil className="h-4 w-4" />
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
204
frontend/app/dashboard/page.tsx
Normal file
204
frontend/app/dashboard/page.tsx
Normal file
@@ -0,0 +1,204 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { cookies } from "next/headers";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { BlogPost, User, UserRole, CurrentUser } from "@/lib/types";
|
||||
import { PostsTable } from "./components/posts-table";
|
||||
import { UsersTable } from "./components/users-table";
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "@/components/ui/card";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { LayoutDashboard, Users, FileText, ShieldAlert } from "lucide-react";
|
||||
|
||||
// ── Decode JWT payload without verification (public payload info only) ─────────
|
||||
function decodeJwtPayload(token: string): CurrentUser | null {
|
||||
try {
|
||||
const base64Payload = token.split(".")[1];
|
||||
const decoded = Buffer.from(base64Payload, "base64url").toString("utf-8");
|
||||
return JSON.parse(decoded) as CurrentUser;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const roleColor: Record<UserRole, string> = {
|
||||
[UserRole.ADMIN]: "bg-red-100 text-red-800 border-red-200",
|
||||
[UserRole.MANAGER]: "bg-amber-100 text-amber-800 border-amber-200",
|
||||
[UserRole.MEMBER]: "bg-blue-100 text-blue-700 border-blue-200",
|
||||
};
|
||||
|
||||
export default async function DashboardPage() {
|
||||
// ── Auth check ─────────────────────────────────────────────────────────────
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get("accessToken")?.value;
|
||||
|
||||
if (!accessToken) {
|
||||
redirect("/auth");
|
||||
}
|
||||
|
||||
const currentUser = decodeJwtPayload(accessToken);
|
||||
if (!currentUser) {
|
||||
redirect("/auth");
|
||||
}
|
||||
|
||||
// ── Fetch posts ────────────────────────────────────────────────────────────
|
||||
let posts: BlogPost[] = [];
|
||||
try {
|
||||
const data = await apiFetch<{ posts: BlogPost[]; total: number }>(
|
||||
"/blog-posts?pageSize=50"
|
||||
);
|
||||
posts = data.posts;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) {
|
||||
redirect("/auth");
|
||||
}
|
||||
// Non-fatal — show empty list
|
||||
}
|
||||
|
||||
// ── Fetch users (ADMIN only) ───────────────────────────────────────────────
|
||||
let users: User[] = [];
|
||||
if (currentUser.role === UserRole.ADMIN) {
|
||||
try {
|
||||
const data = await apiFetch<{ users: User[]; total: number }>(
|
||||
"/users?pageSize=50"
|
||||
);
|
||||
users = data.users;
|
||||
} catch {
|
||||
// Non-fatal — show empty list
|
||||
}
|
||||
}
|
||||
|
||||
const displayName = currentUser.name || currentUser.email;
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
{/* ── Header ──────────────────────────────────────────────────────────── */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<LayoutDashboard className="h-6 w-6 text-muted-foreground" />
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold">Dashboard</h1>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Manage your blog content and users
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-muted-foreground">{displayName}</span>
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-medium ${roleColor[currentUser.role as UserRole]}`}
|
||||
>
|
||||
{currentUser.role}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ── Stats strip ─────────────────────────────────────────────────────── */}
|
||||
<div className="grid gap-4 sm:grid-cols-3">
|
||||
<Card>
|
||||
<CardContent className="pt-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileText className="h-8 w-8 text-muted-foreground/60" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">{posts.length}</p>
|
||||
<p className="text-xs text-muted-foreground">Total posts</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileText className="h-8 w-8 text-emerald-500/60" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">
|
||||
{posts.filter((p) => p.status === "published").length}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">Published</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
<Card>
|
||||
<CardContent className="pt-5">
|
||||
<div className="flex items-center gap-3">
|
||||
<FileText className="h-8 w-8 text-zinc-400/60" />
|
||||
<div>
|
||||
<p className="text-2xl font-bold">
|
||||
{posts.filter((p) => p.status === "draft").length}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">Drafts</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* ── Posts section ───────────────────────────────────────────────────── */}
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-5 w-5 text-muted-foreground" />
|
||||
<h2 className="text-xl font-semibold">Posts</h2>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{posts.length}
|
||||
</Badge>
|
||||
</div>
|
||||
<PostsTable initialPosts={posts} userRole={currentUser.role as UserRole} />
|
||||
</section>
|
||||
|
||||
{/* ── Users section (ADMIN only) ───────────────────────────────────────── */}
|
||||
{currentUser.role === UserRole.ADMIN && (
|
||||
<>
|
||||
<Separator />
|
||||
<section className="space-y-4">
|
||||
<div className="flex items-center gap-2">
|
||||
<Users className="h-5 w-5 text-muted-foreground" />
|
||||
<h2 className="text-xl font-semibold">Users</h2>
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
{users.length}
|
||||
</Badge>
|
||||
</div>
|
||||
{users.length === 0 ? (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<ShieldAlert className="h-4 w-4" /> No users loaded
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Unable to fetch user list. Check your backend connection.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
) : (
|
||||
<UsersTable initialUsers={users} />
|
||||
)}
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* ── Member notice ───────────────────────────────────────────────────── */}
|
||||
{currentUser.role === UserRole.MEMBER && (
|
||||
<Card className="border-dashed">
|
||||
<CardHeader>
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<ShieldAlert className="h-4 w-4 text-muted-foreground" />
|
||||
Read-only access
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
You have the <strong>MEMBER</strong> role. You can view posts but
|
||||
cannot create, edit, or delete them. Contact an admin to upgrade
|
||||
your role.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import { AuthProvider } from "@/lib/auth";
|
||||
import { Navbar } from "@/components/navbar";
|
||||
import { Toaster } from "@/components/ui/sonner";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
@@ -13,8 +16,12 @@ const geistMono = Geist_Mono({
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Duc Binh's Blog",
|
||||
description: "Fastify + Nextjs + Postgres",
|
||||
title: {
|
||||
default: "Duc Binh Blog",
|
||||
template: "%s | Duc Binh Blog",
|
||||
},
|
||||
description:
|
||||
"Practical engineering stories — fast backend patterns, frontend craft, and product lessons.",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -25,9 +32,15 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased min-h-screen bg-background`}
|
||||
>
|
||||
{children}
|
||||
<AuthProvider>
|
||||
<Navbar />
|
||||
<main className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
|
||||
{children}
|
||||
</main>
|
||||
<Toaster position="top-right" richColors />
|
||||
</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
@@ -1,12 +1,332 @@
|
||||
import { Suspense } from "react";
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { BlogPost, PaginatedResult, TagCloudItem } from "@/lib/types";
|
||||
import { PostCard } from "@/components/post-card";
|
||||
import { Pagination } from "@/components/pagination";
|
||||
import { PostFilterForm } from "@/components/post-filter-form";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Eye, Star, TrendingUp } from "lucide-react";
|
||||
|
||||
interface HomeSearchParams {
|
||||
q?: string;
|
||||
tags?: string;
|
||||
category?: string;
|
||||
sort?: string;
|
||||
page?: string;
|
||||
pageSize?: string;
|
||||
}
|
||||
|
||||
async function getFeatured(): Promise<BlogPost[]> {
|
||||
try {
|
||||
return await apiFetch<BlogPost[]>("/blog-posts/public/featured");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function getPosts(
|
||||
params: HomeSearchParams
|
||||
): Promise<PaginatedResult<BlogPost>> {
|
||||
const qs = new URLSearchParams();
|
||||
if (params.q) qs.set("q", params.q);
|
||||
if (params.tags) qs.set("tags", params.tags);
|
||||
if (params.category) qs.set("category", params.category);
|
||||
if (params.sort) qs.set("sort", params.sort);
|
||||
qs.set("page", params.page || "1");
|
||||
qs.set("pageSize", params.pageSize || "9");
|
||||
try {
|
||||
return await apiFetch<PaginatedResult<BlogPost>>(
|
||||
`/blog-posts/public?${qs.toString()}`
|
||||
);
|
||||
} catch {
|
||||
return { items: [], total: 0, page: 1, pageSize: 9, totalPages: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
async function getAllPostsForCloud(): Promise<BlogPost[]> {
|
||||
try {
|
||||
const result = await apiFetch<PaginatedResult<BlogPost>>(
|
||||
"/blog-posts/public?pageSize=100"
|
||||
);
|
||||
return result.items;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function buildTagCloud(posts: BlogPost[]): TagCloudItem[] {
|
||||
const counts: Record<string, number> = {};
|
||||
for (const post of posts) {
|
||||
for (const tag of post.tags || []) {
|
||||
const t = tag.trim();
|
||||
if (t) counts[t] = (counts[t] || 0) + 1;
|
||||
}
|
||||
}
|
||||
return Object.entries(counts)
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 20);
|
||||
}
|
||||
|
||||
function buildCategoryCloud(posts: BlogPost[]): TagCloudItem[] {
|
||||
const counts: Record<string, number> = {};
|
||||
for (const post of posts) {
|
||||
for (const cat of post.categories || []) {
|
||||
const c = cat.trim();
|
||||
if (c) counts[c] = (counts[c] || 0) + 1;
|
||||
}
|
||||
}
|
||||
return Object.entries(counts)
|
||||
.map(([name, count]) => ({ name, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
.slice(0, 10);
|
||||
}
|
||||
|
||||
export default async function HomePage({
|
||||
searchParams,
|
||||
}: {
|
||||
searchParams: Promise<HomeSearchParams>;
|
||||
}) {
|
||||
const params = await searchParams;
|
||||
|
||||
const [featured, postsResult, allPosts, popularResult] = await Promise.all([
|
||||
getFeatured(),
|
||||
getPosts(params),
|
||||
getAllPostsForCloud(),
|
||||
apiFetch<PaginatedResult<BlogPost>>(
|
||||
"/blog-posts/public?sort=most_viewed&pageSize=5"
|
||||
).catch(() => ({ items: [] as BlogPost[] })),
|
||||
]);
|
||||
|
||||
const topTags = buildTagCloud(allPosts);
|
||||
const topCategories = buildCategoryCloud(allPosts);
|
||||
const popularPosts = (popularResult as PaginatedResult<BlogPost>).items || [];
|
||||
const { items: posts, page, totalPages, total } = postsResult;
|
||||
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<>
|
||||
<div>
|
||||
<Button>Blank page with nextjs + Shadcn ui</Button>
|
||||
<div className="space-y-6">
|
||||
{/* ── Hero ──────────────────────────────────────────────────────────── */}
|
||||
<section className="rounded-2xl border bg-gradient-to-r from-background via-muted/30 to-background p-5">
|
||||
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||
<div className="max-w-2xl">
|
||||
<h1 className="text-3xl font-bold tracking-tight">
|
||||
Practical Engineering Stories
|
||||
</h1>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
Fast backend patterns, frontend craft, and product lessons from
|
||||
shipping real systems.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{topCategories.slice(0, 6).map((c) => (
|
||||
<Link
|
||||
key={c.name}
|
||||
href={`/?category=${encodeURIComponent(c.name)}`}
|
||||
>
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className="cursor-pointer hover:bg-secondary/80"
|
||||
>
|
||||
{c.name} ({c.count})
|
||||
</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* ── Featured posts ─────────────────────────────────────────────────── */}
|
||||
{featured.length > 0 && (
|
||||
<section className="rounded-2xl border bg-gradient-to-r from-background via-sky-50 to-emerald-50 dark:via-sky-950/20 dark:to-emerald-950/20 p-5">
|
||||
<div className="flex items-center gap-2 mb-4">
|
||||
<Star className="h-4 w-4 text-amber-500 fill-amber-500" />
|
||||
<h2 className="font-semibold text-lg">Featured</h2>
|
||||
</div>
|
||||
<div className="grid gap-4 lg:grid-cols-[1.5fr_1fr]">
|
||||
{/* Primary featured */}
|
||||
<article className="rounded-xl border bg-background/80 p-5">
|
||||
<Badge className="mb-3 bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200 border-amber-200">
|
||||
Featured pick
|
||||
</Badge>
|
||||
{featured[0].featuredImageUrl && (
|
||||
<Link href={`/blog/${featured[0].slug}`} className="block mb-4">
|
||||
<div className="relative h-52 w-full overflow-hidden rounded-lg">
|
||||
<Image
|
||||
src={featured[0].featuredImageUrl}
|
||||
alt={featured[0].featuredImageAlt || featured[0].title}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="(max-width: 1024px) 100vw, 60vw"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
)}
|
||||
<Link href={`/blog/${featured[0].slug}`} className="group">
|
||||
<h2 className="text-2xl font-bold leading-tight group-hover:text-primary transition-colors">
|
||||
{featured[0].title}
|
||||
</h2>
|
||||
</Link>
|
||||
<p className="mt-2 text-muted-foreground">
|
||||
{featured[0].excerpt}
|
||||
</p>
|
||||
<p className="mt-2 text-sm text-muted-foreground flex items-center gap-1">
|
||||
<Eye className="h-3 w-3" />
|
||||
{featured[0].views.toLocaleString()} views
|
||||
</p>
|
||||
</article>
|
||||
|
||||
{/* Secondary featured */}
|
||||
<div className="grid gap-3">
|
||||
{featured.slice(1).map((post) => (
|
||||
<article
|
||||
key={post.id}
|
||||
className="rounded-xl border bg-background/80 p-4 flex gap-3"
|
||||
>
|
||||
{post.featuredImageUrl && (
|
||||
<div className="relative h-16 w-16 shrink-0 overflow-hidden rounded-lg">
|
||||
<Image
|
||||
src={post.featuredImageUrl}
|
||||
alt={post.featuredImageAlt || post.title}
|
||||
fill
|
||||
className="object-cover"
|
||||
sizes="64px"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0">
|
||||
<Link href={`/blog/${post.slug}`} className="group">
|
||||
<h3 className="font-semibold leading-tight group-hover:text-primary transition-colors line-clamp-2">
|
||||
{post.title}
|
||||
</h3>
|
||||
</Link>
|
||||
<p className="mt-1 text-sm text-muted-foreground line-clamp-2">
|
||||
{post.excerpt}
|
||||
</p>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* ── Main content + sidebar ─────────────────────────────────────────── */}
|
||||
<div className="grid gap-6 lg:grid-cols-[1fr_20rem]">
|
||||
<div className="space-y-4">
|
||||
{/* Filter form */}
|
||||
<Suspense fallback={null}>
|
||||
<PostFilterForm
|
||||
topCategories={topCategories}
|
||||
currentQ={params.q || ""}
|
||||
currentCategory={params.category || ""}
|
||||
currentSort={params.sort || "newest"}
|
||||
currentTags={params.tags || ""}
|
||||
/>
|
||||
</Suspense>
|
||||
|
||||
{/* Post grid */}
|
||||
{posts.length === 0 ? (
|
||||
<div className="rounded-xl border bg-muted/30 p-8 text-center">
|
||||
<p className="text-muted-foreground">
|
||||
No posts found for this filter.
|
||||
</p>
|
||||
<Button asChild variant="link" className="mt-2">
|
||||
<Link href="/">Clear filters</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{posts.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Pagination */}
|
||||
<Suspense fallback={null}>
|
||||
<Pagination page={page} totalPages={totalPages} total={total} />
|
||||
</Suspense>
|
||||
</div>
|
||||
|
||||
{/* Sidebar */}
|
||||
<aside className="space-y-4">
|
||||
{/* Popular Posts */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center gap-2">
|
||||
<TrendingUp className="h-4 w-4" /> Popular Posts
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-2">
|
||||
{popularPosts.map((post) => (
|
||||
<Link
|
||||
key={post.slug}
|
||||
href={`/blog/${post.slug}`}
|
||||
className="flex items-center justify-between rounded-lg border px-3 py-2 text-sm font-medium hover:bg-muted transition-colors"
|
||||
>
|
||||
<span className="line-clamp-1 mr-2">{post.title}</span>
|
||||
<span className="text-muted-foreground shrink-0 flex items-center gap-1">
|
||||
<Eye className="h-3 w-3" />
|
||||
{post.views.toLocaleString()}
|
||||
</span>
|
||||
</Link>
|
||||
))}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Newsletter */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base">Newsletter</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
One practical note every Friday.
|
||||
</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Input type="email" placeholder="you@example.com" />
|
||||
<Button className="w-full">Join</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Tag Cloud */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base">Tag Cloud</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{topTags.map((tag) => (
|
||||
<Link
|
||||
key={tag.name}
|
||||
href={`/?tags=${encodeURIComponent(tag.name)}`}
|
||||
>
|
||||
<Badge
|
||||
variant="outline"
|
||||
className="cursor-pointer hover:bg-muted transition-colors"
|
||||
>
|
||||
#{tag.name} ({tag.count})
|
||||
</Badge>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Separator />
|
||||
<p className="text-xs text-center text-muted-foreground">
|
||||
Built with NestJS + Next.js 16 + shadcn/ui
|
||||
</p>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user