Uzanto:Yair rand/TabbedLanguages.js

El Vikivortaro

Notu: Post konservado vi forviŝu la kaŝmemoron de via foliumilo por vidi la ŝanĝojn : Mozilo: alklaku Reŝarĝi (aŭ Stir-Shift-R), IE / Opera: Stir-F5, Safari: Cmd-R, Konqueror Stir-R.

// This is a (very) modified version of User:Atelaes/TabbedLanguages.js.
// Tabbed languages with tabs on the side.
// Tabs design by [[User:Jorm (WMF)]]
// Code still needs cleaning up
window.tabbedLanguages = [];
window.languageContainers = [];
window.currentLanguageTab = 0;
window.languageHeaderEditButtons = [];
window.tabstable = undefined;
/**
 * Create a new DOM node for the current document.
 *    Basic usage:  var mySpan = newNode('span', "Hello World!")
 *    Supports attributes and event handlers*: var mySpan = newNode('span', {style:"color: red", focus: function(){alert(this)}, id:"hello"}, "World, Hello!")
 *    Also allows nesting to create trees: var myPar = newNode('p', newNode('b',{style:"color: blue"},"Hello"), mySpan)
 *
 * *event handlers, there are some issues with IE6 not registering event handlers on some nodes that are not yet attached to the DOM,
 * it may be safer to add event handlers later manually.
**/

function newNode(tagname){
 
  var node = document.createElement(tagname);
 
  for( var i=1;i<arguments.length;i++ ){
 
    if(typeof arguments[i] == 'string'){ //Text
      node.appendChild( document.createTextNode(arguments[i]) );
 
    }else if(typeof arguments[i] == 'object'){ 
 
      if(arguments[i].nodeName){ //If it is a DOM Node
        node.appendChild(arguments[i]);
 
      }else{ //Attributes (hopefully)
        for(var j in arguments[i]){
          if(j == 'class'){ //Classname different because...
            node.className = arguments[i][j];
 
          }else if(j == 'style'){ //Style is special
            node.style.cssText = arguments[i][j];
 
          }else if(typeof arguments[i][j] == 'function'){ //Basic event handlers
            try{ node.addEventListener(j,arguments[i][j],false); //W3C
            }catch(e){try{ node.attachEvent('on'+j,arguments[i][j],"Language"); //MSIE
            }catch(e){ node['on'+j]=arguments[i][j]; }}; //Legacy
 
          }else{
            node.setAttribute(j,arguments[i][j]); //Normal attributes
 
          }
        }
      }
    }
  }
 
  return node;
}

