헤더에 있는 Discourse Gamification 플러그인

일시적이지만 유용한 방법입니다. 개선하려는 것일 수도 있으니, 여기 코드를 남겨두겠습니다.

테스트 웹사이트: https://trgala.com

Js

import { apiInitializer } from "discourse/lib/api";

export default apiInitializer("0.8", (api) => {
    api.onPageChange(() => {
        const currentUser = api.getCurrentUser();
        if (!currentUser) {
            console.warn("사용자가 로그인되지 않았습니다");
            return;
        }

        fetch(`/u/${currentUser.username}.json`)
            .then(response => response.json())
            .then(data => {
                console.log("게임화 데이터:", data);
                let score = data?.user?.gamification_score ?? 0;

                // 이미 점수 상자가 있으면 다시 추가하지 않음
                if (document.querySelector("#gamification-score")) return;

                // 헤더의 .contents 컨테이너 찾기
                let headerContents = document.querySelector(".d-header>.wrap .contents");
                if (headerContents) {
                    // 점수 상자 생성
                    let scoreContainer = document.createElement("a");
                    scoreContainer.id = "gamification-score";
                    scoreContainer.classList.add("gamification-box");
                    scoreContainer.href = "website";
                    scoreContainer.target = "_blank"; // 새 탭에서 열기

                    // 금색 아이콘
                    let icon = document.createElement("span");
                    icon.innerText = "T";
                    icon.classList.add("gold-icon");

                    // 점수 텍스트
                    let scoreText = document.createElement("span");
                    scoreText.innerText = `${score}`;
                    scoreText.classList.add("gold-text");

                    // 아이콘과 텍스트를 상자에 추가
                    scoreContainer.appendChild(icon);
                    scoreContainer.appendChild(scoreText);

                    // 상자를 헤더에 추가
                    headerContents.appendChild(scoreContainer);
                }
            })
            .catch(error => console.error("게임화 점수 가져오기 오류:", error));
    });
});