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(
|
||||
request: Request,
|
||||
{ params }: { params: { slug: string } }
|
||||
{ params }: { params: { slug: string[] | string } }
|
||||
) {
|
||||
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);
|
||||
} 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;
|
||||
}
|
||||
|
||||
async function getPostBySlug(slug: string) {
|
||||
const realSlug = slug.replace(/\.md$/, '');
|
||||
const fullPath = path.join(postsDirectory, `${realSlug}.md`);
|
||||
const fileContents = fs.readFileSync(fullPath, 'utf8');
|
||||
async function getPostByPath(filePath: string, relPath: string) {
|
||||
const fileContents = fs.readFileSync(filePath, 'utf8');
|
||||
const { data, content } = matter(fileContents);
|
||||
const createdAt = getFileCreationDate(fullPath);
|
||||
|
||||
const processedContent = await remark()
|
||||
.use(html)
|
||||
.process(content);
|
||||
|
||||
const createdAt = getFileCreationDate(filePath);
|
||||
const processedContent = await remark().use(html).process(content);
|
||||
return {
|
||||
slug: realSlug,
|
||||
type: 'post',
|
||||
slug: relPath.replace(/\.md$/, ''),
|
||||
title: data.title,
|
||||
date: data.date,
|
||||
tags: data.tags || [],
|
||||
@@ -35,27 +30,31 @@ async function getPostBySlug(slug: string) {
|
||||
};
|
||||
}
|
||||
|
||||
async function getAllPosts() {
|
||||
const fileNames = fs.readdirSync(postsDirectory);
|
||||
const allPostsData = await Promise.all(
|
||||
fileNames
|
||||
.filter((fileName) => fileName.endsWith('.md'))
|
||||
.map(async (fileName) => {
|
||||
const slug = fileName.replace(/\.md$/, '');
|
||||
return getPostBySlug(slug);
|
||||
})
|
||||
);
|
||||
|
||||
return allPostsData.sort((a, b) =>
|
||||
new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
|
||||
);
|
||||
async function readPostsDir(dir: string, relDir = ''): Promise<any[]> {
|
||||
const entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
const folders: any[] = [];
|
||||
const posts: any[] = [];
|
||||
for (const entry of entries) {
|
||||
const fullPath = path.join(dir, entry.name);
|
||||
const relPath = relDir ? path.join(relDir, entry.name) : entry.name;
|
||||
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')) {
|
||||
posts.push(await getPostByPath(fullPath, relPath));
|
||||
}
|
||||
}
|
||||
// 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() {
|
||||
try {
|
||||
const posts = await getAllPosts();
|
||||
return NextResponse.json(posts);
|
||||
const tree = await readPostsDir(postsDirectory);
|
||||
return NextResponse.json(tree);
|
||||
} 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';
|
||||
|
||||
interface Post {
|
||||
type: 'post';
|
||||
slug: string;
|
||||
title: string;
|
||||
date: string;
|
||||
@@ -14,35 +15,92 @@ interface Post {
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface Folder {
|
||||
type: 'folder';
|
||||
name: string;
|
||||
path: string;
|
||||
children: (Folder | Post)[];
|
||||
}
|
||||
|
||||
type Node = Folder | Post;
|
||||
|
||||
export default function Home() {
|
||||
const [posts, setPosts] = useState<Post[]>([]);
|
||||
const [tree, setTree] = useState<Node[]>([]);
|
||||
const [currentPath, setCurrentPath] = useState<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
// Initial load
|
||||
loadPosts();
|
||||
|
||||
// Set up polling for changes
|
||||
const interval = setInterval(loadPosts, 2000);
|
||||
|
||||
// Cleanup
|
||||
loadTree();
|
||||
const interval = setInterval(loadTree, 2000);
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
const loadPosts = async () => {
|
||||
const loadTree = async () => {
|
||||
try {
|
||||
const response = await fetch('/api/posts');
|
||||
const data = await response.json();
|
||||
setPosts(data);
|
||||
setTree(data);
|
||||
} catch (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 (
|
||||
<main className="min-h-screen p-8 max-w-4xl mx-auto">
|
||||
<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">
|
||||
{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">
|
||||
<Link href={`/posts/${post.slug}`}>
|
||||
<h2 className="text-2xl font-semibold mb-2">{post.title}</h2>
|
||||
@@ -52,7 +110,7 @@ export default function Home() {
|
||||
</div>
|
||||
<p className="text-gray-700 mb-4">{post.summary}</p>
|
||||
<div className="flex gap-2">
|
||||
{post.tags.map((tag) => (
|
||||
{post.tags.map((tag: string) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="bg-gray-100 text-gray-800 px-3 py-1 rounded-full text-sm"
|
||||
|
||||
@@ -14,9 +14,12 @@ interface Post {
|
||||
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);
|
||||
|
||||
// Join the slug array to get the full path
|
||||
const slugPath = Array.isArray(params.slug) ? params.slug.join('/') : params.slug;
|
||||
|
||||
useEffect(() => {
|
||||
// Initial load
|
||||
loadPost();
|
||||
@@ -26,11 +29,11 @@ export default function PostPage({ params }: { params: { slug: string } }) {
|
||||
|
||||
// Cleanup
|
||||
return () => clearInterval(interval);
|
||||
}, [params.slug]);
|
||||
}, [slugPath]);
|
||||
|
||||
const loadPost = async () => {
|
||||
try {
|
||||
const response = await fetch(`/api/posts/${params.slug}`);
|
||||
const response = await fetch(`/api/posts/${encodeURIComponent(slugPath)}`);
|
||||
const data = await response.json();
|
||||
setPost(data);
|
||||
} catch (error) {
|
||||
Reference in New Issue
Block a user