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} formatString 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}
589 // Also update the restoration of methods in mediawiki.log.js
590 // when adding or removing methods here.
591 var log = function () {},
592 console
= window
.console
;
600 * Write a message the console's warning channel.
601 * Actions not supported by the browser console are silently ignored.
603 * @param {...string} msg Messages to output to console
605 log
.warn
= console
&& console
.warn
&& Function
.prototype.bind
?
606 Function
.prototype.bind
.call( console
.warn
, console
) :
610 * Write a message the console's error channel.
612 * Most browsers provide a stacktrace by default if the argument
613 * is a caught Error object.
616 * @param {Error|...string} msg Messages to output to console
618 log
.error
= console
&& console
.error
&& Function
.prototype.bind
?
619 Function
.prototype.bind
.call( console
.error
, console
) :
623 * Create a property in a host object that, when accessed, will produce
624 * a deprecation warning in the console with backtrace.
626 * @param {Object} obj Host object of deprecated property
627 * @param {string} key Name of property to create in `obj`
628 * @param {Mixed} val The value this property should return when accessed
629 * @param {string} [msg] Optional text to include in the deprecation message
631 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
633 } : function ( obj
, key
, val
, msg
) {
634 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
636 // Can throw on Object.defineProperty.
638 Object
.defineProperty( obj
, key
, {
642 mw
.track( 'mw.deprecate', key
);
646 set: function ( newVal
) {
647 mw
.track( 'mw.deprecate', key
);
653 // Fallback to creating a copy of the value to the object.
662 * Client for ResourceLoader server end point.
664 * This client is in charge of maintaining the module registry and state
665 * machine, initiating network (batch) requests for loading modules, as
666 * well as dependency resolution and execution of source code.
668 * For more information, refer to
669 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
674 loader
: ( function () {
677 * Fired via mw.track on various resource loading errors.
679 * @event resourceloader_exception
680 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
681 * object, but in theory module code could manually throw something else, and that
682 * might also end up here.
683 * @param {string} [module] Name of the module which caused the error. Omitted if the
684 * error is not module-related or the module cannot be easily identified due to
686 * @param {string} source Source of the error. Possible values:
688 * - style: stylesheet error (only affects old IE where a special style loading method
690 * - load-callback: exception thrown by user callback
691 * - module-execute: exception thrown by module code
692 * - store-eval: could not evaluate module code cached in localStorage
693 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
694 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
695 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
699 * Fired via mw.track on resource loading error conditions.
701 * @event resourceloader_assert
702 * @param {string} source Source of the error. Possible values:
704 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
705 * bug; see <https://phabricator.wikimedia.org/T59567> for details
709 * Mapping of registered modules.
711 * See #implement and #execute for exact details on support for script, style and messages.
717 * // From mw.loader.register()
718 * 'version': '########' (hash)
719 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
720 * 'group': 'somegroup', (or) null
721 * 'source': 'local', (or) 'anotherwiki'
722 * 'skip': 'return !!window.Example', (or) null
724 * // Set from execute() or mw.loader.state()
725 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
727 * // Optionally added at run-time by mw.loader.implement()
729 * 'script': closure, array of urls, or string
730 * 'style': { ... } (see #execute)
731 * 'messages': { 'key': 'value', ... }
738 * The module is known to the system but not yet requested.
739 * Meta data is registered via mw.loader#register. Calls to that method are
740 * generated server-side by the startup module.
742 * The module is requested through mw.loader (either directly or as dependency of
743 * another module). The client will be fetching module contents from the server.
744 * The contents are then stashed in the registry via mw.loader#implement.
746 * The module has been requested from the server and stashed via mw.loader#implement.
747 * If the module has no more dependencies in-fight, the module will be executed
748 * right away. Otherwise execution is deferred, controlled via #handlePending.
750 * The module is being executed.
752 * The module has been successfully executed.
754 * The module (or one of its dependencies) produced an error during execution.
756 * The module was registered client-side and requested, but the server denied knowledge
757 * of the module's existence.
763 // Mapping of sources, keyed by source-id, values are strings.
768 // 'sourceId': 'http://example.org/w/load.php'
773 // List of modules which will be loaded as when ready
776 // List of modules to be loaded
780 * List of callback jobs waiting for modules to be ready.
782 * Jobs are created by #request() and run by #handlePending().
784 * Typically when a job is created for a module, the job's dependencies contain
785 * both the module being requested and all its recursive dependencies.
790 * 'dependencies': [ module names ],
791 * 'ready': Function callback
792 * 'error': Function callback
795 * @property {Object[]} jobs
800 // Selector cache for the marker element. Use getMarker() to get/use the marker!
803 // Buffer for #addEmbeddedCSS
806 // Callbacks for #addEmbeddedCSS
807 cssCallbacks
= $.Callbacks();
809 function getMarker() {
812 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
813 if ( !$marker
.length
) {
814 mw
.log( 'No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically' );
815 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
822 * Create a new style element and add it to the DOM.
825 * @param {string} text CSS text
826 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag
827 * should be inserted before
828 * @return {HTMLElement} Reference to the created style element
830 function newStyleTag( text
, nextnode
) {
831 var s
= document
.createElement( 'style' );
833 // Must attach to document before setting cssText (bug 33305)
835 $( nextnode
).before( s
);
837 document
.getElementsByTagName( 'head' )[ 0 ].appendChild( s
);
839 if ( s
.styleSheet
) {
841 // Old IE ignores appended text nodes, access stylesheet directly.
842 s
.styleSheet
.cssText
= text
;
844 // Standard behaviour
845 s
.appendChild( document
.createTextNode( text
) );
851 * Add a bit of CSS text to the current browser page.
853 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
854 * or create a new one based on whether the given `cssText` is safe for extension.
856 * @param {string} [cssText=cssBuffer] If called without cssText,
857 * the internal buffer will be inserted instead.
858 * @param {Function} [callback]
860 function addEmbeddedCSS( cssText
, callback
) {
861 var $style
, styleEl
, newCssText
;
863 function fireCallbacks() {
864 var oldCallbacks
= cssCallbacks
;
865 // Reset cssCallbacks variable so it's not polluted by any calls to
866 // addEmbeddedCSS() from one of the callbacks (T105973)
867 cssCallbacks
= $.Callbacks();
868 oldCallbacks
.fire().empty();
872 cssCallbacks
.add( callback
);
875 // Yield once before inserting the <style> tag. There are likely
876 // more calls coming up which we can combine this way.
877 // Appending a stylesheet and waiting for the browser to repaint
878 // is fairly expensive, this reduces that (bug 45810)
880 // Be careful not to extend the buffer with css that needs a new stylesheet.
881 // cssText containing `@import` rules needs to go at the start of a buffer,
882 // since those only work when placed at the start of a stylesheet; bug 35562.
883 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
884 // Linebreak for somewhat distinguishable sections
885 // (the rl-cachekey comment separating each)
886 cssBuffer
+= '\n' + cssText
;
887 // TODO: Use requestAnimationFrame in the future which will
888 // perform even better by not injecting styles while the browser
890 setTimeout( function () {
891 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
892 // (below version 13) has the non-standard behaviour of passing a
893 // numerical "lateness" value as first argument to this callback
894 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
900 // This is a delayed call and we got a buffer still
901 } else if ( cssBuffer
) {
906 // This is a delayed call, but buffer was already cleared by
907 // another delayed call.
911 // By default, always create a new <style>. Appending text to a <style>
912 // tag is bad as it means the contents have to be re-parsed (bug 45810).
914 // Except, of course, in IE 9 and below. In there we default to re-using and
915 // appending to a <style> tag due to the IE stylesheet limit (bug 31676).
916 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
918 $style
= getMarker().prev();
919 // Verify that the element before the marker actually is a
920 // <style> tag and one that came from ResourceLoader
921 // (not some other style tag or even a `<meta>` or `<script>`).
922 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) ) {
923 // There's already a dynamic <style> tag present and
924 // we are able to append more to it.
925 styleEl
= $style
.get( 0 );
927 if ( styleEl
.styleSheet
) {
930 // We can't do styleSheet.cssText += cssText, since IE9 mangles this property on
931 // write, dropping @media queries from the CSS text. If we read it and used its
932 // value, we would accidentally apply @media-specific styles to all media. (T108727)
933 if ( document
.documentMode
=== 9 ) {
934 newCssText
= $style
.data( 'ResourceLoaderDynamicStyleTag' ) + cssText
;
935 styleEl
.styleSheet
.cssText
= newCssText
;
936 $style
.data( 'ResourceLoaderDynamicStyleTag', newCssText
);
938 styleEl
.styleSheet
.cssText
+= cssText
;
941 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'stylesheet' } );
944 styleEl
.appendChild( document
.createTextNode( cssText
) );
951 $style
= $( newStyleTag( cssText
, getMarker() ) );
953 if ( document
.documentMode
=== 9 ) {
955 // Preserve original CSS text because IE9 mangles it on write
956 $style
.data( 'ResourceLoaderDynamicStyleTag', cssText
);
958 $style
.data( 'ResourceLoaderDynamicStyleTag', true );
966 * @param {Array} modules List of module names
967 * @return {string} Hash of concatenated version hashes.
969 function getCombinedVersion( modules
) {
970 var hashes
= $.map( modules
, function ( module
) {
971 return registry
[ module
].version
;
973 // Trim for consistency with server-side ResourceLoader::makeHash. It also helps
974 // save precious space in the limited query string. Otherwise modules are more
975 // likely to require multiple HTTP requests.
976 return sha1( hashes
.join( '' ) ).slice( 0, 12 );
980 * Determine whether all dependencies are in state 'ready', which means we may
981 * execute the module or job now.
984 * @param {Array} modules Names of modules to be checked
985 * @return {boolean} True if all modules are in state 'ready', false otherwise
987 function allReady( modules
) {
989 for ( i
= 0; i
< modules
.length
; i
++ ) {
990 if ( mw
.loader
.getState( modules
[ i
] ) !== 'ready' ) {
998 * Determine whether all dependencies are in state 'ready', which means we may
999 * execute the module or job now.
1002 * @param {Array} modules Names of modules to be checked
1003 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1005 function anyFailed( modules
) {
1007 for ( i
= 0; i
< modules
.length
; i
++ ) {
1008 state
= mw
.loader
.getState( modules
[ i
] );
1009 if ( state
=== 'error' || state
=== 'missing' ) {
1017 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1018 * pending jobs and modules that depend upon this module. If the given module failed,
1019 * propagate the 'error' state up the dependency tree. Otherwise, go ahead an execute
1020 * all jobs/modules now having their dependencies satisfied.
1022 * Jobs that depend on a failed module, will have their error callback ran (if any).
1025 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1027 function handlePending( module
) {
1028 var j
, job
, hasErrors
, m
, stateChange
;
1030 if ( registry
[ module
].state
=== 'error' || registry
[ module
].state
=== 'missing' ) {
1031 // If the current module failed, mark all dependent modules also as failed.
1032 // Iterate until steady-state to propagate the error state upwards in the
1035 stateChange
= false;
1036 for ( m
in registry
) {
1037 if ( registry
[ m
].state
!== 'error' && registry
[ m
].state
!== 'missing' ) {
1038 if ( anyFailed( registry
[ m
].dependencies
) ) {
1039 registry
[ m
].state
= 'error';
1044 } while ( stateChange
);
1047 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1048 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
1049 hasErrors
= anyFailed( jobs
[ j
].dependencies
);
1050 if ( hasErrors
|| allReady( jobs
[ j
].dependencies
) ) {
1051 // All dependencies satisfied, or some have errors
1053 jobs
.splice( j
, 1 );
1057 if ( $.isFunction( job
.error
) ) {
1058 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [ module
] );
1061 if ( $.isFunction( job
.ready
) ) {
1066 // A user-defined callback raised an exception.
1067 // Swallow it to protect our state machine!
1068 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1073 if ( registry
[ module
].state
=== 'ready' ) {
1074 // The current module became 'ready'. Set it in the module store, and recursively execute all
1075 // dependent modules that are loaded and now have all dependencies satisfied.
1076 mw
.loader
.store
.set( module
, registry
[ module
] );
1077 for ( m
in registry
) {
1078 if ( registry
[ m
].state
=== 'loaded' && allReady( registry
[ m
].dependencies
) ) {
1086 * Resolve dependencies and detect circular references.
1089 * @param {string} module Name of the top-level module whose dependencies shall be
1090 * resolved and sorted.
1091 * @param {Array} resolved Returns a topological sort of the given module and its
1092 * dependencies, such that later modules depend on earlier modules. The array
1093 * contains the module names. If the array contains already some module names,
1094 * this function appends its result to the pre-existing array.
1095 * @param {Object} [unresolved] Hash used to track the current dependency
1096 * chain; used to report loops in the dependency graph.
1097 * @throws {Error} If any unregistered module or a dependency loop is encountered
1099 function sortDependencies( module
, resolved
, unresolved
) {
1100 var n
, deps
, len
, skip
;
1102 if ( !hasOwn
.call( registry
, module
) ) {
1103 throw new Error( 'Unknown dependency: ' + module
);
1106 if ( registry
[ module
].skip
!== null ) {
1107 /*jshint evil:true */
1108 skip
= new Function( registry
[ module
].skip
);
1109 registry
[ module
].skip
= null;
1111 registry
[ module
].skipped
= true;
1112 registry
[ module
].dependencies
= [];
1113 registry
[ module
].state
= 'ready';
1114 handlePending( module
);
1119 // Resolves dynamic loader function and replaces it with its own results
1120 if ( $.isFunction( registry
[ module
].dependencies
) ) {
1121 registry
[ module
].dependencies
= registry
[ module
].dependencies();
1122 // Ensures the module's dependencies are always in an array
1123 if ( typeof registry
[ module
].dependencies
!== 'object' ) {
1124 registry
[ module
].dependencies
= [ registry
[ module
].dependencies
];
1127 if ( $.inArray( module
, resolved
) !== -1 ) {
1128 // Module already resolved; nothing to do
1131 // Create unresolved if not passed in
1132 if ( !unresolved
) {
1135 // Tracks down dependencies
1136 deps
= registry
[ module
].dependencies
;
1138 for ( n
= 0; n
< len
; n
+= 1 ) {
1139 if ( $.inArray( deps
[ n
], resolved
) === -1 ) {
1140 if ( unresolved
[ deps
[ n
] ] ) {
1142 'Circular reference detected: ' + module
+
1147 // Add to unresolved
1148 unresolved
[ module
] = true;
1149 sortDependencies( deps
[ n
], resolved
, unresolved
);
1150 delete unresolved
[ module
];
1153 resolved
[ resolved
.length
] = module
;
1157 * Get a list of module names that a module depends on in their proper dependency
1161 * @param {string[]} modules Array of string module names
1162 * @return {Array} List of dependencies, including 'module'.
1164 function resolve( modules
) {
1166 $.each( modules
, function ( idx
, module
) {
1167 sortDependencies( module
, resolved
);
1173 * Load and execute a script with callback.
1176 * @param {string} src URL to script, will be used as the src attribute in the script tag
1177 * @return {jQuery.Promise}
1179 function addScript( src
) {
1183 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1184 // XHR for a same domain request instead of <script>, which changes the request
1185 // headers (potentially missing a cache hit), and reduces caching in general
1186 // since browsers cache XHR much less (if at all). And XHR means we retreive
1187 // text, so we'd need to $.globalEval, which then messes up line numbers.
1194 * Utility function for execute()
1198 function addLink( media
, url
) {
1199 var el
= document
.createElement( 'link' );
1201 // Insert in document *before* setting href
1202 getMarker().before( el
);
1203 el
.rel
= 'stylesheet';
1204 if ( media
&& media
!== 'all' ) {
1207 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1208 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1213 * Executes a loaded module, making it ready to use
1216 * @param {string} module Module name to execute
1218 function execute( module
) {
1219 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
, runScript
,
1220 cssHandlesRegistered
= false;
1222 if ( !hasOwn
.call( registry
, module
) ) {
1223 throw new Error( 'Module has not been registered yet: ' + module
);
1225 if ( registry
[ module
].state
!== 'loaded' ) {
1226 throw new Error( 'Module in state "' + registry
[ module
].state
+ '" may not be executed: ' + module
);
1229 registry
[ module
].state
= 'executing';
1231 runScript = function () {
1232 var script
, markModuleReady
, nestedAddScript
, legacyWait
,
1233 // Expand to include dependencies since we have to exclude both legacy modules
1234 // and their dependencies from the legacyWait (to prevent a circular dependency).
1235 legacyModules
= resolve( mw
.config
.get( 'wgResourceLoaderLegacyModules', [] ) );
1237 script
= registry
[ module
].script
;
1238 markModuleReady = function () {
1239 registry
[ module
].state
= 'ready';
1240 handlePending( module
);
1242 nestedAddScript = function ( arr
, callback
, i
) {
1243 // Recursively call addScript() in its own callback
1244 // for each element of arr.
1245 if ( i
>= arr
.length
) {
1246 // We're at the end of the array
1251 addScript( arr
[ i
] ).always( function () {
1252 nestedAddScript( arr
, callback
, i
+ 1 );
1256 legacyWait
= ( $.inArray( module
, legacyModules
) !== -1 )
1257 ? $.Deferred().resolve()
1258 : mw
.loader
.using( legacyModules
);
1260 legacyWait
.always( function () {
1261 if ( $.isArray( script
) ) {
1262 nestedAddScript( script
, markModuleReady
, 0 );
1263 } else if ( $.isFunction( script
) ) {
1264 // Pass jQuery twice so that the signature of the closure which wraps
1265 // the script can bind both '$' and 'jQuery'.
1268 } else if ( typeof script
=== 'string' ) {
1269 // Site and user modules are a legacy scripts that run in the global scope.
1270 // This is transported as a string instead of a function to avoid needing
1271 // to use string manipulation to undo the function wrapper.
1272 if ( module
=== 'user' ) {
1273 // Implicit dependency on the site module. Not real dependency because
1274 // it should run after 'site' regardless of whether it succeeds or fails.
1275 mw
.loader
.using( 'site' ).always( function () {
1276 $.globalEval( script
);
1280 $.globalEval( script
);
1284 // Module without script
1289 // This needs to NOT use mw.log because these errors are common in production mode
1290 // and not in debug mode, such as when a symbol that should be global isn't exported
1291 registry
[ module
].state
= 'error';
1292 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1293 handlePending( module
);
1297 // Add localizations to message system
1298 if ( registry
[ module
].messages
) {
1299 mw
.messages
.set( registry
[ module
].messages
);
1302 // Initialise templates
1303 if ( registry
[ module
].templates
) {
1304 mw
.templates
.set( module
, registry
[ module
].templates
);
1307 // Make sure we don't run the scripts until all stylesheet insertions have completed.
1310 checkCssHandles = function () {
1311 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1312 // one of the cssHandles is fired while we're still creating more handles.
1313 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1315 runScript
= undefined; // Revoke
1318 cssHandle = function () {
1319 var check
= checkCssHandles
;
1321 return function () {
1325 check
= undefined; // Revoke
1331 // Process styles (see also mw.loader.implement)
1332 // * back-compat: { <media>: css }
1333 // * back-compat: { <media>: [url, ..] }
1334 // * { "css": [css, ..] }
1335 // * { "url": { <media>: [url, ..] } }
1336 if ( registry
[ module
].style
) {
1337 for ( key
in registry
[ module
].style
) {
1338 value
= registry
[ module
].style
[ key
];
1341 if ( key
!== 'url' && key
!== 'css' ) {
1342 // Backwards compatibility, key is a media-type
1343 if ( typeof value
=== 'string' ) {
1344 // back-compat: { <media>: css }
1345 // Ignore 'media' because it isn't supported (nor was it used).
1346 // Strings are pre-wrapped in "@media". The media-type was just ""
1347 // (because it had to be set to something).
1348 // This is one of the reasons why this format is no longer used.
1349 addEmbeddedCSS( value
, cssHandle() );
1351 // back-compat: { <media>: [url, ..] }
1357 // Array of css strings in key 'css',
1358 // or back-compat array of urls from media-type
1359 if ( $.isArray( value
) ) {
1360 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
1361 if ( key
=== 'bc-url' ) {
1362 // back-compat: { <media>: [url, ..] }
1363 addLink( media
, value
[ i
] );
1364 } else if ( key
=== 'css' ) {
1365 // { "css": [css, ..] }
1366 addEmbeddedCSS( value
[ i
], cssHandle() );
1369 // Not an array, but a regular object
1370 // Array of urls inside media-type key
1371 } else if ( typeof value
=== 'object' ) {
1372 // { "url": { <media>: [url, ..] } }
1373 for ( media
in value
) {
1374 urls
= value
[ media
];
1375 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
1376 addLink( media
, urls
[ i
] );
1384 cssHandlesRegistered
= true;
1389 * Adds a dependencies to the queue with optional callbacks to be run
1390 * when the dependencies are ready or fail
1393 * @param {string|string[]} dependencies Module name or array of string module names
1394 * @param {Function} [ready] Callback to execute when all dependencies are ready
1395 * @param {Function} [error] Callback to execute when any dependency fails
1397 function request( dependencies
, ready
, error
) {
1398 // Allow calling by single module name
1399 if ( typeof dependencies
=== 'string' ) {
1400 dependencies
= [ dependencies
];
1403 // Add ready and error callbacks if they were given
1404 if ( ready
!== undefined || error
!== undefined ) {
1406 // Narrow down the list to modules that are worth waiting for
1407 dependencies
: $.grep( dependencies
, function ( module
) {
1408 var state
= mw
.loader
.getState( module
);
1409 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading' || state
=== 'executing';
1416 $.each( dependencies
, function ( idx
, module
) {
1417 var state
= mw
.loader
.getState( module
);
1418 // Only queue modules that are still in the initial 'registered' state
1419 // (not ones already loading, ready or error).
1420 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1421 // Private modules must be embedded in the page. Don't bother queuing
1422 // these as the server will deny them anyway (T101806).
1423 if ( registry
[ module
].group
=== 'private' ) {
1424 registry
[ module
].state
= 'error';
1425 handlePending( module
);
1428 queue
.push( module
);
1435 function sortQuery( o
) {
1441 if ( hasOwn
.call( o
, key
) ) {
1446 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1447 sorted
[ a
[ key
] ] = o
[ a
[ key
] ];
1453 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1454 * to a query string of the form foo.bar,baz|bar.baz,quux
1458 function buildModulesString( moduleMap
) {
1462 for ( prefix
in moduleMap
) {
1463 p
= prefix
=== '' ? '' : prefix
+ '.';
1464 arr
.push( p
+ moduleMap
[ prefix
].join( ',' ) );
1466 return arr
.join( '|' );
1470 * Load modules from load.php
1473 * @param {Object} moduleMap Module map, see #buildModulesString
1474 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1475 * @param {string} sourceLoadScript URL of load.php
1477 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
) {
1478 var request
= $.extend(
1479 { modules
: buildModulesString( moduleMap
) },
1482 request
= sortQuery( request
);
1483 addScript( sourceLoadScript
+ '?' + $.param( request
) );
1487 * Resolve indexed dependencies.
1489 * ResourceLoader uses an optimization to save space which replaces module names in
1490 * dependency lists with the index of that module within the array of module
1491 * registration data if it exists. The benefit is a significant reduction in the data
1492 * size of the startup module. This function changes those dependency lists back to
1493 * arrays of strings.
1495 * @param {Array} modules Modules array
1497 function resolveIndexedDependencies( modules
) {
1498 $.each( modules
, function ( idx
, module
) {
1499 if ( module
[ 2 ] ) {
1500 module
[ 2 ] = $.map( module
[ 2 ], function ( dep
) {
1501 return typeof dep
=== 'number' ? modules
[ dep
][ 0 ] : dep
;
1507 /* Public Members */
1510 * The module registry is exposed as an aid for debugging and inspecting page
1511 * state; it is not a public interface for modifying the registry.
1517 moduleRegistry
: registry
,
1520 * @inheritdoc #newStyleTag
1523 addStyleTag
: newStyleTag
,
1526 * Batch-request queued dependencies from the server.
1529 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1530 source
, concatSource
, origBatch
, group
, i
, modules
, sourceLoadScript
,
1531 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1532 lastDotIndex
, prefix
, suffix
, bytesAdded
;
1534 // Build a list of request parameters common to all requests.
1536 skin
: mw
.config
.get( 'skin' ),
1537 lang
: mw
.config
.get( 'wgUserLanguage' ),
1538 debug
: mw
.config
.get( 'debug' )
1540 // Split module batch by source and by group.
1542 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1544 // Appends a list of modules from the queue to the batch
1545 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1546 // Only request modules which are registered
1547 if ( hasOwn
.call( registry
, queue
[ q
] ) && registry
[ queue
[ q
] ].state
=== 'registered' ) {
1548 // Prevent duplicate entries
1549 if ( $.inArray( queue
[ q
], batch
) === -1 ) {
1550 batch
[ batch
.length
] = queue
[ q
];
1551 // Mark registered modules as loading
1552 registry
[ queue
[ q
] ].state
= 'loading';
1557 mw
.loader
.store
.init();
1558 if ( mw
.loader
.store
.enabled
) {
1561 batch
= $.grep( batch
, function ( module
) {
1562 var source
= mw
.loader
.store
.get( module
);
1564 concatSource
.push( source
);
1570 $.globalEval( concatSource
.join( ';' ) );
1572 // Not good, the cached mw.loader.implement calls failed! This should
1573 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1574 // Depending on how corrupt the string is, it is likely that some
1575 // modules' implement() succeeded while the ones after the error will
1576 // never run and leave their modules in the 'loading' state forever.
1578 // Since this is an error not caused by an individual module but by
1579 // something that infected the implement call itself, don't take any
1580 // risks and clear everything in this cache.
1581 mw
.loader
.store
.clear();
1582 // Re-add the ones still pending back to the batch and let the server
1583 // repopulate these modules to the cache.
1584 // This means that at most one module will be useless (the one that had
1585 // the error) instead of all of them.
1586 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1587 origBatch
= $.grep( origBatch
, function ( module
) {
1588 return registry
[ module
].state
=== 'loading';
1590 batch
= batch
.concat( origBatch
);
1594 // Early exit if there's nothing to load...
1595 if ( !batch
.length
) {
1599 // The queue has been processed into the batch, clear up the queue.
1602 // Always order modules alphabetically to help reduce cache
1603 // misses for otherwise identical content.
1606 // Split batch by source and by group.
1607 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1608 bSource
= registry
[ batch
[ b
] ].source
;
1609 bGroup
= registry
[ batch
[ b
] ].group
;
1610 if ( !hasOwn
.call( splits
, bSource
) ) {
1611 splits
[ bSource
] = {};
1613 if ( !hasOwn
.call( splits
[ bSource
], bGroup
) ) {
1614 splits
[ bSource
][ bGroup
] = [];
1616 bSourceGroup
= splits
[ bSource
][ bGroup
];
1617 bSourceGroup
[ bSourceGroup
.length
] = batch
[ b
];
1620 // Clear the batch - this MUST happen before we append any
1621 // script elements to the body or it's possible that a script
1622 // will be locally cached, instantly load, and work the batch
1623 // again, all before we've cleared it causing each request to
1624 // include modules which are already loaded.
1627 for ( source
in splits
) {
1629 sourceLoadScript
= sources
[ source
];
1631 for ( group
in splits
[ source
] ) {
1633 // Cache access to currently selected list of
1634 // modules for this group from this source.
1635 modules
= splits
[ source
][ group
];
1637 currReqBase
= $.extend( {
1638 version
: getCombinedVersion( modules
)
1640 // For user modules append a user name to the request.
1641 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1642 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1644 currReqBaseLength
= $.param( currReqBase
).length
;
1645 // We may need to split up the request to honor the query string length limit,
1646 // so build it piece by piece.
1647 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1649 moduleMap
= {}; // { prefix: [ suffixes ] }
1651 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1652 // Determine how many bytes this module would add to the query string
1653 lastDotIndex
= modules
[ i
].lastIndexOf( '.' );
1655 // If lastDotIndex is -1, substr() returns an empty string
1656 prefix
= modules
[ i
].substr( 0, lastDotIndex
);
1657 suffix
= modules
[ i
].slice( lastDotIndex
+ 1 );
1659 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1660 ? suffix
.length
+ 3 // '%2C'.length == 3
1661 : modules
[ i
].length
+ 3; // '%7C'.length == 3
1663 // If the request would become too long, create a new one,
1664 // but don't create empty requests
1665 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1666 // This request would become too long, create a new one
1667 // and fire off the old one
1668 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1670 l
= currReqBaseLength
+ 9;
1671 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1673 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1674 moduleMap
[ prefix
] = [];
1676 moduleMap
[ prefix
].push( suffix
);
1679 // If there's anything left in moduleMap, request that too
1680 if ( !$.isEmptyObject( moduleMap
) ) {
1681 doRequest( moduleMap
, currReqBase
, sourceLoadScript
);
1688 * Register a source.
1690 * The #work method will use this information to split up requests by source.
1692 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1694 * @param {string} id Short string representing a source wiki, used internally for
1695 * registered modules to indicate where they should be loaded from (usually lowercase a-z).
1696 * @param {Object|string} loadUrl load.php url, may be an object for backwards-compatibility
1699 addSource: function ( id
, loadUrl
) {
1701 // Allow multiple additions
1702 if ( typeof id
=== 'object' ) {
1703 for ( source
in id
) {
1704 mw
.loader
.addSource( source
, id
[ source
] );
1709 if ( hasOwn
.call( sources
, id
) ) {
1710 throw new Error( 'source already registered: ' + id
);
1713 if ( typeof loadUrl
=== 'object' ) {
1714 loadUrl
= loadUrl
.loadScript
;
1717 sources
[ id
] = loadUrl
;
1723 * Register a module, letting the system know about it and its properties.
1725 * The startup modules contain calls to this method.
1727 * When using multiple module registration by passing an array, dependencies that
1728 * are specified as references to modules within the array will be resolved before
1729 * the modules are registered.
1731 * @param {string|Array} module Module name or array of arrays, each containing
1732 * a list of arguments compatible with this method
1733 * @param {string|number} version Module version hash (falls backs to empty string)
1734 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1735 * @param {string|Array|Function} dependencies One string or array of strings of module
1736 * names on which this module depends, or a function that returns that array.
1737 * @param {string} [group=null] Group which the module is in
1738 * @param {string} [source='local'] Name of the source
1739 * @param {string} [skip=null] Script body of the skip function
1741 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1743 // Allow multiple registration
1744 if ( typeof module
=== 'object' ) {
1745 resolveIndexedDependencies( module
);
1746 for ( i
= 0, len
= module
.length
; i
< len
; i
++ ) {
1747 // module is an array of module names
1748 if ( typeof module
[ i
] === 'string' ) {
1749 mw
.loader
.register( module
[ i
] );
1750 // module is an array of arrays
1751 } else if ( typeof module
[ i
] === 'object' ) {
1752 mw
.loader
.register
.apply( mw
.loader
, module
[ i
] );
1758 if ( typeof module
!== 'string' ) {
1759 throw new Error( 'module must be a string, not a ' + typeof module
);
1761 if ( hasOwn
.call( registry
, module
) ) {
1762 throw new Error( 'module already registered: ' + module
);
1764 // List the module as registered
1765 registry
[ module
] = {
1766 version
: version
!== undefined ? String( version
) : '',
1768 group
: typeof group
=== 'string' ? group
: null,
1769 source
: typeof source
=== 'string' ? source
: 'local',
1770 state
: 'registered',
1771 skip
: typeof skip
=== 'string' ? skip
: null
1773 if ( typeof dependencies
=== 'string' ) {
1774 // Allow dependencies to be given as a single module name
1775 registry
[ module
].dependencies
= [ dependencies
];
1776 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1777 // Allow dependencies to be given as an array of module names
1778 // or a function which returns an array
1779 registry
[ module
].dependencies
= dependencies
;
1784 * Implement a module given the components that make up the module.
1786 * When #load or #using requests one or more modules, the server
1787 * response contain calls to this function.
1789 * All arguments are required.
1791 * @param {string} module Name of module
1792 * @param {Function|Array} script Function with module code or Array of URLs to
1793 * be used as the src attribute of a new `<script>` tag.
1794 * @param {Object} [style] Should follow one of the following patterns:
1796 * { "css": [css, ..] }
1797 * { "url": { <media>: [url, ..] } }
1799 * And for backwards compatibility (needs to be supported forever due to caching):
1802 * { <media>: [url, ..] }
1804 * The reason css strings are not concatenated anymore is bug 31676. We now check
1805 * whether it's safe to extend the stylesheet.
1807 * @param {Object} [messages] List of key/value pairs to be added to mw#messages.
1808 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1810 implement: function ( module
, script
, style
, messages
, templates
) {
1812 if ( typeof module
!== 'string' ) {
1813 throw new Error( 'module must be of type string, not ' + typeof module
);
1815 if ( script
&& !$.isFunction( script
) && !$.isArray( script
) && typeof script
!== 'string' ) {
1816 throw new Error( 'script must be of type function, array, or script; not ' + typeof script
);
1818 if ( style
&& !$.isPlainObject( style
) ) {
1819 throw new Error( 'style must be of type object, not ' + typeof style
);
1821 if ( messages
&& !$.isPlainObject( messages
) ) {
1822 throw new Error( 'messages must be of type object, not a ' + typeof messages
);
1824 if ( templates
&& !$.isPlainObject( templates
) ) {
1825 throw new Error( 'templates must be of type object, not a ' + typeof templates
);
1827 // Automatically register module
1828 if ( !hasOwn
.call( registry
, module
) ) {
1829 mw
.loader
.register( module
);
1831 // Check for duplicate implementation
1832 if ( hasOwn
.call( registry
, module
) && registry
[ module
].script
!== undefined ) {
1833 throw new Error( 'module already implemented: ' + module
);
1835 // Attach components
1836 registry
[ module
].script
= script
|| null;
1837 registry
[ module
].style
= style
|| null;
1838 registry
[ module
].messages
= messages
|| null;
1839 registry
[ module
].templates
= templates
|| null;
1840 // The module may already have been marked as erroneous
1841 if ( $.inArray( registry
[ module
].state
, [ 'error', 'missing' ] ) === -1 ) {
1842 registry
[ module
].state
= 'loaded';
1843 if ( allReady( registry
[ module
].dependencies
) ) {
1850 * Execute a function as soon as one or more required modules are ready.
1852 * Example of inline dependency on OOjs:
1854 * mw.loader.using( 'oojs', function () {
1855 * OO.compare( [ 1 ], [ 1 ] );
1858 * @param {string|Array} dependencies Module name or array of modules names the callback
1859 * dependends on to be ready before executing
1860 * @param {Function} [ready] Callback to execute when all dependencies are ready
1861 * @param {Function} [error] Callback to execute if one or more dependencies failed
1862 * @return {jQuery.Promise}
1863 * @since 1.23 this returns a promise
1865 using: function ( dependencies
, ready
, error
) {
1866 var deferred
= $.Deferred();
1868 // Allow calling with a single dependency as a string
1869 if ( typeof dependencies
=== 'string' ) {
1870 dependencies
= [ dependencies
];
1871 } else if ( !$.isArray( dependencies
) ) {
1873 throw new Error( 'Dependencies must be a string or an array' );
1877 deferred
.done( ready
);
1880 deferred
.fail( error
);
1883 // Resolve entire dependency map
1884 dependencies
= resolve( dependencies
);
1885 if ( allReady( dependencies
) ) {
1886 // Run ready immediately
1888 } else if ( anyFailed( dependencies
) ) {
1889 // Execute error immediately if any dependencies have errors
1891 new Error( 'One or more dependencies failed to load' ),
1895 // Not all dependencies are ready: queue up a request
1896 request( dependencies
, deferred
.resolve
, deferred
.reject
);
1899 return deferred
.promise();
1903 * Load an external script or one or more modules.
1905 * @param {string|Array} modules Either the name of a module, array of modules,
1906 * or a URL of an external script or style
1907 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1908 * external script or style; acceptable values are "text/css" and
1909 * "text/javascript"; if no type is provided, text/javascript is assumed.
1911 load: function ( modules
, type
) {
1915 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1916 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1918 // Allow calling with a url or single dependency as a string
1919 if ( typeof modules
=== 'string' ) {
1920 // "https://example.org/x.js", "http://example.org/x.js", "//example.org/x.js", "/x.js"
1921 if ( /^(https?:)?\/?\//.test( modules
) ) {
1922 if ( type
=== 'text/css' ) {
1924 // Use properties instead of attributes as IE throws security
1925 // warnings when inserting a <link> tag with a protocol-relative
1926 // URL set though attributes - when on HTTPS. See bug 41331.
1927 l
= document
.createElement( 'link' );
1928 l
.rel
= 'stylesheet';
1930 $( 'head' ).append( l
);
1933 if ( type
=== 'text/javascript' || type
=== undefined ) {
1934 addScript( modules
);
1938 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1940 // Called with single module
1941 modules
= [ modules
];
1944 // Filter out undefined modules, otherwise resolve() will throw
1945 // an exception for trying to load an undefined module.
1946 // Undefined modules are acceptable here in load(), because load() takes
1947 // an array of unrelated modules, whereas the modules passed to
1948 // using() are related and must all be loaded.
1949 filtered
= $.grep( modules
, function ( module
) {
1950 var state
= mw
.loader
.getState( module
);
1951 return state
!== null && state
!== 'error' && state
!== 'missing';
1954 if ( filtered
.length
=== 0 ) {
1957 // Resolve entire dependency map
1958 filtered
= resolve( filtered
);
1959 // If all modules are ready, or if any modules have errors, nothing to be done.
1960 if ( allReady( filtered
) || anyFailed( filtered
) ) {
1963 // Since some modules are not yet ready, queue up a request.
1964 request( filtered
, undefined, undefined );
1968 * Change the state of one or more modules.
1970 * @param {string|Object} module Module name or object of module name/state pairs
1971 * @param {string} state State name
1973 state: function ( module
, state
) {
1976 if ( typeof module
=== 'object' ) {
1977 for ( m
in module
) {
1978 mw
.loader
.state( m
, module
[ m
] );
1982 if ( !hasOwn
.call( registry
, module
) ) {
1983 mw
.loader
.register( module
);
1985 if ( $.inArray( state
, [ 'ready', 'error', 'missing' ] ) !== -1
1986 && registry
[ module
].state
!== state
) {
1987 // Make sure pending modules depending on this one get executed if their
1988 // dependencies are now fulfilled!
1989 registry
[ module
].state
= state
;
1990 handlePending( module
);
1992 registry
[ module
].state
= state
;
1997 * Get the version of a module.
1999 * @param {string} module Name of module
2000 * @return {string|null} The version, or null if the module (or its version) is not
2003 getVersion: function ( module
) {
2004 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].version
=== undefined ) {
2007 return registry
[ module
].version
;
2011 * Get the state of a module.
2013 * @param {string} module Name of module
2014 * @return {string|null} The state, or null if the module (or its state) is not
2017 getState: function ( module
) {
2018 if ( !hasOwn
.call( registry
, module
) || registry
[ module
].state
=== undefined ) {
2021 return registry
[ module
].state
;
2025 * Get the names of all registered modules.
2029 getModuleNames: function () {
2030 return $.map( registry
, function ( i
, key
) {
2036 * @inheritdoc mw.inspect#runReports
2039 inspect: function () {
2040 var args
= slice
.call( arguments
);
2041 mw
.loader
.using( 'mediawiki.inspect', function () {
2042 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2047 * On browsers that implement the localStorage API, the module store serves as a
2048 * smart complement to the browser cache. Unlike the browser cache, the module store
2049 * can slice a concatenated response from ResourceLoader into its constituent
2050 * modules and cache each of them separately, using each module's versioning scheme
2051 * to determine when the cache should be invalidated.
2054 * @class mw.loader.store
2057 // Whether the store is in use on this page.
2060 // Modules whose string representation exceeds 100 kB are ineligible
2061 // for storage due to bug T66721.
2062 MODULE_SIZE_MAX
: 100000,
2064 // The contents of the store, mapping '[module name]@[version]' keys
2065 // to module implementations.
2069 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2072 * Construct a JSON-serializable object representing the content of the store.
2074 * @return {Object} Module store contents.
2076 toJSON: function () {
2077 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2081 * Get the localStorage key for the entire module store. The key references
2082 * $wgDBname to prevent clashes between wikis which share a common host.
2084 * @return {string} localStorage item key
2086 getStoreKey: function () {
2087 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2091 * Get a key on which to vary the module cache.
2093 * @return {string} String of concatenated vary conditions.
2095 getVary: function () {
2097 mw
.config
.get( 'skin' ),
2098 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2099 mw
.config
.get( 'wgUserLanguage' )
2104 * Get a key for a specific module. The key format is '[name]@[version]'.
2106 * @param {string} module Module name
2107 * @return {string|null} Module key or null if module does not exist
2109 getModuleKey: function ( module
) {
2110 return hasOwn
.call( registry
, module
) ?
2111 ( module
+ '@' + registry
[ module
].version
) : null;
2115 * Initialize the store.
2117 * Retrieves store from localStorage and (if successfully retrieved) decoding
2118 * the stored JSON value to a plain object.
2120 * The try / catch block is used for JSON & localStorage feature detection.
2121 * See the in-line documentation for Modernizr's localStorage feature detection
2122 * code for a full account of why we need a try / catch:
2123 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2128 if ( mw
.loader
.store
.enabled
!== null ) {
2133 if ( !mw
.config
.get( 'wgResourceLoaderStorageEnabled' ) ) {
2134 // Disabled by configuration.
2135 // Clear any previous store to free up space. (T66721)
2136 mw
.loader
.store
.clear();
2137 mw
.loader
.store
.enabled
= false;
2140 if ( mw
.config
.get( 'debug' ) ) {
2141 // Disable module store in debug mode
2142 mw
.loader
.store
.enabled
= false;
2147 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2148 // If we get here, localStorage is available; mark enabled
2149 mw
.loader
.store
.enabled
= true;
2150 data
= JSON
.parse( raw
);
2151 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2152 mw
.loader
.store
.items
= data
.items
;
2156 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2159 if ( raw
=== undefined ) {
2160 // localStorage failed; disable store
2161 mw
.loader
.store
.enabled
= false;
2163 mw
.loader
.store
.update();
2168 * Retrieve a module from the store and update cache hit stats.
2170 * @param {string} module Module name
2171 * @return {string|boolean} Module implementation or false if unavailable
2173 get: function ( module
) {
2176 if ( !mw
.loader
.store
.enabled
) {
2180 key
= mw
.loader
.store
.getModuleKey( module
);
2181 if ( key
in mw
.loader
.store
.items
) {
2182 mw
.loader
.store
.stats
.hits
++;
2183 return mw
.loader
.store
.items
[ key
];
2185 mw
.loader
.store
.stats
.misses
++;
2190 * Stringify a module and queue it for storage.
2192 * @param {string} module Module name
2193 * @param {Object} descriptor The module's descriptor as set in the registry
2195 set: function ( module
, descriptor
) {
2198 if ( !mw
.loader
.store
.enabled
) {
2202 key
= mw
.loader
.store
.getModuleKey( module
);
2205 // Already stored a copy of this exact version
2206 key
in mw
.loader
.store
.items
||
2207 // Module failed to load
2208 descriptor
.state
!== 'ready' ||
2209 // Unversioned, private, or site-/user-specific
2210 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user' ] ) !== -1 ) ||
2211 // Partial descriptor
2212 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2213 descriptor
.messages
, descriptor
.templates
] ) !== -1
2221 JSON
.stringify( module
),
2222 typeof descriptor
.script
=== 'function' ?
2223 String( descriptor
.script
) :
2224 JSON
.stringify( descriptor
.script
),
2225 JSON
.stringify( descriptor
.style
),
2226 JSON
.stringify( descriptor
.messages
),
2227 JSON
.stringify( descriptor
.templates
)
2229 // Attempted workaround for a possible Opera bug (bug T59567).
2230 // This regex should never match under sane conditions.
2231 if ( /^\s*\(/.test( args
[ 1 ] ) ) {
2232 args
[ 1 ] = 'function' + args
[ 1 ];
2233 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2236 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2240 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2241 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2244 mw
.loader
.store
.items
[ key
] = src
;
2245 mw
.loader
.store
.update();
2249 * Iterate through the module store, removing any item that does not correspond
2250 * (in name and version) to an item in the module registry.
2252 prune: function () {
2255 if ( !mw
.loader
.store
.enabled
) {
2259 for ( key
in mw
.loader
.store
.items
) {
2260 module
= key
.slice( 0, key
.indexOf( '@' ) );
2261 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2262 mw
.loader
.store
.stats
.expired
++;
2263 delete mw
.loader
.store
.items
[ key
];
2264 } else if ( mw
.loader
.store
.items
[ key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2265 // This value predates the enforcement of a size limit on cached modules.
2266 delete mw
.loader
.store
.items
[ key
];
2272 * Clear the entire module store right now.
2274 clear: function () {
2275 mw
.loader
.store
.items
= {};
2276 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2280 * Sync modules to localStorage.
2282 * This function debounces localStorage updates. When called multiple times in
2283 * quick succession, the calls are coalesced into a single update operation.
2284 * This allows us to call #update without having to consider the module load
2285 * queue; the call to localStorage.setItem will be naturally deferred until the
2286 * page is quiescent.
2288 * Because localStorage is shared by all pages with the same origin, if multiple
2289 * pages are loaded with different module sets, the possibility exists that
2290 * modules saved by one page will be clobbered by another. But the impact would
2291 * be minor and the problem would be corrected by subsequent page views.
2295 update
: ( function () {
2300 key
= mw
.loader
.store
.getStoreKey();
2302 if ( !mw
.loader
.store
.enabled
) {
2305 mw
.loader
.store
.prune();
2307 // Replacing the content of the module store might fail if the new
2308 // contents would exceed the browser's localStorage size limit. To
2309 // avoid clogging the browser with stale data, always remove the old
2310 // value before attempting to set the new one.
2311 localStorage
.removeItem( key
);
2312 data
= JSON
.stringify( mw
.loader
.store
);
2313 localStorage
.setItem( key
, data
);
2315 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2319 return function () {
2320 clearTimeout( timer
);
2321 timer
= setTimeout( flush
, 2000 );
2329 * HTML construction helper functions
2336 * output = Html.element( 'div', {}, new Html.Raw(
2337 * Html.element( 'img', { src: '<' } )
2339 * mw.log( output ); // <div><img src="<"/></div>
2344 html
: ( function () {
2345 function escapeCallback( s
) {
2362 * Escape a string for HTML.
2364 * Converts special characters to HTML entities.
2366 * mw.html.escape( '< > \' & "' );
2367 * // Returns < > ' & "
2369 * @param {string} s The string to escape
2370 * @return {string} HTML
2372 escape: function ( s
) {
2373 return s
.replace( /['"<>&]/g, escapeCallback
);
2377 * Create an HTML element string, with safe escaping.
2379 * @param {string} name The tag name.
2380 * @param {Object} [attrs] An object with members mapping element names to values
2381 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
2383 * - string: Text to be escaped.
2384 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
2385 * - this.Raw: The raw value is directly included.
2386 * - this.Cdata: The raw value is directly included. An exception is
2387 * thrown if it contains any illegal ETAGO delimiter.
2388 * See <http://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
2389 * @return {string} HTML
2391 element: function ( name
, attrs
, contents
) {
2392 var v
, attrName
, s
= '<' + name
;
2395 for ( attrName
in attrs
) {
2396 v
= attrs
[ attrName
];
2397 // Convert name=true, to name=name
2401 } else if ( v
=== false ) {
2404 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2407 if ( contents
=== undefined || contents
=== null ) {
2414 switch ( typeof contents
) {
2417 s
+= this.escape( contents
);
2421 // Convert to string
2422 s
+= String( contents
);
2425 if ( contents
instanceof this.Raw
) {
2426 // Raw HTML inclusion
2427 s
+= contents
.value
;
2428 } else if ( contents
instanceof this.Cdata
) {
2430 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2431 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2433 s
+= contents
.value
;
2435 throw new Error( 'mw.html.element: Invalid type of contents' );
2438 s
+= '</' + name
+ '>';
2443 * Wrapper object for raw HTML passed to mw.html.element().
2445 * @class mw.html.Raw
2447 Raw: function ( value
) {
2452 * Wrapper object for CDATA element contents passed to mw.html.element()
2454 * @class mw.html.Cdata
2456 Cdata: function ( value
) {
2462 // Skeleton user object. mediawiki.user.js extends this
2468 // OOUI widgets specific to MediaWiki
2472 * Registry and firing of events.
2474 * MediaWiki has various interface components that are extended, enhanced
2475 * or manipulated in some other way by extensions, gadgets and even
2478 * This framework helps streamlining the timing of when these other
2479 * code paths fire their plugins (instead of using document-ready,
2480 * which can and should be limited to firing only once).
2482 * Features like navigating to other wiki pages, previewing an edit
2483 * and editing itself – without a refresh – can then retrigger these
2484 * hooks accordingly to ensure everything still works as expected.
2488 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2489 * mw.hook( 'wikipage.content' ).fire( $content );
2491 * Handlers can be added and fired for arbitrary event names at any time. The same
2492 * event can be fired multiple times. The last run of an event is memorized
2493 * (similar to `$(document).ready` and `$.Deferred().done`).
2494 * This means if an event is fired, and a handler added afterwards, the added
2495 * function will be fired right away with the last given event data.
2497 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2498 * Thus allowing flexible use and optimal maintainability and authority control.
2499 * You can pass around the `add` and/or `fire` method to another piece of code
2500 * without it having to know the event name (or `mw.hook` for that matter).
2502 * var h = mw.hook( 'bar.ready' );
2503 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2505 * Note: Events are documented with an underscore instead of a dot in the event
2506 * name due to jsduck not supporting dots in that position.
2510 hook
: ( function () {
2514 * Create an instance of mw.hook.
2518 * @param {string} name Name of hook.
2521 return function ( name
) {
2522 var list
= hasOwn
.call( lists
, name
) ?
2524 lists
[ name
] = $.Callbacks( 'memory' );
2528 * Register a hook handler
2530 * @param {...Function} handler Function to bind.
2536 * Unregister a hook handler
2538 * @param {...Function} handler Function to unbind.
2541 remove
: list
.remove
,
2546 * @param {...Mixed} data
2550 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2557 // Alias $j to jQuery for backwards compatibility
2558 // @deprecated since 1.23 Use $ or jQuery instead
2559 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2562 * Log a message to window.console, if possible.
2564 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2565 * also in production mode). Gets console references in each invocation instead of caching the
2566 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2570 * @param {string} topic Stream name passed by mw.track
2571 * @param {Object} data Data passed by mw.track
2572 * @param {Error} [data.exception]
2573 * @param {string} data.source Error source
2574 * @param {string} [data.module] Name of module which caused the error
2576 function log( topic
, data
) {
2579 source
= data
.source
,
2580 module
= data
.module
,
2581 console
= window
.console
;
2583 if ( console
&& console
.log
) {
2584 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2586 msg
+= ' in module ' + module
;
2588 msg
+= ( e
? ':' : '.' );
2591 // If we have an exception object, log it to the error channel to trigger a
2592 // proper stacktraces in browsers that support it. No fallback as we have no browsers
2593 // that don't support error(), but do support log().
2594 if ( e
&& console
.error
) {
2595 console
.error( String( e
), e
);
2600 // Subscribe to error streams
2601 mw
.trackSubscribe( 'resourceloader.exception', log
);
2602 mw
.trackSubscribe( 'resourceloader.assert', log
);
2605 * Fired when all modules associated with the page have finished loading.
2607 * @event resourceloader_loadEnd
2611 var loading
= $.grep( mw
.loader
.getModuleNames(), function ( module
) {
2612 return mw
.loader
.getState( module
) === 'loading';
2614 // In order to use jQuery.when (which stops early if one of the promises got rejected)
2615 // cast any loading failures into successes. We only need a callback, not the module.
2616 loading
= $.map( loading
, function ( module
) {
2617 return mw
.loader
.using( module
).then( null, function () {
2618 return $.Deferred().resolve();
2621 $.when
.apply( $, loading
).then( function () {
2622 mwPerformance
.mark( 'mwLoadEnd' );
2623 mw
.hook( 'resourceloader.loadEnd' ).fire();
2627 // Attach to window and globally alias
2628 window
.mw
= window
.mediaWiki
= mw
;