Jump to content

User:Alien333/prefillalt.js

From Wikisource
Note: After saving, changes may not occur immediately. Click here to learn how to bypass your browser's cache.
  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (Cmd-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (Cmd-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Clear the cache in Tools → Preferences

For details and instructions about other browsers, see Wikipedia:Bypass your cache.

/* Preload Template:Header when adding a new text -- forked by [[User:Alien333]] on 27/01/25 */
/* For help, see '''Help:Header preloading script gadget''' */
/*jshint asi:true, eqnull:true, laxbreak:true, forin: false */
/*global mw, $, */
mw.hook("wikipage.editform").add(()=>{let api = new mw.Api();
let parents = () => { // get all possible parents
	let a = [] , i = -1, s = mw.config.get("wgPageName");
	while ( ( i = s.indexOf("/", i+1) ) >= 0 )
		a.push(s.slice(0, i));
	return a;
}
function preloadHeaderTemplate()
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value == "")
	{
		//fill in header template
		api.get({
			action:"query",
			titles:parents().join("|"),
			prop:"info",
		}).done( (response) => {
			let titles = Object.values(new Object(response?.query?.pages))
				.filter(x => x.missing == undefined)
				.map(x => x.title); // list of all existing parents
			var isSubpage = !!titles.length;
			var basePageTitle = isSubpage?(titles.reduce( (a, b) => a.length < b.length ? a : b )):"Main Page"; // base page is the shortest
			var tocPageTitle = isSubpage?(titles.reduce( (a, b) => a.length > b.length ? a : b )):"Main Page"; // toc page is the longest
			// the "Main Page" are just to prevent API crash, as we don't use the content if !isSubpage
			api.get({
				action:"parse",
				page:tocPageTitle,
				prop:"text|wikitext",
			}).done( (re) => {
				var tocPageContent = re.parse.wikitext["*"];
				var tocHtml = re.parse.text["*"];
				var tocPageLinks = Array.from(
					tocHtml
					.matchAll(/<a( class="new")? href="(\/wiki\/|\/w\/index\.php\?title=)([^&"]+)["&][^>]*?>(.*?)<\/a>/g)
				).map(x => [x[3], x[4]].map(x => x.replaceAll("_", " ")))
				.filter(x => !x[0].includes(":"));
				var wpTextbox1value = "{" + "{header\n | title      = "
				
				//output
				if (!isSubpage)
				{
					wpTextbox1value += mw.config.get('wgTitle')
				} else {
					wpTextbox1value += "[["
				
					//output however many "../" will take us to the base page
					wpTextbox1value += "../".repeat(mw.config.get("wgPageName").replaceAll(/[^\/]/g, "").length - basePageTitle.replaceAll(/[^\/]/g, "").length);
					
					wpTextbox1value += "]]"
				}
				
				//author
				wpTextbox1value += "\n | author     = "
				if (isSubpage)
				{
					try
					{
						wpTextbox1value += /\{\{[\s]*[Hh]eader[2]?[\s]*[\s\S]*\|[\s]*author[\s]*\=([^\||\}\}]*)/.exec(tocPageContent)[1].trim();
					}
					catch (e)
					{
						//if there was an error, just leave the field blank
					}
				}
				
				//translator
				wpTextbox1value += "\n | translator = "
				if (isSubpage)
				{
					try
					{
						wpTextbox1value += /\{\{[\s]*[Hh]eader[2]?[\s]*[\s\S]*\|[\s]*translator[\s]*\=([^\||\}\}]*)/.exec(tocPageContent)[1].trim();
					}
					catch (e)
					{
						//if there was an error, just leave the field blank
					}
				}
				
				//used for both previous page and next page determination
				var indexOfCurrentPageInTableOfContents = tocPageLinks.findIndex(x => x[0] == mw.config.get("wgPageName").replaceAll("_", " "));
				//section
				wpTextbox1value += "\n | section    = "
				if (isSubpage) //only subpages have section titles
				{
					try
					{
						wpTextbox1value += tocPageLinks[indexOfCurrentPageInTableOfContents][1];
					}
					catch (e)
					{
						//if there was an error, fall back on just adding the section name
						wpTextbox1value += mw.config.get("wgTitle").split("/").reverse()[0]
					}
				}
				
				//previous
				wpTextbox1value += "\n | previous   = "
				try
				{
					if (indexOfCurrentPageInTableOfContents > 0) {
						var previousPageTitle = tocPageLinks[indexOfCurrentPageInTableOfContents-1];
						wpTextbox1value += "[[" + previousPageTitle[0] + "|" + previousPageTitle[1] + "]]";
					}
				}
				catch (e)
				{
					//if there was an error, just leave the field blank
				}
				
				//next
				wpTextbox1value += "\n | next       = "
				try
				{
					if (indexOfCurrentPageInTableOfContents < tocPageLinks.length-1 && 0 <= indexOfCurrentPageInTableOfContents)
					{
						var nextPageTitle = tocPageLinks[indexOfCurrentPageInTableOfContents+1];
						wpTextbox1value += "[[" + nextPageTitle[0] + "|" + nextPageTitle[1] + "]]";
					}
				}
				catch (e)
				{
					//if there was an error, just leave the field blank
				}
		
				// year (except on subpages)
				if( mw.config.get('wgTitle').indexOf("/") == -1 )
				{
					wpTextbox1value += "\n | year       = ";
				}
				
				//notes
				wpTextbox1.value = wpTextbox1value + "\n | notes      = \n}}\n\n"
			})
		});
	}
}

/* Preload Template:Textinfo when starting a discussion page */
function preloadTextinfoTemplate()
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value == "" && !document.URL.match('&section=new') )
	{
		wpTextbox1.value = "{" + "{textinfo\n | edition      = \n | source       = \n | contributors = \n | progress     = \n | notes	    = \n | proofreaders = \n}}\n"
	}
}

