User:Esperfulmo/vector.js

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

Note – after saving, it will take 5-10 minutes before the changes take effect. You may also 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.

This JavaScript is executed for Esperfulmo on every page load, when User:Esperfulmo is using the Vector skin.


// <nowiki>

/* jshint eqeqeq: true */
/* globals mw, $ */

'use strict';

(function () {
	// Each language array contains a canonical name, code, and an array of
	// row headers.
	// The array will be used to sort the table rows. List row headers in the order
	// that you want them to display.
	// If a row does not have its header listed in the array, it will appear
	// before all the headers in the array.
	// For German noun declension tables, this means that the "Case / #"
	// row will appear directly above the "Nominative" row.
	// Headers are converted to lowercase before this list is used.
	var languages = [
		[ "German", "de", [ "nominative", "accusative", "dative", "genitive" ] ]
	];
	
	function rearrange(languageName, languageCode, rowOrder) {
		if (typeof languageName !== "string" || typeof languageCode !== "string") {
			console.log(`${languageName}, ${languageCode}, ${rowOrder}.`);
			return;
		}
		
		if (mw.config.values.wgCategories.includes(languageName + " lemmas")) {
			var declensionTables = $(".inflection-table-" + languageCode + " tbody")
				// Declension tables for Indo-European languages presumably all
				// have a header with the case name "Nominative" or "nominative".
				.filter(function () {
					var html = $(this).html();
					return html.includes("Nominative") || html.includes("nominative");
				});
			
			// Get text of first header in row.
			var getCompareValue = function (row) {
				var header = $(row).children("th").first();
				if (header.find("a").length !== 0) {
					return rowOrder.indexOf(header.find("a").html().toLowerCase());
				} else if (header.find("i").length !== 0) {
					return rowOrder.indexOf(header.find("i").html().toLowerCase());
				} else {
					return rowOrder.indexOf(header.html().toLowerCase());
				}
			};
			
			declensionTables.each(function () {
				
				$(this).replaceWith(function () {
					return $(this)
						.children()
						.sort(function (a, b) {
							return getCompareValue(a) - getCompareValue(b);
						});
					}
				);
				
			});
		}
	}
	
	languages.forEach(function (language) {
		rearrange(language[0], language[1], language[2]);
	});
}());

// </nowiki>