User:Martin of Sheffield/Shortdesc helper.js

//Initial version based on code by TheDJ; see MediaWiki:Gadget-Page_descriptions.js //shows short descriptions, and allows easier editing, importing wikidata descriptiosn, and adding descriptions //by giving buttons and inputbox for doing so

if (mw.config.get( 'wgAction' ) === 'view' ) { mw.loader.using( 'mediawiki.api'); var API = new mw.Api( {	   ajax: {	        headers: { 				'Api-User-Agent': 'Short description editer/viewer (User:Galobtter/Shortdesc helper.js)'				}	    	}	} ); var title = mw.config.get( "wgPageName"); var wgQid = mw.config.get( 'wgWikibaseItemId' ), callPromise = API.get( {			action: 'query',			titles: title,			prop: 'description',			formatversion: 2		} ), isEditor = mw.config.get( 'wgUserGroups' ).indexOf( 'autoconfirmed' ) !== -1; $.when( callPromise, $.ready ).then( function ( results ) {		var pageDescription, summary, done, sep, change, $description,			response = results[ 0 ];		var namespace = mw.config.get( 'wgNamespaceNumber' );		var showClicky = ![10, 14, 710, 828, 2300, 2302].includes(namespace);//exclude in template and category namespaces, to prevent accidental addition		if (showClicky) {sep = ' · '}		var clicky = function ( descrip, text, func) {			if (showClicky) {			return $( '' )				.addClass ('descriptionclicky')				.attr( 'title', descrip )				.text( text )				.click( func );			}		};		if ( response.query && response.query.pages && response.query.pages[ 0 ].description ) {			pageDescription = response.query.pages[ 0 ].description;			$description = $( ' ' )				.addClass( 'mw-page-description' )				.attr('id', 'showdescrip')				.text( pageDescription );			if ( response.query.pages[ 0 ].descriptionsource !== 'local' && isEditor ) {				$description.append( ' (',					$( '' )						.attr( 'href', 'https://www.wikidata.org/wiki/Special:SetLabelDescriptionAliases/' + wgQid + '/' + mw.config.get( 'wgContentLanguage' ) )						.css( 'color', 'hotpink' )						.text( 'Wikidata' ),					sep,					clicky ('Import description from Wikidata', 'Import', function {summary = "Importing Wikidata"; addDescription( pageDescription );}),					sep,					clicky( 'Edit and import description from Wikidata', 'Edit and Import', function { summary = "Adding local"; textInput;})					,')' );			}			else if (showClicky){			$description.append( ' (',				clicky ('Edit short description', 'Edit', function {summary = "Changing"; change = true; textInput;})				,')' );			}		}		else if (namespace === 0 && isEditor) {			API.get ({action: "query", titles: title, formatversion: 2}).done(function(result){ if (!result.query.pages[ 0 ].missing){ $description = ($( ' ' )						.css( 'color', 'red' )						.attr('id', 'showdescrip')						.append( 'Missing ', $( '' ) .attr( 'href', '/wiki/Wikipedia:Short description' ) .text( 'article description' ), ' (',							clicky ( 'Add description', 'Add', function { summary = "Adding"; textInput})							,')' )					);				}				$description.appendTo( '#contentSub' ); }			);		}		var saveInput = function {			if (done !== 'true') {				done = 'true';				addDescription($( '#descriptioninput' ).val);			}		};		var textInput = function {			$( '#showdescrip' ).hide (0);			if ($('#descripeditbox').length){				$( '#descripeditbox' ).show;			}			else {				$( '#contentSub' ).append($(" ") .attr ('id', 'descripeditbox') .append(					$(" ")						.attr( 'id', 'descriptioninput')						.attr( 'type', 'text' )						.attr( 'size', '40')						.val(pageDescription)						.keypress ( function (e) { if (e.which == 13) { saveInput; }						})					,' (',					clicky ( 'Save description', 'Save', function { saveInput; }) ,sep, clicky ( 'Cancel editing', 'Cancel',					function {						$( '#descripeditbox' ).hide;						$( '#showdescrip' ).show (0);					}) ,')'					));				}		};

var addDescription = function ( newDescription){ var changes, prependtext, text, section = 0; var quotify = function (text) {return '"' + text + '"';}; var makeEdit = function { API.postWithToken( "csrf", {				action: "edit",				section: section,				text: text,				title: title,				prependtext: prependtext,				summary: summary + " short description" + changes + " (Shortdesc helper)"			}).done( function {				// Code to execute if saved successfully				// Maybe reload the page:				location.reload;			}).fail( function( code, jqxhr ) {				// Edit failed. The reason will be in the code and/or jqxhr parameters...				if ( code === "http" && jqxhr.textStatus === "error" ) {					console.log( "HTTP error " + jqxhr.xhr.status );				} else if ( code === "http" ) {					console.log( "HTTP error: " + jqxhr.textStatus );				} else if ( code === "ok-but-empty" ) {					console.log( "Error: Got an empty response from the server" );				} else {					console.log( "API error: " + code );				}			}); };			newDescription = newDescription.trim; var replacement = "{"+"{"+"short description\|"+newDescription+"}}"; if (!change) { changes = ": " + quotify(newDescription); prependtext = replacement+'\n'; makeEdit ; }			else { changes = " from " + quotify(pageDescription) + " to " + quotify(newDescription); var pattern = /\{\{short description\|.*?\}\}/; var getText = function { return API.get ({ //get text						action: "query",						prop: "revisions",						titles: title,						rvprop: "content",						rvsection: section,						formatversion: 2				}); };				var replaceAndEdit = function (result){ var oldtext = result.query.pages[0].revisions[0].content; if (oldtext.match (pattern)) { text = oldtext.replace(pattern, replacement); makeEdit ; return true; }					else {return false} };				getText.done(function (result){					if (!replaceAndEdit(result)) {						section = null;						getText.done(function(result){ if (!replaceAndEdit(result)) { $( '.descripeditbox' ).append ($(" ")								.css( 'color', 'red' )								.text(" Edit failed, as unable to find short description in page text.")							); }						});					}				});			}		};		if ( $description ) { var prepend; if ($('.mw-redirectedfrom').length) { //put newline if redirect text is there prepend = ' '; }			$('#contentSub').append(prepend, $description); }	} ); }