2026-02-19 23:20:19 +09:00
commit 0e21562088
139 changed files with 35467 additions and 0 deletions

13
frontend/.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
node_modules
npm-debug.log
Dockerfile*
docker-compose*
.dockerignore
.git
.gitignore
README.md
LICENSE
.vscode
.next
*.swp
/scripts

4
frontend/.env.example Normal file
View File

@@ -0,0 +1,4 @@
NEXT_PUBLIC_API_URL=http://localhost:5001
UPLOAD_R2_WORKER_API=***.workers.dev
R2_UPLOAD_API_KEY=***

41
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,41 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# testing
/coverage
# next.js
/.next/
/out/
# production
/build
# misc
.DS_Store
*.pem
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.pnpm-debug.log*
# env files (can opt-in for committing if needed)
.env
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts

25
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,25 @@
FROM node:20-alpine AS base
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
# Build args for NEXT_PUBLIC_ vars (baked in at build time)
ARG NEXT_PUBLIC_API_URL
ARG UPLOAD_R2_WORKER_API
ARG R2_UPLOAD_API_KEY
ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL
ENV UPLOAD_R2_WORKER_API=$UPLOAD_R2_WORKER_API
ENV R2_UPLOAD_API_KEY=$R2_UPLOAD_API_KEY
RUN npm run build
FROM node:20-alpine AS production
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=base /app/.next ./.next
COPY --from=base /app/public ./public
EXPOSE 3000
CMD ["npm", "start"]

View 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
View 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>
);
}

View 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>
);
}

View 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;
}

View 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>
);
}

View 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>
&quot;{post.title}&quot; 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}
/>
</>
);
}

View 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>
</>
);
}

View 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

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

239
frontend/app/globals.css Normal file
View 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
View 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
View 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>
);
}

23
frontend/components.json Normal file
View File

@@ -0,0 +1,23 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "app/globals.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"registries": {}
}

View File

@@ -0,0 +1,203 @@
"use client";
import { useCallback, useRef, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, Upload, X, ImageIcon } from "lucide-react";
import type { UploadImageResponse } from "@/app/api/upload-image/route";
interface Props {
/** Current image URL (controlled) */
value?: string;
/** Called when a new image URL is ready (after upload) or cleared (empty string) */
onChange: (url: string) => void;
/** Alt text value */
altValue?: string;
/** Called when alt text changes */
onAltChange?: (alt: string) => void;
/** Label shown above the dropzone */
label?: string;
}
const ACCEPTED = "image/jpeg,image/png,image/gif,image/webp,image/svg+xml,image/avif";
export function ImageUploader({
value,
onChange,
altValue = "",
onAltChange,
label = "Featured Image",
}: Props) {
const [uploading, setUploading] = useState(false);
const [dragOver, setDragOver] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const uploadFile = useCallback(
async (file: File) => {
setUploading(true);
try {
const fd = new FormData();
fd.append("file", file);
const res = await fetch("/api/upload-image", {
method: "POST",
body: fd,
});
const data = (await res.json()) as UploadImageResponse & { error?: string };
if (!res.ok || !data.success) {
throw new Error(data.error || "Upload failed");
}
onChange(data.url);
toast.success("Image uploaded successfully!");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Upload failed");
} finally {
setUploading(false);
}
},
[onChange]
);
// ── Drag & Drop handlers ───────────────────────────────────────────────────
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
setDragOver(true);
};
const handleDragLeave = () => setDragOver(false);
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
setDragOver(false);
const file = e.dataTransfer.files[0];
if (file) uploadFile(file);
};
// ── File input change ──────────────────────────────────────────────────────
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
uploadFile(file);
// Reset so the same file can be re-selected if removed
e.target.value = "";
}
};
const handleRemove = () => {
onChange("");
onAltChange?.("");
};
return (
<div className="space-y-2">
<Label>{label}</Label>
{value ? (
/* ── Preview ──────────────────────────────────────────────────────── */
<div className="relative rounded-xl overflow-hidden border bg-muted">
{/* Plain <img> — domain is dynamic (R2/custom), avoids next/image remotePatterns config */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={value}
alt={altValue || "Featured image preview"}
className="aspect-video w-full object-cover"
/>
{/* Overlay — Replace / Remove actions */}
<div className="absolute inset-0 flex items-center justify-center gap-2 bg-black/40 opacity-0 hover:opacity-100 transition-opacity">
<Button
type="button"
size="sm"
variant="secondary"
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
>
{uploading ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Upload className="h-4 w-4" />
)}
<span className="ml-1.5">Replace</span>
</Button>
<Button
type="button"
size="sm"
variant="destructive"
onClick={handleRemove}
disabled={uploading}
>
<X className="h-4 w-4" />
<span className="ml-1.5">Remove</span>
</Button>
</div>
{uploading && (
<div className="absolute inset-0 flex items-center justify-center bg-black/50">
<Loader2 className="h-8 w-8 animate-spin text-white" />
</div>
)}
</div>
) : (
/* ── Dropzone ─────────────────────────────────────────────────────── */
<button
type="button"
onClick={() => fileInputRef.current?.click()}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
disabled={uploading}
className={`
w-full rounded-xl border-2 border-dashed p-8
flex flex-col items-center justify-center gap-2
text-sm text-muted-foreground transition-colors cursor-pointer
hover:border-primary/50 hover:bg-muted/40
focus:outline-none focus-visible:ring-2 focus-visible:ring-ring
disabled:cursor-not-allowed disabled:opacity-60
${dragOver ? "border-primary bg-primary/5" : "border-border"}
`}
>
{uploading ? (
<>
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<span>Uploading</span>
</>
) : (
<>
<ImageIcon className="h-8 w-8 opacity-40" />
<span className="font-medium">
{dragOver ? "Drop to upload" : "Click or drag an image here"}
</span>
<span className="text-xs opacity-70">
JPEG · PNG · GIF · WebP · SVG · AVIF max 10 MB
</span>
</>
)}
</button>
)}
{/* Hidden file input */}
<input
ref={fileInputRef}
type="file"
accept={ACCEPTED}
className="hidden"
onChange={handleFileChange}
/>
{/* Alt text field — always shown */}
<div className="space-y-1">
<Label className="text-xs text-muted-foreground">Image alt text</Label>
<Input
placeholder="Describe the image for accessibility…"
value={altValue}
onChange={(e) => onAltChange?.(e.target.value)}
/>
</div>
</div>
);
}

View File

