Discourse Gamification Plugin in the Header

It is a temporary but useful method. Maybe they want to improve it, I leave the code here

Test website: 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("User not logged in");
            return;
        }

        fetch(`/u/${currentUser.username}.json`)
            .then(response => response.json())
            .then(data => {
                console.log("Gamification Data:", data);
                let score = data?.user?.gamification_score ?? 0;

                // Eğer puan kutusu zaten varsa tekrar ekleme
                if (document.querySelector("#gamification-score")) return;

                // Header'ın .contents kapsayıcısını bul
                let headerContents = document.querySelector(".d-header>.wrap .contents");
                if (headerContents) {
                    // Puan kutusunu oluştur
                    let scoreContainer = document.createElement("a");
                    scoreContainer.id = "gamification-score";
                    scoreContainer.classList.add("gamification-box");
                    scoreContainer.href = "website";
                    scoreContainer.target = "_blank"; // Yeni sekmede aç

                    // Altın simge
                    let icon = document.createElement("span");
                    icon.innerText = "T";
                    icon.classList.add("gold-icon");

                    // Puan metni
                    let scoreText = document.createElement("span");
                    scoreText.innerText = `${score}`;
                    scoreText.classList.add("gold-text");

                    // Simge ve metni kutuya ekle
                    scoreContainer.appendChild(icon);
                    scoreContainer.appendChild(scoreText);

                    // Kutuyu header'a ekle
                    headerContents.appendChild(scoreContainer);
                }
            })
            .catch(error => console.error("Error fetching gamification score:", error));
    });
});
4 Likes