Difference between revisions of "MediaWiki:ExportDocSnippets.js"

From HSYCO
Jump to navigation Jump to search
 
(14 intermediate revisions by the same user not shown)
Line 62: Line 62:
 
s = jsSnippets[i];
 
s = jsSnippets[i];
 
str += "a.push({\n";
 
str += "a.push({\n";
str += "\ttitle:\""+s.title+"\",\n";
+
str += "\ttitle:\""+s.title.split("(")[0]+"\",\n";
 
str += "\ttabTrigger:\""+s.tabTrigger+"\",\n";
 
str += "\ttabTrigger:\""+s.tabTrigger+"\",\n";
 
str += "\tcontent:\""+s.content.replace(/\t/g,"\\t").replace(/\n/g,"\\n")+"\"\n";
 
str += "\tcontent:\""+s.content.replace(/\t/g,"\\t").replace(/\n/g,"\\n")+"\"\n";
Line 68: Line 68:
 
}
 
}
 
str += "\n\n\n";
 
str += "\n\n\n";
str += tail.replace("%what","events");;
+
str += tail.replace("%what","javascript");;
 
openWin("javascript.js",str);
 
openWin("javascript.js",str);
  
Line 113: Line 113:
 
myWindow.document.write("\
 
myWindow.document.write("\
 
<script>\n\
 
<script>\n\
function addDownload(n) {\n\
+
function addDownload(n,f) {\n\
 
var data = document.getElementById('txt'+n).value;\n\
 
var data = document.getElementById('txt'+n).value;\n\
 
var link = document.createElement('a');\n\
 
var link = document.createElement('a');\n\
 
link.setAttribute('href','data:text/text;charset=utf-8,'+encodeURI(data));\n\
 
link.setAttribute('href','data:text/text;charset=utf-8,'+encodeURI(data));\n\
link.setAttribute('download', 'fileName.txt');\n\
+
link.setAttribute('download', f);\n\
 
link.innerHTML = 'download file';\n\
 
link.innerHTML = 'download file';\n\
 
document.getElementById('p'+n).appendChild(link);\n\
 
document.getElementById('p'+n).appendChild(link);\n\
Line 132: Line 132:
  
 
myWindow.document.write("<hr>");
 
myWindow.document.write("<hr>");
myWindow.document.write("<p>"+title+"</p>");
+
myWindow.document.write("<h1>"+title+"</h1>");
 
myWindow.document.write("<p id='p"+_no+"'>");
 
myWindow.document.write("<p id='p"+_no+"'>");
 
myWindow.document.write("</p>");
 
myWindow.document.write("</p>");
 
myWindow.document.write("<textarea id='txt"+_no+"' style='width:800px; height:400px'>"+str+"</textarea>");
 
myWindow.document.write("<textarea id='txt"+_no+"' style='width:800px; height:400px'>"+str+"</textarea>");
myWindow.document.write("<script>addDownload("+_no+")</script>");
+
myWindow.document.write("<script>addDownload("+_no+",'"+title+"')</script>");
 
myWindow.document.write("<p></p>");
 
myWindow.document.write("<p></p>");
 
myWindow.document.getElementById('txt'+_no).select();
 
myWindow.document.getElementById('txt'+_no).select();
Line 189: Line 189:
 
}
 
}
 
descr = "";
 
descr = "";
var grabAll = opt.event || opt.action; // grab all html
+
var grabAll = true; //opt.event || opt.action; // grab all html
 
while (nE) {
 
while (nE) {
 
if (!grabAll && nE.nodeName != "P" && nE.nodeName != "UL")
 
if (!grabAll && nE.nodeName != "P" && nE.nodeName != "UL")
Line 200: Line 200:
 
var d = rr(grabAll ? nE.outerHTML : nE.innerHTML);
 
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) {
 
if (!grabAll) {
 
d = stripDescr(d);
 
d = stripDescr(d);
Line 213: Line 212:
 
descr += "<br>";
 
descr += "<br>";
 
}
 
}
 +
if (d)
 +
descr += (descr ? "<br>" : "") + d;
 
} else {
 
} else {
 
// bulb image
 
// bulb image
 
d = d.replace(/<img .+src=".+Bulbgraph.png".+(width="[^"]+").+(height="[^"]+")[^>]+>/g,
 
d = d.replace(/<img .+src=".+Bulbgraph.png".+(width="[^"]+").+(height="[^"]+")[^>]+>/g,
 
"<img src=\"/manager/pic/bulb.png\" $1 $2>");
 
"<img src=\"/manager/pic/bulb.png\" $1 $2>");
// remove \n
+
// replace \n\t
d = d.replace(/\n/g,"");
+
d = d.replace(/\n/g,"\\n").replace(/\t/g,"\\t");
 
// variations?
 
// variations?
 
if (nE.nodeName == "TABLE") {
 
if (nE.nodeName == "TABLE") {
Line 239: Line 240:
 
}
 
}
 
}
 
}
 +
if (d)
 +
descr += d;
 
}
 
}
  
if (d)
 
descr += (descr ? "<br>" : "") + d;
 
 
nE = nE.nextElementSibling;
 
nE = nE.nextElementSibling;
 
}
 
}
Line 249: Line 250:
 
