MediaWiki:TeamBingo.js: Difference between revisions

From Roat Pkz
Jump to navigation Jump to search
No edit summary
No edit summary
Tag: Reverted
Line 1: Line 1:
// --- Team Bingo Board with Captains and Shared JSON ---
// --- Team Bingo Board with Real-Time Updates ---
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 11: Line 8:
     const infoBox = document.getElementById("teamBingoInfoBox");
     const infoBox = document.getElementById("teamBingoInfoBox");


     // Fetch the JSON data from the Module page
     // Polling interval (ms)
    function fetchBoardData(callback) {
    const POLL_INTERVAL = 5000;
        $.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 = "";


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


         // Parse items: Item Name::Tooltip (%% for line breaks)
         // Parse items
         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 63: Line 38:
         const cols = Math.ceil(parsedItems.length / rows);
         const cols = Math.ceil(parsedItems.length / rows);


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


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


            for (let r = 0; r < rows; r++) {
                const item = parsedItems[index];
                 const row = table.insertRow();
                 const cell = row.insertCell();
                 for (let c = 0; c < cols; c++) {
                 cell.style.width = `${100 / cols}%`;
                    const index = r * cols + c;
                cell.style.padding = "10px";
                    if (index >= parsedItems.length) break;
                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";
                cell.id = `${teamKey}_tile_${index}`;


                    const item = parsedItems[index];
                // Cell container
                    const cell = row.insertCell();
                const containerDiv = document.createElement("div");
                    cell.style.width = `${100 / cols}%`;
                containerDiv.style.position = "relative";
                    cell.style.padding = "10px";
                containerDiv.style.width = "100%";
                    cell.style.border = "1px solid #596e96";
                containerDiv.style.height = "100%";
                    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}`;
                // Image placeholder
                    cell.id = id;
                const imgDiv = document.createElement("img");
                imgDiv.style.width = "40px";
                imgDiv.style.height = "auto";
                imgDiv.style.display = "block";
                imgDiv.style.margin = "0 auto";
                containerDiv.appendChild(imgDiv);


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


                    // Image
                // Checkmark
                    if (imgs[index]) {
                const checkmark = document.createElement("div");
                        const img = document.createElement("img");
                checkmark.textContent = "✔";
                        img.src = imgs[index].src;
                checkmark.className = "bingoCheckmark";
                        img.alt = item.name;
                checkmark.style.position = "absolute";
                        img.style.width = "40px";
                checkmark.style.top = "2px";
                        img.style.height = "auto";
                checkmark.style.right = "2px";
                        img.style.display = "block";
                checkmark.style.fontSize = "20px";
                        img.style.margin = "0 auto";
                checkmark.style.color = "#4CAF50";
                        cellContainer.appendChild(img);
                checkmark.style.background = "none";
                     }
                checkmark.style.display = "none";
                containerDiv.appendChild(checkmark);
 
                cell.appendChild(containerDiv);
                cellRefs.push({ cell, checkmark, imgDiv });
 
                // Hover: update info box
                cell.addEventListener("mouseenter", () => {
                     cell.style.background = localStorage.getItem(cell.id) !== "true" ? "#3b4a6b" : cell.style.background;


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


                     // Checkmark top-right
                     // Image in info box
                     const checkmark = document.createElement("div");
                     if (imgDiv.src) {
                    checkmark.textContent = "✔";
                        const hoverImg = document.createElement("img");
                    checkmark.className = "bingoCheckmark";
                        hoverImg.src = imgDiv.src;
                    checkmark.style.position = "absolute";
                        hoverImg.style.width = "40px";
                    checkmark.style.top = "2px";
                        hoverImg.style.height = "auto";
                    checkmark.style.right = "2px";
                        hoverImg.style.display = "block";
                    checkmark.style.fontSize = "20px";
                        hoverImg.style.marginBottom = "5px";
                    checkmark.style.color = "#4CAF50";
                        infoBox.appendChild(hoverImg);
                     checkmark.style.background = "none";
                     }
                    checkmark.style.display = boardData[teamKey][`tile_${index}`] ? "block" : "none";
                    cellContainer.appendChild(checkmark);


                     // Hover updates shared info box
                     item.tooltip.split("%%").forEach(line => {
                    cell.addEventListener("mouseenter", function() {
                         const div = document.createElement("div");
                         cell.style.background = "#3b4a6b";
                        div.innerHTML = line.trim();
                        infoBox.appendChild(div);
                    });
                });


                        infoBox.innerHTML = "";
                cell.addEventListener("mouseleave", () => {
                        const header = document.createElement("div");
                    cell.style.background = localStorage.getItem(cell.id) !== "true" ? "#313e59" : cell.style.background;
                        header.style.fontWeight = "bold";
                    infoBox.innerHTML = "Hover over a tile to see its info here.";
                        header.style.marginBottom = "5px";
                });
                        header.textContent = item.name;
                        infoBox.appendChild(header);


                        if (imgs[index]) {
                // Click: only captain can update JSON
                            const hoverImg = document.createElement("img");
                cell.addEventListener("click", () => {
                            hoverImg.src = imgs[index].src;
                    if (mw.config.get('wgUserName') !== captain) return;
                            hoverImg.style.width = "40px";
                            hoverImg.style.height = "auto";
                            hoverImg.style.display = "block";
                            hoverImg.style.marginBottom = "5px";
                            infoBox.appendChild(hoverImg);
                        }


                        item.tooltip.split("%%").forEach(line => {
                    // Update JSON via MediaWiki API
                            const div = document.createElement("div");
                    const tileKey = `tile_${index}`;
                            div.innerHTML = line.trim();
                    const data = {};
                            infoBox.appendChild(div);
                    data[teamKey] = {};
                        });
                     data[teamKey][tileKey] = true;
                     });


                     cell.addEventListener("mouseleave", function() {
                     fetchBoardData(true, data); // force update with this change
                        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)
        // Initial load & polling
                    cell.addEventListener("click", function() {
        function fetchBoardData(forceUpdate = false, updateTile = null) {
                        if (currentUser !== captain) return; // Only captain can mark tiles
            const url = `/w/api.php?action=parse&page=Module:TeamBingo/data.json&format=json`;
            $.getJSON(url).done(res => {
                let jsonText = res.parse.text["*"];
                try {
                    const boardData = JSON.parse(jsonText);


                         const done = boardData[teamKey][`tile_${index}`];
                    // Apply updates if captain clicked
                        boardData[teamKey][`tile_${index}`] = !done;
                    if (updateTile) {
                         checkmark.style.display = !done ? "block" : "none";
                         Object.keys(updateTile).forEach(team => {
                            Object.keys(updateTile[team]).forEach(tile => {
                                boardData[team][tile] = updateTile[team][tile];
                            });
                         });


                         // Save back to MediaWiki page using API (example with edit token)
                         // Save updated JSON back via API
                        $.post(mw.util.wikiScript('api'), {
                        mw.loader.using('mediawiki.api').then(() => {
                            action: 'edit',
                            const api = new mw.Api();
                            title: 'Module:TeamBingo/data.json',
                            api.postWithToken('csrf', {
                            token: mw.user.tokens.get('csrfToken'),
                                action: 'edit',
                            format: 'json',
                                title: 'Module:TeamBingo/data.json',
                            text: JSON.stringify(boardData, null, 4)
                                summary: 'Update team bingo tile',
                        }).done(function(){
                                bot: true,
                            console.log("Board updated for everyone!");
                                text: JSON.stringify(boardData, null, 4),
                            });
                         });
                         });
                    }
                    // Update board display
                    cellRefs.forEach(({ cell, checkmark }, i) => {
                        const tileKey = `tile_${i}`;
                        if (boardData[teamKey] && boardData[teamKey][tileKey]) {
                            cell.style.background = "rgba(76,175,80,0.5)";
                            checkmark.style.display = "block";
                        } else {
                            cell.style.background = "#313e59";
                            checkmark.style.display = "none";
                        }
                     });
                     });


                     cell.appendChild(cellContainer);
                } catch (e) {
                     console.error("Failed to parse Team Bingo JSON", e);
                 }
                 }
             }
             });
        }


            // Progress
        // Initial fetch
            const progressDiv = document.createElement("div");
        fetchBoardData();
            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
        // Poll every 5 seconds
    fetchBoardData(function(boardData) {
         setInterval(fetchBoardData, POLL_INTERVAL);
         containers.forEach(container => {
            const teamKey = container.getAttribute("data-team");
            renderBoard(container, teamKey, boardData);
        });
     });
     });


});
});

Revision as of 15:56, 7 March 2026

// --- Team Bingo Board with Real-Time Updates ---
mw.hook('wikipage.content').add(function () {

    const containers = document.querySelectorAll(".teamBingoContainer");
    if (!containers.length) return;

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

    // Polling interval (ms)
    const POLL_INTERVAL = 5000;

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

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

        // Parse items
        const itemsAttr = container.getAttribute("data-items");
        if (!itemsAttr) return;
        const items = itemsAttr.split("|").filter(i => i.trim() !== "");
        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);

        // Store references to cells for live updates
        const cellRefs = [];

        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";
                cell.id = `${teamKey}_tile_${index}`;

                // Cell container
                const containerDiv = document.createElement("div");
                containerDiv.style.position = "relative";
                containerDiv.style.width = "100%";
                containerDiv.style.height = "100%";

                // Image placeholder
                const imgDiv = document.createElement("img");
                imgDiv.style.width = "40px";
                imgDiv.style.height = "auto";
                imgDiv.style.display = "block";
                imgDiv.style.margin = "0 auto";
                containerDiv.appendChild(imgDiv);

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

                // Checkmark
                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 = "none";
                containerDiv.appendChild(checkmark);

                cell.appendChild(containerDiv);
                cellRefs.push({ cell, checkmark, imgDiv });

                // Hover: update info box
                cell.addEventListener("mouseenter", () => {
                    cell.style.background = localStorage.getItem(cell.id) !== "true" ? "#3b4a6b" : cell.style.background;

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

                    // Image in info box
                    if (imgDiv.src) {
                        const hoverImg = document.createElement("img");
                        hoverImg.src = imgDiv.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", () => {
                    cell.style.background = localStorage.getItem(cell.id) !== "true" ? "#313e59" : cell.style.background;
                    infoBox.innerHTML = "Hover over a tile to see its info here.";
                });

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

                    // Update JSON via MediaWiki API
                    const tileKey = `tile_${index}`;
                    const data = {};
                    data[teamKey] = {};
                    data[teamKey][tileKey] = true;

                    fetchBoardData(true, data); // force update with this change
                });
            }
        }

        // Initial load & polling
        function fetchBoardData(forceUpdate = false, updateTile = null) {
            const url = `/w/api.php?action=parse&page=Module:TeamBingo/data.json&format=json`;
            $.getJSON(url).done(res => {
                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
                        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
                    cellRefs.forEach(({ cell, checkmark }, i) => {
                        const tileKey = `tile_${i}`;
                        if (boardData[teamKey] && boardData[teamKey][tileKey]) {
                            cell.style.background = "rgba(76,175,80,0.5)";
                            checkmark.style.display = "block";
                        } else {
                            cell.style.background = "#313e59";
                            checkmark.style.display = "none";
                        }
                    });

                } catch (e) {
                    console.error("Failed to parse Team Bingo JSON", e);
                }
            });
        }

        // Initial fetch
        fetchBoardData();

        // Poll every 5 seconds
        setInterval(fetchBoardData, POLL_INTERVAL);
    });

});