Jump to content

User:Erutuon/common.js: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
add ZWNJ before cedilla in Marshallese text
trim whitespace from parser report
(One intermediate revision by the same user not shown)
Line 358: Line 358:
$(":lang(mh)").get().forEach(addZwnjBeforeCedilla);
$(":lang(mh)").get().forEach(addZwnjBeforeCedilla);
});
});

(function findParserReport() {
const iter = document.createNodeIterator(document.getElementById("content"), NodeFilter.SHOW_COMMENT, function() { return NodeFilter.FILTER_ACCEPT; });
var node;
while ((node = iter.nextNode())) {
const value = node.nodeValue;
if (value.includes("NewPP limit report")) {
console.info(value.trim()); break;
}
}
})();

Revision as of 20:45, 8 June 2021

/* globals $ */
// <nowiki>

$.ajax('//tools-static.wmflabs.org/meta/scripts/pathoschild.templatescript.js', { dataType:'script', cache:true }).then(function() {
	pathoschild.TemplateScript.add([
		// add your own templates or scripts here
		{
			name: 'proto wikt-lang',
			enabled: false,
			script: function(editor) {
				editor
					.replace(/'*\*?\[\[:?wikt:Reconstruction:Proto-Germanic\/([^\|\]]+)\|\*?([^\]]+)\]\]'*/g, '{{wikt-lang|gem-pro|*$2}}')
					.replace(/'*\*?\[\[:?wikt:Reconstruction:Proto-Indo-European\/([^\|\]]+)\|\*?([^\]]+)\]\]'*/g, '{{wikt-lang|ine-pro|*$2}}')
					.replace(/'*\*?\[\[:?wikt:Reconstruction:Proto-Hellenic\/([^\|\]]+)\|\*?([^\]]+)\]\]'*/g, '{{wikt-lang|grk-pro|*$2}}')
					.replace(/'*\*?\[\[:?wikt:Reconstruction:Proto-Slavic\/([^\|\]]+)\|\*?([^\]]+)\]\]'*/g, '{{wikt-lang|sla-pro|*$2}}')
					.appendEditSummary('simplified links to Wiktionary with [[Template:wikt-lang]]');
			},
		},
		{
			name: 'fix refs',
			enabled: false,
			script: function(editor) {
				editor
					.replace(/(<ref[^\w\s\"]*\>[^<>]*<\/ref\>)([\.\,\;\:\)]{1,3})/g, '$2$1') // Move refs after 1-3 punctuation characters.
					.replace(/(\{\{[s|r?e]fn[^\}]+\}\})([\.\,\;\:\)]{1,3})/g, '$2$1') // Move refn and efn templates after 1-3 punctuation characters.
					.replace(/(\{\{[Cc]itation needed[^\}]+\}\})([\.,;:\)]{1,3})/g, '$2$1'); // Move citation needed templates after 1-3 punctuation characters.
			}
		},
		{
			name: 'tag Amharic',
			category: 'formatting',
			enabled: false,
			isMinorEdit: true,
			script: function(editor) {
				editor
					.replace(/([ሀ-᎙ⶀ-ⷞꬁ-ꬮ]+)(?=[\s\)\;\:\.\,\!\|<\'])/g, '{{lang|am|$1}}')
					.appendEditSummary('tag Amharic text with the help of [[m:TemplateScript|TemplateScript]]');
			}
		},
		{
			name: 'add IPA template',
			category: 'formatting',
			enabled: false,
			script: function(editor) {
				editor
					.replaceSelection(function (selected) {
						return selected
							.replace(/(\/[^\/]+\/)/g, '{{IPA|$1}}')
							.replace(/(\[[^\]]+\])/g, '{{IPA|$1}}');
					})
					.appendEditSummary('added IPA template with the help of [[m:TemplateScript|TemplateScript]]');
			},
		},
		{
			name: 'IPA link template cleanup',
			category: 'formatting',
			enabled: false,
			script: function(editor) {
				editor
					.replace(/\/\{\{IPA ?link\|([^\}]+)\}\}\//g, '{{IPAslink|$1}}')
					.replace(/\[\{\{IPA ?link\|([^\}]+)\}\}\]/g, '{{IPAblink|$1}}');
			}
		},
		{
			name: 'tag Armenian',
			category: 'formatting',
			isMinorEdit: true,
			enabled: false,
			script: function(editor) {
				editor
					.replace(/([Ա-֏ﬓ-ﬗ]+)(?=[\s\)\;\:\.\,\!\|<\'])/g, '{{lang|hy|$1}}')
					.replace(/\}\}(\'+)\{\{lang\|hy\|/g, '$1')
					.replace(/(\'+)(\{\{lang\|hy\|)/g, '$2$1')
					.appendEditSummary('tag Armenian text with the help of [[m:TemplateScript|TemplateScript]]');
			}
		},
	]);
});

// Add or modify CharInsert entries
window.charinsertCustom = { 
	"Latin": ' ꟾ  {{lang|la|+}} {{wikt-lang|la|+}}',
	"Arabic": ' {{lang|ar|+}} {{wikt-lang|ar|+}}',
	"Cyrillic": ' {{lang|ru|+}} {{wikt-lang|ru|+}} {{lang|orv|+}} {{lang|cu|+}} {{lang|uk|+}} {{lang|be|+}}',
	"Greek": ' {{wikt-lang|grc|+}}',
	"IPA": ' ◌ {{IPA|{{subst:x2i|+}}}}',
	"Templates": ' {{lang|ang|+}} {{IPA|+}} {{lang|zh|+}}',
};
// </nowiki>

window.simplePopups = false;

switch (mw.config.get('wgNamespaceNumber')) {
	case 0: // main
		importScript('User:Gary/subjects age from year.js'); break; // [[User:Gary/subjects age from year.js]]
	case 2: // User:
		// [[User:Erutuon/ScriptInstaller.js]]
		importWiktionaryScript("User:Erutuon/ScriptInstaller.js");
		importScript('User:PleaseStand/userinfo.js'); break; // [[User:PleaseStand/userinfo.js]]
}

/*
If text with the language attribute "grc" (Ancient and Medieval Greek) contains
non-Greek scripts, marks it with the class "error".
*/

function importWiktionaryScript(pageName) {
	return mw.loader.load("//en.wiktionary.org/enwiki/w/index.php?title=" + pageName
		+ "&action=raw&ctype=text/javascript");
}

window.withWiktionaryScript = function (pageName, successCallback, failureCallback) {
	return $.getScript('//en.wiktionary.org/enwiki/w/index.php?title=' + pageName
		+ '&action=raw&ctype=text/javascript')
		.done(successCallback)
		.fail(failureCallback);
};

const LatnToGrek = {
	'E': 'Ε', 'M': 'Μ', 'v': 'ν', 'o': 'ο', 'ó': 'ό', 'ò': 'ὸ',
};

const grc = $("[lang=grc]");
if (grc.length > 0) {
	$.getScript(
		"//en.wikipedia.org/enwiki/w/index.php?action=raw&title=User:Erutuon/scripts/scriptRecognition.js&ctype=text/javascript&smaxage=21600&maxage=86400",
		function () {
			const countScripts = window.countSignificantScripts;
			const fixGreek = function(str) {
				return str.replace(/./g, function(char) {
					return LatnToGrek[char] || char;
				});
			};
			grc.addClass(
				function() {
					const innerHTML = this.innerHTML;
					for (const script in countScripts(innerHTML.replace(/<\/?[^>]+>/g, ""))) {
						if (script !== "Grek") {
							console.log("Non-Latin script " + script + " in "
								+ innerHTML + " (corrected: " + fixGreek(innerHTML) + ").");
							return "error";
						}
					}
				});
		});
}

// </nowiki>

if ([ "edit", "submit" ].includes(mw.config.get("wgAction"))) {
	importScript('User:Erutuon/scripts/charinsert-names.js');
	
	var addApiResultToTextbox = function (funcName) {
		return function (str) {
			return withWiktionaryScript('User:Erutuon/scripts/apiWrapper.js', function () {
				if (!(funcName in apiWrapper))
					throw new Error("Function " + funcName + " not in apiWrapper");
	
				apiWrapper[funcName](str, function (result) {
					var $textbox = $('#wpTextbox1');
					try { // avoid error: currSelection is undefined
						$textbox.textSelection('replaceSelection', result);
					} catch (e) {
						$textbox.textSelection('setContents', result);
					}
				});
			});
		};
	};
	
	// Insert expanded wikitext into the text box, as if from
	// [[Special:ExpandTemplates]].
	window.insertExpandedTemplate = addApiResultToTextbox('expandTemplates');
	
	// Replace selection in text box with the wikitext of a page.
	window.insertWikitext = addApiResultToTextbox('getWikitext');
	
	if (mw.config.get("wgCanonicalNamespace") === "") {
		importScript('User:Uglemat/RefMan.js'); // Backlink: [[User:Uglemat/RefMan.js]]
		importScript('User:Erutuon/scripts/cleanup.js'); // Backlink: [[User:Erutuon/scripts/cleanup.js]]
	}
}

if ([ "css", "javascript", "Scribunto" ].includes(mw.config.get("wgPageContentModel")))
	mw.loader.using("mediawiki.util").done(function () {
		importWiktionaryScript("MediaWiki:Gadget-CodeLinks.js");
	});

if (mw.config.get("wgPageName") === "MediaWiki:Gadgets-definition")
	importWiktionaryScript("User:Erutuon/scripts/gadgets-definition.js");

(function templatePreviewIIFE () {
"use strict";

// from [[wikt:User:Erutuon/scripts/storageUtils.js]]
var StorageWrapper = function() {
	this.cookiePreferences = {
		expires: 30, path: '/'
	};
};

StorageWrapper.prototype = {
	constructor: StorageWrapper,
	
	localStorageAvailable: mw.storage.get("localStorageTest") !== false,
	cookieAvailable: navigator.cookieEnabled,
	get storageAvailable () {
		return this.localStorageAvailable || this.cookieAvailable;
	},
	
	set: function(name, value) {
		if (this.localStorageAvailable) {
			localStorage[name] = value;
		} else {
			$.cookie(name, value, {});
		}
	},
	
	get: function(name) {
		if (this.localStorageAvailable) {
			return localStorage[name];
		} else {
			return $.cookie(name);
		}
	},
	
	remove: function(name) {
		if (this.localStorageAvailable) {
			delete localStorage[name];
		} else {
			return $.removeCookie(name);
		}
	},
};

// from [[wikt:User:Erutuon/scripts/templatePreview.js]]
		
function TemplatePreviewStorage(key) {
	this.key = key;
}

TemplatePreviewStorage.prototype = Object.create(StorageWrapper.prototype, {
	rawStorage: {
		get: function () {
			return StorageWrapper.prototype.get.call(this, this.key);
		},
		set: function (value) {
			return StorageWrapper.prototype.set.call(this, this.key, value);
		},
	},
	
	// Get and save storage in JSON format.
	storage: {
		get: function () {
			try {
				const previewPageNames = this.rawStorage;
				if (previewPageNames) {
					const previewPageNamesObject = JSON.parse(previewPageNames); // possible error
					if (previewPageNamesObject)
						return previewPageNamesObject;
				}
			} catch (e) {
				console.log("Error parsing storage:", e);
			}
			
			return {};
		},
		
		set: function (previewPageNamesObject) {
			try {
				const previewPageNames = JSON.stringify(previewPageNamesObject); // possible error
				this.rawStorage = previewPageNames;
			} catch (e) {
				console.log("Error stringifying object: ", e);
			}
		},
	},
	
	get: {
		value: function (templateName) {
			return this.storage[templateName];
		},
	},
	set: {
		value: function (templateName, previewPageName) {
			const storage = this.storage;
			storage[templateName] = previewPageName;
			this.storage = storage;
		},
	},
});

const getDefaultPreviewPage = function (pageName) {
	pageName = pageName.replace(/_/g, " ");
	return (!/\/doc$/.test(pageName))
		? pageName + "/doc"
		: pageName;
};

function doIt() {
	const button = $("#wpTemplateSandboxPreview input");
	const box = $("#wpTemplateSandboxPage input");
	
	if (!(box.length > 0 && button.length > 0))
		return;
	
	const storage = new TemplatePreviewStorage("previewPage");
	window.templatePreviewStorage = storage;
	const pageName = mw.config.get("wgPageName");
	
	if (box.val() === "") {
		const pageToPreview = storage.get(pageName) || getDefaultPreviewPage(pageName);
		box.val(pageToPreview);
	}
	
	button.click(function () {
		storage.set(pageName, box.val());
	});
}

$(doIt);

})();

function getSearchTitles() {
	return $('.mw-search-result-heading a').get()
		.map(function (elem) {
			return elem.textContent;
		});
}

$('p').get().forEach(function (elem) {
	if (elem.textContent.trim() === "") {
		elem.style.backgroundColor = 'pink';
	}
});

$(function() {
	const addZwnjBeforeCedilla = function(elem) {
		for (var child = elem.firstChild; child !== null; child = child.nextSibling) {
			if (child.processedCedilla)
				continue;
			switch (child.nodeType) {
				case Node.ELEMENT_NODE: {
					addZwnjBeforeCedilla(child); break;
				}
				case Node.TEXT_NODE: {
					child.nodeValue = child.nodeValue
						.normalize('NFD')
						.replace(/\u0327/g, '\u200C\u0327')
						.normalize('NFC');
				}
			}
			child.processedCedilla = true;
		}
	};
	
	$(":lang(mh)").get().forEach(addZwnjBeforeCedilla);
});

(function findParserReport() {
	const iter = document.createNodeIterator(document.getElementById("content"), NodeFilter.SHOW_COMMENT, function() { return NodeFilter.FILTER_ACCEPT; });
	var node;
	while ((node = iter.nextNode())) {
		const value = node.nodeValue;
		if (value.includes("NewPP limit report")) {
			console.info(value.trim()); break;
		}
	}
})();