MediaWiki:Common.js

From NetHackWiki
Revision as of 16:53, 22 August 2017 by Ilmari Karonen (talk | contribs) (remove unnecessary mw.loader.using() call, it might be slowing things down)
Jump to navigation Jump to search

Note: After saving, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Internet Explorer: Hold Ctrl while clicking Refresh, or press Ctrl-F5
  • Opera: Go to Menu → Settings (Opera → Preferences on a Mac) and then to Privacy & security → Clear browsing data → Cached images and files.
//<syntaxhighlight lang="javascript">
( function () {  // begin local scope

/*
 * Preload some config settings to avoid deprecation warnings.
 */ 
var wgPageName = mw.config.get('wgPageName');
var wgUserName = mw.config.get('wgUserName');
var wgAction = mw.config.get('wgAction');
var wgNamespaceNumber = mw.config.get('wgNamespaceNumber');
var wgCanonicalNamespace = mw.config.get('wgCanonicalNamespace');
var wgScript = mw.config.get('wgScript');
var wgScriptPath = mw.config.get('wgScriptPath');
var wgScriptExtension = mw.config.get('wgScriptExtension');


/*
 * Compatibility wrapper around mw.loader.load():
 */
window.importScript = function (page) {
  mw.loader.load( wgScript + '?title=' + encodeURIComponent(page) + '&action=raw&ctype=text/javascript' );
}


/*
 * Greet registered users by name on Main Page, hide the spoiler warning and load random ttymap.
 */
if (wgPageName == 'Main_Page') {
  var mainPageStyle = document.createElement('style');
  mainPageStyle.type = 'text/css';
  if (typeof wgUserName == 'string') {
    var escapedName = wgUserName.replace(/['"\\\n]/, '\\$1');
    mainPageStyle.textContent =
      '#mainpage-greet-username::before { content: "\\A0 ' + escapedName + '" }\n' +
      '#mainpage-hide-registered { display: none }\n';
  } else {
    mainPageStyle.textContent = '#ca-talk { display: none }\n';
  }
  document.head.appendChild(mainPageStyle);

  jQuery( document ).ready( function( $ ) {
    $('#mainpage-ttyscreen').load('/wiki/Special:RandomInCategory/Main_Page_rotation .ttyscreen');
  } );
}

/*
 * AJAX login popup
 */
if (wgUserName === null) importScript("MediaWiki:AJAXLogin.js");

/*
   Changes <span class="NH_replacechars">{{cyan|@}}</span>
   so that it'll show the logical color symbol, but clicking on it
   will do insertTags('{{cyan|@}}', '', '')

   Used in http://nethackwiki.com/wiki/MediaWiki:Edittools

   Relies on specific behaviour of the logical color templates:
   http://nethackwiki.com/wiki/Category:Function_templates
*/
function WikiHack_replacechars()
{
  var l = document.getElementsByTagName('span');
  if (!l) return;
  for (var i = 0; i < l.length; i++) {
    if (l[i].className == "NH_replacechars") {
      for (var j = 0; j < l[i].childNodes.length; j++) {
        var fc = l[i].childNodes[j];
        if (fc.className && fc.className.match(/^nhsym clr-/)) {
          var clr = fc.className.replace("nhsym clr-", "");
          var chr = fc.innerHTML;
          var a = document.createElement('a');
          a.setAttribute('href', 'javascript:insertTags("{"+"{"+"'+clr+'|'+chr+'"+"}"+"}","","");');
          a.appendChild(fc.cloneNode(true));
          l[i].replaceChild(a, fc);
        }
      }
    }
  }
}


if(wgAction == 'edit' || wgAction == 'submit' ||
  (wgAction == 'view' && wgPageName == 'Special:Upload')) {
   importScript('MediaWiki:Common.js/nhsympopup.js');
}


if(wgAction == 'edit' || wgAction == 'submit') {

  /***** Custom edit buttons *****/
  /* Only used if "Editing->Show edit toolbar" in Preferences is ticked. */
  mw.loader.using( ['mediawiki.toolbar'] ).done( function () {
	mw.toolbar.addButtons( {
	  "imageFile": "/images/nethackwiki/Button_redirect.png",
	  "speedTip": "Redirect",
	  "tagOpen": "#REDIRECT [[",
	  "tagClose": "]]",
	  "sampleText": "Insert text"},
	{
	  "imageFile": "/images/nethackwiki/Button_table.png",
	  "speedTip": "Insert a table",
	  "tagOpen": '{| class="prettytable striped"\n|-\n',
	  "tagClose": "\n|}",
	  "sampleText": "! header 1\n! header 2\n! header 3\n|-\n| row 1, cell 1\n| row 1, cell 2\n| row 1, cell 3\n|-\n| row 2, cell 1\n| row 2, cell 2\n| row 2, cell 3"},
	{
	  "imageFile": "/images/nethackwiki/Button_enter.png",
	  "speedTip": "Line break",
	  "tagOpen": "<br />",
	  "tagClose": "",
	  "sampleText": ""} );
  } );

  // check for signature on talk page edits
  // based on http://en.wikipedia.org/wiki/User:Ilmari_Karonen/signcheck.js
  if (wgNamespaceNumber % 2 == 1 || wgCanonicalNamespace == "Forum" || wgCanonicalNamespace == "Project") jQuery(function () {
      if (window.disableSignCheck) return;  // has the user disabled this feature?
      if (!document.editform || !document.editform.wpSave || !document.editform.wpTextbox1) return;
      var nowikiRegexp = /<(nowiki|pre|source|syntaxhighlight)(\s[^>*])?>.*?<\/\1>/g;
      if (wgCanonicalNamespace == "Project") {  // not all project pages are discussions
          var wpSection = document.editform.wpSection;
          var isDiscussion = function (text) {
              text = text.replace(nowikiRegexp, '$1');
              return /_{2}NEWSECTIONLINK_{2}/.test(text);
          };
          if (!wpSection || wpSection.value == "") {  // if not editing a section, we can just check the source
              if (!isDiscussion(document.editform.wpTextbox1.value)) return;
          } else if (wpSection.value != "new") {  // if editing a new section, this must be a discussion page
              // editing an existing section is the hard case: we must do an API query
              window.signCheckAPICallback = function (json) {
                  for (id in json.query.pages) {
                      var text = json.query.pages[id].revisions[0]['*'];
                      if (!isDiscussion(text)) window.disableSignCheck = true;
                  }
              };
              importScriptURI(wgScriptPath + '/api' + (wgScriptExtension || ".php") +
                              '?format=json&callback=signCheckAPICallback&action=query&prop=revisions&rvprop=content' +
                              '&titles=' + encodeURIComponent(wgPageName) + '&maxage=3600&smaxage=3600');
          }
      }
      var oldOnclick = document.editform.wpSave.onclick;
      document.editform.wpSave.onclick = function () {
          if (oldOnclick && !oldOnclick.apply(this, arguments)) return false;
          if (window.disableSignCheck) return true;  // might've been disabled in the meanwhile
          var text = document.editform.wpTextbox1.value.replace(nowikiRegexp, '$1');
          if (text.match(/~{3}/)) return true;
          return confirm("You have not signed your name using \"--~~"+"~~\". Save anyway?" +
                         (wgUserName ? "\nYou may turn this warning off in your preferences under \"Gadgets\"." : ""));
      };
  });
}


/* Hilight a line of code in the Source-namespace, when we're given a line to go to. For example
 * http://nethackwiki.com/wiki/Source:Do.c#line1673
 */
function WikiHack_sourceline_hilite() {
  var h = window.location.hash;
  if (h.match(/^#line[0-9]+/)) {
    var e = document.getElementById(h.substring(1));
    if (e) {
      window.scrollBy(0, -(($(window).height()) / 3));
      if (document.all) { /* IE Idiocy */
        e.setAttribute('className', 'source-line-hilite');           
        e.className = 'source-line-hilite';
      }
      e.setAttribute('class', 'source-line-hilite');           
    }
  }
}

if (wgCanonicalNamespace == 'Source' && wgAction == 'view') {
  $(WikiHack_sourceline_hilite);
}
/* End of Source code line hilite */



/* Embed IRC into a page, by replacing id="IRCReplace" with freenode webchat.
   Original code by GreenReaper & ShadowTale */
$(function() {
  var nick = (wgUserName == null) ? ('NHWGuest' + Math.floor(Math.random() * 10)) : wgUserName.replace(/ /g, '_'); 
  $('#IRCReplace').html('<iframe src="http://webchat.freenode.net/?nick=' + nick + '&channels=NetHack&prompt=1&uio=MT1mYWxzZSYxMT01MQ42" style="border:0;width:inherit;height:inherit;"></iframe>');
});


importScript('MediaWiki:Common.js/showhide.js');

/*
 * Show random true rumors on Main Page (and other pages using [[Template:Random true rumor]])
 */
if ( wgPageName == "Main_Page" ) {
    importScript( 'MediaWiki:Rumors.js' );
} else {
    jQuery( document ).ready( function( $ ) {
        if ( $( '.nhw-randomtruerumor' ).length > 0 ) {
            importScript( 'MediaWiki:Rumors.js' );
        }
    } );
}

/* Allow users to click on anywhere in the [[Special:Search]] results */
if (wgPageName == 'Special:Search') {
  $('.mw-search-results li').each(function(index) {
    $(this).click(function() { document.location = $(this).find('a:first').attr('href'); } );
    });
}

} )();   // end local scope
//</syntaxhighlight>