function makeLanguageTabs() {
	if ((mw.config.get('wgNamespaceNumber') == 0 || mw.config.get('wgPageName') == "Vikivortaro:Testejo") && mw.config.get('wgAction') != 'edit' && $.cookie('disable-tabbed-languages') == null && location.search.indexOf("tabbedlanguages=off") == -1 && !window.loadedTabs) {
		window.loadedTabs = true;
		mw.util.addCSS("#tabstable{clear:both;}#languageLinks .selectedTab a{font-size:19px;color:#000;padding:6px;display:block;border-left:1px solid #AAA;border-bottom:1px solid #AAA;margin-bottom:-3px;background-color:#fff;margin-right:-6px;position:relative;border-top:1px solid #aaa;white-space:nowrap;}.unselectedTab a{font-size:16px;color:#AAA;padding:6px;display:block;border-left:1px solid #AAA;border-top:1px solid #AAA;border-bottom:1px solid #AAA;margin-bottom:-3px;margin-left:15px;margin-right:-5px;white-space:nowrap;background-color:#F3F3F3;}#languageLinks tr td{padding:0px;}tr td.languageContainer{padding-left:8px;padding-bottom:10px;padding-right:8px;border:1px solid #AAA;vertical-align:top;width:100%;}.unselectedtab{margin-left:5px;}.editlangsection{margin-top:-13px;margin-right:5px;border:1px solid #AAA;margin-bottom:-2px;border-bottom-width:0px;-webkit-border-top-left-radius:5px;-webkit-border-top-right-radius:5px;-moz-border-radius-topleft:5px;-moz-border-radius-topright:5px;border-top-left-radius:5px;border-top-right-radius:5px;color:white;line-height:14px;font-size:12px;padding:0px 7px;text-align:center;clear:both;background-color:white;}")
		var languageContainer, li, language, toc = document.getElementById('toc'), languageLinks, ttr,
			catDiv = document.getElementById('mw-normal-catlinks'),
			isIE9, bodyContent_ = $(".mw-content-ltr")[0]; // document.getElementById('wikiPreview') || document.getElementById('bodyContent') || document.getElementById('mw_contentholder') || document.getElementById('article') || document.getElementById('content');

		// Dump everything into a documentfragment, to be put back at the end (this is somehow faster, I don't know why)
		var bodyContent = document.createDocumentFragment();
		while (bodyContent_.firstChild) bodyContent.appendChild(bodyContent_.firstChild);
		tabstable = newNode('table', {id: 'tabstable'}, 
			newNode('tbody', 
				ttr = newNode('tr', 
					newNode('td', {'style': 'padding-top:0px;vertical-align:top;'}, 
						newNode('table', {'style': 'margin-top: -2px;'}, 
							languageLinks = newNode('tbody', {id: 'languageLinks'}))))))
		window.toggleLanguageTabs = function (language) {
			// Find the destination language.
			for (var destinationLanguageTab = tabbedLanguages.length - 1; destinationLanguageTab >= 0; destinationLanguageTab--) {
				if (language.indexOf(tabbedLanguages[destinationLanguageTab]) == 0) {
					break;
				}
			}
			// Style the right toggle button, hide the old language section and show the new one.
			// var languageButtons = document.getElementById('languageLinks').getElementsByTagName('span');
			var languageButtons = $("#languageLinks .selectedTab, #languageLinks .unselectedTab");
			if (destinationLanguageTab >= 0) {
				languageButtons[currentLanguageTab].className = 'unselectedTab';
				languageContainers[currentLanguageTab].style.display = 'none';
				currentLanguageTab = destinationLanguageTab
				languageButtons[destinationLanguageTab].className = 'selectedTab'
				languageContainers[currentLanguageTab].style.display = 'table-cell';
				if (languageHeaderEditButtons.length) {
					tabstable.parentNode.removeChild(tabstable.previousSibling)
					tabstable.parentNode.insertBefore(languageHeaderEditButtons[currentLanguageTab], tabstable)
				}

				if (isIE9) {
					for (var ols = languageContainers[currentLanguageTab].getElementsByTagName('ol'), i = 0; i < ols.length; i++) {
						(function (i) {
							setTimeout(function () {
								ols[i].removeChild(ols[i].insertBefore(document.createElement('li'), ols[i].firstChild))
							}, 0)
						})(i)
					}
				}
			} else if ((language = language.replace(/\ /g, '_')) && document.getElementById(language) && document.getElementById(language).parentNode.parentNode.className == 'languageContainer') {
				toggleLanguageTabs(document.getElementById(language).parentNode.parentNode.id.split('container')[0])
			}
		}
		// Look through all the nodes in bodyContent, placing them in the correct language containers.
		for (var child = bodyContent.firstChild; child && (child.nodeName != "H2" || child.getElementsByTagName('span').length == 0); child = child.nextSibling);
		for (child = child && bodyContent.insertBefore(tabstable, child).nextSibling; child && child.className != 'printfooter' && child.className != 'catlinks'; child = child.nextSibling) {
			if (child.nodeName == 'H2') {
				var spans = child.getElementsByTagName('span');
				if (spans.length != 0 && ( spans[1] && languageHeaderEditButtons.push(spans[1]), language = (language = spans[0]).innerText || language.textContent)) {
					tabbedLanguages.push(language);
					languageContainers.push(languageContainer = ttr.appendChild(newNode('td', {
						'class': 'languageContainer',
						'id': language + 'container'
					})));
					bodyContent.removeChild(child);
					child = tabstable
				}
			} else {
				child.nodeName != "HR" ? languageContainer.appendChild(child) : bodyContent.removeChild(child);
				child = tabstable
			}
		}
		if(toc) {
			toc.parentNode.removeChild(toc)
		}
		if (tabbedLanguages.length > 0) {
			try {
				// Make the toggle.
				for (var b = 0; b < tabbedLanguages.length; b++) {
					language = tabbedLanguages[b];
					languageLinks.appendChild(newNode('tr', newNode('td', {
						'class': (b ? 'un' : '') + 'selectedTab'
					}, newNode('a', language, {
						'href': location.pathname + location.search + '#' + language
					}), ' ')))
				}
				// If there are section edit links, add edit link, and a new language button.
				if (languageHeaderEditButtons.length) {
					for (var b = 0; b < languageHeaderEditButtons.length; b++) {
						languageHeaderEditButtons[b].className += " editlangsection"
					}
					bodyContent.insertBefore(languageHeaderEditButtons[0], tabstable);
				}

				for (var a = 0; a < languageContainers.length; a++) {
					languageContainer = languageContainers[a];
					if (a != 0) {
						languageContainer.style.display = 'none';
					}
					// Put a container in each for categories.  
					languageContainer.appendChild(newNode('div', languageContainer.id.split('container')[0].replace(/.$/,'aj') + ' kategorioj: ', {
						'class': 'catlinks'
					}));
				}
				// Now for category sorting
				if (catDiv) {
					var cats = catDiv.getElementsByTagName('span'),
						catname, 
						langcurrent = 0,
						catskip = 1;
					do {
						while (cats.length > 0) {
							catname = cats[0].getElementsByTagName('a')[0].innerHTML;
							if (catname.indexOf(tabbedLanguages[langcurrent + catskip]) == 0) {
								langcurrent += catskip;
								catskip = 1;
							}
							var currentCatDiv = languageContainers[langcurrent].lastChild;
							if (currentCatDiv.lastChild.nodeName == 'SPAN') {
								currentCatDiv.appendChild(document.createTextNode(' | '))
							}
							currentCatDiv.appendChild(cats[0]);
						}
						if (langcurrent + 1 < languageContainers.length - catskip) {
							while (currentCatDiv.childNodes[1]) {
								catDiv.appendChild(currentCatDiv.childNodes[1]);
							}
							catskip++;
						} else {
							break;
						}
					} while (true)
				}
				// place patrol link at the bottom of the page
				var pl = languageContainer.lastChild.previousSibling;
				if(pl && pl.className == "patrollink"){
					bodyContent.appendChild(pl)
				}
				// rm old cat box, allow display of hidden cats box
				if (catDiv && !(catDiv.nextSibling && catDiv.nextSibling.className == "mw-hidden-cats-user-shown")) {
					catDiv.parentNode.parentNode.removeChild(catDiv.parentNode)
				} else {
					if (catDiv) {
						catDiv.parentNode.removeChild(catDiv);
					}
				}
				// put everything back into the bodyContent
				bodyContent_.appendChild(bodyContent);
				bodyContent = bodyContent_;
			} catch (e) {
				if (bodyContent_ != bodyContent) {
					'console' in window && typeof console.log == "function" && console.log(e);
					bodyContent_.appendChild(bodyContent);
					bodyContent = bodyContent_;
				}
			}
			if (isIE9 = $.client.profile().name == "msie" && $.client.profile().versionNumber == 9) { // IE9 is EVIL
				toggleLanguageTabs(tabbedLanguages[currentLanguageTab])
			}
			// If there's a location hash, the window may have scrolled down before we got a chance to reorganize everything.
			// If the destination was a subsection or sense id, switch to the right tab, and rescroll.
			// If it was simply a language, switch to the appropriate tab, and scroll back up.
			if (location.hash != '') {
				var hash = decodeURI(location.hash).substr(1);
				var destination = hash.replace(/_/g, ' ');
				toggleLanguageTabs(destination);
				if (document.getElementById(hash)) {
					resetHash()
				} else {
					window.scrollY && window.scroll(0, 0);
				}
			} else {
				if ('localStorage' in window) {
					if ($.inArray(localStorage.langTabPref, tabbedLanguages) != -1) {
						toggleLanguageTabs(tabbedLanguages[$.inArray(localStorage.langTabPref, tabbedLanguages)])
					}
				}
			}
			if ("onhashchange" in window) {
				window.onhashchange = hashToggleLT;
			} else {
				jQuery('a[href^=' + location.pathname + location.search + '#], a[href^=#]',bodyContent_).live('click',function () {
					setTimeout(hashToggleLT, 10)
				})
			}
			if ('localStorage' in window) {
				window.onunload = function () {
					if (tabbedLanguages[currentLanguageTab] && tabbedLanguages[currentLanguageTab] != 'English' && tabbedLanguages[currentLanguageTab] != 'Translingual') {
						localStorage.langTabPref = tabbedLanguages[currentLanguageTab]
					}
				}
			}
		} else {
			bodyContent_.appendChild(bodyContent);
			bodyContent = bodyContent_;
		}
	}
}

function hashToggleLT() {
	var destination = decodeURI(location.hash.substr(1)).replace('_', ' ');
	toggleLanguageTabs(destination);
}

function resetHash() {
	window.scroll(0, $(location.hash).offset().top)
}

jQuery(document).ready(makeLanguageTabs);