Wikipedista:Mormegil/tools.js

Z Wikipedie, otevřené encyklopedie

Poznámka: Po uložení musíte vyprázdnit mezipaměť vašeho prohlížeče, jinak změny neuvidíte.

/*
'''JavaScriptové funkce''' k vložení do uživatelského skriptu (na stránce [[Speciální:Mypage/monobook.js|monobook.js pod vaší uživatelskou stránkou]]). Pokud si chcete využít některé z následujících funkcí, '''nejprve následujte návod [[#Instalace]]''', poté si vyberte požadované funkce.

<noinclude>
*******************************************************************************
*******************************************************************************
***                                                                         ***
*** Dokumentaci si můžete přečíst na [[Wikipedista:Mormegil/tools.js.help]] ***
***                                                                         ***
*******************************************************************************
*******************************************************************************
</noinclude>

__TOC__

== Instalace ==
Pokud chcete jakoukoli z následujících funkcí používat, musíte nejprve přidat odkaz na tento soubor. To provedete tak, že na začátek [[Speciální:Mypage/monobook.js|svého monobook.js]] přidáte následující kousek kódu:
<pre>
mw.loader.load("//cs.wikipedia.org/w/index.php?title=Wikipedista:Mormegil/tools.js&action=raw&ctype=text/javascript&dontcountme=s");
</pre>

Dále si tam vložte řádky podle toho, které funkce chcete (viz „použití“ u každé z následujících funkcí).

<noinclude><pre><nowiki> */

// nastavení shrnutí editace
function setWpSummary(str) {
	var eSummary = document.getElementById('wpSummary');
	if (eSummary !== null) eSummary.value = str;
}

// přidání do shrnutí editace
function appendToWpSummary(str) {
	var eSummary = document.getElementById('wpSummary');
	if (eSummary !== null) eSummary.value += str;
}

// najít element s nadpisem stránky
function findFirstHeading() {
	var eContent = document.getElementById('content');
	if (eContent === null) return null;
	var elems = eContent.getElementsByTagName("h1");
	if (elems.length === 0) return null;
	return elems[0];
}

// zjistit nadpis stránky
function getPagetitle() {
	var eHeading = findFirstHeading();
	if (eHeading === null) return "";
	var title = eHeading.innerHTML;
	// TODO: vyřešit stránky, kde se nečte článek (editace, přesouvání, …)
	return title;
}

// nastavit nadpis stránky
function setPagetitle(title) {
	var eHeading = findFirstHeading();
	if (eHeading === null) return;
	// TODO: vyřešit stránky, kde se nečte článek (editace, přesouvání, …)
	eHeading.innerHTML = title;
}

// získat (enkódované) lokální URL nějaké stránky (obdoba localurl:)
function getLocalURL(text) {
	text = text.substring(0, 1).toUpperCase() + text.substring(1);
	return "/wiki/" + encodeURIComponent(text.replace(/ /g,"_")).replace(/%2f/gi,"/");
}

// Appends a new tab.
// Převzato z [[commons:MediaWiki:Extra-tabs.js]].
function appendTab(url, name) {
  var na = document.createElement('a');
  na.setAttribute('href', url);

  var txt = document.createTextNode(name);
  na.appendChild(txt);

  var li = document.createElement('li');
  li.appendChild(na);

  // Grab the element we want to append the tab and append the tab to it.
  var c1 = document.getElementById(mw.config.get( 'skin' ) === 'vector' ? 'p-cactions' : 'column-one');
  if (!c1) return;
  var tabs = c1.getElementsByTagName('div')[0].getElementsByTagName('ul')[0];
  tabs.appendChild(li);
}

