2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
10 /*jshint latedef:false */
16 hasOwn
= Object
.prototype.hasOwnProperty
,
17 slice
= Array
.prototype.slice
,
18 trackCallbacks
= $.Callbacks( 'memory' ),
23 * Create an object that can be read from or written to from methods that allow
24 * interaction both with single and multiple properties at once.
28 * var collection, query, results;
30 * // Create your address book
31 * collection = new mw.Map();
33 * // This data could be coming from an external source (eg. API/AJAX)
35 * 'John Doe': 'john@example.org',
36 * 'Jane Doe': 'jane@example.org',
37 * 'George van Halen': 'gvanhalen@example.org'
40 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
42 * // You can detect missing keys first
43 * if ( !collection.exists( wanted ) ) {
44 * // One or more are missing (in this case: "Daniel Jackson")
45 * mw.log( 'One or more names were not found in your address book' );
48 * // Or just let it give you what it can. Optionally fill in from a default.
49 * results = collection.get( wanted, 'nobody@example.com' );
50 * mw.log( results['Jane Doe'] ); // "jane@example.org"
51 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
56 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
58 * For backwards-compatibility with mw.config, this can also be `true` in which case values
59 * are copied to the Window object as global variables (T72470). Values are copied in
60 * one direction only. Changes to globals are not reflected in the map.
62 function Map( values
) {
63 if ( values
=== true ) {
66 // Override #set to also set the global variable
67 this.set = function ( selection
, value
) {
70 if ( $.isPlainObject( selection
) ) {
71 for ( s
in selection
) {
72 setGlobalMapValue( this, s
, selection
[s
] );
76 if ( typeof selection
=== 'string' && arguments
.length
) {
77 setGlobalMapValue( this, selection
, value
);
86 this.values
= values
|| {};
90 * Alias property to the global object.
96 * @param {Mixed} value
98 function setGlobalMapValue( map
, key
, value
) {
99 map
.values
[key
] = value
;
104 // Deprecation notice for mw.config globals (T58550, T72470)
105 map
=== mw
.config
&& 'Use mw.config instead.'
111 * Get the value of one or more keys.
113 * If called with no arguments, all values are returned.
115 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
116 * @param {Mixed} [fallback=null] Value for keys that don't exist.
117 * @return {Mixed|Object| null} If selection was a string, returns the value,
118 * If selection was an array, returns an object of key/values.
119 * If no selection is passed, the 'values' container is returned. (Beware that,
120 * as is the default in JavaScript, the object is returned by reference.)
122 get: function ( selection
, fallback
) {
124 // If we only do this in the `return` block, it'll fail for the
125 // call to get() from the mutli-selection block.
126 fallback
= arguments
.length
> 1 ? fallback
: null;
128 if ( $.isArray( selection
) ) {
129 selection
= slice
.call( selection
);
131 for ( i
= 0; i
< selection
.length
; i
++ ) {
132 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
137 if ( typeof selection
=== 'string' ) {
138 if ( !hasOwn
.call( this.values
, selection
) ) {
141 return this.values
[selection
];
144 if ( selection
=== undefined ) {
148 // Invalid selection key
153 * Set one or more key/value pairs.
155 * @param {string|Object} selection Key to set value for, or object mapping keys to values
156 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
157 * @return {boolean} True on success, false on failure
159 set: function ( selection
, value
) {
162 if ( $.isPlainObject( selection
) ) {
163 for ( s
in selection
) {
164 this.values
[s
] = selection
[s
];
168 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
169 this.values
[selection
] = value
;
176 * Check if one or more keys exist.
178 * @param {Mixed} selection Key or array of keys to check
179 * @return {boolean} True if the key(s) exist
181 exists: function ( selection
) {
184 if ( $.isArray( selection
) ) {
185 for ( s
= 0; s
< selection
.length
; s
++ ) {
186 if ( typeof selection
[s
] !== 'string' || !hasOwn
.call( this.values
, selection
[s
] ) ) {
192 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
197 * Object constructor for messages.
199 * Similar to the Message class in MediaWiki PHP.
201 * Format defaults to 'text'.
207 * 'hello': 'Hello world',
208 * 'hello-user': 'Hello, $1!',
209 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
212 * obj = new mw.Message( mw.messages, 'hello' );
213 * mw.log( obj.text() );
216 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
217 * mw.log( obj.text() );
218 * // Hello, John Doe!
220 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
221 * mw.log( obj.text() );
222 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
224 * // Using mw.message shortcut
225 * obj = mw.message( 'hello-user', 'John Doe' );
226 * mw.log( obj.text() );
227 * // Hello, John Doe!
229 * // Using mw.msg shortcut
230 * str = mw.msg( 'hello-user', 'John Doe' );
232 * // Hello, John Doe!
234 * // Different formats
235 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
237 * obj.format = 'text';
238 * str = obj.toString();
243 * // Hello, John "Wiki" <3 Doe!
245 * mw.log( obj.escaped() );
246 * // Hello, John "Wiki" <3 Doe!
251 * @param {mw.Map} map Message store
252 * @param {string} key
253 * @param {Array} [parameters]
255 function Message( map
, key
, parameters
) {
256 this.format
= 'text';
259 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
263 Message
.prototype = {
265 * Get parsed contents of the message.
267 * The default parser does simple $N replacements and nothing else.
268 * This may be overridden to provide a more complex message parser.
269 * The primary override is in the mediawiki.jqueryMsg module.
271 * This function will not be called for nonexistent messages.
273 * @return {string} Parsed message
275 parser: function () {
276 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
280 * Add (does not replace) parameters for `N$` placeholder values.
282 * @param {Array} parameters
285 params: function ( parameters
) {
287 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
288 this.parameters
.push( parameters
[i
] );
294 * Convert message object to its string form based on current format.
296 * @return {string} Message as a string in the current form, or `<key>` if key
299 toString: function () {
302 if ( !this.exists() ) {
303 // Use <key> as text if key does not exist
304 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
305 // format 'escaped' and 'parse' need to have the brackets and key html escaped
306 return mw
.html
.escape( '<' + this.key
+ '>' );
308 return '<' + this.key
+ '>';
311 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
312 text
= this.parser();
315 if ( this.format
=== 'escaped' ) {
316 text
= this.parser();
317 text
= mw
.html
.escape( text
);
324 * Change format to 'parse' and convert message to string
326 * If jqueryMsg is loaded, this parses the message text from wikitext
327 * (where supported) to HTML
329 * Otherwise, it is equivalent to plain.
331 * @return {string} String form of parsed message
334 this.format
= 'parse';
335 return this.toString();
339 * Change format to 'plain' and convert message to string
341 * This substitutes parameters, but otherwise does not change the
344 * @return {string} String form of plain message
347 this.format
= 'plain';
348 return this.toString();
352 * Change format to 'text' and convert message to string
354 * If jqueryMsg is loaded, {{-transformation is done where supported
355 * (such as {{plural:}}, {{gender:}}, {{int:}}).
357 * Otherwise, it is equivalent to plain
359 * @return {string} String form of text message
362 this.format
= 'text';
363 return this.toString();
367 * Change the format to 'escaped' and convert message to string
369 * This is equivalent to using the 'text' format (see #text), then
370 * HTML-escaping the output.
372 * @return {string} String form of html escaped message
374 escaped: function () {
375 this.format
= 'escaped';
376 return this.toString();
380 * Check if a message exists
385 exists: function () {
386 return this.map
.exists( this.key
);
396 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
398 * On browsers that implement the Navigation Timing API, this function will produce floating-point
399 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
400 * it will fall back to using `Date`.
402 * @return {number} Current time
405 var perf
= window
.performance
,
406 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
407 return navStart
&& typeof perf
.now
=== 'function' ?
408 function () { return navStart
+ perf
.now(); } :
409 function () { return +new Date(); };
413 * Format a string. Replace $1, $2 ... $N with positional arguments.
415 * Used by Message#parser().
418 * @param {string} fmt Format string
419 * @param {Mixed...} parameters Values for $N replacements
420 * @return {string} Formatted string
422 format: function ( formatString
) {
423 var parameters
= slice
.call( arguments
, 1 );
424 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
425 var index
= parseInt( match
, 10 ) - 1;
426 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
431 * Track an analytic event.
433 * This method provides a generic means for MediaWiki JavaScript code to capture state
434 * information for analysis. Each logged event specifies a string topic name that describes
435 * the kind of event that it is. Topic names consist of dot-separated path components,
436 * arranged from most general to most specific. Each path component should have a clear and
437 * well-defined purpose.
439 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
440 * events that match their subcription, including those that fired before the handler was
443 * @param {string} topic Topic name
444 * @param {Object} [data] Data describing the event, encoded as an object
446 track: function ( topic
, data
) {
447 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
448 trackCallbacks
.fire( trackQueue
);
452 * Register a handler for subset of analytic events, specified by topic.
454 * Handlers will be called once for each tracked event, including any events that fired before the
455 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
456 * the exact time at which the event fired, a string 'topic' property naming the event, and a
457 * 'data' property which is an object of event-specific data. The event topic and event data are
458 * also passed to the callback as the first and second arguments, respectively.
460 * @param {string} topic Handle events whose name starts with this string prefix
461 * @param {Function} callback Handler to call for each matching tracked event
462 * @param {string} callback.topic
463 * @param {Object} [callback.data]
465 trackSubscribe: function ( topic
, callback
) {
467 function handler( trackQueue
) {
469 for ( ; seen
< trackQueue
.length
; seen
++ ) {
470 event
= trackQueue
[ seen
];
471 if ( event
.topic
.indexOf( topic
) === 0 ) {
472 callback
.call( event
, event
.topic
, event
.data
);
477 trackHandlers
.push( [ handler
, callback
] );
479 trackCallbacks
.add( handler
);
483 * Stop handling events for a particular handler
485 * @param {Function} callback
487 trackUnsubscribe: function ( callback
) {
488 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
489 if ( fns
[1] === callback
) {
490 trackCallbacks
.remove( fns
[0] );
491 // Ensure the tuple is removed to avoid holding on to closures
498 // Expose Map constructor
501 // Expose Message constructor
505 * Map of configuration values.
507 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
510 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
511 * global `window` object.
513 * @property {mw.Map} config
515 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
519 * Empty object for third-party libraries, for cases where you don't
520 * want to add a new global, or the global is bad and needs containment
528 * Access container for deprecated functionality that can be moved from
529 * from their legacy location and attached to this object (e.g. a global
530 * function that is deprecated and as stop-gap can be exposed through here).
532 * This was reserved for future use but never ended up being used.
534 * @deprecated since 1.22 Let deprecated identifiers keep their original name
535 * and use mw.log#deprecate to create an access container for tracking.
541 * Store for messages.
548 * Store for templates associated with a module.
552 templates
: new Map(),
555 * Get a message object.
557 * Shorcut for `new mw.Message( mw.messages, key, parameters )`.
560 * @param {string} key Key of message to get
561 * @param {Mixed...} parameters Values for $N replacements
562 * @return {mw.Message}
564 message: function ( key
) {
565 var parameters
= slice
.call( arguments
, 1 );
566 return new Message( mw
.messages
, key
, parameters
);
570 * Get a message string using the (default) 'text' format.
572 * Shortcut for `mw.message( key, parameters... ).text()`.
575 * @param {string} key Key of message to get
576 * @param {Mixed...} parameters Values for $N replacements
580 return mw
.message
.apply( mw
.message
, arguments
).toString();
584 * Dummy placeholder for {@link mw.log}
588 // Also update the restoration of methods in mediawiki.log.js
589 // when adding or removing methods here.
590 var log = function () {};
598 * Write a message the console's warning channel.
599 * Actions not supported by the browser console are silently ignored.
601 * @param {string...} msg Messages to output to console
603 log
.warn = function () {
604 var console
= window
.console
;
605 if ( console
&& console
.warn
&& console
.warn
.apply
) {
606 console
.warn
.apply( console
, arguments
);
611 * Write a message the console's error channel.
613 * Most browsers provide a stacktrace by default if the argument
614 * is a caught Error object.
617 * @param {Error|string...} msg Messages to output to console
619 log
.error = function () {
620 var console
= window
.console
;
621 if ( console
&& console
.error
&& console
.error
.apply
) {
622 console
.error
.apply( console
, arguments
);
627 * Create a property in a host object that, when accessed, will produce
628 * a deprecation warning in the console with backtrace.
630 * @param {Object} obj Host object of deprecated property
631 * @param {string} key Name of property to create in `obj`
632 * @param {Mixed} val The value this property should return when accessed
633 * @param {string} [msg] Optional text to include in the deprecation message
635 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
637 } : function ( obj
, key
, val
, msg
) {
638 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
640 // Can throw on Object.defineProperty.
642 Object
.defineProperty( obj
, key
, {
646 mw
.track( 'mw.deprecate', key
);
650 set: function ( newVal
) {
651 mw
.track( 'mw.deprecate', key
);
657 // Fallback to creating a copy of the value to the object.
666 * Client for ResourceLoader server end point.
668 * This client is in charge of maintaining the module registry and state
669 * machine, initiating network (batch) requests for loading modules, as
670 * well as dependency resolution and execution of source code.
672 * For more information, refer to
673 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
678 loader
: ( function () {
681 * Fired via mw.track on various resource loading errors.
683 * @event resourceloader_exception
684 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
685 * object, but in theory module code could manually throw something else, and that
686 * might also end up here.
687 * @param {string} [module] Name of the module which caused the error. Omitted if the
688 * error is not module-related or the module cannot be easily identified due to
690 * @param {string} source Source of the error. Possible values:
692 * - style: stylesheet error (only affects old IE where a special style loading method
694 * - load-callback: exception thrown by user callback
695 * - module-execute: exception thrown by module code
696 * - store-eval: could not evaluate module code cached in localStorage
697 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
698 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
699 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
703 * Fired via mw.track on resource loading error conditions.
705 * @event resourceloader_assert
706 * @param {string} source Source of the error. Possible values:
708 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
709 * bug; see <https://phabricator.wikimedia.org/T59567> for details
713 * Mapping of registered modules.
715 * See #implement and #execute for exact details on support for script, style and messages.
721 * // From mw.loader.register() in startup module
722 * 'version': '########' (hash)
723 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
724 * 'group': 'somegroup', (or) null
725 * 'source': 'local', (or) 'anotherwiki'
726 * 'skip': 'return !!window.Example', (or) null
728 * // Set from execute() or mw.loader.state()
729 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
731 * // Optionally added at run-time by mw.loader.implement()
733 * 'script': closure, array of urls, or string
734 * 'style': { ... } (see #execute)
735 * 'messages': { 'key': 'value', ... }
743 // Mapping of sources, keyed by source-id, values are strings.
748 // 'sourceId': 'http://example.org/w/load.php'
753 // List of modules which will be loaded as when ready
756 // List of modules to be loaded
759 // List of callback functions waiting for modules to be ready to be called
762 // Selector cache for the marker element. Use getMarker() to get/use the marker!
765 // Buffer for #addEmbeddedCSS
768 // Callbacks for #addEmbeddedCSS
769 cssCallbacks
= $.Callbacks();
771 function getMarker() {
774 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
775 if ( !$marker
.length
) {
776 mw
.log( 'No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically' );
777 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
784 * Create a new style element and add it to the DOM.
787 * @param {string} text CSS text
788 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag
789 * should be inserted before
790 * @return {HTMLElement} Reference to the created style element
792 function newStyleTag( text
, nextnode
) {
793 var s
= document
.createElement( 'style' );
795 // Must attach to document before setting cssText (bug 33305)
797 $( nextnode
).before( s
);
799 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
801 if ( s
.styleSheet
) {
803 // Old IE ignores appended text nodes, access stylesheet directly.
804 s
.styleSheet
.cssText
= text
;
806 // Standard behaviour
807 s
.appendChild( document
.createTextNode( text
) );
813 * Add a bit of CSS text to the current browser page.
815 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
816 * or create a new one based on whether the given `cssText` is safe for extension.
818 * @param {string} [cssText=cssBuffer] If called without cssText,
819 * the internal buffer will be inserted instead.
820 * @param {Function} [callback]
822 function addEmbeddedCSS( cssText
, callback
) {
825 function fireCallbacks() {
826 var oldCallbacks
= cssCallbacks
;
827 // Reset cssCallbacks variable so it's not polluted by any calls to
828 // addEmbeddedCSS() from one of the callbacks (T105973)
829 cssCallbacks
= $.Callbacks();
830 oldCallbacks
.fire().empty();
834 cssCallbacks
.add( callback
);
837 // Yield once before inserting the <style> tag. There are likely
838 // more calls coming up which we can combine this way.
839 // Appending a stylesheet and waiting for the browser to repaint
840 // is fairly expensive, this reduces that (bug 45810)
842 // Be careful not to extend the buffer with css that needs a new stylesheet.
843 // cssText containing `@import` rules needs to go at the start of a buffer,
844 // since those only work when placed at the start of a stylesheet; bug 35562.
845 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
846 // Linebreak for somewhat distinguishable sections
847 // (the rl-cachekey comment separating each)
848 cssBuffer
+= '\n' + cssText
;
849 // TODO: Use requestAnimationFrame in the future which will
850 // perform even better by not injecting styles while the browser
852 setTimeout( function () {
853 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
854 // (below version 13) has the non-standard behaviour of passing a
855 // numerical "lateness" value as first argument to this callback
856 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
862 // This is a delayed call and we got a buffer still
863 } else if ( cssBuffer
) {
868 // This is a delayed call, but buffer was already cleared by
869 // another delayed call.
873 // By default, always create a new <style>. Appending text to a <style>
874 // tag is bad as it means the contents have to be re-parsed (bug 45810).
876 // Except, of course, in IE 9 and below. In there we default to re-using and
877 // appending to a <style> tag due to the IE stylesheet limit (bug 31676).
878 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
880 $style
= getMarker().prev();
881 // Verify that the element before the marker actually is a
882 // <style> tag and one that came from ResourceLoader
883 // (not some other style tag or even a `<meta>` or `<script>`).
884 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
885 // There's already a dynamic <style> tag present and
886 // we are able to append more to it.
887 styleEl
= $style
.get( 0 );
889 if ( styleEl
.styleSheet
) {
891 styleEl
.styleSheet
.cssText
+= cssText
;
893 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'stylesheet' } );
896 styleEl
.appendChild( document
.createTextNode( cssText
) );
903 $( newStyleTag( cssText
, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
910 * @param {Array} modules List of module names
911 * @return {string} Hash of concatenated version hashes.
913 function getCombinedVersion( modules
) {
914 var hashes
= $.map( modules
, function ( module
) {
915 return registry
[module
].version
;
917 // Trim for consistency with server-side ResourceLoader::makeHash. It also helps
918 // save precious space in the limited query string. Otherwise modules are more
919 // likely to require multiple HTTP requests.
920 return sha1( hashes
.join( '' ) ).slice( 0, 12 );
924 * Determine whether all dependencies are in state 'ready', which means we may
925 * execute the module or job now.
928 * @param {Array} module Names of modules to be checked
929 * @return {boolean} True if all modules are in state 'ready', false otherwise
931 function allReady( modules
) {
933 for ( i
= 0; i
< modules
.length
; i
++ ) {
934 if ( mw
.loader
.getState( modules
[i
] ) !== 'ready' ) {
942 * Determine whether all dependencies are in state 'ready', which means we may
943 * execute the module or job now.
946 * @param {Array} modules Names of modules to be checked
947 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
949 function anyFailed( modules
) {
951 for ( i
= 0; i
< modules
.length
; i
++ ) {
952 state
= mw
.loader
.getState( modules
[i
] );
953 if ( state
=== 'error' || state
=== 'missing' ) {
961 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
962 * pending jobs and modules that depend upon this module. If the given module failed,
963 * propagate the 'error' state up the dependency tree. Otherwise, go ahead an execute
964 * all jobs/modules now having their dependencies satisfied.
966 * Jobs that depend on a failed module, will have their error callback ran (if any).
969 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
971 function handlePending( module
) {
972 var j
, job
, hasErrors
, m
, stateChange
;
974 if ( registry
[module
].state
=== 'error' || registry
[module
].state
=== 'missing' ) {
975 // If the current module failed, mark all dependent modules also as failed.
976 // Iterate until steady-state to propagate the error state upwards in the
980 for ( m
in registry
) {
981 if ( registry
[m
].state
!== 'error' && registry
[m
].state
!== 'missing' ) {
982 if ( anyFailed( registry
[m
].dependencies
) ) {
983 registry
[m
].state
= 'error';
988 } while ( stateChange
);
991 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
992 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
993 hasErrors
= anyFailed( jobs
[j
].dependencies
);
994 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
995 // All dependencies satisfied, or some have errors
1001 if ( $.isFunction( job
.error
) ) {
1002 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [module
] );
1005 if ( $.isFunction( job
.ready
) ) {
1010 // A user-defined callback raised an exception.
1011 // Swallow it to protect our state machine!
1012 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1017 if ( registry
[module
].state
=== 'ready' ) {
1018 // The current module became 'ready'. Set it in the module store, and recursively execute all
1019 // dependent modules that are loaded and now have all dependencies satisfied.
1020 mw
.loader
.store
.set( module
, registry
[module
] );
1021 for ( m
in registry
) {
1022 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
1030 * Resolve dependencies and detect circular references.
1033 * @param {string} module Name of the top-level module whose dependencies shall be
1034 * resolved and sorted.
1035 * @param {Array} resolved Returns a topological sort of the given module and its
1036 * dependencies, such that later modules depend on earlier modules. The array
1037 * contains the module names. If the array contains already some module names,
1038 * this function appends its result to the pre-existing array.
1039 * @param {Object} [unresolved] Hash used to track the current dependency
1040 * chain; used to report loops in the dependency graph.
1041 * @throws {Error} If any unregistered module or a dependency loop is encountered
1043 function sortDependencies( module
, resolved
, unresolved
) {
1044 var n
, deps
, len
, skip
;
1046 if ( !hasOwn
.call( registry
, module
) ) {
1047 throw new Error( 'Unknown dependency: ' + module
);
1050 if ( registry
[module
].skip
!== null ) {
1051 /*jshint evil:true */
1052 skip
= new Function( registry
[module
].skip
);
1053 registry
[module
].skip
= null;
1055 registry
[module
].skipped
= true;
1056 registry
[module
].dependencies
= [];
1057 registry
[module
].state
= 'ready';
1058 handlePending( module
);
1063 // Resolves dynamic loader function and replaces it with its own results
1064 if ( $.isFunction( registry
[module
].dependencies
) ) {
1065 registry
[module
].dependencies
= registry
[module
].dependencies();
1066 // Ensures the module's dependencies are always in an array
1067 if ( typeof registry
[module
].dependencies
!== 'object' ) {
1068 registry
[module
].dependencies
= [registry
[module
].dependencies
];
1071 if ( $.inArray( module
, resolved
) !== -1 ) {
1072 // Module already resolved; nothing to do
1075 // Create unresolved if not passed in
1076 if ( !unresolved
) {
1079 // Tracks down dependencies
1080 deps
= registry
[module
].dependencies
;
1082 for ( n
= 0; n
< len
; n
+= 1 ) {
1083 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
1084 if ( unresolved
[deps
[n
]] ) {
1086 'Circular reference detected: ' + module
+
1091 // Add to unresolved
1092 unresolved
[module
] = true;
1093 sortDependencies( deps
[n
], resolved
, unresolved
);
1094 delete unresolved
[module
];
1097 resolved
[resolved
.length
] = module
;
1101 * Get a list of module names that a module depends on in their proper dependency
1105 * @param {string[]} module Array of string module names
1106 * @return {Array} List of dependencies, including 'module'.
1108 function resolve( modules
) {
1110 $.each( modules
, function ( idx
, module
) {
1111 sortDependencies( module
, resolved
);
1117 * Load and execute a script with callback.
1120 * @param {string} src URL to script, will be used as the src attribute in the script tag
1121 * @param {Function} [callback] Callback which will be run when the script is done
1123 function addScript( src
, callback
) {
1127 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1128 // XHR for a same domain request instead of <script>, which changes the request
1129 // headers (potentially missing a cache hit), and reduces caching in general
1130 // since browsers cache XHR much less (if at all). And XHR means we retreive
1131 // text, so we'd need to $.globalEval, which then messes up line numbers.
1134 } ).always( callback
);
1138 * Executes a loaded module, making it ready to use
1141 * @param {string} module Module name to execute
1143 function execute( module
) {
1144 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1145 cssHandlesRegistered
= false;
1147 if ( !hasOwn
.call( registry
, module
) ) {
1148 throw new Error( 'Module has not been registered yet: ' + module
);
1150 if ( registry
[module
].state
=== 'registered' ) {
1151 throw new Error( 'Module has not been requested from the server yet: ' + module
);
1153 if ( registry
[module
].state
=== 'loading' ) {
1154 throw new Error( 'Module has not completed loading yet: ' + module
);
1156 if ( registry
[module
].state
=== 'ready' ) {
1157 throw new Error( 'Module has already been executed: ' + module
);
1161 * Define loop-function here for efficiency
1162 * and to avoid re-using badly scoped variables.
1165 function addLink( media
, url
) {
1166 var el
= document
.createElement( 'link' );
1168 // Insert in document *before* setting href
1169 getMarker().before( el
);
1170 el
.rel
= 'stylesheet';
1171 if ( media
&& media
!== 'all' ) {
1174 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1175 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1179 runScript = function () {
1180 var script
, markModuleReady
, nestedAddScript
, legacyWait
,
1181 // Expand to include dependencies since we have to exclude both legacy modules
1182 // and their dependencies from the legacyWait (to prevent a circular dependency).
1183 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1185 script
= registry
[module
].script
;
1186 markModuleReady = function () {
1187 registry
[module
].state
= 'ready';
1188 handlePending( module
);
1190 nestedAddScript = function ( arr
, callback
, i
) {
1191 // Recursively call addScript() in its own callback
1192 // for each element of arr.
1193 if ( i
>= arr
.length
) {
1194 // We're at the end of the array
1199 addScript( arr
[i
], function () {
1200 nestedAddScript( arr
, callback
, i
+ 1 );
1204 legacyWait
= ( $.inArray( module
, legacyModules
) !== -1 )
1205 ? $.Deferred().resolve()
1206 : mw
.loader
.using( legacyModules
);
1208 legacyWait
.always( function () {
1209 if ( $.isArray( script
) ) {
1210 nestedAddScript( script
, markModuleReady
, 0 );
1211 } else if ( $.isFunction( script
) ) {
1212 // Pass jQuery twice so that the signature of the closure which wraps
1213 // the script can bind both '$' and 'jQuery'.
1216 } else if ( typeof script
=== 'string' ) {
1217 // Site and user modules are a legacy scripts that run in the global scope.
1218 // This is transported as a string instead of a function to avoid needing
1219 // to use string manipulation to undo the function wrapper.
1220 if ( module
=== 'user' ) {
1221 // Implicit dependency on the site module. Not real dependency because
1222 // it should run after 'site' regardless of whether it succeeds or fails.
1223 mw
.loader
.using( 'site' ).always( function () {
1224 $.globalEval( script
);
1228 $.globalEval( script
);
1234 // This needs to NOT use mw.log because these errors are common in production mode
1235 // and not in debug mode, such as when a symbol that should be global isn't exported
1236 registry
[module
].state
= 'error';
1237 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1238 handlePending( module
);
1242 // This used to be inside runScript, but since that is now fired asychronously
1243 // (after CSS is loaded) we need to set it here right away. It is crucial that
1244 // when execute() is called this is set synchronously, otherwise modules will get
1245 // executed multiple times as the registry will state that it isn't loading yet.
1246 registry
[module
].state
= 'loading';
1248 // Add localizations to message system
1249 if ( registry
[module
].messages
) {
1250 mw
.messages
.set( registry
[module
].messages
);
1253 // Initialise templates
1254 if ( registry
[module
].templates
) {
1255 mw
.templates
.set( module
, registry
[module
].templates
);
1258 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1261 checkCssHandles = function () {
1262 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1263 // one of the cssHandles is fired while we're still creating more handles.
1264 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1266 runScript
= undefined; // Revoke
1269 cssHandle = function () {
1270 var check
= checkCssHandles
;
1272 return function () {
1276 check
= undefined; // Revoke
1282 // Process styles (see also mw.loader.implement)
1283 // * back-compat: { <media>: css }
1284 // * back-compat: { <media>: [url, ..] }
1285 // * { "css": [css, ..] }
1286 // * { "url": { <media>: [url, ..] } }
1287 if ( registry
[module
].style
) {
1288 for ( key
in registry
[module
].style
) {
1289 value
= registry
[module
].style
[key
];
1292 if ( key
!== 'url' && key
!== 'css' ) {
1293 // Backwards compatibility, key is a media-type
1294 if ( typeof value
=== 'string' ) {
1295 // back-compat: { <media>: css }
1296 // Ignore 'media' because it isn't supported (nor was it used).
1297 // Strings are pre-wrapped in "@media". The media-type was just ""
1298 // (because it had to be set to something).
1299 // This is one of the reasons why this format is no longer used.
1300 addEmbeddedCSS( value
, cssHandle() );
1302 // back-compat: { <media>: [url, ..] }
1308 // Array of css strings in key 'css',
1309 // or back-compat array of urls from media-type
1310 if ( $.isArray( value
) ) {
1311 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
1312 if ( key
=== 'bc-url' ) {
1313 // back-compat: { <media>: [url, ..] }
1314 addLink( media
, value
[i
] );
1315 } else if ( key
=== 'css' ) {
1316 // { "css": [css, ..] }
1317 addEmbeddedCSS( value
[i
], cssHandle() );
1320 // Not an array, but a regular object
1321 // Array of urls inside media-type key
1322 } else if ( typeof value
=== 'object' ) {
1323 // { "url": { <media>: [url, ..] } }
1324 for ( media
in value
) {
1325 urls
= value
[media
];
1326 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
1327 addLink( media
, urls
[i
] );
1335 cssHandlesRegistered
= true;
1340 * Adds a dependencies to the queue with optional callbacks to be run
1341 * when the dependencies are ready or fail
1344 * @param {string|string[]} dependencies Module name or array of string module names
1345 * @param {Function} [ready] Callback to execute when all dependencies are ready
1346 * @param {Function} [error] Callback to execute when any dependency fails
1348 function request( dependencies
, ready
, error
) {
1349 // Allow calling by single module name
1350 if ( typeof dependencies
=== 'string' ) {
1351 dependencies
= [dependencies
];
1354 // Add ready and error callbacks if they were given
1355 if ( ready
!== undefined || error
!== undefined ) {
1356 jobs
[jobs
.length
] = {
1357 dependencies
: $.grep( dependencies
, function ( module
) {
1358 var state
= mw
.loader
.getState( module
);
1359 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading';
1366 $.each( dependencies
, function ( idx
, module
) {
1367 var state
= mw
.loader
.getState( module
);
1368 // Only queue modules that are still in the initial 'registered' state
1369 // (not ones already loading, ready or error).
1370 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1371 // Private modules must be embedded in the page. Don't bother queuing
1372 // these as the server will deny them anyway (T101806).
1373 if ( registry
[module
].group
=== 'private' ) {
1374 registry
[module
].state
= 'error';
1375 handlePending( module
);
1378 queue
.push( module
);
1385 function sortQuery( o
) {
1391 if ( hasOwn
.call( o
, key
) ) {
1396 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1397 sorted
[a
[key
]] = o
[a
[key
]];
1403 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1404 * to a query string of the form foo.bar,baz|bar.baz,quux
1407 function buildModulesString( moduleMap
) {
1411 for ( prefix
in moduleMap
) {
1412 p
= prefix
=== '' ? '' : prefix
+ '.';
1413 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
1415 return arr
.join( '|' );
1419 * Load modules from load.php
1421 * @param {Object} moduleMap Module map, see #buildModulesString
1422 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1423 * @param {string} sourceLoadScript URL of load.php
1425 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1426 var request
= $.extend(
1427 { modules
: buildModulesString( moduleMap
) },
1430 request
= sortQuery( request
);
1431 addScript( sourceLoadScript
+ '?' + $.param( request
) );
1435 * Resolve indexed dependencies.
1437 * ResourceLoader uses an optimization to save space which replaces module names in
1438 * dependency lists with the index of that module within the array of module
1439 * registration data if it exists. The benefit is a significant reduction in the data
1440 * size of the startup module. This function changes those dependency lists back to
1441 * arrays of strings.
1443 * @param {Array} modules Modules array
1445 function resolveIndexedDependencies( modules
) {
1446 $.each( modules
, function ( idx
, module
) {
1448 module
[2] = $.map( module
[2], function ( dep
) {
1449 return typeof dep
=== 'number' ? modules
[dep
][0] : dep
;
1455 /* Public Members */
1458 * The module registry is exposed as an aid for debugging and inspecting page
1459 * state; it is not a public interface for modifying the registry.
1465 moduleRegistry
: registry
,
1468 * @inheritdoc #newStyleTag
1471 addStyleTag
: newStyleTag
,
1474 * Batch-request queued dependencies from the server.
1477 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1478 source
, concatSource
, origBatch
, group
, i
, modules
, sourceLoadScript
,
1479 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1480 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1482 // Build a list of request parameters common to all requests.
1484 skin
: mw
.config
.get( 'skin' ),
1485 lang
: mw
.config
.get( 'wgUserLanguage' ),
1486 debug
: mw
.config
.get( 'debug' )
1488 // Split module batch by source and by group.
1490 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1492 // Appends a list of modules from the queue to the batch
1493 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1494 // Only request modules which are registered
1495 if ( hasOwn
.call( registry
, queue
[q
] ) && registry
[queue
[q
]].state
=== 'registered' ) {
1496 // Prevent duplicate entries
1497 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1498 batch
[batch
.length
] = queue
[q
];
1499 // Mark registered modules as loading
1500 registry
[queue
[q
]].state
= 'loading';
1505 mw
.loader
.store
.init();
1506 if ( mw
.loader
.store
.enabled
) {
1509 batch
= $.grep( batch
, function ( module
) {
1510 var source
= mw
.loader
.store
.get( module
);
1512 concatSource
.push( source
);
1518 $.globalEval( concatSource
.join( ';' ) );
1520 // Not good, the cached mw.loader.implement calls failed! This should
1521 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1522 // Depending on how corrupt the string is, it is likely that some
1523 // modules' implement() succeeded while the ones after the error will
1524 // never run and leave their modules in the 'loading' state forever.
1526 // Since this is an error not caused by an individual module but by
1527 // something that infected the implement call itself, don't take any
1528 // risks and clear everything in this cache.
1529 mw
.loader
.store
.clear();
1530 // Re-add the ones still pending back to the batch and let the server
1531 // repopulate these modules to the cache.
1532 // This means that at most one module will be useless (the one that had
1533 // the error) instead of all of them.
1534 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1535 origBatch
= $.grep( origBatch
, function ( module
) {
1536 return registry
[module
].state
=== 'loading';
1538 batch
= batch
.concat( origBatch
);
1542 // Early exit if there's nothing to load...
1543 if ( !batch
.length
) {
1547 // The queue has been processed into the batch, clear up the queue.
1550 // Always order modules alphabetically to help reduce cache
1551 // misses for otherwise identical content.
1554 // Split batch by source and by group.
1555 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1556 bSource
= registry
[batch
[b
]].source
;
1557 bGroup
= registry
[batch
[b
]].group
;
1558 if ( !hasOwn
.call( splits
, bSource
) ) {
1559 splits
[bSource
] = {};
1561 if ( !hasOwn
.call( splits
[bSource
], bGroup
) ) {
1562 splits
[bSource
][bGroup
] = [];
1564 bSourceGroup
= splits
[bSource
][bGroup
];
1565 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1568 // Clear the batch - this MUST happen before we append any
1569 // script elements to the body or it's possible that a script
1570 // will be locally cached, instantly load, and work the batch
1571 // again, all before we've cleared it causing each request to
1572 // include modules which are already loaded.
1575 for ( source
in splits
) {
1577 sourceLoadScript
= sources
[source
];
1579 for ( group
in splits
[source
] ) {
1581 // Cache access to currently selected list of
1582 // modules for this group from this source.
1583 modules
= splits
[source
][group
];
1585 currReqBase
= $.extend( {
1586 version
: getCombinedVersion( modules
)
1588 // For user modules append a user name to the request.
1589 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1590 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1592 currReqBaseLength
= $.param( currReqBase
).length
;
1593 // We may need to split up the request to honor the query string length limit,
1594 // so build it piece by piece.
1595 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1597 moduleMap
= {}; // { prefix: [ suffixes ] }
1599 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1600 // Determine how many bytes this module would add to the query string
1601 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1603 // If lastDotIndex is -1, substr() returns an empty string
1604 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1605 suffix
= modules
[i
].slice( lastDotIndex
+ 1 );
1607 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1608 ? suffix
.length
+ 3 // '%2C'.length == 3
1609 : modules
[i
].length
+ 3; // '%7C'.length == 3
1611 // If the request would become too long, create a new one,
1612 // but don't create empty requests
1613 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1614 // This request would become too long, create a new one
1615 // and fire off the old one
1616 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1618 l
= currReqBaseLength
+ 9;
1619 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1621 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1622 moduleMap
[prefix
] = [];
1624 moduleMap
[prefix
].push( suffix
);
1627 // If there's anything left in moduleMap, request that too
1628 if ( !$.isEmptyObject( moduleMap
) ) {
1629 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1636 * Register a source.
1638 * The #work method will use this information to split up requests by source.
1640 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1642 * @param {string} id Short string representing a source wiki, used internally for
1643 * registered modules to indicate where they should be loaded from (usually lowercase a-z).
1644 * @param {Object|string} loadUrl load.php url, may be an object for backwards-compatibility
1647 addSource: function ( id
, loadUrl
) {
1649 // Allow multiple additions
1650 if ( typeof id
=== 'object' ) {
1651 for ( source
in id
) {
1652 mw
.loader
.addSource( source
, id
[source
] );
1657 if ( hasOwn
.call( sources
, id
) ) {
1658 throw new Error( 'source already registered: ' + id
);
1661 if ( typeof loadUrl
=== 'object' ) {
1662 loadUrl
= loadUrl
.loadScript
;
1665 sources
[id
] = loadUrl
;
1671 * Register a module, letting the system know about it and its properties.
1673 * The startup modules contain calls to this method.
1675 * When using multiple module registration by passing an array, dependencies that
1676 * are specified as references to modules within the array will be resolved before
1677 * the modules are registered.
1679 * @param {string|Array} module Module name or array of arrays, each containing
1680 * a list of arguments compatible with this method
1681 * @param {string|number} version Module version hash (falls backs to empty string)
1682 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1683 * @param {string|Array|Function} dependencies One string or array of strings of module
1684 * names on which this module depends, or a function that returns that array.
1685 * @param {string} [group=null] Group which the module is in
1686 * @param {string} [source='local'] Name of the source
1687 * @param {string} [skip=null] Script body of the skip function
1689 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1691 // Allow multiple registration
1692 if ( typeof module
=== 'object' ) {
1693 resolveIndexedDependencies( module
);
1694 for ( i
= 0, len
= module
.length
; i
< len
; i
++ ) {
1695 // module is an array of module names
1696 if ( typeof module
[i
] === 'string' ) {
1697 mw
.loader
.register( module
[i
] );
1698 // module is an array of arrays
1699 } else if ( typeof module
[i
] === 'object' ) {
1700 mw
.loader
.register
.apply( mw
.loader
, module
[i
] );
1706 if ( typeof module
!== 'string' ) {
1707 throw new Error( 'module must be a string, not a ' + typeof module
);
1709 if ( hasOwn
.call( registry
, module
) ) {
1710 throw new Error( 'module already registered: ' + module
);
1712 // List the module as registered
1713 registry
[module
] = {
1714 version
: version
!== undefined ? String( version
) : '',
1716 group
: typeof group
=== 'string' ? group
: null,
1717 source
: typeof source
=== 'string' ? source
: 'local',
1718 state
: 'registered',
1719 skip
: typeof skip
=== 'string' ? skip
: null
1721 if ( typeof dependencies
=== 'string' ) {
1722 // Allow dependencies to be given as a single module name
1723 registry
[module
].dependencies
= [ dependencies
];
1724 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1725 // Allow dependencies to be given as an array of module names
1726 // or a function which returns an array
1727 registry
[module
].dependencies
= dependencies
;
1732 * Implement a module given the components that make up the module.
1734 * When #load or #using requests one or more modules, the server
1735 * response contain calls to this function.
1737 * All arguments are required.
1739 * @param {string} module Name of module
1740 * @param {Function|Array} script Function with module code or Array of URLs to
1741 * be used as the src attribute of a new `<script>` tag.
1742 * @param {Object} [style] Should follow one of the following patterns:
1744 * { "css": [css, ..] }
1745 * { "url": { <media>: [url, ..] } }
1747 * And for backwards compatibility (needs to be supported forever due to caching):
1750 * { <media>: [url, ..] }
1752 * The reason css strings are not concatenated anymore is bug 31676. We now check
1753 * whether it's safe to extend the stylesheet.
1755 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1756 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1758 implement: function ( module
, script
, style
, messages
, templates
) {
1760 if ( typeof module
!== 'string' ) {
1761 throw new Error( 'module must be of type string, not ' + typeof module
);
1763 if ( script
&& !$.isFunction( script
) && !$.isArray( script
) && typeof script
!== 'string' ) {
1764 throw new Error( 'script must be of type function, array, or script; not ' + typeof script
);
1766 if ( style
&& !$.isPlainObject( style
) ) {
1767 throw new Error( 'style must be of type object, not ' + typeof style
);
1769 if ( messages
&& !$.isPlainObject( messages
) ) {
1770 throw new Error( 'messages must be of type object, not a ' + typeof messages
);
1772 if ( templates
&& !$.isPlainObject( templates
) ) {
1773 throw new Error( 'templates must be of type object, not a ' + typeof templates
);
1775 // Automatically register module
1776 if ( !hasOwn
.call( registry
, module
) ) {
1777 mw
.loader
.register( module
);
1779 // Check for duplicate implementation
1780 if ( hasOwn
.call( registry
, module
) && registry
[module
].script
!== undefined ) {
1781 throw new Error( 'module already implemented: ' + module
);
1783 // Attach components
1784 registry
[module
].script
= script
|| [];
1785 registry
[module
].style
= style
|| {};
1786 registry
[module
].messages
= messages
|| {};
1787 registry
[module
].templates
= templates
|| {};
1788 // The module may already have been marked as erroneous
1789 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1790 registry
[module
].state
= 'loaded';
1791 if ( allReady( registry
[module
].dependencies
) ) {
1798 * Execute a function as soon as one or more required modules are ready.
1800 * Example of inline dependency on OOjs:
1802 * mw.loader.using( 'oojs', function () {
1803 * OO.compare( [ 1 ], [ 1 ] );
1806 * @param {string|Array} dependencies Module name or array of modules names the callback
1807 * dependends on to be ready before executing
1808 * @param {Function} [ready] Callback to execute when all dependencies are ready
1809 * @param {Function} [error] Callback to execute if one or more dependencies failed
1810 * @return {jQuery.Promise}
1811 * @since 1.23 this returns a promise
1813 using: function ( dependencies
, ready
, error
) {
1814 var deferred
= $.Deferred();
1816 // Allow calling with a single dependency as a string
1817 if ( typeof dependencies
=== 'string' ) {
1818 dependencies
= [ dependencies
];
1819 } else if ( !$.isArray( dependencies
) ) {
1821 throw new Error( 'Dependencies must be a string or an array' );
1825 deferred
.done( ready
);
1828 deferred
.fail( error
);
1831 // Resolve entire dependency map
1832 dependencies
= resolve( dependencies
);
1833 if ( allReady( dependencies
) ) {
1834 // Run ready immediately
1836 } else if ( anyFailed( dependencies
) ) {
1837 // Execute error immediately if any dependencies have errors
1839 new Error( 'One or more dependencies failed to load' ),
1843 // Not all dependencies are ready: queue up a request
1844 request( dependencies
, deferred
.resolve
, deferred
.reject
);
1847 return deferred
.promise();
1851 * Load an external script or one or more modules.
1853 * @param {string|Array} modules Either the name of a module, array of modules,
1854 * or a URL of an external script or style
1855 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1856 * external script or style; acceptable values are "text/css" and
1857 * "text/javascript"; if no type is provided, text/javascript is assumed.
1859 load: function ( modules
, type
) {
1863 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1864 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1866 // Allow calling with an external url or single dependency as a string
1867 if ( typeof modules
=== 'string' ) {
1868 if ( /^(https?:)?\/\//.test( modules
) ) {
1869 if ( type
=== 'text/css' ) {
1871 // Use properties instead of attributes as IE throws security
1872 // warnings when inserting a <link> tag with a protocol-relative
1873 // URL set though attributes - when on HTTPS. See bug 41331.
1874 l
= document
.createElement( 'link' );
1875 l
.rel
= 'stylesheet';
1877 $( 'head' ).append( l
);
1880 if ( type
=== 'text/javascript' || type
=== undefined ) {
1881 addScript( modules
);
1885 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1887 // Called with single module
1888 modules
= [ modules
];
1891 // Filter out undefined modules, otherwise resolve() will throw
1892 // an exception for trying to load an undefined module.
1893 // Undefined modules are acceptable here in load(), because load() takes
1894 // an array of unrelated modules, whereas the modules passed to
1895 // using() are related and must all be loaded.
1896 filtered
= $.grep( modules
, function ( module
) {
1897 var state
= mw
.loader
.getState( module
);
1898 return state
!== null && state
!== 'error' && state
!== 'missing';
1901 if ( filtered
.length
=== 0 ) {
1904 // Resolve entire dependency map
1905 filtered
= resolve( filtered
);
1906 // If all modules are ready, or if any modules have errors, nothing to be done.
1907 if ( allReady( filtered
) || anyFailed( filtered
) ) {
1910 // Since some modules are not yet ready, queue up a request.
1911 request( filtered
, undefined, undefined );
1915 * Change the state of one or more modules.
1917 * @param {string|Object} module Module name or object of module name/state pairs
1918 * @param {string} state State name
1920 state: function ( module
, state
) {
1923 if ( typeof module
=== 'object' ) {
1924 for ( m
in module
) {
1925 mw
.loader
.state( m
, module
[m
] );
1929 if ( !hasOwn
.call( registry
, module
) ) {
1930 mw
.loader
.register( module
);
1932 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1933 && registry
[module
].state
!== state
) {
1934 // Make sure pending modules depending on this one get executed if their
1935 // dependencies are now fulfilled!
1936 registry
[module
].state
= state
;
1937 handlePending( module
);
1939 registry
[module
].state
= state
;
1944 * Get the version of a module.
1946 * @param {string} module Name of module
1947 * @return {string|null} The version, or null if the module (or its version) is not
1950 getVersion: function ( module
) {
1951 if ( !hasOwn
.call( registry
, module
) || registry
[module
].version
=== undefined ) {
1954 return registry
[module
].version
;
1958 * Get the state of a module.
1960 * @param {string} module Name of module
1961 * @return {string|null} The state, or null if the module (or its state) is not
1964 getState: function ( module
) {
1965 if ( !hasOwn
.call( registry
, module
) || registry
[module
].state
=== undefined ) {
1968 return registry
[module
].state
;
1972 * Get the names of all registered modules.
1976 getModuleNames: function () {
1977 return $.map( registry
, function ( i
, key
) {
1983 * @inheritdoc mw.inspect#runReports
1986 inspect: function () {
1987 var args
= slice
.call( arguments
);
1988 mw
.loader
.using( 'mediawiki.inspect', function () {
1989 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
1994 * On browsers that implement the localStorage API, the module store serves as a
1995 * smart complement to the browser cache. Unlike the browser cache, the module store
1996 * can slice a concatenated response from ResourceLoader into its constituent
1997 * modules and cache each of them separately, using each module's versioning scheme
1998 * to determine when the cache should be invalidated.
2001 * @class mw.loader.store
2004 // Whether the store is in use on this page.
2007 // Modules whose string representation exceeds 100 kB are ineligible
2008 // for storage due to bug T66721.
2009 MODULE_SIZE_MAX
: 100000,
2011 // The contents of the store, mapping '[module name]@[version]' keys
2012 // to module implementations.
2016 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2019 * Construct a JSON-serializable object representing the content of the store.
2020 * @return {Object} Module store contents.
2022 toJSON: function () {
2023 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2027 * Get the localStorage key for the entire module store. The key references
2028 * $wgDBname to prevent clashes between wikis which share a common host.
2030 * @return {string} localStorage item key
2032 getStoreKey: function () {
2033 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2037 * Get a key on which to vary the module cache.
2038 * @return {string} String of concatenated vary conditions.
2040 getVary: function () {
2042 mw
.config
.get( 'skin' ),
2043 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2044 mw
.config
.get( 'wgUserLanguage' )
2049 * Get a key for a specific module. The key format is '[name]@[version]'.
2051 * @param {string} module Module name
2052 * @return {string|null} Module key or null if module does not exist
2054 getModuleKey: function ( module
) {
2055 return hasOwn
.call( registry
, module
) ?
2056 ( module
+ '@' + registry
[module
].version
) : null;
2060 * Initialize the store.
2062 * Retrieves store from localStorage and (if successfully retrieved) decoding
2063 * the stored JSON value to a plain object.
2065 * The try / catch block is used for JSON & localStorage feature detection.
2066 * See the in-line documentation for Modernizr's localStorage feature detection
2067 * code for a full account of why we need a try / catch:
2068 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2073 if ( mw
.loader
.store
.enabled
!== null ) {
2078 if ( !mw
.config
.get( 'wgResourceLoaderStorageEnabled' ) ) {
2079 // Disabled by configuration.
2080 // Clear any previous store to free up space. (T66721)
2081 mw
.loader
.store
.clear();
2082 mw
.loader
.store
.enabled
= false;
2085 if ( mw
.config
.get( 'debug' ) ) {
2086 // Disable module store in debug mode
2087 mw
.loader
.store
.enabled
= false;
2092 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2093 // If we get here, localStorage is available; mark enabled
2094 mw
.loader
.store
.enabled
= true;
2095 data
= JSON
.parse( raw
);
2096 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2097 mw
.loader
.store
.items
= data
.items
;
2101 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2104 if ( raw
=== undefined ) {
2105 // localStorage failed; disable store
2106 mw
.loader
.store
.enabled
= false;
2108 mw
.loader
.store
.update();
2113 * Retrieve a module from the store and update cache hit stats.
2115 * @param {string} module Module name
2116 * @return {string|boolean} Module implementation or false if unavailable
2118 get: function ( module
) {
2121 if ( !mw
.loader
.store
.enabled
) {
2125 key
= mw
.loader
.store
.getModuleKey( module
);
2126 if ( key
in mw
.loader
.store
.items
) {
2127 mw
.loader
.store
.stats
.hits
++;
2128 return mw
.loader
.store
.items
[key
];
2130 mw
.loader
.store
.stats
.misses
++;
2135 * Stringify a module and queue it for storage.
2137 * @param {string} module Module name
2138 * @param {Object} descriptor The module's descriptor as set in the registry
2140 set: function ( module
, descriptor
) {
2143 if ( !mw
.loader
.store
.enabled
) {
2147 key
= mw
.loader
.store
.getModuleKey( module
);
2150 // Already stored a copy of this exact version
2151 key
in mw
.loader
.store
.items
||
2152 // Module failed to load
2153 descriptor
.state
!== 'ready' ||
2154 // Unversioned, private, or site-/user-specific
2155 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2156 // Partial descriptor
2157 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2158 descriptor
.messages
, descriptor
.templates
] ) !== -1
2166 JSON
.stringify( module
),
2167 typeof descriptor
.script
=== 'function' ?
2168 String( descriptor
.script
) :
2169 JSON
.stringify( descriptor
.script
),
2170 JSON
.stringify( descriptor
.style
),
2171 JSON
.stringify( descriptor
.messages
),
2172 JSON
.stringify( descriptor
.templates
)
2174 // Attempted workaround for a possible Opera bug (bug T59567).
2175 // This regex should never match under sane conditions.
2176 if ( /^\s*\(/.test( args
[1] ) ) {
2177 args
[1] = 'function' + args
[1];
2178 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2181 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2185 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2186 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2189 mw
.loader
.store
.items
[key
] = src
;
2190 mw
.loader
.store
.update();
2194 * Iterate through the module store, removing any item that does not correspond
2195 * (in name and version) to an item in the module registry.
2197 prune: function () {
2200 if ( !mw
.loader
.store
.enabled
) {
2204 for ( key
in mw
.loader
.store
.items
) {
2205 module
= key
.slice( 0, key
.indexOf( '@' ) );
2206 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2207 mw
.loader
.store
.stats
.expired
++;
2208 delete mw
.loader
.store
.items
[key
];
2209 } else if ( mw
.loader
.store
.items
[key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2210 // This value predates the enforcement of a size limit on cached modules.
2211 delete mw
.loader
.store
.items
[key
];
2217 * Clear the entire module store right now.
2219 clear: function () {
2220 mw
.loader
.store
.items
= {};
2221 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2225 * Sync modules to localStorage.
2227 * This function debounces localStorage updates. When called multiple times in
2228 * quick succession, the calls are coalesced into a single update operation.
2229 * This allows us to call #update without having to consider the module load
2230 * queue; the call to localStorage.setItem will be naturally deferred until the
2231 * page is quiescent.
2233 * Because localStorage is shared by all pages with the same origin, if multiple
2234 * pages are loaded with different module sets, the possibility exists that
2235 * modules saved by one page will be clobbered by another. But the impact would
2236 * be minor and the problem would be corrected by subsequent page views.
2240 update
: ( function () {
2245 key
= mw
.loader
.store
.getStoreKey();
2247 if ( !mw
.loader
.store
.enabled
) {
2250 mw
.loader
.store
.prune();
2252 // Replacing the content of the module store might fail if the new
2253 // contents would exceed the browser's localStorage size limit. To
2254 // avoid clogging the browser with stale data, always remove the old
2255 // value before attempting to set the new one.
2256 localStorage
.removeItem( key
);
2257 data
= JSON
.stringify( mw
.loader
.store
);
2258 localStorage
.setItem( key
, data
);
2260 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2264 return function () {
2265 clearTimeout( timer
);
2266 timer
= setTimeout( flush
, 2000 );
2274 * HTML construction helper functions
2281 * output = Html.element( 'div', {}, new Html.Raw(
2282 * Html.element( 'img', { src: '<' } )
2284 * mw.log( output ); // <div><img src="<"/></div>
2289 html
: ( function () {
2290 function escapeCallback( s
) {
2307 * Escape a string for HTML.
2309 * Converts special characters to HTML entities.
2311 * mw.html.escape( '< > \' & "' );
2312 * // Returns < > ' & "
2314 * @param {string} s The string to escape
2315 * @return {string} HTML
2317 escape: function ( s
) {
2318 return s
.replace( /['"<>&]/g, escapeCallback
);
2322 * Create an HTML element string, with safe escaping.
2324 * @param {string} name The tag name.
2325 * @param {Object} attrs An object with members mapping element names to values
2326 * @param {Mixed} contents The contents of the element. May be either:
2328 * - string: The string is escaped.
2329 * - null or undefined: The short closing form is used, e.g. `<br/>`.
2330 * - this.Raw: The value attribute is included without escaping.
2331 * - this.Cdata: The value attribute is included, and an exception is
2332 * thrown if it contains an illegal ETAGO delimiter.
2333 * See <http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2>.
2334 * @return {string} HTML
2336 element: function ( name
, attrs
, contents
) {
2337 var v
, attrName
, s
= '<' + name
;
2339 for ( attrName
in attrs
) {
2340 v
= attrs
[attrName
];
2341 // Convert name=true, to name=name
2345 } else if ( v
=== false ) {
2348 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2350 if ( contents
=== undefined || contents
=== null ) {
2357 switch ( typeof contents
) {
2360 s
+= this.escape( contents
);
2364 // Convert to string
2365 s
+= String( contents
);
2368 if ( contents
instanceof this.Raw
) {
2369 // Raw HTML inclusion
2370 s
+= contents
.value
;
2371 } else if ( contents
instanceof this.Cdata
) {
2373 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2374 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2376 s
+= contents
.value
;
2378 throw new Error( 'mw.html.element: Invalid type of contents' );
2381 s
+= '</' + name
+ '>';
2386 * Wrapper object for raw HTML passed to mw.html.element().
2387 * @class mw.html.Raw
2389 Raw: function ( value
) {
2394 * Wrapper object for CDATA element contents passed to mw.html.element()
2395 * @class mw.html.Cdata
2397 Cdata: function ( value
) {
2403 // Skeleton user object. mediawiki.user.js extends this
2410 * Registry and firing of events.
2412 * MediaWiki has various interface components that are extended, enhanced
2413 * or manipulated in some other way by extensions, gadgets and even
2416 * This framework helps streamlining the timing of when these other
2417 * code paths fire their plugins (instead of using document-ready,
2418 * which can and should be limited to firing only once).
2420 * Features like navigating to other wiki pages, previewing an edit
2421 * and editing itself – without a refresh – can then retrigger these
2422 * hooks accordingly to ensure everything still works as expected.
2426 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2427 * mw.hook( 'wikipage.content' ).fire( $content );
2429 * Handlers can be added and fired for arbitrary event names at any time. The same
2430 * event can be fired multiple times. The last run of an event is memorized
2431 * (similar to `$(document).ready` and `$.Deferred().done`).
2432 * This means if an event is fired, and a handler added afterwards, the added
2433 * function will be fired right away with the last given event data.
2435 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2436 * Thus allowing flexible use and optimal maintainability and authority control.
2437 * You can pass around the `add` and/or `fire` method to another piece of code
2438 * without it having to know the event name (or `mw.hook` for that matter).
2440 * var h = mw.hook( 'bar.ready' );
2441 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2443 * Note: Events are documented with an underscore instead of a dot in the event
2444 * name due to jsduck not supporting dots in that position.
2448 hook
: ( function () {
2452 * Create an instance of mw.hook.
2456 * @param {string} name Name of hook.
2459 return function ( name
) {
2460 var list
= hasOwn
.call( lists
, name
) ?
2462 lists
[name
] = $.Callbacks( 'memory' );
2466 * Register a hook handler
2467 * @param {Function...} handler Function to bind.
2473 * Unregister a hook handler
2474 * @param {Function...} handler Function to unbind.
2477 remove
: list
.remove
,
2481 * @param {Mixed...} data
2485 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2492 // Alias $j to jQuery for backwards compatibility
2493 // @deprecated since 1.23 Use $ or jQuery instead
2494 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2497 * Log a message to window.console, if possible.
2499 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2500 * also in production mode). Gets console references in each invocation instead of caching the
2501 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2505 * @param {string} topic Stream name passed by mw.track
2506 * @param {Object} data Data passed by mw.track
2507 * @param {Error} [data.exception]
2508 * @param {string} data.source Error source
2509 * @param {string} [data.module] Name of module which caused the error
2511 function log( topic
, data
) {
2514 source
= data
.source
,
2515 module
= data
.module
,
2516 console
= window
.console
;
2518 if ( console
&& console
.log
) {
2519 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2521 msg
+= ' in module ' + module
;
2523 msg
+= ( e
? ':' : '.' );
2526 // If we have an exception object, log it to the error channel to trigger a
2527 // proper stacktraces in browsers that support it. No fallback as we have no browsers
2528 // that don't support error(), but do support log().
2529 if ( e
&& console
.error
) {
2530 console
.error( String( e
), e
);
2535 // Subscribe to error streams
2536 mw
.trackSubscribe( 'resourceloader.exception', log
);
2537 mw
.trackSubscribe( 'resourceloader.assert', log
);
2540 * Fired when all modules associated with the page have finished loading.
2542 * @event resourceloader_loadEnd
2546 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2547 return mw
.loader
.getState( module
) === 'loading';
2549 // In order to use jQuery.when (which stops early if one of the promises got rejected)
2550 // cast any loading failures into successes. We only need a callback, not the module.
2551 loading
= $.map( loading
, function ( module
) {
2552 return mw
.loader
.using( module
).then( null, function () {
2553 return $.Deferred().resolve();
2556 $.when
.apply( $, loading
).then( function () {
2557 performance
.mark( 'mwLoadEnd' );
2558 mw
.hook( 'resourceloader.loadEnd' ).fire();
2562 // Attach to window and globally alias
2563 window
.mw
= window
.mediaWiki
= mw
;