User:Kbrown (WMF)/autoTranslationMarkup testing.js

From Meta, a Wikimedia project coordination wiki
This page contains changes which are not marked for translation.

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
mw.loader.using('mediawiki.util', function () {
	$(document).ready(function () {
		//create a button the user can click to indicate they want to run this script 
		//(ganked from https://www.mediawiki.org/wiki/ResourceLoader/Modules#addPortletLink)
		var transLink = mw.util.addPortletLink('p-personal', '#', 'EasyTranslate', 'pt-EasyTranslate');

        
         //what happens when they click it? this! 
         //(as long as you're in edit mode. If you run it while just viewing a page, nothing happens)
         $(transLink).click(function(){
         	$.ajax( { // Get this URL
   			url: '/api/rest_v1/page/html/' + mw.util.rawurlencode( mw.config.get( 'wgPageName' )), 
   			// Interpret the result as HTML (as opposed to XML or JSON or something)
   			dataType: 'html'
  			} )
  			.done( function( html ) { 
  				// Parse the result as HTML and put it into a variable called "doc"
	    		var doc = new DOMParser().parseFromString( html, 'text/html' ),
	      		// You can now use jQuery to find stuff using $( 'selector', doc )
	      		// (you have to specify doc because $('p') finds paragraphs on the current page rather than in the parsed text)
	      		$bodies = $('b, i, dd, p, li, dt, di, td, th, :header, caption, a', doc);
	      		//$links = $('a', doc);
	      		var fmtNumOpen = '\{\{formatnum:';
	      		var fmtNumClose = '\}\}';

	    		$texts = $bodies.contents().filter(function(){ 
	    			return this.nodeType === 3; //filters bodies for text nodes (i.e. displayable text, coded as "3") only
	    			//I have no idea what is magical about this combination of .contents().filter etc, though
	    		});
	    		
	    		$texts.each(function(){
	    			var temp = $(this).text();
	    			if(!temp.match(/(^[0-9,\.]+$)|(^\([0-9,\.]+\)$)/)){ //if node consists of only a number and punctuation, skip the next lines
	    					if($.trim($(this).text()).length>0){ //and if node is not empty
	    					$(this).wrap("<translate></translate>"); // ...then wrap the thing in translate tags
	    				}
	    			}
	    			else { //if node is only a number and punctuation...
	    				$(this).wrap( $('<span>') .attr( { typeof: 'mw:Transclusion', 'data-mw': JSON.stringify( { parts: [ { template: { target: { wt: 'formatnum:' + temp }, params: {} } } ] } )} ));
	    				//Do fancy json footwork to wrap the number in the formatnum template
	    			}
	    		});

	    		$.ajax( { //now to pop the edited wikitext back into the edit window
	      			url:'/api/rest_v1/transform/html/to/wikitext/Main_Page',
	      			method:'POST',
	      			dataType: 'text',
	      			data:{ html: doc.documentElement.outerHTML}
	      		})
	      		.done( function( wikitext ) {
	      			// wikitext is the result of the conversion
	      			$( '#wpTextbox1' ).val( wikitext );
	     		} ); //end the second .done ajax function
  		} ); //end the first .done ajax function
  		
	//borrow "confirm save" code wholesale from https://en.wikipedia.org/wiki/User:JSutherland_%28WMF%29/confirmedit.js
	//This script is imperfect and you should always preview what it does before saving
	//so now you're forced to either tick the box saying you checked, or go through the preview button
	$('.editCheckboxes').append('&nbsp;<input name="confirmEdit" type="checkbox" id="confirmEdit" />&#160;<label for="confirmEdit" id="mw-editpage-confirmedit" title="Tick to confirm edit"><strong>Tick this box to confirm that you have previewed your work and want to save these changes.</strong></span></label>');
        $('#wpSave').prop('disabled', true);
        var confirmCheckbox = $('#confirmEdit');
        // Code on clicking the checkbox...
        confirmCheckbox.click(function (e) {
			if (confirmCheckbox.prop('checked') === true) {
            	doConfirmEdit(); // Actually enable the save button
			} else {
				confirmCheckbox.prop('checked', false); // Uncheck the checkbox
            	$('#wpSave').prop('disabled', true); // Disable the save button again
			}
		function doConfirmEdit () { // Putting this in a function for mediawiki
			confirmCheckbox.prop('checked', true);
            $('#wpSave').prop('disabled', false);
		}
    	});	
	});	//end click TransLink
});//end document.ready
}); //end mw.loader