User:Kaldari/assessmentHelper.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
This user script seems to have a documentation page at User:Kaldari/assessmentHelper. |
// 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.
//<nowiki>
// 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 ( $('<div class="assess-progress" style="text-align:center;margin:1.8em 0;"></div>').html( message+'<br/><img src="//upload.wikimedia.org/wikipedia/commons/4/42/Loading.gif" />' ) );
},
displayError: function( error ) {
$( '#assessment-form div' ).hide(); // remove everything else from the dialog box
$( '#assessment-form' ).append ( $('<div class="assess-error" style="color:#990000;margin-top:0.4em;"></div>').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 = $('<div id="assessment-form" style="position:relative;"></div>')
.append( $('<div style="margin-top:0.4em;"></div>').html( 'WikiProject: ' )
.append( $('<select id="projectSelect" style="padding:1px;vertical-align:baseline;"></select>') )
)
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Class: ' )
.append( $('<select id="classSelect" style="padding:1px;vertical-align:baseline;"></select>') )
)
.append( $('<div style="margin-top:0.4em;"></div>').html( 'Importance: ' )
.append( $('<input type="radio" name="importance" value="Low" />') ).append( ' Low ' )
.append( $('<input type="radio" name="importance" value="Mid" />') ).append( ' Mid ' )
.append( $('<input type="radio" name="importance" value="High" />') ).append( ' High ' )
.append( $('<input type="radio" name="importance" value="Top" />') ).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( $('<option></option>').val(value).html(value).attr('selected', 'selected') );
} else {
$('#projectSelect').append( $('<option></option>').val(value).html(value) );
}
});
}
} );
// Populate class select list
$.each( classList, function(index, value) { $('#classSelect').append( $('<option></option>').val(value).html(value) ); });
// Insert 'Assess' link into page interface
$( document ).ready( function() {
$( '#p-cactions' ).find( 'ul' ).append( "<li><a title=\"Assess this article\" onclick=\"wikiAssess.launchDialog(); return false;\" href=\"#\">Assess</a></li>\n" );
});
} // close initialize function
} // close wikiAssess object
wikiAssess.initialize();
}) // close mw.loader
} // close if
//</nowiki>