Diqqət! 4 aprel 2024-cü il tarixdən saytın yeni versiyası sheki.org domenində fəaliyyət göstərir. Bu köhnə versiyadır və yenilənməsi məhdudlaşdırılıb. Lakin 6 yanvar 2025-ci il tarixədək bu vəziyyətdə internetdə qalacaqdır...

"MediaWiki:Common.js" səhifəsinin versiyaları arasındakı fərqlər

Şəki Ensiklopediyası səhifəsi
Jump to navigation Jump to search
(297 dəyişikliyi WikiSysop (Müzakirə) tərəfindən geri alındı.)
Teq: Undo
Sətir 1: Sətir 1:
/* Burada istifadəçilərin hamısı üçün bütün səhifələrdə istənilən JavaScript yüklənəcək */
+
/**
// Switch language variants of messages (from zh)
+
* Код MediaWiki:Common.js безусловно загружается всем пользователям на всех страницах. Во избежание
function wgULS(latn,arab){
+
* отправки лишних запросов по возможности не используйте здесь mw.loader.using с модулями, которые
        //
+
* не загружаются по умолчанию (см.
        az=latn||arab;
+
* [[Обсуждение MediaWiki:Common.js#Список модулей, загружаемых по умолчанию]]). В таком случае
        az=az;
+
* лучше создать скрытый гаджет, загружаемый по умолчанию, и добавить ему нужные модули в качестве
        latn=latn;
+
* зависимостей.
        arab=arab;
+
*/
        switch(mw.config.get('wgUserLanguage')){
 
                case "az": return ku;
 
                case "az-arab": return arab;
 
                case "az-latn": return latn;
 
                default: return "";
 
        }
 
}
 
  
/** Skript für Vorlage:Galerie */
+
/**
$(function() {
+
  * Локальная функция загрузки скриптов с поддержкой указания проекта
  if (document.URL.match(/printable/g)) return;
+
  */
   
+
var importScript_ = importScript;
  function toggleImageFunction(group, remindex, shwindex) {
+
importScript = function ( page, proj ) {
    return function() {
+
if ( !proj ) {
      document.getElementById("ImageGroupsGr" + group + "Im" + remindex).style.display = "none";
+
importScript_( page );
      document.getElementById("ImageGroupsGr" + group + "Im" + shwindex).style.display = "block";
+
} else {
      return false;
+
if ( proj.indexOf( '.' ) === -1 ) {
    };
+
proj += '.wikipedia.org';
  }
+
}
+
mw.loader.using( 'mediawiki.util' ).done( function () {
  var divs = document.getElementsByTagName("div");
+
mw.loader.load( '//' + proj + '/w/index.php?title=' + mw.util.wikiUrlencode( page ) +
  var i = 0, j = 0;
+
'&action=raw&ctype=text/javascript' );
  var units, search;
+
} );
  var currentimage;
+
}
  var UnitNode;
+
};
  for (i = 0; i < divs.length; i++) {
 
    if (divs[i].className !== "ImageGroup") { continue; }
 
    UnitNode = undefined;
 
    search = divs[i].getElementsByTagName("div");
 
    for (j = 0; j < search.length; j++) {
 
      if (search[j].className !== "ImageGroupUnits") { continue; }
 
      UnitNode=search[j];
 
      break;
 
    }
 
    if (UnitNode === undefined) { continue; }
 
    units = [];
 
    for (j = 0 ; j < UnitNode.childNodes.length ; j++ ) {
 
      var temp = UnitNode.childNodes[j];
 
      if (temp.className === "center") { units.push(temp); }
 
    }
 
    var rightlink;
 
    var commentText;
 
    for (j = 0; j < units.length; j++) {
 
      currentimage = units[j];
 
      currentimage.id = "ImageGroupsGr" + i + "Im" + j;
 
      var leftlink = document.createElement("a");
 
      if (commentText !== undefined) {
 
        leftlink.setAttribute("title", commentText);
 
      }
 
      var comment;
 
      if (typeof(currentimage.getAttribute("title")) !== "string") {
 
        commentText = (j+1) + "/" + units.length;
 
        comment = document.createElement("tt").appendChild(document.createTextNode("("+ commentText + ")"));
 
      }
 
      else {
 
        commentText = currentimage.getAttribute("title");
 
        comment = document.createElement("span").appendChild(document.createTextNode(commentText));
 
        currentimage.removeAttribute("title");
 
      }
 
      if(rightlink !== undefined) {
 
        rightlink.setAttribute("title", commentText);
 
      }
 
      var imghead = document.createElement("div");
 
      rightlink = document.createElement("a");
 
      if (j !== 0) {
 
        leftlink.href = "#";
 
        leftlink.onclick = toggleImageFunction(i, j, j-1);
 
        leftlink.appendChild(document.createTextNode("◀"));
 
      }
 
      if (j != units.length - 1) {
 
        rightlink.href = "#";
 
        rightlink.onclick = toggleImageFunction(i, j, j+1);
 
        rightlink.appendChild(document.createTextNode("▶"));
 
      }
 
      imghead.style.fontSize = "110%";
 
      imghead.style.fontweight = "bold";
 
      imghead.appendChild(leftlink);
 
      imghead.appendChild(document.createTextNode("\xA0"));
 
      imghead.appendChild(comment);
 
      imghead.appendChild(document.createTextNode("\xA0"));
 
      imghead.appendChild(rightlink);
 
      if (units.length > 1) {
 
        currentimage.insertBefore(imghead,currentimage.childNodes[0]);
 
      }
 
      if (j !== 0) {
 
        currentimage.style.display = "none";
 
      }
 
    }
 
  }
 
});
 
  
/* Test if an element has a certain class **************************************
+
/**
  *
+
* Часто те или иные манипуляции со страницей нужно выполнить как можно раньше, но нет гарантии, что
  * Description: Uses regular expressions and caching for better performance.
+
* к моменту выполнения кода нужный участок DOM готов, а событие полной загрузки страницы происходит
  * Maintainers: [[User:Mike Dillon]], [[User:R. Koot]], [[User:SG]]
+
* слишком поздно. В этой функции проверяется наличие элемента $testElement и в случае успеха
  */
+
* функция-колбэк выполняется, иначе же её выполнение поручается другой функции. Если элемент
   
+
* в $testElement имеет содержимое, правильнее указать следующий за ним элемент, чтобы быть
  var hasClass = (function () {
+
* уверенным, что он загрузился до конца. Имейте в виду, что разные скины часто используют разные
    var reCache = {};
+
  * названия классов и идентификаторов.
    return function (element, className) {
+
  */
        return (reCache[className] ? reCache[className] : (reCache[className] = new RegExp("(?:\\s|^)" + className + "(?:\\s|$)"))).test(element.className);
+
function runAsEarlyAsPossible( callback, $testElement, func ) {
    };
+
func = func || $;
})();
+
$testElement = $testElement || $( '#footer' );
  
 +
if ( $testElement.length ) {
 +
callback();
 +
} else {
 +
func( callback );
 +
}
 +
}
  
/** Interwiki links to featured articles ***************************************
+
/**
  *
+
* Настройка обработки «е» и «ё» при сортировке в таблицах
  * Description: Highlights interwiki links to featured articles (or
+
  */
  *               equivalents) by changing the bullet before the interwiki link
+
mw.config.set( 'tableSorterCollation', { 'Ё': 'Е', 'ё': 'е' } );
  *              into a star.
 
  *  Maintainers: [[User:R. Koot]]
 
  */
 
 
//Messages
 
var listFA = {
 
fa:'Bu başqa dildəki seçilmiş məqalədir',
 
fl:'Bu başqa dildəki seçilmiş siyahıdır',
 
ga:'Bu başqa dildəki yaxşı məqalədir'};
 
  
var zeroSectionTip = 'Girişi redaktə et';
+
/**
 +
* Строки. Иноязычный интерфейс предположительно включают весьма редко, поэтому раздувать этот
 +
* список не стоит. При необходимости добавить много сообщений во много языков можно использовать
 +
* механизм системных сообщений (= страниц в пространстве MediaWiki, у которых могут быть суффиксы
 +
* типа /en). См., как их получение реализовано в MediaWiki:Gadget-sidebarRelated.js.
 +
*/
 +
var expandCaption, collapseCaption, zeroSectionTip;
 +
if ( mw.config.get( 'wgUserLanguage' ) === 'en' ) {
 +
expandCaption = 'show';
 +
collapseCaption = 'hide';
 +
zeroSectionTip = 'Edit lead section';
 +
} else {
 +
expandCaption = 'показать';
 +
collapseCaption = 'скрыть';
 +
zeroSectionTip = 'Править преамбулу';
 +
}
  
var NavigationBarHide = '[bağla]';
+
/**
var NavigationBarShow = '[bax]';
+
* [[ВП:Сворачиваемые блоки]]
var NavigationBarShowDefault = 2;
+
  */
 
