User:Thundercraft5/common.js

/** User:Thundercraft5/common.js * Licensed Under CC-BY-SA-3.0. * * =====Contents===== * *Personal Adjustments *	*Upper icons adjustment *	*Top Menu *	* * * Major Scripts *	*blockListLookup *	*rangeBlockLinks *	*blockListTools

/* global mw, test, mediaWiki, ace */ /* jshint esversion: 5, forin: true, immed: true, indent: 4, latedef: false, newcap: true, noarg: true, undef: true, undef: true, unused: true, browser: true, jquery: true, onevar: true, eqeqeq: true, multistr: true, maxerr: 999999

//#==================================================# //# PERSONAL ADJUSTMENTS //#==================================================# window.dontWantRoleSpecificJS = true; mw.requestIdleCallback = function(callback) { setTimeout(callback, 0); }; mw.requestIdleCallbackInternal = mw.requestIdleCallback;

window.test = new Proxy({	test: "$", }, {	deleteProperty: function(o, k) {		throw new TypeError(o, k);	}, }); try { delete test.test; } catch (e) { console.warn(e); } mw.loader.using('mediawiki.Uri', function {	if (mw.config.get('wgPageName').startsWith('Special:Comment')) {		var split = mw.config.get('wgPageName').split('/').slice(1);		if (!split.length) return;		window.location.replace(new mw.Uri('/wiki/' + split[0] + "?" + $.param({ commentId: split[1], replyId: split[2] })));	} });

$(document.body).on('click', 'ul[class^="ActionDropdown_list__"] > li:first-of-type, [class^="Comment_wrapper__"]', function(e) {	if (e.ctrlKey) {		if ($('[class^="EditorForm_editor-form"]').length) return;		var el = $(e.target).parents('[class^="Comment_wrapper__"]');		var replyId = el.attr('data-reply-id');

window.navigator.clipboard.writeText('comment"); } });

document.addEventListener('keydown', function(e) {	var key = e.key.toLowerCase;	if (key === "l" && e.ctrlKey) {		e.preventDefault;		document.querySelector('.oo-ui-iconElement-icon.oo-ui-icon-gotoLine').click;	} else if (key === "s" && e.ctrlKey) {		e.preventDefault;		document.querySelector('.oo-ui-iconElement-icon.oo-ui-icon-pilcrow').click;	} });

// Edit counter if (mw.config.get('wgRelevantUserName') === mw.config.get('wgUserName') && mw.config.get('wgPageName').startsWith('Special:Contributions')) $('#firstHeading').after($(' ', { css: { "font-size": "14px", "font-weight": "initial", },   html: [ 'Edit counter: ', '[',       $('', {            text: 'daily',            click: function {                $(this).html($(' ') .attr({                       src: 'https://images.wikia.nocookie.net/dev/images/8/82/Facebook_throbber.gif',                        border: 0,                    }) .css('vertical-align', 'baseline') );

var date = new Date; date.setDate(new Date.getDate - 1);

new mw.Api.get({                   action: 'query',                    format: 'json',                    list: 'usercontribs',                    ucuser: 'Thundercraft5',                    ucprop: "",                    ucend: date.toISOString,                    uclimit: 1000,                }).then(function(d) {                    $(this).text('daily');                    console.log(d);                    mw.notify('You have made ' + d.query.usercontribs.length + ' edits today.', { type: "success" });                }.bind(this)); },       }),        ']',        ' &bull; ',        '[',        $('', { text: 'weekly', click: function { $(this).html($(' ')                   .attr({ src: 'https://images.wikia.nocookie.net/dev/images/8/82/Facebook_throbber.gif', border: 0, })                   .css('vertical-align', 'baseline')                );

var date = new Date; var day = date.getDay, diff = date.getDate - day + (day === 0 ? -6 : 1);

date = new Date(date.setDate(diff));

new mw.Api.get({                   action: 'query',                    format: 'json',                    list: 'usercontribs',                    ucuser: 'Thundercraft5',                    ucprop: "",                    ucend: date.toISOString,                    uclimit: 1000,                }).then(function(d) {                    $(this).text('weekly');                    mw.notify('You have made ' + d.query.usercontribs.length + ' edits this week.', { type: "success" });                }.bind(this)); },       }),        ']',    ] }));

// Wiki button customization $('div.wds-community-header__wiki-buttons > .createpage') .off('click') .html($(' ', { class: "wds-icon top-note__message-icon wds-icon-small", html: $(' ', {				"xlink:href": "#wds-icons-comment-small",			}), }))		.attr('href', mw.util.getUrl('Special:SocialActivity')) .removeClass('createpage') .attr('title', 'View the wiki\'s social activity') .addClass('wds-button-socialactivity-link') .remove .insertAfter('.wds-community-header__wiki-buttons > a:first-child') .next .clone .html($(' ', { class: "wds-icon wds-icon-small", html: $(' ', {					"xlink:href": "#wds-icons-poll",				}), }))			.attr('title', 'View the wiki\'s abuse log') .attr('href', mw.util.getUrl('Special:AbuseLog')) .addClass('wds-button-abuselog-link') .insertAfter('.wds-button-socialactivity-link');

var pagePathname = mw.config.get('wgArticlePath').replace('$1', ''), sitename = mw.config.get('wgSiteName'), // jshint ignore:line userGroups = mw.config.get('wgUserGroups'), // jshint ignore:line namespace = mw.config.get("wgNamespaceNumber"), // jshint ignore:line pagename = mw.config.get('wgPageName'), // jshint ignore:line wikiUrl = mw.config.get('wgServer').replace(/https?:\/\//g, ''), // jshint ignore:line server = mw.config.get('wgServer'); // jshint ignore:line

var inter = setInterval(function {	if (namespace !== 828) {		clearInterval(inter);		return;	}	if ($('.ace_content').length && namespace === 828) {		clearInterval(inter);	} else {		return;	}	/* PrismJS 1.23.0 https://prismjs.com/download.html#themes=prism&languages=lua */	/* jshint ignore:start */	var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(u){var c=/\blang(?:uage)?-([\w-]+)\b/i,n=0,e={},M={manual:u.Prism&&u.Prism.manual,disableWorkerMessageHandler:u.Prism&&u.Prism.disableWorkerMessageHandler,util:{encode:function e(n){return n instanceof W?new W(n.type,e(n.content),n.alias):Array.isArray(n)?n.map(e):n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/\u00a0/g," ")},type:function(e){return Object.prototype.toString.call(e).slice(8,-1)},objId:function(e){return e.__id||Object.defineProperty(e,"__id",{value:++n}),e.__id},clone:function t(e,r){var a,n;switch(r=r||{},M.util.type(e)){case"Object":if(n=M.util.objId(e),r[n])return r[n];for(var i in a={},r[n]=a,e)e.hasOwnProperty(i)&&(a[i]=t(e[i],r));return a;case"Array":return n=M.util.objId(e),r[n]?r[n]:(a=[],r[n]=a,e.forEach(function(e,n){a[n]=t(e,r)}),a);default:return e}},getLanguage:function(e){for(e&&!c.test(e.className);)e=e.parentElement;return e?(e.className.match(c)||[,"none"])[1].toLowerCase:"none"},currentScript:function{if("undefined"==typeof document)return null;if("currentScript"in document)return document.currentScript;try{throw new Error}catch(e){var n=(/at [^(\r\n]*\((.*):.+:.+\)$/i.exec(e.stack)||[])[1];if(n){var t=document.getElementsByTagName("script");for(var r in t)if(t[r].src==n)return t[r]}return null}},isActive:function(e,n,t){for(var r="no-"+n;e;){var a=e.classList;if(a.contains(n))return!0;if(a.contains(r))return!1;e=e.parentElement}return!!t}},languages:{plain:e,plaintext:e,text:e,txt:e,extend:function(e,n){var t=M.util.clone(M.languages[e]);for(var r in n)t[r]=n[r];return t},insertBefore:function(t,e,n,r){var a=(r=r||M.languages)[t],i={};for(var l in a)if(a.hasOwnProperty(l)){if(l==e)for(var o in n)n.hasOwnProperty(o)&&(i[o]=n[o]);n.hasOwnProperty(l)||(i[l]=a[l])}var s=r[t];return r[t]=i,M.languages.DFS(M.languages,function(e,n){n===s&&e!=t&&(this[e]=i)}),i},DFS:function e(n,t,r,a){a=a||{};var i=M.util.objId;for(var l in n)if(n.hasOwnProperty(l)){t.call(n,l,n[l],r||l);var o=n[l],s=M.util.type(o);"Object"!==s||a[i(o)]?"Array"!==s||a[i(o)]||(a[i(o)]=!0,e(o,t,l,a)):(a[i(o)]=!0,e(o,t,null,a))}}},plugins:{},highlightAll:function(e,n){M.highlightAllUnder(document,e,n)},highlightAllUnder:function(e,n,t){var r={callback:t,container:e,selector:'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code'};M.hooks.run("before-highlightall",r),r.elements=Array.prototype.slice.apply(r.container.querySelectorAll(r.selector)),M.hooks.run("before-all-elements-highlight",r);for(var a,i=0;a=r.elements[i++];)M.highlightElement(a,!0===n,r.callback)},highlightElement:function(e,n,t){var r=M.util.getLanguage(e),a=M.languages[r];e.className=e.className.replace(c,"").replace(/\s+/g," ")+" language-"+r;var i=e.parentElement;i&&"pre"===i.nodeName.toLowerCase&&(i.className=i.className.replace(c,"").replace(/\s+/g," ")+" language-"+r);var l={element:e,language:r,grammar:a,code:e.textContent};function o(e){l.highlightedCode=e,M.hooks.run("before-insert",l),l.element.innerHTML=l.highlightedCode,M.hooks.run("after-highlight",l),M.hooks.run("complete",l),t&&t.call(l.element)}if(M.hooks.run("before-sanity-check",l),(i=l.element.parentElement)&&"pre"===i.nodeName.toLowerCase&&!i.hasAttribute("tabindex")&&i.setAttribute("tabindex","0"),!l.code)return M.hooks.run("complete",l),void(t&&t.call(l.element));if(M.hooks.run("before-highlight",l),l.grammar)if(n&&u.Worker){var s=new Worker(M.filename);s.onmessage=function(e){o(e.data)},s.postMessage(JSON.stringify({language:l.language,code:l.code,immediateClose:!0}))}else o(M.highlight(l.code,l.grammar,l.language));else o(M.util.encode(l.code))},highlight:function(e,n,t){var r={code:e,grammar:n,language:t};return M.hooks.run("before-tokenize",r),r.tokens=M.tokenize(r.code,r.grammar),M.hooks.run("after-tokenize",r),W.stringify(M.util.encode(r.tokens),r.language)},tokenize:function(e,n){var t=n.rest;if(t){for(var r in t)n[r]=t[r];delete n.rest}var a=new i;return I(a,a.head,e),function e(n,t,r,a,i,l){for(var o in r)if(r.hasOwnProperty(o)&&r[o]){var s=r[o];s=Array.isArray(s)?s:[s];for(var u=0;u=l.reach);y+=m.value.length,m=m.next){var b=m.value;if(t.length>n.length)return;if(!(b instanceof W)){var k,x=1;if(h){if(!(k=z(v,y,n,f)))break;var w=k.index,A=k.index+k[0].length,P=y;for(P+=m.value.length;P<=w;)m=m.next,P+=m.value.length;if(P-=m.value.length,y=P,m.value instanceof W)continue;for(var E=m;E!==t.tail&&(Pl.reach&&(l.reach=N);var j=m.prev;O&&(j=I(t,j,O),y+=O.length),q(t,j,x);var C=new W(o,g?M.tokenize(S,g):S,d,S);if(m=I(t,j,C),L&&I(t,m,L),1l.reach&&(l.reach=_.reach)}}}}}}(e,a,n,a.head,0),function(e){var n=[],t=e.head.next;for(t!==e.tail;)n.push(t.value),t=t.next;return n}(a)},hooks:{all:{},add:function(e,n){var t=M.hooks.all;t[e]=t[e]||[],t[e].push(n)},run:function(e,n){var t=M.hooks.all[e];if(t&&t.length)for(var r,a=0;r=t[a++];)r(n)}},Token:W};function W(e,n,t,r){this.type=e,this.content=n,this.alias=t,this.length=0|(r||"").length}function z(e,n,t,r){e.lastIndex=n;var a=e.exec(t);if(a&&r&&a[1]){var i=a[1].length;a.index+=i,a[0]=a[0].slice(i)}return a}function i{var e={value:null,prev:null,next:null},n={value:null,prev:e,next:null};e.next=n,this.head=e,this.tail=n,this.length=0}function I(e,n,t){var r=n.next,a={value:t,prev:n,next:r};return n.next=a,r.prev=a,e.length++,a}function q(e,n,t){for(var r=n.next,a=0;a<t&&r!==e.tail;a++)r=r.next;(n.next=r).prev=n,e.length-=a}if(u.Prism=M,W.stringify=function n(e,t){if("string"==typeof e)return e;if(Array.isArray(e)){var r="";return e.forEach(function(e){r+=n(e,t)}),r}var a={type:e.type,content:n(e.content,t),tag:"span",classes:["token",e.type],attributes:{},language:t},i=e.alias;i&&(Array.isArray(i)?Array.prototype.push.apply(a.classes,i):a.classes.push(i)),M.hooks.run("wrap",a);var l="";for(var o in a.attributes)l+=" "+o+'="'+(a.attributes[o]||"").replace(/"/g,"&quot;")+'"';return"<"+a.tag+' class="'+a.classes.join(" ")+'"'+l+">"+a.content+""},!u.document)return u.addEventListener&&(M.disableWorkerMessageHandler||u.addEventListener("message",function(e){var n=JSON.parse(e.data),t=n.language,r=n.code,a=n.immediateClose;u.postMessage(M.highlight(r,M.languages[t],t)),a&&u.close},!1)),M;var t=M.util.currentScript;function r{M.manual||M.highlightAll}if(t&&(M.filename=t.src,t.hasAttribute("data-manual")&&(M.manual=!0)),!M.manual){var a=document.readyState;"loading"===a||"interactive"===a&&t&&t.defer?document.addEventListener("DOMContentLoaded",r):window.requestAnimationFrame?window.requestAnimationFrame(r):window.setTimeout(r,16)}return M}(_self);"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism); Prism.languages.lua={comment:/^#!.+|--(?:\[(=*)\[[\s\S]*?\]\1\]|.*)/m,string:{pattern:/(["'])(?:(?!\1)[^\\\r\n]|\\z(?:\r\n|\s)|\\(?:\r\n|[^z]))*\1|\[(=*)\[[\s\S]*?\]\2\]/,greedy:!0},number:/\b0x[a-f\d]+(?:\.[a-f\d]*)?(?:p[+-]?\d+)?\b|\b\d+(?:\.\B|(?:\.\d*)?(?:e[+-]?\d+)?\b)|\B\.\d+(?:e[+-]?\d+)?\b/i,keyword:/\b(?:and|break|do|else|elseif|end|false|for|function|goto|if|in|local|nil|not|or|repeat|return|then|true|until|while)\b/,function:/(?!\d)\w+(?=\s*(?:[({]))/,operator:[/[-+*%^&|#]|\/\/?|<[<=]?|>[>=]?|[=~]=?/,{pattern:/(^|[^.])\.\.(?!\.)/,lookbehind:!0}],punctuation:/[\[\]{},;]|\.+|:+/}; 	/* jshint ignore:end */	/**	 * prism.js Twilight theme	 * Based (more or less) on the Twilight theme originally of Textmate fame.	 * @author Remy Bach	 */	mw.util.addCSS("code[class*=\"language-\"],pre[class*=\"language-\"] {color: white;background: none;font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;font-size: 1em;text-align: left;text-shadow: 0 -.1em .2em black;white-space: pre;word-spacing: normal;word-break: normal;word-wrap: normal;line-height: 1.5;-moz-tab-size: 4;-o-tab-size: 4;tab-size: 4;-webkit-hyphens: none;-moz-hyphens: none;-ms-hyphens: none;hyphens: none;}pre[class*=\"language-\"],:not(pre) > code[class*=\"language-\"] {background: hsl(0, 0%, 8%); /* #141414 */}/* Code blocks */pre[class*=\"language-\"] {border-radius: .5em;border: .3em solid hsl(0, 0%, 33%); /* #282A2B */box-shadow: 1px 1px .5em black inset;margin: .5em 0;overflow: auto;padding: 1em;}pre[class*=\"language-\"]::-moz-selection {/* Firefox */background: hsl(200, 4%, 16%); /* #282A2B */}pre[class*=\"language-\"]::selection {/* Safari */background: hsl(200, 4%, 16%); /* #282A2B */}/* Text Selection colour */pre[class*=\"language-\"]::-moz-selection, pre[class*=\"language-\"] ::-moz-selection,code[class*=\"language-\"]::-moz-selection, code[class*=\"language-\"] ::-moz-selection {text-shadow: none;background: hsla(0, 0%, 93%, 0.15); /* #EDEDED */}pre[class*=\"language-\"]::selection, pre[class*=\"language-\"] ::selection,code[class*=\"language-\"]::selection, code[class*=\"language-\"] ::selection {text-shadow: none;background: hsla(0, 0%, 93%, 0.15); /* #EDEDED */}/* Inline code */:not(pre) > code[class*=\"language-\"] {border-radius: .3em;border: .13em solid hsl(0, 0%, 33%); /* #545454 */box-shadow: 1px 1px .3em -.1em black inset;padding: .15em .2em .05em;white-space: normal;}.token.comment,.token.prolog,.token.doctype,.token.cdata {color: hsl(0, 0%, 47%); /* #777777 */}.token.punctuation {opacity: .7;}.token.namespace {opacity: .7;}.token.tag,.token.boolean,.token.number,.token.deleted {color: hsl(14, 58%, 55%); /* #CF6A4C */}.token.keyword,.token.property,.token.selector,.token.constant,.token.symbol,.token.builtin {color: hsl(53, 89%, 79%); /* #F9EE98 */}.token.attr-name,.token.attr-value,.token.string,.token.char,.token.operator,.token.entity,.token.url,.language-css .token.string,.style .token.string,.token.variable,.token.inserted {color: hsl(76, 21%, 52%); /* #8F9D6A */}.token.atrule {color: hsl(218, 22%, 55%); /* #7587A6 */}.token.regex,.token.important {color: hsl(42, 75%, 65%); /* #E9C062 */}.token.important,.token.bold {font-weight: bold;}.token.italic {font-style: italic;}.token.entity {cursor: help;}pre[data-line] {padding: 1em 0 1em 3em;position: relative;}/* Markup */.language-markup .token.tag,.language-markup .token.attr-name,.language-markup .token.punctuation {color: hsl(33, 33%, 52%); /* #AC885B */}/* Make the tokens sit above the line highlight so the colours don't look faded. */.token {position: relative;z-index: 1;}.line-highlight {background: hsla(0, 0%, 33%, 0.25); /* #545454 */background: linear-gradient(to right, hsla(0, 0%, 33%, .1) 70%, hsla(0, 0%, 33%, 0)); /* #545454 */border-bottom: 1px dashed hsl(0, 0%, 33%); /* #545454 */border-top: 1px dashed hsl(0, 0%, 33%); /* #545454 */left: 0;line-height: inherit;margin-top: 0.75em; /* Same as .prism’s padding-top */padding: inherit 0;pointer-events: none;position: absolute;right: 0;white-space: pre;z-index: 0;}.line-highlight:before,.line-highlight[data-end]:after {background-color: hsl(215, 15%, 59%); /* #8794A6 */border-radius: 999px;box-shadow: 0 1px white;color: hsl(24, 20%, 95%); /* #F5F2F0 */content: attr(data-start);font: bold 65%/1.5 sans-serif;left: .6em;min-width: 1em;padding: 0 .5em;position: absolute;text-align: center;text-shadow: none;top: .4em;vertical-align: .3em;}.line-highlight[data-end]:after {bottom: .4em;content: attr(data-end);top: auto;}");	function highlight(text) {		return Prism.highlight(text, Prism.languages.lua);	}	var histList = [''], 		histPos = 0, 		question, input, output, $spinner, 		sessionContent = null, 		sessionKey = null, 		pending = false, 		clearNextRequest = false,		debugConsole,		session,		api = new mw.Api,		doRender = false;	function refocus { // jshint ignore:line		debugConsole.blur;		debugConsole.focus;	}	function initConsole { // jshint ignore:line		input = document.getElementById('mw-scribunto-input');		output = document.getElementById('mw-scribunto-output');		$spinner = $.createSpinner({			size: 'small',			type: 'block',			id: "consoleSpinner",		});		println(mw.msg('scribunto-console-intro'), 'mw-scribunto-message');		debugConsole = ace.edit('debugConsole');		ace.console = {};		ace.console.editor = debugConsole;		session = debugConsole.session;		debugConsole.resize;		debugConsole.getSession.setMode('ace/mode/lua');		session.on('change', function {			var size = debugConsole.session.getScreenLength				* debugConsole.renderer.lineHeight				+ debugConsole.renderer.scrollBar.getWidth;			$('#debugConsole').css('height', size);			debugConsole.resize;		});		debugConsole.setOptions({			enableSnippets: true,			enableLiveAutocompletion: true,			enableBasicAutocompletion: true,		});		// Toggle enableLiveAutocompletion (Ctrl-S)		debugConsole.commands.addCommand({			name: 'toggleAutocomplete',			bindKey: {win: 'Ctrl-S'},			exec: function(editor) {				var on = editor.$enableLiveAutocompletion === true;				editor.setOptions({					enableLiveAutocompletion: !editor.$enableLiveAutocompletion,				});				if (on) editor.completer.detach;			}		});		// Clear Console (Ctrl-Alt-C)		debugConsole.commands.addCommand({			name: 'clearConsole',			bindKey: {win: 'Ctrl-Alt-C'},			exec: function {				clearOutput;			}		});		// Clear Console State (Ctrl-Shift-C)		debugConsole.commands.addCommand({			name: 'clearConsoleState',			bindKey: {win: 'Ctrl-Shift-C'},			exec: function {				onClearClick;			}		});		// Replace Spaces (Ctrl-Shift-S)		debugConsole.commands.addCommand({			name: 'replaceSpaces',			bindKey: {win: 'Ctrl-Shift-S'},			exec: function(editor) {				var pos = editor.getCursorPosition;				editor.find('	');				editor.replaceAll('\t');				editor.moveCursorToPosition(pos);			}		});

session.on('focus', inputFocus); // Submit (Ctrl-Enter) debugConsole.commands.addCommand({			name: 'consoleSubmit',			bindKey: {win: 'Ctrl-Enter'},			exec: function {				go;			}		}); // Go To previous history entry (UpArrow) debugConsole.commands.addCommand({			name: 'navigateUp',			bindKey: { win: 'Up' },			exec: function(editor) {				if (caretInFirstLine) {					hist('up');				} else {					// If cursor is not in first posistion, dont suppress default behavior					editor.navigateUp;				}			},		}); // Go To next history entry (DownArrow) debugConsole.commands.addCommand({			name: 'navigateDown',			bindKey: { win: 'Down' },			exec: function(editor) {				if (caretInLastLine) {					hist('down');				} else {					// If cursor is not in last posistion, dont suppress default behavior					editor.navigateDown;				}			},		}); }	function inputFocus { // jshint ignore:line if (sessionContent === null) { return; }		if (clearNextRequest) { return; }		if (getContent !== sessionContent) { printClearBar('scribunto-console-cleared'); clearNextRequest = true; }	}	function caretInFirstLine { // jshint ignore:line return debugConsole.getCursorPosition.row === 0; }	function caretInLastLine { // jshint ignore:line return debugConsole.getCursorPosition.row+1 === debugConsole.session.getLength; }	function println(s, type) { // jshint ignore:line var newdiv; if ((s = String(s))) { newdiv = document.createElement('div'); newdiv.appendChild(document.createTextNode(s)); newdiv.className = type; output.appendChild(newdiv); return newdiv; }	}	function printClearBar(msg) { // jshint ignore:line $(' ').attr('class', 'mw-scribunto-clear').text(mw.msg(msg)).appendTo(output); }	function hist(direction) {// jshint ignore:line var L = histList.length; var session = debugConsole.session; if (L === 1) { return; }		if (direction === 'up') { if (histPos === L - 1) { histList[histPos] = session.getValue; }			if (histPos > 0) { histPos--; setTimeout(function {					session.setValue('');					session.setValue(histList[histPos]);				}, 0); }		} else { if (histPos < L - 1) { histPos++; session.setValue(histList[histPos]); } else if (histPos === L - 1) { if (session.getValue) { histList[histPos] = session.getValue; ++histPos; session.setValue(''); }			}		}	}	function printQuestion(q) { // jshint ignore:line println(q.match(/^=/) ? q.replace(/^=/, '') : q, 'mw-scribunto-input' + (q.match(/^=/) ? ' exp' : '')); }	function printError(er) { // jshint ignore:line var lineNumberString; if (er.name) { lineNumberString = (er.lineNumber !== undefined) ? (' on line ' + er.lineNumber + ': ') : ': '; println(er.name + lineNumberString + er.message, 'mw-scribunto-error'); } else { println(er, 'mw-scribunto-error'); }	}	function setPending { // jshint ignore:line pending = true; debugConsole.setOptions({			readOnly: true,		}); $spinner.insertBefore($('#debugConsole').parent); }	function clearPending { // jshint ignore:line $spinner.remove; pending = false; debugConsole.setOptions({			readOnly: false,		}); }	function renderHtml(html) { return api.get({			action: "parse",			text: html,			disablelimitreport: true,			wrapoutputclass: "",		}).then(function(d) {			return $(d.parse.text['*']);		}); }	function go { // jshint ignore:line var params, content, sentContent; if (pending) { return; }		question = debugConsole.session.getValue; if (question === '') { return; }		histList[histList.length - 1] = question; histList[histList.length] = ''; histPos = histList.length - 1; debugConsole.session.setValue(''); setTimeout(function {			debugConsole.session.setValue('');		}, 0); printQuestion(question); params = { action: 'scribunto-console', title: mw.config.get('wgPageName'), question: question };		content = getContent; sentContent = false; if (!sessionKey || sessionContent !== content) { params.clear = true; params.content = content; sentContent = true; }		if (sessionKey) { params.session = sessionKey; }		if (clearNextRequest) { params.clear = true; clearNextRequest = false; }		setPending; api.post(params).done(function(result) {			if (result.sessionIsNew ===  && !sentContent) {				printClearBar('scribunto-console-cleared-session-lost');				sessionContent = null;				clearPending;				debugConsole.setValue(params.question);				go;				return;			}			sessionKey = result.session;			sessionContent = content;			if (result.type === 'error') {				$(' ')					.addClass('mw-scribunto-error')					.html(result.html)					.appendTo(output);			} else {				if (result.print !== ) {					println(result.print, 'mw-scribunto-print');				}				if (result.return !== '') {					if (doRender) renderHtml(result.return).then(function(html) { if (html.length === 1 && html.first[0].tagName === "P") html = html.text; $(' ')							.addClass('mw-scribunto-normalOutput') .html(html) .appendTo(output); });					else println(result.return, 'mw-scribunto-normalOutput');				}			}			clearPending;			setTimeout(refocus, 0);		}).fail(function(code, result) {			if (result.error && result.error.info) {				printError(result.error.info);			} else if (result.exception) {				printError('Error sending API request: ' + result.exception);			} else {				console.log(result);				printError('Error sending API request: ' + code);			}			clearPending;			setTimeout(refocus, 0);		}); }	function getContent { // jshint ignore:line var $textarea = $('#wpTextbox1'), context = $textarea.data('wikiEditor-context'); if (context === undefined || context.codeEditor === undefined) { return $textarea.val; } else { return $textarea.textSelection('getContents'); }	}	function onClearClick {// jshint ignore:line $('#mw-scribunto-output').empty; clearNextRequest = true; refocus; }	function clearOutput {// jshint ignore:line $('#mw-scribunto-output').empty; refocus; }	function initEditPage { // jshint ignore:line $('#mw-scribunto-console').first.remove; var $wpTextbox1, $console = $('#mw-scribunto-console'); mw.messages.set('scribunto-console-clear-output', 'Clear Console Output'); mw.messages.set('scribunto-console-clear', 'Clear Console State'); mw.messages.set('scribunto-console-submit', 'Submit'); if (!$console.length) { $wpTextbox1 = $('#wpTextbox1'); $console = $(' ').attr({				id: 'mw-scribunto-console'			}); $('.editOptions').before($console); }		$(' ')			.attr('class', 'mw-scribunto-console-fieldset') .append($(' ')				.text(mw.msg('scribunto-console-title'))			) .append($(' ')) .append($(' ').append( $(' ', {					id: "debugConsole",					css: {						'width': 'calc(-webkit-fill-available+100px)',						'font-size': '14px',						'line-height': '18px',						'min-height': '100px',						'max-height': '400px',					}				}) ))			.append($(' ').append( $(' ', {					type: 'button',					value: 'Clear Console Output',					click: clearOutput,				}), $(' ', {					type: 'button',					value: mw.msg('scribunto-console-clear'),					click: onClearClick,				}), $(' ', {					type: 'button',					value: mw.msg('scribunto-console-submit'),					click: function(e) {						e.preventDefault;						go;					},				}), $(' ', {					type: "checkbox",					id: "RenderHTML",					change: function {						doRender = this.checked;						},				}), $(' ', {					'for': "RenderHTML",					id: "RenderHTML-label",					css: {						cursor: "pointer",					},					text: "Render Output as HTML",				}) ))			.wrap(' ') .appendTo($console); initConsole; }	$(function {		var action = mw.config.get('wgAction');		if (action === 'edit' || action === 'submit' || action === 'editredlink') {			initEditPage;		}	}); });