MediaWiki:Common.js

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.
// ----------------------------------------------------------------
// Code to add Auto-Translate-Button on translation-page - START
$("<div style='float:right;margin:6px'><button id='startAutoTranslate' onclick='onAutoTranslateClick();'>Auto-Translate</button>"
+"<span id='autoTranslateRunning' style='display:none' >Translation running, please wait...</span></div>")
.insertAfter(".ext-translate-language-selector");

function onAutoTranslateClick(){
   var config = mw.config.get("wgForTrainingToolsAutoTranslateUrl");
   if(!config) {
      alert("AutoTranslateBot is currently not available. Please ask an administrator for help.");
      return;  //no config available -> cancel
   }
   var pageName = getPageNameFromTranslationPage();

   showTranslationRunning(true);
   console.log("Autotranslate page='"+pageName+"'");
   var postArgs = { page: pageName};
   mw.notify($("<p>AutoTranslateBot is automatically translating the whole worksheet. This may take a while. We hope this will give you a good start. Thank you for your patience and all your work!</p>"), 
      { title: 'Processing...', type: 'info'}
   );
   $.post(config, postArgs)
      .done( function( data ) {
         mw.notify($("<p>"+data+"<br/>Click <b><a href='"+window.location+"'>here to reload this page</a></b>.</p>"), { title: 'Success!', type: 'info', autoHide: false});
         showTranslationRunning(false);
      })
	  .fail( function() {
         alert('Unkown error while trying to run AutoTranslateBot! Please ask an administrator for help.');
         showTranslationRunning(false);
      });
}

function showTranslationRunning(isRunning){
   if(isRunning){
     $("#startAutoTranslate").hide();
     $("#autoTranslateRunning").show();
   }
   else{
     $("#startAutoTranslate").show();
     $("#autoTranslateRunning").hide();
   }
}

function getPageNameFromTranslationPage(){
   var language = $(".ext-translate-target-language").attr("lang");
   var urlGroupParam = new URLSearchParams(window.location.search).get("group");
   var rawPage = decodeURIComponent(urlGroupParam).replaceAll(" ", "_").slice("page-".length);
   return rawPage +"/"+language;
}
/* Code to add Auto-Translate-Button on translation-page - END */


// ----------------------------------------------------------------
/* Code to add CorrectBot-Button on last translations-unit - START */
//Install Button if cancel-button shows up
function waitForElement(selector, onPresent){
   console.log("element '"+selector+"' missing, waiting for it...");
   var element = $(selector);
   if(element.length > 0){
      console.log("elemen '"+selector+"' detected");
      onPresent(element);
   }
   else{
     setTimeout(function(){ waitForElement(selector, onPresent);},1000); //active wait, because we want to support jquery-selectors
  }
}

waitForElement(".tux-editor-cancel-button:visible",function(cancelButton){
   var button = $("<button class='mw-ui-button mw-ui-quiet' onclick='onRunCorrectBotClick(this);'>Run Correct-Bot</button>");
   $(".tux-editor-cancel-button:visible").parent().append(button);
});

function onRunCorrectBotClick(button){
   var pageName = getPageNameFromTranslationPage();
   console.log("Autotranslate page='"+pageName+"'");
   var postArgs = { page: pageName };
		mw.notify($("<p>CorrectBot is working hard to make the translation even better. " +
					"He's fast and should be finished within seconds, then you'll get another notification. " +
					"Thank you for your patience and all your work!</p>"), { title: 'Processing...', type: 'info'});
		$.post(mw.config.get('wgForTrainingToolsCorrectBotUrl'), postArgs)
			.done( function( data ) {
				var nothing_saved = data.indexOf('NOTHING SAVED.');
				if (nothing_saved > -1) {
					// CorrectBot didn't save anything. In the next line is the reason, let's get it
					var reason = data.substring(nothing_saved + 14).split(/\n/, 3)[1]
					mw.notify($('<p>' + reason + '<br/>' +
								'You may want to look at the <a href="/CorrectBot:' + pageName +
								'">previous CorrectBot report</a></p>'),
								{ title: 'Nothing saved!', type: 'info', autoHide: false});
				} else {
					// .* doesn't match newlines, so we use the workaround [\s\S]*
					var matches = data.match(/(\d+) correction[\s\S]*?(\d+) suggestion[\s\S]*?(\d+) warning/);
					if (matches != null) {
						mw.notify($('<p>CorrectBot did ' + matches[1] + ' corrections and had '
												         + matches[2] + ' suggestions and '
														 + matches[3] + ' warnings. ' +
									'Please check the <a href="/CorrectBot:' + pageName +
									'">CorrectBot report</a> for details.</p>'),
									{ title: 'Success!', type: 'info', autoHide: false});
					} else {
						mw.notify($('<p>CorrectBot failed. Please contact an administrator. Log:</p><p>' + data + '</p>'),
									{ title: 'Error!', type: 'info', autoHide: false});
					}
				}
			})
			.fail( function() {
				alert('Unkown error while trying to run CorrectBot! Please ask an administrator for help.');
			});
}
/* Code to add CorrectBot-Button on last translations-unit - END */