@@ -0,0 +1,243 @@
"use client";
import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Placeholder from "@tiptap/extension-placeholder";
import Underline from "@tiptap/extension-underline";
import Highlight from "@tiptap/extension-highlight";
import TextAlign from "@tiptap/extension-text-align";
import Link from "@tiptap/extension-link";
import { Button } from "@/components/ui/button";
import { Separator } from "@/components/ui/separator";
import {
Bold,
Italic,
UnderlineIcon,
Strikethrough,
Highlighter,
Heading1,
Heading2,
Heading3,
List,
ListOrdered,
Quote,
Code,
Code2,
AlignLeft,
AlignCenter,
AlignRight,
Minus,
Undo2,
Redo2,
Link2,
Link2Off,
} from "lucide-react";
import { useCallback, useEffect } from "react";
interface Props {
value?: string;
onChange: (html: string) => void;
placeholder?: string;
minHeight?: string;
}
export function TiptapEditor({
value = "",
onChange,
placeholder = "Write your post content here…",
minHeight = "320px",
}: Props) {
const editor = useEditor({
immediatelyRender: false,
extensions: [
StarterKit.configure({
bulletList: { keepMarks: true, keepAttributes: false },
orderedList: { keepMarks: true, keepAttributes: false },
}),
Underline,
Highlight.configure({ multicolor: false }),
TextAlign.configure({ types: ["heading", "paragraph"] }),
Placeholder.configure({ placeholder }),
Link.configure({
openOnClick: false,
HTMLAttributes: { class: "text-primary underline underline-offset-2" },
}),
],
content: value,
onUpdate: ({ editor }) => {
onChange(editor.getHTML());
},
});
// Sync external value changes (e.g. when edit form opens with existing content)
useEffect(() => {
if (!editor) return;
const current = editor.getHTML();
if (value !== current) {
editor.commands.setContent(value || "", { emitUpdate: false });
}
}, [value, editor]);
const setLink = useCallback(() => {
if (!editor) return;
const prev = editor.getAttributes("link").href as string | undefined;
const url = window.prompt("URL", prev ?? "https://");
if (url === null) return; // cancelled
if (url === "") {
editor.chain().focus().extendMarkRange("link").unsetLink().run();
} else {
editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
}
}, [editor]);
if (!editor) return null;
const btn = (active: boolean) =>
`h-7 w-7 p-0 ${active ? "bg-muted text-foreground" : "text-muted-foreground hover:text-foreground hover:bg-muted/60"}`;
return (
<div className="rounded-xl border bg-background overflow-hidden">
{/* ── Toolbar ─────────────────────────────────────────────────────────── */}
<div className="flex flex-wrap items-center gap-0.5 border-b bg-muted/30 p-1.5">
{/* History */}
<Button type="button" variant="ghost" size="sm" className={btn(false)}
onClick={() => editor.chain().focus().undo().run()}
disabled={!editor.can().undo()}>
<Undo2 className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm" className={btn(false)}
onClick={() => editor.chain().focus().redo().run()}
disabled={!editor.can().redo()}>
<Redo2 className="h-3.5 w-3.5" />
</Button>
<Separator orientation="vertical" className="mx-1 h-5" />
{/* Headings */}
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("heading", { level: 1 }))}
onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}>
<Heading1 className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("heading", { level: 2 }))}
onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}>
<Heading2 className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("heading", { level: 3 }))}
onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}>
<Heading3 className="h-3.5 w-3.5" />
</Button>
<Separator orientation="vertical" className="mx-1 h-5" />
{/* Inline marks */}
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("bold"))}
onClick={() => editor.chain().focus().toggleBold().run()}>
<Bold className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("italic"))}
onClick={() => editor.chain().focus().toggleItalic().run()}>
<Italic className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("underline"))}
onClick={() => editor.chain().focus().toggleUnderline().run()}>
<UnderlineIcon className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("strike"))}
onClick={() => editor.chain().focus().toggleStrike().run()}>
<Strikethrough className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("highlight"))}
onClick={() => editor.chain().focus().toggleHighlight().run()}>
<Highlighter className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("code"))}
onClick={() => editor.chain().focus().toggleCode().run()}>
<Code className="h-3.5 w-3.5" />
</Button>
<Separator orientation="vertical" className="mx-1 h-5" />
{/* Link */}
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("link"))}
onClick={setLink}>
<Link2 className="h-3.5 w-3.5" />
</Button>
{editor.isActive("link") && (
<Button type="button" variant="ghost" size="sm"
className={btn(false)}
onClick={() => editor.chain().focus().unsetLink().run()}>
<Link2Off className="h-3.5 w-3.5" />
</Button>
)}
<Separator orientation="vertical" className="mx-1 h-5" />
{/* Lists */}
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("bulletList"))}
onClick={() => editor.chain().focus().toggleBulletList().run()}>
<List className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("orderedList"))}
onClick={() => editor.chain().focus().toggleOrderedList().run()}>
<ListOrdered className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("blockquote"))}
onClick={() => editor.chain().focus().toggleBlockquote().run()}>
<Quote className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive("codeBlock"))}
onClick={() => editor.chain().focus().toggleCodeBlock().run()}>
<Code2 className="h-3.5 w-3.5" />
</Button>
<Separator orientation="vertical" className="mx-1 h-5" />
{/* Alignment */}
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive({ textAlign: "left" }))}
onClick={() => editor.chain().focus().setTextAlign("left").run()}>
<AlignLeft className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive({ textAlign: "center" }))}
onClick={() => editor.chain().focus().setTextAlign("center").run()}>
<AlignCenter className="h-3.5 w-3.5" />
</Button>
<Button type="button" variant="ghost" size="sm"
className={btn(editor.isActive({ textAlign: "right" }))}
onClick={() => editor.chain().focus().setTextAlign("right").run()}>
<AlignRight className="h-3.5 w-3.5" />
</Button>
<Separator orientation="vertical" className="mx-1 h-5" />
{/* Divider */}
<Button type="button" variant="ghost" size="sm" className={btn(false)}
onClick={() => editor.chain().focus().setHorizontalRule().run()}>
<Minus className="h-3.5 w-3.5" />
</Button>
</div>
{/* ── Editor area ─────────────────────────────────────────────────────── */}
<EditorContent
editor={editor}
className="tiptap-content px-4 py-3 text-sm focus-within:outline-none"
style={{ minHeight }}
/>
</div>
);
}

View File

@@ -0,0 +1,78 @@
"use client";
import Link from "next/link";
import { useAuth } from "@/lib/auth";
import { Button } from "@/components/ui/button";
import { BookOpen, LayoutDashboard, LogOut, LogIn } from "lucide-react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
export function Navbar() {
const { currentUser, loading, logout } = useAuth();
const router = useRouter();
const handleLogout = async () => {
await logout();
toast.success("Logged out successfully");
router.push("/");
router.refresh();
};
return (
<header className="sticky top-0 z-50 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<div className="mx-auto flex h-14 max-w-7xl items-center justify-between px-4 sm:px-6 lg:px-8">
{/* Logo */}
<Link
href="/"
className="flex items-center gap-2 font-semibold text-foreground hover:text-primary transition-colors"
>
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-primary text-xs font-bold text-primary-foreground">
DB
</span>
<span className="hidden sm:inline">Duc Binh Blog</span>
</Link>
{/* Nav */}
<nav className="flex items-center gap-2">
<Button variant="ghost" size="sm" asChild>
<Link href="/">
<BookOpen className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Home</span>
</Link>
</Button>
{!loading && (
<>
{currentUser ? (
<>
<Button variant="ghost" size="sm" asChild>
<Link href="/dashboard">
<LayoutDashboard className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Dashboard</span>
</Link>
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleLogout}
className="text-destructive hover:text-destructive"
>
<LogOut className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Logout</span>
</Button>
</>
) : (
<Button variant="ghost" size="sm" asChild>
<Link href="/auth">
<LogIn className="h-4 w-4 mr-1" />
<span className="hidden sm:inline">Sign In</span>
</Link>
</Button>
)}
</>
)}
</nav>
</div>
</header>
);
}

View File

