MediaWiki:QIvoter.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
window.QIVoter = {
 // configuration defaults
 thumbSize : 100,

 // working variables and constants
 b1 : null,
 b2 : null,
 file : null,
 imfileRE : /^\s*([Ii]mage:|[Ff]ile:|)([^\|]*)\s*\|/,
 newn : /\{\{\/[Nn]omination\|/,
 nomi : /\{\{\/([Nn]omination|[Pp]romotion|[Dd]ecline)\|/,
 disc : /\{\{\/([Pp]romotion|[Dd]ecline)\|/,
 tb : null,
 report : null,
 rcache : {},
 cookiename : 'qinomtext',
 storednom : null,
 iniTry : 0,

 getPos : null,
 getPosSane : function()
 {
  return QIVoter.tb.selectionStart;
 },
 getPosInsane : function() 
 { 
  var tb = QIVoter.tb;
  if( document.selection )
  { 
   tb.focus(); 
   var r = document.selection.createRange(); 
   if (r === null) return 0; 

   var re = tb.createTextRange(), rc = re.duplicate(); 
   re.moveToBookmark(r.getBookmark()); 
   rc.setEndPoint('EndToStart', re); 
   return rc.text.length; 
  }  
  return 0; 
 },
 analyzeCallback : function( file, data )
 {
  QIVoter.rcache[encodeURIComponent(file)] = data;
  QIVoter.analyze(data);
 },
 analyze : function( data )
 {
  var flaws = '', report = '';
  if( data !== null )
  {
   var megapixel = Math.round( ( 100 * data.width * data.height ) / (1000*1000) ) / 100;
   var megabyte = Math.round( ( 100 * data.size ) / (1024*1024) ) / 100;
   if( megapixel < 2.0 ) flaws += '<b>Below minimum size requirement!</b><br/>';

   report = 'Size: ' + data.width + '×' + data.height + 'px = ' + megapixel + 'MP at ' + megabyte + 'MB<br/>' + flaws;
  }
  QIVoter.report.innerHTML = report;
 },
 cursorHandler : function()
 {
  // analyze current line
  var tb = QIVoter.tb;
  var cp = QIVoter.getPos();
  var a1 = tb.value.lastIndexOf('\n',cp-1);
  var a2 = tb.value.indexOf('\n',cp);

  // new line?
  if( a1 !== QIVoter.b1 || a2 !== QIVoter.b2 )
  {
   // first hide the old examine box
   $('#qivexaminebox').hide('fast');

   QIVoter.b1 = a1;
   QIVoter.b2 = a2;
   QIVoter.line = tb.value.substr(a1,a2-a1);
   if(QIVoter.imfileRE.test(QIVoter.line))
   {
    QIVoter.file = encodeURIComponent( QIVoter.imfileRE.exec(QIVoter.line)[2] );
    // request a report on the image
    if( QIVoter.file in QIVoter.rcache ) 
     QIVoter.analyze( QIVoter.rcache[QIVoter.file] );
    else
     $.getScript( 'https://dschwenbot.toolforge.org/qivoter/analyze.php?f=' + QIVoter.file );

    // now update everything else
    $('#qivlink').attr( 'href', 'https://commons.wikimedia.org/wiki/File:' + QIVoter.file );
    $('#qivthumb').attr( 'src', 'https://commons.wikimedia.org/w/thumb.php?w=' + QIVoter.thumbSize + '&f=' + QIVoter.file );
    if(QIVoter.nomi.test(QIVoter.line))
    {
     if(QIVoter.newn.test(QIVoter.line))
     {
      $('#qivpromote').attr('disabled', false);
      $('#qivdecline').attr('disabled', false);
      $('#qivdiscuss').attr('disabled', true);
     }
     else
     {
      $('#qivpromote').attr('disabled', true);
      $('#qivdecline').attr('disabled', true);
      $('#qivdiscuss').attr('disabled', false);
     }
    }
    else
    {
     $('#qivpromote').attr('disabled', true);
     $('#qivdecline').attr('disabled', true);
     $('#qivdiscuss').attr('disabled', true);
    }
    $('#qivbox').show('fast');
   }
   else
    $('#qivbox').hide('fast');
  }
 },
 examine : function()
 {
  $('#qiviframe').attr('src','https://commons.wikimedia.org/w/index.php?title=Special%3AFilePath&file=' + QIVoter.file );
  $('#qivexaminebox').show('fast');
  return false;
 },
 tag : function( name, separator, caption, defaulttext )
 {
  var pnumRE = /\|[12]=\s*/g;
  var tendRE = /\|{0,1}\s*\}\}\s*$/;
  var tb = QIVoter.tb;
  var pre = tb.value.substr(0,QIVoter.b1);
  var post = tb.value.substr(QIVoter.b2);
  var boilerplate = prompt( caption, defaulttext );

  if( boilerplate === null ) return;
  boilerplate = separator + boilerplate;

  $('#qivexaminebox').hide('fast');
  $('#qivbox').hide('fast');

  // remove superfluous parameter numbers
  QIVoter.line = QIVoter.line.replace(pnumRE,'|');

  // tag
  if( QIVoter.nomi.test(QIVoter.line) && tendRE.test(QIVoter.line) )
    QIVoter.line = QIVoter.line.replace(tendRE, boilerplate + ' --~~'+'~~}}').replace(QIVoter.nomi,'{{/' +  name + '|');
  
  tb.value = pre + QIVoter.line + post;
  
  // fallback for CodeMirror users
  var cm = $(".CodeMirror") && $(".CodeMirror").prop("CodeMirror");
  if( cm ) cm.setValue( tb.value );
  
  QIVoter.b1 = null;
  QIVoter.tb.focus();
 },
 promote : function() { QIVoter.tag('Promotion','|','Promote reason','Good quality.'); return false; },
 decline : function() { QIVoter.tag('Decline','|','Decline reason','Insufficient quality.'); return false; },
 discuss : function() { QIVoter.tag('Discuss','<br/>','Discuss reason','I disagree '); return false; },
 activate : function()
 {
  QIVoter.report = $('#qivreport')[0];
  $('#qivactivate').hide('fast');
  $('#qivexamine').click(QIVoter.examine);
  $('#qivpromote').click(QIVoter.promote);
  $('#qivdecline').click(QIVoter.decline);
  $('#qivdiscuss').click(QIVoter.discuss);
  $('#wpTextbox1').keyup(QIVoter.cursorHandler).click(QIVoter.cursorHandler);
 },
 insertNom : function()
 {
  var galleryRE = /<[Gg]allery[^>]*>/;
  var nominations = '', i, sn = QIVoter.storednom;
  if (sn.length > 5) {
  	alert('Please nominate no more than five images per day.');
  }
  for( i=0; i < sn.length && i < 5; ++i ) {
    nominations += sn[i].file + '|{{/Nomination|' + sn[i].text + ' --~~'+'~~|}}\n';
  }
  if( galleryRE.test(QIVoter.tb.value) )
  {
   var galtag = galleryRE.exec(QIVoter.tb.value);
   QIVoter.tb.value = QIVoter.tb.value.replace( galleryRE, galtag + '\n' + nominations );
  }
  else
  {
   QIVoter.tb.value = '<gallery>\n' + nominations + '</gallery>';
  }
  
  // fallback for CodeMirror users
  var cm = $(".CodeMirror") && $(".CodeMirror").prop("CodeMirror");
  if( cm ) cm.setValue( QIVoter.tb.value );
  
  $('#qivnom').hide('fast');
  // empty stored nominations
  window.localStorage.removeItem('QINominator');
 },
 tryInit : function() {
  // get existing nomination data
  if( window.localStorage ) {
    QIVoter.storednom = JSON.parse( window.localStorage.getItem('QINominator') );
    if( QIVoter.storednom !== null ) {
        $('#qivnom').show().click(QIVoter.insertNom);
    } else {
        if( !window.QInominator ) {
          // no QInominator gadged found after 3 tries, show banner
          if( QIVoter.iniTry >= 3 ) {
            $('#qivnomad').show(200);
            $('#qinomaddismiss').click(function(){
                window.localStorage.setItem('QInomAdDismiss','yes');
                $('#qivnomad').hide();
            });
          } else {
            // let's retry in 1 second
            QIVoter.iniTry++;
            // have not dismissed banner, so keep trying!
            if( window.localStorage.getItem('QInomAdDismiss') === null ) {
                setTimeout(  QIVoter.tryInit, 1000 );
            }
            return;
          }
        }
    }
  }
 },
 install : function()
 {
  QIVoter.tb = $('#wpTextbox1')[0];
  if( typeof(QIVoter.tb.selectionStart) == 'number' )
   QIVoter.getPos = QIVoter.getPosSane;
  else
   QIVoter.getPos = QIVoter.getPosInsane;
  
  $('#wpTextbox1').before('<div style="display:none" id="qivbox"><a id="qivlink"><img id="qivthumb" style="float:left"/>'
   + '</a> <input id="qivexamine" type="button" value="Examine"> <input id="qivpromote"  type="button" value="Promote">'
   + ' <input id="qivdecline" type="button" value="Decline"> <input id="qivdiscuss" type="button" value="Discuss">'
   + '<div id="qivreport" style="padding-left: 1em; line-height: 1"></div><br style="clear:both"/></div>'
   + '<div id="qivactivate" style="line-height: 1; background-color: red; color: white;'
   + ' padding: 0.5em">Click here to activate QIVoter helper!</div>'
   + '<div id="qivnom" style="line-height: 1; background-color: #008800; color: white;'
   + ' display:none; padding: 0.5em">Click here to insert your stored nomination!</div>'
   + '<div id="qivnomad" style="line-height: 1; background-color: #ffff00; color: black;'
   + ' display:none; padding: 0.5em">Check out the <a target="newprefs" href="https://commons.wikimedia.org/wiki/Special:Preferences#mw-prefsection-gadgets">'
   + 'QInominator gadget</a> for easy QIC nominations! (<a id="qinomaddismiss" href="#">dismiss</a>)</div>'
   + '<div style="display:none;'
   + ' height: 400px" id="qivexaminebox"><iframe id="qiviframe" style="width: 100%; height: 400px; border: 0px">'
   + '</iframe><div>');

  QIVoter.tryInit();
  $('#qivactivate').click(QIVoter.activate);
 }
};

if( mw.config.get('wgTitle') == "Quality images candidates/candidate list" && mw.config.get('wgAction') == 'edit' ) 
 $(QIVoter.install);