Utente:Alex brollo bis/GetIndexData.js

Da Wikisource.

Nota: dopo aver pubblicato, potrebbe essere necessario pulire la cache del proprio browser per vedere i cambiamenti.

  • Firefox / Safari: tieni premuto il tasto delle maiuscole Shift e fai clic su Ricarica, oppure premi Ctrl-F5 o Ctrl-R (⌘-R su Mac)
  • Google Chrome: premi Ctrl-Shift-R (⌘-Shift-R su un Mac)
  • Internet Explorer / Edge: tieni premuto il tasto Ctrl e fai clic su Aggiorna, oppure premi Ctrl-F5
  • Opera: premi Ctrl-F5.
/* Tested first into fr.source into fr:User:Alex brollo/GetIndexData.js */

function oggi() {
	var d = new Date();
	return d.getDate() + " " + ["gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio", "agosto", "settembre", "ottobre", "novembre", "dicembre"][d.getMonth()] + " " + d.getFullYear();
}

/* 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];
}

function qiFiller(cdsQi) {
	var testo=('{{Qualità|avz=25%|data=' + oggi() + '|arg=Da definire}}' + 
			'{{IncludiIntestazione|sottotitolo=#1|prec=../#2|succ=../#3}}\n\n')
                  .replace("#1", currentIndexSummaryData[cdsQi].ns0Title);
	var baseNome = wgTitle.substring(0, wgTitle.lastIndexOf("/") + 1);
	var sottotitolo=currentIndexSummaryData[cdsQi].ns0Title;
	// caso primo della lista
		if (currentIndexSummaryData[cdsQi - 1] !== undefined) {
			testo = testo.replace("#2", currentIndexSummaryData[cdsQi - 1].ns0Name.replace(baseNome, ""));
		} else testo = testo.replace("../#2", "");
		//caso ultimo della lista
		if (currentIndexSummaryData[cdsQi + 1] !== undefined) {
			testo = testo.replace("#3", currentIndexSummaryData[cdsQi + 1].ns0Name.replace(baseNome, ""));
		} else testo = testo.replace("../#3", "");
	
	return testo;
}
/* 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= />';
	var csn=findItem();
	var from=currentIndexSummaryData[csn].PageName.split("/")[1];
	var to= currentIndexSummaryData[csn+1].PageName.split("/")[1];
	
	pages=pages.replace("%1", currentIndex.replace("Indice:",""))
     .replace("%2",from)
	 .replace("%3", to);
	return qiFiller(csn)+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 = $(".pagineDellEdizione 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={};
		itemEl.ns0Name=$("a",linksc.eq(item)).first().attr("title").replace(" (tuttora non scritto)","");
		itemEl.ns0Title=$("a",linksc.eq(item)).first().text();
		itemEl.PageName=$("a",linksc.eq(item)).last().attr("title").replace(" (tuttora non scritto)","");
		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:","Livre:");
	}
 
	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();});