// Appends a new tab with JavaScript handler.
// Podle [[commons:MediaWiki:Extra-tabs.js]].
function appendJsTab(js, name) {
  var na = document.createElement('a');
  na.setAttribute('href', '#');
  na.setAttribute('onclick', js);

  var txt = document.createTextNode(name);
  na.appendChild(txt);

  var li = document.createElement('li');
  li.appendChild(na);

  // Grab the element we want to append the tab and append the tab to it.
  var c1 = document.getElementById(mw.config.get( 'skin' ) === 'vector' ? 'p-cactions' : 'column-one');
  if (!c1) return;
  var tabs = c1.getElementsByTagName('div')[0].getElementsByTagName('ul')[0];
  tabs.appendChild(li);
}

// Gets the article lemma, with the namespace and with sub pages.
// S úpravami převzato z [[commons:MediaWiki:Extra-tabs.js]].
function getPageName()
{
  // get the article link from the label 'ca-edit' out of the document text.
  var editlk = document.getElementById('ca-edit');

  // If a page is write protected (for that user, a sysop will always have 'ca-edit')
  // we need 'ca-viewsource' as 'ca-edit' does not exist there.
  if (editlk === null)
  {
    editlk = document.getElementById('ca-viewsource');
  }

  // editlk will still be null on a Special page.  Now we try the ca-article tab.
  if (editlk === null)
  {
    editlk = document.getElementById('ca-article');
  }

  editlk = editlk.getElementsByTagName('a')[0].href;

  // If we found the ca-edit or ca-viewsource tab, the link will have title=.
  // If we found the ca-article tab (on a Special page) it won't.
  if (editlk.indexOf('title=') >= 0)
  {
    // Cut everything up to "title=" from the start and everything past "&action=edit"
    // from the end.
    editlk = editlk.substring(editlk.indexOf('title=') + 6);
    editlk = decodeURIComponent(editlk.substring(0, editlk.indexOf('&')));
  }
  else
  {
    // Cut everything up to "/wiki/" from the start.
    editlk = decodeURIComponent(editlk.substring(editlk.indexOf('/wiki/') + 6));
  }

  return editlk;
}

// Uživatelské jméno aktuálně přihlášeného uživatele ("" pokud nikdo není přihlášen)
function getLoggedInUsername() {
	var el = document.getElementById('pt-userpage');
	if (!el) return "";

	return el.getElementsByTagName('a')[0].innerHTML;
}

// najít v editboxu
function findInEditbox(needle) {
  if (needle.length === 0) {
    alert("ook?");
    return;
  }
  var eEditBox = document.getElementById("wpTextbox1");
  if (eEditBox === null) return;
  var text = eEditBox.value;
  var ofsStart = eEditBox.selectionStart + 1;
  if (ofsStart >= text.length) ofsStart = 1;
  if (ofsStart > 0) {
    text = text.substring(ofsStart, 99999999);
  } else {
    ofsStart = 0;
  }
  var result = new RegExp(needle, "i").exec(text);
  if (result === null) {
    alert("bzzzt… wrong!");
  } else {
    eEditBox.selectionStart = ofsStart + result.index;
    eEditBox.selectionEnd = ofsStart + result.index + result[0].length;
    eEditBox.focus();
  }
}

// najít a nahradit v editboxu
function replaceInEditbox(needle, replacement) {
  if (needle.length === 0) {
    alert("ook?");
    return;
  }
  var eEditBox = document.getElementById("wpTextbox1");
  if (eEditBox === null) return;
  var text = eEditBox.value;
  var ofsStart = eEditBox.selectionStart;
  if (ofsStart >= text.length) ofsStart = 0;
  if (ofsStart < 0) ofsStart = 0;
  var ofsEnd = eEditBox.selectionEnd;
  if (ofsEnd < ofsStart) ofsEnd = ofsStart;
  if (ofsEnd == ofsStart) ofsEnd = 99999999;
  var reNeedle = new RegExp(needle, "gi");
  text = text.substring(ofsStart, ofsEnd);
  if (!text.match(reNeedle)) {
    alert("bzzzt… wrong!");
  } else {
    eEditBox.value = eEditBox.value.substring(0, ofsStart) + text.replace(reNeedle, replacement) + eEditBox.value.substring(ofsEnd, 99999999);
  }
}

