2 * Core MediaWiki JavaScript Library
5 var mw
= ( function ( $, undefined ) {
10 var hasOwn
= Object
.prototype.hasOwnProperty
;
11 /* Object constructors */
16 * Creates an object that can be read from or written to from prototype functions
17 * that allow both single and multiple variables at once.
19 * @param global boolean Whether to store the values in the global window
20 * object or a exclusively in the object property 'values'.
23 function Map( global
) {
24 this.values
= global
=== true ? window
: {};
30 * Get the value of one or multiple a keys.
32 * If called with no arguments, all values will be returned.
34 * @param selection mixed String key or array of keys to get values for.
35 * @param fallback mixed Value to use in case key(s) do not exist (optional).
36 * @return mixed If selection was a string returns the value or null,
37 * If selection was an array, returns an object of key/values (value is null if not found),
38 * If selection was not passed or invalid, will return the 'values' object member (be careful as
39 * objects are always passed by reference in JavaScript!).
40 * @return Values as a string or object, null if invalid/inexistant.
42 get: function ( selection
, fallback
) {
45 if ( $.isArray( selection
) ) {
46 selection
= $.makeArray( selection
);
48 for ( i
= 0; i
< selection
.length
; i
+= 1 ) {
49 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
52 } else if ( typeof selection
=== 'string' ) {
53 if ( this.values
[selection
] === undefined ) {
54 if ( fallback
!== undefined ) {
59 return this.values
[selection
];
61 if ( selection
=== undefined ) {
64 return null; // invalid selection key
69 * Sets one or multiple key/value pairs.
71 * @param selection {mixed} String key or array of keys to set values for.
72 * @param value {mixed} Value to set (optional, only in use when key is a string)
73 * @return {Boolean} This returns true on success, false on failure.
75 set: function ( selection
, value
) {
78 if ( $.isPlainObject( selection
) ) {
79 for ( s
in selection
) {
80 this.values
[s
] = selection
[s
];
83 } else if ( typeof selection
=== 'string' && value
!== undefined ) {
84 this.values
[selection
] = value
;
91 * Checks if one or multiple keys exist.
93 * @param selection {mixed} String key or array of keys to check
94 * @return {Boolean} Existence of key(s)
96 exists: function ( selection
) {
99 if ( $.isArray( selection
) ) {
100 for ( s
= 0; s
< selection
.length
; s
+= 1 ) {
101 if ( this.values
[selection
[s
]] === undefined ) {
107 return this.values
[selection
] !== undefined;
115 * Object constructor for messages,
116 * similar to the Message class in MediaWiki PHP.
118 * @param map Map Instance of mw.Map
120 * @param parameters Array
123 function Message( map
, key
, parameters
) {
124 this.format
= 'plain';
127 this.parameters
= parameters
=== undefined ? [] : $.makeArray( parameters
);
131 Message
.prototype = {
133 * Simple message parser, does $N replacement and nothing else.
134 * This may be overridden to provide a more complex message parser.
136 * This function will not be called for nonexistent messages.
139 var parameters
= this.parameters
;
140 return this.map
.get( this.key
).replace( /\$(\d+)/g, function ( str
, match
) {
141 var index
= parseInt( match
, 10 ) - 1;
142 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
147 * Appends (does not replace) parameters for replacement to the .parameters property.
149 * @param parameters Array
152 params: function ( parameters
) {
154 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
155 this.parameters
.push( parameters
[i
] );
161 * Converts message object to it's string form based on the state of format.
163 * @return string Message as a string in the current form or <key> if key does not exist.
165 toString: function() {
168 if ( !this.exists() ) {
169 // Use <key> as text if key does not exist
170 if ( this.format
!== 'plain' ) {
171 // format 'escape' and 'parse' need to have the brackets and key html escaped
172 return mw
.html
.escape( '<' + this.key
+ '>' );
174 return '<' + this.key
+ '>';
177 if ( this.format
=== 'plain' ) {
178 // @todo FIXME: Although not applicable to core Message,
179 // Plugins like jQueryMsg should be able to distinguish
180 // between 'plain' (only variable replacement and plural/gender)
181 // and actually parsing wikitext to HTML.
182 text
= this.parser();
185 if ( this.format
=== 'escaped' ) {
186 text
= this.parser();
187 text
= mw
.html
.escape( text
);
190 if ( this.format
=== 'parse' ) {
191 text
= this.parser();
198 * Changes format to parse and converts message to string
200 * @return {string} String form of parsed message
203 this.format
= 'parse';
204 return this.toString();
208 * Changes format to plain and converts message to string
210 * @return {string} String form of plain message
213 this.format
= 'plain';
214 return this.toString();
218 * Changes the format to html escaped and converts message to string
220 * @return {string} String form of html escaped message
222 escaped: function() {
223 this.format
= 'escaped';
224 return this.toString();
228 * Checks if message exists
230 * @return {string} String form of parsed message
233 return this.map
.exists( this.key
);
241 * Dummy function which in debug mode can be replaced with a function that
242 * emulates console.log in console-less environments.
247 * @var constructor Make the Map constructor publicly available.
252 * @var constructor Make the Message constructor publicly available.
257 * List of configuration values
259 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
260 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
261 * in the global window object.
268 * Empty object that plugins can be installed in.
272 /* Extension points */
277 * Localization system
284 * Gets a message object, similar to wfMessage()
286 * @param key string Key of message to get
287 * @param parameter_1 mixed First argument in a list of variadic arguments,
288 * each a parameter for $N replacement in messages.
291 message: function ( key
, parameter_1
/* [, parameter_2] */ ) {
293 // Support variadic arguments
294 if ( parameter_1
!== undefined ) {
295 parameters
= $.makeArray( arguments
);
300 return new Message( mw
.messages
, key
, parameters
);
304 * Gets a message string, similar to wfMsg()
306 * @param key string Key of message to get
307 * @param parameters mixed First argument in a list of variadic arguments,
308 * each a parameter for $N replacement in messages.
311 msg: function ( key
, parameters
) {
312 return mw
.message
.apply( mw
.message
, arguments
).toString();
316 * Client-side module loader which integrates with the MediaWiki ResourceLoader
318 loader
: ( function () {
320 /* Private Members */
323 * Mapping of registered modules
325 * The jquery module is pre-registered, because it must have already
326 * been provided for this object to have been built, and in debug mode
327 * jquery would have been provided through a unique loader request,
328 * making it impossible to hold back registration of jquery until after
331 * For exact details on support for script, style and messages, look at
332 * mw.loader.implement.
337 * 'version': ############## (unix timestamp),
338 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
339 * 'group': 'somegroup', (or) null,
340 * 'source': 'local', 'someforeignwiki', (or) null
341 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
344 * 'messages': { 'key': 'value' },
350 * Mapping of sources, keyed by source-id, values are objects.
354 * 'loadScript': 'http://foo.bar/w/load.php'
359 // List of modules which will be loaded as when ready
361 // List of modules to be loaded
363 // List of callback functions waiting for modules to be ready to be called
365 // Flag indicating that document ready has occured
367 // Selector cache for the marker element. Use getMarker() to get/use the marker!
370 /* Cache document ready status */
372 $(document
).ready( function () {
376 /* Private methods */
378 function getMarker() {
383 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
384 if ( $marker
.length
) {
387 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
388 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
393 function addInlineCSS( css
, media
) {
394 var $style
= getMarker().prev(),
396 attrs
= { 'type': 'text/css', 'media': media
};
397 if ( $style
.is( 'style' ) && $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
398 // There's already a dynamic <style> tag present, append to it
399 // This recycling of <style> tags is for bug 31676 (can't have
400 // more than 32 <style> tags in IE)
402 // Also, calling .append() on a <style> tag explodes with a JS error in IE,
403 // so if the .append() fails we fall back to building a new <style> tag and
404 // replacing the existing one
406 // Do cdata sanitization on the provided CSS, and prepend a double newline
407 css
= $( mw
.html
.element( 'style', {}, new mw
.html
.Cdata( "\n\n" + css
) ) ).html();
408 $style
.append( css
);
410 // Generate a new tag with the combined CSS
411 css
= $style
.html() + "\n\n" + css
;
412 $newStyle
= $( mw
.html
.element( 'style', attrs
, new mw
.html
.Cdata( css
) ) )
413 .data( 'ResourceLoaderDynamicStyleTag', true );
414 // Prevent a flash of unstyled content by inserting the new tag
415 // before removing the old one
416 $style
.after( $newStyle
);
420 // Create a new <style> tag and insert it
421 $style
= $( mw
.html
.element( 'style', attrs
, new mw
.html
.Cdata( css
) ) );
422 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
423 getMarker().before( $style
);
427 function compare( a
, b
) {
429 if ( a
.length
!== b
.length
) {
432 for ( i
= 0; i
< b
.length
; i
+= 1 ) {
433 if ( $.isArray( a
[i
] ) ) {
434 if ( !compare( a
[i
], b
[i
] ) ) {
438 if ( a
[i
] !== b
[i
] ) {
446 * Generates an ISO8601 "basic" string from a UNIX timestamp
448 function formatVersionNumber( timestamp
) {
449 var pad = function ( a
, b
, c
) {
450 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
453 d
.setTime( timestamp
* 1000 );
455 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
456 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
461 * Recursively resolves dependencies and detects circular references
463 function recurse( module
, resolved
, unresolved
) {
466 if ( registry
[module
] === undefined ) {
467 throw new Error( 'Unknown dependency: ' + module
);
469 // Resolves dynamic loader function and replaces it with its own results
470 if ( $.isFunction( registry
[module
].dependencies
) ) {
471 registry
[module
].dependencies
= registry
[module
].dependencies();
472 // Ensures the module's dependencies are always in an array
473 if ( typeof registry
[module
].dependencies
!== 'object' ) {
474 registry
[module
].dependencies
= [registry
[module
].dependencies
];
477 // Tracks down dependencies
478 deps
= registry
[module
].dependencies
;
480 for ( n
= 0; n
< len
; n
+= 1 ) {
481 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
482 if ( $.inArray( deps
[n
], unresolved
) !== -1 ) {
484 'Circular reference detected: ' + module
+
490 unresolved
[unresolved
.length
] = module
;
491 recurse( deps
[n
], resolved
, unresolved
);
492 // module is at the end of unresolved
496 resolved
[resolved
.length
] = module
;
500 * Gets a list of module names that a module depends on in their proper dependency order
502 * @param module string module name or array of string module names
503 * @return list of dependencies, including 'module'.
504 * @throws Error if circular reference is detected
506 function resolve( module
) {
507 var modules
, m
, deps
, n
, resolved
;
509 // Allow calling with an array of module names
510 if ( $.isArray( module
) ) {
512 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
513 deps
= resolve( module
[m
] );
514 for ( n
= 0; n
< deps
.length
; n
+= 1 ) {
515 modules
[modules
.length
] = deps
[n
];
519 } else if ( typeof module
=== 'string' ) {
521 recurse( module
, resolved
, [] );
524 throw new Error( 'Invalid module argument: ' + module
);
528 * Narrows a list of module names down to those matching a specific
529 * state (see comment on top of this scope for a list of valid states).
530 * One can also filter for 'unregistered', which will return the
531 * modules names that don't have a registry entry.
533 * @param states string or array of strings of module states to filter by
534 * @param modules array list of module names to filter (optional, by default the entire
536 * @return array list of filtered module names
538 function filter( states
, modules
) {
539 var list
, module
, s
, m
;
541 // Allow states to be given as a string
542 if ( typeof states
=== 'string' ) {
545 // If called without a list of modules, build and use a list of all modules
547 if ( modules
=== undefined ) {
549 for ( module
in registry
) {
550 modules
[modules
.length
] = module
;
553 // Build a list of modules which are in one of the specified states
554 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
555 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
556 if ( registry
[modules
[m
]] === undefined ) {
557 // Module does not exist
558 if ( states
[s
] === 'unregistered' ) {
560 list
[list
.length
] = modules
[m
];
563 // Module exists, check state
564 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
566 list
[list
.length
] = modules
[m
];
575 * Automatically executes jobs and modules which are pending with satistifed dependencies.
577 * This is used when dependencies are satisfied, such as when a module is executed.
579 function handlePending( module
) {
583 // Run jobs whose dependencies have just been met
584 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
586 filter( 'ready', jobs
[j
].dependencies
),
587 jobs
[j
].dependencies
) )
589 if ( $.isFunction( jobs
[j
].ready
) ) {
596 // Execute modules whose dependencies have just been met
597 for ( r
in registry
) {
598 if ( registry
[r
].state
=== 'loaded' ) {
600 filter( ['ready'], registry
[r
].dependencies
),
601 registry
[r
].dependencies
) )
608 // Run error callbacks of jobs affected by this condition
609 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
610 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
611 if ( $.isFunction( jobs
[j
].error
) ) {
612 jobs
[j
].error( e
, module
);
622 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
623 * depending on whether document-ready has occured yet and whether we are in async mode.
625 * @param src String: URL to script, will be used as the src attribute in the script tag
626 * @param callback Function: Optional callback which will be run when the script is done
628 function addScript( src
, callback
, async
) {
629 var done
= false, script
, head
;
630 if ( ready
|| async
) {
631 // jQuery's getScript method is NOT better than doing this the old-fashioned way
632 // because jQuery will eval the script's code, and errors will not have sane
634 script
= document
.createElement( 'script' );
635 script
.setAttribute( 'src', src
);
636 script
.setAttribute( 'type', 'text/javascript' );
637 if ( $.isFunction( callback
) ) {
638 // Attach handlers for all browsers (based on jQuery.ajax)
639 script
.onload
= script
.onreadystatechange = function() {
645 || /loaded|complete/.test( script
.readyState
)
651 // Handle memory leak in IE
652 script
.onload
= script
.onreadystatechange
= null;
656 if ( script
.parentNode
) {
657 script
.parentNode
.removeChild( script
);
660 // Dereference the script
666 if ( window
.opera
) {
667 // Appending to the <head> blocks rendering completely in Opera,
668 // so append to the <body> after document ready. This means the
669 // scripts only start loading after the document has been rendered,
670 // but so be it. Opera users don't deserve faster web pages if their
671 // browser makes it impossible
672 $( function() { document
.body
.appendChild( script
); } );
674 // IE-safe way of getting the <head> . document.documentElement.head doesn't
675 // work in scripts that run in the <head>
676 head
= document
.getElementsByTagName( 'head' )[0];
677 ( document
.body
|| head
).appendChild( script
);
680 document
.write( mw
.html
.element(
681 'script', { 'type': 'text/javascript', 'src': src
}, ''
683 if ( $.isFunction( callback
) ) {
684 // Document.write is synchronous, so this is called when it's done
685 // FIXME: that's a lie. doc.write isn't actually synchronous
692 * Executes a loaded module, making it ready to use
694 * @param module string module name to execute
696 function execute( module
, callback
) {
697 var style
, media
, i
, script
, markModuleReady
, nestedAddScript
;
699 if ( registry
[module
] === undefined ) {
700 throw new Error( 'Module has not been registered yet: ' + module
);
701 } else if ( registry
[module
].state
=== 'registered' ) {
702 throw new Error( 'Module has not been requested from the server yet: ' + module
);
703 } else if ( registry
[module
].state
=== 'loading' ) {
704 throw new Error( 'Module has not completed loading yet: ' + module
);
705 } else if ( registry
[module
].state
=== 'ready' ) {
706 throw new Error( 'Module has already been loaded: ' + module
);
710 if ( $.isPlainObject( registry
[module
].style
) ) {
711 for ( media
in registry
[module
].style
) {
712 style
= registry
[module
].style
[media
];
713 if ( $.isArray( style
) ) {
714 for ( i
= 0; i
< style
.length
; i
+= 1 ) {
715 getMarker().before( mw
.html
.element( 'link', {
722 } else if ( typeof style
=== 'string' ) {
723 addInlineCSS( style
, media
);
727 // Add localizations to message system
728 if ( $.isPlainObject( registry
[module
].messages
) ) {
729 mw
.messages
.set( registry
[module
].messages
);
733 script
= registry
[module
].script
;
734 markModuleReady = function() {
735 registry
[module
].state
= 'ready';
736 handlePending( module
);
737 if ( $.isFunction( callback
) ) {
741 nestedAddScript = function ( arr
, callback
, async
, i
) {
742 // Recursively call addScript() in its own callback
743 // for each element of arr.
744 if ( i
>= arr
.length
) {
745 // We're at the end of the array
750 addScript( arr
[i
], function() {
751 nestedAddScript( arr
, callback
, async
, i
+ 1 );
755 if ( $.isArray( script
) ) {
756 registry
[module
].state
= 'loading';
757 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
758 } else if ( $.isFunction( script
) ) {
763 // This needs to NOT use mw.log because these errors are common in production mode
764 // and not in debug mode, such as when a symbol that should be global isn't exported
765 if ( window
.console
&& typeof window
.console
.log
=== 'function' ) {
766 console
.log( 'mw.loader::execute> Exception thrown by ' + module
+ ': ' + e
.message
);
768 registry
[module
].state
= 'error';
774 * Adds a dependencies to the queue with optional callbacks to be run
775 * when the dependencies are ready or fail
777 * @param dependencies string module name or array of string module names
778 * @param ready function callback to execute when all dependencies are ready
779 * @param error function callback to execute when any dependency fails
780 * @param async (optional) If true, load modules asynchronously even if
781 * document ready has not yet occurred
783 function request( dependencies
, ready
, error
, async
) {
784 var regItemDeps
, regItemDepLen
, n
;
786 // Allow calling by single module name
787 if ( typeof dependencies
=== 'string' ) {
788 dependencies
= [dependencies
];
789 if ( registry
[dependencies
[0]] !== undefined ) {
790 // Cache repetitively accessed deep level object member
791 regItemDeps
= registry
[dependencies
[0]].dependencies
;
792 // Cache to avoid looped access to length property
793 regItemDepLen
= regItemDeps
.length
;
794 for ( n
= 0; n
< regItemDepLen
; n
+= 1 ) {
795 dependencies
[dependencies
.length
] = regItemDeps
[n
];
799 // Add ready and error callbacks if they were given
800 if ( arguments
.length
> 1 ) {
801 jobs
[jobs
.length
] = {
802 'dependencies': filter(
803 ['registered', 'loading', 'loaded'],
810 // Queue up any dependencies that are registered
811 dependencies
= filter( ['registered'], dependencies
);
812 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
813 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
814 queue
[queue
.length
] = dependencies
[n
];
816 // Mark this module as async in the registry
817 registry
[dependencies
[n
]].async
= true;
825 function sortQuery(o
) {
826 var sorted
= {}, key
, a
= [];
828 if ( hasOwn
.call( o
, key
) ) {
833 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
834 sorted
[a
[key
]] = o
[a
[key
]];
840 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
841 * to a query string of the form foo.bar,baz|bar.baz,quux
843 function buildModulesString( moduleMap
) {
844 var arr
= [], p
, prefix
;
845 for ( prefix
in moduleMap
) {
846 p
= prefix
=== '' ? '' : prefix
+ '.';
847 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
849 return arr
.join( '|' );
853 * Asynchronously append a script tag to the end of the body
854 * that invokes load.php
855 * @param moduleMap {Object}: Module map, see buildModulesString()
856 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
857 * @param sourceLoadScript {String}: URL of load.php
858 * @param async {Boolean}: If true, use an asynchrounous request even if document ready has not yet occurred
860 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
861 var request
= $.extend(
862 { 'modules': buildModulesString( moduleMap
) },
865 request
= sortQuery( request
);
866 // Asynchronously append a script tag to the end of the body
867 // Append &* to avoid triggering the IE6 extension check
868 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
874 * Requests dependencies from server, loading and executing when things when ready.
877 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
878 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
879 currReqBase
, currReqBaseLength
, moduleMap
, l
,
880 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
882 // Build a list of request parameters common to all requests.
884 skin
: mw
.config
.get( 'skin' ),
885 lang
: mw
.config
.get( 'wgUserLanguage' ),
886 debug
: mw
.config
.get( 'debug' )
888 // Split module batch by source and by group.
890 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
892 // Appends a list of modules from the queue to the batch
893 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
894 // Only request modules which are registered
895 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
896 // Prevent duplicate entries
897 if ( $.inArray( queue
[q
], batch
) === -1 ) {
898 batch
[batch
.length
] = queue
[q
];
899 // Mark registered modules as loading
900 registry
[queue
[q
]].state
= 'loading';
904 // Early exit if there's nothing to load...
905 if ( !batch
.length
) {
909 // The queue has been processed into the batch, clear up the queue.
912 // Always order modules alphabetically to help reduce cache
913 // misses for otherwise identical content.
916 // Split batch by source and by group.
917 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
918 bSource
= registry
[batch
[b
]].source
;
919 bGroup
= registry
[batch
[b
]].group
;
920 if ( splits
[bSource
] === undefined ) {
921 splits
[bSource
] = {};
923 if ( splits
[bSource
][bGroup
] === undefined ) {
924 splits
[bSource
][bGroup
] = [];
926 bSourceGroup
= splits
[bSource
][bGroup
];
927 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
930 // Clear the batch - this MUST happen before we append any
931 // script elements to the body or it's possible that a script
932 // will be locally cached, instantly load, and work the batch
933 // again, all before we've cleared it causing each request to
934 // include modules which are already loaded.
937 for ( source
in splits
) {
939 sourceLoadScript
= sources
[source
].loadScript
;
941 for ( group
in splits
[source
] ) {
943 // Cache access to currently selected list of
944 // modules for this group from this source.
945 modules
= splits
[source
][group
];
947 // Calculate the highest timestamp
949 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
950 if ( registry
[modules
[g
]].version
> maxVersion
) {
951 maxVersion
= registry
[modules
[g
]].version
;
955 currReqBase
= $.extend( { 'version': formatVersionNumber( maxVersion
) }, reqBase
);
956 currReqBaseLength
= $.param( currReqBase
).length
;
958 // We may need to split up the request to honor the query string length limit,
959 // so build it piece by piece.
960 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
962 moduleMap
= {}; // { prefix: [ suffixes ] }
964 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
965 // Determine how many bytes this module would add to the query string
966 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
967 // Note that these substr() calls work even if lastDotIndex == -1
968 prefix
= modules
[i
].substr( 0, lastDotIndex
);
969 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
970 bytesAdded
= moduleMap
[prefix
] !== undefined
971 ? suffix
.length
+ 3 // '%2C'.length == 3
972 : modules
[i
].length
+ 3; // '%7C'.length == 3
974 // If the request would become too long, create a new one,
975 // but don't create empty requests
976 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
977 // This request would become too long, create a new one
978 // and fire off the old one
979 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
982 l
= currReqBaseLength
+ 9;
984 if ( moduleMap
[prefix
] === undefined ) {
985 moduleMap
[prefix
] = [];
987 moduleMap
[prefix
].push( suffix
);
988 if ( !registry
[modules
[i
]].async
) {
989 // If this module is blocking, make the entire request blocking
990 // This is slightly suboptimal, but in practice mixing of blocking
991 // and async modules will only occur in debug mode.
996 // If there's anything left in moduleMap, request that too
997 if ( !$.isEmptyObject( moduleMap
) ) {
998 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1005 * Register a source.
1007 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
1008 * @param props {Object}: Object containing only the loadScript property which is a url to
1009 * the load.php location of the source.
1012 addSource: function ( id
, props
) {
1014 // Allow multiple additions
1015 if ( typeof id
=== 'object' ) {
1016 for ( source
in id
) {
1017 mw
.loader
.addSource( source
, id
[source
] );
1022 if ( sources
[id
] !== undefined ) {
1023 throw new Error( 'source already registered: ' + id
);
1026 sources
[id
] = props
;
1032 * Registers a module, letting the system know about it and its
1033 * properties. Startup modules contain calls to this function.
1035 * @param module {String}: Module name
1036 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1037 * @param dependencies {String|Array|Function}: One string or array of strings of module
1038 * names on which this module depends, or a function that returns that array.
1039 * @param group {String}: Group which the module is in (optional, defaults to null)
1040 * @param source {String}: Name of the source. Defaults to local.
1042 register: function ( module
, version
, dependencies
, group
, source
) {
1044 // Allow multiple registration
1045 if ( typeof module
=== 'object' ) {
1046 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1047 // module is an array of module names
1048 if ( typeof module
[m
] === 'string' ) {
1049 mw
.loader
.register( module
[m
] );
1050 // module is an array of arrays
1051 } else if ( typeof module
[m
] === 'object' ) {
1052 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1058 if ( typeof module
!== 'string' ) {
1059 throw new Error( 'module must be a string, not a ' + typeof module
);
1061 if ( registry
[module
] !== undefined ) {
1062 throw new Error( 'module already registered: ' + module
);
1064 // List the module as registered
1065 registry
[module
] = {
1066 'version': version
!== undefined ? parseInt( version
, 10 ) : 0,
1068 'group': typeof group
=== 'string' ? group
: null,
1069 'source': typeof source
=== 'string' ? source
: 'local',
1070 'state': 'registered'
1072 if ( typeof dependencies
=== 'string' ) {
1073 // Allow dependencies to be given as a single module name
1074 registry
[module
].dependencies
= [dependencies
];
1075 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1076 // Allow dependencies to be given as an array of module names
1077 // or a function which returns an array
1078 registry
[module
].dependencies
= dependencies
;
1083 * Implements a module, giving the system a course of action to take
1084 * upon loading. Results of a request for one or more modules contain
1085 * calls to this function.
1087 * All arguments are required.
1089 * @param module String: Name of module
1090 * @param script Mixed: Function of module code or String of URL to be used as the src
1091 * attribute when adding a script element to the body
1092 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1093 * keyed by media-type
1094 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1096 implement: function ( module
, script
, style
, msgs
) {
1098 if ( typeof module
!== 'string' ) {
1099 throw new Error( 'module must be a string, not a ' + typeof module
);
1101 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1102 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1104 if ( !$.isPlainObject( style
) ) {
1105 throw new Error( 'style must be an object, not a ' + typeof style
);
1107 if ( !$.isPlainObject( msgs
) ) {
1108 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1110 // Automatically register module
1111 if ( registry
[module
] === undefined ) {
1112 mw
.loader
.register( module
);
1114 // Check for duplicate implementation
1115 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1116 throw new Error( 'module already implemented: ' + module
);
1118 // Mark module as loaded
1119 registry
[module
].state
= 'loaded';
1120 // Attach components
1121 registry
[module
].script
= script
;
1122 registry
[module
].style
= style
;
1123 registry
[module
].messages
= msgs
;
1124 // Execute or queue callback
1126 filter( ['ready'], registry
[module
].dependencies
),
1127 registry
[module
].dependencies
) )
1134 * Executes a function as soon as one or more required modules are ready
1136 * @param dependencies {String|Array} Module name or array of modules names the callback
1137 * dependends on to be ready before executing
1138 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1139 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1141 using: function ( dependencies
, ready
, error
) {
1142 var tod
= typeof dependencies
;
1144 if ( tod
!== 'object' && tod
!== 'string' ) {
1145 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1147 // Allow calling with a single dependency as a string
1148 if ( tod
=== 'string' ) {
1149 dependencies
= [dependencies
];
1151 // Resolve entire dependency map
1152 dependencies
= resolve( dependencies
);
1153 // If all dependencies are met, execute ready immediately
1154 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
1155 if ( $.isFunction( ready
) ) {
1159 // If any dependencies have errors execute error immediately
1160 else if ( filter( ['error'], dependencies
).length
) {
1161 if ( $.isFunction( error
) ) {
1162 error( new Error( 'one or more dependencies have state "error"' ),
1166 // Since some dependencies are not yet ready, queue up a request
1168 request( dependencies
, ready
, error
);
1173 * Loads an external script or one or more modules for future use
1175 * @param modules {mixed} Either the name of a module, array of modules,
1176 * or a URL of an external script or style
1177 * @param type {String} mime-type to use if calling with a URL of an
1178 * external script or style; acceptable values are "text/css" and
1179 * "text/javascript"; if no type is provided, text/javascript is assumed.
1180 * @param async {Boolean} (optional) If true, load modules asynchronously
1181 * even if document ready has not yet occurred. If false (default),
1182 * block before document ready and load async after
1184 load: function ( modules
, type
, async
) {
1188 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1189 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1191 // Allow calling with an external url or single dependency as a string
1192 if ( typeof modules
=== 'string' ) {
1193 // Support adding arbitrary external scripts
1194 if ( /^(https?:)?\/\//.test( modules
) ) {
1195 if ( type
=== 'text/css' ) {
1196 $( 'head' ).append( $( '<link>', {
1202 } else if ( type
=== 'text/javascript' || type
=== undefined ) {
1203 addScript( modules
, null, async
);
1207 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1209 // Called with single module
1210 modules
= [modules
];
1213 // Filter out undefined modules, otherwise resolve() will throw
1214 // an exception for trying to load an undefined module.
1215 // Undefined modules are acceptable here in load(), because load() takes
1216 // an array of unrelated modules, whereas the modules passed to
1217 // using() are related and must all be loaded.
1218 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1219 if ( registry
[modules
[m
]] !== undefined ) {
1220 filtered
[filtered
.length
] = modules
[m
];
1224 // Resolve entire dependency map
1225 filtered
= resolve( filtered
);
1226 // If all modules are ready, nothing dependency be done
1227 if ( compare( filter( ['ready'], filtered
), filtered
) ) {
1230 // If any modules have errors
1231 else if ( filter( ['error'], filtered
).length
) {
1234 // Since some modules are not yet ready, queue up a request
1236 request( filtered
, null, null, async
);
1242 * Changes the state of a module
1244 * @param module {String|Object} module name or object of module name/state pairs
1245 * @param state {String} state name
1247 state: function ( module
, state
) {
1249 if ( typeof module
=== 'object' ) {
1250 for ( m
in module
) {
1251 mw
.loader
.state( m
, module
[m
] );
1255 if ( registry
[module
] === undefined ) {
1256 mw
.loader
.register( module
);
1258 registry
[module
].state
= state
;
1262 * Gets the version of a module
1264 * @param module string name of module to get version for
1266 getVersion: function ( module
) {
1267 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1268 return formatVersionNumber( registry
[module
].version
);
1274 * @deprecated since 1.18 use mw.loader.getVersion() instead
1276 version: function () {
1277 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1281 * Gets the state of a module
1283 * @param module string name of module to get state for
1285 getState: function ( module
) {
1286 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1287 return registry
[module
].state
;
1293 * Get names of all registered modules.
1297 getModuleNames: function () {
1298 return $.map( registry
, function ( i
, key
) {
1304 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1307 mw
.loader
.load( 'mediawiki.user' );
1312 /** HTML construction helper functions */
1313 html
: ( function () {
1314 function escapeCallback( s
) {
1331 * Escape a string for HTML. Converts special characters to HTML entities.
1332 * @param s The string to escape
1334 escape: function ( s
) {
1335 return s
.replace( /['"<>&]/g, escapeCallback
);
1339 * Wrapper object for raw HTML passed to mw.html.element().
1342 Raw: function ( value
) {
1347 * Wrapper object for CDATA element contents passed to mw.html.element()
1350 Cdata: function ( value
) {
1355 * Create an HTML element string, with safe escaping.
1357 * @param name The tag name.
1358 * @param attrs An object with members mapping element names to values
1359 * @param contents The contents of the element. May be either:
1360 * - string: The string is escaped.
1361 * - null or undefined: The short closing form is used, e.g. <br/>.
1362 * - this.Raw: The value attribute is included without escaping.
1363 * - this.Cdata: The value attribute is included, and an exception is
1364 * thrown if it contains an illegal ETAGO delimiter.
1365 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1369 * return h.element( 'div', {},
1370 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1371 * Returns <div><img src="<"/></div>
1373 element: function ( name
, attrs
, contents
) {
1374 var v
, attrName
, s
= '<' + name
;
1376 for ( attrName
in attrs
) {
1377 v
= attrs
[attrName
];
1378 // Convert name=true, to name=name
1382 } else if ( v
=== false ) {
1385 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
1387 if ( contents
=== undefined || contents
=== null ) {
1394 switch ( typeof contents
) {
1397 s
+= this.escape( contents
);
1401 // Convert to string
1402 s
+= String( contents
);
1405 if ( contents
instanceof this.Raw
) {
1406 // Raw HTML inclusion
1407 s
+= contents
.value
;
1408 } else if ( contents
instanceof this.Cdata
) {
1410 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1411 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1413 s
+= contents
.value
;
1415 throw new Error( 'mw.html.element: Invalid type of contents' );
1418 s
+= '</' + name
+ '>';
1427 // Alias $j to jQuery for backwards compatibility
1430 // Attach to window and globally alias
1431 window
.mw
= window
.mediaWiki
= mw
;
1433 // Auto-register from pre-loaded startup scripts
1434 if ( typeof startUp
!== 'undefined' && jQuery
.isFunction( startUp
) ) {
1436 startUp
= undefined;