Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Common.js: Difference between revisions

MediaWiki interface page
mNo edit summary
mNo edit summary
Line 41: Line 41:
     var defaultBackgrounds = ['https://cemodding.wiki/images/1/1f/Wiki_page.png'];
     var defaultBackgrounds = ['https://cemodding.wiki/images/1/1f/Wiki_page.png'];


     function preloadImage(url) {
    // Function to preload the image
     function preloadImage(url, callback) {
         var img = new Image();
         var img = new Image();
        img.onload = () => callback(true);
        img.onerror = () => callback(false);
         img.src = url;
         img.src = url;
     }
     }


     // Preload all background images
     // Function to get a random background from an array
    Object.values(categoryBackgrounds).flat().forEach(preloadImage);
    defaultBackgrounds.forEach(preloadImage);
 
     function getRandomBackground(images) {
     function getRandomBackground(images) {
         return images[Math.floor(Math.random() * images.length)];
         return images[Math.floor(Math.random() * images.length)];
Line 57: Line 57:
     let selectedBackground = null;
     let selectedBackground = null;


    // Apply background image after checking if it's loaded
     function applyBackground() {
     function applyBackground() {
         const htmlElement = document.documentElement;
         const htmlElement = document.documentElement;
         const isLightMode = htmlElement.classList.contains("skin-citizen-light");
         const isLightMode = htmlElement.classList.contains("skin-citizen-light");
        let backgroundUrl = "";


         if (isLightMode) {
         if (isLightMode) {
             // Light mode background
             backgroundUrl = 'https://cemodding.wiki/images/c/c8/Lightgreybackground.png';
            $('body').css({
                'background': 'url("https://cemodding.wiki/images/c/c8/Lightgreybackground.png")',
                'background-repeat': 'no-repeat',
                'background-position': 'top center',
                'background-size': 'cover',
                'background-attachment': 'fixed'
            });
         } else {
         } else {
             // If background is already selected, don't change it
             // Pick a random category background
            if (!selectedBackground) {
            for (let category of categories) {
                // Pick a random category background
                if (categoryBackgrounds[category]) {
                for (let category of categories) {
                    selectedBackground = getRandomBackground(categoryBackgrounds[category]);
                    if (categoryBackgrounds[category]) {
                    break;
                        selectedBackground = getRandomBackground(categoryBackgrounds[category]);
                        break;
                    }
                 }
                 }
            }


                // If no category-specific background, use default
            // If no category-specific background, use default
                if (!selectedBackground) {
            if (!selectedBackground) {
                    selectedBackground = getRandomBackground(defaultBackgrounds);
                selectedBackground = getRandomBackground(defaultBackgrounds);
                }
             }
             }


             // Apply background (fixed, no random changes while on page)
             backgroundUrl = selectedBackground;
            $('body').css({
                'background': `linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.15)), url("${selectedBackground}")`,
                'background-repeat': 'no-repeat',
                'background-position': 'top center',
                'background-size': 'cover',
                'background-attachment': 'fixed'
            });
         }
         }
        // Preload and check if the background image is loaded
        preloadImage(backgroundUrl, function (isLoaded) {
            if (isLoaded) {
                console.log("✅ Background image loaded successfully!");
                $('body').css({
                    'background': isLightMode
                        ? `url("${backgroundUrl}")`
                        : `linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.15)), url("${backgroundUrl}")`,
                    'background-repeat': 'no-repeat',
                    'background-position': 'top center',
                    'background-size': 'cover',
                    'background-attachment': 'fixed'
                });
                $('#loading-screen').fadeOut(500);
            } else {
                console.error("❌ Background image failed to load.");
                // Fallback or other handling here, e.g., applying a default background or retrying
                $('#loading-screen').fadeOut(500);
            }
        });
     }
     }


     // Apply the background on page load
     // Apply the background when the page loads
     applyBackground();
     applyBackground();


Line 108: Line 115:
     observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
     observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
});
});




