Մասնակից:Xelgen/sandbox.js

Վիքիդարանից՝ ազատ գրադարանից

Ծանուցում. Հիշելուց հետո կատարված փոփոխությունները տեսնելու համար մաքրեք ձեր զննարկիչի հիշապահեստը. Mozilla / Firefox / Safari՝ Ctrl+Shift+R (Cmd+Shift+R Mac OS X-ում) Konqueror՝ F5 Opera՝ Tools→Preferences ընտրացանկից։ Internet Explorer՝ Ctrl+F5

//Set of tools to simplify proofreading of SAE articles.

String.prototype.IsWideArmText = function(tolerance)
{
	text=this;
	if (typeof tolerance === 'undefined')
	{
		tolerance=1; //no tolerance if it's not set
	}
	numberofUs=0;
	numberofSpaces=text.trim().split(" ").length-1;
	if (text.search('ու')!=-1) {numberofUs=text.trim().match(/ու/g).length;} //number of ու digraphs
	numberofLetters=text.trim().length-numberofSpaces-numberofUs;
	if (numberofSpaces>=(numberofLetters-1)*tolerance) //*tolerance <1 for some% tolerance, in case spaces miss between some of the letters (~25% of letters)
	{
		return true;
	}
	else
	{
		return false;
	}	
}

var SAEInitialize = function ()
{

	if (parseInt($('input[name=wpQuality]:checked').val())<4) //checking if page is not Profread and not Confirmed
	{
		document.getElementById("wpTextbox1").value=document.getElementById("wpTextbox1").value.replace(/(.)\n{1,2}(?:«)?([Ա-Ֆ]{5,})/g, "$1\n\n$2"); //Add one more line before article names for distigushing in text. 
		document.getElementById("wpTextbox1").value=document.getElementById("wpTextbox1").value.replace(/[¬֊-—-]/g, "–"); //there are way to many different symbols used for dash, changing everything to n dash    
	}
	AddSAEToolsButtons();

}
//We're adding button here
var AddSAEToolsButtons = function() {

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
		'section': 'main',
		'groups': {
			'SAE': { 'label': 'ՀՍՀ' }
		}
} );


$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
		'section': 'main',
		'group': 'SAE',
		'tools': {
			'Wide': {
				label: 'Լայն տեքստ',
				type: 'button',
				icon: 'http://upload.wikimedia.org/wikipedia/commons/3/3b/Toolbaricon_regular_a_to_b.png',
				action: {
							type: 'callback',
								execute: function(context){
									WideText();
						} 
				}
			}
		}
	} );

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
		'section': 'main',
		'group': 'SAE',
		'tools': {
			'addpageimage': {
				label: 'Ավելացնել էջի տեսածրված պատկերը',
				type: 'button',
				icon: '//upload.wikimedia.org/wikipedia/commons/5/54/Vector_toolbar_insert_image_button_grayscale.png',
				action: {
					type: 'encapsulate',
					options: {
						pre: "[[Պատկեր:" + mw.config.get("wgTitle").replace("/","|page=") + "|right|thumb|",
						post: "]]",
						ownline:true
					}
				}
			}
		}
	} );

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
        'section': 'main',
        'group': 'SAE',
        'tools': {
                'smile': {
                        label: 'Բաժին ընտրված բառից (Alt + երկկտոց բառի վրա, կամ Alt + բառերի ընտրություն, եթե հավելյալ պահել Ctrl բաժնի ամեն բառը կսկվի մեծատառ)', // or use labelMsg for a localized label, see above
                        type: 'button',
                        icon: '//upload.wikimedia.org/wikipedia/commons/thumb/0/02/Oxygen480-actions-irc-join-channel.svg/22px-Oxygen480-actions-irc-join-channel.svg.png',
                        action: {
							type: 'callback',
								execute: function(context){
									addSAESection();
							} 
						}
                }
        }
} );

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
        'section': 'main',
        'group': 'SAE',
        'tools': {
                'RmHyphnes': {
                        label: 'Հեռացնել տողադարձերը', // or use labelMsg for a localized label, see above
                        type: 'button',
                        icon: '//upload.wikimedia.org/wikipedia/commons/thumb/b/b9/Crystal_Clear_action_edit_remove.png/22px-Crystal_Clear_action_edit_remove.png',
                        action: {
							type: 'callback',
								execute: function(context){
									RemoveHyphens();
							} 
						}
                }
        }
} );

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
        'section': 'main',
        'group': 'SAE',
        'tools': {
                'RmHyphnes': {
                        label: 'Հեռացնել նոր տողերը', // or use labelMsg for a localized label, see above
                        type: 'button',
                        icon: '//upload.wikimedia.org/wikipedia/commons/a/a8/Toolbaricon_definition_list.png',
                        action: {
							type: 'callback',
								execute: function(context){
									RemoveNewLines();
							} 
						}
                }
        }
} );

