User:Kaldari/assessmentHelper.js

// This script adds a new "Assess" item to the More menu on article talk pages,

// which allows you to easily add new WikiProject Assessments to an article.

//

// Make sure we are on a talk page and in view or edit mode. If we are in edit

// mode, make sure we are not editing a section.

if ( mw.config.get( 'wgNamespaceNumber' ) === 1

&& ( mw.config.get( 'wgAction' ) === 'view' || ( mw.config.get( 'wgAction' ) === 'edit' && !$( 'input[name=wpSection]' ).val() ) )

) {

// Script depends on jQuery UI dialog and jQuery cookie modules

mw.loader.using( ['jquery.ui', 'mediawiki.cookie'], function() {

// Construct object (to prevent namespace conflicts)

wikiAssess = {

pageName: mw.config.get( 'wgPageName' ),

displayProgress: function( message ) {

$( '#assessment-form div' ).hide(); // remove everything else from the dialog box

$( '#assessment-form' ).append ( $('

').html( message+'
' ) );

},

displayError: function( error ) {

$( '#assessment-form div' ).hide(); // remove everything else from the dialog box

$( '#assessment-form' ).append ( $('

').html( 'Error: '+error ) );

},

addAssessment: function() {

var oldContent,

newContent,

selectedImportance,

project = 'WikiProject ' + $( '#projectSelect' ).val(),

classRank = $( '#classSelect' ).val(),

importance = '',

template;

wikiAssess.displayProgress( 'Adding assessment to article...' );

selectedImportance = $( "input[type='radio'][name='importance']:checked" );

if ( selectedImportance.length > 0 ) {

importance = selectedImportance.val();

}

if ( project !== 'WikiProject ' ) {

mw.cookie.set( 'assessmentHelper', $('#projectSelect').val(), { expires: 30 } );

template = '{{' + project + '|class=' + classRank + '|importance=' + importance + '}}';

} else {

wikiAssess.displayError( 'Invalid WikiProject selection.' );

return;

}

if ( mw.config.get( 'wgAction' ) === 'view' ) {

$.ajax({

url: mw.util.wikiScript( 'api' ),

data: {

action: 'query',

prop: 'revisions',

rvprop: 'content',

titles: wikiAssess.pageName,

formatversion: 2,

format: 'json'

},

dataType: 'json',

type: 'GET',

success: function( data ) {

if ( data.query !== undefined

&& data.query.pages[0] !== undefined

&& data.query.pages[0].revisions[0] !== undefined

&& typeof data.query.pages[0].revisions[0].content === 'string'

) {

oldContent = data.query.pages[0].revisions[0].content;

// Make sure there isn't already an assessment for this WikiProject.

// Note that this isn't foolproof due to template aliases.

if ( oldContent.search( '{{' + project ) !== -1 ) {

wikiAssess.displayError( 'Article already assessed for that project.' );

return;

}

// Insert the WikiProject template into the content

newContent = wikiAssess.insertTemplate( template, oldContent );

// Check for accidental content deletion

if ( newContent.length <= oldContent.length ) {

wikiAssess.displayError( 'Unknown error during template insertion.' );

return;

}

// Make the actual edit to the talk page

wikiAssess.editTalkPage( 'Adding template for ' + project + ' (via AssessmentHelper)', newContent );

} else {

wikiAssess.displayError( 'Failed to retrieve page content.' );

}

},

error: function( xhr ) {

wikiAssess.displayError( 'Failed to retrieve page content.' );

}

});

} else if ( mw.config.get( 'wgAction' ) === 'edit' ) {

oldContent = $( '#wpTextbox1' ).val();

// Make sure there isn't already an assessment for this WikiProject

if ( oldContent.search( '{{' + project ) !== -1 ) {

wikiAssess.displayError( 'Article already assessed for that project.' );

return;

}

// Insert the WikiProject template into the content

newContent = wikiAssess.insertTemplate( template, oldContent );

// Check for accidental content deletion

if ( newContent.length <= oldContent.length ) {

wikiAssess.displayError( 'Unknown error during template insertion.' );

return;

}

// Replace the edit box contents with the new content

$( '#wpTextbox1' ).val( newContent );

// Close the dialog

$assessInterface.dialog( 'close' );

}

},

insertTemplate: function( template, oldContent ) {

var newContent,

earliestPosition,

testPosition1 = oldContent.search( /{{WikiProject(?!Banner)/ ),

testPosition2 = oldContent.search( /{{WP(?!BS*\|)/ );

if ( testPosition1 === -1 && testPosition2 === -1 ) {

// No existing assessments

if ( oldContent.search( /^{{/ ) === 0 ) {

newContent = template + "\n" + oldContent;

} else {

newContent = template + "\n\n" + oldContent;

}

} else {

// Talk page already includes assessments

if ( testPosition1 > -1 ) {

if ( testPosition2 > -1 ) {

earliestPosition = Math.min( testPosition1, testPosition2 );

} else {

earliestPosition = testPosition1;

}

} else {

earliestPosition = testPosition2;

}

newContent = oldContent.substr( 0, earliestPosition ) +

template + "\n" +

oldContent.substr( earliestPosition );

}

return newContent;

},

editTalkPage: function( summary, newContent ) {

$.ajax({

url: mw.util.wikiScript( 'api' ),

data: {

action: 'edit',

title: wikiAssess.pageName,

summary: summary,

text: newContent,

format: 'json',

token: mw.user.tokens.get( 'csrfToken' ),

},

dataType: 'json',

type: 'POST',

success: function( data ) {

if ( data.edit !== undefined && data.edit.result == "Success" ) {

window.location.reload();

} else {

wikiAssess.displayError( 'Unknown result from API during edit attempt.' );

}

},

error: function( xhr ) {

wikiAssess.displayError( 'Edit failed.' );

//console.debug( xhr.responseText );

}

});

},

launchDialog: function() {

// Restore dialog to original state

$assessInterface.find( '.assess-progress, .assess-error' ).remove();

$assessInterface.find( 'div' ).show();

// Open the dialog box

$assessInterface.dialog( 'open' );

},

initialize: function() {

var classList = [

'',

'Stub',

'Start',

'C',

'B',

'GA',

'A',

'FA',

'List',

'FL',

'Disambig',

'NA'

];

// Define assessment interface

$assessInterface = $('

')

.append( $('

').html( 'WikiProject: ' )

.append( $('') )

)

.append( $('

').html( 'Class: ' )

.append( $('') )

)

.append( $('

').html( 'Importance: ' )

.append( $('') ).append( ' Low ' )

.append( $('') ).append( ' Mid ' )

.append( $('') ).append( ' High ' )

.append( $('') ).append( ' Top ' )

)

.dialog({

width: 500,

autoOpen: false,

title: 'Assess this article',

modal: true,

buttons: { "Add assessment": wikiAssess.addAssessment }

});

// Get list of WikiProjects and populate select list

wikiProjectList = [ '' ]; // empty initial option

$.ajax( {

url: mw.util.wikiScript( 'api' ),

data: {

action: 'query',

list: 'projects',

format: 'json'

}

} )

.done( function( data ) {

if ( data.query.projects !== undefined ) {

wikiProjectList = wikiProjectList.concat( data.query.projects );

// Sort the list of WikiProjects (case-insensitive)

wikiProjectList.sort( function ( a, b ) {

return a.toLowerCase().localeCompare( b.toLowerCase() );

} );

// Populate WikiProject select list

$.each( wikiProjectList, function( index, value ) {

if ( mw.cookie.get( 'assessmentHelper' ) === value ) {

$('#projectSelect').append( $('').val(value).html(value).attr('selected', 'selected') );

} else {

$('#projectSelect').append( $('').val(value).html(value) );

}

});

}

} );

// Populate class select list

$.each( classList, function(index, value) { $('#classSelect').append( $('').val(value).html(value) ); });

// Insert 'Assess' link into page interface

$( document ).ready( function() {

$( '#p-cactions' ).find( 'ul' ).append( "

  • Assess
  • \n" );

    });

    } // close initialize function

    } // close wikiAssess object

    wikiAssess.initialize();

    }) // close mw.loader

    } // close if

    //