/* </nowiki></pre></noinclude>
== Editační toolbary ==
;Příklad použití
 addOnloadHook(function() { addSummaryToolbar(["typo", "interwiki", "", "pahýl", "upravit", "", "experimenty", "experimenty2"]); });
;Funkce
: Přidá odkazy pro vložení prefabrikovaných shrnutí editaci kliknutím.
;Parametry
: Seznam nabízených shrnutí, prázdné řetězce vkládají řádkové zlomy

<noinclude><pre><nowiki> */
function addSummaryToolbar(items) {
	var elem = document.getElementById('editpage-copywarn');
	if (elem === null) return;
	if (document.getElementById('summarytools') !== null) return;
	var addedBox = "<div id='summaryTools' class='infobox' style='float:right; text-align:center'><h5>Shrnutí editace</h5>";
	var firstOnLine = true;
	for (var i = 0; i < items.length; i++) {
		if (items[i] === "") {
			addedBox += "<br />";
			firstOnLine = true;
		} else {
			if (!firstOnLine) addedBox += " &bull; ";
			firstOnLine = false;
			addedBox += "<a href=\"javascript:appendToWpSummary('" + items[i] + "');\">" + items[i] + "</a>";
		}
	}
	addedBox += "</div>";
	$(elem).prepend($(addedBox));
}
/* </nowiki></pre></noinclude>

== Lišta s odkazy ==
;Příklad použití:
 addOnloadHook(function() { addLinktoolbar("Poslední změny", [ ["Wikipedie:Žádost o práva správce", "RfA"], ["Wikipedie:Hlasování o smazání", "VfD"] ]); });
;Funkce:
: Vloží lištu s odkazy na další stránky
;Parametry:
* První parametr může být buď prázdný řetězec, nebo název stránky, na které se pouze mají tyto odkazy zobrazit.
* Druhý parametr obsahuje seznam dvojic stránka, zobrazený text odkazu.

Alternativně lze použít <code>addLinktoolbarEx</code>, který má dva další parametry: ID elementu, na začátek kterého se má lišta vložit (u základního použití se používá <code>bodyContent</code>), a nadpis lišty.

<noinclude><pre><nowiki> */
function addLinktoolbar(page, items) {
  addLinktoolbarEx(page, items, 'bodyContent', '<b>Odkazy:</b> ');
}

function addLinktoolbarEx(page, items, parent, caption) {
	if (page !== "" && getPagetitle() != page) return;
	var elem = document.getElementById(parent);
	if (elem === null) return;
	var addedToolbar = "<div id='linktoolbar' class='small'>" + caption;
	var firstOnLine = true;
	for (var i = 0; i < items.length; i++) {
		if (items[i] == "") {
			addedToolbar += "<br />";
			firstOnLine = true;
		} else {
			if (!firstOnLine) addedToolbar += " &bull; ";
			firstOnLine = false;
			addedToolbar += "<a href=\"" + getLocalURL(items[i][0]) + "\">" + items[i][1] + "</a>";
		}
	}
	addedToolbar += "</div>";
	$(elem).prepend($(addedToolbar));
}
/* </nowiki></pre></noinclude>

== Toolbar pro find&replace ==
;Použití
 addOnloadHook(addFindAndReplaceToolbar);
;Funkce
: Pod editační okno vloží lištu pro find&replace

<noinclude><pre><nowiki> */
function onFindClick(needle) {
  var elem = document.getElementById(needle);
  if (elem == null) return;
  findInEditbox(elem.value);
}

function onReplaceClick(needle, replacement) {
  var eNeedle = document.getElementById(needle);
  if (eNeedle == null) return;
  var eReplacement = document.getElementById(replacement);
  if (eReplacement == null) return;
  replaceInEditbox(eNeedle.value, eReplacement.value);
}