@@ -0,0 +1,72 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface PaginationProps {
page: number;
totalPages: number;
total: number;
}
export function Pagination({ page, totalPages, total }: PaginationProps) {
const router = useRouter();
const searchParams = useSearchParams();
if (totalPages <= 1) return null;
const goToPage = (p: number) => {
const params = new URLSearchParams(searchParams.toString());
params.set("page", String(p));
router.push(`?${params.toString()}`);
};
// Show at most 5 page numbers
const getPageNumbers = () => {
const pages: number[] = [];
const start = Math.max(1, page - 2);
const end = Math.min(totalPages, start + 4);
for (let i = start; i <= end; i++) pages.push(i);
return pages;
};
return (
<div className="flex items-center justify-between gap-2 pt-4 border-t">
<p className="text-sm text-muted-foreground">
Page {page} of {totalPages} ({total} posts)
</p>
<div className="flex items-center gap-1">
<Button
variant="outline"
size="sm"
disabled={page <= 1}
onClick={() => goToPage(page - 1)}
>
<ChevronLeft className="h-4 w-4" />
</Button>
{getPageNumbers().map((p) => (
<Button
key={p}
variant={p === page ? "default" : "outline"}
size="sm"
onClick={() => goToPage(p)}
className="w-9"
>
{p}
</Button>
))}
<Button
variant="outline"
size="sm"
disabled={page >= totalPages}
onClick={() => goToPage(page + 1)}
>
<ChevronRight className="h-4 w-4" />
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,72 @@
import Link from "next/link";
import Image from "next/image";
import { Badge } from "@/components/ui/badge";
import { Card, CardContent, CardFooter } from "@/components/ui/card";
import { Eye } from "lucide-react";
import { BlogPost } from "@/lib/types";
interface PostCardProps {
post: BlogPost;
}
export function PostCard({ post }: PostCardProps) {
return (
<Card className="flex flex-col overflow-hidden hover:shadow-md transition-shadow h-full">
{post.featuredImageUrl && (
<Link href={`/blog/${post.slug}`} className="block overflow-hidden">
<div className="relative h-48 w-full">
<Image
src={post.featuredImageUrl}
alt={post.featuredImageAlt || post.title}
fill
className="object-cover transition-transform duration-300 hover:scale-[1.02]"
sizes="(max-width: 768px) 100vw, (max-width: 1200px) 50vw, 33vw"
/>
</div>
</Link>
)}
<CardContent className="flex-1 pt-4 pb-2">
{post.categories.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
{post.categories.slice(0, 3).map((cat) => (
<Badge
key={cat}
variant="secondary"
className="text-xs uppercase tracking-wide"
>
{cat}
</Badge>
))}
</div>
)}
<Link href={`/blog/${post.slug}`} className="group">
<h3 className="font-semibold leading-tight text-foreground group-hover:text-primary transition-colors line-clamp-2">
{post.title}
</h3>
</Link>
{post.excerpt && (
<p className="mt-2 text-sm text-muted-foreground line-clamp-3">
{post.excerpt}
</p>
)}
</CardContent>
<CardFooter className="pt-0 pb-4 px-6 flex flex-wrap gap-1.5 items-center justify-between">
<div className="flex flex-wrap gap-1">
{post.tags.slice(0, 3).map((tag) => (
<Badge key={tag} variant="outline" className="text-xs">
#{tag}
</Badge>
))}
</div>
<span className="flex items-center gap-1 text-xs text-muted-foreground ml-auto">
<Eye className="h-3 w-3" />
{post.views.toLocaleString()}
</span>
</CardFooter>
</Card>
);
}

View File

@@ -0,0 +1,137 @@
"use client";
import { useRouter, useSearchParams } from "next/navigation";
import { useCallback } from "react";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Search, X } from "lucide-react";
import { TagCloudItem } from "@/lib/types";
interface PostFilterFormProps {
topCategories: TagCloudItem[];
currentQ: string;
currentCategory: string;
currentSort: string;
currentTags: string;
}
export function PostFilterForm({
topCategories,
currentQ,
currentCategory,
currentSort,
currentTags,
}: PostFilterFormProps) {
const router = useRouter();
const searchParams = useSearchParams();
const updateParam = useCallback(
(updates: Record<string, string>) => {
const params = new URLSearchParams(searchParams.toString());
for (const [key, val] of Object.entries(updates)) {
if (val) {
params.set(key, val);
} else {
params.delete(key);
}
}
params.set("page", "1");
router.push(`?${params.toString()}`);
},
[router, searchParams]
);
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const fd = new FormData(e.currentTarget);
updateParam({
q: fd.get("q") as string,
tags: fd.get("tags") as string,
});
};
const clearFilters = () => {
router.push("/");
};
const hasFilters = currentQ || currentCategory || currentTags || (currentSort && currentSort !== "newest");
return (
<form
onSubmit={handleSubmit}
className="rounded-xl border bg-card p-4 shadow-sm space-y-3"
>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
{/* Search */}
<div className="sm:col-span-2 relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
name="q"
defaultValue={currentQ}
placeholder="Search posts…"
className="pl-9"
/>
</div>
{/* Category */}
<Select
defaultValue={currentCategory || "all"}
onValueChange={(val) =>
updateParam({ category: val === "all" ? "" : val })
}
>
<SelectTrigger>
<SelectValue placeholder="Category" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All categories</SelectItem>
{topCategories.map((c) => (
<SelectItem key={c.name} value={c.name}>
{c.name} ({c.count})
</SelectItem>
))}
</SelectContent>
</Select>
{/* Sort */}
<Select
defaultValue={currentSort || "newest"}
onValueChange={(val) => updateParam({ sort: val })}
>
<SelectTrigger>
<SelectValue placeholder="Sort" />
</SelectTrigger>
<SelectContent>
<SelectItem value="newest">Newest</SelectItem>
<SelectItem value="oldest">Oldest</SelectItem>
<SelectItem value="most_viewed">Most viewed</SelectItem>
<SelectItem value="featured">Featured first</SelectItem>
</SelectContent>
</Select>
</div>
<div className="flex gap-2 items-end">
<div className="flex-1">
<Input
name="tags"
defaultValue={currentTags}
placeholder="Tags (comma separated): nextjs, typescript"
/>
</div>
<Button type="submit">Apply</Button>
{hasFilters && (
<Button type="button" variant="ghost" onClick={clearFilters}>
<X className="h-4 w-4" />
</Button>
)}
</div>
</form>
);
}

View File

