2ceb3eac7807d8cb6356e7890f978191b31ae1ef
2 * Core MediaWiki JavaScript Library
5 var mw
= ( function ( $, undefined ) {
10 var hasOwn
= Object
.prototype.hasOwnProperty
,
11 slice
= Array
.prototype.slice
;
13 /* 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.
21 * @param {boolean} global Whether to store the values in the global window
22 * object or a exclusively in the object property 'values'.
24 function Map( global
) {
25 this.values
= global
=== true ? window
: {};
31 * Get the value of one or multiple a keys.
33 * If called with no arguments, all values will be returned.
35 * @param selection mixed String key or array of keys to get values for.
36 * @param fallback mixed Value to use in case key(s) do not exist (optional).
37 * @return mixed If selection was a string returns the value or null,
38 * If selection was an array, returns an object of key/values (value is null if not found),
39 * If selection was not passed or invalid, will return the 'values' object member (be careful as
40 * objects are always passed by reference in JavaScript!).
41 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
43 get: function ( selection
, fallback
) {
45 // If we only do this in the `return` block, it'll fail for the
46 // call to get() from the mutli-selection block.
47 fallback
= arguments
.length
> 1 ? fallback
: null;
49 if ( $.isArray( selection
) ) {
50 selection
= slice
.call( selection
);
52 for ( i
= 0; i
< selection
.length
; i
++ ) {
53 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
58 if ( typeof selection
=== 'string' ) {
59 if ( !hasOwn
.call( this.values
, selection
) ) {
62 return this.values
[selection
];
65 if ( selection
=== undefined ) {
69 // invalid selection key
74 * Sets one or multiple key/value pairs.
76 * @param selection {mixed} String key or array of keys to set values for.
77 * @param value {mixed} Value to set (optional, only in use when key is a string)
78 * @return {Boolean} This returns true on success, false on failure.
80 set: function ( selection
, value
) {
83 if ( $.isPlainObject( selection
) ) {
84 for ( s
in selection
) {
85 this.values
[s
] = selection
[s
];
89 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
90 this.values
[selection
] = value
;
97 * Checks if one or multiple keys exist.
99 * @param selection {mixed} String key or array of keys to check
100 * @return {boolean} Existence of key(s)
102 exists: function ( selection
) {
105 if ( $.isArray( selection
) ) {
106 for ( s
= 0; s
< selection
.length
; s
++ ) {
107 if ( typeof selection
[s
] !== 'string' || !hasOwn
.call( this.values
, selection
[s
] ) ) {
113 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
118 * Object constructor for messages,
119 * similar to the Message class in MediaWiki PHP.
123 * @param {mw.Map} map Message storage
124 * @param {string} key
125 * @param {Array} [parameters]
127 function Message( map
, key
, parameters
) {
128 this.format
= 'text';
131 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
135 Message
.prototype = {
137 * Simple message parser, does $N replacement, HTML-escaping (only for
138 * 'escaped' format), and nothing else.
140 * This may be overridden to provide a more complex message parser.
142 * The primary override is in mediawiki.jqueryMsg.
144 * This function will not be called for nonexistent messages.
146 parser: function () {
147 var parameters
= this.parameters
;
148 return this.map
.get( this.key
).replace( /\$(\d+)/g, function ( str
, match
) {
149 var index
= parseInt( match
, 10 ) - 1;
150 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
155 * Appends (does not replace) parameters for replacement to the .parameters property.
157 * @param {Array} parameters
160 params: function ( parameters
) {
162 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
163 this.parameters
.push( parameters
[i
] );
169 * Converts message object to it's string form based on the state of format.
171 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
173 toString: function () {
176 if ( !this.exists() ) {
177 // Use <key> as text if key does not exist
178 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
179 // format 'escaped' and 'parse' need to have the brackets and key html escaped
180 return mw
.html
.escape( '<' + this.key
+ '>' );
182 return '<' + this.key
+ '>';
185 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
186 text
= this.parser();
189 if ( this.format
=== 'escaped' ) {
190 text
= this.parser();
191 text
= mw
.html
.escape( text
);
198 * Changes format to 'parse' and converts message to string
200 * If jqueryMsg is loaded, this parses the message text from wikitext
201 * (where supported) to HTML
203 * Otherwise, it is equivalent to plain.
205 * @return {string} String form of parsed message
208 this.format
= 'parse';
209 return this.toString();
213 * Changes format to 'plain' and converts message to string
215 * This substitutes parameters, but otherwise does not change the
218 * @return {string} String form of plain message
221 this.format
= 'plain';
222 return this.toString();
226 * Changes format to 'text' and converts message to string
228 * If jqueryMsg is loaded, {{-transformation is done where supported
229 * (such as {{plural:}}, {{gender:}}, {{int:}}).
231 * Otherwise, it is equivalent to plain.
234 this.format
= 'text';
235 return this.toString();
239 * Changes the format to 'escaped' and converts message to string
241 * This is equivalent to using the 'text' format (see text method), then
242 * HTML-escaping the output.
244 * @return {string} String form of html escaped message
246 escaped: function () {
247 this.format
= 'escaped';
248 return this.toString();
252 * Checks if message exists
257 exists: function () {
258 return this.map
.exists( this.key
);
264 * @alternateClassName mediaWiki
271 * Dummy function which in debug mode can be replaced with a function that
272 * emulates console.log in console-less environments.
274 log: function () { },
276 // Make the Map constructor publicly available.
279 // Make the Message constructor publicly available.
283 * List of configuration values
285 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
286 * If `$wgLegacyJavaScriptGlobals` is true, this Map will have its values
287 * in the global window object.
293 * Empty object that plugins can be installed in.
298 /* Extension points */
306 * Localization system
314 * Gets a message object, similar to wfMessage().
316 * @param {string} key Key of message to get
317 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
318 * @return {mw.Message}
320 message: function ( key
) {
321 // Variadic arguments
322 var parameters
= slice
.call( arguments
, 1 );
323 return new Message( mw
.messages
, key
, parameters
);
327 * Gets a message string, similar to wfMessage()
329 * @see mw.Message#toString
330 * @param {string} key Key of message to get
331 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
334 msg: function ( /* key, parameters... */ ) {
335 return mw
.message
.apply( mw
.message
, arguments
).toString();
339 * Client-side module loader which integrates with the MediaWiki ResourceLoader
343 loader
: ( function () {
345 /* Private Members */
348 * Mapping of registered modules
350 * The jquery module is pre-registered, because it must have already
351 * been provided for this object to have been built, and in debug mode
352 * jquery would have been provided through a unique loader request,
353 * making it impossible to hold back registration of jquery until after
356 * For exact details on support for script, style and messages, look at
357 * mw.loader.implement.
362 * 'version': ############## (unix timestamp),
363 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
364 * 'group': 'somegroup', (or) null,
365 * 'source': 'local', 'someforeignwiki', (or) null
366 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
369 * 'messages': { 'key': 'value' },
378 // Mapping of sources, keyed by source-id, values are objects.
382 // 'loadScript': 'http://foo.bar/w/load.php'
387 // List of modules which will be loaded as when ready
389 // List of modules to be loaded
391 // List of callback functions waiting for modules to be ready to be called
393 // Selector cache for the marker element. Use getMarker() to get/use the marker!
395 // Buffer for addEmbeddedCSS.
398 /* Private methods */
400 function getMarker() {
406 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
407 if ( $marker
.length
) {
410 mw
.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
411 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
417 * Create a new style tag and add it to the DOM.
420 * @param {string} text CSS text
421 * @param {Mixed} [nextnode] An Element or jQuery object for an element where
422 * the style tag should be inserted before. Otherwise appended to the `<head>`.
423 * @return {HTMLElement} Node reference to the created `<style>` tag.
425 function addStyleTag( text
, nextnode
) {
426 var s
= document
.createElement( 'style' );
427 // Insert into document before setting cssText (bug 33305)
429 // Must be inserted with native insertBefore, not $.fn.before.
430 // When using jQuery to insert it, like $nextnode.before( s ),
431 // then IE6 will throw "Access is denied" when trying to append
432 // to .cssText later. Some kind of weird security measure.
433 // http://stackoverflow.com/q/12586482/319266
434 // Works: jsfiddle.net/zJzMy/1
435 // Fails: jsfiddle.net/uJTQz
436 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
437 if ( nextnode
.jquery
) {
438 nextnode
= nextnode
.get( 0 );
440 nextnode
.parentNode
.insertBefore( s
, nextnode
);
442 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
444 if ( s
.styleSheet
) {
446 s
.styleSheet
.cssText
= text
;
449 // (Safari sometimes borks on non-string values,
450 // play safe by casting to a string, just in case.)
451 s
.appendChild( document
.createTextNode( String( text
) ) );
457 * Checks whether it is safe to add this css to a stylesheet.
460 * @param {string} cssText
461 * @return {boolean} False if a new one must be created.
463 function canExpandStylesheetWith( cssText
) {
464 // Makes sure that cssText containing `@import`
465 // rules will end up in a new stylesheet (as those only work when
466 // placed at the start of a stylesheet; bug 35562).
467 return cssText
.indexOf( '@import' ) === -1;
471 * @param {string} [cssText=cssBuffer] If called without cssText,
472 * the internal buffer will be inserted instead.
474 function addEmbeddedCSS( cssText
) {
477 // Yield once before inserting the <style> tag. There are likely
478 // more calls coming up which we can combine this way.
479 // Appending a stylesheet and waiting for the browser to repaint
480 // is fairly expensive, this reduces it (bug 45810)
482 // Be careful not to extend the buffer with css that needs a new stylesheet
483 if ( !cssBuffer
|| canExpandStylesheetWith( cssText
) ) {
484 // Linebreak for somewhat distinguishable sections
485 // (the rl-cachekey comment separating each)
486 cssBuffer
+= '\n' + cssText
;
487 // TODO: Use requestAnimationFrame in the future which will
488 // perform even better by not injecting styles while the browser
490 setTimeout( addEmbeddedCSS
);
494 // This is a delayed call and we got a buffer still
495 } else if ( cssBuffer
) {
499 // This is a delayed call, but buffer is already cleared by
500 // another delayed call.
504 // By default, always create a new <style>. Appending text
505 // to a <style> tag means the contents have to be re-parsed (bug 45810).
506 // Except, of course, in IE below 9, in there we default to
507 // re-using and appending to a <style> tag due to the
508 // IE stylesheet limit (bug 31676).
509 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
511 $style
= getMarker().prev();
512 // Verify that the the element before Marker actually is a
513 // <style> tag and one that came from ResourceLoader
514 // (not some other style tag or even a `<meta>` or `<script>`).
515 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
516 // There's already a dynamic <style> tag present and
517 // canExpandStylesheetWith() gave a green light to append more to it.
518 styleEl
= $style
.get( 0 );
519 if ( styleEl
.styleSheet
) {
521 styleEl
.styleSheet
.cssText
+= cssText
; // IE
523 log( 'addEmbeddedCSS fail\ne.message: ' + e
.message
, e
);
526 styleEl
.appendChild( document
.createTextNode( String( cssText
) ) );
532 $( addStyleTag( cssText
, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
536 * Generates an ISO8601 "basic" string from a UNIX timestamp
539 function formatVersionNumber( timestamp
) {
541 function pad( a
, b
, c
) {
542 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
544 d
.setTime( timestamp
* 1000 );
546 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
547 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
552 * Resolves dependencies and detects circular references.
555 * @param {string} module Name of the top-level module whose dependencies shall be
556 * resolved and sorted.
557 * @param {Array} resolved Returns a topological sort of the given module and its
558 * dependencies, such that later modules depend on earlier modules. The array
559 * contains the module names. If the array contains already some module names,
560 * this function appends its result to the pre-existing array.
561 * @param {Object} [unresolved] Hash used to track the current dependency
562 * chain; used to report loops in the dependency graph.
563 * @throws {Error} If any unregistered module or a dependency loop is encountered
565 function sortDependencies( module
, resolved
, unresolved
) {
568 if ( registry
[module
] === undefined ) {
569 throw new Error( 'Unknown dependency: ' + module
);
571 // Resolves dynamic loader function and replaces it with its own results
572 if ( $.isFunction( registry
[module
].dependencies
) ) {
573 registry
[module
].dependencies
= registry
[module
].dependencies();
574 // Ensures the module's dependencies are always in an array
575 if ( typeof registry
[module
].dependencies
!== 'object' ) {
576 registry
[module
].dependencies
= [registry
[module
].dependencies
];
579 if ( $.inArray( module
, resolved
) !== -1 ) {
580 // Module already resolved; nothing to do.
583 // unresolved is optional, supply it if not passed in
587 // Tracks down dependencies
588 deps
= registry
[module
].dependencies
;
590 for ( n
= 0; n
< len
; n
+= 1 ) {
591 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
592 if ( unresolved
[deps
[n
]] ) {
594 'Circular reference detected: ' + module
+
600 unresolved
[module
] = true;
601 sortDependencies( deps
[n
], resolved
, unresolved
);
602 delete unresolved
[module
];
605 resolved
[resolved
.length
] = module
;
609 * Gets a list of module names that a module depends on in their proper dependency
613 * @param {string} module Module name or array of string module names
614 * @return {Array} list of dependencies, including 'module'.
615 * @throws {Error} If circular reference is detected
617 function resolve( module
) {
620 // Allow calling with an array of module names
621 if ( $.isArray( module
) ) {
623 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
624 sortDependencies( module
[m
], resolved
);
629 if ( typeof module
=== 'string' ) {
631 sortDependencies( module
, resolved
);
635 throw new Error( 'Invalid module argument: ' + module
);
639 * Narrows a list of module names down to those matching a specific
640 * state (see comment on top of this scope for a list of valid states).
641 * One can also filter for 'unregistered', which will return the
642 * modules names that don't have a registry entry.
645 * @param {string|string[]} states Module states to filter by
646 * @param {Array} modules List of module names to filter (optional, by default the entire
648 * @return {Array} List of filtered module names
650 function filter( states
, modules
) {
651 var list
, module
, s
, m
;
653 // Allow states to be given as a string
654 if ( typeof states
=== 'string' ) {
657 // If called without a list of modules, build and use a list of all modules
659 if ( modules
=== undefined ) {
661 for ( module
in registry
) {
662 modules
[modules
.length
] = module
;
665 // Build a list of modules which are in one of the specified states
666 for ( s
= 0; s
< states
.length
; s
+= 1 ) {
667 for ( m
= 0; m
< modules
.length
; m
+= 1 ) {
668 if ( registry
[modules
[m
]] === undefined ) {
669 // Module does not exist
670 if ( states
[s
] === 'unregistered' ) {
672 list
[list
.length
] = modules
[m
];
675 // Module exists, check state
676 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
678 list
[list
.length
] = modules
[m
];
687 * Determine whether all dependencies are in state 'ready', which means we may
688 * execute the module or job now.
691 * @param {Array} dependencies Dependencies (module names) to be checked.
692 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
694 function allReady( dependencies
) {
695 return filter( 'ready', dependencies
).length
=== dependencies
.length
;
699 * Log a message to window.console, if possible. Useful to force logging of some
700 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
701 * Gets console references in each invocation, so that delayed debugging tools work
702 * fine. No need for optimization here, which would only result in losing logs.
705 * @param {string} msg text for the log entry.
708 function log( msg
, e
) {
709 var console
= window
.console
;
710 if ( console
&& console
.log
) {
712 // If we have an exception object, log it through .error() to trigger
713 // proper stacktraces in browsers that support it. There are no (known)
714 // browsers that don't support .error(), that do support .log() and
715 // have useful exception handling through .log().
716 if ( e
&& console
.error
) {
723 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
724 * and modules that depend upon this module. if the given module failed, propagate the 'error'
725 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
726 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
729 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
731 function handlePending( module
) {
732 var j
, job
, hasErrors
, m
, stateChange
;
735 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) !== -1 ) {
736 // If the current module failed, mark all dependent modules also as failed.
737 // Iterate until steady-state to propagate the error state upwards in the
741 for ( m
in registry
) {
742 if ( $.inArray( registry
[m
].state
, ['error', 'missing'] ) === -1 ) {
743 if ( filter( ['error', 'missing'], registry
[m
].dependencies
).length
> 0 ) {
744 registry
[m
].state
= 'error';
749 } while ( stateChange
);
752 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
753 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
754 hasErrors
= filter( ['error', 'missing'], jobs
[j
].dependencies
).length
> 0;
755 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
756 // All dependencies satisfied, or some have errors
762 throw new Error( 'Module ' + module
+ ' failed.');
764 if ( $.isFunction( job
.ready
) ) {
769 if ( $.isFunction( job
.error
) ) {
771 job
.error( e
, [module
] );
773 // A user-defined operation raised an exception. Swallow to protect
774 // our state machine!
775 log( 'Exception thrown by job.error()', ex
);
782 if ( registry
[module
].state
=== 'ready' ) {
783 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
784 // and now have all dependencies satisfied.
785 for ( m
in registry
) {
786 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
794 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
795 * depending on whether document-ready has occurred yet and whether we are in async mode.
798 * @param {string} src URL to script, will be used as the src attribute in the script tag
799 * @param {Function} [callback] Callback which will be run when the script is done
801 function addScript( src
, callback
, async
) {
802 /*jshint evil:true */
806 // Using isReady directly instead of storing it locally from
807 // a $.fn.ready callback (bug 31895).
808 if ( $.isReady
|| async
) {
809 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
810 // it uses XHR and eval for same-domain scripts, which we don't want because it
811 // messes up line numbers.
812 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
814 // IE-safe way of getting the <head>. document.head isn't supported
815 // in old IE, and doesn't work when in the <head>.
816 head
= document
.getElementsByTagName( 'head' )[0] || document
.body
;
818 script
= document
.createElement( 'script' );
821 if ( $.isFunction( callback
) ) {
822 script
.onload
= script
.onreadystatechange = function () {
827 || /loaded|complete/.test( script
.readyState
)
832 // Handle memory leak in IE
833 script
.onload
= script
.onreadystatechange
= null;
836 if ( script
.parentNode
) {
837 script
.parentNode
.removeChild( script
);
840 // Dereference the script
848 if ( window
.opera
) {
849 // Appending to the <head> blocks rendering completely in Opera,
850 // so append to the <body> after document ready. This means the
851 // scripts only start loading after the document has been rendered,
852 // but so be it. Opera users don't deserve faster web pages if their
853 // browser makes it impossible.
855 document
.body
.appendChild( script
);
858 head
.appendChild( script
);
861 document
.write( mw
.html
.element( 'script', { 'src': src
}, '' ) );
862 if ( $.isFunction( callback
) ) {
863 // Document.write is synchronous, so this is called when it's done
864 // FIXME: that's a lie. doc.write isn't actually synchronous
871 * Executes a loaded module, making it ready to use
874 * @param {string} module Module name to execute
876 function execute( module
) {
877 var key
, value
, media
, i
, urls
, script
, markModuleReady
, nestedAddScript
;
879 if ( registry
[module
] === undefined ) {
880 throw new Error( 'Module has not been registered yet: ' + module
);
881 } else if ( registry
[module
].state
=== 'registered' ) {
882 throw new Error( 'Module has not been requested from the server yet: ' + module
);
883 } else if ( registry
[module
].state
=== 'loading' ) {
884 throw new Error( 'Module has not completed loading yet: ' + module
);
885 } else if ( registry
[module
].state
=== 'ready' ) {
886 throw new Error( 'Module has already been loaded: ' + module
);
890 * Define loop-function here for efficiency
891 * and to avoid re-using badly scoped variables.
894 function addLink( media
, url
) {
895 var el
= document
.createElement( 'link' );
896 getMarker().before( el
); // IE: Insert in dom before setting href
897 el
.rel
= 'stylesheet';
898 if ( media
&& media
!== 'all' ) {
904 // Process styles (see also mw.loader.implement)
905 // * back-compat: { <media>: css }
906 // * back-compat: { <media>: [url, ..] }
907 // * { "css": [css, ..] }
908 // * { "url": { <media>: [url, ..] } }
909 if ( $.isPlainObject( registry
[module
].style
) ) {
910 for ( key
in registry
[module
].style
) {
911 value
= registry
[module
].style
[key
];
914 if ( key
!== 'url' && key
!== 'css' ) {
915 // Backwards compatibility, key is a media-type
916 if ( typeof value
=== 'string' ) {
917 // back-compat: { <media>: css }
918 // Ignore 'media' because it isn't supported (nor was it used).
919 // Strings are pre-wrapped in "@media". The media-type was just ""
920 // (because it had to be set to something).
921 // This is one of the reasons why this format is no longer used.
922 addEmbeddedCSS( value
);
924 // back-compat: { <media>: [url, ..] }
930 // Array of css strings in key 'css',
931 // or back-compat array of urls from media-type
932 if ( $.isArray( value
) ) {
933 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
934 if ( key
=== 'bc-url' ) {
935 // back-compat: { <media>: [url, ..] }
936 addLink( media
, value
[i
] );
937 } else if ( key
=== 'css' ) {
938 // { "css": [css, ..] }
939 addEmbeddedCSS( value
[i
] );
942 // Not an array, but a regular object
943 // Array of urls inside media-type key
944 } else if ( typeof value
=== 'object' ) {
945 // { "url": { <media>: [url, ..] } }
946 for ( media
in value
) {
948 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
949 addLink( media
, urls
[i
] );
956 // Add localizations to message system
957 if ( $.isPlainObject( registry
[module
].messages
) ) {
958 mw
.messages
.set( registry
[module
].messages
);
963 script
= registry
[module
].script
;
964 markModuleReady = function () {
965 registry
[module
].state
= 'ready';
966 handlePending( module
);
968 nestedAddScript = function ( arr
, callback
, async
, i
) {
969 // Recursively call addScript() in its own callback
970 // for each element of arr.
971 if ( i
>= arr
.length
) {
972 // We're at the end of the array
977 addScript( arr
[i
], function () {
978 nestedAddScript( arr
, callback
, async
, i
+ 1 );
982 if ( $.isArray( script
) ) {
983 registry
[module
].state
= 'loading';
984 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
985 } else if ( $.isFunction( script
) ) {
986 registry
[module
].state
= 'ready';
988 handlePending( module
);
991 // This needs to NOT use mw.log because these errors are common in production mode
992 // and not in debug mode, such as when a symbol that should be global isn't exported
993 log( 'Exception thrown by ' + module
+ ': ' + e
.message
, e
);
994 registry
[module
].state
= 'error';
995 handlePending( module
);
1000 * Adds a dependencies to the queue with optional callbacks to be run
1001 * when the dependencies are ready or fail
1004 * @param {string|string[]} dependencies Module name or array of string module names
1005 * @param {Function} [ready] Callback to execute when all dependencies are ready
1006 * @param {Function} [error] Callback to execute when any dependency fails
1007 * @param {boolean} [async] If true, load modules asynchronously even if
1008 * document ready has not yet occurred.
1010 function request( dependencies
, ready
, error
, async
) {
1013 // Allow calling by single module name
1014 if ( typeof dependencies
=== 'string' ) {
1015 dependencies
= [dependencies
];
1018 // Add ready and error callbacks if they were given
1019 if ( ready
!== undefined || error
!== undefined ) {
1020 jobs
[jobs
.length
] = {
1021 'dependencies': filter(
1022 ['registered', 'loading', 'loaded'],
1030 // Queue up any dependencies that are registered
1031 dependencies
= filter( ['registered'], dependencies
);
1032 for ( n
= 0; n
< dependencies
.length
; n
+= 1 ) {
1033 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
1034 queue
[queue
.length
] = dependencies
[n
];
1036 // Mark this module as async in the registry
1037 registry
[dependencies
[n
]].async
= true;
1046 function sortQuery(o
) {
1047 var sorted
= {}, key
, a
= [];
1049 if ( hasOwn
.call( o
, key
) ) {
1054 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1055 sorted
[a
[key
]] = o
[a
[key
]];
1061 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1062 * to a query string of the form foo.bar,baz|bar.baz,quux
1065 function buildModulesString( moduleMap
) {
1066 var arr
= [], p
, prefix
;
1067 for ( prefix
in moduleMap
) {
1068 p
= prefix
=== '' ? '' : prefix
+ '.';
1069 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
1071 return arr
.join( '|' );
1075 * Asynchronously append a script tag to the end of the body
1076 * that invokes load.php
1078 * @param {Object} moduleMap Module map, see #buildModulesString
1079 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1080 * @param {string} sourceLoadScript URL of load.php
1081 * @param {boolean} async If true, use an asynchrounous request even if document ready has not yet occurred
1083 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
1084 var request
= $.extend(
1085 { modules
: buildModulesString( moduleMap
) },
1088 request
= sortQuery( request
);
1089 // Asynchronously append a script tag to the end of the body
1090 // Append &* to avoid triggering the IE6 extension check
1091 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
1094 /* Public Methods */
1096 addStyleTag
: addStyleTag
,
1099 * Requests dependencies from server, loading and executing when things when ready.
1102 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1103 source
, group
, g
, i
, modules
, maxVersion
, sourceLoadScript
,
1104 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1105 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
1107 // Build a list of request parameters common to all requests.
1109 skin
: mw
.config
.get( 'skin' ),
1110 lang
: mw
.config
.get( 'wgUserLanguage' ),
1111 debug
: mw
.config
.get( 'debug' )
1113 // Split module batch by source and by group.
1115 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', -1 );
1117 // Appends a list of modules from the queue to the batch
1118 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1119 // Only request modules which are registered
1120 if ( registry
[queue
[q
]] !== undefined && registry
[queue
[q
]].state
=== 'registered' ) {
1121 // Prevent duplicate entries
1122 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1123 batch
[batch
.length
] = queue
[q
];
1124 // Mark registered modules as loading
1125 registry
[queue
[q
]].state
= 'loading';
1129 // Early exit if there's nothing to load...
1130 if ( !batch
.length
) {
1134 // The queue has been processed into the batch, clear up the queue.
1137 // Always order modules alphabetically to help reduce cache
1138 // misses for otherwise identical content.
1141 // Split batch by source and by group.
1142 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1143 bSource
= registry
[batch
[b
]].source
;
1144 bGroup
= registry
[batch
[b
]].group
;
1145 if ( splits
[bSource
] === undefined ) {
1146 splits
[bSource
] = {};
1148 if ( splits
[bSource
][bGroup
] === undefined ) {
1149 splits
[bSource
][bGroup
] = [];
1151 bSourceGroup
= splits
[bSource
][bGroup
];
1152 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1155 // Clear the batch - this MUST happen before we append any
1156 // script elements to the body or it's possible that a script
1157 // will be locally cached, instantly load, and work the batch
1158 // again, all before we've cleared it causing each request to
1159 // include modules which are already loaded.
1162 for ( source
in splits
) {
1164 sourceLoadScript
= sources
[source
].loadScript
;
1166 for ( group
in splits
[source
] ) {
1168 // Cache access to currently selected list of
1169 // modules for this group from this source.
1170 modules
= splits
[source
][group
];
1172 // Calculate the highest timestamp
1174 for ( g
= 0; g
< modules
.length
; g
+= 1 ) {
1175 if ( registry
[modules
[g
]].version
> maxVersion
) {
1176 maxVersion
= registry
[modules
[g
]].version
;
1180 currReqBase
= $.extend( { version
: formatVersionNumber( maxVersion
) }, reqBase
);
1181 // For user modules append a user name to the request.
1182 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1183 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1185 currReqBaseLength
= $.param( currReqBase
).length
;
1187 // We may need to split up the request to honor the query string length limit,
1188 // so build it piece by piece.
1189 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1191 moduleMap
= {}; // { prefix: [ suffixes ] }
1193 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1194 // Determine how many bytes this module would add to the query string
1195 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1196 // Note that these substr() calls work even if lastDotIndex == -1
1197 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1198 suffix
= modules
[i
].substr( lastDotIndex
+ 1 );
1199 bytesAdded
= moduleMap
[prefix
] !== undefined
1200 ? suffix
.length
+ 3 // '%2C'.length == 3
1201 : modules
[i
].length
+ 3; // '%7C'.length == 3
1203 // If the request would become too long, create a new one,
1204 // but don't create empty requests
1205 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1206 // This request would become too long, create a new one
1207 // and fire off the old one
1208 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1211 l
= currReqBaseLength
+ 9;
1213 if ( moduleMap
[prefix
] === undefined ) {
1214 moduleMap
[prefix
] = [];
1216 moduleMap
[prefix
].push( suffix
);
1217 if ( !registry
[modules
[i
]].async
) {
1218 // If this module is blocking, make the entire request blocking
1219 // This is slightly suboptimal, but in practice mixing of blocking
1220 // and async modules will only occur in debug mode.
1225 // If there's anything left in moduleMap, request that too
1226 if ( !$.isEmptyObject( moduleMap
) ) {
1227 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1234 * Register a source.
1236 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1237 * @param {Object} props Object containing only the loadScript property which is a url to
1238 * the load.php location of the source.
1241 addSource: function ( id
, props
) {
1243 // Allow multiple additions
1244 if ( typeof id
=== 'object' ) {
1245 for ( source
in id
) {
1246 mw
.loader
.addSource( source
, id
[source
] );
1251 if ( sources
[id
] !== undefined ) {
1252 throw new Error( 'source already registered: ' + id
);
1255 sources
[id
] = props
;
1261 * Registers a module, letting the system know about it and its
1262 * properties. Startup modules contain calls to this function.
1264 * @param module {String}: Module name
1265 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1266 * @param dependencies {String|Array|Function}: One string or array of strings of module
1267 * names on which this module depends, or a function that returns that array.
1268 * @param group {String}: Group which the module is in (optional, defaults to null)
1269 * @param source {String}: Name of the source. Defaults to local.
1271 register: function ( module
, version
, dependencies
, group
, source
) {
1273 // Allow multiple registration
1274 if ( typeof module
=== 'object' ) {
1275 for ( m
= 0; m
< module
.length
; m
+= 1 ) {
1276 // module is an array of module names
1277 if ( typeof module
[m
] === 'string' ) {
1278 mw
.loader
.register( module
[m
] );
1279 // module is an array of arrays
1280 } else if ( typeof module
[m
] === 'object' ) {
1281 mw
.loader
.register
.apply( mw
.loader
, module
[m
] );
1287 if ( typeof module
!== 'string' ) {
1288 throw new Error( 'module must be a string, not a ' + typeof module
);
1290 if ( registry
[module
] !== undefined ) {
1291 throw new Error( 'module already registered: ' + module
);
1293 // List the module as registered
1294 registry
[module
] = {
1295 version
: version
!== undefined ? parseInt( version
, 10 ) : 0,
1297 group
: typeof group
=== 'string' ? group
: null,
1298 source
: typeof source
=== 'string' ? source
: 'local',
1301 if ( typeof dependencies
=== 'string' ) {
1302 // Allow dependencies to be given as a single module name
1303 registry
[module
].dependencies
= [ dependencies
];
1304 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1305 // Allow dependencies to be given as an array of module names
1306 // or a function which returns an array
1307 registry
[module
].dependencies
= dependencies
;
1312 * Implements a module, giving the system a course of action to take
1313 * upon loading. Results of a request for one or more modules contain
1314 * calls to this function.
1316 * All arguments are required.
1318 * @param {string} module Name of module
1319 * @param {Function|Array} script Function with module code or Array of URLs to
1320 * be used as the src attribute of a new `<script>` tag.
1321 * @param {Object} style Should follow one of the following patterns:
1322 * { "css": [css, ..] }
1323 * { "url": { <media>: [url, ..] } }
1324 * And for backwards compatibility (needs to be supported forever due to caching):
1326 * { <media>: [url, ..] }
1328 * The reason css strings are not concatenated anymore is bug 31676. We now check
1329 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1331 * @param {Object} msgs List of key/value pairs to be added to {@link mw#messages}.
1333 implement: function ( module
, script
, style
, msgs
) {
1335 if ( typeof module
!== 'string' ) {
1336 throw new Error( 'module must be a string, not a ' + typeof module
);
1338 if ( !$.isFunction( script
) && !$.isArray( script
) ) {
1339 throw new Error( 'script must be a function or an array, not a ' + typeof script
);
1341 if ( !$.isPlainObject( style
) ) {
1342 throw new Error( 'style must be an object, not a ' + typeof style
);
1344 if ( !$.isPlainObject( msgs
) ) {
1345 throw new Error( 'msgs must be an object, not a ' + typeof msgs
);
1347 // Automatically register module
1348 if ( registry
[module
] === undefined ) {
1349 mw
.loader
.register( module
);
1351 // Check for duplicate implementation
1352 if ( registry
[module
] !== undefined && registry
[module
].script
!== undefined ) {
1353 throw new Error( 'module already implemented: ' + module
);
1355 // Attach components
1356 registry
[module
].script
= script
;
1357 registry
[module
].style
= style
;
1358 registry
[module
].messages
= msgs
;
1359 // The module may already have been marked as erroneous
1360 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1361 registry
[module
].state
= 'loaded';
1362 if ( allReady( registry
[module
].dependencies
) ) {
1369 * Executes a function as soon as one or more required modules are ready
1371 * @param dependencies {String|Array} Module name or array of modules names the callback
1372 * dependends on to be ready before executing
1373 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1374 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1376 using: function ( dependencies
, ready
, error
) {
1377 var tod
= typeof dependencies
;
1379 if ( tod
!== 'object' && tod
!== 'string' ) {
1380 throw new Error( 'dependencies must be a string or an array, not a ' + tod
);
1382 // Allow calling with a single dependency as a string
1383 if ( tod
=== 'string' ) {
1384 dependencies
= [ dependencies
];
1386 // Resolve entire dependency map
1387 dependencies
= resolve( dependencies
);
1388 if ( allReady( dependencies
) ) {
1389 // Run ready immediately
1390 if ( $.isFunction( ready
) ) {
1393 } else if ( filter( ['error', 'missing'], dependencies
).length
) {
1394 // Execute error immediately if any dependencies have errors
1395 if ( $.isFunction( error
) ) {
1396 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1400 // Not all dependencies are ready: queue up a request
1401 request( dependencies
, ready
, error
);
1406 * Loads an external script or one or more modules for future use
1408 * @param modules {mixed} Either the name of a module, array of modules,
1409 * or a URL of an external script or style
1410 * @param type {String} mime-type to use if calling with a URL of an
1411 * external script or style; acceptable values are "text/css" and
1412 * "text/javascript"; if no type is provided, text/javascript is assumed.
1413 * @param async {Boolean} (optional) If true, load modules asynchronously
1414 * even if document ready has not yet occurred. If false (default),
1415 * block before document ready and load async after. If not set, true will
1416 * be assumed if loading a URL, and false will be assumed otherwise.
1418 load: function ( modules
, type
, async
) {
1419 var filtered
, m
, module
, l
;
1422 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1423 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1425 // Allow calling with an external url or single dependency as a string
1426 if ( typeof modules
=== 'string' ) {
1427 // Support adding arbitrary external scripts
1428 if ( /^(https?:)?\/\//.test( modules
) ) {
1429 if ( async
=== undefined ) {
1430 // Assume async for bug 34542
1433 if ( type
=== 'text/css' ) {
1434 // IE7-8 throws security warnings when inserting a <link> tag
1435 // with a protocol-relative URL set though attributes (instead of
1436 // properties) - when on HTTPS. See also bug #.
1437 l
= document
.createElement( 'link' );
1438 l
.rel
= 'stylesheet';
1440 $( 'head' ).append( l
);
1443 if ( type
=== 'text/javascript' || type
=== undefined ) {
1444 addScript( modules
, null, async
);
1448 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1450 // Called with single module
1451 modules
= [ modules
];
1454 // Filter out undefined modules, otherwise resolve() will throw
1455 // an exception for trying to load an undefined module.
1456 // Undefined modules are acceptable here in load(), because load() takes
1457 // an array of unrelated modules, whereas the modules passed to
1458 // using() are related and must all be loaded.
1459 for ( filtered
= [], m
= 0; m
< modules
.length
; m
+= 1 ) {
1460 module
= registry
[modules
[m
]];
1461 if ( module
!== undefined ) {
1462 if ( $.inArray( module
.state
, ['error', 'missing'] ) === -1 ) {
1463 filtered
[filtered
.length
] = modules
[m
];
1468 if ( filtered
.length
=== 0 ) {
1471 // Resolve entire dependency map
1472 filtered
= resolve( filtered
);
1473 // If all modules are ready, nothing to be done
1474 if ( allReady( filtered
) ) {
1477 // If any modules have errors: also quit.
1478 if ( filter( ['error', 'missing'], filtered
).length
) {
1481 // Since some modules are not yet ready, queue up a request.
1482 request( filtered
, undefined, undefined, async
);
1486 * Changes the state of a module
1488 * @param module {String|Object} module name or object of module name/state pairs
1489 * @param state {String} state name
1491 state: function ( module
, state
) {
1494 if ( typeof module
=== 'object' ) {
1495 for ( m
in module
) {
1496 mw
.loader
.state( m
, module
[m
] );
1500 if ( registry
[module
] === undefined ) {
1501 mw
.loader
.register( module
);
1503 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1504 && registry
[module
].state
!== state
) {
1505 // Make sure pending modules depending on this one get executed if their
1506 // dependencies are now fulfilled!
1507 registry
[module
].state
= state
;
1508 handlePending( module
);
1510 registry
[module
].state
= state
;
1515 * Gets the version of a module
1517 * @param module string name of module to get version for
1519 getVersion: function ( module
) {
1520 if ( registry
[module
] !== undefined && registry
[module
].version
!== undefined ) {
1521 return formatVersionNumber( registry
[module
].version
);
1527 * @deprecated since 1.18 use mw.loader.getVersion() instead
1529 version: function () {
1530 return mw
.loader
.getVersion
.apply( mw
.loader
, arguments
);
1534 * Gets the state of a module
1536 * @param module string name of module to get state for
1538 getState: function ( module
) {
1539 if ( registry
[module
] !== undefined && registry
[module
].state
!== undefined ) {
1540 return registry
[module
].state
;
1546 * Get names of all registered modules.
1550 getModuleNames: function () {
1551 return $.map( registry
, function ( i
, key
) {
1557 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1560 mw
.loader
.load( 'mediawiki.user' );
1566 * HTML construction helper functions
1570 html
: ( function () {
1571 function escapeCallback( s
) {
1588 * Escape a string for HTML. Converts special characters to HTML entities.
1589 * @param {string} s The string to escape
1591 escape: function ( s
) {
1592 return s
.replace( /['"<>&]/g, escapeCallback
);
1596 * Wrapper object for raw HTML passed to mw.html.element().
1597 * @class mw.html.Raw
1599 Raw: function ( value
) {
1604 * Wrapper object for CDATA element contents passed to mw.html.element()
1605 * @class mw.html.Cdata
1607 Cdata: function ( value
) {
1612 * Create an HTML element string, with safe escaping.
1614 * @param name The tag name.
1615 * @param attrs An object with members mapping element names to values
1616 * @param contents The contents of the element. May be either:
1617 * - string: The string is escaped.
1618 * - null or undefined: The short closing form is used, e.g. <br/>.
1619 * - this.Raw: The value attribute is included without escaping.
1620 * - this.Cdata: The value attribute is included, and an exception is
1621 * thrown if it contains an illegal ETAGO delimiter.
1622 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1626 * return h.element( 'div', {},
1627 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1628 * Returns <div><img src="<"/></div>
1630 element: function ( name
, attrs
, contents
) {
1631 var v
, attrName
, s
= '<' + name
;
1633 for ( attrName
in attrs
) {
1634 v
= attrs
[attrName
];
1635 // Convert name=true, to name=name
1639 } else if ( v
=== false ) {
1642 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
1644 if ( contents
=== undefined || contents
=== null ) {
1651 switch ( typeof contents
) {
1654 s
+= this.escape( contents
);
1658 // Convert to string
1659 s
+= String( contents
);
1662 if ( contents
instanceof this.Raw
) {
1663 // Raw HTML inclusion
1664 s
+= contents
.value
;
1665 } else if ( contents
instanceof this.Cdata
) {
1667 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
1668 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1670 s
+= contents
.value
;
1672 throw new Error( 'mw.html.element: Invalid type of contents' );
1675 s
+= '</' + name
+ '>';
1681 // Skeleton user object. mediawiki.user.js extends this
1690 // Alias $j to jQuery for backwards compatibility
1693 // Attach to window and globally alias
1694 window
.mw
= window
.mediaWiki
= mw
;
1696 // Auto-register from pre-loaded startup scripts
1697 if ( jQuery
.isFunction( window
.startUp
) ) {
1699 window
.startUp
= undefined;