+
// Число раскрытых по умолчанию навигационных (и не только) шаблонов, если им задан параметр
function LinkFA(){
+
// autocollapse. Участники могут переопределять это значение в личных JS.
  var ll, s;
+
var NavigationBarShowDefault;
$('#p-lang li').each( function(i, iw){
+
if ( typeof NavigationBarShowDefault === 'undefined' ) {
  ll = iw.className.replace(/^.*?(interwiki-)/, '$1').replace(/\s.*$/, '') + '-';
+
NavigationBarShowDefault = 1;
  for( var s in listFA )
 
    if( document.getElementById(ll + s) && !$( iw ).hasClass( 'badge-featuredarticle' ) && !$( iw ).hasClass( 'badge-goodarticle' ) && !$( iw ).hasClass( 'badge-featuredlist' ) )
 
      $( iw )
 
        .addClass( s.toUpperCase() )
 
        .attr( 'title',  listFA[s] + textFA );
 
});
 
 
}
 
}
  
 +
// table.collapsible
 +
function collapsibleTables( $content ) {
 +
var $btn,
 +
$a,
 +
tblIdx = 0,
 +
navboxCount = 0,
 +
notNavboxCount = 0,
 +
colTables = [],
 +
$Tables = $content.find( 'table' );
  
function editZeroSection(){
+
$Tables.each( function ( i, table ) {
if( !mw.config.get('wgArticleId') ) return;
+
if ( $( table ).hasClass( 'collapsible' ) ) {
mw.util.$content.find('h2')
+
var $table = $( this ),
.children('.mw-editsection:first')
+
$row = $table.find( 'tr' ).first(),
.clone().prependTo('#bodyContent')
+
$cell = $row.find( 'th' ).first();
.css('float','right')
+
if ( !$cell.length ) {
.find('a')
+
return;
.each(function(index) {
+
}
$( this ).attr('title', zeroSectionTip);
+
$table.attr( 'id', 'collapsibleTable' + tblIdx );
if ($( this ).attr('class') === "mw-editsection-visualeditor" ) {
+
$btn = $( '<span>' ).addClass( 'collapseButton' );
$( this ).attr('href', mw.config.get('wgScript') + '?title='+mw.util.wikiUrlencode(mw.config.get('wgPageName')) + '&veaction=edit&vesection=0');
+
$a = $( '<a>' )
} else {  
+
.attr( 'id', 'collapseButton' + tblIdx )
$( this ).attr('href', mw.config.get('wgScript') + '?title='+mw.util.wikiUrlencode(mw.config.get('wgPageName')) + '&action=edit&section=0');
+
.attr( 'href', 'javascript:collapseTable(' + tblIdx + ');' )
}  
+
// Изменяем цвет ссылки, только если цвет текста в навбоксе нестандартный
});
+
.css( 'color', $cell.css( 'color' ) === $( '.mw-body' ).css( 'color' ) ? 'auto' :
 +
$cell.css( 'color' ) )
 +
.text( collapseCaption );
 +
$btn
 +
.append( '[' )
 +
.append( $a )
 +
.append( ']' );
 +
if ( $cell.contents().length ) {
 +
$btn.insertBefore( $cell.contents().first() );
 +
} else {
 +
$btn.appendTo( $cell );
 +
}
 +
// hasClass( 'navbox' ) — временное решение для навшаблонов, ещё не переведённых
 +
// на {{Навигационная таблица}} (также ниже)
 +
if ( $table.hasClass( 'navbox-inner' ) || $table.hasClass( 'navbox' ) ) {
 +
navboxCount++;
 +
} else {
 +
notNavboxCount++;
 +
}
 +
colTables[tblIdx++] = $table;
 +
}
 +
} );
 +
for ( var i = 0; i < tblIdx; i++ ) {
 +
if ( colTables[i].hasClass( 'collapsed' ) ||
 +
( colTables[i].hasClass( 'autocollapse' ) &&
 +
( ( ( colTables[i].hasClass( 'navbox-inner' ) || colTables[i].hasClass( 'navbox' ) ) &&
 +
navboxCount > NavigationBarShowDefault ) ||
 +
( !( colTables[i].hasClass( 'navbox-inner' ) || colTables[i].hasClass( 'navbox' ) ) &&
 +
notNavboxCount > NavigationBarShowDefault ) ) ) )
 +
{
 +
collapseTable( i );
 +
}
 +
}
 
}
 
}
  
 +
mw.hook( 'wikipage.content' ).add( collapsibleTables );
  
/** Collapsible tables *********************************************************
+
function collapseTable( idx ) {
  *
+
var $table = $( '#collapsibleTable' + idx ),
  *  Description: Allows tables to be collapsed, showing only the header. See
+
$rows = $table.children().children( 'tr' ),
  *              [[Wikipedia:NavFrame]].
+
$btn = $( '#collapseButton' + idx );
  *  Maintainers: [[User:R. Koot]]
+
if ( !$table.length || !$rows.length || !$btn.length ) {
  */
+
return false;
+
}
var autoCollapse = 2;
 
var collapseCaption = "bağla";
 
var expandCaption = "bax";
 
 
function collapseTable( tableIndex )
 
{
 
    var Button = document.getElementById( "collapseButton" + tableIndex );
 
    var Table = document.getElementById( "collapsibleTable" + tableIndex );
 
    var i;
 
    if ( !Table || !Button ) {
 
        return false;
 
    }
 
 
    var Rows = Table.getElementsByTagName( "tr" );
 
 
    if ( Button.firstChild.data == collapseCaption ) {
 
        for ( i = 1; i < Rows.length; i++ ) {
 
            Rows[i].style.display = "none";
 
        }
 
        Button.firstChild.data = expandCaption;
 
    } else {
 
        for ( 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 = {};
 
    var Tables = document.getElementsByTagName( "table" );
 
    var i;
 
    for ( i = 0; i < Tables.length; i++ ) {
 
        if ( hasClass( Tables[i], "collapsible" ) ) {
 
            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.style.styleFloat = "right";
 
            Button.style.cssFloat = "right";
 
            Button.style.fontWeight = "normal";
 
            Button.style.textAlign = "right";
 
            Button.style.width = "6em";
 
 
            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( "]" ) );
 
 
            var Header = Tables[i].getElementsByTagName( "tr" )[0].getElementsByTagName( "th" )[0];
 
            /* only add button and increment count if there is a header row to work with */
 
            if (Header) {
 
                Header.insertBefore( Button, Header.childNodes[0] );
 
                tableIndex++;
 
            }
 
        }
 
    }
 
 
    for ( i = 0;  i < tableIndex; i++ ) {
 
        if ( hasClass( NavigationBoxes[i], "collapsed" ) || ( tableIndex >= autoCollapse && hasClass( NavigationBoxes[i], "autocollapse" ) ) ) {
 
            collapseTable( i );
 
        }
 
    }
 
}
 
 
$( createCollapseButtons );
 
  
/** Dynamic Navigation Bars (experimental) *************************************
+
var isExpanded = ( $btn.text() === collapseCaption ),
  *
+
cssDisplay = isExpanded ? 'none' : $rows.first().css( 'display' );
  *  Description: See [[Wikipedia:NavFrame]].
 
  *  Maintainers: UNMAINTAINED
 
  */
 
 
  // set up the words in your language
 
  var NavigationBarHide = '[' + collapseCaption + ']';
 
  var NavigationBarShow = '[' + expandCaption + ']';
 
 
 
  // set up max count of Navigation Bars on page,
 
  // if there are more, all will be hidden
 
  // NavigationBarShowDefault = 0; // all bars will be hidden
 
  // NavigationBarShowDefault = 1; // on pages with more than 1 bar all bars will be hidden
 
  var NavigationBarShowDefault = autoCollapse;
 
 
 
 
 
  // shows and hides content and picture (if available) of navigation bars
 
  // Parameters:
 
  //    indexNavigationBar: the index of navigation bar to be toggled
 
  function toggleNavigationBar(indexNavigationBar)
 
  {
 
    var NavToggle = document.getElementById("NavToggle" + indexNavigationBar);
 
    var NavFrame = document.getElementById("NavFrame" + indexNavigationBar);
 
 
 
    if (!NavFrame || !NavToggle) {
 
        return false;
 
    }
 
 
 
    // if shown now
 
    if (NavToggle.firstChild.data == NavigationBarHide) {
 
        for (
 
                var NavChild = NavFrame.firstChild;
 
                NavChild != null;
 
                NavChild = NavChild.nextSibling
 
            ) {
 
            if ( hasClass( NavChild, 'NavPic' ) ) {
 
                NavChild.style.display = 'none';
 
            }
 
            if ( hasClass( NavChild, 'NavContent') ) {
 
                NavChild.style.display = 'none';
 
            }
 
        }
 
    NavToggle.firstChild.data = NavigationBarShow;
 
 
 
    // if hidden now
 
    } else if (NavToggle.firstChild.data == NavigationBarShow) {
 
        for (
 
                var NavChild = NavFrame.firstChild;
 
                NavChild != null;
 
                NavChild = NavChild.nextSibling
 
            ) {
 
            if (hasClass(NavChild, 'NavPic')) {
 
                NavChild.style.display = 'block';
 
            }
 
            if (hasClass(NavChild, 'NavContent')) {
 
                NavChild.style.display = 'block';
 
            }
 
        }
 
    NavToggle.firstChild.data = NavigationBarHide;
 
    }
 
  }
 
 
 
  // adds show/hide-button to navigation bars
 
  function createNavigationBarToggleButton()
 
  {
 
    var indexNavigationBar = 0;
 
    // iterate over all < div >-elements
 
    var divs = document.getElementsByTagName("div");
 
    for(
 
            var i=0;
 
            NavFrame = divs[i];
 
            i++
 
        ) {
 
        // if found a navigation bar
 
        if (hasClass(NavFrame, "NavFrame")) {
 
 
 
            indexNavigationBar++;
 
            var NavToggle = document.createElement("a");
 
            NavToggle.className = 'NavToggle';
 
            NavToggle.setAttribute('id', 'NavToggle' + indexNavigationBar);
 
            NavToggle.setAttribute('href', 'javascript:toggleNavigationBar(' + indexNavigationBar + ');');
 
           
 
            var NavToggleText = document.createTextNode(NavigationBarHide);
 
            NavToggle.appendChild(NavToggleText);
 
            // Find the NavHead and attach the toggle link (Must be this complicated because Moz's firstChild handling is borked)
 
            for(
 
              var j=0;
 
              j < NavFrame.childNodes.length;
 
              j++
 
            ) {
 
              if (hasClass(NavFrame.childNodes[j], "NavHead")) {
 
                NavFrame.childNodes[j].appendChild(NavToggle);
 
              }
 
            }
 
            NavFrame.setAttribute('id', 'NavFrame' + indexNavigationBar);
 
        }
 
    }
 
    // if more Navigation Bars found than Default: hide all
 
    if (NavigationBarShowDefault < indexNavigationBar) {
 
        for(
 
                var i=1;
 
                i<=indexNavigationBar;
 
                i++
 
        ) {
 
            toggleNavigationBar(i);
 
        }
 
    }
 
 
 
  }
 
 
 
  $( createNavigationBarToggleButton );
 
  
/** "Technical restrictions" title fix *****************************************
+
$btn.text( isExpanded ? expandCaption : collapseCaption );
*
+
$rows.slice( 1 ).each( function () {
* Description:
+
$( this ).css( 'display', cssDisplay );
* Maintainers: User:Interiot, User:Mets501, User:Freakofnurture
+
} );
*/
+
}
//
 