@@ -0,0 +1,66 @@
"use client"
import * as React from "react"
import { ChevronDownIcon } from "lucide-react"
import { Accordion as AccordionPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Accordion({
...props
}: React.ComponentProps<typeof AccordionPrimitive.Root>) {
return <AccordionPrimitive.Root data-slot="accordion" {...props} />
}
function AccordionItem({
className,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Item>) {
return (
<AccordionPrimitive.Item
data-slot="accordion-item"
className={cn("border-b last:border-b-0", className)}
{...props}
/>
)
}
function AccordionTrigger({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
return (
<AccordionPrimitive.Header className="flex">
<AccordionPrimitive.Trigger
data-slot="accordion-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 flex flex-1 items-start justify-between gap-4 rounded-md py-4 text-left text-sm font-medium transition-all outline-none hover:underline focus-visible:ring-[3px] disabled:pointer-events-none disabled:opacity-50 [&[data-state=open]>svg]:rotate-180",
className
)}
{...props}
>
{children}
<ChevronDownIcon className="text-muted-foreground pointer-events-none size-4 shrink-0 translate-y-0.5 transition-transform duration-200" />
</AccordionPrimitive.Trigger>
</AccordionPrimitive.Header>
)
}
function AccordionContent({
className,
children,
...props
}: React.ComponentProps<typeof AccordionPrimitive.Content>) {
return (
<AccordionPrimitive.Content
data-slot="accordion-content"
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
{...props}
>
<div className={cn("pt-0 pb-4", className)}>{children}</div>
</AccordionPrimitive.Content>
)
}
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

View File

@@ -0,0 +1,196 @@
"use client"
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 group/alert-dialog-content fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"bg-muted mb-2 inline-flex size-16 items-center justify-center rounded-md sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

View File

@@ -0,0 +1,66 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const alertVariants = cva(
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
{
variants: {
variant: {
default: "bg-card text-card-foreground",
destructive:
"text-destructive bg-card [&>svg]:text-current *:data-[slot=alert-description]:text-destructive/90",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Alert({
className,
variant,
...props
}: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
return (
<div
data-slot="alert"
role="alert"
className={cn(alertVariants({ variant }), className)}
{...props}
/>
)
}
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-title"
className={cn(
"col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight",
className
)}
{...props}
/>
)
}
function AlertDescription({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-description"
className={cn(
"text-muted-foreground col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed",
className
)}
{...props}
/>
)
}
export { Alert, AlertTitle, AlertDescription }

View File

@@ -0,0 +1,11 @@
"use client"
import { AspectRatio as AspectRatioPrimitive } from "radix-ui"
function AspectRatio({
...props
}: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />
}
export { AspectRatio }

View File

@@ -0,0 +1,109 @@
"use client"
import * as React from "react"
import { Avatar as AvatarPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Avatar({
className,
size = "default",
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root> & {
size?: "default" | "sm" | "lg"
}) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
className
)}
{...props}
/>
)
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
{...props}
/>
)
}
function AvatarFallback({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted text-muted-foreground flex size-full items-center justify-center rounded-full text-sm group-data-[size=sm]/avatar:text-xs",
className
)}
{...props}
/>
)
}
function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="avatar-badge"
className={cn(
"bg-primary text-primary-foreground ring-background absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full ring-2 select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
className
)}
{...props}
/>
)
}
function AvatarGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group"
className={cn(
"*:data-[slot=avatar]:ring-background group/avatar-group flex -space-x-2 *:data-[slot=avatar]:ring-2",
className
)}
{...props}
/>
)
}
function AvatarGroupCount({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="avatar-group-count"
className={cn(
"bg-muted text-muted-foreground ring-background relative flex size-8 shrink-0 items-center justify-center rounded-full text-sm ring-2 group-has-data-[size=lg]/avatar-group:size-10 group-has-data-[size=sm]/avatar-group:size-6 [&>svg]:size-4 group-has-data-[size=lg]/avatar-group:[&>svg]:size-5 group-has-data-[size=sm]/avatar-group:[&>svg]:size-3",
className
)}
{...props}
/>
)
}
export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarBadge,
AvatarGroup,
AvatarGroupCount,
}

View File

@@ -0,0 +1,48 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const badgeVariants = cva(
"inline-flex items-center justify-center rounded-full border border-transparent px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
secondary:
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive:
"bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
ghost: "[a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
link: "text-primary underline-offset-4 [a&]:hover:underline",
},
},
defaultVariants: {
variant: "default",
},
}
)
function Badge({
className,
variant = "default",
asChild = false,
...props
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : "span"
return (
<Comp
data-slot="badge"
data-variant={variant}
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
)
}
export { Badge, badgeVariants }

View File

@@ -0,0 +1,64 @@
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
{
variants: {
variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90",
destructive:
"bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
outline:
"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
secondary:
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3",
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
icon: "size-9",
"icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
"icon-sm": "size-8",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Button({
className,
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
data-slot="button"
data-variant={variant}
data-size={size}
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Button, buttonVariants }

View File

@@ -0,0 +1,92 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card"
className={cn(
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
className
)}
{...props}
/>
)
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
)}
{...props}
/>
)
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
{...props}
/>
)
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
)
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
{...props}
/>
)
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -0,0 +1,241 @@
"use client"
import * as React from "react"
import useEmblaCarousel, {
type UseEmblaCarouselType,
} from "embla-carousel-react"
import { ArrowLeft, ArrowRight } from "lucide-react"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
type CarouselApi = UseEmblaCarouselType[1]
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
type CarouselOptions = UseCarouselParameters[0]
type CarouselPlugin = UseCarouselParameters[1]
type CarouselProps = {
opts?: CarouselOptions
plugins?: CarouselPlugin
orientation?: "horizontal" | "vertical"
setApi?: (api: CarouselApi) => void
}
type CarouselContextProps = {
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
api: ReturnType<typeof useEmblaCarousel>[1]
scrollPrev: () => void
scrollNext: () => void
canScrollPrev: boolean
canScrollNext: boolean
} & CarouselProps
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
function useCarousel() {
const context = React.useContext(CarouselContext)
if (!context) {
throw new Error("useCarousel must be used within a <Carousel />")
}
return context
}
function Carousel({
orientation = "horizontal",
opts,
setApi,
plugins,
className,
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
axis: orientation === "horizontal" ? "x" : "y",
},
plugins
)
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
const [canScrollNext, setCanScrollNext] = React.useState(false)
const onSelect = React.useCallback((api: CarouselApi) => {
if (!api) return
setCanScrollPrev(api.canScrollPrev())
setCanScrollNext(api.canScrollNext())
}, [])
const scrollPrev = React.useCallback(() => {
api?.scrollPrev()
}, [api])
const scrollNext = React.useCallback(() => {
api?.scrollNext()
}, [api])
const handleKeyDown = React.useCallback(
(event: React.KeyboardEvent<HTMLDivElement>) => {
if (event.key === "ArrowLeft") {
event.preventDefault()
scrollPrev()
} else if (event.key === "ArrowRight") {
event.preventDefault()
scrollNext()
}
},
[scrollPrev, scrollNext]
)
React.useEffect(() => {
if (!api || !setApi) return
setApi(api)
}, [api, setApi])
React.useEffect(() => {
if (!api) return
onSelect(api)
api.on("reInit", onSelect)
api.on("select", onSelect)
return () => {
api?.off("select", onSelect)
}
}, [api, onSelect])
return (
<CarouselContext.Provider
value={{
carouselRef,
api: api,
opts,
orientation:
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
scrollPrev,
scrollNext,
canScrollPrev,
canScrollNext,
}}
>
<div
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
data-slot="carousel"
{...props}
>
{children}
</div>
</CarouselContext.Provider>
)
}
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
const { carouselRef, orientation } = useCarousel()
return (
<div
ref={carouselRef}
className="overflow-hidden"
data-slot="carousel-content"
>
<div
className={cn(
"flex",
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
className
)}
{...props}
/>
</div>
)
}
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel()
return (
<div
role="group"
aria-roledescription="slide"
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
orientation === "horizontal" ? "pl-4" : "pt-4",
className
)}
{...props}
/>
)
}
function CarouselPrevious({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
return (
<Button
data-slot="carousel-previous"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -left-12 -translate-y-1/2"
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollPrev}
onClick={scrollPrev}
{...props}
>
<ArrowLeft />
<span className="sr-only">Previous slide</span>
</Button>
)
}
function CarouselNext({
className,
variant = "outline",
size = "icon",
...props
}: React.ComponentProps<typeof Button>) {
const { orientation, scrollNext, canScrollNext } = useCarousel()
return (
<Button
data-slot="carousel-next"
variant={variant}
size={size}
className={cn(
"absolute size-8 rounded-full",
orientation === "horizontal"
? "top-1/2 -right-12 -translate-y-1/2"
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
className
)}
disabled={!canScrollNext}
onClick={scrollNext}
{...props}
>
<ArrowRight />
<span className="sr-only">Next slide</span>
</Button>
)
}
export {
type CarouselApi,
Carousel,
CarouselContent,
CarouselItem,
CarouselPrevious,
CarouselNext,
}

