Jump to content

User:Jts1882/taxonomybrowser.js

From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Jts1882 (talk | contribs) at 16:17, 16 February 2019 (update to newer version). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
//importScript('User:Jts1882/taxonomybrowser.js');

var nLevels = 1;  // this determines how many levels are shown in each iteration

/**
 * This script is modified from the following tutorial script
 * 
 * Tutorial script: QuickRC ("Quick Recent Changes")
 *
 * A tutorial user script which adds a "Quick changelog" link to the page skin's
 * toolbox, and when clicked it pops up a dialog with up to 25 recent edits.
 *
 * Demonstrates:
 * - Use of the API
 * - Use of jQuery
 * - Use of ResourceLoader and some of the default modules that come with it
 * - Use of localization
 *
 * (Be bold and improve it!)
 *
 * Authors:
 * Erik Moeller, 2011, public domain
 * Brion Vibber, 2012, public domain
 */

messages = {
    'en': {
        'taxonomy-title': 'Taxonomy template browser',
        'taxonomy-greeting': 'Welcome, $1!',
        'taxonomy-intro': 'The following templates are children of this taxon taxonomy template:',
        'taxonomy-link': 'Taxonomy list',
        'taxonomy-link2': 'Taxonomy browser',
        'taxonomy-tooltip': 'Get children for particular taxonomy template'
    },
    'fr': {
        'taxonomy-title': 'Bonjour !',
        'taxonomy-greeting': 'Bienvenue, $1!',
        'taxonomy-intro': 'Taxonomique :',
        'taxonomy-link': 'Taxonomique'
        // Leave tooltip out to demonstrate fallback behavior
    }
};

mw.messages.set(messages.en);
var lang = mw.config.get('wgUserLanguage');
if (lang && lang != 'en' && lang in messages) {
    mw.messages.set(messages[lang]);
}