Line 261: Line 269:
         } else {
         } else {
             content.show();
             content.show();
        }
    });
});
$(document).ready(function () {
    console.log("🔄 Loading screen script initialized.");
    if ($('#loading-screen').length === 0) {
        $('body').prepend(`
            <div id="loading-screen">
                <div class="loading-circle"></div>
                <p>Loading...</p>
            </div>
        `);
    }
    let preloadedPages = new Map();
    // Function to force reload the background image and check its status
    function waitForBackgroundToLoad(callback) {
        let backgroundUrl = $('body').css('background-image');
        let match = backgroundUrl.match(/url\(["']?(.*?)["']?\)/);
        let bgImageUrl = match ? match[1] : null;
        if (bgImageUrl) {
            console.log("🖼 Detected Background URL:", bgImageUrl);
            // Add a random query parameter to force reload (bypass cache)
            let reloadUrl = bgImageUrl + "?t=" + new Date().getTime();
            // Create a new Image object to check the background load explicitly
            let img = new Image();
            img.src = reloadUrl;
            // Check if the image is cached
            if (img.complete) {
                console.log("✅ Background image already loaded (cached).");
                callback();
            } else {
                img.onload = function () {
                    console.log("✅ Background image loaded!");
                    callback();
                };
                img.onerror = function () {
                    console.error("❌ Failed to load background image!");
                    callback();
                };
                // Failsafe: Hide after 5 seconds max
                setTimeout(() => {
                    console.warn("⏳ Failsafe triggered: Hiding loading screen after 5s.");
                    callback();
                }, 5000);
            }
        } else {
            console.warn("⚠ No background image detected, skipping check.");
            callback();  // No background image, hide the loading screen immediately
        }
    }
    // Function to check if all images have loaded
    function waitForImagesToLoad(callback) {
        let images = $('body').find('img');
        let loadedImages = 0;
        let totalImages = images.length;
        if (totalImages === 0) {
            callback();
            return;
        }
        images.each(function () {
            let imgElement = $(this);
            if (imgElement[0].complete) {
                loadedImages++;
            } else {
                imgElement.on('load', function () {
                    loadedImages++;
                    if (loadedImages === totalImages) callback();
                });
            }
        });
        setTimeout(callback, 5000); // Failsafe: Hide after 5s if images take too long
    }
    // Function to hide the loading screen
    function hideLoadingScreen() {
        console.log("📉 Fading out loading screen...");
        $('#loading-screen').fadeOut(500, function () {
            $(this).hide();
        });
    }
    // On page load
    $(window).on('load', function () {
        console.log("🌐 Window fully loaded, checking background image...");
        waitForBackgroundToLoad(function () {
            // After background image is handled, check for other images
            waitForImagesToLoad(hideLoadingScreen);
        });
    });
    // For link navigation
    $('a').on('click', function (event) {
        var link = $(this).attr('href');
        if (link && link.startsWith(window.location.origin) && !link.includes('#')) {
            event.preventDefault();
            console.log("🔄 Navigating to:", link);
            $('#loading-screen').css({ display: 'flex', opacity: '1' });
            setTimeout(() => {
                window.location.href = link;
            }, 100);
        }
    });
    // For link prefetching
    $('a').on('mouseenter', function () {
        var link = $(this).attr('href');
        if (link && link.startsWith(window.location.origin) && !preloadedPages.has(link)) {
            let preloadLink = document.createElement('link');
            preloadLink.rel = 'prefetch';
            preloadLink.href = link;
            document.head.appendChild(preloadLink);
            preloadedPages.set(link, preloadLink);
        }
    });
    $('a').on('mouseleave', function () {
        var link = $(this).attr('href');
        if (preloadedPages.has(link)) {
            document.head.removeChild(preloadedPages.get(link));
            preloadedPages.delete(link);
         }
         }
     });
     });
});
});

Revision as of 19:19, 10 February 2025

/* Any JavaScript here will be loaded for all users on every page load. */
 $(function(){
  $('.card').on('mousenter', function(event){
    event.preventDefault();
    $(this).toggleClass('hovered');
  });
   $('.card').on('mouseleave', function(event){
    event.preventDefault();
    $(this).toggleClass('hovered');
  });
});


