feat(blog): refactor blog components and improve category/tag handling

- Add new CategoryCard and TagCard components to centralize UI logic
- Convert BlogList from React to Astro component
- Improve category and tag matching by using IDs from frontmatter
- Update all blog pages to use new components
- Add line-height to global styles for better readability
This commit is contained in:
joyzhao
2025-06-19 14:45:29 +08:00
parent deb80c0df7
commit 429b13985f
11 changed files with 545 additions and 363 deletions

View File

@@ -1,111 +0,0 @@
import React from 'react';
import { useTranslations, type Lang } from '@/i18n/utils';
import { type BlogPost, type BlogListProps } from '@/types';
/**
* Reusable blog list component that displays blog posts in a grid layout
* @param posts - Array of blog posts to display
* @param lang - Current language for internationalization
* @param baseUrl - Base URL for blog post links
*/
export default function BlogList({ posts, lang, baseUrl = '/blog/posts/' }: BlogListProps) {
const t = useTranslations(lang);
// Adjust base URL for Chinese language
const postBaseUrl = lang === 'zh' ? '/zh/blog/posts/' : baseUrl;
// Get localized "Read More" text
const readMoreText = lang === 'zh' ? '阅读更多' : 'Read More';
return (
<div className="space-y-6">
{posts.map((post, index) => (
<article key={post.slug || index} className="group">
<div className="bg-card/50 backdrop-blur-sm rounded-2xl overflow-hidden border border-border hover:border-purple-500/50 transition-all duration-300 hover:transform hover:scale-[1.02]">
<div className="flex flex-col md:flex-row">
{/* Featured Image */}
<div className="relative overflow-hidden md:w-80 md:flex-shrink-0">
<img
src={post.image}
alt={post.title}
className="w-full h-48 md:h-full object-cover group-hover:scale-110 transition-transform duration-300"
/>
<div className="absolute inset-0 bg-gradient-to-t md:bg-gradient-to-r from-background/50 to-transparent"></div>
</div>
{/* Content */}
<div className="p-6 flex-1 flex flex-col justify-between">
<div>
<h2 className="text-xl font-bold text-card-foreground mb-3 group-hover:text-purple-500 transition-colors duration-200">
<a href={`${postBaseUrl}${post.slug}`}>
{post.title}
</a>
</h2>
<p className="text-muted-foreground mb-4 line-clamp-3">
{post.description}
</p>
{/* Tags */}
<div className="flex flex-wrap gap-2 mb-4">
{post.tags.map((tag, tagIndex) => {
// 使用 tagId 如果存在,否则使用 tag 本身
const tagRoute = post.tagId && Array.isArray(post.tagId) && tagIndex < post.tagId.length
? post.tagId[tagIndex]
: tag.toLowerCase();
return (
<a
href={`/${lang === 'en' ? '' : 'zh/'}blog/tags/${encodeURIComponent(tagRoute)}`}
key={`${tag}-${tagIndex}`}
className="px-2 py-1 text-xs bg-muted text-muted-foreground rounded-full hover:bg-muted/80 transition-colors"
>
# {tag}
</a>
);
})}
</div>
</div>
{/* Meta Info */}
<div className="flex items-center justify-between text-sm text-muted-foreground">
<div className="flex items-center space-x-4">
<span className="flex items-center">
<svg className="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 002 2v12a2 2 0 002 2z"></path>
</svg>
{post.date}
</span>
<span>{post.readTime}</span>
</div>
<a
href={`${postBaseUrl}${post.slug}`}
className="text-purple-500 hover:text-purple-400 font-medium flex items-center group"
>
{readMoreText}
<svg className="w-4 h-4 ml-1 group-hover:translate-x-1 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path>
</svg>
</a>
</div>
</div>
</div>
</div>
</article>
))}
</div>
);
}
/**
* CSS styles for line clamping (to be included in global styles)
*/
export const blogListStyles = `
.line-clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
`;

View File

