tailwind-nextjs-blog/components/comments/Giscus.tsx

79 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-10-17 23:37:01 +08:00
import React, { useState, useEffect, useCallback } from 'react';
import { useTheme } from 'next-themes';
2022-07-17 21:40:41 +08:00
2022-10-17 23:37:01 +08:00
import siteMetadata from '@/data/siteMetadata';
2022-07-17 21:40:41 +08:00
interface Props {
2022-10-17 23:37:01 +08:00
mapping: string;
}
const Giscus = ({ mapping }: Props) => {
2022-10-17 23:37:01 +08:00
const [enableLoadComments, setEnabledLoadComments] = useState(true);
const { theme, resolvedTheme } = useTheme();
2022-07-17 21:40:41 +08:00
const commentsTheme =
siteMetadata.comment.giscusConfig.themeURL === ''
? theme === 'dark' || resolvedTheme === 'dark'
? siteMetadata.comment.giscusConfig.darkTheme
: siteMetadata.comment.giscusConfig.theme
2022-10-17 23:37:01 +08:00
: siteMetadata.comment.giscusConfig.themeURL;
2022-07-17 21:40:41 +08:00
2022-10-17 23:37:01 +08:00
const COMMENTS_ID = 'comments-container';
2022-07-17 21:40:41 +08:00
const LoadComments = useCallback(() => {
2022-10-17 23:37:01 +08:00
setEnabledLoadComments(false);
const script = document.createElement('script');
script.src = 'https://giscus.app/client.js';
script.setAttribute('data-repo', siteMetadata.comment.giscusConfig.repo);
script.setAttribute(
'data-repo-id',
siteMetadata.comment.giscusConfig.repositoryId
);
script.setAttribute(
'data-category',
siteMetadata.comment.giscusConfig.category
);
script.setAttribute(
'data-category-id',
siteMetadata.comment.giscusConfig.categoryId
);
script.setAttribute('data-mapping', mapping);
script.setAttribute(
'data-reactions-enabled',
siteMetadata.comment.giscusConfig.reactions
);
script.setAttribute(
'data-emit-metadata',
siteMetadata.comment.giscusConfig.metadata
);
script.setAttribute('data-theme', commentsTheme);
script.setAttribute('crossorigin', 'anonymous');
script.async = true;
const comments = document.getElementById(COMMENTS_ID);
if (comments) comments.appendChild(script);
2022-07-17 21:40:41 +08:00
return () => {
2022-10-17 23:37:01 +08:00
const comments = document.getElementById(COMMENTS_ID);
if (comments) comments.innerHTML = '';
};
}, [commentsTheme, mapping]);
2022-07-17 21:40:41 +08:00
// Reload on theme change
useEffect(() => {
2022-10-17 23:37:01 +08:00
const iframe = document.querySelector('iframe.giscus-frame');
if (!iframe) return;
LoadComments();
}, [LoadComments]);
2022-07-17 21:40:41 +08:00
return (
<div className="pt-6 pb-6 text-center text-gray-700 dark:text-gray-300">
2022-10-17 23:37:01 +08:00
{enableLoadComments && (
<button onClick={LoadComments}>Load Comments</button>
)}
2022-07-17 21:40:41 +08:00
<div className="giscus" id={COMMENTS_ID} />
</div>
2022-10-17 23:37:01 +08:00
);
};
2022-07-17 21:40:41 +08:00
2022-10-17 23:37:01 +08:00
export default Giscus;