MediaWiki:Common.js

From Primal Fear 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.
/* Any JavaScript here will be loaded for all users on every page load. */

// #region I18n accessor factory
// This takes in a module name and a localised string table (map[language -> map[name -> string]]),
// and returns a function to look-up a string by its name.
// Translations should either be put into the script's string table, or provided locally via
// [[MediaWiki:Common.js]].
// To provide a string locally, provide window.arkLocalI18n (map[module -> map[name -> string]]).
window.arkCreateI18nInterface = function(module, strings) {
    var lang = mw.config.get('wgPageContentLanguage');
    var localStrings = window.arkLocalI18n && window.arkLocalI18n[module];
    return function (key) {
        return ( // try from local store
                 (localStrings && localStrings[key])
                 // try from script store
                 || (strings[lang] && (strings[lang][key] || strings['en'][key]))
                 // fallback
                 || '<'+key+'>' );
    };
};
// #endregion


// #region importArticles with transparent ARK Wiki interwiki support
window.arkIsEnglishWiki = false; // Required for interface compatibility
function getArticleAsModule(pageName) {
	pageName = pageName.replace(/^en:/, 'arkgg:'); // Remap "en" to "arkgg" for compatibility
    if (!pageName.startsWith('arkgg:')) {
        return pageName;
    }
    return arkIsEnglishWiki ? (pageName.slice(6)) : ('u:'+pageName);
}
window.arkImportArticles = function(articles) {
    // Race warning: the ImportArticles extension script might be loaded after our script. Require it before executing the call.
    mw.loader.using(['ext.importarticles'], function() {
        importArticles({ type: 'script', articles: articles.map(getArticleAsModule) });
    });
}
window.arkUsingArticles = function(articles, callback) {
    return mw.loader.using(articles.map(getArticleAsModule), callback);
}
// #endregion


// #region Conditionally loaded modules
// Extracted into global scope, so translation wikis or gadgets can insert their own if needed in future.
window.arkConditionalModules = (window.arkConditionalModules||[]).concat([
    // [[Template:LoadPage]]
    [ '.load-page', [ 'arkgg:MediaWiki:LoadPage.js' ] ],
    // Countdown timers
    [ '.countdown', [ 'arkgg:MediaWiki:Countdown.js' ] ],
    // Creature article scripts
    [ '.cloningcalc, .killxpcalc', [
        // Kill XP calculator
        'arkgg:MediaWiki:KillXP.js',
        // Experimental cloning calculator
        'arkgg:MediaWiki:CloningCalculator.js' 
    ] ],
]);
// #endregion


// #region Disable animations for #mw-head collapsing
mw.loader.using('skins.vector.legacy.js', function() {
    var realFn = $.collapsibleTabs.handleResize;
    $.collapsibleTabs.handleResize = function () {
        realFn();
        $('#mw-head .mw-portlet .collapsible').finish();
    };
});
// #endregion


/* Fires when DOM is ready */
$(function(){
    // #region Make sidebar sections collapsible
    $("#mw-panel .portal").each(function(index, el){
        var $el = $(el);
        var $id = $el.attr("id");
        if(!$id){
            return;
        }
        if(localStorage.getItem('sidebar_c_'+$id) === "y"){
            $el.addClass('collapsed').find('.body').slideUp(0);
        }
    });
    $("#mw-panel .portal").on("click", "h3", function(event){
        var $el = $(this).parent();
        var $id = $el.attr("id");
        if(!$id){
            return;
        }
        event.stopPropagation();
        $el.toggleClass('collapsed');
        if($el.hasClass('collapsed')){ // more consistent between class and slide status.
            $el.find('.body').slideUp('fast');
            localStorage.setItem('sidebar_c_'+$id, "y");
        }
        else{
            $el.find('.body').slideDown('fast');
            localStorage.setItem('sidebar_c_'+$id, "n");
        }
    });
    // #endregion

    // #region Copy to clipboard
    {
        var I18n = arkCreateI18nInterface('CopyToClipboard', {
            en: {
                ButtonTitle: 'Copy to clipboard',
                Success: 'Successfully copied to clipboard.',
                Failure: 'Copy to Clipboard failed. Please do it yourself.'
            }
        });
        function selectElementText(element) {
            var range, selection;    
            if (document.body.createTextRange) {
                range = document.body.createTextRange();
                range.moveToElementText(element);
                range.select();
            } else if (window.getSelection) {
                selection = window.getSelection();        
                range = document.createRange();
                range.selectNodeContents(element);
                selection.removeAllRanges();
                selection.addRange(range);
            }
        }
        $('.copy-clipboard').each(function () {
            var $this = $(this);
            var $button = $('<button title="'+I18n('ButtonTitle')+'">&#xf0ea;</button>');
            $this.append($button);
            $button.click(function () {
                var $content = $this.find('.copy-content');
                $content.children().remove();
                selectElementText($content[0]);
            
                try {
                    if (!document.execCommand('copy'))
                        throw 42;
                    mw.notify(I18n('Success'));
                } catch (err) {
                    mw.notify(I18n('Failure'), {type:'error'});
                }
            });
        });
    }
    // #endregion

    // #region Load our other scripts conditionally
    arkConditionalModules.forEach(function (req) {
        if (document.querySelectorAll(req[0]).length > 0) {
            arkImportArticles(req[1])
        }
    });
    // #endregion

});
/* End DOM ready */