User:Ricordisamoa/RenameSection.js

From Wikimedia Commons, the free media repository
Jump to navigation Jump to search
Note: After saving, you have to bypass your browser's cache to see the changes. Internet Explorer: press Ctrl-F5, Mozilla: hold down Shift while clicking Reload (or press Ctrl-Shift-R), Opera/Konqueror: press F5, Safari: hold down Shift + Alt while clicking Reload, Chrome: hold down Shift while clicking Reload.
/* <nowiki>
 * RenameSection.js by [[User:Ricordisamoa]]
 * uses jQuery & Ajax
 * adds a link to simply *rename* a section
*/
$(document).ready(function(){
	if(wgAction==="view"){// in 'view' mode
		$("span.editsection").each(function(i,e){
			$("<a>")
			.text("rename")
			.attr("title","rename this section")
			.attr("href","#")
			.click(function(event){
				event.preventDefault();
				var index=parseInt($(e).children("a").first().attr("href").replace(/^.+[\?&]section=([0-9]+)$/,"$1"));
				$.get(
					mw.util.wikiScript(),
					{title:wgPageName,action:"raw",section:index}
				)
				.done(function(d){
					var oldName=$(e).siblings("span.mw-headline")
					.text(d.match(/^[\s\n\r]*=+\s*([^=\n\r]+[^\s=])\s*=+/)[1])// putting the original heading
					.attr("contenteditable",true)// make editable
					.keydown(function(evt){
						if(evt.keyCode===13){// 'enter'
							var newName=$(e).siblings("span.mw-headline").text();
							var newText=d.replace(/^([\s\n\r]*=+\s*)[^=\n\r]+[^\s=](\s*=+)/,"$1"+newName+"$2");
							$.post(
								mw.util.wikiScript("api"),
								{
									action:"edit",
									text:newText,
									title:wgPageName,
									section:index,
									summary:"[["+
										(wgServer==="//commons.wikimedia.org"?"":"commons:")
									+"User:Ricordisamoa/RenameSection|RenameSection.js]]: renamed '"+oldName+"' to '"+newName+"'",
									token:mw.user.tokens.get("editToken")
								}
							)
							.done(function(){
								jsMsg("Section renamed!");
								//document.location.reload();
							})
							.fail(function(){
								jsMsg("The ajax request failed.");
							});
							return false;
						}
					})
					.text();
				});
			})
			.insertAfter($(e).children().last())
			.before(" | ");
		});
	}
});
/* </nowiki> */