MediaWiki:TeamBingo.js

From Roat Pkz
Revision as of 15:56, 7 March 2026 by Hefner (talk | contribs)
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
// --- 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);
    });

});