User:Darkbitlike/global.js

importArticles({   type: 'script',    articles: [        'u:dev:MediaWiki:View Source/code.js',        'u:dev:MediaWiki:ViewRemoved/code.js',        'u:dev:MediaWiki:RevealAnonIP/usercode.js',        'u:dev:MediaWiki:LastEdited/code.js',        'u:dev:MediaWiki:UnhideUserMasthead/code.js',        'u:dev:MediaWiki:Discussions Delete All/code.js',        // Tools        'u:dev:MediaWiki:RecentChangesMultiple/code.2.js',        'u:dev:MediaWiki:GlobalEditcount/code.js',        'u:dev:MediaWiki:UserAndIPTools.js',        'u:dev:WHAM/code.js',    ] });

if (wgPageName == 'Special:Imagelist') { addOnloadHook(imagelistTools); } function imagelistTools { addPortletLink('p-cactions', 'javascript:showFLimages(0)', 'Show images (full)', 'ca-showim0', 'loads the images in a full sized image tag'); addPortletLink('p-cactions', 'javascript:showFLimages(1)', 'Show images (small)', 'ca-showim1', 'loads the images in a 200x200 image tag'); addPortletLink('p-cactions', 'javascript:filelistprune', 'Desc links only', 'ca-prune', 'turns the whole page into just a list of links'); } function showFLimages(full) { var links = document.getElementById('bodyContent').getElementsByTagName('a'); var img; for (var i = 0; i < links.length; i++) { if (links[i].firstChild.nodeValue == 'file') { links[i].firstChild.nodeValue = ''; links[i].parentNode.setAttribute('class', 'plainlinks'); img = document.createElement('img'); img.setAttribute('src', links[i].href); if (full == 0) { img.setAttribute('style', 'border:2px outset blue;'); } else { img.setAttribute('style', 'width:200px;height:200px;border:2px outset blue;'); }           links[i].appendChild(img); }   }    document.getElementById('ca-showim0').style.display = 'none'; document.getElementById('ca-showim1').style.display = 'none'; } function filelistprune { var descs = getElementsByClassName(document, 'td', 'TablePager_col_img_name'); var dlist = ' '; for (var i = 0; i < descs.length; i++) { dlist += '' + descs[i].firstChild.title + '\n'; }   dlist += ' \n'; document.getElementById('bodyContent').innerHTML = dlist; document.getElementById('ca-prune').style.display = 'none'; } $(function {   if (mw.config.get('wgNamespaceNumber') == 6) {        $('#WikiaPageHeader').append(' ');        if ($('#ca-undelete').length) {            $('#WikiaPageHeader').append('Undelete | ');        }        $('#WikiaPageHeader').append('Log');        mw.util.addPortletLink('p-cactions', mw.util.wikiGetlink( 'Special:Log?page=' + mw.config.get('wgPageName')), 'Log');    } });

// ***************************************************************** // Load various external scripts // ***************************************************************** // importScriptPage('User:Sannse/forumtools.js', 'community'); // importScriptPage('User:Splarka/contribtools.js', 'community'); // importScriptPage('FastDelete/code.js', 'dev'); /** * Ajax Fast Delete * * @author Splarka * @author Uberfuzzy * @author Grunny * * @version 2.3 */ /*global jQuery, mediaWiki */ "use strict"; window.dev = window.dev || {}; // Don't load twice... if (window.dev.ajaxFastDelete !== undefined) { return false; }   var conf = mw.config.get([            'wgNamespaceNumber',            'wgPageName',            'skin'        ]), self = { version: '2.3', init: function { if (conf.wgNamespaceNumber === -1 || !window.fdButtons || !$('#ca-delete').length) { return; }               var deleteButtons = ''; switch (conf.skin) { case 'uncyclopedia': case 'wowwiki': case 'monobook': deleteButtons = window.fdButtons.map(function (b) {                           var sum = b.summary;                            return '' + b.label + '';                        }).join(''); $('#p-cactions > .pBody > ul').append(deleteButtons); break; case 'oasis': case 'wikia': var $profile = $('.UserProfileActionButton'); deleteButtons = window.fdButtons.map(function (b) {                           var sum = b.summary;                            return '' + b.label + '';                        }).join(' '); if ($profile.exists) { $profile.append(deleteButtons); } else if ($('.page-header__subtitle-blog-post').exists) { $('.page-header__subtitle-blog-post').append(deleteButtons); $('.page-header__blog-post-details').css('margin-right', '5px'); } else { $('.page-header__title').append(deleteButtons); mw.util.addCSS('a[data-id="fastdelete"]:nth-child(1){margin-left:5px}'); }                       break; }               if ($('a[data-id="fastdelete"]').length) { $('a[data-id="fastdelete"]').click(function {                       self.deletePage($(this).attr('data-summary'));                    }); }               mw.hook('fastdelete.init').fire(deleteButtons); },           deletePage: function (deleteReason) { (new mw.Api) .post({                       action: 'delete',                        title: conf.wgPageName,                        reason: deleteReason,                        token: mw.user.tokens.get('editToken')                    }) .done(function (res) {                       location.reload;                    }); }       };    window.dev.ajaxFastDelete = self; mw.loader.using(['mediawiki.util', 'mediawiki.api'], function {        $(self.init);    }); }(window, jQuery, mediaWiki)); // ***************************************************************** // Custom automatic delete buttons // ***************************************************************** // Adds customizable one-click deletion buttons to any deletable page. // Requires w:User:Splarka/fastdelete.js in appendScript; var fdButtons = []; fdButtons[fdButtons.length] = {   'summary': '* Violation of Fandom\'s Terms of Use ',    'label': 'ToU-Violation' }; fdButtons[fdButtons.length] = {    'summary': 'Requested deletion',    'label': 'request-deletion' }; fdButtons[fdButtons.length] = {    'summary': 'Spam ',    'label': 'Spam' }; fdButtons[fdButtons.length] = {    'summary': 'Removed due to DMCA claim',    'label': 'DMCA' }; fdButtons[fdButtons.length] = {    'summary': 'Housekeeping',    'label': 'house-keep' }; fdButtons[fdButtons.length] = {    'summary': 'Unused video', 'label': 'unused-vid' }; // end Custom automatic delete buttons if (wgNamespaceNumber != -1) addOnloadHook(function {   addPortletLink('p-cactions', '/wiki/Special:Prefixindex/' + escape(wgPageName), 'Subpages', 'ca-subpages', 'Show subages of ' + wgPageName); }); //gear fixer (from uberfuzzy) $('a[data-name="customize"]').html(function {   return $(this).parent.find('img').detach; }); //Thingy from Sactage to fix lookupuser $(function {   if (mw.config.get('wgCanonicalSpecialPageName') === 'Contributions' && mw.config.get('wgCityId') != '177') {        var target = mw.util.getParamValue('target') || mw.config.get('wgPageName').split('/', 2)[1] || null;        if (!target) {            return;        }        $('#contentSub > a:nth-child(9)').attr('href', 'http://community.wikia.com/wiki/Special:LookupUser?target=' + encodeURIComponent(target));    } }); /** * @author: Flightmare (http://elderscrolls.wikia.com/wiki/User:Flightmare) * @version: 1.0 * @license: CC-BY-SA 3.0 * @description: Imports biography from discussions to ns:2 if no profile page is present. */ //replace redlink placeholder with discussions bio. function addDProfile(text) { var content = document.getElementsByClassName("noarticletext")[0]; content.innerHTML = text.replace(/(?:\r\n|\r|\n)/g, ' '); } function getUserBio(userId) { var request = new XMLHttpRequest; request.onreadystatechange = function { if (request.readyState == 4 && request.status == 200) { var arr = JSON.parse(request.responseText); if (Boolean(arr.value)) { //Only continue if there is an actual bio written. addDProfile(arr.value); }       }    };    request.open("GET", "https://services.wikia.com/user-attribute/user/" + userId + "/attr/bio", true); request.send; } //Is there a better way to get the user id? function getUserIdByName(username) { var request = new XMLHttpRequest; request.onreadystatechange = function { if (request.readyState == 4 && request.status == 200) { var arr = JSON.parse(request.responseText); userId = arr["query"]["allusers"][0].id; if (Boolean(userId)) { getUserBio(userId); }       }    };    request.open("GET", "/api.php?action=query&list=allusers&aufrom=" + username + "&format=json&aulimit=1", true); request.send; } $(function createDProfiles {   if (wgNamespaceNumber == 2) {        //Test if profile page exists (we want this to 404)        var request = new XMLHttpRequest;        request.onreadystatechange = function {            if (request.readyState == 4 && request.status == 404) {                var username = wgPageName.substring(wgCanonicalNamespace.length + 1); //This should be i18n-safe.                getUserIdByName(username);            }        };        request.open("GET", "/wiki/" + wgPageName, true);        request.send;    } }); // Adds log link to deleted images header $(function {   if ($('#mw-imagepage-nofile').length) {        $('View logs for this page ').insertAfter('.page-header__title');    } });
 * (function (window, $, mw, undefined) {

// Fire an Vandalism Reverter

mw.loader.using('mediawiki.api', function {	//Exit if normal rollback links are present	if ($('.mw-rollback-link').length || window.RollbackWikiDisable) return;	var conf = mw.config.get([ 'wgAction', 'wgCanonicalSpecialPageName', 'wgContentLanguage', 'wgPageName', 'wgUserLanguage' ]),	i18n = {		en: {			rollback: "rollback",			description: "&quot;Rollback&quot; reverts edit(s) to this page of the last contributor in one click",			summary: "Reverted edits by $1 (talk) to last version by $2 (script)",			summaryShort: "Reverted edits by $1 (script)",			editConflict: "Unable to rollback (edit conflict)",			contentFail: "Unable to rollback (failed to get page content)",			singleEditor: "Unable to rollback (no different editor found)",			revisionFail: "Unable to rollback (failed to get revisions)",			editFail: "Unable to rollback (failed to publish edit)",			success: "Rollback successful"		},		ru: {			rollback: "rollback",			description: "&quot;Rollback&quot; reverts edit(s) to this page of the last contributor in one click",			summary: "Откат правок без статуса откатчика (скрипт)", summaryShort: "Reverted edits by $1 (script)", editConflict: "Произошёл конфликт правок", contentFail: "Произошла ошибка", singleEditor: "Произошла ошибка", revisionFail: "Произошла ошибка", editFail: "Произошла ошибка", success: "Откат совершен" },		fr: { rollback: "révoquer", description: "&quot;Rollback&quot; révoque la/les modification(s) du dernier contributeur de cette page en un clic", summary: "Révoqué les modifications par $1 (talk) à la dernière version par $2 (script)", summaryShort: "Révoqué les modifications par $1 (script)", editConflict: "Impossible de révoquer (conflit de modifications)", contentFail: "Impossible de révoquer (échec de l'obtention du contenu de la page)", singleEditor: "Impossible de révoquer (aucun éditeur différent trouvé)", revisionFail: "Impossible de révoquer (échec de l'obtention des révisions)", editFail: "Impossible de révoquer (échec de la publication de la modification)", success: "Révocation(s) réussie(s) !" }	};	i18n = i18n[conf.wgContentLanguage] || i18n[conf.wgContentLanguage.split('-')[0]] || i18n[conf.wgUserLanguage] || i18n[conf.wgUserLanguage.split('-')[0]] || i18n.en; //History if (conf.wgAction == "history" && $('#pagehistory li').length > 1) $('#pagehistory li:first .mw-history-undo a').before(' ' + i18n.rollback + '</a> | '); //Contributions else if (conf.wgCanonicalSpecialPageName == "Contributions") { $('#mw-content-text ul').find('li').each(function {			if ($(this).find('.mw-uctop').length)				$(this).append(' [' + i18n.rollback + '</a>] ');		}); }	//Diffs else if (($.getUrlVar('diff') || $.getUrlVar('oldid')) && $('#differences-nextlink').length === 0) $('.mw-usertoollinks:last').after('   [' + i18n.rollback + '</a>] '); else return; conf.API = new mw.Api; conf.token = mw.user.tokens.values.editToken; mw.util.addCSS('.mw-custom-rollback-link a { cursor: pointer; }'); $('.mw-custom-rollback-link a').click(function {		getRevisionIdAndContent($(this).data('id'),$(this).data('user').replace(/_/g, " "));		$(this).parent.remove;	}); function getRevisionIdAndContent(title,target) { conf.API.get({		action: 'query',		prop: 'revisions',		titles: title,		rvprop: 'user|ids',		rvlimit: 500,		cb: new Date.getTime		}) .done(function(d) {			if (!d.error) {				var revisions;				for (var i in d.query.pages) {					revisions = d.query.pages[i].revisions;				}				//Don't rollback if the page has been edited by somebody else				if (target != revisions[0].user) {					outputError(i18n.editConflict);					return;				}				var lastUser,				revId;				for (var i in revisions) {					if (revisions[i].user != target) {						lastUser = revisions[i].user; //remember last author						revId = revisions[i].revid; //get revision to revert to						break;					}				}				if (lastUser) {					conf.API.get({ action: 'query', prop: 'revisions', rvprop: 'content', revids: revId, cb: new Date.getTime })					.done(function(d) { if (!d.error) { var content = ""; //can be no content on page for (var i in d.query.pages) { if (d.query.pages[i].revisions) content = d.query.pages[i].revisions[0]["*"]; }							performRollback(title,content,target,lastUser); }						else outputError(i18n.contentFail + ': ' + d.error.code); })					.fail(function { outputError(i18n.contentFail); });				}				else					outputError(i18n.singleEditor);			}			else				outputError(i18n.revisionFail + ': ' + d.error.code);		}) .fail(function {			outputError(i18n.revisionFail);		}); }	function performRollback(page,text,user,user2) { var summary = i18n.summary.replace(/\$1/g,user).replace(/\$2/g,user2); if (summary.length > 150) summary = i18n.summaryShort.replace('$1',user); conf.API.post({		action: 'edit',		title: page,		text: text,		summary: summary,		minor: true,		token: conf.token		}) .done(function(d) {			if (!d.error) {				new BannerNotification(i18n.success,'confirm').show;							}			else				outputError(i18n.editFail + ': ' + d.error.code);		}) .fail(function {			outputError(i18n.editFail);		}); }	function outputError(text) { new BannerNotification(text,'error').show; } });

// Vanguard Tools

/** *  * @module                  VanguardTools * @description            Accelerates Vanguard migration workflow. * @author                 Speedit * @version                1.2.1 * @license                CC-BY-SA 3.0 * */ require(['wikia.window', 'jquery', 'mw', 'wikia.nirvana', 'ext.wikia.design-system.loading-spinner'], function (window, $, mw, nirvana, Spinner) {    'use strict';    // Script variables and double run protection.    if (window.vanguardToolsLoaded) {        return;    }    window.vanguardToolsLoaded = true;    var VAN = {};    // MediaWiki variables.    VAN.mw = mw.config.get([ 'wgMessages', 'wgDBname', 'wgCanonicalNamespace', 'wgCanonicalSpecialPageName', 'wgTitle', 'wgAction', 'wgArticleId', 'wgArticlePath', 'wgLoadScript', 'wgUserGroups' ]);   // User parrot status.    VAN.parrot = VAN.mw.wgUserGroups.some(function(ug) { return ['user'].indexOf(ug) > -1; });   // Script configuration.    VAN.config = window.vanguardToolsConfig || {        state: true,        modules: [],        redirect: true,        nav: true,        template: true,        showdraft: true,        insights: true,        adminalert: true    };    if (VAN.config.modules && !$.isArray(VAN.config.modules)) {        delete VAN.config.modules;    }    // Design system integration.    VAN.wds = {        // Library handler.        handler: function(wds) {            // Cache our design system utils.            $.extend(VAN.wds, wds);            // Asset loading done.            VAN.wds.$loaded.resolve;        },        // Asset loading event.        $loaded: $.Deferred    };    // I18n implementation.    VAN.i18n = {        // Message & utility loader.        handler: function(i18no) {            i18no.loadMessages('VanguardTools').done(VAN.i18n.store);        }, // Message data handler. store: function(i18n) { // Cache our msg data, utils $.extend(VAN.i18n, i18n); // Message loading done. VAN.i18n.$loaded.resolve; },       // I18n event. $loaded: $.Deferred };   // Main script VAN.init = function { if (!VAN.parrot || !VAN.config.state) { return; } // Dispatch dependency handlers. mw.hook('dev.i18n').add(VAN.i18n.handler); mw.hook('dev.wds').add(VAN.wds.handler); // Module activator. $.when(VAN.i18n.$loaded, VAN.wds.$loaded).then(function {           // Run all modules by default.            VAN.config.modules = VAN.config.modules.length > 0 ?                VAN.config.modules :                VAN.modules;            // Validation for modules.            $.each(VAN.config.modules, function(i, m) { if (VAN.modules.indexOf(m) === -1) { VAN.modules.splice(i, 1); }           });            // Initialise all configured modules.            $.each(VAN.config.modules, function(i, m) { VAN[m].init; });           // Post-execution event            $.when.apply(null, VAN.config.modules.map(function(m) {                return VAN[m].$executed;            })).then(function { // Loaded class. $(document.body).addClass('van-is-loaded'); // Fire hook. mw.hook('dev.van').fire(VAN); });       });        // Import dependencies. importArticle({ type: 'script', article: 'u:dev:I18n-js/code.js' }); importArticle({ type: 'script', article: 'u:dev:WDSIcons/code.js' }); importArticle({ type: 'script', article: 'u:dev:ProtectionIcons.js' }); };   // Redirect module for S:IB. VAN.redirect = { init: function { if (               VAN.config.redirect !== true ||                VAN.mw.wgCanonicalSpecialPageName !== 'InfoboxBuilder' ||                VAN.mw.wgTitle.indexOf('/') === -1            ) { VAN.redirect.$executed.resolve; return; }           // Template existence check. VAN.redirect.template = mw.util.wikiUrlencode(VAN.mw.wgTitle.match(/\/([\s\S]+)$/)[1]); nirvana.getJson('PortableInfoboxBuilderController', 'getTemplateExists', {               title: VAN.redirect.template            }, VAN.redirect.builder); },       // Redirect notification. builder: function(t) { if (t.exists) { VAN.redirect.execute; return; }           if (navigator.serviceWorker) { // Create notification service worker. VAN.redirect.worker = navigator.serviceWorker.register(new mw.Uri(VAN.mw.wgLoadScript).extend({ 'debug': mw.config.get('debug'), 'lang': mw.config.get('wgUserLanguage'), 'mode': 'articles', 'skin': mw.config.get('skin'), 'missingCallback': 'importNotifications.importArticleMissing', 'articles': mw.util.wikiUrlencode('u:dev:VanguardTools/service-worker.js'), 'reviewed': mw.config.get('wgReviewedScriptsTimestamp'), 'only': 'scripts' }).getRelativePath); // Create two-way message channel. VAN.redirect.mch = new MessageChannel; VAN.redirect.mch.port1.onmessage = VAN.redirect.handler; // Post notification data to worker. Notification.requestPermission.then(VAN.redirect.post); }       },        post: function(r) { if (r !== 'granted') { return; }           navigator.serviceWorker.controller.postMessage({                command: 'van_send_notif',                i18n: {                    cancel: VAN.mw.wgMessages['cancel'],                    ok: VAN.mw.wgMessages['ok'],                    source: VAN.i18n.msg('sourceredirect').plain                }            }, [VAN.redirect.mch.port2]); },       // Infobox builder template creation. handler: function(e) { if (e.data.command !== 'van_create_infobox') { return; } // Spinner code. VAN.redirect.spinner = $(' ').css({                   background:                        $(document.body).css('background-color')                            .replace('rgb','rgba').replace(')', ', 0.5)'),                    position: 'fixed',                    height: '100%',                    width: '100%',                    left: '0',                    top: '0',                    'z-index': '1000000000'                }).html(function {                    return new Spinner(38, 2).html                        .replace('wds-block', 'wds-spinner__block')                        .replace('wds-path', 'wds-spinner__stroke');                }).appendTo(document.body); // Create infobox. nirvana.sendRequest({               controller: 'PortableInfoboxBuilderController',                method: 'publish',                data: {                    data: VAN.redirect.infobox,                    title: VAN.redirect.template,                    oldTitle: VAN.redirect.template,                    token: mw.user.tokens.get('editToken')                },                callback: VAN.redirect.callback            }); },       // Infobox data object. infobox: function { return JSON.stringify({               "data": [                    {                        "data": { "defaultValue": "" },                        "source": "name",                        "type": "title"                    },                    {                        "data": { "caption": { "source": "caption" }},                        "source": "image",                        "type": "image"                    },                    {                        "data": VAN.i18n.msg('piheader').plain,                        "collapsible": false,                        "type": "section-header"                    },                    {                        "data": {"label": VAN.i18n.msg('pitype').plain },                        "source": "type",                        "type": "row",                        "sourceFrozen": false                    }                ]            }); },       // Infobox builder redirection. callback: function(d) { VAN.redirect.spinner.remove; if (d.success) { VAN.redirect.execute; } else { VAN.redirect.handler; }       },        execute: function { var uri = new mw.Uri(               mw.util.getUrl('Template:' + VAN.redirect.template)            ); uri.extend({               action: 'edit',                useeditor: 'source'            }); window.location.href = uri.toString; VAN.redirect.$executed.resolve; },       $executed: $.Deferred };   // Global navigation links module. VAN.nav = { init: function { if (VAN.config.nav !== true) { VAN.nav.$executed.resolve; return; }           var $l = $('<ul>').addClass('wds-list wds-is-linked'); $.each(VAN.nav.uri, function(l, t) {               $l.append( $('').append(                       $('', { 'href': (function(t) {                               var p = VAN.mw.wgArticlePath.replace('$1', t);                                return p;                            }(t)), text: VAN.i18n.msg(l).plain })                   )                );            });            // Icon and dropdown generation. var icon = VAN.wds.icon('menu-control-tiny', {               'class': 'wds-dropdown-chevron'            }); var $c = VAN.nav.dropdown($l, icon); // Append to menu $('.wds-global-navigation__user-menu') // Prevent scrollable dropdown. .children('.wds-dropdown__content') .addClass('wds-is-not-scrollable') // Insert dropdown. .find('.wds-list > li > a[data-tracking-label="account.profile"]').parent.after($c); VAN.nav.$executed.resolve; },       // Create dropdown. dropdown: function($l, icon) { return $('', {               'id': 'van-tools-dropdown',                'class': 'wds-dropdown-level-2'            }).append(                $('', { 'href': mw.util.getUrl(VAN.nav.uri.insights), 'target': '_blank', 'rel': 'noopener noreferrer', 'class': [ 'wds-dropdown-level-2__toggle', 'van-tools-link' ].join(' ') }).append( $(' ', {                       text: VAN.i18n.msg('tools').plain                    }), icon ),               $(' ', {                    'class': [ 'wds-dropdown-level-2__content', 'wds-is-not-scrollable', 'van-tools-menu' ].join(' ') }).append($l)           ); },       // Global navigation links. uri: { insights:       'Special:Insights/nonportableinfoboxes', infoboxes:      'Special:Templates?type=infobox', templates:      'Special:Templates', sitecss:        'Special:CSS', personalcss:    'Special:MyPage/common.css', themescss:      'MediaWiki:Themes.css?action=edit', admins:         'Special:ListUsers/sysop,bureaucrat,rollback,threadmoderator,content-moderator,chatmoderator', wikifeatures:   'Special:WikiFeatures' },       $executed: $.Deferred };   // Template reclassification hotkey module. VAN.template = { init: function { if (               VAN.config.template !== true ||                VAN.mw.wgCanonicalNamespace !== 'Template' ||                VAN.mw.wgAction !== 'view'            ) { VAN.template.$executed.resolve; return; }           var $popout = $(' ', {                'class': 'van-popout color1'            }).hide.append(                $('<b>', { text: VAN.i18n.msg('templatetypeguide').plain }),               $('<ul>')            ); $popout.appendTo(document.body); nirvana.getJson(               'TemplateClassification',                'getTemplateClassificationEditForm',                function(d) {                    // Extract labels.                    d.templateTypes.forEach(function(dt) { VAN.template.labels[dt.type] = dt.name; });                   // Ready the popout.                    $popout.children('ul').append( $.map(VAN.template.types, function(o, k) {                           return $('').append( $(' ', {                                   text: o.key                                }), $(' ', {                                   text: VAN.template.labels[o.type]                                }) );                       })                    );                    $popout.show;                    // Delegate keyboard handler.                    $(document).keyup(VAN.template.shortcut);                    VAN.template.$executed.resolve;                }            ); },       // Shortcut keys. shortcut: function(e) { if (               !VAN.template.types.hasOwnProperty(e.which) ||                !e.altKey            ) { return; }           VAN.template.type = VAN.template.types[e.which].type, VAN.template.label = VAN.template.labels[VAN.template.type]; nirvana.postJson(               'TemplateClassificationApi',                'classifyTemplate',                {                    pageId: mw.config.get('wgArticleId'),                    type: VAN.template.type,                    editToken: mw.user.tokens.values.editToken                },                VAN.template.success            ); },       // Callback for TemplateClassification controller. success: function { $('.template-classification-type-label').text(VAN.template.label); var message = VAN.i18n.msg('templatetypechange', VAN.template.label).plain; notification = new BannerNotification(message, 'confirm'); notification.show; },       // Template type map for keyboard shortkeys. types: { 223: { key: '`', type: 'infobox' }, 49: { key: '1', type: 'quote' }, 50: { key: '2', type: 'navbox'}, 51: { key: '3', type: 'notice' }, 52: { key: '4', type: 'context-link' }, 53: { key: '5', type: 'infoicon' }, 54: { key: '6', type: 'scrollbox' }, 55: { key: '7', type: 'references' }, 56: { key: '8', type: 'media' }, 57: { key: '9', type: 'data' }, 48: { key: '0', type: 'design' }, 189: { key: '-', type: 'navigation' }, 187: { key: '=', type: 'nonarticle' } },       labels: {}, $executed: $.Deferred };   // S:I/NPI utility extension. VAN.insights = { // Module initialiser. init: function { if (               VAN.config.insights !== true ||                !$('.insights-nav-item.insights-icon-nonportableinfoboxes.active')                    .find('.insights-red-dot').exists            ) { VAN.insights.$executed.resolve; return; }           // Data lists. VAN.insights.list = {}; var chunks = []; [].slice.call($('.insights-list-item-title')).map(function(e, i) {               // Template name.                var t = e.innerText;                $(e).closest('.insights-list-item')                    .attr('data-template', t);                // API data.                VAN.insights.list[t] = {};                ( chunks[Math.floor(i / 50)] = chunks[Math.floor(i / 50)] || []               )[i % 50] = t;            }); VAN.insights.api = new mw.Api; chunks.forEach(function(c) {               VAN.insights.api.get({ 'action': 'query', 'prop': 'info', 'inprop': 'protection', 'titles': c.join('|') }).done(VAN.insights.handler);           }); },       // Template list list: {}, // API handler. handler: function(d) { $.each(d.query.pages, function(id, data) {               VAN.insights.list[data.title].protection =                    data.protection.filter(function(obj) { return (obj.type === 'edit'); }).length > 0;           }); if (Object.keys(VAN.insights.list).every(function(t) { return VAN.insights.list[t].hasOwnProperty('protection'); })) {               VAN.insights.ui; }       },        // Interface configuration map for actions. map: { 'viewdraft': { icon: 'eye-small' },           'conversion': { icon: 'gear-small' },           'rawcode': { icon: 'article-small', query: { action: 'raw', ctype: 'text/css' // Firefox fix. }           },            'protected': { icon: 'lock-small', query: { action: 'history' }           },            'unprotected': { icon: 'unlock-small', query: { action: 'history' }              }        },        // UI modification. ui: function { // Add page header class (hack for button colors). $('.insights-content').addClass('page-header'); // Button map for WDS icon addition. $('.insights-list-cell-altaction .wikia-button').each(function {               var $b = $(this),                    t = $(this).closest('.insights-list-item')                        .attr('data-template');                VAN.insights.list[t].$toolbar =                    $(' ', { 'class': [ 'wds-button-group', 'van-action-button-group' ].join(' ') }).insertBefore($b).append($b);               // Class addition.                $b                    .removeAttr('class')                    .addClass([ 'wds-button', 'wds-is-squished' ].join(' '))                   .addClass(function(i, c) { if ($b.attr('href').indexOf('action=edit') > -1) { return [ 'van-action-button', 'van-is-conversion' ].join(' '); } else { return [ 'wds-is-secondary', 'van-action-button', 'van-is-viewdraft' ].join(' '); }                   }).html(function(i, html) { return ' ' + mw.html.escape(html) + ' '; });               // List buttons.                VAN.insights.list[t].$buttons = [$b];                // Generate toolbar.                VAN.insights.tbr(t);            }); },       // Template toolbar generator. tbr: function(t) { var b = { 'unprotected': false, 'protected': true },               $t = VAN.insights.list[t].$toolbar; // Button creation. $.each(VAN.insights.map, function(l, c) {               // Prevent duplication.                if ( !['conversion', 'viewdraft'].some(function(s) {                       return l === s;                    }) && (                       Object.keys(b).indexOf(l) === -1 ||                        VAN.insights.list[t].protection === b[l]                    ) ) {                   // Button element.                    var $b = $('', { 'href': (function {                               var uri = new mw.Uri(mw.util.getUrl(t));                                // Add query                                if (c.query) {                                    uri.extend(c.query);                                }                                return uri.toString;                            }), html: $(' ', {                               text: VAN.i18n.msg(l).plain                            }) })                       .addClass([ 'wds-button', 'wds-is-squished', 'wds-is-secondary', 'van-tools-button', 'van-is-' + l                       ].join(' '))                        .appendTo(VAN.insights.list[t].$toolbar);                    // Cache button.                    VAN.insights.list[t].$buttons.push($b);                }                // Icon addition.                $t.children('.van-is-' + l)                    .prepend(VAN.wds.icon(c.icon));            }); VAN.insights.$executed.resolve; },       $executed: $.Deferred };   // "You are editing this page without admin" alert. VAN.adminalert = { init: function { if (VAN.config.adminalert !== true) { VAN.adminalert.$executed.resolve; return; }           if (                !['dev', 'communitytest'].includes(VAN.mw.wgDBname) &&                VAN.mw.wgCanonicalNamespace === 'MediaWiki' &&                !/sysop/.test(VAN.mw.wgUserGroups)            ) { $('#ca-edit') .addClass('van-admin-alert') .attr('title', VAN.i18n.msg('adminalert').plain) .find('svg').before(VAN.wds.icon('alert-small').outerHTML); }           VAN.adminalert.$executed.resolve; },       $executed: $.Deferred };   // Replace the create draft button with a link to the page if it is already available. VAN.showdraft = { init: function { var draftDiv = $('section.templatedraft-module.module'); var draftAnchor = draftDiv.children('a'); var draftAnchorHref = draftAnchor.attr('href'); if (               VAN.config.showdraft !== true ||                VAN.mw.wgCanonicalNamespace !== 'Template' ||                VAN.mw.wgAction !== 'view' ||                draftDiv.length <= 0 ||                draftAnchor.length <= 0 ||                draftAnchorHref.indexOf('action=approvedraft') > 0            ) { VAN.showdraft.$executed.resolve; return; }           var draftUrl = draftAnchorHref.slice(0,draftAnchorHref.lastIndexOf('?')); $.ajax(draftUrl + '?action=raw').done(function {                draftDiv.children('h2').text(VAN.i18n.msg('showdraftheader').plain);                draftDiv.children('.templatedraft-module-subtitle').remove;                draftDiv.children('p').text(VAN.i18n.msg('showdraftbody').plain);                draftAnchor.attr('href', draftUrl);                draftAnchor.children('button').text(VAN.i18n.msg('showdraftbutton').plain);            }); VAN.showdraft.$executed.resolve; },       $executed: $.Deferred };   // Module registry. VAN.modules = Object.keys(VAN).filter(function(m) {       return ( typeof VAN[m] === 'object' && // class check VAN[m].init                  // initializer check );   });    // Import styling. importArticle({       type: 'style',        article: 'u:dev:MediaWiki:VanguardTools.css'    }); // Script initializer. mw.loader.using([       'mediawiki.util',        'mediawiki.api',        'jquery.tablesorter',        'ext.bannerNotifications'    ]).then(VAN.init); }); /** **/