$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
        'section': 'main',
        'group': 'SAE',
        'tools': {
                'RmHyphnes': {
                        label: 'Լատինական կետադրական նշանները փոխել հայերեն նշաններով', // or use labelMsg for a localized label, see above
                        type: 'button',
                        icon: '//upload.wikimedia.org/wikipedia/commons/b/b9/Toolbaricon_ellipsis.png',
                        action: {
							type: 'callback',
								execute: function(context){
									FixArmPunctuation();
							} 
						}
                }
        }
} );
	
$(".group.group-insert").css("border-right","1px solid #DDDDDD"); //spend an hour to bring separator line, after insert group
	
};

jQuery( function () {   
$('#wpTextbox1')	
	.mouseup(function(e) {		
		var textarea = document.getElementById("wpTextbox1");		
		var start = textarea.selectionStart;
		var end = textarea.selectionEnd;
		var sel = textarea.value.substring(start, end);
		//I don't check for Edit action, as event is binded to Edit textarea. This will currently work only for properly titled SAE pages, you can take out second condition, or add ORs if needed for other books in future
		if (start!=end && e.altKey && mw.config.get( 'wgPageName' ).substr(0,66) == 'Էջ:Հայկական_Սովետական_Հանրագիտարան_(Soviet_Armenian_Encyclopedia)_')
		{			
			if (sel.length<=2 || sel.search(/[^\n]/)==-1) //if it's only newlines then exit without asking, nothing to do
			{
				return false;
			}			
			//now we make trick to see if it's wide text or all lowcase, then let's put template լայն and exit instead of adding section
			
			if (sel.length>3 && (sel.IsWideArmText(0.7) || sel.search(/[Ա-Ֆ]/)==-1)) //*0.7 for 30% tolerance, in case spaces miss between some of the letters (~30% of letters)
			{
				WideText();
				return false;
			}
			
				
				addSAESection(e.ctrlKey);			
			}	
    });
}
);

var RemoveHyphens = function() {
// [Ա-և] բոլոր հայերեն տառերը
// [Ա-ԷԹ-Ֆա-էթ-և] բոոլոր տառեը բացի ը և Ը
// [ա-էթ-և] բոլոր փոքրատառը բացի ը-ից

	var text = document.getElementById("wpTextbox1").value;
	origHyphenCount=text.split("–\n").length;
	
	text=text.replace(/([0-9])[–]\n([0-9])/g, "$1–$2"); //removing new lines between numbers, leaving dash intact
	text=text.replace(/ե–\nվ/g, "եTMP\nվ"); //Regexp for not touching hidden Y is already too complex, to mantain, so instead of making it skip e-/nv we're making a dirty trick here	
    
	text=text.replace(/([\s«\(])(([Ա-և](?!ը)){2,6})[–]\n([ա-էթ-և]{1,5}[ա-և]|ը$)([\s,:։․՝»\)])/g, "$1$2$4$5"); //Remove (we're very careful taking max 6 letter long words, not to brake dashed phrases)
    text=text.replace(/([\s«\(])(([Ա-և](?!ը)){2,})[–]\n([ա-էթ-և]{1,2}[ա-և]|ը$)([\s,:։․՝»\)])/g, "$1$2$4$5"); //Remove (if part after hyphen is max 3 letters, then it can't be compoissues with Ev unsolved & we're very careful taking max 6 letter long words, not to brake dashed phrases)
    text=text.replace(/([\s«\(])([Ա-և][ա-էթ-և]|[Ա-և]{1}ու|ու[ա-և]{1})[–]\n([ա-էթ-և]{1,}[ա-և])([\s,:։՝»\)])/g, "$1$2$3$4"); //if first part has just 2 letters, it's not a dashed word, ու is basically one letter, so 2 special caes for that
	
	text=text.replace(/([Ա-և](?!ը))[–]\n([ա-և]{0,3}թյուն(?:ը|ն|ներ|ների|ներից|ները|ներն|ներում)?|[ա-և]{0,3}թյամբ|[ա-և]{0,3}թյան(?:ը|ն|ներ|ների|ները|ներն|ներում)?|[ա-և]{0,2}յինը?|[ա-և]ում|յան|[ա-և]{0,2}կանը?|ներ[ա-և]{0,2})([\s,:։․՝»])/g, "$1$2$3"); //after being so careful, not to brake dashes where they should be, we need to take most common suffixes, and try to do some more work
    
	text=text.replace(/եTMP\nվ/g, "ե–\nվ"); //Regexp for not touching hidden Y is already too complex, to mantain, so instead of making it skip e-/nv we're removing dirty trick here. Sorry for this.
		
	document.getElementById("wpTextbox1").value=text;
	removedHyphenCount=origHyphenCount-text.split("–\n").length;
	mw.notify("Հեռացվեց " + removedHyphenCount + " տողադարձ " + origHyphenCount + "-ից");
	insertSummary("-տողադարձեր");
};


