MediaWiki:Gadget-PreloadTemplates.js: Difference between revisions

From Tardis Wiki, the free Doctor Who reference
(Created page with "// ================================ // Custom preload templates // ================================ /* @author Grunny From http://harrypotter.wikia.com/wiki/Media...")
 
(+de, better skin support)
Line 49: Line 49:
                 devWiki: 'Check the documentation on Dev Wiki',
                 devWiki: 'Check the documentation on Dev Wiki',
                 error: 'No valid syntax found at $1 or page is missing.'
                 error: 'No valid syntax found at $1 or page is missing.'
            },
            // German
            de: {
                preload: 'Preload-Vorlage:',
                choose: '(Auswählen)',
                help: 'Wähle eine Textvorlage, die an der aktuellen Position eingefügt werden soll',
                devWiki: 'Lies die Dokumenation im Dev-Wiki',
                error: 'Keine gültige Syntax unter $1 gefunden bzw. keine Seite.'
             },
             },
             // Italian
             // Italian
Line 97: Line 105:
     if (skin === 'oasis') {
     if (skin === 'oasis') {
         $('div.module_content:first').append('<div id="preload-templates" style="display:block; padding:0 10px;"><h3 style="font-size:14px;">' + i18n.preload + '</h4></div>');
         $('div.module_content:first').append('<div id="preload-templates" style="display:block; padding:0 10px;"><h3 style="font-size:14px;">' + i18n.preload + '</h4></div>');
     } else if (skin === 'monobook') {
     } else {
         $('div.editButtons').append('<div id="preload-templates" style="display:block; float:right; padding:10px;">' + i18n.preload + '&nbsp;</div>');
         $('div.editButtons').append('<div id="preload-templates" style="display:block; float:right; padding:10px;">' + i18n.preload + '&nbsp;</div>');
     }
     }

Revision as of 09:40, 9 October 2016

//  ================================
//      Custom preload templates
//  ================================
/*  @author Grunny 
    From http://harrypotter.wikia.com/wiki/MediaWiki:Wikia.js
    edited by leviathan_89

    ** Info: **
    Template list loaded by default from "MediaWiki:Custom-PreloadTemplates",
    each syntax is loaded by default from the "/preload" subpage of the
    template.
*/

