User:Williek11/global.js

// // ToC // // import scripts // global variables // global functions // instantiate objects // content adjustments // modals // williek11 apis // navbar adjustments //

// // // import scripts // //

importArticles({	type: 'script',	articles: [		'u:dev:MediaWiki:Rollback/code.js',		'u:dev:MediaWiki:AnchoredRollback/code.js',		'u:dev:MediaWiki:Modal.js',		'u:dev:MediaWiki:WDSIcons/code.js',	] });

// // // global variables // //

const lang = mw.config.get("wgContentLanguage"); const pageName = mw.config.get("wgPageName");

// // // global functions // //

function linkify (text) { return lang === "en" ? "/wiki/"+text : "/"+lang+"/wiki/"+text; }

// // // instantiate objects // //

window.sidebar = {}; window.sidebar.addNodeToSide = function (obj, sideContainer) { const node = document.createElement("div"); const titleNode = document.createElement("div"); const ulNode = document.createElement("ul"); node.className = "side_item"; ulNode.className = "side_items-list"; titleNode.className = "side_items-title"; titleNode.innerHTML = obj.title; node.appendChild(titleNode); node.appendChild(ulNode); for (var i = 0, l = obj.items.length; i < l; i++) { const currentItem = obj.items[i]; const itemLink = currentItem.link; const itemHTML = currentItem.html; const itemNode = document.createElement("li"); const linkNode = document.createElement("a"); if (currentItem.id !== undefined) { itemNode.id = currentItem.id; }		linkNode.href = itemLink; linkNode.innerHTML = itemHTML; itemNode.appendChild(linkNode); ulNode.appendChild(itemNode); }	sideContainer.appendChild(node); };

window.tabs = {};

window.tabs.createTab = function (obj) { const aNode = document.createElement("a"); const node = document.createElement("div"); node.className = "community-header-tab"; node.innerText = obj.text; if (obj.event) { node.addEventListener("click", obj.event); } if (obj.link) { aNode.href = obj.link; aNode.appendChild(node); return aNode; } return node; };

window.tabs.createTabBasedOnNode = function (name) { const miscNode = $("#ca-"+name)[0]; if (miscNode === undefined) { return null; } return window.tabs.createTab({		text: miscNode.textContent.trim,		link: miscNode.href	}); };

// // // content adjustments // //

var contentAdjustmentsLoaded = false;

