User:M~enwiki/reword2.js

/* debug - v0.3 - 6/8/2009 http://benalman.com/projects/javascript-debug-console-log/. Copyright (c) 2009 "Cowboy" Ben Alman. Licensed under the MIT license http://benalman.com/about/license/ With lots of help from Paul Irish! http://paulirish.com/ */ var debug=(function{var c=this,e=Array.prototype.slice,b=c.console,i={},f,g,j=9,d=["error","warn","info","debug","log"],m="assert clear count dir dirxml group groupEnd profile profileEnd time timeEnd trace".split(" "),k=m.length,a=[];while(--k>=0){(function(n){i[n]=function{j!==0&&b&&b[n]&&b[n].apply(b,arguments)}})(m[k])}k=d.length;while(--k>=0){(function(n,o){i[o]=function{var q=e.call(arguments),p=[o].concat(q);a.push(p);h(p);if(!b||!l(n)){return}b.firebug?b[o].apply(c,q):b[o]?b[o](q):b.log(q)}})(k,d[k])}function h(n){if(f&&(g||!b||!b.log)){f.apply(c,n)}}i.setLevel=function(n){j=typeof n==="number"?n:9};function l(n){return j>0?j>n:d.length+j<=n}i.setCallback=function{var o=e.call(arguments),n=a.length,p=n;f=o.shift||null;g=typeof o[0]==="boolean"?o.shift:false;p-=typeof o[0]==="number"?o.shift:n;while(p<n){h(a[p++])}};return i}); function logg(message) { debug.log(message); //if (console && console.log) console.log(message); }

(function(getmarkupf, submitnewf, element) {	var $=jQuery;	//if (window.location.href.indexOf("index.php") != -1) return;	var getmarkup = getmarkupf; // for getting the markup	var submitnew = submitnewf; // for submitting the changes	var markupText;  // We get markup	var markupToken;  //  and any extra tokens/timestamps.	var selectedText; // As the selection changes we search for the selection within markup,	var mIndex  = -1; // recording the location index	var mLength = -1; //  and the length	var $div;         // the button div	var busy=false;   // whether the edit dialog is open, to prevent selection changes	logg("Reword is being loaded...");	$(window).load(function { $("body").mousedown(updateSelection); $("body").mousemove(updateSelection); $("body").mouseup(releaseSelection); $("body").keyup(updateSelection); logg("Reword is loading the markup text..."); getmarkup(function(markup, token) {			markupText=markup;			markupToken=token;			logg("Markup was fetched.");		}); });	function updateSelection(e) {		if (busy) return;		var text = getSelectedText;		text = (text.length<5) ? null : text;		if (text == selectedText) return;		selectedText = text;		selectionChanged(e);	}	function releaseSelection(e){		if (busy) return;		updateSelection(e)		if ($div) $div.css({top:e.pageY-$div.height/2, left:e.pageX-10});	};	function enableDiv   {$div.stop.fadeIn.fadeTo(300,1);}	function disableDiv   {$div.hide;$div.css("color","bbb");}	function notfoundDiv  {$div.css("color","#bbb");};	function duplicateDiv {$div.css("color","orange");};	function notreadyDiv  {$div.css("color","blue");};	function foundDiv     {$div.css("color","black");};	function selectionChanged(e) {		logg("Selection was changed.");		mIndex=-1;		mLength=-1;		if (!$div) $div = createRewordButton;		if ( ! selectedText ) {			disableDiv;			return;		};		if ( ! markupText ) {			notreadyDiv;			return;		};		enableDiv;		/* the index/length within the fetched markup text. */		var i=indexOfUnique(selectedText, markupText);		var l=selectedText.length;		//logg(i+": " +selectedText.replace(/\n/g,"\\n"));		if (i==-1) { //not found. Try a search for unique ends			notfoundDiv;			if (selectedText.length>6) {				var leftn=3;				var rightn=3;				var lefti;				var righti;				// OPTIMIZATION-- if it's slow during selection-dragging, this is probably what needs fixing				// could just not calculate until there's no change to selection for 500~ms, using timeout				// a binary search on leftn/rightn would be better too, if it were skewed towards lower numbers				while (true) {					var left = selectedText.substr(0,leftn);					lefti = indexOfUnique(left, markupText);					//logg("# "+left +" "+lefti);					if (lefti!=-2) break; // otherwise still dupe, keep going leftn+=2; //TODO a binary search here? if (leftn >= selectedText.length-rightn) { lefti=-1; break; }				}				if (lefti>=0) { while (true) { var right = selectedText.substr(selectedText.length-rightn,rightn); righti = indexOfUnique(right, markupText); //logg("# "+right +" "+righti); if (righti!=-2) break; // otherwise still dupe, keep going rightn+=2; if (rightn >= selectedText.length-leftn) { righti=-1; break; }					}				}				if (righti==-2) duplicateDiv;; if (lefti>0&&righti>0) { i=lefti; l=righti+rightn-i; foundDiv; }			}		} else if (i==-2){ duplicateDiv; } else { foundDiv; }		mIndex=i; mLength=l; //logg(markupText.substr(i,l).replace(/\n/g,"\\n"));logg(""); e=fixEvent(e); $div.css({top:e.pageY+20, left:e.pageX+5}); }	function tryToEdit(text) { if (mIndex<0 || mLength<0) return; busy = true; var mt = markupText.substr(mIndex,mLength); var textbox = $(" ").css({width:"98%",height:"10em"}).val(mt); var commentbox = $(" ").css({width:"50%"}); var editform = $(" ").append(textbox).append("Comment: ").append(commentbox); var textbox = $(" ").css({width:"98%",height:"10em"}).val(mt); var commentbox = $(" ").css({width:"50%"}); var editform = $(" ").append(textbox).append("Comment: ").append(commentbox); textbox.keyup(function {			var n = textbox.val;			var o = mt;			var s = 0;			while (o.charAt(s) && o.charAt(s) == n.charAt(s)) s++;			var e = 0;			while (o.charAt(o.length-e-1) && o.charAt(o.length-e-1) == n.charAt(n.length-e-1) && (o.length-e)>s && (n.length-e)>s) e++;			var l1 = o.length-(e+s);			var l2 = n.length-(e+s);			var diffchars = l1+l2;			if (diffchars > 0) { // there were changes				// extend the boundaries a bit				s-=5;				if (s<0)s=0;				l1+=10; // 5 from start, and then another 5.				if (s+l1>o.length) l1=o.length-s;				l2+=10;				if (s+l2>n.length) l2=n.length-s;				var od = o.substr(s,l1); //old diff				var nd = n.substr(s,l2); //new difference				od = od.replace(/\n/g,"\\n");				nd = nd.replace(/\n/g,"\\n");				while (od.length+nd.length > 160) {					if (od.length>60) od=od.substring(0,od.length-5)+"…";					if (nd.length>60) nd=nd.substring(0,nd.length-5)+"…";				} var edsum = "'"+od+"' → '"+nd+"' "; commentbox.val(edsum); } else { commentbox.val(""); //TODO, this clears it... need separate boxes? // disable submit? }		});

$(editform).dialog({			bgiframe: true,			//autoOpen: false,			modal: true,			width:"50%",			closeOnEscape: false,			title: "Reword",			position: 'center',			buttons: {				//Cancel: function {$(this).dialog('close');},				Submit: function {					var newText = markupText.substring(0,mIndex)+textbox.val+markupText.substring(mIndex+mLength);					var comment = commentbox.val;					var outcome = submitnew(newText, markupToken, comment); //this should block?					$(this).dialog('close');				}			},			close: function{editform.remove; busy=false;},		}); }	function createRewordButton { var x = ' '+ ' '+//eee '  Reword   '+//bbb '  '; var $div = $(x).appendTo("body"); //" blah " $div.css({position:"absolute",font:"9pt tahoma,Sans-serif",display:"none"});//,background:"white", border:"1px solid gray"});		$div.click(function { tryToEdit; });		return $div;	}	// ============ UTILS =============	function indexOfUnique(text, within) {		var first = within.indexOf(text);		if (first==-1) return -1; //none found		var second = within.indexOf(text, first+1);		return (second!=-1)?-2:first; //both found?	}	function getSelectedText{		if(window.getSelection){return window.getSelection.toString; 		} else if(document.getSelection){return document.getSelection; 		} else if(document.selection){return document.selection.createRange.text; 		} 	}	function fixEvent(e) {		var posx = 0;		var posy = 0;		if (!e) var e = window.event;		if (e.pageX || e.pageY) {			posx = e.pageX;			posy = e.pageY;		} else if (e.clientX || e.clientY) 	{			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;			posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;		}		e.pageX=posx;		e.pageY=posy;		return e;	}

})(updateData /*function(callbackfunction) { setTimeout(function blah {		callbackfunction("The quick brown fox\n\n\n* jumps over\nthe lazy dog brown fox",{tokenx:"t"});	},100); }*/, submitData /*function(newText, token) {// submitnew logg("===========SUBMITTED============="); logg(newText); logg(token.tokenx); }*/);

function updateData(callbackfunction) { var $=jQuery; $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+wgPageName+"&rvprop=timestamp|user|comment|content&format=json",		function(data){			$.each(data.query.pages, function(i,item){ logg(item); var text = item.revisions[0]["*"]; var timestamp = item.revisions[0]["timestamp"]; callbackfunction(text, {timestamp:timestamp}); });		}	); } function submitData(newText, token, comment) { var $=jQuery; $.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=info|revisions&intoken=edit&titles="+wgPageName+"&format=json", function(data){		$.each(data.query.pages, function(i,item){ logg(item); var edsum = comment+" (using Reword)"; var qeToken = item.edittoken; var qeTimestamp = token.timestamp;//item.starttimestamp; $.post("/w/api.php", {				action: "edit", title: wgPageName, notminor:"", summary:edsum, 				text:newText, basetimestamp:qeTimestamp, token:qeToken, format:"json" 			}, function(data) {				alert("(Please reload now.)\nRESULT:\n"+data);				window.location.reload(true); //updateData;				history.go(0);				window.location.href=window.location.href;			}); });	}); }