2 * Base library for MediaWiki.
4 * Exposed globally as `mediaWiki` with `mw` as shortcut.
7 * @alternateClassName mediaWiki
15 hasOwn
= Object
.prototype.hasOwnProperty
,
16 slice
= Array
.prototype.slice
,
17 trackCallbacks
= $.Callbacks( 'memory' ),
22 * Create an object that can be read from or written to from methods that allow
23 * interaction both with single and multiple properties at once.
27 * var collection, query, results;
29 * // Create your address book
30 * collection = new mw.Map();
32 * // This data could be coming from an external source (eg. API/AJAX)
34 * 'John Doe': 'john@example.org',
35 * 'Jane Doe': 'jane@example.org',
36 * 'George van Halen': 'gvanhalen@example.org'
39 * wanted = ['John Doe', 'Jane Doe', 'Daniel Jackson'];
41 * // You can detect missing keys first
42 * if ( !collection.exists( wanted ) ) {
43 * // One or more are missing (in this case: "Daniel Jackson")
44 * mw.log( 'One or more names were not found in your address book' );
47 * // Or just let it give you what it can. Optionally fill in from a default.
48 * results = collection.get( wanted, 'nobody@example.com' );
49 * mw.log( results['Jane Doe'] ); // "jane@example.org"
50 * mw.log( results['Daniel Jackson'] ); // "nobody@example.com"
55 * @param {Object|boolean} [values] The value-baring object to be mapped. Defaults to an
57 * For backwards-compatibility with mw.config, this can also be `true` in which case values
58 * are copied to the Window object as global variables (T72470). Values are copied in
59 * one direction only. Changes to globals are not reflected in the map.
61 function Map( values
) {
62 if ( values
=== true ) {
65 // Override #set to also set the global variable
66 this.set = function ( selection
, value
) {
69 if ( $.isPlainObject( selection
) ) {
70 for ( s
in selection
) {
71 setGlobalMapValue( this, s
, selection
[s
] );
75 if ( typeof selection
=== 'string' && arguments
.length
) {
76 setGlobalMapValue( this, selection
, value
);
85 this.values
= values
|| {};
89 * Alias property to the global object.
95 * @param {Mixed} value
97 function setGlobalMapValue( map
, key
, value
) {
98 map
.values
[key
] = value
;
103 // Deprecation notice for mw.config globals (T58550, T72470)
104 map
=== mw
.config
&& 'Use mw.config instead.'
110 * Get the value of one or more keys.
112 * If called with no arguments, all values are returned.
114 * @param {string|Array} [selection] Key or array of keys to retrieve values for.
115 * @param {Mixed} [fallback=null] Value for keys that don't exist.
116 * @return {Mixed|Object| null} If selection was a string, returns the value,
117 * If selection was an array, returns an object of key/values.
118 * If no selection is passed, the 'values' container is returned. (Beware that,
119 * as is the default in JavaScript, the object is returned by reference.)
121 get: function ( selection
, fallback
) {
123 // If we only do this in the `return` block, it'll fail for the
124 // call to get() from the mutli-selection block.
125 fallback
= arguments
.length
> 1 ? fallback
: null;
127 if ( $.isArray( selection
) ) {
128 selection
= slice
.call( selection
);
130 for ( i
= 0; i
< selection
.length
; i
++ ) {
131 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
136 if ( typeof selection
=== 'string' ) {
137 if ( !hasOwn
.call( this.values
, selection
) ) {
140 return this.values
[selection
];
143 if ( selection
=== undefined ) {
147 // Invalid selection key
152 * Set one or more key/value pairs.
154 * @param {string|Object} selection Key to set value for, or object mapping keys to values
155 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
156 * @return {boolean} True on success, false on failure
158 set: function ( selection
, value
) {
161 if ( $.isPlainObject( selection
) ) {
162 for ( s
in selection
) {
163 this.values
[s
] = selection
[s
];
167 if ( typeof selection
=== 'string' && arguments
.length
> 1 ) {
168 this.values
[selection
] = value
;
175 * Check if one or more keys exist.
177 * @param {Mixed} selection Key or array of keys to check
178 * @return {boolean} True if the key(s) exist
180 exists: function ( selection
) {
183 if ( $.isArray( selection
) ) {
184 for ( s
= 0; s
< selection
.length
; s
++ ) {
185 if ( typeof selection
[s
] !== 'string' || !hasOwn
.call( this.values
, selection
[s
] ) ) {
191 return typeof selection
=== 'string' && hasOwn
.call( this.values
, selection
);
196 * Object constructor for messages.
198 * Similar to the Message class in MediaWiki PHP.
200 * Format defaults to 'text'.
206 * 'hello': 'Hello world',
207 * 'hello-user': 'Hello, $1!',
208 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
211 * obj = new mw.Message( mw.messages, 'hello' );
212 * mw.log( obj.text() );
215 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
216 * mw.log( obj.text() );
217 * // Hello, John Doe!
219 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
220 * mw.log( obj.text() );
221 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
223 * // Using mw.message shortcut
224 * obj = mw.message( 'hello-user', 'John Doe' );
225 * mw.log( obj.text() );
226 * // Hello, John Doe!
228 * // Using mw.msg shortcut
229 * str = mw.msg( 'hello-user', 'John Doe' );
231 * // Hello, John Doe!
233 * // Different formats
234 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
236 * obj.format = 'text';
237 * str = obj.toString();
242 * // Hello, John "Wiki" <3 Doe!
244 * mw.log( obj.escaped() );
245 * // Hello, John "Wiki" <3 Doe!
250 * @param {mw.Map} map Message store
251 * @param {string} key
252 * @param {Array} [parameters]
254 function Message( map
, key
, parameters
) {
255 this.format
= 'text';
258 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
262 Message
.prototype = {
264 * Get parsed contents of the message.
266 * The default parser does simple $N replacements and nothing else.
267 * This may be overridden to provide a more complex message parser.
268 * The primary override is in the mediawiki.jqueryMsg module.
270 * This function will not be called for nonexistent messages.
272 * @return {string} Parsed message
274 parser: function () {
275 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
279 * Add (does not replace) parameters for `N$` placeholder values.
281 * @param {Array} parameters
284 params: function ( parameters
) {
286 for ( i
= 0; i
< parameters
.length
; i
+= 1 ) {
287 this.parameters
.push( parameters
[i
] );
293 * Convert message object to its string form based on current format.
295 * @return {string} Message as a string in the current form, or `<key>` if key
298 toString: function () {
301 if ( !this.exists() ) {
302 // Use <key> as text if key does not exist
303 if ( this.format
=== 'escaped' || this.format
=== 'parse' ) {
304 // format 'escaped' and 'parse' need to have the brackets and key html escaped
305 return mw
.html
.escape( '<' + this.key
+ '>' );
307 return '<' + this.key
+ '>';
310 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
311 text
= this.parser();
314 if ( this.format
=== 'escaped' ) {
315 text
= this.parser();
316 text
= mw
.html
.escape( text
);
323 * Change format to 'parse' and convert message to string
325 * If jqueryMsg is loaded, this parses the message text from wikitext
326 * (where supported) to HTML
328 * Otherwise, it is equivalent to plain.
330 * @return {string} String form of parsed message
333 this.format
= 'parse';
334 return this.toString();
338 * Change format to 'plain' and convert message to string
340 * This substitutes parameters, but otherwise does not change the
343 * @return {string} String form of plain message
346 this.format
= 'plain';
347 return this.toString();
351 * Change format to 'text' and convert message to string
353 * If jqueryMsg is loaded, {{-transformation is done where supported
354 * (such as {{plural:}}, {{gender:}}, {{int:}}).
356 * Otherwise, it is equivalent to plain
358 * @return {string} String form of text message
361 this.format
= 'text';
362 return this.toString();
366 * Change the format to 'escaped' and convert message to string
368 * This is equivalent to using the 'text' format (see #text), then
369 * HTML-escaping the output.
371 * @return {string} String form of html escaped message
373 escaped: function () {
374 this.format
= 'escaped';
375 return this.toString();
379 * Check if a message exists
384 exists: function () {
385 return this.map
.exists( this.key
);
395 * Get the current time, measured in milliseconds since January 1, 1970 (UTC).
397 * On browsers that implement the Navigation Timing API, this function will produce floating-point
398 * values with microsecond precision that are guaranteed to be monotonic. On all other browsers,
399 * it will fall back to using `Date`.
401 * @return {number} Current time
404 var perf
= window
.performance
,
405 navStart
= perf
&& perf
.timing
&& perf
.timing
.navigationStart
;
406 return navStart
&& typeof perf
.now
=== 'function' ?
407 function () { return navStart
+ perf
.now(); } :
408 function () { return +new Date(); };
412 * Format a string. Replace $1, $2 ... $N with positional arguments.
414 * Used by Message#parser().
417 * @param {string} fmt Format string
418 * @param {Mixed...} parameters Values for $N replacements
419 * @return {string} Formatted string
421 format: function ( formatString
) {
422 var parameters
= slice
.call( arguments
, 1 );
423 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
424 var index
= parseInt( match
, 10 ) - 1;
425 return parameters
[index
] !== undefined ? parameters
[index
] : '$' + match
;
430 * Track an analytic event.
432 * This method provides a generic means for MediaWiki JavaScript code to capture state
433 * information for analysis. Each logged event specifies a string topic name that describes
434 * the kind of event that it is. Topic names consist of dot-separated path components,
435 * arranged from most general to most specific. Each path component should have a clear and
436 * well-defined purpose.
438 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
439 * events that match their subcription, including those that fired before the handler was
442 * @param {string} topic Topic name
443 * @param {Object} [data] Data describing the event, encoded as an object
445 track: function ( topic
, data
) {
446 trackQueue
.push( { topic
: topic
, timeStamp
: mw
.now(), data
: data
} );
447 trackCallbacks
.fire( trackQueue
);
451 * Register a handler for subset of analytic events, specified by topic.
453 * Handlers will be called once for each tracked event, including any events that fired before the
454 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
455 * the exact time at which the event fired, a string 'topic' property naming the event, and a
456 * 'data' property which is an object of event-specific data. The event topic and event data are
457 * also passed to the callback as the first and second arguments, respectively.
459 * @param {string} topic Handle events whose name starts with this string prefix
460 * @param {Function} callback Handler to call for each matching tracked event
461 * @param {string} callback.topic
462 * @param {Object} [callback.data]
464 trackSubscribe: function ( topic
, callback
) {
466 function handler( trackQueue
) {
468 for ( ; seen
< trackQueue
.length
; seen
++ ) {
469 event
= trackQueue
[ seen
];
470 if ( event
.topic
.indexOf( topic
) === 0 ) {
471 callback
.call( event
, event
.topic
, event
.data
);
476 trackHandlers
.push( [ handler
, callback
] );
478 trackCallbacks
.add( handler
);
482 * Stop handling events for a particular handler
484 * @param {Function} callback
486 trackUnsubscribe: function ( callback
) {
487 trackHandlers
= $.grep( trackHandlers
, function ( fns
) {
488 if ( fns
[1] === callback
) {
489 trackCallbacks
.remove( fns
[0] );
490 // Ensure the tuple is removed to avoid holding on to closures
497 // Expose Map constructor
500 // Expose Message constructor
504 * Map of configuration values.
506 * Check out [the complete list of configuration values](https://www.mediawiki.org/wiki/Manual:Interface/JavaScript#mw.config)
509 * If `$wgLegacyJavaScriptGlobals` is true, this Map will add its values to the
510 * global `window` object.
512 * @property {mw.Map} config
514 // Dummy placeholder later assigned in ResourceLoaderStartUpModule
518 * Empty object for third-party libraries, for cases where you don't
519 * want to add a new global, or the global is bad and needs containment
527 * Access container for deprecated functionality that can be moved from
528 * from their legacy location and attached to this object (e.g. a global
529 * function that is deprecated and as stop-gap can be exposed through here).
531 * This was reserved for future use but never ended up being used.
533 * @deprecated since 1.22 Let deprecated identifiers keep their original name
534 * and use mw.log#deprecate to create an access container for tracking.
540 * Store for messages.
547 * Store for templates associated with a module.
551 templates
: new Map(),
554 * Get a message object.
556 * Shorcut for `new mw.Message( mw.messages, key, parameters )`.
559 * @param {string} key Key of message to get
560 * @param {Mixed...} parameters Values for $N replacements
561 * @return {mw.Message}
563 message: function ( key
) {
564 var parameters
= slice
.call( arguments
, 1 );
565 return new Message( mw
.messages
, key
, parameters
);
569 * Get a message string using the (default) 'text' format.
571 * Shortcut for `mw.message( key, parameters... ).text()`.
574 * @param {string} key Key of message to get
575 * @param {Mixed...} parameters Values for $N replacements
579 return mw
.message
.apply( mw
.message
, arguments
).toString();
583 * Dummy placeholder for {@link mw.log}
587 // Also update the restoration of methods in mediawiki.log.js
588 // when adding or removing methods here.
589 var log = function () {};
597 * Write a message the console's warning channel.
598 * Actions not supported by the browser console are silently ignored.
600 * @param {string...} msg Messages to output to console
602 log
.warn = function () {
603 var console
= window
.console
;
604 if ( console
&& console
.warn
&& console
.warn
.apply
) {
605 console
.warn
.apply( console
, arguments
);
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 = function () {
619 var console
= window
.console
;
620 if ( console
&& console
.error
&& console
.error
.apply
) {
621 console
.error
.apply( console
, arguments
);
626 * Create a property in a host object that, when accessed, will produce
627 * a deprecation warning in the console with backtrace.
629 * @param {Object} obj Host object of deprecated property
630 * @param {string} key Name of property to create in `obj`
631 * @param {Mixed} val The value this property should return when accessed
632 * @param {string} [msg] Optional text to include in the deprecation message
634 log
.deprecate
= !Object
.defineProperty
? function ( obj
, key
, val
) {
636 } : function ( obj
, key
, val
, msg
) {
637 msg
= 'Use of "' + key
+ '" is deprecated.' + ( msg
? ( ' ' + msg
) : '' );
639 // Can throw on Object.defineProperty.
641 Object
.defineProperty( obj
, key
, {
645 mw
.track( 'mw.deprecate', key
);
649 set: function ( newVal
) {
650 mw
.track( 'mw.deprecate', key
);
656 // Fallback to creating a copy of the value to the object.
665 * Client for ResourceLoader server end point.
667 * This client is in charge of maintaining the module registry and state
668 * machine, initiating network (batch) requests for loading modules, as
669 * well as dependency resolution and execution of source code.
671 * For more information, refer to
672 * <https://www.mediawiki.org/wiki/ResourceLoader/Features>
677 loader
: ( function () {
680 * Fired via mw.track on various resource loading errors.
682 * @event resourceloader_exception
683 * @param {Error|Mixed} e The error that was thrown. Almost always an Error
684 * object, but in theory module code could manually throw something else, and that
685 * might also end up here.
686 * @param {string} [module] Name of the module which caused the error. Omitted if the
687 * error is not module-related or the module cannot be easily identified due to
689 * @param {string} source Source of the error. Possible values:
691 * - style: stylesheet error (only affects old IE where a special style loading method
693 * - load-callback: exception thrown by user callback
694 * - module-execute: exception thrown by module code
695 * - store-eval: could not evaluate module code cached in localStorage
696 * - store-localstorage-init: localStorage or JSON parse error in mw.loader.store.init
697 * - store-localstorage-json: JSON conversion error in mw.loader.store.set
698 * - store-localstorage-update: localStorage or JSON conversion error in mw.loader.store.update
702 * Fired via mw.track on resource loading error conditions.
704 * @event resourceloader_assert
705 * @param {string} source Source of the error. Possible values:
707 * - bug-T59567: failed to cache script due to an Opera function -> string conversion
708 * bug; see <https://phabricator.wikimedia.org/T59567> for details
712 * Mapping of registered modules.
714 * See #implement for exact details on support for script, style and messages.
720 * // From startup mdoule
721 * 'version': '################' (Hash)
722 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
723 * 'group': 'somegroup', (or) null
724 * 'source': 'local', (or) 'anotherwiki'
725 * 'skip': 'return !!window.Example', (or) null
726 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error', or 'missing'
728 * // Added during implementation
732 * 'messages': { 'key': 'value' }
740 // Mapping of sources, keyed by source-id, values are strings.
745 // 'sourceId': 'http://example.org/w/load.php'
750 // List of modules which will be loaded as when ready
753 // List of modules to be loaded
756 // List of callback functions waiting for modules to be ready to be called
759 // Selector cache for the marker element. Use getMarker() to get/use the marker!
762 // Buffer for #addEmbeddedCSS
765 // Callbacks for #addEmbeddedCSS
766 cssCallbacks
= $.Callbacks();
768 function getMarker() {
771 $marker
= $( 'meta[name="ResourceLoaderDynamicStyles"]' );
772 if ( !$marker
.length
) {
773 mw
.log( 'No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically' );
774 $marker
= $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
781 * Create a new style element and add it to the DOM.
784 * @param {string} text CSS text
785 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag
786 * should be inserted before
787 * @return {HTMLElement} Reference to the created style element
789 function newStyleTag( text
, nextnode
) {
790 var s
= document
.createElement( 'style' );
792 // Must attach to document before setting cssText (bug 33305)
794 $( nextnode
).before( s
);
796 document
.getElementsByTagName( 'head' )[0].appendChild( s
);
798 if ( s
.styleSheet
) {
800 // Old IE ignores appended text nodes, access stylesheet directly.
801 s
.styleSheet
.cssText
= text
;
803 // Standard behaviour
804 s
.appendChild( document
.createTextNode( text
) );
810 * Add a bit of CSS text to the current browser page.
812 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
813 * or create a new one based on whether the given `cssText` is safe for extension.
815 * @param {string} [cssText=cssBuffer] If called without cssText,
816 * the internal buffer will be inserted instead.
817 * @param {Function} [callback]
819 function addEmbeddedCSS( cssText
, callback
) {
822 function fireCallbacks() {
823 var oldCallbacks
= cssCallbacks
;
824 // Reset cssCallbacks variable so it's not polluted by any calls to
825 // addEmbeddedCSS() from one of the callbacks (T105973)
826 cssCallbacks
= $.Callbacks();
827 oldCallbacks
.fire().empty();
831 cssCallbacks
.add( callback
);
834 // Yield once before inserting the <style> tag. There are likely
835 // more calls coming up which we can combine this way.
836 // Appending a stylesheet and waiting for the browser to repaint
837 // is fairly expensive, this reduces that (bug 45810)
839 // Be careful not to extend the buffer with css that needs a new stylesheet.
840 // cssText containing `@import` rules needs to go at the start of a buffer,
841 // since those only work when placed at the start of a stylesheet; bug 35562.
842 if ( !cssBuffer
|| cssText
.slice( 0, '@import'.length
) !== '@import' ) {
843 // Linebreak for somewhat distinguishable sections
844 // (the rl-cachekey comment separating each)
845 cssBuffer
+= '\n' + cssText
;
846 // TODO: Use requestAnimationFrame in the future which will
847 // perform even better by not injecting styles while the browser
849 setTimeout( function () {
850 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
851 // (below version 13) has the non-standard behaviour of passing a
852 // numerical "lateness" value as first argument to this callback
853 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
859 // This is a delayed call and we got a buffer still
860 } else if ( cssBuffer
) {
865 // This is a delayed call, but buffer was already cleared by
866 // another delayed call.
870 // By default, always create a new <style>. Appending text to a <style>
871 // tag is bad as it means the contents have to be re-parsed (bug 45810).
873 // Except, of course, in IE 9 and below. In there we default to re-using and
874 // appending to a <style> tag due to the IE stylesheet limit (bug 31676).
875 if ( 'documentMode' in document
&& document
.documentMode
<= 9 ) {
877 $style
= getMarker().prev();
878 // Verify that the element before the marker actually is a
879 // <style> tag and one that came from ResourceLoader
880 // (not some other style tag or even a `<meta>` or `<script>`).
881 if ( $style
.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
882 // There's already a dynamic <style> tag present and
883 // we are able to append more to it.
884 styleEl
= $style
.get( 0 );
886 if ( styleEl
.styleSheet
) {
888 styleEl
.styleSheet
.cssText
+= cssText
;
890 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'stylesheet' } );
893 styleEl
.appendChild( document
.createTextNode( cssText
) );
900 $( newStyleTag( cssText
, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
907 * @param {Array} modules List of module names
908 * @return {string} Hash of concatenated version hashes.
910 function getCombinedVersion( modules
) {
911 var hashes
= $.map( modules
, function ( module
) {
912 return registry
[module
].version
;
914 // Trim for consistency with server-side ResourceLoader::makeHash. It also helps
915 // save precious space in the limited query string. Otherwise modules are more
916 // likely to require multiple HTTP requests.
917 return sha1( hashes
.join( '' ) ).slice( 0, 12 );
921 * Resolve dependencies and detect circular references.
924 * @param {string} module Name of the top-level module whose dependencies shall be
925 * resolved and sorted.
926 * @param {Array} resolved Returns a topological sort of the given module and its
927 * dependencies, such that later modules depend on earlier modules. The array
928 * contains the module names. If the array contains already some module names,
929 * this function appends its result to the pre-existing array.
930 * @param {Object} [unresolved] Hash used to track the current dependency
931 * chain; used to report loops in the dependency graph.
932 * @throws {Error} If any unregistered module or a dependency loop is encountered
934 function sortDependencies( module
, resolved
, unresolved
) {
935 var n
, deps
, len
, skip
;
937 if ( !hasOwn
.call( registry
, module
) ) {
938 throw new Error( 'Unknown dependency: ' + module
);
941 if ( registry
[module
].skip
!== null ) {
942 /*jshint evil:true */
943 skip
= new Function( registry
[module
].skip
);
944 registry
[module
].skip
= null;
946 registry
[module
].skipped
= true;
947 registry
[module
].dependencies
= [];
948 registry
[module
].state
= 'ready';
949 handlePending( module
);
954 // Resolves dynamic loader function and replaces it with its own results
955 if ( $.isFunction( registry
[module
].dependencies
) ) {
956 registry
[module
].dependencies
= registry
[module
].dependencies();
957 // Ensures the module's dependencies are always in an array
958 if ( typeof registry
[module
].dependencies
!== 'object' ) {
959 registry
[module
].dependencies
= [registry
[module
].dependencies
];
962 if ( $.inArray( module
, resolved
) !== -1 ) {
963 // Module already resolved; nothing to do
966 // Create unresolved if not passed in
970 // Tracks down dependencies
971 deps
= registry
[module
].dependencies
;
973 for ( n
= 0; n
< len
; n
+= 1 ) {
974 if ( $.inArray( deps
[n
], resolved
) === -1 ) {
975 if ( unresolved
[deps
[n
]] ) {
977 'Circular reference detected: ' + module
+
983 unresolved
[module
] = true;
984 sortDependencies( deps
[n
], resolved
, unresolved
);
985 delete unresolved
[module
];
988 resolved
[resolved
.length
] = module
;
992 * Get a list of module names that a module depends on in their proper dependency
996 * @param {string[]} module Array of string module names
997 * @return {Array} List of dependencies, including 'module'.
999 function resolve( modules
) {
1001 $.each( modules
, function ( idx
, module
) {
1002 sortDependencies( module
, resolved
);
1008 * Determine whether all dependencies are in state 'ready', which means we may
1009 * execute the module or job now.
1012 * @param {Array} module Names of modules to be checked
1013 * @return {boolean} True if all modules are in state 'ready', false otherwise
1015 function allReady( modules
) {
1017 for ( i
= 0; i
< modules
.length
; i
++ ) {
1018 if ( mw
.loader
.getState( modules
[i
] ) !== 'ready' ) {
1026 * Determine whether all dependencies are in state 'ready', which means we may
1027 * execute the module or job now.
1030 * @param {Array} modules Names of modules to be checked
1031 * @return {boolean} True if no modules are in state 'error' or 'missing', false otherwise
1033 function anyFailed( modules
) {
1035 for ( i
= 0; i
< modules
.length
; i
++ ) {
1036 state
= mw
.loader
.getState( modules
[i
] );
1037 if ( state
=== 'error' || state
=== 'missing' ) {
1045 * A module has entered state 'ready', 'error', or 'missing'. Automatically update
1046 * pending jobs and modules that depend upon this module. If the given module failed,
1047 * propagate the 'error' state up the dependency tree. Otherwise, go ahead an execute
1048 * all jobs/modules now having their dependencies satisfied.
1050 * Jobs that depend on a failed module, will have their error callback ran (if any).
1053 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
1055 function handlePending( module
) {
1056 var j
, job
, hasErrors
, m
, stateChange
;
1058 if ( registry
[module
].state
=== 'error' || registry
[module
].state
=== 'missing' ) {
1059 // If the current module failed, mark all dependent modules also as failed.
1060 // Iterate until steady-state to propagate the error state upwards in the
1063 stateChange
= false;
1064 for ( m
in registry
) {
1065 if ( registry
[m
].state
!== 'error' && registry
[m
].state
!== 'missing' ) {
1066 if ( anyFailed( registry
[m
].dependencies
) ) {
1067 registry
[m
].state
= 'error';
1072 } while ( stateChange
);
1075 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
1076 for ( j
= 0; j
< jobs
.length
; j
+= 1 ) {
1077 hasErrors
= anyFailed( jobs
[j
].dependencies
);
1078 if ( hasErrors
|| allReady( jobs
[j
].dependencies
) ) {
1079 // All dependencies satisfied, or some have errors
1081 jobs
.splice( j
, 1 );
1085 if ( $.isFunction( job
.error
) ) {
1086 job
.error( new Error( 'Module ' + module
+ ' has failed dependencies' ), [module
] );
1089 if ( $.isFunction( job
.ready
) ) {
1094 // A user-defined callback raised an exception.
1095 // Swallow it to protect our state machine!
1096 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'load-callback' } );
1101 if ( registry
[module
].state
=== 'ready' ) {
1102 // The current module became 'ready'. Set it in the module store, and recursively execute all
1103 // dependent modules that are loaded and now have all dependencies satisfied.
1104 mw
.loader
.store
.set( module
, registry
[module
] );
1105 for ( m
in registry
) {
1106 if ( registry
[m
].state
=== 'loaded' && allReady( registry
[m
].dependencies
) ) {
1114 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
1115 * depending on whether document-ready has occurred yet and whether we are in async mode.
1118 * @param {string} src URL to script, will be used as the src attribute in the script tag
1119 * @param {Function} [callback] Callback which will be run when the script is done
1120 * @param {boolean} [async=false] Whether to load modules asynchronously.
1121 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1123 function addScript( src
, callback
, async
) {
1124 // Using isReady directly instead of storing it locally from a $().ready callback (bug 31895)
1125 if ( $.isReady
|| async
) {
1129 // Force jQuery behaviour to be for crossDomain. Otherwise jQuery would use
1130 // XHR for a same domain request instead of <script>, which changes the request
1131 // headers (potentially missing a cache hit), and reduces caching in general
1132 // since browsers cache XHR much less (if at all). And XHR means we retreive
1133 // text, so we'd need to $.globalEval, which then messes up line numbers.
1137 } ).always( callback
);
1139 /*jshint evil:true */
1140 document
.write( mw
.html
.element( 'script', { 'src': src
}, '' ) );
1142 // Document.write is synchronous, so this is called when it's done.
1143 // FIXME: That's a lie. doc.write isn't actually synchronous.
1150 * Executes a loaded module, making it ready to use
1153 * @param {string} module Module name to execute
1155 function execute( module
) {
1156 var key
, value
, media
, i
, urls
, cssHandle
, checkCssHandles
,
1157 cssHandlesRegistered
= false;
1159 if ( !hasOwn
.call( registry
, module
) ) {
1160 throw new Error( 'Module has not been registered yet: ' + module
);
1161 } else if ( registry
[module
].state
=== 'registered' ) {
1162 throw new Error( 'Module has not been requested from the server yet: ' + module
);
1163 } else if ( registry
[module
].state
=== 'loading' ) {
1164 throw new Error( 'Module has not completed loading yet: ' + module
);
1165 } else if ( registry
[module
].state
=== 'ready' ) {
1166 throw new Error( 'Module has already been executed: ' + module
);
1170 * Define loop-function here for efficiency
1171 * and to avoid re-using badly scoped variables.
1174 function addLink( media
, url
) {
1175 var el
= document
.createElement( 'link' );
1177 // Insert in document *before* setting href
1178 getMarker().before( el
);
1179 el
.rel
= 'stylesheet';
1180 if ( media
&& media
!== 'all' ) {
1183 // If you end up here from an IE exception "SCRIPT: Invalid property value.",
1184 // see #addEmbeddedCSS, bug 31676, and bug 47277 for details.
1188 function runScript() {
1189 var script
, markModuleReady
, nestedAddScript
;
1191 script
= registry
[module
].script
;
1192 markModuleReady = function () {
1193 registry
[module
].state
= 'ready';
1194 handlePending( module
);
1196 nestedAddScript = function ( arr
, callback
, async
, i
) {
1197 // Recursively call addScript() in its own callback
1198 // for each element of arr.
1199 if ( i
>= arr
.length
) {
1200 // We're at the end of the array
1205 addScript( arr
[i
], function () {
1206 nestedAddScript( arr
, callback
, async
, i
+ 1 );
1210 if ( $.isArray( script
) ) {
1211 nestedAddScript( script
, markModuleReady
, registry
[module
].async
, 0 );
1212 } else if ( $.isFunction( script
) ) {
1213 registry
[module
].state
= 'ready';
1214 // Pass jQuery twice so that the signature of the closure which wraps
1215 // the script can bind both '$' and 'jQuery'.
1217 handlePending( module
);
1220 // This needs to NOT use mw.log because these errors are common in production mode
1221 // and not in debug mode, such as when a symbol that should be global isn't exported
1222 registry
[module
].state
= 'error';
1223 mw
.track( 'resourceloader.exception', { exception
: e
, module
: module
, source
: 'module-execute' } );
1224 handlePending( module
);
1228 // This used to be inside runScript, but since that is now fired asychronously
1229 // (after CSS is loaded) we need to set it here right away. It is crucial that
1230 // when execute() is called this is set synchronously, otherwise modules will get
1231 // executed multiple times as the registry will state that it isn't loading yet.
1232 registry
[module
].state
= 'loading';
1234 // Add localizations to message system
1235 if ( $.isPlainObject( registry
[module
].messages
) ) {
1236 mw
.messages
.set( registry
[module
].messages
);
1239 // Initialise templates
1240 if ( registry
[module
].templates
) {
1241 mw
.templates
.set( module
, registry
[module
].templates
);
1244 if ( $.isReady
|| registry
[module
].async
) {
1245 // Make sure we don't run the scripts until all (potentially asynchronous)
1246 // stylesheet insertions have completed.
1249 checkCssHandles = function () {
1250 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
1251 // one of the cssHandles is fired while we're still creating more handles.
1252 if ( cssHandlesRegistered
&& pending
=== 0 && runScript
) {
1254 runScript
= undefined; // Revoke
1257 cssHandle = function () {
1258 var check
= checkCssHandles
;
1260 return function () {
1264 check
= undefined; // Revoke
1270 // We are in blocking mode, and so we can't afford to wait for CSS
1271 cssHandle = function () {};
1273 checkCssHandles
= runScript
;
1276 // Process styles (see also mw.loader.implement)
1277 // * back-compat: { <media>: css }
1278 // * back-compat: { <media>: [url, ..] }
1279 // * { "css": [css, ..] }
1280 // * { "url": { <media>: [url, ..] } }
1281 if ( $.isPlainObject( registry
[module
].style
) ) {
1282 for ( key
in registry
[module
].style
) {
1283 value
= registry
[module
].style
[key
];
1286 if ( key
!== 'url' && key
!== 'css' ) {
1287 // Backwards compatibility, key is a media-type
1288 if ( typeof value
=== 'string' ) {
1289 // back-compat: { <media>: css }
1290 // Ignore 'media' because it isn't supported (nor was it used).
1291 // Strings are pre-wrapped in "@media". The media-type was just ""
1292 // (because it had to be set to something).
1293 // This is one of the reasons why this format is no longer used.
1294 addEmbeddedCSS( value
, cssHandle() );
1296 // back-compat: { <media>: [url, ..] }
1302 // Array of css strings in key 'css',
1303 // or back-compat array of urls from media-type
1304 if ( $.isArray( value
) ) {
1305 for ( i
= 0; i
< value
.length
; i
+= 1 ) {
1306 if ( key
=== 'bc-url' ) {
1307 // back-compat: { <media>: [url, ..] }
1308 addLink( media
, value
[i
] );
1309 } else if ( key
=== 'css' ) {
1310 // { "css": [css, ..] }
1311 addEmbeddedCSS( value
[i
], cssHandle() );
1314 // Not an array, but a regular object
1315 // Array of urls inside media-type key
1316 } else if ( typeof value
=== 'object' ) {
1317 // { "url": { <media>: [url, ..] } }
1318 for ( media
in value
) {
1319 urls
= value
[media
];
1320 for ( i
= 0; i
< urls
.length
; i
+= 1 ) {
1321 addLink( media
, urls
[i
] );
1329 cssHandlesRegistered
= true;
1334 * Adds a dependencies to the queue with optional callbacks to be run
1335 * when the dependencies are ready or fail
1338 * @param {string|string[]} dependencies Module name or array of string module names
1339 * @param {Function} [ready] Callback to execute when all dependencies are ready
1340 * @param {Function} [error] Callback to execute when any dependency fails
1341 * @param {boolean} [async=false] Whether to load modules asynchronously.
1342 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1344 function request( dependencies
, ready
, error
, async
) {
1345 // Allow calling by single module name
1346 if ( typeof dependencies
=== 'string' ) {
1347 dependencies
= [dependencies
];
1350 // Add ready and error callbacks if they were given
1351 if ( ready
!== undefined || error
!== undefined ) {
1352 jobs
[jobs
.length
] = {
1353 dependencies
: $.grep( dependencies
, function ( module
) {
1354 var state
= mw
.loader
.getState( module
);
1355 return state
=== 'registered' || state
=== 'loaded' || state
=== 'loading';
1362 $.each( dependencies
, function ( idx
, module
) {
1363 var state
= mw
.loader
.getState( module
);
1364 // Only queue modules that are still in the initial 'registered' state
1365 // (not ones already loading, ready or error).
1366 if ( state
=== 'registered' && $.inArray( module
, queue
) === -1 ) {
1367 // Private modules must be embedded in the page. Don't bother queuing
1368 // these as the server will deny them anyway (T101806).
1369 if ( registry
[module
].group
=== 'private' ) {
1370 registry
[module
].state
= 'error';
1371 handlePending( module
);
1374 queue
.push( module
);
1376 registry
[module
].async
= true;
1384 function sortQuery( o
) {
1390 if ( hasOwn
.call( o
, key
) ) {
1395 for ( key
= 0; key
< a
.length
; key
+= 1 ) {
1396 sorted
[a
[key
]] = o
[a
[key
]];
1402 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1403 * to a query string of the form foo.bar,baz|bar.baz,quux
1406 function buildModulesString( moduleMap
) {
1410 for ( prefix
in moduleMap
) {
1411 p
= prefix
=== '' ? '' : prefix
+ '.';
1412 arr
.push( p
+ moduleMap
[prefix
].join( ',' ) );
1414 return arr
.join( '|' );
1418 * Asynchronously append a script tag to the end of the body
1419 * that invokes 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
1424 * @param {boolean} async Whether to load modules asynchronously.
1425 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1427 function doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
) {
1428 var request
= $.extend(
1429 { modules
: buildModulesString( moduleMap
) },
1432 request
= sortQuery( request
);
1434 // Append &* to satisfy load.php's WebRequest::checkUrlExtension test. This script
1435 // isn't actually used in IE6, but MediaWiki enforces it in general.
1436 addScript( sourceLoadScript
+ '?' + $.param( request
) + '&*', null, async
);
1440 * Resolve indexed dependencies.
1442 * ResourceLoader uses an optimization to save space which replaces module names in
1443 * dependency lists with the index of that module within the array of module
1444 * registration data if it exists. The benefit is a significant reduction in the data
1445 * size of the startup module. This function changes those dependency lists back to
1446 * arrays of strings.
1448 * @param {Array} modules Modules array
1450 function resolveIndexedDependencies( modules
) {
1451 $.each( modules
, function ( idx
, module
) {
1453 module
[2] = $.map( module
[2], function ( dep
) {
1454 return typeof dep
=== 'number' ? modules
[dep
][0] : dep
;
1460 /* Public Members */
1463 * The module registry is exposed as an aid for debugging and inspecting page
1464 * state; it is not a public interface for modifying the registry.
1470 moduleRegistry
: registry
,
1473 * @inheritdoc #newStyleTag
1476 addStyleTag
: newStyleTag
,
1479 * Batch-request queued dependencies from the server.
1482 var reqBase
, splits
, maxQueryLength
, q
, b
, bSource
, bGroup
, bSourceGroup
,
1483 source
, concatSource
, origBatch
, group
, i
, modules
, sourceLoadScript
,
1484 currReqBase
, currReqBaseLength
, moduleMap
, l
,
1485 lastDotIndex
, prefix
, suffix
, bytesAdded
, async
;
1487 // Build a list of request parameters common to all requests.
1489 skin
: mw
.config
.get( 'skin' ),
1490 lang
: mw
.config
.get( 'wgUserLanguage' ),
1491 debug
: mw
.config
.get( 'debug' )
1493 // Split module batch by source and by group.
1495 maxQueryLength
= mw
.config
.get( 'wgResourceLoaderMaxQueryLength', 2000 );
1497 // Appends a list of modules from the queue to the batch
1498 for ( q
= 0; q
< queue
.length
; q
+= 1 ) {
1499 // Only request modules which are registered
1500 if ( hasOwn
.call( registry
, queue
[q
] ) && registry
[queue
[q
]].state
=== 'registered' ) {
1501 // Prevent duplicate entries
1502 if ( $.inArray( queue
[q
], batch
) === -1 ) {
1503 batch
[batch
.length
] = queue
[q
];
1504 // Mark registered modules as loading
1505 registry
[queue
[q
]].state
= 'loading';
1510 mw
.loader
.store
.init();
1511 if ( mw
.loader
.store
.enabled
) {
1514 batch
= $.grep( batch
, function ( module
) {
1515 var source
= mw
.loader
.store
.get( module
);
1517 concatSource
.push( source
);
1523 $.globalEval( concatSource
.join( ';' ) );
1525 // Not good, the cached mw.loader.implement calls failed! This should
1526 // never happen, barring ResourceLoader bugs, browser bugs and PEBKACs.
1527 // Depending on how corrupt the string is, it is likely that some
1528 // modules' implement() succeeded while the ones after the error will
1529 // never run and leave their modules in the 'loading' state forever.
1531 // Since this is an error not caused by an individual module but by
1532 // something that infected the implement call itself, don't take any
1533 // risks and clear everything in this cache.
1534 mw
.loader
.store
.clear();
1535 // Re-add the ones still pending back to the batch and let the server
1536 // repopulate these modules to the cache.
1537 // This means that at most one module will be useless (the one that had
1538 // the error) instead of all of them.
1539 mw
.track( 'resourceloader.exception', { exception
: err
, source
: 'store-eval' } );
1540 origBatch
= $.grep( origBatch
, function ( module
) {
1541 return registry
[module
].state
=== 'loading';
1543 batch
= batch
.concat( origBatch
);
1547 // Early exit if there's nothing to load...
1548 if ( !batch
.length
) {
1552 // The queue has been processed into the batch, clear up the queue.
1555 // Always order modules alphabetically to help reduce cache
1556 // misses for otherwise identical content.
1559 // Split batch by source and by group.
1560 for ( b
= 0; b
< batch
.length
; b
+= 1 ) {
1561 bSource
= registry
[batch
[b
]].source
;
1562 bGroup
= registry
[batch
[b
]].group
;
1563 if ( !hasOwn
.call( splits
, bSource
) ) {
1564 splits
[bSource
] = {};
1566 if ( !hasOwn
.call( splits
[bSource
], bGroup
) ) {
1567 splits
[bSource
][bGroup
] = [];
1569 bSourceGroup
= splits
[bSource
][bGroup
];
1570 bSourceGroup
[bSourceGroup
.length
] = batch
[b
];
1573 // Clear the batch - this MUST happen before we append any
1574 // script elements to the body or it's possible that a script
1575 // will be locally cached, instantly load, and work the batch
1576 // again, all before we've cleared it causing each request to
1577 // include modules which are already loaded.
1580 for ( source
in splits
) {
1582 sourceLoadScript
= sources
[source
];
1584 for ( group
in splits
[source
] ) {
1586 // Cache access to currently selected list of
1587 // modules for this group from this source.
1588 modules
= splits
[source
][group
];
1590 currReqBase
= $.extend( {
1591 version
: getCombinedVersion( modules
)
1593 // For user modules append a user name to the request.
1594 if ( group
=== 'user' && mw
.config
.get( 'wgUserName' ) !== null ) {
1595 currReqBase
.user
= mw
.config
.get( 'wgUserName' );
1597 currReqBaseLength
= $.param( currReqBase
).length
;
1599 // We may need to split up the request to honor the query string length limit,
1600 // so build it piece by piece.
1601 l
= currReqBaseLength
+ 9; // '&modules='.length == 9
1603 moduleMap
= {}; // { prefix: [ suffixes ] }
1605 for ( i
= 0; i
< modules
.length
; i
+= 1 ) {
1606 // Determine how many bytes this module would add to the query string
1607 lastDotIndex
= modules
[i
].lastIndexOf( '.' );
1609 // If lastDotIndex is -1, substr() returns an empty string
1610 prefix
= modules
[i
].substr( 0, lastDotIndex
);
1611 suffix
= modules
[i
].slice( lastDotIndex
+ 1 );
1613 bytesAdded
= hasOwn
.call( moduleMap
, prefix
)
1614 ? suffix
.length
+ 3 // '%2C'.length == 3
1615 : modules
[i
].length
+ 3; // '%7C'.length == 3
1617 // If the request would become too long, create a new one,
1618 // but don't create empty requests
1619 if ( maxQueryLength
> 0 && !$.isEmptyObject( moduleMap
) && l
+ bytesAdded
> maxQueryLength
) {
1620 // This request would become too long, create a new one
1621 // and fire off the old one
1622 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1625 l
= currReqBaseLength
+ 9;
1626 mw
.track( 'resourceloader.splitRequest', { maxQueryLength
: maxQueryLength
} );
1628 if ( !hasOwn
.call( moduleMap
, prefix
) ) {
1629 moduleMap
[prefix
] = [];
1631 moduleMap
[prefix
].push( suffix
);
1632 if ( !registry
[modules
[i
]].async
) {
1633 // If this module is blocking, make the entire request blocking
1634 // This is slightly suboptimal, but in practice mixing of blocking
1635 // and async modules will only occur in debug mode.
1640 // If there's anything left in moduleMap, request that too
1641 if ( !$.isEmptyObject( moduleMap
) ) {
1642 doRequest( moduleMap
, currReqBase
, sourceLoadScript
, async
);
1649 * Register a source.
1651 * The #work method will use this information to split up requests by source.
1653 * mw.loader.addSource( 'mediawikiwiki', '//www.mediawiki.org/w/load.php' );
1655 * @param {string} id Short string representing a source wiki, used internally for
1656 * registered modules to indicate where they should be loaded from (usually lowercase a-z).
1657 * @param {Object|string} loadUrl load.php url, may be an object for backwards-compatibility
1660 addSource: function ( id
, loadUrl
) {
1662 // Allow multiple additions
1663 if ( typeof id
=== 'object' ) {
1664 for ( source
in id
) {
1665 mw
.loader
.addSource( source
, id
[source
] );
1670 if ( hasOwn
.call( sources
, id
) ) {
1671 throw new Error( 'source already registered: ' + id
);
1674 if ( typeof loadUrl
=== 'object' ) {
1675 loadUrl
= loadUrl
.loadScript
;
1678 sources
[id
] = loadUrl
;
1684 * Register a module, letting the system know about it and its properties.
1686 * The startup modules contain calls to this method.
1688 * When using multiple module registration by passing an array, dependencies that
1689 * are specified as references to modules within the array will be resolved before
1690 * the modules are registered.
1692 * @param {string|Array} module Module name or array of arrays, each containing
1693 * a list of arguments compatible with this method
1694 * @param {string|number} version Module version hash (falls backs to empty string)
1695 * Can also be a number (timestamp) for compatibility with MediaWiki 1.25 and earlier.
1696 * @param {string|Array|Function} dependencies One string or array of strings of module
1697 * names on which this module depends, or a function that returns that array.
1698 * @param {string} [group=null] Group which the module is in
1699 * @param {string} [source='local'] Name of the source
1700 * @param {string} [skip=null] Script body of the skip function
1702 register: function ( module
, version
, dependencies
, group
, source
, skip
) {
1704 // Allow multiple registration
1705 if ( typeof module
=== 'object' ) {
1706 resolveIndexedDependencies( module
);
1707 for ( i
= 0, len
= module
.length
; i
< len
; i
++ ) {
1708 // module is an array of module names
1709 if ( typeof module
[i
] === 'string' ) {
1710 mw
.loader
.register( module
[i
] );
1711 // module is an array of arrays
1712 } else if ( typeof module
[i
] === 'object' ) {
1713 mw
.loader
.register
.apply( mw
.loader
, module
[i
] );
1719 if ( typeof module
!== 'string' ) {
1720 throw new Error( 'module must be a string, not a ' + typeof module
);
1722 if ( hasOwn
.call( registry
, module
) ) {
1723 throw new Error( 'module already registered: ' + module
);
1725 // List the module as registered
1726 registry
[module
] = {
1727 version
: version
!== undefined ? String( version
) : '',
1729 group
: typeof group
=== 'string' ? group
: null,
1730 source
: typeof source
=== 'string' ? source
: 'local',
1731 state
: 'registered',
1732 skip
: typeof skip
=== 'string' ? skip
: null
1734 if ( typeof dependencies
=== 'string' ) {
1735 // Allow dependencies to be given as a single module name
1736 registry
[module
].dependencies
= [ dependencies
];
1737 } else if ( typeof dependencies
=== 'object' || $.isFunction( dependencies
) ) {
1738 // Allow dependencies to be given as an array of module names
1739 // or a function which returns an array
1740 registry
[module
].dependencies
= dependencies
;
1745 * Implement a module given the components that make up the module.
1747 * When #load or #using requests one or more modules, the server
1748 * response contain calls to this function.
1750 * All arguments are required.
1752 * @param {string} module Name of module
1753 * @param {Function|Array} script Function with module code or Array of URLs to
1754 * be used as the src attribute of a new `<script>` tag.
1755 * @param {Object} [style] Should follow one of the following patterns:
1757 * { "css": [css, ..] }
1758 * { "url": { <media>: [url, ..] } }
1760 * And for backwards compatibility (needs to be supported forever due to caching):
1763 * { <media>: [url, ..] }
1765 * The reason css strings are not concatenated anymore is bug 31676. We now check
1766 * whether it's safe to extend the stylesheet.
1768 * @param {Object} [msgs] List of key/value pairs to be added to mw#messages.
1769 * @param {Object} [templates] List of key/value pairs to be added to mw#templates.
1771 implement: function ( module
, script
, style
, msgs
, templates
) {
1773 if ( typeof module
!== 'string' ) {
1774 throw new Error( 'module must be of type string, not ' + typeof module
);
1776 if ( script
&& !$.isFunction( script
) && !$.isArray( script
) ) {
1777 throw new Error( 'script must be of type function or array, not ' + typeof script
);
1779 if ( style
&& !$.isPlainObject( style
) ) {
1780 throw new Error( 'style must be of type object, not ' + typeof style
);
1782 if ( msgs
&& !$.isPlainObject( msgs
) ) {
1783 throw new Error( 'msgs must be of type object, not a ' + typeof msgs
);
1785 if ( templates
&& !$.isPlainObject( templates
) ) {
1786 throw new Error( 'templates must be of type object, not a ' + typeof templates
);
1788 // Automatically register module
1789 if ( !hasOwn
.call( registry
, module
) ) {
1790 mw
.loader
.register( module
);
1792 // Check for duplicate implementation
1793 if ( hasOwn
.call( registry
, module
) && registry
[module
].script
!== undefined ) {
1794 throw new Error( 'module already implemented: ' + module
);
1796 // Attach components
1797 registry
[module
].script
= script
|| [];
1798 registry
[module
].style
= style
|| {};
1799 registry
[module
].messages
= msgs
|| {};
1800 registry
[module
].templates
= templates
|| {};
1801 // The module may already have been marked as erroneous
1802 if ( $.inArray( registry
[module
].state
, ['error', 'missing'] ) === -1 ) {
1803 registry
[module
].state
= 'loaded';
1804 if ( allReady( registry
[module
].dependencies
) ) {
1811 * Execute a function as soon as one or more required modules are ready.
1813 * Example of inline dependency on OOjs:
1815 * mw.loader.using( 'oojs', function () {
1816 * OO.compare( [ 1 ], [ 1 ] );
1819 * @param {string|Array} dependencies Module name or array of modules names the callback
1820 * dependends on to be ready before executing
1821 * @param {Function} [ready] Callback to execute when all dependencies are ready
1822 * @param {Function} [error] Callback to execute if one or more dependencies failed
1823 * @return {jQuery.Promise}
1824 * @since 1.23 this returns a promise
1826 using: function ( dependencies
, ready
, error
) {
1827 var deferred
= $.Deferred();
1829 // Allow calling with a single dependency as a string
1830 if ( typeof dependencies
=== 'string' ) {
1831 dependencies
= [ dependencies
];
1832 } else if ( !$.isArray( dependencies
) ) {
1834 throw new Error( 'Dependencies must be a string or an array' );
1838 deferred
.done( ready
);
1841 deferred
.fail( error
);
1844 // Resolve entire dependency map
1845 dependencies
= resolve( dependencies
);
1846 if ( allReady( dependencies
) ) {
1847 // Run ready immediately
1849 } else if ( anyFailed( dependencies
) ) {
1850 // Execute error immediately if any dependencies have errors
1852 new Error( 'One or more dependencies failed to load' ),
1856 // Not all dependencies are ready: queue up a request
1857 request( dependencies
, deferred
.resolve
, deferred
.reject
);
1860 return deferred
.promise();
1864 * Load an external script or one or more modules.
1866 * @param {string|Array} modules Either the name of a module, array of modules,
1867 * or a URL of an external script or style
1868 * @param {string} [type='text/javascript'] MIME type to use if calling with a URL of an
1869 * external script or style; acceptable values are "text/css" and
1870 * "text/javascript"; if no type is provided, text/javascript is assumed.
1871 * @param {boolean} [async] Whether to load modules asynchronously.
1872 * Ignored (and defaulted to `true`) if the document-ready event has already occurred.
1873 * Defaults to `true` if loading a URL, `false` otherwise.
1875 load: function ( modules
, type
, async
) {
1879 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
1880 throw new Error( 'modules must be a string or an array, not a ' + typeof modules
);
1882 // Allow calling with an external url or single dependency as a string
1883 if ( typeof modules
=== 'string' ) {
1884 if ( /^(https?:)?\/\//.test( modules
) ) {
1885 if ( async
=== undefined ) {
1886 // Assume async for bug 34542
1889 if ( type
=== 'text/css' ) {
1891 // Use properties instead of attributes as IE throws security
1892 // warnings when inserting a <link> tag with a protocol-relative
1893 // URL set though attributes - when on HTTPS. See bug 41331.
1894 l
= document
.createElement( 'link' );
1895 l
.rel
= 'stylesheet';
1897 $( 'head' ).append( l
);
1900 if ( type
=== 'text/javascript' || type
=== undefined ) {
1901 addScript( modules
, null, async
);
1905 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type
);
1907 // Called with single module
1908 modules
= [ modules
];
1911 // Filter out undefined modules, otherwise resolve() will throw
1912 // an exception for trying to load an undefined module.
1913 // Undefined modules are acceptable here in load(), because load() takes
1914 // an array of unrelated modules, whereas the modules passed to
1915 // using() are related and must all be loaded.
1916 filtered
= $.grep( modules
, function ( module
) {
1917 var state
= mw
.loader
.getState( module
);
1918 return state
!== null && state
!== 'error' && state
!== 'missing';
1921 if ( filtered
.length
=== 0 ) {
1924 // Resolve entire dependency map
1925 filtered
= resolve( filtered
);
1926 // If all modules are ready, or if any modules have errors, nothing to be done.
1927 if ( allReady( filtered
) || anyFailed( filtered
) ) {
1930 // Since some modules are not yet ready, queue up a request.
1931 request( filtered
, undefined, undefined, async
);
1935 * Change the state of one or more modules.
1937 * @param {string|Object} module Module name or object of module name/state pairs
1938 * @param {string} state State name
1940 state: function ( module
, state
) {
1943 if ( typeof module
=== 'object' ) {
1944 for ( m
in module
) {
1945 mw
.loader
.state( m
, module
[m
] );
1949 if ( !hasOwn
.call( registry
, module
) ) {
1950 mw
.loader
.register( module
);
1952 if ( $.inArray( state
, ['ready', 'error', 'missing'] ) !== -1
1953 && registry
[module
].state
!== state
) {
1954 // Make sure pending modules depending on this one get executed if their
1955 // dependencies are now fulfilled!
1956 registry
[module
].state
= state
;
1957 handlePending( module
);
1959 registry
[module
].state
= state
;
1964 * Get the version of a module.
1966 * @param {string} module Name of module
1967 * @return {string|null} The version, or null if the module (or its version) is not
1970 getVersion: function ( module
) {
1971 if ( !hasOwn
.call( registry
, module
) || registry
[module
].version
=== undefined ) {
1974 return registry
[module
].version
;
1978 * Get the state of a module.
1980 * @param {string} module Name of module
1981 * @return {string|null} The state, or null if the module (or its state) is not
1984 getState: function ( module
) {
1985 if ( !hasOwn
.call( registry
, module
) || registry
[module
].state
=== undefined ) {
1988 return registry
[module
].state
;
1992 * Get the names of all registered modules.
1996 getModuleNames: function () {
1997 return $.map( registry
, function ( i
, key
) {
2003 * @inheritdoc mw.inspect#runReports
2006 inspect: function () {
2007 var args
= slice
.call( arguments
);
2008 mw
.loader
.using( 'mediawiki.inspect', function () {
2009 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
2014 * On browsers that implement the localStorage API, the module store serves as a
2015 * smart complement to the browser cache. Unlike the browser cache, the module store
2016 * can slice a concatenated response from ResourceLoader into its constituent
2017 * modules and cache each of them separately, using each module's versioning scheme
2018 * to determine when the cache should be invalidated.
2021 * @class mw.loader.store
2024 // Whether the store is in use on this page.
2027 // Modules whose string representation exceeds 100 kB are ineligible
2028 // for storage due to bug T66721.
2029 MODULE_SIZE_MAX
: 100000,
2031 // The contents of the store, mapping '[module name]@[version]' keys
2032 // to module implementations.
2036 stats
: { hits
: 0, misses
: 0, expired
: 0 },
2039 * Construct a JSON-serializable object representing the content of the store.
2040 * @return {Object} Module store contents.
2042 toJSON: function () {
2043 return { items
: mw
.loader
.store
.items
, vary
: mw
.loader
.store
.getVary() };
2047 * Get the localStorage key for the entire module store. The key references
2048 * $wgDBname to prevent clashes between wikis which share a common host.
2050 * @return {string} localStorage item key
2052 getStoreKey: function () {
2053 return 'MediaWikiModuleStore:' + mw
.config
.get( 'wgDBname' );
2057 * Get a key on which to vary the module cache.
2058 * @return {string} String of concatenated vary conditions.
2060 getVary: function () {
2062 mw
.config
.get( 'skin' ),
2063 mw
.config
.get( 'wgResourceLoaderStorageVersion' ),
2064 mw
.config
.get( 'wgUserLanguage' )
2069 * Get a key for a specific module. The key format is '[name]@[version]'.
2071 * @param {string} module Module name
2072 * @return {string|null} Module key or null if module does not exist
2074 getModuleKey: function ( module
) {
2075 return hasOwn
.call( registry
, module
) ?
2076 ( module
+ '@' + registry
[module
].version
) : null;
2080 * Initialize the store.
2082 * Retrieves store from localStorage and (if successfully retrieved) decoding
2083 * the stored JSON value to a plain object.
2085 * The try / catch block is used for JSON & localStorage feature detection.
2086 * See the in-line documentation for Modernizr's localStorage feature detection
2087 * code for a full account of why we need a try / catch:
2088 * <https://github.com/Modernizr/Modernizr/blob/v2.7.1/modernizr.js#L771-L796>.
2093 if ( mw
.loader
.store
.enabled
!== null ) {
2098 if ( !mw
.config
.get( 'wgResourceLoaderStorageEnabled' ) ) {
2099 // Disabled by configuration.
2100 // Clear any previous store to free up space. (T66721)
2101 mw
.loader
.store
.clear();
2102 mw
.loader
.store
.enabled
= false;
2105 if ( mw
.config
.get( 'debug' ) ) {
2106 // Disable module store in debug mode
2107 mw
.loader
.store
.enabled
= false;
2112 raw
= localStorage
.getItem( mw
.loader
.store
.getStoreKey() );
2113 // If we get here, localStorage is available; mark enabled
2114 mw
.loader
.store
.enabled
= true;
2115 data
= JSON
.parse( raw
);
2116 if ( data
&& typeof data
.items
=== 'object' && data
.vary
=== mw
.loader
.store
.getVary() ) {
2117 mw
.loader
.store
.items
= data
.items
;
2121 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-init' } );
2124 if ( raw
=== undefined ) {
2125 // localStorage failed; disable store
2126 mw
.loader
.store
.enabled
= false;
2128 mw
.loader
.store
.update();
2133 * Retrieve a module from the store and update cache hit stats.
2135 * @param {string} module Module name
2136 * @return {string|boolean} Module implementation or false if unavailable
2138 get: function ( module
) {
2141 if ( !mw
.loader
.store
.enabled
) {
2145 key
= mw
.loader
.store
.getModuleKey( module
);
2146 if ( key
in mw
.loader
.store
.items
) {
2147 mw
.loader
.store
.stats
.hits
++;
2148 return mw
.loader
.store
.items
[key
];
2150 mw
.loader
.store
.stats
.misses
++;
2155 * Stringify a module and queue it for storage.
2157 * @param {string} module Module name
2158 * @param {Object} descriptor The module's descriptor as set in the registry
2160 set: function ( module
, descriptor
) {
2163 if ( !mw
.loader
.store
.enabled
) {
2167 key
= mw
.loader
.store
.getModuleKey( module
);
2170 // Already stored a copy of this exact version
2171 key
in mw
.loader
.store
.items
||
2172 // Module failed to load
2173 descriptor
.state
!== 'ready' ||
2174 // Unversioned, private, or site-/user-specific
2175 ( !descriptor
.version
|| $.inArray( descriptor
.group
, [ 'private', 'user', 'site' ] ) !== -1 ) ||
2176 // Partial descriptor
2177 $.inArray( undefined, [ descriptor
.script
, descriptor
.style
,
2178 descriptor
.messages
, descriptor
.templates
] ) !== -1
2186 JSON
.stringify( module
),
2187 typeof descriptor
.script
=== 'function' ?
2188 String( descriptor
.script
) :
2189 JSON
.stringify( descriptor
.script
),
2190 JSON
.stringify( descriptor
.style
),
2191 JSON
.stringify( descriptor
.messages
),
2192 JSON
.stringify( descriptor
.templates
)
2194 // Attempted workaround for a possible Opera bug (bug T59567).
2195 // This regex should never match under sane conditions.
2196 if ( /^\s*\(/.test( args
[1] ) ) {
2197 args
[1] = 'function' + args
[1];
2198 mw
.track( 'resourceloader.assert', { source
: 'bug-T59567' } );
2201 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-json' } );
2205 src
= 'mw.loader.implement(' + args
.join( ',' ) + ');';
2206 if ( src
.length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2209 mw
.loader
.store
.items
[key
] = src
;
2210 mw
.loader
.store
.update();
2214 * Iterate through the module store, removing any item that does not correspond
2215 * (in name and version) to an item in the module registry.
2217 prune: function () {
2220 if ( !mw
.loader
.store
.enabled
) {
2224 for ( key
in mw
.loader
.store
.items
) {
2225 module
= key
.slice( 0, key
.indexOf( '@' ) );
2226 if ( mw
.loader
.store
.getModuleKey( module
) !== key
) {
2227 mw
.loader
.store
.stats
.expired
++;
2228 delete mw
.loader
.store
.items
[key
];
2229 } else if ( mw
.loader
.store
.items
[key
].length
> mw
.loader
.store
.MODULE_SIZE_MAX
) {
2230 // This value predates the enforcement of a size limit on cached modules.
2231 delete mw
.loader
.store
.items
[key
];
2237 * Clear the entire module store right now.
2239 clear: function () {
2240 mw
.loader
.store
.items
= {};
2241 localStorage
.removeItem( mw
.loader
.store
.getStoreKey() );
2245 * Sync modules to localStorage.
2247 * This function debounces localStorage updates. When called multiple times in
2248 * quick succession, the calls are coalesced into a single update operation.
2249 * This allows us to call #update without having to consider the module load
2250 * queue; the call to localStorage.setItem will be naturally deferred until the
2251 * page is quiescent.
2253 * Because localStorage is shared by all pages with the same origin, if multiple
2254 * pages are loaded with different module sets, the possibility exists that
2255 * modules saved by one page will be clobbered by another. But the impact would
2256 * be minor and the problem would be corrected by subsequent page views.
2260 update
: ( function () {
2265 key
= mw
.loader
.store
.getStoreKey();
2267 if ( !mw
.loader
.store
.enabled
) {
2270 mw
.loader
.store
.prune();
2272 // Replacing the content of the module store might fail if the new
2273 // contents would exceed the browser's localStorage size limit. To
2274 // avoid clogging the browser with stale data, always remove the old
2275 // value before attempting to set the new one.
2276 localStorage
.removeItem( key
);
2277 data
= JSON
.stringify( mw
.loader
.store
);
2278 localStorage
.setItem( key
, data
);
2280 mw
.track( 'resourceloader.exception', { exception
: e
, source
: 'store-localstorage-update' } );
2284 return function () {
2285 clearTimeout( timer
);
2286 timer
= setTimeout( flush
, 2000 );
2294 * HTML construction helper functions
2301 * output = Html.element( 'div', {}, new Html.Raw(
2302 * Html.element( 'img', { src: '<' } )
2304 * mw.log( output ); // <div><img src="<"/></div>
2309 html
: ( function () {
2310 function escapeCallback( s
) {
2327 * Escape a string for HTML.
2329 * Converts special characters to HTML entities.
2331 * mw.html.escape( '< > \' & "' );
2332 * // Returns < > ' & "
2334 * @param {string} s The string to escape
2335 * @return {string} HTML
2337 escape: function ( s
) {
2338 return s
.replace( /['"<>&]/g, escapeCallback
);
2342 * Create an HTML element string, with safe escaping.
2344 * @param {string} name The tag name.
2345 * @param {Object} attrs An object with members mapping element names to values
2346 * @param {Mixed} contents The contents of the element. May be either:
2348 * - string: The string is escaped.
2349 * - null or undefined: The short closing form is used, e.g. `<br/>`.
2350 * - this.Raw: The value attribute is included without escaping.
2351 * - this.Cdata: The value attribute is included, and an exception is
2352 * thrown if it contains an illegal ETAGO delimiter.
2353 * See <http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2>.
2354 * @return {string} HTML
2356 element: function ( name
, attrs
, contents
) {
2357 var v
, attrName
, s
= '<' + name
;
2359 for ( attrName
in attrs
) {
2360 v
= attrs
[attrName
];
2361 // Convert name=true, to name=name
2365 } else if ( v
=== false ) {
2368 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
2370 if ( contents
=== undefined || contents
=== null ) {
2377 switch ( typeof contents
) {
2380 s
+= this.escape( contents
);
2384 // Convert to string
2385 s
+= String( contents
);
2388 if ( contents
instanceof this.Raw
) {
2389 // Raw HTML inclusion
2390 s
+= contents
.value
;
2391 } else if ( contents
instanceof this.Cdata
) {
2393 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
2394 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
2396 s
+= contents
.value
;
2398 throw new Error( 'mw.html.element: Invalid type of contents' );
2401 s
+= '</' + name
+ '>';
2406 * Wrapper object for raw HTML passed to mw.html.element().
2407 * @class mw.html.Raw
2409 Raw: function ( value
) {
2414 * Wrapper object for CDATA element contents passed to mw.html.element()
2415 * @class mw.html.Cdata
2417 Cdata: function ( value
) {
2423 // Skeleton user object. mediawiki.user.js extends this
2430 * Registry and firing of events.
2432 * MediaWiki has various interface components that are extended, enhanced
2433 * or manipulated in some other way by extensions, gadgets and even
2436 * This framework helps streamlining the timing of when these other
2437 * code paths fire their plugins (instead of using document-ready,
2438 * which can and should be limited to firing only once).
2440 * Features like navigating to other wiki pages, previewing an edit
2441 * and editing itself – without a refresh – can then retrigger these
2442 * hooks accordingly to ensure everything still works as expected.
2446 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
2447 * mw.hook( 'wikipage.content' ).fire( $content );
2449 * Handlers can be added and fired for arbitrary event names at any time. The same
2450 * event can be fired multiple times. The last run of an event is memorized
2451 * (similar to `$(document).ready` and `$.Deferred().done`).
2452 * This means if an event is fired, and a handler added afterwards, the added
2453 * function will be fired right away with the last given event data.
2455 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
2456 * Thus allowing flexible use and optimal maintainability and authority control.
2457 * You can pass around the `add` and/or `fire` method to another piece of code
2458 * without it having to know the event name (or `mw.hook` for that matter).
2460 * var h = mw.hook( 'bar.ready' );
2461 * new mw.Foo( .. ).fetch( { callback: h.fire } );
2463 * Note: Events are documented with an underscore instead of a dot in the event
2464 * name due to jsduck not supporting dots in that position.
2468 hook
: ( function () {
2472 * Create an instance of mw.hook.
2476 * @param {string} name Name of hook.
2479 return function ( name
) {
2480 var list
= hasOwn
.call( lists
, name
) ?
2482 lists
[name
] = $.Callbacks( 'memory' );
2486 * Register a hook handler
2487 * @param {Function...} handler Function to bind.
2493 * Unregister a hook handler
2494 * @param {Function...} handler Function to unbind.
2497 remove
: list
.remove
,
2501 * @param {Mixed...} data
2505 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
2512 // Alias $j to jQuery for backwards compatibility
2513 // @deprecated since 1.23 Use $ or jQuery instead
2514 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
2517 * Log a message to window.console, if possible.
2519 * Useful to force logging of some errors that are otherwise hard to detect (i.e., this logs
2520 * also in production mode). Gets console references in each invocation instead of caching the
2521 * reference, so that debugging tools loaded later are supported (e.g. Firebug Lite in IE).
2525 * @param {string} topic Stream name passed by mw.track
2526 * @param {Object} data Data passed by mw.track
2527 * @param {Error} [data.exception]
2528 * @param {string} data.source Error source
2529 * @param {string} [data.module] Name of module which caused the error
2531 function log( topic
, data
) {
2534 source
= data
.source
,
2535 module
= data
.module
,
2536 console
= window
.console
;
2538 if ( console
&& console
.log
) {
2539 msg
= ( e
? 'Exception' : 'Error' ) + ' in ' + source
;
2541 msg
+= ' in module ' + module
;
2543 msg
+= ( e
? ':' : '.' );
2546 // If we have an exception object, log it to the error channel to trigger a
2547 // proper stacktraces in browsers that support it. No fallback as we have no browsers
2548 // that don't support error(), but do support log().
2549 if ( e
&& console
.error
) {
2550 console
.error( String( e
), e
);
2555 // subscribe to error streams
2556 mw
.trackSubscribe( 'resourceloader.exception', log
);
2557 mw
.trackSubscribe( 'resourceloader.assert', log
);
2559 // Attach to window and globally alias
2560 window
.mw
= window
.mediaWiki
= mw
;