$(document).ready(function () {
    var categories = mw.config.get('wgCategories');

    var categoryBackgrounds = {
        'Dead Island': ['https://cemodding.wiki/images/5/5b/Dead_islan_background.png'],
        'Dying Light': ['https://cemodding.wiki/images/f/fe/Dying_light.png'],
        'Call of Juarez: Gunslinger': ['https://cemodding.wiki/images/4/4b/Call_of_juaez_gunslinger.png'],
        'Dead Island Riptide': ['https://cemodding.wiki/images/b/b6/Random_project_di_riptide_1.png'],
        'Dead Island Riptide DE': ['https://cemodding.wiki/images/0/09/Dead_island_riptide_DE.png'],
        'Call of Juarez: BiB': ['https://cemodding.wiki/images/2/24/Project_juaez_no_title_1.png'],
        'Call of Juarez: The Cartel': ['https://cemodding.wiki/images/6/64/Callofjuarezcartel.png'],
        'Call of Juarez': [
            'https://cemodding.wiki/images/c/cf/Call_of_juarez_background_1.png',
            'https://cemodding.wiki/images/3/38/Call_of_juarez_background_2.png'
        ],
        'Dead Island DE': ['https://cemodding.wiki/images/4/45/Dead_island_DE.png'],
        'Dying Light: The Beast': [
            'https://cemodding.wiki/images/1/12/Dying_light_the_beast.png',
            'https://cemodding.wiki/images/c/c3/Dying_light_the_beast_2.png'
        ],
        'Dying Light 2': [
            'https://cemodding.wiki/images/0/04/Dying_light_2.png',
            'https://cemodding.wiki/images/0/02/Dying_light_2_.png',
            'https://cemodding.wiki/images/3/3f/Dying_light_2_some_layered_effects.png'
        ]
    };

    var defaultBackgrounds = ['https://cemodding.wiki/images/1/1f/Wiki_page.png'];

    // Function to preload the image
    function preloadImage(url, callback) {
        var img = new Image();
        img.onload = () => callback(true);
        img.onerror = () => callback(false);
        img.src = url;
    }

    // Function to get a random background from an array
    function getRandomBackground(images) {
        return images[Math.floor(Math.random() * images.length)];
    }

    // Store background for this session
    let selectedBackground = null;

    // Apply background image after checking if it's loaded
    function applyBackground() {
        const htmlElement = document.documentElement;
        const isLightMode = htmlElement.classList.contains("skin-citizen-light");

        let backgroundUrl = "";

        if (isLightMode) {
            backgroundUrl = 'https://cemodding.wiki/images/c/c8/Lightgreybackground.png';
        } else {
            // Pick a random category background
            for (let category of categories) {
                if (categoryBackgrounds[category]) {
                    selectedBackground = getRandomBackground(categoryBackgrounds[category]);
                    break;
                }
            }

            // If no category-specific background, use default
            if (!selectedBackground) {
                selectedBackground = getRandomBackground(defaultBackgrounds);
            }

            backgroundUrl = selectedBackground;
        }

        // Preload and check if the background image is loaded
        preloadImage(backgroundUrl, function (isLoaded) {
            if (isLoaded) {
                console.log("✅ Background image loaded successfully!");
                $('body').css({
                    'background': isLightMode
                        ? `url("${backgroundUrl}")`
                        : `linear-gradient(rgba(0, 0, 0, 0.15), rgba(0, 0, 0, 0.15)), url("${backgroundUrl}")`,
                    'background-repeat': 'no-repeat',
                    'background-position': 'top center',
                    'background-size': 'cover',
                    'background-attachment': 'fixed'
                });
                $('#loading-screen').fadeOut(500);
            } else {
                console.error("❌ Background image failed to load.");
                // Fallback or other handling here, e.g., applying a default background or retrying
                $('#loading-screen').fadeOut(500);
            }
        });
    }

    // Apply the background when the page loads
    applyBackground();

    // Observe theme switch (Light/Dark mode toggle)
    const observer = new MutationObserver(() => {
        setTimeout(() => applyBackground(), 50); // Prevent flicker
    });

    observer.observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
});








