Difference between revisions of "MediaWiki:ExportDocSnippets.js"

From HSYCO
Jump to navigation Jump to search
Line 23: Line 23:
  
 
function next() {
 
function next() {
if (!myWindow)
+
if (!myWindow) {
 
myWindow = window.open();
 
myWindow = window.open();
 +
myWindow.document.write("Please wait...");
 +
}
 
l++;
 
l++;
 
if (urls[l]) {
 
if (urls[l]) {
Line 109: Line 111:
 
if (!myWindow)
 
if (!myWindow)
 
myWindow = window.open();
 
myWindow = window.open();
 +
myWindow.document.write("<hr>");
 
myWindow.document.write("<p>"+title+"</p>");
 
myWindow.document.write("<p>"+title+"</p>");
 
myWindow.document.write("<textarea id='txt' style='width:80%; height:80%'>"+str+"</textarea>");
 
myWindow.document.write("<textarea id='txt' style='width:80%; height:80%'>"+str+"</textarea>");

Revision as of 14:30, 16 January 2017

// copy/paste and call print()
var myWindow;

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
var l = -1;
var baseUrl = "http://wiki.hsyco.com/3.6.0/index.php/"
var urls = [
	{url: "Event_Keywords", sub:"Events", opt:{event:true}, arr:"events"},
	{url: "Action_Keywords", sub:"Actions", opt:{action:true}, arr:"actions"},
	{url: "JavaScript_Callback_Functions_API", sub:"Javascript Callback Functions", opt:{jsEvent:true}, arr:"events"},
	{url: "JavaScript_Command_and_Utility_Functions_API", sub:"Javascript Command and Utility Functions", opt:{jsAction:true}, arr:"js"},
	{url: "Index.js", sub:"Javascript", opt:{js:true}, arr:"indexjs"},
];

function reqListener () {
	console.log("loaded "+urls[l].url);
	var div = document.createElement('div');
	div.innerHTML = this.responseText;
	urls[l].res = parse(div, urls[l].sub, urls[l].opt);
	next();
}

function next() {
	if (!myWindow) {
		myWindow = window.open();
		myWindow.document.write("Please wait...");
	}
	l++;
	if (urls[l]) {
		oReq.open("GET", baseUrl+urls[l].url);
		oReq.send();
	} else {
		var head = "\
ace.define('ace/snippets/%what',['require','exports','module'], function(require, exports, module) {\n\
var s = {\n\
\t// scopes\n\
\tevents:[],\n\
\tactions:[],\n\
\tjs:[]\n\
};\n\n\
exports.snippetText = s;\n\n\n";

		var tail = "exports.scope = '%what';\n});";

		str = head.replace("%what","events");
		for (var i = 0; i < urls.length-1; i++) { // skip index.js
			str += "var a = s."+urls[i].arr+";\n";
			str += urls[i].res;
			str += "\n\n\n";
		}
		str += tail.replace("%what","events");;
		openWin("events.js",str);


		str = head.replace("%what","javascript");
		str += "var a = s.js;\n";
		str += urls[4].res;
		str += "\n\n\n// js\n\n";
		var s;
		for (var i=0; i<jsSnippets.length; i++) {
			s = jsSnippets[i];
			str += "a.push({\n";
			str += "\ttitle:\""+s.title+"\",\n";
			str += "\ttabTrigger:\""+s.tabTrigger+"\",\n";
			str += "\tcontent:\""+s.content+"\"\n";
			str += "});\n";
		}
		str += "\n\n\n";
		str += tail.replace("%what","events");;
		openWin("javascript.js",str);



		console.log("done");
	}
}

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

// CALL THIS
function print(sub, opt) {
	var url = "";
	for (var i=0; i<urls.length; i++) {
		if (window.location.href.indexOf(urls[i].url)!=-1) {
			sub = urls[i].sub;
			opt = urls[i].opt;
			url = urls[i].url;
			break;
		}
	}

	var str = parse(document,sub,opt,baseUrl+url);
	openWin("",str);
}

function openWin(title,str) {
	if (!myWindow)
		myWindow = window.open();
	myWindow.document.write("<hr>");
	myWindow.document.write("<p>"+title+"</p>");
	myWindow.document.write("<textarea id='txt' style='width:80%; height:80%'>"+str+"</textarea>");
	myWindow.document.write("<p></p>");
	myWindow.document.getElementById('txt').select();
}

function parse(e, asub, opt, url) {
	function rr(s) { // remove return and trim
		s = s.trim();
		while (s[s.length-1] == "\n")
			s = s.substr(0,s.length-1);
		return s;
	}
	function stripDescr(d) {
		d = d.replace(/\n+/g, "");
		d = d.replace(/(^(<br>)+|(<br>)+$)/g, ""); // initial, end br
		d = d.replace(/\n+/g, "<br>");
		d = d.replace(/(<br>)+/g, "<br>");
		d = d.replace(/\<(\/?(ul|li|string|br))\>/g, "+___$1___-"); // keep these
		d = d.replace(/<(?:.|\n)*?>/gm, ''); // strip html
		d = d.replace(/\+___/g, "<"); // restore
		d = d.replace(/___-/g, ">");
		d = d.replace(/(<br>)?<\/li>(<br>)?/g, "</li>"); // remove breaklines inside/outside li
		d = d.trim();
		return d;
	}
	var a = e.getElementsByClassName("mw-headline");
	if (!opt) opt = {};

	var nl = "\\n\\"+"\n";

	var snippets = [];
	var variations = [];
	var pE, nE;
	var str = "";
	var title, subtitle, descr, snippet, content;
	var bsub; // combined with asub to create subtitle
	for (var i=0; i<a.length; i++) {
		pE = a[i].parentElement;
		nE = pE ? pE.nextElementSibling : null;

		title = rr(a[i].innerHTML);
		subtitle = asub + (bsub? ", "+bsub : "");

		snippet = "";
		if (pE.nodeName == "H3") {
			if (nE && (nE.nodeName == "PRE" || nE.className.indexOf("mw-code")!=-1)) {
				snippet = nE.innerHTML;
				snippet = snippet.replace(/<(?:.|\n)*?>/gm, ''); // strip html
				content = snippet;
				title = snippet;
				nE = nE.nextElementSibling;
			}
			descr = "";
			var grabAll = opt.event || opt.action; // grab all html
			while (nE) {
				if (!grabAll && nE.nodeName != "P" && nE.nodeName != "UL")
					break;
				if (nE.className == "mw-headline" || nE.getElementsByClassName("mw-headline").length)
					break;
				if (nE.getAttribute("data-skipeditordoc"))
					break;

				var d = rr(grabAll ? nE.outerHTML : nE.innerHTML);

				//d = d.replace(/<a href="/g, "<a target='_blank' href=\"http://wiki.hsyco.com/3.6.0");
				if (!grabAll) {
					d = stripDescr(d);
					if (nE.nodeName == "UL")
						d = "<ul>"+d+"</ul>";

					if (d.indexOf("Examples:")!=-1)
						break;

					if (d.indexOf("Parameters:")!=-1 ||
						d.indexOf("Returns:")!=-1) {
						descr += "<br>";
					}
				} else {
					// bulb image
					d = d.replace(/<img .+src=".+Bulbgraph.png".+(width="[^"]+").+(height="[^"]+")[^>]+>/g,
									"<img src=\"/manager/pic/bulb.png\" $1 $2>");
					// remove \n
					d = d.replace(/\n/g,"");
					// variations?
					if (nE.nodeName == "TABLE") {
						var f = nE.getElementsByTagName("TD")[0];
						if (f && f.innerHTML &&
							(f.innerHTML.indexOf("Action")!=-1 ||f.innerHTML.indexOf("Event")!=-1)) {
							var rows = nE.getElementsByTagName("TR");
							var cols;
							var txt, atxt;
							for (var r = 1; r < rows.length; r++) {
								cols = rows[r].getElementsByTagName("TD");
								txt = cols[0] ? cols[0].innerHTML : "";
								if (txt && txt != title) {
									atxt = txt.split(/\s*\<br[^\>]*\>\s*/);
									for (var v = 0; v < atxt.length; v++) {
										variations.push({src:atxt[v].trim(), descr:cols[1] ? cols[1].innerHTML : ""});
									}
								}
							}
						}
					}
				}

				if (d)
					descr += (descr ? "<br>" : "") + d;
				nE = nE.nextElementSibling;
			}
			// check variations
			var s,c;
			for (var v = 0; v < variations.length; v++) {
				s = variations[v].src;
				// replace lowercase words, separated by space or start/end line
				c = s.replace(/(^|\s+)("?[a-z0-9]+"?)($|\s+)/g, "$1\${0:$2}$3");
				var count = 1;
				c = c.replace(/\$\{0/g, function (match, capture) { return '${' + count++;});

				// strip html, new lines
				s = s.replace(/<(?:.|\n)*?>/gm, '').replace(/\n/g,"");
				c = c.replace(/<(?:.|\n)*?>/gm, '').replace(/\n/g,"");
				variations[v].snippet = s;
				variations[v].content = c; // strip html;
			}

			if (!snippet) {
				snippet = title;
				content = snippet;
			}

			title = rr(title);
			snippet = rr(snippet);
			content = rr(content);

			if (opt.jsEvent || (opt.js && bsub == "Events")) {
				snippet = "function " + snippet;
				if (content.indexOf("function") != 0)
					content = "function " + content;
				content += (opt.js? " {" : " : {") + "\\n";
				content += "\\t${1:// body...} " + "\\n";
				content += "}";
			} else if (opt.jsAction || (opt.js && bsub == "Functions")) {
				content = content.replace(/([\(,]+\s?)([^\)^\s^,]+)/g, "$1\${0:$2}");
				var count = 1;
				content = content.replace(/\$\{0/g, function (match, capture) { return '${' + count++;});
			} else if (opt.js && (bsub == "Examples" || bsub == "User Object")) {
				continue;
			} else {
				content += " ";
			}

			if (title && descr) {
				descr = descr.replace(/["“”]/g,'\\"');
				/*
				var _url = url+"#"+title;
				title = "<br><br><a target='_blank' href='"+_url+"'>"+title+"</a>";
				*/
				if (variations.length) {
					for (var v = 0; v < variations.length; v++) {
						snippets.push({
							title:variations[v].snippet,
							subtitle:subtitle,
							descr:v?"_again_":descr, //+"<br><br>"+variations[v].descr+_url,
							snippet:variations[v].snippet,
							content:variations[v].content
						});
					}
					variations = [];
				} else {
					snippets.push({
						title:title,
						subtitle:subtitle,
						descr:descr,
						snippet:snippet,
						content:content
					});
				}
			}
		} else if (pE.nodeName == "H2"){
			bsub = title;
		}
	}

	if (false && !opt.noSort) {
		snippets.sort(function(a,b){
			if (a.snippet > b.snippet) {
				return 1;
			}
			if (a.snippet < b.snippet) {
				return -1;
			}
			// a must be equal to b
			return 0;
		});
	}

	var s;
	for (var i=0; i<snippets.length; i++) {
		s = snippets[i];
		str += "a.push({\n";
		str += "\ttitle:\""+s.title.replace(/["“”]/g,'\\"')+"\",\n";
		str += "\tsubTitle:\""+s.subtitle.replace(/["“”]/g,'\\"')+"\",\n";

		if (s.descr == "_again_")
			str += "\tdocHTML:a.last().docHTML,\n";
		else
			str += "\tdocHTML:\""+s.descr+"\",\n";

		str += "\ttabTrigger:\""+s.snippet.replace(/["“”]/g,'\\"')+"\",\n";
		str += "\tcontent:\""+s.content.replace(/["“”]/g,'\\"')+"\"\n";
		str += "});\n";
	}

	return str;
}

//////////////////////////////////////////////////////////////////////
// DEFAULT JS
//////////////////////////////////////////////////////////////////////
var jsSnippets = [];
var a = jsSnippets;
a.push({
	title:"fun",
	tabTrigger:"fun",
	content:"function ${1?:function_name}(${2:argument}) {\n\t${3:// body...}\n}"
});
a.push({
	title:"if",
	tabTrigger:"if",
	content:"if (${1:true}) {\n\t${0}\n}"
});
a.push({
	title:"ife",
	tabTrigger:"ife",
	content:"if (${1:true}) {\n\t${2}\n} else {\n\t${0}\n}"
});
a.push({
	title:"ter",
	tabTrigger:"ter",
	content:"${1:/* condition */} ? ${2:a} : ${3:b}"
});
a.push({
	title:"switch",
	tabTrigger:"switch",
	content:"switch (${1:expression}) {\n\tcase '${3:case}':\n\t\t${4:// code}\n\t\tbreak;\n\t${5}\n\tdefault:\n\t\t${2:// code}\n}"
});
a.push({
	title:"case",
	tabTrigger:"case",
	content:"case '${1:case}':\n\t${2:// code}\n\tbreak;\n${3}"
});
a.push({
	title:"wh",
	tabTrigger:"wh",
	content:"while (${1:/* condition */}) {\n\t${0:/* code */}\n}"
});
a.push({
	title:"try",
	tabTrigger:"try",
	content:"try {\n\t${0:/* code */}\n} catch (e) {}"
});
a.push({
	title:"do",
	tabTrigger:"do",
	content:"do {\n\t${2:/* code */}\n} while (${1:/* condition */});"
});
a.push({
	title:"setTimeout",
	tabTrigger:"setTimeout",
	content:"setTimeout(function() {${3:$TM_SELECTED_TEXT}}, ${1:10});"
});
a.push({
	title:"gett",
	tabTrigger:"gett",
	content:"getElementsBy${1:TagName}('${2}')${3}"
});
a.push({
	title:"get",
	tabTrigger:"get",
	content:"getElementBy${1:Id}('${2}')${3}"
});
a.push({
	title:"cl",
	tabTrigger:"cl",
	content:"console.log(${1});"
});
a.push({
	title:"ret",
	tabTrigger:"ret",
	content:"return ${1:result}"
});
a.push({
	title:"fori",
	tabTrigger:"fori",
	content:"for (var ${1:prop} in ${2:Things}) {\n\t${0:$2[$1]}\n}"
});
a.push({
	title:"jsonp",
	tabTrigger:"jsonp",
	content:"JSON.parse(${1:jstr});"
});
a.push({
	title:"jsons",
	tabTrigger:"jsons",
	content:"JSON.stringify(${1:object});"
});
a.push({
	title:"for-",
	tabTrigger:"for-",
	content:"for (var ${1:i} = ${2:Things}.length; ${1:i}--; ) {\n\t${0:${2:Things}[${1:i}];}\n}"
});
a.push({
	title:"for",
	tabTrigger:"for",
	content:"for (var ${1:i} = 0; $1 < ${2:Things}.length; $1++) {\n\t${3:$2[$1]}$0\n}"
});
a.push({
	title:"forr",
	tabTrigger:"forr",
	content:"for (var ${1:i} = ${2:Things}.length - 1; $1 >= 0; $1--) {\n\t${3:$2[$1]}$0\n}"
});