$(function() {

    // Run conditions
    if (    wgAction != 'edit' || 
            (!$('div.module_content').length && skin == 'oasis') ||
            (!$('div.editButtons').length && skin == 'monobook') ||
             mw.config.get('wgNamespaceNumber') == 8 // MediaWiki:
        ) {
        return;
    }
    
    // =================
    //   Configuration
    // =================
    var config = {
            list: null,
            subpage: null
        };

    // Checking user's custom settings
    config.list = ( typeof preloadTemplates_list == 'string' ) ? preloadTemplates_list : 'MediaWiki:Custom-PreloadTemplates';
    config.subpage = ( typeof preloadTemplates_subpage == 'string' ) ? preloadTemplates_subpage : 'preload';


    // ========
    //   i18n
    // ========
    var lang = mw.config.get('wgUserLanguage');
    var splitLang = lang.split('-')[0];
    var i18n = {
            // English
            en: {
                preload: 'Preload template:',
                choose: '(choose)',
                help: 'Select a template to insert its preloaded syntax at the current position ',
                devWiki: 'Check the documentation on Dev Wiki',
                error: 'No valid syntax found at $1 or page is missing.'
            },
            // German
            de: {
                preload: 'Preload-Vorlage:',
                choose: '(Auswählen)',
                help: 'Wähle eine Textvorlage, die an der aktuellen Position eingefügt werden soll',
                devWiki: 'Lies die Dokumenation im Dev-Wiki',
                error: 'Keine gültige Syntax unter $1 gefunden bzw. keine Seite.'
            },
            // Italian
            it: {
                preload: 'Precarica un template:',
                choose: '(scegli)',
                help: 'Seleziona un template per inserire la sua sintassi precaricata nella posizione corrente',
                devWiki: 'Controlla la documentazione su Dev Wiki',
                error: 'Nessuna sintassi valida trovata su $1 o la pagina è mancante.'
            },
            // Polish
            pl: {
                preload: 'Gotowy szablon:',
                choose: '(wybierz)',
                help: 'Wybierz przygotowany szablon, aby wstawić kod w obecnym miejscu',
                devWiki: 'Zobacz dokumentację na Dev Wiki',
                error: 'Nie znaleziono odpowiedniej składni w $1 lub strona nie istnieje.'
            }
    };

    // Select language
    // Check if user's language is present
    if (typeof i18n[lang] === 'object') {
        $.extend( i18n, i18n.en, i18n[lang] );
    } else {
        // Check to see if the parent language has a translation, example pt-br -> pt
        if (typeof i18n[splitLang] === 'object') {
            $.extend( i18n, i18n.en, i18n[splitLang] );
        } else {
        // Fallback to English
        $.extend( i18n, i18n.en );
        }
    }
    // END i18n

    // =============
    //   Execution  
    // =============
    
    // Variables
    var namespace = mw.config.get('wgFormattedNamespaces')['10'];
    var $preloadOptionsHtml;
    var preloadOptionsList;
    var defaultOption = '<option selected disabled>' + i18n.choose + '</option>';
    var preloadHelp = '<span style="display:inline-block; vertical-align:middle; cursor:help; margin-left:5px;" class="sprite question"><a href="http://dev.wikia.com/wiki/PreloadTemplates" target="_blank" title="' + i18n.devWiki + '" style="display:inline-block; width:12px; height:12px;"></a></span>';

    // Append HTML container
    if (skin === 'oasis') {
        $('div.module_content:first').append('<div id="preload-templates" style="display:block; padding:0 10px;"><h3 style="font-size:14px;">' + i18n.preload + '</h4></div>');
    } else {
        $('div.editButtons').append('<div id="preload-templates" style="display:block; float:right; padding:10px;">' + i18n.preload + '&nbsp;</div>');
    }

    // Create template list
    // Get list
    $.get(wgScript, {
            title: mw.util.wikiUrlencode(config.list), // Encode string for eventual special characters
            action: 'raw',
            ctype: 'text/plain'
    }).done( function(listData) {
            var listDataParsed = parseMW(listData); // Parse data for MediaWiki tags
            var lines = listDataParsed.split('\n'); // Split data in lines

            // Display error if no valid data is present
            if ( listDataParsed === '' ) {
                $('div#preload-templates').append( i18n.error.replace('$1' , '"<a href="/wiki/' + mw.util.wikiUrlencode(config.list) + '">' + config.list + '</a>"') ).append(preloadHelp);
                return;
            }
            
            // Building the list HTML
            for (var i in lines) {
                var title;
                var string;

                // Ignore empty lines
                if (lines[i].trim() === '') {
                    continue;
                }
                // Text in a list is the template name
                if (lines[i].indexOf('*') === 0) {
                    title = lines[i].substring(1).trim();
                    $preloadOptionsHtml += '<option value="' + title + '">' + title + '</option>';
                } else {
                    // Rest are normal strings
                    string = lines[i];
                    $preloadOptionsHtml += '<option disabled>' + string + '</option>';
                }
            }
                
            // Build list HTML
            preloadOptionsList = $('<select />').attr('id', 'pt-list').attr('title', i18n.help).css('max-width' , '220px').html(defaultOption + $preloadOptionsHtml).change(function() {
                    var templateTitle = $(this).val();
                    
                    // Restore default option
                    $('#pt-list option:first-child').prop('selected', true);

                    // Preload the template on click
                    getPreloadPage(templateTitle);
                });

            // Append template list and messageges
            $('div#preload-templates').append(preloadOptionsList).append(preloadHelp);

            // Import required CSS for monobook
            if (skin === 'monobook') {
                // Importing sprite for monobook
                $('.sprite.question').css({
                    'background-image': 'url(http://slot1.images.wikia.nocookie.net/__cb1475164013/common/skins/shared/images/sprite.png)',
                    'background-position': '-1144px -20px',
                    'background-color': 'transparent',
                    'background-repeat': 'no-repeat',
                    'height': '12px',
                    'width': '12px'
                });
            }
    }).fail( function(){
        // Add an error if failed to retrieve list
        $('div#preload-templates').append( i18n.error.replace('$1' , '"<a href="/wiki/' + mw.util.wikiUrlencode(config.list) + '">' + config.list + '</a>"') ).append(preloadHelp);
    });

    // =============
    //   Functions  
    // =============

    // Get preload text and add it to the text area
    function getPreloadPage(title) {
        var page = namespace + ':' + title + '/' + config.subpage;
        
        $.get(wgScript, {
                title: mw.util.wikiUrlencode(page), // Encode string for eventual special characters
                action: 'raw',
                ctype: 'text/plain'
        }).done(function(preloadData) {
            // Parse some MediaWiki tags
            var preloadDataParsed = parseMW(preloadData);
            
            // Display error if no useful data is present
            if ( preloadDataParsed === '' ) {
                notFound(page);
                return;
            }

            // Insert syntax
            if (document.getElementById('wpTextbox1')) {
                insertAtCursor(document.getElementById('wpTextbox1'), preloadDataParsed);
            } else {
                // Visual editor
                insertAtCursor(document.getElementsByClassName('cke_source')[0], preloadDataParsed);
            }
        }).fail( function(){
            notFound(page);
        });
    }

    // Inserts text at the cursor's current position - originally from Wookieepedia
    function insertAtCursor(myField, myValue) {
    //IE support
        if (document.selection) {
            myField.focus();
            sel = document.selection.createRange();
            sel.text = myValue;
        }
        //MOZILLA/NETSCAPE support
        else if (myField.selectionStart || myField.selectionStart == '0') {
            var startPos = myField.selectionStart;
            var endPos = myField.selectionEnd;
            myField.value = myField.value.substring(0, startPos) +
                myValue +
                myField.value.substring(endPos, myField.value.length);
        } else {
            myField.value += myValue;
        }
    }
    
    // Parse MediaWiki code to allow the use of incudeoonly and noninclude tags in the preload page
    function parseMW(source){
        var parsed = source.replace(/<includeonly>(\n)?|(\n)?<\/includeonly>|\s*<noinclude>[^]*<\/noinclude>/g, '');
        
        return parsed;
    }
    
    // Error alert
    function notFound(page){
        var message = i18n.error.replace('$1' , '"' + page + '"');
        
        alert(message);
    }
});