// We have to wait for WP QUality to load, otherwise we can't know in which status page is (Not Profread, Profread, etc..)
 
/* Check if view is in edit mode and that the required modules are available. Then, customize the toolbar */
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 && mw.config.get( 'wgPageName' ).substr(0,66) == 'Էջ:Հայկական_Սովետական_Հանրագիտարան_(Soviet_Armenian_Encyclopedia)_') {
        mw.loader.using( 'user.options', function () {
                if ( mw.user.options.get('usebetatoolbar') ) {
                        mw.loader.using( 'ext.wikiEditor', function () {
                                $(window).load( SAEInitialize );
                        } );
                }
        } );
}

var FixArmPunctuation = function()
{
	var text = document.getElementById("wpTextbox1").value;	
	
	text=text.replace(/([Ա-և]):/g, "$1։"); // Verjaket issue. Brakes namespaces, we need to make something here
    text=text.replace(/:\s([Ա-և])/g, "։ $1"); //Again for verjaket
	
	document.getElementById("wpTextbox1").value=text;
	insertSummary("+հայ․ կետ․ ");
}

var RemoveNewLines = function ()
{
	var text = document.getElementById("wpTextbox1").value;	
	origNewLineCount=text.split("\n").length;
	text=text.replace(/([ա-և])\n([ա-և])/g, "$1 $2"); //remove new lines
	//text=text.replace(/(։)\n{1}([Ա-Ֆ]{1})/g, "$1\n\n$2"); //add double new lines where we see paragraphs UPD Commented out, as it gives to much false positives
	
	document.getElementById("wpTextbox1").value=text;
	removedNewLineCount=origNewLineCount-text.split("\n").length;
	mw.notify("Հեռացվեց " + removedNewLineCount + " նոր տող " + origNewLineCount + "-ից");
	insertSummary("-նոր տողեր");
}

function WideText()
{
	var textarea = document.getElementById("wpTextbox1");		
	var start = textarea.selectionStart;
	var end = textarea.selectionEnd;
	var sel = textarea.value.substring(start, end);
	var len = sel.length;
	var spaceBeforeWide="";
	var spaceAfterWide="";
		
	if (sel.substring(0,1)==" ")
	{
		spaceBeforeWide=" ";		
	}
	
	if (sel.substring(len-1, len)==" ")
	{
		spaceAfterWide=" ";		
	}		
	
	
	if (sel.IsWideArmText(0.75))
	{
		sel = sel.replace(/\s/g, "");
	}
	
	curtext=textarea.value;
	newtext=curtext.substring(0,start) + spaceBeforeWide + "{{լայն|" + sel.trim() + "}}" + spaceAfterWide + curtext.substring(end);
	document.getElementById("wpTextbox1").value=newtext;	
}

function toProperCase(s)
{
  return s.toLowerCase().replace(/^(.)|[\s—–](.)/g, 
          function($1) { return $1.toUpperCase(); });
};

