MediaWiki:Gadget-NameSwitch.js

From JoJo's Bizarre Encyclopedia - JoJo Wiki
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.
const path = window.location.pathname;
const hash = window.location.hash.split("#").pop();
var redirect = "";
var redirectDisplay;

var redirectMapping = {
    "Hatsune": ['TV_Drama'],
    "Hatsune Morishima": ['TV_Drama'],
    "Satoru Akefu": ['Akefu', 'Satoru_Akefu-1', 'Satoru_Akefu'],
    "DIO": ['Part_3', 'CDDH'],
    "Erina Joestar": ['Part_2'],
    "Suzi Q Joestar": ['Part_3'],
    "Golden Spirit (Reprise)": ['Reprise']
};

// Add necessary data and listeners to each switcher tab
function initTabs(switcherTabber) {
    if (!switcherTabber.dataset || !switcherTabber.dataset.processed || switcherTabber.dataset.processed !== "true") {
        var switchTabs = switcherTabber.getElementsByClassName("tabcontainer")[0];
        switchTabs = Array.from(switchTabs.getElementsByClassName("tab"));

        var switchNames = [];
        for (var i = 1; switcherTabber.getAttribute('data-name' + i); i++) {
            switchNames.push(switcherTabber.getAttribute('data-name' + i));
        };
        var switchURLs = [];
        for (var i = 1; switcherTabber.getAttribute('data-url' + i); i++) {
            switchURLs.push(switcherTabber.getAttribute('data-url' + i));
        };

        var i = 0;
        var tabberContent = switcherTabber.getElementsByClassName("tabcontents")[0];
        switchTabs.some(function (tab) {
            tab.dataset.pageName = switchNames[i] || "";
            tab.dataset.urlName = switchURLs[i] || "";
            tab.dataset.slot = i;
            var tabContent = tabberContent.children[i];

            tab.addEventListener("click", function (event) { updateTab(this, tabContent) });
            tab.dataset.listenerAdded = true;

            if (tab.classList.contains("active") && tab.clientWidth > 0) {
                if (tab.dataset.pageName && tab.dataset.pageName !== "undefined") {
                    tab.click();
                }
            }

            if (hash === tab.dataset.tabHash && redirect) {
                redirectDisplay.style.display = "none";
                redirectDisplay.style.opacity = "0";
                window.scrollTo(0, 0);
            }
            i++;
        });
        switcherTabber.dataset.processed = "true";
    }
}

// Switch page/infobox name and/or trigger sub-tabs to do so. To be run on tab click
function updateTab(tab, tabContent) {
    if (tab.classList.contains("active")) {
        if (tab.dataset.pageName && tab.dataset.pageName !== "undefined") {
            setAll(tab.id, tab.dataset.pageName, (tab.dataset.urlName || false), tab.dataset.slot, 5);
        }
    }
    if (tabContent.getElementsByClassName("switcherTabber")[0]) {
        var subTabs = Array.from(tabContent.getElementsByClassName("tab"));
        subTabs.some(function (subTab) {
            if (subTab.classList.contains("active")) {
                subTab.click();
            }
        });
    }
}

// Function to update the address bar with the tab's name
function updateURL(pageName) {
    var currentPath = decodeURI(window.location.pathname);
    var currentHash = window.location.hash;

    // Get the original names from the data attributes
    var switcherTabber = document.querySelector('.switcherTabber');
    if (!switcherTabber) return;

    var originalNames = [];
    for (var i = 1; switcherTabber.getAttribute('data-name' + i); i++) {
        originalNames.push(switcherTabber.getAttribute('data-name' + i));
    }

    var newPath = currentPath;
    originalNames.forEach(function (originalName) {
        var originalNameEscaped = originalName.split(' ').join('_');
        var pageNameEscaped = pageName.split(' ').join('_');
        if (newPath.includes(originalNameEscaped)) {
            newPath = newPath.split(originalNameEscaped)[0] + pageNameEscaped;
        }
    });

    history.replaceState(null, null, encodeURI(newPath + currentHash));
}

// Helper function to get the redirect notice element
function getRedirect() {
    var redirectNotice = document.getElementById("contentSub");
    var redirectNoticeMobile = document.getElementsByClassName("mw-redirectedfrom")[0];
    var redirectElement = "";
    if (!redirectNotice && redirectNoticeMobile) {
        redirectDisplay = document.getElementsByClassName("mw-notification-area")[0];
        redirectElement = redirectNoticeMobile.getElementsByTagName("a")[0];
    }
    if (redirectNotice) {
        redirectDisplay = redirectNotice;
        redirectElement = redirectNotice.getElementsByClassName("mw-redirect")[0];
    }
    if (redirectElement && redirectElement.title) {
        return redirectElement.title;
    }
    return null;
}

// Function to check for redirects and set tab and title accordingly
function checkRedirects(retryCount) {
    retryCount = typeof retryCount !== 'undefined' ? retryCount : 5;
    if (redirect) {
        var redirectTabs = redirectMapping[redirect] || [];

        if (redirectTabs.length > 0) {
            redirectTabs.forEach(function (redirectTab) {
                redirectDisplay.style.display = "none";
                redirectDisplay.style.opacity = "0";
                var tabElement = document.querySelector("[data-tab-hash="+redirectTab+"]");
                if (tabElement) {
                    tabElement.click();
                }
            });
        } else if (retryCount > 0) {
            setTimeout(function () { checkRedirects(retryCount - 1); }, 500);
        }
    } else if (retryCount > 0) {
        setTimeout(function () { checkRedirects(retryCount - 1); }, 500);
    }
}

// Function to set page title
function setPageTitle(newTitle) {
    const pageTitle = document.getElementById("firstHeading");
    if (pageTitle) {
        pageTitle.textContent = newTitle;
    }
}

// Function to set infobox title
function setInfoboxTitle(newTitle) {
    const titleElement = document.querySelector(".pi-item.pi-item-spacing.pi-title[data-source='title']");
    if (titleElement) {
        titleElement.textContent = newTitle;
    }
}

// Function to toggle introSwitch and introSwitch2 visibility
function toggleIntroSwitches(activeSlot) {
    const introSwitchElements = document.querySelectorAll(".introSwitch");
    const introSwitch2Elements = document.querySelectorAll(".introSwitch2");
    introSwitchElements.forEach(function (element) {
        element.style.display = (activeSlot == 0) ? "inline" : "none";
    });

    introSwitch2Elements.forEach(function (element) {
        element.style.display = (activeSlot != 0) ? "inline" : "none";
    });
}

// Function to select tab and set title with retry mechanism
function setAll(tabId, newTitle, newURL, slot, retryCount) {
    if (retryCount <= 0) {
        console.error('Failed to set title and select tab for ' + newTitle + ' after multiple attempts');
        return;
    }

    try {
        history.replaceState(null, null, ' ');
        setPageTitle(newTitle);
        setInfoboxTitle(newTitle);
        toggleIntroSwitches(slot);
        if (newURL && newURL !== "undefined") {
            updateURL(newURL);
        }
    } catch(error) {
        console.log(error);
        setTimeout(function () { setAll(tabId, newTitle, newURL, slot, retryCount - 1) }, 500);
    }
}

// Initialize tabs and check redirects on page load
jQuery(function () {
    var switchSpan = document.body.getElementsByClassName("switcherTabber");
    redirect = getRedirect();
    Array.from(switchSpan).forEach(function (ss) {
        initTabs(ss);
    });
    checkRedirects();
});