View File

@@ -0,0 +1,32 @@
"use client"
import * as React from "react"
import { CheckIcon } from "lucide-react"
import { Checkbox as CheckboxPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Checkbox({
className,
...props
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
return (
<CheckboxPrimitive.Root
data-slot="checkbox"
className={cn(
"peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator
data-slot="checkbox-indicator"
className="grid place-content-center text-current transition-none"
>
<CheckIcon className="size-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
)
}
export { Checkbox }

View File

@@ -0,0 +1,158 @@
"use client"
import * as React from "react"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
}
function DialogOverlay({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
return (
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function DialogContent({
className,
children,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 outline-none sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
)}
</DialogPrimitive.Content>
</DialogPortal>
)
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
{...props}
/>
)
}
function DialogFooter({
className,
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close asChild>
<Button variant="outline">Close</Button>
</DialogPrimitive.Close>
)}
</div>
)
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
{...props}
/>
)
}
function DialogDescription({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Description>) {
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,257 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
)
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
)
}
function DropdownMenuContent({
className,
sideOffset = 4,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
return (
<DropdownMenuPrimitive.Portal>
<DropdownMenuPrimitive.Content
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
)}
{...props}
/>
</DropdownMenuPrimitive.Portal>
)
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
)
}
function DropdownMenuItem({
className,
inset,
variant = "default",
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean
variant?: "default" | "destructive"
}) {
return (
<DropdownMenuPrimitive.Item
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
/>
)
}
function DropdownMenuCheckboxItem({
className,
children,
checked,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
return (
<DropdownMenuPrimitive.CheckboxItem
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
checked={checked}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.CheckboxItem>
)
}
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
)
}
function DropdownMenuRadioItem({
className,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
return (
<DropdownMenuPrimitive.RadioItem
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
<DropdownMenuPrimitive.ItemIndicator>
<CircleIcon className="size-2 fill-current" />
</DropdownMenuPrimitive.ItemIndicator>
</span>
{children}
</DropdownMenuPrimitive.RadioItem>
)
}
function DropdownMenuLabel({
className,
inset,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props}
/>
)
}
function DropdownMenuSeparator({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
}
function DropdownMenuSubTrigger({
className,
inset,
children,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
inset?: boolean
}) {
return (
<DropdownMenuPrimitive.SubTrigger
data-slot="dropdown-menu-sub-trigger"
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ChevronRightIcon className="ml-auto size-4" />
</DropdownMenuPrimitive.SubTrigger>
)
}
function DropdownMenuSubContent({
className,
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
return (
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
)}
{...props}
/>
)
}
export {
DropdownMenu,
DropdownMenuPortal,
DropdownMenuTrigger,
DropdownMenuContent,
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuSub,
DropdownMenuSubTrigger,
DropdownMenuSubContent,
}

View File

@@ -0,0 +1,21 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
)}
{...props}
/>
)
}
export { Input }

View File

@@ -0,0 +1,24 @@
"use client"
import * as React from "react"
import { Label as LabelPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
className={cn(
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
className
)}
{...props}
/>
)
}
export { Label }

View File

@@ -0,0 +1,89 @@
"use client"
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-1 text-sm", className)}
{...props}
/>
)
}
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
return (
<div
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
}
function PopoverDescription({
className,
...props
}: React.ComponentProps<"p">) {
return (
<p
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
{...props}
/>
)
}
export {
Popover,
PopoverTrigger,
PopoverContent,
PopoverAnchor,
PopoverHeader,
PopoverTitle,
PopoverDescription,
}

View File

@@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import { Progress as ProgressPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Progress({
className,
value,
...props
}: React.ComponentProps<typeof ProgressPrimitive.Root>) {
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
"bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",
className
)}
{...props}
>
<ProgressPrimitive.Indicator
data-slot="progress-indicator"
className="bg-primary h-full w-full flex-1 transition-all"
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
}
export { Progress }

View File

@@ -0,0 +1,45 @@
"use client"
import * as React from "react"
import { CircleIcon } from "lucide-react"
import { RadioGroup as RadioGroupPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function RadioGroup({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Root>) {
return (
<RadioGroupPrimitive.Root
data-slot="radio-group"
className={cn("grid gap-3", className)}
{...props}
/>
)
}
function RadioGroupItem({
className,
...props
}: React.ComponentProps<typeof RadioGroupPrimitive.Item>) {
return (
<RadioGroupPrimitive.Item
data-slot="radio-group-item"
className={cn(
"border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",
className
)}
{...props}
>
<RadioGroupPrimitive.Indicator
data-slot="radio-group-indicator"
className="relative flex items-center justify-center"
>
<CircleIcon className="fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2" />
</RadioGroupPrimitive.Indicator>
</RadioGroupPrimitive.Item>
)
}
export { RadioGroup, RadioGroupItem }

View File

@@ -0,0 +1,58 @@
"use client"
import * as React from "react"
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function ScrollArea({
className,
children,
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
data-slot="scroll-area-viewport"
className="focus-visible:ring-ring/50 size-full rounded-[inherit] transition-[color,box-shadow] outline-none focus-visible:ring-[3px] focus-visible:outline-1"
>
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
}
function ScrollBar({
className,
orientation = "vertical",
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
<ScrollAreaPrimitive.ScrollAreaScrollbar
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb
data-slot="scroll-area-thumb"
className="bg-border relative flex-1 rounded-full"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
)
}
export { ScrollArea, ScrollBar }

View File

@@ -0,0 +1,190 @@
"use client"
import * as React from "react"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { Select as SelectPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
}
function SelectTrigger({
className,
size = "default",
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
}) {
return (
<SelectPrimitive.Trigger
data-slot="select-trigger"
data-size={size}
className={cn(
"border-input data-[placeholder]:text-muted-foreground [&_svg:not([class*='text-'])]:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 dark:hover:bg-input/50 flex w-fit items-center justify-between gap-2 rounded-md border bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border shadow-md",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
align={align}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("text-muted-foreground px-2 py-1.5 text-xs", className)}
{...props}
/>
)
}
function SelectItem({
className,
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Item>) {
return (
<SelectPrimitive.Item
data-slot="select-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
)}
{...props}
>
<span
data-slot="select-item-indicator"
className="absolute right-2 flex size-3.5 items-center justify-center"
>
<SelectPrimitive.ItemIndicator>
<CheckIcon className="size-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
}
function SelectSeparator({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Separator>) {
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("bg-border pointer-events-none -mx-1 my-1 h-px", className)}
{...props}
/>
)
}
function SelectScrollUpButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollUpButton>) {
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
}
function SelectScrollDownButton({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.ScrollDownButton>) {
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
}
export {
Select,
SelectContent,
SelectGroup,
SelectItem,
SelectLabel,
SelectScrollDownButton,
SelectScrollUpButton,
SelectSeparator,
SelectTrigger,
SelectValue,
}

View File

@@ -0,0 +1,28 @@
"use client"
import * as React from "react"
import { Separator as SeparatorPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Separator({
className,
orientation = "horizontal",
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
return (
<SeparatorPrimitive.Root
data-slot="separator"
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
)}
{...props}
/>
)
}
export { Separator }

View File

@@ -0,0 +1,143 @@
"use client"
import * as React from "react"
import { XIcon } from "lucide-react"
import { Dialog as SheetPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
}
function SheetOverlay({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Overlay>) {
return (
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
)}
{...props}
/>
)
}
function SheetContent({
className,
children,
side = "right",
showCloseButton = true,
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
showCloseButton?: boolean
}) {
return (
<SheetPortal>
<SheetOverlay />
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
)}
{...props}
>
{children}
{showCloseButton && (
<SheetPrimitive.Close className="ring-offset-background focus:ring-ring data-[state=open]:bg-secondary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none">
<XIcon className="size-4" />
<span className="sr-only">Close</span>
</SheetPrimitive.Close>
)}
</SheetPrimitive.Content>
</SheetPortal>
)
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
{...props}
/>
)
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
{...props}
/>
)
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
{...props}
/>
)
}
function SheetDescription({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Description>) {
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Sheet,
SheetTrigger,
SheetClose,
SheetContent,
SheetHeader,
SheetFooter,
SheetTitle,
SheetDescription,
}

View File

@@ -0,0 +1,13 @@
import { cn } from "@/lib/utils"
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="skeleton"
className={cn("bg-accent animate-pulse rounded-md", className)}
{...props}
/>
)
}
export { Skeleton }