mw.hook("wikipage.content").add(function justAnotherName {	if (contentAdjustmentsLoaded) {		return;	}	contentAdjustmentsLoaded = true;	const MPLang = mw.storage.get("MP-"+lang);	const mainContainer = $(".main-container")[0];	const resizableContainer = $(".resizable-container")[0];	const navigationHeader = document.createElement("div");	const sideContainer = document.createElement("div");	const dualContainer = document.createElement("div");	const screenSwitch = document.createElement("div");	const themeSwitch = document.createElement("div");	const pageLookupButton = document.createElement("div");	const ToDoButton = document.createElement("div");	navigationHeader.className = "navigation-header";	sideContainer.className = "side-container";	dualContainer.className = "dual-container";	mw.hook('dev.wds').add(function (wds) { $(screenSwitch).append(wds.icon('zoom-out-small')); $(themeSwitch).append(wds.icon('clock-small')); $(pageLookupButton).append(wds.icon('magnifying-glass-small')); $(ToDoButton).append(wds.icon('pencil-small')); });	navigationHeader.replaceChildren( $(".notifications")[0], themeSwitch, screenSwitch, pageLookupButton, ToDoButton );	dualContainer.appendChild(sideContainer);	dualContainer.appendChild(resizableContainer);	mainContainer.insertBefore(navigationHeader, $(".global-footer")[0]);	mainContainer.insertBefore(dualContainer, $(".global-footer")[0]);	mw.hook("williek-utils").add(function{ function page_lookup_show { window.dev.modal.modals['page-lookup'].show; }		function to_do_list_show { window.dev.modal.modals['williek11--to-do-modal'].events.show[0]; }		$(themeSwitch).click(window.Williek11.toggleWithoutReload); $(screenSwitch).click(window.Williek11.toggleScreen); $(pageLookupButton).click(page_lookup_show); $(ToDoButton).click(to_do_list_show); });	window.sidebar.addNodeToSide({title: "Profile", items: [ {link: linkify("User:Williek11"), html: "Own profile"}, {link: linkify("Message Wall:Williek11"), html: "Message wall"}, {link: linkify("User blog:Williek11"), html: "User blog"}, {link: linkify("Special:Contributions/Williek11"), html: "Contributions"}, {link: linkify("Special:UserProfileActivity/Williek11"), html: "User activity"}, {link: linkify("User:Williek11/Sandbox"), html: "Sandbox"}, ]}, sideContainer);	window.sidebar.addNodeToSide({title: "Site tools", items: [ {link: MPLang, html: "Main page"}, {link: linkify("Special:RecentChanges"), html: "Recent changes"}, {link: linkify("Special:SocialActivity"), html: "Social activity"}, {link: linkify("Special:Search"), html: "Search"}, {link: linkify("Special:NewFiles"), html: "New files"}, {link: linkify("Category:Maintenance"), html: "Maintenance"}, {link: linkify("Category:Templates"), html: "Templates"}, {link: linkify("Special:SpecialPages"), html: "Special pages"}, {link: linkify("Special:Preferences"), html: "Change preferences"}, ]}, sideContainer);	window.sidebar.addNodeToSide({title: "Page tools", items: [ {link: linkify("Special:WhatLinksHere/"+pageName), html: "What links here", id:"side_item-what_links_here"}, {link: linkify(pageName+"?action=info"), html: "Information"}, ]}, sideContainer);	window.sidebar.addNodeToSide({title: "Scripts", items: [ {link: linkify("User:Williek11/common.js?action=edit"), html: "Common JS"}, {link: linkify("User:Williek11/common.css?action=edit"), html: "Common CSS"}, {link: "https://community.fandom.com/wiki/User:Williek11/global.js?action=edit", html: "Global JS"}, {link: "https://community.fandom.com/wiki/User:Williek11/global.css?action=edit", html: "Global CSS"}, {link: linkify(pageName+"?useuserjs=0&useusercss=0"), html: "Remove User Scripts"}, {link: linkify(pageName+"?usesitejs=0&usesitecss=0"), html: "Remove Site Scripts"}, {link: linkify(pageName+"?safemode=1"), html: "Remove Both Scripts"}, ]}, sideContainer);	if (MPLang === null) {		$.ajax({ url: linkify("MediaWiki:Mainpage?action=raw"), success: function (data) { $("[href='null']")[0].href = linkify(data); mw.storage.set("MP-"+lang, linkify(data)); },		});	}	mw.loader.using('mediawiki.api').then(function{ new mw.Api.get({			action: 'query',			format: 'json',			list: 'backlinks',			bltitle: pageName,		}).done(function(data) {			const text = "What links here: "+data.query.backlinks.length;			$("#side_item-what_links_here")[0].firstElementChild.innerText = text;		}); }); });

// // // modals // //

