MediaWiki:Common.js — различия между версиями

Материал из Ролевая энциклопедии
Перейти к: навигация, поиск
(возможно, так?)
(решение с Википереводов)
Строка 1: Строка 1:
 
/* Размещённый здесь код JavaScript будет загружен всем пользователям при обращении к какой-либо странице */
 
/* Размещённый здесь код JavaScript будет загружен всем пользователям при обращении к какой-либо странице */
  
//кнопка викификатора
+
function addOnloadHook(callback)
if (wgAction == 'edit' || wgAction == 'submit') {
+
{
mw.loader.load('//ru.wikipedia.org/w/index.php?title=MediaWiki:Wikificator.js&action=raw&ctype=text/javascript')
+
$(callback)
mwCustomEditButtons['wikif']  = [function(){Wikify()}, '//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png', 'Викификатор — автоматический обработчик текста']
 
if ( typeof $j != 'undefined' && typeof $j.fn.wikiEditor != 'undefined' ) {
 
  $j( function() {$j( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {'section': 'main','group': 'format','tools': { 'wikif': {
 
    label: 'Викификатор', type: 'button', icon: '//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png',
 
    action: { type: 'callback', execute: function(){Wikify()} }}}});});
 
 
}
 
}
 +
 +
/*WikiEditor/Викификатор*/
 +
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 ) {
 +
        mw.loader.load( 'http://trans.rpground.ru/index.php?title=MediaWiki:Wikificator.js&action=raw&ctype=text/javascript' );
 +
}
 +
 +
var customizeToolbar = function() {
 +
$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
 +
        'section': 'main',
 +
        'group': 'format',
 +
        'tools': {
 +
                'wikify': {
 +
                        label: 'Викификатор',
 +
                        type: 'button',
 +
                        icon: '//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png',
 +
                            action: {
 +
                                  type: 'callback',
 +
                                      execute: function(context){
 +
                                              Wikify();
 +
                                      }
 +
                            }
 +
                }
 +
        }
 +
} );
 +
};
 +
 +
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 ) {
 +
        mw.loader.using( 'user.options', function () {
 +
                if ( mw.user.options.get('usebetatoolbar') ) {
 +
                        mw.loader.using( 'ext.wikiEditor.toolbar', function () {
 +
                                $(document).ready( customizeToolbar );
 +
                        } );
 +
                }
 +
        } );
 +
}
 +
 +
function AddLegacyButton(imgsrc, title, onclick){
 +
var toolbar = document.getElementById('toolbar')
 +
var textbox = document.getElementById('wpTextbox1')
 +
if (!textbox || !toolbar) return
 +
var i = document.createElement('img')
 +
i.src = imgsrc
 +
i.alt = i.title = title
 +
i.onclick = onclick
 +
i.style.cursor = 'pointer'
 +
toolbar.appendChild(i)
 +
}
 +
 +
function addWikifyButton()
 +
{
 +
AddLegacyButton('//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png', 'Викификатор', function() { Wikify() } )
 +
}
 +
if (wgAction == 'edit' || wgAction == 'submit'){
 +
addOnloadHook(addWikifyButton)
 
}
 
}
  
Строка 169: Строка 218:
 
})();
 
})();
  
function addWikifButton() {
 
var toolbar = document.getElementById('toolbar')
 
if (!toolbar) return
 
var i = document.createElement('img')
 
i.src = 'http://upload.wikimedia.org/wikisource/ru/d/d1/Button-wikifikator.png'
 
i.alt = i.title = 'викификатор'
 
i.onclick = Wikify
 
i.style.cursor = 'pointer'
 
toolbar.appendChild(i)
 
}
 
if (wgAction == 'edit' || wgAction == 'submit') {
 
mw.loader.load('http://wiki.rpgverse.ru/index.php?title=MediaWiki:Wikificator.js&action=raw&ctype=text/javascript')
 
addOnloadHook(addWikifButton)
 
}
 
  
 
//перемещение ссылок "править" влево, к заголовку секции, для борьбы с багом движка
 
