From c6370470b6f09be6d7d13a8185b20abd2b85884a Mon Sep 17 00:00:00 2001 From: Rylan <1217013295@qq.com> Date: Fri, 12 Jan 2024 05:37:11 +0800 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=90=9B=20Twikoo=20+=20Utterances=20?= =?UTF-8?q?=E8=AF=84=E8=AE=BA=E6=8F=92=E4=BB=B6=E8=A1=A5=E4=B8=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/Utterances.js | 61 +++++++++++++++++++++++++++------------- styles/globals.css | 5 ++++ 2 files changed, 46 insertions(+), 20 deletions(-) diff --git a/components/Utterances.js b/components/Utterances.js index 3524c646..34c4f09c 100644 --- a/components/Utterances.js +++ b/components/Utterances.js @@ -1,5 +1,6 @@ +import { useEffect, useState } from 'react' import { siteConfig } from '@/lib/config' -import { useEffect } from 'react' +import { useGlobal } from '@/lib/global' /** * 评论插件 @@ -9,28 +10,48 @@ import { useEffect } from 'react' * @constructor */ const Utterances = ({ issueTerm, layout }) => { + const { isDarkMode } = useGlobal() + + const [isLoading, setLoading] = useState(true); + useEffect(() => { - const theme = - siteConfig('APPEARANCE') === 'auto' - ? 'preferred-color-scheme' - : siteConfig('APPEARANCE') === 'light' - ? 'github-light' - : 'github-dark' - const script = document.createElement('script') - const anchor = document.getElementById('comments') - script.setAttribute('src', 'https://utteranc.es/client.js') - script.setAttribute('crossorigin', 'anonymous') - script.setAttribute('async', true) - script.setAttribute('repo', siteConfig('COMMENT_UTTERRANCES_REPO')) - script.setAttribute('issue-term', 'title') - script.setAttribute('theme', theme) - anchor.appendChild(script) + const script = document.createElement('script'); + const anchor = document.getElementById('comments'); + script.onload = () => setLoading(false); + script.setAttribute('src', 'https://utteranc.es/client.js'); + script.setAttribute('crossorigin', 'anonymous'); + script.setAttribute('async', true); + script.setAttribute('repo', siteConfig('COMMENT_UTTERRANCES_REPO')); + script.setAttribute('issue-term', 'title'); + // 初始主题 + script.setAttribute('theme', isDarkMode ? 'github-dark' : 'github-light'); + anchor.appendChild(script); + return () => { - anchor.innerHTML = '' + // anchor.innerHTML = '' + }; + }, []); + + useEffect(() => { + // 直接设置 iframe 的类来改变主题,不重新加载脚本 + const iframe = document.querySelector('iframe.utterances-frame'); + if (iframe) { + iframe.contentWindow.postMessage({ + type: 'set-theme', + theme: isDarkMode ? 'github-dark' : 'github-light' + }, 'https://utteranc.es'); } - }) - return