MediaWiki:Common.js: Difference between revisions

From MB Wiki
Jump to navigation Jump to search
mNo edit summary
Tag: Reverted
m (fix title set.)
 
(8 intermediate revisions by the same user not shown)
Line 1: Line 1:
var config = mw.config.values;
/* ============================================
window.dev = window.dev || {};
  THEME TOGGLER
window.dev.waitFor = function(query, callback, extraDelay) {
  ============================================ */
if ('function' == typeof callback && 'string' == typeof query) {
extraDelay = extraDelay || 0;
if (document.querySelector(query)) {
setTimeout(callback, extraDelay);
} else {
// set up the mutation observer
var observer = new MutationObserver(function (mutations, me) {
// mutations is an array of mutations that occurred
// me is the MutationObserver instance
var targetNode = document.querySelector(query);
if (targetNode) {
setTimeout(callback, extraDelay);
me.disconnect(); // stop observing
return;
}
});
// start observing
observer.observe(document, {
  childList: true,
  subtree: true
});
}
}
};


// Load site JS
// 1. INSTANT EXECUTION (PREVENTS FLASH OF WRONG THEME)
[
// This runs the millisecond the script loads, before the body renders.
'ThemeToggle.js', // Add link button on sidebar for mass renaming files and pages
(function() {
'MassRename.js', // Add link button on sidebar for mass renaming files and pages
    var savedTheme = localStorage.getItem('mb-wiki-theme');
'BetterUpload.js', // Improvements to Special:Upload
    if (savedTheme === 'break') {
'BetterDiff.js' // Aids with patrolling and with diff viewing on RC, page history and user contribs
        document.documentElement.classList.add('theme-break');
]
    }
.forEach(function(src){
})();
importScript('MediaWiki:'+src);
 
});
// 2. DOM READY EXECUTION (UI BINDING)
$(function() {
    var isBreak = document.documentElement.classList.contains('theme-break');
   
    var $btn = $('<button>', {
        id: 'theme-toggle',
        class: 'floating-theme-toggle',
        text: isBreak ? '✦ Switch to Mana' : '✦ Switch to Break',
        title: 'Toggle Light/Dark Theme'
    });
   
    $('body').append($btn);


// Run when page content is added and loaded
    $btn.on('click', function() {
mw.hook('wikipage.content').add(function(){
        var $html = $('html');
// Add navigational keybinds
       
if (config.wgAction=='view') {
        if ($html.hasClass('theme-break')) {
var actions = {
            // Switching to Mana (Light)
e: function(page){ return config.wgServer+mw.util.getUrl(page)+'?action=edit'; },
            $html.removeClass('theme-break');
h: function(page){ return config.wgServer+mw.util.getUrl(page)+'?action=history'; },
            localStorage.setItem('mb-wiki-theme', 'mana');
m: function(page){ return config.wgServer+mw.util.getUrl('Special:MovePage/'+page); },
            $(this).text('✦ Switch to Break');
d: function(page){ return config.wgServer+mw.util.getUrl(page)+'?action=delete'; },
        } else {
};
            // Switching to Break (Dark)
var url = new URL(document.location.href);
            $html.addClass('theme-break');
var title =
            localStorage.setItem('mb-wiki-theme', 'break');
url.searchParams.get('title') || // for `/w/index.php?title=XYZ` links
            $(this).text('✦ Switch to Mana');
url.pathname.replace(/^.*?wi?k?i?\//, ''); // for `/wiki/XYZ` links
        }
$(document).on('keydown', function(e) {
    });
var key = e.key.toLocaleLowerCase();
if (
actions[key] &&
!(e.target && ['INPUT', 'TEXTAREA'].includes(e.target.nodeName)) &&
config.wgCanonicalSpecialPageName===false
) {
document.location.href= actions[key](title);
}
});
}
// Run through sidebar to make sure classes align with collapse status
window.dev.waitFor('#mw-navigation > .collapsible-nav > nav', function() {
$('#mw-navigation > .collapsible-nav > nav').each(function(_, nav) {
if (getComputedStyle(nav).display!=='none') {
if (
nav.classList.contains('collapsed') &&
getComputedStyle(nav.querySelector('.vector-menu-content')).display!=='none'
) {
nav.classList.remove('collapsed');
nav.classList.add('expanded');
} else if (
nav.classList.contains('expanded') &&
getComputedStyle(nav.querySelector('.vector-menu-content')).display=='none'
) {
nav.classList.add('collapsed');
nav.classList.remove('expanded');
}
}
});
});
});
});
 
/* ============================================
// Load personal JS & CSS if logged in user
  TITTLE FIX
if (config.wgUserName && config.wgUserName.length>0) {
  ============================================ */
importScript('User:'+config.wgUserName+'/common.js');
importStylesheet('User:'+config.wgUserName+'/common.css');
}
// === EMERGENCY TITLE OVERRIDE ===
(function() {
(function() {
     // Only on main page
     // Only on main page
Line 150: Line 101:
      
      
     console.log('Emergency title fix applied');
     console.log('Emergency title fix applied');
})();/* ============================================
  THEME TOGGLER
  ============================================ */
// 1. INSTANT EXECUTION (PREVENTS FLASH OF WRONG THEME)
// This runs the millisecond the script loads, before the body renders.
(function() {
    var savedTheme = localStorage.getItem('mb-wiki-theme');
    if (savedTheme === 'break') {
        document.documentElement.classList.add('theme-break');
    }
})();
})();
// ===== WIKI FONT FIXER =====
 