//перемещение ссылок "править" влево, к заголовку секции, для борьбы с багом движка

Версия 10:34, 15 февраля 2021

/* Размещённый здесь код JavaScript будет загружен всем пользователям при обращении к какой-либо странице */

function addOnloadHook(callback)
{
 $(callback)
}

/*WikiEditor/Викификатор*/
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 ) {
        mw.loader.load( 'http://trans.rpground.ru/index.php?title=MediaWiki:Wikificator.js&action=raw&ctype=text/javascript' );
}
 
var customizeToolbar = function() {
$( '#wpTextbox1' ).wikiEditor( 'addToToolbar', {
        'section': 'main',
        'group': 'format',
        'tools': {
                'wikify': {
                        label: 'Викификатор',
                        type: 'button',
                        icon: '//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png',
                             action: {
                                  type: 'callback',
                                       execute: function(context){
                                              Wikify();
                                       } 
                             }
                }
        }
} );
};
 
if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) !== -1 ) {
        mw.loader.using( 'user.options', function () {
                if ( mw.user.options.get('usebetatoolbar') ) {
                        mw.loader.using( 'ext.wikiEditor.toolbar', function () {
                                $(document).ready( customizeToolbar );
                        } );
                }
        } );
}

function AddLegacyButton(imgsrc, title, onclick){
 var toolbar = document.getElementById('toolbar')
 var textbox = document.getElementById('wpTextbox1')
 if (!textbox || !toolbar) return
 var i = document.createElement('img')
 i.src = imgsrc
 i.alt = i.title = title
 i.onclick = onclick
 i.style.cursor = 'pointer'
 toolbar.appendChild(i)
}

function addWikifyButton()
{
AddLegacyButton('//upload.wikimedia.org/wikipedia/commons/0/06/Wikify-toolbutton.png', 'Викификатор', function() { Wikify() } )
}
if (wgAction == 'edit' || wgAction == 'submit'){
 addOnloadHook(addWikifyButton)
}

var auto_comment = 0;

if (document.URL.indexOf("action=edit") > 0 || document.URL.indexOf("action=submit") > 0)
{
       if (wgCanonicalNamespace != "Special")
       {
               document.write('<script type="text/javascript" src="/w/index.php' +
               '?title=MediaWiki:Onlyifediting.js&action=raw' +
               '&ctype=text/javascript&dontcountme=s"></script>');
       }
}

//Кнопки быстрого описания правки
 
//список кнопок
function SummaryButtons(){
 var wpSummary = document.getElementById('wpSummary')
 if (!wpSummary || (wpSummary.form.wpSection && wpSummary.form.wpSection.value == 'new')) return
 wpSummaryBtn = document.createElement('span') //global var
 wpSummaryBtn.id = 'userSummaryButtonsA'

// +Рекомендация
 var wpSummaryBtnRec = document.createElement('i');
 wpSummaryBtnRec.appendChild(document.createTextNode('Пожалуйста, если вы не торопитесь, опишите вашу правку подробно: например, не «дополнение», а «+персонажи».'));
 wpSummaryBtnRec.appendChild(document.createElement('br'));
 wpSummaryBtn.appendChild(wpSummaryBtnRec);

 wpSummary.parentNode.insertBefore(wpSummaryBtn, wpSummary.nextSibling);
 wpSummary.parentNode.insertBefore(document.createElement('br'), wpSummary.nextSibling);
 addSumButton('новости', 'новости', 'Учтены последние новости');
 addSumButton('викификация', 'викификация', 'Произведена викификация');
 addSumButton('правила', 'правила', 'Добавлены сведения о правилах');
 addSumButton('сеттинг', 'сеттинг', 'Добавлены сведения о сеттинге');
 addSumButton('оформление', 'оформление', 'Оформление');
 addSumButton('стиль', 'стилевые правки', 'Стилевые правки');
 addSumButton('грамматика', 'грамматика', 'Поправлена орфография/пунктуация');
 addSumButton('категории', 'категоризация', 'Изменены категории');
 addSumButton('шаблон', 'шаблон', 'Добавлен / изменён шаблон');
 addSumButton('дополнение', 'дополнение', 'Добавлены новые сведения');
 addSumButton('иллюстрация', 'иллюстрация', 'Размещена иллюстрация');
 addSumButton('обновление', 'обновление сведений', 'Обновлены устаревшие сведения');
 addSumButton('разметка', 'правка разметки', 'Изменение разметки');
}
 