// For pages that have something like Template:Lowercase, replace the title, but only if it is cut-and-pasteable as a valid wikilink.
 
// (for instance iPod's title is updated. But [[C#]] is not an equivalent
 
// wikilink, so [[C Sharp]] doesn't have its main title changed)
 
// Likewise for users who have selected the U.K. date format ("1 March") the 
 
// titles of day-of-the-year articles will appear in that style. Users with any
 
// other date setting are not affected.
 
//
 
// The function looks for a banner like this:
 
// &lt;div id="RealTitleBanner"&gt;  ... &lt;span id="RealTitle"&gt;title&lt;/span&gt; ... &lt;/div&gt;
 
// An element with id=DisableRealTitle disables the function.
 
//
 
var disableRealTitle = 0; // users can set disableRealTitle = 1 locally to disable.
 
if (mw.config.get('wgIsArticle')) { // don't display the RealTitle when editing, since it is apparently inconsistent (doesn't show when editing sections, doesn't show when not previewing)
 
  $(function() {
 
    try {
 
        var realTitleBanner = document.getElementById("RealTitleBanner");
 
        if (realTitleBanner && !document.getElementById("DisableRealTitle") && !disableRealTitle ) {
 
            var realTitle = document.getElementById("RealTitle");
 
            if (realTitle) {
 
                var realTitleHTML = realTitle.innerHTML;
 
                realTitleText = pickUpText(realTitle);
 
  
                var isPasteable = 0;
+
// div.NavFrame
                //var containsHTML = /</.test(realTitleHTML);    // contains ANY HTML
+
var navFrameExpandCaption = '[' + expandCaption + ']',
                var containsTooMuchHTML = /</.test( realTitleHTML.replace(/<\/?(sub|sup|small|big)>/gi, "") ); // contains HTML that will be ignored when cut-n-pasted as a wikilink
+
navFrameCollapseCaption = '[' + collapseCaption + ']';
                // calculate whether the title is pasteable
 
                var verifyTitle = realTitleText.replace(/^ +/, "");      // trim left spaces
 
                verifyTitle = verifyTitle.charAt(0).toUpperCase() + verifyTitle.substring(1, verifyTitle.length);   // uppercase first character
 
  
                // if the namespace prefix is there, remove it on our verification copy. If it isn't there, add it to the original realValue copy.
+
// Изолируем код из глобальной области видимости
                if (mw.config.get('wgNamespaceNumber') != 0) {
+
( function () {
                    if (mw.config.get('wgCanonicalNamespace') == verifyTitle.substr(0, mw.config.get('wgCanonicalNamespace').length).replace(/ /g, "_") && verifyTitle.charAt(mw.config.get('wgCanonicalNamespace').length) == ":") {
+
function collapsibleDivs( $content ) {
                        verifyTitle = verifyTitle.substr(mw.config.get('wgCanonicalNamespace').length + 1);
+
var navFrameIndex = 0,
                    } else {
+
navFrames = [],
                        realTitleText = mw.config.get('wgCanonicalNamespace').replace(/_/g, " ") + ":" + realTitleText;
+
i;
                        realTitleHTML = mw.config.get('wgCanonicalNamespace').replace(/_/g, " ") + ":" + realTitleHTML;
 
                    }
 
                }
 
  
                // verify whether wgTitle matches
+
$content.find( 'div' ).each( function () {
                verifyTitle = verifyTitle.replace(/[\s_]+/g, " ");      // underscores and multiple spaces to single spaces
+
var $div = $( this );
                verifyTitle = verifyTitle.replace(/^\s+/, "").replace(/\s+$/, "");        // trim left and right spaces
+
if ( $div.hasClass( 'NavFrame' ) ) {
                verifyTitle = verifyTitle.charAt(0).toUpperCase() + verifyTitle.substring(1, verifyTitle.length);   // uppercase first character
+
var $btn = $( '<a>' )
                if ( (verifyTitle == mw.config.get('wgTitle')) || (verifyTitle == mw.config.get('wgTitle').replace(/^(.+)?(January|February|March|April|May|June|July|August|September|October|November|December)\s+([12]?[0-9]|3[0123])([^\d].*)?$/g, "$1$3 $2$4") )) isPasteable = 1;
+
.addClass( 'NavToggle' )
                var h1 = document.getElementsByTagName("h1")[0];
+
.attr( 'href', 'javascript:' )
                if (h1 && isPasteable) {
+
.text( navFrameCollapseCaption )
                    h1.innerHTML = containsTooMuchHTML ? realTitleText : realTitleHTML;
+
.click( navToggleClickHandler );
                    if (!containsTooMuchHTML)
+
$div.children( '.NavHead' ).append( $btn );
                        realTitleBanner.style.display = "none";
+
navFrames[ navFrameIndex++ ] = $div;
                }
+
}
                document.title = realTitleText + " - Wikipedia, the free encyclopedia";
+
} );
            }
+
for ( i = 0; i < navFrameIndex; i++ ) {
        }
+
if ( navFrames[ i ].hasClass( 'collapsed' ) ||
    } catch (e) {
+
( navFrameIndex > NavigationBarShowDefault &&
        /* Something went wrong. */
+
!navFrames[ i ].hasClass( 'expanded' )
    }
+
)
  });
+
) {
}
+
toggleDiv( navFrames[ i ] );
 
+
}
// similar to innerHTML, but only returns the text portions of the insides, excludes HTML
+
}
function pickUpText(aParentElement) {
+
}
var str = "";
 
 
 
function pickUpTextInternal(aElement) {
 
  var child = aElement.firstChild;
 
  while (child) {
 
  if (child.nodeType == 1)     // ELEMENT_NODE
 
    pickUpTextInternal(child);
 
  else if (child.nodeType == 3)   // TEXT_NODE
 
    str += child.nodeValue;
 
 
 
  child = child.nextSibling;
 
  }
 
}
 
 
 
  pickUpTextInternal(aParentElement);
 
  return str;
 
}
 
  
//fix edit summary prompt for undo
+
mw.hook( 'wikipage.content' ).add( collapsibleDivs );
//this code fixes the fact that the undo function combined with the "no edit summary prompter" causes problems if leaving the
 
//edit summary unchanged
 
//this was added by [[User:Deskana]], code by [[User:Tra]]
 
$(function () {
 
  if (document.location.search.indexOf("undo=") != -1
 
  && document.getElementsByName('wpAutoSummary')[0]) {
 
    document.getElementsByName('wpAutoSummary')[0].value='';
 
  }
 
})
 
  
/**
+
function navToggleClickHandler() {
* Qeydiyyatdan keçmiş istifadəçilər üçün gizli kateqoriyaların göstərilməsi üçün (+) düyməsini əlavə edən funksiya
+
var $btn = $( this );
*/
+
toggleDiv( $btn.closest( '.NavFrame' ), $btn );
function hiddencat( $ ) {
 
if (mw.util.getParamValue('printable') === 'yes') {
 
return;
 
}
 
var cl = document.getElementById('catlinks');
 
if (!cl) {
 
return;
 
}
 
var $hc = $('#mw-hidden-catlinks');
 
if ( !$hc.length ) {
 
return;
 
 
}
 
}
if ( $hc.hasClass('mw-hidden-cats-user-shown') ) {
 
return;
 
}
 
if ( $hc.hasClass('mw-hidden-cats-ns-shown') ) {
 
$hc.addClass('mw-hidden-cats-hidden');
 
}
 
var nc = document.getElementById('mw-normal-catlinks');
 
if ( !nc ) {
 
var catline = document.createElement('div');
 
catline.id = 'mw-normal-catlinks';
 
var a = document.createElement('a');
 
a.href = '';
 
a.title = '';
 
a.appendChild(document.createTextNode('Kateqoriyalar'));
 
catline.appendChild(a);
 
catline.appendChild(document.createTextNode(' : '));
 
nc = cl.insertBefore(catline, cl.firstChild);
 
}
 
var lnk = document.createElement('a');
 
lnk.id = 'mw-hidden-cats-link';
 
lnk.title = 'Bu məqalədə gizli kateqoriyalar var';
 
lnk.style.cursor = 'pointer';
 
lnk.style.color = 'black';
 
lnk.style.marginLeft = '0.3em';
 
$(lnk).click(toggleHiddenCats);
 
lnk.appendChild(document.createTextNode('[+]'));
 
nc.appendChild(lnk);
 
}
 
  
function toggleHiddenCats(e) {
+
function toggleDiv( $div, $btn ) {
var $hc = $('#mw-hidden-catlinks');
+
$btn = $btn || $div.find( '.NavToggle' ).first();
if ( $hc.hasClass('mw-hidden-cats-hidden') ) {
+
if ( !$div.length || !$btn.length ) return false;
$hc.removeClass('mw-hidden-cats-hidden');
+
var isExpanded = ( $btn.text() === navFrameCollapseCaption );
$hc.addClass('mw-hidden-cat-user-shown');
+
$btn.text( isExpanded ? navFrameExpandCaption : navFrameCollapseCaption );
$(e.target).text('[–]');
+
$div.children( '.NavContent, .NavPic' ).each( function () {
} else {
+
$( this ).css( 'display', isExpanded ? 'none' : 'block' );
$hc.removeClass('mw-hidden-cat-user-shown');
+
} );
$hc.addClass('mw-hidden-cats-hidden');
 
$(e.target).text('[+]');
 
 
}
 
}
}
 
  
mw.loader.using('mediawiki.util', function () {
+
/**
$( hiddencat );
+
* Загрузка скриптов через систему подгаджетов
});
+
*/
 +
var namespaceNumber = mw.config.get( 'wgNamespaceNumber' );
  
/** Add dismiss button to watchlist-message *************************************
+
// Скрипты для служебных страниц
  *
+
if ( namespaceNumber === -1 ) {
  *  Description: Hide the watchlist message for one week.
+
var specialGadgets = [
  *  Maintainers: [[User:Ruud Koot|Ruud Koot]]
+
'Abusefilter',
  */
+
'Block',
+
'Log',
function addDismissButton() {
+
'Movepage',
    var watchlistMessage = document.getElementById("watchlist-message");
+
'Newpages',
    if ( watchlistMessage == null ) return;
+
'Search',
+
'Upload'
    if ( document.cookie.indexOf( "hidewatchlistmessage=yes" ) != -1 ) {
+
];
        watchlistMessage.style.display = "none";
+
var canonicalSpecialPageName = mw.config.get( 'wgCanonicalSpecialPageName' );
    }
+
if ( specialGadgets.indexOf( canonicalSpecialPageName ) > -1 ) {
+
mw.loader.load( 'ext.gadget.common-special-' + canonicalSpecialPageName.toLowerCase() );
    var Button    = document.createElement( "span" );
+
}
    var ButtonLink = document.createElement( "a" );
+
} else {
    var ButtonText = document.createTextNode( "dismiss" );
+
// Скрипты для действий
+
var action = mw.config.get( 'wgAction' );
    ButtonLink.setAttribute( "id", "dismissButton" );
+
var actionGadgets = {
    ButtonLink.setAttribute( "href", "javascript:dismissWatchlistMessage();" );
+
'edit': [ 'ext.gadget.common-action-edit', 'ext.gadget.wikificator', 'ext.gadget.summaryButtons' ]
    ButtonLink.setAttribute( "title", "Hide this message for one week" );
+
};
    ButtonLink.appendChild( ButtonText );
+
actionGadgets[ 'submit' ] = actionGadgets[ 'edit' ];
 
    Button.appendChild( document.createTextNode( "[" ) );
 
    Button.appendChild( ButtonLink );
 
    Button.appendChild( document.createTextNode( "]" ) );
 
 
    watchlistMessage.appendChild( Button );
 
}
 
 
function dismissWatchlistMessage() {
 
    var e = new Date();
 
    e.setTime( e.getTime() + (7*24*60*60*1000) );
 
    document.cookie = "hidewatchlistmessage=yes; expires=" + e.toGMTString() + "; path=/";
 
    var watchlistMessage = document.getElementById("watchlist-message");
 
    watchlistMessage.style.display = "none";
 
}
 
 
$( addDismissButton );
 
  
/** MediaWiki media player *******************************************************
+
if ( actionGadgets[ action ] ) {
  *
+
mw.loader.load( actionGadgets[ action ] );
  *  Description: A Java player for in-browser playback of media files.
+
}
  *  Created by: [[User:Gmaxwell]]
 
  */
 
 
mw.loader.load('//en.wikipedia.org/w/index.php?title=Mediawiki:Wikimediaplayer.js&action=raw&ctype=text/javascript');
 
  
// Choice of multiple search engines
+
// Скрипты для пространств
// Autor: Jakob Voss, Guillaume (tret de de:MediaWiki:SpezialSuche.js)
+
var namespaceGadgets = {
// Version: 0.3.8
+
6: [ 'ext.gadget.common-namespace-file' ]
// Published as Public Domain
+
};
  
// Map of search engines and some OpenSearch-based fields
+
if ( namespaceGadgets[ namespaceNumber ] ) {
var searchEngines = {
+
mw.loader.load( namespaceGadgets[ namespaceNumber ] );
  mediawiki: {
+
}
    ShortName: "MediaWiki axtarışı",
+
}
    Template: "/w/index.php?search={searchTerms}"
+
}() );
  },
 
  globalwpsearch: {
 
    ShortName: "Qlobal vikipediyalar",
 
    Template: "http://vs.aka-online.de/cgi-bin/globalwpsearch.pl?timeout=120&search={searchTerms}"
 
  },
 
  google: {
 
    ShortName: "Google",
 
    Template: "http://www.google.cat/search?as_sitesearch=az.wikipedia.org&hl={language}&q={searchTerms}"
 
  },
 
  wikiwix: {
 
    ShortName: "Wikiwix",
 
    Template: "http://www.wikiwix.com/index.php?action={searchTerms}&lang=az"
 
  },
 
  yahoo: {
 
    ShortName: "Yahoo!",
 
    Template: "http://search.yahoo.com/search?p={searchTerms}&vs=az.wikipedia.org"
 
  },
 
  wlive: {
 
    ShortName: "Windows Live",
 
    Template: "http://search.live.com/results.aspx?q={searchTerms}&q1=site:http://az.wikipedia.org"
 
  }
 
};
 
 
  
