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

59 lines
1.9 KiB
TypeScript
Raw Permalink 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
issueTerm: string;
}
const Utterances = ({ issueTerm }: 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 =
theme === 'dark' || resolvedTheme === 'dark'
? siteMetadata.comment.utterancesConfig.darkTheme
2022-10-17 23:37:01 +08:00
: siteMetadata.comment.utterancesConfig.theme;
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://utteranc.es/client.js';
script.setAttribute('repo', siteMetadata.comment.utterancesConfig.repo);
script.setAttribute('issue-term', issueTerm);
script.setAttribute('label', siteMetadata.comment.utterancesConfig.label);
script.setAttribute('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, issueTerm]);
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.utterances-frame');
if (!iframe) return;
LoadComments();
}, [LoadComments]);
2022-07-17 21:40:41 +08:00
// Added `relative` to fix a weird bug with `utterances-frame` position
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="utterances-frame relative" 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 Utterances;