User:Jts1882/taxonomybrowser.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
![]() | This user script seems to have a documentation page at User:Jts1882/taxonomybrowser. |
//importScript('User:Jts1882/taxonomybrowser.js');
var nLevels = 3; // this determines how many levels are show in each iteration
var nListLevels = 3
var nInteractiveLevels = 1;
var debug = false;
var nRun = 1;
/**
* This script adds a tool and dialog using code 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'
}
};
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 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
});
}
//------------------------------------ the list function ---------------------------
function getTreeList(taxon) {
cleanUpAfterPreviousRuns();
var level = nListLevels;
//taxon = prompt("Enter the parent taxon:", getDefaultTaxonName(taxon));
taxon = getTaxonName(taxon); // prompt for taxon name
level =nLevels; // can be changed in getTaxonName
// top level taxon with empty ul tags
var output= '<ul class="taxon_identifier" ><li>' + taxon + '<ul id="' + encodeID(taxon) + '-ul"></ul></li></ul>';
addChildrenList(taxon, level ); // get data jQuery's AJAX functions
renderTaxonomyDialog( output ); // open dialog
nRun += 1;
}
// get data jQuery's AJAX functions and create hierarchy tree
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/>"
var nResults = data.query.searchinfo.totalhits;
if (nResults === 0) {
// alert ("zero hits: " + taxon);
output = ' [no children]'; // "zero hits: " + taxon;
}
else {
$.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>' ;
if (debug) output += extraInfo;
// + ' <button class="childbutton" id="' + child + '">+</button>'
output += '<ul id="' + encodeID(child) + '-ul"></ul>'
+ '</li>' ;
addChildrenList(child, level );
} ) ;
}
// insert children taxa
if (nResults > 0) {
$('#'+encodeID(taxon)+'-ul').html(output);
} else {
$('#'+encodeID(taxon)+'-ul').parent().append(' [no children]');
//$('#'+encodeID(taxon)+'-ul').parent().append(output);
$('#'+encodeID(taxon)+'-ul').remove();
}
}
);
}
}
// ----------------------------- 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) {
taxon = prompt("Enter the parent taxon:", getDefaultTaxonName(taxon));
var split = taxon.split(" ");
if (split[1]) {
var number = parseInt(split[1]);
//if (number != NaN) nLevels = number;
if (!isNaN(number)) {
nLevels = number;
nInteractiveLevels= number; // TODO make decision on level parameters
nListLevels= number;
}
taxon = split[0];
}
return taxon;
}
function getDefaultTaxonName(taxon) { // get default from page name
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];
}
}
function formatByRank(name, rank) {
// check for genus and species; inlcude should pick up subgenus, species group, etc
if ( rank.includes("genus") || rank.includes("species") ) {
name = '<i>' + name + '</i>';
}
return name;
}
function cleanUpAfterPreviousRuns() {
if (nRun > 1) {
//if (debug) alert ("run number = "+ nRun);
$('.taxon_identifier').remove();
}
}
///------------------------------- interactive function --------------------------------
function getTreeInteractive(taxon) {
cleanUpAfterPreviousRuns();
//taxon = prompt("Enter the parent taxon:", getDefaultTaxonName(taxon));
taxon = getTaxonName(taxon);
var output= '<br/><ul><li class="taxon_identifier" id="' + taxon + '-li"><b>' + taxon + '</b></li><br/></ul>';
var level = nInteractiveLevels; // nLevels is globally set at top
addChildrenInteractive(taxon, level );
renderTaxonomyDialog( output );
nRun += 1;
}
function addChildrenInteractive(taxon, level, callbackfunction) {
if (level == 0) return;
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',
'srnamespace' :10, // search in template namespace
'srlimit' : 500,
'srsearch' : 'insource:"parent[ ]+=[ ]+' + taxon + '" prefix:Template:Taxonomy/'
},
function( data ) {
var output = "";
var nResults = data.query.searchinfo.totalhits;
if (nResults === 0) {
// alert ("zero hits: " + taxon);
output = ' [no children]'; // "zero hits: " + taxon;
$('#'+encodeID(taxon)+'-li').append(output);
}
else { // so we have some results
$('#'+encodeID(taxon)+'-li').append('<ul></ul>'); // add ul element to contain children
//output = '<ul>';
$.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 = formatByRank(child, rank);
//if (rank == "genus") name = '<i>' + child + '</i>';
output = '<li id="' + encodeID(child) + '-li" class="taxon_identifier" >';
output += '<a href="/wiki/' + sr.title + '">' + name + '</a>' ;
if (debug) 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%;"> ⊞ </span>'; // +/- in square ⊞/⊟ +/-/x in circle ⊕/⊖/⊗
}
//output += '<br/><ul id="' + encodeID(child) + '-ul"></ul>';
output += '</li>' ;
$('#'+encodeID(taxon)+'-li > ul').append(output); // append child li element
$('#'+encodeID(child)).click(function (e) {
e.preventDefault();
addChildrenInteractive(child, nInteractiveLevels ); // trigger new run
$(this).hide();
});
if (level > 0) addChildrenInteractive(child, level );
});
output += '</ul>';
}
} // end processing function (data)
);
} // end function addChildrenInteractive()
// ----------------- 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
});
});
});