function externalSearchEngines() {
+
/**
  if (typeof SpecialSearchEnhanced2Disabled != 'undefined') return;
+
* Старые коды
 +
*/
 +
if ( navigator.platform.indexOf( 'Win' ) !== -1 ) {
 +
mw.loader.using( 'mediawiki.util' ).done( function () {
 +
mw.util.addCSS( '.IPA, .Unicode { font-family: "Arial Unicode MS", "Lucida Sans Unicode"; }' );
 +
} );
 +
}
  
 +
/**
 +
* Дополнительный функционал для заглавной страницы
 +
*/
 +
if ( mw.config.get( 'wgIsMainPage' ) && mw.config.get( 'wgAction' ) === 'view' ) {
 +
mw.hook( 'wikipage.content' ).add( function () {
 +
mw.loader.using( 'mediawiki.util' ).done( function () {
 +
var el = mw.util.addPortletLink(
 +
'p-lang',
 +
mw.config.get( 'wgArticlePath' ).replace( /\$1/, 'Википедия:Список_Википедий' ),
 +
'Полный список',
 +
'interwiki-completelist'
 +
);
 +
if ( el ) {
 +
el.style.fontWeight = 'bold';
 +
}
  
  var mainNode = document.getElementById("powersearch");
+
$( '#p-wikibase-otherprojects li.wb-otherproject-link a' ).each( function () {
  if (!mainNode) mainNode = document.getElementById("search");
+
var $link = $( this ),
  if (!mainNode) return;
+
url = $link.attr( 'href' ).replace( '/Main_Page', mw.util.wikiUrlencode( '/Заглавная_страница' ) );
 +
if ( $link.parent().hasClass( 'wb-otherproject-mediawiki' ) ) {
 +
url = $link.attr( 'href' ) + '/ru';
 +
}
 +
$link.attr( 'href', url );
 +
} );
 +
} );
 +
} );
 +
 +
// Закрываем меню при клике за его пределами
 +
mw.hook( 'wikipage.content' ).add( function () {
 +
var $items = $( '.main-footer-menuToggle' ),
 +
$target;
 +
 +
document.body.addEventListener( 'click', function ( event ) {
 +
    $target = $( event.target ).parents( '.main-footer-menuToggle' )[0];
 +
    $items.each( function () {
 +
        if( this !== $target && !$( this ).hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
 +
            $( this ).click();
 +
        }
 +
    } );
 +
}, true );
 +
} );
 +
}
  
  var beforeNode = document.getElementById("mw-search-top-table");
+
/**
  if (!beforeNode) return;
+
* Выполнение скриптов из пространства MediaWiki, указанных в URL
  beforeNode = beforeNode.nextSibling;
+
* См. также https://www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
  if (!beforeNode) return;
+
  */
+
var withJS = location.href.match( /[&?]withjs=((mediawiki:)?([^&#]+))/i );
  var firstEngine = "mediawiki";
+
if ( withJS ) {
   
+
importScript_( 'MediaWiki:' + withJS[3] );
  var choices = document.createElement("div");
+
}
  choices.setAttribute("id","searchengineChoices");
 
  choices.style.textAlign = "center";
 
 
  var lsearchbox = document.getElementById("searchText");
 
  var initValue = lsearchbox.value;
 
 
  var space = "";
 
  
  for (var id in searchEngines) {
+
/**
    var engine = searchEngines[id];
+
* Код, который нужно выполнить как можно раньше. Он выполняется, если загружен подвал страницы,
if(engine.ShortName)
+
* иначе же ждёт наступления события wikipage.content (см. выше определение runAsEarlyAsPossible
  {
+
* и ниже про wikipage.content).
    if (space) choices.appendChild(space);
+
  */
    space = document.createTextNode(" ");
+
runAsEarlyAsPossible( function () {
   
+
/**
    var attr = {  
+
* {{выполнить скрипт}}
      type: "radio",
+
*/
      name: "searchengineselect",
+
$( '.executeJS' ).each( function () {
      value: id,
+
var names = $( this ).data( 'scriptnames' );
      onFocus: "changeSearchEngine(this.value)",
+
if (names) {
      id: "searchengineRadio-"+id
+
names.split( ' ' ).forEach( function ( name ) {
    };
+
name = name.replace( /[^\w_-]/g, '' );
+
if ( name ) {
    var html = "<input";
+
importScript( 'MediaWiki:Script/' + name + '.js' );
    for (var a in attr) html += " " + a + "='" + attr[a] + "'";
+
}
    html += " />";
+
} );
    var span = document.createElement("span");
+
}
    span.innerHTML = html;
+
} );
 
    choices.appendChild( span );
 
    var label
 
    if (engine.Template.indexOf('http') == 0) {
 
      label = document.createElement("a");
 
      label.href = engine.Template.replace("{searchTerms}", initValue).replace("{language}", "fr");
 
    } else {
 
      label = document.createElement("label");
 
    }
 
 
 
    label.appendChild( document.createTextNode( engine.ShortName ) );
 
    choices.appendChild( label );
 
  }
 
}
 
  mainNode.insertBefore(choices, beforeNode);
 
 
  var input = document.createElement("input");
 
  input.id = "searchengineextraparam";
 
  input.type = "hidden";
 
 
  mainNode.insertBefore(input, beforeNode);
 
  
  changeSearchEngine(firstEngine, initValue);
+
/**
}
+
* Чтобы ссылки на очистку кэша не требовали подтверждения (они должны быть помещены в тег с классом
 +
* purgelink и именем страницы в атрибуте data-pagename, например как в шаблоне {{очистить кэш}})
 +
*/
 +
$( '.purgelink a' ).click( function ( e ) {
 +
mw.loader.using( [ 'mediawiki.api', 'mediawiki.util', 'mediawiki.notify' ] ).done( function () {
 +
var pageName = $( this ).parent( '.purgelink' ).data( 'pagename' ) || mw.config.get( 'wgPageName' );
 +
new mw.Api().post( {
 +
action: 'purge',
 +
titles: pageName
 +
} ).then( function () {
 +
var url = mw.util.getUrl( pageName );
 +
if ( e.ctrlKey ) {
 +
if ( !window.open( url ) ) {
 +
location.assign( url );
 +
}
 +
} else {
 +
location.assign( url );
 +
}
 +
}, function () {
 +
mw.notify( 'Не удалось очистить кэш.', { type: 'error' } );
 +
} );
 +
e.preventDefault();
 +
} );
 +
} );
 +
}, $( '#footer' ), mw.hook( 'wikipage.content' ).add );
  
function changeSearchEngine(selectedId, searchTerms) {
+
// По какой-то причине фикс для FlaggedRevs работает только при использовании then(), но не done().
 +
mw.loader.using( 'ext.visualEditor.desktopArticleTarget.init' ).then( function () {
 +
/**
 +
* Исправление поведения FlaggedRevs в сочетании с визуальным редактором, чтобы
 +
* в стабилизированных статьях на правку в визреде открывалась последняя версия, что
 +
* соответствует поведению обычного редактора. См. [[phab:T165283]],
 +
* [[Википедия:Форум/Архив/Общий/2017/12#Серьёзная проблема с анонимными правками в стабилизированных статьях]].
 +
*/
 +
runAsEarlyAsPossible( function () {
 +
function fixEditLinksForStableRevs( removeClickHandlers ) {
 +
if ( $( '#ca-view.selected' ).length ) {
 +
// При выходе из визреда (сохранении или переключении) ссылки работают правильно
 +
// и убирать обработчики событий нет нужды — только исправить URL’ы на случай
 +
// открытия правки в новой вкладке.
 +
if ( removeClickHandlers ) {
 +
$( '#ca-ve-edit, .mw-editsection-visualeditor' ).off( 'click' );
 +
}
 +
$( '#ca-ve-edit a, .mw-editsection-visualeditor' ).each( function () {
 +
var href = $( this ).attr( 'href' );
 +
if ( !/[?&]stable=0/.test( href ) ) {
 +
$( this ).attr( 'href',
 +
href
 +
.replace( /&veaction=edit/, '&stable=0&veaction=edit' )
 +
.replace( /&oldid=\d+/,  '' )
 +
);
 +
}
 +
} );
 +
}
 +
}
  
  var currentId = document.getElementById("searchengineChoices").currentChoice;
+
// Не включаем сюда проверку на наличие #ca-view.selected, чтобы не вычёркивать случай,
  if (selectedId == currentId) return;
+
// когда визред открыт без Ajax и по выходу из него нужно заменить URL’ы в ссылках.
+
if ( $( '#ca-current' ).length && !/[?&](oldid|diff)=\d+/.test( location.search ) ) {
  document.getElementById("searchengineChoices").currentChoice = selectedId;
+
fixEditLinksForStableRevs( true );
  var radio = document.getElementById('searchengineRadio-' + selectedId);
+
  radio.checked = "checked";
+
mw.hook( 've.deactivationComplete' ).add( function () {
+
fixEditLinksForStableRevs( false );
  var engine = searchEngines[selectedId];
+
} );
  var p = engine.Template.indexOf('?');
+
}
  var params = engine.Template.substr(p+1);
+
} );
+
  var form;
+
/**
  if (document.forms["search"]) {
+
* Поддержка Викификатора в новом режиме вики-текста aka 2017 wikitext editor
    form = document.forms["search"];
+
*/
  } else {
+
mw.libs.ve.addPlugin( function () {
    form = document.getElementById("powersearch");
+
return mw.loader.using( 'ext.gadget.wikificator' );
  }
+
} );
  form.setAttribute("action", engine.Template.substr(0,p));
+
} );
 
  var l = ("" + params).split("&");
 
  for (var idx = 0;idx < l.length;idx++) {
 
    var p = l[idx].split("=");
 
    var pValue = p[1];
 
 
    if (pValue == "{language}") {
 
    } else if (pValue == "{searchTerms}") {
 
      var input;
 
      input = document.getElementById("searchText");
 
 
      input.name = p[0];
 
    } else {
 
      var input = document.getElementById("searchengineextraparam");
 
 
      input.name = p[0];
 
      input.value = pValue;
 
    }
 
  }
 
}
 
  
 
+
/**
if (mw.config.get('wgCanonicalSpecialPageName') == "Search") {
+
* {{TOC hidden}}
  $(externalSearchEngines);
+
*/
}
+
function TOChidden() {
if (mw.config.get('wgAction') == "edit" || mw.config.get('wgAction') == "submit") {
+
$( '.tochidden-wrapper > #toc > #toctogglecheckbox' ).prop('checked', true );
  importScript('MediaWiki:Editpage.js');
+
$( '.tochidden-wrapper' ).attr( "class", "toc-wrapper" );
 
}
 
}
  
// Sidebar Dəyişiklikləri
+
runAsEarlyAsPossible( function () {
function ModifySidebar(action, section, name, link) {
+
if ( $( '.tochidden-wrapper' ).length ) {
    try {
+
mw.loader.using( [ 'mediawiki.cookie' ] ).done( function () {
        switch (section) {
+
if ( mw.cookie.get( 'hidetoc' ) === null ) {
          case "Başqa dillərdə":
+
$.when( mw.loader.using( [ 'mediawiki.toc' ] ), $.ready ).then( TOChidden );
            var target = "p-lang";
+
}
            break;
+
} );
          case "Alətlər sandığı":
+
}
            var target = "p-tb";
+
}, $( '#toc' ), mw.hook( 'wikipage.content' ).add );
            break;
 
          case "rəhbər":
 
            var target = "p-navigation";
 
            break;
 
          default:
 
            var target = "p-" + section;
 
            break;
 
        }
 
 
        if (action == "add") {
 
            var node = document.getElementById(target)
 
                              .getElementsByTagName('div')[0]
 
                              .getElementsByTagName('ul')[0];
 
 
            var aNode = document.createElement('a');
 
            var liNode = document.createElement('li');
 
 
            aNode.appendChild(document.createTextNode(name));
 
            aNode.setAttribute('href', link);
 
            liNode.appendChild(aNode);
 
            liNode.className='plainlinks';
 
            node.appendChild(liNode);
 
        }
 
 
        if (action == "remove") {
 
            var list = document.getElementById(target)
 
                              .getElementsByTagName('div')[0]
 
                              .getElementsByTagName('ul')[0];
 
 
            var listelements = list.getElementsByTagName('li');
 
 
            for (var i = 0; i < listelements.length; i++) {
 
                if (listelements[i].getElementsByTagName('a')[0].innerHTML == name ||
 
                    listelements[i].getElementsByTagName('a')[0].href == link) {
 
 
                    list.removeChild(listelements[i]);
 
                }
 
            }
 
        }
 
 
    } catch(e) {
 
      // lets just ignore what's happened
 
      return;
 
    }
 
}
 
//</source>
 
// Results from Wikidata
 
// [[File:Wdsearch_script_screenshot.png]]
 
if ( mw.config.get( 'wgCanonicalSpecialPageName' ) === 'Search' ||  ( mw.config.get( 'wgArticleId' ) === 0 && mw.config.get( 'wgCanonicalSpecialPageName' ) === false ) ) {
 
        mw.loader.load("//en.wikipedia.org/w/index.php?title=MediaWiki:Wdsearch.js&action=raw&ctype=text/javascript");
 
}
 
  
 +
/**
 +
* Код, выполняемый по событию wikipage.content (его обработчики выполняются раньше колбэков для $,
 +
* хотя в глубине это одно и то же событие, просто колбэк, инициирующий wikipage.content, становится
 +
* в очередь раньше). Так как wikipage.content инициируется после обновления страницы в результате
 +
* Ajax-запросов (например, гаджетом быстрого предпросмотра), не добавляйте сюда коды, которые
 +
* должны гарантированно выполниться не более одного раза на странице.
 +
*/
 +
mw.hook( 'wikipage.content' ).add( function () {
 +
/**
 +
* Отключение обтекания раздела примечаний, если в нём есть колонки.
 +
* Короткие (до 16 ссылок) списки примечаний обтекаются только справа.
 +
*/
 +
$( '.reflist.columns' ).each( function () {
 +
var clear = 'both';
 +
if ( $( this ).find( 'ol.references > li' ).length < 16 ) {
 +
clear = 'left';
 +
}
 +
$( this )
 +
.prevUntil( 'h1, h2, h3, h4, h5, h6' )
 +
.addBack()
 +
.first()
 +
.prev()
 +
.css( 'clear', clear );
 +
} );
  
 
/**
 
/**
Sətir 784: Sətir 458:
 
importScript( 'MediaWiki:Imagemap-Highlight.js' );
 
importScript( 'MediaWiki:Imagemap-Highlight.js' );
 
}
 
}
    /**
+
 
 +
/**
 
* imgToggle
 
* imgToggle
 
*/
 
*/
Sətir 791: Sətir 466:
 
mw.loader.load( 'ext.gadget.imgToggle' );
 
mw.loader.load( 'ext.gadget.imgToggle' );
 
}
 
}
 +
 +
/**
 +
* Авторазбиение списков на колонки. Будет работать только для однострочных списков. 35em
 +
* (из Mediawiki:Common.css) является предварительным числом, а фактическое будет посчитано исходя
 +
* из ширины элементов. Должно использоваться только для UL внутри DIV. Пример использования —
 +
* шаблон {{Wikidata/SisterCities}}.
 +
*/
 +
$("div.autocolumns").each(function(d, div) {
 +
var parentWidth = $(div).parent()[0].offsetWidth;
 +
if (!parentWidth) return;
 +
 +
var maxWidth = 0;
 +
var elements = 0;
 +
$(div).find("ul>li").each(function(l, li) {
 +
elements++;
 +
var jLi = $(li);
 +
if (jLi.children().length != jLi.contents().length)
 +
jLi.wrapInner(document.createElement("span"));
 +
 +
var liWidth = 0;
 +
jLi.children().each(function(c, child) {
 +
liWidth += child.offsetWidth;
 +
});
 +
if (liWidth > maxWidth)
 +
maxWidth = liWidth;
 +
});
 +
if ( maxWidth === 0 ) return;
 +
// UL/LI bullet width + padding
 +
maxWidth += 22.5 * 2;
 +
 +
var maxColumns = "" + Math.ceil( elements / 5 );
 +
$(div).css({"-moz-columns": maxWidth + "px " + maxColumns, "columns" : maxWidth + "px " + maxColumns});
 +
});
 +
});
 +
 
