-
Notifications
You must be signed in to change notification settings - Fork 0
feat(blog): giscus 기반 댓글 기능 #79
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
c1fbb8c
feat(blog): giscus 기반 댓글 기능 추가 (이슈 #57)
SimYunSup 3abe792
fix(giscus): 단일 마운트 + setConfig로 리스너 누수·테마 레이스 해소 (이슈 #57)
SimYunSup fb8cdd2
fix(giscus): lint 에러 수정 + 주석 다듬기 (이슈 #57)
SimYunSup 9e7fa0c
ci(giscus): 빌드 스텝에 VITE_GISCUS_*_ID 주입 (이슈 #57)
SimYunSup 762fbfd
fix(giscus): 기존 블로그 discussion에 number 매핑으로 연결 (이슈 #57)
SimYunSup 375f02f
refactor(giscus): 직접 구현 대신 공식 @giscus/react로 교체 (이슈 #57)
SimYunSup b8a866c
refactor(giscus): 설정값 하드코딩, CI VITE_GISCUS_* 주입 제거 (이슈 #57)
SimYunSup File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| import { useEffect, useRef } from "react"; | ||
| import { useTheme } from "../hooks/useTheme"; | ||
| import { | ||
| GISCUS_ORIGIN, | ||
| GISCUS_SCRIPT_SRC, | ||
| buildGiscusAttributes, | ||
| giscusConfig, | ||
| } from "../constants/giscus"; | ||
|
|
||
| interface GiscusProps { | ||
| /** 댓글을 붙일 글의 discussion 번호(= slug). */ | ||
| term: string; | ||
| } | ||
|
|
||
| /** | ||
| * giscus 댓글 위젯. | ||
| * | ||
| * 글마다 재마운트하면(key={slug}) client.js가 다시 실행되면서 window에 걸리는 | ||
| * message 리스너가 계속 쌓인다. 그래서 한 번만 마운트하고, 글·테마가 바뀌면 | ||
| * iframe에 setConfig 메시지를 보내 갱신한다. | ||
| */ | ||
| export function Giscus({ term }: GiscusProps) { | ||
| const containerRef = useRef<HTMLDivElement>(null); | ||
| const { isDark } = useTheme(); | ||
| const theme = isDark ? "dark" : "light"; | ||
|
|
||
| // iframe이 늦게 떴을 때 load 시점에 다시 보낼 최신 설정. | ||
| const configRef = useRef({ theme, number: Number(term) }); | ||
|
|
||
| useEffect(() => { | ||
| const container = containerRef.current; | ||
| if (!container) return; | ||
|
|
||
| if ( | ||
| import.meta.env.DEV && | ||
| (!giscusConfig.repoId || !giscusConfig.categoryId) | ||
| ) { | ||
| console.warn( | ||
| "[giscus] VITE_GISCUS_REPO_ID / VITE_GISCUS_CATEGORY_ID가 비어 있어 댓글 위젯이 뜨지 않습니다.", | ||
| ); | ||
| } | ||
|
|
||
| const sendConfig = () => { | ||
| const iframe = container.querySelector<HTMLIFrameElement>( | ||
| "iframe.giscus-frame", | ||
| ); | ||
| iframe?.contentWindow?.postMessage( | ||
| { giscus: { setConfig: configRef.current } }, | ||
| GISCUS_ORIGIN, | ||
| ); | ||
| }; | ||
|
|
||
| // client.js가 iframe을 비동기로 만든다. 만들어지면 load 때 현재 설정을 다시 | ||
| // 보내, 로딩 중에 테마나 글이 바뀌어도 어긋나지 않게 한다. | ||
| const observer = new MutationObserver(() => { | ||
| const iframe = container.querySelector<HTMLIFrameElement>( | ||
| "iframe.giscus-frame", | ||
| ); | ||
| if (!iframe) return; | ||
| observer.disconnect(); | ||
| iframe.addEventListener("load", sendConfig); | ||
| }); | ||
| observer.observe(container, { childList: true }); | ||
|
|
||
| const script = document.createElement("script"); | ||
| script.src = GISCUS_SCRIPT_SRC; | ||
| script.async = true; | ||
| script.crossOrigin = "anonymous"; | ||
| for (const [name, value] of Object.entries( | ||
| buildGiscusAttributes(theme, term), | ||
| )) { | ||
| script.setAttribute(name, value); | ||
| } | ||
| container.appendChild(script); | ||
|
|
||
| return () => { | ||
| observer.disconnect(); | ||
| container.replaceChildren(); | ||
| }; | ||
| // 마운트 때 한 번만 실행한다. theme·term 변경은 아래 effect가 맡는다. | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, []); | ||
|
|
||
| // 글이나 테마가 바뀌면 위젯에 반영한다. | ||
| useEffect(() => { | ||
| const config = { theme, number: Number(term) }; | ||
| configRef.current = config; | ||
| const iframe = containerRef.current?.querySelector<HTMLIFrameElement>( | ||
| "iframe.giscus-frame", | ||
| ); | ||
| iframe?.contentWindow?.postMessage( | ||
| { giscus: { setConfig: config } }, | ||
| GISCUS_ORIGIN, | ||
| ); | ||
| }, [theme, term]); | ||
|
|
||
| return <div ref={containerRef} className="giscus" />; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,37 @@ | ||
| import { describe, expect, it } from "vitest"; | ||
| import { buildGiscusAttributes, giscusConfig } from "./giscus"; | ||
|
|
||
| describe("buildGiscusAttributes", () => { | ||
| it("설정 상수를 data 속성으로 전달한다", () => { | ||
| const attrs = buildGiscusAttributes("light", "682"); | ||
|
|
||
| expect(attrs["data-repo"]).toBe(giscusConfig.repo); | ||
| expect(attrs["data-repo-id"]).toBe(giscusConfig.repoId); | ||
| expect(attrs["data-category"]).toBe(giscusConfig.category); | ||
| expect(attrs["data-category-id"]).toBe(giscusConfig.categoryId); | ||
| }); | ||
|
|
||
| it("글의 discussion 번호로 매핑한다", () => { | ||
| const attrs = buildGiscusAttributes("light", "682"); | ||
|
|
||
| expect(attrs["data-mapping"]).toBe("number"); | ||
| expect(attrs["data-term"]).toBe("682"); | ||
| }); | ||
|
|
||
| it("언어는 ko로 고정한다", () => { | ||
| expect(buildGiscusAttributes("light", "1")["data-lang"]).toBe("ko"); | ||
| }); | ||
|
|
||
| it("반응·입력 위치 등 고정 옵션을 설정한다", () => { | ||
| const attrs = buildGiscusAttributes("light", "1"); | ||
|
|
||
| expect(attrs["data-reactions-enabled"]).toBe("1"); | ||
| expect(attrs["data-emit-metadata"]).toBe("0"); | ||
| expect(attrs["data-input-position"]).toBe("bottom"); | ||
| }); | ||
|
|
||
| it("테마 인자를 data-theme에 반영한다", () => { | ||
| expect(buildGiscusAttributes("light", "1")["data-theme"]).toBe("light"); | ||
| expect(buildGiscusAttributes("dark", "1")["data-theme"]).toBe("dark"); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| // giscus 댓글 위젯 설정값. | ||
| // 블로그 글은 DaleStudy/daleui "블로그" 카테고리 Discussion에서 오고 slug가 곧 | ||
| // discussion 번호라, mapping=number로 글마다 원본 토론에 그대로 연결한다. | ||
| // repo-id·category-id는 공개돼도 되는 값이라 상수로 두되 VITE_GISCUS_* 로 덮어쓸 수 있다. | ||
| export const giscusConfig = { | ||
| repo: (import.meta.env.VITE_GISCUS_REPO ?? | ||
| "DaleStudy/daleui") as `${string}/${string}`, | ||
| repoId: import.meta.env.VITE_GISCUS_REPO_ID ?? "R_kgDOMovgOA", | ||
| category: import.meta.env.VITE_GISCUS_CATEGORY ?? "블로그", | ||
| categoryId: import.meta.env.VITE_GISCUS_CATEGORY_ID ?? "DIC_kwDOMovgOM4CqB1o", | ||
| } as const; | ||
|
|
||
| export const GISCUS_SCRIPT_SRC = "https://giscus.app/client.js"; | ||
| export const GISCUS_ORIGIN = "https://giscus.app"; | ||
|
|
||
| export type GiscusTheme = "light" | "dark"; | ||
|
|
||
| /** client.js `<script>`에 붙일 `data-*` 속성. term은 글의 discussion 번호다. */ | ||
| export function buildGiscusAttributes( | ||
| theme: GiscusTheme, | ||
| term: string, | ||
| ): Record<string, string> { | ||
| return { | ||
| "data-repo": giscusConfig.repo, | ||
| "data-repo-id": giscusConfig.repoId, | ||
| "data-category": giscusConfig.category, | ||
| "data-category-id": giscusConfig.categoryId, | ||
| "data-mapping": "number", | ||
| "data-term": term, | ||
| "data-reactions-enabled": "1", | ||
| "data-emit-metadata": "0", | ||
| "data-input-position": "bottom", | ||
| "data-theme": theme, | ||
| "data-lang": "ko", | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
giscus component lib를 사용하시는줄 알았는데 직접 구현하셨네요 특별한 이유가 있을까요?
https://github.com/giscus/giscus-component
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아, 예전에 만들었던 기억에 의존하다보니 있다는걸 몰랐네요 😅