// Import the jQuery dialog plugin before starting the rest of this script
mw.loader.using(['jquery.ui.dialog'], function() {

    function renderQuickRCDialog( pageLinks ) {
		var $dialog = $( '<div></div>' )
			.html(
				'<strong>' +
				mw.message('taxonomy-greeting', mw.user.getName()).escaped() +
				'</strong> ' +
				mw.message('taxonomy-intro').escaped() +
				'<br/><ul><li>' +
				pageLinks.join( '<br /><li>' ) + '</ul>'
			)
			.dialog({
				autoOpen: true,
				title: mw.message('taxonomy-title').plain(),
				width: '70%',
				modal: true
			});
	}
    function renderTaxonomyDialog( output ) {
		var $dialog = $( '<div></div>' )
			.html(
				'<strong>' +
				mw.message('taxonomy-greeting', mw.user.getName()).escaped() +
				'</strong> ' +
				mw.message('taxonomy-intro').escaped() +
				output
			)
			.dialog({
				autoOpen: true,
				title: mw.message('taxonomy-title').plain(),
				width: '50%',
				modal: true
			});
	}

	// function quickRC() {
	function getChildren(taxon) { // test version based on function quickRC() No longer active
	
		//alert("hello from my test function: " + taxon) 
		taxon = prompt("Please enter your name", taxon);


		var myPageLinks = [];
		var myTitles = [];

		// Fetch recent changes from the API by one of jQuery's AJAX functions
		jQuery.getJSON(
			mw.util.wikiScript( 'api' ),
			{
				'format': 'json',
				'action': 'query',
				'list': 'search',
				'srlimit' : 500,
				'srnamespace' :10,
				'srsearch' : 'insource:"parent[ ]+=[ ]+' + taxon + '" prefix:Template:Taxonomy/'

			},
			function( data ) {

				// Build a unique array of links, using the mw.html library to format them.
				$.each ( data.query.search , function( index , sr ) {
					// Don't link to this title if we've seen this title already
					if ( $.inArray( sr.title, myTitles ) === -1 ) {
						myPageLinks.push(
							mw.html.element(
								'a', { href: mw.util.getUrl( sr.title ) }, sr.title
							)
						);
					}

					myTitles.push( sr.title );
				} ) ;

				renderQuickRCDialog( myPageLinks );
			}
		);
		
	}
	
	//------------------------------------ the list function ---------------------------
    function getTreeList(taxon) {
        //alert("hello from my test tree function: " + taxon) ;
       // taxon = prompt("Please enter your name", taxon);
        taxon = prompt("Enter the parent taxon:", getTaxonName(taxon));
        
        // top level taxon with empty ul tags
        
		var output= '<br/><ul><li>' + taxon + '<ul id="' + encodeID(taxon) + '-ul"></ul></li><br/></ul>';
		
		// Fetch recent changes from the API by one of jQuery's AJAX functions
		var level = 3;
		addChildrenList(taxon, level );  
		renderTaxonomyDialog( output );
        
    }
    
    function addChildrenList(taxon, level, callbackfunction) {
       if (level > 0) {
       	    level -= 1;
	 		jQuery.getJSON(
				mw.util.wikiScript( 'api' ),
				{
					'format': 'json',
					'action': 'query',
					'list': 'search',
					'srlimit' : 500,
					'srnamespace' :10,
					'srsearch' : 'insource:"parent[ ]+=[ ]+' + taxon + '" prefix:Template:Taxonomy/'
	
				},
				function( data ) {
	                var output = "";// an empty element with ID exists "<ul><br/>"

					$.each ( data.query.search , function( index , sr ) {
	                     var child =  sr.title.replace("Template:Taxonomy/", "");
                         var extraInfo = extraText(index , sr);
                         var rank = getRank(index , sr);
                         var name = child;
                         if (rank == "genus") name = '<i>' + child + '</i>';
	                     // href="/wiki/Template:Taxonomy/Machairodontinae">
	                     output += '<li><a href="/wiki/' + sr.title + '">' + name + '</a>'	+ extraInfo
	                    //            + ' <button class="childbutton" id="' + child + '">+</button>'
	                                + '<br/><ul id="' + encodeID(child) + '-ul"></ul>'
	                                + '</li>' ;
	                     addChildrenList(child, level );
                     
	                     
					} ) ;
	                // insert children taxa
	                $('#'+encodeID(taxon)+'-ul').html(output);   
				}
			);        
    	}
    	
    }
    
    // ----------------------------- utlity functions -------------------------------
    function escapeSeq(taxon) {
    	taxon = taxon.replace(" ("," \("); 
    	taxon = taxon.replace(")","\)");
    	return taxon;
    }
    function encodeID(taxon) {
    	taxon = taxon.replace("/","_X_");
    	taxon = taxon.replace("(","_Y_");
    	taxon = taxon.replace(")","_Z_");
    	taxon = taxon.replace(" ","_S_");
    	taxon = taxon.replace("?","_Q_");
    	return taxon;
	    //return encodeURIComponent(taxon);
    }
    function decodeID(taxon) {
    	taxon = taxon.replace("_X_","/");
     	taxon = taxon.replace("_Y_","(");
   	    taxon = taxon.replace("_Z_",")");
   	    taxon = taxon.replace("_S_"," ");
   	    taxon = taxon.replace("_Q_","?");
   	    return taxon;
	    //return encodeURIComponent(taxon);
    }    
    function getTaxonName(taxon) {
    	
    	var page = mw.config.get( 'wgPageName' ) ;

    	if (page.includes("Template:Taxonomy/") ) {
    	   var res = page.split("Template:Taxonomy/");	
    	   taxon = res[1];
    	}
    	else  {
    	    var title = new mw.Title ( page );
    	    var ns = title.getNamespaceId();
    	    if ( ns === 0 && !page.includes(" ") ) 	taxon = page;
    	}
    	return taxon;
    }
    function  extraText(index , sr) {
		
		var extraInfo = " [extra info] ";
		//if (1==1) return sr.snippet;
		
		var templateData =sr.snippet; // this contains the template code
		
		if (templateData.includes("rank")) {
		  //var rank = templateData.match(/rank[\s]*=[\s]*[a-zA-Z]*/); //gets "rank%s=%sclassis"
		  var rank = templateData.match(/rank[\s]*=[\s]*([a-zA-Z ]*)/);
		  if (rank && rank[0] ) 	extraInfo  = ' ['+rank[0]+']';
		  if (rank && rank[1] ) 	extraInfo += ' ['+rank[1]+']';
		  var sameas = templateData.match(/same[ _]as[\s]*=[\s]*([a-zA-Z]*)/);
		  if (sameas && sameas[0] ) 	extraInfo += ' ['+sameas[0]+']';

		}
		
		return extraInfo; 
    }   
    function  getRank(index , sr) {
		var templateData =sr.snippet; // this contains the template code
		if (templateData.includes("rank")) {
		  var rank = templateData.match(/rank[\s]*=[\s]*([a-zA-Z ]*)/);
		  if (rank && rank[1] ) 	return rank[1];
		}
    }
    ///-------------------------------  interactive function --------------------------------
    function getTreeInteractive(taxon) {
        //alert("hello from my test tree function: " + taxon) ;
        
        taxon = prompt("Enter the parent taxon:", getTaxonName(taxon));
        
        // top level taxon with empty ul tags
		var output= '<br/><ul><li>' + taxon + '<ul id="' + taxon + '-ul"></ul></li><br/></ul>';
		
		var level = nLevels; // nLevels is globally set at top
		addChildrenInteractive(taxon, level );  
		renderTaxonomyDialog( output );
        
    }
    
    function addChildrenInteractive(taxon, level, callbackfunction) {
       if (level > 0) {
       	    level -= 1;
		    // perform search using API with one of jQuery's AJAX functions
	 		jQuery.getJSON(
				mw.util.wikiScript( 'api' ),
				{
					'format': 'json',
					'action': 'query',
					'list': 'search',
					'srlimit' : 500,
					'srnamespace' :10,
					'srsearch' : 'insource:"parent[ ]+=[ ]+' + escapeSeq(taxon) + '" prefix:Template:Taxonomy/'
	
				},
				function( data ) {
	                var output = ""; // an empty element with ID exists "<ul><br/>"

					$.each ( data.query.search , function( index , sr ) {
	                     var child = sr.title.replace("Template:Taxonomy/", "");
	                     // href="/wiki/Template:Taxonomy/Machairodontinae">
                         var rank = getRank(index , sr);
                         var name = child;
                         if (rank == "genus") name = '<i>' + child + '</i>';
                          
                         
	                     output += '<li><a href="/wiki/' + sr.title + '">' + name + '</a>'	;
	                     output += extraText(index , sr);
	                     if (level === 0) {
	                     	//output += ' <button class="childbutton" id="' + encodeID(child) + '">+</button>';
	                     	output += ' <span class="childbutton" id="' + encodeID(child) + '" style="font-size:120%;"> &#8862; </span>'; // +/- in square &#8862;/&#8863; +/-/x in circle &#8853;/&#8854;/&#8855;
	                     }
	                     output += '<br/><ul id="' + encodeID(child) + '-ul"></ul>'
	                                + '</li>' ;
	                     //
	                     if (level > 0) addChildrenInteractive(child, level );
                     
	                     
					} ) ;
	                // insert children taxa
	                $('#'+encodeID(taxon)+'-ul').html(output);   
	           		$('.childbutton').click(function (e) {
					          //e.preventDefault();
					        addChildrenInteractive(decodeID($(this).attr('id')), nLevels );  // trigger new run
					        $(this).hide();
					        
					 });	
				}
			);        
    	}
    	
    }
    
    // ----------------- document ready - add functions to tool menu ------------------
	$(document).ready( function() {
		
       // alert("hello")   // my test that the page is loading
		
		// Add a link to the toolbox
		var link = mw.util.addPortletLink(
			'p-tb',
			'#',
			mw.message('taxonomy-link').plain(),
			't-prettylinkwidget',
			mw.message('taxonomy-tooltip').plain(),
			'/'
			//'#t-whatlinkshere'    // this places it at the top of the tools
		);
		var link2 = mw.util.addPortletLink(
			'p-tb',
			'#',
			mw.message('taxonomy-link2').plain(),
			't-prettylinkwidget',
			mw.message('taxonomy-tooltip').plain()
		);

		// Create a jQuery object for this link so that we get
		// to use jQuery awesomeness like .click() for binding functions to events
		// and methods like e.preventDefault();
		$(link).click( function( e ) {
			
			e.preventDefault(); // Avoid the browser going to '#'
			
			//getChildren("Felidae");  // get children for prompted taxon
			getTreeList("Plantae");  // get more than one level of tree 
		});
		$(link2).click( function( e ) {
			
			e.preventDefault();// Avoid the browser going to '#'
			
			getTreeInteractive("Carnivora");  // get more than one level of tree
		});

	});

});