User:SPage (WMF)/JStransforms.js

( function ( $, mw ) {	if ( !mw.config.get( 'wgTitle' ).match( /^SPage \(WMF\)\/(JS test|ApiEx utility)$/ ) ) {		return;	}	mw.loader.using( 'mediawiki.Uri', function { var transforms = { "make API ex": makeApiEx, "linkify": makeLinks },		$cpanel;

/**		 * given an apiEx uri struct, * returns a {{TNT|ApiEx method invocation * e.g. take https://en.wikipedia.org/w/api.php?action=query&list=geosearch&format=json&gscoord=37.786952%7C-122.399523&gsradius=10000&gslimit=10 * and turn it into {{TNT|ApiEx | p1=action=query | p2=list=geosearch ... }}		 */		function toApiEx( apiEx ) { var res = '{{TNT|ApiEx', paramCount = 1; // the first ApiEx query param is p1			if ( apiEx.lang ) { res += '\n| lang=' + apiEx.lang; }			if ( apiEx.site ) { res += '\n| site=' + apiEx.site; }			$.each ( apiEx.query, function( key, value ) {				value = value.replace( /\|/g, '{{!}}')					.replace( / /g, '%20');				res += '\n| p' + paramCount + '=' + key + '=' + value;				paramCount++;			}); res += '\n}}'; return res; }

function makeApiEx ( str ) { // TODO: This doesn't work if the input has more than one URL in it. var uri = new mw.Uri( str ), apiEx = {}, hostMatch; if ( uri.host && ( uri.host != 'en.wikipedia.org') ) { hostMatch = uri.host.match( /(.*)\.wikipedia.org/ ); if ( hostMatch && ( hostMatch[1] != 'en') ) { apiEx.lang = hostMatch[1]; } else { apiEx.site = uri.host; }			}			apiEx.query = uri.query; return toApiEx( apiEx ); }

/**		 * Linkify all the things */		function makeLinks ( str ) { // TODO: convert interwiki table to a set of regexps var phabRE = new RegExp( 'https?://phabricator.wi(kimedia.org/([^\\s,.]+)', 'g' ),				phabTRE = new RegExp( '([^/:\\w])(T\\d{3,7})(\\W)', 'g' );			return str.replace( phabRE, '$1' )				.replace( phabTRE, '$1$2$3');		}

function doTransform { var res, transform; transform = $( 'input[name="workJStransform"]:checked' ).val; res = transforms[transform]( $( '#inp' ).val ); $cpanel.find( '#result').html( res ); }

// Set up the input area $cpanel = $( '  ' ); $cpanel.find( '#inp,input[name="workJStransform"]' ).change( doTransform ); // Create a radio button for each transform $.each( transforms, function( key, value ) {		   var $element=$('' + key + ' ');		    $cpanel.html( $element );		} ); // Check the first radiobutton $cpanel.find( '[name="workJStransform"]:first').prop( 'checked', true ); $cpanel.append( ' ' );

$ ( document ).ready( function {		   $( '#workArea' ).after( $cpanel );		}); 	} ); window.console.log( 'mw.makeApiEx defined' ); } )( jQuery, mediaWiki );