1 /*jslint browser: true, continue: true, white: true, forin: true*/
4 * Core MediaWiki JavaScript Library
7 var mw
= ( function ( $, undefined ) {
12 var hasOwn
= Object
.prototype.hasOwnProperty
;
13 /* Object constructors */
18 * Creates an object that can be read from or written to from prototype functions
19 * that allow both single and multiple variables at once.
21 * @param global boolean Whether to store the values in the global window
22 * object or a exclusively in the object property 'values'.
25 function Map( global
) {
26 this.values
= global
=== true ? window
: {};
32 * Get the value of one or multiple a keys.
34 * If called with no arguments, all values will be returned.
36 * @param selection mixed String key or array of keys to get values for.
37 * @param fallback mixed Value to use in case key(s) do not exist (optional).
38 * @return mixed If selection was a string returns the value or null,
39 * If selection was an array, returns an object of key/values (value is null if not found),
40 * If selection was not passed or invalid, will return the 'values' object member (be careful as
41 * objects are always passed by reference in JavaScript!).
42 * @return Values as a string or object, null if invalid/inexistant.
44 get: function ( selection
, fallback
) {
47 if ( $.isArray( selection
) ) {
48 selection
= $.makeArray( selection
);
50 for ( i
= 0; i
< selection
.length
; i
+= 1 ) {
51 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
56 if ( typeof selection
=== 'string' ) {
57 if ( this.values
[selection
] === undefined ) {
58 if ( fallback
!== undefined ) {
63 return this.values
[selection
];
66 if ( selection
=== undefined ) {
70 // invalid selection key
75 * Sets one or multiple key/value pairs.
77 * @param selection {mixed} String key or array of keys to set values for.
78 * @param value {mixed} Value to set (optional, only in use when key is a string)
79 * @return {Boolean} This returns true on success, false on failure.
81 set: function ( selection
, value
) {
84 if ( $.isPlainObject( selection
) ) {
85 for ( s
in selection
) {
86 this.values
[s
] = selection
[s
];
90 if ( typeof selection
=== 'string' && value
!== undefined ) {
91 this.values
[selection
] = value
;
98 * Checks if one or multiple keys exist.
100 * @param selection {mixed} String key or array of keys to check
101 * @return {Boolean} Existence of key(s)
103 exists: function ( selection
) {
106 if ( $.isArray( selection
) ) {
107 for ( s
= 0; s
< selection
.length
; s
+= 1 ) {
108 if ( this.values
[selection
[s
]] === undefined ) {
114 return this.values
[selection
] !== undefined;
121 * Object constructor for messages,
122 * similar to the Message class in MediaWiki PHP.
124 * @param map Map Instance of mw.Map
126 * @param parameters Array
129 function Message( map
, key
, parameters
) {
130 this.format
= 'plain';
133 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
137 Message
.prototype = {
139 * Simple message parser, does $N replacement and nothing else.
140 * This may be overridden to provide a more complex message parser.
142 * This function will not be called for nonexistent messages.
145 var parameters
= this.parameters
;
146 return this.map
.get( this.key
).replace( /\$(\d+)/g, function ( str
, match
) {
147 var index
= parseInt( match
, 10 ) - 1;
148 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
153 * Appends (does not replace) parameters for replacement to the .parameters property.
155 * @param parameters Array
158 params: function ( parameters
) {
160 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
161 this.parameters
.push( parameters
[i
] );
167 * Converts message object to it's string form based on the state of format.
169 * @return string Message as a string in the current form or <key> if key does not exist.
171 toString: function() {
174 if ( !this.exists() ) {
175 // Use <key> as text if key does not exist
176 if ( this.format
!== 'plain' ) {
177 // format 'escape' and 'parse' need to have the brackets and key html escaped
178 return mw
.html
.escape( '<' + this.key
+ '>' );
180 return '<' + this.key
+ '>';
183 if ( this.format
=== 'plain' ) {
184 // @todo FIXME: Although not applicable to core Message,
185 // Plugins like jQueryMsg should be able to distinguish
186 // between 'plain' (only variable replacement and plural/gender)
187 // and actually parsing wikitext to HTML.
188 text
= this.parser();
191 if ( this.format
=== 'escaped' ) {
192 text
= this.parser();
193 text
= mw
.html
.escape( text
);
196 if ( this.format
=== 'parse' ) {
197 text
= this.parser();
204 * Changes format to parse and converts message to string
206 * @return {string} String form of parsed message
209 this.format
= 'parse';
210 return this.toString();
214 * Changes format to plain and converts message to string
216 * @return {string} String form of plain message
219 this.format
= 'plain';
220 return this.toString();
224 * Changes the format to html escaped and converts message to string
226 * @return {string} String form of html escaped message
228 escaped: function() {
229 this.format
= 'escaped';
230 return this.toString();
234 * Checks if message exists
236 * @return {string} String form of parsed message
239 return this.map
.exists( this.key
);
247 * Dummy function which in debug mode can be replaced with a function that
248 * emulates console.log in console-less environments.
253 * @var constructor Make the Map constructor publicly available.
258 * @var constructor Make the Message constructor publicly available.
263 * List of configuration values
265 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
266 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
267 * in the global window object.
274 * Empty object that plugins can be installed in.
278 /* Extension points */
283 * Localization system
290 * Gets a message object, similar to wfMessage()
292 * @param key string Key of message to get
293 * @param parameter_1 mixed First argument in a list of variadic arguments,
294 * each a parameter for $N replacement in messages.
297 message: function ( key
, parameter_1
/* [, parameter_2] */ ) {
299 // Support variadic arguments
300 if ( parameter_1
!== undefined ) {
301 parameters
= $.makeArray( arguments
);
306 return new Message( mw
.messages
, key
, parameters
);
310 * Gets a message string, similar to wfMsg()
312 * @param key string Key of message to get
313 * @param parameters mixed First argument in a list of variadic arguments,
314 * each a parameter for $N replacement in messages.
317 msg: function ( /* key, parameter_1, parameter_2, .. */ ) {
318 return mw
.message
.apply( mw
.message
, arguments
).toString();
322 * Client-side module loader which integrates with the MediaWiki ResourceLoader
324 loader
: ( function () {
326 /* Private Members */
329 * Mapping of registered modules
331 * The jquery module is pre-registered, because it must have already
332 * been provided for this object to have been built, and in debug mode
333 * jquery would have been provided through a unique loader request,
334 * making it impossible to hold back registration of jquery until after
337 * For exact details on support for script, style and messages, look at
338 * mw.loader.implement.
343 * 'version': ############## (unix timestamp),
344 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
345 * 'group': 'somegroup', (or) null,
346 * 'source': 'local', 'someforeignwiki', (or) null
347 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
350 * 'messages': { 'key': 'value' },
356 * Mapping of sources, keyed by source-id, values are objects.
360 * 'loadScript': 'http://foo.bar/w/load.php'
365 // List of modules which will be loaded as when ready
367 // List of modules to be loaded
369 // List of callback functions waiting for modules to be ready to be called
371 // Selector cache for the marker element. Use getMarker() to get/use the marker!
374 /* Private methods */
376 function getMarker() {
382 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
383 if ( $marker
.length
) {
386 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
387 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
393 * Create a new style tag and add it to the DOM.
395 * @param text String: CSS text
396 * @param $nextnode mixed: [optional] An Element or jQuery object for an element where
397 * the style tag should be inserted before. Otherwise appended to the <head>.
398 * @return HTMLStyleElement
400 function addStyleTag( text
, $nextnode
) {
401 var s
= document
.createElement( 'style' );
403 s
.rel
= 'stylesheet';
404 // Insert into document before setting cssText (bug 33305)
406 // If a raw element, create a jQuery object, otherwise use directly
407 if ( $nextnode
.nodeType
) {
408 $nextnode
= $( $nextnode
);
410 $nextnode
.before( s
);
412 document
.getElementsByTagName('head')[0].appendChild( s
);
414 if ( s
.styleSheet
) {
415 s
.styleSheet
.cssText
= text
; // IE
417 // Safari sometimes borks on null
418 s
.appendChild( document
.createTextNode( String( text
) ) );
423 function addInlineCSS( css
) {
424 var $style
, style
, $newStyle
;
425 $style
= getMarker().prev();
426 // Disable <style> tag recycling/concatenation because of bug 34669
427 if ( false && $style
.is( 'style' ) && $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
428 // There's already a dynamic <style> tag present, append to it. This recycling of
429 // <style> tags is for bug 31676 (can't have more than 32 <style> tags in IE)
430 style
= $style
.get( 0 );
431 if ( style
.styleSheet
) {
432 style
.styleSheet
.cssText
+= css
; // IE
434 style
.appendChild( document
.createTextNode( String( css
) ) );
437 $newStyle
= $( addStyleTag( css
, getMarker() ) )
438 .data( 'ResourceLoaderDynamicStyleTag', true );
442 function compare( a
, b
) {
444 if ( a
.length
!== b
.length
) {
447 for ( i
= 0; i
< b
.length
; i
+= 1 ) {
448 if ( $.isArray( a
[i
] ) ) {
449 if ( !compare( a
[i
], b
[i
] ) ) {
453 if ( a
[i
] !== b
[i
] ) {
461 * Generates an ISO8601 "basic" string from a UNIX timestamp
463 function formatVersionNumber( timestamp
) {
464 var pad = function ( a
, b
, c
) {
465 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
468 d
.setTime( timestamp
* 1000 );
470 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
471 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
476 * Resolves dependencies and detects circular references.
478 * @param module String Name of the top-level module whose dependencies shall be
479 * resolved and sorted.
480 * @param resolved Array Returns a topological sort of the given module and its
481 * dependencies, such that later modules depend on earlier modules. The array
482 * contains the module names. If the array contains already some module names,
483 * this function appends its result to the pre-existing array.
484 * @param unresolved Object [optional] Hash used to track the current dependency
485 * chain; used to report loops in the dependency graph.
486 * @throws Error if any unregistered module or a dependency loop is encountered
488 function sortDependencies( module
, resolved
, unresolved
) {
491 if ( registry
[module
] === undefined ) {
492 throw new Error( 'Unknown dependency: ' + module
);
494 // Resolves dynamic loader function and replaces it with its own results
495 if ( $.isFunction( registry
[module
].dependencies
) ) {
496 registry
[module
].dependencies
= registry
[module
].dependencies();
497 // Ensures the module's dependencies are always in an array
498 if ( typeof registry
[module
].dependencies
!== 'object' ) {
499 registry
[module
].dependencies
= [registry
[module
].dependencies
];
502 if ( $.inArray( module
, resolved
) !== -1 ) {
503 // Module already resolved; nothing to do.
506 // unresolved is optional, supply it if not passed in
510 // Tracks down dependencies
511 deps
= registry
[module
].dependencies
;
513 for ( n
= 0; n
< len
; n
+= 1 ) {
514 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
515 if ( unresolved
[deps
[n
]] ) {
517 'Circular reference detected: ' + module
+
523 unresolved
[module
] = true;
524 sortDependencies( deps
[n
], resolved
, unresolved
);
525 delete unresolved
[module
];
528 resolved
[resolved
.length
] = module
;
532 * Gets a list of module names that a module depends on in their proper dependency
535 * @param module string module name or array of string module names
536 * @return list of dependencies, including 'module'.
537 * @throws Error if circular reference is detected
539 function resolve( module
) {
542 // Allow calling with an array of module names
543 if ( $.isArray( module
) ) {
545 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
546 sortDependencies( module
[m
], resolved
);
551 if ( typeof module
=== 'string' ) {
553 sortDependencies( module
, resolved
);
557 throw new Error( 'Invalid module argument: ' + module
);
561 * Narrows a list of module names down to those matching a specific
562 * state (see comment on top of this scope for a list of valid states).
563 * One can also filter for 'unregistered', which will return the
564 * modules names that don't have a registry entry.
566 * @param states string or array of strings of module states to filter by
567 * @param modules array list of module names to filter (optional, by default the entire
569 * @return array list of filtered module names
571 function filter( states
, modules
) {
572 var list
, module
, s
, m
;
574 // Allow states to be given as a string
575 if ( typeof states
=== 'string' ) {
578 // If called without a list of modules, build and use a list of all modules
580 if ( modules
=== undefined ) {
582 for ( module
in registry
) {
583 modules
[modules
.length
] = module
;
586 // Build a list of modules which are in one of the specified states
587 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
588 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
589 if ( registry
[modules
[m
]] === undefined ) {
590 // Module does not exist
591 if ( states
[s
] === 'unregistered' ) {
593 list
[list
.length
] = modules
[m
];
596 // Module exists, check state
597 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
599 list
[list
.length
] = modules
[m
];
608 * Determine whether all dependencies are in state 'ready', which means we may
609 * execute the module or job now.
611 * @param dependencies Array dependencies (module names) to be checked.
613 * @return Boolean true if all dependencies are in state 'ready', false otherwise
615 function allReady( dependencies
) {
616 return filter( 'ready', dependencies
).length
=== dependencies
.length
;
620 * Log a message to window.console, if possible. Useful to force logging of some
621 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
622 * Gets console references in each invocation, so that delayed debugging tools work
623 * fine. No need for optimization here, which would only result in losing logs.
625 * @param msg String text for the log entry.
626 * @param e Error [optional] to also log.
628 function log( msg
, e
) {
629 var console
= window
.console
;
630 if ( console
&& console
.log
) {
632 // If we have an exception object, log it through .error() to trigger
633 // proper stacktraces in browsers that support it. There are no (known)
634 // browsers that don't support .error(), that do support .log() and
635 // have useful exception handling through .log().
636 if ( e
&& console
.error
) {
643 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
644 * and modules that depend upon this module. if the given module failed, propagate the 'error'
645 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
646 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
648 * @param module String name of module that entered one of the states 'ready', 'error', or 'missing'.
650 function handlePending( module
) {
651 var j
, job
, hasErrors
, m
, stateChange
;
654 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) !== -1 ) {
655 // If the current module failed, mark all dependent modules also as failed.
656 // Iterate until steady-state to propagate the error state upwards in the
660 for ( m
in registry
) {
661 if ( $.inArray( registry
[m
].state
, ['error', 'missing'] ) === -1 ) {
662 if ( filter( ['error', 'missing'], registry
[m
].dependencies
).length
> 0 ) {
663 registry
[m
].state
= 'error';
668 } while ( stateChange
);
671 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
672 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
673 hasErrors
= filter( ['error', 'missing'], jobs
[j
].dependencies
).length
> 0;
674 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
675 // All dependencies satisfied, or some have errors
681 throw new Error ("Module " + module
+ " failed.");
683 if ( $.isFunction( job
.ready
) ) {
688 if ( $.isFunction( job
.error
) ) {
690 job
.error( e
, [module
] );
692 // A user-defined operation raised an exception. Swallow to protect
693 // our state machine!
694 log( 'Exception thrown by job.error()', ex
);
701 if ( registry
[module
].state
=== 'ready' ) {
702 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
703 // and now have all dependencies satisfied.
704 for ( m
in registry
) {
705 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
713 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
714 * depending on whether document-ready has occurred yet and whether we are in async mode.
716 * @param src String: URL to script, will be used as the src attribute in the script tag
717 * @param callback Function: Optional callback which will be run when the script is done
719 function addScript( src
, callback
, async
) {
723 // Using isReady directly instead of storing it locally from
724 // a $.fn.ready callback (bug 31895).
725 if ( $.isReady
|| async
) {
726 // jQuery's getScript method is NOT better than doing this the old-fashioned way
727 // because jQuery will eval the script's code, and errors will not have sane
729 script
= document
.createElement( 'script' );
730 script
.setAttribute( 'src', src
);
731 script
.setAttribute( 'type', 'text/javascript' );
732 if ( $.isFunction( callback
) ) {
733 // Attach handlers for all browsers (based on jQuery.ajax)
734 script
.onload
= script
.onreadystatechange = function() {
740 || /loaded|complete/.test( script
.readyState
)
748 // Handle memory leak in IE. This seems to fail in
749 // IE7 sometimes (Permission Denied error when
750 // accessing script.parentNode) so wrap it in
753 script
.onload
= script
.onreadystatechange
= null;
754 if ( script
.parentNode
) {
755 script
.parentNode
.removeChild( script
);
758 // Dereference the script
765 if ( window
.opera
) {
766 // Appending to the <head> blocks rendering completely in Opera,
767 // so append to the <body> after document ready. This means the
768 // scripts only start loading after the document has been rendered,
769 // but so be it. Opera users don't deserve faster web pages if their
770 // browser makes it impossible
771 $( function() { document
.body
.appendChild( script
); } );
773 // IE-safe way of getting the <head> . document.documentElement.head doesn't
774 // work in scripts that run in the <head>
775 head
= document
.getElementsByTagName( 'head' )[0];
776 ( document
.body
|| head
).appendChild( script
);
779 document
.write( mw
.html
.element(
780 'script', { 'type': 'text/javascript', 'src': src
}, ''
782 if ( $.isFunction( callback
) ) {
783 // Document.write is synchronous, so this is called when it's done
784 // FIXME: that's a lie. doc.write isn't actually synchronous
791 * Executes a loaded module, making it ready to use
793 * @param module string module name to execute
795 function execute( module
) {
796 var style
, media
, i
, script
, markModuleReady
, nestedAddScript
;
798 if ( registry
[module
] === undefined ) {
799 throw new Error( 'Module has not been registered yet: ' + module
);
800 } else if ( registry
[module
].state
=== 'registered' ) {
801 throw new Error( 'Module has not been requested from the server yet: ' + module
);
802 } else if ( registry
[module
].state
=== 'loading' ) {
803 throw new Error( 'Module has not completed loading yet: ' + module
);
804 } else if ( registry
[module
].state
=== 'ready' ) {
805 throw new Error( 'Module has already been loaded: ' + module
);
809 if ( $.isPlainObject( registry
[module
].style
) ) {
810 // 'media' type ignored, see documentation of mw.loader.implement
811 for ( media
in registry
[module
].style
) {
812 style
= registry
[module
].style
[media
];
813 if ( $.isArray( style
) ) {
814 for ( i
= 0; i
< style
.length
; i
+= 1 ) {
815 getMarker().before( mw
.html
.element( 'link', {
821 } else if ( typeof style
=== 'string' ) {
822 addInlineCSS( style
);
826 // Add localizations to message system
827 if ( $.isPlainObject( registry
[module
].messages
) ) {
828 mw
.messages
.set( registry
[module
].messages
);
832 script
= registry
[module
].script
;
833 markModuleReady = function() {
834 registry
[module
].state
= 'ready';
835 handlePending( module
);
837 nestedAddScript = function ( arr
, callback
, async
, i
) {
838 // Recursively call addScript() in its own callback
839 // for each element of arr.
840 if ( i
>= arr
.length
) {
841 // We're at the end of the array
846 addScript( arr
[i
], function() {
847 nestedAddScript( arr
, callback
, async
, i
+ 1 );
851 if ( $.isArray( script
) ) {
852 registry
[module
].state
= 'loading';
853 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
854 } else if ( $.isFunction( script
) ) {
859 // This needs to NOT use mw.log because these errors are common in production mode
860 // and not in debug mode, such as when a symbol that should be global isn't exported
861 log('mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
, e
);
862 registry
[module
].state
= 'error';
863 handlePending( module
);
868 * Adds a dependencies to the queue with optional callbacks to be run
869 * when the dependencies are ready or fail
871 * @param dependencies string module name or array of string module names
872 * @param ready function callback to execute when all dependencies are ready
873 * @param error function callback to execute when any dependency fails
874 * @param async (optional) If true, load modules asynchronously even if
875 * document ready has not yet occurred
877 function request( dependencies
, ready
, error
, async
) {
878 var regItemDeps
, regItemDepLen
, n
;
880 // Allow calling by single module name
881 if ( typeof dependencies
=== 'string' ) {
882 dependencies
= [dependencies
];
883 if ( registry
[dependencies
[0]] !== undefined ) {
884 // Cache repetitively accessed deep level object member
885 regItemDeps
= registry
[dependencies
[0]].dependencies
;
886 // Cache to avoid looped access to length property
887 regItemDepLen
= regItemDeps
.length
;
888 for ( n
= 0; n
< regItemDepLen
; n
+= 1 ) {
889 dependencies
[dependencies
.length
] = regItemDeps
[n
];
894 // Add ready and error callbacks if they were given
895 if ( ready
!== undefined || error
!== undefined ) {
896 jobs
[jobs
.length
] = {
897 'dependencies': filter(
898 ['registered', 'loading', 'loaded'],
906 // Queue up any dependencies that are registered
907 dependencies
= filter( ['registered'], dependencies
);
908 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
909 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
910 queue
[queue
.length
] = dependencies
[n
];
912 // Mark this module as async in the registry
913 registry
[dependencies
[n
]].async
= true;
922 function sortQuery(o
) {
923 var sorted
= {}, key
, a
= [];
925 if ( hasOwn
.call( o
, key
) ) {
930 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
931 sorted
[a
[key
]] = o
[a
[key
]];
937 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
938 * to a query string of the form foo.bar,baz|bar.baz,quux
940 function buildModulesString( moduleMap
) {
941 var arr
= [], p
, prefix
;
942 for ( prefix
in moduleMap
) {
943 p
= prefix
=== '' ? '' : prefix
+ '.';
944 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
946 return arr
.join( '|' );
950 * Asynchronously append a script tag to the end of the body
951 * that invokes load.php
952 * @param moduleMap {Object}: Module map, see buildModulesString()
953 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
954 * @param sourceLoadScript {String}: URL of load.php
955 * @param async {Boolean}: If true, use an asynchrounous request even if document ready has not yet occurred
957 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
958 var request
= $.extend(
959 { 'modules': buildModulesString( moduleMap
) },
962 request
= sortQuery( request
);
963 // Asynchronously append a script tag to the end of the body
964 // Append &* to avoid triggering the IE6 extension check
965 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
970 addStyleTag
: addStyleTag
,
973 * Requests dependencies from server, loading and executing when things when ready.
976 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
977 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
978 currReqBase
, currReqBaseLength
, moduleMap
, l
,
979 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
981 // Build a list of request parameters common to all requests.
983 skin
: mw
.config
.get( 'skin' ),
984 lang
: mw
.config
.get( 'wgUserLanguage' ),
985 debug
: mw
.config
.get( 'debug' )
987 // Split module batch by source and by group.
989 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
991 // Appends a list of modules from the queue to the batch
992 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
993 // Only request modules which are registered
994 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
995 // Prevent duplicate entries
996 if ( $.inArray( queue
[q
], batch
) === -1 ) {
997 batch
[batch
.length
] = queue
[q
];
998 // Mark registered modules as loading
999 registry
[queue
[q
]].state
= 'loading';
1003 // Early exit if there's nothing to load...
1004 if ( !batch
.length
) {
1008 // The queue has been processed into the batch, clear up the queue.
1011 // Always order modules alphabetically to help reduce cache
1012 // misses for otherwise identical content.
1015 // Split batch by source and by group.
1016 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1017 bSource
= registry
[batch
[b
]].source
;
1018 bGroup
= registry
[batch
[b
]].group
;
1019 if ( splits
[bSource
] === undefined ) {
1020 splits
[bSource
] = {};
1022 if ( splits
[bSource
][bGroup
] === undefined ) {
1023 splits
[bSource
][bGroup
] = [];
1025 bSourceGroup
= splits
[bSource
][bGroup
];
1026 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1029 // Clear the batch - this MUST happen before we append any
1030 // script elements to the body or it's possible that a script
1031 // will be locally cached, instantly load, and work the batch
1032 // again, all before we've cleared it causing each request to
1033 // include modules which are already loaded.
1036 for ( source
in splits
) {
1038 sourceLoadScript
= sources
[source
].loadScript
;
1040 for ( group
in splits
[source
] ) {
1042 // Cache access to currently selected list of
1043 // modules for this group from this source.
1044 modules
= splits
[source
][group
];
1046 // Calculate the highest timestamp
1048 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
1049 if ( registry
[modules
[g
]].version
> maxVersion
) {
1050 maxVersion
= registry
[modules
[g
]].version
;
1054 currReqBase
= $.extend( { 'version': formatVersionNumber( maxVersion
) }, reqBase
);
1055 // For user modules append a user name to the request.
1056 if ( group
=== "user" && mw
.config
.get( 'wgUserName' ) !== null ) {
1057 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1059 currReqBaseLength
= $.param( currReqBase
).length
;
1061 // We may need to split up the request to honor the query string length limit,
1062 // so build it piece by piece.
1063 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1065 moduleMap
= {}; // { prefix: [ suffixes ] }
1067 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1068 // Determine how many bytes this module would add to the query string
1069 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1070 // Note that these substr() calls work even if lastDotIndex == -1
1071 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1072 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
1073 bytesAdded
= moduleMap
[prefix
] !== undefined
1074 ? suffix
.length
+ 3 // '%2C'.length == 3
1075 : modules
[i
].length
+ 3; // '%7C'.length == 3
1077 // If the request would become too long, create a new one,
1078 // but don't create empty requests
1079 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1080 // This request would become too long, create a new one
1081 // and fire off the old one
1082 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1085 l
= currReqBaseLength
+ 9;
1087 if ( moduleMap
[prefix
] === undefined ) {
1088 moduleMap
[prefix
] = [];
1090 moduleMap
[prefix
].push( suffix
);
1091 if ( !registry
[modules
[i
]].async
) {
1092 // If this module is blocking, make the entire request blocking
1093 // This is slightly suboptimal, but in practice mixing of blocking
1094 // and async modules will only occur in debug mode.
1099 // If there's anything left in moduleMap, request that too
1100 if ( !$.isEmptyObject( moduleMap
) ) {
1101 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1108 * Register a source.
1110 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
1111 * @param props {Object}: Object containing only the loadScript property which is a url to
1112 * the load.php location of the source.
1115 addSource: function ( id
, props
) {
1117 // Allow multiple additions
1118 if ( typeof id
=== 'object' ) {
1119 for ( source
in id
) {
1120 mw
.loader
.addSource( source
, id
[source
] );
1125 if ( sources
[id
] !== undefined ) {
1126 throw new Error( 'source already registered: ' + id
);
1129 sources
[id
] = props
;
1135 * Registers a module, letting the system know about it and its
1136 * properties. Startup modules contain calls to this function.
1138 * @param module {String}: Module name
1139 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1140 * @param dependencies {String|Array|Function}: One string or array of strings of module
1141 * names on which this module depends, or a function that returns that array.
1142 * @param group {String}: Group which the module is in (optional, defaults to null)
1143 * @param source {String}: Name of the source. Defaults to local.
1145 register: function ( module
, version
, dependencies
, group
, source
) {
1147 // Allow multiple registration
1148 if ( typeof module
=== 'object' ) {
1149 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1150 // module is an array of module names
1151 if ( typeof module
[m
] === 'string' ) {
1152 mw
.loader
.register( module
[m
] );
1153 // module is an array of arrays
1154 } else if ( typeof module
[m
] === 'object' ) {
1155 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1161 if ( typeof module
!== 'string' ) {
1162 throw new Error( 'module must be a string, not a ' + typeof module
);
1164 if ( registry
[module
] !== undefined ) {
1165 throw new Error( 'module already registered: ' + module
);
1167 // List the module as registered
1168 registry
[module
] = {
1169 'version': version
!== undefined ? parseInt( version
, 10 ) : 0,
1171 'group': typeof group
=== 'string' ? group
: null,
1172 'source': typeof source
=== 'string' ? source
: 'local',
1173 'state': 'registered'
1175 if ( typeof dependencies
=== 'string' ) {
1176 // Allow dependencies to be given as a single module name
1177 registry
[module
].dependencies
= [dependencies
];
1178 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1179 // Allow dependencies to be given as an array of module names
1180 // or a function which returns an array
1181 registry
[module
].dependencies
= dependencies
;
1186 * Implements a module, giving the system a course of action to take
1187 * upon loading. Results of a request for one or more modules contain
1188 * calls to this function.
1190 * All arguments are required.
1192 * @param module String: Name of module
1193 * @param script Mixed: Function of module code or String of URL to be used as the src
1194 * attribute when adding a script element to the body
1195 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1196 * keyed by media-type. Media-type should be "all" or "", actual types are not supported
1197 * right now due to the way execute() processes the stylesheets (they are concatenated
1198 * into a single <style> tag). In the past these weren't concatenated together (which is
1199 * these are keyed by media-type), but bug 31676 forces us to. In practice this is not a
1200 * problem because ResourceLoader only generates stylesheets for media-type all (e.g. print
1201 * stylesheets are wrapped in @media print {} and concatenated with the others).
1202 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1204 implement: function ( module
, script
, style
, msgs
) {
1206 if ( typeof module
!== 'string' ) {
1207 throw new Error( 'module must be a string, not a ' + typeof module
);
1209 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1210 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1212 if ( !$.isPlainObject( style
) ) {
1213 throw new Error( 'style must be an object, not a ' + typeof style
);
1215 if ( !$.isPlainObject( msgs
) ) {
1216 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1218 // Automatically register module
1219 if ( registry
[module
] === undefined ) {
1220 mw
.loader
.register( module
);
1222 // Check for duplicate implementation
1223 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1224 throw new Error( 'module already implemented: ' + module
);
1226 // Attach components
1227 registry
[module
].script
= script
;
1228 registry
[module
].style
= style
;
1229 registry
[module
].messages
= msgs
;
1230 // The module may already have been marked as erroneous
1231 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1232 registry
[module
].state
= 'loaded';
1233 if ( allReady( registry
[module
].dependencies
) ) {
1240 * Executes a function as soon as one or more required modules are ready
1242 * @param dependencies {String|Array} Module name or array of modules names the callback
1243 * dependends on to be ready before executing
1244 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1245 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1247 using: function ( dependencies
, ready
, error
) {
1248 var tod
= typeof dependencies
;
1250 if ( tod
!== 'object' && tod
!== 'string' ) {
1251 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1253 // Allow calling with a single dependency as a string
1254 if ( tod
=== 'string' ) {
1255 dependencies
= [dependencies
];
1257 // Resolve entire dependency map
1258 dependencies
= resolve( dependencies
);
1259 if ( allReady( dependencies
) ) {
1260 // Run ready immediately
1261 if ( $.isFunction( ready
) ) {
1264 } else if ( filter( ['error', 'missing'], dependencies
).length
) {
1265 // Execute error immediately if any dependencies have errors
1266 if ( $.isFunction( error
) ) {
1267 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1271 // Not all dependencies are ready: queue up a request
1272 request( dependencies
, ready
, error
);
1277 * Loads an external script or one or more modules for future use
1279 * @param modules {mixed} Either the name of a module, array of modules,
1280 * or a URL of an external script or style
1281 * @param type {String} mime-type to use if calling with a URL of an
1282 * external script or style; acceptable values are "text/css" and
1283 * "text/javascript"; if no type is provided, text/javascript is assumed.
1284 * @param async {Boolean} (optional) If true, load modules asynchronously
1285 * even if document ready has not yet occurred. If false (default),
1286 * block before document ready and load async after. If not set, true will
1287 * be assumed if loading a URL, and false will be assumed otherwise.
1289 load: function ( modules
, type
, async
) {
1290 var filtered
, m
, module
;
1293 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1294 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1296 // Allow calling with an external url or single dependency as a string
1297 if ( typeof modules
=== 'string' ) {
1298 // Support adding arbitrary external scripts
1299 if ( /^(https?:)?\/\//.test( modules
) ) {
1300 if ( async
=== undefined ) {
1301 // Assume async for bug 34542
1304 if ( type
=== 'text/css' ) {
1305 $( 'head' ).append( $( '<link>', {
1312 if ( type
=== 'text/javascript' || type
=== undefined ) {
1313 addScript( modules
, null, async
);
1317 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1319 // Called with single module
1320 modules
= [modules
];
1323 // Filter out undefined modules, otherwise resolve() will throw
1324 // an exception for trying to load an undefined module.
1325 // Undefined modules are acceptable here in load(), because load() takes
1326 // an array of unrelated modules, whereas the modules passed to
1327 // using() are related and must all be loaded.
1328 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1329 module
= registry
[modules
[m
]];
1330 if ( module
!== undefined ) {
1331 if ( $.inArray( module
.state
, ['error', 'missing'] ) === -1 ) {
1332 filtered
[filtered
.length
] = modules
[m
];
1337 if (filtered
.length
=== 0) {
1340 // Resolve entire dependency map
1341 filtered
= resolve( filtered
);
1342 // If all modules are ready, nothing to be done
1343 if ( allReady( filtered
) ) {
1346 // If any modules have errors: also quit.
1347 if ( filter( ['error', 'missing'], filtered
).length
) {
1350 // Since some modules are not yet ready, queue up a request.
1351 request( filtered
, null, null, async
);
1355 * Changes the state of a module
1357 * @param module {String|Object} module name or object of module name/state pairs
1358 * @param state {String} state name
1360 state: function ( module
, state
) {
1363 if ( typeof module
=== 'object' ) {
1364 for ( m
in module
) {
1365 mw
.loader
.state( m
, module
[m
] );
1369 if ( registry
[module
] === undefined ) {
1370 mw
.loader
.register( module
);
1372 if ( $.inArray(state
, ['ready', 'error', 'missing']) !== -1
1373 && registry
[module
].state
!== state
) {
1374 // Make sure pending modules depending on this one get executed if their
1375 // dependencies are now fulfilled!
1376 registry
[module
].state
= state
;
1377 handlePending( module
);
1379 registry
[module
].state
= state
;
1384 * Gets the version of a module
1386 * @param module string name of module to get version for
1388 getVersion: function ( module
) {
1389 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1390 return formatVersionNumber( registry
[module
].version
);
1396 * @deprecated since 1.18 use mw.loader.getVersion() instead
1398 version: function () {
1399 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1403 * Gets the state of a module
1405 * @param module string name of module to get state for
1407 getState: function ( module
) {
1408 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1409 return registry
[module
].state
;
1415 * Get names of all registered modules.
1419 getModuleNames: function () {
1420 return $.map( registry
, function ( i
, key
) {
1426 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1429 mw
.loader
.load( 'mediawiki.user' );
1434 /** HTML construction helper functions */
1435 html
: ( function () {
1436 function escapeCallback( s
) {
1453 * Escape a string for HTML. Converts special characters to HTML entities.
1454 * @param s The string to escape
1456 escape: function ( s
) {
1457 return s
.replace( /['"<>&]/g, escapeCallback
);
1461 * Wrapper object for raw HTML passed to mw.html.element().
1464 Raw: function ( value
) {
1469 * Wrapper object for CDATA element contents passed to mw.html.element()
1472 Cdata: function ( value
) {
1477 * Create an HTML element string, with safe escaping.
1479 * @param name The tag name.
1480 * @param attrs An object with members mapping element names to values
1481 * @param contents The contents of the element. May be either:
1482 * - string: The string is escaped.
1483 * - null or undefined: The short closing form is used, e.g. <br/>.
1484 * - this.Raw: The value attribute is included without escaping.
1485 * - this.Cdata: The value attribute is included, and an exception is
1486 * thrown if it contains an illegal ETAGO delimiter.
1487 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1491 * return h.element( 'div', {},
1492 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1493 * Returns <div><img src="<"/></div>
1495 element: function ( name
, attrs
, contents
) {
1496 var v
, attrName
, s
= '<' + name
;
1498 for ( attrName
in attrs
) {
1499 v
= attrs
[attrName
];
1500 // Convert name=true, to name=name
1504 } else if ( v
=== false ) {
1507 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
1509 if ( contents
=== undefined || contents
=== null ) {
1516 switch ( typeof contents
) {
1519 s
+= this.escape( contents
);
1523 // Convert to string
1524 s
+= String( contents
);
1527 if ( contents
instanceof this.Raw
) {
1528 // Raw HTML inclusion
1529 s
+= contents
.value
;
1530 } else if ( contents
instanceof this.Cdata
) {
1532 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1533 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1535 s
+= contents
.value
;
1537 throw new Error( 'mw.html.element: Invalid type of contents' );
1540 s
+= '</' + name
+ '>';
1546 // Skeleton user object. mediawiki.user.js extends this
1555 // Alias $j to jQuery for backwards compatibility
1558 // Attach to window and globally alias
1559 window
.mw
= window
.mediaWiki
= mw
;
1561 // Auto-register from pre-loaded startup scripts
1562 if ( jQuery
.isFunction( window
.startUp
) ) {
1564 window
.startUp
= undefined;