//код вставки кнопок быстрого описания
function addSumButton(name, text, title) {
 var btn = document.createElement('a');
 btn.appendChild(document.createTextNode(name));
 btn.title = title;
 btn.onclick = function(){insertSummary(text)};
 wpSummaryBtn.appendChild(btn);
 wpSummaryBtn.appendChild(document.createTextNode(' '));
}
 
//код вставки описания
function insertSummary(text) {
 var wpSummary = document.getElementById('wpSummary')
 if (wpSummary.value.indexOf(text) != -1) return 
 if (wpSummary.value.match(/[^,; \/]$/)) wpSummary.value += ','
 if (wpSummary.value.match(/[^ ]$/)) wpSummary.value += ' '
 wpSummary.value += text
}

//вызов функции вставки кнопок быстрого описания правки при загрузке страницы
addOnloadHook(SummaryButtons)

/** Collapsible tables *********************************************************
 *
 *  Description: Allows tables to be collapsed, showing only the header. See
 *               http://www.mediawiki.org/wiki/Manual:Collapsible_tables.
 *  Maintainers: [[**MAINTAINERS**]]
 */
var autoCollapse = 2;
var collapseCaption = 'скрыть';
var expandCaption = 'показать';
 
function collapseTable( tableIndex ) {
	var Button = document.getElementById( 'collapseButton' + tableIndex );
	var Table = document.getElementById( 'collapsibleTable' + tableIndex );
 
	if ( !Table || !Button ) {
		return false;
	}
 
	var Rows = Table.rows;
 
	if ( Button.firstChild.data == collapseCaption ) {
		for ( var i = 1; i < Rows.length; i++ ) {
			Rows[i].style.display = 'none';
		}
		Button.firstChild.data = expandCaption;
	} else {
		for ( var i = 1; i < Rows.length; i++ ) {
			Rows[i].style.display = Rows[0].style.display;
		}
		Button.firstChild.data = collapseCaption;
	}
}
 
function createCollapseButtons() {
	var tableIndex = 0;
	var NavigationBoxes = new Object();
	var Tables = document.getElementsByTagName( 'table' );
 
	for ( var i = 0; i < Tables.length; i++ ) {
		if ( hasClass( Tables[i], 'collapsible' ) ) {
			/* only add button and increment count if there is a header row to work with */
			var HeaderRow = Tables[i].getElementsByTagName( 'tr' )[0];
			if( !HeaderRow ) continue;
			var Header = HeaderRow.getElementsByTagName( 'th' )[0];
			if( !Header ) continue;
 
			NavigationBoxes[tableIndex] = Tables[i];
			Tables[i].setAttribute( 'id', 'collapsibleTable' + tableIndex );
 
			var Button     = document.createElement( 'span' );
			var ButtonLink = document.createElement( 'a' );
			var ButtonText = document.createTextNode( collapseCaption );
 
			Button.className = 'collapseButton'; // Styles are declared in MediaWiki:Common.css
 
			ButtonLink.style.color = Header.style.color;
			ButtonLink.setAttribute( 'id', 'collapseButton' + tableIndex );
			ButtonLink.setAttribute( 'href', "javascript:collapseTable(" + tableIndex + ");" );
			ButtonLink.appendChild( ButtonText );
 
			Button.appendChild( document.createTextNode( '[' ) );
			Button.appendChild( ButtonLink );
			Button.appendChild( document.createTextNode( ']' ) );
 
			Header.insertBefore( Button, Header.childNodes[0] );
			tableIndex++;
		}
	}
 
	for ( var i = 0;  i < tableIndex; i++ ) {
		if ( hasClass( NavigationBoxes[i], 'collapsed' ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], 'autocollapse' ) ) ) {
			collapseTable( i );
		}
	}
}
 