/**
 
/**
  * Magic editintros ****************************************************
+
  * Кнопки описания правок для визуального редактора
*
 
* Description: Adds editintros on disambiguation pages and BLP pages.
 
* Maintainers: [[User:RockMFR]]
 
 
  */
 
  */
function addEditIntro( name ) {
+
mw.hook( 've.activationComplete' ).add( function () {
$( '.mw-editsection, #ca-edit, #ca-ve-edit' ).find( 'a' ).each( function ( i, el ) {
+
mw.loader.load( 'ext.gadget.summaryButtons' );
el.href = $( this ).attr( 'href' ) + '&editintro=' + name;
+
} );
} );
 
}
 
 
 
if ( mw.config.get( 'wgNamespaceNumber' ) === 0 ) {
 
$( function () {
 
if ( document.getElementById( 'disambigbox' ) ) {
 
addEditIntro( 'Template:Disambig_editintro' );
 
}
 
} );
 
 
 
$( function () {
 
var cats = mw.config.get('wgCategories');
 
if ( !cats ) {
 
return;
 
}
 
if ( $.inArray( 'Yaşayan insanlar', cats ) !== -1 || $.inArray( 'Yaşayan insanlar', cats ) !== -1 ) {
 
addEditIntro( 'Template:BLP_editintro' );
 
}
 
} );
 
}
 

