first commit
This commit is contained in:
132
src/app/admin/editor/[id]/page.tsx
Normal file
132
src/app/admin/editor/[id]/page.tsx
Normal file
@@ -0,0 +1,132 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback, use } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Skeleton } from "@/components/ui/Skeleton";
|
||||
import { MarkdownEditor } from "@/components/editor/MarkdownEditor";
|
||||
import { ImageUpload } from "@/components/editor/ImageUpload";
|
||||
import { PostContent } from "@/components/post/PostContent";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
interface EditPostPageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export default function EditPostEditor({ params }: EditPostPageProps) {
|
||||
const { id } = use(params);
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [published, setPublished] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchPost() {
|
||||
try {
|
||||
const post = await api.getPost(id);
|
||||
setTitle(post.title);
|
||||
setContent(post.content);
|
||||
setPublished(post.published);
|
||||
} catch {
|
||||
router.push("/admin");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchPost();
|
||||
}, [id, router]);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!title.trim()) return;
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.updatePost(id, {
|
||||
title,
|
||||
content,
|
||||
published,
|
||||
});
|
||||
setSaved(true);
|
||||
} catch {
|
||||
alert("Failed to save post");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [id, title, content, published]);
|
||||
|
||||
const handleImageUpload = (url: string) => {
|
||||
const imageMarkdown = `\n`;
|
||||
setContent((prev) => prev + imageMarkdown);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (saved) {
|
||||
const timer = setTimeout(() => setSaved(false), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [saved]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Container className="py-12">
|
||||
<Skeleton className="h-12 w-1/2 mb-8" />
|
||||
<Skeleton className="h-[60vh]" />
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container className="py-12">
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Post title"
|
||||
className="text-4xl font-bold tracking-tighter bg-transparent focus:outline-none placeholder:text-neutral-300 w-full"
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-4 ml-6">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={published}
|
||||
onChange={(e) => setPublished(e.target.checked)}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span className="text-sm tracking-wide">Publish</span>
|
||||
</label>
|
||||
|
||||
<Button onClick={handleSave} disabled={saving || !title.trim()}>
|
||||
{saving ? "Saving..." : saved ? "Saved." : "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<ImageUpload onUpload={handleImageUpload} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-8 h-[calc(100vh-280px)]">
|
||||
<div className="border border-neutral-200 p-6 overflow-auto">
|
||||
<MarkdownEditor value={content} onChange={setContent} />
|
||||
</div>
|
||||
|
||||
<div className="border border-neutral-200 p-6 overflow-auto bg-neutral-50">
|
||||
<div className="prose prose-sm max-w-none">
|
||||
{content ? (
|
||||
<PostContent content={content} />
|
||||
) : (
|
||||
<p className="text-neutral-400">Preview will appear here...</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
102
src/app/admin/editor/page.tsx
Normal file
102
src/app/admin/editor/page.tsx
Normal file
@@ -0,0 +1,102 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, useCallback } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { MarkdownEditor } from "@/components/editor/MarkdownEditor";
|
||||
import { ImageUpload } from "@/components/editor/ImageUpload";
|
||||
import { PostContent } from "@/components/post/PostContent";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
export default function NewPostEditor() {
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState("");
|
||||
const [content, setContent] = useState("");
|
||||
const [published, setPublished] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!title.trim()) return;
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const post = await api.createPost({
|
||||
title,
|
||||
content,
|
||||
published,
|
||||
});
|
||||
setSaved(true);
|
||||
setTimeout(() => {
|
||||
router.push(`/admin/editor/${post.id}`);
|
||||
}, 1000);
|
||||
} catch {
|
||||
alert("Failed to save post");
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [title, content, published, router]);
|
||||
|
||||
const handleImageUpload = (url: string) => {
|
||||
const imageMarkdown = `\n`;
|
||||
setContent((prev) => prev + imageMarkdown);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (saved) {
|
||||
const timer = setTimeout(() => setSaved(false), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [saved]);
|
||||
|
||||
return (
|
||||
<Container className="py-12">
|
||||
<div className="flex items-center justify-between mb-8">
|
||||
<input
|
||||
type="text"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
placeholder="Post title"
|
||||
className="text-4xl font-bold tracking-tighter bg-transparent focus:outline-none placeholder:text-neutral-300 w-full"
|
||||
/>
|
||||
|
||||
<div className="flex items-center gap-4 ml-6">
|
||||
<label className="flex items-center gap-2 cursor-pointer">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={published}
|
||||
onChange={(e) => setPublished(e.target.checked)}
|
||||
className="w-4 h-4"
|
||||
/>
|
||||
<span className="text-sm tracking-wide">Publish</span>
|
||||
</label>
|
||||
|
||||
<Button onClick={handleSave} disabled={saving || !title.trim()}>
|
||||
{saving ? "Saving..." : saved ? "Saved." : "Save"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mb-6">
|
||||
<ImageUpload onUpload={handleImageUpload} />
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-8 h-[calc(100vh-280px)]">
|
||||
<div className="border border-neutral-200 p-6 overflow-auto">
|
||||
<MarkdownEditor value={content} onChange={setContent} />
|
||||
</div>
|
||||
|
||||
<div className="border border-neutral-200 p-6 overflow-auto bg-neutral-50">
|
||||
<div className="prose prose-sm max-w-none">
|
||||
{content ? (
|
||||
<PostContent content={content} />
|
||||
) : (
|
||||
<p className="text-neutral-400">Preview will appear here...</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
12
src/app/admin/layout.tsx
Normal file
12
src/app/admin/layout.tsx
Normal file
@@ -0,0 +1,12 @@
|
||||
"use client";
|
||||
|
||||
import { type ReactNode } from "react";
|
||||
import { ProtectedRoute } from "@/components/auth/ProtectedRoute";
|
||||
|
||||
interface AdminLayoutProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export default function AdminLayout({ children }: AdminLayoutProps) {
|
||||
return <ProtectedRoute>{children}</ProtectedRoute>;
|
||||
}
|
||||
106
src/app/admin/page.tsx
Normal file
106
src/app/admin/page.tsx
Normal file
@@ -0,0 +1,106 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { Skeleton } from "@/components/ui/Skeleton";
|
||||
import { Tag } from "@/components/ui/Tag";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Post } from "@/types/api";
|
||||
|
||||
export default function AdminDashboard() {
|
||||
const [posts, setPosts] = useState<Post[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [deleting, setDeleting] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
fetchPosts();
|
||||
}, []);
|
||||
|
||||
async function fetchPosts() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const response = await api.getPosts(1, 100);
|
||||
setPosts(response.posts ?? []);
|
||||
} catch {
|
||||
// Handle error silently
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(id: string) {
|
||||
if (!confirm("Are you sure you want to delete this post?")) return;
|
||||
|
||||
setDeleting(id);
|
||||
try {
|
||||
await api.deletePost(id);
|
||||
setPosts((prev) => prev.filter((p) => p.id !== id));
|
||||
} catch {
|
||||
alert("Failed to delete post");
|
||||
} finally {
|
||||
setDeleting(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Container className="py-24">
|
||||
<div className="flex items-center justify-between mb-12">
|
||||
<h1 className="text-5xl font-bold tracking-tighter">Dashboard</h1>
|
||||
<Link href="/admin/editor">
|
||||
<Button>New Post</Button>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{loading && (
|
||||
<div className="space-y-6">
|
||||
<Skeleton className="h-20" />
|
||||
<Skeleton className="h-20" />
|
||||
<Skeleton className="h-20" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && posts.length === 0 && (
|
||||
<p className="text-neutral-400 text-lg">No posts yet. Create your first one.</p>
|
||||
)}
|
||||
|
||||
{!loading && posts.length > 0 && (
|
||||
<div className="space-y-6">
|
||||
{posts.map((post) => (
|
||||
<div
|
||||
key={post.id}
|
||||
className="border border-neutral-200 p-6 flex items-center justify-between"
|
||||
>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-3 mb-2">
|
||||
<h2 className="text-xl font-bold tracking-tight truncate">
|
||||
{post.title || "Untitled"}
|
||||
</h2>
|
||||
<Tag>{post.published ? "Published" : "Draft"}</Tag>
|
||||
</div>
|
||||
<p className="text-sm text-neutral-500 truncate">
|
||||
{post.content.slice(0, 100).replace(/[#*`]/g, "")}...
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4 ml-6">
|
||||
<Link href={`/admin/editor/${post.id}`}>
|
||||
<Button size="sm">Edit</Button>
|
||||
</Link>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => handleDelete(post.id)}
|
||||
disabled={deleting === post.id}
|
||||
className="border-red-500 text-red-500 hover:bg-red-500 hover:text-white"
|
||||
>
|
||||
{deleting === post.id ? "..." : "Delete"}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
@@ -1,26 +1,86 @@
|
||||
@import "tailwindcss";
|
||||
@plugin "@tailwindcss/typography";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
@theme {
|
||||
--font-sans: "Inter", ui-sans-serif, system-ui, sans-serif;
|
||||
--font-mono: "JetBrains Mono", "Fira Code", ui-monospace, monospace;
|
||||
|
||||
--spacing-18: 4.5rem;
|
||||
--spacing-24: 6rem;
|
||||
--spacing-32: 8rem;
|
||||
|
||||
--tracking-tighter: -0.04em;
|
||||
--tracking-tight: -0.02em;
|
||||
--tracking-normal: -0.01em;
|
||||
--tracking-wide: 0.02em;
|
||||
--tracking-widest: 0.08em;
|
||||
|
||||
--leading-relaxed: 1.8;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
@keyframes shake {
|
||||
0%, 100% { transform: translateX(0); }
|
||||
25% { transform: translateX(-4px); }
|
||||
75% { transform: translateX(4px); }
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
.animate-shake {
|
||||
animation: shake 0.3s ease-in-out;
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
/* Syntax highlighting for code blocks */
|
||||
.hljs {
|
||||
background: #fafafa !important;
|
||||
padding: 1.5rem;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.hljs-comment,
|
||||
.hljs-quote {
|
||||
color: #6b7280;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.hljs-keyword,
|
||||
.hljs-selector-tag,
|
||||
.hljs-built_in {
|
||||
color: #1f2937;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.hljs-string,
|
||||
.hljs-attr {
|
||||
color: #374151;
|
||||
}
|
||||
|
||||
.hljs-number,
|
||||
.hljs-literal {
|
||||
color: #4b5563;
|
||||
}
|
||||
|
||||
.hljs-title,
|
||||
.hljs-section {
|
||||
color: #111827;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.hljs-type,
|
||||
.hljs-class {
|
||||
color: #1f2937;
|
||||
}
|
||||
|
||||
/* Prose customizations */
|
||||
.prose pre {
|
||||
background-color: #fafafa;
|
||||
border: 1px solid #e5e5e5;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.prose code {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.875em;
|
||||
}
|
||||
|
||||
.prose img {
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import { Inter, JetBrains_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
import "highlight.js/styles/github.css";
|
||||
import { AuthProvider } from "@/lib/auth-context";
|
||||
import { Header } from "@/components/layout/Header";
|
||||
import { Footer } from "@/components/layout/Footer";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
const inter = Inter({
|
||||
variable: "--font-sans",
|
||||
subsets: ["latin"],
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
const jetbrainsMono = JetBrains_Mono({
|
||||
variable: "--font-mono",
|
||||
subsets: ["latin"],
|
||||
display: "swap",
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "AI Blog",
|
||||
description: "Minimalist blog powered by AI",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
@@ -25,9 +31,13 @@ export default function RootLayout({
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
className={`${inter.variable} ${jetbrainsMono.variable} font-sans font-medium antialiased bg-white text-black min-h-screen flex flex-col`}
|
||||
>
|
||||
{children}
|
||||
<AuthProvider>
|
||||
<Header />
|
||||
<main className="flex-1">{children}</main>
|
||||
<Footer />
|
||||
</AuthProvider>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
|
||||
82
src/app/login/page.tsx
Normal file
82
src/app/login/page.tsx
Normal file
@@ -0,0 +1,82 @@
|
||||
"use client";
|
||||
|
||||
import { useState, type FormEvent } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
import { Input } from "@/components/ui/Input";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { useAuth } from "@/lib/hooks/useAuth";
|
||||
|
||||
export default function LoginPage() {
|
||||
const router = useRouter();
|
||||
const { login } = useAuth();
|
||||
const [email, setEmail] = useState("");
|
||||
const [password, setPassword] = useState("");
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [success, setSuccess] = useState(false);
|
||||
|
||||
const handleSubmit = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
setError(null);
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
await login({ email, password });
|
||||
setSuccess(true);
|
||||
setTimeout(() => {
|
||||
router.push("/admin");
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : "Login failed");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (success) {
|
||||
return (
|
||||
<Container className="py-24 min-h-[60vh] flex flex-col items-center justify-center">
|
||||
<p className="text-3xl font-bold tracking-tighter">Welcome</p>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Container className="py-24">
|
||||
<div className="max-w-md mx-auto">
|
||||
<h1 className="text-5xl font-bold tracking-tighter mb-12">Login</h1>
|
||||
|
||||
<form onSubmit={handleSubmit} className="space-y-8">
|
||||
<Input
|
||||
type="email"
|
||||
label="Email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
placeholder="you@example.com"
|
||||
required
|
||||
error={error ? " " : undefined}
|
||||
/>
|
||||
|
||||
<Input
|
||||
type="password"
|
||||
label="Password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
placeholder="••••••••"
|
||||
required
|
||||
error={error ? " " : undefined}
|
||||
/>
|
||||
|
||||
{error && (
|
||||
<p className="text-sm text-red-500">{error}</p>
|
||||
)}
|
||||
|
||||
<Button type="submit" disabled={loading} className="w-full">
|
||||
{loading ? "Signing in..." : "Sign In"}
|
||||
</Button>
|
||||
</form>
|
||||
</div>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
21
src/app/not-found.tsx
Normal file
21
src/app/not-found.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import Link from "next/link";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
|
||||
export default function NotFound() {
|
||||
return (
|
||||
<Container className="py-24 min-h-[60vh] flex flex-col items-center justify-center text-center">
|
||||
<h1 className="text-[12rem] md:text-[20rem] font-bold tracking-tighter leading-none">
|
||||
404
|
||||
</h1>
|
||||
<p className="text-2xl md:text-3xl tracking-tight mt-4">
|
||||
Signal Lost
|
||||
</p>
|
||||
<Link
|
||||
href="/"
|
||||
className="mt-12 text-sm font-bold tracking-widest uppercase border-b border-black pb-0.5 hover:border-transparent transition-colors"
|
||||
>
|
||||
Return Home
|
||||
</Link>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
137
src/app/page.tsx
137
src/app/page.tsx
@@ -1,65 +1,86 @@
|
||||
import Image from "next/image";
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
import { PostCard } from "@/components/post/PostCard";
|
||||
import { PostCardSkeleton } from "@/components/post/PostCardSkeleton";
|
||||
import { Button } from "@/components/ui/Button";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Post } from "@/types/api";
|
||||
|
||||
export default function HomePage() {
|
||||
const [posts, setPosts] = useState<Post[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [total, setTotal] = useState(0);
|
||||
const limit = 10;
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchPosts() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await api.getPosts(page, limit);
|
||||
setPosts(response.posts ?? []);
|
||||
setTotal(response.total ?? 0);
|
||||
} catch {
|
||||
setError("Could not retrieve latest transmission.");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchPosts();
|
||||
}, [page]);
|
||||
|
||||
const totalPages = Math.ceil(total / limit);
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
||||
To get started, edit the page.tsx file.
|
||||
</h1>
|
||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
<Container className="py-24">
|
||||
<h1 className="text-6xl md:text-8xl font-bold tracking-tighter mb-24">
|
||||
Latest
|
||||
</h1>
|
||||
|
||||
{error && (
|
||||
<p className="text-neutral-400 text-lg">{error}</p>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<>
|
||||
<PostCardSkeleton />
|
||||
<PostCardSkeleton />
|
||||
<PostCardSkeleton />
|
||||
</>
|
||||
)}
|
||||
|
||||
{!loading && !error && posts?.length === 0 && (
|
||||
<p className="text-neutral-400 text-lg">No posts yet.</p>
|
||||
)}
|
||||
|
||||
{!loading && !error && posts?.map((post) => (
|
||||
<PostCard key={post.id} post={post} />
|
||||
))}
|
||||
|
||||
{!loading && totalPages > 1 && (
|
||||
<div className="flex items-center justify-center gap-4 mt-24">
|
||||
<Button
|
||||
onClick={() => setPage((p) => Math.max(1, p - 1))}
|
||||
disabled={page === 1}
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
Previous
|
||||
</Button>
|
||||
<span className="text-sm tracking-widest uppercase text-neutral-500">
|
||||
{page} / {totalPages}
|
||||
</span>
|
||||
<Button
|
||||
onClick={() => setPage((p) => Math.min(totalPages, p + 1))}
|
||||
disabled={page === totalPages}
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
Next
|
||||
</Button>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
92
src/app/posts/[id]/page.tsx
Normal file
92
src/app/posts/[id]/page.tsx
Normal file
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect, use } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import Image from "next/image";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
import { PostContent } from "@/components/post/PostContent";
|
||||
import { PostMeta } from "@/components/post/PostMeta";
|
||||
import { Skeleton } from "@/components/ui/Skeleton";
|
||||
import { TextLink } from "@/components/ui/TextLink";
|
||||
import { api } from "@/lib/api";
|
||||
import type { Post } from "@/types/api";
|
||||
|
||||
interface PostPageProps {
|
||||
params: Promise<{ id: string }>;
|
||||
}
|
||||
|
||||
export default function PostPage({ params }: PostPageProps) {
|
||||
const { id } = use(params);
|
||||
const router = useRouter();
|
||||
const [post, setPost] = useState<Post | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchPost() {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await api.getPost(id);
|
||||
setPost(data);
|
||||
} catch {
|
||||
setError(true);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchPost();
|
||||
}, [id]);
|
||||
|
||||
if (error) {
|
||||
router.push("/not-found");
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Container className="py-24">
|
||||
<TextLink href="/" className="text-sm">
|
||||
Back to all posts
|
||||
</TextLink>
|
||||
|
||||
{loading && (
|
||||
<div className="mt-12">
|
||||
<Skeleton className="h-4 w-24" />
|
||||
<Skeleton className="h-16 w-full mt-4" />
|
||||
<Skeleton className="h-16 w-3/4 mt-2" />
|
||||
<Skeleton className="aspect-video w-full mt-12" />
|
||||
<Skeleton className="h-4 w-full mt-12" />
|
||||
<Skeleton className="h-4 w-full mt-2" />
|
||||
<Skeleton className="h-4 w-2/3 mt-2" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!loading && post && (
|
||||
<article className="mt-12">
|
||||
<PostMeta date={post.created_at} />
|
||||
|
||||
<h1 className="text-5xl md:text-7xl font-bold tracking-tighter mt-4 leading-tight">
|
||||
{post.title}
|
||||
</h1>
|
||||
|
||||
{post.cover_image && (
|
||||
<div className="aspect-video overflow-hidden mt-12 bg-neutral-100">
|
||||
<Image
|
||||
src={post.cover_image}
|
||||
alt={post.title}
|
||||
width={1200}
|
||||
height={675}
|
||||
className="w-full h-full object-cover"
|
||||
priority
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-12 max-w-3xl">
|
||||
<PostContent content={post.content} />
|
||||
</div>
|
||||
</article>
|
||||
)}
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
35
src/components/auth/ProtectedRoute.tsx
Normal file
35
src/components/auth/ProtectedRoute.tsx
Normal file
@@ -0,0 +1,35 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, type ReactNode } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useAuth } from "@/lib/hooks/useAuth";
|
||||
import { Container } from "@/components/layout/Container";
|
||||
|
||||
interface ProtectedRouteProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ProtectedRoute({ children }: ProtectedRouteProps) {
|
||||
const router = useRouter();
|
||||
const { isAuthenticated, loading } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (!loading && !isAuthenticated) {
|
||||
router.push("/login");
|
||||
}
|
||||
}, [isAuthenticated, loading, router]);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Container className="py-24 min-h-[60vh] flex items-center justify-center">
|
||||
<p className="text-neutral-400">Loading...</p>
|
||||
</Container>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <>{children}</>;
|
||||
}
|
||||
119
src/components/editor/ImageUpload.tsx
Normal file
119
src/components/editor/ImageUpload.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useRef, type DragEvent, type ChangeEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { api } from "@/lib/api";
|
||||
|
||||
interface ImageUploadProps {
|
||||
onUpload: (url: string) => void;
|
||||
}
|
||||
|
||||
const ACCEPTED_TYPES = ["image/jpeg", "image/png", "image/webp"];
|
||||
const MAX_SIZE = 5 * 1024 * 1024; // 5MB
|
||||
|
||||
export function ImageUpload({ onUpload }: ImageUploadProps) {
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const inputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const validateFile = (file: File): string | null => {
|
||||
if (!ACCEPTED_TYPES.includes(file.type)) {
|
||||
return "Only JPG, PNG, and WebP files are allowed.";
|
||||
}
|
||||
if (file.size > MAX_SIZE) {
|
||||
return "File size must be under 5MB.";
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
const uploadFile = async (file: File) => {
|
||||
const validationError = validateFile(file);
|
||||
if (validationError) {
|
||||
setError(validationError);
|
||||
setTimeout(() => setError(null), 3000);
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
setUploading(true);
|
||||
|
||||
try {
|
||||
const response = await api.uploadImage(file);
|
||||
onUpload(response.url);
|
||||
} catch {
|
||||
setError("Upload failed. Please try again.");
|
||||
setTimeout(() => setError(null), 3000);
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDragOver = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(true);
|
||||
};
|
||||
|
||||
const handleDragLeave = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
};
|
||||
|
||||
const handleDrop = (e: DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragging(false);
|
||||
|
||||
const file = e.dataTransfer.files[0];
|
||||
if (file) {
|
||||
uploadFile(file);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) {
|
||||
uploadFile(file);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClick = () => {
|
||||
inputRef.current?.click();
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
onClick={handleClick}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
className={clsx(
|
||||
"border-2 border-dashed p-8 text-center cursor-pointer transition-colors",
|
||||
isDragging && "border-black bg-neutral-50",
|
||||
error && "border-red-500 animate-shake",
|
||||
!isDragging && !error && "border-neutral-300 hover:border-neutral-400"
|
||||
)}
|
||||
>
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept={ACCEPTED_TYPES.join(",")}
|
||||
onChange={handleChange}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
{uploading ? (
|
||||
<p className="text-sm text-neutral-500">Uploading...</p>
|
||||
) : error ? (
|
||||
<p className="text-sm text-red-500">{error}</p>
|
||||
) : (
|
||||
<p className="text-sm text-neutral-500">
|
||||
Drop an image here or click to upload
|
||||
</p>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-neutral-400 mt-2">
|
||||
JPG, PNG, WebP up to 5MB
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
28
src/components/editor/MarkdownEditor.tsx
Normal file
28
src/components/editor/MarkdownEditor.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
"use client";
|
||||
|
||||
import { type ChangeEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface MarkdownEditorProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function MarkdownEditor({ value, onChange, className }: MarkdownEditorProps) {
|
||||
const handleChange = (e: ChangeEvent<HTMLTextAreaElement>) => {
|
||||
onChange(e.target.value);
|
||||
};
|
||||
|
||||
return (
|
||||
<textarea
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
placeholder="Write your content in Markdown..."
|
||||
className={clsx(
|
||||
"w-full h-full resize-none bg-transparent font-mono text-sm leading-relaxed focus:outline-none placeholder:text-neutral-400",
|
||||
className
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
15
src/components/layout/Container.tsx
Normal file
15
src/components/layout/Container.tsx
Normal file
@@ -0,0 +1,15 @@
|
||||
import { type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface ContainerProps {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Container({ children, className }: ContainerProps) {
|
||||
return (
|
||||
<div className={clsx("max-w-screen-xl mx-auto px-6", className)}>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
13
src/components/layout/Footer.tsx
Normal file
13
src/components/layout/Footer.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import { Container } from "./Container";
|
||||
|
||||
export function Footer() {
|
||||
return (
|
||||
<footer className="py-12 border-t border-neutral-100 mt-24">
|
||||
<Container>
|
||||
<p className="text-sm text-neutral-400 tracking-wide">
|
||||
{new Date().getFullYear()}
|
||||
</p>
|
||||
</Container>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
51
src/components/layout/Header.tsx
Normal file
51
src/components/layout/Header.tsx
Normal file
@@ -0,0 +1,51 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
import Link from "next/link";
|
||||
import { Container } from "./Container";
|
||||
import { TextLink } from "@/components/ui/TextLink";
|
||||
import { useAuth } from "@/lib/hooks/useAuth";
|
||||
|
||||
export function Header() {
|
||||
const { isAuthenticated, logout } = useAuth();
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<header className="py-8 border-b border-neutral-100">
|
||||
<Container>
|
||||
<nav className="flex items-center justify-between">
|
||||
<Link
|
||||
href="/"
|
||||
className="text-xl font-bold tracking-tighter hover:opacity-70 transition-opacity"
|
||||
>
|
||||
AI Blog
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center gap-8">
|
||||
{mounted && (
|
||||
<>
|
||||
{isAuthenticated ? (
|
||||
<>
|
||||
<TextLink href="/admin">Dashboard</TextLink>
|
||||
<button
|
||||
onClick={logout}
|
||||
className="text-sm tracking-wide uppercase text-neutral-500 hover:text-black transition-colors"
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<TextLink href="/login">Login</TextLink>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</nav>
|
||||
</Container>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
58
src/components/post/PostCard.tsx
Normal file
58
src/components/post/PostCard.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import Link from "next/link";
|
||||
import Image from "next/image";
|
||||
import { PostMeta } from "./PostMeta";
|
||||
import type { Post } from "@/types/api";
|
||||
|
||||
interface PostCardProps {
|
||||
post: Post;
|
||||
}
|
||||
|
||||
export function PostCard({ post }: PostCardProps) {
|
||||
return (
|
||||
<article className="grid grid-cols-12 gap-6 md:gap-12 mb-24">
|
||||
{post.cover_image && (
|
||||
<div className="col-span-12 md:col-span-5">
|
||||
<Link href={`/posts/${post.id}`}>
|
||||
<div className="aspect-[3/2] overflow-hidden bg-neutral-100">
|
||||
<Image
|
||||
src={post.cover_image}
|
||||
alt={post.title}
|
||||
width={600}
|
||||
height={400}
|
||||
className="w-full h-full object-cover hover:scale-105 transition-transform duration-500"
|
||||
/>
|
||||
</div>
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
className={
|
||||
post.cover_image
|
||||
? "col-span-12 md:col-span-7 flex flex-col justify-center"
|
||||
: "col-span-12 flex flex-col justify-center"
|
||||
}
|
||||
>
|
||||
<PostMeta date={post.created_at} />
|
||||
|
||||
<Link href={`/posts/${post.id}`}>
|
||||
<h2 className="text-3xl md:text-5xl font-bold tracking-tighter mt-4 hover:opacity-70 transition-opacity leading-tight">
|
||||
{post.title}
|
||||
</h2>
|
||||
</Link>
|
||||
|
||||
<p className="text-neutral-600 mt-6 leading-relaxed line-clamp-3">
|
||||
{post.content.slice(0, 200).replace(/[#*`]/g, "")}
|
||||
{post.content.length > 200 ? "..." : ""}
|
||||
</p>
|
||||
|
||||
<Link
|
||||
href={`/posts/${post.id}`}
|
||||
className="mt-6 text-sm font-bold tracking-widest uppercase border-b border-black pb-0.5 hover:border-transparent transition-colors self-start"
|
||||
>
|
||||
Read More
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
21
src/components/post/PostCardSkeleton.tsx
Normal file
21
src/components/post/PostCardSkeleton.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
import { Skeleton } from "@/components/ui/Skeleton";
|
||||
|
||||
export function PostCardSkeleton() {
|
||||
return (
|
||||
<article className="grid grid-cols-12 gap-6 md:gap-12 mb-24">
|
||||
<div className="col-span-12 md:col-span-5">
|
||||
<Skeleton className="aspect-[3/2]" />
|
||||
</div>
|
||||
|
||||
<div className="col-span-12 md:col-span-7 flex flex-col justify-center">
|
||||
<Skeleton className="h-3 w-24" />
|
||||
<Skeleton className="h-12 w-full mt-4" />
|
||||
<Skeleton className="h-12 w-3/4 mt-2" />
|
||||
<Skeleton className="h-4 w-full mt-6" />
|
||||
<Skeleton className="h-4 w-full mt-2" />
|
||||
<Skeleton className="h-4 w-2/3 mt-2" />
|
||||
<Skeleton className="h-4 w-20 mt-6" />
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
52
src/components/post/PostContent.tsx
Normal file
52
src/components/post/PostContent.tsx
Normal file
@@ -0,0 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import ReactMarkdown from "react-markdown";
|
||||
import rehypeHighlight from "rehype-highlight";
|
||||
import remarkGfm from "remark-gfm";
|
||||
|
||||
interface PostContentProps {
|
||||
content: string;
|
||||
}
|
||||
|
||||
export function PostContent({ content }: PostContentProps) {
|
||||
return (
|
||||
<div className="prose prose-lg max-w-none prose-headings:tracking-tight prose-headings:font-bold prose-p:leading-relaxed prose-p:text-neutral-700 prose-a:border-b prose-a:border-black prose-a:no-underline hover:prose-a:border-transparent prose-img:my-8 prose-pre:bg-[#f6f8fa] prose-pre:p-6 prose-code:font-mono prose-code:text-base">
|
||||
<ReactMarkdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
rehypePlugins={[rehypeHighlight]}
|
||||
components={{
|
||||
img: ({ src, alt }) => (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img
|
||||
src={src}
|
||||
alt={alt || ""}
|
||||
className="w-full aspect-video object-cover my-8"
|
||||
/>
|
||||
),
|
||||
pre: ({ children }) => (
|
||||
<pre className="bg-[#f6f8fa] p-6 font-mono text-base overflow-x-auto text-black rounded-none border border-neutral-200">
|
||||
{children}
|
||||
</pre>
|
||||
),
|
||||
code: ({ className, children, ...props }) => {
|
||||
const isInline = !className;
|
||||
if (isInline) {
|
||||
return (
|
||||
<code className="bg-neutral-100 px-1.5 py-0.5 font-mono text-base text-black" {...props}>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<code className={className} {...props}>
|
||||
{children}
|
||||
</code>
|
||||
);
|
||||
},
|
||||
}}
|
||||
>
|
||||
{content}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
21
src/components/post/PostMeta.tsx
Normal file
21
src/components/post/PostMeta.tsx
Normal file
@@ -0,0 +1,21 @@
|
||||
interface PostMetaProps {
|
||||
date?: string;
|
||||
}
|
||||
|
||||
export function PostMeta({ date }: PostMetaProps) {
|
||||
const formatDate = (dateString?: string) => {
|
||||
if (!dateString) return "";
|
||||
const d = new Date(dateString);
|
||||
return d.toLocaleDateString("en-US", {
|
||||
year: "numeric",
|
||||
month: "long",
|
||||
day: "numeric",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<time className="text-xs font-bold tracking-widest uppercase text-neutral-400">
|
||||
{formatDate(date)}
|
||||
</time>
|
||||
);
|
||||
}
|
||||
42
src/components/ui/Button.tsx
Normal file
42
src/components/ui/Button.tsx
Normal file
@@ -0,0 +1,42 @@
|
||||
import { type ButtonHTMLAttributes, type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
|
||||
children: ReactNode;
|
||||
variant?: "ghost" | "solid";
|
||||
size?: "sm" | "md" | "lg";
|
||||
}
|
||||
|
||||
export function Button({
|
||||
children,
|
||||
variant = "ghost",
|
||||
size = "md",
|
||||
className,
|
||||
disabled,
|
||||
...props
|
||||
}: ButtonProps) {
|
||||
return (
|
||||
<button
|
||||
className={clsx(
|
||||
"font-medium tracking-wide uppercase transition-all duration-200",
|
||||
{
|
||||
"border border-black hover:bg-black hover:text-white": variant === "ghost",
|
||||
"bg-black text-white hover:bg-neutral-800": variant === "solid",
|
||||
},
|
||||
{
|
||||
"px-4 py-2 text-xs": size === "sm",
|
||||
"px-6 py-3 text-sm": size === "md",
|
||||
"px-8 py-4 text-sm": size === "lg",
|
||||
},
|
||||
{
|
||||
"opacity-50 cursor-not-allowed": disabled,
|
||||
},
|
||||
className
|
||||
)}
|
||||
disabled={disabled}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
37
src/components/ui/Input.tsx
Normal file
37
src/components/ui/Input.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { type InputHTMLAttributes, forwardRef } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
|
||||
label?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export const Input = forwardRef<HTMLInputElement, InputProps>(
|
||||
({ label, error, className, ...props }, ref) => {
|
||||
return (
|
||||
<div className="w-full">
|
||||
{label && (
|
||||
<label className="block text-xs font-bold tracking-widest uppercase text-neutral-500 mb-2">
|
||||
{label}
|
||||
</label>
|
||||
)}
|
||||
<input
|
||||
ref={ref}
|
||||
className={clsx(
|
||||
"w-full border-b py-3 bg-transparent text-black placeholder:text-neutral-400 focus:outline-none transition-colors",
|
||||
error
|
||||
? "border-red-500 animate-shake"
|
||||
: "border-neutral-200 focus:border-black",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
{error && (
|
||||
<p className="mt-2 text-xs text-red-500">{error}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
Input.displayName = "Input";
|
||||
13
src/components/ui/Skeleton.tsx
Normal file
13
src/components/ui/Skeleton.tsx
Normal file
@@ -0,0 +1,13 @@
|
||||
import clsx from "clsx";
|
||||
|
||||
interface SkeletonProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Skeleton({ className }: SkeletonProps) {
|
||||
return (
|
||||
<div
|
||||
className={clsx("animate-pulse bg-neutral-200", className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
20
src/components/ui/Tag.tsx
Normal file
20
src/components/ui/Tag.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface TagProps {
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function Tag({ children, className }: TagProps) {
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
"text-xs font-bold tracking-widest uppercase border border-black px-2 py-1",
|
||||
className
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
33
src/components/ui/TextLink.tsx
Normal file
33
src/components/ui/TextLink.tsx
Normal file
@@ -0,0 +1,33 @@
|
||||
import Link from "next/link";
|
||||
import { type ReactNode } from "react";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface TextLinkProps {
|
||||
href: string;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
external?: boolean;
|
||||
}
|
||||
|
||||
export function TextLink({ href, children, className, external }: TextLinkProps) {
|
||||
const baseStyles = "border-b border-black pb-0.5 hover:border-transparent transition-colors";
|
||||
|
||||
if (external) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={clsx(baseStyles, className)}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Link href={href} className={clsx(baseStyles, className)}>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
177
src/lib/api.ts
Normal file
177
src/lib/api.ts
Normal file
@@ -0,0 +1,177 @@
|
||||
import type {
|
||||
AuthResponse,
|
||||
LoginRequest,
|
||||
RegisterRequest,
|
||||
Post,
|
||||
PostsResponse,
|
||||
UploadResponse,
|
||||
} from "@/types/api";
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_URL || "http://127.0.0.1:8765";
|
||||
|
||||
class ApiClient {
|
||||
private static instance: ApiClient;
|
||||
private token: string | null = null;
|
||||
|
||||
private constructor() {
|
||||
if (typeof window !== "undefined") {
|
||||
this.token = localStorage.getItem("auth_token");
|
||||
}
|
||||
}
|
||||
|
||||
static getInstance(): ApiClient {
|
||||
if (!ApiClient.instance) {
|
||||
ApiClient.instance = new ApiClient();
|
||||
}
|
||||
return ApiClient.instance;
|
||||
}
|
||||
|
||||
setToken(token: string | null) {
|
||||
this.token = token;
|
||||
if (typeof window !== "undefined") {
|
||||
if (token) {
|
||||
localStorage.setItem("auth_token", token);
|
||||
} else {
|
||||
localStorage.removeItem("auth_token");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getToken(): string | null {
|
||||
return this.token;
|
||||
}
|
||||
|
||||
private async request<T>(
|
||||
endpoint: string,
|
||||
options: RequestInit = {}
|
||||
): Promise<T> {
|
||||
const headers: HeadersInit = {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
if (this.token) {
|
||||
(headers as Record<string, string>)["Authorization"] = `Bearer ${this.token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}${endpoint}`, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
this.setToken(null);
|
||||
if (typeof window !== "undefined") {
|
||||
window.location.href = "/login";
|
||||
}
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json().catch(() => ({ message: "Request failed" }));
|
||||
throw new Error(error.message || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
async login(data: LoginRequest): Promise<AuthResponse> {
|
||||
const response = await this.request<AuthResponse>("/api/auth/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
this.setToken(response.token);
|
||||
return response;
|
||||
}
|
||||
|
||||
async register(data: RegisterRequest): Promise<AuthResponse> {
|
||||
const response = await this.request<AuthResponse>("/api/auth/register", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
this.setToken(response.token);
|
||||
return response;
|
||||
}
|
||||
|
||||
async logout(): Promise<void> {
|
||||
this.setToken(null);
|
||||
}
|
||||
|
||||
async getPosts(page = 1, limit = 10): Promise<PostsResponse> {
|
||||
const response = await this.request<any>(`/api/posts?page=${page}&limit=${limit}`);
|
||||
|
||||
// Handle response with 'data' field (backend format)
|
||||
if (response.data && Array.isArray(response.data)) {
|
||||
return {
|
||||
posts: response.data,
|
||||
total: response.total || response.data.length,
|
||||
page: response.page || page,
|
||||
limit: response.limit || limit,
|
||||
};
|
||||
}
|
||||
|
||||
// Handle array response
|
||||
if (Array.isArray(response)) {
|
||||
return {
|
||||
posts: response,
|
||||
total: response.length,
|
||||
page,
|
||||
limit,
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
async getPost(id: string): Promise<Post> {
|
||||
return this.request<Post>(`/api/posts/${id}`);
|
||||
}
|
||||
|
||||
async getMyPosts(): Promise<Post[]> {
|
||||
return this.request<Post[]>("/api/posts/me");
|
||||
}
|
||||
|
||||
async createPost(data: Partial<Post>): Promise<Post> {
|
||||
return this.request<Post>("/api/posts", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
async updatePost(id: string, data: Partial<Post>): Promise<Post> {
|
||||
return this.request<Post>(`/api/posts/${id}`, {
|
||||
method: "PUT",
|
||||
body: JSON.stringify(data),
|
||||
});
|
||||
}
|
||||
|
||||
async deletePost(id: string): Promise<void> {
|
||||
await this.request<void>(`/api/posts/${id}`, {
|
||||
method: "DELETE",
|
||||
});
|
||||
}
|
||||
|
||||
async uploadImage(file: File): Promise<UploadResponse> {
|
||||
const formData = new FormData();
|
||||
formData.append("file", file);
|
||||
|
||||
const headers: HeadersInit = {};
|
||||
if (this.token) {
|
||||
headers["Authorization"] = `Bearer ${this.token}`;
|
||||
}
|
||||
|
||||
const response = await fetch(`${API_BASE}/api/upload`, {
|
||||
method: "POST",
|
||||
headers,
|
||||
body: formData,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Upload failed");
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
}
|
||||
|
||||
export const api = ApiClient.getInstance();
|
||||
76
src/lib/auth-context.tsx
Normal file
76
src/lib/auth-context.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useState,
|
||||
useEffect,
|
||||
useCallback,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { api } from "./api";
|
||||
import type { User, LoginRequest, RegisterRequest } from "@/types/api";
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
loading: boolean;
|
||||
login: (data: LoginRequest) => Promise<void>;
|
||||
register: (data: RegisterRequest) => Promise<void>;
|
||||
logout: () => void;
|
||||
isAuthenticated: boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = api.getToken();
|
||||
if (token) {
|
||||
// Token exists, user is authenticated
|
||||
// In a real app, you might validate the token or fetch user data
|
||||
setUser({ id: "", email: "" });
|
||||
}
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const login = useCallback(async (data: LoginRequest) => {
|
||||
const response = await api.login(data);
|
||||
setUser(response.user);
|
||||
}, []);
|
||||
|
||||
const register = useCallback(async (data: RegisterRequest) => {
|
||||
const response = await api.register(data);
|
||||
setUser(response.user);
|
||||
}, []);
|
||||
|
||||
const logout = useCallback(() => {
|
||||
api.logout();
|
||||
setUser(null);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{
|
||||
user,
|
||||
loading,
|
||||
login,
|
||||
register,
|
||||
logout,
|
||||
isAuthenticated: !!user || !!api.getToken(),
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("useAuth must be used within an AuthProvider");
|
||||
}
|
||||
return context;
|
||||
}
|
||||
1
src/lib/hooks/useAuth.ts
Normal file
1
src/lib/hooks/useAuth.ts
Normal file
@@ -0,0 +1 @@
|
||||
export { useAuth } from "../auth-context";
|
||||
49
src/types/api.ts
Normal file
49
src/types/api.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
export interface User {
|
||||
id: string;
|
||||
email: string;
|
||||
}
|
||||
|
||||
export interface AuthResponse {
|
||||
token: string;
|
||||
user: User;
|
||||
}
|
||||
|
||||
export interface LoginRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface RegisterRequest {
|
||||
email: string;
|
||||
password: string;
|
||||
}
|
||||
|
||||
export interface Post {
|
||||
id: string;
|
||||
title: string;
|
||||
content: string;
|
||||
published: boolean;
|
||||
created_at?: string;
|
||||
cover_image?: string;
|
||||
}
|
||||
|
||||
export interface PostsResponse {
|
||||
posts: Post[];
|
||||
total: number;
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface PageParams {
|
||||
page: number;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export interface UploadResponse {
|
||||
url: string;
|
||||
}
|
||||
|
||||
export interface ApiError {
|
||||
message: string;
|
||||
status: number;
|
||||
}
|
||||
Reference in New Issue
Block a user