function addFindAndReplaceToolbar() {
  // TODO: Checkboxy pro regulární výrazy a case sensitivitu
  var elem = document.getElementById('editpage-copywarn');
  if (elem == null) return;
  if (document.getElementById('findTools') != null) return;
  var summary = document.getElementById('wpSummary');
  if (summary != null) summary.style.width = '60%';
  var addedBox = "<form id='findform' action='#'><div id='findTools' class='infobox' style='float:right; text-align:right'><label for='needle'>Najít: </label><input tabindex='8' type='text' value='' name='needle' id='needle' maxlength='200' size='20' /><br /><label for='replacement'>Nahradit za: </label><input tabindex='9' type='text' value='' name='replacement' id='replacement' maxlength='200' size='20' /><br /><center><button id='find' name='find' tabindex='10' accesskey='f' onclick='javascript:onFindClick(\"needle\");return false;'>Najít</button><button id='replace' name='replace' tabindex='11' accesskey='r' onclick='javascript:onReplaceClick(\"needle\", \"replacement\");return false;'>Nahradit</button></center></div></form>";
  $(elem).prepend($(addedBox));
}
/* </nowiki></pre></noinclude>

== Některé dodatečné záložky ==
;Použití
 addOnloadHook(addAdditionalTabs);
;Funkce
: Přidá některé užitečné záložky: U anonymů odkaz na WHOIS, u neexistujících a zamčených stránek odkaz na log

<noinclude><pre><nowiki> */
function addAdditionalTabs() {
  var title = mw.config.get( 'wgPageName' );
  var username = null;
  var addWhois = false, addLog = false;
  var ns = mw.config.get( 'wgCanonicalNamespace' )

  if (ns === 'User' || ns === 'User_talk') {
    // uživatelská stránka nebo diskuse (příp. podstránka)
    username = title;
    addWhois = true;
    addLog = true;
  } else if (ns === 'Special' && mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Contributions') {
    // příspěvky uživatele
    for (var i = 0; i < document.forms.length; ++i) {
      var form = document.forms[i];
      if (form.elements['target']) username = form.elements['target'].value;
      if (username) break;
    }
    if (!username) return;
    username = 'User:' + username;
    addWhois = true;
  } else if (ns !== 'Special') {
    // normální, nespeciální stránka
    if (!document.getElementById('ca-history') || !document.getElementById('ca-edit')) {
      // neexistující nebo zamčená stránka – přidat odkaz na log
      appendTab('/w/index.php?title=Special:Log&page=' + title, "Log");
    }
    return;
  } else return;

  username = username.substring(username.indexOf(':') + 1);
  username = username.replace(/\/.*$/, '');

  if (addLog) appendTab('/w/index.php?title=Special:Log&page=User:' + username, "Log");

  if (username.match(/([0-9]{1,3}\.){3}[0-9]{1,3}/)) {
    // anonymní uživatel
    if (addWhois) appendTab("http://toolserver.org/~chm/whois.php?ip=" + username, "Whois");
  }
}

