MediaWiki:PreloadTemplates.js

// ================================ //      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.' },           // 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 = ' ' + i18n.choose + ' '; var preloadHelp = ' ';

// Append HTML container if (skin === 'oasis') { $('div.module_content:first').append(' ' + i18n.preload + ' '); } else if (skin === 'monobook') { $('div.editButtons').append(' ' + i18n.preload + ' '); }

// 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', '"' + config.list + '"') ).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 += '' + title + ' '; } else { // Rest are normal strings string = lines[i]; $preloadOptionsHtml += ' ' + string + ' '; }           }            // Build list HTML preloadOptionsList = $(' ').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', '"' + config.list + '"') ).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(/ (\n)?|(\n)?<\/includeonly>|\s* [^]*<\/noinclude>/g, ''); return parsed; }   // Error alert function notFound(page){ var message = i18n.error.replace('$1', '"' + page + '"'); alert(message); } });