MediaWiki:TeamBingo.js: Difference between revisions

From Roat Pkz
Jump to navigation Jump to search
No edit summary
Tag: Reverted
No edit summary
Tag: Manual revert
Line 1: Line 1:
// --- Team Bingo Board with Real-Time Updates ---
// --- Team Bingo Board with Captains and Shared JSON ---
mw.hook('wikipage.content').add(function () {
mw.hook('wikipage.content').add(function () {


    const currentUser = mw.config.get('wgUserName'); // Logged-in user
    // Select all team bingo containers
     const containers = document.querySelectorAll(".teamBingoContainer");
     const containers = document.querySelectorAll(".teamBingoContainer");
     if (!containers.length) return;
     if (!containers.length) return;
Line 8: Line 11:
     const infoBox = document.getElementById("teamBingoInfoBox");
     const infoBox = document.getElementById("teamBingoInfoBox");


     // Polling interval (ms)
     // Fetch the JSON data from the Module page
    const POLL_INTERVAL = 5000;
    function fetchBoardData(callback) {
        $.getJSON(mw.util.wikiScript('api'), {
            action: 'query',
            titles: 'Module:TeamBingo/data.json',
            prop: 'revisions',
            rvprop: 'content',
            format: 'json',
            formatversion: 2
        }).done(function(data){
            if (!data.query.pages[0].revisions) return;
            const content = data.query.pages[0].revisions[0].content;
            try {
                const boardData = JSON.parse(content);
                callback(boardData);
            } catch(e) {
                console.error("Failed to parse JSON from Module:TeamBingo/data.json", e);
            }
        });
    }
 
    // Render the board for a container
    function renderBoard(container, teamKey, boardData) {


    containers.forEach(container => {
         container.innerHTML = "";
         container.innerHTML = "";


         const captain = container.getAttribute("data-captain"); // Wiki username
        // Get captain username
        const teamKey = container.id; // "teamA" or "teamB"
         const captain = container.getAttribute("data-captain");


         // Parse items
         // Parse items: Item Name::Tooltip (%% for line breaks)
         const itemsAttr = container.getAttribute("data-items");
         const itemsAttr = container.getAttribute("data-items");
         if (!itemsAttr) return;
         if (!itemsAttr) return;
         const items = itemsAttr.split("|").filter(i => i.trim() !== "");
         const items = itemsAttr.split("|").filter(i => i.trim() !== "");
        if (!items.length) return;
         const parsedItems = items.map(entry => {
         const parsedItems = items.map(entry => {
             const parts = entry.split("::");
             const parts = entry.split("::");
Line 38: Line 63:
         const cols = Math.ceil(parsedItems.length / rows);
         const cols = Math.ceil(parsedItems.length / rows);


         // Store references to cells for live updates
         // Single API call for images
         const cellRefs = [];
         const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
        $.getJSON("/api.php", {
            action: "parse",
            text: allTemplates,
            format: "json"
        }).done(function(data) {
            if (!data.parse || !data.parse.text) return;


        for (let r = 0; r < rows; r++) {
             const tempDiv = document.createElement("div");
             const row = table.insertRow();
             tempDiv.innerHTML = data.parse.text["*"];
             for (let c = 0; c < cols; c++) {
            const imgs = tempDiv.querySelectorAll("img");
                const index = r * cols + c;
                if (index >= parsedItems.length) break;


                const item = parsedItems[index];
            for (let r = 0; r < rows; r++) {
                 const cell = row.insertCell();
                 const row = table.insertRow();
                 cell.style.width = `${100 / cols}%`;
                 for (let c = 0; c < cols; c++) {
                cell.style.padding = "10px";
                    const index = r * cols + c;
                cell.style.border = "1px solid #596e96";
                    if (index >= parsedItems.length) break;
                cell.style.textAlign = "center";
                cell.style.background = "#313e59";
                cell.style.color = "#fff";
                cell.style.cursor = "pointer";
                cell.style.transition = "all 0.2s ease";
                cell.style.userSelect = "none";
                cell.style.wordWrap = "break-word";
                cell.style.overflow = "visible";
                cell.style.position = "relative";
                cell.id = `${teamKey}_tile_${index}`;


                // Cell container
                    const item = parsedItems[index];
                const containerDiv = document.createElement("div");
                    const cell = row.insertCell();
                containerDiv.style.position = "relative";
                    cell.style.width = `${100 / cols}%`;
                containerDiv.style.width = "100%";
                    cell.style.padding = "10px";
                containerDiv.style.height = "100%";
                    cell.style.border = "1px solid #596e96";
                    cell.style.textAlign = "center";
                    cell.style.background = "#313e59";
                    cell.style.color = "#fff";
                    cell.style.cursor = "pointer";
                    cell.style.transition = "all 0.2s ease";
                    cell.style.userSelect = "none";
                    cell.style.wordWrap = "break-word";
                    cell.style.overflow = "visible";
                    cell.style.position = "relative";


                // Image placeholder
                    const id = `${container.id}_cell_${index}`;
                const imgDiv = document.createElement("img");
                    cell.id = id;
                imgDiv.style.width = "40px";
                imgDiv.style.height = "auto";
                imgDiv.style.display = "block";
                imgDiv.style.margin = "0 auto";
                containerDiv.appendChild(imgDiv);


                // Name
                    // Container for image, name, checkmark
                const nameDiv = document.createElement("div");
                    const cellContainer = document.createElement("div");
                nameDiv.textContent = item.name;
                    cellContainer.style.position = "relative";
                nameDiv.style.marginTop = "5px";
                    cellContainer.style.width = "100%";
                nameDiv.style.pointerEvents = "none";
                    cellContainer.style.height = "100%";
                containerDiv.appendChild(nameDiv);


                // Checkmark
                    // Image
                const checkmark = document.createElement("div");
                    if (imgs[index]) {
                checkmark.textContent = "✔";
                        const img = document.createElement("img");
                checkmark.className = "bingoCheckmark";
                        img.src = imgs[index].src;
                checkmark.style.position = "absolute";
                        img.alt = item.name;
                checkmark.style.top = "2px";
                        img.style.width = "40px";
                checkmark.style.right = "2px";
                        img.style.height = "auto";
                checkmark.style.fontSize = "20px";
                        img.style.display = "block";
                checkmark.style.color = "#4CAF50";
                        img.style.margin = "0 auto";
                checkmark.style.background = "none";
                        cellContainer.appendChild(img);
                checkmark.style.display = "none";
                    }
                containerDiv.appendChild(checkmark);


                cell.appendChild(containerDiv);
                    // Name
                cellRefs.push({ cell, checkmark, imgDiv });
                    const nameDiv = document.createElement("div");
                    nameDiv.textContent = item.name;
                    nameDiv.style.marginTop = "5px";
                    nameDiv.style.pointerEvents = "none";
                    cellContainer.appendChild(nameDiv);


                // Hover: update info box
                    // Checkmark top-right
                cell.addEventListener("mouseenter", () => {
                    const checkmark = document.createElement("div");
                     cell.style.background = localStorage.getItem(cell.id) !== "true" ? "#3b4a6b" : cell.style.background;
                    checkmark.textContent = "✔";
                    checkmark.className = "bingoCheckmark";
                     checkmark.style.position = "absolute";
                    checkmark.style.top = "2px";
                    checkmark.style.right = "2px";
                    checkmark.style.fontSize = "20px";
                    checkmark.style.color = "#4CAF50";
                    checkmark.style.background = "none";
                    checkmark.style.display = boardData[teamKey][`tile_${index}`] ? "block" : "none";
                    cellContainer.appendChild(checkmark);


                     infoBox.innerHTML = "";
                     // Hover updates shared info box
                     const header = document.createElement("div");
                     cell.addEventListener("mouseenter", function() {
                    header.style.fontWeight = "bold";
                        cell.style.background = "#3b4a6b";
                    header.style.marginBottom = "5px";
                    header.textContent = item.name;
                    infoBox.appendChild(header);


                    // Image in info box
                        infoBox.innerHTML = "";
                    if (imgDiv.src) {
                        const header = document.createElement("div");
                        const hoverImg = document.createElement("img");
                        header.style.fontWeight = "bold";
                        hoverImg.src = imgDiv.src;
                        header.style.marginBottom = "5px";
                        hoverImg.style.width = "40px";
                        header.textContent = item.name;
                        hoverImg.style.height = "auto";
                        infoBox.appendChild(header);
                        hoverImg.style.display = "block";
 
                        hoverImg.style.marginBottom = "5px";
                        if (imgs[index]) {
                        infoBox.appendChild(hoverImg);
                            const hoverImg = document.createElement("img");
                    }
                            hoverImg.src = imgs[index].src;
                            hoverImg.style.width = "40px";
                            hoverImg.style.height = "auto";
                            hoverImg.style.display = "block";
                            hoverImg.style.marginBottom = "5px";
                            infoBox.appendChild(hoverImg);
                        }


                    item.tooltip.split("%%").forEach(line => {
                        item.tooltip.split("%%").forEach(line => {
                        const div = document.createElement("div");
                            const div = document.createElement("div");
                        div.innerHTML = line.trim();
                            div.innerHTML = line.trim();
                        infoBox.appendChild(div);
                            infoBox.appendChild(div);
                        });
                     });
                     });
                });


                cell.addEventListener("mouseleave", () => {
                    cell.addEventListener("mouseleave", function() {
                    cell.style.background = localStorage.getItem(cell.id) !== "true" ? "#313e59" : cell.style.background;
                        cell.style.background = "#313e59";
                    infoBox.innerHTML = "Hover over a tile to see its info here.";
                        infoBox.innerHTML = `
                });
<strong>Roat Pkz PVM Bingo #3</strong><br>
Collect drops from PVM or skilling to score points — each drop = 1 point. Screenshots required; no chests, crates, or boxes. Event ends <strong>June 28th, 11:59 PM GMT</strong>.<br><br>
<strong>Rewards:</strong><br>
- 500 CREDITS (25M+)<br>
- 300 CREDITS (15M+)<br>
- 200 CREDITS (10M+)<br><br>
Only drops <strong>after this announcement</strong> count. Submit sheets via the <strong>No Access</strong> channel or message <strong>@JAY</strong>.
                        `;
                    });


                // Click: only captain can update JSON
                    // Click toggle complete (captain only)
                cell.addEventListener("click", () => {
                    cell.addEventListener("click", function() {
                    if (mw.config.get('wgUserName') !== captain) return;
                        if (currentUser !== captain) return; // Only captain can mark tiles


                    // Update JSON via MediaWiki API
                        const done = boardData[teamKey][`tile_${index}`];
                    const tileKey = `tile_${index}`;
                        boardData[teamKey][`tile_${index}`] = !done;
                    const data = {};
                        checkmark.style.display = !done ? "block" : "none";
                    data[teamKey] = {};
                    data[teamKey][tileKey] = true;


                    fetchBoardData(true, data); // force update with this change
                        // Save back to MediaWiki page using API (example with edit token)
                });
                        $.post(mw.util.wikiScript('api'), {
            }
                            action: 'edit',
        }
                            title: 'Module:TeamBingo/data.json',
 
                            token: mw.user.tokens.get('csrfToken'),
        // Initial load & polling
                            format: 'json',
        function fetchBoardData(forceUpdate = false, updateTile = null) {
                            text: JSON.stringify(boardData, null, 4)
            const url = `/w/api.php?action=parse&page=Module:TeamBingo/data.json&format=json`;
                        }).done(function(){
            $.getJSON(url).done(res => {
                             console.log("Board updated for everyone!");
                let jsonText = res.parse.text["*"];
                try {
                    const boardData = JSON.parse(jsonText);
 
                    // Apply updates if captain clicked
                    if (updateTile) {
                        Object.keys(updateTile).forEach(team => {
                             Object.keys(updateTile[team]).forEach(tile => {
                                boardData[team][tile] = updateTile[team][tile];
                            });
                         });
                         });
                    });


                        // Save updated JSON back via API
                    cell.appendChild(cellContainer);
                        mw.loader.using('mediawiki.api').then(() => {
                }
                            const api = new mw.Api();
            }
                            api.postWithToken('csrf', {
                                action: 'edit',
                                title: 'Module:TeamBingo/data.json',
                                summary: 'Update team bingo tile',
                                bot: true,
                                text: JSON.stringify(boardData, null, 4),
                            });
                        });
                    }


                    // Update board display
            // Progress
                    cellRefs.forEach(({ cell, checkmark }, i) => {
            const progressDiv = document.createElement("div");
                        const tileKey = `tile_${i}`;
            progressDiv.style.marginTop = "10px";
                        if (boardData[teamKey] && boardData[teamKey][tileKey]) {
            progressDiv.style.color = "#fff";
                            cell.style.background = "rgba(76,175,80,0.5)";
            progressDiv.className = "bingoProgress";
                            checkmark.style.display = "block";
            container.appendChild(progressDiv);
                        } else {
                            cell.style.background = "#313e59";
                            checkmark.style.display = "none";
                        }
                    });


                 } catch (e) {
            function updateProgress() {
                     console.error("Failed to parse Team Bingo JSON", e);
                 let completed = 0;
                for (let i = 0; i < parsedItems.length; i++) {
                     if (boardData[teamKey][`tile_${i}`]) completed++;
                 }
                 }
             });
                progressDiv.textContent = `Completed ${completed} of ${parsedItems.length} items`;
         }
             }
            updateProgress();
         });
    }


        // Initial fetch
    // Initialize boards after fetching JSON
        fetchBoardData();
    fetchBoardData(function(boardData) {
 
        containers.forEach(container => {
        // Poll every 5 seconds
            const teamKey = container.getAttribute("data-team");
        setInterval(fetchBoardData, POLL_INTERVAL);
            renderBoard(container, teamKey, boardData);
        });
     });
     });


});
});

Revision as of 15:57, 7 March 2026

// --- Team Bingo Board with Captains and Shared JSON ---
mw.hook('wikipage.content').add(function () {

    const currentUser = mw.config.get('wgUserName'); // Logged-in user

    // Select all team bingo containers
    const containers = document.querySelectorAll(".teamBingoContainer");
    if (!containers.length) return;

    // Shared info box
    const infoBox = document.getElementById("teamBingoInfoBox");

    // Fetch the JSON data from the Module page
    function fetchBoardData(callback) {
        $.getJSON(mw.util.wikiScript('api'), {
            action: 'query',
            titles: 'Module:TeamBingo/data.json',
            prop: 'revisions',
            rvprop: 'content',
            format: 'json',
            formatversion: 2
        }).done(function(data){
            if (!data.query.pages[0].revisions) return;
            const content = data.query.pages[0].revisions[0].content;
            try {
                const boardData = JSON.parse(content);
                callback(boardData);
            } catch(e) {
                console.error("Failed to parse JSON from Module:TeamBingo/data.json", e);
            }
        });
    }

    // Render the board for a container
    function renderBoard(container, teamKey, boardData) {

        container.innerHTML = "";

        // Get captain username
        const captain = container.getAttribute("data-captain");

        // Parse items: Item Name::Tooltip (%% for line breaks)
        const itemsAttr = container.getAttribute("data-items");
        if (!itemsAttr) return;
        const items = itemsAttr.split("|").filter(i => i.trim() !== "");
        if (!items.length) return;

        const parsedItems = items.map(entry => {
            const parts = entry.split("::");
            return { name: parts[0].trim(), tooltip: parts[1] ? parts[1].trim() : parts[0].trim() };
        });

        // Build table
        const table = document.createElement("table");
        table.style.tableLayout = "fixed";
        table.style.border = "2px solid #596e96";
        table.style.borderCollapse = "collapse";
        table.style.borderRadius = "8px";
        table.style.width = "100%";
        container.appendChild(table);

        const rows = Math.ceil(Math.sqrt(parsedItems.length));
        const cols = Math.ceil(parsedItems.length / rows);

        // Single API call for images
        const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
        $.getJSON("/api.php", {
            action: "parse",
            text: allTemplates,
            format: "json"
        }).done(function(data) {
            if (!data.parse || !data.parse.text) return;

            const tempDiv = document.createElement("div");
            tempDiv.innerHTML = data.parse.text["*"];
            const imgs = tempDiv.querySelectorAll("img");

            for (let r = 0; r < rows; r++) {
                const row = table.insertRow();
                for (let c = 0; c < cols; c++) {
                    const index = r * cols + c;
                    if (index >= parsedItems.length) break;

                    const item = parsedItems[index];
                    const cell = row.insertCell();
                    cell.style.width = `${100 / cols}%`;
                    cell.style.padding = "10px";
                    cell.style.border = "1px solid #596e96";
                    cell.style.textAlign = "center";
                    cell.style.background = "#313e59";
                    cell.style.color = "#fff";
                    cell.style.cursor = "pointer";
                    cell.style.transition = "all 0.2s ease";
                    cell.style.userSelect = "none";
                    cell.style.wordWrap = "break-word";
                    cell.style.overflow = "visible";
                    cell.style.position = "relative";

                    const id = `${container.id}_cell_${index}`;
                    cell.id = id;

                    // Container for image, name, checkmark
                    const cellContainer = document.createElement("div");
                    cellContainer.style.position = "relative";
                    cellContainer.style.width = "100%";
                    cellContainer.style.height = "100%";

                    // Image
                    if (imgs[index]) {
                        const img = document.createElement("img");
                        img.src = imgs[index].src;
                        img.alt = item.name;
                        img.style.width = "40px";
                        img.style.height = "auto";
                        img.style.display = "block";
                        img.style.margin = "0 auto";
                        cellContainer.appendChild(img);
                    }

                    // Name
                    const nameDiv = document.createElement("div");
                    nameDiv.textContent = item.name;
                    nameDiv.style.marginTop = "5px";
                    nameDiv.style.pointerEvents = "none";
                    cellContainer.appendChild(nameDiv);

                    // Checkmark top-right
                    const checkmark = document.createElement("div");
                    checkmark.textContent = "✔";
                    checkmark.className = "bingoCheckmark";
                    checkmark.style.position = "absolute";
                    checkmark.style.top = "2px";
                    checkmark.style.right = "2px";
                    checkmark.style.fontSize = "20px";
                    checkmark.style.color = "#4CAF50";
                    checkmark.style.background = "none";
                    checkmark.style.display = boardData[teamKey][`tile_${index}`] ? "block" : "none";
                    cellContainer.appendChild(checkmark);

                    // Hover updates shared info box
                    cell.addEventListener("mouseenter", function() {
                        cell.style.background = "#3b4a6b";

                        infoBox.innerHTML = "";
                        const header = document.createElement("div");
                        header.style.fontWeight = "bold";
                        header.style.marginBottom = "5px";
                        header.textContent = item.name;
                        infoBox.appendChild(header);

                        if (imgs[index]) {
                            const hoverImg = document.createElement("img");
                            hoverImg.src = imgs[index].src;
                            hoverImg.style.width = "40px";
                            hoverImg.style.height = "auto";
                            hoverImg.style.display = "block";
                            hoverImg.style.marginBottom = "5px";
                            infoBox.appendChild(hoverImg);
                        }

                        item.tooltip.split("%%").forEach(line => {
                            const div = document.createElement("div");
                            div.innerHTML = line.trim();
                            infoBox.appendChild(div);
                        });
                    });

                    cell.addEventListener("mouseleave", function() {
                        cell.style.background = "#313e59";
                        infoBox.innerHTML = `
<strong>Roat Pkz PVM Bingo #3</strong><br>
Collect drops from PVM or skilling to score points — each drop = 1 point. Screenshots required; no chests, crates, or boxes. Event ends <strong>June 28th, 11:59 PM GMT</strong>.<br><br>
<strong>Rewards:</strong><br>
- 500 CREDITS (25M+)<br>
- 300 CREDITS (15M+)<br>
- 200 CREDITS (10M+)<br><br>
Only drops <strong>after this announcement</strong> count. Submit sheets via the <strong>No Access</strong> channel or message <strong>@JAY</strong>.
                        `;
                    });

                    // Click toggle complete (captain only)
                    cell.addEventListener("click", function() {
                        if (currentUser !== captain) return; // Only captain can mark tiles

                        const done = boardData[teamKey][`tile_${index}`];
                        boardData[teamKey][`tile_${index}`] = !done;
                        checkmark.style.display = !done ? "block" : "none";

                        // Save back to MediaWiki page using API (example with edit token)
                        $.post(mw.util.wikiScript('api'), {
                            action: 'edit',
                            title: 'Module:TeamBingo/data.json',
                            token: mw.user.tokens.get('csrfToken'),
                            format: 'json',
                            text: JSON.stringify(boardData, null, 4)
                        }).done(function(){
                            console.log("Board updated for everyone!");
                        });
                    });

                    cell.appendChild(cellContainer);
                }
            }

            // Progress
            const progressDiv = document.createElement("div");
            progressDiv.style.marginTop = "10px";
            progressDiv.style.color = "#fff";
            progressDiv.className = "bingoProgress";
            container.appendChild(progressDiv);

            function updateProgress() {
                let completed = 0;
                for (let i = 0; i < parsedItems.length; i++) {
                    if (boardData[teamKey][`tile_${i}`]) completed++;
                }
                progressDiv.textContent = `Completed ${completed} of ${parsedItems.length} items`;
            }
            updateProgress();
        });
    }

    // Initialize boards after fetching JSON
    fetchBoardData(function(boardData) {
        containers.forEach(container => {
            const teamKey = container.getAttribute("data-team");
            renderBoard(container, teamKey, boardData);
        });
    });

});