MediaWiki:Common.js

Материал из Urbanculture
Перейти к: навигация, поиск

Замечание. Возможно, после сохранения вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl-F5 или Ctrl-R (⌘-R на Mac)
  • Google Chrome: Нажмите Ctrl-Shift-R (⌘-Shift-R на Mac)
  • Internet Explorer: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl-F5
  • Opera: Выберите очистку кэша в меню Инструменты → Настройки
/** Misc common defines ****/ 
 
 
/* Неоднократно нужные проверки: */
/*** _is_editpage - я на странице редактирования? */
/*** _is_editable - у меня есть права на правку текущей страницы? */
/*** _is_autoconfirmed  */
var _is_editpage = mw.config.get( 'wgAction' ) == 'edit' || mw.config.get( 'wgAction' ) == 'submit';
var _is_editable = (function isEditable() {
    var restrict = mw.config.get( 'wgRestrictionEdit' ) || [], g;
    if (restrict.length < 1) {return true;}
    if (!mw.config.get( 'wgUserGroups' )) {return false;}
    for( g=0; g<mw.config.get( 'wgUserGroups' ).length; g++) {if ($.inArray(mw.config.get( 'wgUserGroups' )[g], restrict)!=-1) {return true;}}
    return false;
}());
var _is_autoconfirmed = mw.config.get( 'wgUserGroups' ) && ($.inArray('autoconfirmed', mw.config.get( 'wgUserGroups' )) != -1),
    f5s=('localStorage' in window) && window.localStorage!==null ? window.localStorage : false,
    Queue
    ;
/** /Misc common defines ****/
 
 
 
/** Processing queue ****/
 
/**** Queue.addOnce(function(){}, condition = true) - adds a function to run once on page load */
/**** Queue.addOnce('module.name', [function(){} | function name string string], condition = true) - loads a module and adds a function to run once on page load */
/**** Queue.addEachFragment(function(scope){}, condtion = true) - adds function to run on page load AND on each AJAX loaded fragment */
/**** Queue.addEachFragment('module.name', [function(scope){} | function name string string], condtion = true) - loads a module and adds function to run on page load AND on each AJAX loaded fragment */
/****     Function must take a single parameter - currently processed fragment */
/**** Both functions take optional second parameter - if false, function won't be run on current page */
/**** Queue.runOnce - self-descriptive, shouldn't be run directly */
/**** Queue.runEachFragment(scope) - scope can be an html element or array of elements */
 
