folder support
This commit is contained in:
10
posts/folder/folder.md
Normal file
10
posts/folder/folder.md
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
title: "Testing Folders"
|
||||||
|
date: "2024-03-10"
|
||||||
|
tags: ["test", "feature"]
|
||||||
|
summary: "A test post to demonstrate folders"
|
||||||
|
---
|
||||||
|
|
||||||
|
# Folders
|
||||||
|
|
||||||
|
i hate TS
|
||||||
@@ -37,12 +37,15 @@ async function getPostBySlug(slug: string) {
|
|||||||
|
|
||||||
export async function GET(
|
export async function GET(
|
||||||
request: Request,
|
request: Request,
|
||||||
{ params }: { params: { slug: string } }
|
{ params }: { params: { slug: string[] | string } }
|
||||||
) {
|
) {
|
||||||
try {
|
try {
|
||||||
const post = await getPostBySlug(params.slug);
|
// Support catch-all route: slug can be string or string[]
|
||||||
|
const slugArr = Array.isArray(params.slug) ? params.slug : [params.slug];
|
||||||
|
const slugPath = slugArr.join('/');
|
||||||
|
const post = await getPostBySlug(slugPath);
|
||||||
return NextResponse.json(post);
|
return NextResponse.json(post);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return NextResponse.json({ error: 'Failed to fetch post' }, { status: 500 });
|
return NextResponse.json({ error: 'Fehler beim Laden des Beitrags' }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -13,19 +13,14 @@ function getFileCreationDate(filePath: string): Date {
|
|||||||
return stats.birthtime;
|
return stats.birthtime;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getPostBySlug(slug: string) {
|
async function getPostByPath(filePath: string, relPath: string) {
|
||||||
const realSlug = slug.replace(/\.md$/, '');
|
const fileContents = fs.readFileSync(filePath, 'utf8');
|
||||||
const fullPath = path.join(postsDirectory, `${realSlug}.md`);
|
|
||||||
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
|
||||||
const { data, content } = matter(fileContents);
|
const { data, content } = matter(fileContents);
|
||||||
const createdAt = getFileCreationDate(fullPath);
|
const createdAt = getFileCreationDate(filePath);
|
||||||
|
const processedContent = await remark().use(html).process(content);
|
||||||
const processedContent = await remark()
|
|
||||||
.use(html)
|
|
||||||
.process(content);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
slug: realSlug,
|
type: 'post',
|
||||||
|
slug: relPath.replace(/\.md$/, ''),
|
||||||
title: data.title,
|
title: data.title,
|
||||||
date: data.date,
|
date: data.date,
|
||||||
tags: data.tags || [],
|
tags: data.tags || [],
|
||||||
@@ -35,27 +30,31 @@ async function getPostBySlug(slug: string) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function getAllPosts() {
|
async function readPostsDir(dir: string, relDir = ''): Promise<any[]> {
|
||||||
const fileNames = fs.readdirSync(postsDirectory);
|
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||||
const allPostsData = await Promise.all(
|
const folders: any[] = [];
|
||||||
fileNames
|
const posts: any[] = [];
|
||||||
.filter((fileName) => fileName.endsWith('.md'))
|
for (const entry of entries) {
|
||||||
.map(async (fileName) => {
|
const fullPath = path.join(dir, entry.name);
|
||||||
const slug = fileName.replace(/\.md$/, '');
|
const relPath = relDir ? path.join(relDir, entry.name) : entry.name;
|
||||||
return getPostBySlug(slug);
|
if (entry.isDirectory()) {
|
||||||
})
|
const children = await readPostsDir(fullPath, relPath);
|
||||||
);
|
folders.push({ type: 'folder', name: entry.name, path: relPath, children });
|
||||||
|
} else if (entry.isFile() && entry.name.endsWith('.md')) {
|
||||||
return allPostsData.sort((a, b) =>
|
posts.push(await getPostByPath(fullPath, relPath));
|
||||||
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
}
|
||||||
);
|
}
|
||||||
|
// Sort posts by creation date (newest first)
|
||||||
|
posts.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||||
|
// Folders first, then posts
|
||||||
|
return [...folders, ...posts];
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
try {
|
try {
|
||||||
const posts = await getAllPosts();
|
const tree = await readPostsDir(postsDirectory);
|
||||||
return NextResponse.json(posts);
|
return NextResponse.json(tree);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return NextResponse.json({ error: 'Failed to fetch posts' }, { status: 500 });
|
return NextResponse.json({ error: 'Fehler beim Laden der Beiträge' }, { status: 500 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import Link from 'next/link';
|
|||||||
import { format } from 'date-fns';
|
import { format } from 'date-fns';
|
||||||
|
|
||||||
interface Post {
|
interface Post {
|
||||||
|
type: 'post';
|
||||||
slug: string;
|
slug: string;
|
||||||
title: string;
|
title: string;
|
||||||
date: string;
|
date: string;
|
||||||
@@ -14,35 +15,92 @@ interface Post {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface Folder {
|
||||||
|
type: 'folder';
|
||||||
|
name: string;
|
||||||
|
path: string;
|
||||||
|
children: (Folder | Post)[];
|
||||||
|
}
|
||||||
|
|
||||||
|
type Node = Folder | Post;
|
||||||
|
|
||||||
export default function Home() {
|
export default function Home() {
|
||||||
const [posts, setPosts] = useState<Post[]>([]);
|
const [tree, setTree] = useState<Node[]>([]);
|
||||||
|
const [currentPath, setCurrentPath] = useState<string[]>([]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Initial load
|
loadTree();
|
||||||
loadPosts();
|
const interval = setInterval(loadTree, 2000);
|
||||||
|
|
||||||
// Set up polling for changes
|
|
||||||
const interval = setInterval(loadPosts, 2000);
|
|
||||||
|
|
||||||
// Cleanup
|
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const loadPosts = async () => {
|
const loadTree = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/posts');
|
const response = await fetch('/api/posts');
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setPosts(data);
|
setTree(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Fehler beim Laden der Beiträge:', error);
|
console.error('Fehler beim Laden der Beiträge:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Traverse the tree to the current path
|
||||||
|
const getCurrentNodes = (): Node[] => {
|
||||||
|
let nodes: Node[] = tree;
|
||||||
|
for (const segment of currentPath) {
|
||||||
|
const folder = nodes.find(
|
||||||
|
(n) => n.type === 'folder' && n.name === segment
|
||||||
|
) as Folder | undefined;
|
||||||
|
if (folder) {
|
||||||
|
nodes = folder.children;
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nodes;
|
||||||
|
};
|
||||||
|
|
||||||
|
const nodes = getCurrentNodes();
|
||||||
|
|
||||||
|
// Breadcrumbs
|
||||||
|
const breadcrumbs = [
|
||||||
|
{ name: 'Startseite', path: [] },
|
||||||
|
...currentPath.map((name, idx) => ({
|
||||||
|
name,
|
||||||
|
path: currentPath.slice(0, idx + 1),
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="min-h-screen p-8 max-w-4xl mx-auto">
|
<main className="min-h-screen p-8 max-w-4xl mx-auto">
|
||||||
<h1 className="text-4xl font-bold mb-8">Sebastian Zinkls - Blog</h1>
|
<h1 className="text-4xl font-bold mb-8">Sebastian Zinkls - Blog</h1>
|
||||||
|
<nav className="mb-6 text-sm text-gray-600 flex gap-2 items-center">
|
||||||
|
{breadcrumbs.map((bc, idx) => (
|
||||||
|
<span key={bc.path.join('/') + idx}>
|
||||||
|
{idx > 0 && <span className="mx-1">/</span>}
|
||||||
|
<button
|
||||||
|
className="hover:underline"
|
||||||
|
onClick={() => setCurrentPath(bc.path)}
|
||||||
|
disabled={idx === breadcrumbs.length - 1}
|
||||||
|
>
|
||||||
|
{bc.name}
|
||||||
|
</button>
|
||||||
|
</span>
|
||||||
|
))}
|
||||||
|
</nav>
|
||||||
<div className="grid gap-8">
|
<div className="grid gap-8">
|
||||||
{posts.map((post) => (
|
{/* Folders */}
|
||||||
|
{nodes.filter((n) => n.type === 'folder').map((folder: any) => (
|
||||||
|
<div
|
||||||
|
key={folder.path}
|
||||||
|
className="border rounded-lg p-6 bg-gray-50 cursor-pointer hover:bg-gray-100 transition"
|
||||||
|
onClick={() => setCurrentPath([...currentPath, folder.name])}
|
||||||
|
>
|
||||||
|
<span className="font-semibold text-lg">📁 {folder.name}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{/* Posts */}
|
||||||
|
{nodes.filter((n) => n.type === 'post').map((post: any) => (
|
||||||
<article key={post.slug} className="border rounded-lg p-6 hover:shadow-lg transition-shadow">
|
<article key={post.slug} className="border rounded-lg p-6 hover:shadow-lg transition-shadow">
|
||||||
<Link href={`/posts/${post.slug}`}>
|
<Link href={`/posts/${post.slug}`}>
|
||||||
<h2 className="text-2xl font-semibold mb-2">{post.title}</h2>
|
<h2 className="text-2xl font-semibold mb-2">{post.title}</h2>
|
||||||
@@ -52,7 +110,7 @@ export default function Home() {
|
|||||||
</div>
|
</div>
|
||||||
<p className="text-gray-700 mb-4">{post.summary}</p>
|
<p className="text-gray-700 mb-4">{post.summary}</p>
|
||||||
<div className="flex gap-2">
|
<div className="flex gap-2">
|
||||||
{post.tags.map((tag) => (
|
{post.tags.map((tag: string) => (
|
||||||
<span
|
<span
|
||||||
key={tag}
|
key={tag}
|
||||||
className="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm"
|
className="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm"
|
||||||
|
|||||||
@@ -14,9 +14,12 @@ interface Post {
|
|||||||
createdAt: string;
|
createdAt: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function PostPage({ params }: { params: { slug: string } }) {
|
export default function PostPage({ params }: { params: { slug: string[] } }) {
|
||||||
const [post, setPost] = useState<Post | null>(null);
|
const [post, setPost] = useState<Post | null>(null);
|
||||||
|
|
||||||
|
// Join the slug array to get the full path
|
||||||
|
const slugPath = Array.isArray(params.slug) ? params.slug.join('/') : params.slug;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
// Initial load
|
// Initial load
|
||||||
loadPost();
|
loadPost();
|
||||||
@@ -26,11 +29,11 @@ export default function PostPage({ params }: { params: { slug: string } }) {
|
|||||||
|
|
||||||
// Cleanup
|
// Cleanup
|
||||||
return () => clearInterval(interval);
|
return () => clearInterval(interval);
|
||||||
}, [params.slug]);
|
}, [slugPath]);
|
||||||
|
|
||||||
const loadPost = async () => {
|
const loadPost = async () => {
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`/api/posts/${params.slug}`);
|
const response = await fetch(`/api/posts/${encodeURIComponent(slugPath)}`);
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setPost(data);
|
setPost(data);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
Reference in New Issue
Block a user