01:43, 13 mart 2020 versiyası

/**
 * Код MediaWiki:Common.js безусловно загружается всем пользователям на всех страницах. Во избежание
 * отправки лишних запросов по возможности не используйте здесь mw.loader.using с модулями, которые
 * не загружаются по умолчанию (см.
 * [[Обсуждение MediaWiki:Common.js#Список модулей, загружаемых по умолчанию]]). В таком случае
 * лучше создать скрытый гаджет, загружаемый по умолчанию, и добавить ему нужные модули в качестве
 * зависимостей.
 */

/**
 * Локальная функция загрузки скриптов с поддержкой указания проекта
 */
var importScript_ = importScript;
importScript = function ( page, proj ) {
	if ( !proj ) {
		importScript_( page );
	} else {
		if ( proj.indexOf( '.' ) === -1 ) {
			proj += '.wikipedia.org';
		}
		mw.loader.using( 'mediawiki.util' ).done( function () {
			mw.loader.load( '//' + proj + '/w/index.php?title=' + mw.util.wikiUrlencode( page ) +
				'&action=raw&ctype=text/javascript' );
		} );
	}
};

/**
 * Часто те или иные манипуляции со страницей нужно выполнить как можно раньше, но нет гарантии, что
 * к моменту выполнения кода нужный участок DOM готов, а событие полной загрузки страницы происходит
 * слишком поздно. В этой функции проверяется наличие элемента $testElement и в случае успеха
 * функция-колбэк выполняется, иначе же её выполнение поручается другой функции. Если элемент
 * в $testElement имеет содержимое, правильнее указать следующий за ним элемент, чтобы быть
 * уверенным, что он загрузился до конца. Имейте в виду, что разные скины часто используют разные
 * названия классов и идентификаторов.
 */