// 2. DOM READY EXECUTION (UI BINDING)
$(function() {
    var isBreak = document.documentElement.classList.contains('theme-break');
   
    var $btn = $('<button>', {
        id: 'theme-toggle',
        class: 'floating-theme-toggle',
        text: isBreak ? '✦ Switch to Mana' : '✦ Switch to Break',
        title: 'Toggle Light/Dark Theme'
    });
   
    $('body').append($btn);
 
    $btn.on('click', function() {
        var $html = $('html');
       
        if ($html.hasClass('theme-break')) {
            // Switching to Mana (Light)
            $html.removeClass('theme-break');
            localStorage.setItem('mb-wiki-theme', 'mana');
            $(this).text('✦ Switch to Break');
        } else {
            // Switching to Break (Dark)
            $html.addClass('theme-break');
            localStorage.setItem('mb-wiki-theme', 'break');
            $(this).text('✦ Switch to Mana');
        }
    });
});
/* ============================================
  TITTLE FIX
  ============================================ */
(function() {
(function() {
     'use strict';
     // Only on main page
    if (mw.config.get('wgPageName') !== 'Main_Page' &&
        !window.location.href.includes('Main_Page')) return;
      
      
     console.log('MB Wiki: Loading Font Fixer...');
     console.log('=== APPLYING EMERGENCY TITLE FIX ===');
      
      
     // Configuration
     // 1. IMMEDIATELY set the title
     var fontConfig = {
     document.title = 'MB Wiki - The Official Wiki';
        bodyFontFamily: 'Helvetica, Arial, sans-serif',
        bodyFontSize: '16px',
        codeFontFamily: 'monospace, monospace',
        codeFontSize: '13px',
        headingsFontFamily: 'Verdana, Helvetica, Arial, sans-serif',
        debug: false // Set to true to see detailed logs
    };
      
      
     // Utility function to apply styles with !important
     // 2. Override the heading
     function applyFontStyle(element, property, value) {
     function fixHeading() {
         if (!element) return;
        var heading = document.querySelector('#firstHeading, h1.firstHeading, .mw-page-title-main');
        element.style.setProperty(property, value, 'important');
        if (heading) {
            heading.textContent = 'MB Wiki - The Official Wiki';
            heading.style.display = 'none';
            heading.style.visibility = 'hidden';
         } else {
            // Create heading if it doesn't exist
            var newHeading = document.createElement('h1');
            newHeading.id = 'firstHeading';
            newHeading.className = 'firstHeading';
            newHeading.textContent = 'MB Wiki - The Official Wiki';
            var content = document.querySelector('#content, .mw-body');
            if (content) content.prepend(newHeading);
        }
     }
     }
      
      
     // Apply styles to selector
     // 3. Run now and keep running
     function applyToSelector(selector, property, value) {
     fixHeading();
        document.querySelectorAll(selector).forEach(function(el) {
    setTimeout(fixHeading, 100);
            applyFontStyle(el, property, value);
    setTimeout(fixHeading, 500);
        });
    setTimeout(fixHeading, 1000);
    }
    setTimeout(fixHeading, 2000);
      
      
     // Main font fixing function
     // 4. Monitor and fix any time title changes
     function fixFonts() {
     var lastTitle = document.title;
        if (fontConfig.debug) console.log('MB Wiki: Fixing fonts...');
    setInterval(function() {
       
         if (document.title !== lastTitle &&
        // 1. Fix body text
             document.title.includes('Coral Island')) {
        applyFontStyle(document.body, 'font-family', fontConfig.bodyFontFamily);
             console.log('Title changed to wrong value, fixing...');
        applyFontStyle(document.body, 'font-size', fontConfig.bodyFontSize);
            document.title = 'MB Wiki - The Official Wiki';
       
            lastTitle = document.title;
        // 2. Fix vector body classes
            fixHeading();
        applyToSelector('.vector-body, .mw-body-content, .mw-parser-output', 'font-family', fontConfig.bodyFontFamily);
         }
         applyToSelector('.vector-body, .mw-body-content, .mw-parser-output', 'font-size', fontConfig.bodyFontSize);
    }, 500);
       
        // 3. CRITICAL: Protect code editors
        var codeSelectors = [
            '.CodeMirror',
            '.CodeMirror *',
            '.ace_editor',
            '.ace_editor *',
            '.ve-ce-contentBranchNode',
            '.ve-ce-contentBranchNode *',
            '.wikiEditor-ui .ace_editor',
            '.wikiEditor-ui .ace_editor *',
            '.mw-editfont-monospace',
            '.mw-editfont-monospace *',
            'textarea',
            'input[type="text"]',
            'input[type="search"]',
             'input[type="password"]',
            '.mw-abusefilter-editor',
            '.mw-abusefilter-editor *'
        ];
       
        codeSelectors.forEach(function(selector) {
            applyToSelector(selector, 'font-family', fontConfig.codeFontFamily);
            applyToSelector(selector, 'font-size', fontConfig.codeFontSize);
             applyToSelector(selector, 'line-height', '1.5');
        });
       
        // 4. Fix inline code/pre
        applyToSelector('pre, code, .mw-code', 'font-family', fontConfig.codeFontFamily);
        applyToSelector('pre, code, .mw-code', 'font-size', fontConfig.codeFontSize);
       
        // 5. Fix headings
        applyToSelector('h1, .firstHeading', 'font-family', fontConfig.headingsFontFamily);
        applyToSelector('h1, .firstHeading', 'font-size', '32px');
        applyToSelector('h1, .firstHeading', 'font-weight', 'bold');
          
        applyToSelector('h2', 'font-family', fontConfig.headingsFontFamily);
        applyToSelector('h2', 'font-size', '26px');
        applyToSelector('h2', 'font-weight', 'bold');
       
        applyToSelector('h3', 'font-family', fontConfig.headingsFontFamily);
        applyToSelector('h3', 'font-size', '22px');
        applyToSelector('h3', 'font-weight', 'bold');
       
        // 6. Fix tables
        applyToSelector('.wikitable td, .wikitable th, .scheduletable td, .scheduletable th', 'font-family', fontConfig.bodyFontFamily);
        applyToSelector('.wikitable td, .wikitable th, .scheduletable td, .scheduletable th', 'font-size', '14px');
       
        if (fontConfig.debug) console.log('MB Wiki: Font fixes applied');
    }
      
      
     // Initialize font fixer
     // 5. Also fix meta tags
     function initFontFixer() {
     function fixMetaTags() {
         console.log('MB Wiki: Initializing Font Fixer');
         var metaTags = document.querySelectorAll('meta[property="og:title"], meta[name="twitter:title"]');
          
         metaTags.forEach(function(tag) {
        // Use your existing waitFor function for better integration
             tag.setAttribute('content', 'MB Wiki - The Official Wiki');
        window.dev.waitFor('body', function() {
             // Run immediately
            fixFonts();
           
            // Run with delays for dynamic content
            setTimeout(fixFonts, 100);
            setTimeout(fixFonts, 500);
            setTimeout(fixFonts, 1000);
            setTimeout(fixFonts, 3000);
           
            // Also run when content is added
            mw.hook('wikipage.content').add(fixFonts);
           
            // Monitor for new code editors
            var observer = new MutationObserver(function(mutations) {
                var needsFix = false;
                mutations.forEach(function(mutation) {
                    if (mutation.addedNodes.length) {
                        mutation.addedNodes.forEach(function(node) {
                            if (node.nodeType === 1) { // Element node
                                if (node.matches && (
                                    node.matches('.CodeMirror, .ace_editor, textarea, pre, code') ||
                                    node.querySelector('.CodeMirror, .ace_editor, textarea, pre, code')
                                )) {
                                    needsFix = true;
                                }
                            }
                        });
                    }
                });
                if (needsFix) {
                    setTimeout(fixFonts, 100);
                }
            });
           
            observer.observe(document.body, {
                childList: true,
                subtree: true
            });
           
            console.log('MB Wiki: Font Fixer initialized successfully');
         });
         });
     }
     }
    fixMetaTags();
      
      
     // Start the font fixer
     console.log('Emergency title fix applied');
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initFontFixer);
    } else {
        initFontFixer();
    }
   
})();
})();