@@ -0,0 +1,192 @@
---
import { type BlogPost, type Lang } from '@/types';
interface Props {
posts?: BlogPost[];
lang: Lang;
baseUrl?: string;
category?: string;
tag?: string;
}
// 获取组件属性
const { lang, baseUrl, category, tag, posts: providedPosts } = Astro.props;
// 如果没有提供 posts则直接从文件系统读取
let posts: BlogPost[] = [];
if (providedPosts) {
// 使用提供的文章列表
posts = providedPosts;
} else {
// 根据当前语言读取博客文章
let allPosts = [];
if (lang === 'zh') {
// 读取中文博客文章
allPosts = await Astro.glob('../zh/blog/posts/*.md');
} else {
// 读取英文博客文章
allPosts = await Astro.glob('../blog/posts/*.md');
}
// 处理博客文章数据
posts = allPosts.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 || [],
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',
};
});
// 按日期排序
posts = posts
.filter(post => post.date) // 过滤掉没有日期的文章
.sort((a, b) => {
const dateA = new Date(a.date).getTime();
const dateB = new Date(b.date).getTime();
return dateB - dateA; // 降序排列,最新的文章在前
});
}
// 如果指定了分类,则过滤文章
if (category) {
posts = posts.filter(post => {
// 优先检查文章是否包含当前分类ID
if (post.categoryId && Array.isArray(post.categoryId)) {
return post.categoryId.some(catId =>
catId.toLowerCase() === category.toLowerCase()
);
}
// 如果没有 categoryId则检查 category
else if (post.category && Array.isArray(post.category)) {
return post.category.some(cat =>
cat.toLowerCase() === category.toLowerCase()
);
}
return false;
});
}
// 如果指定了标签,则过滤文章
if (tag) {
posts = posts.filter(post => {
// 优先检查文章是否包含当前标签ID
if (post.tagId && Array.isArray(post.tagId)) {
return post.tagId.some(tagId =>
tagId.toLowerCase() === tag.toLowerCase()
);
}
// 如果没有 tagId则检查 tags
else if (post.tags && Array.isArray(post.tags)) {
return post.tags.some(postTag =>
postTag.toLowerCase() === tag.toLowerCase()
);
}
return false;
});
}
// 调整基础URL
const postBaseUrl = lang === 'zh' ? '/zh/blog/posts/' : '/blog/posts/';
// 获取本地化的"阅读更多"文本
const readMoreText = lang === 'zh' ? '阅读更多' : 'Read More';
---
<div class="space-y-6">
{posts.map((post, index) => (
<article class="group">
<div class="bg-card/50 backdrop-blur-sm rounded-2xl overflow-hidden border border-border hover:border-purple-500/50 transition-all duration-300 hover:transform hover:scale-[1.02]">
<div class="flex flex-col md:flex-row">
{/* Featured Image */}
<div class="relative overflow-hidden md:w-80 md:flex-shrink-0">
<img
src={post.image}
alt={post.title}
class="w-full h-48 md:h-full object-cover group-hover:scale-110 transition-transform duration-300"
/>
<div class="absolute inset-0 bg-gradient-to-t md:bg-gradient-to-r from-background/50 to-transparent"></div>
</div>
{/* Content */}
<div class="p-6 flex-1 flex flex-col justify-between">
<div>
<h2 class="text-xl font-bold text-card-foreground mb-3 group-hover:text-purple-500 transition-colors duration-200">
<a href={`${postBaseUrl}${post.slug}`}>
{post.title}
</a>
</h2>
<p class="text-muted-foreground mb-4 line-clamp-3">
{post.description}
</p>
{/* Tags */}
<div class="flex flex-wrap gap-2 mb-4">
{post.tags.map((tag, tagIndex) => {
// 使用 tagId 如果存在,否则使用 tag 本身
const tagRoute = post.tagId && Array.isArray(post.tagId) && tagIndex < post.tagId.length
? post.tagId[tagIndex]
: tag.toLowerCase();
return (
<a
href={`/${lang === 'en' ? '' : 'zh/'}blog/tags/${encodeURIComponent(tagRoute)}`}
class="px-2 py-1 text-xs bg-muted text-muted-foreground rounded-full hover:bg-muted/80 transition-colors"
>
# {tag}
</a>
);
})}
</div>
</div>
{/* Meta Info */}
<div class="flex items-center justify-between text-sm text-muted-foreground">
<div class="flex items-center space-x-4">
<span class="flex items-center">
<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 002 2v12a2 2 0 002 2z"></path>
</svg>
{post.date}
</span>
<span>{post.readTime}</span>
</div>
<a
href={`${postBaseUrl}${post.slug}`}
class="text-purple-500 hover:text-purple-400 font-medium flex items-center group"
>
{readMoreText}
<svg class="w-4 h-4 ml-1 group-hover:translate-x-1 transition-transform duration-200" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 8l4 4m0 0l-4 4m4-4H3"></path>
</svg>
</a>
</div>
</div>
</div>
</div>
</article>
))}
</div>
<style>
.line-clamp-3 {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
</style>

View File

@@ -0,0 +1,95 @@
---
// 导入必要的依赖
import { type Lang } from '@/i18n/utils';
import { defaultLang } from '@/i18n/ui';
// 定义组件属性
interface Props {
lang?: Lang;
currentCategory?: string;
}
// 获取组件属性
const { lang = defaultLang, currentCategory = '' } = Astro.props;
// 确定基础URL路径
const baseUrl = lang === defaultLang ? '/blog' : `/${lang}/blog`;
// 读取所有博客文章 - 根据语言选择不同的静态路径
let allPosts = [];
if (lang === 'zh') {
allPosts = await Astro.glob('/src/pages/zh/blog/posts/*.md');
} else {
allPosts = await Astro.glob('/src/pages/blog/posts/*.md');
}
// 收集所有分类
const allCategories = new Set<string>();
// 处理所有文章的分类
const categoryMap = new Map<string, string>(); // 存储 categoryId 到 category 名称的映射
allPosts.forEach(post => {
// 处理分类
if (post.frontmatter?.category) {
const categories = Array.isArray(post.frontmatter.category)
? post.frontmatter.category
: [post.frontmatter.category];
const categoryIds = Array.isArray(post.frontmatter.categoryId)
? post.frontmatter.categoryId
: post.frontmatter.categoryId ? [post.frontmatter.categoryId] : [];
// 如果有 categoryId则使用 categoryId 和 category 的映射
if (categoryIds.length > 0 && categoryIds.length === categories.length) {
categories.forEach((cat, index) => {
if (cat && categoryIds[index]) {
allCategories.add(cat);
categoryMap.set(cat, categoryIds[index]);
}
});
} else {
// 如果没有 categoryId 或长度不匹配,则使用 category 名称作为 ID
categories.forEach(cat => {
if (cat) {
allCategories.add(cat);
categoryMap.set(cat, cat.toLowerCase());
}
});
}
}
});
// 转换为数组并排序
const categories = Array.from(allCategories).sort();
// 多语言标题
const titles = {
en: 'Categories',
zh: '分类'
};
// 获取当前语言的标题
const title = titles[lang] || titles[defaultLang];
---
<div class="bg-card/50 backdrop-blur-sm rounded-2xl p-6 border border-border">
<h3 class="text-xl font-semibold text-card-foreground mb-4 flex items-center">
<svg class="w-5 h-5 mr-2 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14-7l2 2-2 2m2-2H9m10 0V9M5 19l2-2-2-2m2 2H3m2 0v2"></path>
</svg>
{title}
</h3>
<div class="space-y-2">
{categories.map((cat) => {
const categoryId = categoryMap.get(cat) || cat.toLowerCase();
return (
<a href={`${baseUrl}/categories/${encodeURIComponent(categoryId)}`}
class={`block transition-colors duration-200 ${categoryId === currentCategory.toLowerCase() ? 'text-purple-500 font-medium' : 'text-muted-foreground hover:text-purple-500'}`}>
{cat}
</a>
);
})}
</div>
</div>

View File

@@ -0,0 +1,92 @@
---
// 导入必要的依赖
import { type Lang } from '@/i18n/utils';
import { defaultLang } from '@/i18n/ui';
// 定义组件属性
interface Props {
lang?: Lang;
currentTag?: string;
}
// 获取组件属性
const { lang = defaultLang, currentTag = '' } = Astro.props;
// 确定基础URL路径
const baseUrl = lang === defaultLang ? '/blog' : `/${lang}/blog`;
// 读取所有博客文章 - 根据语言选择不同的静态路径
let allPosts = [];
if (lang === 'zh') {
allPosts = await Astro.glob('/src/pages/zh/blog/posts/*.md');
} else {
allPosts = await Astro.glob('/src/pages/blog/posts/*.md');
}
// 收集所有标签
const allTags = new Set<string>();
const tagMap = new Map<string, string>(); // 存储 tag 到 tagId 的映射
// 处理所有文章的标签
allPosts.forEach(post => {
// 处理标签
if (post.frontmatter?.tags && Array.isArray(post.frontmatter.tags)) {
const tags = post.frontmatter.tags;
const tagIds = Array.isArray(post.frontmatter.tagId)
? post.frontmatter.tagId
: post.frontmatter.tagId ? [post.frontmatter.tagId] : [];
// 如果有 tagId则使用 tagId 和 tag 的映射
if (tagIds.length > 0 && tagIds.length === tags.length) {
tags.forEach((tag, index) => {
if (tag && tagIds[index]) {
allTags.add(tag);
tagMap.set(tag, tagIds[index]);
}
});
} else {
// 如果没有 tagId 或长度不匹配,则使用 tag 名称作为 ID
tags.forEach(tag => {
if (tag) {
allTags.add(tag);
tagMap.set(tag, tag.toLowerCase());
}
});
}
}
});
// 转换为数组,添加 # 前缀,并排序
const tags = Array.from(allTags).map(tag => `# ${tag}`).sort();
// 多语言标题
const titles = {
en: '# Tags',
zh: '# 标签'
};
// 获取当前语言的标题
const title = titles[lang] || titles[defaultLang];
---
<div class="bg-card/50 backdrop-blur-sm rounded-2xl p-6 border border-border">
<h3 class="text-xl font-semibold text-card-foreground mb-4 flex items-center">
<svg class="w-5 h-5 mr-2 text-purple-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
</svg>
{title}
</h3>
<div class="flex flex-wrap gap-2">
{tags.map((tagItem) => {
const tagName = tagItem.slice(2); // 去掉 '# ' 前缀
const tagId = tagMap.get(tagName) || tagName.toLowerCase();
const isCurrentTag = tagId === currentTag.toLowerCase();
return (
<a href={`${baseUrl}/tags/${encodeURIComponent(tagId)}`}
class={`inline-block px-3 py-1 text-sm rounded-full transition-all duration-200 ${isCurrentTag ? 'bg-purple-500/20 text-purple-500 font-medium' : 'bg-muted text-muted-foreground hover:bg-purple-500/20 hover:text-purple-500'}`}>
{tagItem}
</a>
);
})}
</div>
</div>