function runAsEarlyAsPossible( callback, $testElement, func ) {
	func = func || $;
	$testElement = $testElement || $( '#footer' );

	if ( $testElement.length ) {
		callback();
	} else {
		func( callback );
	}
}

/**
 * Настройка обработки «е» и «ё» при сортировке в таблицах
 */
mw.config.set( 'tableSorterCollation', { 'Ё': 'Е', 'ё': 'е' } );

/**
 * Строки. Иноязычный интерфейс предположительно включают весьма редко, поэтому раздувать этот
 * список не стоит. При необходимости добавить много сообщений во много языков можно использовать
 * механизм системных сообщений (= страниц в пространстве MediaWiki, у которых могут быть суффиксы
 * типа /en). См., как их получение реализовано в MediaWiki:Gadget-sidebarRelated.js.
 */
var expandCaption, collapseCaption, zeroSectionTip;
if ( mw.config.get( 'wgUserLanguage' ) === 'en' ) {
	expandCaption = 'show';
	collapseCaption = 'hide';
	zeroSectionTip = 'Edit lead section';
} else {
	expandCaption = 'показать';
	collapseCaption = 'скрыть';
	zeroSectionTip = 'Править преамбулу';
}

/**
 * [[ВП:Сворачиваемые блоки]]
 */
// Число раскрытых по умолчанию навигационных (и не только) шаблонов, если им задан параметр
// autocollapse. Участники могут переопределять это значение в личных JS.
var NavigationBarShowDefault;
if ( typeof NavigationBarShowDefault === 'undefined' ) {
	NavigationBarShowDefault = 1;
}

// table.collapsible
function collapsibleTables( $content ) {
	var $btn,
		$a,
		tblIdx = 0,
		navboxCount = 0,
		notNavboxCount = 0,
		colTables = [],
		$Tables = $content.find( 'table' );

	$Tables.each( function ( i, table ) {
		if ( $( table ).hasClass( 'collapsible' ) ) {
			var $table = $( this ),
				$row = $table.find( 'tr' ).first(),
				$cell = $row.find( 'th' ).first();
			if ( !$cell.length ) {
				return;
			}
			$table.attr( 'id', 'collapsibleTable' + tblIdx );
			$btn = $( '<span>' ).addClass( 'collapseButton' );
			$a = $( '<a>' )
				.attr( 'id', 'collapseButton' + tblIdx )
				.attr( 'href', 'javascript:collapseTable(' + tblIdx + ');' )
				// Изменяем цвет ссылки, только если цвет текста в навбоксе нестандартный
				.css( 'color', $cell.css( 'color' ) === $( '.mw-body' ).css( 'color' ) ? 'auto' :
					$cell.css( 'color' ) )
				.text( collapseCaption );
			$btn
				.append( '[' )
				.append( $a )
				.append( ']' );
			if ( $cell.contents().length ) {
				$btn.insertBefore( $cell.contents().first() );
			} else {
				$btn.appendTo( $cell );
			}
			// hasClass( 'navbox' ) — временное решение для навшаблонов, ещё не переведённых
			// на {{Навигационная таблица}} (также ниже)
			if ( $table.hasClass( 'navbox-inner' ) || $table.hasClass( 'navbox' ) ) {
				navboxCount++;
			} else {
				notNavboxCount++;
			}
			colTables[tblIdx++] = $table;
		}
	} );
	for ( var i = 0; i < tblIdx; i++ ) {
		if ( colTables[i].hasClass( 'collapsed' ) ||
			( colTables[i].hasClass( 'autocollapse' ) &&
				( ( ( colTables[i].hasClass( 'navbox-inner' ) || colTables[i].hasClass( 'navbox' ) ) &&
						navboxCount > NavigationBarShowDefault ) ||
					( !( colTables[i].hasClass( 'navbox-inner' ) || colTables[i].hasClass( 'navbox' ) ) &&
						notNavboxCount > NavigationBarShowDefault ) ) ) )
		{
			collapseTable( i );
		}
	}
}

mw.hook( 'wikipage.content' ).add( collapsibleTables );

function collapseTable( idx ) {
	var $table = $( '#collapsibleTable' + idx ),
		$rows = $table.children().children( 'tr' ),
		$btn = $( '#collapseButton' + idx );
	if ( !$table.length || !$rows.length || !$btn.length ) {
		return false;
	}

	var isExpanded = ( $btn.text() === collapseCaption ),
		cssDisplay = isExpanded ? 'none' : $rows.first().css( 'display' );

	$btn.text( isExpanded ? expandCaption : collapseCaption );
	$rows.slice( 1 ).each( function () {
		$( this ).css( 'display', cssDisplay );
	} );
}

// div.NavFrame
var navFrameExpandCaption = '[' + expandCaption + ']',
	navFrameCollapseCaption = '[' + collapseCaption + ']';

// Изолируем код из глобальной области видимости
( function () {
	function collapsibleDivs( $content ) {
		var navFrameIndex = 0,
			navFrames = [],
			i;

		$content.find( 'div' ).each( function () {
			var $div = $( this );
			if ( $div.hasClass( 'NavFrame' ) ) {
				var $btn = $( '<a>' )
					.addClass( 'NavToggle' )
					.attr( 'href', 'javascript:' )
					.text( navFrameCollapseCaption )
					.click( navToggleClickHandler );
				$div.children( '.NavHead' ).append( $btn );
				navFrames[ navFrameIndex++ ] = $div;
			}
		} );
		for ( i = 0; i < navFrameIndex; i++ ) {
			if ( navFrames[ i ].hasClass( 'collapsed' ) ||
				( navFrameIndex > NavigationBarShowDefault &&
					!navFrames[ i ].hasClass( 'expanded' )
				)
			) {
				toggleDiv( navFrames[ i ] );
			}
		}
	}

	mw.hook( 'wikipage.content' ).add( collapsibleDivs );

	function navToggleClickHandler() {
		var $btn = $( this );
		toggleDiv( $btn.closest( '.NavFrame' ), $btn );
	}

	function toggleDiv( $div, $btn ) {
		$btn = $btn || $div.find( '.NavToggle' ).first();
		if ( !$div.length || !$btn.length ) return false;
		var isExpanded = ( $btn.text() === navFrameCollapseCaption );
		$btn.text( isExpanded ? navFrameExpandCaption : navFrameCollapseCaption );
		$div.children( '.NavContent, .NavPic' ).each( function () {
			$( this ).css( 'display', isExpanded ? 'none' : 'block' );
		} );
	}

	/**
	 * Загрузка скриптов через систему подгаджетов
	 */
	var namespaceNumber = mw.config.get( 'wgNamespaceNumber' );

	// Скрипты для служебных страниц
	if ( namespaceNumber === -1 ) {
		var specialGadgets = [
			'Abusefilter',
			'Block',
			'Log',
			'Movepage',
			'Newpages',
			'Search',
			'Upload'
		];
		var canonicalSpecialPageName = mw.config.get( 'wgCanonicalSpecialPageName' );
		if ( specialGadgets.indexOf( canonicalSpecialPageName ) > -1 ) {
			mw.loader.load( 'ext.gadget.common-special-' + canonicalSpecialPageName.toLowerCase() );
		}
	} else {
		// Скрипты для действий
		var action = mw.config.get( 'wgAction' );
		var actionGadgets = {
			'edit': [ 'ext.gadget.common-action-edit', 'ext.gadget.wikificator', 'ext.gadget.summaryButtons' ]
		};
		actionGadgets[ 'submit' ] = actionGadgets[ 'edit' ];

		if ( actionGadgets[ action ] ) {
			mw.loader.load( actionGadgets[ action ] );
		}

		// Скрипты для пространств
		var namespaceGadgets = {
			6: [ 'ext.gadget.common-namespace-file' ]
		};

		if ( namespaceGadgets[ namespaceNumber ] ) {
			mw.loader.load( namespaceGadgets[ namespaceNumber ] );
		}
	}
}() );

/**
 * Старые коды
 */
if ( navigator.platform.indexOf( 'Win' ) !== -1 ) {
	mw.loader.using( 'mediawiki.util' ).done( function () {
		mw.util.addCSS( '.IPA, .Unicode { font-family: "Arial Unicode MS", "Lucida Sans Unicode"; }' );
	} );
}

/**
 * Дополнительный функционал для заглавной страницы
 */