Latest revision as of 04:08, 19 May 2026

/* ============================================
   THEME TOGGLER
   ============================================ */

// 1. INSTANT EXECUTION (PREVENTS FLASH OF WRONG THEME)
// This runs the millisecond the script loads, before the body renders.
(function() {
    var savedTheme = localStorage.getItem('mb-wiki-theme');
    if (savedTheme === 'break') {
        document.documentElement.classList.add('theme-break');
    }
})();

// 2. DOM READY EXECUTION (UI BINDING)
$(function() {
    var isBreak = document.documentElement.classList.contains('theme-break');
    
    var $btn = $('<button>', {
        id: 'theme-toggle',
        class: 'floating-theme-toggle',
        text: isBreak ? '✦ Switch to Mana' : '✦ Switch to Break',
        title: 'Toggle Light/Dark Theme'
    });
    
    $('body').append($btn);

    $btn.on('click', function() {
        var $html = $('html');
        
        if ($html.hasClass('theme-break')) {
            // Switching to Mana (Light)
            $html.removeClass('theme-break');
            localStorage.setItem('mb-wiki-theme', 'mana');
            $(this).text('✦ Switch to Break');
        } else {
            // Switching to Break (Dark)
            $html.addClass('theme-break');
            localStorage.setItem('mb-wiki-theme', 'break');
            $(this).text('✦ Switch to Mana');
        }
    });
});
/* ============================================
   TITTLE FIX
   ============================================ */
