MediaWiki:Common.js: Difference between revisions
Jump to navigation
Jump to search
Jack Phoenix (talk | contribs) (JSHinting, coding conventions, removed commented-out Google Analytics stuff) |
Bizzeebeever (talk | contribs) (Added code to properly open external links in a new tab, as the server-side setting doesn't work right) |
||
Line 101: | Line 101: | ||
;( function() { |
;( function() { |
||
var pageName = mw.config.get( 'wgPageName' ), |
var pageName = mw.config.get( 'wgPageName' ), |
||
+ | skin = mw.config.get( 'skin' ), |
||
isArticle = mw.config.get( 'wgIsArticle' ), |
isArticle = mw.config.get( 'wgIsArticle' ), |
||
reskin = { |
reskin = { |
||
Line 143: | Line 144: | ||
'Rp:': '', |
'Rp:': '', |
||
'ROT13': '', |
'ROT13': '', |
||
− | 'SOPA': ( /^(vector|monobook)$/.test( |
+ | 'SOPA': ( /^(vector|monobook)$/.test( skin ) ) ? 'SOPA ' + skin + '.css' : undefined, |
'Sdrawkcab': '', |
'Sdrawkcab': '', |
||
'Slime_Cube': '', |
'Slime_Cube': '', |
||
Line 453: | Line 454: | ||
} ); |
} ); |
||
} |
} |
||
+ | |||
+ | /** Open external links in new tab (better than $wgExternalLinkTarget) *** |
||
+ | * see: [[Forum:External_links_to_open_in_a_new_tab_or_window]] |
||
+ | * this is better-behaved than the server-side setting |
||
+ | */ |
||
+ | $( document ).on( 'click', 'a[href]', function( e ) { |
||
+ | if ( !this.href.match( mw.config.get( 'wgServer' ) ) ) |
||
+ | this.target = '_BLANK'; |
||
+ | }); |
||
+ | |||
//============TODO=============== |
//============TODO=============== |
Revision as of 03:52, 22 November 2015
/**
* Some tips when editing this page...
*
** Make sure that your code has been tested in the latest version of Firefox AND Internet Explorer! (Nobody cares about older versions)
** No compressed JS. Ever. As of MediaWiki 1.19+ we have [[mw:ResourceLoader]] to compress JS and make it fugly.
** Make sure that your code follows some coding conventions, preferrably MediaWiki's (see http://www.mediawiki.org/wiki/Manual:Coding_conventions)
*
* Your friendly neighborhood MediaWiki developer,
* --Jack Phoenix, 26 July 2009
* <jack@countervandalism.net>
*/
/* global mw, mwCustomEditButtons */
var $j = jQuery; //Touch this, and I will kill you.
// A stupid hack to account for the fact that you can't redirect to special pages. --[[User:Bizzeebeever]] 2014-06-06
;( function() {
if ( location.href.match( /(Uncyclopedia:Chat|UN:CHAT|UN:IRC)$/ ) ) { // ends with this string
location.href = '/wiki/Special:WebChat';
}
})();
// * @name jquery-onAvailable
// * @dependencies jquery
// * @source
// * @revision 1.1
// * @revision date Jan 15, 2013
// * @author: Bizzeebeever, David Furfero
// * @license unknown
// * @comment based on jquery-onAvailable by David Furfero (https://github.com/furf/jquery-onavailable)
// * @comment Example: $.onAvailable( /* String */ id, /* Function */ callback, /* Object */ [overrideObj] );
// * @comment overrideObj overrides the scope (the DOM element referenced by id) of callback
if ( !jQuery.onAvailable ) {
( function ( $ ) {
$.extend( {
onAvailable: function( id, callback, override, cc ) {
if ( typeof callback !== 'function' ) {
throw new TypeError();
}
var ids = !( id instanceof Array ) ? [ id ] : id,
oA = $.onAvailable;
for ( var i = 0; i < id.length; ++i )
oA.listeners.push( {
id: ids[i],
callback: callback,
override: override,
checkContent: !!cc
} );
if ( !oA.interval ) {
oA.interval = window.setInterval( oA.checkAvailable, oA.POLL_INTERVAL );
}
return this;
},
onContentReady: function( id, callback, override ) {
$.onAvailable( id, callback, override, true );
}
} );
$.extend( $.onAvailable, {
POLL_RETRIES: 2000,
POLL_INTERVAL: 20,
interval: null,
listeners: [],
executeCallback: function( elem, obj ) {
var scope = obj.override ? obj.override : elem;
obj.callback.call( scope, obj.obj );
},
checkAvailable: function() {
var oA = $.onAvailable;
for ( var i = 0; i < oA.listeners.length; ++i ) {
var obj = oA.listeners[i];
var elem = document.getElementById( obj.id );
if ( elem && ( !obj.checkContent || ( obj.checkContent && ( elem.nextSibling || elem.parentNode.nextSibling || $.isReady ) ) ) ) {
oA.executeCallback( elem, obj );
oA.listeners.splice( i, 1 );
--i;
}
if ( oA.listeners.length === 0 || --$.onAvailable.POLL_RETRIES === 0 ) {
oA.interval = window.clearInterval( oA.interval );
}
}
}
} );
} )( jQuery );
}
/** Reskin parser ***********************************************************
* Instructions:
* 1) Use the full page name, INCLUDING NAMESPACE
* USE UNDERSCORES *NOT* SPACES
* Example:
* 'HowTo:Set_yourself_on_fire': '',
* If the stylesheet for [[HowTo:Set yourself on fire]] already
* exists at [[MediaWiki:Skin/Some crummy stylesheet.css]],
* do it this way:
* 'HowTo:Set_yourself_on_fire': 'Some crummy stylesheet.css',
*
* 2) If the stylesheet you want to use doesn't exist yet,
* create MediaWiki:Skin/Name_Space:Page_Name.css and
* place reskin CSS content there.
*/
;( function() {
var pageName = mw.config.get( 'wgPageName' ),
skin = mw.config.get( 'skin' ),
isArticle = mw.config.get( 'wgIsArticle' ),
reskin = {
'Main_Page': '',
'Main_Page_test': 'Fullscreen.css',
'UnNews:Main_Page': 'UnNewsNew.css',
'UnNews:Main_Page_Beta': 'UnNewsNew.css',
'UnNews:Religion_Section': 'UnNewsNew.css',
')': 'Sdrawkcab.css',
'AAAAAAAAA!': 'Aaaa.css',
'An:': '',
'Babel:666': '',
'Babel:96': '',
'Babel:Aa': 'Aaaa.css',
'Babel:Ap': 'Fullscreen.css',
'Babel:APPL': 'Fullscreen.css',
'Babel:CaD': '',
'Babel:Communpedia': 'Communpedia.css',
'Babel:F@H': '',
'Babel:Gbs': '',
'Babel:Hi': '',
'Babel:Pumpkin': 'Fullscreen.css',
'Babel:Newspeak': '',
'Babel:US': '',
'Babel:Vogon': 'Vg:.css',
'Babel:W2': 'Fullscreen.css',
'Cart': 'Fullscreen.css',
'EBay': '',
'Ea:': 'Fullscreen.css',
'Em:': '',
'File_8AO4F:_The_God_Case': 'Fullscreen.css',
'Half-Life_2:_Episode_Three': 'Fullscreen.css',
'Kenny_McCormick': '',
'Loneliness': 'Em:.css',
'Talk:Loneliness': 'Em:.css',
'Memento': '',
'Movie_Trailer_Announcer_Guy': '',
'MS_Paint': '',
'Namespace:Main_Page': '',
'Nihilism': '',
'Rafael_Nadal': '',
'Rp:': '',
'ROT13': '',
'SOPA': ( /^(vector|monobook)$/.test( skin ) ) ? 'SOPA ' + skin + '.css' : undefined,
'Sdrawkcab': '',
'Slime_Cube': '',
'Time_Cubicle': 'Slime Cube.css',
'The_Consumerist': '',
'Tx:': '',
'UnTunes:Artsy_and_Misunderstood:_A_Bedroom_Emo_Song': 'Em:.css',
'Uncyclopedia!_Answers': 'Fullscreen.css',
'Upside_Down': '',
'User:02barryc/UnNews/Site2': '',
'User:Bradaphraser/SupperBowl': '',
'User:Codeine/Em:': 'Em:.css',
'Twm': 'TWM.css',
'User:Mhaille/UnTube': 'UnTube.css',
'User:Mhaille/Rufus': 'Rufus.css',
'User:Nacky/Phantom_of_the_Drama': 'Phantom_of_the_Drama.css',
'User:Severian/Germ_Warfare': 'Germ_Warfare.css',
'User:Spintherism/Penmanship': '',
'User:Xamralco/Christianity': 'Blue.css',
'User:Zombiebaron/wip/Deeply_Undercovered': 'Fullscreen.css',
'User:Zombiebaron/Uncyclopedia_Reskin_Committee/Defacebook': 'Defacebook.css',
'User:Kelpan/Conservapedia': 'Conservapedia.css',
'Vd:': '',
'Wikimedia_fundraising': '',
'Wikimedia_fundraising/Zombiebaron': '',
'Wikipedia': '',
'Yahoo!': 'Fullscreen.css'
// Make sure all lines in this list except the last one have a comma after!
},
cssPath = mw.config.get( 'wgServer' )
+ mw.config.get( 'wgScript' )
+ '?title=MediaWiki:Skin/'
+ ( reskin[ pageName ] || ( pageName + '.css' ) )
+ '&action=raw&ctype=text/css';
if ( reskin[ pageName ] !== undefined && isArticle ) {
mw.loader.load( cssPath, 'text/css' );
}
} )();
/** Faux namespace crap **************************************************
* [[User:Bizzeebeever]] - 2011, 2013
* For use with [[MediaWiki:Common.css]]
* example Common.css rule:
* body.ns-[bodyClass] #p-logo > a {
* background-image: url( someimage.png );
* }
* where [bodyClass] is the CSS class you define here
*/
;( function( $ ) {
// faux-namespaces go in here vvv
var namespaces = {
//'HowTo': { tabText : 'HowTo', bodyClass: 'howto' }, //both are optional
'Un-Bestiary': { tabText: 'Bestiary' },
'Uncycloversity': { tabText: 'Resource' }
},
// extracting the "namespace" requires large amounts of extra-virgin Bolivian olive oil
namespace = mw.config.get( 'wgPageName' ).match( /^(Talk:)?([-\w\?]+)/ )[2];
function setBodyClass() {
$( 'body' ).addClass( 'ns-' + ( namespaces[namespace].bodyClass || namespace ).replace( /\W/g, '' ).toLowerCase() );
}
function setTabText() {
$( '#ca-nstab-main a' ).text( namespaces[namespace].tabText || namespace );
}
if ( namespace in namespaces ) {
$.onAvailable( 'p-logo', setBodyClass );
$.onContentReady( 'ca-nstab-main', setTabText );
}
} )( jQuery );
/** Dynamic navigation bars **********************************************
* Allows navigations templates to expand and collapse their content to save space
* Documentation on Wikipedia at [[wikipedia:Wikipedia:NavFrame|Wikipedia:NavFrame]]
* Rewritten by [[User:Bizzeebeever]] becuz he iz awesome
*/
;( function( $ ) {
// set up max count of Navigation Bars on page,
// if there are more, all will be hidden
// showDefault = 0; // all bars will be hidden
// showDefault = 1; // on pages with more than 1 bar all bars will be hidden
var showDefault = 1,
// set up the words in your language
hide = '[hide]',
show = '[show]';
// shows and hides content and picture (if available) of navigation bars
function toggle() {
var isClosed = this.data( 'isClosed' );
this.data( 'isClosed', !isClosed )
.children( '.NavContent,.NavPic' )
[ isClosed ? 'show' : 'hide' ]();
this.data( 'toggle' ).text( isClosed ? hide : show );
}
// adds show/hide-button to navigation bars
$( function() {
var $frames = $( 'div.NavFrame' ),
hideAll = $frames.length > showDefault;
$frames.each( function() {
var $t = $( this ),
isClosed = ( hideAll && !$t.hasClass( 'NavOpen' ) ) || $t.hasClass( 'NavClosed' );
$t.data( 'toggle', $( '<a/>', {
'class': 'NavToggle',
'href': 'javascript:void(0)',
'text': isClosed ? show : hide,
'click': $.proxy( toggle, $t ),
'appendTo': $t.children( '.NavHead' )
} ) );
if ( isClosed ) {
toggle.apply( $t );
}
} );
} );
} )( jQuery );
/** Another collapsible whatnits implementation **************************
* For the sidebar mostly, but can be used with whatever
* By [[User:Lyrithya]], updated by [[User:Bizzeebeever]]
* Lyrithia would've written documentation, but she couldn't be arsed.
*/
$j( function() {
$j( '.collapsed > *' ).next().hide();
$j( '.expanded > *, .collapsed > *' ).click( function() {
var $t = $j( this );
$t.next().toggle();
$t.parent().toggleClass( 'expanded collapsed' );
} );
} );
/** Logo replacement *****************************************************
* Replaces the page-logo's backgroundImage with the source of any image in
* $( '#logotipo' )
* Used by [[Template:Logo]] (and others)
* By [[User:Sikon|Sikon]], updated by [[User:Bizzeebeever]]
*/
function validateImageURL( str ) {
// may use this at some other time
//var host = ( String( str ).match( /^\w+:\/\/([^\/]+)\// ) || [ '', '' ] )[1];
var pattern = /https?:\/\/images\.uncyclomedia\.co\/uncyclopedia\/en\/([\w]+)\/([\w]+)(\/thumb)?\/([^.]+\.(gif|jpe?g|png|svg)\/?){1,2}$/i;
return ( pattern.test( str ) && ( str.length < 200 ) );
}
$j( function() {
if ( $j( '#logotipo' ).length ) {
var src = $j( '#logotipo img' ).attr( 'src' );
if ( validateImageURL( src ) ) {
$( '<a/>', {
href: '/wiki/Main_Page',
title: 'Visit the main page',
css: { 'background-image': 'url("' + src + '")' }
} )
.appendTo( $j( '#p-logo' ).empty() );
}
}
} );
/** Title replacement ****************************************************
* Rewrites the page's title, used by [[Template:Title]]
* Should use {{DISPLAYTITLE}}, unless you want to use an image
* By [[User:Sikon|Sikon]], updated by [[User:Bizzeebeever]]
*/
$j( function() {
var $title = $j( '#title-meta' ),
text = $title.text().toLowerCase(),
name = mw.config.get( 'wgPageName' ).replace( /_/g, '' ).toLowerCase();
if ( $title.length && !window.SKIP_TITLE_REWRITE ) {
$title.appendTo( $j( '#firstHeading' ).empty() ).show();
if ( text == name ) {
document.title = text;
}
}
} );
/** Logo remover *********************************************************
* Used by [[Template:Nologo]]
* By some idiot, updated by [[User:Bizzeebeever]]
*/
$j( function() {
if ( $j( '#nologo' ).length ) {
$j( '#p-logo' ).hide();
}
} );
/** Title remover ********************************************************
* Used by [[Template:Notitle]]
* By some idiot, updated by [[User:Bizzeebeever]]
*/
$j( function () {
if ( $j( '#notitle' ).length ) {
$j( '#firstHeading' ).hide();
}
} );
/** Categories remover ***************************************************
* Used by [[Template:Nocategories]]
* By some idiot, updated by [[User:Bizzeebeever]]
*/
$j( function() {
if ( $j( '#nocategories' ).length ) {
$j( '#catlinks' ).hide();
}
} );
/** Show username ********************************************************
* The annoying hack used by [[Template:USERNAME]]!
* Inserts user name into <span class='insertusername'></span>
* Originally by [[wikia:User:Splarka|Splarka]], [[User:Spang]]
* New version by [[User:Bizzeebeever]]
*/
$j( function() {
var name = mw.config.get( 'wgUserName' );
if ( !window.disableUsernameReplace && name ) {
$j( 'span.insertusername' ).text( name );
}
} );
/** Archive edit tab disabling *******************************************
* Disables the edit tab on old forums to stop noobs from bumping them.
* Page can still be edited by going via the edit tab on the history etc,
* or by typing the edit address manually.
* By [[User:Spang|Spang]], rewritten by [[User:Bizzeebeever]]
*/
$j( function() {
if ( $j( '#old-forum-warning' ).length && !window.enableOldForumEdit ) {
$j( '#ca-edit a' ).removeAttr( 'href' )
.css( 'color', 'gray' )
.text( 'No editing' );
}
} );
/** Add-section tab disabling ********************************************
* Disables the add section tab on any page you like, mainly useful for
* your user page (depending on how you have your user page set up)
* To use it: include any HTML element with an ID of disableAddSection
* example: <div id="disableAddSection"></div>
* By [[User:Olipro|Olipro]], updated by [[User:Bizzeebeever]]
*/
$j( function() {
if ( $j( '#disableAddSection' ).length ) {
$j( '#ca-addsection' ).remove();
}
} );
/** Forum talkpage tab **************************************************
* If #talkforum present, adds talkpage tab back to forum talk pages.
* Why? Hellifiknow.
* Blame <some idiot> and/or [[User:Bizzeebeever]]
*/
$j( function() {
if ( $j( '#talkforum' ).hide().length ) {
$j( '#ca-talk' ).css( 'display', 'block !important' );
}
} );
/** UnNews edit link remover **********************************************
* Removes the edit links from the UnNews Main Page if you're not signed in
* as a user, since these pages are semi-protected and always will be.
* Is this even needed?
*/
if( mw.config.get( 'wgPageName' ) == 'UnNews:Main_Page' && !mw.config.get( 'wgUserName' ) ) {
$j( function() {
$j( '.editor' ).remove();
} );
}
/** Remove example text **************************************************
* Automatically removes any example text left on the page upon saving.
* By [[User:Spang]], updated by [[User:Bizzeebeever]]. FU SPANG!
* Can't use $.live(), because it is deprecated. FU JQUERY!
*/
$j( document ).on( 'submit', '#editform', function() {
var $box = $j( '#wpTextbox1' ),
text = $box.val().replace( /||\[\[Link title\]\]|\[http:\/\/www\.example\.com link title\]|\n== Headline text ==\n|\[\[Image:Example\.jpg\]\]|\[\[File:Example\.jpg\]\]|<math>Insert formula here<\/math>|<nowiki>Insert non-formatted text here<\/nowiki>|<code><\/code>|\[\[Media:Example\.ogg\]\]|\n(?=\n\n\n)/g, '' );
$box.val( text ).scrollTop( $box.scrollTop() );
return true;
} );
/** Featured Interwiki ***************************************************
* Stolen from Wikipedia, updated by [[User:Bizzeebeever]]
*/
$j( function() {
$j( '#p-lang li' ).each( function() {
var $li = $j( this );
if ( $j( '#' + $li.attr( 'class' ) + '-fa' ).length ) {
$li.addClass( 'FA' ).attr( 'title', 'This is a featured article in another language' );
}
} );
} );
/** IP template for [[Uncyclopedia:Ban Patrol]]***************************
* Others can be added for other or all pages.
*/
if ( window.mwCustomEditButtons && mw.config.get( 'wgPageName' ) == 'Uncyclopedia:Ban_Patrol' ) {
mwCustomEditButtons.push( {
'imageFile': 'http://images.uncyclomedia.co/uncyclopedia/en/d/d7/IP_button.png',
'speedTip': 'IP template',
'tagOpen': '{' + '{' + 'IP|',
'tagClose': '}' + '}',
'sampleText': '127.0.0.1'
} );
}
/** Open external links in new tab (better than $wgExternalLinkTarget) ***
* see: [[Forum:External_links_to_open_in_a_new_tab_or_window]]
* this is better-behaved than the server-side setting
*/
$( document ).on( 'click', 'a[href]', function( e ) {
if ( !this.href.match( mw.config.get( 'wgServer' ) ) )
this.target = '_BLANK';
});
//============TODO===============
//#localNotice {margin: 0 !important;}
//#mw-dismissable-notice div[style="float: right;"] {display: none;}
/** Dismiss notice remover
* (only removes if you have made a custom sitenotice designed to use its own close button)
*/
$( function() {
if ( $j( '#siteNoticehide' ).length ) {
$j( '#localNotice' ).css( 'margin', '0 0 .9em 0' );
$j( '#mw-dismissable-notice div[style="float: right;"]').css( 'display', 'none' );
$j( '#siteNoticehide > a' ).attr( 'href', 'javascript:dismissNotice();' );
// Because caching and stupidity, dammit.
$j( 'div[style="position:absolute; right:7px; top:4px; font-size:16px;"] > a' ).attr( 'href', 'javascript:dismissNotice();' );
if ( $j( '#mw-dismissable-notice' ).length === 0 ) {
$j( '#siteNoticehide' ).css( 'display', 'none' );
}
}
} );
/** Embed flash movies **************************************************
* Allows embedding of flash files in a page. Only enabled in userspace currently.
* See [[Template:Flash]]
* By [[User:Olipro|Olipro]]
*/
/* Disabling for now, there is a replacement at {{Flash2}}
var flashOk;
function embedFlashMovie( flashOk ) {
var mainbody = document.getElementById( 'bodyContent' );
mainbody.innerHTML = contentTempHolder;
var spancheck = document.getElementsByTagName( 'span' );
for ( var i = 0; i < spancheck.length; i++ ) {
if ( spancheck[i].getAttribute( 'id' ) != 'embedFlashDoc' ) {
continue;
}
var obj = spancheck[i].innerHTML.split( '@' );
var flwidth = obj[0];
var flheight = obj[1];
var flfile = obj[2].replace( 'fullurl://', 'http://' );
var showFlash = ' ';
if ( flashOk ) {
showFlash = '<object width="' + flwidth + '" height="' + flheight + '"';
showFlash += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
showFlash += 'codebase="http://fpdownload.macromedia.com/pub/';
showFlash += 'shockwave/cabs/flash/swflash.cab#version=8,0,0,0">';
showFlash += '<param name="movie" value="' + flfile + '" />';
showFlash += '<embed src="' + flfile + '" width="' + flwidth + '" height=';
showFlash += '"' + flheight + '" type="application/x-shockwave-flash" ';
showFlash += 'pluginspage="http://www.macromedia.com/go/getflashplayer" />';
showFlash += '</object>';
} else {
showFlash = '<a class="plainlinks" href="javascript:embedFlashMovie(true)" onClick="embedFlashMovie(true)">' + flfile + '</a> (Click to show)';
}
spancheck[i].innerHTML = showFlash;
spancheck[i].style.display = 'inline';
}
}
var contentTempHolder;
function embedFlashCheck() {
if ( !document.getElementById( 'embedFlashDoc' ) ) {
return;
}
var mainbody = document.getElementById( 'bodyContent' );
contentTempHolder = mainbody.innerHTML;
if ( typeof displayFlashOverride != 'undefined' ) {
embedFlashMovie( displayFlashOverride );
return;
}
var askmessage = '<div align="center" id="askflash">This page contains ';
askmessage += '<a href="/wiki/Flash_Gordon" class="plainlinks">Flash</a>; would you ';
askmessage += 'like to see it? <b><a href="javascript:embedFlashMovie(true)" ';
askmessage += 'onClick="embedFlashMovie(true)">Yes</a> | <a ';
askmessage += 'href="javascript:embedFlashMovie(false)" ';
askmessage += 'onClick="embedFlashMovie(false)">No</a> | <a ';
askmessage += 'href="/index.php?title=User:' + mw.config.get( 'wgUserName' ) + '/' + mw.config.get( 'skin' ) + '.js&';
askmessage += 'action=edit§ion=new&preload=Template:Flash/disable">';
askmessage += 'Don\'t show this again</a></b></div>';
mainbody.innerHTML = askmessage;
}
addOnloadHook( embedFlashCheck );*/
mw.loader.load( '//en.uncyclopedia.co/w/index.php?title=MediaWiki:Spackling_of_cats.js&action=raw&ctype=text/javascript' );