mw.hook("dev.modal").add(function(modal){	new modal.Modal({ id: "talk", title: "Talk page", size: "content-size", content: "Loading...", buttons: (function{			const talkObject = new mw.Title(pageName).getTalkPage;			if (talkObject === null) { return []; }			const talkPage = talkObject.getPrefixedText;			return [		       { text: 'Go to talk page', href: linkify(talkPage), type: "link", },		        { text: 'Edit talk page', href: linkify(talkPage+"?action=edit"), type: "link", },		        { text: 'Talk page history', href: linkify(talkPage+"?action=history"), type: "link", },			];		}), }).create.then(function{ mw.hook("williek-talkModal").fire; });	new modal.Modal({ id: "href-preview", title: "Page Preview", size: "content-size", content: "Loading...", buttons: [ {				text: "Go to page", href: "#" },			{				text: "Edit page", href: "#" },			{				text: "Page history", href: "#" },			{				text: "Lookup other pages", event: "lookup_modal" },		],		events: { lookup_modal: function { window.dev.modal.modals['href-preview'].close; window.dev.modal.modals['page-lookup'].show; },		},	}).create;	new modal.Modal({ id: "page-lookup", title: "Page Lookup", size: "medium", content: ' This modal helps you lookup a page\'s content without needing ' + 'to change your tab at all. Set the page you\'re looking for below ' + 'and we\'ll gladly let you look at it. ' +			' ' ,		buttons: [ {				text: "Lookup Source", event: "lookup_src" },			{				text: "Lookup Visual", event: "lookup_visual" },		],		events: { lookup_src: function { window.dev.modal.modals['page-lookup'].close; var page = $('#williek11-lookup')[0].value; if (page.indexOf("/") === -1) { page = '/' + page; } window.Williek11.expandPage(linkify(page), false); },		   lookup_visual: function { window.dev.modal.modals['page-lookup'].close; var page = $('#williek11-lookup')[0].value; if (page.indexOf("/") === -1) { page = '/' + page; } window.Williek11.expandPage(linkify(page), true); }		},	}).create;	new modal.Modal({ id: "williek11--to-do-modal", title: "To Do List", size: "content-size", content: ' ' +			' ' +			'	 ' + ' '		,		buttons: [ {				text: "Edit Source", id: 'williek11--to-do-edit', event: 'edit_src', },			{				text: "Submit Changes", id: 'williek11--to-do-submit', event: 'submit_changes', },			{				text: "View", id: 'williek11--to-do-view-button', event: 'view', },		],		events: { show: function { this.show; $("#williek11--to-do-modal")[0].classList.add("view"); $("#williek11--to-do-modal")[0].classList.remove("source"); $.ajax({					url: linkify('User:Williek11/To_Do?action=render'),					success: function (data) {		   			$("#williek11--to-do-view")[0].innerHTML = data;		    		},		    		fail: function  {		    			$("#williek11--to-do-view")[0].innerHTML = 'Your to do list does not currently exist on this wiki.';		    			$("#williek11--to-do-editor")[0].value = '';		    		}				}); },			view: function { $("#williek11--to-do-modal")[0].classList.add("view"); $("#williek11--to-do-modal")[0].classList.remove("source"); },		   edit_src: function  { $("#williek11--to-do-modal")[0].classList.add("source"); $("#williek11--to-do-modal")[0].classList.remove("view"); $.ajax({		   		url: linkify('User:Williek11/To_Do?action=raw'),		    		success: function (data) {		    			$("#williek11--to-do-editor")[0].value = data;		    		}		    	}); },		   submit_changes: function  { $.ajax({		   		url: '/api.php?action=query&meta=tokens&format=json',		    		success: function(tokenObject){		    			$.ajax({ type: 'POST', url: '/api.php', data: { action: 'edit', title: 'User:Williek11/To_Do', text: $("#williek11--to-do-editor")[0].value, token: tokenObject.query.tokens.csrftoken, format: 'json' },						   success: function  { $("#williek11--to-do-view")[0].innerHTML = $("#williek11--to-do-editor")[0].value; $("#williek11--to-do-modal")[0].classList.add("view"); $("#williek11--to-do-modal")[0].classList.remove("source"); new BannerNotification("Successfully saved!", "confirm"); },						   fail: function  { new BannerNotification("There was an error saving.", "error"); }		   			})			    	}		    	})		    },		},	}).create; });

// // // navbar adjustments // //

mw.hook("williek-talkModal").add(function {	const communityHeader = $(".community-header-wrapper")[0];	communityHeader.replaceChildren;	const arrayOfTabs = [		(function{ const talkNode = $("#ca-talk")[0]; if (talkNode === undefined) { return null; } const talkModal = window.dev.modal.modals.talk; const text = talkNode.textContent.trim; const amount = parseInt(text.substr(6)); var eventFunction; if (amount === 0) { talkModal.setContent("The talk page does not exist."); eventFunction = function {talkModal.show} } else { eventFunction = function { talkModal.show; if (window.loadedTalkPage === true) {return;} $.ajax({				       type: 'GET',				        url: talkNode.href+"?action=render",				        success: function (data) {				        	talkModal.setContent(data);				        	window.loadedTalkPage = true;				        },				    }); }			}			return window.tabs.createTab({				text: text,				event: eventFunction			}); }),		window.tabs.createTabBasedOnNode("edit"),		window.tabs.createTabBasedOnNode("move"),		window.tabs.createTabBasedOnNode("history"),		window.tabs.createTabBasedOnNode("delete"),		window.tabs.createTabBasedOnNode("protect"),		window.tabs.createTabBasedOnNode("unprotect"),		window.tabs.createTab({ text: "Purge", link: linkify(pageName+"?action=purge"), }),	];	for (var i = 0, l = arrayOfTabs.length; i < l; i++) {		const node_or_null = arrayOfTabs[i];		if (node_or_null === null) {continue}		communityHeader.appendChild(node_or_null);	} });

// // // williek11 apis // huge thanks to ThemeToggler on dev wiki // https://dev.fandom.com/wiki/ThemeToggler // //

