User:Erutuon/scripts/simpleTranslations.js

From Wiktionary, the free dictionary
Jump to navigation Jump to search

Note – after saving, you may have to bypass your browser’s cache to see the changes.

  • Mozilla / Firefox / Safari: hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Command-R on a Macintosh);
  • Konqueror and Chrome: click Reload or press F5;
  • Opera: clear the cache in Tools → Preferences;
  • Internet Explorer: hold Ctrl while clicking Refresh, or press Ctrl-F5.

/*
 * Converts Latin-script translations with no parameters besides language, term, and gender to {{t-simple}}.
 * Add a link just above the edit box, if you're in the main namespace,
 * and if a Translations header exists on the page.
 */

/* jshint eqeqeq: true, esversion: 6, undef: true, unused: true, varstmt: true */
/* globals $, CleanupButtons, mw */
// <nowiki>

if ( mw.config.get("wgNamespaceNumber") === 0 && document.querySelector(".translations") !== null ) {
	const summary = "{{[[T:t-simple|t-simple]]}} for Latin-script terms with just lang, term, and gender, to reduce Lua memory usage, using [[User:Erutuon/simpleTranslations.js|JavaScript]]";
			
	// Uses Latin-script pattern from [[Module:scripts/data]]: A-Za-zÀ-ÖØ-öø-ɏḀ-ỿ
	const translationRegex = /\n\* ([^\:\{\n]+)\: *(.*)\{\{t(\+?)\|([^\|\}\n]+?)\|([A-Za-zÀ-ÖØ-öø-ɏḀ-ỿ]+)(?:\|([^|}]+))?\}\}/g;
	
	const convertToSimple = (content) => {
		let count = 0;
		
		const addSimple = (wholeMatch, langName, intervening, interwiki, langCode, term, gender) => {
			++count;
			return "\n* " + langName + ": " + intervening + "{{t-simple|"
				+ langCode + "|" + term
				+ (gender ? "|" + gender : "")
				+ "|langname=" + langName
				+ (interwiki === "+" ? "|interwiki=1" : "")
				+ "}}";
		};
		
		while ( translationRegex.test(content) )
			content = content.replace(translationRegex, addSimple);
		
		mw.notify(count > 0
			? `${count} replacement${count > 1 ? "s" : ""} made.`
			: "No replacements of translation templates were made.");
		
		$("#wpSummary").val((index, value) => {
			const match = value.match(/^\/\*[^\*]+\*\/\s+(.+)/);
			let addition;
			const afterSectionName = match ? match[1] : "";
			if ( count > 0 && !afterSectionName.includes(summary) ) {
				addition = (afterSectionName.length > 1 ? "; " : "")
					+ summary;
			}
			
			return value + (addition || "");
		});
		
		return content;
	};
	
	$.getScript("//en.wiktionary.org/w/index.php?title=User:Erutuon/scripts/CleanupButtons.js&action=raw&ctype=text/javascript")
		.done(() => {
			const buttons = new CleanupButtons();
			
			buttons.addButton({
				button: {
					text: "switch Latin-script translations to {{t-simple}}"
				},
				func: convertToSimple,
			});
		});
}

// </nowiki>