// ----------------------------------------------------------------
/* Code to add Apply/Edit/Discard-Buttons under Suggestions of the CorrectBot-Page - START */
var suggestionButtonsCss = "cursor:pointer;border: 1px solid currentColor;border-radius:3px;padding:2px;";
var suggestionButtonsHtml = '<tr><td/><td/><td/><td>'
        +'<span onclick="applyChange(this);" style="'+suggestionButtonsCss+'color:green">✓ Apply</span>&nbsp;'
        +'<span onclick="editChange(this);" style="'+suggestionButtonsCss+'color:black">🖉 Edit</span> &nbsp;'
        +'<span onclick="discardChange(this)" style="'+suggestionButtonsCss+'color:red">🗙 Discard</span>'
        +'</td></tr>';
var suggestionTables = [];

// Find all suggestion-tables
// As the suggestion-headline is the only indicator. Therefore we have to start from there and find only the tables between
// the Suggestion-Headline and the next one (usually "Corrections"). Note that it is <h2><span id="#Suggestions"/></h2>
var suggestionsIndex = $("#Suggestions").parent().index(); //Index of Suggestions-Headline-elements in their parents
$("#Suggestions").parent().siblings().each(function(index){
   if(index <= suggestionsIndex){ return; } // Not past suggestions-headline yet -> skip
   
   if(this.matches("table.diff")){
      suggestionTables.push(this); //Relevant table for Suggestions found
   } 
   if(this.matches("h2")){
      return false; //Next headline detected. Cancel loop
   }
});

// Add buttons beneath
suggestionTables.forEach(function(table){
    var tbody= $(table).children("tbody")[0];
    if(!tbody) return;
    $(table).append(suggestionButtonsHtml);
});

// Implement buttons-functions
function discardChange(span){
   var jTable = $(span).parent().closest('table'); //search table relative to given span
   var jHeader = jTable.prev();
   jTable.hide();
   jHeader.hide();
}

function applyChange(span){
   var jTable = $(span).parent().closest('table'); //search table relative to given span
   var jHeader = jTable.prev();
   var title = jHeader.children("span.mw-headline").attr("id"); //Current links do NOT encode the title, so no encoding here also
   var text = jTable.find('.diff-addedline div').text(); //to displayed, escaped string to remove all diff-elements
   var csrfToken = mw.user.tokens.get('csrfToken');

   $.post("/mediawiki/api.php", { action:"edit", format:"json", title:title, text:text, token:csrfToken },
      function(response){
         var isSuccess = response["edit"] && response["edit"]["result"] === "Success";
         if(isSuccess){
            discardChange(span);
         }
         else{
            var error = response.error ? (response.error.code+" - "+response.error.info) : "(unknown error)";
            alert("Could not apply change. Wikimedia-Error: "+error);
         }
      })
      .fail(function(jqXHR, textStatus, errorThrown){
         alert("Could not apply change. Network-Error: status="+textStatus+" errorThrown="+errorThrown);
      });
}

function editChange(span){
   var jTable = $(span).parent().closest('table'); //search table relative to given span
   var jHeader = jTable.prev();
   var editLink = jHeader.find("a");
   window.open(editLink.attr("href"));
}
/* Code to add Apply/Edit/Discard-Buttons under Suggestions of the CorrectBot-Page - END */


/* Any JavaScript here will be loaded for all users on every page load. */
mw.loader.load('mediawiki.diff.styles');