mw.hook("williek-talkModal").add(function {	const fullBackground = $('.fandom-community-header__background.fullScreen');	window.Williek11 = {};	window.Williek11.toggleWithoutReload = function  {		var theme = $( 'body' ).hasClass( 'theme-fandomdesktop-light' ) ? 'light' : 'dark';		var newTheme = theme === 'light' ? 'dark' : 'light';		///////////////////////////////////////////////////		// Implementation by User:Pcj from ThemeSwitcher		///////////////////////////////////////////////////		$.when( $.get(mw.util.wikiScript( 'wikia' ) + '?controller=ThemeApi&method=themeVariables&variant=' + newTheme + '&cb=' + ( new Date.getTime ) ), $.get( mw.util.wikiScript( 'load' ) + '?modules=ext.fandom.GlobalComponents.GlobalComponentsTheme.' + newTheme + '.css%7Cext.fandom.GlobalComponents.GlobalComponentsTheme.nav-' + newTheme + '.css&only=styles' ) )		.done( function( wikiTheme, brandTheme ) { var css = wikiTheme[0] + brandTheme[0]; var $s = $( '#pcjThemeSwitch' )[0] || $( ' ' ).attr( 'id', 'pcjThemeSwitch' ).appendTo('body'); $($s).text(css); if (fullBackground.length) { var bgMatch = wikiTheme[0].match(/--theme-body-background-image\s*?:\s*?url\((.*?)\)/); if (bgMatch) { var bgImage = new Image; bgImage.onload = function { fullBackground.css('--image-ratio', (this.height / this.width).toString); };					bgImage.src = bgMatch[1]; }			}			$( 'body' ).removeClass( 'theme-fandomdesktop-light theme-fandomdesktop-dark' ).addClass( 'theme-fandomdesktop-' + newTheme ); mw.config.set( 'isDarkTheme', !mw.config.get( 'isDarkTheme' ) ); } );	};	window.Williek11.expandPage = function (href, visual) {		const uriObject = new mw.Uri(href);		const hrefPreview = window.dev.modal.modals['href-preview'];		hrefPreview.close;		hrefPreview.buttons[0].setHref(uriObject.toString);		hrefPreview.buttons[1].setHref((uriObject.query.action = "edit", uriObject.toString));		hrefPreview.buttons[2].setHref((uriObject.query.action = "history", uriObject.toString));		const cached__visual = visual;		$.ajax({ url: ((uriObject.query.action = cached__visual ? "render" : "raw", uriObject)), type: 'GET', success: function (data) { if (data.length > 200000) hrefPreview.setContent("408 RENDER TIMEOUT"); else if (cached__visual) hrefPreview.setContent(data); else hrefPreview.setContent('' +	       		new Option(data).innerHTML.replaceAll("\n", " ") +	        		' '); },	       error: function (err) { hrefPreview.setContent('SERVER-SIDE ERROR. CHECK CONSOLE FOR FURTHER INFO.'); console.error(err); }	   });		hrefPreview.create.then(function { hrefPreview.show; });	}	window.Williek11.toggleScreen = function {		const expanded = $('body')[0].classList.contains("is-content-expanded");		if (expanded) {			new mw.Api.postWithToken('csrf', { format: 'json', formatversion: '2', action: 'options', change: 'contentwidth=collapsed' });			$('body')[0].classList.remove("is-content-expanded");		}		else {			new mw.Api.postWithToken('csrf', { format: 'json', formatversion: '2', action: 'options', change: 'contentwidth=expanded' });			$('body')[0].classList.add("is-content-expanded");		}	};	var timeout = setTimeout(function{});	window.addEventListener('keydown', function(e) { if (e.code === "ShiftLeft" || e.code === "ShiftRight") { window.Williek11.stopLinkVisual = true; } else if (e.code === "ControlLeft" || e.code === "ControlRight") { window.Williek11.stopLinkSource = true; }	});	window.addEventListener('keyup', function(e) { if (e.code === "ShiftLeft" || e.code === "ShiftRight") { window.Williek11.stopLinkVisual = false; } else if (e.code === "ControlLeft" || e.code === "ControlRight") { window.Williek11.stopLinkSource = false; }	});	window.addEventListener('click', function(e) { const target = e.target; const aElement = target.tagName === "A" ? target : target.parentElement.tagName === "A" ? target.parentElement : null; if (			aElement !== null &&			aElement.href.indexOf("fandom.com") > -1 &&			(window.Williek11.stopLinkVisual || window.Williek11.stopLinkSource)		) { e.preventDefault; window.Williek11.expandPage(aElement.href, window.Williek11.stopLinkVisual); }	});	mw.hook("williek-utils").fire; });