mw.loader.using('UC.queue', function() {
 
    /**  Edittools ****/
    /* Authors: [[User:Anotubus]], [[User:Obvious]] */
    Queue.addOnce('UC.edittools', 'tabbedEditTools', ( 
        (!mw.config.get( 'wgCanonicalSpecialPageName' ) &&
        ( 
            location.href.match(/&action=(?:edit|submit)/) !== null ||
            mw.config.get( 'wgAction' ) == 'edit' ||
            mw.config.get( 'wgAction' ) == 'submit'
        )) ||
        mw.config.get( 'wgPageName' ).match(/mediawiki:(?:edittools|topedittools)/i) !== null ||
        mw.config.get( 'wgCanonicalNamespace' ).match(/talk$/i) !== null ||
        mw.config.get( 'wgPageName' ) == "Special:Upload" ||
        mw.config.get( 'wgPageName' ) == "Служебная:Загрузка"
    ) );
    Queue.addOnce('UC.edittools', 'fileInsert', ( 
        (!mw.config.get( 'wgCanonicalSpecialPageName' ) &&
        ( 
            location.href.match(/&action=(?:edit|submit)/) !== null ||
            mw.config.get( 'wgAction' ) == 'edit' ||
            mw.config.get( 'wgAction' ) == 'submit'
        )) ||
        mw.config.get( 'wgPageName' ).match(/mediawiki:(?:edittools|topedittools)/i) !== null ||
        mw.config.get( 'wgCanonicalNamespace' ).match(/talk$/i) !== null
    ) );
    Queue.addOnce(function(){
        $('.boxes a').each(function() {
            var parentalt = $(this).parent().attr('title');
            $(this).attr('alt', parentalt);
            if($(this).parent().hasClass('menuicon')) {
                $(this).html('<span class="glyphicon"></span>')
            };
        });
    });
 
    //Fixed edittools on big pages
    Queue.addOnce('jquery.visible', function(){
        $(document).on("scroll", function() {
            var visible = $('.mw-editTools').visible(),
                scrollTop     = $(window).scrollTop(),
                elementOffset = $('.editOptions').offset().top,
                distance      = (elementOffset - scrollTop),
                topPosition = $(window).scrollTop() - 80;
            if (visible || distance < 180) {
                $(this).find('#editpage-specialchars-new').removeClass('fixed')
                    .css('top', '0');
            } else {
                $(this).find('#editpage-specialchars-new').addClass('fixed')
                    .css('top', topPosition);
            }
        });
    }, (!mw.config.get( 'wgCanonicalSpecialPageName' ) &&
        ( 
            location.href.match(/&action=(?:edit|submit)/) !== null ||
            mw.config.get( 'wgAction' ) == 'edit' ||
            mw.config.get( 'wgAction' ) == 'submit'
        ))
    );
 
    /** Collapsible tables ****/
    // Используется в коллапсерах
    Queue.addEachFragment( 'UC.tablecollapsers','createTableCollapsers', !mw.config.get( 'wgCanonicalSpecialPageName' ) );
    Queue.addEachFragment( 'UC.tablecollapsers','createHiderButtons', !mw.config.get( 'wgCanonicalSpecialPageName' ) );
 
 
    /** NSFW Gallery Items ****/
    /* Description: Hides images with |NSFW in description from galleries */
    /* Authors: [[User:Anotubus]], [[User:Obvious]] */
    Queue.addEachFragment('UC.gallerymodify','processNSFWGalleryItems', !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** Dynamic gallery ****/
    Queue.addEachFragment('UC.gallerymodify','dynamicGallery', !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** Ajaxed *****/
    Queue.addEachFragment('UC.ajaxed', 'ajaxed', !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** Sidebar scroll *****/
    Queue.addOnce('jquery.slimscroll', function(){
        if($(window).width() > '980') {
            $('#mw-panel').slimScroll({
                color: '#ffffff',
                distance: '3px',
            });
        };
    });
 
    /** Morph LM Edition **************************************/
    Queue.addEachFragment('UC.morphobjects','createMorphObjects', !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** Ref tooltips******************************************
      *
      *  Description: Replace references with JQuery-based tooltips
      *  Made by:  Tachikoma
      */
 
    Queue.addOnce(function() {
        $(window).click(function(e) {
            if (!($(e.target).hasClass('areference') || $(e.target).parents().andSelf().hasClass('tooltip'))) {
                $('.tooltip').hide(250); $('.curreference').removeClass('curreference');
            }
        });
    }, !mw.config.get( 'wgCanonicalSpecialPageName' )).addEachFragment(function(scope) {
        var refs = $('ol.references', scope);
        if (!refs.size()) { return; }
        refs.before($('<a href="#">[показать примечания]</a>').click(function(e) { e.preventDefault(); refs.toggle(); } )).hide();
        $('.reference a', scope).click(function(e) {
            e.preventDefault();
            var x = $(this), iscurrent = x.hasClass('curreference'), i = $('.tooltip').hide(250),
                par = x.parent(), o = par.offset(), l = o.left, t = o.top+13,
                b = $('body'), mh = b.height(), mw = b.width(),
                c=$(x.attr('href'), refs).clone().find('a:first').remove().end().html();
            $('.curreference').removeClass('curreference');
            if (iscurrent) { return; }
 
            x.addClass('areference').addClass('curreference');
            if (!i.size()) { i = $('<div/>').addClass('tooltip');}
            i.appendTo(b).queue(function() {
                i.empty().append(c).css({ 'left': l-((l+i.width() >= mw) && i.width()), 'top': t-((t+i.height() >= mh) && (i.height()+26)) }).dequeue();
            }).show(250);
        });
    }, !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** Morph LM Edition **************************************/
    Queue.addEachFragment('UC.morphobjects','createMorphObjects', !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** Pre lines******************************************
      *
      *  Description: add lines to <pre> tags
      *  Made by: Munhgauzen
      */
 
    Queue.addOnce(function() {
        $('pre').each(function() {
            $(this).append('<div class="appendedRows"></div>')
            var rows_count = Math.round($(this).height()/parseInt($(this).css('line-height')));
 
            for (var i=0; i<rows_count; i++) {
                $(this).find('.appendedRows').append('<span class="row"></span>');
            }
        });
    });
 
    /** Linkchecker ***/
    function linkchecker(scope) {
        $('.linkchecker', scope).each(function(i, e) {
            var lc_if = $(".linkcheckerif a", this),
                lc_then = $(".linkcheckerthen", this),
                lc_else = $(".linkcheckerelse", this)
            ;
 
            if (lc_if.size() && lc_then.size()) {
                if (lc_if.hasClass('new')) { lc_then.hide(); } else { lc_else.hide(); }
                lc_if.parent().hide();
            } else { $(this).hide(); }
        });
    }
    Queue.addEachFragment(linkchecker, !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
    /** ShortDiffURL ****/
    Queue.addOnce(function shortdiffurl() {
        if (!mw.config.get( 'wgCanonicalSpecialPageName' ) && window.location.href.indexOf("diff=") != '-1' && $("#ca-history").size() > 0 ){
            $("#ca-history").after('<li id="ca-diff" class="collapsible"><span><a href="'+location.href.replace(/^(.+\?).*&?(diff=(?:\d+|prev|next|curr)).*?(&oldid=\d+)?.*$/,"$1$2$3")+'" title="Короткая ссылка на дифф">Дифф</a></span></li>');
        };
    });
 
 
    /** Needed page **/
    Queue.addOnce(function() {
          $('.mw-redirect').addClass('neededpagerdrcts');
          $('ul').addClass('neededpagelist');
    }, !mw.config.get( 'wgCanonicalSpecialPageName' ) && mw.config.get( 'wgPageName' ) == 'Urbanculture:R');
 
    /** Wikificator  ************************************* */
    function wikification() {
        $('<button id="Wikifybutton" onclick="Wikify();" type="button">Викифицировать</button>').insertBefore($('#wpSave'));
        if(mw.config.get( 'wgNamespaceNumber' )==-1 || mw.config.get( 'wgNamespaceNumber' )==108) {$('#Wikifybutton').attr('disabled','disabled');}
        $('#editpage-copywarn').insertAfter('.editOptions');
    }
 
    Queue.addOnce( 'UC.wikificator', wikification, (!mw.config.get( 'wgCanonicalSpecialPageName' ) && mw.config.get( 'wgAction' ) == "edit") || mw.config.get( 'wgAction' ) == "submit" || mw.config.get( 'wgPageName' ) == "Special:Upload");
 
 
    /** Image Categorizer  ************************************* */
    /** Author: Anotubus   */
    /* if ( (mw.config.get( 'wgCanonicalNamespace' ) == 'File' || mw.config.get( 'wgNamespaceNumber' ) == 6) && _is_autoconfirmed && _is_editable ) importScriptURI("/skins/common/imgcat.js");*/
 
 
    /** Section menus ****************************************** */
    /* Authors: [[User:Tachikoma]], [[User:T_kns]], [[User:Мопец Ципельман]] */
    window.excludedSectionHeaders = $('.c-comment :header');
    Queue.addOnce('UC.sectionmenus','addSectionMenus', !mw.config.get( 'wgCanonicalSpecialPageName' ) && mw.config.get( 'skin' )=='vector');
 
 
    /** collapsibledivs *****/
     Queue.addOnce('UC.collapsiblesidebar','collapsibleSideBar', f5s && mw.config.get( 'skin' )=='vector');
 
 
    /* empty pagename ****/
    Queue.addOnce(function() {
        $('#bodySearch').submit(function(e) {
            var wrap = $(this).children(".bodySearchWrap");
            if(/^\s*$/.test(wrap.children('#bodySearchInput').val())) {
                if(wrap.children('.pagenameneeded').size() === 0) {
                    wrap.append($('<p class="pagenameneeded">Введите имя статьи</p>').delay(1500).fadeOut('slow',function() {$(this).remove();}));
                }
                return false;
            }
        });
    }, !mw.config.get( 'wgCanonicalSpecialPageName' ) && mw.config.get( 'wgPageName' ) == "Urbanculture:Новая_статья");
 
    /* b-yauser ****/
    Queue.addEachFragment(function(sc) { $('.b-yauser a', sc).each(function(i) { $(this).html($(this).html().replace(/^([^<])/,'<b>$1</b>')); }); });
 
 
    /* prettyPhoto ****/
    Queue.addOnce( 'UC.prettyphotify', 'prettyPhotifyOptions', f5s && mw.config.get( 'wgCanonicalSpecialPageName' ) == 'Preferences' );
    Queue.addEachFragment( 'UC.prettyphotify', 'prettyPhotify', f5s && localStorage.getItem('gallery_slideshow') != 'false' );
 
    /* By ****/
    Queue.addOnce(function() {
        $('body').addClass('ns-talk');
    }, !mw.config.get( 'wgCanonicalSpecialPageName' ) && mw.config.get( 'wgPageName' ) == "Urbanculture:Вниманию_участников");
 
    /* Spoilers ****/
    Queue.addEachFragment(function(scope) {
        $('.spoiler',scope).click(function() {
            $(this).toggleClass('spoilered');
        });
    }, !mw.config.get( 'wgCanonicalSpecialPageName' ) );
 
    /* new gallerytemplate ****/
    //Queue.addEachFragment('UC.newgallerytemplate', 'newGalleryTemplate', !mw.config.get( 'wgCanonicalSpecialPageName' ));
 
 
    /*** Resize textarea ***/
    Queue.addOnce('jquery.autoSizeTextArea', function () {
        $('#wpTextbox1').autoSizeTextArea();
        $(document).ready(function () {
            $('#wpTextbox1').autoSizeTextArea('update')
        });
    });
 
    /*** define the functions, that will be ran on each Comments display refresh ***/
    window.commentJSrunMultiHooks = function (scope) {};
 
});
 
/** /Processing queue ****/
 
 
/*** Scroll menu ***/
 
var scrollmenu = false;
$(document).ready(function () {
    var windowWidth = $(window).width();
        $(document).scroll(function () {
             if ((scrollmenu == false) && ($(window).scrollTop() > 112) && ($(window).height() > 900) && ($('#content').outerHeight() > 950) && (mw.config.get( 'skin' )=='vector')) {
                $(".editbox").css('position', 'fixed');
                $(".editbox").css('top', '0');
                scrollmenu = true;
            } else if ((scrollmenu === true) && ($(window).scrollTop() < 113)) {
                $(".editbox").css('position', 'absolute');
                $(".editbox").css('top', '');
                scrollmenu = false;
            }
        });
});
 
/*** /Scroll menu ***/
 
/*** Title page ***/
$('#write-article a').click(function () {
    $(this).hide();
    $('#create-page-lay').fadeIn();
    $('#create-page-lay .createboxInput').focus();
    $("#create-page-lay .createboxInput").focusout(function () {
        if ($(this).val() === "") {
            $('#create-page-lay').hide();
            $('#write-article a').fadeIn();
        }
    });
    return false;
});
 
/*** Blog page ***/
$(document).ready(function () {
    $('div.news.old').first().before("<div id='oldnews'></div>");
    $('div.news.old').appendTo($('#oldnews'));
    $('#oldnews').after("<div id='showarchive'><a class='show-link' href='#' class='showarchive'><span>Показать архив</span></a><a class='hide-link' href='#' class='showarchive' style='display:none'><span>Скрыть архив</span></a></div>");
    $('#showarchive a').click(function () {
        if($(this).hasClass('show-link')) {
            $('#oldnews').fadeIn();
            $(this).hide().siblings().show()
                .stop();
        } else {
            $('#oldnews').hide();
            $(this).hide().siblings().show()
                .stop();
        }
    });
});
 
 
/*** Mobile menu ***/
if (mw.config.get( 'skin' )=='mobile') {
    $('.portlet h5').click(function() {
        var portlet = $(this);
        $('#portlet-bg').fadeIn('slow');
        portlet.parent().addClass('visible');
    });
    $('#close-portlet').click(function() {
        $(this).parent().fadeOut('slow');
        $('.portlet').removeClass('visible');
    });
}