User:Magicpiano/NRBot/ReorderNRHPlist.js

/* jshint maxerr: 3000 */ /* This script will place a button at the top of any NRHP county/state list that when clicked on will check and automatically fix the ordering of the numbers in the first column of the NRHP table. If no reordering is needed, a null edit will be performed. This is useful when a property has been added to or removed from the list, causing all rows below it to be off by one. function RenumberButton { if (mw.config.get('wgNamespaceNumber')!==0) { /* only main namespace */ return; }   if (location.href.indexOf('action')!=-1||location.href.indexOf('Talk:')!=-1) return; /* talk page, or editing the page */

if (mw.config.get('wgPageName').search("National_Register_of_Historic_Places_listings_in")===-1 &&   	mw.config.get('wgPageName').search("National_Register_of_Historic_Places_listings_on")===-1 &&    	mw.config.get('wgPageName').search("National_Historic_Landmarks_in")===-1) { return; }   var content=document.getElementById('mw-content-text');

//look to see if button is already here var button = document.getElementById('mw-nrhp-renumber-button'); var needsButton = false; if (button === null) { // no such element needsButton = true; } else if (!button.hasAttributes || !button.hasAttribute("class")) { needsButton = true; } else if (button.getAttribute("class") !== "NRHPRenumberButton") { needsButton = true; }   if (!needsButton) return; button=document.createElement("input"); button.setAttribute("type", "button"); button.setAttribute("class","NRHPRenumberButton"); button.setAttribute("onclick", "RenumberClick"); button.id = 'mw-nrhp-renumber-button';

content.parentNode.insertBefore(button, content); console.log('Reorder NRHP button ready'); ButtonState(false); }

function ButtonState(isDisabled) { var button = document.getElementById('mw-nrhp-renumber-button'); button.disabled = isDisabled; if (isDisabled) { button.value = "Working..."; } else { button.value = "Renumber list"; } }

function RenumberClick { ButtonState(true); getListWikitext(mw.config.get('wgPageName')); }

function getListWikitext(title) { $.ajax({       dataType: "json",        url: mw.util.wikiScript('api'),        data: {            format: 'json',            action: 'query',            prop: 'revisions',            rvprop: 'content',            rvslots: 'main',            titles: title,            indexpageids: true,            redirects: 'true'        },        success: function (data, status, xhr) {        	var response = xhr.responseText; //        	console.log("ReorderNRHPlist: response to initial fetch: "+response);        	var output = JSON.parse(response);        	var wikitext = "error";        	var id;		    for (var page in output.query.pageids) {		    	id = output.query.pageids[page];	        	console.log('ReorderNRHPlist: response pageid = '+id);		        wikitext = output.query.pages[id].revisions[0].slots.main['*'];		    }            RenumberList(wikitext);        },        error: function(ArticlejsonObject) { console.log('ReorderNRHPlist: Error fetching title '+title); alert('Could not get wikitext; failure.'); ButtonState(false); }   }); }

function RenumberList(wikitext) { var splittext = wikitext.split("|}");

var newwikitext = ''; var i, j, k, l, str, skip, StartIndex; var index, RowLocations = []; for (j=0; j -1) { RowLocations.push(index); StartIndex = index + skip; }

var stop=RowLocations.length+1; var comments=splittext[j].match(/<\!\-\-(.|[\r\n])*?\-\-\>/g); if (comments!==null) { for (l=0; lsplittext[j].indexOf(comments[k])&&StartIndex -1) { RowLocations.push(index); StartIndex = index + skip; }       }        newwikitext+=splittext[j]+"|}"; }   newwikitext+=splittext[splittext.length-1]; editNRHPPage({       title: mw.config.get('wgPageName'),        text: newwikitext,        summary: 'Semi-automated renumbering of list items after addition/deletion.'    }); }

function editNRHPPage(info) { var edit_token = mw.user.tokens.get( 'editToken' ); if (edit_token === null) { edit_token = mw.user.tokens.get('csrfToken'); }   $.ajax({        url: mw.util.wikiScript( 'api' ),        type: 'POST',        dataType: 'json',        async: true,        data: {            format: 'json',            action: 'edit',            title: info.title,            text: info.text,            summary: info.summary,            token: edit_token        },        success: function( data ) {            if (data && data.edit && data.edit.result && data.edit.result == 'Success') {                alert("Success! Rows renumbered!");            } else {            	var msg;            	if (data && data.error) {            		msg = "Error editing page: ";            		msg += " code=" + data.error.code;            		msg += " info=" + data.error.info;        		} else {        			msg = "Error editing page (no data or error)";        		}                alert(msg);            }        },        error: function {            alert('Error saving renumbered rows! Refresh the page to try again');       },        complete: function {        	ButtonState(false);        }    }); }

$.when($.ready).then(RenumberButton);