MediaWiki:Common.js

来自汉服百科
YellowTopaz讨论 | 贡献2013年4月6日 (六) 07:48的版本
跳转至: 导航搜索
/*
所有用戶在加載任何頁面時,這裡的JavaScript都會加載
*/

mw.loader.using(['mediawiki.Uri'], function() {
    /* Search Engine variant hack */
    var ref, loc;
    try {
        ref = new mw.Uri( document.referrer );
        loc = new mw.Uri( location.href );
    } catch ( e ) {
        return;
    }
    if (/\.google\./.test(ref.host) && /\/zh(-[^/]+)?\//.test(loc.path)) {
        loc.path = loc.path.replace(/\/zh(-[^/]+)?\//, "/wiki/");
        location = loc.toString();
    }
} );

mw.loader.using(['mediawiki.util', 'ext.gadget.site-lib'], function () {
  (function ($, mw) {
    /* Cookies */
    window.setCookie = function (cookieName, cookieValue, expiryDay) {
      $.cookie(cookieName, cookieValue, {
        expires: expiryDay,
        path: '/'
      });
    };

    window.getCookie = function (cookieName) {
      return $.cookie(cookieName);
    };

    window.deleteCookie = function (cookieName) {
      $.cookie(cookieName, null);
    };

    /* 當需要時載入對應的 scripts */
    if (wgAction == "edit" || wgAction == "submit" || wgCanonicalSpecialPageName == 'Search') { // scripts specific to editing pages
      importScript('MediaWiki:Common.js/edit.js');
    }

    /* 辅助处理 */
    /* 1. 功能設定 */
    window.JSConfig = window.JSconfig || {};
    window.JSConfig.collapseText = wgULS('隐藏▲', '隱藏▲'); // 指示折叠收缩的默认文字
    window.JSConfig.expandText = wgULS('显示▼', '顯示▼'); // 指示折叠展开的默认文字
    window.JSConfig.autoCollapse = 2; // 文章少于 autoCollapse 个折叠块时,不自动折叠
    //window.JSConfig.SpecialSearchEnhancedDisabled=false; // 是否禁止增加其它搜索引擎

    /* 2. 用jQuery实现的getElementsByClassName(需不需要返回DOM对象?) */
    window.getElementsByClassName = function (elm, tag, className) {
      return $(tag + '.' + className, elm);
    };

    /* 3. 遍历 */
    window.applyEach = function (callback, array) {
      var i = 0,
        j = array.length;
      while (i < j) {
        callback(array[i++]);
      }
    };

    /* 4. 移動元素 */
    window.elementMoveto = function (node, refNode, pos) { // 默认位置为refNode前
      if (node && refNode) {
        if (pos && pos == 'after') {
          $(refNode).after(node);
        } else {
          $(refNode).before(node);
        }
      }
    };

    /* 5. 创建元素 */
    window.createElement = function (tag, children, props) {
      var element = document.createElement(tag);
      if (!(children instanceof Array)) {
        children = [children];
      }
      applyEach(function (child) {
        if (typeof child == 'string') {
          child = document.createTextNode(child);
        }
        if (child) {
          element.appendChild(child);
        }
      }, children);
      if (typeof props == 'object') {
        for (var k in props) {
          switch (k) {
          case 'styles':
            var styles = props.styles;
            for (var s in styles) {
              element.style[s] = styles[s];
            }
            break;
          case 'events':
            var events = props.events;
            for (var e in events) {
              addHandler(element, e, events[e]);
            }
            break;
          case 'class':
            element.className = props[k];
            break;
          default:
            element.setAttribute(k, props[k]);
          }
        }
      }
      return element;
    };

    // wiki URL
    window.wgProjectURL = {
      en: '//en.wikipedia.org',
      de: '//de.wikipedia.org',
      fr: '//fr.wikipedia.org',
      pl: '//pl.wikipedia.org',
      ja: '//ja.wikipedia.org',
      it: '//it.wikipedia.org',
      nl: '//nl.wikipedia.org',
      pt: '//pt.wikipedia.org',
      es: '//es.wikipedia.org',
      sv: '//sv.wikipedia.org',
      // 僅列前十名其它語言百科
      m: '//meta.wikimedia.org',
      b: '//zh.wikibooks.org',
      q: '//zh.wikiquote.org',
      n: '//zh.wikinews.org',
      wikt: '//zh.wiktionary.org',
      mw: '//www.mediawiki.org',
      commons: '//commons.wikimedia.org'
    };

    /** 将页面名称转换为URL
     *
     * @param page 页面名称
     * @param paras 附加后缀对象,用空对象{}做参数可以取得源码
     */
    window.getWikiPath = function (page, paras) {
      var reg = /^[a-z]+:/;
      var pre = page.match(reg);
      pre = pre && wgProjectURL[pre[0].replace(/:$/, '').toLowerCase()];
      if (pre) {
        page = page.replace(reg, '');
      } else {
        pre = wgServer;
      } // 保障没有相对路径,以照顾在线代理。
      var url = pre + wgScript + '?title=' + encodeURI(page.replace(' ', '_'));
      if (typeof paras == 'object') {
        paras.ctype = paras.ctype || 'text';
        paras.dontcountme = paras.dontcountme || 's';
        paras.action = paras.action || 'raw';
        for (var k in paras) {
          url += '&' + k + '=' + paras[k];
        }
      }
      return url;
    };

    /* 引入[[Special:Gadgets]]要求的腳本和樣式 */
    if (window.requireScripts instanceof Array) {
      applyEach(importScript, requireScripts);
    }
    if (window.requireStylesheets instanceof Array) {
      applyEach(importStylesheet, requireStylesheets);
    }
    window.requireScripts = [];
    window.requireScripts.push = function (script) {
      importScript(script);
    };
    window.requireStylesheets = [];
    window.requireStylesheets.push = function (style) {
      importStylesheet(style);
    };

    /* 测试元素中是否含有指定的样式 */
    window.hasClass = function (elem, cls) {
      return $(elem).hasClass(cls);
    };

    /** IE兼容性修正
     *
     *  Description: Fixes IE horizontal scrollbar bug
     *  Maintainers: [[User:fdcn]]
     */
    if ($.browser.msie) {
      var oldWidth;
      var docEl = document.documentElement;

      function fixIEScroll() {
        if (!oldWidth || docEl.clientWidth > oldWidth) {
          doFixIEScroll();
        } else {
          setTimeout(doFixIEScroll, 1);
        }
        oldWidth = docEl.clientWidth;
      }

      function doFixIEScroll() {
        docEl.style.overflowX = (docEl.scrollWidth - docEl.clientWidth < 4) ? "hidden" : "";
      }

      document.attachEvent("onreadystatechange", fixIEScroll);
      attachEvent("onresize", fixIEScroll);

      /* Import scripts specific to Internet Explorer 6 */
      if (navigator.appVersion.substr(22, 1) == "6") {
        importScript("MediaWiki:Common.js/IE60Fixes.js")
      }
    }

    /* Fixes for Windows XP font rendering */
    if (navigator.appVersion.search(/windows nt 5/i) != -1) {
        mw.util.addCSS('.IPA {font-family: "Lucida Sans Unicode", "Arial Unicode MS";} ' + 
                       '.Unicode {font-family: "Arial Unicode MS", "Lucida Sans Unicode";}');
    }

    /* 特色條目優良與條目鏈接顯示 */
    $(function () {
      $('#p-lang li').each(function () {
        if ($('#' + this.className + '-fa').length) {
          this.className += " FA"
          this.title = wgULS("此条目在此语言版本中为特色条目", "此條目在此語言版本中為特色條目");
        } else if ($('#' + this.className + '-ga').length) {
          this.className += " GA"
          this.title = wgULS("此条目在此语言版本中为优良条目", "此條目在此語言版本中為優良條目");
        }
      });
    });

    /** 增加摺疊功能
     *
     * 实现div.NavFrame和table.collapsible的可折叠性。
     * JSConfig的collapseText、expandText、autoCollapse属性定义默认文字和默认最少自动折叠块
     * Maintainers: User:fdcn
     */
    function cancelBubble(e) {
      e = e || window.event;
      if (e.stopPropagation) {
        e.stopPropagation();
      } else {
        e.cancelBubble = true;
      }
    }

    function createToggleButton(head) {
      var parent = head;
      if (head.tagName.toLowerCase() == 'tr') { // 对表格特别处理
        if (head.getElementsByTagName("th").length) {
          parent = head.cells[parent.cells.length - 1];
        } else {
          return;
        }
      }
      var textS, textH, button = getElementsByClassName(head, "span", "NavToggle")[0];
      if (button) {
        parent = button.parentNode;
      } else {
        textS = createElement("span", [JSConfig.expandText], {
          'class': 'toggleShow'
        });
        textH = createElement("span", [JSConfig.collapseText], {
          'class': 'toggleHide'
        });
        button = createElement("span", [textS, textH], {
          'class': 'NavToggle collapseButton'
        });
      }
      button.style.visibility = "visible";
      head.className += " uncollapse toggleHotspot";
      parent.insertBefore(button, parent.childNodes[0]);
    }
    window.wgCollapse = function (head, container, defaultCollapse) {
      if (head) {
        createToggleButton(head);
      }
      var self = this;
      this.state = 0;
      this.container = container;
      applyEach(function (h) {
        if (h.nodeType == 1 && !hasClass(h, "uncollapse") && !hasClass(h, "toggleShow") && !hasClass(h, "toggleHide")) {
          h.className += " toggleHide";
        }
      }, defaultCollapse); // 预设的隐藏元素


      function getArray(clsname) {
        var r = [],
          i = 0,
          e, ea = getElementsByClassName(container, "*", clsname);
        while (e = ea[i++]) {
          var parent = e.parentNode;
          while (!hasClass(parent, 'NavFrame') && !hasClass(parent, 'collapsible')) {
            parent = parent.parentNode;
          }
          if (parent == container) {
            r.push(e);
          }
        }
        return r;
      }
      var toggleA = getArray("toggleShow");
      var toggleB = getArray("toggleHide");
      var hotspots = getArray("toggleHotspot");

      function _toggle(list, state) {
        var i = 0,
          e;
        while (e = list[i++]) {
          e.style.display = state ? e.showStyle || '' : 'none';
        }
      }
      this.toggle = function (state) {
        self.state = (typeof state == 'undefined') ? 1 - self.state : state;
        _toggle(toggleA, self.state);
        _toggle(toggleB, 1 - self.state);
      }
      var i = 0,
        h;
      while (h = hotspots[i++]) {
        applyEach(function (link) {
          addClickHandler(link, cancelBubble);
        }, h.getElementsByTagName("A"));
        h.style.cursor = "pointer";
        $(h).attr('tabindex', '0').keydown(function (event) {
          if (event.which == 13) { // Enter
            self.toggle();
          }
        });
        addClickHandler(h, function () {
          self.toggle();
        });
      }
    };

    $(function () {
      if (!window.disableCollapse) {
        // init
        var items = [];
        applyEach(function (NavFrame) {
          var i = 0,
            child = NavFrame.childNodes,
            head;
          while (head = child[i++]) {
            if (head.className && hasClass(head, "NavHead")) {
              break;
            }
          }
          items.push(new wgCollapse(head, NavFrame, NavFrame.childNodes));
        }, getElementsByClassName(document, "div", "NavFrame"));
        applyEach(function (table) {
          var rows = table.rows;
          items.push(new wgCollapse(rows[0], table, rows));
        }, getElementsByClassName(document, "table", "collapsible"));
        var item, i = 0,
          count = items.length;
        while (item = items[i++]) {
          item.toggle(
          hasClass(item.container, "collapsed") || (count >= JSConfig.autoCollapse && hasClass(item.container, "autocollapse")));
        }
      }
    });
    // 修正摺疊後定位變化
    hookEvent("load", function () {
      if (location.hash) {
        location.href = location.hash;
      }
    });

    /* 取消討論頁的[+]按鈕 */
    $(function () {
      if ($('#no-newsection').length) {
        $('#ca-addsection').css('display', 'none');
      }
    });

    /* 避免在主條目中出現捲軸框 */
    if (!wgCanonicalNamespace) $(function () {
      var disableDivOverflowScroll = function (obj) {
        var targetdiv;
        for (var i = obj.childNodes.length; i-- > 0;) {
          if (obj.childNodes[i] && ("" + obj.childNodes[i].tagName).toLowerCase() == "div") {
            targetdiv = obj.childNodes[i];
            if (("" + targetdiv.className).indexOf("noprint") == -1 && ("" + targetdiv.className).indexOf("thumb") == -1) {
              if ( !! (targetdiv.style.overflow) || !! (targetdiv.style.overflowY)) with(targetdiv.style) {
                overflowY = "visible";
                padding = "";
                border = "";
                height = "";
              }
              disableDivOverflowScroll(targetdiv);
            }
          }
        }
      }
      disableDivOverflowScroll(document.getElementsByTagName("body")[0]);
    });

    /** metaBox
     *
     * Funcionament de la Plantilla:Metacaixa
     * Implementat per: Usuari:Peleguer.
     * Actualitzat per Joanjoc seguint les indicacions d'en Martorell
     */
    function MetaCaixaInit() {
      // S'executa al carregar-se la pàgina, si hi ha metacaixes,
      // s'assignen els esdeveniments als botons
      //alert("MetaCaixaInit");
      var i = 0 // Inicialitzem comptador de caixes
      for (i = 0; i <= 9; i++) {
        var vMc = document.getElementById("mc" + i);
        if (!vMc) break;
        //alert("MetaCaixaInit, trobada Metacaixa mc"+i);
        var j = 1 // Inicialitzem comptador de botons dins de la caixa
        var vPsIni = 0 // Pestanya visible inicial
        for (j = 1; j <= 9; j++) {
          var vBt = document.getElementById("mc" + i + "bt" + j);
          if (!vBt) break;
          //alert("MetaCaixaInit, trobat botó mc"+i+"bt"+j);
          vBt.onclick = MetaCaixaMostraPestanya; // A cada botó assignem l'esdeveniment onclick
          //alert (vBt.className);
          if (vBt.className == "mcBotoSel") vPsIni = j; // Si tenim un botó seleccionat, en guardem l'index
        }
        //alert ("mc="+i+", ps="+j+", psini="+vPsIni );
        if (vPsIni == 0) { // Si no tenim cap botó seleccionat, n'agafem un aleatòriament
          vPsIni = 1 + Math.floor((j - 1) * Math.random());
          //alert ("Activant Pestanya a l'atzar; _mc"+i+"bt"+vPsIni +"_");
          document.getElementById("mc" + i + "ps" + vPsIni).style.display = "block";
          document.getElementById("mc" + i + "ps" + vPsIni).style.visibility = "visible";
          document.getElementById("mc" + i + "bt" + vPsIni).className = "mcBotoSel";
        }
      }
    }

    function MetaCaixaMostraPestanya() {
      // S'executa al clicar una pestanya,
      // aquella es fa visible i les altres s'oculten
      var vMcNom = this.id.substr(0, 3); // A partir del nom del botó, deduïm el nom de la caixa
      var vIndex = this.id.substr(5, 1); // I l'index
      var i = 1
      for (i = 1; i <= 9; i++) { // busquem totes les pestanyes d'aquella caixa
        //alert(vMcNom+"ps"+i);
        var vPsElem = document.getElementById(vMcNom + "ps" + i);
        if (!vPsElem) break;
        if (vIndex == i) { // Si és la pestanya bona la mostrem i canviem la classe de botó
          vPsElem.style.display = "block";
          vPsElem.style.visibility = "visible";
          document.getElementById(vMcNom + "bt" + i).className = "mcBotoSel";
        } else { // Sinó, l'ocultem i canviem la classe de botó
          vPsElem.style.display = "none";
          vPsElem.style.visibility = "hidden";
          document.getElementById(vMcNom + "bt" + i).className = "mcBoto";
        }
      }
      return false; // evitem la recàrrega de la pàgina
    }
    addOnloadHook(MetaCaixaInit);

    /* 智能讨论页编辑(新建) */
    $(function () {
      var catalk = $('#ca-talk');
      if (catalk.hasClass('new') && wgNamespaceNumber != 2) {
        var a = $('a:first', catalk);
        a.attr('href', a.attr('href') + '&section=new');
      }
    });

    /** Magic editintros
     *
     * Description: Adds editintros on disambiguation pages and BLP pages.
     * Maintainers: [[:en:User:RockMFR]], [[User:PhiLiP]]
     */
    var addEditIntro = function (name) {
      $('#ca-edit, .editsection').each(function () {
        $('a', this).attr('href',
        $('a', this).attr('href') + '&editintro=' + mw.util.wikiUrlencode(name));
      });
    };

    if (wgNamespaceNumber == 0) {
      $(function () {
        var uei = $('#useeditintro, .useeditintro');
        if (uei.length) {
          addEditIntro(uei.eq(-1).attr('title'));
          uei.attr('title', '');
        }
      });
    }

    /* Top icon: [[Template:Topicon]] */
    $(function () {
      // nostalgia, standard and cologneblue use .pagetitle
      // what's the problem on modern?
      $('<div />').css('float', 'right').append($('.topicon').css({
        'float': 'right',
        'position': 'static'
      }).show()).insertBefore('#firstHeading span[dir=auto], #article .pagetitle span[dir=auto]');
    });

    /* 引用錯誤標籤名字解碼 */
    $(function () {
      $('.anchordecodeme').each(function () {
        $(this).text(decodeURIComponent($(this).text().replace(/\.([0-9A-F]{2})/g, '%$1')));
      });
    });

    /** &withCSS= and &withJS= URL parameters
     * Allow to try custom scripts from MediaWiki space 
     * without editing personal .css or .js files
     */
    {
      var extraCSS = mw.util.getParamValue("withCSS");
      if ( extraCSS && extraCSS.match(/^MediaWiki:[^&<>=%]*\.css$/i) ) {
        importStylesheet(extraCSS);
      }
      var extraJS = mw.util.getParamValue("withJS");
      if ( extraJS && extraJS.match(/^MediaWiki:[^&<>=%]*\.js$/i) ) {
        importScript(extraJS);
      }
    }

    /* 页面历史加&hilight=高亮 */
    {
       var hilight = mw.util.getParamValue('hilight');
       if (wgAction === 'history' && hilight) {
          $.each(hilight.split(','), function (_, v) {
             $('input[name=oldid][value=' + v + ']').parent().addClass('not-patrolled');
          });
       }
    }

    /* 维基百科语言列表 */
    if (mw.config.get('wgIsMainPage') || wgPageName == 'Wikipedia_talk:首页' || wgPageName.indexOf("Wikipedia:首頁/自訂首頁設計/") == 0) {
      $(function () {
        mw.util.addPortletLink('p-lang', wgScriptPath + '/index.php?title=Wikipedia:维基百科语言列表', wgULS('维基百科语言列表', '維基百科語言列表'), 'interwiki-completelist', wgULS('维基百科的完整各语言列表', '維基百科的完整各語言列表'));
      });
    }
  })(jQuery, mediaWiki);
});