View File

@@ -0,0 +1,63 @@
"use client"
import * as React from "react"
import { Slider as SliderPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Slider({
className,
defaultValue,
value,
min = 0,
max = 100,
...props
}: React.ComponentProps<typeof SliderPrimitive.Root>) {
const _values = React.useMemo(
() =>
Array.isArray(value)
? value
: Array.isArray(defaultValue)
? defaultValue
: [min, max],
[value, defaultValue, min, max]
)
return (
<SliderPrimitive.Root
data-slot="slider"
defaultValue={defaultValue}
value={value}
min={min}
max={max}
className={cn(
"relative flex w-full touch-none items-center select-none data-[disabled]:opacity-50 data-[orientation=vertical]:h-full data-[orientation=vertical]:min-h-44 data-[orientation=vertical]:w-auto data-[orientation=vertical]:flex-col",
className
)}
{...props}
>
<SliderPrimitive.Track
data-slot="slider-track"
className={cn(
"bg-muted relative grow overflow-hidden rounded-full data-[orientation=horizontal]:h-1.5 data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-1.5"
)}
>
<SliderPrimitive.Range
data-slot="slider-range"
className={cn(
"bg-primary absolute data-[orientation=horizontal]:h-full data-[orientation=vertical]:w-full"
)}
/>
</SliderPrimitive.Track>
{Array.from({ length: _values.length }, (_, index) => (
<SliderPrimitive.Thumb
data-slot="slider-thumb"
key={index}
className="border-primary ring-ring/50 block size-4 shrink-0 rounded-full border bg-white shadow-sm transition-[color,box-shadow] hover:ring-4 focus-visible:ring-4 focus-visible:outline-hidden disabled:pointer-events-none disabled:opacity-50"
/>
))}
</SliderPrimitive.Root>
)
}
export { Slider }

View File

@@ -0,0 +1,40 @@
"use client"
import {
CircleCheckIcon,
InfoIcon,
Loader2Icon,
OctagonXIcon,
TriangleAlertIcon,
} from "lucide-react"
import { useTheme } from "next-themes"
import { Toaster as Sonner, type ToasterProps } from "sonner"
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
icons={{
success: <CircleCheckIcon className="size-4" />,
info: <InfoIcon className="size-4" />,
warning: <TriangleAlertIcon className="size-4" />,
error: <OctagonXIcon className="size-4" />,
loading: <Loader2Icon className="size-4 animate-spin" />,
}}
style={
{
"--normal-bg": "var(--popover)",
"--normal-text": "var(--popover-foreground)",
"--normal-border": "var(--border)",
"--border-radius": "var(--radius)",
} as React.CSSProperties
}
{...props}
/>
)
}
export { Toaster }

View File

@@ -0,0 +1,35 @@
"use client"
import * as React from "react"
import { Switch as SwitchPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Switch({
className,
size = "default",
...props
}: React.ComponentProps<typeof SwitchPrimitive.Root> & {
size?: "sm" | "default"
}) {
return (
<SwitchPrimitive.Root
data-slot="switch"
data-size={size}
className={cn(
"peer data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:border-ring focus-visible:ring-ring/50 dark:data-[state=unchecked]:bg-input/80 group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6",
className
)}
{...props}
>
<SwitchPrimitive.Thumb
data-slot="switch-thumb"
className={cn(
"bg-background dark:data-[state=unchecked]:bg-foreground dark:data-[state=checked]:bg-primary-foreground pointer-events-none block rounded-full ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-[state=checked]:translate-x-[calc(100%-2px)] data-[state=unchecked]:translate-x-0"
)}
/>
</SwitchPrimitive.Root>
)
}
export { Switch }

View File

@@ -0,0 +1,116 @@
"use client"
import * as React from "react"
import { cn } from "@/lib/utils"
function Table({ className, ...props }: React.ComponentProps<"table">) {
return (
<div
data-slot="table-container"
className="relative w-full overflow-x-auto"
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
{...props}
/>
</div>
)
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
{...props}
/>
)
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"bg-muted/50 border-t font-medium [&>tr]:last:border-b-0",
className
)}
{...props}
/>
)
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
return (
<tr
data-slot="table-row"
className={cn(
"hover:bg-muted/50 data-[state=selected]:bg-muted border-b transition-colors",
className
)}
{...props}
/>
)
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
return (
<th
data-slot="table-head"
className={cn(
"text-foreground h-10 px-2 text-left align-middle font-medium whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
)}
{...props}
/>
)
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
return (
<caption
data-slot="table-caption"
className={cn("text-muted-foreground mt-4 text-sm", className)}
{...props}
/>
)
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}

View File