if ( mw.config.get( 'wgIsMainPage' ) && mw.config.get( 'wgAction' ) === 'view' ) {
	mw.hook( 'wikipage.content' ).add( function () {
		mw.loader.using( 'mediawiki.util' ).done( function () {
			var el = mw.util.addPortletLink(
				'p-lang',
				mw.config.get( 'wgArticlePath' ).replace( /\$1/, 'Википедия:Список_Википедий' ),
				'Полный список',
				'interwiki-completelist'
			);
			if ( el ) {
				el.style.fontWeight = 'bold';
			}

			$( '#p-wikibase-otherprojects li.wb-otherproject-link a' ).each( function () {
				var $link = $( this ),
					url = $link.attr( 'href' ).replace( '/Main_Page', mw.util.wikiUrlencode( '/Заглавная_страница' ) );
				if ( $link.parent().hasClass( 'wb-otherproject-mediawiki' ) ) {
					url = $link.attr( 'href' ) + '/ru';
				}
				$link.attr( 'href', url );
			} );
		} );
	} );
	
	// Закрываем меню при клике за его пределами
	mw.hook( 'wikipage.content' ).add( function () {
		var $items =  $( '.main-footer-menuToggle' ),
			$target;
			
		document.body.addEventListener( 'click', function ( event ) {
		    $target = $( event.target ).parents( '.main-footer-menuToggle' )[0];
		    $items.each( function () {
		        if( this !== $target && !$( this ).hasClass( 'mw-collapsible-toggle-collapsed' ) ) {
		            $( this ).click();
		        }
		    } );
		}, true );
	} );
}

/**
 * Выполнение скриптов из пространства MediaWiki, указанных в URL
 * См. также https://www.mediawiki.org/wiki/Snippets/Load_JS_and_CSS_by_URL
 */
var withJS = location.href.match( /[&?]withjs=((mediawiki:)?([^&#]+))/i );
if ( withJS ) {
	importScript_( 'MediaWiki:' + withJS[3] );
}

/**
 * Код, который нужно выполнить как можно раньше. Он выполняется, если загружен подвал страницы,
 * иначе же ждёт наступления события wikipage.content (см. выше определение runAsEarlyAsPossible
 * и ниже про wikipage.content).
 */
runAsEarlyAsPossible( function () {
	/**
	 * {{выполнить скрипт}}
	 */
	$( '.executeJS' ).each( function () {
		var names = $( this ).data( 'scriptnames' );
		if (names) {
			names.split( ' ' ).forEach( function ( name ) {
				name = name.replace( /[^\w_-]/g, '' );
				if ( name ) {
					importScript( 'MediaWiki:Script/' + name + '.js' );
				}
			} );
		}
	} );

	/**
	 * Чтобы ссылки на очистку кэша не требовали подтверждения (они должны быть помещены в тег с классом
	 * purgelink и именем страницы в атрибуте data-pagename, например как в шаблоне {{очистить кэш}})
	 */
	$( '.purgelink a' ).click( function ( e ) {
		mw.loader.using( [ 'mediawiki.api', 'mediawiki.util', 'mediawiki.notify' ] ).done( function () {
			var pageName = $( this ).parent( '.purgelink' ).data( 'pagename' ) || mw.config.get( 'wgPageName' );
			new mw.Api().post( {
				action: 'purge',
				titles: pageName
			} ).then( function () {
				var url = mw.util.getUrl( pageName );
				if ( e.ctrlKey ) {
					if ( !window.open( url ) ) {
						location.assign( url );
					}
				} else {
					location.assign( url );
				}
			}, function () {
				mw.notify( 'Не удалось очистить кэш.', { type: 'error' } );
			} );
			e.preventDefault();
		} );
	} );
}, $( '#footer' ), mw.hook( 'wikipage.content' ).add );

// По какой-то причине фикс для FlaggedRevs работает только при использовании then(), но не done().
mw.loader.using( 'ext.visualEditor.desktopArticleTarget.init' ).then( function () {
	/**
	 * Исправление поведения FlaggedRevs в сочетании с визуальным редактором, чтобы
	 * в стабилизированных статьях на правку в визреде открывалась последняя версия, что
	 * соответствует поведению обычного редактора. См. [[phab:T165283]],
	 * [[Википедия:Форум/Архив/Общий/2017/12#Серьёзная проблема с анонимными правками в стабилизированных статьях]].
	 */
	runAsEarlyAsPossible( function () {
		function fixEditLinksForStableRevs( removeClickHandlers ) {
			if ( $( '#ca-view.selected' ).length ) {
				// При выходе из визреда (сохранении или переключении) ссылки работают правильно
				// и убирать обработчики событий нет нужды — только исправить URL’ы на случай
				// открытия правки в новой вкладке.
				if ( removeClickHandlers ) {
					$( '#ca-ve-edit, .mw-editsection-visualeditor' ).off( 'click' );
				}
				$( '#ca-ve-edit a, .mw-editsection-visualeditor' ).each( function () {
					var href = $( this ).attr( 'href' );
					if ( !/[?&]stable=0/.test( href ) ) {
						$( this ).attr( 'href',
							href
								.replace( /&veaction=edit/, '&stable=0&veaction=edit' )
								.replace( /&oldid=\d+/,  '' )
						);
					}
				} );
			}
		}

		// Не включаем сюда проверку на наличие #ca-view.selected, чтобы не вычёркивать случай,
		// когда визред открыт без Ajax и по выходу из него нужно заменить URL’ы в ссылках.
		if ( $( '#ca-current' ).length && !/[?&](oldid|diff)=\d+/.test( location.search ) ) {
			fixEditLinksForStableRevs( true );
		
			mw.hook( 've.deactivationComplete' ).add( function () {
				fixEditLinksForStableRevs( false );
			} );
		}
	} );
	
	/**
	 * Поддержка Викификатора в новом режиме вики-текста aka 2017 wikitext editor
	 */
	mw.libs.ve.addPlugin( function () {
		return mw.loader.using( 'ext.gadget.wikificator' );
	} );
} );

/**
 * {{TOC hidden}}
 */
function TOChidden() {
	$( '.tochidden-wrapper > #toc > #toctogglecheckbox' ).prop('checked', true );
	$( '.tochidden-wrapper' ).attr( "class", "toc-wrapper" );
}

runAsEarlyAsPossible( function () {
	if ( $( '.tochidden-wrapper' ).length ) {
		mw.loader.using( [ 'mediawiki.cookie' ] ).done( function () {
			if ( mw.cookie.get( 'hidetoc' ) === null ) {
				$.when( mw.loader.using( [ 'mediawiki.toc' ] ), $.ready ).then( TOChidden );
			}
		} );
	}
}, $( '#toc' ), mw.hook( 'wikipage.content' ).add );

/**
 * Код, выполняемый по событию wikipage.content (его обработчики выполняются раньше колбэков для $,
 * хотя в глубине это одно и то же событие, просто колбэк, инициирующий wikipage.content, становится
 * в очередь раньше). Так как wikipage.content инициируется после обновления страницы в результате
 * Ajax-запросов (например, гаджетом быстрого предпросмотра), не добавляйте сюда коды, которые
 * должны гарантированно выполниться не более одного раза на странице.
 */
mw.hook( 'wikipage.content' ).add( function () {
	/**
	 * Отключение обтекания раздела примечаний, если в нём есть колонки.
	 * Короткие (до 16 ссылок) списки примечаний обтекаются только справа.
	 */
	$( '.reflist.columns' ).each( function () {
		var clear = 'both';
		if ( $( this ).find( 'ol.references > li' ).length < 16 ) {
			clear = 'left';
		}
		$( this )
			.prevUntil( 'h1, h2, h3, h4, h5, h6' )
			.addBack()
			.first()
			.prev()
			.css( 'clear', clear );
	} );

	/**
	 * Imagemap Highlight
	 */
	// На странице есть как минимум один элемент .imageMapHighlighter, а браузер поддерживает <canvas>
	if ( $( '.imageMapHighlighter' ).length && $( '<canvas>' )[ 0 ].getContext ) {
		importScript( 'MediaWiki:Imagemap-Highlight.js' );
	}

	/**
	 * imgToggle
	 */
	// На странице есть как минимум один элемент div.img_toggle
	if ( $( 'div.img_toggle' ).length ) {
		mw.loader.load( 'ext.gadget.imgToggle' );
	}

	/**
	 * Авторазбиение списков на колонки. Будет работать только для однострочных списков. 35em
	 * (из Mediawiki:Common.css) является предварительным числом, а фактическое будет посчитано исходя
	 * из ширины элементов. Должно использоваться только для UL внутри DIV. Пример использования —
	 * шаблон {{Wikidata/SisterCities}}.
	 */
	$("div.autocolumns").each(function(d, div) {
		var parentWidth = $(div).parent()[0].offsetWidth;
		if (!parentWidth) return;

		var maxWidth = 0;
		var elements = 0;
		$(div).find("ul>li").each(function(l, li) {
			elements++;
			var jLi = $(li);
			if (jLi.children().length != jLi.contents().length)
				jLi.wrapInner(document.createElement("span"));

			var liWidth = 0;
			jLi.children().each(function(c, child) {
				liWidth += child.offsetWidth;
			});
			if (liWidth > maxWidth)
				maxWidth = liWidth;
		});
		if ( maxWidth === 0 ) return;
		// UL/LI bullet width + padding
		maxWidth += 22.5 * 2;

		var maxColumns = "" + Math.ceil( elements / 5 );
		$(div).css({"-moz-columns": maxWidth + "px " + maxColumns, "columns" : maxWidth + "px " + maxColumns});
	});
});

/**
 * Кнопки описания правок для визуального редактора
 */
mw.hook( 've.activationComplete' ).add( function () {
	mw.loader.load( 'ext.gadget.summaryButtons' );
} );