2 * Core MediaWiki JavaScript Library
5 var mw
= ( function ( $, undefined ) {
10 var hasOwn
= Object
.prototype.hasOwnProperty
,
11 slice
= Array
.prototype.slice
;
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
= slice
.call( 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 ? [] : slice
.call( 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.
144 parser: function () {
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' || this.format
=== 'parse' ) {
184 text
= this.parser();
187 if ( this.format
=== 'escaped' ) {
188 text
= this.parser();
189 text
= mw
.html
.escape( text
);
196 * Changes format to parse and converts message to string
198 * @return {string} String form of parsed message
201 this.format
= 'parse';
202 return this.toString();
206 * Changes format to plain and converts message to string
208 * @return {string} String form of plain message
211 this.format
= 'plain';
212 return this.toString();
216 * Changes the format to html escaped and converts message to string
218 * @return {string} String form of html escaped message
220 escaped: function () {
221 this.format
= 'escaped';
222 return this.toString();
226 * Checks if message exists
228 * @return {string} String form of parsed message
230 exists: function () {
231 return this.map
.exists( this.key
);
239 * Dummy function which in debug mode can be replaced with a function that
240 * emulates console.log in console-less environments.
242 log: function () { },
245 * @var constructor Make the Map constructor publicly available.
250 * @var constructor Make the Message constructor publicly available.
255 * List of configuration values
257 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
258 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
259 * in the global window object.
266 * Empty object that plugins can be installed in.
270 /* Extension points */
275 * Localization system
282 * Gets a message object, similar to wfMessage()
284 * @param key string Key of message to get
285 * @param parameter1 mixed First argument in a list of variadic arguments,
286 * each a parameter for $N replacement in messages.
289 message: function ( key
, parameter1
) {
291 // Support variadic arguments
292 if ( parameter1
!== undefined ) {
293 parameters
= slice
.call( arguments
);
298 return new Message( mw
.messages
, key
, parameters
);
302 * Gets a message string, similar to wfMessage()
304 * @param key string Key of message to get
305 * @param parameters mixed First argument in a list of variadic arguments,
306 * each a parameter for $N replacement in messages.
309 msg: function ( /* key, parameter_1, parameter_2, .. */ ) {
310 return mw
.message
.apply( mw
.message
, arguments
).toString();
314 * Client-side module loader which integrates with the MediaWiki ResourceLoader
316 loader
: ( function () {
318 /* Private Members */
321 * Mapping of registered modules
323 * The jquery module is pre-registered, because it must have already
324 * been provided for this object to have been built, and in debug mode
325 * jquery would have been provided through a unique loader request,
326 * making it impossible to hold back registration of jquery until after
329 * For exact details on support for script, style and messages, look at
330 * mw.loader.implement.
335 * 'version': ############## (unix timestamp),
336 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
337 * 'group': 'somegroup', (or) null,
338 * 'source': 'local', 'someforeignwiki', (or) null
339 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
342 * 'messages': { 'key': 'value' },
348 * Mapping of sources, keyed by source-id, values are objects.
352 * 'loadScript': 'http://foo.bar/w/load.php'
357 // List of modules which will be loaded as when ready
359 // List of modules to be loaded
361 // List of callback functions waiting for modules to be ready to be called
363 // Selector cache for the marker element. Use getMarker() to get/use the marker!
366 /* Private methods */
368 function getMarker() {
374 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
375 if ( $marker
.length
) {
378 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
379 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
385 * Create a new style tag and add it to the DOM.
387 * @param text String: CSS text
388 * @param nextnode mixed: [optional] An Element or jQuery object for an element where
389 * the style tag should be inserted before. Otherwise appended to the <head>.
390 * @return HTMLStyleElement
392 function addStyleTag( text
, nextnode
) {
393 var s
= document
.createElement( 'style' );
394 // Insert into document before setting cssText (bug 33305)
396 // Must be inserted with native insertBefore, not $.fn.before.
397 // When using jQuery to insert it, like $nextnode.before( s ),
398 // then IE6 will throw "Access is denied" when trying to append
399 // to .cssText later. Some kind of weird security measure.
400 // http://stackoverflow.com/q/12586482/319266
401 // Works: jsfiddle.net/zJzMy/1
402 // Fails: jsfiddle.net/uJTQz
403 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
404 if ( nextnode
.jquery
) {
405 nextnode
= nextnode
.get( 0 );
407 nextnode
.parentNode
.insertBefore( s
, nextnode
);
409 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
411 if ( s
.styleSheet
) {
413 s
.styleSheet
.cssText
= text
;
416 // (Safari sometimes borks on non-string values,
417 // play safe by casting to a string, just in case.)
418 s
.appendChild( document
.createTextNode( String( text
) ) );
424 * Checks if certain cssText is safe to append to
427 * Right now it only makes sure that cssText containing @import
428 * rules will end up in a new stylesheet (as those only work when
429 * placed at the start of a stylesheet; bug 35562).
430 * This could later be extended to take care of other bugs, such as
431 * the IE cssRules limit - not the same as the IE styleSheets limit).
433 function canExpandStylesheetWith( $style
, cssText
) {
434 return cssText
.indexOf( '@import' ) === -1;
437 function addEmbeddedCSS( cssText
) {
439 $style
= getMarker().prev();
440 // Re-use <style> tags if possible, this to try to stay
441 // under the IE stylesheet limit (bug 31676).
442 // Also verify that the the element before Marker actually is one
443 // that came from ResourceLoader, and not a style tag that some
444 // other script inserted before our marker, or, more importantly,
445 // it may not be a style tag at all (could be <meta> or <script>).
447 $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true &&
448 canExpandStylesheetWith( $style
, cssText
)
450 // There's already a dynamic <style> tag present and
451 // canExpandStylesheetWith() gave a green light to append more to it.
452 styleEl
= $style
.get( 0 );
453 if ( styleEl
.styleSheet
) {
455 styleEl
.styleSheet
.cssText
+= cssText
; // IE
457 log( 'addEmbeddedCSS fail\ne.message: ' + e
.message
, e
);
460 styleEl
.appendChild( document
.createTextNode( String( cssText
) ) );
463 $( addStyleTag( cssText
, getMarker() ) )
464 .data( 'ResourceLoaderDynamicStyleTag', true );
469 * Generates an ISO8601 "basic" string from a UNIX timestamp
471 function formatVersionNumber( timestamp
) {
473 function pad( a
, b
, c
) {
474 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
476 d
.setTime( timestamp
* 1000 );
478 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
479 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
484 * Resolves dependencies and detects circular references.
486 * @param module String Name of the top-level module whose dependencies shall be
487 * resolved and sorted.
488 * @param resolved Array Returns a topological sort of the given module and its
489 * dependencies, such that later modules depend on earlier modules. The array
490 * contains the module names. If the array contains already some module names,
491 * this function appends its result to the pre-existing array.
492 * @param unresolved Object [optional] Hash used to track the current dependency
493 * chain; used to report loops in the dependency graph.
494 * @throws Error if any unregistered module or a dependency loop is encountered
496 function sortDependencies( module
, resolved
, unresolved
) {
499 if ( registry
[module
] === undefined ) {
500 throw new Error( 'Unknown dependency: ' + module
);
502 // Resolves dynamic loader function and replaces it with its own results
503 if ( $.isFunction( registry
[module
].dependencies
) ) {
504 registry
[module
].dependencies
= registry
[module
].dependencies();
505 // Ensures the module's dependencies are always in an array
506 if ( typeof registry
[module
].dependencies
!== 'object' ) {
507 registry
[module
].dependencies
= [registry
[module
].dependencies
];
510 if ( $.inArray( module
, resolved
) !== -1 ) {
511 // Module already resolved; nothing to do.
514 // unresolved is optional, supply it if not passed in
518 // Tracks down dependencies
519 deps
= registry
[module
].dependencies
;
521 for ( n
= 0; n
< len
; n
+= 1 ) {
522 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
523 if ( unresolved
[deps
[n
]] ) {
525 'Circular reference detected: ' + module
+
531 unresolved
[module
] = true;
532 sortDependencies( deps
[n
], resolved
, unresolved
);
533 delete unresolved
[module
];
536 resolved
[resolved
.length
] = module
;
540 * Gets a list of module names that a module depends on in their proper dependency
543 * @param module string module name or array of string module names
544 * @return list of dependencies, including 'module'.
545 * @throws Error if circular reference is detected
547 function resolve( module
) {
550 // Allow calling with an array of module names
551 if ( $.isArray( module
) ) {
553 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
554 sortDependencies( module
[m
], resolved
);
559 if ( typeof module
=== 'string' ) {
561 sortDependencies( module
, resolved
);
565 throw new Error( 'Invalid module argument: ' + module
);
569 * Narrows a list of module names down to those matching a specific
570 * state (see comment on top of this scope for a list of valid states).
571 * One can also filter for 'unregistered', which will return the
572 * modules names that don't have a registry entry.
574 * @param states string or array of strings of module states to filter by
575 * @param modules array list of module names to filter (optional, by default the entire
577 * @return array list of filtered module names
579 function filter( states
, modules
) {
580 var list
, module
, s
, m
;
582 // Allow states to be given as a string
583 if ( typeof states
=== 'string' ) {
586 // If called without a list of modules, build and use a list of all modules
588 if ( modules
=== undefined ) {
590 for ( module
in registry
) {
591 modules
[modules
.length
] = module
;
594 // Build a list of modules which are in one of the specified states
595 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
596 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
597 if ( registry
[modules
[m
]] === undefined ) {
598 // Module does not exist
599 if ( states
[s
] === 'unregistered' ) {
601 list
[list
.length
] = modules
[m
];
604 // Module exists, check state
605 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
607 list
[list
.length
] = modules
[m
];
616 * Determine whether all dependencies are in state 'ready', which means we may
617 * execute the module or job now.
619 * @param dependencies Array dependencies (module names) to be checked.
621 * @return Boolean true if all dependencies are in state 'ready', false otherwise
623 function allReady( dependencies
) {
624 return filter( 'ready', dependencies
).length
=== dependencies
.length
;
628 * Log a message to window.console, if possible. Useful to force logging of some
629 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
630 * Gets console references in each invocation, so that delayed debugging tools work
631 * fine. No need for optimization here, which would only result in losing logs.
633 * @param msg String text for the log entry.
634 * @param e Error [optional] to also log.
636 function log( msg
, e
) {
637 var console
= window
.console
;
638 if ( console
&& console
.log
) {
640 // If we have an exception object, log it through .error() to trigger
641 // proper stacktraces in browsers that support it. There are no (known)
642 // browsers that don't support .error(), that do support .log() and
643 // have useful exception handling through .log().
644 if ( e
&& console
.error
) {
651 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
652 * and modules that depend upon this module. if the given module failed, propagate the 'error'
653 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
654 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
656 * @param module String name of module that entered one of the states 'ready', 'error', or 'missing'.
658 function handlePending( module
) {
659 var j
, job
, hasErrors
, m
, stateChange
;
662 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) !== -1 ) {
663 // If the current module failed, mark all dependent modules also as failed.
664 // Iterate until steady-state to propagate the error state upwards in the
668 for ( m
in registry
) {
669 if ( $.inArray( registry
[m
].state
, ['error', 'missing'] ) === -1 ) {
670 if ( filter( ['error', 'missing'], registry
[m
].dependencies
).length
> 0 ) {
671 registry
[m
].state
= 'error';
676 } while ( stateChange
);
679 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
680 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
681 hasErrors
= filter( ['error', 'missing'], jobs
[j
].dependencies
).length
> 0;
682 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
683 // All dependencies satisfied, or some have errors
689 throw new Error( 'Module ' + module
+ ' failed.');
691 if ( $.isFunction( job
.ready
) ) {
696 if ( $.isFunction( job
.error
) ) {
698 job
.error( e
, [module
] );
700 // A user-defined operation raised an exception. Swallow to protect
701 // our state machine!
702 log( 'Exception thrown by job.error()', ex
);
709 if ( registry
[module
].state
=== 'ready' ) {
710 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
711 // and now have all dependencies satisfied.
712 for ( m
in registry
) {
713 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
721 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
722 * depending on whether document-ready has occurred yet and whether we are in async mode.
724 * @param src String: URL to script, will be used as the src attribute in the script tag
725 * @param callback Function: Optional callback which will be run when the script is done
727 function addScript( src
, callback
, async
) {
728 /*jshint evil:true */
732 // Using isReady directly instead of storing it locally from
733 // a $.fn.ready callback (bug 31895).
734 if ( $.isReady
|| async
) {
735 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
736 // it uses XHR and eval for same-domain scripts, which we don't want because it
737 // messes up line numbers.
738 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
740 // IE-safe way of getting the <head>. document.head isn't supported
741 // in old IE, and doesn't work when in the <head>.
742 head
= document
.getElementsByTagName( 'head' )[0] || document
.body
;
744 script
= document
.createElement( 'script' );
747 if ( $.isFunction( callback
) ) {
748 script
.onload
= script
.onreadystatechange = function () {
753 || /loaded|complete/.test( script
.readyState
)
758 // Handle memory leak in IE
759 script
.onload
= script
.onreadystatechange
= null;
762 if ( script
.parentNode
) {
763 script
.parentNode
.removeChild( script
);
766 // Dereference the script
774 if ( window
.opera
) {
775 // Appending to the <head> blocks rendering completely in Opera,
776 // so append to the <body> after document ready. This means the
777 // scripts only start loading after the document has been rendered,
778 // but so be it. Opera users don't deserve faster web pages if their
779 // browser makes it impossible.
781 document
.body
.appendChild( script
);
784 head
.appendChild( script
);
787 document
.write( mw
.html
.element( 'script', { 'src': src
}, '' ) );
788 if ( $.isFunction( callback
) ) {
789 // Document.write is synchronous, so this is called when it's done
790 // FIXME: that's a lie. doc.write isn't actually synchronous
797 * Executes a loaded module, making it ready to use
799 * @param module string module name to execute
801 function execute( module
) {
802 var key
, value
, media
, i
, urls
, script
, markModuleReady
, nestedAddScript
;
804 if ( registry
[module
] === undefined ) {
805 throw new Error( 'Module has not been registered yet: ' + module
);
806 } else if ( registry
[module
].state
=== 'registered' ) {
807 throw new Error( 'Module has not been requested from the server yet: ' + module
);
808 } else if ( registry
[module
].state
=== 'loading' ) {
809 throw new Error( 'Module has not completed loading yet: ' + module
);
810 } else if ( registry
[module
].state
=== 'ready' ) {
811 throw new Error( 'Module has already been loaded: ' + module
);
815 * Define loop-function here for efficiency
816 * and to avoid re-using badly scoped variables.
818 function addLink( media
, url
) {
819 var el
= document
.createElement( 'link' );
820 getMarker().before( el
); // IE: Insert in dom before setting href
821 el
.rel
= 'stylesheet';
822 if ( media
&& media
!== 'all' ) {
828 // Process styles (see also mw.loader.implement)
829 // * back-compat: { <media>: css }
830 // * back-compat: { <media>: [url, ..] }
831 // * { "css": [css, ..] }
832 // * { "url": { <media>: [url, ..] } }
833 if ( $.isPlainObject( registry
[module
].style
) ) {
834 for ( key
in registry
[module
].style
) {
835 value
= registry
[module
].style
[key
];
838 if ( key
!== 'url' && key
!== 'css' ) {
839 // Backwards compatibility, key is a media-type
840 if ( typeof value
=== 'string' ) {
841 // back-compat: { <media>: css }
842 // Ignore 'media' because it isn't supported (nor was it used).
843 // Strings are pre-wrapped in "@media". The media-type was just ""
844 // (because it had to be set to something).
845 // This is one of the reasons why this format is no longer used.
846 addEmbeddedCSS( value
);
848 // back-compat: { <media>: [url, ..] }
854 // Array of css strings in key 'css',
855 // or back-compat array of urls from media-type
856 if ( $.isArray( value
) ) {
857 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
858 if ( key
=== 'bc-url' ) {
859 // back-compat: { <media>: [url, ..] }
860 addLink( media
, value
[i
] );
861 } else if ( key
=== 'css' ) {
862 // { "css": [css, ..] }
863 addEmbeddedCSS( value
[i
] );
866 // Not an array, but a regular object
867 // Array of urls inside media-type key
868 } else if ( typeof value
=== 'object' ) {
869 // { "url": { <media>: [url, ..] } }
870 for ( media
in value
) {
872 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
873 addLink( media
, urls
[i
] );
880 // Add localizations to message system
881 if ( $.isPlainObject( registry
[module
].messages
) ) {
882 mw
.messages
.set( registry
[module
].messages
);
887 script
= registry
[module
].script
;
888 markModuleReady = function () {
889 registry
[module
].state
= 'ready';
890 handlePending( module
);
892 nestedAddScript = function ( arr
, callback
, async
, i
) {
893 // Recursively call addScript() in its own callback
894 // for each element of arr.
895 if ( i
>= arr
.length
) {
896 // We're at the end of the array
901 addScript( arr
[i
], function () {
902 nestedAddScript( arr
, callback
, async
, i
+ 1 );
906 if ( $.isArray( script
) ) {
907 registry
[module
].state
= 'loading';
908 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
909 } else if ( $.isFunction( script
) ) {
910 registry
[module
].state
= 'ready';
912 handlePending( module
);
915 // This needs to NOT use mw.log because these errors are common in production mode
916 // and not in debug mode, such as when a symbol that should be global isn't exported
917 log( 'Exception thrown by ' + module
+ ': ' + e
.message
, e
);
918 registry
[module
].state
= 'error';
919 handlePending( module
);
924 * Adds a dependencies to the queue with optional callbacks to be run
925 * when the dependencies are ready or fail
927 * @param dependencies string module name or array of string module names
928 * @param ready function callback to execute when all dependencies are ready
929 * @param error function callback to execute when any dependency fails
930 * @param async (optional) If true, load modules asynchronously even if
931 * document ready has not yet occurred
933 function request( dependencies
, ready
, error
, async
) {
936 // Allow calling by single module name
937 if ( typeof dependencies
=== 'string' ) {
938 dependencies
= [dependencies
];
941 // Add ready and error callbacks if they were given
942 if ( ready
!== undefined || error
!== undefined ) {
943 jobs
[jobs
.length
] = {
944 'dependencies': filter(
945 ['registered', 'loading', 'loaded'],
953 // Queue up any dependencies that are registered
954 dependencies
= filter( ['registered'], dependencies
);
955 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
956 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
957 queue
[queue
.length
] = dependencies
[n
];
959 // Mark this module as async in the registry
960 registry
[dependencies
[n
]].async
= true;
969 function sortQuery(o
) {
970 var sorted
= {}, key
, a
= [];
972 if ( hasOwn
.call( o
, key
) ) {
977 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
978 sorted
[a
[key
]] = o
[a
[key
]];
984 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
985 * to a query string of the form foo.bar,baz|bar.baz,quux
987 function buildModulesString( moduleMap
) {
988 var arr
= [], p
, prefix
;
989 for ( prefix
in moduleMap
) {
990 p
= prefix
=== '' ? '' : prefix
+ '.';
991 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
993 return arr
.join( '|' );
997 * Asynchronously append a script tag to the end of the body
998 * that invokes load.php
999 * @param moduleMap {Object}: Module map, see buildModulesString()
1000 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
1001 * @param sourceLoadScript {String}: URL of load.php
1002 * @param async {Boolean}: If true, use an asynchrounous request even if document ready has not yet occurred
1004 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
1005 var request
= $.extend(
1006 { modules
: buildModulesString( moduleMap
) },
1009 request
= sortQuery( request
);
1010 // Asynchronously append a script tag to the end of the body
1011 // Append &* to avoid triggering the IE6 extension check
1012 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
1015 /* Public Methods */
1017 addStyleTag
: addStyleTag
,
1020 * Requests dependencies from server, loading and executing when things when ready.
1023 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1024 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
1025 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1026 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
1028 // Build a list of request parameters common to all requests.
1030 skin
: mw
.config
.get( 'skin' ),
1031 lang
: mw
.config
.get( 'wgUserLanguage' ),
1032 debug
: mw
.config
.get( 'debug' )
1034 // Split module batch by source and by group.
1036 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
1038 // Appends a list of modules from the queue to the batch
1039 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1040 // Only request modules which are registered
1041 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
1042 // Prevent duplicate entries
1043 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1044 batch
[batch
.length
] = queue
[q
];
1045 // Mark registered modules as loading
1046 registry
[queue
[q
]].state
= 'loading';
1050 // Early exit if there's nothing to load...
1051 if ( !batch
.length
) {
1055 // The queue has been processed into the batch, clear up the queue.
1058 // Always order modules alphabetically to help reduce cache
1059 // misses for otherwise identical content.
1062 // Split batch by source and by group.
1063 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1064 bSource
= registry
[batch
[b
]].source
;
1065 bGroup
= registry
[batch
[b
]].group
;
1066 if ( splits
[bSource
] === undefined ) {
1067 splits
[bSource
] = {};
1069 if ( splits
[bSource
][bGroup
] === undefined ) {
1070 splits
[bSource
][bGroup
] = [];
1072 bSourceGroup
= splits
[bSource
][bGroup
];
1073 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1076 // Clear the batch - this MUST happen before we append any
1077 // script elements to the body or it's possible that a script
1078 // will be locally cached, instantly load, and work the batch
1079 // again, all before we've cleared it causing each request to
1080 // include modules which are already loaded.
1083 for ( source
in splits
) {
1085 sourceLoadScript
= sources
[source
].loadScript
;
1087 for ( group
in splits
[source
] ) {
1089 // Cache access to currently selected list of
1090 // modules for this group from this source.
1091 modules
= splits
[source
][group
];
1093 // Calculate the highest timestamp
1095 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
1096 if ( registry
[modules
[g
]].version
> maxVersion
) {
1097 maxVersion
= registry
[modules
[g
]].version
;
1101 currReqBase
= $.extend( { version
: formatVersionNumber( maxVersion
) }, reqBase
);
1102 // For user modules append a user name to the request.
1103 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1104 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1106 currReqBaseLength
= $.param( currReqBase
).length
;
1108 // We may need to split up the request to honor the query string length limit,
1109 // so build it piece by piece.
1110 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1112 moduleMap
= {}; // { prefix: [ suffixes ] }
1114 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1115 // Determine how many bytes this module would add to the query string
1116 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1117 // Note that these substr() calls work even if lastDotIndex == -1
1118 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1119 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
1120 bytesAdded
= moduleMap
[prefix
] !== undefined
1121 ? suffix
.length
+ 3 // '%2C'.length == 3
1122 : modules
[i
].length
+ 3; // '%7C'.length == 3
1124 // If the request would become too long, create a new one,
1125 // but don't create empty requests
1126 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1127 // This request would become too long, create a new one
1128 // and fire off the old one
1129 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1132 l
= currReqBaseLength
+ 9;
1134 if ( moduleMap
[prefix
] === undefined ) {
1135 moduleMap
[prefix
] = [];
1137 moduleMap
[prefix
].push( suffix
);
1138 if ( !registry
[modules
[i
]].async
) {
1139 // If this module is blocking, make the entire request blocking
1140 // This is slightly suboptimal, but in practice mixing of blocking
1141 // and async modules will only occur in debug mode.
1146 // If there's anything left in moduleMap, request that too
1147 if ( !$.isEmptyObject( moduleMap
) ) {
1148 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1155 * Register a source.
1157 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
1158 * @param props {Object}: Object containing only the loadScript property which is a url to
1159 * the load.php location of the source.
1162 addSource: function ( id
, props
) {
1164 // Allow multiple additions
1165 if ( typeof id
=== 'object' ) {
1166 for ( source
in id
) {
1167 mw
.loader
.addSource( source
, id
[source
] );
1172 if ( sources
[id
] !== undefined ) {
1173 throw new Error( 'source already registered: ' + id
);
1176 sources
[id
] = props
;
1182 * Registers a module, letting the system know about it and its
1183 * properties. Startup modules contain calls to this function.
1185 * @param module {String}: Module name
1186 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1187 * @param dependencies {String|Array|Function}: One string or array of strings of module
1188 * names on which this module depends, or a function that returns that array.
1189 * @param group {String}: Group which the module is in (optional, defaults to null)
1190 * @param source {String}: Name of the source. Defaults to local.
1192 register: function ( module
, version
, dependencies
, group
, source
) {
1194 // Allow multiple registration
1195 if ( typeof module
=== 'object' ) {
1196 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1197 // module is an array of module names
1198 if ( typeof module
[m
] === 'string' ) {
1199 mw
.loader
.register( module
[m
] );
1200 // module is an array of arrays
1201 } else if ( typeof module
[m
] === 'object' ) {
1202 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1208 if ( typeof module
!== 'string' ) {
1209 throw new Error( 'module must be a string, not a ' + typeof module
);
1211 if ( registry
[module
] !== undefined ) {
1212 throw new Error( 'module already registered: ' + module
);
1214 // List the module as registered
1215 registry
[module
] = {
1216 version
: version
!== undefined ? parseInt( version
, 10 ) : 0,
1218 group
: typeof group
=== 'string' ? group
: null,
1219 source
: typeof source
=== 'string' ? source
: 'local',
1222 if ( typeof dependencies
=== 'string' ) {
1223 // Allow dependencies to be given as a single module name
1224 registry
[module
].dependencies
= [ dependencies
];
1225 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1226 // Allow dependencies to be given as an array of module names
1227 // or a function which returns an array
1228 registry
[module
].dependencies
= dependencies
;
1233 * Implements a module, giving the system a course of action to take
1234 * upon loading. Results of a request for one or more modules contain
1235 * calls to this function.
1237 * All arguments are required.
1239 * @param {String} module Name of module
1240 * @param {Function|Array} script Function with module code or Array of URLs to
1241 * be used as the src attribute of a new <script> tag.
1242 * @param {Object} style Should follow one of the following patterns:
1243 * { "css": [css, ..] }
1244 * { "url": { <media>: [url, ..] } }
1245 * And for backwards compatibility (needs to be supported forever due to caching):
1247 * { <media>: [url, ..] }
1249 * The reason css strings are not concatenated anymore is bug 31676. We now check
1250 * whether it's safe to extend the stylesheet (see canExpandStylesheetWith).
1252 * @param {Object} msgs List of key/value pairs to be passed through mw.messages.set
1254 implement: function ( module
, script
, style
, msgs
) {
1256 if ( typeof module
!== 'string' ) {
1257 throw new Error( 'module must be a string, not a ' + typeof module
);
1259 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1260 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1262 if ( !$.isPlainObject( style
) ) {
1263 throw new Error( 'style must be an object, not a ' + typeof style
);
1265 if ( !$.isPlainObject( msgs
) ) {
1266 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1268 // Automatically register module
1269 if ( registry
[module
] === undefined ) {
1270 mw
.loader
.register( module
);
1272 // Check for duplicate implementation
1273 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1274 throw new Error( 'module already implemented: ' + module
);
1276 // Attach components
1277 registry
[module
].script
= script
;
1278 registry
[module
].style
= style
;
1279 registry
[module
].messages
= msgs
;
1280 // The module may already have been marked as erroneous
1281 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1282 registry
[module
].state
= 'loaded';
1283 if ( allReady( registry
[module
].dependencies
) ) {
1290 * Executes a function as soon as one or more required modules are ready
1292 * @param dependencies {String|Array} Module name or array of modules names the callback
1293 * dependends on to be ready before executing
1294 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1295 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1297 using: function ( dependencies
, ready
, error
) {
1298 var tod
= typeof dependencies
;
1300 if ( tod
!== 'object' && tod
!== 'string' ) {
1301 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1303 // Allow calling with a single dependency as a string
1304 if ( tod
=== 'string' ) {
1305 dependencies
= [ dependencies
];
1307 // Resolve entire dependency map
1308 dependencies
= resolve( dependencies
);
1309 if ( allReady( dependencies
) ) {
1310 // Run ready immediately
1311 if ( $.isFunction( ready
) ) {
1314 } else if ( filter( ['error', 'missing'], dependencies
).length
) {
1315 // Execute error immediately if any dependencies have errors
1316 if ( $.isFunction( error
) ) {
1317 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1321 // Not all dependencies are ready: queue up a request
1322 request( dependencies
, ready
, error
);
1327 * Loads an external script or one or more modules for future use
1329 * @param modules {mixed} Either the name of a module, array of modules,
1330 * or a URL of an external script or style
1331 * @param type {String} mime-type to use if calling with a URL of an
1332 * external script or style; acceptable values are "text/css" and
1333 * "text/javascript"; if no type is provided, text/javascript is assumed.
1334 * @param async {Boolean} (optional) If true, load modules asynchronously
1335 * even if document ready has not yet occurred. If false (default),
1336 * block before document ready and load async after. If not set, true will
1337 * be assumed if loading a URL, and false will be assumed otherwise.
1339 load: function ( modules
, type
, async
) {
1340 var filtered
, m
, module
, l
;
1343 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1344 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1346 // Allow calling with an external url or single dependency as a string
1347 if ( typeof modules
=== 'string' ) {
1348 // Support adding arbitrary external scripts
1349 if ( /^(https?:)?\/\//.test( modules
) ) {
1350 if ( async
=== undefined ) {
1351 // Assume async for bug 34542
1354 if ( type
=== 'text/css' ) {
1355 // IE7-8 throws security warnings when inserting a <link> tag
1356 // with a protocol-relative URL set though attributes (instead of
1357 // properties) - when on HTTPS. See also bug #.
1358 l
= document
.createElement( 'link' );
1359 l
.rel
= 'stylesheet';
1361 $( 'head' ).append( l
);
1364 if ( type
=== 'text/javascript' || type
=== undefined ) {
1365 addScript( modules
, null, async
);
1369 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1371 // Called with single module
1372 modules
= [ modules
];
1375 // Filter out undefined modules, otherwise resolve() will throw
1376 // an exception for trying to load an undefined module.
1377 // Undefined modules are acceptable here in load(), because load() takes
1378 // an array of unrelated modules, whereas the modules passed to
1379 // using() are related and must all be loaded.
1380 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1381 module
= registry
[modules
[m
]];
1382 if ( module
!== undefined ) {
1383 if ( $.inArray( module
.state
, ['error', 'missing'] ) === -1 ) {
1384 filtered
[filtered
.length
] = modules
[m
];
1389 if ( filtered
.length
=== 0 ) {
1392 // Resolve entire dependency map
1393 filtered
= resolve( filtered
);
1394 // If all modules are ready, nothing to be done
1395 if ( allReady( filtered
) ) {
1398 // If any modules have errors: also quit.
1399 if ( filter( ['error', 'missing'], filtered
).length
) {
1402 // Since some modules are not yet ready, queue up a request.
1403 request( filtered
, null, null, async
);
1407 * Changes the state of a module
1409 * @param module {String|Object} module name or object of module name/state pairs
1410 * @param state {String} state name
1412 state: function ( module
, state
) {
1415 if ( typeof module
=== 'object' ) {
1416 for ( m
in module
) {
1417 mw
.loader
.state( m
, module
[m
] );
1421 if ( registry
[module
] === undefined ) {
1422 mw
.loader
.register( module
);
1424 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1425 && registry
[module
].state
!== state
) {
1426 // Make sure pending modules depending on this one get executed if their
1427 // dependencies are now fulfilled!
1428 registry
[module
].state
= state
;
1429 handlePending( module
);
1431 registry
[module
].state
= state
;
1436 * Gets the version of a module
1438 * @param module string name of module to get version for
1440 getVersion: function ( module
) {
1441 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1442 return formatVersionNumber( registry
[module
].version
);
1448 * @deprecated since 1.18 use mw.loader.getVersion() instead
1450 version: function () {
1451 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1455 * Gets the state of a module
1457 * @param module string name of module to get state for
1459 getState: function ( module
) {
1460 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1461 return registry
[module
].state
;
1467 * Get names of all registered modules.
1471 getModuleNames: function () {
1472 return $.map( registry
, function ( i
, key
) {
1478 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1481 mw
.loader
.load( 'mediawiki.user' );
1486 /** HTML construction helper functions */
1487 html
: ( function () {
1488 function escapeCallback( s
) {
1505 * Escape a string for HTML. Converts special characters to HTML entities.
1506 * @param s The string to escape
1508 escape: function ( s
) {
1509 return s
.replace( /['"<>&]/g, escapeCallback
);
1513 * Wrapper object for raw HTML passed to mw.html.element().
1516 Raw: function ( value
) {
1521 * Wrapper object for CDATA element contents passed to mw.html.element()
1524 Cdata: function ( value
) {
1529 * Create an HTML element string, with safe escaping.
1531 * @param name The tag name.
1532 * @param attrs An object with members mapping element names to values
1533 * @param contents The contents of the element. May be either:
1534 * - string: The string is escaped.
1535 * - null or undefined: The short closing form is used, e.g. <br/>.
1536 * - this.Raw: The value attribute is included without escaping.
1537 * - this.Cdata: The value attribute is included, and an exception is
1538 * thrown if it contains an illegal ETAGO delimiter.
1539 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1543 * return h.element( 'div', {},
1544 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1545 * Returns <div><img src="<"/></div>
1547 element: function ( name
, attrs
, contents
) {
1548 var v
, attrName
, s
= '<' + name
;
1550 for ( attrName
in attrs
) {
1551 v
= attrs
[attrName
];
1552 // Convert name=true, to name=name
1556 } else if ( v
=== false ) {
1559 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
1561 if ( contents
=== undefined || contents
=== null ) {
1568 switch ( typeof contents
) {
1571 s
+= this.escape( contents
);
1575 // Convert to string
1576 s
+= String( contents
);
1579 if ( contents
instanceof this.Raw
) {
1580 // Raw HTML inclusion
1581 s
+= contents
.value
;
1582 } else if ( contents
instanceof this.Cdata
) {
1584 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1585 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1587 s
+= contents
.value
;
1589 throw new Error( 'mw.html.element: Invalid type of contents' );
1592 s
+= '</' + name
+ '>';
1598 // Skeleton user object. mediawiki.user.js extends this
1607 // Alias $j to jQuery for backwards compatibility
1610 // Attach to window and globally alias
1611 window
.mw
= window
.mediaWiki
= mw
;
1613 // Auto-register from pre-loaded startup scripts
1614 if ( jQuery
.isFunction( window
.startUp
) ) {
1616 window
.startUp
= undefined;