addOnloadHook( createCollapseButtons );
 
/** Test if an element has a certain class **************************************
 *
 * Description: Uses regular expressions and caching for better performance.
 * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
 */
 
var hasClass = (function() {
	var reCache = {};
	return function( element, className ) {
		return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
	};
})();


//перемещение ссылок "править" влево, к заголовку секции, для борьбы с багом движка
addOnloadHook(function() {
    if (typeof oldEditsectionLinks != 'undefined' && oldEditsectionLinks)   return;
    var spans = document.getElementsByTagName("span");
    for (var i=0; i<spans.length; i++) {
        var span = spans[i];
        if (span.className != "editsection")    continue;
        span.style.fontSize = "x-small";
        span.style.fontWeight = "normal";
        span.style.styleFloat = "none"; // IE-Fix für die folgende Zeile
        span.style.cssFloat = "none";
        span.style.marginLeft = "0px";
        span.parentNode.appendChild(document.createTextNode(" "));
        span.parentNode.appendChild(span);
    }
});

// Основано на RPG Wikia
function RPG_Wikia()
{
 var $wikia=!(document.getElementById('originalRPGverse') || document.getElementById('other_source'));
 if ($wikia)
 {
  var $target=document.getElementById('footer-info-copyright');
  if ($target)
  {
   var $add=' Данный текст основан на материале <a href=\"http://ru.rpg.wikia.com/wiki/'+wgPageName+'\">RPG Wikia</a>. См. <a href=\"http://wiki.rpgverse.ru/wiki/RPG_Wiki:%D0%97%D0%B5%D1%80%D0%BA%D0%B0%D0%BB%D0%BE\">RPG:Зеркало</a>.';
   $target.innerHTML+=$add;
  }
 }
}

if
(
   (wgAction=='view' /* просмотр, не редактирование */) &&
   ( (wgNamespaceNumber==0 /* статьи */ ) || (wgNamespaceNumber==4 /* страницы проекта */) ) &&
   (document.getElementById('mw-content-text').firstChild.className!='redirectMsg') /* кроме перенаправлений */
)
{
 addOnloadHook(RPG_Wikia);
}

function addDefaultContext()
{
 var $container=document.getElementById('mw-content-text');
 if (!$container) return; 

 var $temp=$container.firstChild;
 if ( ($temp) && ($temp.className=="redirectMsg") ) return;

 var $context=document.createElement('div');
 $context.innerHTML='<div id="article_context" style="float:right; clear:right;"><b>Контекст</b>: <div style="display:inline-block; text-align:center;background-color:moccasin; border-width:1px; border-color: orangered; border-style:double; padding-left:3px; padding-right:3px"><a href="http://wiki.rpgverse.ru/wiki/%D0%9A%D0%B0%D1%82%D0%B5%D0%B3%D0%BE%D1%80%D0%B8%D1%8F:%D0%9A%D0%BE%D0%BD%D1%82%D0%B5%D0%BA%D1%81%D1%82:_%D0%BD%D0%B0%D1%81%D1%82%D0%BE%D0%BB%D1%8C%D0%BD%D1%8B%D0%B5_%D1%80%D0%BE%D0%BB%D0%B5%D0%B2%D1%8B%D0%B5_%D0%B8%D0%B3%D1%80%D1%8B" title="Категория:Контекст: настольные ролевые игры"><span style="color:brown">Настольные РПГ</span></a></div></div><div style="clear: both;"></div>';
 $container.insertBefore($context, $container.firstChild);
}

if ( (wgNamespaceNumber==0) && (wgAction!='edit') && (!document.getElementById('article_context')) )
{
 addOnloadHook(addDefaultContext);
}

// Google Analytics
var _gaq = _gaq || [];   _gaq.push(['_setAccount', 'UA-38515594-1']);   _gaq.push(['_setDomainName', 'rpgverse.ru']);   _gaq.push(['_trackPageview']);    (function() {     var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;     ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';     var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);   })();