@@ -0,0 +1,91 @@
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Tabs as TabsPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function Tabs({
className,
orientation = "horizontal",
...props
}: React.ComponentProps<typeof TabsPrimitive.Root>) {
return (
<TabsPrimitive.Root
data-slot="tabs"
data-orientation={orientation}
orientation={orientation}
className={cn(
"group/tabs flex gap-2 data-[orientation=horizontal]:flex-col",
className
)}
{...props}
/>
)
}
const tabsListVariants = cva(
"rounded-lg p-[3px] group-data-[orientation=horizontal]/tabs:h-9 data-[variant=line]:rounded-none group/tabs-list text-muted-foreground inline-flex w-fit items-center justify-center group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col",
{
variants: {
variant: {
default: "bg-muted",
line: "gap-1 bg-transparent",
},
},
defaultVariants: {
variant: "default",
},
}
)
function TabsList({
className,
variant = "default",
...props
}: React.ComponentProps<typeof TabsPrimitive.List> &
VariantProps<typeof tabsListVariants>) {
return (
<TabsPrimitive.List
data-slot="tabs-list"
data-variant={variant}
className={cn(tabsListVariants({ variant }), className)}
{...props}
/>
)
}
function TabsTrigger({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
return (
<TabsPrimitive.Trigger
data-slot="tabs-trigger"
className={cn(
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:outline-ring text-foreground/60 hover:text-foreground dark:text-muted-foreground dark:hover:text-foreground relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start focus-visible:ring-[3px] focus-visible:outline-1 disabled:pointer-events-none disabled:opacity-50 group-data-[variant=default]/tabs-list:data-[state=active]:shadow-sm group-data-[variant=line]/tabs-list:data-[state=active]:shadow-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:border-transparent dark:group-data-[variant=line]/tabs-list:data-[state=active]:bg-transparent",
"data-[state=active]:bg-background dark:data-[state=active]:text-foreground dark:data-[state=active]:border-input dark:data-[state=active]:bg-input/30 data-[state=active]:text-foreground",
"after:bg-foreground after:absolute after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-[state=active]:after:opacity-100",
className
)}
{...props}
/>
)
}
function TabsContent({
className,
...props
}: React.ComponentProps<typeof TabsPrimitive.Content>) {
return (
<TabsPrimitive.Content
data-slot="tabs-content"
className={cn("flex-1 outline-none", className)}
{...props}
/>
)
}
export { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants }

View File

@@ -0,0 +1,18 @@
import * as React from "react"
import { cn } from "@/lib/utils"
function Textarea({ className, ...props }: React.ComponentProps<"textarea">) {
return (
<textarea
data-slot="textarea"
className={cn(
"border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
className
)}
{...props}
/>
)
}
export { Textarea }

View File

@@ -0,0 +1,47 @@
"use client"
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Toggle as TogglePrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
const toggleVariants = cva(
"inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium hover:bg-muted hover:text-muted-foreground disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] outline-none transition-[color,box-shadow] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive whitespace-nowrap",
{
variants: {
variant: {
default: "bg-transparent",
outline:
"border border-input bg-transparent shadow-xs hover:bg-accent hover:text-accent-foreground",
},
size: {
default: "h-9 px-2 min-w-9",
sm: "h-8 px-1.5 min-w-8",
lg: "h-10 px-2.5 min-w-10",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
function Toggle({
className,
variant,
size,
...props
}: React.ComponentProps<typeof TogglePrimitive.Root> &
VariantProps<typeof toggleVariants>) {
return (
<TogglePrimitive.Root
data-slot="toggle"
className={cn(toggleVariants({ variant, size, className }))}
{...props}
/>
)
}
export { Toggle, toggleVariants }

View File

@@ -0,0 +1,57 @@
"use client"
import * as React from "react"
import { Tooltip as TooltipPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
function TooltipProvider({
delayDuration = 0,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return (
<TooltipPrimitive.Provider
data-slot="tooltip-provider"
delayDuration={delayDuration}
{...props}
/>
)
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return <TooltipPrimitive.Root data-slot="tooltip" {...props} />
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
}
function TooltipContent({
className,
sideOffset = 0,
children,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Content>) {
return (
<TooltipPrimitive.Portal>
<TooltipPrimitive.Content
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
)}
{...props}
>
{children}
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

View File

@@ -0,0 +1,18 @@
import { defineConfig, globalIgnores } from "eslint/config";
import nextVitals from "eslint-config-next/core-web-vitals";
import nextTs from "eslint-config-next/typescript";
const eslintConfig = defineConfig([
...nextVitals,
...nextTs,
// Override default ignores of eslint-config-next.
globalIgnores([
// Default ignores of eslint-config-next:
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
]),
]);
export default eslintConfig;

129
frontend/lib/api.ts Normal file
View File

@@ -0,0 +1,129 @@
/**
* API helpers for server components (forwards cookies) and client components (credentials: include).
*/
const API_URL = process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001";
const STATE_CHANGING_METHODS = ["POST", "PATCH", "PUT", "DELETE"];
// ─── Read csrfToken cookie in the browser ─────────────────────────────────────
function getClientCsrfToken(): string {
if (typeof document === "undefined") return "";
const match = document.cookie.match(/(?:^|;\s*)csrfToken=([^;]+)/);
return match ? decodeURIComponent(match[1]) : "";
}
// ─── Server-side fetch (use in Server Components / Route Handlers) ─────────────
export async function apiFetch<T = unknown>(
path: string,
init?: RequestInit
): Promise<T> {
// Dynamic import so this module can also be imported in client components
// The `cookies` call only runs on the server side
let cookieHeader = "";
let csrfToken = "";
try {
const { cookies } = await import("next/headers");
const store = await cookies();
cookieHeader = store
.getAll()
.map((c) => `${c.name}=${c.value}`)
.join("; ");
// Forward the CSRF token from the cookie store for mutating server-side calls
csrfToken = store.get("csrfToken")?.value ?? "";
} catch {
// We're on the client — skip cookie forwarding
}
const method = (init?.method ?? "GET").toUpperCase();
const needsCsrf = STATE_CHANGING_METHODS.includes(method);
const res = await fetch(`${API_URL}${path}`, {
...init,
cache: "no-store",
headers: {
"Content-Type": "application/json",
...(cookieHeader ? { Cookie: cookieHeader } : {}),
...(needsCsrf && csrfToken ? { "x-csrf-token": csrfToken } : {}),
...(init?.headers as Record<string, string> | undefined),
},
});
if (!res.ok) {
let msg = `API error ${res.status}`;
try {
const body = await res.json();
msg = body?.error?.message || body?.message || msg;
} catch {
/* ignore */
}
throw new ApiError(msg, res.status);
}
// Some endpoints return 204 No Content
const text = await res.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
}
// ─── Client-side fetch (use in Client Components) ─────────────────────────────
async function doClientFetch(path: string, init?: RequestInit): Promise<Response> {
const method = (init?.method ?? "GET").toUpperCase();
const needsCsrf = STATE_CHANGING_METHODS.includes(method);
const csrfToken = needsCsrf ? getClientCsrfToken() : "";
return fetch(`${API_URL}${path}`, {
...init,
credentials: "include",
headers: {
"Content-Type": "application/json",
...(needsCsrf && csrfToken ? { "x-csrf-token": csrfToken } : {}),
...(init?.headers as Record<string, string> | undefined),
},
});
}
export async function clientFetch<T = unknown>(
path: string,
init?: RequestInit
): Promise<T> {
let res = await doClientFetch(path, init);
// Auto-refresh expired access token on 401, then retry once.
// Skip for /auth/ paths to avoid refresh loops.
if (res.status === 401 && !path.startsWith("/auth/")) {
const refreshRes = await doClientFetch("/auth/refresh", { method: "POST" });
if (refreshRes.ok) {
res = await doClientFetch(path, init);
}
}
if (!res.ok) {
let msg = `API error ${res.status}`;
try {
const body = await res.json();
msg = body?.error?.message || body?.message || msg;
} catch {
/* ignore */
}
throw new ApiError(msg, res.status);
}
const text = await res.text();
if (!text) return undefined as T;
return JSON.parse(text) as T;
}
export class ApiError extends Error {
constructor(
message: string,
public status: number
) {
super(message);
this.name = "ApiError";
}
}
export { API_URL };

128
frontend/lib/auth.tsx Normal file
View File

@@ -0,0 +1,128 @@
"use client";
import {
createContext,
useCallback,
useContext,
useEffect,
useState,
} from "react";
import { clientFetch, ApiError } from "./api";
import { CurrentUser, UserRole } from "./types";
interface AuthContextValue {
currentUser: CurrentUser | null;
loading: boolean;
login: (email: string, password: string) => Promise<void>;
register: (name: string, email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
refresh: () => Promise<void>;
}
const AuthContext = createContext<AuthContextValue | null>(null);
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [currentUser, setCurrentUser] = useState<CurrentUser | null>(null);
const [loading, setLoading] = useState(true);
/** Calls GET /auth/me with the httpOnly cookie to restore the current user.
* Returns the JWT payload if valid, clears auth state if 401. */
const refresh = useCallback(async () => {
try {
const data = await clientFetch<{ success: boolean; user: CurrentUser }>(
"/auth/me"
);
if (data.user) {
const user: CurrentUser = {
sub: data.user.sub,
email: data.user.email,
role: (data.user.role as string).toUpperCase() as UserRole,
name: data.user.name,
};
setCurrentUser(user);
sessionStorage.setItem("currentUser", JSON.stringify(user));
}
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
setCurrentUser(null);
sessionStorage.removeItem("currentUser");
}
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
refresh();
}, [refresh]);
const login = useCallback(async (email: string, password: string) => {
const data = await clientFetch<{
success: boolean;
user?: CurrentUser;
accessToken?: string;
}>("/auth/login", {
method: "POST",
body: JSON.stringify({ email, password }),
});
// The NestJS login returns { success, accessToken, user } for JSON clients
if (data.user) {
// Normalize role to uppercase enum
const user: CurrentUser = {
sub: data.user.sub || (data.user as unknown as { id?: string }).id || "",
email: data.user.email,
role: (data.user.role as string).toUpperCase() as UserRole,
name: data.user.name,
};
setCurrentUser(user);
sessionStorage.setItem("currentUser", JSON.stringify(user));
}
}, []);
const register = useCallback(
async (name: string, email: string, password: string) => {
const data = await clientFetch<{
success: boolean;
user?: CurrentUser;
}>("/auth/register", {
method: "POST",
body: JSON.stringify({ name, email, password }),
});
if (data.user) {
const user: CurrentUser = {
sub: data.user.sub || (data.user as unknown as { id?: string }).id || "",
email: data.user.email,
role: (data.user.role as string).toUpperCase() as UserRole,
name: data.user.name,
};
setCurrentUser(user);
sessionStorage.setItem("currentUser", JSON.stringify(user));
}
},
[]
);
const logout = useCallback(async () => {
try {
await clientFetch("/auth/logout", { method: "POST" });
} catch {
/* ignore */
}
setCurrentUser(null);
sessionStorage.removeItem("currentUser");
}, []);
return (
<AuthContext.Provider
value={{ currentUser, loading, login, register, logout, refresh }}
>
{children}
</AuthContext.Provider>
);
}
export function useAuth() {
const ctx = useContext(AuthContext);
if (!ctx) throw new Error("useAuth must be used within AuthProvider");
return ctx;
}

86
frontend/lib/types.ts Normal file
View File

@@ -0,0 +1,86 @@
export enum PostStatus {
DRAFT = "draft",
PUBLISHED = "published",
ARCHIVED = "archived",
}
export enum ContentFormat {
MARKDOWN = "markdown",
HTML = "html",
}
export enum UserRole {
ADMIN = "ADMIN",
MANAGER = "MANAGER",
MEMBER = "MEMBER",
}
export interface User {
id: string;
email: string;
name?: string;
role: UserRole;
isActive: boolean;
createdAt: string;
}
export interface FeaturedImage {
url: string;
alt: string;
}
export interface BlogPost {
id: string;
title: string;
slug: string;
status: PostStatus;
excerpt: string;
content: string;
contentFormat: ContentFormat;
authorId: string;
author?: Pick<User, "id" | "email" | "name" | "role">;
featuredImageUrl?: string;
featuredImageAlt?: string;
isFeatured: boolean;
views: number;
tags: string[];
categories: string[];
createdAt: string;
updatedAt: string;
}
export interface PaginatedResult<T> {
items: T[];
total: number;
page: number;
pageSize: number;
totalPages: number;
}
export interface TagCloudItem {
name: string;
count: number;
}
export interface CreatePostDto {
title: string;
slug?: string;
excerpt?: string;
content: string;
contentFormat?: ContentFormat;
status?: PostStatus;
featuredImageUrl?: string;
featuredImageAlt?: string;
isFeatured?: boolean;
tags?: string; // comma-separated string
categories?: string; // comma-separated string
}
export interface CurrentUser {
sub: string;
email: string;
role: UserRole;
name?: string;
iat?: number;
exp?: number;
}

6
frontend/lib/utils.ts Normal file
View File

@@ -0,0 +1,6 @@
import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}

13
frontend/next.config.ts Normal file
View File

@@ -0,0 +1,13 @@
import type { NextConfig } from "next";
import path from "path";
const nextConfig: NextConfig = {
turbopack: {
root: path.resolve(__dirname),
},
images: {
unoptimized: true,
},
};
export default nextConfig;

12719
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

48
frontend/package.json Normal file
View File

@@ -0,0 +1,48 @@
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint"
},
"dependencies": {
"@tailwindcss/typography": "^0.5.19",
"@tiptap/extension-character-count": "^3.20.0",
"@tiptap/extension-highlight": "^3.20.0",
"@tiptap/extension-image": "^3.20.0",
"@tiptap/extension-link": "^3.20.0",
"@tiptap/extension-placeholder": "^3.20.0",
"@tiptap/extension-text-align": "^3.20.0",
"@tiptap/extension-underline": "^3.20.0",
"@tiptap/pm": "^3.20.0",
"@tiptap/react": "^3.20.0",
"@tiptap/starter-kit": "^3.20.0",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"embla-carousel-react": "^8.6.0",
"lucide-react": "^0.574.0",
"marked": "^17.0.3",
"next": "16.1.6",
"next-themes": "^0.4.6",
"radix-ui": "^1.4.3",
"react": "19.2.3",
"react-dom": "19.2.3",
"sonner": "^2.0.7",
"tailwind-merge": "^3.4.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.1.6",
"shadcn": "^3.8.5",
"tailwindcss": "^4",
"tw-animate-css": "^1.4.0",
"typescript": "^5"
}
}

View File

@@ -0,0 +1,7 @@
const config = {
plugins: {
"@tailwindcss/postcss": {},
},
};
export default config;

1
frontend/public/file.svg Normal file
View File

@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

1
frontend/public/next.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

View File

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

34
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts",
"**/*.mts"
],
"exclude": ["node_modules"]
}