function addSAESection(ProperCaseWanted) 
{				
		var textarea = document.getElementById("wpTextbox1");		
		var start = textarea.selectionStart;
		var end = textarea.selectionEnd;
		var sel = textarea.value.substring(start, end);
		var TitleOnly=true;
		var selPartAfterUppercase='';
		var selPartAfterUppercaseIndex=0;
		

		if (sel.length=0 || sel.search(/[^\n]/)==-1) //if it's only newlines or empty then exit without asking, nothing to do
		{
			return false;
		}		
		
		/*If selection looks like user mistake, we need additional confirmation
		It's fishy if 		
		1) previous symbols is not new line, while at the same time it's not in very begining of text, and new line is not first character of text
		2) containt anything but Armenian letters, spaces, or following symbols ,«»()
		3) Doesn't start with at least two Armenian capital letters (I know I know, there are 39 articles about armenian letters, but in rest 99.9% it's user mistake)
		*/
		if (!(start==0 || textarea.value.charAt(start-1)=="\n" || textarea.value.charAt(start)=="\n")|| sel.search(/[^Ա-և\s–«»,\(\)]/)!=-1 || sel.search(/[«\nԱ-Ֆ]{2,}/)!=0) 
		{
			res = confirm ("Դուք նշել եք «" + sel + "» որպես հոդվածանուն։\nՍա փոքր ինչ կասկածելի է թվում։ Համոզվա՞ծ եք որ ուզում եք շարունակել և ստեղծել նման բաժնի անուն։");
			console.log("Message given");
			if (res==false) return false;
		}

		if (sel.search(/[\/\:#<>\[\]|{}_]/)!=-1)
		{
			alert("Բաժնի անունը չի կարող պարունակել, հետևյալ նշաններից որևէ մեկը՝ / ։ # < > [ ] | { } _ ");
			return false;
		}
		
		// If user moves cursor up, he may also select new line, without realising it causing new line before ''', we're fixing this silently
		NewLinePosInSel=sel.search(/\n/);
		
		if (NewLinePosInSel!=-1 && NewLinePosInSel<sel.search(/[Ա-և]/))
		{
			start=start+sel.search(/[Ա-և]/);
			textarea.selectionStart=start;
			sel=sel.substring(NewLinePosInSel);
		}
		
		sel = sel.trim(); //Trim whitespaces, we don't modify start and end here as we use InsertTags which produces valid results
		
		sel = sel.replace(/\n/g,""); //there should be no new lines in section name. We don't do it in previous block, not to remove new lines in beginig, if there were some
		
		if (sel!=sel.toLocaleUpperCase()) //Trying to understand if selection contains not only Article name but other words e.g. Name, Middle name in proper case
		{
			TitleOnly=false;			
		}		
		
		if (!TitleOnly)
		{
			selPartAfterUppercase='';			
			selPartAfterUppercaseIndex=sel.search(/[\s,»][Ա-և][^Ա-Ֆ]/); //Trying to find where UPPERCASES end
			console.log("selPartAfterUppercaseIndex=" + selPartAfterUppercaseIndex);
			if (selPartAfterUppercaseIndex>0) //it shouldn't be -1 not found, or 0 very start of string, but just to be safe
			{
				selPartAfterUppercase=sel.substring(selPartAfterUppercaseIndex);
				sel=sel.substring(0,selPartAfterUppercaseIndex);
				end=start+selPartAfterUppercaseIndex //If selection containt not only uppercase words, then make bold only part till proper/lower case word					
				textarea.selectionEnd=end;				
			}			
		}
		
		sel = sel.replace(/ԵՎ(?!Ր(Ո|Ա))/, "և"); //This should solve Ev issue, with few problems	
		
		//if user accidentaly selects title with comma, we silently remove comma from selection
		if (textarea.value.charAt(end-1)==',') 
		{
			end=end-1;
			textarea.selectionEnd=end;
			sel=sel.substring(0,sel.length-1);
		}		
		
		if (ProperCaseWanted)
		{
			sectname = toProperCase(sel) + selPartAfterUppercase;			
		}
		else
		{
			sectname = sel.substring(0,1) + sel.substr(1).toLocaleLowerCase() + selPartAfterUppercase;
		}				
		
		if (textarea.value.search("## " + sectname + " ##")!=-1 || textarea.value.search("##"+ sectname +"##")!=-1)
		{
			res = window.confirm ("Ուշադրություն:\n«" + sectname + "» անվամբ բաժին արդե՛ն առկա է էջում։\nԽնդրում ենք փոփոխե՛լ այս բաժնի անունը, դարձնելով այն ունիկալ։\nՊարզապես բաժնի անունից հետո ավելացրեք հստակեցնող բառ, օր․ անձի դեպքում անուն ազգանունը, երևույթի դեպքում ոլորտը ( (հոգեբանու)), տեղանվան դեպքում երկիրը, կամ տեսակը (գետ/լիճ/գյուղ Հայաստանում)։");
			
			if (res==false) return false;
		}
		
		if (textarea.value.substring(start-1, start)=="«" && textarea.value.substring(end, end+1)=="»") //If word is in quotes, let's make quotes bold aswell
		{
			textarea.selectionStart=textarea.selectionStart-1;
			textarea.selectionEnd=textarea.selectionEnd+1;
		}		
		
		//console.log("Start=" + start + " End=" + end);
		//console.log("TxStart=" + textarea.selectionStart + " TxEnd=" + textarea.selectionEnd);
		
		insertTags("## " + sectname + " ##\r\n'''","'''",'');	

		
		
		insertSummary("+բաժիններ");
};

function insertSummary(text) {
 var sum = $('#wpSummary'), vv = sum.val()
 if (vv.indexOf(text) != -1) return
 if (/[^,; \/]$/.test(vv)) vv += ','
 if (/[^ ]$/.test(vv)) vv += ' '
 sum.val(vv + text)
}