mirror change from https://github.com/binhkid2/FullStack-Blog-Nestjs-Nextjs-Postgres
This commit is contained in:
86
frontend/app/api/upload-image/route.ts
Normal file
86
frontend/app/api/upload-image/route.ts
Normal file
@@ -0,0 +1,86 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
|
||||
const R2_WORKER = process.env.UPLOAD_R2_WORKER_API;
|
||||
const R2_API_KEY = process.env.R2_UPLOAD_API_KEY;
|
||||
|
||||
export interface UploadImageResponse {
|
||||
success: true;
|
||||
url: string;
|
||||
key: string;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/upload-image
|
||||
*
|
||||
* Accepts a multipart/form-data body with a single "file" field.
|
||||
* Proxies the binary to the Cloudflare R2 worker using the server-side API key
|
||||
* (the key is never exposed to the browser).
|
||||
*
|
||||
* Returns: { success, url, key, contentType }
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
console.log(R2_WORKER);
|
||||
console.log(R2_API_KEY);
|
||||
if (!R2_WORKER || !R2_API_KEY) {
|
||||
return NextResponse.json(
|
||||
{ error: "R2 upload is not configured. Set UPLOAD_R2_WORKER_API and R2_UPLOAD_API_KEY." },
|
||||
{ status: 503 }
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const formData = await req.formData();
|
||||
const file = formData.get("file");
|
||||
|
||||
if (!file || !(file instanceof File)) {
|
||||
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
||||
}
|
||||
|
||||
// Validate file type
|
||||
const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml", "image/avif"];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
return NextResponse.json(
|
||||
{ error: `Unsupported file type: ${file.type}. Allowed: JPEG, PNG, GIF, WebP, SVG, AVIF.` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Validate file size (max 10 MB)
|
||||
const MAX_BYTES = 10 * 1024 * 1024;
|
||||
if (file.size > MAX_BYTES) {
|
||||
return NextResponse.json(
|
||||
{ error: `File is too large (${(file.size / 1024 / 1024).toFixed(1)} MB). Maximum is 10 MB.` },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// Send binary to R2 worker
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const r2Res = await fetch(`${R2_WORKER}/upload`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"X-Api-Key": R2_API_KEY,
|
||||
"Content-Type": file.type,
|
||||
},
|
||||
body: arrayBuffer,
|
||||
});
|
||||
|
||||
if (!r2Res.ok) {
|
||||
let errMsg = `R2 worker error ${r2Res.status}`;
|
||||
try {
|
||||
const body = await r2Res.json();
|
||||
errMsg = body?.error || body?.message || errMsg;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return NextResponse.json({ error: errMsg }, { status: 502 });
|
||||
}
|
||||
|
||||
const data = (await r2Res.json()) as UploadImageResponse;
|
||||
return NextResponse.json(data);
|
||||
} catch (err) {
|
||||
console.error("[upload-image] Unexpected error:", err);
|
||||
return NextResponse.json({ error: "Upload failed" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
373
frontend/app/dashboard/components/post-sheet.tsx
Normal file
373
frontend/app/dashboard/components/post-sheet.tsx
Normal file
@@ -0,0 +1,373 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { clientFetch } from "@/lib/api";
|
||||
import { toast } from "sonner";
|
||||
import { BlogPost, PostStatus, ContentFormat, UserRole } from "@/lib/types";
|
||||
import { TiptapEditor } from "@/components/dashboard/tiptap-editor";
|
||||
import { ImageUploader } from "@/components/dashboard/image-uploader";
|
||||
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 { Switch } from "@/components/ui/switch";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
SheetDescription,
|
||||
} from "@/components/ui/sheet";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Loader2, FileText, Settings2 } from "lucide-react";
|
||||
|
||||
interface Props {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
/** If provided, the sheet is in edit mode. Otherwise, create mode. */
|
||||
post?: BlogPost | null;
|
||||
userRole: UserRole;
|
||||
onSuccess: () => void;
|
||||
}
|
||||
|
||||
const defaultStatus = (role: UserRole): PostStatus =>
|
||||
role === UserRole.ADMIN ? PostStatus.PUBLISHED : PostStatus.DRAFT;
|
||||
|
||||
export function PostSheet({ open, onOpenChange, post, userRole, onSuccess }: Props) {
|
||||
const isEdit = !!post;
|
||||
|
||||
/* ── form state ─────────────────────────────────────────────────────────── */
|
||||
const [title, setTitle] = useState("");
|
||||
const [slug, setSlug] = useState("");
|
||||
const [excerpt, setExcerpt] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [contentFormat, setContentFormat] = useState<ContentFormat>(ContentFormat.HTML);
|
||||
const [status, setStatus] = useState<PostStatus>(defaultStatus(userRole));
|
||||
const [isFeatured, setIsFeatured] = useState(false);
|
||||
const [categories, setCategories] = useState("");
|
||||
const [tags, setTags] = useState("");
|
||||
const [imageUrl, setImageUrl] = useState("");
|
||||
const [imageAlt, setImageAlt] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
/* ── populate when sheet opens ──────────────────────────────────────────── */
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
if (post) {
|
||||
setTitle(post.title);
|
||||
setSlug(post.slug);
|
||||
setExcerpt(post.excerpt ?? "");
|
||||
setContent(post.content ?? "");
|
||||
setContentFormat(post.contentFormat);
|
||||
setStatus(post.status);
|
||||
setIsFeatured(post.isFeatured);
|
||||
setCategories(post.categories.join(","));
|
||||
setTags(post.tags.join(","));
|
||||
setImageUrl(post.featuredImageUrl ?? "");
|
||||
setImageAlt(post.featuredImageAlt ?? "");
|
||||
} else {
|
||||
setTitle("");
|
||||
setSlug("");
|
||||
setExcerpt("");
|
||||
setContent("");
|
||||
setContentFormat(ContentFormat.HTML);
|
||||
setStatus(defaultStatus(userRole));
|
||||
setIsFeatured(false);
|
||||
setCategories("");
|
||||
setTags("");
|
||||
setImageUrl("");
|
||||
setImageAlt("");
|
||||
}
|
||||
}, [open, post, userRole]);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!content || content === "<p></p>") {
|
||||
toast.error("Content cannot be empty.");
|
||||
return;
|
||||
}
|
||||
|
||||
const body = {
|
||||
title: title.trim(),
|
||||
slug: slug.trim() || undefined,
|
||||
excerpt: excerpt.trim() || undefined,
|
||||
content,
|
||||
contentFormat,
|
||||
status: userRole !== UserRole.ADMIN ? PostStatus.DRAFT : status,
|
||||
isFeatured,
|
||||
categories: categories.trim() || undefined,
|
||||
tags: tags.trim() || undefined,
|
||||
featuredImageUrl: imageUrl || undefined,
|
||||
featuredImageAlt: imageAlt || undefined,
|
||||
};
|
||||
|
||||
setLoading(true);
|
||||
try {
|
||||
if (isEdit && post) {
|
||||
await clientFetch(`/blog-posts/${post.id}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post updated!");
|
||||
} else {
|
||||
await clientFetch("/blog-posts", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
toast.success("Post created!");
|
||||
}
|
||||
onOpenChange(false);
|
||||
onSuccess();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Something went wrong");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const statusColor: Record<PostStatus, string> = {
|
||||
[PostStatus.PUBLISHED]: "text-emerald-600",
|
||||
[PostStatus.DRAFT]: "text-zinc-500",
|
||||
[PostStatus.ARCHIVED]: "text-amber-600",
|
||||
};
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={onOpenChange}>
|
||||
{/* Wide sheet — takes 60% of screen on large displays */}
|
||||
<SheetContent
|
||||
side="right"
|
||||
className="w-full sm:max-w-2xl lg:max-w-3xl flex flex-col p-0 gap-0"
|
||||
>
|
||||
{/* ── Sheet header ──────────────────────────────────────────────────── */}
|
||||
<SheetHeader className="px-6 py-4 border-b shrink-0">
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
{isEdit ? "Edit Post" : "New Post"}
|
||||
</SheetTitle>
|
||||
<SheetDescription>
|
||||
{isEdit
|
||||
? `Editing "${post?.title}"`
|
||||
: "Fill in the details below and hit Publish (or save as Draft)."}
|
||||
</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
{/* ── Scrollable form body ──────────────────────────────────────────── */}
|
||||
<form
|
||||
id="post-sheet-form"
|
||||
onSubmit={handleSubmit}
|
||||
className="flex-1 overflow-y-auto"
|
||||
>
|
||||
<div className="px-6 py-5 space-y-5">
|
||||
|
||||
{/* Title + Slug */}
|
||||
<div className="space-y-3">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-title">
|
||||
Title <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="ps-title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="My awesome post"
|
||||
required
|
||||
className="text-base font-medium"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-slug" className="text-muted-foreground text-xs">
|
||||
Slug <span className="text-muted-foreground/60">(auto-generated if empty)</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="ps-slug"
|
||||
value={slug}
|
||||
onChange={(e) => setSlug(e.target.value)}
|
||||
placeholder="my-awesome-post"
|
||||
className="font-mono text-xs"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Content editor */}
|
||||
<div className="space-y-1.5">
|
||||
<Label>
|
||||
Content <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<TiptapEditor
|
||||
value={content}
|
||||
onChange={setContent}
|
||||
placeholder="Write your post content here…"
|
||||
minHeight="340px"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Excerpt */}
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-excerpt">Excerpt</Label>
|
||||
<Textarea
|
||||
id="ps-excerpt"
|
||||
value={excerpt}
|
||||
onChange={(e) => setExcerpt(e.target.value)}
|
||||
placeholder="A short description shown in post listings…"
|
||||
rows={2}
|
||||
className="resize-none"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Settings row */}
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-1.5 text-sm font-medium text-muted-foreground">
|
||||
<Settings2 className="h-3.5 w-3.5" />
|
||||
Post settings
|
||||
</div>
|
||||
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
{/* Status — admin only */}
|
||||
{userRole === UserRole.ADMIN ? (
|
||||
<div className="space-y-1.5">
|
||||
<Label>Status</Label>
|
||||
<Select
|
||||
value={status}
|
||||
onValueChange={(v) => setStatus(v as PostStatus)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={PostStatus.DRAFT}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-zinc-400" />
|
||||
Draft
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={PostStatus.PUBLISHED}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-emerald-500" />
|
||||
Published
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={PostStatus.ARCHIVED}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-amber-500" />
|
||||
Archived
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1.5">
|
||||
<Label className="text-muted-foreground">Status</Label>
|
||||
<div className="flex h-9 items-center text-sm text-muted-foreground border rounded-md px-3">
|
||||
Saved as Draft (Manager)
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Format */}
|
||||
<div className="space-y-1.5">
|
||||
<Label>Content format</Label>
|
||||
<Select
|
||||
value={contentFormat}
|
||||
onValueChange={(v) => setContentFormat(v as ContentFormat)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={ContentFormat.HTML}>HTML (Tiptap)</SelectItem>
|
||||
<SelectItem value={ContentFormat.MARKDOWN}>Markdown</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Categories + Tags */}
|
||||
<div className="grid gap-3 sm:grid-cols-2">
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-cats">Categories</Label>
|
||||
<Input
|
||||
id="ps-cats"
|
||||
value={categories}
|
||||
onChange={(e) => setCategories(e.target.value)}
|
||||
placeholder="tech, tutorials"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="ps-tags">Tags</Label>
|
||||
<Input
|
||||
id="ps-tags"
|
||||
value={tags}
|
||||
onChange={(e) => setTags(e.target.value)}
|
||||
placeholder="nextjs, react"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Featured toggle */}
|
||||
{userRole === UserRole.ADMIN && (
|
||||
<div className="flex items-center justify-between rounded-lg border px-4 py-3">
|
||||
<div>
|
||||
<p className="text-sm font-medium">Featured post</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Shown in the hero/featured section on the home page
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={isFeatured}
|
||||
onCheckedChange={setIsFeatured}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Featured image */}
|
||||
<ImageUploader
|
||||
value={imageUrl}
|
||||
onChange={setImageUrl}
|
||||
altValue={imageAlt}
|
||||
onAltChange={setImageAlt}
|
||||
label="Featured Image"
|
||||
/>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* ── Sticky footer ────────────────────────────────────────────────── */}
|
||||
<div className="border-t px-6 py-4 flex items-center justify-between gap-3 bg-background shrink-0">
|
||||
{isEdit && (
|
||||
<span className={`text-xs font-medium capitalize ${statusColor[status]}`}>
|
||||
● {status}
|
||||
</span>
|
||||
)}
|
||||
<div className="flex gap-2 ml-auto">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={loading}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="submit" form="post-sheet-form" disabled={loading}>
|
||||
{loading && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
|
||||
{isEdit ? "Save changes" : status === PostStatus.PUBLISHED ? "Publish" : "Save Draft"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
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, UserRole } from "@/lib/types";
|
||||
import { PostSheet } from "./post-sheet";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
Eye,
|
||||
Loader2,
|
||||
Pencil,
|
||||
Trash2,
|
||||
PlusCircle,
|
||||
ExternalLink,
|
||||
Star,
|
||||
Search,
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
|
||||
interface Props {
|
||||
initialPosts: BlogPost[];
|
||||
userRole: UserRole;
|
||||
}
|
||||
|
||||
const statusMeta: Record<PostStatus, { label: string; dot: string; row: string }> = {
|
||||
[PostStatus.PUBLISHED]: {
|
||||
label: "Published",
|
||||
dot: "bg-emerald-500",
|
||||
row: "border-l-emerald-400",
|
||||
},
|
||||
[PostStatus.DRAFT]: {
|
||||
label: "Draft",
|
||||
dot: "bg-zinc-400",
|
||||
row: "border-l-zinc-300",
|
||||
},
|
||||
[PostStatus.ARCHIVED]: {
|
||||
label: "Archived",
|
||||
dot: "bg-amber-400",
|
||||
row: "border-l-amber-400",
|
||||
},
|
||||
};
|
||||
|
||||
export function PostsTable({ initialPosts, userRole }: Props) {
|
||||
const [posts, setPosts] = useState<BlogPost[]>(initialPosts);
|
||||
const [sheetOpen, setSheetOpen] = useState(false);
|
||||
const [editingPost, setEditingPost] = useState<BlogPost | null>(null);
|
||||
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
|
||||
const refreshPosts = useCallback(async () => {
|
||||
try {
|
||||
const data = await clientFetch<{ posts: BlogPost[]; total: number }>(
|
||||
"/blog-posts?pageSize=50"
|
||||
);
|
||||
setPosts(data.posts);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}, []);
|
||||
|
||||
const openCreate = () => {
|
||||
setEditingPost(null);
|
||||
setSheetOpen(true);
|
||||
};
|
||||
|
||||
const openEdit = (post: BlogPost) => {
|
||||
setEditingPost(post);
|
||||
setSheetOpen(true);
|
||||
};
|
||||
|
||||
const handleDelete = async (id: string) => {
|
||||
setDeletingId(id);
|
||||
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 {
|
||||
setDeletingId(null);
|
||||
}
|
||||
};
|
||||
|
||||
const canEdit = userRole === UserRole.ADMIN;
|
||||
const canCreate = userRole === UserRole.ADMIN || userRole === UserRole.MANAGER;
|
||||
|
||||
const filtered = search.trim()
|
||||
? posts.filter(
|
||||
(p) =>
|
||||
p.title.toLowerCase().includes(search.toLowerCase()) ||
|
||||
p.slug.toLowerCase().includes(search.toLowerCase())
|
||||
)
|
||||
: posts;
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* ── Toolbar ───────────────────────────────────────────────────────── */}
|
||||
<div className="flex flex-wrap items-center justify-between gap-3 mb-4">
|
||||
<div className="relative">
|
||||
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground" />
|
||||
<Input
|
||||
placeholder="Search posts…"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="pl-8 h-8 w-56 text-sm"
|
||||
/>
|
||||
</div>
|
||||
{canCreate && (
|
||||
<Button size="sm" onClick={openCreate} className="gap-1.5">
|
||||
<PlusCircle className="h-4 w-4" />
|
||||
New Post
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Posts list ────────────────────────────────────────────────────── */}
|
||||
{filtered.length === 0 ? (
|
||||
<div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground">
|
||||
{search
|
||||
? "No posts match your search."
|
||||
: "No posts yet. Create your first post!"}
|
||||
</div>
|
||||
) : (
|
||||
<div className="rounded-xl border overflow-hidden divide-y">
|
||||
{filtered.map((post) => {
|
||||
const meta = statusMeta[post.status];
|
||||
return (
|
||||
<div
|
||||
key={post.id}
|
||||
className={`flex items-start gap-3 px-4 py-3.5 border-l-4 bg-card hover:bg-muted/30 transition-colors ${meta.row}`}
|
||||
>
|
||||
{/* Thumbnail */}
|
||||
{post.featuredImageUrl ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={post.featuredImageUrl}
|
||||
alt={post.featuredImageAlt || ""}
|
||||
className="h-12 w-20 rounded-md object-cover shrink-0 border hidden sm:block"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-12 w-20 rounded-md bg-muted shrink-0 hidden sm:flex items-center justify-center">
|
||||
<span className="text-xs text-muted-foreground/50">No img</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Main content */}
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-1.5 mb-0.5">
|
||||
<span
|
||||
className={`inline-block h-1.5 w-1.5 rounded-full ${meta.dot}`}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{meta.label}
|
||||
</span>
|
||||
{post.isFeatured && (
|
||||
<Star className="h-3 w-3 text-amber-500 fill-amber-500" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Link
|
||||
href={`/blog/${post.slug}`}
|
||||
target="_blank"
|
||||
className="font-semibold text-sm hover:text-primary transition-colors line-clamp-1"
|
||||
>
|
||||
{post.title}
|
||||
<ExternalLink className="inline-block ml-1 h-2.5 w-2.5 opacity-50" />
|
||||
</Link>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 mt-1">
|
||||
<span className="text-xs text-muted-foreground font-mono">
|
||||
/{post.slug}
|
||||
</span>
|
||||
<span className="flex items-center gap-1 text-xs text-muted-foreground">
|
||||
<Eye className="h-3 w-3" /> {post.views.toLocaleString()}
|
||||
</span>
|
||||
{post.author && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{post.author.name || post.author.email}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(post.categories.length > 0 || post.tags.length > 0) && (
|
||||
<div className="flex flex-wrap gap-1 mt-1.5">
|
||||
{post.categories.map((c) => (
|
||||
<Badge
|
||||
key={c}
|
||||
variant="secondary"
|
||||
className="text-xs h-4 px-1.5"
|
||||
>
|
||||
{c}
|
||||
</Badge>
|
||||
))}
|
||||
{post.tags.slice(0, 3).map((t) => (
|
||||
<Badge
|
||||
key={t}
|
||||
variant="outline"
|
||||
className="text-xs h-4 px-1.5"
|
||||
>
|
||||
#{t}
|
||||
</Badge>
|
||||
))}
|
||||
{post.tags.length > 3 && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
+{post.tags.length - 3}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Date */}
|
||||
<span className="text-xs text-muted-foreground shrink-0 hidden md:block">
|
||||
{new Date(post.updatedAt).toLocaleDateString()}
|
||||
</span>
|
||||
|
||||
{/* Actions */}
|
||||
{canEdit && (
|
||||
<div className="flex gap-1 shrink-0">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0"
|
||||
onClick={() => openEdit(post)}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete post?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
"{post.title}" will be permanently deleted.
|
||||
This cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => handleDelete(post.id)}
|
||||
disabled={deletingId === post.id}
|
||||
>
|
||||
{deletingId === post.id && (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Post create/edit sheet ─────────────────────────────────────────── */}
|
||||
<PostSheet
|
||||
open={sheetOpen}
|
||||
onOpenChange={setSheetOpen}
|
||||
post={editingPost}
|
||||
userRole={userRole}
|
||||
onSuccess={refreshPosts}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
329
frontend/app/dashboard/components/users-table.tsx
Normal file
329
frontend/app/dashboard/components/users-table.tsx
Normal file
@@ -0,0 +1,329 @@
|
||||
"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 { Label } from "@/components/ui/label";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
Sheet,
|
||||
SheetContent,
|
||||
SheetDescription,
|
||||
SheetHeader,
|
||||
SheetTitle,
|
||||
} from "@/components/ui/sheet";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Loader2, Pencil, Trash2, Check, Users2 } from "lucide-react";
|
||||
|
||||
interface Props {
|
||||
initialUsers: User[];
|
||||
}
|
||||
|
||||
const roleMeta: Record<UserRole, { label: string; classes: string }> = {
|
||||
[UserRole.ADMIN]: {
|
||||
label: "Admin",
|
||||
classes: "bg-red-100 text-red-800 border-red-200 dark:bg-red-950 dark:text-red-300",
|
||||
},
|
||||
[UserRole.MANAGER]: {
|
||||
label: "Manager",
|
||||
classes: "bg-amber-100 text-amber-800 border-amber-200 dark:bg-amber-950 dark:text-amber-300",
|
||||
},
|
||||
[UserRole.MEMBER]: {
|
||||
label: "Member",
|
||||
classes: "bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-950 dark:text-blue-300",
|
||||
},
|
||||
};
|
||||
|
||||
function Avatar({ name, email }: { name?: string; email: string }) {
|
||||
const letter = (name || email).charAt(0).toUpperCase();
|
||||
return (
|
||||
<div className="h-9 w-9 shrink-0 rounded-full bg-primary/10 flex items-center justify-center text-sm font-semibold text-primary select-none">
|
||||
{letter}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function UsersTable({ initialUsers }: Props) {
|
||||
const [users, setUsers] = useState<User[]>(initialUsers);
|
||||
const [editingUser, setEditingUser] = useState<User | null>(null);
|
||||
const [deletingUser, setDeletingUser] = useState<User | null>(null);
|
||||
const [editName, setEditName] = useState("");
|
||||
const [editRole, setEditRole] = useState<UserRole>(UserRole.MEMBER);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [deleteLoading, setDeleteLoading] = useState(false);
|
||||
|
||||
const openEdit = (user: User) => {
|
||||
setEditingUser(user);
|
||||
setEditName(user.name || "");
|
||||
setEditRole(user.role);
|
||||
};
|
||||
|
||||
const closeEdit = () => setEditingUser(null);
|
||||
|
||||
const handleUpdate = async () => {
|
||||
if (!editingUser) return;
|
||||
setLoading(true);
|
||||
try {
|
||||
let updated = editingUser;
|
||||
|
||||
if (editName.trim() !== (editingUser.name || "")) {
|
||||
const res = await clientFetch<{ success: boolean; user: User }>(
|
||||
`/users/${editingUser.id}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ name: editName.trim() || undefined }),
|
||||
}
|
||||
);
|
||||
updated = res.user;
|
||||
}
|
||||
|
||||
if (editRole !== editingUser.role) {
|
||||
const res = await clientFetch<{ success: boolean; user: User }>(
|
||||
`/users/${editingUser.id}/role`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ role: editRole }),
|
||||
}
|
||||
);
|
||||
updated = res.user;
|
||||
}
|
||||
|
||||
toast.success("User updated.");
|
||||
setUsers((prev) =>
|
||||
prev.map((u) => (u.id === editingUser.id ? updated : u))
|
||||
);
|
||||
closeEdit();
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Update failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async () => {
|
||||
if (!deletingUser) return;
|
||||
setDeleteLoading(true);
|
||||
try {
|
||||
await clientFetch(`/users/${deletingUser.id}`, { method: "DELETE" });
|
||||
toast.success(`User "${deletingUser.email}" deleted.`);
|
||||
setUsers((prev) => prev.filter((u) => u.id !== deletingUser.id));
|
||||
setDeletingUser(null);
|
||||
} catch (err: unknown) {
|
||||
toast.error(err instanceof Error ? err.message : "Delete failed");
|
||||
} finally {
|
||||
setDeleteLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (users.length === 0) {
|
||||
return (
|
||||
<div className="rounded-xl border border-dashed p-10 text-center text-sm text-muted-foreground">
|
||||
No users found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="rounded-xl border overflow-hidden divide-y">
|
||||
{users.map((user) => {
|
||||
const role = roleMeta[user.role];
|
||||
return (
|
||||
<div
|
||||
key={user.id}
|
||||
className="flex items-center gap-3 px-4 py-3 bg-card hover:bg-muted/30 transition-colors"
|
||||
>
|
||||
<Avatar name={user.name} email={user.email} />
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<p className="text-sm font-medium truncate">
|
||||
{user.name || (
|
||||
<span className="italic text-muted-foreground">
|
||||
No name
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-2 py-0.5 text-xs font-medium ${role.classes}`}
|
||||
>
|
||||
{role.label}
|
||||
</span>
|
||||
{!user.isActive && (
|
||||
<Badge variant="outline" className="text-xs text-muted-foreground">
|
||||
Inactive
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate">
|
||||
{user.email}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<span className="text-xs text-muted-foreground shrink-0 hidden sm:block">
|
||||
{new Date(user.createdAt).toLocaleDateString()}
|
||||
</span>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 shrink-0"
|
||||
onClick={() => openEdit(user)}
|
||||
>
|
||||
<Pencil className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-7 w-7 p-0 shrink-0 text-destructive hover:text-destructive hover:bg-destructive/10"
|
||||
onClick={() => setDeletingUser(user)}
|
||||
>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* ── Edit sheet ───────────────────────────────────────────────────── */}
|
||||
<Sheet open={!!editingUser} onOpenChange={(o) => !o && closeEdit()}>
|
||||
<SheetContent side="right" className="sm:max-w-sm">
|
||||
<SheetHeader>
|
||||
<SheetTitle className="flex items-center gap-2">
|
||||
<Users2 className="h-4 w-4 text-muted-foreground" />
|
||||
Edit User
|
||||
</SheetTitle>
|
||||
<SheetDescription>{editingUser?.email}</SheetDescription>
|
||||
</SheetHeader>
|
||||
|
||||
<div className="mt-6 space-y-4 px-1">
|
||||
{/* Avatar preview */}
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center text-lg font-semibold text-primary">
|
||||
{(editName || editingUser?.email || "?").charAt(0).toUpperCase()}
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm font-medium">{editName || "No name"}</p>
|
||||
<p className="text-xs text-muted-foreground">{editingUser?.email}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label htmlFor="eu-name">Display name</Label>
|
||||
<Input
|
||||
id="eu-name"
|
||||
value={editName}
|
||||
onChange={(e) => setEditName(e.target.value)}
|
||||
placeholder="Full name"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1.5">
|
||||
<Label>Role</Label>
|
||||
<Select
|
||||
value={editRole}
|
||||
onValueChange={(v) => setEditRole(v as UserRole)}
|
||||
>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={UserRole.MEMBER}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-blue-500" />
|
||||
Member
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={UserRole.MANAGER}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-amber-500" />
|
||||
Manager
|
||||
</span>
|
||||
</SelectItem>
|
||||
<SelectItem value={UserRole.ADMIN}>
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-2 w-2 rounded-full bg-red-500" />
|
||||
Admin
|
||||
</span>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{editRole === UserRole.ADMIN
|
||||
? "Full access: create, edit, delete posts and manage users."
|
||||
: editRole === UserRole.MANAGER
|
||||
? "Can create posts (saved as draft for review)."
|
||||
: "Read-only access to the dashboard."}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex gap-2 pt-2">
|
||||
<Button variant="outline" className="flex-1" onClick={closeEdit} disabled={loading}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button className="flex-1" onClick={handleUpdate} disabled={loading}>
|
||||
{loading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Check className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
|
||||
{/* ── Delete confirmation dialog ────────────────────────────────────── */}
|
||||
<AlertDialog open={!!deletingUser} onOpenChange={(o) => !o && setDeletingUser(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete user?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will permanently delete{" "}
|
||||
<span className="font-medium text-foreground">
|
||||
{deletingUser?.name || deletingUser?.email}
|
||||
</span>
|
||||
. This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={deleteLoading}>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDelete}
|
||||
disabled={deleteLoading}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{deleteLoading ? (
|
||||
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
)}
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
243
frontend/app/dashboard/page.tsx
Normal file
243
frontend/app/dashboard/page.tsx
Normal file
@@ -0,0 +1,243 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { cookies } from "next/headers";
|
||||
import { apiFetch, ApiError } from "@/lib/api";
|
||||
import { BlogPost, User, UserRole, CurrentUser, PostStatus } from "@/lib/types";
|
||||
import { PostsTable } from "./components/posts-table";
|
||||
import { UsersTable } from "./components/users-table";
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
FileText,
|
||||
Users,
|
||||
Eye,
|
||||
TrendingUp,
|
||||
CheckCircle2,
|
||||
Clock,
|
||||
Archive,
|
||||
} from "lucide-react";
|
||||
|
||||
// ── JWT decode (no verification — display 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 rolePill: Record<UserRole, string> = {
|
||||
[UserRole.ADMIN]: "bg-red-100 text-red-700 border-red-200",
|
||||
[UserRole.MANAGER]: "bg-amber-100 text-amber-700 border-amber-200",
|
||||
[UserRole.MEMBER]: "bg-blue-100 text-blue-700 border-blue-200",
|
||||
};
|
||||
|
||||
// ── Stat card ──────────────────────────────────────────────────────────────
|
||||
function StatCard({
|
||||
icon: Icon,
|
||||
label,
|
||||
value,
|
||||
sub,
|
||||
accent,
|
||||
}: {
|
||||
icon: React.ElementType;
|
||||
label: string;
|
||||
value: number | string;
|
||||
sub?: string;
|
||||
accent?: string;
|
||||
}) {
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="p-5">
|
||||
<div className="flex items-start justify-between gap-2">
|
||||
<div>
|
||||
<p className="text-xs font-medium text-muted-foreground uppercase tracking-wide mb-1">
|
||||
{label}
|
||||
</p>
|
||||
<p className={`text-3xl font-bold tracking-tight ${accent ?? ""}`}>
|
||||
{value}
|
||||
</p>
|
||||
{sub && (
|
||||
<p className="text-xs text-muted-foreground mt-1">{sub}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="h-9 w-9 rounded-lg bg-muted flex items-center justify-center shrink-0">
|
||||
<Icon className="h-4.5 w-4.5 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Page ───────────────────────────────────────────────────────────────────
|
||||
export default async function DashboardPage() {
|
||||
/* Auth */
|
||||
const cookieStore = await cookies();
|
||||
const accessToken = cookieStore.get("accessToken")?.value;
|
||||
if (!accessToken) redirect("/auth");
|
||||
|
||||
const currentUser = decodeJwtPayload(accessToken);
|
||||
if (!currentUser) redirect("/auth");
|
||||
|
||||
/* Posts */
|
||||
let posts: BlogPost[] = [];
|
||||
try {
|
||||
const data = await apiFetch<{ posts: BlogPost[]; total: number }>(
|
||||
"/blog-posts?pageSize=100"
|
||||
);
|
||||
posts = data.posts;
|
||||
} catch (err) {
|
||||
if (err instanceof ApiError && err.status === 401) redirect("/auth");
|
||||
}
|
||||
|
||||
/* Users (ADMIN only) */
|
||||
let users: User[] = [];
|
||||
if (currentUser.role === UserRole.ADMIN) {
|
||||
try {
|
||||
const data = await apiFetch<{ users: User[]; total: number }>(
|
||||
"/users?pageSize=100"
|
||||
);
|
||||
users = data.users;
|
||||
} catch { /* non-fatal */ }
|
||||
}
|
||||
|
||||
/* Stats */
|
||||
const published = posts.filter((p) => p.status === PostStatus.PUBLISHED).length;
|
||||
const drafts = posts.filter((p) => p.status === PostStatus.DRAFT).length;
|
||||
const archived = posts.filter((p) => p.status === PostStatus.ARCHIVED).length;
|
||||
const totalViews = posts.reduce((s, p) => s + (p.views ?? 0), 0);
|
||||
|
||||
const displayName = currentUser.name || currentUser.email;
|
||||
const isAdmin = currentUser.role === UserRole.ADMIN;
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-muted/20">
|
||||
{/* ── Top header bar ──────────────────────────────────────────────────── */}
|
||||
<div className="border-b bg-background">
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 py-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div>
|
||||
<h1 className="text-xl font-bold">Dashboard</h1>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Welcome back, <span className="font-medium text-foreground">{displayName}</span>
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-3 py-1 text-xs font-semibold ${rolePill[currentUser.role as UserRole]}`}
|
||||
>
|
||||
{currentUser.role}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="max-w-6xl mx-auto px-4 sm:px-6 py-6 space-y-6">
|
||||
|
||||
{/* ── Stats grid ────────────────────────────────────────────────────── */}
|
||||
<div className={`grid gap-4 ${isAdmin ? "sm:grid-cols-2 lg:grid-cols-4" : "sm:grid-cols-3"}`}>
|
||||
<StatCard
|
||||
icon={FileText}
|
||||
label="Total posts"
|
||||
value={posts.length}
|
||||
sub={`${published} published`}
|
||||
/>
|
||||
<StatCard
|
||||
icon={CheckCircle2}
|
||||
label="Published"
|
||||
value={published}
|
||||
accent="text-emerald-600"
|
||||
/>
|
||||
<StatCard
|
||||
icon={Clock}
|
||||
label="Drafts"
|
||||
value={drafts}
|
||||
accent="text-zinc-500"
|
||||
/>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<StatCard
|
||||
icon={Eye}
|
||||
label="Total views"
|
||||
value={totalViews.toLocaleString()}
|
||||
sub="across all posts"
|
||||
accent="text-primary"
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Second row for admin — archived + users */}
|
||||
{isAdmin && (
|
||||
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<StatCard
|
||||
icon={Archive}
|
||||
label="Archived"
|
||||
value={archived}
|
||||
accent="text-amber-600"
|
||||
/>
|
||||
<StatCard
|
||||
icon={Users}
|
||||
label="Total users"
|
||||
value={users.length}
|
||||
sub={`${users.filter((u) => u.isActive).length} active`}
|
||||
/>
|
||||
<StatCard
|
||||
icon={TrendingUp}
|
||||
label="Avg. views / post"
|
||||
value={posts.length ? Math.round(totalViews / posts.length).toLocaleString() : "—"}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* ── Tabs ──────────────────────────────────────────────────────────── */}
|
||||
<Tabs defaultValue="posts" className="space-y-4">
|
||||
<TabsList className={isAdmin ? "" : "w-auto"}>
|
||||
<TabsTrigger value="posts" className="gap-1.5">
|
||||
<FileText className="h-3.5 w-3.5" />
|
||||
Posts
|
||||
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground ml-0.5">
|
||||
{posts.length}
|
||||
</span>
|
||||
</TabsTrigger>
|
||||
{isAdmin && (
|
||||
<TabsTrigger value="users" className="gap-1.5">
|
||||
<Users className="h-3.5 w-3.5" />
|
||||
Users
|
||||
<span className="rounded-full bg-muted px-1.5 py-0.5 text-[10px] font-semibold text-muted-foreground ml-0.5">
|
||||
{users.length}
|
||||
</span>
|
||||
</TabsTrigger>
|
||||
)}
|
||||
</TabsList>
|
||||
|
||||
{/* Posts tab */}
|
||||
<TabsContent value="posts" className="mt-0">
|
||||
<PostsTable
|
||||
initialPosts={posts}
|
||||
userRole={currentUser.role as UserRole}
|
||||
/>
|
||||
</TabsContent>
|
||||
|
||||
{/* Users tab (admin only) */}
|
||||
{isAdmin && (
|
||||
<TabsContent value="users" className="mt-0">
|
||||
<UsersTable initialUsers={users} />
|
||||
</TabsContent>
|
||||
)}
|
||||
</Tabs>
|
||||
|
||||
{/* Member read-only notice */}
|
||||
{currentUser.role === UserRole.MEMBER && (
|
||||
<Card className="border-dashed border-muted-foreground/30 bg-muted/20">
|
||||
<CardContent className="py-4 px-5">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
<span className="font-semibold text-foreground">Read-only access.</span>{" "}
|
||||
You can view posts but cannot create, edit, or delete them. Contact an admin to upgrade your role.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
BIN
frontend/app/favicon.ico
Normal file
BIN
frontend/app/favicon.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
239
frontend/app/globals.css
Normal file
239
frontend/app/globals.css
Normal file
@@ -0,0 +1,239 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "shadcn/tailwind.css";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
:root {
|
||||
--background: oklch(1.0000 0 0);
|
||||
--foreground: oklch(0 0 0);
|
||||
--card: oklch(1.0000 0 0);
|
||||
--card-foreground: oklch(0 0 0);
|
||||
--popover: oklch(1.0000 0 0);
|
||||
--popover-foreground: oklch(0 0 0);
|
||||
--primary: oklch(0.5323 0.1730 141.3064);
|
||||
--primary-foreground: oklch(1.0000 0 0);
|
||||
--secondary: oklch(0.5762 0.2175 258.9127);
|
||||
--secondary-foreground: oklch(1.0000 0 0);
|
||||
--muted: oklch(0.9551 0 0);
|
||||
--muted-foreground: oklch(0.3211 0 0);
|
||||
--accent: oklch(0.5635 0.2408 260.8178);
|
||||
--accent-foreground: oklch(1.0000 0 0);
|
||||
--destructive: oklch(0 0 0);
|
||||
--destructive-foreground: oklch(1.0000 0 0);
|
||||
--border: oklch(0 0 0);
|
||||
--input: oklch(0 0 0);
|
||||
--ring: oklch(0.6489 0.2370 26.9728);
|
||||
--chart-1: oklch(0.6489 0.2370 26.9728);
|
||||
--chart-2: oklch(0.9680 0.2110 109.7692);
|
||||
--chart-3: oklch(0.5635 0.2408 260.8178);
|
||||
--chart-4: oklch(0.7323 0.2492 142.4953);
|
||||
--chart-5: oklch(0.5931 0.2726 328.3634);
|
||||
--sidebar: oklch(0.9551 0 0);
|
||||
--sidebar-foreground: oklch(0 0 0);
|
||||
--sidebar-primary: oklch(0.6489 0.2370 26.9728);
|
||||
--sidebar-primary-foreground: oklch(1.0000 0 0);
|
||||
--sidebar-accent: oklch(0.5635 0.2408 260.8178);
|
||||
--sidebar-accent-foreground: oklch(1.0000 0 0);
|
||||
--sidebar-border: oklch(0 0 0);
|
||||
--sidebar-ring: oklch(0.6489 0.2370 26.9728);
|
||||
--font-sans: DM Sans, sans-serif;
|
||||
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||
--font-mono: Space Mono, monospace;
|
||||
--radius: 0px;
|
||||
--shadow-x: 4px;
|
||||
--shadow-y: 4px;
|
||||
--shadow-blur: 0px;
|
||||
--shadow-spread: 0px;
|
||||
--shadow-opacity: 1;
|
||||
--shadow-color: hsl(0 0% 0%);
|
||||
--shadow-2xs: 4px 4px 0px 0px hsl(0 0% 0% / 0.50);
|
||||
--shadow-xs: 4px 4px 0px 0px hsl(0 0% 0% / 0.50);
|
||||
--shadow-sm: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-md: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 2px 4px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-lg: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 4px 6px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-xl: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 8px 10px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-2xl: 4px 4px 0px 0px hsl(0 0% 0% / 2.50);
|
||||
--tracking-normal: 0em;
|
||||
--spacing: 0.25rem;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0 0 0);
|
||||
--foreground: oklch(1.0000 0 0);
|
||||
--card: oklch(0.3211 0 0);
|
||||
--card-foreground: oklch(1.0000 0 0);
|
||||
--popover: oklch(0.3211 0 0);
|
||||
--popover-foreground: oklch(1.0000 0 0);
|
||||
--primary: oklch(0.7044 0.1872 23.1858);
|
||||
--primary-foreground: oklch(0 0 0);
|
||||
--secondary: oklch(0.9691 0.2005 109.6228);
|
||||
--secondary-foreground: oklch(0 0 0);
|
||||
--muted: oklch(0.2178 0 0);
|
||||
--muted-foreground: oklch(0.8452 0 0);
|
||||
--accent: oklch(0.6755 0.1765 252.2592);
|
||||
--accent-foreground: oklch(0 0 0);
|
||||
--destructive: oklch(1.0000 0 0);
|
||||
--destructive-foreground: oklch(0 0 0);
|
||||
--border: oklch(1.0000 0 0);
|
||||
--input: oklch(1.0000 0 0);
|
||||
--ring: oklch(0.7044 0.1872 23.1858);
|
||||
--chart-1: oklch(0.7044 0.1872 23.1858);
|
||||
--chart-2: oklch(0.9691 0.2005 109.6228);
|
||||
--chart-3: oklch(0.6755 0.1765 252.2592);
|
||||
--chart-4: oklch(0.7395 0.2268 142.8504);
|
||||
--chart-5: oklch(0.6131 0.2458 328.0714);
|
||||
--sidebar: oklch(0 0 0);
|
||||
--sidebar-foreground: oklch(1.0000 0 0);
|
||||
--sidebar-primary: oklch(0.7044 0.1872 23.1858);
|
||||
--sidebar-primary-foreground: oklch(0 0 0);
|
||||
--sidebar-accent: oklch(0.6755 0.1765 252.2592);
|
||||
--sidebar-accent-foreground: oklch(0 0 0);
|
||||
--sidebar-border: oklch(1.0000 0 0);
|
||||
--sidebar-ring: oklch(0.7044 0.1872 23.1858);
|
||||
--font-sans: DM Sans, sans-serif;
|
||||
--font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif;
|
||||
--font-mono: Space Mono, monospace;
|
||||
--radius: 0px;
|
||||
--shadow-x: 4px;
|
||||
--shadow-y: 4px;
|
||||
--shadow-blur: 0px;
|
||||
--shadow-spread: 0px;
|
||||
--shadow-opacity: 1;
|
||||
--shadow-color: hsl(0 0% 0%);
|
||||
--shadow-2xs: 4px 4px 0px 0px hsl(0 0% 0% / 0.50);
|
||||
--shadow-xs: 4px 4px 0px 0px hsl(0 0% 0% / 0.50);
|
||||
--shadow-sm: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 1px 2px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-md: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 2px 4px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-lg: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 4px 6px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-xl: 4px 4px 0px 0px hsl(0 0% 0% / 1.00), 4px 8px 10px -1px hsl(0 0% 0% / 1.00);
|
||||
--shadow-2xl: 4px 4px 0px 0px hsl(0 0% 0% / 2.50);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
|
||||
--font-sans: var(--font-sans);
|
||||
--font-mono: var(--font-mono);
|
||||
--font-serif: var(--font-serif);
|
||||
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
|
||||
--shadow-2xs: var(--shadow-2xs);
|
||||
--shadow-xs: var(--shadow-xs);
|
||||
--shadow-sm: var(--shadow-sm);
|
||||
--shadow: var(--shadow);
|
||||
--shadow-md: var(--shadow-md);
|
||||
--shadow-lg: var(--shadow-lg);
|
||||
--shadow-xl: var(--shadow-xl);
|
||||
--shadow-2xl: var(--shadow-2xl);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
/* ── Tiptap editor content styles ─────────────────────────────────────────── */
|
||||
.tiptap-content .ProseMirror {
|
||||
outline: none;
|
||||
min-height: inherit;
|
||||
}
|
||||
.tiptap-content .ProseMirror p.is-editor-empty:first-child::before {
|
||||
content: attr(data-placeholder);
|
||||
float: left;
|
||||
color: oklch(0.556 0 0);
|
||||
pointer-events: none;
|
||||
height: 0;
|
||||
}
|
||||
.tiptap-content .ProseMirror > * + * { margin-top: 0.65em; }
|
||||
.tiptap-content .ProseMirror h1 { font-size: 1.6rem; font-weight: 700; line-height: 1.2; }
|
||||
.tiptap-content .ProseMirror h2 { font-size: 1.3rem; font-weight: 700; line-height: 1.3; }
|
||||
.tiptap-content .ProseMirror h3 { font-size: 1.1rem; font-weight: 600; line-height: 1.4; }
|
||||
.tiptap-content .ProseMirror strong { font-weight: 700; }
|
||||
.tiptap-content .ProseMirror em { font-style: italic; }
|
||||
.tiptap-content .ProseMirror u { text-decoration: underline; }
|
||||
.tiptap-content .ProseMirror s { text-decoration: line-through; }
|
||||
.tiptap-content .ProseMirror mark { background-color: oklch(0.97 0.18 95); border-radius: 0.15em; padding: 0 0.15em; }
|
||||
.tiptap-content .ProseMirror ul { list-style-type: disc; padding-left: 1.4em; }
|
||||
.tiptap-content .ProseMirror ol { list-style-type: decimal; padding-left: 1.4em; }
|
||||
.tiptap-content .ProseMirror li > p { margin: 0; }
|
||||
.tiptap-content .ProseMirror blockquote {
|
||||
border-left: 3px solid oklch(0.708 0 0);
|
||||
margin-left: 0;
|
||||
padding-left: 1em;
|
||||
color: oklch(0.556 0 0);
|
||||
font-style: italic;
|
||||
}
|
||||
.tiptap-content .ProseMirror code {
|
||||
background: oklch(0.97 0 0);
|
||||
border-radius: 0.25em;
|
||||
padding: 0.1em 0.35em;
|
||||
font-size: 0.875em;
|
||||
font-family: var(--font-mono, monospace);
|
||||
}
|
||||
.tiptap-content .ProseMirror pre {
|
||||
background: oklch(0.145 0 0);
|
||||
color: oklch(0.922 0 0);
|
||||
border-radius: 0.5em;
|
||||
padding: 0.85em 1.1em;
|
||||
overflow-x: auto;
|
||||
}
|
||||
.tiptap-content .ProseMirror pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
font-size: 0.85em;
|
||||
color: inherit;
|
||||
}
|
||||
.tiptap-content .ProseMirror hr {
|
||||
border: none;
|
||||
border-top: 2px solid oklch(0.922 0 0);
|
||||
margin: 1.25em 0;
|
||||
}
|
||||
.dark .tiptap-content .ProseMirror p.is-editor-empty:first-child::before { color: oklch(0.708 0 0); }
|
||||
.dark .tiptap-content .ProseMirror mark { background-color: oklch(0.75 0.15 90 / 0.35); }
|
||||
.dark .tiptap-content .ProseMirror code { background: oklch(0.269 0 0); }
|
||||
.dark .tiptap-content .ProseMirror pre { background: oklch(0.1 0 0); }
|
||||
.dark .tiptap-content .ProseMirror blockquote { border-left-color: oklch(0.556 0 0); color: oklch(0.708 0 0); }
|
||||
.dark .tiptap-content .ProseMirror hr { border-top-color: oklch(1 0 0 / 10%); }
|
||||
47
frontend/app/layout.tsx
Normal file
47
frontend/app/layout.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
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",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
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({
|
||||
children,
|
||||
}: Readonly<{
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased min-h-screen bg-background`}
|
||||
>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
332
frontend/app/page.tsx
Normal file
332
frontend/app/page.tsx
Normal file
@@ -0,0 +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;
|
||||
|
||||
return (
|
||||
<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">
|
||||
The blog is all about web dev tech
|
||||
</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