refactor(blog): extract blog utilities into shared module
Move common blog functionality like post filtering, sorting and data extraction into a centralized utils module. Replace Astro.glob with import.meta.glob for better performance. Update all blog components and pages to use the new utilities.
This commit is contained in:
@@ -6,48 +6,49 @@ import TagCard from '../../../components/blog/TagCard.astro';
|
||||
import { type Lang } from '@/i18n/utils';
|
||||
import { defaultLang } from '@/i18n/ui';
|
||||
import { type BlogPost } from '@/types';
|
||||
import { filterPostsByCategory, sortPostsByDate, extractCategories, extractTags } from '@/utils/blog-utils';
|
||||
|
||||
// 为动态路由生成静态路径
|
||||
// Generate static paths for dynamic routing
|
||||
export async function getStaticPaths() {
|
||||
const allPosts = await Astro.glob('../posts/*.md');
|
||||
const allPosts = await import.meta.glob('../posts/*.md', { eager: true });
|
||||
|
||||
// 收集所有分类ID或分类
|
||||
// Collect all category IDs or categories
|
||||
const uniqueCategories = new Set<string>();
|
||||
|
||||
allPosts.forEach(post => {
|
||||
// 优先使用 categoryId 作为路由标识符
|
||||
Object.values(allPosts).forEach((post: any) => {
|
||||
// Prioritize categoryId as route identifier
|
||||
if (post.frontmatter?.categoryId) {
|
||||
const categoryIds = Array.isArray(post.frontmatter.categoryId)
|
||||
? post.frontmatter.categoryId
|
||||
: [post.frontmatter.categoryId];
|
||||
|
||||
categoryIds.forEach(categoryId => {
|
||||
categoryIds.forEach((categoryId: string) => {
|
||||
if (categoryId) uniqueCategories.add(categoryId.toLowerCase());
|
||||
});
|
||||
}
|
||||
// 如果没有 categoryId,则使用 category 作为后备
|
||||
// If no categoryId, use category as fallback
|
||||
else if (post.frontmatter?.category) {
|
||||
const categories = Array.isArray(post.frontmatter.category)
|
||||
? post.frontmatter.category
|
||||
: [post.frontmatter.category];
|
||||
|
||||
categories.forEach(category => {
|
||||
categories.forEach((category: string) => {
|
||||
if (category) uniqueCategories.add(category.toLowerCase());
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 为每个分类生成路径
|
||||
// Generate paths for each category
|
||||
return Array.from(uniqueCategories).map(category => ({
|
||||
params: { category: encodeURIComponent(category) },
|
||||
props: { category }
|
||||
}));
|
||||
}
|
||||
|
||||
// 获取当前语言环境
|
||||
// Get current language environment
|
||||
const lang = Astro.currentLocale as Lang || defaultLang;
|
||||
|
||||
// 获取当前分类(从URL参数)
|
||||
// Get current category (from URL parameters)
|
||||
export interface Props {
|
||||
category: string;
|
||||
}
|
||||
@@ -55,129 +56,94 @@ export interface Props {
|
||||
const { category } = Astro.params;
|
||||
const decodedCategory = category ? decodeURIComponent(category) : '';
|
||||
|
||||
// Read all blog posts using import.meta.glob
|
||||
const allPosts = await import.meta.glob('../posts/*.md', { eager: true });
|
||||
|
||||
// 使用Astro.glob读取所有博客文章
|
||||
const allPosts = await Astro.glob('../posts/*.md');
|
||||
|
||||
// 处理博客文章数据
|
||||
const blogPosts: BlogPost[] = allPosts
|
||||
.filter(post => {
|
||||
// 优先检查文章是否包含当前分类ID
|
||||
if (post.frontmatter?.categoryId) {
|
||||
const postCategoryIds = Array.isArray(post.frontmatter.categoryId)
|
||||
? post.frontmatter.categoryId
|
||||
: [post.frontmatter.categoryId];
|
||||
|
||||
return postCategoryIds.some(catId =>
|
||||
catId.toLowerCase() === decodedCategory.toLowerCase()
|
||||
);
|
||||
}
|
||||
// 如果没有 categoryId,则检查 category
|
||||
else if (post.frontmatter?.category) {
|
||||
const postCategories = Array.isArray(post.frontmatter.category)
|
||||
? post.frontmatter.category
|
||||
: [post.frontmatter.category];
|
||||
|
||||
return postCategories.some(cat =>
|
||||
cat.toLowerCase() === decodedCategory.toLowerCase()
|
||||
);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.map((post) => {
|
||||
const slug = post.url?.split('/').filter(Boolean).pop() || '';
|
||||
|
||||
// 获取文章的默认图片,如果frontmatter中没有指定
|
||||
const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
|
||||
|
||||
return {
|
||||
title: post.frontmatter.title,
|
||||
description: post.frontmatter.description || '',
|
||||
image: post.frontmatter.image || defaultImage,
|
||||
slug: slug,
|
||||
tags: post.frontmatter.tags || [],
|
||||
date: post.frontmatter.date || post.frontmatter.pubDate || '',
|
||||
readTime: post.frontmatter.readTime || post.frontmatter.readingTime || '5 min read',
|
||||
};
|
||||
});
|
||||
|
||||
// 按日期排序
|
||||
const sortedBlogPosts = blogPosts
|
||||
.filter(post => post.date) // 过滤掉没有日期的文章
|
||||
.sort((a, b) => {
|
||||
const dateA = new Date(a.date).getTime();
|
||||
const dateB = new Date(b.date).getTime();
|
||||
return dateB - dateA; // 降序排列,最新的文章在前
|
||||
});
|
||||
|
||||
// 从所有博客文章中提取分类和标签(用于侧边栏)
|
||||
const allCategories = new Set<string>();
|
||||
const allTags = new Set<string>();
|
||||
|
||||
// 收集所有文章的分类和标签
|
||||
allPosts.forEach(post => {
|
||||
// 处理分类
|
||||
if (post.frontmatter?.category) {
|
||||
const categories = Array.isArray(post.frontmatter.category)
|
||||
? post.frontmatter.category
|
||||
: [post.frontmatter.category];
|
||||
|
||||
categories.forEach(cat => {
|
||||
if (cat) allCategories.add(cat);
|
||||
});
|
||||
}
|
||||
// Process blog post data
|
||||
const blogPosts: BlogPost[] = Object.values(allPosts).map((post: any) => {
|
||||
const slug = post.url?.split('/').filter(Boolean).pop() || '';
|
||||
|
||||
// 处理标签
|
||||
if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
|
||||
post.frontmatter.tags.forEach(tag => {
|
||||
if (tag) allTags.add(tag);
|
||||
});
|
||||
}
|
||||
// Default image if not specified in frontmatter
|
||||
const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
|
||||
|
||||
return {
|
||||
title: post.frontmatter.title,
|
||||
description: post.frontmatter.description || '',
|
||||
image: post.frontmatter.image || defaultImage,
|
||||
slug: slug,
|
||||
tags: post.frontmatter.tags || [],
|
||||
tagId: post.frontmatter.tagId || [],
|
||||
category: Array.isArray(post.frontmatter.category) ? post.frontmatter.category : post.frontmatter.category ? [post.frontmatter.category] : [],
|
||||
categoryId: Array.isArray(post.frontmatter.categoryId) ? post.frontmatter.categoryId : post.frontmatter.categoryId ? [post.frontmatter.categoryId] : [],
|
||||
date: post.frontmatter.date || post.frontmatter.pubDate || '',
|
||||
readTime: post.frontmatter.readTime || post.frontmatter.readingTime || '5 min read',
|
||||
};
|
||||
});
|
||||
|
||||
// 转换为数组并排序
|
||||
const categories = Array.from(allCategories).sort();
|
||||
const tags = Array.from(allTags).map(tag => `# ${tag}`).sort();
|
||||
// Filter posts by category
|
||||
const filteredPosts = filterPostsByCategory(blogPosts, decodedCategory);
|
||||
|
||||
// 查找与当前分类ID匹配的分类名称
|
||||
let displayCategoryName = "";
|
||||
// Sort posts by date
|
||||
const sortedBlogPosts = sortPostsByDate(filteredPosts);
|
||||
|
||||
// 从博客文章中查找匹配的分类名称
|
||||
for (const post of allPosts) {
|
||||
if (post.frontmatter?.categoryId && Array.isArray(post.frontmatter.categoryId) &&
|
||||
post.frontmatter?.category && Array.isArray(post.frontmatter.category)) {
|
||||
// 查找分类ID和分类名称的索引匹配
|
||||
const categoryIndex = post.frontmatter.categoryId.findIndex(id =>
|
||||
// Find category name matching the current category ID
|
||||
let categoryName = decodedCategory;
|
||||
|
||||
// Try to find matching category name from all posts
|
||||
Object.values(allPosts).forEach((post: any) => {
|
||||
// Check categoryId
|
||||
if (post.frontmatter?.categoryId) {
|
||||
const categoryIds = Array.isArray(post.frontmatter.categoryId)
|
||||
? post.frontmatter.categoryId
|
||||
: [post.frontmatter.categoryId];
|
||||
|
||||
const matchingCategoryIdIndex = categoryIds.findIndex((id: string) =>
|
||||
id.toLowerCase() === decodedCategory.toLowerCase()
|
||||
);
|
||||
|
||||
if (categoryIndex !== -1 && categoryIndex < post.frontmatter.category.length) {
|
||||
displayCategoryName = post.frontmatter.category[categoryIndex];
|
||||
break;
|
||||
if (matchingCategoryIdIndex !== -1 && post.frontmatter.category) {
|
||||
// If matching categoryId is found and post has category attribute
|
||||
const categories = Array.isArray(post.frontmatter.category)
|
||||
? post.frontmatter.category
|
||||
: [post.frontmatter.category];
|
||||
|
||||
// Ensure categories array length matches categoryIds
|
||||
if (categories.length > matchingCategoryIdIndex) {
|
||||
categoryName = categories[matchingCategoryIdIndex];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 如果没有找到匹配的分类名称,则使用分类ID并格式化(首字母大写)
|
||||
if (!displayCategoryName) {
|
||||
displayCategoryName = decodedCategory.charAt(0).toUpperCase() + decodedCategory.slice(1);
|
||||
}
|
||||
// Page title and description
|
||||
const title = `${categoryName} - Blog | Joy Zhao`;
|
||||
const description = `Explore articles about ${categoryName}. Dive into my thoughts on ${categoryName} and related topics.`;
|
||||
|
||||
// 动态生成页面标题和描述
|
||||
const pageTitle = `${displayCategoryName} - Blog | Joy Zhao`;
|
||||
const pageDescription = `Explore articles about ${displayCategoryName}. Dive into my thoughts on ${displayCategoryName} and related topics.`;
|
||||
// Extract categories and tags from all posts for sidebar
|
||||
const allPostsArray = Object.values(allPosts).map((post: any) => ({
|
||||
category: post.frontmatter.category || [],
|
||||
categoryId: post.frontmatter.categoryId || [],
|
||||
tags: post.frontmatter.tags || [],
|
||||
tagId: post.frontmatter.tagId || []
|
||||
}));
|
||||
|
||||
// Get categories and tags for sidebar
|
||||
|
||||
// Get categories and tags for sidebar
|
||||
const categories = extractCategories(allPostsArray);
|
||||
const tags = extractTags(allPostsArray);
|
||||
---
|
||||
|
||||
<BlogLayout title={pageTitle} description={pageDescription}>
|
||||
<BlogLayout title={title} description={description}>
|
||||
<main class="min-h-screen">
|
||||
<!-- Header Section -->
|
||||
<div class="container mx-auto px-4 pt-24 pb-12">
|
||||
<div class="text-center mb-16">
|
||||
<h1 class="text-5xl md:text-6xl font-bold bg-gradient-to-r from-foreground via-purple-600 to-purple-800 dark:from-foreground dark:via-purple-200 dark:to-purple-300 bg-clip-text text-transparent mb-6">
|
||||
Category: <span class="text-purple-500">{displayCategoryName}</span>
|
||||
Category: <span class="text-purple-500">{categoryName}</span>
|
||||
</h1>
|
||||
<p class="text-xl text-muted-foreground max-w-3xl mx-auto">
|
||||
Explore articles about {displayCategoryName}. Found {sortedBlogPosts.length} article{sortedBlogPosts.length !== 1 ? 's' : ''}.
|
||||
Explore articles about {categoryName}. Found {sortedBlogPosts.length} article{sortedBlogPosts.length !== 1 ? 's' : ''}.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
@@ -187,23 +153,23 @@ const pageDescription = `Explore articles about ${displayCategoryName}. Dive int
|
||||
<div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
|
||||
<!-- Sidebar -->
|
||||
<div class="lg:col-span-1 space-y-8">
|
||||
<!-- 分类卡片 -->
|
||||
<CategoryCard lang="en" currentCategory={decodedCategory} />
|
||||
<!-- Categories card -->
|
||||
<CategoryCard lang={lang} currentCategory={decodedCategory} />
|
||||
|
||||
<!-- 标签卡片 -->
|
||||
<TagCard lang="en" />
|
||||
<!-- Tags card -->
|
||||
<TagCard lang={lang} />
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Blog Posts -->
|
||||
<div class="lg:col-span-3">
|
||||
{sortedBlogPosts.length > 0 ? (
|
||||
<BlogList posts={sortedBlogPosts} lang="en" category={decodedCategory} />
|
||||
<BlogList posts={sortedBlogPosts} lang={lang} category={decodedCategory} />
|
||||
) : (
|
||||
<div class="bg-card/50 backdrop-blur-sm rounded-2xl p-8 border border-border text-center">
|
||||
<h2 class="text-2xl font-semibold mb-4">No articles found</h2>
|
||||
<p class="text-muted-foreground mb-6">There are no articles in this category yet. Check back later or explore other categories.</p>
|
||||
<a href="/blog" class="inline-flex items-center px-4 py-2 rounded-md bg-purple-500 text-white hover:bg-purple-600 transition-colors">
|
||||
<a href={`/${lang}/blog`} class="inline-flex items-center px-4 py-2 rounded-md bg-purple-500 text-white hover:bg-purple-600 transition-colors">
|
||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
|
||||
</svg>
|
||||
|
||||
@@ -6,18 +6,19 @@ import TagCard from '../../components/blog/TagCard.astro';
|
||||
import { type BlogPost } from '@/types';
|
||||
import { type Lang } from '@/i18n/utils';
|
||||
import { defaultLang } from '@/i18n/ui';
|
||||
import { sortPostsByDate } from '@/utils/blog-utils';
|
||||
|
||||
// 使用Astro.currentLocale获取当前语言环境
|
||||
// Get current language environment using Astro.currentLocale
|
||||
const lang = Astro.currentLocale as Lang || defaultLang;
|
||||
|
||||
// 使用Astro.glob读取所有博客文章
|
||||
const allPosts = await Astro.glob('./posts/*.md');
|
||||
// Read all blog posts using import.meta.glob
|
||||
const allPosts = await import.meta.glob('./posts/*.md', { eager: true });
|
||||
|
||||
// 处理博客文章数据
|
||||
const blogPosts: BlogPost[] = allPosts.map((post) => {
|
||||
// Process blog post data
|
||||
const blogPosts: BlogPost[] = Object.values(allPosts).map((post: any) => {
|
||||
const slug = post.url?.split('/').filter(Boolean).pop() || '';
|
||||
|
||||
// 获取文章的默认图片,如果frontmatter中没有指定
|
||||
// Default image if not specified in frontmatter
|
||||
const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
|
||||
|
||||
return {
|
||||
@@ -34,43 +35,8 @@ const blogPosts: BlogPost[] = allPosts.map((post) => {
|
||||
};
|
||||
});
|
||||
|
||||
// 按日期排序
|
||||
const sortedBlogPosts = blogPosts
|
||||
.filter(post => post.date) // 过滤掉没有日期的文章
|
||||
.sort((a, b) => {
|
||||
const dateA = new Date(a.date).getTime();
|
||||
const dateB = new Date(b.date).getTime();
|
||||
return dateB - dateA; // 降序排列,最新的文章在前
|
||||
});
|
||||
|
||||
// 从博客文章中提取分类和标签
|
||||
const allCategories = new Set<string>();
|
||||
const allTags = new Set<string>();
|
||||
|
||||
// 收集所有文章的分类和标签
|
||||
allPosts.forEach(post => {
|
||||
// 处理分类
|
||||
if (post.frontmatter?.category) {
|
||||
const categories = Array.isArray(post.frontmatter.category)
|
||||
? post.frontmatter.category
|
||||
: [post.frontmatter.category];
|
||||
|
||||
categories.forEach(category => {
|
||||
if (category) allCategories.add(category);
|
||||
});
|
||||
}
|
||||
|
||||
// 处理标签
|
||||
if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
|
||||
post.frontmatter.tags.forEach(tag => {
|
||||
if (tag) allTags.add(tag);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 转换为数组并排序
|
||||
const categories = Array.from(allCategories).sort();
|
||||
const tags = Array.from(allTags).map(tag => `# ${tag}`).sort();
|
||||
// Sort posts by date
|
||||
const sortedBlogPosts = sortPostsByDate(blogPosts);
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -6,40 +6,41 @@ import TagCard from '../../../components/blog/TagCard.astro';
|
||||
import { type Lang } from '@/i18n/utils';
|
||||
import { defaultLang } from '@/i18n/ui';
|
||||
import { type BlogPost } from '@/types';
|
||||
import { filterPostsByTag, sortPostsByDate, extractCategories, extractTags } from '@/utils/blog-utils';
|
||||
|
||||
// 为动态路由生成静态路径
|
||||
// Generate static paths for dynamic routing
|
||||
export async function getStaticPaths() {
|
||||
const allPosts = await Astro.glob('../posts/*.md');
|
||||
const allPosts = await import.meta.glob('../posts/*.md', { eager: true });
|
||||
|
||||
// 收集所有标签ID或标签
|
||||
// Collect all tags
|
||||
const uniqueTags = new Set<string>();
|
||||
|
||||
allPosts.forEach(post => {
|
||||
// 优先使用 tagId 作为路由标识符
|
||||
Object.values(allPosts).forEach((post: any) => {
|
||||
// Prioritize tagId as route identifier
|
||||
if (post.frontmatter?.tagId && Array.isArray(post.frontmatter.tagId)) {
|
||||
post.frontmatter.tagId.forEach(tagId => {
|
||||
post.frontmatter.tagId.forEach((tagId: string) => {
|
||||
if (tagId) uniqueTags.add(tagId.toLowerCase());
|
||||
});
|
||||
}
|
||||
// 如果没有 tagId,则使用 tags 作为后备
|
||||
}
|
||||
// If no tagId, use tags as fallback
|
||||
else if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
|
||||
post.frontmatter.tags.forEach(tag => {
|
||||
post.frontmatter.tags.forEach((tag: string) => {
|
||||
if (tag) uniqueTags.add(tag.toLowerCase());
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
// 为每个标签生成路径,对包含特殊字符的标签进行编码
|
||||
// Generate paths for each tag
|
||||
return Array.from(uniqueTags).map(tag => ({
|
||||
params: { tag: encodeURIComponent(tag) },
|
||||
props: { tag }
|
||||
}));
|
||||
}
|
||||
|
||||
// 获取当前语言环境
|
||||
// Get current language environment
|
||||
const lang = Astro.currentLocale as Lang || defaultLang;
|
||||
|
||||
// 获取当前标签(从URL参数)
|
||||
// Get current tag (from URL parameters)
|
||||
export interface Props {
|
||||
tag: string;
|
||||
}
|
||||
@@ -47,151 +48,113 @@ export interface Props {
|
||||
const { tag } = Astro.params;
|
||||
const decodedTag = tag ? decodeURIComponent(tag) : '';
|
||||
|
||||
// Read all blog posts using import.meta.glob
|
||||
const allPosts = await import.meta.glob('../posts/*.md', { eager: true });
|
||||
|
||||
// 使用Astro.glob读取所有博客文章
|
||||
const allPosts = await Astro.glob('../posts/*.md');
|
||||
|
||||
// 处理博客文章数据
|
||||
const blogPosts: BlogPost[] = allPosts
|
||||
.filter(post => {
|
||||
// 优先检查文章是否包含当前标签ID
|
||||
if (post.frontmatter?.tagId && Array.isArray(post.frontmatter.tagId)) {
|
||||
return post.frontmatter.tagId.some(postTagId =>
|
||||
postTagId.toLowerCase() === decodedTag.toLowerCase()
|
||||
);
|
||||
}
|
||||
// 如果没有 tagId,则检查 tags
|
||||
else if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
|
||||
return post.frontmatter.tags.some(postTag =>
|
||||
postTag.toLowerCase() === decodedTag.toLowerCase()
|
||||
);
|
||||
}
|
||||
return false;
|
||||
})
|
||||
.map((post) => {
|
||||
const slug = post.url?.split('/').filter(Boolean).pop() || '';
|
||||
|
||||
// 获取文章的默认图片,如果frontmatter中没有指定
|
||||
const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
|
||||
|
||||
return {
|
||||
title: post.frontmatter.title,
|
||||
description: post.frontmatter.description || '',
|
||||
image: post.frontmatter.image || defaultImage,
|
||||
slug: slug,
|
||||
tags: post.frontmatter.tags || [],
|
||||
date: post.frontmatter.date || post.frontmatter.pubDate || '',
|
||||
readTime: post.frontmatter.readTime || post.frontmatter.readingTime || '5 min read',
|
||||
};
|
||||
});
|
||||
|
||||
// 按日期排序
|
||||
const sortedBlogPosts = blogPosts
|
||||
.filter(post => post.date) // 过滤掉没有日期的文章
|
||||
.sort((a, b) => {
|
||||
const dateA = new Date(a.date).getTime();
|
||||
const dateB = new Date(b.date).getTime();
|
||||
return dateB - dateA; // 降序排列,最新的文章在前
|
||||
});
|
||||
|
||||
// 从所有博客文章中提取分类和标签(用于侧边栏)
|
||||
const allCategories = new Set<string>();
|
||||
const allTags = new Set<string>();
|
||||
|
||||
// 收集所有文章的分类和标签
|
||||
allPosts.forEach(post => {
|
||||
// 处理分类
|
||||
if (post.frontmatter?.category) {
|
||||
const categories = Array.isArray(post.frontmatter.category)
|
||||
? post.frontmatter.category
|
||||
: [post.frontmatter.category];
|
||||
|
||||
categories.forEach(cat => {
|
||||
if (cat) allCategories.add(cat);
|
||||
});
|
||||
}
|
||||
// Process blog post data
|
||||
const blogPosts: BlogPost[] = Object.values(allPosts).map((post: any) => {
|
||||
const slug = post.url?.split('/').filter(Boolean).pop() || '';
|
||||
|
||||
// 处理标签
|
||||
if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
|
||||
post.frontmatter.tags.forEach(postTag => {
|
||||
if (postTag) allTags.add(postTag);
|
||||
});
|
||||
}
|
||||
// 同时收集标签ID(用于内部路由)
|
||||
if (post.frontmatter?.tagId && Array.isArray(post.frontmatter.tagId)) {
|
||||
// 这里我们不添加到 allTags 中,因为 tagId 只用于路由,不用于显示
|
||||
}
|
||||
// Default image if not specified in frontmatter
|
||||
const defaultImage = "https://images.unsplash.com/photo-1516321318423-f06f85e504b3?w=400&h=250&fit=crop&crop=center";
|
||||
|
||||
return {
|
||||
title: post.frontmatter.title,
|
||||
description: post.frontmatter.description || '',
|
||||
image: post.frontmatter.image || defaultImage,
|
||||
slug: slug,
|
||||
tags: post.frontmatter.tags || [],
|
||||
tagId: post.frontmatter.tagId || [],
|
||||
category: Array.isArray(post.frontmatter.category) ? post.frontmatter.category : post.frontmatter.category ? [post.frontmatter.category] : [],
|
||||
categoryId: Array.isArray(post.frontmatter.categoryId) ? post.frontmatter.categoryId : post.frontmatter.categoryId ? [post.frontmatter.categoryId] : [],
|
||||
date: post.frontmatter.date || post.frontmatter.pubDate || '',
|
||||
readTime: post.frontmatter.readTime || post.frontmatter.readingTime || '5 min read',
|
||||
};
|
||||
});
|
||||
|
||||
// 转换为数组并排序
|
||||
const categories = Array.from(allCategories).sort();
|
||||
const tags = Array.from(allTags).map(postTag => `# ${postTag}`).sort();
|
||||
// Filter posts by tag
|
||||
const filteredPosts = filterPostsByTag(blogPosts, decodedTag);
|
||||
|
||||
// 查找与当前标签ID匹配的标签名称
|
||||
let displayTagName = "";
|
||||
// Sort posts by date
|
||||
const sortedBlogPosts = sortPostsByDate(filteredPosts);
|
||||
|
||||
// 从博客文章中查找匹配的标签名称
|
||||
for (const post of allPosts) {
|
||||
// Extract categories and tags from all posts for sidebar
|
||||
const allPostsArray = Object.values(allPosts).map((post: any) => ({
|
||||
category: post.frontmatter.category || [],
|
||||
categoryId: post.frontmatter.categoryId || [],
|
||||
tags: post.frontmatter.tags || [],
|
||||
tagId: post.frontmatter.tagId || []
|
||||
}));
|
||||
|
||||
// Get categories and tags for sidebar
|
||||
const categories = extractCategories(allPostsArray);
|
||||
const tags = extractTags(allPostsArray);
|
||||
|
||||
// Find tag name matching the current tag ID
|
||||
let tagName = decodedTag;
|
||||
|
||||
// Try to find matching tag name from all posts
|
||||
Object.values(allPosts).forEach((post: any) => {
|
||||
// Check tagId
|
||||
if (post.frontmatter?.tagId && Array.isArray(post.frontmatter.tagId) &&
|
||||
post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
|
||||
// 查找标签ID和标签名称的索引匹配
|
||||
const tagIndex = post.frontmatter.tagId.findIndex(id =>
|
||||
// Find matching index between tagId and tag name
|
||||
const tagIndex = post.frontmatter.tagId.findIndex((id: string) =>
|
||||
id.toLowerCase() === decodedTag.toLowerCase()
|
||||
);
|
||||
|
||||
if (tagIndex !== -1 && tagIndex < post.frontmatter.tags.length) {
|
||||
displayTagName = post.frontmatter.tags[tagIndex];
|
||||
break;
|
||||
tagName = post.frontmatter.tags[tagIndex];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// If no matching tag name is found, use tag ID and format it (capitalize first letter)
|
||||
if (tagName === decodedTag) {
|
||||
tagName = decodedTag.charAt(0).toUpperCase() + decodedTag.slice(1);
|
||||
}
|
||||
|
||||
// 如果没有找到匹配的标签名称,则使用标签ID并格式化(首字母大写)
|
||||
if (!displayTagName) {
|
||||
displayTagName = decodedTag.charAt(0).toUpperCase() + decodedTag.slice(1);
|
||||
}
|
||||
|
||||
// 动态生成页面标题和描述
|
||||
const pageTitle = `# ${displayTagName} - Blog | Joy Zhao`;
|
||||
const pageDescription = `Explore articles tagged with # ${displayTagName}. Dive into my thoughts on ${displayTagName} and related topics.`;
|
||||
// Generate page title and description
|
||||
const title = `#${tagName} - Blog | Joy Zhao`;
|
||||
const description = `Explore articles tagged with #${tagName}. Dive into my thoughts on ${tagName} and related topics.`;
|
||||
---
|
||||
|
||||
<BlogLayout title={pageTitle} description={pageDescription}>
|
||||
<BlogLayout title={title} description={description}>
|
||||
<main class="min-h-screen">
|
||||
<!-- Header Section -->
|
||||
<div class="container mx-auto px-4 pt-24 pb-12">
|
||||
<section class="container mx-auto px-4 py-12">
|
||||
<div class="text-center mb-16">
|
||||
<h1 class="text-5xl md:text-6xl font-bold bg-gradient-to-r from-foreground via-purple-600 to-purple-800 dark:from-foreground dark:via-purple-200 dark:to-purple-300 bg-clip-text text-transparent mb-6">
|
||||
Tag: <span class="text-purple-500"># {displayTagName}</span>
|
||||
Tag: <span class="text-purple-500">#{tagName}</span>
|
||||
</h1>
|
||||
<p class="text-xl text-muted-foreground max-w-3xl mx-auto">
|
||||
Explore articles tagged with # {displayTagName}. Found {sortedBlogPosts.length} article{sortedBlogPosts.length !== 1 ? 's' : ''}.
|
||||
Explore articles tagged with #{tagName}. Found {sortedBlogPosts.length} article{sortedBlogPosts.length !== 1 ? 's' : ''}.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="container mx-auto px-4 pb-20">
|
||||
<!-- Content Section -->
|
||||
<section class="container mx-auto px-4 pb-16">
|
||||
<div class="grid grid-cols-1 lg:grid-cols-4 gap-8">
|
||||
<!-- Sidebar -->
|
||||
<div class="lg:col-span-1 space-y-8">
|
||||
<!-- 分类卡片 -->
|
||||
<CategoryCard lang="en" />
|
||||
<!-- Categories card -->
|
||||
<CategoryCard lang={lang} />
|
||||
|
||||
<!-- 标签卡片 -->
|
||||
<TagCard lang="en" currentTag={decodedTag} />
|
||||
<!-- Tags card -->
|
||||
<TagCard lang={lang} currentTag={decodedTag} />
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Blog Posts -->
|
||||
<!-- Main content -->
|
||||
<div class="lg:col-span-3">
|
||||
{sortedBlogPosts.length > 0 ? (
|
||||
<BlogList posts={sortedBlogPosts} lang="en" tag={decodedTag} />
|
||||
<BlogList posts={sortedBlogPosts} lang={lang} tag={decodedTag} />
|
||||
) : (
|
||||
<div class="bg-card/50 backdrop-blur-sm rounded-2xl p-8 border border-border text-center">
|
||||
<h2 class="text-2xl font-semibold mb-4">No articles found</h2>
|
||||
<p class="text-muted-foreground mb-6">There are no articles with this tag yet. Check back later or explore other tags.</p>
|
||||
<a href="/blog" class="inline-flex items-center px-4 py-2 rounded-md bg-purple-500 text-white hover:bg-purple-600 transition-colors">
|
||||
<a href={`/${lang}/blog`} class="inline-flex items-center px-4 py-2 rounded-md bg-purple-500 text-white hover:bg-purple-600 transition-colors">
|
||||
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
|
||||
</svg>
|
||||
@@ -201,7 +164,7 @@ const pageDescription = `Explore articles tagged with # ${displayTagName}. Dive
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
</BlogLayout>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user