MediaWiki:Gadget-NameSwitch.js

From JoJo's Bizarre Encyclopedia - JoJo Wiki
Revision as of 21:21, 28 July 2024 by HudgynS (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.
const path = window.location.pathname;
const hashTab = "tab-"+window.location.hash.split("#").pop();
const redirectNotice = document.getElementById("contentSub");

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

        var switchNames = [];
        for (var i=1; switcherTabber.getAttribute('data-name'+i); i++) {
            switchNames.push(switcherTabber.getAttribute('data-name'+i))
        };
	    
        var i = 0;
        switchTabs.some(function(tab) {
            tab.dataset.pageName = switchNames[i] || switchNames[switchNames.length-1];
            tab.dataset.slot = i;
            var query = "#"+CSS.escape(tab.id.split("tab-").pop());
            var tabContent = document.body.querySelector(query);
            tabContent = Array.from(tabContent.getElementsByClassName("switcherTabber"));

            tab.addEventListener("click", function() {updateTab(tab, tabContent)});
	    
   	        tab.dataset.listenerAdded = true;
   	        if (tabContent) {
                tabContent.forEach(function(ss) {
        	        initTabs(ss, tab.ariaSelected);
                });
   	        }
	    
   	        if (hashTab === tab.id && redirectNotice) {
                redirectNotice.style.display = "none";
            }
   	    	if (tab.ariaSelected === "true" && tabberVisible === "true") {
                if (tab.dataset.pageName && tab.dataset.pageName !== "undefined") {
   	                tab.click();
   	            }
   	        }
            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, subTabbers) {
    if (tab.ariaSelected === "true") {
        if (tab.dataset.pageName && tab.dataset.pageName !== "undefined") {
            selectTabAndSetTitle(tab.id, tab.dataset.pageName, 5);
            toggleIntroSwitches(tab.dataset.slot);
            updateURL(tab.dataset.pageName);
        }
        if (subTabbers) {
            subTabbers.forEach(function(ss) {
                var subTabs = Array.from(ss.getElementsByClassName("tabber__tabs"))[0];
                subTabs = Array.from(subTabs.getElementsByClassName("tabber__tab"));
                subTabs.some(function(subtab) {
                    if (subtab.ariaSelected === "true") {
                        subtab.click();
                    }
                });
            });
        }
   	}
}

// Function to update the address bar with the tab's name
function updateURL(pageName) {
    var currentPath = 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 = encodeURI(originalName.split(' ').join('_'));
        var pageNameEscaped = encodeURI(pageName.split(' ').join('_'));
        if (newPath.includes(originalNameEscaped)) {
            newPath = newPath.replace(originalNameEscaped, pageNameEscaped);
        }
    });

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

// Function to check for redirects and set tab and title accordingly
function checkRedirects(retryCount) {
    retryCount = typeof retryCount !== 'undefined' ? retryCount : 5;
    if (!redirectNotice) return;

    var redirect = redirectNotice.getElementsByClassName("mw-redirect")[0];
    if (redirect) {
        var redirectMapping = {
            "Hatsune": ['tab-TV_Drama-0'],
            "Hatsune Morishima": ['tab-TV_Drama-0'],
            "Satoru Akefu": ['tab-Akefu-1', 'tab-Satoru_Akefu-2', 'tab-Satoru_Akefu-0'],
            "DIO": ['tab-Part_3-0', 'tab-CDDH-4'],
            "Erina Joestar": ['tab-Part_2-0'],
            "Suzi Q Joestar": ['tab-Part_3-0']
        };

        var redirectTabs = redirectMapping[redirect.title] || [];

        if (redirectTabs.length > 0) {
            redirectTabs.forEach(function(redirectTab) {
                var tabElement = document.getElementById(redirectTab);
                if (tabElement) {
                    tabElement.click();
                }
            });
            redirectNotice.style.display = "none";
        } 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 select tab and set title with retry mechanism
function selectTabAndSetTitle(tabId, newTitle, slot, retryCount) {
    if (retryCount == 0) {
        console.error('Failed to set title and select tab for ' + newTitle + 'after multiple attempts');
        return;
    }

    const tab = document.getElementById(tabId);
    if (tab) {
        history.replaceState(null, null, ' ');

        setPageTitle(newTitle);
        setInfoboxTitle(newTitle);
        toggleIntroSwitches(slot);
    } else {
        setTimeout(function() {selectTabAndSetTitle(tabId, newTitle, retryCount - 1)}, 500);
    }
}

// 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";
    });
}

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