MediaWiki:ListingEdit/code.js

window.ListingEdit = { init: function { var listingCat, lists, getCats, cats, inputWrap, inputBox, inputButton; listingCat = this.listingCat ? this.listingCat : /^Category:List\s/; getCats = new XMLHttpRequest; getCats.open( "GET", "/api.php?action=query&format=xml&titles=" + encodeURIComponent( mw.config.get( "wgTitle" ) ) + "&prop=categories" ); getCats.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" ); getCats.onreadystatechange = function { var i, j;	if ( getCats.status != 200 ) { console.log( "Failed to pull categories from the API. Trying manually." ); cats = document.getElementById( "mw-normal-catlinks" ).getElementsByTagName( "ul" )[0].getElementsByTagName( "a" ); return; } else { cats = getCats.responseXML.getElementsByTagName( "cl" ); }	for ( i = 0; i < cats.length; i++ ) { if ( listingCat.test( cats[i].getAttribute( "title" ) ) ) { lists = document.getElementById("mw-content-text").getElementsByTagName("ul"); for ( j = 0; j < lists.length; j++ ) { if ( lists[j].parentNode.nodeName === "DIV" ) { inputWrap = document.createElement("li"); inputWrap.textContent = this.inputDescr ? this.inputDescr : "Add a new element to the listing:"; inputBox = document.createElement("input"); inputBox.id = "listing-edit"; inputBox.type = "text"; inputWrap.appendChild(inputBox); inputButton = document.createElement("button"); inputButton.id = "listing-update"; inputButton.textContent = this.buttonLabel ? this.buttonlabel : "Update!"; inputButton.addEventListener( "click", function {		 var currentElem = document.getElementById("listing-update").parentElement.parentElement, myId;		  while ( currentElem.previousElementSibling.nodeName.indexOf("H") === -1 ) {		    currentElem = currentElem.previousElementSibling;		  }		  myId = currentElem.previousElementSibling.childNodes[0].id;		  ListingEdit.onSubmit(myId)				}, false ); inputWrap.appendChild(inputButton); lists[j].appendChild(inputWrap); }	   }	    break; }	}     };      getCats.send; }, onSubmit: function(listId) { var headings, newItem, xhr, i;   headings = document.getElementsByClassName("mw-headline"); for ( i = 0; i < headings.length; i++ ) { if ( headings[i].id === listId ) { break; }   }    newItem = document.getElementById("listing-edit").value; xhr = new XMLHttpRequest; xhr.open( "POST", "/api.php" ); xhr.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded; charset=UTF-8" ); xhr.send( "action=edit&title=" + encodeURIComponent( mw.config.get("wgPageName" )) + "&token=" + encodeURIComponent(mw.user.tokens.values.editToken) + "&summary=Updated+listing&section=" + String( i+1 ) + "&appendtext=\n*" + encodeURIComponent( newItem ) ); } }