feat: 添加 GiscusComments 组件,支持文章评论功能

This commit is contained in:
joyzhao
2026-01-09 09:07:41 +08:00
parent 4bf7dd83f9
commit 1c9f154652
2 changed files with 58 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
import Giscus from '@giscus/react';
import type { Lang } from '@/types/i18n';
import { useEffect, useState } from 'react';
export interface GiscusCommentsProps {
lang?: Lang;
}
export default function GiscusComments({ lang = 'en' }: GiscusCommentsProps) {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
const [term, setTerm] = useState<string>('');
const giscusLang = lang === 'zh' ? 'zh-CN' : lang;
useEffect(() => {
const getTheme = () => document.documentElement.classList.contains('dark') ? 'dark' : 'light';
const pathname = window.location.pathname;
const postsMatch = pathname.match(/\/posts\/([^/]+)/);
const discussionTerm = postsMatch ? postsMatch[1] : pathname;
setTheme(getTheme());
setTerm(discussionTerm);
const observer = new MutationObserver(() => {
setTheme(getTheme());
});
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['class'] });
return () => observer.disconnect();
}, []);
return (
<Giscus
repo="zguiyang/blog-giscus"
repoId="R_kgDOQ2Wnxw"
category="Announcements"
categoryId="DIC_kwDOQ2Wnx84C0vSJ"
mapping="specific"
term={term}
strict="0"
reactionsEnabled="1"
emitMetadata="0"
inputPosition="top"
theme={theme}
lang={giscusLang}
loading="lazy"
/>
);
}