Jump to content

MediaWiki:Common.js/Wikinews:Make lead

From Wikinews, the free news source you can write!

/*

This javascript deals with stuff specific to [[User:Bawolff/sandbox/makeLead]]. Functions
specific to lead generation are at User:Bawolff/sanbox/leadGenerator.js
functions relating to api access are at User:Bawolff/mwapilib2.js
*/
mw.loader.load( '/w/index.php?title=' + 'User:Bawolff/sanbox/leadGenerator.js' + '&action=raw&ctype=text/javascript' );

var showPreview = function (html) {
 //We assume that the mediawiki api is not malicious...
 document.getElementById('LeadPreview').innerHTML = html;
}
var showLead = function (leadText, leadTitle) {
 var lsp = document.getElementById('leadSourcePrev');
 if (!lsp) {
  var src = document.createElement('textarea');
  src.id = 'leadSourcePrev';
  src.style.width = '48%';
  src.rows = 40;
  src.appendChild(document.createTextNode(leadText));
  document.getElementById('LeadBox').appendChild(src);
  document.getElementById('LeadPreview').style.visibility = 'visible';
 }
 else {
  lsp.value = leadText;
 }
 leadTitle = leadTitle.replace(/(\\|')/g, "\\$1").replace(/"/g, """).replace(/>/g, '>'); //prevent xss
 var leadNumb = document.getElementById('leadNum').selectedIndex + 1;
 document.getElementById('LeadControls').innerHTML = '<button onclick="syncToServer(' + leadNumb + ', \'' + leadTitle + '\')">Save as lead ' + leadNumb + '</button> <button onclick="regeneratePreview()">Refresh preview</button>';

 api(leadText).replace(/<noinclude>[\d\D]*?<\/noinclude>/, '').parse('Main Page').lift(showPreview).exec();
 //this will strip out anything after a noinculde (this is kind of dirty)

}
var regeneratePreview = function() {
var wikiText = document.getElementById('leadSourcePrev').value;
api(wikiText).replace(/<noinclude>[\d\D]*?<\/noinclude>/, '').parse('Main Page').lift(showPreview).exec();
}
var syncToServer = function(leadNum, page) {
 if (leadNum === undefined || !confirm('Are you sure you want to save this to [[template:Lead article ' + leadNum + ']]?')) {
  return false;
 }
 api(document.getElementById('leadSourcePrev').value).setDefaultSummary('Updating lead ' + leadNum + ' to [[' + page + ']] with [[Wikinews:Make Lead|MakeLead JS]]').savePage('Template:Lead article ' + leadNum).sightByRev().inject('Lead successfully updated').alert().lift(function() {location = mw.config.get('wgServer') + mw.config.get('wgArticlePath').replace('$1', mw.config.get('wgPageName')) + '?js-good-update=' + encodeURIComponent(page);}).exec();
}
var startLeadMaker = function () {
 if (mw.config.get('wgAction') !== 'view' && mw.config.get('wgAction') !== 'purge') {
  return false;
 }
 if (!window.api || !window.Bawolff || !window.Bawolff.leadGen) {
  alert('Javascript did not load properly, as a result this page may or may not work. If it doesn\'t work, try doing a soft refresh.');
 }
 if (!mw.config.get('wgUserGroups') || mw.config.get('wgUserGroups').join(' ').indexOf("autoconfirmed") === -1) {
  jsMsg("<div style='border:solid red medium;font-weight: bold; padding:0.5em'>Please note: You cannot edit which articles are lead articles, since only people logged in with a registered account that has been registered for over four days can edit the lead templates.</div>");
 }
 var lastUpdate = location.search.match(/[?&]js-good-update=([^&]*).*/);
 if (lastUpdate) {
  //this is all properly escaped since its in a text node.
  window.setTimeout(function () {jsMsg(document.createTextNode('Lead successfully updated to article "' + decodeURIComponent(lastUpdate[1]) + '".'));}, 400); //to get arround other things using jsMSg
 }
 var setupContainer = document.getElementById('lSetup');
 setupContainer.innerHTML += "<form id='leadForm' action='javascript:doMakeLead();void 0;'><label for='pageNameField'>Page:</label> <input type='text' id='pageNameField' size='50'><br/><label for='leadNum'>Lead number:</label> <select id='leadNum' onchange='doMakeLead(true);'><option selected value='1'>1 (Top)</option><option>2 (Middle-left)</option><option>3 (Middle-right)</option> <option>4 (Bottom-left)</option> <option>5 (Bottom-right)</option> </select> <label for='sumMethod'>Summary&nbsp;method:</label> <select id='sumMethod'><option selected value='0'>1st sentence</option><option value='1'>1st 2 sentences</option><option value='2'>1st paragraph</option><option>1st 250 letters</option> <option>1st 500 letters</option> </select> &nbsp;<input type='submit' value='Make lead'></form>";

 var dpl = document.getElementById('lDPL').getElementsByTagName('a');
 for (var i = 0; i < dpl.length; i++) {
  linkVal = encodeURIComponent(dpl[i].firstChild.data.replace(/(\\|")/g, "\\$1"));
  // %22 = "
  dpl[i].href = 'javascript:document.getElementById(%22pageNameField%22).value=%22' + linkVal + '%22;doMakeLead();void%200';
 }

// autosuggest
mw.loader.using( 'jquery.ui', function () { $( "#pageNameField" ).autocomplete({
	minLength: 2,
	source: function( request, response ) {
		$.getJSON(
			mw.config.get('wgServer') + mw.config.get('wgScriptPath') + '/api.php?format=json&action=opensearch&search=' +
			mw.util.rawurlencode( request.term ) + '&callback=?',
			function( obj ) {
				if ( obj && obj.length > 1 ) {
					response( obj[1] );
				} else {
					response( [] );
				}
			}
		);
	}
})});

 
 var handleAfterLeadInfoTableLoads = function (table) {
  document.getElementById('lMetaTable').innerHTML = table;
  var pageName = location.search.replace(/.*?[?&]use-page=([^&]*).*/, '$1');

  if (Bawolff.leadGen.oldestLead) {
   var oldLeadNum = parseInt(Bawolff.leadGen.oldestLead.charAt(Bawolff.leadGen.oldestLead.length - 1));
   document.getElementById('leadNum').selectedIndex = oldLeadNum - 1;
   if (oldLeadNum === 1) {
    document.getElementById('sumMethod').selectedIndex = 1; //use 2 sentences for longer lead.
   }
  }
  if (pageName !== location.search) { //if it matched
   document.getElementById('pageNameField').value = decodeURIComponent(pageName.replace(/\+/g, ' '));
   location.href = '#leadForm'; //since already filled out.
   doMakeLead();
  }
  
 }
 Bawolff.leadGen.makeLeadTable(handleAfterLeadInfoTableLoads);

}
function doMakeLead (fromLeadNumChange) {
var pageName = document.getElementById('pageNameField').value;
var leadNum = document.getElementById('leadNum').selectedIndex + 1;
 if (fromLeadNumChange && leadNum === 1) {
    document.getElementById('sumMethod').selectedIndex = 1; //use 2 sentences for longer lead.
 }
var sumMethod = document.getElementById('sumMethod').selectedIndex;
if (!pageName) return; //stop error if not initialized.
Bawolff.leadGen(pageName, leadNum, showLead, sumMethod);
}

waitAWhileThenLoadLead.times = 0;
function waitAWhileThenLoadLead () {
//since we're already from an onload event, and mw.loader.load is async. wait a while
 if ((!window.api || !window.Bawolff || !window.Bawolff.leadGen) && waitAWhileThenLoadLead.times < 10) {
  waitAWhileThenLoadLead.times++;
  setTimeout(waitAWhileThenLoadLead, 200);
 } else {
 startLeadMaker();
 }
}
$(waitAWhileThenLoadLead);
/*

*/