ResourceLoader/Core modules: Difference between revisions
some line numbers updated |
→isMainPage: new section |
||
Line 615: | Line 615: | ||
} |
} |
||
</source> |
</source> |
||
=== isMainPage === |
|||
This function checks if the current page is an action of the wiki's main page (eg. view, history, edit etc.). By default it returns true if it is, and false other wise. By passing true as the first argument it will also return true if the current page is in an asociated namespace (eg. Talk:). |
|||
'''NB: This function requires the document to be ready. Be sure it's called inside a document-ready wrapper.''' |
|||
<source lang="javascript"> |
|||
// Adds an interwiki link to Meta-Wiki if we're currently viewing the article content of the Main page article (eg. the second check is to avoid running it when in edit-, delete-, history mode etc.) |
|||
if ( mw.util.isMainPage() && mw.config.get( 'wgIsArticle' ) ) { |
|||
mw.util.addPortletLink( 'p-lang', 'http://meta.wikimedia.org/wiki/List_of_Wikipedias', 'Complete list', 'interwiki-completelist', 'Complete list of Wikipedias' ); |
|||
} |
|||
// Add a special view to the tab bar when we're on a Main page-related page |
|||
// When clicked it will ask "Are you sure you" and continue if you confirm |
|||
if ( mw.util.isMainPage( true ) ) { |
|||
awesomeLink = mw.util.addPortletLink( 'p-views', mw.util.wikiGetlink('Special:Awesome/' + mw.config.get('wgPageName') ), 'Do awesome', 'ca-awesome', 'Do something awesome', null, '#ca-history' ); |
|||
$(awesomeLink).click( function(e){ |
|||
if ( !confirm( 'Are you sure you want to do something awesome ?' ) ) { |
|||
e.preventDefault(); |
|||
return false; |
|||
} |
|||
}); |
|||
} |
|||
=== jsMessage === |
=== jsMessage === |
Revision as of 18:07, 14 March 2011
This page intends to list, document, explain and give examples for all the libraries, plugins and scripts present in MediaWiki's /resources by default as of the current SVN HEAD.
The order of the modules should be kept similar to their definition in Resources.php. And the order of the headings within the modules either by order within the script file or by alphabet (whichever makes sense)
This may or may not correspond to the state in MediaWiki 1.17.
jQuery & plugins
jQuery 1.4.2 is loaded. For more information about jQuery in general and all its core functions, refer to http://api.jquery.com/
jQuery UI 1.8.2: http://jqueryui.com/demos/ The following components are included:
- jquery.ui.accordion.js
- jquery.ui.autocomplete.js
- jquery.ui.button.js
- jquery.ui.core.js
- jquery.ui.datepicker.js
- jquery.ui.dialog.js
- jquery.ui.draggable.js
- jquery.ui.droppable.js
- jquery.ui.mouse.js
- jquery.ui.position.js
- jquery.ui.progressbar.js
- jquery.ui.resizable.js
- jquery.ui.selectable.js
- jquery.ui.slider.js
- jquery.ui.sortable.js
- jquery.ui.tabs.js
- jquery.ui.widget.js
- i18n
This single-function plugin can be called to add this functionality to any number of checkboxes.
By default (onload) it's applied to all input
elements that have a type of checkbox, excluding any with a class of 'noshiftselect'. As it has a built-in prevention to avoid binding the CheckboxShiftClick twice to the same element you can simply run the line below under "Default" again at any time if you want to enable dynamically added checkboxes in the page to be shift-selectable as well.
Or alternatively run it on the specific selector of choise (see second example below).
// Default:
$( 'input[type=checkbox]:not(.noshiftselect)' ).checkboxShiftClick();
// Enable the functionality for checkboxes in dynamically created form <form id="my-tool-form">
$( 'form#my-tool-form input[type=checkbox]' ).checkboxShiftClick();
A plugin that extract information about the client's browser, layout engine and operating system.
Profile
The profile function is the main function here and returns (and caches) all the information in an object in. All possible values (except for version numbers) are predefined. A typical return looks like this:
/* jquery.client.profile() */
{
'name': 'firefox',
'layout': 'gecko',
'layoutVersion': '20101026',
'platform': 'linux'
'version': '3.5.1',
'versionBase': '3',
'versionNumber': 3.5,
}
Here a few examples
if ( $.client.profile().layout == 'gecko' && $.client.profile().platform == 'linux' ) {
// This will only run on Gecko browsers (ie. Mozilla Firefox) on Linux.
}
if ( $.client.profile().name == 'msie' ) {
// Only for good ol' Internet Explorer
}
// Shortcut
var prof = $.client.profile();
if ( prof.name == 'firefox' && prof.versionBase == '2' && prof.platform == 'win' ) {
// Target Mozilla Firefox 2.x on Windows
}
Check jquery.client.js for possible values of browser names, layout engines and platforms.
Test
...
On load
When this module is initialized it adds the four classes to the <html>
:
- client- profile.name
- client- profile.name - profile.versionBase
- client- profile.layout
- client- profile.platform
For example:
<html class="client-safari client-safari-5 client-webkit client-mac">
MediaWiki version: | trunk r79686 |
- getRGB
- colors
- rgbToHsl
- hslToRgb
- getColorBrightness
MediaWiki version: | 1.17 |
// Set cookie (simple, current page/path)
$.cookie( 'myName', 'Flower' );
// Set cookie (extra options)
$.cookie( 'myName', 'Flower', {
expires: 7, // expires in 7 days
path: '/' // domain-wide, entire wiki
} );
// Get cookie
var name = $.cookie( 'myName' );
// Delete cookie
$.cookie( 'myName', null );
MediaWiki version: | trunk r78914 |
Plugin makes all passed elements collapsible. It supports lots of variations such as:
- Simple
- Add "
mw-collapsible
" to a<div>
with some content and save the page. The inner content of this<div>
will be detected as collapsible content and a toggle-link will be added with a localized label (collapsible-expand, collapsible-collapse) - Initial state
- Adding '"
mw-collapsed
'" as additional class will cause the element to be initially collapsed when the page is loaded. - Custom label
- HTML5 only Using the data-collapsetext and data-expandtext attributes one can define a custom text for the toggle labels added by the script. When added in wikitext these could populated by a localized message like:
<div class="mw-collapsible" data-expandtext="{{int:show}}" data-collapsetext="{{int:hide}}">
- Remote toggle
- If you don't want the script to put the default toggle link (wether or not with a custom label) in your element, you can make one of your own. This could reside anywhere inside or outside the collapsible element. It's relationship to the collapsible element is detected by using the prefix
mw-customcollapsible
andmw-customtoggle
for the collapsible element and the togglelink respectively.
Example: Simple collapsible div or table
Input:
{| class="infobox"
! Foo
| Bar
|-
! Lorem
| Ipsum
|-
! More info
|<!--
-->
{| class="wikitable mw-collapsible mw-collapsed" style="width:100%"
! Head
! Top
|-
| Cell
| content
|-
| This table is collapsible
| Because it has the "mw-collapsible" class
|-
| It was initially hidden, because it
| had the "mw-collapsed" class
|}<!--
-->
|-
|}
<div class="toccolours mw-collapsible" style="width:400px">
This is text is collapsible. {{Lorem}}
</div>
Output:
Foo | Bar | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|
Lorem | Ipsum | ||||||||||
More info |
|
Example: Hide the collapsible element by default, the toggle element resides outside of it
<div class="mw-customtoggle-myDivision" style="background:#e0e8ff">Click here to toggle the element</div>
<div class="mw-collapsible mw-collapsed" id="mw-customcollapsible-myDivision">
<div class="toccolours mw-collapsible-content">Lorem ipsum dolor sit amet...</div>
</div>
<div class="mw-customtoggle-myDivision" style="background:#e8ffe0">Clicking will toggle it also!</div>
For live examples, see TranslateWiki - Collapsing Testpage
This plugin adds support for placeholder texts in input fields for browsers that don't support the HTML5 attribute yet. If the attribute is not supported it's applied to all input elements with a 'placeholder' attribute, on-load.
It has a built-in check for browser support, but for efficiency it's best to do this check (also) wrapped around to call.
// Default:
if ( !( 'placeholder' in document.createElement( 'input' ) ) ) {
$('input[placeholder]').placeholder();
}
// Example for your dynamically added foobar fields
$("form#foobar-ajax input[placeholder]").placeholder();
MediaWiki version: | 1.17 |
There are several prototypes for older browsers serving as backwards-compatibility for new native prototypes in newer browser. Also several other convenience functions have been added.
- trimLeft
- Trims whitespace from the left side of the string
- trimRight
- Trims whitespace from the right of the string
- ucFirst
- Returns the string with the first character capitalized
- escapeRE
- Returns a string for literal use in a regular expressions by escaping characters that have a special meaning in a regex.
- isDomElement
- Check whether a passed a variable is a direct link to an element.
- isEmpty
- This function checks if a variable is empty. Supports strings, booleans, arrays and objects. The string "0" is considered empty. A string containing only whitespace (ie. " ") is considered not empty. (Since • r77127)
- compareArray
- Compares two arrays and returns a boolean for whether they are in fact the same
- compareObject
- Compares two objects for it's properties and values (recursive) (Since • r78345)
/**
* Trim
*/
$.trimLeft(' foo bar '); // "foo bar ";
$.trimRight(' foo bar '); // " foo bar";
$.trim(' foo bar '); // "foo bar";
/**
* isEmpty
*/
$.isEmpty( 'string' ); // false
$.isEmpty( '0' ); // true
$.isEmpty( '' ); // true
$.isEmpty( [] ); // true
/**
* compareArray
*/
$.compareArray( [1, "a", [], [2, 'b'] ], [1, 'a', [], [2, "b"] ] ); // true
$.compareArray( [1, 2], [8, 7] ); // false
/**
* isDomElement
*/
// Sure, a plain normal dom element: True
$.isDomElement( document.getElementById('content') );
// This returns an array of dom elements, not a dom element itself: False
$.isDomElement( document.getElementsByClassName('portal') );
// This is a normal dom element: True
$.isDomElement( document.getElementsByClassName('portal')[0] );
// jQuery objects are not dom elements: False
$.isDomElement( $('#content') );
// jQuery.get(0) returns the raw dom element for the object: True
$.isDomElement( $('#content').get(0) );
// Anything else: False
$.isDomElement( 'hello world' );
MediaWiki
This is the main JavaScript library. Defined in window.mediaWiki
. Alias mw
is available everywhere and should be used.
An instance of the Map class that is global by default for backwards compatibility (in 1.17) and contains the wgVars such as wgSiteName, wgArticleId etc.
if ( mw.config.exists( 'wgGlobalGroups' ) ) {
// do stuff
}
if ( mw.config.get( 'wgPageName' ) == 'ResourcerLoader' ) {
// do stuff
}
- mw.html.escape
- Escape a string for HTML. Converts special characters to HTML entities.
mw.html.escape( '< > \' & "' );
// Returns: < > ' & "
- mw.html.element
- Creates an HTML string, with safe escaping.
// shortcut h
var h = mw.html;
var myElement = h.element(
'div', // tagName
{}, // attributes
// content:
new h.Raw( // We don't want to escape the return of h.element(), instead add it raw
// Without this the result would be '<div><img src="&lt;"/></div>'
h.element(
'img', // tagName
{ src: '<' } // attributes
)
)
);
// myElement is '<div><img src="<"/></div>' (as a string)
var h = mw.html;
var loaderContainer = h.element( 'div', { id: 'ext-foobar-loader' },
new h.Raw( h.element( 'img', {
src: mw.config.get( 'stylepath' ) + '/common/images/ajax-loader.gif',
title: 'Loading...'
}
) )
);
// loaderContainer is '<div id="ext-foobar-loader"><img src="/w/skins/common/images/ajax-loader.gif" title="Loading..."/></div>'
- mw.loader.go
- mw.loader.implement
- mw.loader.load is the loader for modules and other sources. It can be called with one or more modules by name. It can also load an external script or style URI beginning with either "http://" or "https://" and a mime-type in the second argument (either "text/css" or "text/javascript"). If no mime-type is provided, "text/javascript" is assumed. mw.loader.load creates an asynchronous request, so if you need to run code that depends on a module, use mw.loader.using instead.
// Load one module by name. Will make 1 http request loading all JS, CSS of this and it's dependencies. Will also load any needed interface messages to the memory of mw.msg mw.loader.load( 'jquery.ui.datepicker' ); // Will do all resources stuff for multiple modules at once mw.loader.load( ['jquery.ui.dialog', 'jquery.hoverIntent', 'mediawiki.foobar'] ); // Load an external javascript file as is mw.loader.load( 'http://www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400' ); // Load an external stylesheet as is mw.loader.load( 'http://example.com/mystyles.css?color=blue', 'text/css' );
- mw.loader.register
- mw.loader.state
- mw.loader.using can be called with two or three arguments (dependencies, function to execute when modules are successfully loaded, function on error)
mw.loader.using( 'jquery.colorUtil', function() { // This function wil be called right away if the required modules are already loaded // Othewise the module(s) are loaded and if all succesfull, the function is called var curColor = 'rgb(70,140,210)'; var newColor = $.colorUtil.getColorBrightness( curColor, +0.2 ); alert( '20% brigher than ' + curColor + ' is ' + newColor ); } );
- mw.loader.version
- mw.loader.work
A reusable class to store, get and set a set of variables.
The core uses this for mw.config
and mw.user.options
When making an instance the function takes one parameter which affects whether the set will be made globally available (ie. as items of window
) or local.
By default this is false (not global) and will thus not not overwrite any global variables with the same name.
- .values
- An object containing all the variables. If 'global' was true during initialization, this is an alias to the
window
object. - .exists(key)
- Function returns true if an entry with the key(s) exists, false otherwise
- .get(key, fallback)
- Returns the value of the key(s) or (optionally) the value of the second argument if the key does not exist (returns null if it doesn't exist and no fallback was provided)
- .set(key, value)
- Creates / Modifies one or multiple values
Examples
// Create a new map
var myMap = new mw.Map();
// Set a few values
myMap.set( {
'name' : 'John Doe',
'age' : 19,
'planet' : 'Earth',
'address' : 'Wikistreet 7, New York'
} );
// Set one more value
myMap.set( 'spouse', 'Jane Jackson' );
// Do something if a value is set
if ( myMap.exists( 'address' ) ) {
alert( 'This map does have a value for "address". It is: ' + myMap.get( 'address' ) );
} else {
alert( 'This map does not have a value for "address".' );
}
// Get multiple values
var NameAgeBirth = myMap.get( ['name', 'age', 'birthdate'] );
// NameAgeBirth.name is 'John Doe'
// NameAgeBirth.age is 19
// NameAgeBirth.birthdate is null
Address Book example
// Create a new map for this
var myAddressBook = new mw.Map();
// Define an object with name / address combinations
// This data could be coming from an AJAX request and/or from a database
var addresses = {
'John Doe' : 'Wikistreet 7, New York',
'Jane Jackson' : 'Oxfordstreet 21, London',
'Max Heinz' : 'Rote strasse 201, Berlin'
}
// Set the variables in the addressbook
myAddressBook.set( addresses );
// A request could come in for a few names
var wantedNames = ['Max Heinz', 'George Johnson', 'Jane Jackson'];
// Check if they all have an entry
if ( !myAddressBook.exists( wantedNames ) ) {
alert( 'One or more names do not have a known address' ); // In our example, there is no address for George Johson
}
wantedData = myAddressBook.get( wantedNames, '<em>Unknown location</em>' );
// wantedData['Jane Jackson'] is 'Oxfordstreet 21, London'
// wantedData['George Johnson'] is '<em>Unknown location</em>'
anonymous
Function returns boolean on whether the user is anonymous (true) or logged in (false).
name
Function returns the username or 'null' if logged out.
if ( !mw.user.anonymous() ) {
alert( 'You are logged in as: ' + mw.user.name() + '.' );
} else {
alert( 'You are anonymous.' );
}
options
Contains the preferences of the user, or the defaults when logged out. (Instance of the Map class)
// Get a preference option and use it directly
alert( 'According to the preferences, your gender is ' + mw.user.options.get( 'gender' ) );
// Get several preferences and compare them with $.compareObject
if ( $.compareObject( mw.user.options.get( ['diffonly', 'showhiddencats'] ), { diffonly: 0, showhiddencats : 0 } ) ) {
// User's preferences match the object
} else {
// User's preferences don't match the given set
}
sessionId
When called for the first time generates a sessionId and sets a domain-wide cookie and returns the sessionId. When it's set already (ie. after calling it, or when it was set earlier this session on another page) returns just the sessionId.
alert( 'Your sessionId is: "' + mw.user.sessionId() + '" !' );
This script is loaded in debug-mode and is an alternative to calling console.log() which would cause errors in browsers that dont have a console or dont have it enabled.
mw.log
Calling this either pushes the messages to console (if available) or adds it to an #mw-log-console (the element is created on the first call)
mw.log( 'To be logged message here' );
addCSS
Adds a <style>
element to the HEAD and returns the CSSStyleSheet object.
The CSSStyleSheet object can be used to disable the css rules at any later time and re-enable them as well. This can be done through the 'disabled' attribute. When setting this to true, the rules no longer apply. When setting to false, the rules apply again.
See also W3 on CSSStyleSheet for more info.
// Add a simple stylesheet rule
mw.util.addCSS( '.plainlinks { color:green; }' );
// Add a rule and set a variable to the sheet
var myCssRules = mw.util.addCSS( '.plainlinks { color:green; }' );
$( '#myButton' ).click( function() {
// When button is clicked, toggle the stylesheet from true to non-true (false), or from false to non-false (true)
myCssRules.disabled = !myCssRules.disabled;
} );
addPortletLink
This function is ported from the legacy wikibits keeping it fully backwards compatible, with a few adjustments that support all core skins and with added support for a CSS-selector as nextnode
.
// Add MediaWiki.org-link in the toolbox before the Print-link
mw.util.addPortletLink('p-tb', 'http://mediawiki.org/', 'MediaWiki.org',
't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print')
// The old way of passing a DOM-node still works
mw.util.addPortletLink('p-tb', 'http://mediawiki.org/', 'MediaWiki.org',
't-mworg', 'Go to MediaWiki.org ', 'm', document.getElementById('t-print'))
$content
A jQuery object for a page's content body regardless of the skin used. This is, for example, #bodyContent in the Vector-skin.
/* Add some HTML to the page content */
mw.util.$content.append( '<h2>Lorem ipsum</h2><p>This section was just added to the bottom of the wiki page.</p>' );
/* Count number of tables in the page's content with a class of "wikitable" */
var $wikitablesInPage = mw.util.$content.find('table.wikitable');
if ( $wikitablesInPage.size() > 0 ) {
alert( 'There are ' + $wikitablesInPage.size() + ' wikitables on this page.' );
} else {
alert( 'There are no wikitables on this page.' );
}
Here is a more advanced example involving loading in extra content with an AJAX request. Run this example on a page other than the main page.
/* Loads in main page (or any page for that matter) over AJAX (may be useful for Special:BlankPage) */
// Put a loading message on top of the page
mw.util.$content.prepend( '<p><em>Loading...</em></p><hr />' );
// Get the address to the main page,
// the css-selector of the $content element,
// load it into the $content element
// and display a message when it's done
mw.util.$content.load( mw.util.wikiGetlink( mw.config.get( 'wgMainPageTitle' ) ) + ' ' + mw.util.$content.selector, function () {
mw.util.$content.prepend( '<p><strong>Load complete!</strong></p><hr />' );
} );
getParamValue
This function returns the value of the specified URL parameter. By default it uses the current window's address. Optionally can be passed a custom location.
It returns null
if is not present.
Returns an empty string(""
) if it was an empty parameter (such as /page.php?some=parameter&emptyparameter=&id=12
// Location: http://www.mediawiki.org/w/index.php?title=ResourceLoader/Default_modules&action=edit§ion=28
// Suppose we're editing a page section, this will return the number of the edit section
mw.util.getParamValue('section'); /* returns '28'; */
// Check if we're in a diff-view
var diff = mw.util.getParamValue('diff');
if ( diff !== null ) {
alert( 'This is a difference view.' );
} else {
alert( 'This is not a difference view.' );
}
// Extract a value from a custom url
// For example on a diff page where there is: "← Older edit" and you need the oldid of the previous edit
var oldid = mw.util.getParamValue('oldid', 'http://www.mediawiki.org/w/index.php?title=ResourceLoader/Default_modules&diff=prev&oldid=365296');
if ( oldid !== null ) {
alert( 'The previous text version of this page has id: ' + oldid );
} else {
alert( 'No "oldid" parameter found in the given address.' );
}
isMainPage
This function checks if the current page is an action of the wiki's main page (eg. view, history, edit etc.). By default it returns true if it is, and false other wise. By passing true as the first argument it will also return true if the current page is in an asociated namespace (eg. Talk:).
NB: This function requires the document to be ready. Be sure it's called inside a document-ready wrapper.
// Adds an interwiki link to Meta-Wiki if we're currently viewing the article content of the Main page article (eg. the second check is to avoid running it when in edit-, delete-, history mode etc.)
if ( mw.util.isMainPage() && mw.config.get( 'wgIsArticle' ) ) {
mw.util.addPortletLink( 'p-lang', 'http://meta.wikimedia.org/wiki/List_of_Wikipedias', 'Complete list', 'interwiki-completelist', 'Complete list of Wikipedias' );
}
// Add a special view to the tab bar when we're on a Main page-related page
// When clicked it will ask "Are you sure you" and continue if you confirm
if ( mw.util.isMainPage( true ) ) {
awesomeLink = mw.util.addPortletLink( 'p-views', mw.util.wikiGetlink('Special:Awesome/' + mw.config.get('wgPageName') ), 'Do awesome', 'ca-awesome', 'Do something awesome', null, '#ca-history' );
$(awesomeLink).click( function(e){
if ( !confirm( 'Are you sure you want to do something awesome ?' ) ) {
e.preventDefault();
return false;
}
});
}
=== jsMessage ===
This function is ported from the legacy wikibits keeping it fully backwards compatible, with a few adjustments and with added support to hide the message by calling with no arguments or when passing null.
<source lang="javascript">
// Basic usage, replace/add the message on top
mw.util.jsMessage( 'This is something a <strong>message</strong> for the <strong>user</strong>' );
// Classed usage, adds/replaces the 'mw-js-message-foobar' as class for the message-box
mw.util.jsMessage( 'Foobar message 01255', 'foobar' );
// Any of the folllowing will empty and hide the box
mw.util.jsMessage();
mw.util.jsMessage( '' );
mw.util.jsMessage( null );
rawurlencode
This function returns an encoded string in its raw form for use in urls.
window.location = 'http://www.google.com/search?q=' + mw.util.rawurlencode( mw.config.get( 'wgPageName' ) );
wikiUrlencode
This function returns an article/page name in its encoded form.
window.location = 'http://www.mediawiki.org/w/api.php?format=json&action=query&list=alllinks&titles=' + mw.util.wikiUrlencode( mw.config.get( 'wgPageName' ) );
wikiGetlink
This function returns the full website address of a local wiki page.
location = mw.util.wikiGetlink( 'Sandbox' ); /* http://www.mediawiki.org/wiki/Sandbox */
ResourceLoader |
---|
Reference |
Tutorials |