(function() {
    // Only on main page
    if (mw.config.get('wgPageName') !== 'Main_Page' && 
        !window.location.href.includes('Main_Page')) return;
    
    console.log('=== APPLYING EMERGENCY TITLE FIX ===');
    
    // 1. IMMEDIATELY set the title
    document.title = 'MB Wiki - The Official Wiki';
    
    // 2. Override the heading
    function fixHeading() {
        var heading = document.querySelector('#firstHeading, h1.firstHeading, .mw-page-title-main');
        if (heading) {
            heading.textContent = 'MB Wiki - The Official Wiki';
            heading.style.display = 'none';
            heading.style.visibility = 'hidden';
        } else {
            // Create heading if it doesn't exist
            var newHeading = document.createElement('h1');
            newHeading.id = 'firstHeading';
            newHeading.className = 'firstHeading';
            newHeading.textContent = 'MB Wiki - The Official Wiki';
            var content = document.querySelector('#content, .mw-body');
            if (content) content.prepend(newHeading);
        }
    }
    
    // 3. Run now and keep running
    fixHeading();
    setTimeout(fixHeading, 100);
    setTimeout(fixHeading, 500);
    setTimeout(fixHeading, 1000);
    setTimeout(fixHeading, 2000);
    
    // 4. Monitor and fix any time title changes
    var lastTitle = document.title;
    setInterval(function() {
        if (document.title !== lastTitle && 
            document.title.includes('Coral Island')) {
            console.log('Title changed to wrong value, fixing...');
            document.title = 'MB Wiki - The Official Wiki';
            lastTitle = document.title;
            fixHeading();
        }
    }, 500);
    
    // 5. Also fix meta tags
    function fixMetaTags() {
        var metaTags = document.querySelectorAll('meta[property="og:title"], meta[name="twitter:title"]');
        metaTags.forEach(function(tag) {
            tag.setAttribute('content', 'MB Wiki - The Official Wiki');
        });
    }
    fixMetaTags();
    
    console.log('Emergency title fix applied');
})();/* ============================================
   THEME TOGGLER
   ============================================ */