/* </nowiki></pre></noinclude>

== Odkaz na aktuální verzi souboru ==
;Použití
 addOnloadHook(function() { imageReuploadLink(); });
;Funkce
: Na stránku [[Speciální:Upload]] přidá odkaz na aktuální verzi souboru (zejména užitečné při červených odkazech na smazaný soubor)

<noinclude><pre><nowiki> */
function imageReuploadLink() {
	if (mw.config.get( 'wgCanonicalNamespace' ) !== 'Special' || mw.config.get( 'wgCanonicalSpecialPageName' ) !== 'Upload') return;

	var editDest = document.getElementById('wpDestFile');
	if (!editDest) return;

	var link = document.createElement('a');
	link.setAttribute('id', 'uploadoriglink');
	link.setAttribute('href', editDest.value ? getLocalURL('File:' + editDest.value) : '#');
	editDest.parentNode.appendChild(link);

	var linkText = document.createTextNode('(aktuální verze)');
	link.appendChild(linkText);

	editDest.onchange = function() {
		var editDest = document.getElementById('wpDestFile');
		if (!editDest) return;

		var link = document.getElementById('uploadoriglink');
		if (!link) return;

		link.setAttribute('href', editDest.value ? getLocalURL('File:' + editDest.value) : '#');
	}
}
/* </nowiki></pre></noinclude>

== Odkaz na soubor na Commons ==
;Použití
 addOnloadHook(function() { addCommonsImageLink(); });
;Funkce
: Na stránku s popisem souboru přidá odkaz na stejně pojmenovaný soubor na Commons.

<noinclude><pre><nowiki> */
function addCommonsImageLink() {
	if (mw.config.get( 'wgNamespaceNumber' ) !== 6) return;
	appendTab('//commons.wikimedia.org' + getLocalURL('File:' + mw.config.get( 'wgTitle' )), 'Commons');
}
/* </nowiki></pre></noinclude>

== Varování při editaci cizí uživatelské stránky ==
;Použití
 addOnloadHook(function() { warnOnEditingOtherUserpage(); });
;Funkce
: Při editaci cizí uživatelské stránky (namísto jeho diskuse) zobrazí upozornění.

<noinclude><pre><nowiki> */
function warnOnEditingOtherUserpage() {
	if (!document.getElementById('wpSave')) return;

	if (mw.config.get( 'wgCanonicalNamespace' ) !== 'User') return;
	var title = mw.config.get( 'wgTitle' );

	var myusername = getLoggedInUsername();

	if (title != myusername && title.indexOf('/') < 0)
	{
		if (document.getElementById('editingotheruserpagewarning')) return

		var ref = document.getElementById('wikiPreview');
		if (!ref)
		{
			alert('Editujete cizí uživatelskou stránku!');
			return;
		}

		var div = document.createElement('div');
		div.id = 'editingotheruserpagewarning';
		div.className = 'editwarning';

		var strong = document.createElement('strong');
		div.appendChild(strong);
		strong.appendChild(document.createTextNode('POZNÁMKA:'));

		div.appendChild(document.createTextNode(' Editujete uživatelskou stránku jiného uživatele. Pokud tomuto uživateli chcete něco sdělit, použijte '));

		var link = document.createElement('a');
		link.href = getLocalURL('User_talk:' + title) + '?action=edit&section=new';
		div.appendChild(link);
		link.appendChild(document.createTextNode('diskusní stránku'));

		div.appendChild(document.createTextNode('.'));

		ref.parentNode.insertBefore(div, ref);
	}
}
/* </nowiki></pre></noinclude>

== Odkazy na jiné Wikipedie při chybějícím interwiki ==
;Použití
 addOnloadHook(function() { showDefaultInterwiki(['cs', 'en']); });
;Funkce
: U stránky, která nemá interwiki, zobrazí odkazy na stejně pojmenované stránky na některých dalších Wikipediích
;Parametry
: Buď seznam jazykových kódů Wikipedií, nebo <code>null</code> pro nějaký implicitní.

<noinclude><pre><nowiki> */
function ShowDefaultInterwiki(langs) {
	if (!langs || langs.length == 0)
	{
		langs = ['cs', 'en', 'de', 'sk', 'pl', 'fr'];
	}

	// stránky, které už interwiki mají
	var langBox = document.getElementById('p-lang');
	if (!langBox || document.getElementById('wbc-linkToItem-link')) return;

	// bez editací, historie atd., s výjimkou situace, kdy stránka dosud ani neexistuje (a ošetřit NS MediaWiki)
	if (!document.getElementById('t-cite') && document.getElementById('ca-history') && mw.config.get( 'wgNamespaceNumber' ) !== 8) return;

	if (!langBox) {
		langBox = document.createElement('div');
		langBox.id = 'p-lang';
		langBox.className = mw.config.get( 'skin' ) === 'vector' ? 'portal' : 'portlet';
		var caption = document.createElement('h5');
		caption.appendChild(document.createTextNode('totéž jinde'));
		langBox.appendChild(caption);
	}
	var langBody = document.createElement('div');
	langBody.className = mw.config.get( 'skin' ) === 'vector' ? 'body' : 'pBody';
	langBox.appendChild(langBody);
	var langList = document.createElement('ul');
	langBody.appendChild(langList);
	for (var i = 0; i < langs.length; ++i)
	{
		var lang = langs[i];
		if (lang == mw.config.get( 'wgContentLanguage' )) continue;
		var item = document.createElement('li');
		item.className = 'interwiki-' + lang;
		langList.appendChild(item);
		var link = document.createElement('a');
		var ns = mw.config.get( 'wgCanonicalNamespace' );
		if (ns.length > 0) ns += ':';
		var title = mw.config.get( 'wgTitle' );
		if (ns === 'Special') title = mw.config.get( 'wgCanonicalSpecialPageName' );
		link.href = '//' + lang + '.wikipedia.org' + getLocalURL(ns + title);
		link.appendChild(document.createTextNode(lang));
		item.appendChild(link);
	}
	var columnOne = document.getElementById(mw.config.get( 'skin' ) === 'vector' ? 'mw-panel' : 'column-one');
	columnOne.appendChild(langBox);
}