$(function () {
    var categoryList = [];

    // Fetch categories from the API
    $.ajax({
        url: mw.util.wikiScript('api'),
        data: {
            action: 'query',
            list: 'allcategories',
            aclimit: '500',
            format: 'json'
        },
        dataType: 'json',
        success: function (data) {
            categoryList = data.query.allcategories.map(function (cat) {
                return cat['*'];
            });
        }
    });

    function createSuggestionBox(input, suggestions, cursorPosition) {
        $('.category-suggestions').remove(); // Clear old suggestions

        var suggestionBox = $('<ul class="category-suggestions"></ul>').css({
            position: 'absolute',
            zIndex: 1000,
            backgroundColor: 'rgba(0, 0, 0, 0.7)',
            color: 'white',
            border: '1px solid #ccc',
            padding: '0',
            listStyleType: 'none',
            margin: '0',
            maxHeight: '200px',
            overflowY: 'auto',
            cursor: 'pointer'
        });

        suggestions.forEach(function (suggestion) {
            var item = $('<li></li>').text(suggestion).css({ padding: '5px' });
            item.on('mousedown', function () {
                var text = input.val();
                var beforeCursor = text.substring(0, cursorPosition).replace(/\[\[Category:[^\]]*$/, '[[Category:' + suggestion);
                var afterCursor = text.substring(cursorPosition);
                input.val(beforeCursor + afterCursor);
                suggestionBox.remove();
            });
            suggestionBox.append(item);
        });

        $('body').append(suggestionBox);
        positionSuggestionBox(input, cursorPosition, suggestionBox);
    }

    function positionSuggestionBox(input, cursorPos, suggestionBox) {
        var text = input.val().substring(0, cursorPos);
        var textarea = input[0];
        var div = $('<div></div>').css({
            position: 'absolute',
            whiteSpace: 'pre-wrap',
            wordWrap: 'break-word',
            visibility: 'hidden',
            font: input.css('font'),
            padding: input.css('padding'),
            width: input.width(),
            lineHeight: input.css('line-height')
        }).appendTo('body');
        
        // Simulate the text up to the cursor
        var beforeCursorText = text.replace(/ /g, '\u00a0');  // Non-breaking spaces for correct width
        div.text(beforeCursorText);
        var span = $('<span>|</span>').appendTo(div);  // Add a cursor marker
        var cursorOffset = span.offset();

        // Adjust position to match textarea
        var inputOffset = input.offset();
        suggestionBox.css({
            top: inputOffset.top + (cursorOffset.top - div.offset().top) + parseInt(input.css('padding-top'), 10),
            left: inputOffset.left + (cursorOffset.left - div.offset().left) + parseInt(input.css('padding-left'), 10)
        });

        div.remove();
    }

    $('#wpTextbox1').on('input', function () {
        var input = $(this);
        var cursorPos = this.selectionStart;
        var text = input.val().substring(0, cursorPos);
        var match = text.match(/\[\[Category:([^\]]*)$/);
        if (match) {
            var partial = match[1].toLowerCase();
            var matches = categoryList.filter(function (category) {
                return category.toLowerCase().startsWith(partial);
            }).slice(0, 10);  // Limit suggestions
            if (matches.length) {
                createSuggestionBox(input, matches, cursorPos);
            }
        } else {
            $('.category-suggestions').remove();
        }
    });

    $(document).on('mousedown', function (e) {
        if (!$(e.target).closest('.category-suggestions').length) {
            $('.category-suggestions').remove();
        }
    });
});

$(document).ready(function() {
    $('.mw-collapsible-header').each(function() {
        // Wrap indicator and spinner inside a container for positioning
        $(this).prepend('<span class="mw-collapsible-icon"><span class="mw-collapsible-indicator">•</span><span class="mw-collapsible-loading hidden"></span></span> ');
    });

    $('.mw-collapsible-header').click(function() {
        var parentDiv = $(this).closest('.mw-collapsible');
        var content = parentDiv.find('.mw-collapsible-content');
        var indicator = $(this).find('.mw-collapsible-indicator');
        var spinner = $(this).find('.mw-collapsible-loading');

        // Fade out indicator and show spinner at the same position
        indicator.addClass('fade-out');
        setTimeout(() => {
            spinner.removeClass('hidden');
        }, 100);

        // Toggle content visibility
        parentDiv.toggleClass('mw-collapsed');
        content.stop(true, true).slideToggle();

        // Restore indicator and hide spinner after animation
        setTimeout(function() {
            indicator.removeClass('fade-out');
            spinner.addClass('hidden');
        }, 300);
    });

    // Ensure correct initial state for collapsibles
    $('.mw-collapsible').each(function() {
        var parentDiv = $(this);
        var content = parentDiv.find('.mw-collapsible-content');

        if (parentDiv.hasClass('mw-collapsed')) {
            content.hide();
        } else {
            content.show();
        }
    });
});
Cookies help us deliver our services. By using our services, you agree to our use of cookies.