feat(blog): 添加博客目录功能并更新logo格式
为博客和关于页面添加可交互的目录组件,方便用户导航 将网站logo从svg格式统一改为png格式 移除generateStaticParams函数以简化构建流程 新增getBlogDetail.ts用于获取博客详情数据
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import MDXComponents from "@/components/mdx/MDXComponents";
|
import MDXComponents from "@/components/mdx/MDXComponents";
|
||||||
|
import TableOfContents from "@/components/mdx/TableOfContents.client";
|
||||||
import { Locale, LOCALES } from "@/i18n/routing";
|
import { Locale, LOCALES } from "@/i18n/routing";
|
||||||
import { constructMetadata } from "@/lib/metadata";
|
import { constructMetadata } from "@/lib/metadata";
|
||||||
import fs from "fs/promises";
|
import fs from "fs/promises";
|
||||||
@@ -16,7 +17,52 @@ const options = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
async function getMDXContent(locale: string, section: string) {
|
interface TableOfContentsItem {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
level: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析MDX内容并提取标题
|
||||||
|
async function parseMDXContent(content: string): Promise<TableOfContentsItem[]> {
|
||||||
|
if (!content) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const headingRegex = /^#{2,4}\s+(.+)$/gm;
|
||||||
|
const headings: TableOfContentsItem[] = [];
|
||||||
|
let match;
|
||||||
|
|
||||||
|
while ((match = headingRegex.exec(content)) !== null) {
|
||||||
|
const fullMatch = match[0];
|
||||||
|
const text = match[1]?.trim();
|
||||||
|
|
||||||
|
if (!text) continue;
|
||||||
|
|
||||||
|
// 确定标题级别
|
||||||
|
let level = 2;
|
||||||
|
if (fullMatch.startsWith("###")) {
|
||||||
|
level = fullMatch.startsWith("####") ? 4 : 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成ID(将文本转换为URL友好的格式)
|
||||||
|
const id = text
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9\u4e00-\u9fa5\s-]/g, "")
|
||||||
|
.replace(/\s+/g, "-");
|
||||||
|
|
||||||
|
headings.push({ id, text, level });
|
||||||
|
}
|
||||||
|
|
||||||
|
return headings;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error parsing MDX content for TOC:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getMDXContent(locale: string, section: string): Promise<string> {
|
||||||
const filePath = path.join(
|
const filePath = path.join(
|
||||||
process.cwd(),
|
process.cwd(),
|
||||||
"content",
|
"content",
|
||||||
@@ -69,15 +115,37 @@ export default async function AboutPage({
|
|||||||
const section = (resolvedSearchParams.section as string) || "company";
|
const section = (resolvedSearchParams.section as string) || "company";
|
||||||
|
|
||||||
const content = await getMDXContent(locale, section);
|
const content = await getMDXContent(locale, section);
|
||||||
|
const tocItems = await parseMDXContent(content);
|
||||||
|
|
||||||
|
// 获取多语言目录标题
|
||||||
|
const t = await getTranslations({ locale, namespace: "Common" });
|
||||||
|
const tocTitle = t("tableOfContents") || "目录";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article className="w-full md:w-3/5 px-2 md:px-12">
|
<div className="flex flex-col md:flex-row w-full gap-8">
|
||||||
<MDXRemote
|
{/* 侧边目录 - 在移动端显示在内容上方 */}
|
||||||
source={content}
|
<div className="w-full md:w-1/4 lg:w-1/5 order-2 md:order-1">
|
||||||
components={MDXComponents}
|
<TableOfContents
|
||||||
options={options}
|
items={tocItems || []}
|
||||||
/>
|
title={tocTitle}
|
||||||
</article>
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* 主要内容 */}
|
||||||
|
<article className="w-full md:w-3/4 lg:w-4/5 px-2 md:px-8 ml-0 md:ml-64 order-1 md:order-2">
|
||||||
|
{content ? (
|
||||||
|
<MDXRemote
|
||||||
|
source={content}
|
||||||
|
components={MDXComponents}
|
||||||
|
options={options}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div className="text-center py-8 text-gray-500">
|
||||||
|
<p>内容加载中...</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</article>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,13 +1,59 @@
|
|||||||
import { Callout } from "@/components/mdx/Callout";
|
import { Callout } from "@/components/mdx/Callout";
|
||||||
import MDXComponents from "@/components/mdx/MDXComponents";
|
import MDXComponents from "@/components/mdx/MDXComponents";
|
||||||
import { Locale, LOCALES } from "@/i18n/routing";
|
import TableOfContents from "@/components/mdx/TableOfContents.client";
|
||||||
import { getPosts } from "@/lib/getBlogs";
|
import { Locale } from "@/i18n/routing";
|
||||||
|
import { getPostDetail } from "@/lib/getBlogDetail";
|
||||||
import { constructMetadata } from "@/lib/metadata";
|
import { constructMetadata } from "@/lib/metadata";
|
||||||
import { BlogPost } from "@/types/blog";
|
import { BlogPost } from "@/types/blog";
|
||||||
import { Metadata } from "next";
|
import { Metadata } from "next";
|
||||||
import { MDXRemote } from "next-mdx-remote-client/rsc";
|
import { MDXRemote } from "next-mdx-remote-client/rsc";
|
||||||
import { notFound } from "next/navigation";
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
interface TableOfContentsItem {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
level: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 解析MDX内容并提取标题
|
||||||
|
async function parseMDXContent(content: string): Promise<TableOfContentsItem[]> {
|
||||||
|
if (!content) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const headingRegex = /^#{2,4}\s+(.+)$/gm;
|
||||||
|
const headings: TableOfContentsItem[] = [];
|
||||||
|
let match;
|
||||||
|
|
||||||
|
while ((match = headingRegex.exec(content)) !== null) {
|
||||||
|
const fullMatch = match[0];
|
||||||
|
const text = match[1]?.trim();
|
||||||
|
|
||||||
|
if (!text) continue;
|
||||||
|
|
||||||
|
// 确定标题级别
|
||||||
|
let level = 2;
|
||||||
|
if (fullMatch.startsWith("###")) {
|
||||||
|
level = fullMatch.startsWith("####") ? 4 : 3;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成ID(将文本转换为URL友好的格式)
|
||||||
|
const id = text
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[^a-z0-9\u4e00-\u9fa5\s-]/g, "")
|
||||||
|
.replace(/\s+/g, "-");
|
||||||
|
|
||||||
|
headings.push({ id, text, level });
|
||||||
|
}
|
||||||
|
|
||||||
|
return headings;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error parsing MDX content for TOC:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type Params = Promise<{
|
type Params = Promise<{
|
||||||
locale: string;
|
locale: string;
|
||||||
slug: string;
|
slug: string;
|
||||||
@@ -21,10 +67,10 @@ export async function generateMetadata({
|
|||||||
params,
|
params,
|
||||||
}: MetadataProps): Promise<Metadata> {
|
}: MetadataProps): Promise<Metadata> {
|
||||||
const { locale, slug } = await params;
|
const { locale, slug } = await params;
|
||||||
let { posts }: { posts: BlogPost[] } = await getPosts(locale);
|
let post: BlogPost = await getPostDetail(slug);
|
||||||
const post = posts.find((post) => post.slug === slug);
|
|
||||||
|
console.log(post);
|
||||||
|
|
||||||
console.log(post, posts);
|
|
||||||
if (!post) {
|
if (!post) {
|
||||||
return constructMetadata({
|
return constructMetadata({
|
||||||
title: "404",
|
title: "404",
|
||||||
@@ -49,56 +95,73 @@ export async function generateMetadata({
|
|||||||
|
|
||||||
export default async function BlogPage({ params }: { params: Params }) {
|
export default async function BlogPage({ params }: { params: Params }) {
|
||||||
const { locale, slug } = await params;
|
const { locale, slug } = await params;
|
||||||
let { posts }: { posts: BlogPost[] } = await getPosts(locale);
|
let post: BlogPost = await getPostDetail(slug);
|
||||||
|
|
||||||
const post = posts.find((item) => item.slug === slug);
|
|
||||||
|
|
||||||
if (!post) {
|
if (!post) {
|
||||||
return notFound();
|
return notFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
console.log(post);
|
||||||
|
|
||||||
|
// 提取博客内容中的标题用于目录
|
||||||
|
const tocItems = await parseMDXContent(post.content || "");
|
||||||
|
|
||||||
|
// 使用默认目录标题
|
||||||
|
const tocTitle = "目录";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full md:w-3/5 px-2 md:px-12">
|
<div className="flex flex-col md:flex-row w-full gap-8">
|
||||||
<h1 className="break-words text-4xl font-bold mt-6 mb-4">{post.title}</h1>
|
{/* 侧边目录 - 在移动端显示在内容上方 */}
|
||||||
{post.image && (
|
<div className="w-full md:w-1/4 lg:w-1/5 order-2 md:order-1">
|
||||||
<img src={post.image} alt={post.title} className="rounded-sm" />
|
<TableOfContents
|
||||||
)}
|
items={tocItems || []}
|
||||||
{post.tags && post.tags.split(",").length ? (
|
title={tocTitle}
|
||||||
<div className="flex flex-wrap gap-2">
|
/>
|
||||||
{post.tags.split(",").map((tag) => {
|
</div>
|
||||||
return (
|
|
||||||
<div
|
{/* 主要内容 */}
|
||||||
key={tag}
|
<article className="w-full md:w-3/4 lg:w-4/5 px-2 md:px-8 ml-0 md:ml-64 order-1 md:order-2">
|
||||||
className={`rounded-md bg-gray-200 hover:!no-underline dark:bg-[#24272E] flex px-2.5 py-1.5 text-sm font-medium transition-colors hover:text-black hover:dark:bg-[#15AFD04C] hover:dark:text-[#82E9FF] text-gray-500 dark:text-[#7F818C] outline-none focus-visible:ring transition`}
|
<h1 className="break-words text-4xl font-bold mt-6 mb-4">{post.title}</h1>
|
||||||
>
|
{post.image && (
|
||||||
{tag.trim()}
|
<img src={post.image} alt={post.title} className="rounded-sm" />
|
||||||
</div>
|
)}
|
||||||
);
|
{post.tags && post.tags.split(",").length ? (
|
||||||
})}
|
<div className="flex flex-wrap gap-2">
|
||||||
</div>
|
{post.tags.split(",").map((tag) => {
|
||||||
) : (
|
return (
|
||||||
<></>
|
<div
|
||||||
)}
|
key={tag}
|
||||||
{post.description && <Callout>{post.description}</Callout>}
|
className={`rounded-md bg-gray-200 hover:!no-underline dark:bg-[#24272E] flex px-2.5 py-1.5 text-sm font-medium transition-colors hover:text-black hover:dark:bg-[#15AFD04C] hover:dark:text-[#82E9FF] text-gray-500 dark:text-[#7F818C] outline-none focus-visible:ring transition`}
|
||||||
<MDXRemote source={post?.content || ""} components={MDXComponents} />
|
>
|
||||||
|
{tag.trim()}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<></>
|
||||||
|
)}
|
||||||
|
{post.description && <Callout>{post.description}</Callout>}
|
||||||
|
<MDXRemote source={post?.content || ""} components={MDXComponents} />
|
||||||
|
</article>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateStaticParams() {
|
// export async function generateStaticParams() {
|
||||||
let posts = (await getPosts()).posts;
|
// let post = (await getPostDetail());
|
||||||
|
|
||||||
|
// // Filter out posts without a slug
|
||||||
|
// posts = posts.filter((post) => post.slug);
|
||||||
|
|
||||||
// Filter out posts without a slug
|
// return LOCALES.flatMap((locale) =>
|
||||||
posts = posts.filter((post) => post.slug);
|
// posts.map((post) => {
|
||||||
|
// const slugPart = post.slug.replace(/^\//, "").replace(/^blog\//, "");
|
||||||
|
|
||||||
return LOCALES.flatMap((locale) =>
|
// return {
|
||||||
posts.map((post) => {
|
// locale,
|
||||||
const slugPart = post.slug.replace(/^\//, "").replace(/^blog\//, "");
|
// slug: slugPart,
|
||||||
|
// };
|
||||||
return {
|
// })
|
||||||
locale,
|
// );
|
||||||
slug: slugPart,
|
// }
|
||||||
};
|
|
||||||
})
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,11 +6,11 @@ export default function Home() {
|
|||||||
return <HomeComponent />;
|
return <HomeComponent />;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function generateStaticParams() {
|
// export async function generateStaticParams() {
|
||||||
return [
|
// return [
|
||||||
{ locale: 'en' },
|
// { locale: 'en' },
|
||||||
{ locale: 'zh' },
|
// { locale: 'zh' },
|
||||||
{ locale: 'vi' },
|
// { locale: 'vi' },
|
||||||
// { locale: 'ja' },
|
// // { locale: 'ja' },
|
||||||
]
|
// ]
|
||||||
}
|
// }
|
||||||
|
|||||||
@@ -16,13 +16,13 @@ const WebsiteLogo = ({
|
|||||||
timeout = 1000, // 1 second
|
timeout = 1000, // 1 second
|
||||||
}: IProps) => {
|
}: IProps) => {
|
||||||
const domain = getDomain(url);
|
const domain = getDomain(url);
|
||||||
const [imgSrc, setImgSrc] = useState(`https://${domain}/logo.svg`);
|
const [imgSrc, setImgSrc] = useState(`https://${domain}/logo.png`);
|
||||||
const [fallbackIndex, setFallbackIndex] = useState(0);
|
const [fallbackIndex, setFallbackIndex] = useState(0);
|
||||||
const [isLoading, setIsLoading] = useState(true);
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
const [hasError, setHasError] = useState(false);
|
const [hasError, setHasError] = useState(false);
|
||||||
|
|
||||||
const fallbackSources = [
|
const fallbackSources = [
|
||||||
`https://${domain}/logo.svg`,
|
`https://${domain}/logo.png`,
|
||||||
`https://${domain}/logo.png`,
|
`https://${domain}/logo.png`,
|
||||||
`https://${domain}/apple-touch-icon.png`,
|
`https://${domain}/apple-touch-icon.png`,
|
||||||
`https://${domain}/apple-touch-icon-precomposed.png`,
|
`https://${domain}/apple-touch-icon-precomposed.png`,
|
||||||
@@ -83,9 +83,8 @@ const WebsiteLogo = ({
|
|||||||
height={size}
|
height={size}
|
||||||
onError={handleError}
|
onError={handleError}
|
||||||
onLoad={handleLoad}
|
onLoad={handleLoad}
|
||||||
className={`inline-block transition-opacity duration-300 ${
|
className={`inline-block transition-opacity duration-300 ${isLoading ? "opacity-0" : "opacity-100"
|
||||||
isLoading ? "opacity-0" : "opacity-100"
|
}`}
|
||||||
}`}
|
|
||||||
style={{
|
style={{
|
||||||
objectFit: "contain",
|
objectFit: "contain",
|
||||||
display: hasError ? "none" : "inline-block",
|
display: hasError ? "none" : "inline-block",
|
||||||
|
|||||||
@@ -20,7 +20,7 @@ const Header = () => {
|
|||||||
>
|
>
|
||||||
<Image
|
<Image
|
||||||
alt={siteConfig.name}
|
alt={siteConfig.name}
|
||||||
src="/logo.svg"
|
src="/logo.png"
|
||||||
className="w-6 h-6"
|
className="w-6 h-6"
|
||||||
width={32}
|
width={32}
|
||||||
height={32}
|
height={32}
|
||||||
|
|||||||
104
components/mdx/TableOfContents.client.tsx
Normal file
104
components/mdx/TableOfContents.client.tsx
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
// components/mdx/TableOfContents.client.tsx
|
||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
interface TableOfContentsItem {
|
||||||
|
id: string;
|
||||||
|
text: string;
|
||||||
|
level: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TableOfContentsProps {
|
||||||
|
items: TableOfContentsItem[];
|
||||||
|
title?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function TableOfContents({
|
||||||
|
items = [],
|
||||||
|
title = "目录"
|
||||||
|
}: TableOfContentsProps) {
|
||||||
|
const [activeId, setActiveId] = useState<string>("");
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (items.length === 0) return;
|
||||||
|
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
entries.forEach((entry) => {
|
||||||
|
if (entry.isIntersecting) {
|
||||||
|
setActiveId(entry.target.id);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
{ rootMargin: "0% 0% -80% 0%" }
|
||||||
|
);
|
||||||
|
|
||||||
|
// 观察所有标题元素
|
||||||
|
items.forEach((item) => {
|
||||||
|
const element = document.getElementById(item.id);
|
||||||
|
if (element) {
|
||||||
|
observer.observe(element);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
items.forEach((item) => {
|
||||||
|
const element = document.getElementById(item.id);
|
||||||
|
if (element) {
|
||||||
|
observer.unobserve(element);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}, [items]);
|
||||||
|
|
||||||
|
const handleClick = (e: React.MouseEvent, id: string) => {
|
||||||
|
e.preventDefault();
|
||||||
|
const element = document.getElementById(id);
|
||||||
|
if (element) {
|
||||||
|
element.scrollIntoView({ behavior: "smooth" });
|
||||||
|
window.history.pushState(null, "", `#${id}`);
|
||||||
|
setActiveId(id);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!items || items.length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<aside className="fixed left-0 top-0 w-64 h-screen border-r border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 z-10 overflow-y-auto">
|
||||||
|
<div className="p-6">
|
||||||
|
<h3 className="text-lg font-semibold mb-4 text-gray-800 dark:text-gray-200">
|
||||||
|
{title}
|
||||||
|
</h3>
|
||||||
|
<nav>
|
||||||
|
<ul className="space-y-2 border-l-2 border-gray-200 dark:border-gray-700">
|
||||||
|
{items.map((item) => {
|
||||||
|
const isActive = activeId === item.id;
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={item.id}
|
||||||
|
style={{ marginLeft: `${(item.level - 2) * 0.75}rem` }}
|
||||||
|
className={`text-sm border-l-2 -ml-0.5 pl-4 transition-colors duration-200 ${isActive
|
||||||
|
? "border-blue-500 text-blue-600 dark:text-blue-400 font-medium"
|
||||||
|
: "border-transparent hover:border-blue-400"
|
||||||
|
} hover:text-blue-600 dark:hover:text-blue-400 cursor-pointer`}
|
||||||
|
>
|
||||||
|
<a
|
||||||
|
href={`#${item.id}`}
|
||||||
|
className={`block py-1 transition-all duration-200 ${isActive ? "translate-x-1" : "hover:translate-x-1"
|
||||||
|
}`}
|
||||||
|
onClick={(e) => handleClick(e, item.id)}
|
||||||
|
>
|
||||||
|
{item.text}
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
);
|
||||||
|
}
|
||||||
23
lib/getBlogDetail.ts
Normal file
23
lib/getBlogDetail.ts
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
import { BlogPost } from '@/types/blog';
|
||||||
|
|
||||||
|
export async function getPostDetail(articleId: string): Promise<BlogPost> {
|
||||||
|
let url = 'http://49.232.154.205:18081/export/article/' + articleId
|
||||||
|
|
||||||
|
const response = await fetch(url);
|
||||||
|
const json = await response.json();
|
||||||
|
const data = json.data;
|
||||||
|
const post = {
|
||||||
|
locale: data.langCode,
|
||||||
|
title: data.title,
|
||||||
|
description: data.summary,
|
||||||
|
image: data.cover || '',
|
||||||
|
slug: data.articleId,
|
||||||
|
tags: '',
|
||||||
|
date: data.publishedTime,
|
||||||
|
// visible: data.visible || 'published',
|
||||||
|
pin: false,
|
||||||
|
content: data.content,
|
||||||
|
metadata: data,
|
||||||
|
}
|
||||||
|
return post;
|
||||||
|
}
|
||||||
2
next-env.d.ts
vendored
2
next-env.d.ts
vendored
@@ -1,6 +1,6 @@
|
|||||||
/// <reference types="next" />
|
/// <reference types="next" />
|
||||||
/// <reference types="next/image-types/global" />
|
/// <reference types="next/image-types/global" />
|
||||||
import "./.next/dev/types/routes.d.ts";
|
import "./.next/types/routes.d.ts";
|
||||||
|
|
||||||
// NOTE: This file should not be edited
|
// NOTE: This file should not be edited
|
||||||
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||||
|
|||||||
BIN
public/logo.png
BIN
public/logo.png
Binary file not shown.
|
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 1.7 KiB |
Reference in New Issue
Block a user