User:Alex brollo/GetIndexData.js

From Wikisource
Jump to navigation Jump to search

Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer / Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Press Ctrl-F5.
/* Tested first into fr.source into fr:User:Alex brollo/GetIndexData.js */


/* Returns the number of djvu page from the number of book page; allows self-compilation of pli2 template
*/
function b2d(book_page){
	return currentIndexData[book_page];
}
/* returns  a self-compiled <pages... /> tag for current ns0 subpage when Summary section of Index (Livre) page is well filled */
function pagesFiller() {
	var pages='<pages index="%1" from=%2 to=%3 fromsection= tosection= header=1 />';
	var csn=findItem();
	var from=currentIndexSummaryData[csn].PageName.split("/")[1];
	var to= currentIndexSummaryData[csn+1].PageName.split("/")[1];
	pages=pages.replace("%1", currentIndex.replace("Index:",""))
     .replace("%2",from)
	 .replace("%3", to);
	return pages;
}
 
/* When in namespace ns0, new pages doesn't contain a proofreadpage_source_href variable; but the name of the Index page pointing to current ns0 page can be recevered bu API.
*/
function getCurrentIndex() {
	try {
	   var bltitle=wgPageName;
	   var blnamespace="112";
	   var api_url=["/w/api.php?action=query",
             "format=json",
             "list=backlinks",
             "blnamespace="+blnamespace,
             "bltitle="+bltitle,
             "redirects="].join("&");
	    var result=JSON.parse($.ajax({url:api_url,async:false}).responseText);
	    return result.query.backlinks[0].title;
		}
	catch(err) {
	    return "No index";
	}
}
 
/* from the name of an Index page, html is retrieved and parsed and data coming bot from pagelist tag and from anything 
into summary field are parsed into two objects.
By now, the script runs when summary field contains a list of table templates (in fr.source) or Indice sommario templates 
(in it.source), any of them containing both the link to ns0 subpage and the link to Page page.
*/
function parseLivre(livre) {
	var pdxpc = []; // pdxpc è una lista semplice in cui la pagina djvu è l'indice
	var pd = ""; // pd è pagina djvu 
	var pc = ""; // pc è pagina cartacea
 
	// lettura dell'html della pagina Indice corrispondente a base
	html = $.ajax({
		url: "/w/index.php?action=render&title=" + livre,
		async: false
	}).responseText;
 
	// estrazione della lista dei link alle pagine
	var links = $("#pagelist a", $(html)); // 
 
	// estrazione di pd e pc dai link e assegnazione a una lista in cui l'indice è pd e il valore è pc
	for (i = 0; i < links.length; i += 1) {
		pd = eval($(links[i]).attr("title").match(/\/(\d+) */)[1]);
		pc = $.trim($(links[i]).text().match(/^0*(.+)/)[1]);
		pdxpc[pd] = pc;
 
	}
 
	// la lista viene popolata con stringhe vuote se vi sono dei "buchi"
	for (i = 1; i < pdxpc.length - 1; i += 1) {
		if (pdxpc[i] === undefined) pdxpc[i] = "";
	}
    // costuisco un array a chiave con chiave pc
	var pcxpd={};
	for (i = 1; i < pdxpc.length - 1; i += 1) {
		pcxpd[pdxpc[i]]=i;
	}
	var linksc=$(".tableItem",  $(html));
	var itemList=[];
	for (var item=0; item<linksc.length; item+=1){
 
		itemEl={};
		itenEl.ns0Name=$("a",linksc.eq(item)).first().attr("title").replace(" (page does not exist)","");
		itemEl.ns0Title=$("a",linksc.eq(item)).first().text();
		itemEl.PageName=$("a",linksc.eq(item)).last().attr("title").replace(" (page does not exist)","");
		itemEl.PageTitle=$("a",linksc.eq(item)).last().text();
		itemList.push(itemEl);
	}
	return [pcxpd,itemList];
}
/* As soon a ns0,Page or Index page has been opened, current index is compared with the saved one and data are updated if needed only
*/
function testIndexData() {
	currentIndex="";
	if (wgNamespaceNumber===0) {
		try {
			currentIndex=decodeURIComponent($(proofreadpage_source_href).attr("href").replace("/wiki/",""))
              .replace(/_/g," ");
			  }
	    catch(err) {
		     currentIndex=getCurrentIndex();
			 }
	}
	if (wgCanonicalNamespace==="Page" || wgCanonicalNamespace==="Index") {
			currentIndex=wgPageName.split("/")[0].replace("Page:","Index:");
	}
 
	if (currentIndex !=="" && currentIndex !=="No index" && localStorage.currentIndex !== currentIndex) {
		localStorage.setItem("currentIndex",currentIndex);
		var dataIndex=parseLivre(currentIndex);
		localStorage.setItem("currentIndexData",JSON.stringify(dataIndex[0]));
		localStorage.setItem("currentIndexSummaryData",JSON.stringify(dataIndex[1]));
		}
 
    currentIndexData=JSON.parse(localStorage.getItem("currentIndexData"));
	currentIndexSummaryData=JSON.parse(localStorage.getItem("currentIndexSummaryData"));
	// addPages (aggiunta tag pages) temporaneamente disattivato
	// if (wgCanonicalNamespace==="" && $.trim($("#wpTextbox1").val())==="") addPages();
 
}
 
function addPages() {
	currentTextboxContent=$("#wpTextbox1").val();
	if ((/<pages(.*?)\/>/).test(currentTextboxContent)) {
		currentTextboxContent=$("#wpTextbox1").val(); 
   		$("#wpTextbox1").val(currentTextboxContent.replace(/<pages(.*?)\/\>/,pagesFiller()));
	}
	else {
   $.trim($("#wpTextbox1").val(pagesFiller()+"\n"+currentTextboxContent));
	}
}
 
/* Finds an item into the currentIndexSummaryData list
*/
function findItem() {
   for (i=0;i<currentIndexSummaryData.length;i+=1) {
       if (wgTitle===currentIndexSummaryData[i].ns0Name) return i;
   }
   return -1;
}
 
$(document).ready(function() {testIndexData();});