/* </nowiki></pre></noinclude>

== Odkaz na index ==
;Použití
 addOnloadHook(function() { addIndexLink(); });
;Funkce
: Na každou stránku přidá odkaz do stránky [[Speciální:Allpages]] zobrazující okolí aktuální stránky.

<noinclude><pre><nowiki> */
function addIndexLink() {
	if (mw.config.get('wgCanonicalNamespace') === "Special") return;
	var pageName = mw.config.get( 'wgPageName' );
	appendTab(getLocalURL('Special:Allpages/' + pageName.substring(0, pageName.length - 1)), 'Index');
}
/* </nowiki></pre></noinclude>

== Uživatelsky vybrané interwiki ==
;Příklad použití
 addOnloadHook(function() { reorderInterwiki(['en', 'de', 'sk'], false); });
;Funkce
: Přeuspořádá interwiki odkazy v tabulce „v jiných jazycích“ tak, aby vybrané jazyky byly navrchu a případně skryje odkazy na ostatní jazyky (řízeno druhým parametrem: <code>true</code> pokud se mají zobrazovat ''jen'' vypsané jazyky, <code>false</code> pokud se mají zobrazovat i ostatní a vybrané se mají jen zobrazovat navrchu).

<noinclude><pre><nowiki> */
function reorderInterwiki(priorityLanguages, removeOthers)
{
	langBox = document.getElementById('p-lang');
	if (!langBox) return;

	langList = langBox.getElementsByTagName('ul');
	if (!langList) return;
	langList = langList[0];
	langItems = langList.getElementsByTagName('li');

	priorityList = new Array();
	for (var l = 0; l < priorityLanguages.length; l++)
	{
		var reLanguageMatch = new RegExp('(^|\\s)interwiki-' + priorityLanguages[l] + '(\\s|$)');
		for (var i = 0; i < langItems.length; i++)
		{
			var item = langItems[i];
			if (reLanguageMatch.test(item.className))
			{
				langList.removeChild(item);
				priorityList.push(item);
				break;
			}
		}
	}

	if (removeOthers)
	{
		while (langList.hasChildNodes())
		{
			langList.removeChild(langList.childNodes[0]);
		}
	}

	if (langList.hasChildNodes())
	{
		var firstNode = langList.childNodes[0];
		for (var i = 0; i < priorityList.length; i++)
		{
			langList.insertBefore(priorityList[i], firstNode);
		}
	}
	else
	{
		for (var i = 0; i < priorityList.length; i++)
		{
			langList.appendChild(priorityList[i]);
		}
	}
}

// </nowiki></pre></noinclude>