let getSpecialWordPos = (words) =>
{
	var i;
	for (i = 0; i < words.length; ++i) {
		if (words[i] == 'van' || words[i] == 'von' ||
			words[i] == 'le' || words[i] == 'de') {
		   return i;
		}
	}
	return -1;
}

let getLastInitial = (words) => 
{
	// get_last_name() can't be used here, we want the last word or the next
	// word following a special word
	var lastname = words[words.length - 1];
	var pos = getSpecialWordPos(words);
	if (pos != -1 && pos < words.length - 1)
		 lastname = words[pos + 1];

	var last_initial = lastname.slice(0, 2);
	// O'Donnel --> Od
	if (lastname.length > 2 && last_initial.charAt(1) == "'")
		last_initial = last_initial.charAt(0) + lastname.charAt(2).toLowerCase();
	return last_initial;
}

// Preload Template:Author when starting an author page, derived from [[User:Remember the dot]] code 
// Try to fill field when creating an author page. Fields always filled, are
// lastname, firstname, lastinitial.
let preloadAuthorTemplate = () =>
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value != "")  return;

	// try to figure out what value we can fill, broken in some case because
	// it's difficult to handle name like Tom Van Moore but Tom van Moore is
	// handled correctly.
	var words = mw.config.get('wgTitle').replace(/ \(.*\)/, "").split(" ");
	var lastname = words.slice(getSpecialWordPos(words)).join(" ");
	var firstname = words.slice(0, getSpecialWordPos(words)).join(" ");
	var last_initial = getLastInitial(words);

	wpTextbox1.value  = "{" + "{author\n" +
						" | firstname    = " + firstname + "\n" +
						" | lastname     = " + lastname + "\n" +
						" | last_initial = " + last_initial + "\n" +
						" | birthyear    = <" + "!--data now imported from wikidata, please consider deleting once matched-->\n" +
						" | deathyear    = <" + "!--data now imported from wikidata, please consider deleting once matched-->\n" +
						" | description  = \n" +
						"}}\n\n" +
						"==Works==\n\n";
}


// Preload Template:Process header when starting a project or help page
// Simple preloader based on the preload code for Template:Textinfo
function preloadProcessHeaderTemplate()
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value == "" && !document.URL.match('&section=new') )
	{
		wpTextbox1.value = "{" + "{process header\n | title    = \n | section  = \n | previous = \n | next     = \n | shortcut = \n | notes    = \n}}\n"
	}
}




// Preload Template:Portal header when starting a portal page
// Simple preloader based on the preload code for Template:Textinfo
function preloadPortalHeaderTemplate()
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value == "" && !document.URL.match('&section=new') )
	{
		wpTextbox1.value = "{" + "{portal header\n | title     = \n | class     = \n | subclass1 = \n | reviewed  = \n | shortcut  = \n | notes     = \n}}\n\n==Works==\n\n"
	}
}

// Preload Template:Portal review when starting a portal discussion page
// Simple preloader based on the preload code for Template:Textinfo
function preloadPortalReviewTemplate()
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value == "" && !document.URL.match('&section=new') )
	{
		wpTextbox1.value = "{" + "{portal review\n | class      = \n | subclass1  = \n | subclass2  = \n | classifier = \n | reviewer   = \n | notes      = \n}}\n"
	}
}




// Preload Template:Translation header when starting a translation page
// Simple preloader based on the preload code for Template:Textinfo
function preloadTranslationHeaderTemplate()
{
	var wpTextbox1 = document.getElementById("wpTextbox1")
	if (wpTextbox1.value == "" && !document.URL.match('&section=new') )
	{
		wpTextbox1.value = "{" + "{translation header\n | title    = \n | author   = \n | section  = \n | previous = \n | next     = \n | year     = \n | language = \n | original = \n | notes    = \n}}\n"
	}
}




// Main preloader loading code:
switch (mw.config.get('wgNamespaceNumber')) {
	case 0: //main
		$(preloadHeaderTemplate)
		break
	case 1: //Talk
		$(preloadTextinfoTemplate)
		break
	case 4: //Wikisource
		$(preloadProcessHeaderTemplate)
		break
	case 12: //Help
		$(preloadProcessHeaderTemplate)
		break
	case 100: //Portal
		$(preloadPortalHeaderTemplate)
		break
	case 101: //Portal talk
		$(preloadPortalReviewTemplate)
		break
	case 102: //Author
		$(preloadAuthorTemplate)
		break
	case 114: //Translation
		$(preloadTranslationHeaderTemplate)
}
});