|
| 1 | +import React, { useEffect, useRef } from "react" |
| 2 | + |
| 3 | +const Utterances: React.FC = () => { |
| 4 | + const commentsRef = useRef<HTMLDivElement>(null) |
| 5 | + |
| 6 | + useEffect(() => { |
| 7 | + if (!commentsRef.current) return |
| 8 | + |
| 9 | + // 현재 테마 감지 |
| 10 | + const isDark = document.documentElement.classList.contains("dark") |
| 11 | + const theme = isDark ? "github-dark" : "github-light" |
| 12 | + |
| 13 | + // 기존 스크립트 제거 |
| 14 | + commentsRef.current.innerHTML = "" |
| 15 | + |
| 16 | + // Utterances 스크립트 생성 |
| 17 | + const script = document.createElement("script") |
| 18 | + script.src = "https://utteranc.es/client.js" |
| 19 | + script.setAttribute("repo", "pjj186/blog-comments") |
| 20 | + script.setAttribute("issue-term", "pathname") |
| 21 | + script.setAttribute("theme", theme) |
| 22 | + script.setAttribute("crossorigin", "anonymous") |
| 23 | + script.async = true |
| 24 | + |
| 25 | + commentsRef.current.appendChild(script) |
| 26 | + |
| 27 | + // 테마 변경 감지 함수 |
| 28 | + const handleThemeChange = () => { |
| 29 | + const iframe = |
| 30 | + document.querySelector<HTMLIFrameElement>(".utterances-frame") |
| 31 | + if (iframe && iframe.contentWindow) { |
| 32 | + const newTheme = document.documentElement.classList.contains("dark") |
| 33 | + ? "github-dark" |
| 34 | + : "github-light" |
| 35 | + |
| 36 | + const message = { |
| 37 | + type: "set-theme", |
| 38 | + theme: newTheme, |
| 39 | + } |
| 40 | + iframe.contentWindow.postMessage(message, "https://utteranc.es") |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + // 테마 변경 감지를 위한 MutationObserver |
| 45 | + const observer = new MutationObserver(handleThemeChange) |
| 46 | + observer.observe(document.documentElement, { |
| 47 | + attributes: true, |
| 48 | + attributeFilter: ["class"], |
| 49 | + }) |
| 50 | + |
| 51 | + return () => { |
| 52 | + observer.disconnect() |
| 53 | + } |
| 54 | + }, []) |
| 55 | + |
| 56 | + return ( |
| 57 | + <div className="mt-16 pt-8 border-t"> |
| 58 | + <h3 className="text-xl font-semibold mb-6">댓글</h3> |
| 59 | + <div ref={commentsRef} className="utterances-container" /> |
| 60 | + </div> |
| 61 | + ) |
| 62 | +} |
| 63 | + |
| 64 | +export default Utterances |
0 commit comments