User:Kaldari/wikilove.js: Difference between revisions

From Wikipedia, the free encyclopedia
Content deleted Content added
adding comment making code a bit more concise
protect against duplicate WikiLoves
(13 intermediate revisions by the same user not shown)
Line 1: Line 1:
//<nowiki>
//<nowiki>
if (( wgCanonicalNamespace == 'User_talk' && wgAction == 'view' && skin == 'vector' )) {
if (( wgCanonicalNamespace == 'User_talk' && wgAction == 'view' && skin == 'vector' && !$.wikiLove )) {
// Script depends on jQuery dialog widget
// Script depends on jQuery dialog widget
mw.loader.using( 'jquery.ui.dialog', function() {
mw.loader.using( 'jquery.ui.dialog', function() {
Line 65: Line 65:


launchDialog: function( interface, emailOption ) {
launchDialog: function( interface, emailOption ) {
// If user is emailable, add email checkbox to forms that request it
if ( emailOption && typeof wikiLove.emailable !== 'undefined' && wikiLove.emailable ) {
if ( emailOption && typeof wikiLove.emailable !== 'undefined' && wikiLove.emailable ) {
if ( typeof interface.data('emailCheckboxAppended') == 'undefined' ) {
if ( typeof interface.data('emailCheckboxAppended') == 'undefined' ) {
Line 71: Line 72:
}
}
}
}
// Open the dialog box
interface.dialog('open');
interface.dialog('open');
// Retrieve the edit token so it will be available when the form is submitted
wikiLove.getEditToken();
wikiLove.getEditToken();
},
},
Line 115: Line 118:
'The Special Barnstar',
'The Special Barnstar',
'The Citation Barnstar',
'The Citation Barnstar',
'The Teamwork Barnstar'
'The Teamwork Barnstar',
'The Barnstar of Diplomacy',
'The Civility Barnstar',
'The Real Life Barnstar'
];
];
// Define barnstar interface
// Define barnstar interface
$barnstars = $('<div id="barnstarForm" style="position:relative;"></div>')
$wlBarnstars = $('<div id="barnstarForm" style="position:relative;"></div>')
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Select barnstar: ' ).append( $('<select id="barnstarSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Select barnstar: ' ).append( $('<select id="barnstarSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a message (without a signature):<br/>' ).append( $('<textarea name="message" id="barnstarMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a message (without a signature):<br/>' ).append( $('<textarea name="message" id="barnstarMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
Line 136: Line 142:
// Perform edit to page
// Perform edit to page
wikiLove.displayProgress( 'barnstarForm', 'Adding barnstar to page...' );
wikiLove.displayProgress( 'barnstarForm', 'Adding barnstar to page...' );
var template = '{{subst:'+$('#barnstarSelect').val()+'|'+$('#barnstarMessage').val() +' ~~~~}}';
var message = $('#barnstarMessage').val();
if ( message.indexOf( '~~~' ) == -1 ) {
message += ' ~~~~';
}
var template = '{{subst:'+$('#barnstarSelect').val()+'|'+ message +'}}';
wikiLove.editPage( 'barnstarForm', 'Barnstar', template );
wikiLove.editPage( 'barnstarForm', 'Barnstar', template );
} else {
} else {
Line 146: Line 156:
// Populate barnstar select list
// Populate barnstar select list
$.each( $barnstarList, function(index, value) { $('#barnstarSelect').append( $('<option></option>').val(value).html(value) ); });
$.each( $barnstarList, function(index, value) { $('#barnstarSelect').append( $('<option></option>').val(value).html(value) ); });

// List of all available foods
var $foodList = [
'brownie',
'cookie',
'cupcake',
'pie',
'plate of sausages'
];

// Define food interface
$wlFood = $('<div id="foodForm" style="position:relative;"></div>')
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Select food: ' ).append( $('<select id="foodSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a personalized message (optional):<br/>' ).append( $('<textarea name="message" id="foodMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
.dialog({
width: 500,
autoOpen: false,
title: 'Give some food',
modal: true,
buttons: { "Give food": function() {
$(this).dialog({buttons:{}});
if ( typeof wikiLove.editToken !== 'undefined' ) {
$selectedFood = $('#foodSelect').val();
// Perform edit to page
wikiLove.displayProgress( 'foodForm', 'Adding '+$selectedFood+' to page...' );
if ( $('#foodMessage').val() != '' ) {
var template = '{{subst:WikiLove-'+$selectedFood+'|'+$('#foodMessage').val()+'}}';
} else {
var template = '{{subst:WikiLove-'+$selectedFood+'}}';
}
wikiLove.editPage( 'foodForm', 'A '+$selectedFood+' for you!', template );
} else {
wikiLove.displayError( 'foodForm', 'Could not retrieve edit token.' );
}
}}
});

// Populate food select list
$.each( $foodList, function(index, value) { $('#foodSelect').append( $('<option></option>').val(value).html(value) ); });


// Define kitten interface
// Define kitten interface
$kittens = $('<div id="kittenForm" style="position:relative;"></div>')
$wlKittens = $('<div id="kittenForm" style="position:relative;"></div>')
.html( '<input type="hidden" id="kittenSelected" name="kittenSelected" value="Kitten-stare.jpg"/>' )
.html( '<input type="hidden" id="kittenSelected" name="kittenSelected" value="Kitten-stare.jpg"/>' )
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Select which kitten you want to give:' ) )
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Select which kitten you want to give:' ) )
Line 169: Line 218:
wikiLove.displayProgress( 'kittenForm', 'Adding kitten to page...' );
wikiLove.displayProgress( 'kittenForm', 'Adding kitten to page...' );
var template = '{{subst:Kitten|image='+$('#kittenSelected').val()+'}}';
var template = '{{subst:Kitten|image='+$('#kittenSelected').val()+'}}';
wikiLove.editPage( 'kittenForm', 'Kitten', template );
wikiLove.editPage( 'kittenForm', 'A kitten for you!', template );
} else {
} else {
wikiLove.displayError( 'kittenForm', 'Could not retrieve edit token.' );
wikiLove.displayError( 'kittenForm', 'Could not retrieve edit token.' );
Line 180: Line 229:
// Insert new tab into page
// Insert new tab into page
var menuBarnstar = '<li id="wl-barnstar"><span><a onclick="wikiLove.launchDialog( $barnstars, true ); return false;" href="#">Barnstar</a></span></li>';
var menuBarnstar = '<li id="wl-barnstar"><span><a onclick="wikiLove.launchDialog( $wlBarnstars, true ); return false;" href="#">Barnstar</a></span></li>';
var menuKitten = '<li id="wl-cookie"><span><a onclick="wikiLove.launchDialog( $kittens, false ); return false;" href="#">Kitten</a></span></li>';
var menuFood = '<li id="wl-food"><span><a onclick="wikiLove.launchDialog( $wlFood, false ); return false;" href="#">Food</a></span></li>';
var wikiLoveMenu = '<div class="vectorMenu" id="p-wikilove"><h5><span>WikiLove</span><a href="#" style="padding:0 0.4em;width:auto;"><span style="display:inline-block;height:2.5em;width:16px;margin-right:14px;background-position:0 60%;background-image:url(http://upload.wikimedia.org/wikipedia/commons/b/bd/Silk_heart_icon.png);background-repeat:no-repeat;">&nbsp;</span></a></h5><div class="menu"><ul>'+menuBarnstar+menuKitten+'</ul></div></div>';
var menuKitten = '<li id="wl-kitten"><span><a onclick="wikiLove.launchDialog( $wlKittens, false ); return false;" href="#">Kitten</a></span></li>';
var wikiLoveMenu = '<div class="vectorMenu" id="p-wikilove"><h5><span>WikiLove</span><a href="#" style="padding:0 0.4em;width:auto;"><span style="display:inline-block;height:2.5em;width:16px;margin-right:14px;background-position:0 60%;background-image:url(http://upload.wikimedia.org/wikipedia/commons/d/d9/Heart.png);background-repeat:no-repeat;">&nbsp;</span></a></h5><div class="menu"><ul>'+menuBarnstar+menuFood+menuKitten+'</ul></div></div>';
$('#p-cactions').after(wikiLoveMenu);
$('#p-cactions').after(wikiLoveMenu);



Revision as of 07:15, 29 June 2011

//<nowiki>
if (( wgCanonicalNamespace == 'User_talk' && wgAction == 'view' && skin == 'vector' && !$.wikiLove )) {
  // Script depends on jQuery dialog widget
  mw.loader.using( 'jquery.ui.dialog', function() {
    // Construct object (to prevent namespace conflicts)
    wikiLove = {

      displayProgress: function( form, message ) {
        $('#'+form+' div').hide(); // remove everything else from the dialog box
        $('#'+form).append ( $('<div style="text-align:center;margin:3em 0;"></div>').html( message+'<br/><img src="http://upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />' ) );
      },
      
      displayError: function( form, error ) {
        $('#'+form+' div').hide(); // remove everything else from the dialog box
        $('#'+form).append ( $('<div style="color:#990000;margin-top:0.4em;"></div>').html( 'Error: '+error ) );
      },
      
      getEditToken: function() {
        $.ajax({
          url: wgScriptPath + '/api.php?',
          data: 'action=query&prop=info&intoken=edit&titles=Main%20Page&indexpageids&format=json',
          dataType: 'json',
          success: function( data ) {
            if ( data.query.pages && data.query.pageids ) {
              var pageid = data.query.pageids[0];
              wikiLove.editToken = data.query.pages[pageid].edittoken;
            }
          }
        });
      },
      
      getEmailable: function() {
        // Test to see if the 'E-mail this user' link exists
        wikiLove.emailable = $('#t-emailuser').length ? true : false;
      },
      
      editPage: function( form, summary, template ) {
        $.ajax({
          url: wgScriptPath + '/api.php?',
          data: 'action=edit&title='+encodeURIComponent(wgPageName)+'&section=new&summary='+encodeURIComponent(summary)+'&text='+encodeURIComponent(template)+'&format=json&token='+encodeURIComponent(wikiLove.editToken),
          dataType: 'json',
          type: 'POST',
          success: function( data ) {
            if ( data.edit.result == "Success" ) {
              window.location.reload();
            } else {
              wikiLove.displayError( form, 'Unknown result from API.' );
            }
          },
          error: function( xhr ) {
            wikiLove.displayError( form, 'Edit failed.' );
            //console.debug( xhr.responseText );
          }
        });
      },
      
      sendEmail: function( form, subject, text ) {
        $.ajax({
          url: wgScriptPath + '/api.php?',
          data: 'action=emailuser&target='+encodeURIComponent(wgTitle)+'&subject='+encodeURIComponent(subject)+'&text='+encodeURIComponent(text)+'&format=json&token='+encodeURIComponent(wikiLove.editToken),
          dataType: 'json',
          type: 'POST'
        });
      },

      launchDialog: function( interface, emailOption ) {
        // If user is emailable, add email checkbox to forms that request it
        if ( emailOption && typeof wikiLove.emailable !== 'undefined' && wikiLove.emailable ) {
          if ( typeof interface.data('emailCheckboxAppended') == 'undefined' ) {
            interface.append( $('<div style="margin-top:0.4em;"></div>').html('<input type="checkbox" name="notify"/> Notify user by email') );
            interface.data('emailCheckboxAppended', true);
          }
        }
        // Open the dialog box
        interface.dialog('open');
        // Retrieve the edit token so it will be available when the form is submitted
        wikiLove.getEditToken();
      },
      
      initialize: function() {

        // Function to make a list of images selectable
        $.fn.selectItem = function() {
          return this.each(function() {
            var containerId = this.id;
            var customId = 0;
            $('#'+containerId+' img').css('border', '8px solid transparent');
            $('#'+containerId+' img').each(function() {
              if (this.id == '') {
                this.id = 'select_img_' + customId;
                customId++;
              }
              $('#'+this.id).click(function() {
                  $('#'+containerId+'Selected').val(this.title);
                  $('#'+containerId+' img').css('border', '8px solid transparent');
                  $('#'+this.id).css('border', '8px solid #AED0EA');
              })
            });
          });
        };
      
        // List of all available barnstars
        var $barnstarList = [
          'The Original Barnstar',
          'The Editor\'s Barnstar',
          'The Working Man\'s Barnstar',
          'The Minor Barnstar',
          'The Random Acts of Kindness Barnstar',
          'The Barnstar of Diligence',
          'The Surreal Barnstar',
          'The Tireless Contributor Barnstar',
          'The Photographer\'s Barnstar',
          'The Defender of the Wiki Barnstar',
          'The Anti-Vandalism Barnstar',
          'The Barnstar of Good Humor',
          'The Graphic Designer\'s Barnstar',
          'The Copyeditor\'s Barnstar',
          'The Special Barnstar',
          'The Citation Barnstar',
          'The Teamwork Barnstar',
          'The Barnstar of Diplomacy',
          'The Civility Barnstar',
          'The Real Life Barnstar'
        ];
        
        // Define barnstar interface
        $wlBarnstars = $('<div id="barnstarForm" style="position:relative;"></div>')
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Select barnstar: ' ).append( $('<select id="barnstarSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a message (without a signature):<br/>' ).append( $('<textarea name="message" id="barnstarMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
          .dialog({
            width: 500,
            autoOpen: false,
            title: 'Award a barnstar',
            modal: true,
            buttons: { "Award barnstar": function() { 
              $(this).dialog({buttons:{}});
              if ( typeof wikiLove.editToken !== 'undefined' ) {
                if ( $('#barnstarForm input[name="notify"]').attr('checked') ) {
                  // Send email
                  wikiLove.sendEmail( 'barnstarForm', 'You\'ve been awarded a barnstar!', 'Hello '+wgTitle+'!\n\nI just awarded you '+$('#barnstarSelect').val()+' on your English Wikipedia talk page.' );
                }
                // Perform edit to page
                wikiLove.displayProgress( 'barnstarForm', 'Adding barnstar to page...' );
                var message = $('#barnstarMessage').val();
                if ( message.indexOf( '~~~' ) == -1 ) {
                  message += ' ~~~~';
                }
                var template = '{{subst:'+$('#barnstarSelect').val()+'|'+ message +'}}';
                wikiLove.editPage( 'barnstarForm', 'Barnstar', template );
              } else {
                wikiLove.displayError( 'barnstarForm', 'Could not retrieve edit token.' );
              }
            }}
          });
    
        // Populate barnstar select list
        $.each( $barnstarList, function(index, value) { $('#barnstarSelect').append( $('<option></option>').val(value).html(value) ); });

        // List of all available foods
        var $foodList = [
          'brownie',
          'cookie',
          'cupcake',
          'pie',
          'plate of sausages'
        ];

        // Define food interface
        $wlFood = $('<div id="foodForm" style="position:relative;"></div>')
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Select food: ' ).append( $('<select id="foodSelect" style="padding:1px;vertical-align:baseline;"></select>') ) )
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Enter a personalized message (optional):<br/>' ).append( $('<textarea name="message" id="foodMessage" style="width:99%" rows="4" cols="60"></textarea>') ) )
          .dialog({
            width: 500,
            autoOpen: false,
            title: 'Give some food',
            modal: true,
            buttons: { "Give food": function() { 
              $(this).dialog({buttons:{}});
              if ( typeof wikiLove.editToken !== 'undefined' ) {
                $selectedFood = $('#foodSelect').val();
                // Perform edit to page
                wikiLove.displayProgress( 'foodForm', 'Adding '+$selectedFood+' to page...' );
                if ( $('#foodMessage').val() != '' ) {
                  var template = '{{subst:WikiLove-'+$selectedFood+'|'+$('#foodMessage').val()+'}}';
                } else {
                  var template = '{{subst:WikiLove-'+$selectedFood+'}}';
                }
                wikiLove.editPage( 'foodForm', 'A '+$selectedFood+' for you!', template );
              } else {
                wikiLove.displayError( 'foodForm', 'Could not retrieve edit token.' );
              }
            }}
          });

        // Populate food select list
        $.each( $foodList, function(index, value) { $('#foodSelect').append( $('<option></option>').val(value).html(value) ); });

        // Define kitten interface
        $wlKittens = $('<div id="kittenForm" style="position:relative;"></div>')
          .html( '<input type="hidden" id="kittenSelected" name="kittenSelected" value="Kitten-stare.jpg"/>' )
          .append( $('<div style="margin-top:0.4em;"></div>').html( 'Select which kitten you want to give:' ) )
          .append( $('<div style="margin-top:1em;text-align:center;" id="kitten"></div>')
            .html( '<img width="80" height="60" src="http://upload.wikimedia.org/wikipedia/commons/thumb/c/cc/Kitten-stare.jpg/80px-Kitten-stare.jpg" title="Kitten-stare.jpg" alt="Staring kitten"/><img width="80" height="60" src="http://upload.wikimedia.org/wikipedia/commons/thumb/9/9f/Cucciolo_gatto_Bibo.jpg/80px-Cucciolo_gatto_Bibo.jpg" title="Cucciolo_gatto_Bibo.jpg" alt="Kitten sticking tongue out"/><img width="80" height="60" src="http://upload.wikimedia.org/wikipedia/commons/thumb/8/87/Kitten_%2806%29_by_Ron.jpg/80px-Kitten_%2806%29_by_Ron.jpg" title="Kitten_(06)_by_Ron.jpg" alt="Attack kitten"/>' )
          )
          .dialog({
            width: 400,
            autoOpen: false,
            title: 'Give a kitten',
            modal: true,
            buttons: { "Give kitten": function() {
              $(this).dialog({buttons:{}});
              if ( typeof wikiLove.editToken !== 'undefined' ) {
                if ( $('#kittenForm input[name="notify"]').attr('checked') ) {
                  // Send email
                  wikiLove.sendEmail( 'kittenForm', 'You\'ve been given a kitten!', 'Hello '+wgTitle+'!\n\nI just left a kitten for you on your English Wikipedia talk page.' );
                }
                // Perform edit to page
                wikiLove.displayProgress( 'kittenForm', 'Adding kitten to page...' );
                var template = '{{subst:Kitten|image='+$('#kittenSelected').val()+'}}';
                wikiLove.editPage( 'kittenForm', 'A kitten for you!', template );
              } else {
                wikiLove.displayError( 'kittenForm', 'Could not retrieve edit token.' );
              }
            }}
          });
    
        // Apply special image selection interface for choosing kittens
        $('#kitten').selectItem();
    
        // Insert new tab into page
        var menuBarnstar = '<li id="wl-barnstar"><span><a onclick="wikiLove.launchDialog( $wlBarnstars, true ); return false;" href="#">Barnstar</a></span></li>';
        var menuFood = '<li id="wl-food"><span><a onclick="wikiLove.launchDialog( $wlFood, false ); return false;" href="#">Food</a></span></li>';
        var menuKitten = '<li id="wl-kitten"><span><a onclick="wikiLove.launchDialog( $wlKittens, false ); return false;" href="#">Kitten</a></span></li>';
        var wikiLoveMenu = '<div class="vectorMenu" id="p-wikilove"><h5><span>WikiLove</span><a href="#" style="padding:0 0.4em;width:auto;"><span style="display:inline-block;height:2.5em;width:16px;margin-right:14px;background-position:0 60%;background-image:url(http://upload.wikimedia.org/wikipedia/commons/d/d9/Heart.png);background-repeat:no-repeat;">&nbsp;</span></a></h5><div class="menu"><ul>'+menuBarnstar+menuFood+menuKitten+'</ul></div></div>';
        $('#p-cactions').after(wikiLoveMenu);

      } // close initialize function

    } // close wikiLove object
    wikiLove.initialize();
    wikiLove.getEmailable();
  }) // close mw.loader
} // close if
//</nowiki>