for (var v = 0; v < variations.length; v++) {
 
for (var v = 0; v < variations.length; v++) {
 
s = variations[v].src;
 
s = variations[v].src;
// replace lowercase words, separated by space or start/end line
+
s = s.replace("&lt;","<");
c = s.replace(/(^|\s+)("?[a-z0-9]+"?)($|\s+)/g, "$1\${0:$2}$3");
+
s = s.replace("&gt;",">");
 +
// replace variables (lowercase words), separated by space or start/end line
 +
c = s.replace(/(^|\s*|:)("?)([a-z0-9:_\.]+)("?)($|\n|\s*|:)/g, "$1$2\${0:$3}$4$5");
 
var count = 1;
 
var count = 1;
 
c = c.replace(/\$\{0/g, function (match, capture) { return '${' + count++;});
 
c = c.replace(/\$\{0/g, function (match, capture) { return '${' + count++;});
Line 271: Line 274:
  
 
if (opt.jsEvent || (opt.js && bsub == "Events")) {
 
if (opt.jsEvent || (opt.js && bsub == "Events")) {
snippet = "function " + snippet;
+
if (title.indexOf("function") != 0)
 +
title = "function " + title;
 +
if (snippet.indexOf("function") != 0)
 +
snippet = "function " + snippet;
 
if (content.indexOf("function") != 0)
 
if (content.indexOf("function") != 0)
 
content = "function " + content;
 
content = "function " + content;
Line 289: Line 295:
 
if (title && descr) {
 
if (title && descr) {
 
descr = descr.replace(/["“”]/g,'\\"');
 
descr = descr.replace(/["“”]/g,'\\"');
/*
 
var _url = url+"#"+title;
 
title = "<br><br><a target='_blank' href='"+_url+"'>"+title+"</a>";
 
*/
 
 
if (variations.length) {
 
if (variations.length) {
 
for (var v = 0; v < variations.length; v++) {
 
for (var v = 0; v < variations.length; v++) {
Line 344: Line 346:
 
str += "\tdocHTML:\""+s.descr+"\",\n";
 
str += "\tdocHTML:\""+s.descr+"\",\n";
  
str += "\ttabTrigger:\""+s.snippet.replace(/["“”]/g,'\\"')+"\",\n";
+
//str += "\ttabTrigger:\""+s.snippet.replace(/["“”]/g,'\\"')+"\",\n";
 
str += "\tcontent:\""+s.content.replace(/["“”]/g,'\\"')+"\"\n";
 
str += "\tcontent:\""+s.content.replace(/["“”]/g,'\\"')+"\"\n";
 
str += "});\n";
 
str += "});\n";

Latest revision as of 10:27, 24 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) {
		initWin();
		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.split("(")[0]+"\",\n";
			str += "\ttabTrigger:\""+s.tabTrigger+"\",\n";
			str += "\tcontent:\""+s.content.replace(/\t/g,"\\t").replace(/\n/g,"\\n")+"\"\n";
			str += "});\n";
		}
		str += "\n\n\n";
		str += tail.replace("%what","javascript");;
		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 initWin() {
	myWindow = window.open("about:blank","Editor Snippets");

	myWindow.document.write("\
	<script>\n\
		function addDownload(n,f) {\n\
			var data = document.getElementById('txt'+n).value;\n\
			var link = document.createElement('a');\n\
			link.setAttribute('href','data:text/text;charset=utf-8,'+encodeURI(data));\n\
			link.setAttribute('download', f);\n\
			link.innerHTML = 'download file';\n\
			document.getElementById('p'+n).appendChild(link);\n\
		}\n\
	</script>");
}

var _no = 0;  // number of outputs
function openWin(title,str) {
	if (!myWindow)
		initWin();

	_no++;

	myWindow.document.write("<hr>");
	myWindow.document.write("<h1>"+title+"</h1>");
	myWindow.document.write("<p id='p"+_no+"'>");
	myWindow.document.write("</p>");
	myWindow.document.write("<textarea id='txt"+_no+"' style='width:800px; height:400px'>"+str+"</textarea>");
	myWindow.document.write("<script>addDownload("+_no+",'"+title+"')</script>");
	myWindow.document.write("<p></p>");
	myWindow.document.getElementById('txt'+_no).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 = true; //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);

				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>";
					}
					if (d)
						descr += (descr ? "<br>" : "") + d;
				} else {
					// bulb image
					d = d.replace(/<img .+src=".+Bulbgraph.png".+(width="[^"]+").+(height="[^"]+")[^>]+>/g,
									"<img src=\"/manager/pic/bulb.png\" $1 $2>");
					// replace \n\t
					d = d.replace(/\n/g,"\\n").replace(/\t/g,"\\t");
					// 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 += d;
				}

				nE = nE.nextElementSibling;
			}
			// check variations
			var s,c;
			for (var v = 0; v < variations.length; v++) {
				s = variations[v].src;
				s = s.replace("&lt;","<");
				s = s.replace("&gt;",">");
				// replace variables (lowercase words), separated by space or start/end line
				c = s.replace(/(^|\s*|:)("?)([a-z0-9:_\.]+)("?)($|\n|\s*|:)/g, "$1$2\${0:$3}$4$5");
				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")) {
				if (title.indexOf("function") != 0)
					title = "function " + title;
				if (snippet.indexOf("function") != 0)
					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,'\\"');
				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}"
});