feat: 添加 GiscusComments 组件,支持文章评论功能
This commit is contained in:
52
src/components/blog/GiscusComments.tsx
Normal file
52
src/components/blog/GiscusComments.tsx
Normal 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"
|
||||
/>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user