User:Alien333/transclude.js

From Wikisource
Jump to navigation Jump to search
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.

/* global $, mw */
"use strict";
mw.loader.using(['mediawiki.util'], () => { $(() => {
	if (mw.config.get("wgCanonicalNamespace") == "User" && ["edit","submit"].includes(mw.config.get("wgAction"))) { // usually do it from my sandbox, so minimize chances of misclicks
	var btn = mw.util.addPortletLink('p-tb', '#', 'Transclude', 'transclude-btn', 'Transclude'); 
	$(btn).click(event => { event.preventDefault(); transclude() });
}})});
var uglify = s => s.replaceAll("{{ld}}", "———");
var prettify = s => s.replaceAll(/ *?\(.*?\)/g, "");
var errormess = { title: "transclude.js error", type : "error"};
var transclude = () => {
	var l = $("#wpTextbox1").val().trim().split("\n");
	var [root, index, ext] = l[0].split("|");
	var author = l[1].split("|");
	index = (index || root.split("/")[0].replaceAll(/\)|\(/g, "")) + "." + (ext || "djvu");
	var rootlink = "../".repeat(root.replaceAll(/[^\/]/g, "").length+1) + "|" + prettify(root.split("/")[0]);
	l = l.slice(2).map(s => s.split("/"));
	let notseen = new Set(l.map(x => x[0]));
	for (let t of l.map(x => x[0])) {
		if (notseen.has(t)) {
			notseen.delete(t);
		} else {
			mw.notify("There were two pages named "+t+".\nTransclusion was stopped, please disambiguate and then try again.", errormess);
			return;
		}
	}
	var loop = (i) => {
		setTimeout(() => {
			var title = l[i][0];
			var ranges = l[i][1].split(";").map(x => x.split(" "));
			var previous, next;
			if (i < 1) {
				previous = " ";
			} else if (uglify(l[i-1][0]) == prettify(l[i-1][0])) {
				previous = "[[../"+l[i-1][0]+"/]]";
			} else {
				previous = "[[../"+uglify(l[i-1][0])+"|"+prettify(l[i-1][0])+"]]";
			}
			if (i > l.length-2) {
				next = " ";
			} else if (uglify(l[i+1][0]) == prettify(l[i+1][0])) {
				next = "[[../"+l[i+1][0]+"/]]";
			} else {
				next = "[[../"+uglify(l[i+1][0])+"|"+prettify(l[i+1][0])+"]]";
			}
			var content =
`{{header
 | title      = [[`+rootlink+`]]`+((author.length == 1)?(`
 | author     = `+author[0]):(`
 | author1    = `+author[0]+`
 | author2    = `+author[1]))+`
 | translator = 
 | section    = `+prettify(title)+`
 | previous   = `+previous+`
 | next       = `+next+`
 | notes      =
}}

`;
			for (let i=0;i<ranges.length;i++) {
				let range = ranges[i];
				if (i > 0) {
					content += "{{ppb}}\n";
				}
				content += `<pages index="`+index+`" include=`+range[0]+((range[1])?(" fromsection="+range[1]):"")+((range[2])?(" tosection="+range[2]):"")+` />\n`;
			}
			editpage(
				uglify(root+"/"+title),
				content,
				"Page " + title + " was successfully created", 
				i
			);
		}, 700);
	};
	var editpage = (title, content, message, i) => {
		$.ajax({
			url: mw.util.wikiScript( 'api' ),
			data: {
				format: 'json',
				action: 'edit',
				title: title,
				summary: "created ([[User:Alien333/transclude.js|assisted]])",
				text: content,
				token: mw.user.tokens.get( 'csrfToken' )
			},
			dataType: 'json',
			type: 'POST',
			success: function( data ) { 
				if ( data && data.edit && data.edit.result == 'Success' ) { 
					mw.notify(
						message,
						{title: "transclude.js success", type: 'success'}
					);
					if (i) {
						return loop(i-1);
					} else {
						mw.notify("All pages given were created.", {title:"transclude.js finished", type:"info"});
					}
				} else { 
					mw.notify( "Error: "+(
							(data && data.error)
							?('Error code ' + data.error.code + ' : ' + data.error.info):
							"Unknown error"
							)+". Trying again soon...", 
						errormess
					);
					return loop(i);
				}
			},
			error: function( xhr ) { 
				mw.notify( 'Error: Request failed.', errormess );
				return loop(i);
			}
		});
	};
	if (window.confirm("CHECK THE ARGUMENTS: rootpage: "+root+", author: "+author+", index: "+index+".\n\nNow, are you absolutely sure you want to do this? Of course, anything you do is your own responsibility, etc.")) {
		loop(l.length-1);
	}
};