// 1. INSTANT EXECUTION (PREVENTS FLASH OF WRONG THEME)
// This runs the millisecond the script loads, before the body renders.
(function() {
    var savedTheme = localStorage.getItem('mb-wiki-theme');
    if (savedTheme === 'break') {
        document.documentElement.classList.add('theme-break');
    }
})();

// 2. DOM READY EXECUTION (UI BINDING)
$(function() {
    var isBreak = document.documentElement.classList.contains('theme-break');
    
    var $btn = $('<button>', {
        id: 'theme-toggle',
        class: 'floating-theme-toggle',
        text: isBreak ? '✦ Switch to Mana' : '✦ Switch to Break',
        title: 'Toggle Light/Dark Theme'
    });
    
    $('body').append($btn);

    $btn.on('click', function() {
        var $html = $('html');
        
        if ($html.hasClass('theme-break')) {
            // Switching to Mana (Light)
            $html.removeClass('theme-break');
            localStorage.setItem('mb-wiki-theme', 'mana');
            $(this).text('✦ Switch to Break');
        } else {
            // Switching to Break (Dark)
            $html.addClass('theme-break');
            localStorage.setItem('mb-wiki-theme', 'break');
            $(this).text('✦ Switch to Mana');
        }
    });
});
/* ============================================
   TITTLE FIX
   ============================================ */
(function() {
    // Only on main page
    if (mw.config.get('wgPageName') !== 'Main_Page' && 
        !window.location.href.includes('Main_Page')) return;
    
    console.log('=== APPLYING EMERGENCY TITLE FIX ===');
    
    // 1. IMMEDIATELY set the title
    document.title = 'MB Wiki - The Official Wiki';
    
    // 2. Override the heading
    function fixHeading() {
        var heading = document.querySelector('#firstHeading, h1.firstHeading, .mw-page-title-main');
        if (heading) {
            heading.textContent = 'MB Wiki - The Official Wiki';
            heading.style.display = 'none';
            heading.style.visibility = 'hidden';
        } else {
            // Create heading if it doesn't exist
            var newHeading = document.createElement('h1');
            newHeading.id = 'firstHeading';
            newHeading.className = 'firstHeading';
            newHeading.textContent = 'MB Wiki - The Official Wiki';
            var content = document.querySelector('#content, .mw-body');
            if (content) content.prepend(newHeading);
        }
    }
    
    // 3. Run now and keep running
    fixHeading();
    setTimeout(fixHeading, 100);
    setTimeout(fixHeading, 500);
    setTimeout(fixHeading, 1000);
    setTimeout(fixHeading, 2000);
    
    // 4. Monitor and fix any time title changes
    var lastTitle = document.title;
    setInterval(function() {
        if (document.title !== lastTitle && 
            document.title.includes('Coral Island')) {
            console.log('Title changed to wrong value, fixing...');
            document.title = 'MB Wiki - The Official Wiki';
            lastTitle = document.title;
            fixHeading();
        }
    }, 500);
    
    // 5. Also fix meta tags
    function fixMetaTags() {
        var metaTags = document.querySelectorAll('meta[property="og:title"], meta[name="twitter:title"]');
        metaTags.forEach(function(tag) {
            tag.setAttribute('content', 'MB Wiki - The Official Wiki');
        });
    }
    fixMetaTags();
    
    console.log('Emergency title fix applied');
})();